Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed #68: 新版本添加同传名单失败。 #72

Merged
merged 2 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ npm-debug.log*
out/
build/
dist/
*.local.yml

# plasmo - https://www.plasmo.com
.plasmo
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"package": "plasmo package",
"clean": "run-script-os",
"clean:nix": "rm -rf build && rm -rf .plasmo",
"clean:windows": "rmdir /s /q build && rmdir /s /q .plasmo",
"clean:windows": "if exist build rmdir /s /q build && if exist .plasmo rmdir /s /q .plasmo",
"test": "playwright test",
"test:prepare": "run-script-os",
"test:prepare:nix": "mv build/chrome-mv3-prod build/extension",
Expand Down Expand Up @@ -66,6 +66,7 @@
"manifest": {
"host_permissions": [
"*://api.vtbs.moe/*",
"*://api.bilibili.com/*",
"*://api.live.bilibili.com/*",
"*://live.bilibili.com/*",
"*://*.bilivideo.com/*",
Expand Down
1 change: 1 addition & 0 deletions src/api/bilibili.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ export async function requestUserInfo(mid: string): Promise<WbiAccInfoResponse>
}
})

if (res.code === -404) return undefined
if (res.code !== 0) throw new Error(`B站API请求错误: ${res.message}`)
return res.data
}
Expand Down
14 changes: 12 additions & 2 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@

function ciOnly(func: any) {
return function (...data: any[]) {
if (process.env.CI || process.env.NODE_ENV === 'development') {
func(...data)
}
}
}


console.info = console.info.bind(console, '[bilibili-vup-stream-enhancer]')
console.warn = console.warn.bind(console, '[bilibili-vup-stream-enhancer]')
console.error = console.error.bind(console, '[bilibili-vup-stream-enhancer]')
console.log = console.log.bind(console, '[bilibili-vup-stream-enhancer]')
console.debug = process.env.NODE_ENV === 'production' ? () => {} : console.debug.bind(console, '[bilibili-vup-stream-enhancer]')
console.trace = process.env.NODE_ENV === 'production' ? () => {} : console.trace.bind(console, '[bilibili-vup-stream-enhancer]')
console.debug = ciOnly(console.debug.bind(console, '[bilibili-vup-stream-enhancer]'))
console.trace = ciOnly(console.trace.bind(console, '[bilibili-vup-stream-enhancer]'))
4 changes: 2 additions & 2 deletions src/settings/components/DataTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export type DataTableProps<T extends object> = {
headers: TableHeader<T>[]
values: T[]
actions: TableAction<T>[]
onAdd?: (value: string) => void
onAdd?: (value: string, e: KeyboardEvent) => void
headerSlot?: React.ReactNode
}

Expand All @@ -45,7 +45,7 @@ function DataTable<T extends object>(props: DataTableProps<T>): JSX.Element {
const onAdd = (e: Event | any) => {
e?.preventDefault()
if (!input) return
props.onAdd?.(input)
props.onAdd?.(input, e)
setInput('')
}

Expand Down
38 changes: 33 additions & 5 deletions src/settings/features/jimaku/components/ListingFragment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { ExposeHandler, StateProxy } from "~hooks/binding"
import type { TableHeader } from "~settings/components/DataTable"
import DataTable from "~settings/components/DataTable"
import DeleteIcon from "~settings/components/DeleteIcon"
import type { WbiAccInfoResponse } from "~types/bilibili"
import type { ArrElement, PickKeys } from "~types/common"
import { catcher } from "~utils/fetch"
import { removeArr } from "~utils/misc"
Expand Down Expand Up @@ -45,21 +46,48 @@ const user_headers: TableHeader<UserRecord>[] = [

function ListingFragment({ state, useHandler }: StateProxy<ListingSchema>): JSX.Element {

const addUserRecord = <K extends PickKeys<ListingSchema, UserRecord[]>>(key: K) => async (value: string) => {
const addUserRecord = <K extends PickKeys<ListingSchema, UserRecord[]>>(key: K) => async (value: string, e: KeyboardEvent) => {

const handler = (state as ExposeHandler<ListingSchema>)

if (state[key].some(e => e.id === value)) {
toast.error(`用户 ${value} 已经在列表中`)
return
}
const user = await catcher(requestUserInfo(value))
if (!user) {
toast.error(`用户 ${value} 不存在`)
return

let user: Partial<WbiAccInfoResponse> = undefined

if (!e.shiftKey) {
try {
user = await requestUserInfo(value)
if (!user) {
toast.error(`用户 ${value} 不存在`)
return
}
} catch (err) {
console.error(err)
toast.error(
<div className="flex flex-col space-y-0 m-0 p-0">
<div className="text-[15px]">
添加用户 {value} 失败: {err?.message ?? String(err)}
</div>
<small>(使用 Shift Enter 可略过用户验证)</small>
</div>
)
}
} else {
const mid = parseInt(value)
if (isNaN(mid)) {
toast.error(`添加用户 ${value} 失败: 不是有效的数字`)
return
}
user = { mid, name: '用戶' + value }
}


state[key].push({ id: user.mid.toString(), name: user.name, addedDate: new Date().toLocaleDateString() })
handler.set(key, state[key] as any)
toast.success(`添加用户 ${value} 成功`)
}


Expand Down
73 changes: 73 additions & 0 deletions tests/features/jimaku.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,79 @@ test('測試房間名單列表(黑名單/白名單)', async ({ room, content, co

})

test('测试添加同传用户名单/黑名单', async ({ content, context, tabUrl, room }) => {

const subtitleList = content.locator('#subtitle-list')
await expect(subtitleList).toBeVisible()

const user1 = 1
const user2 = 2

const txt = '由 playwright 工具發送'
const subtitles = content.locator('#subtitle-list > p').filter({ hasText: txt })

const withBracket = `【${txt}】`

logger.info('正在測試同傳字幕正則覆蓋....')

await room.sendDanmaku(withBracket, user1)
await room.sendDanmaku(withBracket, user1)
await room.sendDanmaku(txt, user1) // this should not be covered

await expect(subtitles).toHaveCount(2)

logger.info('正在測試添加同傳用戶名單...')

const settingsPage = await context.newPage()
await settingsPage.goto(tabUrl('settings.html'), { waitUntil: 'domcontentloaded' })

await settingsPage.getByText('功能设定').click()
await settingsPage.getByText('同传名单设定').click()

await settingsPage.getByTestId('tongchuan-mans-input').fill(user1.toString())
await settingsPage.getByTestId('tongchuan-mans-input').press('Shift+Enter')
await settingsPage.getByText(`添加用户 ${user1} 成功`).waitFor({ state: 'visible' })

await settingsPage.getByText('保存设定').click()

await room.page.bringToFront()
await subtitleList.waitFor({ state: 'visible' })
await room.sendDanmaku(withBracket, user1)
await room.sendDanmaku(withBracket, user1)
await room.sendDanmaku(txt, user1) // this should be covered

await expect(subtitles).toHaveCount(3)

logger.info('正在測試添加同傳用戶黑名單...')

await settingsPage.bringToFront()
await settingsPage.getByTestId('tongchuan-blacklist-input').fill(user2.toString())
await settingsPage.getByTestId('tongchuan-blacklist-input').press('Shift+Enter')
await settingsPage.getByText(`添加用户 ${user2} 成功`).waitFor({ state: 'visible' })

await settingsPage.getByText('保存设定').click()

await room.page.bringToFront()
await subtitleList.waitFor({ state: 'visible' })
await room.sendDanmaku(withBracket, user2) // should be blacklisted
await room.sendDanmaku(withBracket, user2) // should be blacklisted

await expect(subtitles).toHaveCount(0)

// github host runner does not have access to bilibili user api
if (!process.env.CI) {

logger.info('正在嘗試添加不存在用戶...')

await settingsPage.bringToFront()
await settingsPage.getByTestId('tongchuan-mans-input').fill('1234569')
await settingsPage.getByTestId('tongchuan-mans-input').press('Enter')

await expect(settingsPage.getByText('用户 1234569 不存在')).toBeVisible()

}
})

test('測試全屏時字幕區塊是否存在 + 顯示切換', async ({ content: p, room }) => {

test.skip(await room.isThemePage(), '此測試不適用於大海報房間')
Expand Down
12 changes: 7 additions & 5 deletions tests/helpers/bilibili-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,10 @@ export class BilibiliPage implements AsyncDisposable {

/**
* 模拟发送弹幕。
* @param danmaku 弹幕内容。
* @param danmaku 弹幕内容
* @param uid 弹幕发送者用户ID。
*/
async sendDanmaku(danmaku: string): Promise<void> {
async sendDanmaku(danmaku: string, uid: number = randomNumber()): Promise<void> {
const f = await this.getContentLocator()
await sendFakeBLiveMessage(f, 'DANMU_MSG', {
cmd: 'DANMU_MSG',
Expand All @@ -118,7 +119,7 @@ export class BilibiliPage implements AsyncDisposable {
],
danmaku,
[
randomNumber(),
uid,
"username",
undefined,
undefined,
Expand Down Expand Up @@ -154,8 +155,9 @@ export class BilibiliPage implements AsyncDisposable {
* @param user 用户名。
* @param price 价格。
* @param message 消息内容。
* @param uid 用户ID。
*/
async sendSuperChat(user: string, price: number, message: string): Promise<void> {
async sendSuperChat(user: string, price: number, message: string, uid: number = randomNumber()): Promise<void> {
const f = await this.getContentLocator()
await sendFakeBLiveMessage(f, 'SUPER_CHAT_MESSAGE', {
cmd: 'SUPER_CHAT_MESSAGE',
Expand All @@ -169,7 +171,7 @@ export class BilibiliPage implements AsyncDisposable {
name_color: '#444444',
uname: user
},
uid: randomNumber(),
uid: uid,
price: price,
message: message,
start_time: Date.now()
Expand Down
Loading