交付双端账号安全、外观设置和加密草稿
This commit is contained in:
1 parent
961fd68f49
commit
752ba88c5c
22 files changed
+896
-38
No files matched your search
+20
-11
@@ -13,6 +13,8 @@ import VoiceRecorder from './VoiceRecorder.vue'
|
||||
import { enableChat, trust } from './chat'
|
||||
import { discardPendingGroupMessage, forwardGroupMessage, groupAttachmentPath, groupQuote, publishGroup, removeLocalGroupMessage, sendGroupMessage, setGroupFavorite, synchronizeGroup } from './group-chat'
|
||||
import type { ForwardDestination, GroupDetail, GroupDevice, GroupLine } from './group-chat'
|
||||
import { useEncryptedDraft } from './drafts'
|
||||
import { handleComposerKey } from '../preferences'
|
||||
import { focusMessage, groupMessageFocus, groupMessageKey } from './message-key'
|
||||
|
||||
const props = defineProps<{ group: GroupDetail }>()
|
||||
@@ -51,6 +53,8 @@ const draggingFiles = ref(false)
|
||||
const batchProgress = ref('')
|
||||
const pendingVoice = ref<{ file: File; epoch: string }>()
|
||||
const busy = ref(false)
|
||||
const draftStorage = useEncryptedDraft(() => session.identity?.device.id,
|
||||
() => code.value ? 'group/' + props.group.id : '', draft, () => Boolean(editing.value))
|
||||
const error = ref('')
|
||||
const ready = computed(() => view.value?.ready && view.value.current?.membershipVersion === props.group.membershipVersion)
|
||||
const currentEpoch = computed(() => ready.value ? view.value?.current?.id : undefined)
|
||||
@@ -172,17 +176,20 @@ function saveAnnouncement() {
|
||||
}
|
||||
|
||||
function send() {
|
||||
if (!draft.value.trim() || view.value?.hasPending || !draftStorage.ready.value) return
|
||||
const identity = session.identity
|
||||
if (identity) void run(async () => {
|
||||
const text = draft.value
|
||||
if (editing.value?.epoch) {
|
||||
await sendGroupMessage(identity, props.group, { action: 'edit', id: editing.value.id, epoch: editing.value.epoch, text }, session.authorized)
|
||||
const text = draft.value, edited = editing.value, quoted = replying.value
|
||||
if (edited?.epoch) {
|
||||
await sendGroupMessage(identity, props.group, { action: 'edit', id: edited.id, epoch: edited.epoch, text }, session.authorized)
|
||||
} else {
|
||||
await sendGroupMessage(identity, props.group, replying.value ? { text, reply: replying.value } : text, session.authorized)
|
||||
await draftStorage.flush()
|
||||
await sendGroupMessage(identity, props.group, quoted ? { text, reply: quoted } : text, session.authorized, undefined, { expectedDraft: text })
|
||||
}
|
||||
if (draft.value === text) draft.value = ''
|
||||
editing.value = undefined
|
||||
replying.value = undefined
|
||||
if (!active) return
|
||||
if (!edited && !editing.value && draft.value === text) draft.value = ''
|
||||
if (editing.value === edited) editing.value = undefined
|
||||
if (replying.value === quoted) replying.value = undefined
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
@@ -294,7 +301,7 @@ function removeLocal() {
|
||||
const updated = await removeLocalGroupMessage(identity, props.group, message)
|
||||
if (view.value) view.value.lines = updated
|
||||
if (matches(replying.value)) replying.value = undefined
|
||||
if (matches(editing.value)) { editing.value = undefined; draft.value = '' }
|
||||
if (matches(editing.value)) editing.value = undefined
|
||||
if (matches(recalling.value)) recalling.value = undefined
|
||||
if (matches(forwarding.value)) forwarding.value = undefined
|
||||
deleting.value = undefined
|
||||
@@ -344,7 +351,6 @@ watch(currentEpoch, (epoch, previous) => {
|
||||
if (!previous || epoch === previous) return
|
||||
announcementDraft.value = undefined
|
||||
draggingFiles.value = false
|
||||
if (editing.value || replying.value) draft.value = ''
|
||||
editing.value = undefined
|
||||
replying.value = undefined
|
||||
recalling.value = undefined
|
||||
@@ -492,13 +498,16 @@ onBeforeUnmount(() => {
|
||||
<form v-if="ready" class="group-chat-composer" @submit.prevent="send">
|
||||
<div v-if="editing" class="chat-quote">
|
||||
<span>编辑消息</span>
|
||||
<button type="button" class="plain" @click="editing = undefined; draft = ''">取消编辑</button>
|
||||
<button type="button" class="plain" @click="editing = undefined">取消编辑</button>
|
||||
</div>
|
||||
<div v-else-if="replying" class="chat-quote">
|
||||
<span>引用 {{ groupQuote(replying) }}</span>
|
||||
<button type="button" class="plain" @click="replying = undefined">取消引用</button>
|
||||
</div>
|
||||
<label>群消息<textarea v-model="draft" rows="3" maxlength="8000" required /></label>
|
||||
<label>群消息<textarea v-model="draft" :readonly="busy || !draftStorage.ready.value" rows="3" maxlength="8000" required @keydown="handleComposerKey($event, send)" /></label>
|
||||
<p v-if="draftStorage.status.value" class="muted" role="status">{{ draftStorage.status.value }}</p>
|
||||
<button v-if="draftStorage.status.value.includes('保存失败')" type="button" class="plain" @click="draftStorage.retry()">重试保存草稿</button>
|
||||
<button v-if="draftStorage.conflict.value" type="button" class="plain" @click="draftStorage.overwrite()">使用当前草稿覆盖本机记录</button>
|
||||
<button class="primary" :disabled="busy || view?.hasPending || !draft.trim()">{{ editing ? '保存编辑' : '发送群消息' }}</button>
|
||||
</form>
|
||||
<div v-if="ready && !editing" class="group-chat-composer">
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface ChatLine extends FavoriteFields {
|
||||
}
|
||||
|
||||
export interface ChatState {
|
||||
drafts?: Record<string, string>
|
||||
engine: string
|
||||
cursor: string
|
||||
pending: Incoming[]
|
||||
@@ -220,7 +221,7 @@ export function mutateMessage(identity: ChatIdentity, user: string, peer: Peer,
|
||||
}
|
||||
|
||||
export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call,
|
||||
{ reply, onQueued }: { reply?: ChatLine; onQueued?: () => void } = {}) {
|
||||
{ reply, onQueued, expectedDraft }: { reply?: ChatLine; onQueued?: () => void; expectedDraft?: string } = {}) {
|
||||
return update(identity, async (state, save, factory) => {
|
||||
const current = (await directory(call, user)).find((item) => item.id === peer.id)
|
||||
if (!current || state.pinned[current.id] !== current.publicKey) throw new Error('发送前请核验对方设备安全码')
|
||||
@@ -258,6 +259,8 @@ export function send(identity: ChatIdentity, user: string, peer: Peer, content:
|
||||
const ciphertext = engine.encrypt(group, aad(id, identity.device.id, current.id), plaintext)
|
||||
state.outbox.push({ messageId: id, recipientDevice: current.id, ciphertext: base64(ciphertext) })
|
||||
state.lines.push({ id, peer: current.id, contact: user, text, attachment, quote: attachment ? undefined : quote, time: new Date().toISOString(), own: true })
|
||||
const draftKey = 'private/' + user + '/' + current.id
|
||||
if (expectedDraft !== undefined && content === expectedDraft && state.drafts?.[draftKey] === expectedDraft) delete state.drafts[draftKey]
|
||||
state.engine = base64(engine.snapshot())
|
||||
await save(state)
|
||||
onQueued?.()
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { computed, onBeforeUnmount, shallowReactive, shallowRef, watch } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
import type { ChatState } from './chat'
|
||||
import { withVault } from './vault'
|
||||
|
||||
interface Draft {
|
||||
device: string
|
||||
scope: string
|
||||
value: string
|
||||
saved: string
|
||||
loaded: boolean
|
||||
restored: boolean
|
||||
error: string
|
||||
conflict: boolean
|
||||
users: number
|
||||
loading?: Promise<void>
|
||||
writing?: Promise<void>
|
||||
}
|
||||
|
||||
// Failed writes stay available in memory when a user changes conversations.
|
||||
const pending = new Map<string, Draft>()
|
||||
const keyOf = (draft: Draft) => draft.device + ':' + draft.scope
|
||||
window.addEventListener('beforeunload', (event) => {
|
||||
if ([...pending.values()].some((draft) => draft.value !== draft.saved || draft.writing)) {
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
})
|
||||
function release(draft: Draft) {
|
||||
if (!draft.users && !draft.writing && (draft.loaded && draft.value === draft.saved || !draft.loaded)) {
|
||||
if (pending.get(keyOf(draft)) === draft) pending.delete(keyOf(draft))
|
||||
}
|
||||
}
|
||||
|
||||
function obtain(device: string, scope: string): Draft {
|
||||
const existing = pending.get(device + ':' + scope)
|
||||
if (existing) return existing
|
||||
const draft = shallowReactive<Draft>({ device, scope, value: '', saved: '', loaded: false, restored: true,
|
||||
error: '', conflict: false, users: 0 })
|
||||
pending.set(keyOf(draft), draft)
|
||||
draft.loading = withVault<ChatState, void>(device, async (state) => {
|
||||
if (!state) throw new Error('请先启用本机加密聊天')
|
||||
draft.value = draft.saved = state.drafts?.[scope] ?? ''
|
||||
draft.loaded = true
|
||||
}, true).catch(() => {
|
||||
draft.error = '草稿读取失败,请重新进入会话后重试'
|
||||
})
|
||||
return draft
|
||||
}
|
||||
|
||||
async function persist(draft: Draft, overwrite = false): Promise<void> {
|
||||
await draft.loading
|
||||
if (!draft.loaded) throw new Error(draft.error)
|
||||
if (draft.writing) {
|
||||
await draft.writing
|
||||
return persist(draft, overwrite)
|
||||
}
|
||||
if (draft.value === draft.saved && !overwrite) return
|
||||
const value = draft.value, previous = draft.saved
|
||||
draft.error = ''
|
||||
draft.conflict = false
|
||||
draft.writing = withVault<ChatState, void>(draft.device, async (state, save) => {
|
||||
if (!state) throw new Error('请先启用本机加密聊天')
|
||||
const drafts = state.drafts ??= {}
|
||||
const stored = drafts[draft.scope] ?? ''
|
||||
if (!overwrite && stored !== previous && stored !== value) {
|
||||
draft.conflict = true
|
||||
throw new Error('草稿已在其他页面变更,当前输入已保留。可复制内容,或使用当前草稿覆盖本机记录。')
|
||||
}
|
||||
if (stored !== value) {
|
||||
if (value) drafts[draft.scope] = value
|
||||
else delete drafts[draft.scope]
|
||||
await save(state)
|
||||
}
|
||||
draft.saved = value
|
||||
draft.restored = false
|
||||
}, true).catch((cause: unknown) => {
|
||||
draft.error = draft.conflict && cause instanceof Error ? cause.message : '草稿保存失败,请保留当前页面并重试'
|
||||
throw new Error(draft.error)
|
||||
}).finally(() => {
|
||||
draft.writing = undefined
|
||||
release(draft)
|
||||
})
|
||||
await draft.writing
|
||||
if (draft.value !== draft.saved) await persist(draft)
|
||||
}
|
||||
|
||||
export function useEncryptedDraft(device: () => string | undefined, scope: () => string, text: Ref<string>, editing: () => boolean) {
|
||||
const current = shallowRef<Draft>()
|
||||
const ready = computed(() => Boolean(current.value?.loaded))
|
||||
const conflict = computed(() => Boolean(current.value?.conflict))
|
||||
const status = computed(() => {
|
||||
const draft = current.value
|
||||
if (!draft) return ''
|
||||
if (draft.error) return draft.error
|
||||
if (!draft.loaded) return '正在读取本机草稿…'
|
||||
if (draft.writing || draft.value !== draft.saved) return '正在保存草稿…'
|
||||
return draft.value ? draft.restored ? '已恢复本机草稿' : '草稿已保存在本机' : ''
|
||||
})
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let active = true
|
||||
function backgroundSave(draft = current.value) {
|
||||
clearTimeout(timer)
|
||||
if (draft) void persist(draft).catch(() => {})
|
||||
}
|
||||
function detach() {
|
||||
const draft = current.value
|
||||
if (!draft) return
|
||||
backgroundSave(draft)
|
||||
draft.users--
|
||||
release(draft)
|
||||
current.value = undefined
|
||||
}
|
||||
watch(() => [device(), scope()] as const, async ([deviceID, key]) => {
|
||||
detach()
|
||||
text.value = ''
|
||||
if (!deviceID || !key) return
|
||||
const draft = obtain(deviceID, key)
|
||||
draft.users++
|
||||
current.value = draft
|
||||
await draft.loading
|
||||
if (active && current.value === draft && draft.loaded && !editing()) text.value = draft.value
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
watch(text, (value) => {
|
||||
const draft = current.value
|
||||
if (!draft?.loaded || editing() || value === draft.value) return
|
||||
draft.value = value
|
||||
draft.restored = false
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(backgroundSave, 350)
|
||||
}, { flush: 'sync' })
|
||||
watch(editing, (value) => {
|
||||
if (value) backgroundSave()
|
||||
else if (current.value?.loaded) text.value = current.value.value
|
||||
}, { flush: 'sync' })
|
||||
onBeforeUnmount(() => {
|
||||
active = false
|
||||
detach()
|
||||
})
|
||||
async function flush() {
|
||||
clearTimeout(timer)
|
||||
if (current.value) await persist(current.value)
|
||||
}
|
||||
function overwrite() {
|
||||
clearTimeout(timer)
|
||||
if (current.value) void persist(current.value, true).catch(() => {})
|
||||
}
|
||||
return { status, ready, conflict, flush, retry: backgroundSave, overwrite }
|
||||
}
|
||||
@@ -355,7 +355,8 @@ export async function forwardContent(identity: ChatIdentity, destination: Forwar
|
||||
return '转发待投递,请打开目标群重试'
|
||||
}
|
||||
|
||||
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, message: GroupContent, call: Call, expectedEpoch?: string) {
|
||||
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, message: GroupContent, call: Call, expectedEpoch?: string,
|
||||
{ expectedDraft }: { expectedDraft?: string } = {}) {
|
||||
return update(identity, async (state, save, factory) => {
|
||||
const announcement = typeof message === 'object' && 'announcement' in message ? message.announcement.trim() : undefined
|
||||
const text = (typeof message === 'string' ? message : !(message instanceof File) && 'text' in message ? message.text ?? '' : '').trim()
|
||||
@@ -406,6 +407,9 @@ export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, mes
|
||||
chat.pendingMessage = { id, epoch: epoch.id, wire: base64(wire), mutation, announcement,
|
||||
line: { id, epoch: epoch.id, user: identity.user.id, name: own.name, sender: identity.device.id,
|
||||
text, quote, attachment, time: new Date().toISOString() } }
|
||||
const draftedText = typeof message === 'string' ? message : typeof message === 'object' && 'reply' in message ? message.text : undefined
|
||||
const draftKey = 'group/' + group.id
|
||||
if (expectedDraft !== undefined && draftedText === expectedDraft && state.drafts?.[draftKey] === expectedDraft) delete state.drafts[draftKey]
|
||||
state.engine = base64(engine.snapshot())
|
||||
await save(state)
|
||||
} finally {
|
||||
|
||||
@@ -8,11 +8,15 @@ import ContactsView from './views/ContactsView.vue'
|
||||
import ChatView from './views/ChatView.vue'
|
||||
import GroupView from './views/GroupView.vue'
|
||||
import FavoritesView from './views/FavoritesView.vue'
|
||||
import PreferencesView from './views/PreferencesView.vue'
|
||||
import SecurityView from './views/SecurityView.vue'
|
||||
import { initializePreferences } from './preferences'
|
||||
import Workspace from './views/Workspace.vue'
|
||||
import { useSession } from './session'
|
||||
import { incomingGroupInvite, parseGroupInvite } from './chat/group-invites'
|
||||
import './style.css'
|
||||
|
||||
initializePreferences()
|
||||
const pinia = createPinia()
|
||||
const router = createRouter({
|
||||
history: createWebHashHistory(),
|
||||
@@ -25,6 +29,8 @@ const router = createRouter({
|
||||
{ path: 'chat/:user?', component: ChatView },
|
||||
{ path: 'groups/:id?', component: GroupView },
|
||||
{ path: 'favorites', component: FavoritesView },
|
||||
{ path: 'settings', component: PreferencesView },
|
||||
{ path: 'security', component: SecurityView },
|
||||
] },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
],
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { readonly, ref } from 'vue'
|
||||
|
||||
export type Theme = 'system' | 'light' | 'dark'
|
||||
export type SendMode = 'button' | 'enter' | 'ctrl-enter'
|
||||
const key = 'xhchat-appearance-and-input'
|
||||
const theme = ref<Theme>('system')
|
||||
const sendMode = ref<SendMode>('button')
|
||||
|
||||
function readPreferences() {
|
||||
try {
|
||||
const stored = JSON.parse(localStorage.getItem(key) ?? '{}')
|
||||
theme.value = stored?.theme === 'light' || stored?.theme === 'dark' ? stored.theme : 'system'
|
||||
sendMode.value = stored?.sendMode === 'enter' || stored?.sendMode === 'ctrl-enter' ? stored.sendMode : 'button'
|
||||
} catch {
|
||||
theme.value = 'system'
|
||||
sendMode.value = 'button'
|
||||
}
|
||||
document.documentElement.dataset.theme = theme.value
|
||||
}
|
||||
|
||||
export const preferences = { theme: readonly(theme), sendMode: readonly(sendMode) }
|
||||
|
||||
export function savePreferences(nextTheme: Theme, nextSendMode: SendMode) {
|
||||
if (!['system', 'light', 'dark'].includes(nextTheme) || !['button', 'enter', 'ctrl-enter'].includes(nextSendMode)) {
|
||||
throw new Error('请选择有效的外观和发送方式')
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify({ theme: nextTheme, sendMode: nextSendMode }))
|
||||
} catch {
|
||||
throw new Error('本机无法保存设置,请检查浏览器存储权限')
|
||||
}
|
||||
theme.value = nextTheme
|
||||
sendMode.value = nextSendMode
|
||||
document.documentElement.dataset.theme = nextTheme
|
||||
}
|
||||
|
||||
export function initializePreferences() {
|
||||
readPreferences()
|
||||
window.addEventListener('storage', (event) => {
|
||||
if (event.key === key || event.key === null) readPreferences()
|
||||
})
|
||||
}
|
||||
|
||||
export function handleComposerKey(event: KeyboardEvent, send: () => void) {
|
||||
if (event.key !== 'Enter' || event.isComposing || event.keyCode === 229 || event.shiftKey || event.altKey) return
|
||||
const matches = sendMode.value === 'enter' ? !event.ctrlKey && !event.metaKey :
|
||||
sendMode.value === 'ctrl-enter' && (event.ctrlKey || event.metaKey)
|
||||
if (!matches) return
|
||||
event.preventDefault()
|
||||
if (!event.repeat) send()
|
||||
}
|
||||
+6
-1
@@ -118,8 +118,13 @@ export const useSession = defineStore('session', () => {
|
||||
clear()
|
||||
}
|
||||
|
||||
async function changePassword(currentPassword: string, newPassword: string) {
|
||||
await authorized('/auth/password', 'POST', { currentPassword, newPassword })
|
||||
clear()
|
||||
}
|
||||
|
||||
return {
|
||||
identity, connection, contactChanges, inboxChanges, privateNotice, groupChange, groupListChanges, authenticate, logout, authorized,
|
||||
identity, connection, contactChanges, inboxChanges, privateNotice, groupChange, groupListChanges, authenticate, logout, changePassword, authorized,
|
||||
devices: () => authorized<Device[]>('/devices'),
|
||||
revoke: (id: string) => authorized<void>('/devices/' + encodeURIComponent(id), 'DELETE'),
|
||||
contacts: () => authorized<Contact[]>('/contacts'),
|
||||
|
||||
+9
-3
@@ -1,6 +1,6 @@
|
||||
* { box-sizing: border-box; }
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
color-scheme: light;
|
||||
--surface: #ffffff;
|
||||
--base: #f1f5f3;
|
||||
--text: #182822;
|
||||
@@ -14,11 +14,17 @@
|
||||
background: var(--base);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
:root:not([data-theme='light']) {
|
||||
color-scheme: dark;
|
||||
--surface: #182520; --base: #101a16; --text: #edf4ef; --muted: #a8bcb0;
|
||||
--line: #34483d; --green: #7ed8b1; --green-soft: #244236; --danger: #ff9aa2;
|
||||
}
|
||||
}
|
||||
:root[data-theme='dark'] {
|
||||
color-scheme: dark;
|
||||
--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; }
|
||||
@@ -143,7 +149,7 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so
|
||||
.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; }
|
||||
.panel-links { display: flex; flex-wrap: wrap; 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; }
|
||||
|
||||
+46
-18
@@ -15,6 +15,8 @@ import VoiceRecorder from '../chat/VoiceRecorder.vue'
|
||||
import VoiceMessage from '../chat/VoiceMessage.vue'
|
||||
import MediaPreview from '../chat/MediaPreview.vue'
|
||||
import MessageText from '../chat/MessageText.vue'
|
||||
import { handleComposerKey } from '../preferences'
|
||||
import { useEncryptedDraft } from '../chat/drafts'
|
||||
import { focusMessage, privateMessageFocus, privateMessageKey } from '../chat/message-key'
|
||||
|
||||
const session = useSession()
|
||||
@@ -52,6 +54,8 @@ const activeContact = computed(() => contacts.value.find((item) => item.id === t
|
||||
const peer = computed(() => view.value?.peers.find((item) => item.id === selected.value))
|
||||
const trusted = computed(() => peer.value && view.value?.pinned[peer.value.id] === peer.value.publicKey)
|
||||
const changed = computed(() => peer.value && view.value?.pinned[peer.value.id] && !trusted.value)
|
||||
const draftStorage = useEncryptedDraft(() => session.identity?.device.id,
|
||||
() => ownCode.value && target.value && selected.value ? 'private/' + target.value + '/' + selected.value : '', draft, () => Boolean(editing.value))
|
||||
const conversations = computed(() => {
|
||||
const query = conversationQuery.value.trim().toLowerCase()
|
||||
return contacts.value.filter((item) => item.state === 'friend' &&
|
||||
@@ -77,6 +81,7 @@ let markingSeen = false
|
||||
let active = true
|
||||
let refreshRequested = false
|
||||
let refreshTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let backgroundTask: Promise<void> | undefined
|
||||
const seen = new Map<string, string>()
|
||||
|
||||
async function loadConversations() {
|
||||
@@ -132,9 +137,12 @@ function queueSeen() {
|
||||
|
||||
async function execute(action: () => Promise<void>) {
|
||||
if (busy.value || !session.identity) return
|
||||
const deviceID = session.identity.device.id, contact = target.value, peerID = selected.value
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await backgroundTask
|
||||
if (!active || session.identity?.device.id !== deviceID || target.value !== contact || selected.value !== peerID) return
|
||||
await action()
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '加密聊天暂不可用'
|
||||
@@ -145,6 +153,18 @@ async function execute(action: () => Promise<void>) {
|
||||
}
|
||||
}
|
||||
|
||||
function background(action: () => Promise<void>) {
|
||||
if (!active || busy.value || backgroundTask) return
|
||||
backgroundTask = action().catch((cause: unknown) => {
|
||||
if (active && !busy.value) error.value = cause instanceof Error ? cause.message : '同步暂不可用'
|
||||
}).finally(() => {
|
||||
backgroundTask = undefined
|
||||
if (!active) return
|
||||
scheduleReceipt()
|
||||
if (refreshRequested) sync()
|
||||
})
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const identity = session.identity
|
||||
if (!identity || !target.value || !ownCode.value) return
|
||||
@@ -162,7 +182,8 @@ async function refresh() {
|
||||
if (requested && openedMessage.value !== requested.key && current.peers.some((device) => device.id === requested.device)) {
|
||||
selected.value = requested.device
|
||||
} else if (!current.peers.some((device) => device.id === selected.value)) {
|
||||
selected.value = current.peers[0]?.id ?? ''
|
||||
selected.value = (current.peers.find((device) => device.mls && current.pinned[device.id] === device.publicKey) ??
|
||||
current.peers.find((device) => device.mls) ?? current.peers[0])?.id ?? ''
|
||||
}
|
||||
queueSeen()
|
||||
}
|
||||
@@ -179,20 +200,20 @@ function togglePreference(preference: 'mute' | 'pin') {
|
||||
|
||||
function scheduleReceipt() {
|
||||
clearTimeout(receiptTimer)
|
||||
if (!view.value?.shareRead || busy.value || !trusted.value) return
|
||||
if (!view.value?.shareRead || busy.value || backgroundTask || !trusted.value) return
|
||||
receiptTimer = setTimeout(async () => {
|
||||
await nextTick()
|
||||
const identity = session.identity
|
||||
const selectedPeer = peer.value
|
||||
const list = history.value
|
||||
if (busy.value || !identity || !selectedPeer || !list || document.visibilityState !== 'visible' || !document.hasFocus()) return
|
||||
if (busy.value || backgroundTask || !identity || !selectedPeer || !list || document.visibilityState !== 'visible' || !document.hasFocus()) return
|
||||
const bounds = list.getBoundingClientRect()
|
||||
const ids = Array.from(list.querySelectorAll<HTMLElement>('[data-unread]')).filter((row) => {
|
||||
const rect = row.getBoundingClientRect()
|
||||
return Math.min(rect.bottom, bounds.bottom, innerHeight) - Math.max(rect.top, bounds.top, 0) >= Math.min(rect.height, 24)
|
||||
}).map((row) => row.dataset.unread!).slice(0, 64)
|
||||
if (!ids.length) return
|
||||
await execute(async () => {
|
||||
background(async () => {
|
||||
await markRead(identity, target.value, selectedPeer, ids, session.authorized)
|
||||
await refresh()
|
||||
})
|
||||
@@ -232,16 +253,22 @@ function confirm() {
|
||||
}
|
||||
|
||||
function submit() {
|
||||
if (!draft.value.trim() || !draftStorage.ready.value) return
|
||||
void execute(async () => {
|
||||
if (!session.identity || !peer.value) return
|
||||
if (editing.value) {
|
||||
await mutateMessage(session.identity, target.value, peer.value, { action: 'edit', id: editing.value.id, text: draft.value }, session.authorized)
|
||||
const identity = session.identity
|
||||
if (!identity || !peer.value) return
|
||||
const text = draft.value, contact = target.value, device = peer.value, edited = editing.value, quoted = reply.value
|
||||
if (edited) {
|
||||
await mutateMessage(identity, contact, device, { action: 'edit', id: edited.id, text }, session.authorized)
|
||||
} else {
|
||||
await send(session.identity, target.value, peer.value, draft.value, session.authorized, { reply: reply.value })
|
||||
await draftStorage.flush()
|
||||
await send(identity, contact, device, text, session.authorized, { reply: quoted, expectedDraft: text, onQueued: () => {
|
||||
if (target.value === contact && selected.value === device.id && draft.value === text) draft.value = ''
|
||||
} })
|
||||
}
|
||||
draft.value = ''
|
||||
reply.value = undefined
|
||||
editing.value = undefined
|
||||
if (!active || target.value !== contact || selected.value !== device.id) return
|
||||
if (reply.value === quoted) reply.value = undefined
|
||||
if (editing.value === edited) editing.value = undefined
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
@@ -377,12 +404,12 @@ function submitForward(destination: ForwardDestination) {
|
||||
function sync() {
|
||||
if (!active || !ownCode.value || !target.value) return
|
||||
refreshRequested = true
|
||||
if (busy.value || refreshTimer) return
|
||||
if (busy.value || backgroundTask || refreshTimer) return
|
||||
refreshTimer = setTimeout(() => {
|
||||
refreshTimer = undefined
|
||||
if (busy.value) return
|
||||
if (busy.value || backgroundTask) return
|
||||
refreshRequested = false
|
||||
void execute(refresh)
|
||||
background(refresh)
|
||||
}, 180)
|
||||
}
|
||||
|
||||
@@ -390,7 +417,6 @@ watch(target, () => {
|
||||
view.value = undefined
|
||||
selected.value = ''
|
||||
code.value = ''
|
||||
draft.value = ''
|
||||
sync()
|
||||
})
|
||||
watch(selected, () => {
|
||||
@@ -405,7 +431,6 @@ watch(selected, () => {
|
||||
pendingVoice.value = undefined
|
||||
files.value = []
|
||||
draggingFiles.value = false
|
||||
draft.value = ''
|
||||
scheduleReceipt()
|
||||
queueSeen()
|
||||
})
|
||||
@@ -552,7 +577,7 @@ onBeforeUnmount(() => {
|
||||
<form class="chat-compose" @submit.prevent="submit">
|
||||
<div v-if="editing" class="chat-quote">
|
||||
<span>正在编辑消息</span>
|
||||
<button type="button" class="plain" @click="editing = undefined; draft = ''">取消编辑</button>
|
||||
<button type="button" class="plain" @click="editing = undefined">取消编辑</button>
|
||||
</div>
|
||||
<div v-if="reply" class="chat-quote">
|
||||
<span>引用 {{ (reply.text || reply.attachment?.name || '').slice(0, 80) }}</span>
|
||||
@@ -575,7 +600,10 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
</section>
|
||||
<VoiceRecorder v-if="!editing" :key="selected" :disabled="busy" @send="sendVoice" @error="error = $event" />
|
||||
<label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label>
|
||||
<label>消息<textarea v-model="draft" :readonly="busy || !draftStorage.ready.value" required rows="3" maxlength="4000" @keydown="handleComposerKey($event, submit)"></textarea></label>
|
||||
<p v-if="draftStorage.status.value" class="muted" role="status">{{ draftStorage.status.value }}</p>
|
||||
<button v-if="draftStorage.status.value.includes('保存失败')" type="button" class="plain" @click="draftStorage.retry()">重试保存草稿</button>
|
||||
<button v-if="draftStorage.conflict.value" type="button" class="plain" @click="draftStorage.overwrite()">使用当前草稿覆盖本机记录</button>
|
||||
<button class="primary" :disabled="busy || !draft.trim()">{{ editing ? '保存编辑' : '发送' }}</button>
|
||||
</form>
|
||||
</template>
|
||||
|
||||
@@ -8,6 +8,8 @@ const devices = ref<Device[]>([])
|
||||
const error = ref('')
|
||||
const busy = ref(false)
|
||||
const target = ref<Device>()
|
||||
const renaming = ref<Device>()
|
||||
const name = ref('')
|
||||
const dates = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
|
||||
|
||||
async function perform(operation: () => Promise<void>) {
|
||||
@@ -34,6 +36,16 @@ async function revoke() {
|
||||
devices.value = await session.devices()
|
||||
})
|
||||
}
|
||||
|
||||
function rename() {
|
||||
const device = renaming.value
|
||||
if (!device || busy.value) return
|
||||
void perform(async () => {
|
||||
await session.authorized('/devices/' + device.id, 'POST', { name: name.value })
|
||||
renaming.value = undefined
|
||||
devices.value = await session.devices()
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -50,8 +62,14 @@ async function revoke() {
|
||||
<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>
|
||||
<button v-if="!device.revokedAt" class="plain" :disabled="busy" @click="renaming = device; name = device.name">重命名</button>
|
||||
<button v-if="!device.revokedAt && device.id !== session.identity.device.id" class="plain danger" :disabled="busy" @click="target = device">撤销</button>
|
||||
</article>
|
||||
<form v-if="renaming" class="contact-preferences" aria-label="设备重命名" @submit.prevent="rename">
|
||||
<label>设备新名称<input v-model="name" required maxlength="64"></label>
|
||||
<button class="plain" :disabled="busy || !name.trim()">保存设备名称</button>
|
||||
<button type="button" class="plain" :disabled="busy" @click="renaming = undefined">取消</button>
|
||||
</form>
|
||||
<section v-if="target" class="confirmation" aria-label="确认撤销">
|
||||
<p>撤销「{{ target.name }}」后,该设备的登录会话将结束。</p>
|
||||
<button class="plain" @click="target = undefined">取消</button>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { preferences, savePreferences } from '../preferences'
|
||||
|
||||
const theme = ref(preferences.theme.value)
|
||||
const sendMode = ref(preferences.sendMode.value)
|
||||
const error = ref('')
|
||||
const saved = ref(false)
|
||||
|
||||
watch([preferences.theme, preferences.sendMode], ([nextTheme, nextSendMode]) => {
|
||||
theme.value = nextTheme
|
||||
sendMode.value = nextSendMode
|
||||
})
|
||||
watch([theme, sendMode], () => { saved.value = false })
|
||||
|
||||
function save() {
|
||||
error.value = ''
|
||||
try {
|
||||
savePreferences(theme.value, sendMode.value)
|
||||
saved.value = true
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '无法保存设置'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="device-page">
|
||||
<header class="page-header"><h1>设置</h1></header>
|
||||
<div class="device-content">
|
||||
<form class="preference-form" @submit.prevent="save">
|
||||
<label><span id="theme-label">外观</span>
|
||||
<select v-model="theme" aria-labelledby="theme-label">
|
||||
<option value="system">跟随系统</option><option value="light">浅色</option><option value="dark">深色</option>
|
||||
</select>
|
||||
</label>
|
||||
<label><span id="send-mode-label">消息发送方式</span>
|
||||
<select v-model="sendMode" aria-labelledby="send-mode-label">
|
||||
<option value="button">点击发送按钮</option><option value="enter">Enter 发送,Shift + Enter 换行</option>
|
||||
<option value="ctrl-enter">Ctrl / ⌘ + Enter 发送</option>
|
||||
</select>
|
||||
</label>
|
||||
<p class="muted">应用于此设备的私聊和群聊。</p>
|
||||
<p v-if="error" role="alert" class="error">{{ error }}</p>
|
||||
<p v-if="saved" role="status">已保存本机设置</p>
|
||||
<button class="primary">保存设置</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.preference-form { display: grid; gap: 1rem; max-width: 25rem; }
|
||||
.preference-form select { font: inherit; width: 100%; padding: .65rem; background: var(--base); color: var(--text); border: 1px solid var(--line); border-radius: .5rem; }
|
||||
.preference-form button { justify-self: start; }
|
||||
</style>
|
||||
@@ -0,0 +1,96 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useSession } from '../session'
|
||||
|
||||
interface LoginRecord { id: string; deviceName: string; platform: string; createdAt: string; currentDevice: boolean }
|
||||
const session = useSession()
|
||||
const currentPassword = ref('')
|
||||
const newPassword = ref('')
|
||||
const confirmation = ref('')
|
||||
const confirmLogout = ref(false)
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
const status = ref('')
|
||||
const history = ref<LoginRecord[]>([])
|
||||
const dates = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
|
||||
|
||||
async function run(action: () => Promise<void>) {
|
||||
if (busy.value) return
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
status.value = ''
|
||||
try { await action() }
|
||||
catch (cause) { error.value = cause instanceof Error ? cause.message : '账号操作失败' }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
void run(async () => { history.value = await session.authorized<LoginRecord[]>('/auth/history') })
|
||||
}
|
||||
|
||||
function password() {
|
||||
void run(async () => {
|
||||
if (newPassword.value !== confirmation.value) throw new Error('两次输入的新密码不一致')
|
||||
if ([...newPassword.value].length < 12 || new TextEncoder().encode(newPassword.value).length > 256) {
|
||||
throw new Error('新密码须至少 12 个字符且最多 256 字节')
|
||||
}
|
||||
await session.changePassword(currentPassword.value, newPassword.value)
|
||||
currentPassword.value = newPassword.value = confirmation.value = ''
|
||||
})
|
||||
}
|
||||
|
||||
function logoutOthers() {
|
||||
void run(async () => {
|
||||
await session.authorized('/auth/logout-others', 'POST')
|
||||
confirmLogout.value = false
|
||||
status.value = '其他登录会话已退出'
|
||||
})
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="device-page">
|
||||
<header class="page-header"><h1>账号安全</h1></header>
|
||||
<div class="device-content security-settings">
|
||||
<p v-if="error" role="alert" class="error">{{ error }}</p>
|
||||
<p v-if="status" role="status">{{ status }}</p>
|
||||
<form class="security-password" aria-label="修改密码" @submit.prevent="password">
|
||||
<h2>修改密码</h2>
|
||||
<label>当前密码<input v-model="currentPassword" type="password" autocomplete="current-password" required maxlength="256"></label>
|
||||
<label>新密码<input v-model="newPassword" type="password" autocomplete="new-password" required maxlength="256"></label>
|
||||
<label>确认新密码<input v-model="confirmation" type="password" autocomplete="new-password" required maxlength="256"></label>
|
||||
<p class="muted">修改成功后,所有设备需要使用新密码重新登录。</p>
|
||||
<button class="primary" :disabled="busy">修改密码并重新登录</button>
|
||||
</form>
|
||||
<section aria-label="登录会话">
|
||||
<h2>登录会话</h2>
|
||||
<button class="plain" :disabled="busy" @click="confirmLogout = true">退出其他登录会话</button>
|
||||
<div v-if="confirmLogout" class="confirmation">
|
||||
<p>结束此账号的其他登录会话?再次使用时需要重新登录。</p>
|
||||
<button class="plain danger" :disabled="busy" @click="logoutOthers">确认退出其他会话</button>
|
||||
<button class="plain" :disabled="busy" @click="confirmLogout = false">取消</button>
|
||||
</div>
|
||||
</section>
|
||||
<section aria-label="登录记录" class="security-history">
|
||||
<div class="contact-heading"><h2>最近登录记录</h2><button class="plain" :disabled="busy" @click="refresh">刷新记录</button></div>
|
||||
<p class="muted">显示最近 50 次成功登录,记录从此功能启用后开始保存。</p>
|
||||
<p v-if="!history.length && !busy">暂无登录记录。</p>
|
||||
<ul><li v-for="item in history" :key="item.id">
|
||||
<strong>{{ item.deviceName }}</strong><span v-if="item.currentDevice" class="tag">当前设备</span>
|
||||
<small>{{ item.platform === 'windows' ? 'Windows' : 'Web' }} · {{ dates.format(new Date(item.createdAt)) }}</small>
|
||||
</li></ul>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.security-settings { display: grid; gap: 1.5rem; }
|
||||
.security-password { display: grid; gap: .75rem; width: min(100%, 26rem); }
|
||||
.security-password button { justify-self: start; white-space: normal; }
|
||||
.security-settings h2 { font-size: 1.15rem; margin: 0 0 .5rem; }
|
||||
.security-history ul { margin: .5rem 0; padding: 0; list-style: none; }
|
||||
.security-history li { padding: .6rem 0; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
|
||||
.security-history small { display: block; }
|
||||
</style>
|
||||
@@ -145,6 +145,8 @@ async function act(action: () => Promise<void>) {
|
||||
<RouterLink to="/groups">群组</RouterLink>
|
||||
<RouterLink to="/favorites">收藏</RouterLink>
|
||||
<RouterLink to="/devices">设备管理</RouterLink>
|
||||
<RouterLink to="/settings">设置</RouterLink>
|
||||
<RouterLink to="/security">账号安全</RouterLink>
|
||||
<button v-if="browser" class="plain mobile-browser" @click="act(browser)">浏览器</button>
|
||||
</nav>
|
||||
<div class="account-footer">
|
||||
|
||||
Reference in new issue
Block a user