Files
XHChat/web/src/session.ts
T

126 lines
4.3 KiB
TypeScript

import { defineStore } from 'pinia'
import { ref, shallowRef } from 'vue'
import { APIError, realtime, request } from './api'
import { platform, signChallenge } from './identity'
import type { Contact, ContactAction } from './contacts'
export interface Device {
id: string
name: string
platform: 'web' | 'windows'
createdAt: string
lastActiveAt: string
revokedAt?: string
signedIn: boolean
}
interface Identity {
user: { id: string; username: string }
device: Device
}
interface Auth extends Identity { token: string }
export const useSession = defineStore('session', () => {
const identity = shallowRef<Identity>()
const connection = ref('离线')
const contactChanges = ref(0)
const inboxChanges = ref(0)
const groupChange = shallowRef<{ groupId: string; notify: boolean }>()
const groupListChanges = ref(0)
let token = ''
let socket: WebSocket | undefined
let retry: ReturnType<typeof setTimeout> | undefined
let attempts = 0
function clear() {
token = ''
identity.value = undefined
groupChange.value = undefined
connection.value = '离线'
clearTimeout(retry)
const previous = socket
socket = undefined
previous?.close()
}
async function connect(current: string) {
if (current !== token) return
connection.value = '正在连接'
try {
const { ticket } = await request<{ ticket: string }>('/realtime/ticket', 'POST', current)
if (current !== token) return
const active = realtime(ticket)
socket = active
active.onmessage = (event) => {
if (socket !== active) return
const { type, groupId, notify } = JSON.parse(event.data)
if (type === 'ready') {
connection.value = '实时连接已建立'
attempts = 0
}
if (type === 'contacts_changed') contactChanges.value++
if (type === 'inbox_changed') inboxChanges.value++
if (type === 'group_changed' && typeof groupId === 'string') groupChange.value = { groupId, notify: notify === true }
if (type === 'group_list_changed') groupListChanges.value++
}
active.onclose = (event) => {
if (socket !== active) return
socket = undefined
if (event.code === 1008) clear()
else reconnect(current)
}
} catch (error) {
if (current !== token) return
if (error instanceof APIError && error.status === 401) clear()
else reconnect(current)
}
}
function reconnect(current: string) {
connection.value = '正在重连'
retry = setTimeout(() => void connect(current), Math.min(30_000, 1000 * 2 ** attempts++))
}
async function authenticate(mode: 'login' | 'register', username: string, password: string, deviceName: string) {
username = username.trim().toLowerCase()
const { challenge } = await request<{ challenge: string }>('/auth/challenge', 'POST')
const proof = await signChallenge(username, challenge)
const result = await request<Auth>('/auth/' + mode, 'POST', '', {
username, password, deviceName, platform, challenge, ...proof,
})
clear()
token = result.token
identity.value = { user: result.user, device: result.device }
attempts = 0
void connect(token)
}
async function authorized<T>(path: string, method = 'GET', body?: object, binary = false) {
const current = token
try {
const response = await request<T>(path, method, current, body, binary)
if (token !== current) throw new Error('登录会话已变更')
return response
} catch (error) {
if (token === current && error instanceof APIError && error.status === 401) clear()
throw error
}
}
async function logout() {
await authorized('/auth/logout', 'POST')
clear()
}
return {
identity, connection, contactChanges, inboxChanges, groupChange, groupListChanges, authenticate, logout, authorized,
devices: () => authorized<Device[]>('/devices'),
revoke: (id: string) => authorized<void>('/devices/' + encodeURIComponent(id), 'DELETE'),
contacts: () => authorized<Contact[]>('/contacts'),
searchContact: (username: string) => authorized<Contact>('/contacts/search?' + new URLSearchParams({ username })),
changeContact: (id: string, action: ContactAction, alias: string, category: string) =>
authorized<void>('/contacts/' + encodeURIComponent(id), 'POST', { action, alias, category }),
}
})