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
|
|
|
|
2021-04-21 15:51:52 +10:00
|
|
|
// TODO: Move to waku library?
|
2021-03-31 10:43:29 +11:00
|
|
|
export class ChatMessage {
|
|
|
|
public constructor(
|
|
|
|
public timestamp: Date,
|
|
|
|
public nick: string,
|
|
|
|
public message: string
|
|
|
|
) {}
|
|
|
|
|
|
|
|
static decode(bytes: Uint8Array): ChatMessage {
|
2021-05-10 15:12:09 +10:00
|
|
|
const protoMsg = proto.ChatMessage.decode(Reader.create(bytes));
|
2021-03-31 10:43:29 +11:00
|
|
|
const timestamp = new Date(protoMsg.timestamp * 1000);
|
|
|
|
const message = protoMsg.payload
|
|
|
|
? Array.from(protoMsg.payload)
|
|
|
|
.map((char) => {
|
|
|
|
return String.fromCharCode(char);
|
|
|
|
})
|
|
|
|
.join('')
|
|
|
|
: '';
|
|
|
|
return new ChatMessage(timestamp, protoMsg.nick, message);
|
|
|
|
}
|
|
|
|
|
|
|
|
encode(): Uint8Array {
|
|
|
|
const timestamp = Math.floor(this.timestamp.valueOf() / 1000);
|
|
|
|
const payload = Buffer.from(this.message, 'utf-8');
|
|
|
|
|
2021-05-10 15:12:09 +10:00
|
|
|
return proto.ChatMessage.encode({
|
2021-03-31 10:43:29 +11:00
|
|
|
timestamp,
|
|
|
|
nick: this.nick,
|
|
|
|
payload,
|
|
|
|
}).finish();
|
|
|
|
}
|
|
|
|
}
|