summaryrefslogtreecommitdiff
path: root/src/services/note/read.ts
blob: f2c1213363618f4209f6e11477f166082334b16c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import * as mongo from 'mongodb';
import isObjectId from '../../misc/is-objectid';
import { publishMainStream } from '../../stream';
import User from '../../models/user';
import NoteUnread from '../../models/note-unread';

/**
 * Mark a note as read
 */
export default (
	user: string | mongo.ObjectID,
	note: string | mongo.ObjectID
) => new Promise<any>(async (resolve, reject) => {

	const userId: mongo.ObjectID = isObjectId(user)
		? user as mongo.ObjectID
		: new mongo.ObjectID(user);

	const noteId: mongo.ObjectID = isObjectId(note)
		? note as mongo.ObjectID
		: new mongo.ObjectID(note);

	// Remove document
	const res = await NoteUnread.remove({
		userId: userId,
		noteId: noteId
	});

	if (res.deletedCount == 0) {
		return;
	}

	const count1 = await NoteUnread
		.count({
			userId: userId,
			isSpecified: false
		}, {
			limit: 1
		});

	const count2 = await NoteUnread
		.count({
			userId: userId,
			isSpecified: true
		}, {
			limit: 1
		});

	if (count1 == 0 || count2 == 0) {
		User.update({ _id: userId }, {
			$set: {
				hasUnreadMentions: count1 != 0 || count2 != 0,
				hasUnreadSpecifiedNotes: count2 != 0
			}
		});
	}

	if (count1 == 0) {
		// 全て既読になったイベントを発行
		publishMainStream(userId, 'readAllUnreadMentions');
	}

	if (count2 == 0) {
		// 全て既読になったイベントを発行
		publishMainStream(userId, 'readAllUnreadSpecifiedNotes');
	}
});