2021-03-31 10:43:29 +11:00
|
|
|
import { Reader } from 'protobufjs/minimal';
|
|
|
|
|
2021-05-10 15:12:09 +10:00
|
|
|
import * as proto from '../../proto/chat/v2/chat_message';
|
2021-03-31 10:43:29 +11:00
|
|
|
|
|
|
|
export class ChatMessage {
|
2021-05-10 16:07:43 +10:00
|
|
|
public constructor(public proto: proto.ChatMessage) {}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create Chat Message with a utf-8 string as payload.
|
|
|
|
*/
|
|
|
|
static fromUtf8String(
|
|
|
|
timestamp: Date,
|
|
|
|
nick: string,
|
|
|
|
text: string
|
|
|
|
): ChatMessage {
|
|
|
|
const timestampNumber = Math.floor(timestamp.valueOf() / 1000);
|
|
|
|
const payload = Buffer.from(text, 'utf-8');
|
|
|
|
|
|
|
|
return new ChatMessage({
|
|
|
|
timestamp: timestampNumber,
|
|
|
|
nick,
|
|
|
|
payload,
|
|
|
|
});
|
|
|
|
}
|
2021-03-31 10:43:29 +11:00
|
|
|
|
|
|
|
static decode(bytes: Uint8Array): ChatMessage {
|
2021-05-10 15:12:09 +10:00
|
|
|
const protoMsg = proto.ChatMessage.decode(Reader.create(bytes));
|
2021-05-10 16:07:43 +10:00
|
|
|
return new ChatMessage(protoMsg);
|
2021-03-31 10:43:29 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
encode(): Uint8Array {
|
2021-05-10 16:07:43 +10:00
|
|
|
return proto.ChatMessage.encode(this.proto).finish();
|
|
|
|
}
|
2021-03-31 10:43:29 +11:00
|
|
|
|
2021-05-10 16:07:43 +10:00
|
|
|
get timestamp(): Date {
|
|
|
|
return new Date(this.proto.timestamp * 1000);
|
|
|
|
}
|
|
|
|
|
|
|
|
get nick(): string {
|
|
|
|
return this.proto.nick;
|
|
|
|
}
|
|
|
|
|
|
|
|
get payloadAsUtf8(): string {
|
|
|
|
if (!this.proto.payload) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
return Array.from(this.proto.payload)
|
|
|
|
.map((char) => {
|
|
|
|
return String.fromCharCode(char);
|
|
|
|
})
|
|
|
|
.join('');
|
2021-03-31 10:43:29 +11:00
|
|
|
}
|
|
|
|
}
|