hide muted threads from timelines

This commit is contained in:
Hazelnoot 2025-06-09 20:44:29 -04:00
parent a4c0ef824c
commit 7d0f995c9b
18 changed files with 134 additions and 51 deletions

View file

@ -6,7 +6,7 @@
import { Inject, Injectable } from '@nestjs/common';
import * as Redis from 'ioredis';
import { In, IsNull } from 'typeorm';
import type { BlockingsRepository, FollowingsRepository, MutingsRepository, RenoteMutingsRepository, MiUserProfile, UserProfilesRepository, UsersRepository, MiNote, MiFollowing } from '@/models/_.js';
import type { BlockingsRepository, FollowingsRepository, MutingsRepository, RenoteMutingsRepository, MiUserProfile, UserProfilesRepository, UsersRepository, MiNote, MiFollowing, NoteThreadMutingsRepository } from '@/models/_.js';
import { MemoryKVCache, RedisKVCache } from '@/misc/cache.js';
import { QuantumKVCache } from '@/misc/QuantumKVCache.js';
import type { MiLocalUser, MiUser } from '@/models/User.js';
@ -46,6 +46,7 @@ export class CacheService implements OnApplicationShutdown {
public userBlockingCache: QuantumKVCache<Set<string>>;
public userBlockedCache: QuantumKVCache<Set<string>>; // NOTE: 「被」Blockキャッシュ
public renoteMutingsCache: QuantumKVCache<Set<string>>;
public threadMutingsCache: QuantumKVCache<Set<string>>;
public userFollowingsCache: QuantumKVCache<Map<string, Omit<MiFollowing, 'isFollowerHibernated'>>>;
public userFollowersCache: QuantumKVCache<Map<string, Omit<MiFollowing, 'isFollowerHibernated'>>>;
public hibernatedUserCache: QuantumKVCache<boolean>;
@ -77,6 +78,9 @@ export class CacheService implements OnApplicationShutdown {
@Inject(DI.followingsRepository)
private followingsRepository: FollowingsRepository,
@Inject(DI.noteThreadMutingsRepository)
private readonly noteThreadMutingsRepository: NoteThreadMutingsRepository,
private userEntityService: UserEntityService,
private readonly internalEventService: InternalEventService,
) {
@ -145,6 +149,20 @@ export class CacheService implements OnApplicationShutdown {
.then(ms => ms.map(m => [m.muterId, new Set(m.muteeIds)])),
});
this.threadMutingsCache = new QuantumKVCache<Set<string>>(this.internalEventService, 'threadMutings', {
lifetime: 1000 * 60 * 30, // 30m
fetcher: muterId => this.noteThreadMutingsRepository
.find({ where: { userId: muterId }, select: { threadId: true } })
.then(ms => new Set(ms.map(m => m.threadId))),
bulkFetcher: muterIds => this.noteThreadMutingsRepository
.createQueryBuilder('muting')
.select('"muting"."userId"', 'userId')
.addSelect('array_agg("muting"."threadId")', 'threadIds')
.where({ userId: In(muterIds) })
.getRawMany<{ userId: string, threadIds: string[] }>()
.then(ms => ms.map(m => [m.userId, new Set(m.threadIds)])),
});
this.userFollowingsCache = new QuantumKVCache<Map<string, Omit<MiFollowing, 'isFollowerHibernated'>>>(this.internalEventService, 'userFollowings', {
lifetime: 1000 * 60 * 30, // 30m
fetcher: (key) => this.followingsRepository.findBy({ followerId: key }).then(xs => new Map(xs.map(f => [f.followeeId, f]))),

View file

@ -676,18 +676,15 @@ export class NoteCreateService implements OnApplicationShutdown {
});
// 通知
if (data.reply.userHost === null) {
const isThreadMuted = await this.noteThreadMutingsRepository.exists({
where: {
userId: data.reply.userId,
threadId: data.reply.threadId ?? data.reply.id,
},
});
const threadId = data.reply.threadId ?? data.reply.id;
const [
isThreadMuted,
userIdsWhoMeMuting,
] = data.reply.userId ? await Promise.all([
] = await Promise.all([
this.cacheService.threadMutingsCache.fetch(data.reply.userId).then(ms => ms.has(threadId)),
this.cacheService.userMutingsCache.fetch(data.reply.userId),
]) : [new Set<string>()];
]);
const muted = isUserRelated(note, userIdsWhoMeMuting);
@ -705,14 +702,17 @@ export class NoteCreateService implements OnApplicationShutdown {
// Notify
if (data.renote.userHost === null) {
const isThreadMuted = await this.noteThreadMutingsRepository.exists({
where: {
userId: data.renote.userId,
threadId: data.renote.threadId ?? data.renote.id,
},
});
const threadId = data.renote.threadId ?? data.renote.id;
const muted = data.renote.userId && isUserRelated(note, await this.cacheService.userMutingsCache.fetch(data.renote.userId));
const [
isThreadMuted,
userIdsWhoMeMuting,
] = await Promise.all([
this.cacheService.threadMutingsCache.fetch(data.renote.userId).then(ms => ms.has(threadId)),
this.cacheService.userMutingsCache.fetch(data.renote.userId),
]);
const muted = data.renote.userId && isUserRelated(note, userIdsWhoMeMuting);
if (!isThreadMuted && !muted) {
nm.push(data.renote.userId, type);
@ -842,18 +842,23 @@ export class NoteCreateService implements OnApplicationShutdown {
@bindThis
private async createMentionedEvents(mentionedUsers: MinimumUser[], note: MiNote, nm: NotificationManager) {
const [
threadMutings,
userMutings,
] = await Promise.all([
this.cacheService.threadMutingsCache.fetchMany(mentionedUsers.map(u => u.id)).then(ms => new Map(ms)),
this.cacheService.userMutingsCache.fetchMany(mentionedUsers.map(u => u.id)).then(ms => new Map(ms)),
]);
// Only create mention events for local users, and users for whom the note is visible
for (const u of mentionedUsers.filter(u => (note.visibility !== 'specified' || note.visibleUserIds.some(x => x === u.id)) && this.userEntityService.isLocalUser(u))) {
const isThreadMuted = await this.noteThreadMutingsRepository.exists({
where: {
userId: u.id,
threadId: note.threadId ?? note.id,
},
});
const threadId = note.threadId ?? note.id;
const isThreadMuted = threadMutings.get(u.id)?.has(threadId);
const muted = u.id && isUserRelated(note, await this.cacheService.userMutingsCache.fetch(u.id));
const mutings = userMutings.get(u.id);
const isUserMuted = mutings != null && isUserRelated(note, mutings);
if (isThreadMuted || muted) {
if (isThreadMuted || isUserMuted) {
continue;
}

View file

@ -647,18 +647,15 @@ export class NoteEditService implements OnApplicationShutdown {
if (data.reply) {
// 通知
if (data.reply.userHost === null) {
const isThreadMuted = await this.noteThreadMutingsRepository.exists({
where: {
userId: data.reply.userId,
threadId: data.reply.threadId ?? data.reply.id,
},
});
const threadId = data.reply.threadId ?? data.reply.id;
const [
isThreadMuted,
userIdsWhoMeMuting,
] = data.reply.userId ? await Promise.all([
] = await Promise.all([
this.cacheService.threadMutingsCache.fetch(data.reply.userId).then(ms => ms.has(threadId)),
this.cacheService.userMutingsCache.fetch(data.reply.userId),
]) : [new Set<string>()];
]);
const muted = isUserRelated(note, userIdsWhoMeMuting);

View file

@ -275,12 +275,8 @@ export class ReactionService {
// リアクションされたユーザーがローカルユーザーなら通知を作成
if (note.userHost === null) {
const isThreadMuted = await this.noteThreadMutingsRepository.exists({
where: {
userId: note.userId,
threadId: note.threadId ?? note.id,
},
});
const threadId = note.threadId ?? note.id;
const isThreadMuted = await this.cacheService.threadMutingsCache.fetch(note.userId).then(ms => ms.has(threadId));
if (!isThreadMuted) {
this.notificationService.createNotification(note.userId, 'reaction', {

View file

@ -462,6 +462,7 @@ export class NoteEntityService implements OnModuleInit {
const packed: Packed<'Note'> = await awaitAll({
id: note.id,
threadId: note.threadId ?? note.id,
createdAt: this.idService.parse(note.id).date.toISOString(),
updatedAt: note.updatedAt ? note.updatedAt.toISOString() : undefined,
userId: note.userId,

View file

@ -12,6 +12,12 @@ export const packedNoteSchema = {
format: 'id',
example: 'xxxxxxxxxx',
},
threadId: {
type: 'string',
optional: false, nullable: false,
format: 'id',
example: 'xxxxxxxxxx',
},
createdAt: {
type: 'string',
optional: false, nullable: false,

View file

@ -13,8 +13,8 @@ import { DI } from '@/di-symbols.js';
import { IdService } from '@/core/IdService.js';
import { FanoutTimelineEndpointService } from '@/core/FanoutTimelineEndpointService.js';
import { MiLocalUser } from '@/models/User.js';
import { CacheService } from '@/core/CacheService.js';
import { ApiError } from '../../error.js';
import { Brackets } from 'typeorm';
export const meta = {
tags: ['notes', 'channels'],
@ -83,6 +83,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
private queryService: QueryService,
private fanoutTimelineEndpointService: FanoutTimelineEndpointService,
private activeUsersChart: ActiveUsersChart,
private readonly cacheService: CacheService,
) {
super(meta, paramDef, async (ps, me) => {
const untilId = ps.untilId ?? (ps.untilDate ? this.idService.gen(ps.untilDate!) : null);
@ -106,6 +107,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
return await this.noteEntityService.packMany(await this.getFromDb({ untilId, sinceId, limit: ps.limit, channelId: channel.id, withFiles: ps.withFiles, withRenotes: ps.withRenotes }, me), me);
}
const threadMutings = me ? await this.cacheService.threadMutingsCache.fetch(me.id) : null;
return await this.fanoutTimelineEndpointService.timeline({
untilId,
sinceId,
@ -119,6 +122,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
dbFallback: async (untilId, sinceId, limit) => {
return await this.getFromDb({ untilId, sinceId, limit, channelId: channel.id, withFiles: ps.withFiles, withRenotes: ps.withRenotes }, me);
},
noteFilter: note => {
if (threadMutings?.has(note.threadId ?? note.id)) {
return false;
}
return true;
},
});
});
}
@ -148,6 +158,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
if (me) {
this.queryService.generateMutedUserQueryForNotes(query, me);
this.queryService.generateBlockedUserQueryForNotes(query, me);
this.queryService.generateMutedNoteThreadQuery(query, me);
}
if (ps.withFiles) {

View file

@ -100,6 +100,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
if (me) {
this.queryService.generateMutedUserQueryForNotes(query, me);
this.queryService.generateBlockedUserQueryForNotes(query, me);
this.queryService.generateMutedNoteThreadQuery(query, me);
}
if (ps.withFiles) {

View file

@ -12,6 +12,7 @@ import { NoteEntityService } from '@/core/entities/NoteEntityService.js';
import ActiveUsersChart from '@/core/chart/charts/active-users.js';
import { DI } from '@/di-symbols.js';
import { RoleService } from '@/core/RoleService.js';
import { CacheService } from '@/core/CacheService.js';
import { ApiError } from '../../error.js';
export const meta = {
@ -67,6 +68,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
private queryService: QueryService,
private roleService: RoleService,
private activeUsersChart: ActiveUsersChart,
private readonly cacheService: CacheService,
) {
super(meta, paramDef, async (ps, me) => {
const policies = await this.roleService.getUserPolicies(me ? me.id : null);
@ -90,6 +92,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
if (me) {
this.queryService.generateMutedUserQueryForNotes(query, me);
this.queryService.generateBlockedUserQueryForNotes(query, me);
this.queryService.generateMutedNoteThreadQuery(query, me);
}
if (ps.withFiles) {

View file

@ -147,8 +147,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
const [
followings,
mutedThreads,
] = await Promise.all([
this.cacheService.userFollowingsCache.fetch(me.id),
this.cacheService.threadMutingsCache.fetch(me.id),
]);
const redisTimeline = await this.fanoutTimelineEndpointService.timeline({
@ -167,6 +169,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
if (!followings.has(note.reply.userId) && note.reply.userId !== me.id) return false;
}
if (mutedThreads.has(note.threadId ?? note.id)) {
return false;
}
return true;
},
dbFallback: async (untilId, sinceId, limit) => await this.getFromDb({
@ -230,6 +236,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
this.queryService.generateSilencedUserQueryForNotes(query, me);
this.queryService.generateMutedUserQueryForNotes(query, me);
this.queryService.generateBlockedUserQueryForNotes(query, me);
this.queryService.generateMutedNoteThreadQuery(query, me);
if (ps.withFiles) {
query.andWhere('note.fileIds != \'{}\'');

View file

@ -15,6 +15,7 @@ import { IdService } from '@/core/IdService.js';
import { QueryService } from '@/core/QueryService.js';
import { MiLocalUser } from '@/models/User.js';
import { FanoutTimelineEndpointService } from '@/core/FanoutTimelineEndpointService.js';
import { CacheService } from '@/core/CacheService.js';
import { ApiError } from '../../error.js';
export const meta = {
@ -83,6 +84,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
private idService: IdService,
private fanoutTimelineEndpointService: FanoutTimelineEndpointService,
private queryService: QueryService,
private readonly cacheService: CacheService,
) {
super(meta, paramDef, async (ps, me) => {
const untilId = ps.untilId ?? (ps.untilDate ? this.idService.gen(ps.untilDate!) : null);
@ -115,6 +117,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
return await this.noteEntityService.packMany(timeline, me);
}
const mutedThreads = me ? await this.cacheService.threadMutingsCache.fetch(me.id) : null;
const timeline = await this.fanoutTimelineEndpointService.timeline({
untilId,
sinceId,
@ -139,6 +143,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
withBots: ps.withBots,
withRenotes: ps.withRenotes,
}, me),
noteFilter: note => {
if (mutedThreads?.has(note.threadId ?? note.id)) {
return false;
}
return true;
},
});
if (me) {
@ -185,6 +196,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
if (me) {
this.queryService.generateMutedUserQueryForNotes(query, me);
this.queryService.generateBlockedUserQueryForNotes(query, me);
this.queryService.generateMutedNoteThreadQuery(query, me);
}
if (ps.withFiles) {

View file

@ -7,6 +7,7 @@ import { Inject, Injectable } from '@nestjs/common';
import type { NotesRepository, NoteThreadMutingsRepository, NoteFavoritesRepository } from '@/models/_.js';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { DI } from '@/di-symbols.js';
import { CacheService } from '@/core/CacheService.js';
export const meta = {
tags: ['notes'],
@ -55,30 +56,25 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
@Inject(DI.noteFavoritesRepository)
private noteFavoritesRepository: NoteFavoritesRepository,
private readonly cacheService: CacheService,
) {
super(meta, paramDef, async (ps, me) => {
const note = await this.notesRepository.findOneByOrFail({ id: ps.noteId });
const [favorite, threadMuting] = await Promise.all([
this.noteFavoritesRepository.count({
this.noteFavoritesRepository.exists({
where: {
userId: me.id,
noteId: note.id,
},
take: 1,
}),
this.noteThreadMutingsRepository.count({
where: {
userId: me.id,
threadId: note.threadId ?? note.id,
},
take: 1,
}),
this.cacheService.threadMutingsCache.fetch(me.id).then(ms => ms.has(note.threadId ?? note.id)),
]);
return {
isFavorited: favorite !== 0,
isMutedThread: threadMuting !== 0,
isFavorited: favorite,
isMutedThread: threadMuting,
};
});
}

View file

@ -10,6 +10,7 @@ import { IdService } from '@/core/IdService.js';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { GetterService } from '@/server/api/GetterService.js';
import { DI } from '@/di-symbols.js';
import { CacheService } from '@/core/CacheService.js';
import { ApiError } from '../../../error.js';
export const meta = {
@ -52,6 +53,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
private getterService: GetterService,
private idService: IdService,
private readonly cacheService: CacheService,
) {
super(meta, paramDef, async (ps, me) => {
const note = await this.getterService.getNote(ps.noteId).catch(err => {
@ -59,6 +61,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
throw err;
});
/*
const mutedNotes = await this.notesRepository.find({
where: [{
id: note.threadId ?? note.id,
@ -66,12 +69,15 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
threadId: note.threadId ?? note.id,
}],
});
*/
await this.noteThreadMutingsRepository.insert({
id: this.idService.gen(),
threadId: note.threadId ?? note.id,
userId: me.id,
});
await this.cacheService.threadMutingsCache.refresh(me.id);
});
}
}

View file

@ -8,6 +8,7 @@ import type { NoteThreadMutingsRepository } from '@/models/_.js';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { GetterService } from '@/server/api/GetterService.js';
import { DI } from '@/di-symbols.js';
import { CacheService } from '@/core/CacheService.js';
import { ApiError } from '../../../error.js';
export const meta = {
@ -47,6 +48,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
private noteThreadMutingsRepository: NoteThreadMutingsRepository,
private getterService: GetterService,
private readonly cacheService: CacheService,
) {
super(meta, paramDef, async (ps, me) => {
const note = await this.getterService.getNote(ps.noteId).catch(err => {
@ -58,6 +60,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
threadId: note.threadId ?? note.id,
userId: me.id,
});
await this.cacheService.threadMutingsCache.refresh(me.id);
});
}
}

View file

@ -99,8 +99,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
const [
followings,
threadMutings,
] = await Promise.all([
this.cacheService.userFollowingsCache.fetch(me.id),
this.cacheService.threadMutingsCache.fetch(me.id),
]);
const timeline = this.fanoutTimelineEndpointService.timeline({
@ -119,6 +121,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
}
if (!ps.withBots && note.user?.isBot) return false;
if (threadMutings.has(note.threadId ?? note.id)) return false;
return true;
},
dbFallback: async (untilId, sinceId, limit) => await this.getFromDb({
@ -167,6 +171,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
this.queryService.generateSilencedUserQueryForNotes(query, me);
this.queryService.generateMutedUserQueryForNotes(query, me);
this.queryService.generateBlockedUserQueryForNotes(query, me);
this.queryService.generateMutedNoteThreadQuery(query, me);
if (ps.withFiles) {
query.andWhere('note.fileIds != \'{}\'');

View file

@ -42,6 +42,7 @@ export default class Connection {
public userIdsWhoBlockingMe: Set<string> = new Set();
public userIdsWhoMeMutingRenotes: Set<string> = new Set();
public userMutedInstances: Set<string> = new Set();
public userMutedThreads: Set<string> = new Set();
private fetchIntervalId: NodeJS.Timeout | null = null;
private closingConnection = false;
private logger: Logger;
@ -67,13 +68,14 @@ export default class Connection {
@bindThis
public async fetch() {
if (this.user == null) return;
const [userProfile, following, followingChannels, userIdsWhoMeMuting, userIdsWhoBlockingMe, userIdsWhoMeMutingRenotes] = await Promise.all([
const [userProfile, following, followingChannels, userIdsWhoMeMuting, userIdsWhoBlockingMe, userIdsWhoMeMutingRenotes, threadMutings] = await Promise.all([
this.cacheService.userProfileCache.fetch(this.user.id),
this.cacheService.userFollowingsCache.fetch(this.user.id),
this.channelFollowingService.userFollowingChannelsCache.fetch(this.user.id),
this.cacheService.userMutingsCache.fetch(this.user.id),
this.cacheService.userBlockedCache.fetch(this.user.id),
this.cacheService.renoteMutingsCache.fetch(this.user.id),
this.cacheService.threadMutingsCache.fetch(this.user.id),
]);
this.userProfile = userProfile;
this.following = following;
@ -82,6 +84,7 @@ export default class Connection {
this.userIdsWhoBlockingMe = userIdsWhoBlockingMe;
this.userIdsWhoMeMutingRenotes = userIdsWhoMeMutingRenotes;
this.userMutedInstances = new Set(userProfile.mutedInstances);
this.userMutedThreads = threadMutings;
}
@bindThis

View file

@ -53,6 +53,10 @@ export default abstract class Channel {
return this.connection.userMutedInstances;
}
protected get userMutedThreads() {
return this.connection.userMutedThreads;
}
protected get followingChannels() {
return this.connection.followingChannels;
}
@ -94,6 +98,9 @@ export default abstract class Channel {
// 流れてきたNoteがリートをミュートしてるユーザが行ったもの
if (isRenotePacked(note) && !isQuotePacked(note) && this.userIdsWhoMeMutingRenotes.has(note.user.id)) return true;
// Muted thread
if (this.userMutedThreads.has(note.threadId)) return true;
// If it's a boost (pure renote) then we need to check the target as well
if (isPackedPureRenote(note) && note.renote && this.isNoteMutedOrBlocked(note.renote)) return true;

View file

@ -4652,6 +4652,11 @@ export type components = {
* @example xxxxxxxxxx
*/
id: string;
/**
* Format: id
* @example xxxxxxxxxx
*/
threadId: string;
/** Format: date-time */
createdAt: string;
/** Format: date-time */