Whalebird-desktop-client-ma.../renderer/pages/accounts/[id]/[timeline].tsx

64 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-11-01 17:20:27 +01:00
import { useRouter } from 'next/router'
2023-11-03 12:37:40 +01:00
import Timeline from '@/components/timelines/Timeline'
2023-11-09 15:29:10 +01:00
import { useEffect, useRef, useState } from 'react'
2023-11-03 12:37:40 +01:00
import { Account, db } from '@/db'
2023-11-09 15:29:10 +01:00
import generator, { Entity, MegalodonInterface, WebSocketInterface } from 'megalodon'
2023-11-04 10:14:00 +01:00
import Notifications from '@/components/timelines/Notifications'
2023-11-09 15:29:10 +01:00
import generateNotification from '@/utils/notification'
import { useIntl } from 'react-intl'
2023-11-01 17:20:27 +01:00
2023-11-03 12:37:40 +01:00
export default function Page() {
2023-11-01 17:20:27 +01:00
const router = useRouter()
2023-11-03 12:37:40 +01:00
const [account, setAccount] = useState<Account | null>(null)
const [client, setClient] = useState<MegalodonInterface>(null)
2023-11-09 15:29:10 +01:00
const streaming = useRef<WebSocketInterface | null>(null)
const { formatMessage } = useIntl()
2023-11-03 12:37:40 +01:00
useEffect(() => {
if (router.query.id) {
const f = async () => {
const a = await db.accounts.get(parseInt(router.query.id as string))
if (a) {
setAccount(a)
const c = generator(a.sns, a.url, a.access_token, 'Whalebird')
setClient(c)
2023-11-09 15:29:10 +01:00
// Start user streaming for notification
const instance = await c.getInstance()
const ws = generator(a.sns, instance.data.urls.streaming_api, a.access_token, 'Whalebird')
streaming.current = ws.userSocket()
streaming.current.on('connect', () => {
console.log('connect to user streaming')
})
streaming.current.on('notification', (notification: Entity.Notification) => {
const [title, body] = generateNotification(notification, formatMessage)
if (title.length > 0) {
new window.Notification(title, { body: body })
}
})
2023-11-03 12:37:40 +01:00
}
}
f()
}
2023-11-09 15:29:10 +01:00
return () => {
if (streaming.current) {
streaming.current.removeAllListeners()
streaming.current.stop()
streaming.current = null
console.log('close user streaming')
}
}
2023-11-03 12:37:40 +01:00
}, [router.query.id])
2023-11-04 10:14:00 +01:00
if (!account || !client) return null
switch (router.query.timeline as string) {
case 'notifications': {
return <Notifications account={account} client={client} />
}
default: {
return <Timeline timeline={router.query.timeline as string} account={account} client={client} />
}
}
2023-11-01 17:20:27 +01:00
}