使用时间戳范围同步

This commit is contained in:
2023-10-21 18:00:08 +08:00
parent b27340365a
commit 2dd39dc530
2 changed files with 28 additions and 6 deletions

View File

@ -65,7 +65,21 @@ export default class Chat {
event.target.parentNode.parentNode.style.right = '50%' event.target.parentNode.parentNode.style.right = '50%'
} }
if (event.ctrlKey && event.key === 'l') { if (event.ctrlKey && event.key === 'l') {
this.ul.innerHTML = '' this.ul.innerHTML = '' // 清理屏幕
// 获取当前时间戳
const timestamp = new Date().getTime()
// 清理本地存储
values(this.store).then(list => list.forEach(item => {
const t = new Date(item.time).getTime()
console.log('清理', item.id, t, timestamp)
if (t < timestamp) {
del(item.id, this.store)
console.log('清理成功', item.id)
}
}))
const time = new Date().toLocaleString()
console.log('清屏', `store-chat-${name}`, time)
localStorage.setItem(`store-chat-${name}`, time)
} }
} }
}), }),

View File

@ -149,11 +149,19 @@ const chat = new Chat({
// 与每个客户端都建立聊天信道 // 与每个客户端都建立聊天信道
clientList.setChannel('chat', { clientList.setChannel('chat', {
onopen: async event => { onopen: async event => {
//console.debug('打开信道', event.target.label) // 请求指定范围内的消息列表(转换成时间戳)
// 请求指定范围内的消息列表 const last = localStorage.getItem('store-chat-default')
const start = new Date().getTime() - 1000 * 60 * 60 * 24 * 7 // 一周内的消息 const lastTimestamp = new Date(last).getTime()
const end = new Date().getTime() console.log('上次清理消息时间:', last, lastTimestamp)
clientList.send('chat', JSON.stringify({ type: 'pull', start, end })) // 如果超过一周, 则只拉取一周内的消息
if (lastTimestamp > new Date().getTime() - 1000 * 60 * 60 * 24 * 7) {
const start = new Date().getTime() - 1000 * 60 * 60 * 24 * 7
const end = new Date().getTime()
clientList.send('chat', JSON.stringify({ type: 'pull', start, end }))
return
}
// 否则拉取时间戳范围内的消息
clientList.send('chat', JSON.stringify({ type: 'pull', start: lastTimestamp, end: new Date().getTime() }))
}, },
onmessage: async (event, client) => { onmessage: async (event, client) => {
const data = JSON.parse(event.data) const data = JSON.parse(event.data)