交付双端基础、实时联系人和隔离浏览器
This commit is contained in:
1 parent
43687d5e7e
commit
67fef3ff87
59 files changed
+5094
-1
No files matched your search
@@ -0,0 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useSession } from './session'
|
||||
|
||||
const session = useSession()
|
||||
const router = useRouter()
|
||||
watch(() => session.identity, (identity) => {
|
||||
void router.replace(identity ? '/devices' : '/login')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template><RouterView /></template>
|
||||
@@ -0,0 +1,32 @@
|
||||
const base = window.xhchat?.apiBase ?? ''
|
||||
|
||||
export class APIError extends Error {
|
||||
constructor(public status: number, message: string) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export async function request<T>(path: string, method = 'GET', token = '', body?: object): Promise<T> {
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
if (token) headers.Authorization = 'Bearer ' + token
|
||||
if (body) headers['Content-Type'] = 'application/json'
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(base + '/api/v1' + path, {
|
||||
method, headers, body: body ? JSON.stringify(body) : undefined,
|
||||
credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(12000),
|
||||
})
|
||||
} catch {
|
||||
throw new Error('无法连接 XHChat 服务,请检查网络后重试')
|
||||
}
|
||||
if (response.status === 204) return undefined as T
|
||||
const data = await response.json().catch(() => null)
|
||||
if (!response.ok) throw new APIError(response.status, data?.error?.message ?? '请求失败,请稍后重试')
|
||||
return data as T
|
||||
}
|
||||
|
||||
export function realtime(ticket: string) {
|
||||
const url = new URL((base || location.origin) + '/api/v1/realtime')
|
||||
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
return new WebSocket(url, ['xhchat.v1', 'ticket.' + ticket])
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export interface Contact {
|
||||
id: string
|
||||
username: string
|
||||
state: 'none' | 'incoming' | 'outgoing' | 'friend' | 'blocked'
|
||||
alias: string
|
||||
category: string
|
||||
}
|
||||
|
||||
export type ContactAction = 'request' | 'accept' | 'reject' | 'cancel' | 'delete' | 'block' | 'unblock' | 'preferences'
|
||||
@@ -0,0 +1,66 @@
|
||||
interface DeviceProof {
|
||||
publicKey: string
|
||||
signature: string
|
||||
}
|
||||
|
||||
interface DesktopBridge {
|
||||
apiBase: string
|
||||
signChallenge: (username: string, challenge: string) => Promise<DeviceProof>
|
||||
openBrowser?: () => Promise<void>
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window { xhchat?: DesktopBridge }
|
||||
}
|
||||
|
||||
const prefix = 'XHChat device authentication v1\n'
|
||||
|
||||
function base64url(bytes: ArrayBuffer) {
|
||||
return btoa(String.fromCharCode(...new Uint8Array(bytes)))
|
||||
.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
function openDatabase(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open('xhchat-device', 1)
|
||||
request.onupgradeneeded = () => request.result.createObjectStore('keys')
|
||||
request.onsuccess = () => resolve(request.result)
|
||||
request.onerror = () => reject(request.error)
|
||||
request.onblocked = () => reject(new Error('请关闭其他 XHChat 页面后重试'))
|
||||
})
|
||||
}
|
||||
|
||||
async function browserKey(username: string): Promise<CryptoKeyPair> {
|
||||
const candidate = await crypto.subtle.generateKey('Ed25519', false, ['sign', 'verify'])
|
||||
const db = await openDatabase()
|
||||
try {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction('keys', 'readwrite')
|
||||
const keys = transaction.objectStore('keys')
|
||||
const read = keys.get(username)
|
||||
let result = candidate
|
||||
read.onsuccess = () => {
|
||||
if (read.result) result = read.result
|
||||
else keys.add(candidate, username)
|
||||
}
|
||||
transaction.oncomplete = () => resolve(result)
|
||||
transaction.onabort = () => reject(transaction.error)
|
||||
})
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
export const platform = window.xhchat ? 'windows' : 'web'
|
||||
|
||||
export async function signChallenge(username: string, challenge: string): Promise<DeviceProof> {
|
||||
if (window.xhchat) return window.xhchat.signChallenge(username, challenge)
|
||||
try {
|
||||
const pair = await browserKey(username)
|
||||
const publicKey = await crypto.subtle.exportKey('raw', pair.publicKey)
|
||||
const signature = await crypto.subtle.sign('Ed25519', pair.privateKey, new TextEncoder().encode(prefix + challenge))
|
||||
return { publicKey: base64url(publicKey), signature: base64url(signature) }
|
||||
} catch {
|
||||
throw new Error('无法使用本机设备密钥,请检查浏览器是否支持安全密钥存储')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import { createRouter, createWebHashHistory } from 'vue-router'
|
||||
import App from './App.vue'
|
||||
import AuthView from './views/AuthView.vue'
|
||||
import DeviceView from './views/DeviceView.vue'
|
||||
import ContactsView from './views/ContactsView.vue'
|
||||
import Workspace from './views/Workspace.vue'
|
||||
import { useSession } from './session'
|
||||
import './style.css'
|
||||
|
||||
const pinia = createPinia()
|
||||
const router = createRouter({
|
||||
history: createWebHashHistory(),
|
||||
routes: [
|
||||
{ path: '/', redirect: '/devices' },
|
||||
{ path: '/login', component: AuthView },
|
||||
{ path: '/', component: Workspace, children: [
|
||||
{ path: 'devices', component: DeviceView },
|
||||
{ path: 'contacts', component: ContactsView },
|
||||
] },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
],
|
||||
})
|
||||
|
||||
router.beforeEach((to) => {
|
||||
const signedIn = Boolean(useSession(pinia).identity)
|
||||
if (!signedIn && to.path !== '/login') return '/login'
|
||||
if (signedIn && to.path === '/login') return '/devices'
|
||||
})
|
||||
|
||||
createApp(App).use(pinia).use(router).mount('#app')
|
||||
@@ -0,0 +1,115 @@
|
||||
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)
|
||||
let token = ''
|
||||
let socket: WebSocket | undefined
|
||||
let retry: ReturnType<typeof setTimeout> | undefined
|
||||
let attempts = 0
|
||||
|
||||
function clear() {
|
||||
token = ''
|
||||
identity.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 } = JSON.parse(event.data)
|
||||
if (type === 'ready') {
|
||||
connection.value = '实时连接已建立'
|
||||
attempts = 0
|
||||
}
|
||||
if (type === 'contacts_changed') contactChanges.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) {
|
||||
try {
|
||||
return await request<T>(path, method, token, body)
|
||||
} catch (error) {
|
||||
if (error instanceof APIError && error.status === 401) clear()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
await authorized('/auth/logout', 'POST')
|
||||
clear()
|
||||
}
|
||||
|
||||
return {
|
||||
identity, connection, contactChanges, authenticate, logout,
|
||||
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 }),
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,103 @@
|
||||
* { box-sizing: border-box; }
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--surface: #ffffff;
|
||||
--base: #f1f5f3;
|
||||
--text: #182822;
|
||||
--muted: #596c62;
|
||||
--line: #dce6e0;
|
||||
--green: #14664c;
|
||||
--green-soft: #e1f0e8;
|
||||
--danger: #a62e38;
|
||||
font: 15px/1.5 "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;
|
||||
color: var(--text);
|
||||
background: var(--base);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--surface: #182520; --base: #101a16; --text: #edf4ef; --muted: #a8bcb0;
|
||||
--line: #34483d; --green: #7ed8b1; --green-soft: #244236; --danger: #ff9aa2;
|
||||
}
|
||||
}
|
||||
body { margin: 0; }
|
||||
button, input { font: inherit; }
|
||||
button, a { -webkit-tap-highlight-color: transparent; }
|
||||
button { cursor: pointer; }
|
||||
button:disabled { cursor: wait; opacity: .65; }
|
||||
:focus-visible { outline: 2px solid var(--green); outline-offset: 3px; }
|
||||
h1, p { margin: 0; }
|
||||
h1 { font-size: clamp(25px, 3vw, 32px); letter-spacing: -.02em; line-height: 1.25; }
|
||||
small, .muted { color: var(--muted); }
|
||||
.auth-shell { display: grid; grid-template-columns: 1fr 1.1fr; min-height: 100vh; }
|
||||
.auth-brand { position: relative; overflow: hidden; display: grid; align-content: space-between; padding: clamp(26px, 6vw, 80px); background: #12372d; color: #ecf8ee; min-height: 100%; }
|
||||
.brand { display: flex; align-items: center; gap: 14px; font-size: 23px; font-weight: 700; }
|
||||
.mark { display: grid; place-items: center; width: 40px; height: 40px; border-radius: 12px; background: #ceef9a; color: #12372d; font: 800 22px/1 system-ui, sans-serif; text-decoration: none; }
|
||||
.platform { color: #bad5c5; }
|
||||
.brand-art { width: min(100%, 430px); aspect-ratio: 1; position: relative; margin: 36px auto; }
|
||||
.brand-art span { position: absolute; inset: 5% 11% 11% 5%; border: 1px solid #7aab94; border-radius: 45% 45% 10% 45%; }
|
||||
.brand-art span:nth-child(2) { inset: 16% 4% 0% 16%; }
|
||||
.brand-art span:nth-child(3) { inset: 24% 23% 24% 23%; background: #ceef9a; border-color: #ceef9a; border-radius: 50% 50% 50% 10%; }
|
||||
.brand-art span:nth-child(4) { inset: 45% 38% 45% 38%; background: #12372d; border: 0; border-radius: 20px; }
|
||||
.auth-content { display: grid; align-items: center; justify-items: center; background: var(--surface); padding: 32px clamp(22px, 6vw, 72px); }
|
||||
.auth-form { display: grid; gap: 19px; width: min(100%, 390px); }
|
||||
.tabs { display: flex; gap: 16px; border-bottom: 1px solid var(--line); margin-bottom: 8px; }
|
||||
.tabs button { border: 0; border-bottom: 2px solid transparent; padding: 9px 3px; color: var(--muted); background: none; }
|
||||
.tabs button[aria-pressed="true"] { border-color: var(--green); color: var(--green); font-weight: 700; }
|
||||
label { display: grid; gap: 7px; font-weight: 600; }
|
||||
input { width: 100%; color: var(--text); background: var(--base); border: 1px solid var(--line); border-radius: 8px; padding: 11px 12px; }
|
||||
.primary { border: 0; border-radius: 8px; background: #14664c; color: white; padding: 11px 16px; font-weight: 700; margin-top: 7px; }
|
||||
.error { color: var(--danger); }
|
||||
.workspace { display: grid; grid-template-columns: 66px 250px minmax(0, 1fr); min-height: 100vh; }
|
||||
.rail { display: flex; flex-direction: column; align-items: center; gap: 25px; padding: 18px 8px; background: #12372d; }
|
||||
.rail-link { display: grid; place-items: center; color: #ceef9a; background: #275346; width: 38px; height: 38px; border-radius: 9px; text-decoration: none; }
|
||||
.account-panel { display: flex; flex-direction: column; gap: 28px; border-right: 1px solid var(--line); padding: 20px 13px; }
|
||||
.account-summary { display: flex; align-items: center; gap: 12px; padding: 0 6px; overflow-wrap: anywhere; }
|
||||
.account-summary small, .device-meta small { display: block; }
|
||||
.avatar, .device-icon { display: grid; place-items: center; flex-shrink: 0; width: 42px; height: 42px; border-radius: 10px; color: var(--green); background: var(--green-soft); font-weight: 700; }
|
||||
.panel-nav { padding: 10px 12px; border-radius: 8px; color: var(--green); background: var(--green-soft); font-weight: 700; }
|
||||
.panel-links { display: grid; gap: 4px; }
|
||||
.panel-links a { color: var(--text); text-decoration: none; padding: 9px 11px; border-radius: 8px; }
|
||||
.panel-links a.router-link-active { color: var(--green); background: var(--green-soft); font-weight: 700; }
|
||||
.browser-button { border: 0; }
|
||||
.mobile-browser { display: none; }
|
||||
.contacts-layout { display: grid; grid-template-columns: minmax(155px, 255px) minmax(0, 1fr); background: var(--surface); }
|
||||
.contact-list { min-width: 0; padding: 16px; border-right: 1px solid var(--line); }
|
||||
.contact-search, .contact-preferences { display: grid; justify-items: start; gap: 10px; margin-bottom: 20px; }
|
||||
.contact-search label, .contact-preferences label { width: 100%; }
|
||||
.contact-group h2 { margin: 16px 0 7px; color: var(--muted); font-size: 13px; }
|
||||
.contact-item { display: flex; align-items: center; gap: 8px; width: 100%; text-align: left; padding: 8px; border-radius: 8px; border: 0; background: transparent; color: var(--text); overflow-wrap: anywhere; }
|
||||
.contact-item[aria-pressed="true"] { background: var(--green-soft); }
|
||||
.contact-item small { display: block; }
|
||||
.contact-detail { padding: 24px clamp(12px, 4vw, 36px); min-width: 0; overflow-wrap: anywhere; }
|
||||
.contact-heading, .contact-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 18px; }
|
||||
.contact-heading h1 { font-size: 22px; }
|
||||
.contact-detail > button { margin-bottom: 18px; }
|
||||
.contact-preferences { max-width: 340px; }
|
||||
.account-footer { display: grid; gap: 12px; margin-top: auto; }
|
||||
.account-footer p { color: var(--muted); font-size: 13px; }
|
||||
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); margin: 0 8px 1px 4px; }
|
||||
.dot.online { background: var(--green); }
|
||||
.device-page { background: var(--surface); }
|
||||
.page-header { display: flex; justify-content: space-between; gap: 12px; align-items: center; padding: 20px clamp(15px, 4vw, 42px); border-bottom: 1px solid var(--line); }
|
||||
.page-header h1 { font-size: 22px; }
|
||||
.device-content { max-width: 950px; padding: 15px clamp(15px, 4vw, 42px); }
|
||||
.device-row { display: flex; align-items: center; gap: 12px; padding: 17px 0; border-bottom: 1px solid var(--line); }
|
||||
.device-meta { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.tag { display: inline-block; margin-left: 8px; padding: 1px 5px; background: var(--green-soft); color: var(--green); font-size: 11px; border-radius: 4px; }
|
||||
.plain { border: 1px solid var(--line); border-radius: 7px; padding: 6px 10px; background: var(--surface); color: var(--text); white-space: nowrap; }
|
||||
.danger { color: var(--danger); }
|
||||
.confirmation { margin-top: 16px; padding: 16px; border: 1px solid var(--line); border-radius: 8px; }
|
||||
.confirmation button { margin: 9px 8px 0 0; }
|
||||
@media (max-width: 700px) {
|
||||
.auth-shell { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
|
||||
.auth-brand { padding: 16px 22px; display: flex; justify-content: space-between; align-items: center; gap: 12px; }
|
||||
.brand-art, .rail, .panel-nav { display: none; }
|
||||
.workspace { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr; }
|
||||
.account-panel { padding: 12px; flex-direction: row; align-items: center; justify-content: space-between; border-right: 0; border-bottom: 1px solid var(--line); }
|
||||
.panel-links { grid-auto-flow: column; grid-column: 1 / -1; grid-row: 2; justify-content: start; gap: 5px; }
|
||||
.account-panel { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; }
|
||||
.mobile-browser { display: block; }
|
||||
.contacts-layout { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr; }
|
||||
.contact-list { border-right: 0; border-bottom: 1px solid var(--line); }
|
||||
.account-footer { margin: 0; justify-items: end; gap: 4px; }
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { platform } from '../identity'
|
||||
import { useSession } from '../session'
|
||||
|
||||
const session = useSession()
|
||||
const mode = ref<'login' | 'register'>('login')
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const deviceName = ref(platform === 'windows' ? 'Windows 电脑' : '网页浏览器')
|
||||
const error = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
function changeMode(value: 'login' | 'register') {
|
||||
mode.value = value
|
||||
error.value = ''
|
||||
password.value = ''
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await session.authenticate(mode.value, username.value, password.value, deviceName.value)
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '操作失败,请稍后重试'
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="auth-shell">
|
||||
<aside class="auth-brand">
|
||||
<div class="brand"><span class="mark" aria-hidden="true">X</span>XHChat</div>
|
||||
<div class="brand-art" aria-hidden="true"><span></span><span></span><span></span><span></span></div>
|
||||
<p class="platform">{{ platform === 'windows' ? 'Windows 客户端' : 'Web 客户端' }}</p>
|
||||
</aside>
|
||||
<section class="auth-content">
|
||||
<form class="auth-form" @submit.prevent="submit">
|
||||
<div class="tabs" aria-label="账号操作">
|
||||
<button type="button" :disabled="busy" :aria-pressed="mode === 'login'" @click="changeMode('login')">登录</button>
|
||||
<button type="button" :disabled="busy" :aria-pressed="mode === 'register'" @click="changeMode('register')">注册</button>
|
||||
</div>
|
||||
<h1>{{ mode === 'login' ? '登录 XHChat' : '创建 XHChat 账号' }}</h1>
|
||||
<label>用户名<input v-model="username" autocomplete="username" maxlength="32" pattern="[A-Za-z0-9_]{3,32}" placeholder="3–32 位字母、数字或下划线" required></label>
|
||||
<label>密码<input v-model="password" :autocomplete="mode === 'login' ? 'current-password' : 'new-password'" type="password" minlength="12" maxlength="256" placeholder="至少 12 个字符" required></label>
|
||||
<label>设备名称<input v-model="deviceName" maxlength="64" autocomplete="off" required></label>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<button class="primary" :disabled="busy">{{ busy ? '正在验证设备…' : mode === 'login' ? '登录' : '创建账号' }}</button>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
</template>
|
||||
@@ -0,0 +1,135 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useSession } from '../session'
|
||||
import type { Contact, ContactAction } from '../contacts'
|
||||
|
||||
const session = useSession()
|
||||
const list = ref<Contact[]>([])
|
||||
const search = ref('')
|
||||
const result = ref<Contact>()
|
||||
const selected = ref('')
|
||||
const error = ref('')
|
||||
const busy = ref(false)
|
||||
const alias = ref('')
|
||||
const category = ref('')
|
||||
const detail = computed(() => list.value.find((contact) => contact.id === selected.value) ??
|
||||
(result.value?.id === selected.value ? result.value : undefined))
|
||||
const labels = { none: '可添加', incoming: '收到申请', outgoing: '等待接受', friend: '联系人', blocked: '已拉黑' }
|
||||
const sections = [
|
||||
{ state: 'incoming', label: '好友申请' },
|
||||
{ state: 'friend', label: '好友' },
|
||||
{ state: 'outgoing', label: '发出的申请' },
|
||||
{ state: 'blocked', label: '黑名单' },
|
||||
] as const
|
||||
const pendingAction = ref<'delete' | 'block'>()
|
||||
let refreshVersion = 0
|
||||
|
||||
async function refresh() {
|
||||
const version = ++refreshVersion
|
||||
const next = await session.contacts()
|
||||
if (version === refreshVersion) list.value = next
|
||||
}
|
||||
|
||||
async function operation(callback: () => Promise<void>) {
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await callback()
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '操作失败,请稍后重试'
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function refreshQuietly() {
|
||||
void refresh().catch((cause: unknown) => {
|
||||
error.value = cause instanceof Error ? cause.message : '无法加载联系人'
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(refreshQuietly)
|
||||
watch(() => [session.contactChanges, session.connection], ([, connection]) => {
|
||||
if (connection === '实时连接已建立') refreshQuietly()
|
||||
})
|
||||
watch(selected, () => {
|
||||
alias.value = detail.value?.alias ?? ''
|
||||
category.value = detail.value?.category ?? ''
|
||||
pendingAction.value = undefined
|
||||
})
|
||||
|
||||
async function find() {
|
||||
await operation(async () => {
|
||||
const contact = await session.searchContact(search.value.trim())
|
||||
result.value = contact
|
||||
selected.value = contact.id
|
||||
})
|
||||
}
|
||||
|
||||
async function change(action: ContactAction) {
|
||||
const contact = detail.value
|
||||
if (!contact) return
|
||||
await operation(async () => {
|
||||
await session.changeContact(contact.id, action, alias.value, category.value)
|
||||
pendingAction.value = undefined
|
||||
if (['cancel', 'reject', 'delete', 'unblock'].includes(action)) {
|
||||
result.value = undefined
|
||||
selected.value = ''
|
||||
}
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="contacts-layout">
|
||||
<div class="contact-list">
|
||||
<form class="contact-search" @submit.prevent="find">
|
||||
<label>按用户名查找<input v-model="search" required maxlength="32" placeholder="输入完整用户名"></label>
|
||||
<button class="plain" :disabled="busy">查找</button>
|
||||
</form>
|
||||
<section v-for="section in sections" :key="section.state" class="contact-group">
|
||||
<template v-if="list.some((contact) => contact.state === section.state)">
|
||||
<h2>{{ section.label }}</h2>
|
||||
<button v-for="contact in list.filter((item) => item.state === section.state)" :key="contact.id"
|
||||
type="button" class="contact-item" :aria-pressed="selected === contact.id" @click="selected = contact.id">
|
||||
<span class="avatar" aria-hidden="true">{{ contact.username[0]?.toUpperCase() }}</span>
|
||||
<span><strong>{{ contact.alias || contact.username }}</strong><small>{{ contact.category || '@' + contact.username }}</small></span>
|
||||
</button>
|
||||
</template>
|
||||
</section>
|
||||
<p v-if="!list.length" class="muted">还没有联系人</p>
|
||||
</div>
|
||||
<section class="contact-detail">
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<template v-if="detail">
|
||||
<div class="contact-heading">
|
||||
<span class="avatar" aria-hidden="true">{{ detail.username[0]?.toUpperCase() }}</span>
|
||||
<div><h1>{{ detail.alias || detail.username }}</h1><small>@{{ detail.username }} · {{ labels[detail.state] }}</small></div>
|
||||
</div>
|
||||
<div v-if="detail.state === 'incoming'" class="contact-actions">
|
||||
<button class="plain" :disabled="busy" @click="change('accept')">接受申请</button>
|
||||
<button class="plain" :disabled="busy" @click="change('reject')">拒绝申请</button>
|
||||
</div>
|
||||
<button v-if="detail.state === 'none'" class="primary" :disabled="busy" @click="change('request')">添加好友</button>
|
||||
<button v-if="detail.state === 'outgoing'" class="plain" :disabled="busy" @click="change('cancel')">取消申请</button>
|
||||
<button v-if="detail.state === 'blocked'" class="plain" :disabled="busy" @click="change('unblock')">解除拉黑</button>
|
||||
<form v-if="detail.state === 'friend'" class="contact-preferences" @submit.prevent="change('preferences')">
|
||||
<label>备注<input v-model="alias" maxlength="64"></label>
|
||||
<label>分组<input v-model="category" maxlength="32"></label>
|
||||
<button class="plain" :disabled="busy">保存</button>
|
||||
</form>
|
||||
<div v-if="detail.state !== 'blocked'" class="contact-actions">
|
||||
<button v-if="detail.state === 'friend'" class="plain danger" :disabled="busy" @click="pendingAction = 'delete'">删除好友</button>
|
||||
<button class="plain danger" :disabled="busy" @click="pendingAction = 'block'">拉黑</button>
|
||||
</div>
|
||||
<section v-if="pendingAction" class="confirmation" aria-label="确认联系人操作">
|
||||
<p>{{ pendingAction === 'block' ? '拉黑将移除好友关系并阻止新的好友申请。' : '删除后,双方的好友关系将解除。' }}</p>
|
||||
<button class="plain" @click="pendingAction = undefined">取消</button>
|
||||
<button class="plain danger" :disabled="busy" @click="change(pendingAction)">确认</button>
|
||||
</section>
|
||||
</template>
|
||||
<p v-else-if="!error" class="muted">选择联系人,或按用户名查找。</p>
|
||||
</section>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useSession } from '../session'
|
||||
import type { Device } from '../session'
|
||||
|
||||
const session = useSession()
|
||||
const devices = ref<Device[]>([])
|
||||
const error = ref('')
|
||||
const busy = ref(false)
|
||||
const target = ref<Device>()
|
||||
const dates = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
|
||||
|
||||
async function perform(operation: () => Promise<void>) {
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await operation()
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '操作失败,请稍后重试'
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const refresh = () => perform(async () => { devices.value = await session.devices() })
|
||||
onMounted(refresh)
|
||||
|
||||
async function revoke() {
|
||||
if (!target.value) return
|
||||
const id = target.value.id
|
||||
target.value = undefined
|
||||
await perform(async () => {
|
||||
await session.revoke(id)
|
||||
devices.value = await session.devices()
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="session.identity" class="device-page">
|
||||
<header class="page-header"><h1>设备管理</h1><button class="plain" :disabled="busy" @click="refresh">刷新</button></header>
|
||||
<div class="device-content">
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<p v-if="busy && !devices.length" role="status">正在载入设备…</p>
|
||||
<article v-for="device in devices" :key="device.id" class="device-row">
|
||||
<span class="device-icon" aria-hidden="true">▣</span>
|
||||
<div class="device-meta">
|
||||
<div><strong>{{ device.name }}</strong><span v-if="device.id === session.identity.device.id" class="tag">当前设备</span></div>
|
||||
<small>{{ device.platform === 'windows' ? 'Windows · 桌面端' : 'Web · 浏览器' }} · {{ device.signedIn ? '已登录' : '已退出' }}</small>
|
||||
<small>首次登录 {{ dates.format(new Date(device.createdAt)) }} · 最近活动 {{ dates.format(new Date(device.lastActiveAt)) }}</small>
|
||||
</div>
|
||||
<span v-if="device.revokedAt" class="muted">已撤销</span>
|
||||
<button v-else-if="device.id !== session.identity.device.id" class="plain danger" :disabled="busy" @click="target = device">撤销</button>
|
||||
</article>
|
||||
<section v-if="target" class="confirmation" aria-label="确认撤销">
|
||||
<p>撤销「{{ target.name }}」后,该设备的登录会话将结束。</p>
|
||||
<button class="plain" @click="target = undefined">取消</button>
|
||||
<button class="plain danger" @click="revoke">确认撤销</button>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useSession } from '../session'
|
||||
|
||||
const session = useSession()
|
||||
const error = ref('')
|
||||
const busy = ref(false)
|
||||
const browser = window.xhchat?.openBrowser
|
||||
|
||||
async function act(action: () => Promise<void>) {
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await action()
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '操作失败,请稍后重试'
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main v-if="session.identity" class="workspace">
|
||||
<nav class="rail" aria-label="主导航">
|
||||
<RouterLink class="mark" to="/devices" aria-label="XHChat">X</RouterLink>
|
||||
<RouterLink class="rail-link" to="/contacts" title="联系人" aria-label="联系人">人</RouterLink>
|
||||
<RouterLink class="rail-link" to="/devices" title="设备管理" aria-label="设备管理">▣</RouterLink>
|
||||
<button v-if="browser" type="button" class="rail-link browser-button" title="浏览器" aria-label="浏览器" @click="act(browser)">◎</button>
|
||||
</nav>
|
||||
<aside class="account-panel">
|
||||
<div class="account-summary">
|
||||
<span class="avatar" aria-hidden="true">{{ session.identity.user.username[0]?.toUpperCase() }}</span>
|
||||
<div><strong>{{ session.identity.user.username }}</strong><small>我的账号</small></div>
|
||||
</div>
|
||||
<nav class="panel-links" aria-label="工作区">
|
||||
<RouterLink to="/contacts">联系人</RouterLink>
|
||||
<RouterLink to="/devices">设备管理</RouterLink>
|
||||
<button v-if="browser" class="plain mobile-browser" @click="act(browser)">浏览器</button>
|
||||
</nav>
|
||||
<div class="account-footer">
|
||||
<p aria-live="polite"><span class="dot" :class="{ online: session.connection === '实时连接已建立' }"></span>{{ session.connection }}</p>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<button class="plain" :disabled="busy" @click="act(session.logout)">退出登录</button>
|
||||
</div>
|
||||
</aside>
|
||||
<RouterView />
|
||||
</main>
|
||||
</template>
|
||||
Reference in new issue
Block a user