Files
XHChat/tests/group-chat.test.mjs
T

640 lines
40 KiB
JavaScript

import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import electron from 'electron'
import { _electron, chromium } from 'playwright'
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
const work = (page) => page.getByRole('navigation', { name: '工作区' })
const chat = (page) => page.getByRole('region', { name: '群消息' })
const historyView = (page, name) => chat(page).getByRole('group', { name: '群历史视图' }).getByRole('button', { name, exact: true })
const id = () => randomBytes(6).toString('hex')
async function register(page, username, password) {
await page.getByRole('button', { name: '注册', exact: true }).click()
await page.getByLabel('用户名').fill(username)
await page.getByLabel('密码', { exact: true }).fill(password)
const registration = page.waitForResponse((item) => item.url().endsWith('/auth/register') && item.status() === 201)
await page.locator('button.primary').click()
await page.getByText('实时连接已建立').waitFor()
return (await registration).json()
}
async function connect(owner, member, ownerName, memberName) {
await work(owner).getByRole('link', { name: '联系人' }).click()
await work(member).getByRole('link', { name: '联系人' }).click()
await owner.getByLabel('按用户名查找').fill(memberName)
await owner.getByRole('button', { name: '查找' }).click()
await owner.getByRole('button', { name: '添加好友' }).click()
await member.getByRole('button', { name: new RegExp(ownerName) }).click()
await member.getByRole('button', { name: '接受申请' }).click()
await owner.getByRole('link', { name: '打开加密聊天' }).waitFor()
}
async function invite(owner, member, memberName, group) {
await work(member).getByRole('link', { name: '群组' }).click()
await member.getByRole('heading', { name: '群组', exact: true }).waitFor()
await member.getByText('选择或创建群组。').waitFor()
await owner.getByLabel('邀请联系人').selectOption({ label: memberName })
await owner.getByRole('button', { name: '发送邀请' }).click()
await member.getByRole('link', { name: new RegExp(group + '.*待接受邀请') }).click({ timeout: 4500 })
await member.getByRole('button', { name: '接受邀请' }).click()
await owner.getByRole('list', { name: '群成员' }).getByText(memberName + ' · 成员', { exact: true }).waitFor({ timeout: 4500 })
await chat(member).getByRole('button', { name: '启用本机群聊' }).waitFor()
}
async function verify(page, name, code) {
const section = chat(page).locator('.group-device-member').filter({ hasText: name })
const securityCode = section.getByLabel(new RegExp(name + '.*安全码'))
await securityCode.fill(code)
await section.getByRole('button', { name: '核验设备' }).click()
await securityCode.waitFor({ state: 'detached' })
}
async function publish(owner, pages) {
await chat(owner).getByRole('button', { name: '建立群加密会话' }).click()
await Promise.all(pages.map((page) => chat(page).getByText('群加密已建立', { exact: true }).waitFor()))
}
async function send(sender, text, action = '发送群消息') {
await chat(sender).getByRole('textbox', { name: '群消息' }).fill(text)
const response = sender.waitForResponse((item) => /\/groups\/[^/]+\/messages$/.test(item.url()) && item.request().method() === 'POST')
await chat(sender).getByRole('button', { name: action, exact: true }).click()
const sent = await response
assert.equal(sent.status(), 200, await sent.text())
const packet = sent.request().postDataJSON()
assert.deepEqual(Object.keys(packet).sort(), ['epoch', 'id', 'wire'])
const wire = Buffer.from(packet.wire, 'base64')
assert.equal(wire[3], 2)
assert.ok(!wire.includes(Buffer.from(text)))
return packet.epoch
}
async function sendFile(sender, name, mimeType, contents) {
const upload = sender.waitForResponse((item) => /\/groups\/[^/]+\/attachments\/[^/]+\?epoch=/.test(item.url()) && item.request().method() === 'POST')
const message = sender.waitForResponse((item) => /\/groups\/[^/]+\/messages$/.test(item.url()) && item.request().method() === 'POST')
await chat(sender).getByLabel('选择群附件').setInputFiles({ name, mimeType, buffer: contents })
await chat(sender).getByRole('button', { name: '发送群附件' }).click()
const uploaded = await upload
assert.equal(uploaded.status(), 204)
const sent = await message
assert.equal(sent.status(), 200, await sent.text())
const packet = sent.request().postDataJSON()
assert.match(new URL(uploaded.url()).pathname, new RegExp('/' + packet.attachmentId + '$'))
assert.ok(!Buffer.from(packet.wire, 'base64').includes(Buffer.from(name)))
}
async function sendVoice(sender) {
const response = sender.waitForResponse((item) => /\/groups\/[^/]+\/attachments\/[^/]+\?epoch=/.test(item.url()) &&
item.request().method() === 'POST' && item.status() === 204)
await chat(sender).getByRole('button', { name: '录制语音' }).click()
await chat(sender).getByText(/录音中 1 \/ 60 秒/).waitFor()
await chat(sender).getByRole('button', { name: '发送语音' }).click()
const path = new URL((await response).url()).pathname
return path
}
async function playVoice(page, sender, downloadPath) {
const message = chat(page).getByRole('listitem').filter({ hasText: sender }).filter({
has: page.getByRole('button', { name: '播放语音' }),
})
const download = page.waitForResponse((item) => item.url().endsWith(downloadPath) && item.request().method() === 'GET')
await message.getByRole('button', { name: '播放语音' }).click()
const response = await download
assert.equal(response.status(), 200)
const ciphertext = await response.body()
assert.ok(ciphertext.length > 16)
assert.notDeepEqual(ciphertext.subarray(0, 4), Buffer.from([0x1a, 0x45, 0xdf, 0xa3]))
const player = chat(page).getByRole('listitem').filter({ hasText: sender }).locator('audio[aria-label="语音消息"]')
await player.waitFor()
const src = await player.getAttribute('src')
await page.waitForFunction((url) => [...document.querySelectorAll('.group-chat audio')].some((item) =>
item.getAttribute('src') === url && item.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && item.currentTime > 0), src)
assert.match(src, /^blob:/)
await player.evaluate((element) => element.pause())
assert.equal(await player.evaluate((element) => element.paused), true)
}
test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员隔离', { timeout: 120_000 }, async () => {
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge', args: ['--use-fake-device-for-media-stream'] })
const profile = await mkdtemp(join(tmpdir(), 'xhchat-group-test-'))
let desktop
const pages = []
try {
const [owner, removed] = await Promise.all([browser.newPage(), browser.newPage()])
let ownerSocket
let holdConnection = false
await owner.routeWebSocket('**/api/v1/realtime', (route) => {
if (holdConnection) { void route.close({ code: 1012 }); return }
ownerSocket = route
route.connectToServer()
})
await owner.context().grantPermissions(['microphone'], { origin: base })
await Promise.all([owner.goto(base), removed.goto(base)])
desktop = await _electron.launch({
executablePath: electron,
args: [join(import.meta.dirname, '..', 'Desktop'), '--user-data-dir=' + profile, '--use-fake-device-for-media-stream'],
env: { ...process.env, XHCHAT_SERVER_URL: base },
})
const windows = await desktop.firstWindow()
pages.push(owner, windows, removed)
assert.equal(await windows.evaluate(async () => {
try { await window.xhchat.allowVoiceRecording(); return true } catch { return false }
}), false)
const names = pages.map(() => 'groupqa_' + id())
const password = randomBytes(24).toString('hex')
const [, , removedIdentity] = await Promise.all(pages.map((page, index) => register(page, names[index], password)))
await connect(owner, windows, names[0], names[1])
await connect(owner, removed, names[0], names[2])
await work(owner).getByRole('link', { name: '群组' }).click()
const group = '加密测试 ' + id()
await owner.getByLabel('群名称', { exact: true }).fill(group)
await owner.getByRole('button', { name: '创建群组' }).click()
await owner.getByRole('heading', { name: group }).waitFor()
await invite(owner, windows, names[1], group)
await invite(owner, removed, names[2], group)
const settings = (page, name) => page.getByRole('button', { name, exact: true })
await settings(removed, '群聊免打扰').click()
await removed.getByRole('button', { name: '群聊免打扰', pressed: true }).waitFor()
assert.equal(await settings(owner, '群聊免打扰').getAttribute('aria-pressed'), 'false')
await settings(owner, '置顶群聊').click()
await owner.getByRole('button', { name: '置顶群聊', pressed: true }).waitFor()
const ownerCompanion = await browser.newPage()
await ownerCompanion.goto(base)
await ownerCompanion.getByLabel('用户名').fill(names[0])
await ownerCompanion.getByLabel('密码', { exact: true }).fill(password)
await ownerCompanion.locator('button.primary').click()
await ownerCompanion.getByText('实时连接已建立').waitFor()
await work(ownerCompanion).getByRole('link', { name: '群组' }).click()
await ownerCompanion.getByRole('link', { name: new RegExp(group + '.*已置顶') }).click()
await settings(ownerCompanion, '群聊免打扰').click()
await owner.getByRole('button', { name: '群聊免打扰', pressed: true }).waitFor({ timeout: 4500 })
await settings(ownerCompanion, '群聊免打扰').click()
await owner.getByRole('button', { name: '群聊免打扰', pressed: false }).waitFor({ timeout: 4500 })
await ownerCompanion.close()
const codes = await Promise.all(pages.map(async (page) => {
await chat(page).getByRole('button', { name: '启用本机群聊' }).click()
const code = page.locator('.group-security-code')
await code.waitFor()
return code.textContent()
}))
assert.ok(codes.every((code) => /^[0-9a-f]{64}$/.test(code)))
assert.equal(await chat(owner).getByRole('button', { name: '建立群加密会话' }).isEnabled(), false)
await verify(owner, names[1], codes[1])
await verify(owner, names[2], codes[2])
await publish(owner, [owner])
await chat(windows).getByText('请先核验名单内每台设备的安全码').waitFor()
assert.equal(await chat(windows).getByRole('button', { name: '发送群消息' }).count(), 0)
await Promise.all([verify(windows, names[0], codes[0]), verify(removed, names[0], codes[0])])
await Promise.all([verify(windows, names[2], codes[2]), verify(removed, names[1], codes[1])])
await Promise.all(pages.map((page) => chat(page).getByText('群加密已建立', { exact: true }).waitFor()))
const first = 'Windows 群消息 ' + id()
await work(removed).getByRole('link', { name: '联系人' }).click()
holdConnection = true
await ownerSocket.close({ code: 1012 })
await owner.getByText('正在重连', { exact: true }).waitFor()
const epoch = await send(windows, first)
holdConnection = false
await owner.getByText('实时连接已建立', { exact: true }).waitFor()
await Promise.all([owner, windows].map((page) => chat(page).getByText(first, { exact: true }).waitFor({ timeout: 3500 })))
assert.equal(await removed.getByRole('link', { name: '有新的群消息' }).count(), 0)
await work(removed).getByRole('link', { name: '群组' }).click()
const unreadGroup = removed.getByRole('link', { name: new RegExp(group + '.*1 条未读') })
await unreadGroup.click()
await unreadGroup.waitFor()
await chat(removed).getByRole('button', { name: '启用本机群聊' }).click()
await chat(removed).getByText(first, { exact: true }).waitFor()
await unreadGroup.waitFor({ state: 'detached', timeout: 4500 })
assert.equal(await windows.getByRole('link', { name: new RegExp(group + '.*未读') }).count(), 0)
const announcement = '群公告 ' + id()
const ownerAnnouncement = chat(owner).getByRole('region', { name: '群公告' })
await ownerAnnouncement.getByRole('button', { name: '写群公告' }).click()
await ownerAnnouncement.getByLabel('公告内容').fill(announcement)
const announcementPost = owner.waitForRequest((request) => /\/groups\/[^/]+\/messages$/.test(request.url()) && request.method() === 'POST')
await ownerAnnouncement.getByRole('button', { name: '发布公告' }).click()
assert.ok(!Buffer.from((await announcementPost).postDataJSON().wire, 'base64').includes(Buffer.from(announcement)))
const windowsAnnouncement = chat(windows).getByRole('region', { name: '群公告' })
await windowsAnnouncement.getByText(announcement, { exact: true }).waitFor()
assert.equal(await windowsAnnouncement.getByRole('button').count(), 0)
await ownerAnnouncement.getByRole('button', { name: '编辑群公告' }).click()
await ownerAnnouncement.getByLabel('公告内容').clear()
await ownerAnnouncement.getByRole('button', { name: '清除公告' }).click()
await windowsAnnouncement.waitFor({ state: 'detached' })
const original = chat(owner).getByRole('listitem').filter({ hasText: first })
assert.equal(await original.getByRole('button', { name: '编辑', exact: true }).count(), 0)
assert.equal(await original.getByRole('button', { name: '撤回', exact: true }).count(), 0)
await original.getByRole('button', { name: '引用', exact: true }).click()
const reply = '加密引用回复 ' + id()
assert.equal(await send(owner, reply), epoch)
const receivedReply = chat(windows).getByRole('listitem').filter({ hasText: reply })
await receivedReply.locator('blockquote').getByText(first, { exact: true }).waitFor({ timeout: 3500 })
await settings(removed, '群聊免打扰').click()
await removed.getByRole('button', { name: '群聊免打扰', pressed: false }).waitFor()
await work(removed).getByRole('link', { name: '联系人' }).click()
const own = chat(windows).getByRole('listitem').filter({ has: windows.getByText(first, { exact: true }) }).first()
await own.getByRole('button', { name: '编辑', exact: true }).click()
const edited = '已修改群消息 ' + id()
assert.equal(await send(windows, edited, '保存编辑'), epoch)
const notice = removed.getByRole('link', { name: '有新的群消息' })
await notice.waitFor({ timeout: 4500 })
const incomingEdit = chat(owner).getByRole('listitem').filter({ has: owner.getByText(edited, { exact: true }) })
await incomingEdit.getByText('已编辑', { exact: true }).waitFor()
await notice.click()
await chat(removed).getByRole('button', { name: '启用本机群聊' }).click()
await chat(removed).getByText(edited, { exact: true }).waitFor()
const keyword = chat(owner).getByRole('searchbox', { name: '搜索本机群消息' })
const favorites = chat(owner).getByRole('checkbox', { name: '只看收藏' })
const searchedRequests = []
const trackSearch = (request) => searchedRequests.push({ url: request.url(), method: request.method() })
owner.on('request', trackSearch)
await keyword.fill(first.toUpperCase())
await chat(owner).getByRole('listitem').filter({ hasText: reply }).waitFor()
assert.equal(await incomingEdit.count(), 0)
await keyword.fill(edited)
await incomingEdit.getByRole('button', { name: '收藏', exact: true }).click()
await incomingEdit.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
await favorites.check()
assert.equal(await chat(owner).getByRole('listitem').count(), 1)
const unmatched = '没有匹配的验收关键词 ' + id()
await keyword.fill(unmatched)
await chat(owner).getByText('没有匹配的群消息。').waitFor()
owner.off('request', trackSearch)
assert.ok(searchedRequests.filter(({ url }) => url.includes('/groups/')).every(({ url, method }) =>
method === 'GET' && !/search|favorite/i.test(new URL(url).pathname) && !decodeURIComponent(url).includes(unmatched)))
await work(owner).getByRole('link', { name: '联系人' }).click()
await work(owner).getByRole('link', { name: '群组' }).click()
await owner.getByRole('link', { name: new RegExp(group) }).click()
await chat(owner).getByRole('button', { name: '启用本机群聊' }).click()
await favorites.check()
await incomingEdit.getByRole('button', { name: '取消收藏', exact: true }).click()
await chat(owner).getByText('没有匹配的群消息。').waitFor()
await favorites.uncheck()
assert.equal(await chat(windows).getByRole('listitem').filter({ hasText: edited })
.getByRole('button', { name: '取消收藏', exact: true }).count(), 0)
const temporary = '待撤回群消息 ' + id()
assert.equal(await send(windows, temporary), epoch)
const outgoing = chat(windows).getByRole('listitem').filter({ hasText: temporary })
await chat(owner).getByText(temporary, { exact: true }).waitFor()
const incoming = chat(owner).getByRole('listitem').filter({ hasText: temporary })
await incoming.getByRole('button', { name: '收藏', exact: true }).click()
await incoming.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
await outgoing.getByRole('button', { name: '撤回', exact: true }).click()
await chat(windows).getByRole('button', { name: '确认撤回' }).click()
for (const page of pages) {
await chat(page).getByText('消息已撤回', { exact: true }).waitFor()
assert.equal(await chat(page).getByText(temporary, { exact: true }).count(), 0)
}
await favorites.check()
await chat(owner).getByText('没有匹配的群消息。').waitFor()
await favorites.uncheck()
const contents = Buffer.from('Windows 群文件内容 ' + id() + '\n'.repeat(9000))
const filename = '群附件-' + id() + '.txt'
await sendFile(windows, filename, 'text/plain', contents)
await keyword.fill(filename.toUpperCase())
await chat(owner).getByRole('button', { name: '下载 ' + filename }).waitFor()
assert.equal(await chat(owner).getByRole('listitem').count(), 1)
await keyword.clear()
const attachmentRequests = []
const trackAttachment = (request) => { if (request.url().includes('/attachments/')) attachmentRequests.push(request.url()) }
owner.on('request', trackAttachment)
await historyView(owner, '群文件').click()
const fileShelf = chat(owner).getByRole('list', { name: '群文件' })
await keyword.fill(filename.toUpperCase())
const fileButton = fileShelf.getByRole('button', { name: '下载 ' + filename })
await fileButton.waitFor()
assert.deepEqual(attachmentRequests, [])
owner.off('request', trackAttachment)
const fileDownload = owner.waitForEvent('download')
const fileResponse = owner.waitForResponse((item) => item.url().includes('/attachments/') && item.request().method() === 'GET')
await fileButton.click()
const response = await fileResponse
assert.equal(response.status(), 200)
const ciphertext = await response.body()
assert.equal(ciphertext.length, contents.length + 16)
assert.ok(!ciphertext.includes(contents.subarray(0, 24)))
const downloaded = await fileDownload
assert.equal(downloaded.suggestedFilename(), filename)
assert.deepEqual(await readFile(await downloaded.path()), contents)
await owner.route(response.url(), async (route) => {
const tampered = Buffer.from(ciphertext)
tampered[0] ^= 1
await route.fulfill({ status: 200, contentType: 'application/octet-stream', body: tampered })
}, { times: 1 })
await fileButton.click()
await chat(owner).getByRole('alert').getByText('附件完整性校验失败').waitFor()
await keyword.clear()
await historyView(owner, '消息').click()
const photo = '群图片-' + id() + '.png'
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX2sAAAAASUVORK5CYII=', 'base64')
await sendFile(owner, photo, 'image/png', pixel)
await historyView(windows, '群图片').click()
const gallery = chat(windows).getByRole('list', { name: '群图片' })
assert.equal(await gallery.getByText(filename, { exact: false }).count(), 0)
await gallery.getByRole('button', { name: '预览 ' + photo }).click()
const image = chat(windows).getByRole('img', { name: photo })
await image.evaluate((element) => element.decode())
assert.equal(await image.evaluate((element) => element.naturalWidth), 1)
await historyView(windows, '群视频').click()
await image.waitFor({ state: 'detached' })
await chat(windows).getByText('没有匹配的群视频。', { exact: true }).waitFor()
await historyView(windows, '群图片').click()
await gallery.getByRole('button', { name: '预览 ' + photo }).waitFor()
const photoLine = chat(owner).getByRole('listitem').filter({ hasText: photo })
assert.equal(await photoLine.getByRole('button', { name: '编辑', exact: true }).count(), 0)
await photoLine.getByRole('button', { name: '撤回', exact: true }).click()
await chat(owner).getByRole('button', { name: '确认撤回' }).click()
await chat(windows).getByText('没有匹配的群图片。', { exact: true }).waitFor()
const clip = '群视频-' + id() + '.webm'
const videoBytes = await owner.evaluate(async () => {
const canvas = document.createElement('canvas')
canvas.width = 32
canvas.height = 24
const paint = canvas.getContext('2d')
const stream = canvas.captureStream(15)
const recorder = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=vp8' })
const recorded = new Promise((resolve, reject) => {
const chunks = []
recorder.ondataavailable = ({ data }) => chunks.push(data)
recorder.onstop = async () => resolve(Array.from(new Uint8Array(await new Blob(chunks).arrayBuffer())))
recorder.onerror = () => reject(new Error('无法生成验收视频'))
})
recorder.start()
for (const color of ['#108760', '#2052a4', '#f5a12f']) {
paint.fillStyle = color
paint.fillRect(0, 0, 32, 24)
await new Promise((resolve) => setTimeout(resolve, 150))
}
recorder.stop()
stream.getTracks().forEach((track) => track.stop())
return recorded
})
await sendFile(owner, clip, 'video/webm', Buffer.from(videoBytes))
await historyView(windows, '群视频').click()
const videos = chat(windows).getByRole('list', { name: '群视频' })
await videos.getByRole('button', { name: '预览 ' + clip }).click()
const player = videos.locator('video')
await player.evaluate((element) => element.play())
assert.equal(await player.evaluate((element) => element.videoWidth), 32)
assert.match(await player.getAttribute('src'), /^blob:/)
await historyView(windows, '消息').click()
await player.waitFor({ state: 'detached' })
const firstBatch = '批量一-' + id() + '.txt'
const secondBatch = '批量二-' + id() + '.txt'
const payload = (name) => ({ name, mimeType: 'text/plain', buffer: Buffer.from(name) })
const ownerDrop = chat(owner).getByRole('region', { name: '群附件发送区' })
await ownerDrop.locator('input:enabled').setInputFiles([payload(firstBatch), payload(secondBatch)])
const queue = ownerDrop.getByRole('list', { name: '待发附件' })
assert.equal(await queue.getByRole('listitem').count(), 2)
const uploadMatcher = (url) => url.pathname.includes('/groups/') && url.pathname.includes('/attachments/') && url.searchParams.has('epoch')
let uploadAttempts = 0
const interruptSecondUpload = async (route) => {
uploadAttempts++
if (uploadAttempts === 2) await route.fulfill({ status: 503, json: { error: { message: '测试上传暂不可用' } } })
else await route.continue()
}
await owner.route(uploadMatcher, interruptSecondUpload)
await ownerDrop.getByRole('button', { name: '发送群附件', exact: true }).click()
await chat(windows).getByRole('button', { name: '下载 ' + firstBatch, exact: true }).waitFor()
await chat(owner).getByRole('alert').getByText('测试上传暂不可用').waitFor()
assert.equal(await queue.getByRole('listitem').count(), 1)
assert.equal(await queue.getByText(secondBatch, { exact: true }).count(), 1)
await owner.unroute(uploadMatcher, interruptSecondUpload)
await ownerDrop.getByRole('button', { name: '发送群附件', exact: true }).click()
await chat(windows).getByRole('button', { name: '下载 ' + secondBatch, exact: true }).waitFor()
assert.equal(await chat(windows).getByRole('button', { name: '下载 ' + firstBatch, exact: true }).count(), 1)
await queue.waitFor({ state: 'detached' })
const dropped = '拖入附件-' + id() + '.txt'
const rejected = '移出附件-' + id() + '.txt'
const transfer = await windows.evaluateHandle((names) => {
const data = new DataTransfer()
for (const name of names) data.items.add(new File([name], name, { type: 'text/plain' }))
return data
}, [dropped, rejected])
const desktopDrop = chat(windows).getByRole('region', { name: '群附件发送区' })
await desktopDrop.dispatchEvent('dragover', { dataTransfer: transfer })
await desktopDrop.dispatchEvent('drop', { dataTransfer: transfer })
await transfer.dispose()
await desktopDrop.getByRole('button', { name: '移除 ' + rejected, exact: true }).click()
await desktopDrop.getByRole('button', { name: '发送群附件', exact: true }).click()
await chat(owner).getByRole('button', { name: '下载 ' + dropped, exact: true }).waitFor()
assert.equal(await chat(owner).getByRole('button', { name: '下载 ' + rejected, exact: true }).count(), 0)
const voiceUploads = []
windows.on('request', (request) => {
if (request.method() === 'POST' && request.url().includes('/attachments/')) voiceUploads.push(request.url())
})
await chat(windows).getByRole('button', { name: '录制语音' }).click()
await chat(windows).getByText(/录音中 1 \/ 60 秒/).waitFor()
await chat(windows).getByRole('button', { name: '取消录音' }).click()
const desktopVoice = await sendVoice(windows)
assert.equal(voiceUploads.length, 1)
await playVoice(owner, names[1], desktopVoice)
await playVoice(removed, names[1], desktopVoice)
const webVoice = await sendVoice(owner)
await playVoice(windows, names[0], webVoice)
await chat(windows).getByRole('button', { name: '录制语音' }).click()
await chat(windows).getByText(/录音中 1 \/ 60 秒/).waitFor()
const member = owner.getByRole('list', { name: '群成员' }).getByRole('listitem').filter({ hasText: names[2] })
await member.getByRole('button', { name: '移除成员' }).click()
await owner.getByRole('button', { name: '确认操作' }).click()
await removed.getByRole('heading', { name: group }).waitFor({ state: 'hidden', timeout: 4500 })
const fetchRemovedVoice = () => fetch(base + desktopVoice, { headers: { Authorization: 'Bearer ' + removedIdentity.token } })
assert.equal((await fetchRemovedVoice()).status, 404)
assert.equal((await fetch(base + '/api/v1/devices/' + removedIdentity.device.id, {
method: 'DELETE', headers: { Authorization: 'Bearer ' + removedIdentity.token },
})).status, 204)
assert.equal((await fetchRemovedVoice()).status, 401)
await chat(windows).getByText('等待群主建立群加密会话。').waitFor()
assert.equal(await chat(windows).getByRole('button', { name: '发送语音' }).count(), 0)
await publish(owner, [owner, windows])
assert.equal(voiceUploads.length, 1)
const second = '新世代 Web 群消息 ' + id()
assert.notEqual(await send(owner, second), epoch)
await chat(windows).getByText(second, { exact: true }).waitFor()
assert.equal(await removed.getByText(second, { exact: true }).count(), 0)
const history = chat(windows).getByRole('listitem').filter({ hasText: edited })
assert.equal(await history.count(), 1)
assert.equal(await history.getByRole('button', { name: '编辑', exact: true }).count(), 0)
await chat(windows).getByRole('searchbox', { name: '搜索本机群消息' }).fill(edited)
await history.getByRole('button', { name: '收藏', exact: true }).click()
await chat(windows).getByRole('checkbox', { name: '只看收藏' }).check()
await history.getByRole('button', { name: '取消收藏', exact: true }).waitFor()
assert.equal(await chat(windows).getByRole('listitem').count(), 1)
await chat(windows).getByRole('searchbox', { name: '搜索本机群消息' }).clear()
await chat(windows).getByRole('checkbox', { name: '只看收藏' }).uncheck()
const targetGroup = '转发目标 ' + id()
await owner.getByLabel('群名称', { exact: true }).fill(targetGroup)
await owner.getByRole('button', { name: '创建群组' }).click()
await owner.getByRole('heading', { name: targetGroup }).waitFor()
assert.match(await owner.getByRole('complementary', { name: '群组列表' }).getByRole('link').first().textContent(), /已置顶/)
await owner.getByText('群邀请链接和二维码', { exact: true }).click()
await owner.getByRole('button', { name: '生成邀请链接', exact: true }).click()
const qr = owner.getByRole('img', { name: '群邀请二维码' })
const inviteURL = await owner.getByLabel('邀请链接', { exact: true }).inputValue()
assert.match(inviteURL, /#\/groups\?invite=[A-Za-z0-9_-]{43}$/)
await owner.waitForFunction(() => {
const image = document.querySelector('canvas[aria-label="群邀请二维码"]')
return image?.getContext('2d').getImageData(0, 0, 1, 1).data[3] === 255
})
assert.ok(await qr.evaluate((canvas) => canvas.width > 150))
await windows.getByLabel('群邀请链接或邀请码').fill(inviteURL)
await windows.getByRole('button', { name: '领取群邀请' }).click()
await windows.getByRole('heading', { name: targetGroup }).waitFor()
await windows.getByRole('button', { name: '接受邀请' }).click()
await owner.getByRole('list', { name: '群成员' }).getByRole('listitem').getByText(names[1] + ' · 成员', { exact: true }).waitFor()
await owner.getByRole('button', { name: '重新生成邀请链接', exact: true }).click()
await owner.waitForFunction((old) => document.querySelector('.invite-output input')?.value !== old, inviteURL)
const newURL = await owner.getByLabel('邀请链接', { exact: true }).inputValue()
const invitePage = await browser.newPage()
await invitePage.goto(newURL)
await invitePage.getByRole('heading', { name: '登录 XHChat' }).waitFor()
assert.ok(!new URL(invitePage.url()).hash.includes('invite='))
await register(invitePage, 'inviteqa_' + id(), password)
await invitePage.getByRole('button', { name: '领取群邀请' }).click()
await invitePage.getByRole('heading', { name: targetGroup }).waitFor()
await invitePage.getByRole('button', { name: '拒绝邀请' }).click()
await invitePage.getByRole('heading', { name: targetGroup }).waitFor({ state: 'detached' })
await invitePage.close()
await windows.getByRole('link', { name: new RegExp(group) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
const forwardPanel = chat(windows).getByRole('form', { name: '转发群消息' })
const forwardFile = chat(windows).getByRole('listitem').filter({ hasText: filename }).getByRole('button', { name: '转发', exact: true })
await forwardFile.click()
await forwardPanel.getByLabel('转发给').selectOption({ label: targetGroup })
await forwardPanel.getByRole('button', { name: '确认转发' }).click()
await chat(windows).getByRole('alert').getByText('请先在目标群加入加密会话').waitFor()
await forwardPanel.getByRole('button', { name: '取消', exact: true }).click()
await windows.getByRole('link', { name: new RegExp(targetGroup) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
await chat(owner).getByRole('button', { name: '启用本机群聊' }).click()
await publish(owner, [owner, windows])
await windows.getByRole('link', { name: new RegExp(group) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
const forwarded = windows.waitForResponse((item) => /\/groups\/[^/]+\/attachments\/[^/]+\?epoch=/.test(item.url()) &&
item.request().method() === 'POST')
await forwardFile.click()
await forwardPanel.getByLabel('转发给').selectOption({ label: targetGroup })
await forwardPanel.getByRole('button', { name: '确认转发' }).click()
const newBlob = await forwarded
assert.equal(newBlob.status(), 204)
assert.notEqual(new URL(newBlob.url()).pathname.split('/').at(-1), new URL(response.url()).pathname.split('/').at(-1))
await chat(windows).getByText('已转发到群聊', { exact: true }).waitFor()
const newResponse = owner.waitForResponse((item) => item.url().endsWith(new URL(newBlob.url()).pathname) && item.request().method() === 'GET')
const newDownload = owner.waitForEvent('download')
await chat(owner).getByRole('button', { name: '下载 ' + filename }).click()
assert.notDeepEqual(await (await newResponse).body(), ciphertext)
assert.deepEqual(await readFile(await (await newDownload).path()), contents)
await chat(windows).getByRole('listitem').filter({ hasText: edited }).getByRole('button', { name: '转发', exact: true }).click()
await forwardPanel.getByLabel('转发给').selectOption({ label: names[0] })
await forwardPanel.getByLabel('目标设备').waitFor()
await forwardPanel.getByRole('button', { name: '确认转发' }).click()
await chat(windows).getByText('已提交转发', { exact: true }).waitFor()
await work(owner).getByRole('link', { name: '消息', exact: true }).click()
await owner.getByRole('link', { name: names[1] }).click()
await owner.getByRole('button', { name: '启用本机加密聊天' }).click()
await owner.getByText(edited, { exact: true }).waitFor()
await owner.getByRole('listitem').filter({ hasText: edited }).getByRole('button', { name: '转发', exact: true }).click()
const privateForward = owner.getByRole('form', { name: '转发私聊消息' })
await privateForward.getByLabel('转发给').selectOption({ label: targetGroup })
await privateForward.getByRole('button', { name: '确认转发' }).click()
await owner.getByText('已转发到群聊', { exact: true }).waitFor()
await windows.getByRole('link', { name: new RegExp(targetGroup) }).click()
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
await chat(windows).getByText(edited, { exact: true }).waitFor()
const pendingGroup = '待加密群 ' + id()
await windows.getByLabel('群名称', { exact: true }).fill(pendingGroup)
await windows.getByRole('button', { name: '创建群组' }).click()
await windows.getByRole('heading', { name: pendingGroup }).waitFor()
await work(windows).getByRole('link', { name: '消息', exact: true }).click()
await windows.getByRole('link', { name: names[0] }).click()
await windows.getByRole('button', { name: '启用本机加密聊天' }).click()
const privateFile = '私聊文件-' + id() + '.txt'
const originalUpload = windows.waitForResponse((item) => /\/api\/v1\/attachments\//.test(item.url()) && item.request().method() === 'POST')
const attachmentInput = windows.locator('input[type=file]:enabled')
const [originalFile] = await Promise.all([
originalUpload,
attachmentInput.setInputFiles({ name: privateFile, mimeType: 'text/plain', buffer: contents }),
])
assert.equal(originalFile.status(), 204)
const originalBytes = originalFile.request().postDataBuffer()
assert.ok(originalBytes && originalBytes.length === contents.length + 16)
await windows.getByRole('listitem').filter({ hasText: privateFile }).getByRole('button', { name: '转发', exact: true }).click()
const desktopForward = windows.getByRole('form', { name: '转发私聊消息' })
const writes = []
const recordWrite = (req) => { if (req.method() === 'POST' && req.url().includes('/groups/')) writes.push(req.url()) }
windows.on('request', recordWrite)
await desktopForward.getByLabel('转发给').selectOption({ label: pendingGroup })
await desktopForward.getByRole('button', { name: '确认转发' }).click()
await windows.getByRole('alert').getByText('请先在目标群加入加密会话').waitFor()
windows.off('request', recordWrite)
assert.deepEqual(writes, [])
await desktopForward.getByLabel('转发给').selectOption({ label: targetGroup })
const groupUpload = windows.waitForResponse((item) => item.url().includes('/groups/') && item.url().includes('/attachments/') && item.request().method() === 'POST')
await desktopForward.getByRole('button', { name: '确认转发' }).click()
const targetFile = await groupUpload
assert.equal(targetFile.status(), 204)
assert.notEqual(new URL(targetFile.url()).pathname.split('/').at(-1), new URL(originalFile.url()).pathname.split('/').at(-1))
await windows.getByText('已转发到群聊', { exact: true }).waitFor()
await work(owner).getByRole('link', { name: '群组' }).click()
await owner.getByRole('link', { name: new RegExp(targetGroup) }).click()
await chat(owner).getByRole('button', { name: '启用本机群聊' }).click()
const groupDownload = owner.waitForEvent('download')
const groupFileResponse = owner.waitForResponse((item) => item.url().endsWith(new URL(targetFile.url()).pathname) && item.request().method() === 'GET')
await chat(owner).getByRole('button', { name: '下载 ' + privateFile, exact: true }).click()
assert.notDeepEqual(await (await groupFileResponse).body(), originalBytes)
assert.deepEqual(await readFile(await (await groupDownload).path()), contents)
await work(windows).getByRole('link', { name: '群组' }).click()
await windows.getByRole('link', { name: new RegExp(targetGroup) }).click()
const successor = owner.getByRole('list', { name: '群成员' }).getByRole('listitem').filter({ hasText: names[1] })
await successor.getByRole('button', { name: '转让群主', exact: true }).click()
await owner.getByText(new RegExp('确认将群主转让给 ' + names[1])).waitFor()
const transferred = owner.waitForResponse((response) => response.request().method() === 'POST' &&
/\/groups\/[^/]+$/.test(response.url()) && response.request().postDataJSON().action === 'transfer')
await owner.getByRole('button', { name: '确认操作', exact: true }).click()
assert.equal((await transferred).status(), 204)
await windows.getByRole('list', { name: '群成员' }).getByText(names[1] + ' · 群主', { exact: true }).waitFor()
await owner.getByRole('button', { name: '退出群组', exact: true }).waitFor()
await owner.getByRole('button', { name: '退出群组', exact: true }).click()
await owner.getByRole('button', { name: '确认操作', exact: true }).click()
await owner.getByRole('heading', { name: targetGroup }).waitFor({ state: 'detached' })
await windows.getByRole('list', { name: '群成员' }).getByText(names[0] + ' · 成员', { exact: true }).waitFor({ state: 'detached' })
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
await publish(windows, [windows])
const successorAnnouncement = chat(windows).getByRole('region', { name: '群公告' })
await successorAnnouncement.getByRole('button', { name: '写群公告' }).click()
await successorAnnouncement.getByLabel('公告内容').fill('新群主公告')
await successorAnnouncement.getByRole('button', { name: '发布公告' }).click()
await successorAnnouncement.getByText('新群主公告', { exact: true }).waitFor()
} catch (error) {
const status = await Promise.all(pages.map((page) => page.locator('[role=alert], .group-chat [role=status]').allTextContents()))
throw new Error(JSON.stringify(status), { cause: error })
} finally {
await desktop?.close()
await browser.close()
await rm(profile, { recursive: true, force: true })
}
})