yumechi-no-kuni/packages/backend/src/server/api/stream/Connection.ts

300 lines
8.2 KiB
TypeScript
Raw Normal View History

/*
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
import * as WebSocket from 'ws';
import type { MiUser } from '@/models/User.js';
import type { MiAccessToken } from '@/models/AccessToken.js';
2023-03-09 23:22:37 -06:00
import type { Packed } from '@/misc/json-schema.js';
2022-09-17 13:27:08 -05:00
import type { NoteReadService } from '@/core/NoteReadService.js';
import type { NotificationService } from '@/core/NotificationService.js';
import { bindThis } from '@/decorators.js';
2023-04-04 20:21:10 -05:00
import { CacheService } from '@/core/CacheService.js';
import { MiFollowing, MiUserProfile } from '@/models/_.js';
2023-09-28 21:29:54 -05:00
import type { StreamEventEmitter, GlobalEvents } from '@/core/GlobalEventService.js';
2022-09-17 13:27:08 -05:00
import type { ChannelsService } from './ChannelsService.js';
import type { EventEmitter } from 'events';
import type Channel from './channel.js';
2020-03-27 21:24:37 -05:00
/**
* Main stream connection
*/
// eslint-disable-next-line import/no-default-export
export default class Connection {
public user?: MiUser;
public token?: MiAccessToken;
private wsConnection: WebSocket.WebSocket;
refactor: publishHogeStreamとStreamのEventEmitterに型定義する (#7769) * wip * wip * wip * :v: * add main stream * packedNotificationSchemaを更新 * read:gallery, write:gallery, read:gallery-likes, write:gallery-likesに翻訳を追加 * fix * ok * add header, choice, invitation * add header, choice, invitation * test * fix * fix * yatta * remove no longer needed "as PackedUser/PackedNote" * clean up * add simple-schema * fix lint * fix lint * wip * wip! * wip * fix * wip * wip * :v: * 送信側に型エラーがないことを3回確認した * :v: * wip * update typescript * define items in full Schema * edit comment * edit comment * edit comment * Update src/prelude/types.ts Co-authored-by: Acid Chicken (硫酸鶏) <root@acid-chicken.com> * https://github.com/misskey-dev/misskey/pull/7769#discussion_r703058458 * user packとnote packの型不整合を修正 * revert https://github.com/misskey-dev/misskey/pull/7772#discussion_r706627736 * revert https://github.com/misskey-dev/misskey/pull/7772#discussion_r706627736 * user packとnote packの型不整合を修正 * add prelude/types.ts * emoji * signin * game * matching * clean up * ev => data * refactor * clean up * add type * antenna * channel * fix * add Packed type * add PackedRef * fix lint * add emoji schema * add reversiGame * add reversiMatching * remove signin schema (use Signin entity) * add schemas refs, fix Packed type * wip PackedHoge => Packed<'Hoge'> * add Packed type * note-reaction * user * user-group * user-list * note * app, messaging-message * notification * drive-file * drive-folder * following * muting * blocking * hashtag * page * app (with modifying schema) * import user? * channel * antenna * clip * gallery-post * emoji * Packed * reversi-matching * update stream.ts * https://github.com/misskey-dev/misskey/pull/7769#issuecomment-917542339 * fix lint * clean up? * add changelog * add changelog * add changelog * fix: アンテナが既読にならないのを修正 * revert fix * https://github.com/misskey-dev/misskey/pull/7769#discussion_r711474875 * spec => payload * edit commetn Co-authored-by: Acid Chicken (硫酸鶏) <root@acid-chicken.com>
2021-10-20 11:04:10 -05:00
public subscriber: StreamEventEmitter;
private channels: Channel[] = [];
private subscribingNotes: any = {};
private cachedNotes: Packed<'Note'>[] = [];
public userProfile: MiUserProfile | null = null;
public following: Record<string, Pick<MiFollowing, 'withReplies'> | undefined> = {};
2023-04-04 20:21:10 -05:00
public followingChannels: Set<string> = new Set();
public userIdsWhoMeMuting: Set<string> = new Set();
public userIdsWhoBlockingMe: Set<string> = new Set();
public userIdsWhoMeMutingRenotes: Set<string> = new Set();
private fetchIntervalId: NodeJS.Timeout | null = null;
constructor(
2022-09-17 13:27:08 -05:00
private channelsService: ChannelsService,
private noteReadService: NoteReadService,
private notificationService: NotificationService,
2023-04-04 20:21:10 -05:00
private cacheService: CacheService,
2022-09-17 13:27:08 -05:00
user: MiUser | null | undefined,
token: MiAccessToken | null | undefined,
) {
if (user) this.user = user;
2020-03-28 04:07:41 -05:00
if (token) this.token = token;
2023-04-04 20:21:10 -05:00
}
2023-04-04 20:21:10 -05:00
@bindThis
public async fetch() {
if (this.user == null) return;
const [userProfile, following, followingChannels, userIdsWhoMeMuting, userIdsWhoBlockingMe, userIdsWhoMeMutingRenotes] = await Promise.all([
this.cacheService.userProfileCache.fetch(this.user.id),
this.cacheService.userFollowingsCache.fetch(this.user.id),
this.cacheService.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.userProfile = userProfile;
this.following = following;
this.followingChannels = followingChannels;
this.userIdsWhoMeMuting = userIdsWhoMeMuting;
this.userIdsWhoBlockingMe = userIdsWhoBlockingMe;
this.userIdsWhoMeMutingRenotes = userIdsWhoMeMutingRenotes;
}
2020-04-02 08:17:17 -05:00
2023-04-04 20:21:10 -05:00
@bindThis
public async init() {
if (this.user != null) {
await this.fetch();
if (!this.fetchIntervalId) {
this.fetchIntervalId = setInterval(this.fetch, 1000 * 10);
}
}
}
@bindThis
public async listen(subscriber: EventEmitter, wsConnection: WebSocket.WebSocket) {
this.subscriber = subscriber;
2023-04-04 20:21:10 -05:00
this.wsConnection = wsConnection;
this.wsConnection.on('message', this.onWsConnectionMessage);
this.subscriber.on('broadcast', data => {
this.onBroadcastMessage(data);
});
}
/**
*
*/
@bindThis
private async onWsConnectionMessage(data: WebSocket.RawData) {
let obj: Record<string, any>;
try {
obj = JSON.parse(data.toString());
} catch (e) {
return;
}
const { type, body } = obj;
switch (type) {
case 'readNotification': this.onReadNotification(body); break;
2021-03-21 03:38:09 -05:00
case 'subNote': this.onSubscribeNote(body); break;
case 's': this.onSubscribeNote(body); break; // alias
case 'sr': this.onSubscribeNote(body); this.readNote(body); break;
case 'unsubNote': this.onUnsubscribeNote(body); break;
case 'un': this.onUnsubscribeNote(body); break; // alias
case 'connect': this.onChannelConnectRequested(body); break;
case 'disconnect': this.onChannelDisconnectRequested(body); break;
case 'channel': this.onChannelMessageRequested(body); break;
2018-10-09 13:24:09 -05:00
case 'ch': this.onChannelMessageRequested(body); break; // alias
}
}
@bindThis
2023-09-28 21:29:54 -05:00
private onBroadcastMessage(data: GlobalEvents['broadcast']['payload']) {
refactor: publishHogeStreamとStreamのEventEmitterに型定義する (#7769) * wip * wip * wip * :v: * add main stream * packedNotificationSchemaを更新 * read:gallery, write:gallery, read:gallery-likes, write:gallery-likesに翻訳を追加 * fix * ok * add header, choice, invitation * add header, choice, invitation * test * fix * fix * yatta * remove no longer needed "as PackedUser/PackedNote" * clean up * add simple-schema * fix lint * fix lint * wip * wip! * wip * fix * wip * wip * :v: * 送信側に型エラーがないことを3回確認した * :v: * wip * update typescript * define items in full Schema * edit comment * edit comment * edit comment * Update src/prelude/types.ts Co-authored-by: Acid Chicken (硫酸鶏) <root@acid-chicken.com> * https://github.com/misskey-dev/misskey/pull/7769#discussion_r703058458 * user packとnote packの型不整合を修正 * revert https://github.com/misskey-dev/misskey/pull/7772#discussion_r706627736 * revert https://github.com/misskey-dev/misskey/pull/7772#discussion_r706627736 * user packとnote packの型不整合を修正 * add prelude/types.ts * emoji * signin * game * matching * clean up * ev => data * refactor * clean up * add type * antenna * channel * fix * add Packed type * add PackedRef * fix lint * add emoji schema * add reversiGame * add reversiMatching * remove signin schema (use Signin entity) * add schemas refs, fix Packed type * wip PackedHoge => Packed<'Hoge'> * add Packed type * note-reaction * user * user-group * user-list * note * app, messaging-message * notification * drive-file * drive-folder * following * muting * blocking * hashtag * page * app (with modifying schema) * import user? * channel * antenna * clip * gallery-post * emoji * Packed * reversi-matching * update stream.ts * https://github.com/misskey-dev/misskey/pull/7769#issuecomment-917542339 * fix lint * clean up? * add changelog * add changelog * add changelog * fix: アンテナが既読にならないのを修正 * revert fix * https://github.com/misskey-dev/misskey/pull/7769#discussion_r711474875 * spec => payload * edit commetn Co-authored-by: Acid Chicken (硫酸鶏) <root@acid-chicken.com>
2021-10-20 11:04:10 -05:00
this.sendMessageToWs(data.type, data.body);
2020-04-02 08:17:17 -05:00
}
@bindThis
public cacheNote(note: Packed<'Note'>) {
const add = (note: Packed<'Note'>) => {
2021-03-21 03:38:09 -05:00
const existIndex = this.cachedNotes.findIndex(n => n.id === note.id);
if (existIndex > -1) {
this.cachedNotes[existIndex] = note;
return;
}
this.cachedNotes.unshift(note);
if (this.cachedNotes.length > 32) {
this.cachedNotes.splice(32);
}
};
add(note);
if (note.reply) add(note.reply);
if (note.renote) add(note.renote);
2021-03-21 03:38:09 -05:00
}
@bindThis
2021-03-21 03:38:09 -05:00
private readNote(body: any) {
const id = body.id;
const note = this.cachedNotes.find(n => n.id === id);
if (note == null) return;
if (this.user && (note.userId !== this.user.id)) {
this.noteReadService.read(this.user.id, [note]);
2021-03-21 03:38:09 -05:00
}
}
@bindThis
private onReadNotification(payload: any) {
this.notificationService.readAllNotification(this.user!.id);
}
/**
* 稿
*/
@bindThis
2021-03-21 03:38:09 -05:00
private onSubscribeNote(payload: any) {
if (!payload.id) return;
if (this.subscribingNotes[payload.id] == null) {
this.subscribingNotes[payload.id] = 0;
}
this.subscribingNotes[payload.id]++;
2020-03-28 20:39:36 -05:00
if (this.subscribingNotes[payload.id] === 1) {
this.subscriber.on(`noteStream:${payload.id}`, this.onNoteStreamMessage);
}
}
/**
* 稿
*/
@bindThis
private onUnsubscribeNote(payload: any) {
if (!payload.id) return;
this.subscribingNotes[payload.id]--;
if (this.subscribingNotes[payload.id] <= 0) {
delete this.subscribingNotes[payload.id];
this.subscriber.off(`noteStream:${payload.id}`, this.onNoteStreamMessage);
}
}
@bindThis
2023-09-28 21:29:54 -05:00
private async onNoteStreamMessage(data: GlobalEvents['note']['payload']) {
this.sendMessageToWs('noteUpdated', {
id: data.body.id,
type: data.type,
body: data.body.body,
});
}
/**
*
*/
@bindThis
private onChannelConnectRequested(payload: any) {
const { channel, id, params, pong } = payload;
this.connectChannel(id, params, channel, pong);
}
/**
*
*/
@bindThis
private onChannelDisconnectRequested(payload: any) {
const { id } = payload;
this.disconnectChannel(id);
}
/**
*
*/
@bindThis
public sendMessageToWs(type: string, payload: any) {
this.wsConnection.send(JSON.stringify({
type: type,
2021-12-09 08:58:30 -06:00
body: payload,
}));
}
/**
*
*/
@bindThis
public connectChannel(id: string, params: any, channel: string, pong = false) {
2022-09-17 13:27:08 -05:00
const channelService = this.channelsService.getChannelService(channel);
if (channelService.requireCredential && this.user == null) {
2018-11-10 11:22:34 -06:00
return;
}
// 共有可能チャンネルに接続しようとしていて、かつそのチャンネルに既に接続していたら無意味なので無視
2022-09-17 13:27:08 -05:00
if (channelService.shouldShare && this.channels.some(c => c.chName === channel)) {
return;
}
2022-09-17 13:27:08 -05:00
const ch: Channel = channelService.create(id, this);
this.channels.push(ch);
2023-05-16 21:10:31 -05:00
ch.init(params ?? {});
if (pong) {
this.sendMessageToWs('connected', {
2021-12-09 08:58:30 -06:00
id: id,
});
}
}
/**
*
2018-10-07 03:06:28 -05:00
* @param id ID
*/
@bindThis
2018-10-07 03:19:52 -05:00
public disconnectChannel(id: string) {
const channel = this.channels.find(c => c.id === id);
if (channel) {
if (channel.dispose) channel.dispose();
this.channels = this.channels.filter(c => c.id !== id);
}
}
2018-10-07 03:06:28 -05:00
/**
*
* @param data
*/
@bindThis
private onChannelMessageRequested(data: any) {
const channel = this.channels.find(c => c.id === data.id);
if (channel != null && channel.onMessage != null) {
channel.onMessage(data.type, data.body);
}
}
/**
*
*/
@bindThis
public dispose() {
2023-04-04 20:21:10 -05:00
if (this.fetchIntervalId) clearInterval(this.fetchIntervalId);
for (const c of this.channels.filter(c => c.dispose)) {
if (c.dispose) c.dispose();
}
}
}