summaryrefslogtreecommitdiff
path: root/packages/backend/src/server/api/endpoints/i/read-all-messaging-messages.ts
blob: 36c3566f5593de81ced3e12c0c0c334083cd5965 (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
import { Inject, Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { MessagingMessagesRepository, UserGroupJoiningsRepository } from '@/models/index.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import { DI } from '@/di-symbols.js';

export const meta = {
	tags: ['account', 'messaging'],

	requireCredential: true,

	kind: 'write:account',
} as const;

export const paramDef = {
	type: 'object',
	properties: {},
	required: [],
} as const;

// eslint-disable-next-line import/no-default-export
@Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> {
	constructor(
		@Inject(DI.messagingMessagesRepository)
		private messagingMessagesRepository: MessagingMessagesRepository,

		@Inject(DI.userGroupJoiningsRepository)
		private userGroupJoiningsRepository: UserGroupJoiningsRepository,

		private globalEventService: GlobalEventService,
	) {
		super(meta, paramDef, async (ps, me) => {
			// Update documents
			await this.messagingMessagesRepository.update({
				recipientId: me.id,
				isRead: false,
			}, {
				isRead: true,
			});

			const joinings = await this.userGroupJoiningsRepository.findBy({ userId: me.id });

			await Promise.all(joinings.map(j => this.messagingMessagesRepository.createQueryBuilder().update()
				.set({
					reads: (() => `array_append("reads", '${me.id}')`) as any,
				})
				.where('groupId = :groupId', { groupId: j.userGroupId })
				.andWhere('userId != :userId', { userId: me.id })
				.andWhere('NOT (:userId = ANY(reads))', { userId: me.id })
				.execute()));

			this.globalEventService.publishMainStream(me.id, 'readAllMessagingMessages');
		});
	}
}