2023-01-10 21:29:16 +09:00
|
|
|
import type { WsEvents } from 'masto'
|
|
|
|
|
|
|
|
const notifications = reactive<Record<string, undefined | [Promise<WsEvents>, string[]]>>({})
|
|
|
|
|
2023-03-31 04:01:24 +09:00
|
|
|
export function useNotifications() {
|
2023-01-10 21:29:16 +09:00
|
|
|
const id = currentUser.value?.account.id
|
2023-01-15 17:38:02 +09:00
|
|
|
|
|
|
|
const { client, canStreaming } = $(useMasto())
|
2023-01-10 21:29:16 +09:00
|
|
|
|
|
|
|
async function clearNotifications() {
|
|
|
|
if (!id || !notifications[id])
|
|
|
|
return
|
|
|
|
const lastReadId = notifications[id]![1][0]
|
|
|
|
notifications[id]![1] = []
|
2023-01-16 05:26:59 +09:00
|
|
|
if (lastReadId) {
|
|
|
|
await client.v1.markers.create({
|
|
|
|
notifications: { lastReadId },
|
|
|
|
})
|
|
|
|
}
|
2023-01-10 21:29:16 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
async function connect(): Promise<void> {
|
2023-01-15 17:38:02 +09:00
|
|
|
if (!isHydrated.value || !id || notifications[id] || !currentUser.value?.token)
|
2023-01-10 21:29:16 +09:00
|
|
|
return
|
|
|
|
|
2023-01-16 05:26:59 +09:00
|
|
|
let resolveStream
|
|
|
|
const stream = new Promise<WsEvents>(resolve => resolveStream = resolve)
|
|
|
|
notifications[id] = [stream, []]
|
|
|
|
|
2023-01-15 17:38:02 +09:00
|
|
|
await until($$(canStreaming)).toBe(true)
|
|
|
|
|
2023-01-16 05:26:59 +09:00
|
|
|
client.v1.stream.streamUser().then(resolveStream)
|
2023-01-10 21:29:16 +09:00
|
|
|
stream.then(s => s.on('notification', (n) => {
|
|
|
|
if (notifications[id])
|
|
|
|
notifications[id]![1].unshift(n.id)
|
|
|
|
}))
|
|
|
|
|
2023-01-15 17:38:02 +09:00
|
|
|
const position = await client.v1.markers.fetch({ timeline: ['notifications'] })
|
|
|
|
const paginator = client.v1.notifications.list({ limit: 30 })
|
2023-01-10 21:29:16 +09:00
|
|
|
do {
|
|
|
|
const result = await paginator.next()
|
|
|
|
if (!result.done && result.value.length) {
|
|
|
|
for (const notification of result.value) {
|
|
|
|
if (notification.id === position.notifications.lastReadId)
|
|
|
|
return
|
|
|
|
notifications[id]![1].push(notification.id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
} while (true)
|
|
|
|
}
|
|
|
|
|
|
|
|
function disconnect(): void {
|
|
|
|
if (!id || !notifications[id])
|
|
|
|
return
|
|
|
|
notifications[id]![0].then(stream => stream.disconnect())
|
|
|
|
notifications[id] = undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
watch(currentUser, disconnect)
|
2023-01-15 17:38:02 +09:00
|
|
|
|
|
|
|
onHydrated(() => {
|
2023-01-10 21:29:16 +09:00
|
|
|
connect()
|
2023-01-15 17:38:02 +09:00
|
|
|
})
|
2023-01-10 21:29:16 +09:00
|
|
|
|
|
|
|
return {
|
|
|
|
notifications: computed(() => id ? notifications[id]?.[1].length ?? 0 : 0),
|
|
|
|
disconnect,
|
|
|
|
clearNotifications,
|
|
|
|
}
|
|
|
|
}
|