summaryrefslogtreecommitdiff
path: root/src/services/note/read.ts
blob: 5a39ab30b7414e2cf2bf074810ee92c88678a053 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { publishMainStream } from '../stream';
import { Note } from '../../models/entities/note';
import { User } from '../../models/entities/user';
import { NoteUnreads, Antennas, AntennaNotes, Users } from '../../models';
import { Not, IsNull } from 'typeorm';

/**
 * Mark a note as read
 */
export default async function(
	userId: User['id'],
	noteId: Note['id']
) {
	async function careNoteUnreads() {
		const exist = await NoteUnreads.findOne({
			userId: userId,
			noteId: noteId,
		});

		if (!exist) return;

		// Remove the record
		await NoteUnreads.delete({
			userId: userId,
			noteId: noteId,
		});

		if (exist.isMentioned) {
			NoteUnreads.count({
				userId: userId,
				isMentioned: true
			}).then(mentionsCount => {
				if (mentionsCount === 0) {
					// 全て既読になったイベントを発行
					publishMainStream(userId, 'readAllUnreadMentions');
				}
			});
		}

		if (exist.isSpecified) {
			NoteUnreads.count({
				userId: userId,
				isSpecified: true
			}).then(specifiedCount => {
				if (specifiedCount === 0) {
					// 全て既読になったイベントを発行
					publishMainStream(userId, 'readAllUnreadSpecifiedNotes');
				}
			});
		}

		if (exist.noteChannelId) {
			NoteUnreads.count({
				userId: userId,
				noteChannelId: Not(IsNull())
			}).then(channelNoteCount => {
				if (channelNoteCount === 0) {
					// 全て既読になったイベントを発行
					publishMainStream(userId, 'readAllChannels');
				}
			});
		}
	}

	async function careAntenna() {
		const beforeUnread = await Users.getHasUnreadAntenna(userId);
		if (!beforeUnread) return;

		const antennas = await Antennas.find({ userId });

		await Promise.all(antennas.map(async antenna => {
			const countBefore = await AntennaNotes.count({
				antennaId: antenna.id,
				read: false
			});

			if (countBefore === 0) return;

			await AntennaNotes.update({
				antennaId: antenna.id,
				noteId: noteId
			}, {
				read: true
			});

			const countAfter = await AntennaNotes.count({
				antennaId: antenna.id,
				read: false
			});

			if (countAfter === 0) {
				publishMainStream(userId, 'readAntenna', antenna);
			}
		}));

		Users.getHasUnreadAntenna(userId).then(unread => {
			if (!unread) {
				publishMainStream(userId, 'readAllAntennas');
			}
		});
	}

	careNoteUnreads();
	careAntenna();
}