-
Notifications
You must be signed in to change notification settings - Fork 36
/
chat.ts
671 lines (566 loc) · 17.2 KB
/
chat.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
import { PageDirection } from '@waku/interfaces'
import { createDecoder } from '@waku/message-encryption/symmetric'
import { containsOnlyEmoji } from '../helpers/contains-only-emoji'
import { ApplicationMetadataMessage_Type } from '../protos/application-metadata-message_pb'
import {
ChatMessage as ChatMessageProto,
ChatMessage_ContentType,
DeleteMessage,
EditMessage,
} from '../protos/chat-message_pb'
import { EmojiReaction, EmojiReaction_Type } from '../protos/emoji-reaction_pb'
import { MessageType } from '../protos/enums_pb'
import { createChannelURLWithChatKey } from '../utils/create-url'
import { generateKeyFromPassword } from '../utils/generate-key-from-password'
import { getNextClock } from '../utils/get-next-clock'
import { idToContentTopic } from '../utils/id-to-content-topic'
import { getReactions } from './community/get-reactions'
import type { ImageMessage } from '../protos/chat-message_pb'
import type { CommunityChat as CommunityChatProto } from '../protos/communities_pb'
import type { Client } from './client'
import type { Community } from './community/community'
import type { Reactions } from './community/get-reactions'
import type { Member } from './member'
import type { PlainMessage } from '@bufbuild/protobuf'
export { ChatMessage_ContentType as ChatMessageContentType } from '../protos/chat-message_pb'
export type CommunityChat = PlainMessage<CommunityChatProto>
export type ChatMessage = PlainMessage<ChatMessageProto> & {
messageId: string
pinned: boolean
reactions: Reactions
chatUuid: string
signer: string
member: Member
communityDisplayName: string
chatDisplayName: string
responseToMessage?: ChatMessage
edittedClock?: bigint
pinnedClock?: bigint
}
type FetchedMessage = { messageId: string; timestamp?: Date }
export class Chat {
private readonly client: Client
#clock: bigint
public readonly uuid: string
public readonly id: string
public readonly contentTopic: string
public readonly type: MessageType.COMMUNITY_CHAT
public readonly symmetricKey: Uint8Array
public description: CommunityChat
public readonly chatCallbacks: Set<(description: CommunityChat) => void>
#messages: Map<string, ChatMessage>
#editTextEvents: Map<string, Pick<ChatMessage, 'clock' | 'signer' | 'text'>>
#pinEvents: Map<string, Pick<ChatMessage, 'clock' | 'pinned'>>
#reactEvents: Map<string, Pick<ChatMessage, 'clock' | 'reactions'>>
#deleteEvents: Map<string, Pick<ChatMessage, 'clock' | 'signer'>>
#isActive: boolean
#fetchingMessages?: boolean
#previousFetchedStartTime?: Date
#oldestFetchedMessage?: FetchedMessage
public readonly messageCallbacks: Set<(messages: ChatMessage[]) => void>
constructor(options: {
client: Client
uuid: string
id: string
contentTopic: string
type: MessageType.COMMUNITY_CHAT
symmetricKey: Uint8Array
description: CommunityChat
}) {
this.client = options.client
this.uuid = options.uuid
this.id = options.id
this.contentTopic = options.contentTopic
this.type = options.type
this.symmetricKey = options.symmetricKey
this.description = options.description
this.#clock = BigInt(Date.now())
this.chatCallbacks = new Set()
this.#messages = new Map()
this.#editTextEvents = new Map()
this.#pinEvents = new Map()
this.#reactEvents = new Map()
this.#deleteEvents = new Map()
this.#isActive = false
this.messageCallbacks = new Set()
}
public static create = async (
community: Community,
client: Client,
uuid: string,
type: MessageType.COMMUNITY_CHAT,
description: CommunityChat,
) => {
const id = `${community.publicKey}${uuid}`
const contentTopic = idToContentTopic(id)
const symmetricKey = await generateKeyFromPassword(id)
return new Chat({
client,
uuid,
id,
contentTopic,
type,
symmetricKey,
description,
})
}
/**
* Returns chat messages soreted in ascending order and reply references resolved.
*/
public getMessages = () => {
const messages: ChatMessage[] = []
for (const message of this.#messages.values()) {
// resolve references
const referencedMessage = this.#messages.get(message.responseTo)
if (referencedMessage) {
message.responseToMessage = referencedMessage
}
messages.push(message)
}
// sort
messages.sort((a, b) => {
if (a.clock < b.clock) {
return -1
}
if (a.clock > b.clock) {
return 1
}
return 0
})
return messages
}
public getMessage = (id: string) => {
return this.#messages.get(id)
}
public get link(): URL {
return createChannelURLWithChatKey(this.uuid, this.client.community.chatKey)
}
public onChange = (callback: (description: CommunityChat) => void) => {
this.chatCallbacks.add(callback)
return () => {
this.chatCallbacks.delete(callback)
}
}
public emitChange = (description: CommunityChat) => {
this.chatCallbacks.forEach(callback => callback(description))
}
public onMessage = (
callback: (messages: ChatMessage[]) => void,
): (() => void) => {
this.messageCallbacks.add(callback)
// todo?: set from ui, think use case without an ui
this.#isActive = true
// todo?!: only if in `unreadChats`, keep "unreads" separate from `notifications`
// todo?: only if at the bottom and all unread messages are in view
// todo?: call from ui
this.client.activityCenter.removeChatNotifications(this.uuid)
return () => {
this.messageCallbacks.delete(callback)
this.#isActive = false
}
}
public fetchMessages = async (options: { start: Date }) => {
const previousOldestMessage = this.#oldestFetchedMessage
const startTime = options.start
// nothing to fetch
if (
previousOldestMessage &&
previousOldestMessage.timestamp &&
previousOldestMessage.timestamp < options.start
) {
return
}
let endTime: Date
if (this.#previousFetchedStartTime) {
endTime = this.#previousFetchedStartTime
} else {
endTime = new Date()
}
await this.client.waku.store.queryWithOrderedCallback(
[
createDecoder(this.contentTopic, this.symmetricKey, {
clusterId: 16,
shard: 32,
}),
],
wakuMessage => {
this.#fetchingMessages = true
this.client.handleWakuMessage(wakuMessage)
this.#fetchingMessages = false
},
{
timeFilter: {
startTime: startTime,
endTime: endTime,
},
pageSize: 50,
// most recent page first
pageDirection: PageDirection.BACKWARD,
},
)
this.#previousFetchedStartTime = startTime
// more chat messages not found
if (
previousOldestMessage &&
this.#oldestFetchedMessage &&
// same message
previousOldestMessage.messageId === this.#oldestFetchedMessage.messageId
) {
return
}
const messages = this.emitMessages()
return messages
}
public emitMessages = () => {
if (this.#fetchingMessages) {
return
}
// fixme?: to stop the loading we need to let the listeners know even if there are no messages
// if (!this.#messages.size) {
// return
// }
const messages = this.getMessages()
this.messageCallbacks.forEach(callback => callback(messages))
return messages
}
public handleChange = (description: CommunityChat) => {
// state
this.description = description
// callback
this.emitChange(description)
}
public handleNewMessage = (newMessage: ChatMessage, timestamp: Date) => {
// fetching in progress
if (this.#fetchingMessages) {
this.#oldestFetchedMessage = this.getOldestFetchedMessage(
this.#oldestFetchedMessage,
newMessage.messageId,
timestamp,
)
}
// delete event received first
const deletedEvent = this.#deleteEvents.get(newMessage.messageId)
if (deletedEvent) {
if (this.isAuthor(newMessage, deletedEvent.signer)) {
return
}
// delete unathorized event from stash
this.#deleteEvents.delete(newMessage.messageId)
}
// message already received
const message = this.#messages.get(newMessage.messageId)
if (message) {
return
}
// action events received prior
const editTextEvent = this.#editTextEvents.get(newMessage.messageId)
if (editTextEvent) {
if (this.isAuthor(newMessage, editTextEvent.signer)) {
newMessage.text = editTextEvent.text
newMessage.edittedClock = editTextEvent.clock
}
// finally, delete event from stash whether it was authorized or not
this.#editTextEvents.delete(newMessage.messageId)
}
const pinEvent = this.#pinEvents.get(newMessage.messageId)
if (pinEvent) {
newMessage.pinned = pinEvent.pinned
newMessage.pinnedClock = pinEvent.clock
this.#pinEvents.delete(newMessage.messageId)
}
const reactEvent = this.#reactEvents.get(newMessage.messageId)
if (reactEvent) {
newMessage.reactions = reactEvent.reactions
this.#reactEvents.delete(newMessage.messageId)
}
// state
this.#messages.set(newMessage.messageId, newMessage)
// callback
this.emitMessages()
// notifications
const isAuthor =
this.client.account !== undefined &&
this.isAuthor(newMessage, `0x${this.client.account.publicKey}`)
if (!this.#isActive && !isAuthor) {
this.client.activityCenter.addMessageNotification(
newMessage,
this.#messages.get(newMessage.responseTo),
)
}
}
public handleEditedMessage = (
messageId: string,
text: string,
clock: bigint,
signerPublicKey: string,
) => {
const message = this.#messages.get(messageId)
if (message && this.isAuthor(message, signerPublicKey)) {
message.text = text
this.emitMessages()
return
}
const editTextEvent = this.#editTextEvents.get(messageId)
if (!editTextEvent || editTextEvent.clock < clock) {
this.#editTextEvents.set(messageId, {
clock,
signer: signerPublicKey,
text,
})
}
}
public handleDeletedMessage = (
messageId: string,
clock: bigint,
signerPublicKey: string,
) => {
const message = this.#messages.get(messageId)
if (message && this.isAuthor(message, signerPublicKey)) {
this.#messages.delete(messageId)
this.#deleteEvents.set(messageId, { clock, signer: signerPublicKey })
this.emitMessages()
return
}
const deleteEvent = this.#deleteEvents.get(messageId)
if (!deleteEvent || deleteEvent.clock > clock) {
this.#deleteEvents.set(messageId, { clock, signer: signerPublicKey })
}
}
public handlePinnedMessage = (
messageId: string,
clock: bigint,
pinned?: boolean,
) => {
const message = this.#messages.get(messageId)
if (message) {
message.pinned = Boolean(pinned)
message.pinnedClock = clock
this.emitMessages()
return
}
const pinEvent = this.#pinEvents.get(messageId)
if (!pinEvent || pinEvent.clock < clock) {
this.#pinEvents.set(messageId, {
clock,
pinned: Boolean(pinned),
})
}
}
public handleEmojiReaction = (
messageId: string,
reaction: EmojiReaction,
clock: bigint,
signerPublicKey: string,
) => {
const message = this.#messages.get(messageId)
if (message) {
const reactions = getReactions(
reaction,
message.reactions,
signerPublicKey,
)
message.reactions = reactions
this.emitMessages()
return
}
const reactEvent = this.#reactEvents.get(messageId)
if (!reactEvent) {
const reactions = getReactions(
reaction,
{
THUMBS_UP: new Set<string>(),
THUMBS_DOWN: new Set<string>(),
LOVE: new Set<string>(),
LAUGH: new Set<string>(),
SAD: new Set<string>(),
ANGRY: new Set<string>(),
},
signerPublicKey,
)
this.#reactEvents.set(messageId, { clock, reactions })
} else {
const reactions = getReactions(
reaction,
reactEvent.reactions,
signerPublicKey,
)
this.#reactEvents.set(messageId, { clock, reactions })
}
}
public sendTextMessage = async (text: string, responseTo?: string) => {
if (text === '') {
throw new Error('Text message cannot be empty')
}
const type = containsOnlyEmoji(text)
? ChatMessage_ContentType.EMOJI
: ChatMessage_ContentType.TEXT_PLAIN
// TODO: protos does not support optional fields :-(
const payload = new ChatMessageProto({
clock: this.setClock(this.#clock),
timestamp: BigInt(Date.now()),
text,
responseTo: responseTo ?? '',
ensName: '',
chatId: this.id,
contentType: type,
messageType: MessageType.COMMUNITY_CHAT,
grant: new Uint8Array([]),
displayName: '',
}).toBinary()
await this.client.sendWakuMessage(
ApplicationMetadataMessage_Type.CHAT_MESSAGE,
payload,
this.contentTopic,
this.symmetricKey,
)
}
public sendImageMessage = async (image: ImageMessage) => {
const payload = new ChatMessageProto({
clock: this.setClock(this.#clock),
timestamp: BigInt(Date.now()),
text: '',
responseTo: '',
ensName: '',
chatId: this.id,
messageType: MessageType.COMMUNITY_CHAT,
contentType: ChatMessage_ContentType.IMAGE,
payload: {
case: 'image',
value: {
format: image.format,
payload: image.payload,
},
},
grant: new Uint8Array([]),
displayName: '',
}).toBinary()
await this.client.sendWakuMessage(
ApplicationMetadataMessage_Type.CHAT_MESSAGE,
payload,
this.contentTopic,
this.symmetricKey,
)
}
public editMessage = async (messageId: string, text: string) => {
if (!this.client.account) {
throw new Error('Text message cannot be edited without a created account')
}
const message = this.#messages.get(messageId)
if (!message) {
throw new Error('Message not found')
}
if (!this.isAuthor(message, `0x${this.client.account.publicKey}`)) {
throw new Error('Text message can only be edited by its author')
}
if (text === '') {
throw new Error('Text message cannot be empty')
}
const payload = new EditMessage({
clock: this.setClock(this.#clock),
text,
messageId,
chatId: this.id,
grant: new Uint8Array([]),
messageType: MessageType.COMMUNITY_CHAT,
}).toBinary()
await this.client.sendWakuMessage(
ApplicationMetadataMessage_Type.EDIT_MESSAGE,
payload,
this.contentTopic,
this.symmetricKey,
)
}
public deleteMessage = async (messageId: string) => {
if (!this.client.account) {
throw new Error(
'Text message cannot be deleted without a created account',
)
}
const message = this.#messages.get(messageId)
if (!message) {
throw new Error('Message not found')
}
if (!this.isAuthor(message, `0x${this.client.account.publicKey}`)) {
throw new Error('Text message can only be deleted by its author')
}
const payload = new DeleteMessage({
clock: this.setClock(this.#clock),
messageId,
chatId: this.id,
grant: new Uint8Array([]),
messageType: MessageType.COMMUNITY_CHAT,
}).toBinary()
await this.client.sendWakuMessage(
ApplicationMetadataMessage_Type.DELETE_MESSAGE,
payload,
this.contentTopic,
this.symmetricKey,
)
}
public sendReaction = async (
messageId: string,
reaction: keyof ChatMessage['reactions'],
) => {
if (!this.client.account) {
throw new Error('Account not initialized')
}
const message = this.#messages.get(messageId)
if (!message) {
throw new Error('Message not found')
}
const retracted = message.reactions[reaction].has(
`0x${this.client.account.publicKey}`,
)
const payload = new EmojiReaction({
clock: this.setClock(this.#clock),
chatId: this.id,
messageType: MessageType.COMMUNITY_CHAT,
messageId,
type: EmojiReaction_Type[reaction],
retracted,
grant: new Uint8Array([]),
}).toBinary()
await this.client.sendWakuMessage(
ApplicationMetadataMessage_Type.EMOJI_REACTION,
payload,
this.contentTopic,
this.symmetricKey,
)
}
public isAuthor = (
message: ChatMessage,
signerPublicKey: string,
): boolean => {
return message.signer === signerPublicKey
}
private getOldestFetchedMessage(
oldestMessage: FetchedMessage | undefined,
messageId: string,
messageTimestamp?: Date,
): FetchedMessage {
let message: FetchedMessage
if (!oldestMessage) {
message = {
messageId: messageId,
timestamp: messageTimestamp,
}
} else if (
messageTimestamp &&
oldestMessage.timestamp &&
// is older
messageTimestamp < oldestMessage.timestamp
) {
message = {
messageId: messageId,
timestamp: messageTimestamp,
}
} else {
message = oldestMessage
}
return message
}
public setClock = (currentClock?: bigint): bigint => {
this.#clock = getNextClock(currentClock)
return this.#clock
}
}