Skip to content

Commit

Permalink
feat: notification grouping
Browse files Browse the repository at this point in the history
Resolve #12211
  • Loading branch information
syuilo committed Nov 2, 2023
1 parent c7129d5 commit f62ad3e
Show file tree
Hide file tree
Showing 19 changed files with 581 additions and 66 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
- Feat: プラグイン・テーマを外部サイトから直接インストールできるようになりました
- 外部サイトでの実装が必要です。詳細は Misskey Hub をご覧ください
https://misskey-hub.net/docs/advanced/publish-on-your-website.html
- Enhance: スワイプしてタイムラインを再読込できるように
- Feat: 通知をグルーピングして表示するオプション(オプトアウト)
- Feat: スワイプしてタイムラインを再読込できるように
- PCの場合は右上のボタンからでも再読込できます
- Enhance: タイムラインの自動更新を無効にできるように
- Enhance: コードのシンタックスハイライトエンジンをShikiに変更
Expand Down
4 changes: 4 additions & 0 deletions locales/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1157,6 +1157,7 @@ export interface Locale {
"refreshing": string;
"pullDownToRefresh": string;
"disableStreamingTimeline": string;
"useGroupedNotifications": string;
"_announcement": {
"forExistingUsers": string;
"forExistingUsersDescription": string;
Expand Down Expand Up @@ -2200,6 +2201,9 @@ export interface Locale {
"checkNotificationBehavior": string;
"sendTestNotification": string;
"notificationWillBeDisplayedLikeThis": string;
"reactedBySomeUsers": string;
"renotedBySomeUsers": string;
"followedBySomeUsers": string;
"_types": {
"all": string;
"note": string;
Expand Down
4 changes: 4 additions & 0 deletions locales/ja-JP.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1154,6 +1154,7 @@ releaseToRefresh: "離してリロード"
refreshing: "リロード中"
pullDownToRefresh: "引っ張ってリロード"
disableStreamingTimeline: "タイムラインのリアルタイム更新を無効にする"
useGroupedNotifications: "通知をグルーピングして表示する"

_announcement:
forExistingUsers: "既存ユーザーのみ"
Expand Down Expand Up @@ -2114,6 +2115,9 @@ _notification:
checkNotificationBehavior: "通知の表示を確かめる"
sendTestNotification: "テスト通知を送信する"
notificationWillBeDisplayedLikeThis: "通知はこのように表示されます"
reactedBySomeUsers: "{n}人がリアクションしました"
renotedBySomeUsers: "{n}人がリノートしました"
followedBySomeUsers: "{n}人にフォローされました"

_types:
all: "すべて"
Expand Down
19 changes: 8 additions & 11 deletions packages/backend/src/core/NoteCreateService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,17 +100,14 @@ class NotificationManager {
}

@bindThis
public async deliver() {
public async notify() {
for (const x of this.queue) {
// ミュート情報を取得
const mentioneeMutes = await this.mutingsRepository.findBy({
muterId: x.target,
});

const mentioneesMutedUserIds = mentioneeMutes.map(m => m.muteeId);

// 通知される側のユーザーが通知する側のユーザーをミュートしていない限りは通知する
if (!mentioneesMutedUserIds.includes(this.notifier.id)) {
if (x.reason === 'renote') {
this.notificationService.createNotification(x.target, 'renote', {
noteId: this.note.id,
targetNoteId: this.note.renoteId!,
}, this.notifier.id);
} else {
this.notificationService.createNotification(x.target, x.reason, {
noteId: this.note.id,
}, this.notifier.id);
Expand Down Expand Up @@ -642,7 +639,7 @@ export class NoteCreateService implements OnApplicationShutdown {
}
}

nm.deliver();
nm.notify();

//#region AP deliver
if (this.userEntityService.isLocalUser(user)) {
Expand Down
13 changes: 8 additions & 5 deletions packages/backend/src/core/NotificationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { IdService } from '@/core/IdService.js';
import { CacheService } from '@/core/CacheService.js';
import type { Config } from '@/config.js';
import { UserListService } from '@/core/UserListService.js';
import type { FilterUnionByProperty } from '@/types.js';

@Injectable()
export class NotificationService implements OnApplicationShutdown {
Expand Down Expand Up @@ -73,10 +74,10 @@ export class NotificationService implements OnApplicationShutdown {
}

@bindThis
public async createNotification(
public async createNotification<T extends MiNotification['type']>(
notifieeId: MiUser['id'],
type: MiNotification['type'],
data: Omit<Partial<MiNotification>, 'notifierId'>,
type: T,
data: Omit<FilterUnionByProperty<MiNotification, 'type', T>, 'type' | 'id' | 'createdAt' | 'notifierId'>,
notifierId?: MiUser['id'] | null,
): Promise<MiNotification | null> {
const profile = await this.cacheService.userProfileCache.fetch(notifieeId);
Expand Down Expand Up @@ -128,9 +129,11 @@ export class NotificationService implements OnApplicationShutdown {
id: this.idService.gen(),
createdAt: new Date(),
type: type,
notifierId: notifierId,
...(notifierId ? {
notifierId,
} : {}),
...data,
} as MiNotification;
} as any as FilterUnionByProperty<MiNotification, 'type', T>;

const redisIdPromise = this.redisClient.xadd(
`notificationTimeline:${notifieeId}`,
Expand Down
1 change: 0 additions & 1 deletion packages/backend/src/core/UserFollowingService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,6 @@ export class UserFollowingService implements OnModuleInit {

// 通知を作成
this.notificationService.createNotification(followee.id, 'receiveFollowRequest', {
followRequestId: followRequest.id,
}, follower.id);
}

Expand Down
162 changes: 150 additions & 12 deletions packages/backend/src/core/entities/NotificationEntityService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,19 @@ import { In } from 'typeorm';
import { DI } from '@/di-symbols.js';
import type { FollowRequestsRepository, NotesRepository, MiUser, UsersRepository } from '@/models/_.js';
import { awaitAll } from '@/misc/prelude/await-all.js';
import type { MiNotification } from '@/models/Notification.js';
import type { MiGroupedNotification, MiNotification } from '@/models/Notification.js';
import type { MiNote } from '@/models/Note.js';
import type { Packed } from '@/misc/json-schema.js';
import { bindThis } from '@/decorators.js';
import { isNotNull } from '@/misc/is-not-null.js';
import { notificationTypes } from '@/types.js';
import { FilterUnionByProperty, notificationTypes } from '@/types.js';
import type { OnModuleInit } from '@nestjs/common';
import type { CustomEmojiService } from '../CustomEmojiService.js';
import type { UserEntityService } from './UserEntityService.js';
import type { NoteEntityService } from './NoteEntityService.js';

const NOTE_REQUIRED_NOTIFICATION_TYPES = new Set(['note', 'mention', 'reply', 'renote', 'quote', 'reaction', 'pollEnded'] as (typeof notificationTypes[number])[]);
const NOTE_REQUIRED_GROUPED_NOTIFICATION_TYPES = new Set(['note', 'mention', 'reply', 'renote', 'renote:grouped', 'quote', 'reaction', 'reaction:grouped', 'pollEnded']);

@Injectable()
export class NotificationEntityService implements OnModuleInit {
Expand Down Expand Up @@ -66,17 +67,17 @@ export class NotificationEntityService implements OnModuleInit {
},
): Promise<Packed<'Notification'>> {
const notification = src;
const noteIfNeed = NOTE_REQUIRED_NOTIFICATION_TYPES.has(notification.type) && notification.noteId != null ? (
const noteIfNeed = NOTE_REQUIRED_NOTIFICATION_TYPES.has(notification.type) && 'noteId' in notification ? (
hint?.packedNotes != null
? hint.packedNotes.get(notification.noteId)
: this.noteEntityService.pack(notification.noteId!, { id: meId }, {
: this.noteEntityService.pack(notification.noteId, { id: meId }, {
detail: true,
})
) : undefined;
const userIfNeed = notification.notifierId != null ? (
const userIfNeed = 'notifierId' in notification ? (
hint?.packedUsers != null
? hint.packedUsers.get(notification.notifierId)
: this.userEntityService.pack(notification.notifierId!, { id: meId }, {
: this.userEntityService.pack(notification.notifierId, { id: meId }, {
detail: false,
})
) : undefined;
Expand All @@ -85,7 +86,7 @@ export class NotificationEntityService implements OnModuleInit {
id: notification.id,
createdAt: new Date(notification.createdAt).toISOString(),
type: notification.type,
userId: notification.notifierId,
userId: 'notifierId' in notification ? notification.notifierId : undefined,
...(userIfNeed != null ? { user: userIfNeed } : {}),
...(noteIfNeed != null ? { note: noteIfNeed } : {}),
...(notification.type === 'reaction' ? {
Expand All @@ -111,7 +112,7 @@ export class NotificationEntityService implements OnModuleInit {

let validNotifications = notifications;

const noteIds = validNotifications.map(x => x.noteId).filter(isNotNull);
const noteIds = validNotifications.map(x => 'noteId' in x ? x.noteId : null).filter(isNotNull);
const notes = noteIds.length > 0 ? await this.notesRepository.find({
where: { id: In(noteIds) },
relations: ['user', 'reply', 'reply.user', 'renote', 'renote.user'],
Expand All @@ -121,9 +122,9 @@ export class NotificationEntityService implements OnModuleInit {
});
const packedNotes = new Map(packedNotesArray.map(p => [p.id, p]));

validNotifications = validNotifications.filter(x => x.noteId == null || packedNotes.has(x.noteId));
validNotifications = validNotifications.filter(x => !('noteId' in x) || packedNotes.has(x.noteId));

const userIds = validNotifications.map(x => x.notifierId).filter(isNotNull);
const userIds = validNotifications.map(x => 'notifierId' in x ? x.notifierId : null).filter(isNotNull);
const users = userIds.length > 0 ? await this.usersRepository.find({
where: { id: In(userIds) },
}) : [];
Expand All @@ -133,10 +134,10 @@ export class NotificationEntityService implements OnModuleInit {
const packedUsers = new Map(packedUsersArray.map(p => [p.id, p]));

// 既に解決されたフォローリクエストの通知を除外
const followRequestNotifications = validNotifications.filter(x => x.type === 'receiveFollowRequest');
const followRequestNotifications = validNotifications.filter((x): x is FilterUnionByProperty<MiGroupedNotification, 'type', 'receiveFollowRequest'> => x.type === 'receiveFollowRequest');
if (followRequestNotifications.length > 0) {
const reqs = await this.followRequestsRepository.find({
where: { followerId: In(followRequestNotifications.map(x => x.notifierId!)) },
where: { followerId: In(followRequestNotifications.map(x => x.notifierId)) },
});
validNotifications = validNotifications.filter(x => (x.type !== 'receiveFollowRequest') || reqs.some(r => r.followerId === x.notifierId));
}
Expand All @@ -146,4 +147,141 @@ export class NotificationEntityService implements OnModuleInit {
packedUsers,
})));
}

@bindThis
public async packGrouped(
src: MiGroupedNotification,
meId: MiUser['id'],
// eslint-disable-next-line @typescript-eslint/ban-types
options: {

},
hint?: {
packedNotes: Map<MiNote['id'], Packed<'Note'>>;
packedUsers: Map<MiUser['id'], Packed<'User'>>;
},
): Promise<Packed<'Notification'>> {
const notification = src;
const noteIfNeed = NOTE_REQUIRED_GROUPED_NOTIFICATION_TYPES.has(notification.type) && 'noteId' in notification ? (
hint?.packedNotes != null
? hint.packedNotes.get(notification.noteId)
: this.noteEntityService.pack(notification.noteId, { id: meId }, {
detail: true,
})
) : undefined;
const userIfNeed = 'notifierId' in notification ? (
hint?.packedUsers != null
? hint.packedUsers.get(notification.notifierId)
: this.userEntityService.pack(notification.notifierId, { id: meId }, {
detail: false,
})
) : undefined;

if (notification.type === 'reaction:grouped') {
const reactions = await Promise.all(notification.reactions.map(async reaction => {
const user = hint?.packedUsers != null
? hint.packedUsers.get(reaction.userId)!
: await this.userEntityService.pack(reaction.userId, { id: meId }, {
detail: false,
});
return {
user,
reaction: reaction.reaction,
};
}));
return await awaitAll({
id: notification.id,
createdAt: new Date(notification.createdAt).toISOString(),
type: notification.type,
note: noteIfNeed,
reactions,
});
} else if (notification.type === 'renote:grouped') {
const users = await Promise.all(notification.userIds.map(userId => {
const user = hint?.packedUsers != null
? hint.packedUsers.get(userId)
: this.userEntityService.pack(userId!, { id: meId }, {
detail: false,
});
return user;
}));
return await awaitAll({
id: notification.id,
createdAt: new Date(notification.createdAt).toISOString(),
type: notification.type,
note: noteIfNeed,
users,
});
}

return await awaitAll({
id: notification.id,
createdAt: new Date(notification.createdAt).toISOString(),
type: notification.type,
userId: 'notifierId' in notification ? notification.notifierId : undefined,
...(userIfNeed != null ? { user: userIfNeed } : {}),
...(noteIfNeed != null ? { note: noteIfNeed } : {}),
...(notification.type === 'reaction' ? {
reaction: notification.reaction,
} : {}),
...(notification.type === 'achievementEarned' ? {
achievement: notification.achievement,
} : {}),
...(notification.type === 'app' ? {
body: notification.customBody,
header: notification.customHeader,
icon: notification.customIcon,
} : {}),
});
}

@bindThis
public async packGroupedMany(
notifications: MiGroupedNotification[],
meId: MiUser['id'],
) {
if (notifications.length === 0) return [];

let validNotifications = notifications;

const noteIds = validNotifications.map(x => 'noteId' in x ? x.noteId : null).filter(isNotNull);
const notes = noteIds.length > 0 ? await this.notesRepository.find({
where: { id: In(noteIds) },
relations: ['user', 'reply', 'reply.user', 'renote', 'renote.user'],
}) : [];
const packedNotesArray = await this.noteEntityService.packMany(notes, { id: meId }, {
detail: true,
});
const packedNotes = new Map(packedNotesArray.map(p => [p.id, p]));

validNotifications = validNotifications.filter(x => !('noteId' in x) || packedNotes.has(x.noteId));

const userIds = [];
for (const notification of validNotifications) {
if ('notifierId' in notification) userIds.push(notification.notifierId);
if (notification.type === 'reaction:grouped') userIds.push(...notification.reactions.map(x => x.userId));
if (notification.type === 'renote:grouped') userIds.push(...notification.userIds);
}
const users = userIds.length > 0 ? await this.usersRepository.find({
where: { id: In(userIds) },
}) : [];
const packedUsersArray = await this.userEntityService.packMany(users, { id: meId }, {
detail: false,
});
const packedUsers = new Map(packedUsersArray.map(p => [p.id, p]));

// 既に解決されたフォローリクエストの通知を除外
const followRequestNotifications = validNotifications.filter((x): x is FilterUnionByProperty<MiGroupedNotification, 'type', 'receiveFollowRequest'> => x.type === 'receiveFollowRequest');
if (followRequestNotifications.length > 0) {
const reqs = await this.followRequestsRepository.find({
where: { followerId: In(followRequestNotifications.map(x => x.notifierId)) },
});
validNotifications = validNotifications.filter(x => (x.type !== 'receiveFollowRequest') || reqs.some(r => r.followerId === x.notifierId));
}

return await Promise.all(validNotifications.map(x => this.packGrouped(x, meId, {}, {
packedNotes,
packedUsers,
})));
}
}
Loading

0 comments on commit f62ad3e

Please sign in to comment.