You've already forked bilibili-subtitle
Compare commits
35 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
194df8525c | ||
![]() |
28bb3dbb96 | ||
![]() |
640f6d89fd | ||
![]() |
338e3145f2 | ||
![]() |
e2121e83bd | ||
![]() |
7583b05289 | ||
![]() |
ae60303a15 | ||
![]() |
5bcedf0c9d | ||
![]() |
d4e5e407a4 | ||
![]() |
ce2a2da6f5 | ||
![]() |
368f5d721c | ||
![]() |
21e2ca958c | ||
![]() |
149653ffac | ||
![]() |
f977b5e238 | ||
![]() |
c13ef4597b | ||
![]() |
65026f62af | ||
![]() |
bcff8b4f90 | ||
![]() |
ee1eaf9e08 | ||
![]() |
cc732de8e6 | ||
![]() |
cccf7e6149 | ||
![]() |
30dc724ebb | ||
![]() |
51a7e998b9 | ||
![]() |
556ccef4b2 | ||
![]() |
42b719fb98 | ||
![]() |
fa66445466 | ||
![]() |
d711b2abf8 | ||
![]() |
47fcb1de11 | ||
![]() |
be3d3624bc | ||
![]() |
910b1ce6d9 | ||
![]() |
0a6bda667e | ||
![]() |
5a0a123af9 | ||
![]() |
b481b8a55a | ||
![]() |
3cede8650d | ||
![]() |
69e0497081 | ||
![]() |
8776186486 |
@@ -4,3 +4,4 @@ node_modules/
|
||||
postcss.config.cjs
|
||||
vite.config.ts
|
||||
vite-env.d.ts
|
||||
manifest.config.ts
|
@@ -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"
|
||||
|
@@ -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的这个操作。
|
||||
|
||||
## 贡献指南
|
||||
|
||||
欢迎贡献代码或提出改进建议!如果您希望为该项目做出贡献,请遵循以下步骤:
|
||||
|
7
fix.cjs
7
fix.cjs
@@ -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');
|
||||
|
@@ -12,9 +12,10 @@ const [major, minor, patch, label = '0'] = version
|
||||
.split(/[.-]/)
|
||||
|
||||
export default defineManifest(async (env) => ({
|
||||
"name": "哔哔君 - 哔哩哔哩字幕列表",
|
||||
"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
|
||||
}
|
||||
]
|
||||
}))
|
||||
|
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "bilibili-subtitle",
|
||||
"version": "1.11.3",
|
||||
"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",
|
||||
@@ -24,6 +25,7 @@
|
||||
"ahooks": "^3.7.1",
|
||||
"classnames": "^2.3.2",
|
||||
"daisyui": "^2.42.1",
|
||||
"dayjs": "^1.11.13",
|
||||
"js-search": "^2.0.0",
|
||||
"less": "^4.1.3",
|
||||
"lodash-es": "^4.17.21",
|
||||
|
70
pnpm-lock.yaml
generated
70
pnpm-lock.yaml
generated
@@ -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
|
||||
@@ -41,6 +44,9 @@ importers:
|
||||
daisyui:
|
||||
specifier: ^2.42.1
|
||||
version: 2.42.1(autoprefixer@10.4.13(postcss@8.4.19))(postcss@8.4.19)
|
||||
dayjs:
|
||||
specifier: ^1.11.13
|
||||
version: 1.11.13
|
||||
js-search:
|
||||
specifier: ^2.0.0
|
||||
version: 2.0.0
|
||||
@@ -307,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'}
|
||||
@@ -387,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==}
|
||||
|
||||
@@ -651,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==}
|
||||
|
||||
@@ -856,8 +875,8 @@ packages:
|
||||
autoprefixer: ^10.0.2
|
||||
postcss: ^8.1.6
|
||||
|
||||
dayjs@1.11.5:
|
||||
resolution: {integrity: sha512-CAdX5Q3YW3Gclyo5Vpqkgpj8fSdLQcRuzfX6mC6Phy0nfJ0eGYOeS7m4mt2plDWLAtA4TqTakvbboHvUxfe4iA==}
|
||||
dayjs@1.11.13:
|
||||
resolution: {integrity: sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==}
|
||||
|
||||
debug@2.6.9:
|
||||
resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==}
|
||||
@@ -1557,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==}
|
||||
|
||||
@@ -2045,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'}
|
||||
@@ -2132,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'}
|
||||
@@ -2693,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
|
||||
@@ -2813,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
|
||||
@@ -3114,7 +3155,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@types/js-cookie': 2.2.7
|
||||
ahooks-v3-count: 1.0.0
|
||||
dayjs: 1.11.5
|
||||
dayjs: 1.11.13
|
||||
intersection-observer: 0.12.2
|
||||
js-cookie: 2.2.1
|
||||
lodash: 4.17.21
|
||||
@@ -3126,7 +3167,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@types/js-cookie': 2.2.7
|
||||
ahooks-v3-count: 1.0.0
|
||||
dayjs: 1.11.5
|
||||
dayjs: 1.11.13
|
||||
intersection-observer: 0.12.2
|
||||
js-cookie: 2.2.1
|
||||
lodash: 4.17.21
|
||||
@@ -3135,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
|
||||
@@ -3385,7 +3439,7 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- ts-node
|
||||
|
||||
dayjs@1.11.5: {}
|
||||
dayjs@1.11.13: {}
|
||||
|
||||
debug@2.6.9:
|
||||
dependencies:
|
||||
@@ -4073,6 +4127,8 @@ snapshots:
|
||||
|
||||
js-cookie@2.2.1: {}
|
||||
|
||||
js-cookie@3.0.5: {}
|
||||
|
||||
js-search@2.0.0: {}
|
||||
|
||||
js-tokens@4.0.0: {}
|
||||
@@ -4695,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)
|
||||
@@ -4787,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
|
||||
|
8
public/_locales/zh_CN/messages.json
Normal file
8
public/_locales/zh_CN/messages.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"appName": {
|
||||
"message": "哔哔君 - bilibili哔哩哔哩字幕列表"
|
||||
},
|
||||
"appDescription": {
|
||||
"message": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!"
|
||||
}
|
||||
}
|
BIN
public/bibigpt.png
Normal file
BIN
public/bibigpt.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 4.0 KiB |
@@ -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'}/>
|
||||
|
@@ -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)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
@@ -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',
|
||||
|
@@ -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
|
||||
|
@@ -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'
|
||||
@@ -304,22 +311,22 @@ const Body = () => {
|
||||
{/* </button>} */}
|
||||
{/* </div> */}
|
||||
<div className='flex flex-col'>
|
||||
{/* <div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'> */}
|
||||
{/* <div className='font-semibold text-accent flex items-center gap-1'><img src='/bibigpt.png' */}
|
||||
{/* alt='BibiGPT logo' */}
|
||||
{/* className='w-8 h-8'/>BibiGPT */}
|
||||
{/* </div> */}
|
||||
{/* <div className='text-sm px-2 desc'>这是<span className='text-amber-600 font-semibold text-base'>网页</span>版的字幕列表,支持<span */}
|
||||
{/* className='font-semibold'>任意</span>视频提取字幕总结(包括没有字幕的视频) */}
|
||||
{/* </div> */}
|
||||
{/* <div className='flex gap-2'> */}
|
||||
{/* <a title='BibiGPT' href='https://bibigpt.co/r/bilibili' */}
|
||||
{/* onClick={(e) => { */}
|
||||
{/* e.preventDefault() */}
|
||||
{/* openUrl('https://bibigpt.co/r/bilibili') */}
|
||||
{/* }} className='link text-sm text-accent'>✨ BibiGPT ✨</a> */}
|
||||
{/* </div> */}
|
||||
{/* </div> */}
|
||||
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
|
||||
<div className='font-semibold text-accent flex items-center gap-1'><img src='/bibigpt.png'
|
||||
alt='BibiGPT logo'
|
||||
className='w-8 h-8'/>BibiGPT
|
||||
</div>
|
||||
<div className='text-sm px-2 desc'>这是<span className='text-amber-600 font-semibold text-base'>网页</span>版的字幕列表,支持<span
|
||||
className='font-semibold'>任意</span>视频提取字幕总结(包括没有字幕的视频)
|
||||
</div>
|
||||
<div className='flex gap-2'>
|
||||
<a title='BibiGPT' href='https://bibigpt.co/r/bilibili'
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
openUrl('https://bibigpt.co/r/bilibili')
|
||||
}} className='link text-sm text-accent'>✨ BibiGPT ✨</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
|
||||
<div className='font-semibold text-accent flex items-center gap-1'><img src='/youtube-caption.png'
|
||||
alt='youtube caption logo'
|
||||
@@ -415,4 +422,4 @@ const Body = () => {
|
||||
</div>
|
||||
}
|
||||
|
||||
export default Body
|
||||
export default Body
|
||||
|
43
src/components/DebateChat.tsx
Normal file
43
src/components/DebateChat.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import { useAppSelector } from '@/hooks/redux'
|
||||
import React from 'react'
|
||||
|
||||
const DebateChat: React.FC<DebateProps> = ({ messages }) => {
|
||||
const fontSize = useAppSelector(state => state.env.envData.fontSize)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
{messages.map((message, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`flex mb-4 ${
|
||||
message.side === 'pro' ? 'justify-start' : 'justify-end'
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={`max-w-[85%] rounded-2xl p-3 shadow-md relative ${
|
||||
message.side === 'pro'
|
||||
? 'bg-blue-100 text-blue-800 ml-2'
|
||||
: 'bg-green-100 text-green-800 mr-2'
|
||||
}`}
|
||||
>
|
||||
<p className={`${fontSize === 'large' ? 'text-sm' : 'text-xs'} font-bold mb-1`}>
|
||||
{message.side === 'pro' ? '正方' : '反方'}
|
||||
</p>
|
||||
<p className={fontSize === 'large' ? 'text-sm' : 'text-xs'}>{message.content}</p>
|
||||
<div
|
||||
className={`absolute w-4 h-4 ${
|
||||
message.side === 'pro'
|
||||
? 'bg-blue-100 -left-2 top-2 rounded-bl-full'
|
||||
: 'bg-green-100 -right-2 top-2 rounded-br-full'
|
||||
}`}
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default DebateChat
|
@@ -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]'>
|
||||
|
@@ -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,7 +16,9 @@ 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 { useMessage } from '@/hooks/useMessageService'
|
||||
|
||||
interface Props {
|
||||
placement: Placement
|
||||
}
|
||||
@@ -68,9 +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 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) {
|
||||
@@ -79,20 +81,21 @@ const MoreBtn = (props: Props) => {
|
||||
|
||||
let fileName = title
|
||||
let s, suffix
|
||||
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\n`
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
|
||||
for (const item of data.body) {
|
||||
s += item.content + '\n'
|
||||
}
|
||||
suffix = 'txt'
|
||||
} else if (downloadType === 'textWithTime') {
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
|
||||
for (const item of data.body) {
|
||||
s += formatTime(item.from) + ' ' + item.content + '\n'
|
||||
}
|
||||
suffix = 'txt'
|
||||
} else if (downloadType === 'article') {
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
|
||||
for (const item of data.body) {
|
||||
s += item.content + ', '
|
||||
}
|
||||
@@ -142,7 +145,7 @@ const MoreBtn = (props: Props) => {
|
||||
s = JSON.stringify(data)
|
||||
suffix = 'json'
|
||||
} else if (downloadType === 'summarize') {
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
|
||||
const [success, content] = getSummarize(title, segments, curSummaryType)
|
||||
if (!success) return
|
||||
s += content
|
||||
@@ -159,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({
|
||||
@@ -245,7 +248,7 @@ const MoreBtn = (props: Props) => {
|
||||
下载音频(m4s)
|
||||
</a>
|
||||
</li>
|
||||
<li className='hover:bg-accent'>
|
||||
{/* <li className='hover:bg-accent'>
|
||||
<a className='flex items-center' onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
@@ -264,7 +267,7 @@ const MoreBtn = (props: Props) => {
|
||||
<AiFillWechat className='w-[20px] h-[20px] text-primary/75 bg-white rounded-sm p-0.5'/>
|
||||
微信公众号(IndieKKY)
|
||||
</a>
|
||||
</li>
|
||||
</li> */}
|
||||
{/* <li className='hover:bg-accent'> */}
|
||||
{/* <a className='flex items-center' onClick={(e) => { */}
|
||||
{/* e.preventDefault() */}
|
||||
@@ -297,6 +300,17 @@ const MoreBtn = (props: Props) => {
|
||||
选项
|
||||
</a>
|
||||
</li>
|
||||
{/* 官网 */}
|
||||
<li className='hover:bg-accent'>
|
||||
<a className='flex items-center' onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
openUrl('https://www.bibijun.cc')
|
||||
}}>
|
||||
<img alt='哔哔君' src='/favicon-128x128.png' className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/>
|
||||
🏠 哔哔君官网
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</Popover>}
|
||||
</>
|
||||
|
@@ -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
|
||||
|
@@ -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} from 'react-icons/fa'
|
||||
import {PAGE_MAIN, PAGE_SETTINGS, SUMMARIZE_THRESHOLD, SUMMARIZE_TYPES} from '../consts/const'
|
||||
import {FaClipboardList, FaComments} from 'react-icons/fa'
|
||||
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'
|
||||
@@ -12,6 +12,7 @@ import {useInViewport} from 'ahooks'
|
||||
import SegmentItem from './SegmentItem'
|
||||
import {stopPopFunc} from '../utils/util'
|
||||
import useSubtitle from '../hooks/useSubtitle'
|
||||
import DebateChat from './DebateChat'
|
||||
|
||||
const SummarizeItemOverview = (props: {
|
||||
segment: Segment
|
||||
@@ -113,6 +114,8 @@ const Summarize = (props: {
|
||||
<div className={classNames('font-normal', fontSize === 'large' ? 'text-sm' : 'text-xs')}>{question.a}</div>
|
||||
</div>)}
|
||||
</div>}
|
||||
{summary?.type === 'debate' && (summary.content != null) &&
|
||||
<DebateChat messages={summary.content} />}
|
||||
</div>
|
||||
<div className='flex flex-col justify-center items-center'>
|
||||
{segment.text.length < SUMMARIZE_THRESHOLD && <div className='desc-lighter text-xs'>文字过短,无法总结.</div>}
|
||||
@@ -200,8 +203,14 @@ const SegmentCard = (props: {
|
||||
}))
|
||||
}, [dispatch])
|
||||
|
||||
const onSelDebate = useCallback(() => {
|
||||
dispatch(setTempData({
|
||||
curSummaryType: 'debate'
|
||||
}))
|
||||
}, [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'>
|
||||
@@ -215,6 +224,7 @@ const SegmentCard = (props: {
|
||||
<a className={classNames('tab tab-lifted tab-xs', curSummaryType === 'overview' && 'tab-active')} onClick={onSelOverview}><GrOverview/>概览</a>
|
||||
<a className={classNames('tab tab-lifted tab-xs', curSummaryType === 'keypoint' && 'tab-active')} onClick={onSelKeypoint}><FaClipboardList/>要点</a>
|
||||
<a className={classNames('tab tab-lifted tab-xs', curSummaryType === 'question' && 'tab-active')} onClick={onSelQuestion}><FaQuestion/>问题</a>
|
||||
<a className={classNames('tab tab-lifted tab-xs', curSummaryType === 'debate' && 'tab-active')} onClick={onSelDebate}><FaComments/>辩论</a>
|
||||
<a className="tab tab-lifted tab-xs tab-disabled cursor-default"></a>
|
||||
</div>}
|
||||
<div
|
||||
|
@@ -1,3 +1,5 @@
|
||||
export const DEFAULT_USE_PORT = false
|
||||
|
||||
export const EVENT_EXPAND = 'expand'
|
||||
|
||||
export const APP_DOM_ID = 'bilibili-subtitle'
|
||||
@@ -11,6 +13,7 @@ export const PROMPT_TYPE_TRANSLATE = 'translate'
|
||||
export const PROMPT_TYPE_SUMMARIZE_OVERVIEW = 'summarize_overview'
|
||||
export const PROMPT_TYPE_SUMMARIZE_KEYPOINT = 'summarize_keypoint'
|
||||
export const PROMPT_TYPE_SUMMARIZE_QUESTION = 'summarize_question'
|
||||
export const PROMPT_TYPE_SUMMARIZE_DEBATE = 'summarize_debate'
|
||||
export const PROMPT_TYPE_SUMMARIZE_BRIEF = 'summarize_brief'
|
||||
export const PROMPT_TYPE_ASK = 'ask'
|
||||
export const PROMPT_TYPES = [{
|
||||
@@ -28,6 +31,9 @@ export const PROMPT_TYPES = [{
|
||||
}, {
|
||||
name: '问题',
|
||||
type: PROMPT_TYPE_SUMMARIZE_QUESTION,
|
||||
}, {
|
||||
name: '辩论',
|
||||
type: PROMPT_TYPE_SUMMARIZE_DEBATE,
|
||||
}, {
|
||||
name: '提问',
|
||||
type: PROMPT_TYPE_ASK,
|
||||
@@ -58,6 +64,12 @@ export const SUMMARIZE_TYPES = {
|
||||
downloadName: '💡常见问题💡',
|
||||
promptType: PROMPT_TYPE_SUMMARIZE_QUESTION,
|
||||
},
|
||||
debate: {
|
||||
name: '辩论',
|
||||
desc: '辩论',
|
||||
downloadName: '💡辩论💡',
|
||||
promptType: PROMPT_TYPE_SUMMARIZE_DEBATE,
|
||||
},
|
||||
}
|
||||
|
||||
export const PROMPT_DEFAULTS = {
|
||||
@@ -175,6 +187,42 @@ 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.
|
||||
|
||||
## Context
|
||||
|
||||
The video's title: '''{{title}}'''.
|
||||
The video's subtitles:
|
||||
|
||||
'''
|
||||
{{segment}}
|
||||
'''
|
||||
|
||||
## Command
|
||||
|
||||
Please play the roles of both the affirmative and negative sides to discuss the author's viewpoint.
|
||||
The conversation should consist of 10 rounds(5 sentences from the affirmative side, 5 sentences from the negative side.).
|
||||
The tone should be straightforward.
|
||||
|
||||
Answer in language '{{language}}'.
|
||||
|
||||
## Output format
|
||||
|
||||
Provide an example to illustrate the expected output:
|
||||
|
||||
\`\`\`json
|
||||
[
|
||||
{
|
||||
"side": "pro",
|
||||
"content": "xxx"
|
||||
},
|
||||
{
|
||||
"side": "con",
|
||||
"content": "xxx"
|
||||
}
|
||||
]
|
||||
\`\`\`
|
||||
`,
|
||||
[PROMPT_TYPE_ASK]: `You are a helpful assistant who answers question related to video subtitles.
|
||||
Answer in language '{{language}}'.
|
||||
@@ -245,6 +293,9 @@ for (const model of MODELS) {
|
||||
export const LANGUAGES = [{
|
||||
code: 'en',
|
||||
name: 'English',
|
||||
}, {
|
||||
code: 'ja',
|
||||
name: '日本語',
|
||||
}, {
|
||||
code: 'ena',
|
||||
name: 'American English',
|
||||
@@ -278,6 +329,39 @@ export const LANGUAGES = [{
|
||||
}, {
|
||||
code: 'Italian',
|
||||
name: 'Italiano',
|
||||
}, {
|
||||
code: 'ko',
|
||||
name: '한국어',
|
||||
}, {
|
||||
code: 'hi',
|
||||
name: 'हिन्दी',
|
||||
}, {
|
||||
code: 'tr',
|
||||
name: 'Türkçe',
|
||||
}, {
|
||||
code: 'nl',
|
||||
name: 'Nederlands',
|
||||
}, {
|
||||
code: 'pl',
|
||||
name: 'Polski',
|
||||
}, {
|
||||
code: 'sv',
|
||||
name: 'Svenska',
|
||||
}, {
|
||||
code: 'vi',
|
||||
name: 'Tiếng Việt',
|
||||
}, {
|
||||
code: 'th',
|
||||
name: 'ไทย',
|
||||
}, {
|
||||
code: 'id',
|
||||
name: 'Bahasa Indonesia',
|
||||
}, {
|
||||
code: 'el',
|
||||
name: 'Ελληνικά',
|
||||
}, {
|
||||
code: 'he',
|
||||
name: 'עברית',
|
||||
}]
|
||||
export const LANGUAGES_MAP: {[key: string]: typeof LANGUAGES[number]} = {}
|
||||
for (const language of LANGUAGES) {
|
||||
|
@@ -1,3 +0,0 @@
|
||||
import useMessaging from "@/messaging/layer2/useMessaging";
|
||||
|
||||
export const useMessage = useMessaging<AllExtensionMessages, AllInjectMessages>
|
@@ -1,15 +1,17 @@
|
||||
import { setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
|
||||
import { useMemo } from 'react'
|
||||
import { useAppDispatch } from './redux'
|
||||
import useMessagingService from '@/messaging/layer2/useMessagingService'
|
||||
import { setAuthor, setCtime, setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
|
||||
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))
|
||||
@@ -20,11 +22,14 @@ const useMessageService = () => {
|
||||
dispatch(setInfos(params.infos))
|
||||
dispatch(setUrl(params.url))
|
||||
dispatch(setTitle(params.title))
|
||||
dispatch(setCtime(params.ctime))
|
||||
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>
|
||||
|
@@ -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'})
|
||||
|
@@ -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
|
||||
|
@@ -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}
|
||||
}
|
||||
|
@@ -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,13 +114,15 @@ const debug = (...args: any[]) => {
|
||||
if (danmukuBox) {
|
||||
clearInterval(timerIframe)
|
||||
|
||||
//延迟插入iframe(插入太快,网络较差时容易出现b站网页刷新,原因暂时未知,可能b站的某种机制?)
|
||||
// 延迟插入iframe(插入太快,网络较差时容易出现b站网页刷新,原因暂时未知,可能b站的某种机制?)
|
||||
setTimeout(createIframe, 1500)
|
||||
}
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
let aid: number | null = null
|
||||
let ctime: number | null = null
|
||||
let author: string | undefined
|
||||
let title = ''
|
||||
let pages: any[] = []
|
||||
let pagesMap: Record<string, any> = {}
|
||||
@@ -137,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
|
||||
@@ -155,30 +159,34 @@ 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
|
||||
ctime = res.data.ctime
|
||||
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
|
||||
@@ -186,11 +194,13 @@ 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,
|
||||
ctime,
|
||||
author,
|
||||
pages,
|
||||
infos: subtitles,
|
||||
})
|
||||
@@ -210,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)
|
||||
@@ -218,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
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -271,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()
|
||||
@@ -324,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'
|
||||
}
|
||||
@@ -345,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`
|
||||
|
164
src/message-typings.d.ts
vendored
164
src/message-typings.d.ts
vendored
@@ -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, 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
|
||||
|
@@ -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. 应用端:同注入端。
|
@@ -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'
|
@@ -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
|
@@ -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
|
@@ -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
|
@@ -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
|
@@ -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
|
28
src/messaging/messaging-typings.d.ts
vendored
28
src/messaging/messaging-typings.d.ts
vendored
@@ -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
|
@@ -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
|
||||
|
@@ -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.9人民币可充值1美元(约官方价格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
|
||||
|
@@ -32,7 +32,8 @@ interface EnvState {
|
||||
segments?: Segment[]
|
||||
url?: string
|
||||
title?: string
|
||||
|
||||
ctime?: number | null
|
||||
author?: string
|
||||
taskIds?: string[]
|
||||
transResults: { [key: number]: TransResult }
|
||||
lastTransTime?: number
|
||||
@@ -49,7 +50,7 @@ interface EnvState {
|
||||
searchText: string
|
||||
searchResult: Record<string, boolean>
|
||||
|
||||
//当前视频是否计算过操作
|
||||
// 当前视频是否计算过操作
|
||||
reviewAction: boolean
|
||||
}
|
||||
|
||||
@@ -271,6 +272,12 @@ export const slice = createSlice({
|
||||
setTitle: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.title = action.payload
|
||||
},
|
||||
setCtime: (state, action: PayloadAction<number | null | undefined>) => {
|
||||
state.ctime = action.payload
|
||||
},
|
||||
setAuthor: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.author = action.payload
|
||||
},
|
||||
setInfos: (state, action: PayloadAction<any[]>) => {
|
||||
state.infos = action.payload
|
||||
},
|
||||
@@ -342,6 +349,8 @@ export const {
|
||||
addAskInfo,
|
||||
delAskInfo,
|
||||
mergeAskInfo,
|
||||
setCtime,
|
||||
setAuthor,
|
||||
} = slice.actions
|
||||
|
||||
export default slice.reducer
|
||||
|
13
src/typings.d.ts
vendored
13
src/typings.d.ts
vendored
@@ -7,7 +7,7 @@ interface MethodContext {
|
||||
|
||||
interface EnvData {
|
||||
sidePanel?: boolean
|
||||
manualInsert?: boolean //是否手动插入字幕列表
|
||||
manualInsert?: boolean // 是否手动插入字幕列表
|
||||
autoExpand?: boolean
|
||||
flagDot?: boolean
|
||||
|
||||
@@ -151,4 +151,13 @@ interface BriefSummary extends Summary {
|
||||
}
|
||||
|
||||
type SummaryStatus = 'init' | 'pending' | 'done'
|
||||
type SummaryType = 'overview' | 'keypoint' | 'brief' | 'question'
|
||||
type SummaryType = 'overview' | 'keypoint' | 'brief' | 'question' | 'debate'
|
||||
|
||||
interface DebateMessage {
|
||||
side: 'pro' | 'con'
|
||||
content: string
|
||||
}
|
||||
|
||||
interface DebateProps {
|
||||
messages: DebateMessage[]
|
||||
}
|
||||
|
@@ -81,6 +81,9 @@ export const isSummaryEmpty = (summary: Summary) => {
|
||||
} else if (summary.type === 'question') {
|
||||
const content: any[] = summary.content??[]
|
||||
return content.length === 0
|
||||
} else if (summary.type === 'debate') {
|
||||
const content: Array<{ side: string, content: string }> = summary.content ?? []
|
||||
return content.length === 0
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -107,6 +110,11 @@ export const getSummaryStr = (summary: Summary) => {
|
||||
s += content.map(item => {
|
||||
return item.q + '\n' + item.a + '\n'
|
||||
}).join('\n')
|
||||
} else if (summary.type === 'debate') {
|
||||
const content: Array<{ side: string, content: string }> = summary.content ?? []
|
||||
s += content.map(item => {
|
||||
return (item.side === 'pro'?'正方:':'反方:') + item.content + '\n'
|
||||
}).join('\n')
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
@@ -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'))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@@ -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) => {
|
||||
|
@@ -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'),
|
||||
|
Reference in New Issue
Block a user