-
Notifications
You must be signed in to change notification settings - Fork 4
/
message.ts
413 lines (362 loc) · 11.2 KB
/
message.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
import { Chat } from "./chat"
import PubNub from "pubnub"
import {
MessageActionType,
MessageActions,
DeleteParameters,
MessageDTOParams,
TextMessageContent,
} from "../types"
import { INTERNAL_ADMIN_CHANNEL } from "../constants"
import { getErrorProxiedEntity } from "../error-logging"
import { MessageElementsUtils } from "../message-elements-utils"
export type MessageFields = Pick<
Message,
"timetoken" | "content" | "channelId" | "userId" | "actions" | "meta"
>
export class Message {
protected chat: Chat
readonly timetoken: string
readonly content: TextMessageContent
readonly channelId: string
readonly userId: string
readonly actions?: MessageActions
readonly meta?: {
[key: string]: any
}
readonly error?: string
get hasThread() {
if (!this.actions?.["threadRootId"]) {
return false
}
const key = Object.keys(this.actions["threadRootId"])[0]
return !!key && !!this.actions["threadRootId"][key].length
}
get mentionedUsers() {
if (this.meta?.mentionedUsers) {
return this.meta.mentionedUsers
}
return {}
}
get referencedChannels() {
if (this.meta?.referencedChannels) {
return this.meta.referencedChannels
}
return {}
}
get textLinks() {
if (this.meta?.textLinks) {
return this.meta.textLinks
}
return []
}
get type() {
return this.content.type
}
get quotedMessage() {
if (this.meta?.quotedMessage) {
return this.meta.quotedMessage
}
return undefined
}
get files() {
return this.content.files || []
}
/** @internal */
constructor(chat: Chat, params: MessageFields) {
this.chat = chat
this.timetoken = params.timetoken
this.content = params.content
this.channelId = params.channelId
this.userId = params.userId
Object.assign(this, params)
}
/** @internal */
static fromDTO(chat: Chat, params: MessageDTOParams) {
const data = {
timetoken: String(params.timetoken),
content:
typeof params.message === "string"
? {
type: "text",
text: params.message,
files: [],
}
: params.message,
channelId: params.channel,
userId: "publisher" in params ? params.publisher : params.uuid || "unknown-user",
actions: "actions" in params ? params.actions : undefined,
meta:
"meta" in params ? params.meta : "userMetadata" in params ? params.userMetadata : undefined,
error: params.error || undefined,
}
return getErrorProxiedEntity(new Message(chat, data), chat.errorLogger)
}
/** @internal */
private clone(params: Partial<MessageFields>) {
const { timetoken, content, channelId, userId, actions, meta } = this
const data = Object.assign({}, { timetoken, content, channelId, userId, actions, meta }, params)
return new Message(this.chat, data)
}
/** @internal */
private assignAction(action: PubNub.MessageAction) {
const { actionTimetoken, type, value, uuid } = action
const newActions = this.actions || {}
newActions[type] ||= {}
newActions[type][value] ||= []
if (newActions[type][value].find((a) => a.actionTimetoken === actionTimetoken)) {
return newActions
}
newActions[type][value] = [...newActions[type][value], { uuid, actionTimetoken }]
return newActions
}
/** @internal */
private filterAction(action: PubNub.MessageAction) {
const { actionTimetoken, type, value, uuid } = action
const newActions = this.actions || {}
newActions[type] ||= {}
newActions[type][value] ||= []
newActions[type][value] = newActions[type][value].filter(
(r) => r.actionTimetoken !== actionTimetoken || r.uuid !== uuid
)
return newActions
}
/*
* Updates
*/
static streamUpdatesOn(messages: Message[], callback: (messages: Message[]) => unknown) {
if (!messages.length) throw "Cannot stream message updates on an empty list"
const listener = {
messageAction: (event: PubNub.MessageActionEvent) => {
const message = messages.find((msg) => msg.timetoken === event.data.messageTimetoken)
if (!message) return
if (message.channelId !== event.channel) return
let actions
if (event.event === "added") actions = message.assignAction(event.data)
if (event.event === "removed") actions = message.filterAction(event.data)
const newMessage = message.clone({ actions })
const newMessages = messages.map((msg) =>
msg.timetoken === newMessage.timetoken ? newMessage : msg
)
callback(newMessages)
},
}
const { chat } = messages[0]
const removeListener = chat.addListener(listener)
const subscriptions = messages
.filter((m1, i) => messages.findIndex((m2) => m1.channelId === m2.channelId) === i)
.map((message) => chat.subscribe(message.channelId))
return () => {
removeListener()
subscriptions.map((unsub) => unsub())
}
}
streamUpdates(callback: (message: Message) => unknown) {
return Message.streamUpdatesOn([this], (messages) => callback(messages[0]))
}
/*
* Message text
*/
get text() {
const type = MessageActionType.EDITED
const edits = this.actions?.[type]
if (!edits) return this.content.text || ""
const flatEdits = Object.entries(edits).map(([k, v]) => ({ value: k, ...v[0] }))
const lastEdit = flatEdits.reduce((a, b) => (a.actionTimetoken > b.actionTimetoken ? a : b))
return lastEdit.value
}
getMessageElements() {
const text = this.text
return MessageElementsUtils.getMessageElements({
text,
textLinks: this.textLinks,
mentionedUsers: this.mentionedUsers,
referencedChannels: this.referencedChannels,
})
}
/**
@deprecated use getMessageElements instead
*/
getLinkedText() {
return this.getMessageElements()
}
async editText(newText: string) {
const type = MessageActionType.EDITED
try {
const { data } = await this.chat.sdk.addMessageAction({
channel: this.channelId,
messageTimetoken: this.timetoken,
action: { type, value: newText },
})
const actions = this.assignAction(data)
return this.clone({ actions })
} catch (error) {
throw error
}
}
/*
* Deletions
*/
get deleted() {
const type = MessageActionType.DELETED
return !!this.actions?.[type] && !!this.actions?.[type][type].length
}
async delete(params: DeleteParameters & { preserveFiles?: boolean } = {}) {
const { soft } = params
const type = MessageActionType.DELETED
try {
if (soft) {
const { data } = await this.chat.sdk.addMessageAction({
channel: this.channelId,
messageTimetoken: this.timetoken,
action: { type, value: type },
})
const actions = this.assignAction(data)
await this.deleteThread(params)
return this.clone({ actions })
} else {
const previousTimetoken = String(BigInt(this.timetoken) - BigInt(1))
await this.chat.sdk.deleteMessages({
channel: this.channelId,
start: previousTimetoken,
end: this.timetoken,
})
await this.deleteThread(params)
if (this.files.length && !params.preserveFiles) {
for (const file of this.files) {
const { id, name } = file
await this.chat.sdk.deleteFile({ channel: this.channelId, id, name })
}
}
return true
}
} catch (error) {
throw error
}
}
async restore() {
if (!this.deleted) {
console.warn("This message has not been deleted")
return
}
const deletedActions = this.actions?.[MessageActionType.DELETED]?.[MessageActionType.DELETED]
if (!deletedActions) {
console.warn("Malformed data", deletedActions)
return
}
// in practise it's possible to have a few soft deletions on a message
// so take care of it
for (let i = 0; i < deletedActions.length; i++) {
const deleteActionTimetoken = deletedActions[i].actionTimetoken
await this.chat.sdk.removeMessageAction({
channel: this.channelId,
messageTimetoken: this.timetoken,
actionTimetoken: String(deleteActionTimetoken),
})
}
const [{ data }, restoredThreadAction] = await Promise.all([
this.chat.sdk.getMessageActions({
channel: this.channelId,
start: this.timetoken,
end: this.timetoken,
}),
this.restoreThread(),
])
let allActions = this.actions || {}
delete allActions[MessageActionType.DELETED]
for (let i = 0; i < data.length; i++) {
const actions = this.assignAction(data[i])
allActions = {
...allActions,
...actions,
}
}
if (restoredThreadAction) {
allActions = {
...allActions,
...this.assignAction(restoredThreadAction.data),
}
}
return this.clone({ actions: allActions })
}
/**
* Reactions
*/
get reactions() {
const type = MessageActionType.REACTIONS
return this.actions?.[type] || {}
}
hasUserReaction(reaction: string) {
return !!this.reactions[reaction]?.find((r) => r.uuid === this.chat.sdk.getUUID())
}
async toggleReaction(reaction: string) {
const type = MessageActionType.REACTIONS
const uuid = this.chat.sdk.getUUID()
const messageTimetoken = this.timetoken
const channel = this.channelId
const value = reaction
let actions
try {
const existingReaction = this.reactions[value]?.find((r) => r.uuid === uuid)
if (existingReaction) {
const actionTimetoken = String(existingReaction.actionTimetoken)
await this.chat.sdk.removeMessageAction({ actionTimetoken, channel, messageTimetoken })
actions = this.filterAction({ actionTimetoken, messageTimetoken, type, uuid, value })
} else {
const { data } = await this.chat.sdk.addMessageAction({
channel,
messageTimetoken,
action: { type, value },
})
actions = this.assignAction(data)
}
return this.clone({ actions })
} catch (error) {
throw error
}
}
/*
* Other
*/
async forward(channelId: string) {
return this.chat.forwardMessage(this, channelId)
}
async pin() {
const channel = await this.chat.getChannel(this.channelId)
await this.chat.pinMessageToChannel(this, channel!)
}
async report(reason: string) {
const channel = INTERNAL_ADMIN_CHANNEL
const payload = {
text: this.text,
reason,
reportedMessageChannelId: this.channelId,
reportedMessageTimetoken: this.timetoken,
reportedUserId: this.userId,
}
return await this.chat.emitEvent({ channel, type: "report", payload })
}
/**
* Threads
*/
getThread() {
return this.chat.getThreadChannel(this)
}
createThread() {
return this.chat.createThreadChannel(this)
}
removeThread() {
return this.chat.removeThreadChannel(this)
}
/** @internal */
private async deleteThread(params: DeleteParameters = {}) {
if (this.hasThread) {
const thread = await this.getThread()
await thread.delete(params)
}
}
/** @internal */
private async restoreThread() {
return this.chat.restoreThreadChannel(this)
}
}