summaryrefslogtreecommitdiff
path: root/packages/backend/src/core/entities/FollowingEntityService.ts
blob: d54c954bf29ec8c46f98d38445d2d8d60291a332 (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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { Inject, Injectable } from '@nestjs/common';
import { DI } from '@/di-symbols.js';
import type { FollowingsRepository } from '@/models/_.js';
import { awaitAll } from '@/misc/prelude/await-all.js';
import type { Packed } from '@/misc/json-schema.js';
import { MiBlocking } from '@/models/Blocking.js';
import { MiUserProfile } from '@/models/UserProfile.js';
import type { MiLocalUser, MiUser } from '@/models/User.js';
import { MiFollowing } from '@/models/Following.js';
import { bindThis } from '@/decorators.js';
import { IdService } from '@/core/IdService.js';
import { QueryService } from '@/core/QueryService.js';
import { RoleService } from '@/core/RoleService.js';
import { UserEntityService } from './UserEntityService.js';

type LocalFollowerFollowing = MiFollowing & {
	followerHost: null;
	followerInbox: null;
	followerSharedInbox: null;
};

type RemoteFollowerFollowing = MiFollowing & {
	followerHost: string;
	followerInbox: string;
	followerSharedInbox: string;
};

type LocalFolloweeFollowing = MiFollowing & {
	followeeHost: null;
	followeeInbox: null;
	followeeSharedInbox: null;
};

type RemoteFolloweeFollowing = MiFollowing & {
	followeeHost: string;
	followeeInbox: string;
	followeeSharedInbox: string;
};

@Injectable()
export class FollowingEntityService {
	constructor(
		@Inject(DI.followingsRepository)
		private followingsRepository: FollowingsRepository,

		private userEntityService: UserEntityService,
		private idService: IdService,
		private queryService: QueryService,
		private roleService: RoleService,
	) {
	}

	@bindThis
	public isLocalFollower(following: MiFollowing): following is LocalFollowerFollowing {
		return following.followerHost == null;
	}

	@bindThis
	public isRemoteFollower(following: MiFollowing): following is RemoteFollowerFollowing {
		return following.followerHost != null;
	}

	@bindThis
	public isLocalFollowee(following: MiFollowing): following is LocalFolloweeFollowing {
		return following.followeeHost == null;
	}

	@bindThis
	public isRemoteFollowee(following: MiFollowing): following is RemoteFolloweeFollowing {
		return following.followeeHost != null;
	}

	@bindThis
	public async getFollowing(me: MiLocalUser, params: FollowsQueryParams) {
		return await this.getFollows(me, params, 'following.followerHost = :host');
	}

	@bindThis
	public async getFollowers(me: MiLocalUser, params: FollowsQueryParams) {
		return await this.getFollows(me, params, 'following.followeeHost = :host');
	}

	private async getFollows(me: MiLocalUser, params: FollowsQueryParams, condition: string) {
		const builder = this.followingsRepository.createQueryBuilder('following');
		const query = this.queryService
			.makePaginationQuery(builder, params.sinceId, params.untilId)
			.andWhere(condition, { host: params.host })
			.limit(params.limit);

		if (!await this.roleService.isModerator(me)) {
			query.setParameter('me', me.id);

			// Make sure that the followee doesn't block us, if their profile will be included.
			if (params.includeFollowee) {
				query.leftJoin(MiBlocking, 'followee_blocking', 'followee_blocking."blockerId" = following."followeeId" AND followee_blocking."blockeeId" = :me');
				query.andWhere('followee_blocking.id IS NULL');
			}

			// Make sure that the follower doesn't block us, if their profile will be included.
			if (params.includeFollower) {
				query.leftJoin(MiBlocking, 'follower_blocking', 'follower_blocking."blockerId" = following."followerId" AND follower_blocking."blockeeId" = :me');
				query.andWhere('follower_blocking.id IS NULL');
			}

			// Make sure that the followee hasn't hidden this connection.
			query.leftJoin(MiUserProfile, 'followee', 'followee."userId" = following."followeeId"');
			query.leftJoin(MiFollowing, 'me_following_followee', 'me_following_followee."followerId" = :me AND me_following_followee."followeeId" = following."followerId"');
			query.andWhere('(followee."userId" = :me OR followee."followersVisibility" = \'public\' OR (followee."followersVisibility" = \'followers\' AND me_following_followee.id IS NOT NULL))');

			// Make sure that the follower hasn't hidden this connection.
			query.leftJoin(MiUserProfile, 'follower', 'follower."userId" = following."followerId"');
			query.leftJoin(MiFollowing, 'me_following_follower', 'me_following_follower."followerId" = :me AND me_following_follower."followeeId" = following."followerId"');
			query.andWhere('(follower."userId" = :me OR follower."followingVisibility" = \'public\' OR (follower."followingVisibility" = \'followers\' AND me_following_follower.id IS NOT NULL))');
		}

		const followings = await query.getMany();
		return await this.packMany(followings, me, { populateFollowee: params.includeFollowee, populateFollower: params.includeFollower });
	}

	@bindThis
	public async pack(
		src: MiFollowing['id'] | MiFollowing,
		me?: { id: MiUser['id'] } | null | undefined,
		opts?: {
			populateFollowee?: boolean;
			populateFollower?: boolean;
		},
		hint?: {
			packedFollowee?: Packed<'UserDetailedNotMe'>,
			packedFollower?: Packed<'UserDetailedNotMe'>,
		},
	): Promise<Packed<'Following'>> {
		const following = typeof src === 'object' ? src : await this.followingsRepository.findOneByOrFail({ id: src });

		if (opts == null) opts = {};

		return await awaitAll({
			id: following.id,
			createdAt: this.idService.parse(following.id).date.toISOString(),
			followeeId: following.followeeId,
			followerId: following.followerId,
			followee: opts.populateFollowee ? hint?.packedFollowee ?? this.userEntityService.pack(following.followee ?? following.followeeId, me, {
				schema: 'UserDetailedNotMe',
			}) : undefined,
			follower: opts.populateFollower ? hint?.packedFollower ?? this.userEntityService.pack(following.follower ?? following.followerId, me, {
				schema: 'UserDetailedNotMe',
			}) : undefined,
		});
	}

	@bindThis
	public async packMany(
		followings: MiFollowing[],
		me?: { id: MiUser['id'] } | null | undefined,
		opts?: {
			populateFollowee?: boolean;
			populateFollower?: boolean;
		},
	) {
		const _followees = opts?.populateFollowee ? followings.map(({ followee, followeeId }) => followee ?? followeeId) : [];
		const _followers = opts?.populateFollower ? followings.map(({ follower, followerId }) => follower ?? followerId) : [];
		const _userMap = await this.userEntityService.packMany([..._followees, ..._followers], me, { schema: 'UserDetailedNotMe' })
			.then(users => new Map(users.map(u => [u.id, u])));
		return Promise.all(
			followings.map(following => {
				const packedFollowee = opts?.populateFollowee ? _userMap.get(following.followeeId) : undefined;
				const packedFollower = opts?.populateFollower ? _userMap.get(following.followerId) : undefined;
				return this.pack(following, me, opts, { packedFollowee, packedFollower });
			}),
		);
	}
}

interface FollowsQueryParams {
	readonly host: string;
	readonly limit: number;
	readonly includeFollower: boolean;
	readonly includeFollowee: boolean;

	readonly sinceId?: string;
	readonly untilId?: string;
}