-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo.js
402 lines (381 loc) · 13.3 KB
/
demo.js
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
import { Client } from './src/client.js'
import { Conversation, ChatLog } from './src/types.js'
import { createRsClient } from './src/main.js'
import Alpine from 'alpinejs'
const endpoint = 'https://chat.ruzhila.cn'
class LogItem {
/**
* @param {string} text
* @param {string} time
* */
constructor(text, time) {
this.text = text
this.time = time
}
}
class DemoApp {
constructor() {
/** @type {Client} */
this.client = undefined
/** @type {LogItem[]} */
this.logs = []
/** @type {Conversation[]} */
this.conversations = []
/** @type {ChatLog[]} */
this.messages = []
/** @type {Map<string, Number>} */
this.messageIds = {}
/** @type {Conversation} */
this.current = undefined
this.textMessage = ''
/** @type {ChatLog} */
this.quoteMessage = undefined
this.lastTyping = 0
}
init() {
this.logit('init app')
}
clearLogs() {
this.logs = []
}
logit() {
let text = Array.from(arguments).map((arg) => {
if (typeof arg === 'object') {
return JSON.stringify(arg)
} else {
return arg
}
}).join(' ')
this.logs.push(new LogItem(text, new Date().toLocaleTimeString()))
}
shutdown() {
if (this.client) {
this.client.shutdown()
this.client = undefined
}
this.conversations = []
}
async startApp(username, guestRandom) {
this.shutdown()
const client = createRsClient(endpoint)
let authInfo = undefined
try {
if (!username) {
let guestId = 'guest-demo'
if (guestRandom) {
guestId = `${Math.random().toString(36).substring(2)}-guest-random`
}
this.logit('start app with', guestId)
authInfo = await client.guestLogin({ guestId })
} else {
authInfo = await client.login({ username, password: `${username}:demo` })
}
} catch (e) {
this.logit('login failed', e)
return
}
this.logit('current user is ', authInfo.firstName || authInfo.username || authInfo.email)
this.buildClient(client)
await client.connect()
}
/**
* @param {Client} client
*/
buildClient(client) {
this.lastTyping = 0
this.client = client
this.quoteMessage = undefined
client.onConnected = this.onConnected.bind(this)
client.onDisconnected = this.onDisconnected.bind(this)
client.onConversationUpdated = this.onConversationUpdated.bind(this)
client.onConversationRemoved = this.onConversationRemoved.bind(this)
client.onTopicMessage = this.onTopicMessage.bind(this)
client.onTyping = this.onTyping.bind(this)
}
onConnected() {
this.logit('connected', this.client.myId)
this.client.beginSyncConversations()
}
onDisconnected() {
this.logit('disconnected', client.myId)
}
onConversationUpdated(conversation) {
this.logit('conversation updated', conversation.id, 'lastSeq:', conversation.lastSeq, 'unread:', conversation.unread)
let idx = this.conversations.findIndex((c) => c.topicId === conversation.topicId)
if (idx >= 0) {
this.conversations[idx] = conversation
} else {
this.conversations.push(conversation)
}
this.conversations.sort((a, b) => a.compareSort(b))
if (this.current && conversation.topicId === this.current.topicId) {
const lastSeq = this.current.lastSeq
const newLastSeq = Math.max(conversation.lastSeq, lastSeq)
const limit = newLastSeq - lastSeq
this.current = conversation
this.fetchLastLogs({ topicId: conversation.topicId, lastSeq: newLastSeq, limit }).then()
}
}
onConversationRemoved(topicId) {
this.logit('conversation removed', topicId)
let idx = this.conversations.findIndex((c) => c.topicId === topicId)
if (idx >= 0) {
this.conversations.splice(idx, 1)
}
if (this.current && this.current.topicId === topicId) {
this.current = undefined
this.messages = []
}
}
/**
* @param {Topic} topic
* @param {ChatLog} message
*/
onTopicMessage(topic, message) {
let hasRead = this.current && this.current.topicId === topic.id
if (hasRead && message.readable) {
this.current.typing = false
}
return { code: 200, hasRead }
}
onTyping(topicId, senderId) {
if (this.current && this.current.topicId === topicId) {
let conversation = this.current
conversation.typing = true
setTimeout(() => {
conversation.typing = false
}, 5000)
}
}
doTyping(e) {
if (!this.current || !this.client || e.target.value.length < 1) {
return
}
let now = new Date().getTime()
if (now - this.lastTyping < 5000) {
return
}
this.lastTyping = now
this.client.doTyping(this.current.topicId)
}
async sendMessage() {
const text = this.textMessage
if (!text) {
return
}
if (!this.current) {
this.logit('no current conversation')
return
}
let reply = undefined
if (this.quoteMessage) {
reply = this.quoteMessage.chatId
}
let onsent = (req) => {
this.logit('message sent', req)
}
await this.client.doSendText({ topicId: this.current.topicId, text, reply, onsent })
this.textMessage = ''
this.lastTyping = 0
this.quoteMessage = undefined
}
/**
* @param {Conversation} conversation
* */
async chatWith(conversation) {
this.messages = [] // clear chat logs
this.messageIds = {}
this.lastTyping = 0
this.current = conversation
this.quoteMessage = undefined
await this.client.setConversationRead(conversation)
this.current.unread = 0
await this.fetchLastLogs({ topicId: conversation.topicId })
}
async fetchLastLogs({ topicId, lastSeq, limit }) {
const { logs, hasMore } = await this.client.syncChatlogs({ topicId, lastSeq, limit })
if (logs) {
logs.forEach((log) => {
if (!log.chatId) {
return
}
if (this.messageIds[log.chatId] === undefined) {
this.messages.push(log)
this.messageIds[log.chatId] = this.messages.length - 1
} else {
let idx = this.messageIds[log.chatId]
this.messages[idx] = log
//update ui
let elm = document.getElementById('chat-item-' + log.chatId)
if (elm) {
elm.innerHTML = this.renderLog(log)
}
}
})
this.messages.sort((a, b) => a.compareSort(b))
}
// scroll to bottom
// TODO: check the scroll position and only scroll to bottom if it is already at the bottom
const chatbox = document.getElementById('chatbox')
let scrollToEnd = chatbox.scrollTop + chatbox.clientHeight + 100 >= chatbox.scrollHeight
if (scrollToEnd) {
setTimeout(() => {
chatbox.scrollTop = chatbox.scrollHeight
}, 100)
}
}
async onScrollMessages(event) {
if (event.target.scrollTop > 0) {
return
}
if (!this.current) {
return
}
event.preventDefault()
let firstSeq = undefined
// sync older messages
if (this.messages && this.messages[0].seq > this.current.startSeq) {
firstSeq = this.messages[0].seq
}
firstSeq = Math.max(firstSeq, this.current.startSeq)
await this.fetchLastLogs({ topicId: this.current.topicId, lastSeq: firstSeq })
}
/**
* @param {ChatLog} item
*/
renderLog(item) {
let content = item.content ? item.content : item;
let output = '';
switch (content.type) {
case 'text':
output = `<div>${content.text}</div>`;
break;
case 'logs':
output = `<div class="border border-gray-400 rounded-md bg-gray-100 p-3">
<a href="${content.text}" target="_blank">
<p>${content.placeholder}</p>
<p class="mt-1">size:<span class="mx-1">(${content.size})</span>Bytes</p>
</a>
</div>`;
break;
case 'image':
output = `<div><img class="max-w-40 max-h-40" src="${content.text}"></div>`;
break;
case 'file':
const filename = content.placeholder || content.text.split('/').pop();
output = `<div><a href="${content.text}" target="_blank">${filename} size(${content.size})</a></div>`;
break;
case 'recall':
item.content.type = '';
return;
case 'recalled':
return `<div><span class="text-gray-400">[Recalled]</span></div>`;
default:
output = `<div><span>[${content.type}]</span>${content.placeholder || content.text}</div>`;
break;
}
if (content.reply) {
if (content.replyContent) {
const replyOutput = this.renderLog(JSON.parse(content.replyContent))
output = `<div class="bg-gray-50 text-gray-600 text-sm px-2 py-1 rounded-sm mb-1">${replyOutput}</div>` + output;
}
else if (!content.replyContent && !content.senderId) {
output = `<div class="bg-gray-50 text-gray-600 text-sm px-2 py-1 rounded-sm mb-1">[Recalled]</div>` + output;
}
}
return output;
}
async doSendFiles(event) {
if (!this.current) {
return
}
const topicId = this.current.topicId
let file = event.target.files[0]
let result = await this.client.uploadFile({ topicId, file, isPrivate: false })
if (file.type.startsWith('image/')) {
await this.client.doSendImage({ topicId, urlOrData: result.path })
} else {
await this.client.doSendFile({ topicId, urlOrData: result.path, filename: result.fileName, size: result.size })
}
}
/**
*
* @param {ChatLog} item
*/
async doRecallMessage(item) {
if (item.content.type === 'recall') {
return
}
let resp = await this.client.doRecall({ topicId: this.current.topicId, chatId: item.chatId })
if (resp.code !== 200) {
this.logit('recall failed', resp)
}
}
/**
*
* @param {ChatLog} item
*/
async doDeleteMessage(item) {
item.content.type = ''
await this.client.deleteMessage({ topicId: this.current.topicId, chatId: item.chatId })
}
/**
*
* @param {ChatLog} item
*/
async doQuoteMessage(item) {
this.quoteMessage = item
}
// renderQuote() {
// if (!this.quoteMessage) {
// return ''
// }
// let content = this.quoteMessage.content
// switch (content.type) {
// case 'text':
// return `${content.text}`
// case 'logs':
// return `${content.placeholder} size(${content.size})`
// case 'image':
// return `<img :src="${content.thumbnail}" class="max-w-20 max-h-20"/>`
// // return `[image]`
// case 'file':
// const filename = content.placeholder || content.text.split('/').pop()
// return `${filename} size(${content.size})`
// default:
// return `[${content.type}] ${content.placeholder || content.text}`
// }
// }
renderQuote() {
if (!this.quoteMessage) {
return null;
}
let content = this.quoteMessage.content;
let container = document.createElement('div');
switch (content.type) {
case 'text':
container.textContent = content.text;
break;
case 'logs':
container.textContent = `${content.placeholder} size(${content.size})`;
break;
case 'image':
let img = document.createElement('img');
img.src = content.thumbnail;
img.className = 'max-w-20 max-h-20';
container.appendChild(img);
break;
case 'file':
const filename = content.placeholder || content.text.split('/').pop();
container.textContent = `${filename} size(${content.size})`;
break;
default:
container.textContent = `[${content.type}] ${content.placeholder || content.text}`;
break;
}
return container.outerHTML;
}
}
window.demoapp = new DemoApp()
window.Alpine = Alpine
Alpine.start()