summaryrefslogtreecommitdiff
path: root/packages/backend/src/services/note/reaction/delete.ts
blob: a7cbcb1c17fa9f530c14606130c35d8cde7e8ac1 (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
import { publishNoteStream } from '@/services/stream.js';
import { renderLike } from '@/remote/activitypub/renderer/like.js';
import renderUndo from '@/remote/activitypub/renderer/undo.js';
import { renderActivity } from '@/remote/activitypub/renderer/index.js';
import DeliverManager from '@/remote/activitypub/deliver-manager.js';
import { IdentifiableError } from '@/misc/identifiable-error.js';
import { User, IRemoteUser } from '@/models/entities/user.js';
import { Note } from '@/models/entities/note.js';
import { NoteReactions, Users, Notes } from '@/models/index.js';
import { decodeReaction } from '@/misc/reaction-lib.js';

export default async (user: { id: User['id']; host: User['host']; }, note: Note) => {
	// if already unreacted
	const exist = await NoteReactions.findOneBy({
		noteId: note.id,
		userId: user.id,
	});

	if (exist == null) {
		throw new IdentifiableError('60527ec9-b4cb-4a88-a6bd-32d3ad26817d', 'not reacted');
	}

	// Delete reaction
	const result = await NoteReactions.delete(exist.id);

	if (result.affected !== 1) {
		throw new IdentifiableError('60527ec9-b4cb-4a88-a6bd-32d3ad26817d', 'not reacted');
	}

	// Decrement reactions count
	const sql = `jsonb_set("reactions", '{${exist.reaction}}', (COALESCE("reactions"->>'${exist.reaction}', '0')::int - 1)::text::jsonb)`;
	await Notes.createQueryBuilder().update()
		.set({
			reactions: () => sql,
		})
		.where('id = :id', { id: note.id })
		.execute();

	Notes.decrement({ id: note.id }, 'score', 1);

	publishNoteStream(note.id, 'unreacted', {
		reaction: decodeReaction(exist.reaction).reaction,
		userId: user.id,
	});

	//#region 配信
	if (Users.isLocalUser(user) && !note.localOnly) {
		const content = renderActivity(renderUndo(await renderLike(exist, note), user));
		const dm = new DeliverManager(user, content);
		if (note.userHost !== null) {
			const reactee = await Users.findOneBy({ id: note.userId });
			dm.addDirectRecipe(reactee as IRemoteUser);
		}
		dm.addFollowersRecipe();
		dm.execute();
	}
	//#endregion
};