24 Commits

Author SHA1 Message Date
IndieKKY
194df8525c chore: release 1.12.1 2025-03-06 18:57:13 +08:00
IndieKKY
28bb3dbb96 优化字体大小 2025-03-06 18:56:55 +08:00
IndieKKY
640f6d89fd fix serverUrl bug 2025-03-06 18:56:47 +08:00
IndieKKY
338e3145f2 update package version 2025-02-24 15:06:50 +08:00
IndieKKY
e2121e83bd chore: release 1.12.0 2025-02-24 09:20:31 +08:00
IndieKKY
7583b05289 fix消息通信 2025-02-24 09:19:40 +08:00
IndieKKY
ae60303a15 fix消息通信 2025-02-24 09:13:25 +08:00
IndieKKY
5bcedf0c9d fix消息通信 2025-02-23 20:19:41 +08:00
IndieKKY
d4e5e407a4 优化 2025-02-13 15:09:18 +08:00
IndieKKY
ce2a2da6f5 update readme 2024-11-09 20:47:10 +08:00
IndieKKY
368f5d721c readme 2024-11-09 19:52:17 +08:00
IndieKKY
21e2ca958c readme 2024-11-09 19:52:00 +08:00
IndieKKY
149653ffac chore: release 1.11.13 2024-11-01 13:41:46 +08:00
IndieKKY
f977b5e238 fix字幕解析bug 2024-11-01 13:41:29 +08:00
IndieKKY
c13ef4597b chore: release 1.11.12 2024-11-01 09:22:13 +08:00
IndieKKY
65026f62af 优化显示 2024-11-01 09:20:53 +08:00
IndieKKY
bcff8b4f90 fix 字幕不显示的bug 2024-11-01 09:12:03 +08:00
IndieKKY
ee1eaf9e08 chore: release 1.11.11 2024-10-19 15:21:47 +08:00
IndieKKY
cc732de8e6 fix csp 2024-10-19 15:21:24 +08:00
IndieKKY
cccf7e6149 chore: release 1.11.10 2024-10-16 09:08:09 +08:00
IndieKKY
30dc724ebb 断开连接提示 2024-10-16 09:07:49 +08:00
IndieKKY
51a7e998b9 chore: release 1.11.9 2024-10-13 21:14:44 +08:00
IndieKKY
556ccef4b2 代理推荐 2024-10-13 21:12:10 +08:00
IndieKKY
42b719fb98 语言文件 2024-10-13 21:12:04 +08:00
42 changed files with 361 additions and 820 deletions

View File

@@ -4,3 +4,4 @@ node_modules/
postcss.config.cjs
vite.config.ts
vite-env.d.ts
manifest.config.ts

View File

@@ -25,9 +25,12 @@ module.exports = {
"@typescript-eslint/no-empty-interface": "warn",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/strict-boolean-expressions": "warn",
"@typescript-eslint/prefer-nullish-coalescing": "off",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/object-curly-spacing": "off",
"@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/space-infix-ops": "off",
"@typescript-eslint/no-floating-promises": "off",
"operator-linebreak": "off",
"@typescript-eslint/space-before-function-paren": "off",
"@typescript-eslint/comma-dangle": "off"

View File

@@ -21,7 +21,6 @@
- [chrome商店](https://chrome.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp)
- [edge商店](https://microsoftedge.microsoft.com/addons/detail/lignnlhlpiefmcjkdkmfjdckhlaiajan)
- [firefox商店](https://addons.mozilla.org/zh-CN/firefox/addon/bilibili-subtitle)
## 使用说明
@@ -46,11 +45,15 @@ github: [IndieKKY](https://github.com/IndieKKY)
node版本18.15.0
包管理器pnpm
- 本地调试:`pnpm run dev`,然后加载`dist`目录。
- 打生产包:`pnpm run build`,然后加载`dist`目录。
- 本地调试:`pnpm run dev`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
- 打生产包:`pnpm run build`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
注:`./push.sh`是作者自用脚本,可以忽略。
提示最新版浏览器安全方面有更新开发调试可能有问题会报csp错误
暂时的解决办法是`pnpm run dev`运行起来后,手动将`dist/manifest.json`文件里的web_accessible_resources里的use_dynamic_url都修改为false然后浏览器扩展管理页面点击重载一下就能正常@crxjs/vite-plugin依赖的问题这个依赖很长时间没更新了这个bug也没修复暂时没发现更好的解决办法
构建后正常关键是fix.cjs里将use_dynamic_url设置为false的这个操作。
## 贡献指南
欢迎贡献代码或提出改进建议!如果您希望为该项目做出贡献,请遵循以下步骤:

View File

@@ -5,4 +5,11 @@ const fs = require('fs')
//copy index.html to sidepanel.html
fs.copyFileSync('./dist/index.html', './dist/sidepanel.html')
//set all use_dynamic_url to false
const manifest = require('./dist/manifest.json')
manifest.web_accessible_resources.forEach(resource => {
resource.use_dynamic_url = false
})
fs.writeFileSync('./dist/manifest.json', JSON.stringify(manifest, null, 2))
console.log('fix.js done');

View File

@@ -12,9 +12,10 @@ const [major, minor, patch, label = '0'] = version
.split(/[.-]/)
export default defineManifest(async (env) => ({
"name": "哔哔君 - bilibili哔哩哔哩字幕列表",
"description": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!",
"name": '__MSG_appName__',
"description": '__MSG_appDescription__',
"version": `${major}.${minor}.${patch}`,
"default_locale": "zh_CN",
"manifest_version": 3,
"permissions": [
"sidePanel",
@@ -56,7 +57,7 @@ export default defineManifest(async (env) => ({
"resources": [
"index.html",
],
"use_dynamic_url": true
"use_dynamic_url": false
}
]
}))

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "bilibili-subtitle",
"version": "1.11.8",
"version": "1.12.1",
"type": "module",
"description": "哔哩哔哩字幕列表",
"main": "index.js",
@@ -15,6 +15,7 @@
"dependencies": {
"@crxjs/vite-plugin": "^1.0.14",
"@kky002/kky-hooks": "^1.2.1",
"@kky002/kky-message": "^0.2.1",
"@kky002/kky-ui": "^1.0.9",
"@kky002/kky-util": "^1.13.13",
"@logto/react": "1.0.0-beta.13",

57
pnpm-lock.yaml generated
View File

@@ -14,6 +14,9 @@ importers:
'@kky002/kky-hooks':
specifier: ^1.2.1
version: 1.2.1
'@kky002/kky-message':
specifier: ^0.2.1
version: 0.2.1
'@kky002/kky-ui':
specifier: ^1.0.9
version: 1.0.9
@@ -310,6 +313,10 @@ packages:
resolution: {integrity: sha512-eR8Lo9hnDS7tqkO7NsV+mKvCmv5boaXFSZ70DnfhcgiEne8hv9oCEd36Klw74EtizEqLsy4YnW8UWwpBVolHZA==}
engines: {node: '>=6.9.0'}
'@babel/runtime@7.26.9':
resolution: {integrity: sha512-aA63XwOkcl4xxQa3HjPMqOP6LiK0ZDv3mUPYEFXkpHbaFjtGggE1A61FjFzJnB+p7/oy2gA8E+rcBNl/zC1tMg==}
engines: {node: '>=6.9.0'}
'@babel/template@7.25.7':
resolution: {integrity: sha512-wRwtAgI3bAS+JGU2upWNL9lSlDcRCqD05BZ1n3X2ONLH1WilFP6O1otQjeMK/1g0pvYcXC7b/qVUB1keofjtZA==}
engines: {node: '>=6.9.0'}
@@ -390,6 +397,9 @@ packages:
'@kky002/kky-hooks@1.2.1':
resolution: {integrity: sha512-AJM2gm75TtkZqOPd/WX0+4h/dfjSb8HlDQLwAJsYIHRNw8MQUKu32Ih6OxhKL2l9pdPsuj+S9/lBc4Cwu4tP+Q==}
'@kky002/kky-message@0.2.1':
resolution: {integrity: sha512-LIg4T89t3TmjflepZeOPH/OMN3xxwLE0AxnfDycTlCpjHAiuvm/Aj3IIHLfzqbz5azRaGNu2ZcUsrUdb2jAtiQ==}
'@kky002/kky-ui@1.0.9':
resolution: {integrity: sha512-pepfRcLfC1eIQ1lsSJLWNr4PgdLqFLuvQMlitJy7W668yZ7qu8yAHSjg8A20R7HB4mFkJ+B96WETalOar1e/kA==}
@@ -654,6 +664,12 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0
ahooks@3.8.4:
resolution: {integrity: sha512-39wDEw2ZHvypaT14EpMMk4AzosHWt0z9bulY0BeDsvc9PqJEV+Kjh/4TZfftSsotBMq52iYIOFPd3PR56e0ZJg==}
engines: {node: '>=8.0.0'}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0
ajv@6.12.6:
resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==}
@@ -1560,6 +1576,10 @@ packages:
js-cookie@2.2.1:
resolution: {integrity: sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ==}
js-cookie@3.0.5:
resolution: {integrity: sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==}
engines: {node: '>=14'}
js-search@2.0.0:
resolution: {integrity: sha512-lJ8KzjlwcelIWuAdKyzsXv45W6OIwRpayzc7XmU8mzgWadg5UVOKVmnq/tXudddEB9Ceic3tVaGu6QOK/eebhg==}
@@ -2048,6 +2068,9 @@ packages:
react-fast-compare@3.2.0:
resolution: {integrity: sha512-rtGImPZ0YyLrscKI9xTpV8psd6I8VAtjKCzQDlzyDvqJA8XOW78TXYQwNRNd8g8JZnDu8q9Fu/1v4HPAVwVdHA==}
react-fast-compare@3.2.2:
resolution: {integrity: sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==}
react-hot-toast@2.4.0:
resolution: {integrity: sha512-qnnVbXropKuwUpriVVosgo8QrB+IaPJCpL8oBI6Ov84uvHZ5QQcTp2qg6ku2wNfgJl6rlQXJIQU5q+5lmPOutA==}
engines: {node: '>=10'}
@@ -2135,6 +2158,9 @@ packages:
regenerator-runtime@0.13.9:
resolution: {integrity: sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==}
regenerator-runtime@0.14.1:
resolution: {integrity: sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==}
regexp.prototype.flags@1.4.3:
resolution: {integrity: sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==}
engines: {node: '>= 0.4'}
@@ -2696,6 +2722,10 @@ snapshots:
dependencies:
regenerator-runtime: 0.13.9
'@babel/runtime@7.26.9':
dependencies:
regenerator-runtime: 0.14.1
'@babel/template@7.25.7':
dependencies:
'@babel/code-frame': 7.25.7
@@ -2816,6 +2846,14 @@ snapshots:
lodash-es: 4.17.21
react: 18.2.0
'@kky002/kky-message@0.2.1':
dependencies:
'@kky002/kky-util': 1.13.13
ahooks: 3.8.4(react@18.2.0)
lodash-es: 4.17.21
qs: 6.11.0
react: 18.2.0
'@kky002/kky-ui@1.0.9':
dependencies:
react: 18.2.0
@@ -3138,6 +3176,19 @@ snapshots:
screenfull: 5.2.0
tslib: 2.5.0
ahooks@3.8.4(react@18.2.0):
dependencies:
'@babel/runtime': 7.26.9
dayjs: 1.11.13
intersection-observer: 0.12.2
js-cookie: 3.0.5
lodash: 4.17.21
react: 18.2.0
react-fast-compare: 3.2.2
resize-observer-polyfill: 1.5.1
screenfull: 5.2.0
tslib: 2.5.0
ajv@6.12.6:
dependencies:
fast-deep-equal: 3.1.3
@@ -4076,6 +4127,8 @@ snapshots:
js-cookie@2.2.1: {}
js-cookie@3.0.5: {}
js-search@2.0.0: {}
js-tokens@4.0.0: {}
@@ -4698,6 +4751,8 @@ snapshots:
react-fast-compare@3.2.0: {}
react-fast-compare@3.2.2: {}
react-hot-toast@2.4.0(csstype@3.1.2)(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
dependencies:
goober: 2.1.12(csstype@3.1.2)
@@ -4790,6 +4845,8 @@ snapshots:
regenerator-runtime@0.13.9: {}
regenerator-runtime@0.14.1: {}
regexp.prototype.flags@1.4.3:
dependencies:
call-bind: 1.0.2

View File

@@ -0,0 +1,8 @@
{
"appName": {
"message": "哔哔君 - bilibili哔哩哔哩字幕列表"
},
"appDescription": {
"message": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!"
}
}

View File

@@ -8,7 +8,7 @@ import OptionsPage from './pages/OptionsPage'
import {handleJson} from '@kky002/kky-util'
import {useLocalStorage} from '@kky002/kky-hooks'
import {Toaster} from 'react-hot-toast'
import useMessagingService from './hooks/useMessageService'
import useMessageService from './hooks/useMessageService'
import MainPage from './pages/MainPage'
function App() {
@@ -44,7 +44,7 @@ function App() {
useLocalStorage<TempData>('chrome_client', STORAGE_TEMP, savedTempData, onLoadTemp)
// services
useMessagingService()
useMessageService()
return <div>
<Toaster position={path === 'app'?'bottom-center':'top-center'}/>

View File

@@ -1,8 +1,8 @@
import {v4} from 'uuid'
import {handleTask, initTaskService, tasksMap} from './taskService'
import { STORAGE_ENV} from '@/consts/const'
import ExtensionMessaging from '@/messaging/layer2/ExtensionMessaging'
import { TAG_TARGET_INJECT } from '@/messaging/const'
import { DEFAULT_USE_PORT, STORAGE_ENV} from '@/consts/const'
import { AllExtensionMessages } from '@/message-typings'
import { ExtensionMessaging, TAG_TARGET_INJECT } from '@kky002/kky-message'
const setBadgeOk = async (tabId: number, ok: boolean) => {
await chrome.action.setBadgeText({
@@ -34,6 +34,9 @@ const methods: {
CLOSE_SIDE_PANEL: async (params, context) => {
closeSidePanel()
},
GET_TAB_ID: async (params, context) => {
return context.tabId
},
ADD_TASK: async (params, context) => {
// 新建任务
const task: Task = {
@@ -75,7 +78,7 @@ const methods: {
},
}
// 初始化backgroundMessage
const extensionMessaging = new ExtensionMessaging()
const extensionMessaging = new ExtensionMessaging(DEFAULT_USE_PORT)
extensionMessaging.init(methods)
chrome.runtime.onMessage.addListener((event: any, sender: chrome.runtime.MessageSender, sendResponse: (result: any) => void) => {
@@ -89,14 +92,12 @@ chrome.runtime.onMessage.addListener((event: any, sender: chrome.runtime.Message
return true
} else if (event.type === 'syncSet') { // sync.set
chrome.storage.sync.set(event.items).catch(console.error)
return
} else if (event.type === 'syncRemove') { // sync.remove
chrome.storage.sync.remove(event.keys).catch(console.error)
return
}
})
//点击扩展图标
// 点击扩展图标
chrome.action.onClicked.addListener(async (tab) => {
chrome.storage.sync.get(STORAGE_ENV, (envDatas) => {
const envDataStr = envDatas[STORAGE_ENV]
@@ -115,7 +116,7 @@ chrome.action.onClicked.addListener(async (tab) => {
})
} else {
closeSidePanel()
extensionMessaging.broadcastMessageExact([tab.id!], [TAG_TARGET_INJECT], 'TOGGLE_DISPLAY').catch(console.error)
extensionMessaging.sendMessage(false, tab.id!, TAG_TARGET_INJECT, 'TOGGLE_DISPLAY').catch(console.error)
}
})
})

View File

@@ -7,13 +7,17 @@ const getServerUrl = (serverUrl?: string) => {
if (serverUrl.endsWith('/')) {
serverUrl = serverUrl.slice(0, -1)
}
//如果serverUrl不以/vxxx结尾则添加/v1
if (!/\/v\d+$/.test(serverUrl.toLowerCase())) {
serverUrl += '/v1'
}
return serverUrl
}
export const handleChatCompleteTask = async (task: Task) => {
const data = task.def.data
const serverUrl = getServerUrl(task.def.serverUrl)
const resp = await fetch(`${serverUrl}/v1/chat/completions`, {
const resp = await fetch(`${serverUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View File

@@ -1,14 +1,14 @@
import React from 'react';
import { useAppSelector } from '../hooks/redux';
import { openOptionsPage } from '../utils/chromeUtils';
import React from 'react'
import { useAppSelector } from '../hooks/redux'
import { openOptionsPage } from '../utils/chromeUtils'
const ApiKeyReminder: React.FC = () => {
const apiKey = useAppSelector(state => state.env.envData.apiKey);
const geminiApiKey = useAppSelector(state => state.env.envData.geminiApiKey);
const aiType = useAppSelector(state => state.env.envData.aiType);
const apiKey = useAppSelector(state => state.env.envData.apiKey)
const geminiApiKey = useAppSelector(state => state.env.envData.geminiApiKey)
const aiType = useAppSelector(state => state.env.envData.aiType)
if ((aiType === 'gemini' && geminiApiKey) || (aiType !== 'gemini' && apiKey)) {
return null;
return null
}
return (
@@ -21,7 +21,7 @@ const ApiKeyReminder: React.FC = () => {
</button>
</div>
);
};
)
}
export default ApiKeyReminder;
export default ApiKeyReminder

View File

@@ -25,6 +25,7 @@ import toast from 'react-hot-toast'
import SegmentCard from './SegmentCard'
import {
ASK_ENABLED_DEFAULT,
DEFAULT_USE_PORT,
HEADER_HEIGHT,
PAGE_SETTINGS,
SEARCH_BAR_HEIGHT,
@@ -39,6 +40,7 @@ import Ask from './Ask'
import { v4 } from 'uuid'
import RateExtension from '../components/RateExtension'
import ApiKeyReminder from './ApiKeyReminder'
import { useMessaging } from '@kky002/kky-message'
const Body = () => {
const dispatch = useAppDispatch()
@@ -65,6 +67,7 @@ const Body = () => {
// const fontSize = useAppSelector(state => state.env.envData.fontSize)
const searchText = useAppSelector(state => state.env.searchText)
const asks = useAppSelector(state => state.env.asks)
const {disconnected} = useMessaging(DEFAULT_USE_PORT)
// const recommendIdx = useMemo(() => random(0, 3), [])
const showSearchInput = useMemo(() => {
return (segments != null && segments.length > 0) && (envData.searchEnabled ? envData.searchEnabled : (envData.askEnabled ?? ASK_ENABLED_DEFAULT))
@@ -124,7 +127,7 @@ const Body = () => {
}
toast.success(`已添加${segments_.length}个总结任务!`)
}
}, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
}, [addSummarizeTask, curSummaryType, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
const onFoldAll = useCallback(() => {
dispatch(setFoldAll(!foldAll))
@@ -262,6 +265,10 @@ const Body = () => {
{searchText && <button className='absolute top-1 right-2 btn btn-ghost btn-xs btn-circle text-base-content/75' onClick={onClearSearchText}><AiOutlineCloseCircle /></button>}
</div>}
{disconnected && <div className='flex flex-col justify-center items-center gap-2 text-sm bg-red-400 rounded mx-2'>
<span className='flex items-center gap-1 text-white'><AiOutlineCloseCircle className='text-white' /></span>
</div>}
{/* auto scroll btn */}
{!autoScroll && <div
className='absolute z-[999] top-[96px] right-6 tooltip tooltip-left cursor-pointer rounded-full bg-primary/25 hover:bg-primary/75 text-primary-content p-1.5 text-xl'

View File

@@ -1,8 +1,8 @@
import { useAppSelector } from '@/hooks/redux';
import React from 'react';
import { useAppSelector } from '@/hooks/redux'
import React from 'react'
const DebateChat: React.FC<DebateProps> = ({ messages }) => {
const fontSize = useAppSelector(state => state.env.envData.fontSize)
const fontSize = useAppSelector(state => state.env.envData.fontSize)
return (
<div className="flex flex-col h-full">
@@ -37,7 +37,7 @@ const DebateChat: React.FC<DebateProps> = ({ messages }) => {
))}
</div>
</div>
);
};
)
}
export default DebateChat;
export default DebateChat

View File

@@ -83,8 +83,8 @@ const Header = (props: {
}
}}>
<div className='shrink-0 flex items-center'>
<img src="bibijun.png" alt="Logo" className="w-auto h-6 ml-2 mr-1" />
{/* <span className='shrink-0 text-[15px] font-medium pl-1 pr-[14px]'>字幕列表</span> */}
{/* <img src="bibijun.png" alt="Logo" className="w-auto h-6 ml-2 mr-1" /> */}
<span className='shrink-0 text-[15px] font-medium pl-[16px] pr-[14px]'></span>
<MoreBtn placement={'right-start'}/>
</div>
<div className='flex gap-0.5 items-center mr-[16px]'>

View File

@@ -1,8 +1,6 @@
import React, {MouseEvent, useCallback, useContext, useRef, useState} from 'react'
import {MouseEvent, useCallback, useContext, useRef, useState} from 'react'
import {useClickAway} from 'ahooks'
import {
AiFillWechat,
BsFillChatDotsFill,
FiMoreVertical,
ImDownload3,
IoMdSettings,
@@ -18,8 +16,8 @@ import {formatSrtTime, formatTime, formatVttTime} from '../utils/util'
import {downloadText, openUrl} from '@kky002/kky-util'
import toast from 'react-hot-toast'
import {getSummarize} from '../utils/bizUtil'
import { useMessage } from '@/hooks/message'
import dayjs from 'dayjs';
import dayjs from 'dayjs'
import { useMessage } from '@/hooks/useMessageService'
interface Props {
placement: Placement
@@ -70,11 +68,11 @@ const MoreBtn = (props: Props) => {
const segments = useAppSelector(state => state.env.segments)
const url = useAppSelector(state => state.env.url)
const title = useAppSelector(state => state.env.title)
const ctime = useAppSelector(state => state.env.ctime) //时间戳单位s
const ctime = useAppSelector(state => state.env.ctime) // 时间戳单位s
const author = useAppSelector(state => state.env.author)
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
const {sendInject} = useMessage()
const {sendInject} = useMessage(!!envData.sidePanel)
const downloadCallback = useCallback((download: boolean) => {
if (data == null) {
@@ -83,7 +81,7 @@ const MoreBtn = (props: Props) => {
let fileName = title
let s, suffix
let time = ctime ? dayjs(ctime * 1000).format('YYYY-MM-DD HH:mm:ss') : '' // 2024-05-01 12:00:00
const time = ctime ? dayjs(ctime * 1000).format('YYYY-MM-DD HH:mm:ss') : '' // 2024-05-01 12:00:00
if (!downloadType || downloadType === 'text') {
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
for (const item of data.body) {
@@ -164,11 +162,11 @@ const MoreBtn = (props: Props) => {
}).catch(console.error)
}
setMoreVisible(false)
}, [curSummaryType, data, downloadType, segments, title, url])
}, [author, ctime, curSummaryType, data, downloadType, segments, title, url])
const downloadAudioCallback = useCallback(() => {
sendInject('DOWNLOAD_AUDIO', {})
}, [])
sendInject(null, 'DOWNLOAD_AUDIO', {})
}, [sendInject])
const selectCallback = useCallback((e: any) => {
dispatch(setTempData({

View File

@@ -1,14 +1,14 @@
import React, { useState } from 'react';
import { FaStar } from 'react-icons/fa';
import { IoMdClose } from 'react-icons/io';
import { setTempData } from '../redux/envReducer';
import { useAppDispatch, useAppSelector } from '../hooks/redux';
import { openUrl } from '@kky002/kky-util';
import { isEdgeBrowser } from '../utils/util';
import React, { useState } from 'react'
import { FaStar } from 'react-icons/fa'
import { IoMdClose } from 'react-icons/io'
import { setTempData } from '../redux/envReducer'
import { useAppDispatch, useAppSelector } from '../hooks/redux'
import { openUrl } from '@kky002/kky-util'
import { isEdgeBrowser } from '../utils/util'
const RateExtension: React.FC = () => {
const dispatch = useAppDispatch()
const [isHovered, setIsHovered] = useState(false);
const [isHovered, setIsHovered] = useState(false)
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
const handleRateClick = () => {
@@ -21,9 +21,9 @@ const RateExtension: React.FC = () => {
} else {
openUrl('https://chromewebstore.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp/reviews')
}
};
}
if (reviewed === true || reviewed === undefined) return null;
if (reviewed === true || reviewed === undefined) return null
return (
<div className="relative bg-gradient-to-r from-primary to-secondary text-primary-content p-4 rounded-lg shadow-lg text-sm transition-all duration-300 ease-in-out hover:shadow-xl">
@@ -52,7 +52,7 @@ const RateExtension: React.FC = () => {
</span>
</button>
</div>
);
};
)
}
export default RateExtension;
export default RateExtension

View File

@@ -1,9 +1,9 @@
import React, {MutableRefObject, useCallback, useEffect, useMemo, useRef} from 'react'
import {MutableRefObject, useCallback, useEffect, useMemo, useRef} from 'react'
import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {setFloatKeyPointsSegIdx, setSegmentFold, setTempData} from '../redux/envReducer'
import classNames from 'classnames'
import {FaClipboardList, FaComments} from 'react-icons/fa'
import {PAGE_MAIN, PAGE_SETTINGS, SUMMARIZE_THRESHOLD, SUMMARIZE_TYPES} from '../consts/const'
import {SUMMARIZE_THRESHOLD, SUMMARIZE_TYPES} from '../consts/const'
import useTranslate from '../hooks/useTranslate'
import {BsDashSquare, BsPlusSquare, CgFileDocument, FaQuestion, GrOverview, RiFileCopy2Line} from 'react-icons/all'
import toast from 'react-hot-toast'
@@ -210,7 +210,7 @@ const SegmentCard = (props: {
}, [dispatch])
return <div
className={classNames('border border-base-300 bg-base-200/25 rounded flex flex-col m-1.5 p-1.5 gap-1 shadow', showCurrent && 'shadow-primary')}>
className={classNames('border border-base-300 bg-base-200/25 rounded flex flex-col m-1.5 p-1.5 gap-1', showCurrent && 'shadow shadow-md')}>
<div className='relative flex justify-center min-h-[20px]'>
{segments != null && segments.length > 0 &&
<div className='absolute left-0 top-0 bottom-0 text-xs select-none flex-center desc'>

View File

@@ -1,3 +1,5 @@
export const DEFAULT_USE_PORT = false
export const EVENT_EXPAND = 'expand'
export const APP_DOM_ID = 'bilibili-subtitle'
@@ -186,7 +188,7 @@ Provide an example to illustrate the expected output:
]
\`\`\`
`,
[PROMPT_TYPE_SUMMARIZE_DEBATE]: `You are a helpful assistant skilled at generating debates based on video subtitles.
[PROMPT_TYPE_SUMMARIZE_DEBATE]: `You are a helpful assistant skilled at generating debates based on video subtitles.
## Context

View File

@@ -1,3 +0,0 @@
import useMessaging from "@/messaging/layer2/useMessaging";
export const useMessage = useMessaging<AllExtensionMessages, AllInjectMessages>

View File

@@ -1,15 +1,17 @@
import { setAuthor, setCtime, setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
import { useMemo } from 'react'
import { useAppDispatch } from './redux'
import useMessagingService from '@/messaging/layer2/useMessagingService'
import { useAppDispatch, useAppSelector } from './redux'
import { AllAPPMessages, AllExtensionMessages, AllInjectMessages } from '@/message-typings'
import { useMessaging, useMessagingService } from '@kky002/kky-message'
import { useMemoizedFn } from 'ahooks'
const useMessageService = () => {
const dispatch = useAppDispatch()
//methods
const methods: {
const envData = useAppSelector((state) => state.env.envData)
// methods
const methodsFunc: () => {
[K in AllAPPMessages['method']]: (params: Extract<AllAPPMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
} = useMemo(() => ({
} = useMemoizedFn(() => ({
SET_INFOS: async (params, context: MethodContext) => {
dispatch(setInfos(params.infos))
dispatch(setCurInfo(undefined))
@@ -24,9 +26,10 @@ const useMessageService = () => {
dispatch(setAuthor(params.author))
console.debug('video title: ', params.title)
},
}), [dispatch])
}))
useMessagingService(methods)
useMessagingService(!!envData.sidePanel, methodsFunc)
}
export default useMessageService
export default useMessageService
export const useMessage = useMessaging<AllExtensionMessages, AllInjectMessages>

View File

@@ -1,25 +1,26 @@
import {useAppDispatch, useAppSelector} from './redux'
import React, {useCallback} from 'react'
import {setNeedScroll, setReviewAction, setTempData} from '../redux/envReducer'
import { useMessage } from './message'
import { useMessage } from './useMessageService'
const useSubtitle = () => {
const dispatch = useAppDispatch()
const envData = useAppSelector(state => state.env.envData)
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
const reviewAction = useAppSelector(state => state.env.reviewAction)
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
const {sendInject} = useMessage()
const move = useCallback((time: number, togglePause: boolean) => {
sendInject('MOVE', {time, togglePause})
const {sendInject} = useMessage(!!envData.sidePanel)
//review action
const move = useCallback((time: number, togglePause: boolean) => {
sendInject(null, 'MOVE', {time, togglePause})
// review action
if (reviewed === undefined && !reviewAction) {
dispatch(setReviewAction(true))
dispatch(setTempData({
reviewActions: (reviewActions ?? 0) + 1
}))
}
}, [dispatch, reviewAction, reviewActions, reviewed])
}, [dispatch, reviewAction, reviewActions, reviewed, sendInject])
const scrollIntoView = useCallback((ref: React.RefObject<HTMLDivElement>) => {
ref.current?.scrollIntoView({behavior: 'smooth', block: 'center'})

View File

@@ -19,7 +19,7 @@ import {EventBusContext} from '../Router'
import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../consts/const'
import {useAsyncEffect, useInterval} from 'ahooks'
import {getModelMaxTokens, getWholeText} from '../utils/bizUtil'
import { useMessage } from './message'
import { useMessage } from './useMessageService'
/**
* Service是单例类似后端的服务概念
@@ -43,9 +43,9 @@ const useSubtitleService = () => {
const autoTranslate = useAppSelector(state => state.env.autoTranslate)
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
const {sendInject} = useMessage()
const {sendInject} = useMessage(!!envData.sidePanel)
//如果reviewActions达到15次则设置reviewed为false
// 如果reviewActions达到15次则设置reviewed为false
useEffect(() => {
if (reviewed === undefined && reviewActions && reviewActions >= 15) {
dispatch(setTempData({
@@ -74,11 +74,11 @@ const useSubtitleService = () => {
dispatch(setCurInfo(infos[0]))
dispatch(setCurFetched(false))
}
}, [curInfo, dispatch, envData.autoExpand, envReady, fold, infos])
}, [curInfo, dispatch, envData.autoExpand, envReady, fold, infos, envData.sidePanel])
// 获取
useEffect(() => {
if (curInfo && !curFetched) {
sendInject('GET_SUBTITLE', {info: curInfo}).then(data => {
sendInject(null, 'GET_SUBTITLE', {info: curInfo}).then(data => {
data?.body?.forEach((item: TranscriptItem, idx: number) => {
item.idx = idx
})
@@ -86,28 +86,30 @@ const useSubtitleService = () => {
dispatch(setCurFetched(true))
dispatch(setData(data))
console.log('subtitle', data)
console.debug('subtitle', data)
})
}
}, [curFetched, curInfo])
}, [curFetched, curInfo, dispatch, sendInject])
useAsyncEffect(async () => {
// 初始获取列表
sendInject('REFRESH_VIDEO_INFO', {force: true})
}, [])
if (envReady) {
sendInject(null, 'REFRESH_VIDEO_INFO', {force: true})
}
}, [envReady, sendInject])
useAsyncEffect(async () => {
// 更新设置信息
sendInject('GET_VIDEO_ELEMENT_INFO', {}).then(info => {
sendInject(null, 'GET_VIDEO_ELEMENT_INFO', {}).then(info => {
dispatch(setNoVideo(info.noVideo))
if (envData.sidePanel) {
// get screen height
dispatch(setTotalHeight(window.innerHeight))
}else {
} else {
dispatch(setTotalHeight(Math.min(Math.max(info.totalHeight, TOTAL_HEIGHT_MIN), TOTAL_HEIGHT_MAX)))
}
})
}, [envData.sidePanel, infos])
}, [envData.sidePanel, infos, sendInject])
// 更新当前位置
useEffect(() => {
@@ -194,7 +196,7 @@ const useSubtitleService = () => {
// 每0.5秒更新当前视频时间
useInterval(() => {
sendInject('GET_VIDEO_STATUS', {}).then(status => {
sendInject(null, 'GET_VIDEO_STATUS', {}).then(status => {
dispatch(setCurrentTime(status.currentTime))
})
}, 500)
@@ -202,17 +204,17 @@ const useSubtitleService = () => {
// show translated text in the video
useEffect(() => {
if (hideOnDisableAutoTranslate && !autoTranslate) {
sendInject('HIDE_TRANS', {})
sendInject(null, 'HIDE_TRANS', {})
return
}
const transResult = curIdx?transResults[curIdx]:undefined
if (transResult?.code === '200' && transResult.data) {
sendInject('UPDATE_TRANS_RESULT', {result: transResult.data})
sendInject(null, 'UPDATE_TRANS_RESULT', {result: transResult.data})
} else {
sendInject('HIDE_TRANS', {})
sendInject(null, 'HIDE_TRANS', {})
}
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, transResults])
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, sendInject, transResults])
}
export default useSubtitleService

View File

@@ -29,7 +29,7 @@ import toast from 'react-hot-toast'
import {useMemoizedFn} from 'ahooks/es'
import {extractJsonArray, extractJsonObject, getModel} from '../utils/bizUtil'
import {formatTime} from '../utils/util'
import { useMessage } from './message'
import { useMessage } from './useMessageService'
const useTranslate = () => {
const dispatch = useAppDispatch()
const data = useAppSelector(state => state.env.data)
@@ -43,7 +43,7 @@ const useTranslate = () => {
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
const reviewAction = useAppSelector(state => state.env.reviewAction)
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
const {sendExtension} = useMessage()
const {sendExtension} = useMessage(!!envData.sidePanel)
/**
* 获取下一个需要翻译的行
* 会检测冷却
@@ -135,14 +135,14 @@ const useTranslate = () => {
}
})
dispatch(addTransResults(result))
const task = await sendExtension('ADD_TASK', {taskDef})
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
dispatch(addTaskId(task.id))
}
}
}, [data?.body, envData, language.name, title, dispatch])
}, [data?.body, envData, language.name, title, dispatch, sendExtension])
const addSummarizeTask = useCallback(async (type: SummaryType, segment: Segment) => {
//review action
// review action
if (reviewed === undefined && !reviewAction) {
dispatch(setReviewAction(true))
dispatch(setTempData({
@@ -205,10 +205,10 @@ const useTranslate = () => {
console.debug('addSummarizeTask', taskDef)
dispatch(setSummaryStatus({segmentStartIdx: segment.startIdx, type, status: 'pending'}))
dispatch(setLastSummarizeTime(Date.now()))
const task = await sendExtension('ADD_TASK', {taskDef})
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
dispatch(addTaskId(task.id))
}
}, [dispatch, envData, summarizeLanguage.name, title])
}, [dispatch, envData, reviewAction, reviewActions, reviewed, sendExtension, summarizeLanguage.name, title])
const addAskTask = useCallback(async (id: string, segment: Segment, question: string) => {
if (segment.text.length >= SUMMARIZE_THRESHOLD) {
@@ -262,10 +262,10 @@ const useTranslate = () => {
id,
status: 'pending'
}))
const task = await sendExtension('ADD_TASK', {taskDef})
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
dispatch(addTaskId(task.id))
}
}, [dispatch, envData, summarizeLanguage.name, title])
}, [dispatch, envData, sendExtension, summarizeLanguage.name, title])
const handleTranslate = useMemoizedFn((task: Task, content: string) => {
let map: {[key: string]: string} = {}
@@ -330,7 +330,7 @@ const useTranslate = () => {
})
const getTask = useCallback(async (taskId: string) => {
const taskResp = await sendExtension('GET_TASK', {taskId})
const taskResp = await sendExtension(null, 'GET_TASK', {taskId})
if (taskResp.code === 'ok') {
console.debug('getTask', taskResp.task)
const task: Task = taskResp.task
@@ -355,7 +355,7 @@ const useTranslate = () => {
} else {
dispatch(delTaskId(taskId))
}
}, [dispatch, envData.aiType, handleAsk, handleSummarize, handleTranslate])
}, [dispatch, envData.aiType, handleAsk, handleSummarize, handleTranslate, sendExtension])
return {getFetch, getTask, addTask, addSummarizeTask, addAskTask}
}

View File

@@ -1,5 +1,6 @@
import { TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID, STORAGE_ENV } from '@/consts/const'
import InjectMessaging from '@/messaging/layer2/InjectMessaging'
import { TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID, STORAGE_ENV, DEFAULT_USE_PORT } from '@/consts/const'
import { AllExtensionMessages, AllInjectMessages, AllAPPMessages } from '@/message-typings'
import { InjectMessaging } from '@kky002/kky-message'
const debug = (...args: any[]) => {
console.debug('[Inject]', ...args)
@@ -12,7 +13,7 @@ const debug = (...args: any[]) => {
return
}
//读取envData
// 读取envData
const envDataStr = (await chrome.storage.sync.get(STORAGE_ENV))[STORAGE_ENV]
let sidePanel: boolean | null = null
let manualInsert: boolean | null = null
@@ -41,7 +42,7 @@ const debug = (...args: any[]) => {
showTrans: boolean
curTrans?: string
} = {
injectMessaging: new InjectMessaging(),
injectMessaging: new InjectMessaging(DEFAULT_USE_PORT),
fold: true,
videoElementHeight: TOTAL_HEIGHT_DEF,
showTrans: false,
@@ -93,7 +94,7 @@ const debug = (...args: any[]) => {
iframe.dataset[vKey] = danmukuBox?.dataset[vKey]
}
//insert before first child
// insert before first child
danmukuBox?.insertBefore(iframe, danmukuBox?.firstChild)
// show badge
@@ -113,7 +114,7 @@ const debug = (...args: any[]) => {
if (danmukuBox) {
clearInterval(timerIframe)
//延迟插入iframe插入太快网络较差时容易出现b站网页刷新原因暂时未知可能b站的某种机制
// 延迟插入iframe插入太快网络较差时容易出现b站网页刷新原因暂时未知可能b站的某种机制
setTimeout(createIframe, 1500)
}
}, 1000)
@@ -139,6 +140,7 @@ const debug = (...args: any[]) => {
// fix: https://github.com/IndieKKY/bilibili-subtitle/issues/5
// 处理稍后再看的url( https://www.bilibili.com/list/watchlater?bvid=xxx&oid=xxx )
const pathSearchs: Record<string, string> = {}
// eslint-disable-next-line no-return-assign
location.search.slice(1).replace(/([^=&]*)=([^=&]*)/g, (matchs, a, b, c) => pathSearchs[a] = b)
// bvid
@@ -157,21 +159,21 @@ const debug = (...args: any[]) => {
lastAidOrBvid = aidOrBvid
if (aidOrBvid) {
//aid,pages
let cid
// aid,pages
let cid: string | undefined
let subtitles
if (aidOrBvid.toLowerCase().startsWith('av')) {//avxxx
if (aidOrBvid.toLowerCase().startsWith('av')) { // avxxx
aid = parseInt(aidOrBvid.slice(2))
pages = await fetch(`https://api.bilibili.com/x/player/pagelist?aid=${aid}`, { credentials: 'include' }).then(res => res.json()).then(res => res.data)
pages = await fetch(`https://api.bilibili.com/x/player/pagelist?aid=${aid}`, { credentials: 'include' }).then(async res => await res.json()).then(res => res.data)
cid = pages[0].cid
ctime = pages[0].ctime
author = pages[0].owner?.name
title = pages[0].part
await fetch(`https://api.bilibili.com/x/player/v2?aid=${aid}&cid=${cid}`, { credentials: 'include' }).then(res => res.json()).then(res => {
await fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid}&cid=${cid!}`, { credentials: 'include' }).then(async res => await res.json()).then(res => {
subtitles = res.data.subtitle.subtitles
})
} else {//bvxxx
await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${aidOrBvid}`, { credentials: 'include' }).then(res => res.json()).then(async res => {
} else { // bvxxx
await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${aidOrBvid}`, { credentials: 'include' }).then(async res => await res.json()).then(async res => {
title = res.data.title
aid = res.data.aid
cid = res.data.cid
@@ -179,12 +181,12 @@ const debug = (...args: any[]) => {
author = res.data.owner?.name
pages = res.data.pages
})
await fetch(`https://api.bilibili.com/x/player/v2?aid=${aid}&cid=${cid}`, { credentials: 'include' }).then(res => res.json()).then(res => {
await fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid!}&cid=${cid!}`, { credentials: 'include' }).then(async res => await res.json()).then(res => {
subtitles = res.data.subtitle.subtitles
})
}
//pagesMap
// pagesMap
pagesMap = {}
pages.forEach(page => {
pagesMap[page.page + ''] = page
@@ -192,8 +194,8 @@ const debug = (...args: any[]) => {
debug('refreshVideoInfo: ', aid, cid, pages, subtitles)
//send setVideoInfo
runtime.injectMessaging.sendApp('SET_VIDEO_INFO', {
// send setVideoInfo
runtime.injectMessaging.sendApp(!!sidePanel, 'SET_VIDEO_INFO', {
url: location.origin + location.pathname,
title,
aid,
@@ -218,7 +220,7 @@ const debug = (...args: any[]) => {
const p = urlSearchParams.get('p') || 1
const page = pagesMap[p]
if (!page) return
const cid = page.cid
const cid: number | null = page.cid
if (aid !== lastAid || cid !== lastCid) {
debug('refreshSubtitles', aid, cid)
@@ -226,15 +228,18 @@ const debug = (...args: any[]) => {
lastAid = aid
lastCid = cid
if (aid && cid) {
fetch(`https://api.bilibili.com/x/player/v2?aid=${aid}&cid=${cid}`, {
fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid}&cid=${cid}`, {
credentials: 'include',
})
.then(res => res.json())
.then(async res => await res.json())
.then(res => {
// console.log('refreshSubtitles: ', aid, cid, res)
runtime.injectMessaging.sendApp('SET_INFOS', {
infos: res.data.subtitle.subtitles
})
// remove elements with empty subtitle_url
res.data.subtitle.subtitles = res.data.subtitle.subtitles.filter((item: any) => item.subtitle_url)
if (res.data.subtitle.subtitles.length > 0) {
runtime.injectMessaging.sendApp(!!sidePanel, 'SET_INFOS', {
infos: res.data.subtitle.subtitles
})
}
})
}
}
@@ -279,7 +284,7 @@ const debug = (...args: any[]) => {
if (url.startsWith('http://')) {
url = url.replace('http://', 'https://')
}
return await fetch(url).then(res => res.json())
return await fetch(url).then(async res => await res.json())
},
GET_VIDEO_STATUS: async (params) => {
const video = getVideoElement()
@@ -332,7 +337,7 @@ const debug = (...args: any[]) => {
runtime.showTrans = false
runtime.curTrans = undefined
let text = document.getElementById('trans-result-text')
const text = document.getElementById('trans-result-text')
if (text) {
text.style.display = 'none'
}
@@ -353,7 +358,7 @@ const debug = (...args: any[]) => {
const playInfo = JSON.parse(html.match(/window.__playinfo__=(.+?)<\/script/)?.[1] ?? '{}')
const audioUrl = playInfo.data.dash.audio[0].baseUrl
fetch(audioUrl).then(res => res.blob()).then(blob => {
fetch(audioUrl).then(async res => await res.blob()).then(blob => {
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = `${title}.m4s`

View File

@@ -1,89 +1,87 @@
//extension
import {ExtensionMessage, InjectMessage, AppMessage} from '@kky002/kky-message'
// extension
interface ExtensionCloseSidePanelMessage extends ExtensionMessage {
method: 'CLOSE_SIDE_PANEL';
}
interface ExtensionAddTaskMessage extends ExtensionMessage<{ taskDef: TaskDef }, Task> {
method: 'ADD_TASK';
}
interface ExtensionGetTaskMessage extends ExtensionMessage<{ taskId: string }, {
code: 'ok'
task: Task
} | {
code: 'not_found'
}> {
method: 'GET_TASK';
}
interface ExtensionShowFlagMessage extends ExtensionMessage<{ show: boolean }> {
method: 'SHOW_FLAG';
}
type AllExtensionMessages = ExtensionCloseSidePanelMessage | ExtensionAddTaskMessage | ExtensionGetTaskMessage | ExtensionShowFlagMessage
method: 'CLOSE_SIDE_PANEL'
}
interface ExtensionAddTaskMessage extends ExtensionMessage<{ taskDef: TaskDef }, Task> {
method: 'ADD_TASK'
}
interface ExtensionGetTaskMessage extends ExtensionMessage<{ taskId: string }, {
code: 'ok'
task: Task
} | {
code: 'not_found'
}> {
method: 'GET_TASK'
}
//inject
interface InjectToggleDisplayMessage extends InjectMessage<{}> {
method: 'TOGGLE_DISPLAY';
}
interface InjectFoldMessage extends InjectMessage<{ fold: boolean }> {
method: 'FOLD';
}
interface InjectMoveMessage extends InjectMessage<{ time: number, togglePause: boolean }> {
method: 'MOVE';
}
interface InjectGetSubtitleMessage extends InjectMessage<{ info: any }> {
method: 'GET_SUBTITLE';
}
interface InjectGetVideoStatusMessage extends InjectMessage<{}> {
method: 'GET_VIDEO_STATUS';
}
interface InjectGetVideoElementInfoMessage extends InjectMessage<{}> {
method: 'GET_VIDEO_ELEMENT_INFO';
}
interface InjectRefreshVideoInfoMessage extends InjectMessage<{ force: boolean }> {
method: 'REFRESH_VIDEO_INFO';
}
interface InjectUpdateTransResultMessage extends InjectMessage<{ result: string }> {
method: 'UPDATE_TRANS_RESULT';
}
interface InjectHideTransMessage extends InjectMessage<{}> {
method: 'HIDE_TRANS';
}
interface InjectPlayMessage extends InjectMessage<{ play: boolean }> {
method: 'PLAY';
}
interface InjectDownloadAudioMessage extends InjectMessage<{}> {
method: 'DOWNLOAD_AUDIO';
}
type AllInjectMessages = InjectToggleDisplayMessage | InjectFoldMessage | InjectMoveMessage | InjectGetSubtitleMessage | InjectGetVideoStatusMessage | InjectGetVideoElementInfoMessage | InjectRefreshVideoInfoMessage | InjectUpdateTransResultMessage | InjectHideTransMessage | InjectPlayMessage | InjectDownloadAudioMessage
interface ExtensionShowFlagMessage extends ExtensionMessage<{ show: boolean }> {
method: 'SHOW_FLAG'
}
interface ExtensionGetTabIdMessage extends ExtensionMessage<{ show: boolean }> {
method: 'GET_TAB_ID'
}
//app
interface AppSetInfosMessage extends AppMessage<{ infos: any }> {
method: 'SET_INFOS';
}
interface AppSetVideoInfoMessage extends AppMessage<{ url: string, title: string, aid: number | null, ctime: number | null, author?: string, pages: any, infos: any }> {
method: 'SET_VIDEO_INFO';
}
type AllAPPMessages = AppSetInfosMessage | AppSetVideoInfoMessage
export type AllExtensionMessages = ExtensionGetTabIdMessage | ExtensionCloseSidePanelMessage | ExtensionAddTaskMessage | ExtensionGetTaskMessage | ExtensionShowFlagMessage
// inject
interface InjectToggleDisplayMessage extends InjectMessage<{}> {
method: 'TOGGLE_DISPLAY'
}
interface InjectFoldMessage extends InjectMessage<{ fold: boolean }> {
method: 'FOLD'
}
interface InjectMoveMessage extends InjectMessage<{ time: number, togglePause: boolean }> {
method: 'MOVE'
}
interface InjectGetSubtitleMessage extends InjectMessage<{ info: any }> {
method: 'GET_SUBTITLE'
}
interface InjectGetVideoStatusMessage extends InjectMessage<{}> {
method: 'GET_VIDEO_STATUS'
}
interface InjectGetVideoElementInfoMessage extends InjectMessage<{}> {
method: 'GET_VIDEO_ELEMENT_INFO'
}
interface InjectRefreshVideoInfoMessage extends InjectMessage<{ force: boolean }> {
method: 'REFRESH_VIDEO_INFO'
}
interface InjectUpdateTransResultMessage extends InjectMessage<{ result: string }> {
method: 'UPDATE_TRANS_RESULT'
}
interface InjectHideTransMessage extends InjectMessage<{}> {
method: 'HIDE_TRANS'
}
interface InjectPlayMessage extends InjectMessage<{ play: boolean }> {
method: 'PLAY'
}
interface InjectDownloadAudioMessage extends InjectMessage<{}> {
method: 'DOWNLOAD_AUDIO'
}
export type AllInjectMessages = InjectToggleDisplayMessage | InjectFoldMessage | InjectMoveMessage | InjectGetSubtitleMessage | InjectGetVideoStatusMessage | InjectGetVideoElementInfoMessage | InjectRefreshVideoInfoMessage | InjectUpdateTransResultMessage | InjectHideTransMessage | InjectPlayMessage | InjectDownloadAudioMessage
// app
interface AppSetInfosMessage extends AppMessage<{ infos: any }> {
method: 'SET_INFOS'
}
interface AppSetVideoInfoMessage extends AppMessage<{ url: string, title: string, aid: number | null, ctime: number | null, author?: string, pages: any, infos: any }> {
method: 'SET_VIDEO_INFO'
}
export type AllAPPMessages = AppSetInfosMessage | AppSetVideoInfoMessage

View File

@@ -1,38 +0,0 @@
## 消息通信库封装
此消息通信库设计为通用的,后面可能会提取到单独的项目中。
### 消息端
一共分3个端
1. 扩展端(`background.ts`):扩展后台服务,整个浏览器最多一个实例。
2. 注入端(`inject.ts`会注入到网页中运行可以访问网页元素每个网页可能n个实例看注入的次数但多个实例一般是不必要的所以尽量控制在一个实例。
3. 应用端(`App.tsx`会放入iframe中然后iframe元素添加到网页上每个iframe一个实例或者options.html选项页面也是应用实例或者sidepanel.html页面也是应用实例。
### 消息协议
协议分两层:
1. (底层)一层协议为`Layer1Protocol`内部封装了port支持双向通信发送与接收
2. 高层二层协议分3个部分基于一层协议
1. `ExtensionMessaging`:扩展端的
2. `InjectMessaging`:注入端端
3. `useMessagingService``useMessaging`:应用端的
### 通信方向
通信分为6个方向
1. 扩展端 --> 注入端
2. 扩展端 --> 应用端
3. 注入端 --> 扩展端
4. 注入端 --> 应用端
5. 应用端 --> 注入端
6. 应用端 --> 扩展端
应用端与注入端通信实现方式:通过扩展端中转。
### 通信流程
1. 注入端通过port连接扩展端然后发送握手信息里面包含了此端的一些信息
2. 应用端:同注入端。

View File

@@ -1,16 +0,0 @@
// 请求信息
export type L2ReqMsg = {
from: 'extension' | 'inject' | 'app'
method: string
params?: any
}
// 响应信息
export type L2ResMsg<L2Res = any> = {
code: number
msg?: string
data?: L2Res
}
export const TAG_TARGET_INJECT = 'target:inject'
export const TAG_TARGET_APP = 'target:app'

View File

@@ -1,114 +0,0 @@
// 请求信息
type ReqMsg<L1Req = any, L1Res = any> = {
id: string
// 类型
type: 'req' | 'res'
// 请求
req?: L1Req
// 响应
res?: RespMsg<L1Res>
}
// 响应信息
type RespMsg<T = any> = {
code: number
data?: T
msg?: string
}
// 处理函数
type Handler<L1Req = any, L1Res = any> = (req: L1Req) => Promise<L1Res>
// 创建一个 Layer1Protocol 类,用于持久监听 port 并通过消息 ID 处理响应,支持超时
class Layer1Protocol<L1Req = any, L1Res = any> {
private port: chrome.runtime.Port
private timeout: number
private requests: Map<string, { resolve: (value: L1Res) => void, reject: (reason?: any) => void, timer: number }>
private handler: Handler<L1Req, L1Res>
constructor(handler: Handler<L1Req, L1Res>, port: chrome.runtime.Port, autoDispose = true, timeout = 30000) { // 默认超时 30 秒
this.port = port;
this.timeout = timeout;
this.requests = new Map();
this.handler = handler
// 开始监听
this.port.onMessage.addListener(this._messageListener);
if (autoDispose) {
this.port.onDisconnect.addListener(this.dispose);
}
}
// 生成唯一 ID简单示例可以使用更复杂的生成策略
private _generateUniqueId() {
return crypto.randomUUID()
}
private _messageListener = (msg: ReqMsg<L1Req, L1Res>) => {
const { id, type, req, res } = msg;
if (type === 'req') {
this.handler(req!).then(res => {
const response: RespMsg<L1Res> = {
code: 200,
data: res
}
this.port.postMessage({ id, type: 'res', res: response });
}).catch(error => {//业务错误
const response: RespMsg<L1Res> = {
code: 500,
msg: error instanceof Error ? error.message : String(error),
}
this.port.postMessage({ id, type: 'res', res: response });
});
} else if (type === 'res') {
if (this.requests.has(id)) {
const { resolve, reject, timer } = this.requests.get(id)!;
// 清除超时定时器
clearTimeout(timer);
// 移除消息 ID
this.requests.delete(id);
// 通过 ID 找到对应的 Promise 并 resolve
if (res!.code === 200) {
resolve(res!.data!);
} else {//业务错误
reject(new Error(`${res!.code}: ${res!.msg || 'Unknown error'}`));
}
} else {
console.error('unknown response message id: ', id)
}
} else {//语法格式错误
console.error('unknown message type: ', type)
}
}
dispose() {
this.port.onMessage.removeListener(this._messageListener);
if (this.port.onDisconnect) {
this.port.onDisconnect.removeListener(this.dispose);
}
this.requests.forEach(({ timer }) => clearTimeout(timer));
this.requests.clear();
}
// 使用 Promise 发送消息并等待响应,支持超时
sendMessage(req: L1Req): Promise<L1Res> {
const id = this._generateUniqueId();
return new Promise<L1Res>((resolve, reject) => {
// 设置一个超时定时器
const timer = setTimeout(() => {
// 超时后执行 reject 并从 Map 中删除
this.requests.delete(id);
reject(new Error(`Request timed out after ${this.timeout / 1000} seconds`));
}, this.timeout);
// 将 resolve 和 timer 函数与消息 ID 绑定,存入 Map
this.requests.set(id, { resolve, reject, timer });
// 发送消息,并附带 ID
this.port.postMessage({ id, type: 'req', req });
});
}
}
export default Layer1Protocol

View File

@@ -1,134 +0,0 @@
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg } from '../const'
type PortContext<L2ReqMsg, L2ResMsg> = {
id: string
name: string //暂时没什么用
port: chrome.runtime.Port
l1protocol: Layer1Protocol<L2ReqMsg, L2ResMsg>
ready: boolean
tabId?: number // 所属tab
tags?: string[] // 标签,用来筛选消息发送目标
}
type L2MethodHandler<M extends ExtensionMessage, K, L2ReqMsg, L2ResMsg> = (params: Extract<M, { method: K }>['params'], context: MethodContext, portContext: PortContext<L2ReqMsg, L2ResMsg>) => Promise<any>
type L2MethodHandlers<M extends ExtensionMessage, L2ReqMsg, L2ResMsg> = {
[K in M['method']]: L2MethodHandler<M, K, L2ReqMsg, L2ResMsg>
}
class ExtensionMessaging<M extends ExtensionMessage, AllInjectMessagesType extends InjectMessage, AllAPPMessagesType extends AppMessage> {
portIdToPort: Map<string, PortContext<L2ReqMsg, L2ResMsg>> = new Map()
methods?: L2MethodHandlers<M, L2ReqMsg, L2ResMsg>
debug = (...args: any[]) => {
console.debug('[Extension Messaging]', ...args)
}
init = (methods: L2MethodHandlers<M, L2ReqMsg, L2ResMsg>) => {
const innerMethods: L2MethodHandlers<MessagingExtensionMessages, L2ReqMsg, L2ResMsg> = {
_HANDSHAKE: async (params, context: MethodContext, portContext: PortContext<L2ReqMsg, L2ResMsg>) => {
const tags = params.tags
let tabId = params.tabId
//get current tabId
if (tabId == null) {
const tabs = await chrome.tabs.query({
active: true,
currentWindow: true,
})
tabId = tabs[0]?.id
}
portContext.tabId = tabId
portContext.tags = tags
portContext.ready = true
},
_ROUTE: async (params, context: MethodContext) => {
return this.broadcastMessageExact([context.tabId!], params.tags, params.method as any, params.params)
},
}
this.methods = { ...innerMethods, ...methods }
chrome.runtime.onConnect.addListener((port: chrome.runtime.Port) => {
this.debug('onConnect', port)
const id = crypto.randomUUID()
const name = port.name
// 创建消息处理器
const l1protocol = new Layer1Protocol<L2ReqMsg, L2ResMsg>(async (req: L2ReqMsg) => {
const { tabId } = portContext
const method = this.methods?.[req.method as keyof typeof this.methods]
// console.log('msg>>>', tabId, req, method != null)
if (method != null) {
return method(req.params, {
from: req.from,
event: req,
tabId,
// sender: portContext.port.sender,
}, portContext).then((data) => ({
code: 200,
data,
})).catch((err) => {
console.error(err)
return {
code: 500,
msg: err.message,
}
})
} else {
return {
code: 501,
msg: 'Unknown method: ' + req.method,
}
}
}, port)
// 创建portContext
const portContext: PortContext<L2ReqMsg, L2ResMsg> = { id, name, port, l1protocol, ready: false }
this.portIdToPort.set(id, portContext)
// 监听断开连接
port.onDisconnect.addListener(() => {
this.debug('onDisconnect', id)
this.portIdToPort.delete(id)
})
})
}
//tags 如果为null则不检查tags如果为空数组则不会发送消息
//返回:最后一个响应(因此如果只发送给一个tab则返回的是该tab的响应)
broadcastMessageExact = async <M extends AllInjectMessagesType | AllAPPMessagesType, K extends M['method']>(tabIds: number[], tags: string[] | null, method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
// 如果tags为空数组则不会发送消息
if (tags != null && tags.length === 0) {
return
}
let res: L2ResMsg | undefined
for (const portContext of this.portIdToPort.values()) {
//check tabId
if (tabIds.includes(portContext.tabId!)) {
//check tags
if (tags == null || tags.some(tag => portContext.tags?.includes(tag))) {
try {
res = await portContext.l1protocol.sendMessage({ method, params, from: 'extension' })
} catch (e) {
console.error('send message to port error', portContext.id, e)
}
}
}
}
return res?.data
}
broadcastMessage = async <M extends AllInjectMessagesType | AllAPPMessagesType, K extends M['method']>(ignoreTabIds: number[] | undefined | null, tags: string[], method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
const tabs = await chrome.tabs.query({
discarded: false,
})
const tabIds: number[] = tabs.map(tab => tab.id).filter(tabId => tabId != null) as number[]
const filteredTabIds: number[] = tabIds.filter(tabId => !ignoreTabIds?.includes(tabId))
return await this.broadcastMessageExact(filteredTabIds, tags, method, params)
}
}
export default ExtensionMessaging

View File

@@ -1,103 +0,0 @@
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg, TAG_TARGET_APP, TAG_TARGET_INJECT } from '../const'
class InjectMessaging<AllExtensionMessagesType extends ExtensionMessage, AllInjectMessagesType extends InjectMessage, AllAPPMessagesType extends AppMessage> {
port?: chrome.runtime.Port
l1protocol?: Layer1Protocol<L2ReqMsg, L2ResMsg>
//类实例
methods?: {
[K in AllInjectMessagesType['method']]: (params: Extract<AllInjectMessagesType, { method: K }>['params'], context: MethodContext) => Promise<any>
}
debug = (...args: any[]) => {
console.debug('[Inject Messaging]', ...args)
}
messageHandler = async (req: L2ReqMsg): Promise<L2ResMsg> => {
this.debug(`[${req.from}] ${req.method}`, JSON.stringify(req))
// check event target
// if (req.target !== MESSAGE_TARGET_INJECT) return Promise.resolve({
// success: false,
// code: 501,
// message: 'Target Error: ' + req.target,
// })
const method = this.methods?.[req.method as keyof typeof this.methods]
if (method != null) {
return method(req.params, {
from: req.from,
event: req,
// sender,
}).then(data => {
// debug(`${source} <= `, event.method, JSON.stringify(data))
return {
code: 200,
data,
}
}).catch(err => {
console.error(err)
let msg
if (err instanceof Error) {
msg = err.message
} else if (typeof err === 'string') {
msg = err
} else {
msg = 'error: ' + JSON.stringify(err)
}
return {
code: 500,
msg,
}
})
} else {
return {
code: 501,
msg: 'Unknown method: ' + req.method,
}
}
}
init(methods: {
[K in AllInjectMessagesType['method']]: (params: Extract<AllInjectMessagesType, { method: K }>['params'], context: MethodContext) => Promise<any>
}) {
this.methods = methods
this.port = chrome.runtime.connect({
name: 'bilibili-inject',
})
this.l1protocol = new Layer1Protocol<L2ReqMsg, L2ResMsg>(this.messageHandler, this.port)
//握手
this.l1protocol.sendMessage({
from: 'inject',
method: '_HANDSHAKE',
params: {
tags: [TAG_TARGET_INJECT],
},
})
}
sendExtension = async <M extends AllExtensionMessagesType | MessagingExtensionMessages, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
return await this.l1protocol!.sendMessage({
from: 'inject',
method,
params: params ?? {},
}).then((res) => {
if (res.code === 200) {
return res.data
} else {
throw new Error(res.msg)
}
})
}
sendApp = async <M extends AllAPPMessagesType, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
return this.sendExtension('_ROUTE' as any, {
tags: [TAG_TARGET_APP],
method,
params,
})
}
}
export default InjectMessaging

View File

@@ -1,37 +0,0 @@
import { msgWaiter } from './useMessagingService'
import { useCallback } from 'react'
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg, TAG_TARGET_INJECT } from '../const'
const useMessaging = <AllExtensionMessagesType extends ExtensionMessage, AllInjectMessagesType extends InjectMessage>() => {
const sendExtension = useCallback(async <M extends AllExtensionMessagesType | MessagingExtensionMessages, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
// wait
const pmh = await msgWaiter.wait() as Layer1Protocol<L2ReqMsg, L2ResMsg>
// send message
const res = await pmh.sendMessage({
from: 'app',
method,
params: params ?? {},
})
if (res.code === 200) {
return res.data
} else {
throw new Error(res.msg)
}
}, [])
const sendInject = useCallback(async <M extends AllInjectMessagesType, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
return await sendExtension('_ROUTE' as any, {
tags: [TAG_TARGET_INJECT],
method,
params: params ?? {},
})
}, [])
return {
sendExtension,
sendInject
}
}
export default useMessaging

View File

@@ -1,93 +0,0 @@
import { useCallback, useMemo } from 'react'
import { Waiter } from '@kky002/kky-util'
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg, TAG_TARGET_APP } from '../const'
const debug = (...args: any[]) => {
console.debug('[App Messaging]', ...args)
}
let l1protocolInit: boolean = false
let l1protocol: Layer1Protocol<L2ReqMsg, L2ResMsg> | undefined
// let postInjectMessage: (method: string, params: PostMessagePayload) => Promise<PostMessageResponse> | undefined
export const msgWaiter = new Waiter<Layer1Protocol<L2ReqMsg, L2ResMsg>>(() => ({
finished: l1protocolInit,
data: l1protocol!,
}), 100, 15000)
const useMessagingService = <AllAPPMessagesType extends AppMessage>(methods?: {
[K in AllAPPMessagesType['method']]: (params: Extract<AllAPPMessagesType, { method: K }>['params'], context: MethodContext) => Promise<any>
}) => {
const messageHandler = useCallback(async (req: L2ReqMsg): Promise<L2ResMsg> => {
debug(`[${req.from}] ${req.method}`, JSON.stringify(req))
// // check event target
// if (req.target !== MESSAGE_TARGET_APP) return {
// code: 501,
// msg: 'Target Error: ' + req.target,
// }
const method = methods?.[req.method as keyof typeof methods]
if (method != null) {
return method(req.params, {
from: req.from,
event: req,
}).then(data => {
// debug(`${source} <= `, event.method, JSON.stringify(data))
return {
code: 200,
data,
}
}).catch(err => {
console.error(err)
let msg
if (err instanceof Error) {
msg = err.message
} else if (typeof err === 'string') {
msg = err
} else {
msg = 'error: ' + JSON.stringify(err)
}
return {
code: 500,
msg,
}
})
} else {
return {
code: 501,
msg: 'Unknown method: ' + req.method,
}
}
}, [methods])
const port = useMemo(() => {
return chrome.runtime.connect({
name: 'bilibili-app',
})
}, [])
l1protocol = useMemo(() => {
if (messageHandler && port) {
const pmh = new Layer1Protocol<L2ReqMsg, L2ResMsg>(messageHandler, port)
//get tabId from url params
let tabIdStr = window.location.search.split('tabId=')[1]
let tabId = tabIdStr ? parseInt(tabIdStr) : undefined
// 初始化
pmh.sendMessage({
from: 'app',
method: '_HANDSHAKE',
params: {
tabId,
tags: [TAG_TARGET_APP],
},
})
l1protocolInit = true
return pmh
}
}, [messageHandler, port])
}
export default useMessagingService

View File

@@ -1,28 +0,0 @@
interface Message<T = any, R = any> {
method: string
params: T
return: R
}
interface ExtensionMessage<T = any, R = any> extends Message<T, R> {
}
interface InjectMessage<T = any, R = any> extends Message<T, R> {
}
interface AppMessage<T = any, R = any> extends Message<T, R> {
}
interface ExtensionHandshakeMessage extends ExtensionMessage<{ tabId?: number, tags: string[] }> {
method: '_HANDSHAKE';
}
interface ExtensionRouteMessage extends ExtensionMessage<{ tags: string[], method: string, params: any }> {
method: '_ROUTE';
}
type MessagingExtensionMessages = ExtensionHandshakeMessage | ExtensionRouteMessage

View File

@@ -9,19 +9,19 @@ import useTranslateService from '../hooks/useTranslateService'
import {setTheme} from '../utils/bizUtil'
import useSearchService from '../hooks/useSearchService'
import {setFold} from '../redux/envReducer'
import { useMessage } from '@/hooks/message'
import { useMessage } from '@/hooks/useMessageService'
function App() {
const dispatch = useAppDispatch()
const fold = useAppSelector(state => state.env.fold)
const envData = useAppSelector(state => state.env.envData)
const eventBus = useContext(EventBusContext)
const totalHeight = useAppSelector(state => state.env.totalHeight)
const {sendInject} = useMessage()
const envData = useAppSelector(state => state.env.envData)
const {sendInject} = useMessage(!!envData.sidePanel)
const foldCallback = useCallback(() => {
dispatch(setFold(!fold))
sendInject('FOLD', {fold: !fold})
sendInject(null, 'FOLD', {fold: !fold})
}, [dispatch, fold, sendInject])
// handle event

View File

@@ -26,11 +26,11 @@ import classNames from 'classnames'
import toast from 'react-hot-toast'
import {useBoolean, useEventTarget} from 'ahooks'
import {useEventChecked} from '@kky002/kky-hooks'
import { useMessage } from '@/hooks/message'
import { FaChevronDown, FaChevronUp } from 'react-icons/fa'
import { FaChevronDown, FaChevronUp, FaGripfire } from 'react-icons/fa'
import { useMessage } from '@/hooks/useMessageService'
const OptionCard = ({ title, children, defaultExpanded = true }: { title: React.ReactNode; children: React.ReactNode; defaultExpanded?: boolean }) => {
const [isExpanded, setIsExpanded] = useState(defaultExpanded);
const OptionCard = ({ title, children, defaultExpanded = true }: { title: React.ReactNode, children: React.ReactNode, defaultExpanded?: boolean }) => {
const [isExpanded, setIsExpanded] = useState(defaultExpanded)
return (
<div className="card bg-base-200 shadow-xl mb-4">
@@ -42,8 +42,8 @@ const OptionCard = ({ title, children, defaultExpanded = true }: { title: React.
{isExpanded && <div className="mt-4">{children}</div>}
</div>
</div>
);
};
)
}
const FormItem = (props: {
title: ShowElement
@@ -66,7 +66,7 @@ const FormItem = (props: {
const OptionsPage = () => {
const dispatch = useAppDispatch()
const envData = useAppSelector(state => state.env.envData)
const {sendExtension} = useMessage()
const {sendExtension} = useMessage(false)
const {value: sidePanelValue, onChange: setSidePanelValue} = useEventChecked(envData.sidePanel)
const {value: autoInsertValue, onChange: setAutoInsertValue} = useEventChecked(!envData.manualInsert)
const {value: autoExpandValue, onChange: setAutoExpandValue} = useEventChecked(envData.autoExpand)
@@ -148,7 +148,7 @@ const OptionsPage = () => {
askEnabled: askEnabledValue,
}))
toast.success('保存成功')
sendExtension('CLOSE_SIDE_PANEL')
sendExtension(null, 'CLOSE_SIDE_PANEL')
// 3秒后关闭
setTimeout(() => {
window.close()
@@ -261,14 +261,15 @@ const OptionsPage = () => {
<div><a className='link link-primary'
onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_OPENAI)}
rel='noreferrer'></a></div>
{/* <div className='flex justify-center font-semibold'>【第三方代理】</div> */}
{/* <div>代理网址:<a className='link link-primary' href='https://api.openai-up.com/register?aff=varM' */}
{/* target='_blank' */}
{/* rel="noreferrer">点击访问</a></div> */}
{/* <div>服务器地址:<a className='link link-primary' */}
{/* onClick={() => setServerUrlValue('https://api.openai-up.com')} */}
{/* rel='noreferrer'>点击设置</a></div> */}
{/* <div className='text-amber-600 flex justify-center items-center'><FaGripfire/>目前价格不到官方价格的6折<FaGripfire/></div> */}
<div className='flex justify-center font-semibold'></div>
<div><a className='link link-primary' href='https://api.kksj.org/register?aff=ucVc'
target='_blank'
rel="noreferrer">访</a></div>
<div><a className='link link-primary'
onClick={() => setServerUrlValue('https://api.kksj.org')}
rel='noreferrer'></a></div>
<div className='text-amber-600 flex justify-center items-center'><FaGripfire/>0.91(1/8)<FaGripfire/></div>
<div className='text-amber-600 flex justify-center items-center'><FaGripfire/>访🪜<FaGripfire/></div>
</div>
</div>}
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='模型选择' htmlFor='modelSel' tip='注意不同模型有不同价格与token限制'>
@@ -429,4 +430,4 @@ const OptionsPage = () => {
)
}
export default OptionsPage
export default OptionsPage

View File

@@ -50,7 +50,7 @@ interface EnvState {
searchText: string
searchResult: Record<string, boolean>
//当前视频是否计算过操作
// 当前视频是否计算过操作
reviewAction: boolean
}

8
src/typings.d.ts vendored
View File

@@ -7,7 +7,7 @@ interface MethodContext {
interface EnvData {
sidePanel?: boolean
manualInsert?: boolean //是否手动插入字幕列表
manualInsert?: boolean // 是否手动插入字幕列表
autoExpand?: boolean
flagDot?: boolean
@@ -154,10 +154,10 @@ type SummaryStatus = 'init' | 'pending' | 'done'
type SummaryType = 'overview' | 'keypoint' | 'brief' | 'question' | 'debate'
interface DebateMessage {
side: 'pro' | 'con';
content: string;
side: 'pro' | 'con'
content: string
}
interface DebateProps {
messages: DebateMessage[];
messages: DebateMessage[]
}

View File

@@ -115,7 +115,7 @@ export const getSummaryStr = (summary: Summary) => {
s += content.map(item => {
return (item.side === 'pro'?'正方:':'反方:') + item.content + '\n'
}).join('\n')
}
}
return s
}

View File

@@ -1,7 +1,7 @@
export const openOptionsPage = () => {
if (chrome.runtime.openOptionsPage) {
chrome.runtime.openOptionsPage();
chrome.runtime.openOptionsPage()
} else {
window.open(chrome.runtime.getURL('options.html'));
window.open(chrome.runtime.getURL('options.html'))
}
};
}

View File

@@ -1,8 +1,8 @@
import {SyntheticEvent} from 'react'
export const isEdgeBrowser = () => {
const userAgent = navigator.userAgent.toLowerCase();
return userAgent.includes('edg/') && !userAgent.includes('edge/');
const userAgent = navigator.userAgent.toLowerCase()
return userAgent.includes('edg/') && !userAgent.includes('edge/')
}
export const formatTime = (time: number) => {

View File

@@ -3,7 +3,11 @@ module.exports = {
darkMode: 'class',
content: ["./src/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {},
extend: {
fontSize: {
xs: '13px',
},
},
},
plugins: [
require('tailwind-scrollbar-hide'),