summaryrefslogtreecommitdiff
path: root/packages/backend/src/models/LatestNote.ts
blob: 064fcccc0a469ae3d0ac7099b1a0cb5e2626ef2f (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
/*
 * SPDX-FileCopyrightText: hazelnoot and other Sharkey contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { PrimaryColumn, Entity, JoinColumn, Column, ManyToOne } from 'typeorm';
import { MiUser } from '@/models/User.js';
import { MiNote } from '@/models/Note.js';
import { isQuote, isRenote } from '@/misc/is-renote.js';

/**
 * Maps a user to the most recent post by that user.
 * Public, home-only, and followers-only posts are included.
 * DMs are not counted.
 */
@Entity('latest_note')
export class SkLatestNote {
	@PrimaryColumn({
		name: 'user_id',
		type: 'varchar' as const,
		length: 32,
	})
	public userId: string;

	@PrimaryColumn('boolean', {
		name: 'is_public',
		default: false,
	})
	public isPublic: boolean;

	@PrimaryColumn('boolean', {
		name: 'is_reply',
		default: false,
	})
	public isReply: boolean;

	@PrimaryColumn('boolean', {
		name: 'is_quote',
		default: false,
	})
	public isQuote: boolean;

	@ManyToOne(() => MiUser, {
		onDelete: 'CASCADE',
	})
	@JoinColumn({
		name: 'user_id',
	})
	public user: MiUser | null;

	@Column({
		name: 'note_id',
		type: 'varchar' as const,
		length: 32,
	})
	public noteId: string;

	@ManyToOne(() => MiNote, {
		onDelete: 'CASCADE',
	})
	@JoinColumn({
		name: 'note_id',
	})
	public note: MiNote | null;

	constructor(data?: Partial<SkLatestNote>) {
		if (!data) return;

		for (const [k, v] of Object.entries(data)) {
			(this as Record<string, unknown>)[k] = v;
		}
	}

	/**
	 * Generates a compound key matching a provided note.
	 */
	static keyFor(note: MiNote) {
		return {
			userId: note.userId,
			isPublic: note.visibility === 'public',
			isReply: note.replyId != null,
			isQuote: isRenote(note) && isQuote(note),
		};
	}

	/**
	 * Checks if two notes would produce equivalent compound keys.
	 */
	static areEquivalent(first: MiNote, second: MiNote): boolean {
		const firstKey = SkLatestNote.keyFor(first);
		const secondKey = SkLatestNote.keyFor(second);

		return (
			firstKey.userId === secondKey.userId &&
			firstKey.isPublic === secondKey.isPublic &&
			firstKey.isReply === secondKey.isReply &&
			firstKey.isQuote === secondKey.isQuote
		);
	}
}