67 Commits

Author SHA1 Message Date
IndieKKY
e4693cde6a chore: release 1.13.1 2025-06-02 09:31:24 +08:00
IndieKKY
fea22fae61 优化性能 2025-06-02 09:26:38 +08:00
IndieKKY
d5b5b5d374 优化性能 2025-06-02 09:18:02 +08:00
IndieKKY
17d4e60de0 chore: release 1.13.0 2025-05-05 23:14:46 +08:00
IndieKKY
2cd633cbd4 由于gemini兼容了openai格式,因此去除了专门的gemini选项,简化代码 2025-05-05 23:13:07 +08:00
IndieKKY
3ad198948f gemini优化 2025-05-05 22:43:00 +08:00
IndieKKY
774cc2726d Merge branch 'refs/heads/vector090/master' 2025-05-05 22:30:00 +08:00
IndieKKY
4765244638 Merge pull request #77 from 2-3-5-7/feature/time-format-enhancement
feat(时间): 支持 HH:MM:SS 格式的解析与格式化
2025-05-05 17:00:03 +08:00
2-3-5-7
b0107c4959 feat(时间): 支持 HH:MM:SS 格式的解析与格式化
改进 parseStrTimeToSeconds 以处理 MM:SS 和 HH:MM:SS 输入。更新 formatTime 以在存在小时的情况下输出 HH:MM:SS 格式。
2025-05-04 16:28:07 +08:00
user
e900b11f05 fix building under linux 2025-04-30 05:04:13 +00:00
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
IndieKKY
fa66445466 chore: release 1.11.8 2024-10-12 14:01:32 +08:00
IndieKKY
d711b2abf8 bibigpt 2024-10-12 14:01:16 +08:00
IndieKKY
47fcb1de11 bibigpt 2024-10-12 14:01:07 +08:00
IndieKKY
be3d3624bc chore: release 1.11.7 2024-10-10 11:24:18 +08:00
IndieKKY
910b1ce6d9 优化描述 2024-10-10 11:23:23 +08:00
IndieKKY
0a6bda667e chore: release 1.11.6 2024-10-10 11:21:23 +08:00
IndieKKY
5a0a123af9 优化导出 2024-10-10 09:23:42 +08:00
IndieKKY
b481b8a55a chore: release 1.11.5 2024-10-09 20:17:33 +08:00
IndieKKY
3cede8650d 增加总结:辩论 2024-10-09 20:17:08 +08:00
IndieKKY
69e0497081 chore: release 1.11.4 2024-10-09 08:36:01 +08:00
IndieKKY
8776186486 添加官网链接 2024-10-08 19:27:24 +08:00
IndieKKY
d31c2d7b03 chore: release 1.11.3 2024-10-07 19:10:54 +08:00
IndieKKY
1c5534fc82 fix 2024-10-07 19:10:39 +08:00
IndieKKY
44895a98a6 chore: release 1.11.2 2024-10-07 18:59:16 +08:00
IndieKKY
53d3522fd6 完善 2024-10-07 18:56:39 +08:00
IndieKKY
56bb936aaa 哔哔君 2024-10-07 18:15:20 +08:00
IndieKKY
d52a4e8378 fix 2024-10-07 09:43:38 +08:00
IndieKKY
f69bc7f040 优化 2024-10-07 09:36:48 +08:00
IndieKKY
5005806917 chore: release 1.11.1 2024-10-06 19:55:04 +08:00
IndieKKY
6928b5fa00 fix 2024-10-06 19:54:40 +08:00
IndieKKY
5ba2b9fd6d 优化 2024-10-06 19:22:01 +08:00
IndieKKY
d11b517d5e 优化 2024-10-06 19:18:42 +08:00
IndieKKY
2460b0b822 优化 2024-10-06 19:16:22 +08:00
IndieKKY
9bcf6ee48d 优化 2024-10-06 18:59:21 +08:00
IndieKKY
2bb5f41189 优化 2024-10-06 18:55:41 +08:00
IndieKKY
e5a645611b 优化 2024-10-06 18:48:52 +08:00
IndieKKY
97bd23bcc0 优化 2024-10-06 18:42:27 +08:00
IndieKKY
02aaba6a83 优化 2024-10-06 18:41:12 +08:00
IndieKKY
3e1e69f13e 优化 2024-10-06 18:36:23 +08:00
IndieKKY
9384c1419a 优化 2024-10-06 18:28:20 +08:00
IndieKKY
50e6579116 fix 2024-10-06 17:51:07 +08:00
IndieKKY
751961687b tmp 2024-10-06 17:42:15 +08:00
IndieKKY
5ce146803e 优化 2024-10-06 16:04:02 +08:00
67 changed files with 832 additions and 1058 deletions

View File

@@ -1,3 +1 @@
VITE_ENV=web-dev VITE_ENV=web-dev
VITE_EXTENSION_ID=nejipfbcnfhckfpmlgibfommbnahchko

View File

@@ -1,4 +1,3 @@
NODE_ENV=production NODE_ENV=production
VITE_ENV=chrome VITE_ENV=chrome
VITE_EXTENSION_ID=bciglihaegkdhoogebcdblfhppoilclp

View File

@@ -4,3 +4,4 @@ node_modules/
postcss.config.cjs postcss.config.cjs
vite.config.ts vite.config.ts
vite-env.d.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-empty-interface": "warn",
"@typescript-eslint/no-unused-vars": "warn", "@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/strict-boolean-expressions": "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/object-curly-spacing": "off",
"@typescript-eslint/no-misused-promises": "off", "@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/space-infix-ops": "off", "@typescript-eslint/space-infix-ops": "off",
"@typescript-eslint/no-floating-promises": "off",
"operator-linebreak": "off", "operator-linebreak": "off",
"@typescript-eslint/space-before-function-paren": "off", "@typescript-eslint/space-before-function-paren": "off",
"@typescript-eslint/comma-dangle": "off" "@typescript-eslint/comma-dangle": "off"

View File

@@ -21,7 +21,6 @@
- [chrome商店](https://chrome.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp) - [chrome商店](https://chrome.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp)
- [edge商店](https://microsoftedge.microsoft.com/addons/detail/lignnlhlpiefmcjkdkmfjdckhlaiajan) - [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 node版本18.15.0
包管理器pnpm 包管理器pnpm
- 本地调试:`pnpm run dev`,然后加载`dist`目录。 - 本地调试:`pnpm run dev`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
- 打生产包:`pnpm run build`,然后加载`dist`目录。 - 打生产包:`pnpm run build`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
注:`./push.sh`是作者自用脚本,可以忽略。 注:`./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的这个操作。
## 贡献指南 ## 贡献指南
欢迎贡献代码或提出改进建议!如果您希望为该项目做出贡献,请遵循以下步骤: 欢迎贡献代码或提出改进建议!如果您希望为该项目做出贡献,请遵循以下步骤:
@@ -65,7 +68,3 @@ node版本18.15.0
## 许可证 ## 许可证
该项目采用 **MIT 许可证**,详情请参阅许可证文件。 该项目采用 **MIT 许可证**,详情请参阅许可证文件。
## 截图
![完整截图](./screenshot/完整截图.png)

View File

@@ -5,4 +5,11 @@ const fs = require('fs')
//copy index.html to sidepanel.html //copy index.html to sidepanel.html
fs.copyFileSync('./dist/index.html', './dist/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'); console.log('fix.js done');

View File

@@ -1,7 +1,7 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="zh" data-theme="light"> <html lang="zh" data-theme="light">
<head> <head>
<title>bilibili-subtitle - 哔哩哔哩字幕</title> <title>哔哔君 - 哔哩哔哩字幕列表</title>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="icon" href="/favicon-128x128.png" sizes="128x128"> <link rel="icon" href="/favicon-128x128.png" sizes="128x128">

View File

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

View File

@@ -1,7 +1,7 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" data-theme="light"> <html lang="en" data-theme="light">
<head> <head>
<title>哔哩哔哩字幕列表选项</title> <title>哔君 - 哔哩哔哩字幕列表选项</title>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="icon" href="/favicon-16x16.png" sizes="16x16"> <link rel="icon" href="/favicon-16x16.png" sizes="16x16">

View File

@@ -1,7 +1,7 @@
{ {
"private": true, "private": true,
"name": "bilibili-subtitle", "name": "bilibili-subtitle",
"version": "1.11.0", "version": "1.13.1",
"type": "module", "type": "module",
"description": "哔哩哔哩字幕列表", "description": "哔哩哔哩字幕列表",
"main": "index.js", "main": "index.js",
@@ -15,6 +15,7 @@
"dependencies": { "dependencies": {
"@crxjs/vite-plugin": "^1.0.14", "@crxjs/vite-plugin": "^1.0.14",
"@kky002/kky-hooks": "^1.2.1", "@kky002/kky-hooks": "^1.2.1",
"@kky002/kky-message": "^0.2.1",
"@kky002/kky-ui": "^1.0.9", "@kky002/kky-ui": "^1.0.9",
"@kky002/kky-util": "^1.13.13", "@kky002/kky-util": "^1.13.13",
"@logto/react": "1.0.0-beta.13", "@logto/react": "1.0.0-beta.13",
@@ -24,6 +25,7 @@
"ahooks": "^3.7.1", "ahooks": "^3.7.1",
"classnames": "^2.3.2", "classnames": "^2.3.2",
"daisyui": "^2.42.1", "daisyui": "^2.42.1",
"dayjs": "^1.11.13",
"js-search": "^2.0.0", "js-search": "^2.0.0",
"less": "^4.1.3", "less": "^4.1.3",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",

70
pnpm-lock.yaml generated
View File

@@ -14,6 +14,9 @@ importers:
'@kky002/kky-hooks': '@kky002/kky-hooks':
specifier: ^1.2.1 specifier: ^1.2.1
version: 1.2.1 version: 1.2.1
'@kky002/kky-message':
specifier: ^0.2.1
version: 0.2.1
'@kky002/kky-ui': '@kky002/kky-ui':
specifier: ^1.0.9 specifier: ^1.0.9
version: 1.0.9 version: 1.0.9
@@ -41,6 +44,9 @@ importers:
daisyui: daisyui:
specifier: ^2.42.1 specifier: ^2.42.1
version: 2.42.1(autoprefixer@10.4.13(postcss@8.4.19))(postcss@8.4.19) 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: js-search:
specifier: ^2.0.0 specifier: ^2.0.0
version: 2.0.0 version: 2.0.0
@@ -307,6 +313,10 @@ packages:
resolution: {integrity: sha512-eR8Lo9hnDS7tqkO7NsV+mKvCmv5boaXFSZ70DnfhcgiEne8hv9oCEd36Klw74EtizEqLsy4YnW8UWwpBVolHZA==} resolution: {integrity: sha512-eR8Lo9hnDS7tqkO7NsV+mKvCmv5boaXFSZ70DnfhcgiEne8hv9oCEd36Klw74EtizEqLsy4YnW8UWwpBVolHZA==}
engines: {node: '>=6.9.0'} 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': '@babel/template@7.25.7':
resolution: {integrity: sha512-wRwtAgI3bAS+JGU2upWNL9lSlDcRCqD05BZ1n3X2ONLH1WilFP6O1otQjeMK/1g0pvYcXC7b/qVUB1keofjtZA==} resolution: {integrity: sha512-wRwtAgI3bAS+JGU2upWNL9lSlDcRCqD05BZ1n3X2ONLH1WilFP6O1otQjeMK/1g0pvYcXC7b/qVUB1keofjtZA==}
engines: {node: '>=6.9.0'} engines: {node: '>=6.9.0'}
@@ -387,6 +397,9 @@ packages:
'@kky002/kky-hooks@1.2.1': '@kky002/kky-hooks@1.2.1':
resolution: {integrity: sha512-AJM2gm75TtkZqOPd/WX0+4h/dfjSb8HlDQLwAJsYIHRNw8MQUKu32Ih6OxhKL2l9pdPsuj+S9/lBc4Cwu4tP+Q==} 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': '@kky002/kky-ui@1.0.9':
resolution: {integrity: sha512-pepfRcLfC1eIQ1lsSJLWNr4PgdLqFLuvQMlitJy7W668yZ7qu8yAHSjg8A20R7HB4mFkJ+B96WETalOar1e/kA==} resolution: {integrity: sha512-pepfRcLfC1eIQ1lsSJLWNr4PgdLqFLuvQMlitJy7W668yZ7qu8yAHSjg8A20R7HB4mFkJ+B96WETalOar1e/kA==}
@@ -651,6 +664,12 @@ packages:
peerDependencies: peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 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: ajv@6.12.6:
resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==}
@@ -856,8 +875,8 @@ packages:
autoprefixer: ^10.0.2 autoprefixer: ^10.0.2
postcss: ^8.1.6 postcss: ^8.1.6
dayjs@1.11.5: dayjs@1.11.13:
resolution: {integrity: sha512-CAdX5Q3YW3Gclyo5Vpqkgpj8fSdLQcRuzfX6mC6Phy0nfJ0eGYOeS7m4mt2plDWLAtA4TqTakvbboHvUxfe4iA==} resolution: {integrity: sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==}
debug@2.6.9: debug@2.6.9:
resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==}
@@ -1557,6 +1576,10 @@ packages:
js-cookie@2.2.1: js-cookie@2.2.1:
resolution: {integrity: sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ==} 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: js-search@2.0.0:
resolution: {integrity: sha512-lJ8KzjlwcelIWuAdKyzsXv45W6OIwRpayzc7XmU8mzgWadg5UVOKVmnq/tXudddEB9Ceic3tVaGu6QOK/eebhg==} resolution: {integrity: sha512-lJ8KzjlwcelIWuAdKyzsXv45W6OIwRpayzc7XmU8mzgWadg5UVOKVmnq/tXudddEB9Ceic3tVaGu6QOK/eebhg==}
@@ -2045,6 +2068,9 @@ packages:
react-fast-compare@3.2.0: react-fast-compare@3.2.0:
resolution: {integrity: sha512-rtGImPZ0YyLrscKI9xTpV8psd6I8VAtjKCzQDlzyDvqJA8XOW78TXYQwNRNd8g8JZnDu8q9Fu/1v4HPAVwVdHA==} 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: react-hot-toast@2.4.0:
resolution: {integrity: sha512-qnnVbXropKuwUpriVVosgo8QrB+IaPJCpL8oBI6Ov84uvHZ5QQcTp2qg6ku2wNfgJl6rlQXJIQU5q+5lmPOutA==} resolution: {integrity: sha512-qnnVbXropKuwUpriVVosgo8QrB+IaPJCpL8oBI6Ov84uvHZ5QQcTp2qg6ku2wNfgJl6rlQXJIQU5q+5lmPOutA==}
engines: {node: '>=10'} engines: {node: '>=10'}
@@ -2132,6 +2158,9 @@ packages:
regenerator-runtime@0.13.9: regenerator-runtime@0.13.9:
resolution: {integrity: sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==} 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: regexp.prototype.flags@1.4.3:
resolution: {integrity: sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==} resolution: {integrity: sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@@ -2693,6 +2722,10 @@ snapshots:
dependencies: dependencies:
regenerator-runtime: 0.13.9 regenerator-runtime: 0.13.9
'@babel/runtime@7.26.9':
dependencies:
regenerator-runtime: 0.14.1
'@babel/template@7.25.7': '@babel/template@7.25.7':
dependencies: dependencies:
'@babel/code-frame': 7.25.7 '@babel/code-frame': 7.25.7
@@ -2813,6 +2846,14 @@ snapshots:
lodash-es: 4.17.21 lodash-es: 4.17.21
react: 18.2.0 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': '@kky002/kky-ui@1.0.9':
dependencies: dependencies:
react: 18.2.0 react: 18.2.0
@@ -3114,7 +3155,7 @@ snapshots:
dependencies: dependencies:
'@types/js-cookie': 2.2.7 '@types/js-cookie': 2.2.7
ahooks-v3-count: 1.0.0 ahooks-v3-count: 1.0.0
dayjs: 1.11.5 dayjs: 1.11.13
intersection-observer: 0.12.2 intersection-observer: 0.12.2
js-cookie: 2.2.1 js-cookie: 2.2.1
lodash: 4.17.21 lodash: 4.17.21
@@ -3126,7 +3167,7 @@ snapshots:
dependencies: dependencies:
'@types/js-cookie': 2.2.7 '@types/js-cookie': 2.2.7
ahooks-v3-count: 1.0.0 ahooks-v3-count: 1.0.0
dayjs: 1.11.5 dayjs: 1.11.13
intersection-observer: 0.12.2 intersection-observer: 0.12.2
js-cookie: 2.2.1 js-cookie: 2.2.1
lodash: 4.17.21 lodash: 4.17.21
@@ -3135,6 +3176,19 @@ snapshots:
screenfull: 5.2.0 screenfull: 5.2.0
tslib: 2.5.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: ajv@6.12.6:
dependencies: dependencies:
fast-deep-equal: 3.1.3 fast-deep-equal: 3.1.3
@@ -3385,7 +3439,7 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- ts-node - ts-node
dayjs@1.11.5: {} dayjs@1.11.13: {}
debug@2.6.9: debug@2.6.9:
dependencies: dependencies:
@@ -4073,6 +4127,8 @@ snapshots:
js-cookie@2.2.1: {} js-cookie@2.2.1: {}
js-cookie@3.0.5: {}
js-search@2.0.0: {} js-search@2.0.0: {}
js-tokens@4.0.0: {} js-tokens@4.0.0: {}
@@ -4695,6 +4751,8 @@ snapshots:
react-fast-compare@3.2.0: {} 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): react-hot-toast@2.4.0(csstype@3.1.2)(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
dependencies: dependencies:
goober: 2.1.12(csstype@3.1.2) goober: 2.1.12(csstype@3.1.2)
@@ -4787,6 +4845,8 @@ snapshots:
regenerator-runtime@0.13.9: {} regenerator-runtime@0.13.9: {}
regenerator-runtime@0.14.1: {}
regexp.prototype.flags@1.4.3: regexp.prototype.flags@1.4.3:
dependencies: dependencies:
call-bind: 1.0.2 call-bind: 1.0.2

View File

@@ -1,11 +0,0 @@
<!DOCTYPE html>
<html lang="zh" style="width: 500px;">
<head>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<img src="shot.jpg" style="width: 100%; object-fit: contain;"/>
</body>
</html>

View File

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

BIN
public/bibigpt.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
public/bibijun.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 278 B

After

Width:  |  Height:  |  Size: 651 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 363 B

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 400 B

After

Width:  |  Height:  |  Size: 2.4 KiB

BIN
public/favicon-64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 447 B

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

View File

@@ -1,3 +0,0 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg t="1672795365953" class="icon" viewBox="0 0 1303 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2585"
width="254.4921875" height="200"><path d="M110.964364 1023.720727c-60.509091 0-109.847273-48.872727-109.847273-108.916363V109.009455C1.117091 48.965818 50.455273 0 110.964364 0h1081.902545c60.509091 0 109.847273 48.872727 109.847273 108.916364v805.794909c0 60.043636-49.338182 108.916364-109.847273 108.916363H110.964364z m0-927.650909c-6.609455 0-12.101818 5.771636-12.101819 12.939637v805.794909c0 7.168 5.492364 13.032727 12.101819 13.032727h1081.902545c6.609455 0 12.101818-5.864727 12.101818-13.032727V109.009455c0-7.168-5.492364-13.032727-12.101818-13.032728H110.964364z" fill="#00AEEC" p-id="2586"></path><path d="M1003.054545 520.098909a51.572364 51.572364 0 0 1-50.26909 52.689455h-80.058182a51.572364 51.572364 0 0 1-50.269091-52.689455c0-29.137455 22.434909-52.782545 50.269091-52.782545h80.058182c27.834182 0 50.269091 23.645091 50.26909 52.782545zM1096.610909 270.149818c0 28.858182-22.341818 52.410182-49.989818 52.410182H232.541091a51.293091 51.293091 0 0 1-50.082909-52.410182c0-29.044364 22.434909-52.503273 50.082909-52.503273h814.08c27.648 0 50.082909 23.458909 50.082909 52.503273zM768.744727 520.098909c0 28.858182-22.341818 52.410182-50.082909 52.410182H232.541091a51.293091 51.293091 0 0 1-50.082909-52.410182c0-29.044364 22.434909-52.503273 50.082909-52.503273H718.661818c27.648 0 50.082909 23.458909 50.082909 52.503273zM1096.610909 735.976727c0 29.044364-22.341818 52.503273-49.989818 52.503273H560.500364a51.293091 51.293091 0 0 1-50.082909-52.503273c0-28.951273 22.341818-52.410182 50.082909-52.410182h486.120727c27.648 0 50.082909 23.458909 50.082909 52.410182z" fill="#00AEEC" p-id="2587"></path></svg>

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 867 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 333 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 413 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 280 KiB

View File

@@ -1,7 +1,7 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="zh" data-theme="light"> <html lang="zh" data-theme="light">
<head> <head>
<title>哔哩哔哩字幕列表</title> <title>哔君 - 哔哩哔哩字幕列表</title>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="icon" href="/favicon-128x128.png" sizes="128x128"> <link rel="icon" href="/favicon-128x128.png" sizes="128x128">

View File

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

View File

@@ -4,7 +4,7 @@ import './index.less'
import store from './store' import store from './store'
import {Provider} from 'react-redux' import {Provider} from 'react-redux'
import Router from './Router' import Router from './Router'
import {APP_DOM_ID} from './consts/const' import { APP_DOM_ID } from './consts/const'
const body = document.querySelector('body') const body = document.querySelector('body')
const app = document.createElement('div') const app = document.createElement('div')

View File

@@ -1,8 +1,8 @@
import {v4} from 'uuid' import {v4} from 'uuid'
import {handleTask, initTaskService, tasksMap} from './taskService' import {handleTask, initTaskService, tasksMap} from './taskService'
import { MESSAGE_TO_EXTENSION_ADD_TASK, MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL, MESSAGE_TO_EXTENSION_GET_TASK, MESSAGE_TO_EXTENSION_SHOW_FLAG, MESSAGE_TO_INJECT_TOGGLE_DISPLAY, STORAGE_ENV} from '@/consts/const' import { DEFAULT_USE_PORT, STORAGE_ENV} from '@/consts/const'
import ExtensionMessaging from '@/messaging/layer2/ExtensionMessaging' import { AllExtensionMessages } from '@/message-typings'
import { TAG_TARGET_INJECT } from '@/messaging/const' import { ExtensionMessaging, TAG_TARGET_INJECT } from '@kky002/kky-message'
const setBadgeOk = async (tabId: number, ok: boolean) => { const setBadgeOk = async (tabId: number, ok: boolean) => {
await chrome.action.setBadgeText({ await chrome.action.setBadgeText({
@@ -29,12 +29,15 @@ const closeSidePanel = async () => {
} }
const methods: { const methods: {
[key: string]: (params: any, context: MethodContext) => Promise<any> [K in AllExtensionMessages['method']]: (params: Extract<AllExtensionMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
} = { } = {
[MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL]: async (params, context) => { CLOSE_SIDE_PANEL: async (params, context) => {
closeSidePanel() closeSidePanel()
}, },
[MESSAGE_TO_EXTENSION_ADD_TASK]: async (params, context) => { GET_TAB_ID: async (params, context) => {
return context.tabId
},
ADD_TASK: async (params, context) => {
// 新建任务 // 新建任务
const task: Task = { const task: Task = {
id: v4(), id: v4(),
@@ -49,7 +52,7 @@ const methods: {
return task return task
}, },
[MESSAGE_TO_EXTENSION_GET_TASK]: async (params, context) => { GET_TASK: async (params, context) => {
// 返回任务信息 // 返回任务信息
const taskId = params.taskId const taskId = params.taskId
const task = tasksMap.get(taskId) const task = tasksMap.get(taskId)
@@ -70,15 +73,15 @@ const methods: {
task, task,
} }
}, },
[MESSAGE_TO_EXTENSION_SHOW_FLAG]: async (params, context) => { SHOW_FLAG: async (params, context) => {
await setBadgeOk(context.tabId!, params.show) await setBadgeOk(context.tabId!, params.show)
}, },
} }
// 初始化backgroundMessage // 初始化backgroundMessage
const extensionMessaging = new ExtensionMessaging() const extensionMessaging = new ExtensionMessaging(DEFAULT_USE_PORT)
extensionMessaging.init(methods) extensionMessaging.init(methods)
chrome.runtime.onMessage.addListener((event: MessageData, sender: chrome.runtime.MessageSender, sendResponse: (result: any) => void) => { chrome.runtime.onMessage.addListener((event: any, sender: chrome.runtime.MessageSender, sendResponse: (result: any) => void) => {
// debug((sender.tab != null) ? `tab ${sender.tab.url ?? ''} => ` : 'extension => ', event) // debug((sender.tab != null) ? `tab ${sender.tab.url ?? ''} => ` : 'extension => ', event)
// legacy // legacy
@@ -89,14 +92,12 @@ chrome.runtime.onMessage.addListener((event: MessageData, sender: chrome.runtime
return true return true
} else if (event.type === 'syncSet') { // sync.set } else if (event.type === 'syncSet') { // sync.set
chrome.storage.sync.set(event.items).catch(console.error) chrome.storage.sync.set(event.items).catch(console.error)
return
} else if (event.type === 'syncRemove') { // sync.remove } else if (event.type === 'syncRemove') { // sync.remove
chrome.storage.sync.remove(event.keys).catch(console.error) chrome.storage.sync.remove(event.keys).catch(console.error)
return
} }
}) })
//点击扩展图标 // 点击扩展图标
chrome.action.onClicked.addListener(async (tab) => { chrome.action.onClicked.addListener(async (tab) => {
chrome.storage.sync.get(STORAGE_ENV, (envDatas) => { chrome.storage.sync.get(STORAGE_ENV, (envDatas) => {
const envDataStr = envDatas[STORAGE_ENV] const envDataStr = envDatas[STORAGE_ENV]
@@ -115,7 +116,7 @@ chrome.action.onClicked.addListener(async (tab) => {
}) })
} else { } else {
closeSidePanel() closeSidePanel()
extensionMessaging.broadcastMessageExact([tab.id!], [TAG_TARGET_INJECT], MESSAGE_TO_INJECT_TOGGLE_DISPLAY).catch(console.error) extensionMessaging.sendMessage(false, tab.id!, TAG_TARGET_INJECT, 'TOGGLE_DISPLAY').catch(console.error)
} }
}) })
}) })

View File

@@ -7,13 +7,21 @@ const getServerUrl = (serverUrl?: string) => {
if (serverUrl.endsWith('/')) { if (serverUrl.endsWith('/')) {
serverUrl = serverUrl.slice(0, -1) serverUrl = serverUrl.slice(0, -1)
} }
//如果serverUrl以https://generativelanguage.googleapis.com开头则直接返回
if (serverUrl.toLowerCase().startsWith('https://generativelanguage.googleapis.com')) {
return serverUrl
}
//如果serverUrl不以/vxxx结尾则添加/v1
if (!/\/v\d+$/.test(serverUrl.toLowerCase())) {
serverUrl += '/v1'
}
return serverUrl return serverUrl
} }
export const handleChatCompleteTask = async (task: Task) => { export const handleChatCompleteTask = async (task: Task) => {
const data = task.def.data const data = task.def.data
const serverUrl = getServerUrl(task.def.serverUrl) const serverUrl = getServerUrl(task.def.serverUrl)
const resp = await fetch(`${serverUrl}/v1/chat/completions`, { const resp = await fetch(`${serverUrl}/chat/completions`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -28,16 +36,3 @@ export const handleChatCompleteTask = async (task: Task) => {
throw new Error(`${task.resp.error.code as string??''} ${task.resp.error.message as string ??''}`) throw new Error(`${task.resp.error.code as string??''} ${task.resp.error.message as string ??''}`)
} }
} }
export const handleGeminiChatCompleteTask = async (task: Task) => {
const data = task.def.data
const resp = await fetch('https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': task.def.extra.geminiApiKey,
},
body: JSON.stringify(data),
})
task.resp = await resp.json()
}

View File

@@ -1,5 +1,5 @@
import {TASK_EXPIRE_TIME} from '../consts/const' import {TASK_EXPIRE_TIME} from '../consts/const'
import {handleChatCompleteTask, handleGeminiChatCompleteTask} from './openaiService' import {handleChatCompleteTask} from './openaiService'
export const tasksMap = new Map<string, Task>() export const tasksMap = new Map<string, Task>()
@@ -11,9 +11,6 @@ export const handleTask = async (task: Task) => {
case 'chatComplete': case 'chatComplete':
await handleChatCompleteTask(task) await handleChatCompleteTask(task)
break break
case 'geminiChatComplete':
await handleGeminiChatCompleteTask(task)
break
default: default:
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`任务类型不支持: ${task.def.type}`) throw new Error(`任务类型不支持: ${task.def.type}`)

View File

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

View File

@@ -18,7 +18,7 @@ const Ask = (props: {
const {addAskTask} = useTranslate() const {addAskTask} = useTranslate()
const onRegenerate = useCallback(() => { const onRegenerate = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey const apiKey = envData.apiKey
if (apiKey) { if (apiKey) {
if (segments != null && segments.length > 0) { if (segments != null && segments.length > 0) {
addAskTask(ask.id, segments[0], ask.question).catch(console.error) addAskTask(ask.id, segments[0], ask.question).catch(console.error)
@@ -26,7 +26,7 @@ const Ask = (props: {
} else { } else {
toast.error('请先在选项页面设置ApiKey!') toast.error('请先在选项页面设置ApiKey!')
} }
}, [addAskTask, ask.id, ask.question, envData.aiType, envData.apiKey, envData.geminiApiKey, segments]) }, [addAskTask, ask.id, ask.question, envData.apiKey, segments])
const onAskFold = useCallback(() => { const onAskFold = useCallback(() => {
dispatch(mergeAskInfo({ dispatch(mergeAskInfo({

View File

@@ -25,6 +25,7 @@ import toast from 'react-hot-toast'
import SegmentCard from './SegmentCard' import SegmentCard from './SegmentCard'
import { import {
ASK_ENABLED_DEFAULT, ASK_ENABLED_DEFAULT,
DEFAULT_USE_PORT,
HEADER_HEIGHT, HEADER_HEIGHT,
PAGE_SETTINGS, PAGE_SETTINGS,
SEARCH_BAR_HEIGHT, SEARCH_BAR_HEIGHT,
@@ -39,6 +40,7 @@ import Ask from './Ask'
import { v4 } from 'uuid' import { v4 } from 'uuid'
import RateExtension from '../components/RateExtension' import RateExtension from '../components/RateExtension'
import ApiKeyReminder from './ApiKeyReminder' import ApiKeyReminder from './ApiKeyReminder'
import { useMessaging } from '@kky002/kky-message'
const Body = () => { const Body = () => {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
@@ -65,6 +67,7 @@ const Body = () => {
// const fontSize = useAppSelector(state => state.env.envData.fontSize) // const fontSize = useAppSelector(state => state.env.envData.fontSize)
const searchText = useAppSelector(state => state.env.searchText) const searchText = useAppSelector(state => state.env.searchText)
const asks = useAppSelector(state => state.env.asks) const asks = useAppSelector(state => state.env.asks)
const {disconnected} = useMessaging(DEFAULT_USE_PORT)
// const recommendIdx = useMemo(() => random(0, 3), []) // const recommendIdx = useMemo(() => random(0, 3), [])
const showSearchInput = useMemo(() => { const showSearchInput = useMemo(() => {
return (segments != null && segments.length > 0) && (envData.searchEnabled ? envData.searchEnabled : (envData.askEnabled ?? ASK_ENABLED_DEFAULT)) return (segments != null && segments.length > 0) && (envData.searchEnabled ? envData.searchEnabled : (envData.askEnabled ?? ASK_ENABLED_DEFAULT))
@@ -102,7 +105,7 @@ const Body = () => {
}, [dispatch]) }, [dispatch])
const onSummarizeAll = useCallback(() => { const onSummarizeAll = useCallback(() => {
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey const apiKey = envData.apiKey
if (!apiKey) { if (!apiKey) {
toast.error('请先在选项页面设置ApiKey!') toast.error('请先在选项页面设置ApiKey!')
return return
@@ -124,7 +127,7 @@ const Body = () => {
} }
toast.success(`已添加${segments_.length}个总结任务!`) toast.success(`已添加${segments_.length}个总结任务!`)
} }
}, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segments]) }, [addSummarizeTask, curSummaryType, envData.apiKey, segments])
const onFoldAll = useCallback(() => { const onFoldAll = useCallback(() => {
dispatch(setFoldAll(!foldAll)) dispatch(setFoldAll(!foldAll))
@@ -143,13 +146,13 @@ const Body = () => {
}, [asks, dispatch, foldAll, segments]) }, [asks, dispatch, foldAll, segments])
const toggleAutoTranslateCallback = useCallback(() => { const toggleAutoTranslateCallback = useCallback(() => {
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey const apiKey = envData.apiKey
if (apiKey) { if (apiKey) {
dispatch(setAutoTranslate(!autoTranslate)) dispatch(setAutoTranslate(!autoTranslate))
} else { } else {
toast.error('请先在选项页面设置ApiKey!') toast.error('请先在选项页面设置ApiKey!')
} }
}, [autoTranslate, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey]) }, [autoTranslate, dispatch, envData.apiKey])
const onEnableAutoScroll = useCallback(() => { const onEnableAutoScroll = useCallback(() => {
dispatch(setAutoScroll(true)) dispatch(setAutoScroll(true))
@@ -182,7 +185,7 @@ const Body = () => {
const onAsk = useCallback(() => { const onAsk = useCallback(() => {
if ((envData.askEnabled ?? ASK_ENABLED_DEFAULT) && searchText) { if ((envData.askEnabled ?? ASK_ENABLED_DEFAULT) && searchText) {
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey const apiKey = envData.apiKey
if (apiKey) { if (apiKey) {
if (segments != null && segments.length > 0) { if (segments != null && segments.length > 0) {
const id = v4() const id = v4()
@@ -198,7 +201,7 @@ const Body = () => {
toast.error('请先在选项页面设置ApiKey!') toast.error('请先在选项页面设置ApiKey!')
} }
} }
}, [addAskTask, dispatch, envData.aiType, envData.apiKey, envData.askEnabled, envData.geminiApiKey, searchText, segments]) }, [addAskTask, dispatch, envData.apiKey, envData.askEnabled, searchText, segments])
// service // service
useKeyService() useKeyService()
@@ -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>} {searchText && <button className='absolute top-1 right-2 btn btn-ghost btn-xs btn-circle text-base-content/75' onClick={onClearSearchText}><AiOutlineCloseCircle /></button>}
</div>} </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 */} {/* auto scroll btn */}
{!autoScroll && <div {!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' 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>} */} {/* </button>} */}
{/* </div> */} {/* </div> */}
<div className='flex flex-col'> <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='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' */} <div className='font-semibold text-accent flex items-center gap-1'><img src='/bibigpt.png'
{/* alt='BibiGPT logo' */} alt='BibiGPT logo'
{/* className='w-8 h-8'/>BibiGPT */} className='w-8 h-8'/>BibiGPT
{/* </div> */} </div>
{/* <div className='text-sm px-2 desc'>这是<span className='text-amber-600 font-semibold text-base'>网页</span>版的字幕列表,支持<span */} <div className='text-sm px-2 desc'><span className='text-amber-600 font-semibold text-base'></span><span
{/* className='font-semibold'>任意</span>视频提取字幕总结(包括没有字幕的视频) */} className='font-semibold'></span>
{/* </div> */} </div>
{/* <div className='flex gap-2'> */} <div className='flex gap-2'>
{/* <a title='BibiGPT' href='https://bibigpt.co/r/bilibili' */} <a title='BibiGPT' href='https://bibigpt.co/r/bilibili'
{/* onClick={(e) => { */} onClick={(e) => {
{/* e.preventDefault() */} e.preventDefault()
{/* openUrl('https://bibigpt.co/r/bilibili') */} openUrl('https://bibigpt.co/r/bilibili')
{/* }} className='link text-sm text-accent'>✨ BibiGPT ✨</a> */} }} className='link text-sm text-accent'> BibiGPT </a>
{/* </div> */} </div>
{/* </div> */} </div>
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'> <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' <div className='font-semibold text-accent flex items-center gap-1'><img src='/youtube-caption.png'
alt='youtube caption logo' alt='youtube caption logo'
@@ -415,4 +422,4 @@ const Body = () => {
</div> </div>
} }
export default Body export default Body

View 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

View File

@@ -83,6 +83,7 @@ const Header = (props: {
} }
}}> }}>
<div className='shrink-0 flex items-center'> <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-[16px] pr-[14px]'></span> <span className='shrink-0 text-[15px] font-medium pl-[16px] pr-[14px]'></span>
<MoreBtn placement={'right-start'}/> <MoreBtn placement={'right-start'}/>
</div> </div>

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 {useClickAway} from 'ahooks'
import { import {
AiFillWechat,
BsFillChatDotsFill,
FiMoreVertical, FiMoreVertical,
ImDownload3, ImDownload3,
IoMdSettings, IoMdSettings,
@@ -13,12 +11,14 @@ import {Placement} from '@popperjs/core/lib/enums'
import {useAppDispatch, useAppSelector} from '../hooks/redux' import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {setEnvData, setTempData} from '../redux/envReducer' import {setEnvData, setTempData} from '../redux/envReducer'
import {EventBusContext} from '../Router' import {EventBusContext} from '../Router'
import {EVENT_EXPAND, MESSAGE_TO_INJECT_DOWNLOAD_AUDIO} from '../consts/const' import {EVENT_EXPAND} from '../consts/const'
import {formatSrtTime, formatTime, formatVttTime} from '../utils/util' import {formatSrtTime, formatTime, formatVttTime} from '../utils/util'
import {downloadText, openUrl} from '@kky002/kky-util' import {downloadText, openUrl} from '@kky002/kky-util'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import {getSummarize} from '../utils/bizUtil' import {getSummarize} from '../utils/bizUtil'
import useMessage from '../messaging/layer2/useMessaging' import dayjs from 'dayjs'
import { useMessage } from '@/hooks/useMessageService'
interface Props { interface Props {
placement: Placement placement: Placement
} }
@@ -68,9 +68,11 @@ const MoreBtn = (props: Props) => {
const segments = useAppSelector(state => state.env.segments) const segments = useAppSelector(state => state.env.segments)
const url = useAppSelector(state => state.env.url) const url = useAppSelector(state => state.env.url)
const title = useAppSelector(state => state.env.title) 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 curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
const {sendInject} = useMessage() const {sendInject} = useMessage(!!envData.sidePanel)
const downloadCallback = useCallback((download: boolean) => { const downloadCallback = useCallback((download: boolean) => {
if (data == null) { if (data == null) {
@@ -79,20 +81,21 @@ const MoreBtn = (props: Props) => {
let fileName = title let fileName = title
let s, suffix 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') { 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) { for (const item of data.body) {
s += item.content + '\n' s += item.content + '\n'
} }
suffix = 'txt' suffix = 'txt'
} else if (downloadType === 'textWithTime') { } 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) { for (const item of data.body) {
s += formatTime(item.from) + ' ' + item.content + '\n' s += formatTime(item.from) + ' ' + item.content + '\n'
} }
suffix = 'txt' suffix = 'txt'
} else if (downloadType === 'article') { } 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) { for (const item of data.body) {
s += item.content + ', ' s += item.content + ', '
} }
@@ -142,7 +145,7 @@ const MoreBtn = (props: Props) => {
s = JSON.stringify(data) s = JSON.stringify(data)
suffix = 'json' suffix = 'json'
} else if (downloadType === 'summarize') { } 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) const [success, content] = getSummarize(title, segments, curSummaryType)
if (!success) return if (!success) return
s += content s += content
@@ -159,11 +162,11 @@ const MoreBtn = (props: Props) => {
}).catch(console.error) }).catch(console.error)
} }
setMoreVisible(false) setMoreVisible(false)
}, [curSummaryType, data, downloadType, segments, title, url]) }, [author, ctime, curSummaryType, data, downloadType, segments, title, url])
const downloadAudioCallback = useCallback(() => { const downloadAudioCallback = useCallback(() => {
sendInject(MESSAGE_TO_INJECT_DOWNLOAD_AUDIO, {}) sendInject(null, 'DOWNLOAD_AUDIO', {})
}, []) }, [sendInject])
const selectCallback = useCallback((e: any) => { const selectCallback = useCallback((e: any) => {
dispatch(setTempData({ dispatch(setTempData({
@@ -245,7 +248,7 @@ const MoreBtn = (props: Props) => {
(m4s) (m4s)
</a> </a>
</li> </li>
<li className='hover:bg-accent'> {/* <li className='hover:bg-accent'>
<a className='flex items-center' onClick={(e) => { <a className='flex items-center' onClick={(e) => {
e.preventDefault() e.preventDefault()
e.stopPropagation() 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'/> <AiFillWechat className='w-[20px] h-[20px] text-primary/75 bg-white rounded-sm p-0.5'/>
微信公众号(IndieKKY) 微信公众号(IndieKKY)
</a> </a>
</li> </li> */}
{/* <li className='hover:bg-accent'> */} {/* <li className='hover:bg-accent'> */}
{/* <a className='flex items-center' onClick={(e) => { */} {/* <a className='flex items-center' onClick={(e) => { */}
{/* e.preventDefault() */} {/* e.preventDefault() */}
@@ -297,6 +300,17 @@ const MoreBtn = (props: Props) => {
</a> </a>
</li> </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> </ul>
</Popover>} </Popover>}
</> </>

View File

@@ -1,14 +1,14 @@
import React, { useState } from 'react'; import React, { useState } from 'react'
import { FaStar } from 'react-icons/fa'; import { FaStar } from 'react-icons/fa'
import { IoMdClose } from 'react-icons/io'; import { IoMdClose } from 'react-icons/io'
import { setTempData } from '../redux/envReducer'; import { setTempData } from '../redux/envReducer'
import { useAppDispatch, useAppSelector } from '../hooks/redux'; import { useAppDispatch, useAppSelector } from '../hooks/redux'
import { openUrl } from '@kky002/kky-util'; import { openUrl } from '@kky002/kky-util'
import { isEdgeBrowser } from '../utils/util'; import { isEdgeBrowser } from '../utils/util'
const RateExtension: React.FC = () => { const RateExtension: React.FC = () => {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const [isHovered, setIsHovered] = useState(false); const [isHovered, setIsHovered] = useState(false)
const reviewed = useAppSelector(state => state.env.tempData.reviewed) const reviewed = useAppSelector(state => state.env.tempData.reviewed)
const handleRateClick = () => { const handleRateClick = () => {
@@ -21,9 +21,9 @@ const RateExtension: React.FC = () => {
} else { } else {
openUrl('https://chromewebstore.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp/reviews') openUrl('https://chromewebstore.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp/reviews')
} }
}; }
if (reviewed === true || reviewed === undefined) return null; if (reviewed === true || reviewed === undefined) return null
return ( 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"> <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> </span>
</button> </button>
</div> </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 {useAppDispatch, useAppSelector} from '../hooks/redux'
import {setFloatKeyPointsSegIdx, setSegmentFold, setTempData} from '../redux/envReducer' import {setFloatKeyPointsSegIdx, setSegmentFold, setTempData} from '../redux/envReducer'
import classNames from 'classnames' import classNames from 'classnames'
import {FaClipboardList} from 'react-icons/fa' 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 useTranslate from '../hooks/useTranslate'
import {BsDashSquare, BsPlusSquare, CgFileDocument, FaQuestion, GrOverview, RiFileCopy2Line} from 'react-icons/all' import {BsDashSquare, BsPlusSquare, CgFileDocument, FaQuestion, GrOverview, RiFileCopy2Line} from 'react-icons/all'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
@@ -12,6 +12,8 @@ import {useInViewport} from 'ahooks'
import SegmentItem from './SegmentItem' import SegmentItem from './SegmentItem'
import {stopPopFunc} from '../utils/util' import {stopPopFunc} from '../utils/util'
import useSubtitle from '../hooks/useSubtitle' import useSubtitle from '../hooks/useSubtitle'
import DebateChat from './DebateChat'
import { RootState } from '../store'
const SummarizeItemOverview = (props: { const SummarizeItemOverview = (props: {
segment: Segment segment: Segment
@@ -24,7 +26,7 @@ const SummarizeItemOverview = (props: {
const {move} = useSubtitle() const {move} = useSubtitle()
const time = parseStrTimeToSeconds(overviewItem.time) const time = parseStrTimeToSeconds(overviewItem.time)
const currentTime = useAppSelector(state => state.env.currentTime) const currentTime = useAppSelector((state: RootState) => state.currentTime.currentTime)
const isIn = useMemo(() => { const isIn = useMemo(() => {
if (currentTime != null) { if (currentTime != null) {
// check in current segment // check in current segment
@@ -72,13 +74,13 @@ const Summarize = (props: {
const {addSummarizeTask} = useTranslate() const {addSummarizeTask} = useTranslate()
const onGenerate = useCallback(() => { const onGenerate = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey const apiKey = envData.apiKey
if (apiKey) { if (apiKey) {
addSummarizeTask(curSummaryType, segment).catch(console.error) addSummarizeTask(curSummaryType, segment).catch(console.error)
} else { } else {
toast.error('请先在选项页面设置ApiKey!') toast.error('请先在选项页面设置ApiKey!')
} }
}, [addSummarizeTask, curSummaryType, envData.aiType, envData.apiKey, envData.geminiApiKey, segment]) }, [addSummarizeTask, curSummaryType, envData.apiKey, segment])
const onCopy = useCallback(() => { const onCopy = useCallback(() => {
if (summary != null) { if (summary != null) {
@@ -113,6 +115,8 @@ const Summarize = (props: {
<div className={classNames('font-normal', fontSize === 'large' ? 'text-sm' : 'text-xs')}>{question.a}</div> <div className={classNames('font-normal', fontSize === 'large' ? 'text-sm' : 'text-xs')}>{question.a}</div>
</div>)} </div>)}
</div>} </div>}
{summary?.type === 'debate' && (summary.content != null) &&
<DebateChat messages={summary.content} />}
</div> </div>
<div className='flex flex-col justify-center items-center'> <div className='flex flex-col justify-center items-center'>
{segment.text.length < SUMMARIZE_THRESHOLD && <div className='desc-lighter text-xs'>.</div>} {segment.text.length < SUMMARIZE_THRESHOLD && <div className='desc-lighter text-xs'>.</div>}
@@ -200,8 +204,14 @@ const SegmentCard = (props: {
})) }))
}, [dispatch]) }, [dispatch])
const onSelDebate = useCallback(() => {
dispatch(setTempData({
curSummaryType: 'debate'
}))
}, [dispatch])
return <div 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]'> <div className='relative flex justify-center min-h-[20px]'>
{segments != null && segments.length > 0 && {segments != null && segments.length > 0 &&
<div className='absolute left-0 top-0 bottom-0 text-xs select-none flex-center desc'> <div className='absolute left-0 top-0 bottom-0 text-xs select-none flex-center desc'>
@@ -215,6 +225,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 === '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 === '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 === '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> <a className="tab tab-lifted tab-xs tab-disabled cursor-default"></a>
</div>} </div>}
<div <div

View File

@@ -1,26 +1,4 @@
export const MESSAGE_TARGET_EXTENSION = 'BilibiliExtension' export const DEFAULT_USE_PORT = false
export const MESSAGE_TARGET_INJECT = 'BilibiliInject'
export const MESSAGE_TARGET_APP = 'BilibiliAPP'
export const MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL = 'closeSidePanel'
export const MESSAGE_TO_EXTENSION_ADD_TASK = 'addTask'
export const MESSAGE_TO_EXTENSION_GET_TASK = 'getTask'
export const MESSAGE_TO_EXTENSION_SHOW_FLAG = 'showFlag'
export const MESSAGE_TO_INJECT_TOGGLE_DISPLAY = 'toggleDisplay'
export const MESSAGE_TO_INJECT_FOLD = 'fold'
export const MESSAGE_TO_INJECT_MOVE = 'move'
export const MESSAGE_TO_INJECT_PLAY = 'play'
export const MESSAGE_TO_INJECT_DOWNLOAD_AUDIO = 'downloadAudio'
export const MESSAGE_TO_INJECT_GET_VIDEO_STATUS = 'getVideoStatus'
export const MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO = 'getVideoElementInfo'
export const MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO = 'refreshVideoInfo'
export const MESSAGE_TO_INJECT_UPDATETRANSRESULT = 'updateTransResult'
export const MESSAGE_TO_INJECT_HIDE_TRANS = 'hideTrans'
export const MESSAGE_TO_INJECT_GET_SUBTITLE = 'getSubtitle'
export const MESSAGE_TO_APP_SET_INFOS = 'setInfos'
export const MESSAGE_TO_APP_SET_VIDEO_INFO = 'setVideoInfo'
export const EVENT_EXPAND = 'expand' export const EVENT_EXPAND = 'expand'
@@ -35,6 +13,7 @@ export const PROMPT_TYPE_TRANSLATE = 'translate'
export const PROMPT_TYPE_SUMMARIZE_OVERVIEW = 'summarize_overview' export const PROMPT_TYPE_SUMMARIZE_OVERVIEW = 'summarize_overview'
export const PROMPT_TYPE_SUMMARIZE_KEYPOINT = 'summarize_keypoint' export const PROMPT_TYPE_SUMMARIZE_KEYPOINT = 'summarize_keypoint'
export const PROMPT_TYPE_SUMMARIZE_QUESTION = 'summarize_question' 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_SUMMARIZE_BRIEF = 'summarize_brief'
export const PROMPT_TYPE_ASK = 'ask' export const PROMPT_TYPE_ASK = 'ask'
export const PROMPT_TYPES = [{ export const PROMPT_TYPES = [{
@@ -52,6 +31,9 @@ export const PROMPT_TYPES = [{
}, { }, {
name: '问题', name: '问题',
type: PROMPT_TYPE_SUMMARIZE_QUESTION, type: PROMPT_TYPE_SUMMARIZE_QUESTION,
}, {
name: '辩论',
type: PROMPT_TYPE_SUMMARIZE_DEBATE,
}, { }, {
name: '提问', name: '提问',
type: PROMPT_TYPE_ASK, type: PROMPT_TYPE_ASK,
@@ -82,6 +64,12 @@ export const SUMMARIZE_TYPES = {
downloadName: '💡常见问题💡', downloadName: '💡常见问题💡',
promptType: PROMPT_TYPE_SUMMARIZE_QUESTION, promptType: PROMPT_TYPE_SUMMARIZE_QUESTION,
}, },
debate: {
name: '辩论',
desc: '辩论',
downloadName: '💡辩论💡',
promptType: PROMPT_TYPE_SUMMARIZE_DEBATE,
},
} }
export const PROMPT_DEFAULTS = { export const PROMPT_DEFAULTS = {
@@ -199,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. [PROMPT_TYPE_ASK]: `You are a helpful assistant who answers question related to video subtitles.
Answer in language '{{language}}'. Answer in language '{{language}}'.
@@ -244,6 +268,7 @@ export const SUMMARIZE_LANGUAGE_DEFAULT = 'cn'
export const SUMMARIZE_ALL_THRESHOLD = 5 export const SUMMARIZE_ALL_THRESHOLD = 5
export const ASK_ENABLED_DEFAULT = true export const ASK_ENABLED_DEFAULT = true
export const DEFAULT_SERVER_URL_OPENAI = 'https://api.openai.com' export const DEFAULT_SERVER_URL_OPENAI = 'https://api.openai.com'
export const DEFAULT_SERVER_URL_GEMINI = 'https://generativelanguage.googleapis.com/v1beta/openai/'
export const CUSTOM_MODEL_TOKENS = 16385 export const CUSTOM_MODEL_TOKENS = 16385
export const MODEL_TIP = '推荐gpt-4o-mini能力强价格低token上限大' export const MODEL_TIP = '推荐gpt-4o-mini能力强价格低token上限大'
@@ -259,7 +284,6 @@ export const MODELS = [{
code: 'custom', code: 'custom',
name: '自定义', name: '自定义',
}] }]
export const GEMINI_TOKENS = 32768
export const MODEL_DEFAULT = MODELS[0].code export const MODEL_DEFAULT = MODELS[0].code
export const MODEL_MAP: {[key: string]: typeof MODELS[number]} = {} export const MODEL_MAP: {[key: string]: typeof MODELS[number]} = {}
for (const model of MODELS) { for (const model of MODELS) {
@@ -269,6 +293,9 @@ for (const model of MODELS) {
export const LANGUAGES = [{ export const LANGUAGES = [{
code: 'en', code: 'en',
name: 'English', name: 'English',
}, {
code: 'ja',
name: '日本語',
}, { }, {
code: 'ena', code: 'ena',
name: 'American English', name: 'American English',
@@ -302,6 +329,39 @@ export const LANGUAGES = [{
}, { }, {
code: 'Italian', code: 'Italian',
name: 'Italiano', 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]} = {} export const LANGUAGES_MAP: {[key: string]: typeof LANGUAGES[number]} = {}
for (const language of LANGUAGES) { for (const language of LANGUAGES) {

View File

@@ -1,31 +1,35 @@
import { setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer' import { setAuthor, setCtime, setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
import { useMemo } from 'react' import { useAppDispatch, useAppSelector } from './redux'
import { useAppDispatch } from './redux' import { AllAPPMessages, AllExtensionMessages, AllInjectMessages } from '@/message-typings'
import { MESSAGE_TO_APP_SET_INFOS, MESSAGE_TO_APP_SET_VIDEO_INFO } from '@/consts/const' import { useMessaging, useMessagingService } from '@kky002/kky-message'
import useMessagingService from '@/messaging/layer2/useMessagingService' import { useMemoizedFn } from 'ahooks'
const useMessageService = () => { const useMessageService = () => {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const envData = useAppSelector((state) => state.env.envData)
//methods
const methods: { // methods
[key: string]: (params: any, context: MethodContext) => Promise<any> const methodsFunc: () => {
} = useMemo(() => ({ [K in AllAPPMessages['method']]: (params: Extract<AllAPPMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
[MESSAGE_TO_APP_SET_INFOS]: async (params: any, context: MethodContext) => { } = useMemoizedFn(() => ({
SET_INFOS: async (params, context: MethodContext) => {
dispatch(setInfos(params.infos)) dispatch(setInfos(params.infos))
dispatch(setCurInfo(undefined)) dispatch(setCurInfo(undefined))
dispatch(setCurFetched(false)) dispatch(setCurFetched(false))
dispatch(setData(undefined)) dispatch(setData(undefined))
}, },
[MESSAGE_TO_APP_SET_VIDEO_INFO]: async (params: any, context: MethodContext) => { SET_VIDEO_INFO: async (params, context: MethodContext) => {
dispatch(setInfos(params.infos)) dispatch(setInfos(params.infos))
dispatch(setUrl(params.url)) dispatch(setUrl(params.url))
dispatch(setTitle(params.title)) dispatch(setTitle(params.title))
dispatch(setCtime(params.ctime))
dispatch(setAuthor(params.author))
console.debug('video title: ', params.title) 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,26 +1,26 @@
import {useAppDispatch, useAppSelector} from './redux' import {useAppDispatch, useAppSelector} from './redux'
import React, {useCallback} from 'react' import React, {useCallback} from 'react'
import {setNeedScroll, setReviewAction, setTempData} from '../redux/envReducer' import {setNeedScroll, setReviewAction, setTempData} from '../redux/envReducer'
import {MESSAGE_TO_INJECT_MOVE} from '../consts/const' import { useMessage } from './useMessageService'
import useMessage from '../messaging/layer2/useMessaging'
const useSubtitle = () => { const useSubtitle = () => {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const envData = useAppSelector(state => state.env.envData)
const reviewed = useAppSelector(state => state.env.tempData.reviewed) const reviewed = useAppSelector(state => state.env.tempData.reviewed)
const reviewAction = useAppSelector(state => state.env.reviewAction) const reviewAction = useAppSelector(state => state.env.reviewAction)
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions) const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
const {sendInject} = useMessage() const {sendInject} = useMessage(!!envData.sidePanel)
const move = useCallback((time: number, togglePause: boolean) => {
sendInject(MESSAGE_TO_INJECT_MOVE, {time, togglePause})
//review action const move = useCallback((time: number, togglePause: boolean) => {
sendInject(null, 'MOVE', {time, togglePause})
// review action
if (reviewed === undefined && !reviewAction) { if (reviewed === undefined && !reviewAction) {
dispatch(setReviewAction(true)) dispatch(setReviewAction(true))
dispatch(setTempData({ dispatch(setTempData({
reviewActions: (reviewActions ?? 0) + 1 reviewActions: (reviewActions ?? 0) + 1
})) }))
} }
}, [dispatch, reviewAction, reviewActions, reviewed]) }, [dispatch, reviewAction, reviewActions, reviewed, sendInject])
const scrollIntoView = useCallback((ref: React.RefObject<HTMLDivElement>) => { const scrollIntoView = useCallback((ref: React.RefObject<HTMLDivElement>) => {
ref.current?.scrollIntoView({behavior: 'smooth', block: 'center'}) ref.current?.scrollIntoView({behavior: 'smooth', block: 'center'})

View File

@@ -4,23 +4,20 @@ import {
setCurFetched, setCurFetched,
setCurIdx, setCurIdx,
setCurInfo, setCurInfo,
setCurrentTime,
setData, setData,
setInfos,
setNoVideo, setNoVideo,
setSegmentFold, setSegmentFold,
setSegments, setSegments,
setTitle,
setTotalHeight, setTotalHeight,
setUrl,
setTempData, setTempData,
} from '../redux/envReducer' } from '../redux/envReducer'
import {EventBusContext} from '../Router' import {EventBusContext} from '../Router'
import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE, MESSAGE_TO_INJECT_GET_VIDEO_STATUS, MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO, MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO, MESSAGE_TO_INJECT_HIDE_TRANS, MESSAGE_TO_INJECT_UPDATETRANSRESULT, TOTAL_HEIGHT_DEF} from '../consts/const' import {EVENT_EXPAND, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../consts/const'
import {useAsyncEffect, useInterval} from 'ahooks' import {useAsyncEffect, useInterval} from 'ahooks'
import {getModelMaxTokens, getWholeText} from '../utils/bizUtil' import {getModelMaxTokens, getWholeText} from '../utils/bizUtil'
import {MESSAGE_TO_INJECT_GET_SUBTITLE} from '../consts/const' import { useMessage } from './useMessageService'
import useMessage from '../messaging/layer2/useMessaging' import { setCurrentTime } from '../redux/currentTimeReducer'
import { RootState } from '../store'
/** /**
* Service是单例类似后端的服务概念 * Service是单例类似后端的服务概念
@@ -32,10 +29,10 @@ const useSubtitleService = () => {
const curFetched = useAppSelector(state => state.env.curFetched) const curFetched = useAppSelector(state => state.env.curFetched)
const fold = useAppSelector(state => state.env.fold) const fold = useAppSelector(state => state.env.fold)
const envReady = useAppSelector(state => state.env.envReady) const envReady = useAppSelector(state => state.env.envReady)
const envData = useAppSelector(state => state.env.envData) const envData = useAppSelector((state: RootState) => state.env.envData)
const data = useAppSelector(state => state.env.data) const data = useAppSelector((state: RootState) => state.env.data)
const currentTime = useAppSelector(state => state.env.currentTime) const currentTime = useAppSelector((state: RootState) => state.currentTime.currentTime)
const curIdx = useAppSelector(state => state.env.curIdx) const curIdx = useAppSelector((state: RootState) => state.env.curIdx)
const eventBus = useContext(EventBusContext) const eventBus = useContext(EventBusContext)
const needScroll = useAppSelector(state => state.env.needScroll) const needScroll = useAppSelector(state => state.env.needScroll)
const segments = useAppSelector(state => state.env.segments) const segments = useAppSelector(state => state.env.segments)
@@ -44,9 +41,9 @@ const useSubtitleService = () => {
const autoTranslate = useAppSelector(state => state.env.autoTranslate) const autoTranslate = useAppSelector(state => state.env.autoTranslate)
const reviewed = useAppSelector(state => state.env.tempData.reviewed) const reviewed = useAppSelector(state => state.env.tempData.reviewed)
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions) 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(() => { useEffect(() => {
if (reviewed === undefined && reviewActions && reviewActions >= 15) { if (reviewed === undefined && reviewActions && reviewActions >= 15) {
dispatch(setTempData({ dispatch(setTempData({
@@ -75,11 +72,11 @@ const useSubtitleService = () => {
dispatch(setCurInfo(infos[0])) dispatch(setCurInfo(infos[0]))
dispatch(setCurFetched(false)) dispatch(setCurFetched(false))
} }
}, [curInfo, dispatch, envData.autoExpand, envReady, fold, infos]) }, [curInfo, dispatch, envData.autoExpand, envReady, fold, infos, envData.sidePanel])
// 获取 // 获取
useEffect(() => { useEffect(() => {
if (curInfo && !curFetched) { if (curInfo && !curFetched) {
sendInject(MESSAGE_TO_INJECT_GET_SUBTITLE, {info: curInfo}).then(data => { sendInject(null, 'GET_SUBTITLE', {info: curInfo}).then(data => {
data?.body?.forEach((item: TranscriptItem, idx: number) => { data?.body?.forEach((item: TranscriptItem, idx: number) => {
item.idx = idx item.idx = idx
}) })
@@ -87,41 +84,49 @@ const useSubtitleService = () => {
dispatch(setCurFetched(true)) dispatch(setCurFetched(true))
dispatch(setData(data)) dispatch(setData(data))
console.log('subtitle', data) console.debug('subtitle', data)
}) })
} }
}, [curFetched, curInfo]) }, [curFetched, curInfo, dispatch, sendInject])
useAsyncEffect(async () => { useAsyncEffect(async () => {
// 初始获取列表 // 初始获取列表
sendInject(MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO, {force: true}) if (envReady) {
// 初始获取设置信息 sendInject(null, 'REFRESH_VIDEO_INFO', {force: true})
sendInject(MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO, {}).then(info => { }
}, [envReady, sendInject])
useAsyncEffect(async () => {
// 更新设置信息
sendInject(null, 'GET_VIDEO_ELEMENT_INFO', {}).then(info => {
dispatch(setNoVideo(info.noVideo)) dispatch(setNoVideo(info.noVideo))
if (envData.sidePanel) { if (envData.sidePanel) {
// get screen height // get screen height
dispatch(setTotalHeight(window.innerHeight)) dispatch(setTotalHeight(window.innerHeight))
}else { } else {
dispatch(setTotalHeight(Math.min(Math.max(info.totalHeight, TOTAL_HEIGHT_MIN), TOTAL_HEIGHT_MAX))) dispatch(setTotalHeight(Math.min(Math.max(info.totalHeight, TOTAL_HEIGHT_MIN), TOTAL_HEIGHT_MAX)))
} }
}) })
}, [envData.sidePanel]) }, [envData.sidePanel, infos, sendInject])
// 更新当前位置 // 更新当前位置
useEffect(() => { useEffect(() => {
let curIdx let newCurIdx
if (((data?.body) != null) && currentTime) { if (((data?.body) != null) && currentTime) {
for (let i=0; i<data.body.length; i++) { for (let i=0; i<data.body.length; i++) {
const item = data.body[i] const item = data.body[i]
if (item.from && currentTime < item.from) { if (item.from && currentTime < item.from) {
break break
} else { } else {
curIdx = i newCurIdx = i
} }
} }
} }
dispatch(setCurIdx(curIdx)) // 只有当索引发生变化时才更新状态
}, [currentTime, data?.body, dispatch]) if (newCurIdx !== curIdx) {
dispatch(setCurIdx(newCurIdx))
}
}, [currentTime, data?.body, dispatch, curIdx])
// 需要滚动 => segment自动展开 // 需要滚动 => segment自动展开
useEffect(() => { useEffect(() => {
@@ -148,11 +153,7 @@ const useSubtitleService = () => {
if (envData.summarizeEnable) { // 分段 if (envData.summarizeEnable) { // 分段
let size = envData.words let size = envData.words
if (!size) { // 默认 if (!size) { // 默认
if (envData.aiType === 'gemini') { size = getModelMaxTokens(envData)*WORDS_RATE
size = GEMINI_TOKENS*WORDS_RATE
} else {
size = getModelMaxTokens(envData)*WORDS_RATE
}
} }
size = Math.max(size, WORDS_MIN) size = Math.max(size, WORDS_MIN)
@@ -192,25 +193,28 @@ const useSubtitleService = () => {
// 每0.5秒更新当前视频时间 // 每0.5秒更新当前视频时间
useInterval(() => { useInterval(() => {
sendInject(MESSAGE_TO_INJECT_GET_VIDEO_STATUS, {}).then(status => { sendInject(null, 'GET_VIDEO_STATUS', {}).then(status => {
dispatch(setCurrentTime(status.currentTime)) // 只有当时间发生显著变化时才更新状态差异大于0.1秒),避免不必要的重新渲染
if (currentTime == null || Math.abs(status.currentTime - currentTime) > 0.1) {
dispatch(setCurrentTime(status.currentTime))
}
}) })
}, 500) }, 500)
// show translated text in the video // show translated text in the video
useEffect(() => { useEffect(() => {
if (hideOnDisableAutoTranslate && !autoTranslate) { if (hideOnDisableAutoTranslate && !autoTranslate) {
sendInject(MESSAGE_TO_INJECT_HIDE_TRANS, {}) sendInject(null, 'HIDE_TRANS', {})
return return
} }
const transResult = curIdx?transResults[curIdx]:undefined const transResult = curIdx?transResults[curIdx]:undefined
if (transResult?.code === '200' && transResult.data) { if (transResult?.code === '200' && transResult.data) {
sendInject(MESSAGE_TO_INJECT_UPDATETRANSRESULT, {result: transResult.data}) sendInject(null, 'UPDATE_TRANS_RESULT', {result: transResult.data})
} else { } else {
sendInject(MESSAGE_TO_INJECT_HIDE_TRANS, {}) sendInject(null, 'HIDE_TRANS', {})
} }
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, transResults]) }, [autoTranslate, curIdx, hideOnDisableAutoTranslate, sendInject, transResults])
} }
export default useSubtitleService export default useSubtitleService

View File

@@ -16,8 +16,6 @@ import {
import { import {
LANGUAGE_DEFAULT, LANGUAGE_DEFAULT,
LANGUAGES_MAP, LANGUAGES_MAP,
MESSAGE_TO_EXTENSION_ADD_TASK,
MESSAGE_TO_EXTENSION_GET_TASK,
PROMPT_DEFAULTS, PROMPT_DEFAULTS,
PROMPT_TYPE_ASK, PROMPT_TYPE_ASK,
PROMPT_TYPE_TRANSLATE, PROMPT_TYPE_TRANSLATE,
@@ -31,7 +29,7 @@ import toast from 'react-hot-toast'
import {useMemoizedFn} from 'ahooks/es' import {useMemoizedFn} from 'ahooks/es'
import {extractJsonArray, extractJsonObject, getModel} from '../utils/bizUtil' import {extractJsonArray, extractJsonObject, getModel} from '../utils/bizUtil'
import {formatTime} from '../utils/util' import {formatTime} from '../utils/util'
import useMessaging from '@/messaging/layer2/useMessaging' import { useMessage } from './useMessageService'
const useTranslate = () => { const useTranslate = () => {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const data = useAppSelector(state => state.env.data) const data = useAppSelector(state => state.env.data)
@@ -45,7 +43,7 @@ const useTranslate = () => {
const reviewed = useAppSelector(state => state.env.tempData.reviewed) const reviewed = useAppSelector(state => state.env.tempData.reviewed)
const reviewAction = useAppSelector(state => state.env.reviewAction) const reviewAction = useAppSelector(state => state.env.reviewAction)
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions) const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
const {sendExtension} = useMessaging() const {sendExtension} = useMessage(!!envData.sidePanel)
/** /**
* 获取下一个需要翻译的行 * 获取下一个需要翻译的行
* 会检测冷却 * 会检测冷却
@@ -90,24 +88,9 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{subtitles}}', lineStr) prompt = prompt.replaceAll('{{subtitles}}', lineStr)
const taskDef: TaskDef = { const taskDef: TaskDef = {
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete', type: 'chatComplete',
serverUrl: envData.serverUrl, serverUrl: envData.serverUrl,
data: envData.aiType === 'gemini' data: {
?{
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
}
:{
model: getModel(envData), model: getModel(envData),
messages: [ messages: [
{ {
@@ -122,7 +105,6 @@ const useTranslate = () => {
extra: { extra: {
type: 'translate', type: 'translate',
apiKey: envData.apiKey, apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
startIdx, startIdx,
size: lines.length, size: lines.length,
} }
@@ -137,14 +119,14 @@ const useTranslate = () => {
} }
}) })
dispatch(addTransResults(result)) dispatch(addTransResults(result))
const task = await sendExtension(MESSAGE_TO_EXTENSION_ADD_TASK, {taskDef}) const task = await sendExtension(null, 'ADD_TASK', {taskDef})
dispatch(addTaskId(task.id)) 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) => { const addSummarizeTask = useCallback(async (type: SummaryType, segment: Segment) => {
//review action // review action
if (reviewed === undefined && !reviewAction) { if (reviewed === undefined && !reviewAction) {
dispatch(setReviewAction(true)) dispatch(setReviewAction(true))
dispatch(setTempData({ dispatch(setTempData({
@@ -167,24 +149,9 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{segment}}', segment.text) prompt = prompt.replaceAll('{{segment}}', segment.text)
const taskDef: TaskDef = { const taskDef: TaskDef = {
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete', type: 'chatComplete',
serverUrl: envData.serverUrl, serverUrl: envData.serverUrl,
data: envData.aiType === 'gemini' data: {
?{
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
}
:{
model: getModel(envData), model: getModel(envData),
messages: [ messages: [
{ {
@@ -201,16 +168,15 @@ const useTranslate = () => {
summaryType: type, summaryType: type,
startIdx: segment.startIdx, startIdx: segment.startIdx,
apiKey: envData.apiKey, apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
} }
} }
console.debug('addSummarizeTask', taskDef) console.debug('addSummarizeTask', taskDef)
dispatch(setSummaryStatus({segmentStartIdx: segment.startIdx, type, status: 'pending'})) dispatch(setSummaryStatus({segmentStartIdx: segment.startIdx, type, status: 'pending'}))
dispatch(setLastSummarizeTime(Date.now())) dispatch(setLastSummarizeTime(Date.now()))
const task = await sendExtension(MESSAGE_TO_EXTENSION_ADD_TASK, {taskDef}) const task = await sendExtension(null, 'ADD_TASK', {taskDef})
dispatch(addTaskId(task.id)) 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) => { const addAskTask = useCallback(async (id: string, segment: Segment, question: string) => {
if (segment.text.length >= SUMMARIZE_THRESHOLD) { if (segment.text.length >= SUMMARIZE_THRESHOLD) {
@@ -222,24 +188,9 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{question}}', question) prompt = prompt.replaceAll('{{question}}', question)
const taskDef: TaskDef = { const taskDef: TaskDef = {
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete', type: 'chatComplete',
serverUrl: envData.serverUrl, serverUrl: envData.serverUrl,
data: envData.aiType === 'gemini' data: {
?{
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
}
:{
model: getModel(envData), model: getModel(envData),
messages: [ messages: [
{ {
@@ -255,7 +206,6 @@ const useTranslate = () => {
type: 'ask', type: 'ask',
// startIdx: segment.startIdx, // startIdx: segment.startIdx,
apiKey: envData.apiKey, apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
askId: id, askId: id,
} }
} }
@@ -264,10 +214,10 @@ const useTranslate = () => {
id, id,
status: 'pending' status: 'pending'
})) }))
const task = await sendExtension(MESSAGE_TO_EXTENSION_ADD_TASK, {taskDef}) const task = await sendExtension(null, 'ADD_TASK', {taskDef})
dispatch(addTaskId(task.id)) dispatch(addTaskId(task.id))
} }
}, [dispatch, envData, summarizeLanguage.name, title]) }, [dispatch, envData, sendExtension, summarizeLanguage.name, title])
const handleTranslate = useMemoizedFn((task: Task, content: string) => { const handleTranslate = useMemoizedFn((task: Task, content: string) => {
let map: {[key: string]: string} = {} let map: {[key: string]: string} = {}
@@ -332,12 +282,12 @@ const useTranslate = () => {
}) })
const getTask = useCallback(async (taskId: string) => { const getTask = useCallback(async (taskId: string) => {
const taskResp = await sendExtension(MESSAGE_TO_EXTENSION_GET_TASK, {taskId}) const taskResp = await sendExtension(null, 'GET_TASK', {taskId})
if (taskResp.code === 'ok') { if (taskResp.code === 'ok') {
console.debug('getTask', taskResp.task) console.debug('getTask', taskResp.task)
const task: Task = taskResp.task const task: Task = taskResp.task
const taskType: string | undefined = task.def.extra?.type const taskType: string | undefined = task.def.extra?.type
const content = envData.aiType === 'gemini'?task.resp?.candidates[0]?.content?.parts[0]?.text?.trim():task.resp?.choices?.[0]?.message?.content?.trim() const content = task.resp?.choices?.[0]?.message?.content?.trim()
if (task.status === 'done') { if (task.status === 'done') {
// 异常提示 // 异常提示
if (task.error) { if (task.error) {
@@ -357,7 +307,7 @@ const useTranslate = () => {
} else { } else {
dispatch(delTaskId(taskId)) dispatch(delTaskId(taskId))
} }
}, [dispatch, envData.aiType, handleAsk, handleSummarize, handleTranslate]) }, [dispatch, handleAsk, handleSummarize, handleTranslate, sendExtension])
return {getFetch, getTask, addTask, addSummarizeTask, addAskTask} return {getFetch, getTask, addTask, addSummarizeTask, addAskTask}
} }

View File

@@ -1,6 +1,6 @@
import { TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID, MESSAGE_TO_INJECT_DOWNLOAD_AUDIO, MESSAGE_TARGET_INJECT, MESSAGE_TO_APP_SET_INFOS, MESSAGE_TO_INJECT_TOGGLE_DISPLAY, STORAGE_ENV, MESSAGE_TO_EXTENSION_SHOW_FLAG } from '@/consts/const' import { TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID, STORAGE_ENV, DEFAULT_USE_PORT } from '@/consts/const'
import { MESSAGE_TO_INJECT_FOLD, MESSAGE_TO_INJECT_MOVE, MESSAGE_TO_APP_SET_VIDEO_INFO, MESSAGE_TO_INJECT_GET_SUBTITLE, MESSAGE_TO_INJECT_GET_VIDEO_STATUS, MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO, MESSAGE_TO_INJECT_UPDATETRANSRESULT, MESSAGE_TO_INJECT_PLAY, MESSAGE_TO_INJECT_HIDE_TRANS, MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO } from '@/consts/const' import { AllExtensionMessages, AllInjectMessages, AllAPPMessages } from '@/message-typings'
import InjectMessaging from '@/messaging/layer2/InjectMessaging' import { InjectMessaging } from '@kky002/kky-message'
const debug = (...args: any[]) => { const debug = (...args: any[]) => {
console.debug('[Inject]', ...args) console.debug('[Inject]', ...args)
@@ -13,7 +13,7 @@ const debug = (...args: any[]) => {
return return
} }
//读取envData // 读取envData
const envDataStr = (await chrome.storage.sync.get(STORAGE_ENV))[STORAGE_ENV] const envDataStr = (await chrome.storage.sync.get(STORAGE_ENV))[STORAGE_ENV]
let sidePanel: boolean | null = null let sidePanel: boolean | null = null
let manualInsert: boolean | null = null let manualInsert: boolean | null = null
@@ -30,7 +30,7 @@ const debug = (...args: any[]) => {
} }
const runtime: { const runtime: {
injectMessaging: InjectMessaging injectMessaging: InjectMessaging<AllExtensionMessages, AllInjectMessages, AllAPPMessages>
// lastV?: string | null // lastV?: string | null
// lastVideoInfo?: VideoInfo // lastVideoInfo?: VideoInfo
@@ -42,7 +42,7 @@ const debug = (...args: any[]) => {
showTrans: boolean showTrans: boolean
curTrans?: string curTrans?: string
} = { } = {
injectMessaging: new InjectMessaging(), injectMessaging: new InjectMessaging(DEFAULT_USE_PORT),
fold: true, fold: true,
videoElementHeight: TOTAL_HEIGHT_DEF, videoElementHeight: TOTAL_HEIGHT_DEF,
showTrans: false, showTrans: false,
@@ -94,11 +94,11 @@ const debug = (...args: any[]) => {
iframe.dataset[vKey] = danmukuBox?.dataset[vKey] iframe.dataset[vKey] = danmukuBox?.dataset[vKey]
} }
//insert before first child // insert before first child
danmukuBox?.insertBefore(iframe, danmukuBox?.firstChild) danmukuBox?.insertBefore(iframe, danmukuBox?.firstChild)
// show badge // show badge
runtime.injectMessaging.sendExtension(MESSAGE_TO_EXTENSION_SHOW_FLAG, { runtime.injectMessaging.sendExtension('SHOW_FLAG', {
show: true show: true
}) })
@@ -114,13 +114,15 @@ const debug = (...args: any[]) => {
if (danmukuBox) { if (danmukuBox) {
clearInterval(timerIframe) clearInterval(timerIframe)
//延迟插入iframe插入太快网络较差时容易出现b站网页刷新原因暂时未知可能b站的某种机制 // 延迟插入iframe插入太快网络较差时容易出现b站网页刷新原因暂时未知可能b站的某种机制
setTimeout(createIframe, 1500) setTimeout(createIframe, 1500)
} }
}, 1000) }, 1000)
} }
let aid: number | null = null let aid: number | null = null
let ctime: number | null = null
let author: string | undefined
let title = '' let title = ''
let pages: any[] = [] let pages: any[] = []
let pagesMap: Record<string, any> = {} let pagesMap: Record<string, any> = {}
@@ -138,6 +140,7 @@ const debug = (...args: any[]) => {
// fix: https://github.com/IndieKKY/bilibili-subtitle/issues/5 // fix: https://github.com/IndieKKY/bilibili-subtitle/issues/5
// 处理稍后再看的url( https://www.bilibili.com/list/watchlater?bvid=xxx&oid=xxx ) // 处理稍后再看的url( https://www.bilibili.com/list/watchlater?bvid=xxx&oid=xxx )
const pathSearchs: Record<string, string> = {} 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) location.search.slice(1).replace(/([^=&]*)=([^=&]*)/g, (matchs, a, b, c) => pathSearchs[a] = b)
// bvid // bvid
@@ -156,30 +159,34 @@ const debug = (...args: any[]) => {
lastAidOrBvid = aidOrBvid lastAidOrBvid = aidOrBvid
if (aidOrBvid) { if (aidOrBvid) {
//aid,pages // aid,pages
let cid let cid: string | undefined
let subtitles let subtitles
if (aidOrBvid.toLowerCase().startsWith('av')) {//avxxx if (aidOrBvid.toLowerCase().startsWith('av')) { // avxxx
aid = parseInt(aidOrBvid.slice(2)) 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 cid = pages[0].cid
ctime = pages[0].ctime
author = pages[0].owner?.name
title = pages[0].part 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 subtitles = res.data.subtitle.subtitles
}) })
} else {//bvxxx } else { // bvxxx
await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${aidOrBvid}`, { credentials: 'include' }).then(res => res.json()).then(async res => { 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 title = res.data.title
aid = res.data.aid aid = res.data.aid
cid = res.data.cid cid = res.data.cid
ctime = res.data.ctime
author = res.data.owner?.name
pages = res.data.pages 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 subtitles = res.data.subtitle.subtitles
}) })
} }
//pagesMap // pagesMap
pagesMap = {} pagesMap = {}
pages.forEach(page => { pages.forEach(page => {
pagesMap[page.page + ''] = page pagesMap[page.page + ''] = page
@@ -187,11 +194,13 @@ const debug = (...args: any[]) => {
debug('refreshVideoInfo: ', aid, cid, pages, subtitles) debug('refreshVideoInfo: ', aid, cid, pages, subtitles)
//send setVideoInfo // send setVideoInfo
runtime.injectMessaging.sendApp(MESSAGE_TO_APP_SET_VIDEO_INFO, { runtime.injectMessaging.sendApp(!!sidePanel, 'SET_VIDEO_INFO', {
url: location.origin + location.pathname, url: location.origin + location.pathname,
title, title,
aid, aid,
ctime,
author,
pages, pages,
infos: subtitles, infos: subtitles,
}) })
@@ -211,7 +220,7 @@ const debug = (...args: any[]) => {
const p = urlSearchParams.get('p') || 1 const p = urlSearchParams.get('p') || 1
const page = pagesMap[p] const page = pagesMap[p]
if (!page) return if (!page) return
const cid = page.cid const cid: number | null = page.cid
if (aid !== lastAid || cid !== lastCid) { if (aid !== lastAid || cid !== lastCid) {
debug('refreshSubtitles', aid, cid) debug('refreshSubtitles', aid, cid)
@@ -219,15 +228,18 @@ const debug = (...args: any[]) => {
lastAid = aid lastAid = aid
lastCid = cid lastCid = cid
if (aid && 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', credentials: 'include',
}) })
.then(res => res.json()) .then(async res => await res.json())
.then(res => { .then(res => {
// console.log('refreshSubtitles: ', aid, cid, res) // remove elements with empty subtitle_url
runtime.injectMessaging.sendApp(MESSAGE_TO_APP_SET_INFOS, { res.data.subtitle.subtitles = res.data.subtitle.subtitles.filter((item: any) => item.subtitle_url)
infos: res.data.subtitle.subtitles if (res.data.subtitle.subtitles.length > 0) {
}) runtime.injectMessaging.sendApp(!!sidePanel, 'SET_INFOS', {
infos: res.data.subtitle.subtitles
})
}
}) })
} }
} }
@@ -241,24 +253,24 @@ const debug = (...args: any[]) => {
} }
const methods: { const methods: {
[key: string]: (params: any, context: MethodContext) => Promise<any> [K in AllInjectMessages['method']]: (params: Extract<AllInjectMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
} = { } = {
[MESSAGE_TO_INJECT_TOGGLE_DISPLAY]: async (params) => { TOGGLE_DISPLAY: async (params) => {
const iframe = document.getElementById(IFRAME_ID) as HTMLIFrameElement | undefined const iframe = document.getElementById(IFRAME_ID) as HTMLIFrameElement | undefined
if (iframe != null) { if (iframe != null) {
iframe.style.display = iframe.style.display === 'none' ? 'block' : 'none' iframe.style.display = iframe.style.display === 'none' ? 'block' : 'none'
runtime.injectMessaging.sendExtension(MESSAGE_TO_EXTENSION_SHOW_FLAG, { runtime.injectMessaging.sendExtension('SHOW_FLAG', {
show: iframe.style.display !== 'none' show: iframe.style.display !== 'none'
}) })
} else { } else {
createIframe() createIframe()
} }
}, },
[MESSAGE_TO_INJECT_FOLD]: async (params) => { FOLD: async (params) => {
runtime.fold = params.fold runtime.fold = params.fold
updateIframeHeight() updateIframeHeight()
}, },
[MESSAGE_TO_INJECT_MOVE]: async (params) => { MOVE: async (params) => {
const video = getVideoElement() const video = getVideoElement()
if (video != null) { if (video != null) {
video.currentTime = params.time video.currentTime = params.time
@@ -267,14 +279,14 @@ const debug = (...args: any[]) => {
} }
} }
}, },
[MESSAGE_TO_INJECT_GET_SUBTITLE]: async (params) => { GET_SUBTITLE: async (params) => {
let url = params.info.subtitle_url let url = params.info.subtitle_url
if (url.startsWith('http://')) { if (url.startsWith('http://')) {
url = url.replace('http://', 'https://') url = url.replace('http://', 'https://')
} }
return await fetch(url).then(res => res.json()) return await fetch(url).then(async res => await res.json())
}, },
[MESSAGE_TO_INJECT_GET_VIDEO_STATUS]: async (params) => { GET_VIDEO_STATUS: async (params) => {
const video = getVideoElement() const video = getVideoElement()
if (video != null) { if (video != null) {
return { return {
@@ -283,17 +295,17 @@ const debug = (...args: any[]) => {
} }
} }
}, },
[MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO]: async (params) => { GET_VIDEO_ELEMENT_INFO: async (params) => {
refreshVideoElement() refreshVideoElement()
return { return {
noVideo: runtime.videoElement == null, noVideo: runtime.videoElement == null,
totalHeight: runtime.videoElementHeight, totalHeight: runtime.videoElementHeight,
} }
}, },
[MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO]: async (params) => { REFRESH_VIDEO_INFO: async (params) => {
refreshVideoInfo(params.force) refreshVideoInfo(params.force)
}, },
[MESSAGE_TO_INJECT_UPDATETRANSRESULT]: async (params) => { UPDATE_TRANS_RESULT: async (params) => {
runtime.showTrans = true runtime.showTrans = true
runtime.curTrans = params?.result runtime.curTrans = params?.result
@@ -321,16 +333,16 @@ const debug = (...args: any[]) => {
} }
text && (text.style.display = runtime.curTrans ? 'block' : 'none') text && (text.style.display = runtime.curTrans ? 'block' : 'none')
}, },
[MESSAGE_TO_INJECT_HIDE_TRANS]: async (params) => { HIDE_TRANS: async (params) => {
runtime.showTrans = false runtime.showTrans = false
runtime.curTrans = undefined runtime.curTrans = undefined
let text = document.getElementById('trans-result-text') const text = document.getElementById('trans-result-text')
if (text) { if (text) {
text.style.display = 'none' text.style.display = 'none'
} }
}, },
[MESSAGE_TO_INJECT_PLAY]: async (params) => { PLAY: async (params) => {
const { play } = params const { play } = params
const video = getVideoElement() const video = getVideoElement()
if (video != null) { if (video != null) {
@@ -341,12 +353,12 @@ const debug = (...args: any[]) => {
} }
} }
}, },
[MESSAGE_TO_INJECT_DOWNLOAD_AUDIO]: async (params) => { DOWNLOAD_AUDIO: async (params) => {
const html = document.getElementsByTagName('html')[0].innerHTML const html = document.getElementsByTagName('html')[0].innerHTML
const playInfo = JSON.parse(html.match(/window.__playinfo__=(.+?)<\/script/)?.[1] ?? '{}') const playInfo = JSON.parse(html.match(/window.__playinfo__=(.+?)<\/script/)?.[1] ?? '{}')
const audioUrl = playInfo.data.dash.audio[0].baseUrl 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') const a = document.createElement('a')
a.href = URL.createObjectURL(blob) a.href = URL.createObjectURL(blob)
a.download = `${title}.m4s` a.download = `${title}.m4s`

87
src/message-typings.d.ts vendored Normal file
View File

@@ -0,0 +1,87 @@
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'
}
interface ExtensionGetTabIdMessage extends ExtensionMessage<{ show: boolean }> {
method: 'GET_TAB_ID'
}
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,19 +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 MESSAGE_TO_EXTENSION_HANDSHAKE = '_handshake'
export const MESSAGE_TO_EXTENSION_ROUTE = '_route'
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,133 +0,0 @@
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg, MESSAGE_TO_EXTENSION_HANDSHAKE, MESSAGE_TO_EXTENSION_ROUTE } 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<L2ReqMsg, L2ResMsg> = (params: any, context: MethodContext, portContext: PortContext<L2ReqMsg, L2ResMsg>) => Promise<any>
type L2MethodHandlers<L2ReqMsg, L2ResMsg> = {
[key: string]: L2MethodHandler<L2ReqMsg, L2ResMsg>
}
class ExtensionMessaging {
portIdToPort: Map<string, PortContext<L2ReqMsg, L2ResMsg>> = new Map()
methods?: L2MethodHandlers<L2ReqMsg, L2ResMsg>
debug = (...args: any[]) => {
console.debug('[Extension Messaging]', ...args)
}
init = (methods: L2MethodHandlers<L2ReqMsg, L2ResMsg>) => {
const innerMethods: L2MethodHandlers<L2ReqMsg, L2ResMsg> = {
[MESSAGE_TO_EXTENSION_HANDSHAKE]: async (params: any, 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
},
[MESSAGE_TO_EXTENSION_ROUTE]: async (params: any, context: MethodContext) => {
return this.broadcastMessageExact([context.tabId!], params.tags, params.method, 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]
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 (tabIds: number[], tags: string[] | null, method: string, params?: any) => {
// 如果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 (ignoreTabIds: number[] | undefined | null, tags: string[], method: string, params?: any) => {
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))
await this.broadcastMessageExact(filteredTabIds, tags, method, params)
}
}
export default ExtensionMessaging

View File

@@ -1,107 +0,0 @@
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg, MESSAGE_TO_EXTENSION_HANDSHAKE, MESSAGE_TO_EXTENSION_ROUTE, TAG_TARGET_APP, TAG_TARGET_INJECT } from '../const'
class InjectMessaging {
port?: chrome.runtime.Port
l1protocol?: Layer1Protocol<L2ReqMsg, L2ResMsg>
//类实例
methods?: {
[key: string]: (params: any, context: MethodContext) => Promise<L2ResMsg>
}
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]
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: {
[key: string]: (params: any, context: MethodContext) => Promise<any>
}) {
this.methods = methods
this.port = chrome.runtime.connect(import.meta.env.VITE_EXTENSION_ID, {
name: 'bilibili-inject',
})
this.l1protocol = new Layer1Protocol<L2ReqMsg, L2ResMsg>(this.messageHandler, this.port)
//握手
this.l1protocol.sendMessage({
from: 'inject',
method: MESSAGE_TO_EXTENSION_HANDSHAKE,
params: {
type: 'inject',
tags: [TAG_TARGET_INJECT],
},
})
}
sendExtension = async <T = any>(method: string, params?: any): Promise<T> => {
return await this.l1protocol!.sendMessage({
from: 'inject',
method,
params: params ?? {},
}).then((res) => {
if (res.code === 200) {
return res.data as T
} else {
throw new Error(res.msg)
}
})
}
sendApp = async <T>(method: string, params: any): Promise<T> => {
if (method === 'setVideoInfo') {
console.log('sendApp>>>', method, params)
}
return this.sendExtension(MESSAGE_TO_EXTENSION_ROUTE, {
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, MESSAGE_TO_EXTENSION_ROUTE, TAG_TARGET_INJECT } from '../const'
const useMessaging = () => {
const sendExtension = useCallback(async <T = any>(method: string, params?: any) => {
// 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 as T
} else {
throw new Error(res.msg)
}
}, [])
const sendInject = useCallback(async <T = any>(method: string, params?: any): Promise<T> => {
return await sendExtension(MESSAGE_TO_EXTENSION_ROUTE, {
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, MESSAGE_TO_EXTENSION_HANDSHAKE, 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 = (methods?: {
[key: string]: (params: any, 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]
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(import.meta.env.VITE_EXTENSION_ID, {
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: MESSAGE_TO_EXTENSION_HANDSHAKE,
params: {
tabId,
tags: [TAG_TARGET_APP],
},
})
l1protocolInit = true
return pmh
}
}, [messageHandler, port])
}
export default useMessagingService

View File

@@ -3,25 +3,25 @@ import {useAppDispatch, useAppSelector} from '../hooks/redux'
import Header from '../components/Header' import Header from '../components/Header'
import Body from '../components/Body' import Body from '../components/Body'
import useSubtitleService from '../hooks/useSubtitleService' import useSubtitleService from '../hooks/useSubtitleService'
import {EVENT_EXPAND, MESSAGE_TO_INJECT_FOLD} from '../consts/const' import {EVENT_EXPAND} from '../consts/const'
import {EventBusContext} from '../Router' import {EventBusContext} from '../Router'
import useTranslateService from '../hooks/useTranslateService' import useTranslateService from '../hooks/useTranslateService'
import {setTheme} from '../utils/bizUtil' import {setTheme} from '../utils/bizUtil'
import useSearchService from '../hooks/useSearchService' import useSearchService from '../hooks/useSearchService'
import useMessage from '../messaging/layer2/useMessaging'
import {setFold} from '../redux/envReducer' import {setFold} from '../redux/envReducer'
import { useMessage } from '@/hooks/useMessageService'
function App() { function App() {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const fold = useAppSelector(state => state.env.fold) const fold = useAppSelector(state => state.env.fold)
const envData = useAppSelector(state => state.env.envData)
const eventBus = useContext(EventBusContext) const eventBus = useContext(EventBusContext)
const totalHeight = useAppSelector(state => state.env.totalHeight) const totalHeight = useAppSelector(state => state.env.totalHeight)
const {sendInject} = useMessage() const {sendInject} = useMessage(!!envData.sidePanel)
const envData = useAppSelector(state => state.env.envData)
const foldCallback = useCallback(() => { const foldCallback = useCallback(() => {
dispatch(setFold(!fold)) dispatch(setFold(!fold))
sendInject(MESSAGE_TO_INJECT_FOLD, {fold: !fold}) sendInject(null, 'FOLD', {fold: !fold})
}, [dispatch, fold, sendInject]) }, [dispatch, fold, sendInject])
// handle event // handle event

View File

@@ -1,20 +1,17 @@
import React, {PropsWithChildren, useCallback, useMemo, useState} from 'react' import React, {PropsWithChildren, useCallback, useMemo, useState} from 'react'
import {setEnvData, setTempData} from '../redux/envReducer' import {setEnvData} from '../redux/envReducer'
import {useAppDispatch, useAppSelector} from '../hooks/redux' import {useAppDispatch, useAppSelector} from '../hooks/redux'
import { import {
ASK_ENABLED_DEFAULT, ASK_ENABLED_DEFAULT,
CUSTOM_MODEL_TOKENS, CUSTOM_MODEL_TOKENS,
DEFAULT_SERVER_URL_GEMINI,
DEFAULT_SERVER_URL_OPENAI, DEFAULT_SERVER_URL_OPENAI,
GEMINI_TOKENS,
HEADER_HEIGHT,
LANGUAGE_DEFAULT, LANGUAGE_DEFAULT,
LANGUAGES, LANGUAGES,
MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL,
MODEL_DEFAULT, MODEL_DEFAULT,
MODEL_MAP, MODEL_MAP,
MODEL_TIP, MODEL_TIP,
MODELS, MODELS,
PAGE_MAIN,
PROMPT_DEFAULTS, PROMPT_DEFAULTS,
PROMPT_TYPES, PROMPT_TYPES,
SUMMARIZE_LANGUAGE_DEFAULT, SUMMARIZE_LANGUAGE_DEFAULT,
@@ -29,17 +26,23 @@ import classNames from 'classnames'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import {useBoolean, useEventTarget} from 'ahooks' import {useBoolean, useEventTarget} from 'ahooks'
import {useEventChecked} from '@kky002/kky-hooks' import {useEventChecked} from '@kky002/kky-hooks'
import useMessaging from '@/messaging/layer2/useMessaging' import { FaChevronDown, FaChevronUp, FaGripfire } from 'react-icons/fa'
import { useMessage } from '@/hooks/useMessageService'
const Section = (props: { const OptionCard = ({ title, children, defaultExpanded = true }: { title: React.ReactNode, children: React.ReactNode, defaultExpanded?: boolean }) => {
title: ShowElement const [isExpanded, setIsExpanded] = useState(defaultExpanded)
htmlFor?: string
} & PropsWithChildren) => { return (
const {title, htmlFor, children} = props <div className="card bg-base-200 shadow-xl mb-4">
return <div className='flex flex-col gap-1'> <div className="card-body p-4">
<label className='font-medium desc-lighter text-sm' htmlFor={htmlFor}>{title}</label> <h2 className="card-title flex justify-between cursor-pointer" onClick={() => setIsExpanded(!isExpanded)}>
<div className='flex flex-col gap-1 rounded py-2 px-2 bg-base-200/75'>{children}</div> {title}
</div> {isExpanded ? <FaChevronUp /> : <FaChevronDown />}
</h2>
{isExpanded && <div className="mt-4">{children}</div>}
</div>
</div>
)
} }
const FormItem = (props: { const FormItem = (props: {
@@ -48,20 +51,22 @@ const FormItem = (props: {
htmlFor?: string htmlFor?: string
} & PropsWithChildren) => { } & PropsWithChildren) => {
const {title, tip, htmlFor, children} = props const {title, tip, htmlFor, children} = props
return <div className='flex items-center gap-2'> return (
<div className={classNames('basis-3/12 justify-end flex-center', tip && 'tooltip tooltip-right z-[100] underline underline-offset-2 decoration-dashed')} data-tip={tip}> <div className='flex items-center gap-4 mb-2'>
<label className='font-medium desc' htmlFor={htmlFor}>{title}</label> <div className={classNames('w-1/3 text-right', tip && 'tooltip tooltip-right z-50')} data-tip={tip}>
<label className={classNames('font-medium', tip && 'border-b border-dotted border-current pb-[2px]')} htmlFor={htmlFor}>{title}</label>
</div>
<div className='w-2/3'>
{children}
</div>
</div> </div>
<div className='basis-9/12 flex items-center'> )
{children}
</div>
</div>
} }
const OptionsPage = () => { const OptionsPage = () => {
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const envData = useAppSelector(state => state.env.envData) const envData = useAppSelector(state => state.env.envData)
const {sendExtension} = useMessaging() const {sendExtension} = useMessage(false)
const {value: sidePanelValue, onChange: setSidePanelValue} = useEventChecked(envData.sidePanel) const {value: sidePanelValue, onChange: setSidePanelValue} = useEventChecked(envData.sidePanel)
const {value: autoInsertValue, onChange: setAutoInsertValue} = useEventChecked(!envData.manualInsert) const {value: autoInsertValue, onChange: setAutoInsertValue} = useEventChecked(!envData.manualInsert)
const {value: autoExpandValue, onChange: setAutoExpandValue} = useEventChecked(envData.autoExpand) const {value: autoExpandValue, onChange: setAutoExpandValue} = useEventChecked(envData.autoExpand)
@@ -74,7 +79,6 @@ const OptionsPage = () => {
const {value: summarizeFloatValue, onChange: setSummarizeFloatValue} = useEventChecked(envData.summarizeFloat) const {value: summarizeFloatValue, onChange: setSummarizeFloatValue} = useEventChecked(envData.summarizeFloat)
const [apiKeyValue, { onChange: onChangeApiKeyValue }] = useEventTarget({initialValue: envData.apiKey??''}) const [apiKeyValue, { onChange: onChangeApiKeyValue }] = useEventTarget({initialValue: envData.apiKey??''})
const [serverUrlValue, setServerUrlValue] = useState(envData.serverUrl) const [serverUrlValue, setServerUrlValue] = useState(envData.serverUrl)
const [geminiApiKeyValue, { onChange: onChangeGeminiApiKeyValue }] = useEventTarget({initialValue: envData.geminiApiKey??''})
const [languageValue, { onChange: onChangeLanguageValue }] = useEventTarget({initialValue: envData.language??LANGUAGE_DEFAULT}) const [languageValue, { onChange: onChangeLanguageValue }] = useEventTarget({initialValue: envData.language??LANGUAGE_DEFAULT})
const [modelValue, { onChange: onChangeModelValue }] = useEventTarget({initialValue: envData.model??MODEL_DEFAULT}) const [modelValue, { onChange: onChangeModelValue }] = useEventTarget({initialValue: envData.model??MODEL_DEFAULT})
const [customModelValue, { onChange: onChangeCustomModelValue }] = useEventTarget({initialValue: envData.customModel}) const [customModelValue, { onChange: onChangeCustomModelValue }] = useEventTarget({initialValue: envData.customModel})
@@ -83,7 +87,6 @@ const OptionsPage = () => {
const [hideOnDisableAutoTranslateValue, setHideOnDisableAutoTranslateValue] = useState(envData.hideOnDisableAutoTranslate) const [hideOnDisableAutoTranslateValue, setHideOnDisableAutoTranslateValue] = useState(envData.hideOnDisableAutoTranslate)
const [themeValue, setThemeValue] = useState(envData.theme) const [themeValue, setThemeValue] = useState(envData.theme)
const [fontSizeValue, setFontSizeValue] = useState(envData.fontSize) const [fontSizeValue, setFontSizeValue] = useState(envData.fontSize)
const [aiTypeValue, setAiTypeValue] = useState(envData.aiType)
const [transDisplayValue, setTransDisplayValue] = useState(envData.transDisplay) const [transDisplayValue, setTransDisplayValue] = useState(envData.transDisplay)
const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words) const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words)
const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT) const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT)
@@ -104,11 +107,8 @@ const OptionsPage = () => {
return list return list
}, []) }, [])
const apiKeySetted = useMemo(() => { const apiKeySetted = useMemo(() => {
if (aiTypeValue === 'gemini') {
return !!geminiApiKeyValue
}
return !!apiKeyValue return !!apiKeyValue
}, [aiTypeValue, apiKeyValue, geminiApiKeyValue]) }, [apiKeyValue])
const onChangeHideOnDisableAutoTranslate = useCallback((e: any) => { const onChangeHideOnDisableAutoTranslate = useCallback((e: any) => {
setHideOnDisableAutoTranslateValue(e.target.checked) setHideOnDisableAutoTranslateValue(e.target.checked)
@@ -119,13 +119,11 @@ const OptionsPage = () => {
sidePanel: sidePanelValue, sidePanel: sidePanelValue,
manualInsert: !autoInsertValue, manualInsert: !autoInsertValue,
autoExpand: autoExpandValue, autoExpand: autoExpandValue,
aiType: aiTypeValue,
apiKey: apiKeyValue, apiKey: apiKeyValue,
serverUrl: serverUrlValue, serverUrl: serverUrlValue,
model: modelValue, model: modelValue,
customModel: customModelValue, customModel: customModelValue,
customModelTokens: customModelTokensValue, customModelTokens: customModelTokensValue,
geminiApiKey: geminiApiKeyValue,
translateEnable: translateEnableValue, translateEnable: translateEnableValue,
language: languageValue, language: languageValue,
hideOnDisableAutoTranslate: hideOnDisableAutoTranslateValue, hideOnDisableAutoTranslate: hideOnDisableAutoTranslateValue,
@@ -143,12 +141,12 @@ const OptionsPage = () => {
askEnabled: askEnabledValue, askEnabled: askEnabledValue,
})) }))
toast.success('保存成功') toast.success('保存成功')
sendExtension(MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL) sendExtension(null, 'CLOSE_SIDE_PANEL')
// 3秒后关闭 // 3秒后关闭
setTimeout(() => { setTimeout(() => {
window.close() window.close()
}, 3000) }, 3000)
}, [dispatch, sendExtension, sidePanelValue, autoInsertValue, autoExpandValue, aiTypeValue, apiKeyValue, serverUrlValue, modelValue, customModelValue, customModelTokensValue, geminiApiKeyValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue, askEnabledValue]) }, [dispatch, sendExtension, sidePanelValue, autoInsertValue, autoExpandValue, apiKeyValue, serverUrlValue, modelValue, customModelValue, customModelTokensValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue, askEnabledValue])
const onCancel = useCallback(() => { const onCancel = useCallback(() => {
window.close() window.close()
@@ -194,17 +192,9 @@ const OptionsPage = () => {
setFontSizeValue('large') setFontSizeValue('large')
}, []) }, [])
const onSelOpenai = useCallback(() => { return (
setAiTypeValue('openai') <div className='container mx-auto max-w-3xl p-4'>
}, []) <OptionCard title="通用配置">
const onSelGemini = useCallback(() => {
setAiTypeValue('gemini')
}, [])
return <div className='flex justify-center'>
<div className="w-2/3 max-w-[600px] flex flex-col gap-3 p-2">
<Section title='通用配置'>
<FormItem title='侧边栏' htmlFor='sidePanel' tip='字幕列表是否显示在侧边栏'> <FormItem title='侧边栏' htmlFor='sidePanel' tip='字幕列表是否显示在侧边栏'>
<input id='sidePanel' type='checkbox' className='toggle toggle-primary' checked={sidePanelValue} <input id='sidePanel' type='checkbox' className='toggle toggle-primary' checked={sidePanelValue}
onChange={setSidePanelValue}/> onChange={setSidePanelValue}/>
@@ -219,62 +209,63 @@ const OptionsPage = () => {
</FormItem>} </FormItem>}
<FormItem title='主题'> <FormItem title='主题'>
<div className="btn-group"> <div className="btn-group">
<button onClick={onSelTheme1} className={classNames('btn btn-xs no-animation', (!themeValue || themeValue === 'system')?'btn-active':'')}></button> <button onClick={onSelTheme1} className={classNames('btn btn-sm no-animation', (!themeValue || themeValue === 'system')?'btn-active':'')}></button>
<button onClick={onSelTheme2} className={classNames('btn btn-xs no-animation', themeValue === 'light'?'btn-active':'')}></button> <button onClick={onSelTheme2} className={classNames('btn btn-sm no-animation', themeValue === 'light'?'btn-active':'')}></button>
<button onClick={onSelTheme3} className={classNames('btn btn-xs no-animation', themeValue === 'dark'?'btn-active':'')}></button> <button onClick={onSelTheme3} className={classNames('btn btn-sm no-animation', themeValue === 'dark'?'btn-active':'')}></button>
</div> </div>
</FormItem> </FormItem>
<FormItem title='字体大小'> <FormItem title='字体大小'>
<div className="btn-group"> <div className="btn-group">
<button onClick={onSelFontSize1} className={classNames('btn btn-xs no-animation', (!fontSizeValue || fontSizeValue === 'normal')?'btn-active':'')}></button> <button onClick={onSelFontSize1} className={classNames('btn btn-sm no-animation', (!fontSizeValue || fontSizeValue === 'normal')?'btn-active':'')}></button>
<button onClick={onSelFontSize2} className={classNames('btn btn-xs no-animation', fontSizeValue === 'large'?'btn-active':'')}></button> <button onClick={onSelFontSize2} className={classNames('btn btn-sm no-animation', fontSizeValue === 'large'?'btn-active':'')}></button>
</div> </div>
</FormItem> </FormItem>
<FormItem title='AI类型' tip='OPENAI质量更高'> </OptionCard>
<div className="btn-group">
<button onClick={onSelOpenai} className={classNames('btn btn-xs no-animation', (!aiTypeValue || aiTypeValue === 'openai')?'btn-active':'')}>OpenAI</button>
<button onClick={onSelGemini} className={classNames('btn btn-xs no-animation', aiTypeValue === 'gemini'?'btn-active':'')}>Gemini</button>
</div>
</FormItem>
</Section>
{(!aiTypeValue || aiTypeValue === 'openai') && <Section title='openai配置'> <OptionCard title="AI 配置">
<FormItem title='ApiKey' htmlFor='apiKey'> {<FormItem title='ApiKey' htmlFor='apiKey'>
<input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx' <input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx'
value={apiKeyValue} onChange={onChangeApiKeyValue}/> value={apiKeyValue} onChange={onChangeApiKeyValue}/>
</FormItem> </FormItem>}
<FormItem title='服务器' htmlFor='serverUrl'> {<FormItem title='服务器' htmlFor='serverUrl'>
<input id='serverUrl' type='text' className='input input-sm input-bordered w-full' <input id='serverUrl' type='text' className='input input-sm input-bordered w-full'
placeholder={DEFAULT_SERVER_URL_OPENAI} value={serverUrlValue} placeholder={DEFAULT_SERVER_URL_OPENAI} value={serverUrlValue}
onChange={e => setServerUrlValue(e.target.value)}/> onChange={e => setServerUrlValue(e.target.value)}/>
</FormItem> </FormItem>}
<div> {<div>
<div className='desc text-xs text-center'> <div className='desc text-sm text-center'>
<div className='flex justify-center font-semibold'></div> <div className='flex justify-center font-semibold'>OpenAI官方地</div>
<div><a className='link link-primary' href='https://platform.openai.com/' target='_blank' <div><a className='link link-primary' href='https://platform.openai.com/' target='_blank'
rel="noreferrer">访</a></div> rel="noreferrer">访</a></div>
<div><a className='link link-primary' <div><a className='link link-primary'
onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_OPENAI)} onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_OPENAI)}
rel='noreferrer'></a></div> rel='noreferrer'></a></div>
{/* <div className='flex justify-center font-semibold'>【第三方代理】</div> */} <div className='flex justify-center font-semibold'>Gemini官方地址</div>
{/* <div>代理网址:<a className='link link-primary' href='https://api.openai-up.com/register?aff=varM' */} <div><a className='link link-primary' href='https://aistudio.google.com/apikey' target='_blank'
{/* target='_blank' */} rel="noreferrer">访</a></div>
{/* rel="noreferrer">点击访问</a></div> */} <div><a className='link link-primary'
{/* <div>服务器地址:<a className='link link-primary' */} onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_GEMINI)}
{/* onClick={() => setServerUrlValue('https://api.openai-up.com')} */} rel='noreferrer'></a></div>
{/* rel='noreferrer'>点击设置</a></div> */} <div className='flex justify-center font-semibold'></div>
{/* <div className='text-amber-600 flex justify-center items-center'><FaGripfire/>目前价格不到官方价格的6折<FaGripfire/></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>
</div> </div>}
<FormItem title='模型选择' htmlFor='modelSel' tip='注意不同模型有不同价格与token限制'> {<FormItem title='模型选择' htmlFor='modelSel' tip='注意不同模型有不同价格与token限制'>
<select id='modelSel' className="select select-sm select-bordered" value={modelValue} <select id='modelSel' className="select select-sm select-bordered" value={modelValue}
onChange={onChangeModelValue}> onChange={onChangeModelValue}>
{MODELS.map(model => <option key={model.code} value={model.code}>{model.name}</option>)} {MODELS.map(model => <option key={model.code} value={model.code}>{model.name}</option>)}
</select> </select>
</FormItem> </FormItem>}
<div className='desc text-xs'> {<div className='desc text-sm'>
{MODEL_TIP} {MODEL_TIP}
</div> </div>}
{modelValue === 'custom' && <FormItem title='模型名' htmlFor='customModel'> {modelValue === 'custom' && <FormItem title='模型名' htmlFor='customModel'>
<input id='customModel' type='text' className='input input-sm input-bordered w-full' placeholder='llama2' <input id='customModel' type='text' className='input input-sm input-bordered w-full' placeholder='llama2'
value={customModelValue} onChange={onChangeCustomModelValue}/> value={customModelValue} onChange={onChangeCustomModelValue}/>
@@ -285,26 +276,9 @@ const OptionsPage = () => {
value={customModelTokensValue} value={customModelTokensValue}
onChange={e => setCustomModelTokensValue(e.target.value ? parseInt(e.target.value) : undefined)}/> onChange={e => setCustomModelTokensValue(e.target.value ? parseInt(e.target.value) : undefined)}/>
</FormItem>} </FormItem>}
</Section>} </OptionCard>
{aiTypeValue === 'gemini' && <Section title='gemini配置'> <OptionCard title={<div className='flex items-center'>
<FormItem title='ApiKey' htmlFor='geminiApiKey'>
<input id='geminiApiKey' type='text' className='input input-sm input-bordered w-full' placeholder='xxx'
value={geminiApiKeyValue} onChange={onChangeGeminiApiKeyValue}/>
</FormItem>
<div>
<div className='desc text-xs'>
<div><a className='link link-primary' href='https://makersuite.google.com/app/apikey'
target='_blank'
rel="noreferrer">Google AI Studio</a> ()
</div>
<div className='text-xs text-error flex items-center'><IoWarning className='text-sm text-warning'/>!
</div>
</div>
</div>
</Section>}
<Section title={<div className='flex items-center'>
{!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'> {!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
<IoWarning className='text-sm text-warning'/> <IoWarning className='text-sm text-warning'/>
@@ -323,24 +297,24 @@ const OptionsPage = () => {
<FormItem title='翻译条数' tip='每次翻译条数'> <FormItem title='翻译条数' tip='每次翻译条数'>
<div className='flex-1 flex flex-col'> <div className='flex-1 flex flex-col'>
<input type="range" min={TRANSLATE_FETCH_MIN} max={TRANSLATE_FETCH_MAX} step={TRANSLATE_FETCH_STEP} value={fetchAmountValue} className="range range-primary" onChange={onFetchAmountChange} /> <input type="range" min={TRANSLATE_FETCH_MIN} max={TRANSLATE_FETCH_MAX} step={TRANSLATE_FETCH_STEP} value={fetchAmountValue} className="range range-primary" onChange={onFetchAmountChange} />
<div className="w-full flex justify-between text-xs px-2"> <div className="w-full flex justify-between text-sm px-2">
{transFetchAmountList.map(amount => <span key={amount}>{amount}</span>)} {transFetchAmountList.map(amount => <span key={amount}>{amount}</span>)}
</div> </div>
</div> </div>
</FormItem> </FormItem>
<FormItem title='翻译显示'> <FormItem title='翻译显示'>
<div className="btn-group"> <div className="btn-group">
<button onClick={onSel1} className={classNames('btn btn-xs no-animation', (!transDisplayValue || transDisplayValue === 'originPrimary')?'btn-active':'')}></button> <button onClick={onSel1} className={classNames('btn btn-sm no-animation', (!transDisplayValue || transDisplayValue === 'originPrimary')?'btn-active':'')}></button>
<button onClick={onSel2} className={classNames('btn btn-xs no-animation', transDisplayValue === 'targetPrimary'?'btn-active':'')}></button> <button onClick={onSel2} className={classNames('btn btn-sm no-animation', transDisplayValue === 'targetPrimary'?'btn-active':'')}></button>
<button onClick={onSel3} className={classNames('btn btn-xs no-animation', transDisplayValue === 'target'?'btn-active':'')}></button> <button onClick={onSel3} className={classNames('btn btn-sm no-animation', transDisplayValue === 'target'?'btn-active':'')}></button>
</div> </div>
</FormItem> </FormItem>
<FormItem title='隐藏翻译' tip='取消自动翻译时,隐藏已翻译内容' htmlFor='hideOnDisableAutoTranslate'> <FormItem title='隐藏翻译' tip='取消自动翻译时,隐藏已翻译内容' htmlFor='hideOnDisableAutoTranslate'>
<input id='hideOnDisableAutoTranslate' type='checkbox' className='toggle toggle-primary' checked={hideOnDisableAutoTranslateValue} <input id='hideOnDisableAutoTranslate' type='checkbox' className='toggle toggle-primary' checked={hideOnDisableAutoTranslateValue}
onChange={onChangeHideOnDisableAutoTranslate}/> onChange={onChangeHideOnDisableAutoTranslate}/>
</FormItem> </FormItem>
</Section> </OptionCard>
<Section title={<div className='flex items-center'> <OptionCard title={<div className='flex items-center'>
{!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'> {!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
<IoWarning className='text-sm text-warning'/> <IoWarning className='text-sm text-warning'/>
@@ -363,17 +337,17 @@ const OptionsPage = () => {
<div className='flex-1 flex flex-col'> <div className='flex-1 flex flex-col'>
<input id='words' type='number' className='input input-sm input-bordered w-full' placeholder={`默认为上限x${WORDS_RATE}`} value={wordsValue??''} onChange={e => setWordsValue(e.target.value?parseInt(e.target.value):undefined)}/> <input id='words' type='number' className='input input-sm input-bordered w-full' placeholder={`默认为上限x${WORDS_RATE}`} value={wordsValue??''} onChange={e => setWordsValue(e.target.value?parseInt(e.target.value):undefined)}/>
{/* <input type="range" min={WORDS_MIN} max={WORDS_MAX} step={WORDS_STEP} value={wordsValue} className="range range-primary" onChange={onWordsChange} /> */} {/* <input type="range" min={WORDS_MIN} max={WORDS_MAX} step={WORDS_STEP} value={wordsValue} className="range range-primary" onChange={onWordsChange} /> */}
{/* <div className="w-full flex justify-between text-xs px-2"> */} {/* <div className="w-full flex justify-between text-sm px-2"> */}
{/* {wordsList.map(words => <span key={words}>{words}</span>)} */} {/* {wordsList.map(words => <span key={words}>{words}</span>)} */}
{/* </div> */} {/* </div> */}
</div> </div>
</FormItem> </FormItem>
<div className='desc text-xs'> <div className='desc text-sm'>
<span className='font-semibold font-mono'>{aiTypeValue === 'gemini'?GEMINI_TOKENS:(MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知')}</span> <span className='font-semibold font-mono'>{MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知'}</span>
</div> </div>
</Section> </OptionCard>
<Section title={<div className='flex items-center'> <OptionCard title={<div className='flex items-center'>
</div>}> </div>}>
<FormItem title='启用搜索' htmlFor='searchEnabled' tip='是否启用字幕搜索功能'> <FormItem title='启用搜索' htmlFor='searchEnabled' tip='是否启用字幕搜索功能'>
@@ -384,23 +358,23 @@ const OptionsPage = () => {
<input id='cnSearchEnabled' type='checkbox' className='toggle toggle-primary' checked={cnSearchEnabledValue} <input id='cnSearchEnabled' type='checkbox' className='toggle toggle-primary' checked={cnSearchEnabledValue}
onChange={setCnSearchEnabledValue}/> onChange={setCnSearchEnabledValue}/>
</FormItem> </FormItem>
</Section> </OptionCard>
<Section title={<div className='flex items-center'> <OptionCard title={<div className='flex items-center'>
</div>}> </div>}>
<FormItem title='启用提问' htmlFor='askEnabled' tip='是否启用字幕提问功能'> <FormItem title='启用提问' htmlFor='askEnabled' tip='是否启用字幕提问功能'>
<input id='askEnabled' type='checkbox' className='toggle toggle-primary' checked={askEnabledValue} <input id='askEnabled' type='checkbox' className='toggle toggle-primary' checked={askEnabledValue}
onChange={setAskEnabledValue}/> onChange={setAskEnabledValue}/>
</FormItem> </FormItem>
</Section> </OptionCard>
<Section title='提示词配置'> <OptionCard title='提示词配置'>
<div className='flex justify-center'> <div className='flex justify-center'>
<a className='text-xs link link-primary' onClick={togglePromptsFold}>{promptsFold ? '展开' : '折叠'}</a> <a className='text-sm link link-primary' onClick={togglePromptsFold}>{promptsFold ? '展开' : '折叠'}</a>
</div> </div>
{!promptsFold && PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div> {!promptsFold && PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div>
<div>{item.name}</div> <div>{item.name}</div>
<div className='link text-xs' onClick={() => { <div className='link text-sm' onClick={() => {
setPromptsValue({ setPromptsValue({
...promptsValue, ...promptsValue,
// @ts-expect-error // @ts-expect-error
@@ -417,20 +391,14 @@ const OptionsPage = () => {
}) })
}}/> }}/>
</FormItem>)} </FormItem>)}
</Section> </OptionCard>
<div className='flex justify-center gap-5'> <div className='flex flex-col justify-center items-center gap-5 mt-6'>
<button className='btn btn-primary btn-sm' onClick={onSave}></button> <button className='btn btn-primary btn-wide' onClick={onSave}></button>
<button className='btn btn-sm' onClick={onCancel}></button> <button className='btn btn-wide' onClick={onCancel}></button>
{/* <button className='btn btn-sm' onClick={() => {
dispatch(setTempData({
reviewed: undefined,
// reviewActions: 0
}))
}}>重置</button> */}
</div> </div>
</div> </div>
</div> )
} }
export default OptionsPage export default OptionsPage

View File

@@ -0,0 +1,23 @@
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
interface CurrentTimeState {
currentTime?: number
}
const initialState: CurrentTimeState = {
currentTime: undefined
}
export const slice = createSlice({
name: 'currentTime',
initialState,
reducers: {
setCurrentTime: (state, action: PayloadAction<number | undefined>) => {
state.currentTime = action.payload
}
}
})
export const { setCurrentTime } = slice.actions
export default slice.reducer

View File

@@ -23,7 +23,6 @@ interface EnvState {
totalHeight: number totalHeight: number
curIdx?: number // 从0开始 curIdx?: number // 从0开始
needScroll?: boolean needScroll?: boolean
currentTime?: number
infos?: any[] infos?: any[]
curInfo?: any curInfo?: any
curFetched?: boolean curFetched?: boolean
@@ -32,7 +31,8 @@ interface EnvState {
segments?: Segment[] segments?: Segment[]
url?: string url?: string
title?: string title?: string
ctime?: number | null
author?: string
taskIds?: string[] taskIds?: string[]
transResults: { [key: number]: TransResult } transResults: { [key: number]: TransResult }
lastTransTime?: number lastTransTime?: number
@@ -49,7 +49,7 @@ interface EnvState {
searchText: string searchText: string
searchResult: Record<string, boolean> searchResult: Record<string, boolean>
//当前视频是否计算过操作 // 当前视频是否计算过操作
reviewAction: boolean reviewAction: boolean
} }
@@ -262,15 +262,18 @@ export const slice = createSlice({
setNeedScroll: (state, action: PayloadAction<boolean>) => { setNeedScroll: (state, action: PayloadAction<boolean>) => {
state.needScroll = action.payload state.needScroll = action.payload
}, },
setCurrentTime: (state, action: PayloadAction<number | undefined>) => {
state.currentTime = action.payload
},
setUrl: (state, action: PayloadAction<string | undefined>) => { setUrl: (state, action: PayloadAction<string | undefined>) => {
state.url = action.payload state.url = action.payload
}, },
setTitle: (state, action: PayloadAction<string | undefined>) => { setTitle: (state, action: PayloadAction<string | undefined>) => {
state.title = action.payload 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[]>) => { setInfos: (state, action: PayloadAction<any[]>) => {
state.infos = action.payload state.infos = action.payload
}, },
@@ -330,7 +333,6 @@ export const {
setCurIdx, setCurIdx,
setEnvData, setEnvData,
setEnvReady, setEnvReady,
setCurrentTime,
setInfos, setInfos,
setCurInfo, setCurInfo,
setCurFetched, setCurFetched,
@@ -342,6 +344,8 @@ export const {
addAskInfo, addAskInfo,
delAskInfo, delAskInfo,
mergeAskInfo, mergeAskInfo,
setCtime,
setAuthor,
} = slice.actions } = slice.actions
export default slice.reducer export default slice.reducer

View File

@@ -1,9 +1,11 @@
import {configureStore} from '@reduxjs/toolkit' import {configureStore} from '@reduxjs/toolkit'
import envReducer from './redux/envReducer' import envReducer from './redux/envReducer'
import currentTimeReducer from './redux/currentTimeReducer'
const store = configureStore({ const store = configureStore({
reducer: { reducer: {
env: envReducer, env: envReducer,
currentTime: currentTimeReducer,
}, },
}) })

37
src/typings.d.ts vendored
View File

@@ -1,22 +1,5 @@
type MessageFrom = 'extension' | 'inject' | 'app'
interface MessageData {
from: MessageFrom
target: string
method: string
params?: any
[key: string]: any
}
interface MessageResult {
success: boolean
code: number
message?: string
data?: any
}
interface MethodContext { interface MethodContext {
from: MessageFrom from: 'extension' | 'inject' | 'app'
event: any event: any
tabId?: number tabId?: number
// sender?: chrome.runtime.MessageSender | null // sender?: chrome.runtime.MessageSender | null
@@ -24,19 +7,16 @@ interface MethodContext {
interface EnvData { interface EnvData {
sidePanel?: boolean sidePanel?: boolean
manualInsert?: boolean //是否手动插入字幕列表 manualInsert?: boolean // 是否手动插入字幕列表
autoExpand?: boolean autoExpand?: boolean
flagDot?: boolean flagDot?: boolean
aiType?: 'openai' | 'gemini'
// openai // openai
apiKey?: string apiKey?: string
serverUrl?: string serverUrl?: string
model?: string model?: string
customModel?: string customModel?: string
customModelTokens?: number customModelTokens?: number
// gemini
geminiApiKey?: string
translateEnable?: boolean translateEnable?: boolean
language?: string language?: string
@@ -71,7 +51,7 @@ interface TempData {
} }
interface TaskDef { interface TaskDef {
type: 'chatComplete' | 'geminiChatComplete' type: 'chatComplete'
serverUrl?: string serverUrl?: string
data: any data: any
extra?: any extra?: any
@@ -168,4 +148,13 @@ interface BriefSummary extends Summary {
} }
type SummaryStatus = 'init' | 'pending' | 'done' 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[]
}

View File

@@ -2,7 +2,6 @@ import {APP_DOM_ID, CUSTOM_MODEL_TOKENS, MODEL_DEFAULT, MODEL_MAP, SUMMARIZE_TYP
import {isDarkMode} from '@kky002/kky-util' import {isDarkMode} from '@kky002/kky-util'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import {findIndex} from 'lodash-es' import {findIndex} from 'lodash-es'
export const debug = (...args: any[]) => { export const debug = (...args: any[]) => {
console.debug('[APP]', ...args) console.debug('[APP]', ...args)
} }
@@ -82,6 +81,9 @@ export const isSummaryEmpty = (summary: Summary) => {
} else if (summary.type === 'question') { } else if (summary.type === 'question') {
const content: any[] = summary.content??[] const content: any[] = summary.content??[]
return content.length === 0 return content.length === 0
} else if (summary.type === 'debate') {
const content: Array<{ side: string, content: string }> = summary.content ?? []
return content.length === 0
} }
return true return true
} }
@@ -108,6 +110,11 @@ export const getSummaryStr = (summary: Summary) => {
s += content.map(item => { s += content.map(item => {
return item.q + '\n' + item.a + '\n' return item.q + '\n' + item.a + '\n'
}).join('\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 return s
} }
@@ -188,12 +195,56 @@ export const getSummarize = (title: string | undefined, segments: Segment[] | un
} }
/** /**
* @param time '03:10' * 将 MM:SS 或 HH:MM:SS 格式的时间字符串转换为总秒数。
* @param time '03:10' 或 '01:03:10' 格式的时间字符串
* @returns number 总秒数,如果格式无效则返回 0 或 NaN (根据下面选择)。
* 建议添加更严格的错误处理,例如抛出错误。
*/ */
export const parseStrTimeToSeconds = (time: string): number => { export const parseStrTimeToSeconds = (time: string): number => {
const parts = time.split(':') // 1. 基本输入验证 (可选但推荐)
return parseInt(parts[0]) * 60 + parseInt(parts[1]) if (!time || typeof time !== 'string') {
} console.warn(`Invalid input type for time: ${typeof time}`);
return 0; // 或者 return NaN;
}
const parts = time.split(':');
const partCount = parts.length;
let hours = 0;
let minutes = 0;
let seconds = 0;
try {
if (partCount === 2) {
// 格式: MM:SS
minutes = parseInt(parts[0]);
seconds = parseInt(parts[1]);
} else if (partCount === 3) {
// 格式: HH:MM:SS
hours = parseInt(parts[0]);
minutes = parseInt(parts[1]);
seconds = parseInt(parts[2]);
} else {
// 格式无效
console.warn(`Invalid time format: "${time}". Expected MM:SS or HH:MM:SS.`);
return 0; // 或者 return NaN;
}
// 2. 验证解析出的部分是否为有效数字
if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
console.warn(`Invalid numeric values in time string: "${time}"`);
return 0; // 或者 return NaN;
}
// 3. 计算总秒数
return hours * 3600 + minutes * 60 + seconds;
} catch (error) {
// 捕获潜在的错误 (虽然在此逻辑中不太可能,但以防万一)
console.error(`Error parsing time string: "${time}"`, error);
return 0; // 或者 return NaN;
}
};
/** /**
* @param time '00:04:11,599' or '00:04:11.599' or '04:11,599' or '04:11.599' * @param time '00:04:11,599' or '00:04:11.599' or '04:11,599' or '04:11.599'

View File

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

View File

@@ -1,17 +1,44 @@
import {SyntheticEvent} from 'react' import {SyntheticEvent} from 'react'
export const isEdgeBrowser = () => { export const isEdgeBrowser = () => {
const userAgent = navigator.userAgent.toLowerCase(); const userAgent = navigator.userAgent.toLowerCase()
return userAgent.includes('edg/') && !userAgent.includes('edge/'); return userAgent.includes('edg/') && !userAgent.includes('edge/')
} }
export const formatTime = (time: number) => { /**
if (!time) return '00:00' * 将总秒数格式化为 MM:SS 或 HH:MM:SS 格式的字符串。
* 如果时间小于 1 小时,则使用 MM:SS 格式。
* 如果时间大于或等于 1 小时,则使用 HH:MM:SS 格式。
*
* @param time 总秒数 (number)
* @returns string 格式化后的时间字符串 ('MM:SS' 或 'HH:MM:SS')
*/
export const formatTime = (time: number): string => {
// 1. 输入验证和处理 0 或负数的情况
if (typeof time !== 'number' || isNaN(time) || time <= 0) {
return '00:00'; // 对于无效输入、0 或负数,返回 '00:00'
}
const minutes = Math.floor(time / 60) // 取整确保我们处理的是整数秒
const seconds = Math.floor(time % 60) const totalSeconds = Math.floor(time);
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
} // 2. 计算小时、分钟和秒
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
// 3. 格式化各个部分,确保是两位数 (例如 0 -> '00', 5 -> '05', 10 -> '10')
const formattedSeconds = seconds.toString().padStart(2, '0');
const formattedMinutes = minutes.toString().padStart(2, '0');
// 4. 根据是否有小时来决定最终格式
if (hours > 0) {
const formattedHours = hours.toString().padStart(2, '0');
return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
} else {
return `${formattedMinutes}:${formattedSeconds}`;
}
};
/** /**
* @param time 2.82 * @param time 2.82

1
src/vite-env.d.ts vendored
View File

@@ -1,7 +1,6 @@
/// <reference types="vite/client" /> /// <reference types="vite/client" />
interface ImportMetaEnv { interface ImportMetaEnv {
readonly VITE_EXTENSION_ID: string
} }
interface ImportMeta { interface ImportMeta {

View File

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