hippofish/src/server/api/stream/channels/messaging.ts

105 lines
2.8 KiB
TypeScript
Raw Normal View History

import autobind from 'autobind-decorator';
import { readUserMessagingMessage, readGroupMessagingMessage, deliverReadActivity } from '../../common/read-messaging-message';
import Channel from '../channel';
import { UserGroupJoinings, Users, MessagingMessages } from '../../../../models';
import { User, ILocalUser, IRemoteUser } from '../../../../models/entities/user';
export default class extends Channel {
public readonly chName = 'messaging';
2018-10-11 16:07:20 +02:00
public static shouldShare = false;
2018-11-10 18:22:34 +01:00
public static requireCredential = true;
2019-05-18 13:36:33 +02:00
private otherpartyId: string | null;
private otherparty?: User;
2019-05-18 13:36:33 +02:00
private groupId: string | null;
private subCh: string;
private typers: Record<User['id'], Date> = {};
private emitTypersIntervalId: ReturnType<typeof setInterval>;
@autobind
public async init(params: any) {
this.otherpartyId = params.otherparty as string;
this.otherparty = await Users.findOne({ id: this.otherpartyId });
2019-05-18 13:36:33 +02:00
this.groupId = params.group as string;
// Check joining
if (this.groupId) {
const joining = await UserGroupJoinings.findOne({
userId: this.user!.id,
userGroupId: this.groupId
});
if (joining == null) {
return;
}
}
this.emitTypersIntervalId = setInterval(this.emitTypers, 5000);
this.subCh = this.otherpartyId
2019-05-18 13:36:33 +02:00
? `messagingStream:${this.user!.id}-${this.otherpartyId}`
: `messagingStream:${this.groupId}`;
// Subscribe messaging stream
this.subscriber.on(this.subCh, this.onEvent);
}
@autobind
private onEvent(data: any) {
if (data.type === 'typing') {
const id = data.body;
const begin = this.typers[id] == null;
this.typers[id] = new Date();
if (begin) {
this.emitTypers();
}
} else {
this.send(data);
}
}
@autobind
public onMessage(type: string, body: any) {
switch (type) {
case 'read':
2019-05-18 13:36:33 +02:00
if (this.otherpartyId) {
readUserMessagingMessage(this.user!.id, this.otherpartyId, [body.id]);
// リモートユーザーからのメッセージだったら既読配信
if (Users.isLocalUser(this.user!) && Users.isRemoteUser(this.otherparty!)) {
MessagingMessages.findOne(body.id).then(message => {
if (message) deliverReadActivity(this.user as ILocalUser, this.otherparty as IRemoteUser, message);
});
}
2019-05-18 13:36:33 +02:00
} else if (this.groupId) {
readGroupMessagingMessage(this.user!.id, this.groupId, [body.id]);
}
break;
}
}
@autobind
private async emitTypers() {
const now = new Date();
// Remove not typing users
for (const [userId, date] of Object.entries(this.typers)) {
if (now.getTime() - date.getTime() > 5000) delete this.typers[userId];
}
const users = await Users.packMany(Object.keys(this.typers), null, { detail: false });
this.send({
type: 'typers',
body: users,
});
}
@autobind
public dispose() {
this.subscriber.off(this.subCh, this.onEvent);
2021-02-21 05:38:03 +01:00
clearInterval(this.emitTypersIntervalId);
}
}