Compare commits
146 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
e4693cde6a | ||
![]() |
fea22fae61 | ||
![]() |
d5b5b5d374 | ||
![]() |
17d4e60de0 | ||
![]() |
2cd633cbd4 | ||
![]() |
3ad198948f | ||
![]() |
774cc2726d | ||
![]() |
4765244638 | ||
![]() |
b0107c4959 | ||
![]() |
e900b11f05 | ||
![]() |
194df8525c | ||
![]() |
28bb3dbb96 | ||
![]() |
640f6d89fd | ||
![]() |
338e3145f2 | ||
![]() |
e2121e83bd | ||
![]() |
7583b05289 | ||
![]() |
ae60303a15 | ||
![]() |
5bcedf0c9d | ||
![]() |
d4e5e407a4 | ||
![]() |
ce2a2da6f5 | ||
![]() |
368f5d721c | ||
![]() |
21e2ca958c | ||
![]() |
149653ffac | ||
![]() |
f977b5e238 | ||
![]() |
c13ef4597b | ||
![]() |
65026f62af | ||
![]() |
bcff8b4f90 | ||
![]() |
ee1eaf9e08 | ||
![]() |
cc732de8e6 | ||
![]() |
cccf7e6149 | ||
![]() |
30dc724ebb | ||
![]() |
51a7e998b9 | ||
![]() |
556ccef4b2 | ||
![]() |
42b719fb98 | ||
![]() |
fa66445466 | ||
![]() |
d711b2abf8 | ||
![]() |
47fcb1de11 | ||
![]() |
be3d3624bc | ||
![]() |
910b1ce6d9 | ||
![]() |
0a6bda667e | ||
![]() |
5a0a123af9 | ||
![]() |
b481b8a55a | ||
![]() |
3cede8650d | ||
![]() |
69e0497081 | ||
![]() |
8776186486 | ||
![]() |
d31c2d7b03 | ||
![]() |
1c5534fc82 | ||
![]() |
44895a98a6 | ||
![]() |
53d3522fd6 | ||
![]() |
56bb936aaa | ||
![]() |
d52a4e8378 | ||
![]() |
f69bc7f040 | ||
![]() |
5005806917 | ||
![]() |
6928b5fa00 | ||
![]() |
5ba2b9fd6d | ||
![]() |
d11b517d5e | ||
![]() |
2460b0b822 | ||
![]() |
9bcf6ee48d | ||
![]() |
2bb5f41189 | ||
![]() |
e5a645611b | ||
![]() |
97bd23bcc0 | ||
![]() |
02aaba6a83 | ||
![]() |
3e1e69f13e | ||
![]() |
9384c1419a | ||
![]() |
50e6579116 | ||
![]() |
751961687b | ||
![]() |
5ce146803e | ||
![]() |
b10d816e18 | ||
![]() |
4b13230dc2 | ||
![]() |
6e9132d657 | ||
![]() |
86746dc2a3 | ||
![]() |
7df231443e | ||
![]() |
296469ebf1 | ||
![]() |
3140b91f72 | ||
![]() |
b690a7ef08 | ||
![]() |
6a921d4c5a | ||
![]() |
5c37ea9d4e | ||
![]() |
15dde412e4 | ||
![]() |
240f760ae9 | ||
![]() |
6c008feb3f | ||
![]() |
b91e1476d6 | ||
![]() |
faa15b9510 | ||
![]() |
d7b274d338 | ||
![]() |
fde80103d9 | ||
![]() |
77f6864f44 | ||
![]() |
c71e8e2eab | ||
![]() |
4f03e75b6d | ||
![]() |
b44a73cd2f | ||
![]() |
1bae3f8406 | ||
![]() |
69453f7bce | ||
![]() |
4189818939 | ||
![]() |
090651c4b5 | ||
![]() |
b385730152 | ||
![]() |
d52231227e | ||
![]() |
b283695b02 | ||
![]() |
c1c21c2fee | ||
![]() |
a8352e2725 | ||
![]() |
d3537a39ba | ||
![]() |
a2655710e5 | ||
![]() |
e025723d9f | ||
![]() |
38baf571b7 | ||
![]() |
a02825b3eb | ||
![]() |
cf737b9976 | ||
![]() |
e238d83f78 | ||
![]() |
46955e0a59 | ||
![]() |
564f032e3a | ||
![]() |
6ffb9073ab | ||
![]() |
c19ad1b0e1 | ||
![]() |
8b3bd44d59 | ||
![]() |
c3b53a016c | ||
![]() |
125996408e | ||
![]() |
abb97813d1 | ||
![]() |
f50a2e3abd | ||
![]() |
e3ddf386cb | ||
![]() |
4d9128eb29 | ||
![]() |
288c9eda81 | ||
![]() |
66cd431c3b | ||
![]() |
5b6b4211a4 | ||
![]() |
da7357c7eb | ||
![]() |
1ff47ee148 | ||
![]() |
1bf8188980 | ||
![]() |
3a9a8d9d56 | ||
![]() |
78b5d7a18b | ||
![]() |
ff6dae7a21 | ||
![]() |
3adb541e99 | ||
![]() |
1ef7537251 | ||
![]() |
be6b94164d | ||
![]() |
1f1d48b56a | ||
![]() |
02b7a09f42 | ||
![]() |
9320928b34 | ||
![]() |
1fbdeaa8f6 | ||
![]() |
2f22a8c4a2 | ||
![]() |
baa15581ed | ||
![]() |
7e4733dfa8 | ||
![]() |
5c6dcab653 | ||
![]() |
975c524369 | ||
![]() |
4a6ebf0894 | ||
![]() |
64059f71e5 | ||
![]() |
be97b1d51a | ||
![]() |
19553de975 | ||
![]() |
39d3f9be8e | ||
![]() |
75235883a5 | ||
![]() |
aeac55cb6b | ||
![]() |
cf1bd97dec | ||
![]() |
915cd8022d | ||
![]() |
e7f3eef6dc |
1
.cursorrules
Normal file
@@ -0,0 +1 @@
|
|||||||
|
This chrome extension project use typescript, react, vite, tailwindcss, daisyui.
|
@@ -1,3 +1,3 @@
|
|||||||
NODE_ENV=production
|
NODE_ENV=production
|
||||||
|
|
||||||
VITE_ENV=chrome
|
VITE_ENV=chrome
|
@@ -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
|
@@ -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"
|
||||||
|
28
README.md
@@ -21,20 +21,20 @@
|
|||||||
|
|
||||||
- [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)
|
|
||||||
|
|
||||||
## 使用说明
|
## 使用说明
|
||||||
|
|
||||||
安装扩展后,在哔哩哔哩网站观看视频时,视频右侧会显示字幕列表面板。
|
安装扩展后,在哔哩哔哩网站观看视频时,视频右侧会显示字幕列表面板。
|
||||||
|
|
||||||
|
### 使用本地Ollama模型
|
||||||
|
如果你使用本地Ollama模型,需要配置环境变量:`OLLAMA_ORIGINS=chrome-extension://bciglihaegkdhoogebcdblfhppoilclp`,否则访问会出现403错误。
|
||||||
|
|
||||||
|
然后在插件配置里,apiKey随便填一个,服务器地址填`http://localhost:11434`,模型选自定义,然后填入自定义模型名如`llama2`。
|
||||||
|
|
||||||
|
但是测试发现llama2 7b模型比较弱,无法返回需要的json格式,因此总结很可能会无法解析响应而报错(但提问功能不需要解析响应格式,因此没问题)。
|
||||||
|
|
||||||
## 交流联系
|
## 交流联系
|
||||||
|
|
||||||
QQ群:194536885
|
|
||||||
|
|
||||||
微信公众号:IndieKKY
|
|
||||||
|
|
||||||
twitter:[https://twitter.com/IndieKky](https://twitter.com/IndieKky)
|
|
||||||
|
|
||||||
github: [IndieKKY](https://github.com/IndieKKY)
|
github: [IndieKKY](https://github.com/IndieKKY)
|
||||||
|
|
||||||
## 问题反馈
|
## 问题反馈
|
||||||
@@ -45,8 +45,14 @@ github: [IndieKKY](https://github.com/IndieKKY)
|
|||||||
node版本:18.15.0
|
node版本:18.15.0
|
||||||
包管理器:pnpm
|
包管理器:pnpm
|
||||||
|
|
||||||
本地开发时,`pnpm run dev`可以开启本地调试,但只能调试部分功能;
|
- 本地调试:`pnpm run dev`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
|
||||||
`pnpm run build_chrome`可以构建项目,然后浏览器扩展中加载`dist`目录即可,此方式可以调试完整功能,但不是很方便,从改代码到构建完看到效果耗时比较长(取决于你的电脑性能)。
|
- 打生产包:`pnpm run build`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
|
||||||
|
|
||||||
|
注:`./push.sh`是作者自用脚本,可以忽略。
|
||||||
|
|
||||||
|
提示:最新版浏览器安全方面有更新,开发调试可能有问题,会报csp错误!
|
||||||
|
暂时的解决办法是`pnpm run dev`运行起来后,手动将`dist/manifest.json`文件里的web_accessible_resources里的use_dynamic_url都修改为false,然后浏览器扩展管理页面点击重载一下,就能正常(是@crxjs/vite-plugin依赖的问题,这个依赖很长时间没更新了,这个bug也没修复,暂时没发现更好的解决办法)。
|
||||||
|
构建后正常,关键是fix.cjs里将use_dynamic_url设置为false的这个操作。
|
||||||
|
|
||||||
## 贡献指南
|
## 贡献指南
|
||||||
|
|
||||||
@@ -62,7 +68,3 @@ node版本:18.15.0
|
|||||||
## 许可证
|
## 许可证
|
||||||
|
|
||||||
该项目采用 **MIT 许可证**,详情请参阅许可证文件。
|
该项目采用 **MIT 许可证**,详情请参阅许可证文件。
|
||||||
|
|
||||||
## 截图
|
|
||||||
|
|
||||||

|
|
||||||
|
15
fix.cjs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
console.log('fix.js loaded');
|
||||||
|
|
||||||
|
const fs = require('fs')
|
||||||
|
|
||||||
|
//copy index.html to sidepanel.html
|
||||||
|
fs.copyFileSync('./dist/index.html', './dist/sidepanel.html')
|
||||||
|
|
||||||
|
//set all use_dynamic_url to false
|
||||||
|
const manifest = require('./dist/manifest.json')
|
||||||
|
manifest.web_accessible_resources.forEach(resource => {
|
||||||
|
resource.use_dynamic_url = false
|
||||||
|
})
|
||||||
|
fs.writeFileSync('./dist/manifest.json', JSON.stringify(manifest, null, 2))
|
||||||
|
|
||||||
|
console.log('fix.js done');
|
@@ -1,11 +0,0 @@
|
|||||||
console.log('fixChrome.js loaded');
|
|
||||||
|
|
||||||
const fs = require('fs')
|
|
||||||
|
|
||||||
const manifest = require('./dist/manifest.json')
|
|
||||||
manifest.web_accessible_resources[0].resources.push('index.html')
|
|
||||||
manifest.action.default_popup = 'popup.html'
|
|
||||||
//写回文件
|
|
||||||
fs.writeFileSync('./dist/manifest.json', JSON.stringify(manifest, null, 2))
|
|
||||||
|
|
||||||
console.log('fixChrome.js done');
|
|
@@ -1,22 +0,0 @@
|
|||||||
console.log('fixFirefox.js loaded');
|
|
||||||
|
|
||||||
const fs = require('fs')
|
|
||||||
|
|
||||||
const manifest = require('./dist/manifest.json')
|
|
||||||
manifest.web_accessible_resources[0].resources.push('index.html')
|
|
||||||
manifest.action.default_popup = 'popup.html'
|
|
||||||
//browser_specific_settings
|
|
||||||
manifest.browser_specific_settings = {
|
|
||||||
"gecko": {
|
|
||||||
"id": "bilibili-subtitle@indiekky"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//background
|
|
||||||
manifest.background = {
|
|
||||||
type: "module",
|
|
||||||
scripts: [manifest.background.service_worker]
|
|
||||||
}
|
|
||||||
//写回文件
|
|
||||||
fs.writeFileSync('./dist/manifest.json', JSON.stringify(manifest, null, 2))
|
|
||||||
|
|
||||||
console.log('fixFirefox.js done');
|
|
@@ -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">
|
||||||
@@ -11,6 +11,6 @@
|
|||||||
<meta name="keywords" content="哔哩哔哩,b站,字幕" />
|
<meta name="keywords" content="哔哩哔哩,b站,字幕" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<script type="module" src="/src/main.tsx"></script>
|
<script type="module" src="/src/Main.tsx"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
63
manifest.config.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import {defineManifest} from '@crxjs/vite-plugin'
|
||||||
|
// @ts-ignore
|
||||||
|
import packageJson from './package.json'
|
||||||
|
|
||||||
|
const {version} = packageJson
|
||||||
|
|
||||||
|
// Convert from Semver (example: 0.1.0-beta6)
|
||||||
|
const [major, minor, patch, label = '0'] = version
|
||||||
|
// can only contain digits, dots, or dash
|
||||||
|
.replace(/[^\d.-]+/g, '')
|
||||||
|
// split into version parts
|
||||||
|
.split(/[.-]/)
|
||||||
|
|
||||||
|
export default defineManifest(async (env) => ({
|
||||||
|
"name": '__MSG_appName__',
|
||||||
|
"description": '__MSG_appDescription__',
|
||||||
|
"version": `${major}.${minor}.${patch}`,
|
||||||
|
"default_locale": "zh_CN",
|
||||||
|
"manifest_version": 3,
|
||||||
|
"permissions": [
|
||||||
|
"sidePanel",
|
||||||
|
"storage",
|
||||||
|
],
|
||||||
|
"host_permissions": [
|
||||||
|
"http://localhost/*",
|
||||||
|
"http://127.0.0.1/*"
|
||||||
|
],
|
||||||
|
"background": {
|
||||||
|
"service_worker": "src/chrome/background.ts",
|
||||||
|
"type": "module"
|
||||||
|
},
|
||||||
|
"options_page": "options.html",
|
||||||
|
"content_scripts": [
|
||||||
|
{
|
||||||
|
"matches": ["https://*.bilibili.com/*"],
|
||||||
|
"js": ["src/inject/inject.ts"]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"icons": {
|
||||||
|
"16": "favicon-16x16.png",
|
||||||
|
"32": "favicon-32x32.png",
|
||||||
|
"48": "favicon-48x48.png",
|
||||||
|
"128": "favicon-128x128.png"
|
||||||
|
},
|
||||||
|
"action": {
|
||||||
|
// "default_popup": "popup.html",
|
||||||
|
"default_icon": {
|
||||||
|
"16": "favicon-16x16.png",
|
||||||
|
"32": "favicon-32x32.png",
|
||||||
|
"48": "favicon-48x48.png",
|
||||||
|
"128": "favicon-128x128.png"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"web_accessible_resources": [
|
||||||
|
{
|
||||||
|
"matches": ["https://*.bilibili.com/*"],
|
||||||
|
"resources": [
|
||||||
|
"index.html",
|
||||||
|
],
|
||||||
|
"use_dynamic_url": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}))
|
@@ -1,37 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "哔哩哔哩字幕列表",
|
|
||||||
"description": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!",
|
|
||||||
"version": "1.9.2",
|
|
||||||
"manifest_version": 3,
|
|
||||||
"permissions": [
|
|
||||||
"storage"
|
|
||||||
],
|
|
||||||
"host_permissions": [
|
|
||||||
"http://localhost/*",
|
|
||||||
"http://127.0.0.1/*"
|
|
||||||
],
|
|
||||||
"background": {
|
|
||||||
"service_worker": "src/chrome/background.ts"
|
|
||||||
},
|
|
||||||
"content_scripts": [
|
|
||||||
{
|
|
||||||
"matches": ["https://www.bilibili.com/video/*", "https://www.bilibili.com/list/*"],
|
|
||||||
"js": ["src/chrome/content-script.cjs"]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"icons": {
|
|
||||||
"16": "favicon-16x16.png",
|
|
||||||
"32": "favicon-32x32.png",
|
|
||||||
"48": "favicon-48x48.png",
|
|
||||||
"128": "favicon-128x128.png"
|
|
||||||
},
|
|
||||||
"action": {
|
|
||||||
"default_popup": "index.html",
|
|
||||||
"default_icon": {
|
|
||||||
"16": "favicon-16x16.png",
|
|
||||||
"32": "favicon-32x32.png",
|
|
||||||
"48": "favicon-48x48.png",
|
|
||||||
"128": "favicon-128x128.png"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
17
options.html
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en" data-theme="light">
|
||||||
|
<head>
|
||||||
|
<title>哔哔君 - 哔哩哔哩字幕列表选项</title>
|
||||||
|
<meta 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-32x32.png" sizes="32x32">
|
||||||
|
<link rel="icon" href="/favicon-64x64.png" sizes="64x64">
|
||||||
|
<link rel="icon" href="/favicon-128x128.png" sizes="128x128">
|
||||||
|
<link rel="manifest" href="/manifest.json" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="module" src="/src/Main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
17
package.json
@@ -1,15 +1,13 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "bilibili-subtitle",
|
"name": "bilibili-subtitle",
|
||||||
"version": "1.9.2",
|
"version": "1.13.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "哔哩哔哩字幕列表",
|
"description": "哔哩哔哩字幕列表",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc && vite build -m production_chrome",
|
"build": "tsc && vite build && node fix.cjs",
|
||||||
"build_chrome": "pnpm run build && node fixChrome.cjs",
|
|
||||||
"build_firefox": "pnpm run build && node fixFirefox.cjs",
|
|
||||||
"fix": "eslint --fix --quiet ."
|
"fix": "eslint --fix --quiet ."
|
||||||
},
|
},
|
||||||
"author": "IndieKKY",
|
"author": "IndieKKY",
|
||||||
@@ -17,8 +15,9 @@
|
|||||||
"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.4.2",
|
"@kky002/kky-util": "^1.13.13",
|
||||||
"@logto/react": "1.0.0-beta.13",
|
"@logto/react": "1.0.0-beta.13",
|
||||||
"@popperjs/core": "^2.11.6",
|
"@popperjs/core": "^2.11.6",
|
||||||
"@reduxjs/toolkit": "^1.8.5",
|
"@reduxjs/toolkit": "^1.8.5",
|
||||||
@@ -26,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",
|
||||||
@@ -48,9 +48,10 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/line-clamp": "^0.4.2",
|
"@tailwindcss/line-clamp": "^0.4.2",
|
||||||
"@tailwindcss/typography": "^0.5.8",
|
"@tailwindcss/typography": "^0.5.8",
|
||||||
"@types/chrome": "^0.0.203",
|
"@types/chrome": "^0.0.277",
|
||||||
"@types/js-search": "^1.4.0",
|
"@types/js-search": "^1.4.0",
|
||||||
"@types/lodash-es": "^4.17.6",
|
"@types/lodash-es": "^4.17.6",
|
||||||
|
"@types/node": "^20.8.10",
|
||||||
"@types/pako": "^2.0.0",
|
"@types/pako": "^2.0.0",
|
||||||
"@types/qs": "^6.9.7",
|
"@types/qs": "^6.9.7",
|
||||||
"@types/react": "^18.0.20",
|
"@types/react": "^18.0.20",
|
||||||
@@ -59,7 +60,7 @@
|
|||||||
"@types/uuid": "^8.3.4",
|
"@types/uuid": "^8.3.4",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.37.0",
|
"@typescript-eslint/eslint-plugin": "^5.37.0",
|
||||||
"@typescript-eslint/parser": "^5.37.0",
|
"@typescript-eslint/parser": "^5.37.0",
|
||||||
"@vitejs/plugin-react": "^2.1.0",
|
"@vitejs/plugin-react": "^2.2.0",
|
||||||
"autoprefixer": "^10.4.13",
|
"autoprefixer": "^10.4.13",
|
||||||
"eslint": "8.22.0",
|
"eslint": "8.22.0",
|
||||||
"eslint-config-standard": "^17.0.0",
|
"eslint-config-standard": "^17.0.0",
|
||||||
@@ -73,6 +74,6 @@
|
|||||||
"rollup-plugin-visualizer": "^5.8.3",
|
"rollup-plugin-visualizer": "^5.8.3",
|
||||||
"tailwindcss": "^3.2.4",
|
"tailwindcss": "^3.2.4",
|
||||||
"typescript": "^4.8.3",
|
"typescript": "^4.8.3",
|
||||||
"vite": "^3.1.1"
|
"vite": "^3.2.7"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
5800
pnpm-lock.yaml
generated
8
public/_locales/zh_CN/messages.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"appName": {
|
||||||
|
"message": "哔哔君 - bilibili哔哩哔哩字幕列表"
|
||||||
|
},
|
||||||
|
"appDescription": {
|
||||||
|
"message": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!"
|
||||||
|
}
|
||||||
|
}
|
BIN
public/bibijun.png
Normal file
After Width: | Height: | Size: 74 KiB |
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 9.5 KiB |
Before Width: | Height: | Size: 278 B After Width: | Height: | Size: 651 B |
Before Width: | Height: | Size: 363 B After Width: | Height: | Size: 1.5 KiB |
Before Width: | Height: | Size: 400 B After Width: | Height: | Size: 2.4 KiB |
BIN
public/favicon-64x64.png
Normal file
After Width: | Height: | Size: 3.5 KiB |
Before Width: | Height: | Size: 447 B After Width: | Height: | Size: 4.2 KiB |
Before Width: | Height: | Size: 23 KiB |
Before Width: | Height: | Size: 40 KiB |
@@ -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>
|
|
BIN
public/shot.jpg
Before Width: | Height: | Size: 50 KiB |
@@ -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 |
4
push.sh
@@ -17,13 +17,11 @@ done
|
|||||||
|
|
||||||
# Update the version in package.json
|
# Update the version in package.json
|
||||||
sed -i '' "s/\"version\": \"$current_version\"/\"version\": \"$new_version\"/g" package.json
|
sed -i '' "s/\"version\": \"$current_version\"/\"version\": \"$new_version\"/g" package.json
|
||||||
# Update the version in manifest.json
|
|
||||||
sed -i '' "s/\"version\": \"$current_version\"/\"version\": \"$new_version\"/g" manifest.json
|
|
||||||
|
|
||||||
echo "Version updated to: $new_version"
|
echo "Version updated to: $new_version"
|
||||||
|
|
||||||
# build
|
# build
|
||||||
pnpm run build_chrome
|
pnpm run build
|
||||||
# zip dist
|
# zip dist
|
||||||
rm -f dist.zip
|
rm -f dist.zip
|
||||||
cd dist
|
cd dist
|
||||||
|
Before Width: | Height: | Size: 280 KiB |
Before Width: | Height: | Size: 867 KiB |
Before Width: | Height: | Size: 333 KiB |
Before Width: | Height: | Size: 413 KiB |
Before Width: | Height: | Size: 280 KiB |
16
sidepanel.html
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh" data-theme="light">
|
||||||
|
<head>
|
||||||
|
<title>哔哔君 - 哔哩哔哩字幕列表</title>
|
||||||
|
<meta 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="manifest" href="/manifest.json" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<meta name="description" content="哔哩哔哩字幕" />
|
||||||
|
<meta name="keywords" content="哔哩哔哩,b站,字幕" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="module" src="/src/Main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
60
src/App.tsx
@@ -1,45 +1,23 @@
|
|||||||
import React, {useCallback, useContext, useEffect, useMemo} from 'react'
|
import React, {useCallback, useEffect, useMemo} from 'react'
|
||||||
import 'tippy.js/dist/tippy.css'
|
import 'tippy.js/dist/tippy.css'
|
||||||
import {useAppDispatch, useAppSelector} from './hooks/redux'
|
import {useAppDispatch, useAppSelector} from './hooks/redux'
|
||||||
import {setEnvData, setEnvReady, setFold, setPage, setTempData, setTempReady} from './redux/envReducer'
|
import {setEnvData, setEnvReady, setTempData, setTempReady} from './redux/envReducer'
|
||||||
import Header from './biz/Header'
|
|
||||||
import Body from './biz/Body'
|
|
||||||
import useSubtitleService from './hooks/useSubtitleService'
|
|
||||||
import {cloneDeep} from 'lodash-es'
|
import {cloneDeep} from 'lodash-es'
|
||||||
import {EVENT_EXPAND, PAGE_MAIN, PAGE_SETTINGS, STORAGE_ENV, STORAGE_TEMP} from './const'
|
import {STORAGE_ENV, STORAGE_TEMP} from './consts/const'
|
||||||
import {EventBusContext} from './Router'
|
import OptionsPage from './pages/OptionsPage'
|
||||||
import useTranslateService from './hooks/useTranslateService'
|
|
||||||
import Settings from './biz/Settings'
|
|
||||||
import classNames from 'classnames'
|
|
||||||
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 {setTheme} from './util/biz_util'
|
import useMessageService from './hooks/useMessageService'
|
||||||
import useSearchService from './hooks/useSearchService'
|
import MainPage from './pages/MainPage'
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const dispatch = useAppDispatch()
|
const dispatch = useAppDispatch()
|
||||||
const envData = useAppSelector(state => state.env.envData)
|
const envData = useAppSelector(state => state.env.envData)
|
||||||
const tempData = useAppSelector(state => state.env.tempData)
|
const tempData = useAppSelector(state => state.env.tempData)
|
||||||
const fold = useAppSelector(state => state.env.fold)
|
const path = useAppSelector(state => state.env.path)
|
||||||
const eventBus = useContext(EventBusContext)
|
const envReady = useAppSelector(state => state.env.envReady)
|
||||||
const page = useAppSelector(state => state.env.page)
|
const tempReady = useAppSelector(state => state.env.tempReady)
|
||||||
const totalHeight = useAppSelector(state => state.env.totalHeight)
|
|
||||||
|
|
||||||
const foldCallback = useCallback(() => {
|
|
||||||
dispatch(setFold(!fold))
|
|
||||||
dispatch(setPage(PAGE_MAIN))
|
|
||||||
window.parent.postMessage({type: 'fold', fold: !fold}, '*')
|
|
||||||
}, [dispatch, fold])
|
|
||||||
|
|
||||||
// handle event
|
|
||||||
eventBus.useSubscription((event: any) => {
|
|
||||||
if (event.type === EVENT_EXPAND) {
|
|
||||||
if (fold) {
|
|
||||||
foldCallback()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// env数据
|
// env数据
|
||||||
const savedEnvData = useMemo(() => {
|
const savedEnvData = useMemo(() => {
|
||||||
@@ -65,23 +43,13 @@ function App() {
|
|||||||
}, [dispatch])
|
}, [dispatch])
|
||||||
useLocalStorage<TempData>('chrome_client', STORAGE_TEMP, savedTempData, onLoadTemp)
|
useLocalStorage<TempData>('chrome_client', STORAGE_TEMP, savedTempData, onLoadTemp)
|
||||||
|
|
||||||
// theme改变时,设置主题
|
|
||||||
useEffect(() => {
|
|
||||||
setTheme(envData.theme)
|
|
||||||
}, [envData.theme])
|
|
||||||
|
|
||||||
// services
|
// services
|
||||||
useSubtitleService()
|
useMessageService()
|
||||||
useTranslateService()
|
|
||||||
useSearchService()
|
|
||||||
|
|
||||||
return <div className={classNames('select-none', import.meta.env.VITE_ENV === 'web-dev'?'w-[350px]':'w-full')} style={{
|
return <div>
|
||||||
height: fold?undefined:`${totalHeight}px`,
|
<Toaster position={path === 'app'?'bottom-center':'top-center'}/>
|
||||||
}}>
|
{path === 'app' && <MainPage/>}
|
||||||
<Header foldCallback={foldCallback}/>
|
{path === 'options' && envReady && tempReady && <OptionsPage/>}
|
||||||
{!fold && page === PAGE_MAIN && <Body/>}
|
|
||||||
{!fold && page === PAGE_SETTINGS && <Settings/>}
|
|
||||||
<Toaster position='bottom-center'/>
|
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -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 './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')
|
@@ -1,15 +1,20 @@
|
|||||||
import App from './App'
|
import App from './App'
|
||||||
import {useEventEmitter} from 'ahooks'
|
import {useEventEmitter} from 'ahooks'
|
||||||
import React from 'react'
|
import React, { useEffect } from 'react'
|
||||||
|
import { useAppDispatch } from './hooks/redux'
|
||||||
|
import { setPath } from './redux/envReducer'
|
||||||
|
|
||||||
export const EventBusContext = React.createContext<any>(null)
|
export const EventBusContext = React.createContext<any>(null)
|
||||||
|
|
||||||
const map: { [key: string]: string } = {
|
const map: { [key: string]: string } = {
|
||||||
|
'/options.html': 'options',
|
||||||
|
'/sidepanel.html': 'app',
|
||||||
// '/close': 'close',
|
// '/close': 'close',
|
||||||
}
|
}
|
||||||
|
|
||||||
const Router = () => {
|
const Router = () => {
|
||||||
const path = map[window.location.pathname] ?? 'app'
|
const path = map[window.location.pathname] ?? 'app'
|
||||||
|
const dispatch = useAppDispatch()
|
||||||
|
|
||||||
if (path === 'close') {
|
if (path === 'close') {
|
||||||
window.close()
|
window.close()
|
||||||
@@ -18,8 +23,12 @@ const Router = () => {
|
|||||||
// 事件总线
|
// 事件总线
|
||||||
const eventBus = useEventEmitter()
|
const eventBus = useEventEmitter()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
dispatch(setPath(path as 'app' | 'options'))
|
||||||
|
}, [dispatch, path])
|
||||||
|
|
||||||
return <EventBusContext.Provider value={eventBus}>
|
return <EventBusContext.Provider value={eventBus}>
|
||||||
{path === 'app' && <App/>}
|
{(path === 'app' || path === 'options') && <App/>}
|
||||||
</EventBusContext.Provider>
|
</EventBusContext.Provider>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
439
src/biz/Body.tsx
@@ -1,439 +0,0 @@
|
|||||||
import React, {useCallback, useEffect, useMemo, useRef} from 'react'
|
|
||||||
import {
|
|
||||||
setAskFold,
|
|
||||||
setAskQuestion,
|
|
||||||
setAutoScroll,
|
|
||||||
setAutoTranslate,
|
|
||||||
setCheckAutoScroll,
|
|
||||||
setFoldAll,
|
|
||||||
setNeedScroll,
|
|
||||||
setPage,
|
|
||||||
setSearchText,
|
|
||||||
setSegmentFold,
|
|
||||||
setTempData
|
|
||||||
} from '../redux/envReducer'
|
|
||||||
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
|
||||||
import {
|
|
||||||
AiOutlineAim,
|
|
||||||
AiOutlineCloseCircle,
|
|
||||||
BsDashSquare,
|
|
||||||
BsPlusSquare,
|
|
||||||
FaGripfire,
|
|
||||||
FaQuestion,
|
|
||||||
FaRegArrowAltCircleDown,
|
|
||||||
IoWarning,
|
|
||||||
MdExpand,
|
|
||||||
RiTranslate
|
|
||||||
} from 'react-icons/all'
|
|
||||||
import classNames from 'classnames'
|
|
||||||
import toast from 'react-hot-toast'
|
|
||||||
import SegmentCard from './SegmentCard'
|
|
||||||
import {
|
|
||||||
ASK_ENABLED_DEFAULT,
|
|
||||||
HEADER_HEIGHT,
|
|
||||||
PAGE_SETTINGS,
|
|
||||||
RECOMMEND_HEIGHT,
|
|
||||||
SEARCH_BAR_HEIGHT,
|
|
||||||
SUMMARIZE_ALL_THRESHOLD,
|
|
||||||
TITLE_HEIGHT
|
|
||||||
} from '../const'
|
|
||||||
import {FaClipboardList} from 'react-icons/fa'
|
|
||||||
import useTranslate from '../hooks/useTranslate'
|
|
||||||
import {getSummarize} from '../util/biz_util'
|
|
||||||
import {openUrl} from '@kky002/kky-util'
|
|
||||||
import Markdown from '../components/Markdown'
|
|
||||||
import {random} from 'lodash-es'
|
|
||||||
import useKeyService from '../hooks/useKeyService'
|
|
||||||
|
|
||||||
const Body = () => {
|
|
||||||
const dispatch = useAppDispatch()
|
|
||||||
const noVideo = useAppSelector(state => state.env.noVideo)
|
|
||||||
const autoTranslate = useAppSelector(state => state.env.autoTranslate)
|
|
||||||
const autoScroll = useAppSelector(state => state.env.autoScroll)
|
|
||||||
const segments = useAppSelector(state => state.env.segments)
|
|
||||||
const foldAll = useAppSelector(state => state.env.foldAll)
|
|
||||||
const envData = useAppSelector(state => state.env.envData)
|
|
||||||
const compact = useAppSelector(state => state.env.tempData.compact)
|
|
||||||
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
|
|
||||||
const translateEnable = useAppSelector(state => state.env.envData.translateEnable)
|
|
||||||
const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable)
|
|
||||||
const {addSummarizeTask, addAskTask} = useTranslate()
|
|
||||||
const infos = useAppSelector(state => state.env.infos)
|
|
||||||
const askFold = useAppSelector(state => state.env.askFold)
|
|
||||||
const askQuestion = useAppSelector(state => state.env.askQuestion)
|
|
||||||
const askContent = useAppSelector(state => state.env.askContent)
|
|
||||||
const askStatus = useAppSelector(state => state.env.askStatus)
|
|
||||||
const askError = useAppSelector(state => state.env.askError)
|
|
||||||
const bodyRef = useRef<any>()
|
|
||||||
const curOffsetTop = useAppSelector(state => state.env.curOffsetTop)
|
|
||||||
const checkAutoScroll = useAppSelector(state => state.env.checkAutoScroll)
|
|
||||||
const needScroll = useAppSelector(state => state.env.needScroll)
|
|
||||||
const totalHeight = useAppSelector(state => state.env.totalHeight)
|
|
||||||
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
|
|
||||||
const title = useAppSelector(state => state.env.title)
|
|
||||||
const fontSize = useAppSelector(state => state.env.envData.fontSize)
|
|
||||||
const searchText = useAppSelector(state => state.env.searchText)
|
|
||||||
const recommendIdx = useMemo(() => random(0, 3), [])
|
|
||||||
const showSearchInput = useMemo(() => {
|
|
||||||
return (segments != null && segments.length > 0) && (envData.searchEnabled ? envData.searchEnabled : (envData.askEnabled ?? ASK_ENABLED_DEFAULT))
|
|
||||||
}, [envData.askEnabled, envData.searchEnabled, segments])
|
|
||||||
const searchPlaceholder = useMemo(() => {
|
|
||||||
let placeholder = ''
|
|
||||||
if (envData.searchEnabled) {
|
|
||||||
if (envData.askEnabled??ASK_ENABLED_DEFAULT) {
|
|
||||||
placeholder = '搜索或提问字幕内容'
|
|
||||||
} else {
|
|
||||||
placeholder = '搜索字幕内容'
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (envData.askEnabled??ASK_ENABLED_DEFAULT) {
|
|
||||||
placeholder = '提问字幕内容'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return placeholder
|
|
||||||
}, [envData.askEnabled, envData.searchEnabled])
|
|
||||||
|
|
||||||
const normalCallback = useCallback(() => {
|
|
||||||
dispatch(setTempData({
|
|
||||||
compact: false
|
|
||||||
}))
|
|
||||||
}, [dispatch])
|
|
||||||
|
|
||||||
const compactCallback = useCallback(() => {
|
|
||||||
dispatch(setTempData({
|
|
||||||
compact: true
|
|
||||||
}))
|
|
||||||
}, [dispatch])
|
|
||||||
|
|
||||||
const posCallback = useCallback(() => {
|
|
||||||
dispatch(setNeedScroll(true))
|
|
||||||
}, [dispatch])
|
|
||||||
|
|
||||||
const onSummarizeAll = useCallback(() => {
|
|
||||||
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
|
|
||||||
if (!apiKey) {
|
|
||||||
dispatch(setPage(PAGE_SETTINGS))
|
|
||||||
toast.error('需要先设置ApiKey!')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const segments_ = []
|
|
||||||
for (const segment of segments ?? []) {
|
|
||||||
const summary = segment.summaries[curSummaryType]
|
|
||||||
if (!summary || summary.status === 'init' || (summary.status === 'done' && summary.error)) {
|
|
||||||
segments_.push(segment)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (segments_.length === 0) {
|
|
||||||
toast.error('没有可总结的段落!')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (segments_.length < SUMMARIZE_ALL_THRESHOLD || confirm(`确定总结${segments_.length}个段落?`)) {
|
|
||||||
for (const segment of segments_) {
|
|
||||||
addSummarizeTask(curSummaryType, segment).catch(console.error)
|
|
||||||
}
|
|
||||||
toast.success(`已添加${segments_.length}个总结任务!`)
|
|
||||||
}
|
|
||||||
}, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
|
|
||||||
|
|
||||||
const onFoldAll = useCallback(() => {
|
|
||||||
dispatch(setFoldAll(!foldAll))
|
|
||||||
dispatch(setAskFold(!foldAll))
|
|
||||||
for (const segment of segments ?? []) {
|
|
||||||
dispatch(setSegmentFold({
|
|
||||||
segmentStartIdx: segment.startIdx,
|
|
||||||
fold: !foldAll
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}, [dispatch, foldAll, segments])
|
|
||||||
|
|
||||||
const toggleAutoTranslateCallback = useCallback(() => {
|
|
||||||
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
|
|
||||||
if (apiKey) {
|
|
||||||
dispatch(setAutoTranslate(!autoTranslate))
|
|
||||||
} else {
|
|
||||||
dispatch(setPage(PAGE_SETTINGS))
|
|
||||||
toast.error('需要先设置ApiKey!')
|
|
||||||
}
|
|
||||||
}, [autoTranslate, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey])
|
|
||||||
|
|
||||||
const onEnableAutoScroll = useCallback(() => {
|
|
||||||
dispatch(setAutoScroll(true))
|
|
||||||
dispatch(setNeedScroll(true))
|
|
||||||
}, [dispatch])
|
|
||||||
|
|
||||||
const onWheel = useCallback(() => {
|
|
||||||
if (autoScroll) {
|
|
||||||
dispatch(setAutoScroll(false))
|
|
||||||
}
|
|
||||||
}, [autoScroll, dispatch])
|
|
||||||
|
|
||||||
const onCopy = useCallback(() => {
|
|
||||||
const [success, content] = getSummarize(title, segments, curSummaryType)
|
|
||||||
if (success) {
|
|
||||||
navigator.clipboard.writeText(content).then(() => {
|
|
||||||
toast.success('复制成功')
|
|
||||||
}).catch(console.error)
|
|
||||||
}
|
|
||||||
}, [curSummaryType, segments, title])
|
|
||||||
|
|
||||||
const onSearchTextChange = useCallback((e: any) => {
|
|
||||||
const searchText = e.target.value
|
|
||||||
dispatch(setSearchText(searchText))
|
|
||||||
}, [dispatch])
|
|
||||||
|
|
||||||
const onClearSearchText = useCallback(() => {
|
|
||||||
dispatch(setSearchText(''))
|
|
||||||
}, [dispatch])
|
|
||||||
|
|
||||||
const onAsk = useCallback(() => {
|
|
||||||
if ((envData.askEnabled??ASK_ENABLED_DEFAULT) && searchText) {
|
|
||||||
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
|
|
||||||
if (apiKey) {
|
|
||||||
if (segments != null && segments.length > 0) {
|
|
||||||
dispatch(setAskQuestion(searchText))
|
|
||||||
addAskTask(segments[0], searchText).catch(console.error)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
dispatch(setPage(PAGE_SETTINGS))
|
|
||||||
toast.error('需要先设置ApiKey!')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [addAskTask, dispatch, envData.aiType, envData.apiKey, envData.askEnabled, envData.geminiApiKey, searchText, segments])
|
|
||||||
|
|
||||||
const onSetAsk = useCallback(() => {
|
|
||||||
dispatch(setSearchText(askQuestion??''))
|
|
||||||
}, [askQuestion, dispatch])
|
|
||||||
|
|
||||||
const onAskFold = useCallback(() => {
|
|
||||||
dispatch(setAskFold(!askFold))
|
|
||||||
}, [askFold, dispatch])
|
|
||||||
|
|
||||||
// service
|
|
||||||
useKeyService()
|
|
||||||
|
|
||||||
// 自动滚动
|
|
||||||
useEffect(() => {
|
|
||||||
if (checkAutoScroll && curOffsetTop && autoScroll && !needScroll) {
|
|
||||||
if (bodyRef.current.scrollTop <= curOffsetTop - bodyRef.current.offsetTop - (totalHeight-160) + (floatKeyPointsSegIdx != null ? 100 : 0) ||
|
|
||||||
bodyRef.current.scrollTop >= curOffsetTop - bodyRef.current.offsetTop - 40 - 10
|
|
||||||
) {
|
|
||||||
dispatch(setNeedScroll(true))
|
|
||||||
dispatch(setCheckAutoScroll(false))
|
|
||||||
console.debug('need scroll')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [autoScroll, checkAutoScroll, curOffsetTop, dispatch, floatKeyPointsSegIdx, needScroll, totalHeight])
|
|
||||||
|
|
||||||
return <div className='relative'>
|
|
||||||
{/* title */}
|
|
||||||
<div className='absolute top-1 left-6 flex-center gap-1'>
|
|
||||||
<AiOutlineAim className='cursor-pointer' onClick={posCallback} title='滚动到视频位置'/>
|
|
||||||
{segments != null && segments.length > 0 &&
|
|
||||||
<MdExpand className={classNames('cursor-pointer', foldAll ? 'text-accent' : '')} onClick={onFoldAll}
|
|
||||||
title='展开/折叠全部'/>}
|
|
||||||
</div>
|
|
||||||
<div className='flex justify-center'>
|
|
||||||
<div className='tabs'>
|
|
||||||
<a className={classNames('tab tab-sm tab-bordered', !compact && 'tab-active')}
|
|
||||||
onClick={normalCallback}>列表视图</a>
|
|
||||||
<a className={classNames('tab tab-sm tab-bordered', compact && 'tab-active')}
|
|
||||||
onClick={compactCallback}>文章视图</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className='absolute top-1 right-6'>
|
|
||||||
{translateEnable && <div className='tooltip tooltip-left cursor-pointer' data-tip='点击切换自动翻译'
|
|
||||||
onClick={toggleAutoTranslateCallback}>
|
|
||||||
<RiTranslate className={autoTranslate ? 'text-accent' : ''}/>
|
|
||||||
</div>}
|
|
||||||
{summarizeEnable &&
|
|
||||||
<div className='tooltip tooltip-left cursor-pointer z-[100] ml-2' data-tip='总结全部' onClick={onSummarizeAll}>
|
|
||||||
<FaClipboardList/>
|
|
||||||
</div>}
|
|
||||||
{noVideo && <div className='tooltip tooltip-left ml-2' data-tip='当前浏览器不支持视频跳转'>
|
|
||||||
<IoWarning className='text-warning'/>
|
|
||||||
</div>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* search */}
|
|
||||||
{showSearchInput && <div className='px-2 py-1 flex flex-col relative'>
|
|
||||||
<input type='text' className='input input-xs bg-base-200' placeholder={searchPlaceholder} value={searchText} onChange={onSearchTextChange}/>
|
|
||||||
{searchText && <button className='absolute top-1 right-2 btn btn-ghost btn-xs btn-circle text-base-content/75' onClick={onClearSearchText}><AiOutlineCloseCircle/></button>}
|
|
||||||
</div>}
|
|
||||||
|
|
||||||
{/* auto scroll btn */}
|
|
||||||
{!autoScroll && <div
|
|
||||||
className='absolute z-[999] top-[96px] right-6 tooltip tooltip-left cursor-pointer rounded-full bg-primary/25 hover:bg-primary/75 text-primary-content p-1.5 text-xl'
|
|
||||||
data-tip='开启自动滚动'
|
|
||||||
onClick={onEnableAutoScroll}>
|
|
||||||
<FaRegArrowAltCircleDown className={autoScroll ? 'text-accent' : ''}/>
|
|
||||||
</div>}
|
|
||||||
|
|
||||||
{/* body */}
|
|
||||||
<div ref={bodyRef} onWheel={onWheel}
|
|
||||||
className={classNames('flex flex-col gap-1.5 overflow-y-auto select-text scroll-smooth', floatKeyPointsSegIdx != null && 'pb-[100px]')}
|
|
||||||
style={{
|
|
||||||
height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT - RECOMMEND_HEIGHT - (showSearchInput ? SEARCH_BAR_HEIGHT : 0)}px`
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{/* ask */}
|
|
||||||
{(envData.askEnabled ?? ASK_ENABLED_DEFAULT) && (searchText || askQuestion) &&
|
|
||||||
<div className='shadow bg-base-200 my-0.5 mx-1.5 p-1.5 rounded flex flex-col justify-center items-center'>
|
|
||||||
<div className='w-full relative flex justify-center min-h-[20px]'>
|
|
||||||
<div className='absolute left-0 top-0 bottom-0 text-xs select-none flex-center desc'>
|
|
||||||
{askFold
|
|
||||||
? <BsPlusSquare className='cursor-pointer' onClick={onAskFold}/> :
|
|
||||||
<BsDashSquare className='cursor-pointer' onClick={onAskFold}/>}
|
|
||||||
</div>
|
|
||||||
<div className="tabs">
|
|
||||||
<a className="tab tab-lifted tab-xs tab-disabled cursor-default"></a>
|
|
||||||
<a className='tab tab-lifted tab-xs tab-active'><FaQuestion/>提问</a>
|
|
||||||
<a className="tab tab-lifted tab-xs tab-disabled cursor-default"></a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{!askFold && askQuestion &&
|
|
||||||
<div className='link link-hover text-sm font-medium max-w-[90%]' onClick={onSetAsk}>{askQuestion}</div>}
|
|
||||||
{!askFold && askContent &&
|
|
||||||
<div className={classNames('font-medium max-w-[90%] mt-1', fontSize === 'large' ? 'text-sm' : 'text-xs')}>
|
|
||||||
<Markdown content={askContent}/>
|
|
||||||
</div>}
|
|
||||||
{!askFold && <button disabled={askStatus === 'pending'}
|
|
||||||
className={classNames('btn btn-link btn-xs', askStatus === 'pending' && 'loading')}
|
|
||||||
onClick={onAsk}>{askStatus === 'init' ? '点击提问' : (askStatus === 'pending' ? '生成中' : '重新生成')}</button>}
|
|
||||||
{!askFold && askStatus === 'init' && <div className='desc-lighter text-xs'>提问举例:这个视频说了什么</div>}
|
|
||||||
{!askFold && askError && <div className='text-xs text-error'>{askError}</div>}
|
|
||||||
</div>}
|
|
||||||
|
|
||||||
{/* segments */}
|
|
||||||
{segments?.map((segment, segmentIdx) => <SegmentCard key={segment.startIdx} segment={segment}
|
|
||||||
segmentIdx={segmentIdx} bodyRef={bodyRef}/>)}
|
|
||||||
|
|
||||||
{/* tip */}
|
|
||||||
<div className='text-sm font-semibold text-center'>快捷键提示</div>
|
|
||||||
<ul className='list-disc text-sm desc pl-5'>
|
|
||||||
<li>单击字幕跳转,双击字幕跳转+切换暂停。</li>
|
|
||||||
<li>alt+单击字幕复制单条字幕。</li>
|
|
||||||
<li>上下方向键来移动当前字幕(可先点击字幕使焦点在字幕列表内)。</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
{/* <div className='flex flex-col items-center text-center pt-1 pb-2'> */}
|
|
||||||
{/* <div className='font-semibold text-accent'>💡<span className='underline underline-offset-4'>提示</span>💡</div> */}
|
|
||||||
{/* <div className='text-sm desc px-2'>可以尝试将<span className='text-amber-600 font-semibold'>概览</span>生成的内容粘贴到<span */}
|
|
||||||
{/* className='text-secondary/75 font-semibold'>视频评论</span>里,发布后看看有什么效果🥳 */}
|
|
||||||
{/* </div> */}
|
|
||||||
{/* {(segments?.length ?? 0) > 0 && <button className='mt-1.5 btn btn-xs btn-info' */}
|
|
||||||
{/* onClick={onCopy}>点击复制生成的{SUMMARIZE_TYPES[curSummaryType].name}<RiFileCopy2Line/> */}
|
|
||||||
{/* </button>} */}
|
|
||||||
{/* </div> */}
|
|
||||||
<div className='flex flex-col'>
|
|
||||||
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
|
|
||||||
<div className='font-semibold text-accent flex items-center gap-1'><img src='/bibigpt.png'
|
|
||||||
alt='BibiGPT logo'
|
|
||||||
className='w-8 h-8'/>BibiGPT
|
|
||||||
</div>
|
|
||||||
<div className='text-sm px-2 desc'>这是<span className='text-amber-600 font-semibold text-base'>网页</span>版的字幕列表,支持<span
|
|
||||||
className='font-semibold'>任意</span>视频提取字幕总结(包括没有字幕的视频)
|
|
||||||
</div>
|
|
||||||
<div className='flex gap-2'>
|
|
||||||
<a title='BibiGPT' href='https://bibigpt.co/r/bilibili'
|
|
||||||
onClick={(e) => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://bibigpt.co/r/bilibili')
|
|
||||||
}} className='link text-sm text-accent'>✨ BibiGPT ✨</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
|
|
||||||
<div className='font-semibold text-accent flex items-center gap-1'><img src='/youtube-caption.png'
|
|
||||||
alt='youtube caption logo'
|
|
||||||
className='w-8 h-8'/>YouTube Caption
|
|
||||||
</div>
|
|
||||||
<div className='text-sm px-2 desc'>这是<span className='text-amber-600 font-semibold text-base'>YouTube</span>版的字幕列表
|
|
||||||
</div>
|
|
||||||
<div className='flex gap-2'>
|
|
||||||
<a title='Chrome商店' href='https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf'
|
|
||||||
onClick={(e) => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
|
|
||||||
}} className='link text-sm text-accent'>Chrome商店</a>
|
|
||||||
<a title='Edge商店'
|
|
||||||
href='https://microsoftedge.microsoft.com/addons/detail/galeejdehabppfgooagmkclpppnbccpc'
|
|
||||||
onClick={e => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://microsoftedge.microsoft.com/addons/detail/galeejdehabppfgooagmkclpppnbccpc')
|
|
||||||
}} className='link text-sm text-accent'>Edge商店</a>
|
|
||||||
<a title='Crx搜搜(国内可访问)'
|
|
||||||
href='https://www.crxsoso.com/webstore/detail/fiaeclpicddpifeflpmlgmbjgaedladf'
|
|
||||||
onClick={(e) => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://www.crxsoso.com/webstore/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
|
|
||||||
}} className='link text-sm text-accent'>Crx搜搜(国内可访问)</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
|
|
||||||
<div className='font-semibold text-accent flex items-center gap-1'><img src='/immersive-summary.png'
|
|
||||||
alt='Immersive Summary logo'
|
|
||||||
className='w-8 h-8'/>Immersive Summary
|
|
||||||
</div>
|
|
||||||
<div className='text-sm px-2 desc'>沉浸式总结,多种方式总结网页文章。</div>
|
|
||||||
<div className='flex gap-2'>
|
|
||||||
<a title='Chrome商店' href='https://chromewebstore.google.com/detail/mcijpllinkhflgpkggimnafkbmpiijah'
|
|
||||||
onClick={(e) => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://chromewebstore.google.com/detail/mcijpllinkhflgpkggimnafkbmpiijah')
|
|
||||||
}} className='link text-sm text-accent'>Chrome商店</a>
|
|
||||||
<a title='Crx搜搜(国内可访问)'
|
|
||||||
href='https://www.crxsoso.com/webstore/detail/mcijpllinkhflgpkggimnafkbmpiijah'
|
|
||||||
onClick={(e) => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://www.crxsoso.com/webstore/detail/mcijpllinkhflgpkggimnafkbmpiijah')
|
|
||||||
}} className='link text-sm text-accent'>Crx搜搜(国内可访问)</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* recommend */}
|
|
||||||
<div className='p-0.5' style={{
|
|
||||||
height: `${RECOMMEND_HEIGHT}px`
|
|
||||||
}}>
|
|
||||||
{recommendIdx === 0 && <div className='flex items-center gap-1.5 rounded shadow-sm bg-base-200/10'>
|
|
||||||
<a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://bibigpt.co/r/bilibili')
|
|
||||||
}}><img src='/bibigpt.png'
|
|
||||||
alt='BibiGPT logo'
|
|
||||||
className='w-8 h-8'/>✨ BibiGPT ✨</a>
|
|
||||||
<span className='text-sm desc'>支持任意视频的网页版总结。</span>
|
|
||||||
</div>}
|
|
||||||
{recommendIdx === 1 && <div className='flex items-center gap-1 rounded shadow-sm bg-base-200/10'>
|
|
||||||
<a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
|
|
||||||
}}><img src='/youtube-caption.png'
|
|
||||||
alt='youtube caption logo'
|
|
||||||
className='w-8 h-8'/>YouTube Caption</a>
|
|
||||||
<span className='text-sm desc'>YouTube版的字幕列表。</span>
|
|
||||||
</div>}
|
|
||||||
{recommendIdx === 2 && <div className='flex items-center gap-1 rounded shadow-sm bg-base-200/10'>
|
|
||||||
<a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://chromewebstore.google.com/detail/mcijpllinkhflgpkggimnafkbmpiijah')
|
|
||||||
}}><img src='/immersive-summary.png'
|
|
||||||
alt='Immersive Summary logo'
|
|
||||||
className='w-8 h-8'/>Immersive Summary</a>
|
|
||||||
<span className='text-sm desc'>沉浸式总结网页文章。</span>
|
|
||||||
</div>}
|
|
||||||
{recommendIdx === 3 && <div className='flex items-center gap-1 rounded shadow-sm bg-base-200/10'>
|
|
||||||
<a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => {
|
|
||||||
e.preventDefault()
|
|
||||||
openUrl('https://api.openai-up.com/register?aff=varM')
|
|
||||||
}}><img src='/openai-up.ico'
|
|
||||||
alt='Openai Up logo'
|
|
||||||
className='w-8 h-8'/>Openai代理</a>
|
|
||||||
<span className='text-sm desc flex items-center'>目前价格不到官方的6折<FaGripfire
|
|
||||||
className='text-amber-600'/></span>
|
|
||||||
</div>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
export default Body
|
|
@@ -1,59 +1,65 @@
|
|||||||
import {v4} from 'uuid'
|
import {v4} from 'uuid'
|
||||||
import {handleTask, initTaskService, tasksMap} from './taskService'
|
import {handleTask, initTaskService, tasksMap} from './taskService'
|
||||||
|
import { DEFAULT_USE_PORT, STORAGE_ENV} from '@/consts/const'
|
||||||
|
import { AllExtensionMessages } from '@/message-typings'
|
||||||
|
import { ExtensionMessaging, TAG_TARGET_INJECT } from '@kky002/kky-message'
|
||||||
|
|
||||||
/**
|
const setBadgeOk = async (tabId: number, ok: boolean) => {
|
||||||
* 消息处理入口
|
await chrome.action.setBadgeText({
|
||||||
* 注意:需要异步sendResponse时返回true
|
text: ok ? '✓' : '',
|
||||||
*/
|
tabId,
|
||||||
chrome.runtime.onMessage.addListener((event, sender, sendResponse) => {
|
})
|
||||||
console.debug('收到请求: ', event)
|
await chrome.action.setBadgeBackgroundColor({
|
||||||
if (event.type === 'p') { // 发出http请求
|
color: '#3245e8',
|
||||||
const {url, options} = event
|
tabId,
|
||||||
// 发出请求
|
})
|
||||||
fetch('http://localhost:27081/oproxy/p', {
|
await chrome.action.setBadgeTextColor({
|
||||||
method: 'POST',
|
color: '#ffffff',
|
||||||
headers: {
|
tabId,
|
||||||
'Content-Type': 'application/json',
|
})
|
||||||
},
|
}
|
||||||
body: JSON.stringify({
|
|
||||||
url,
|
const closeSidePanel = async () => {
|
||||||
options,
|
chrome.sidePanel.setOptions({
|
||||||
}),
|
enabled: false,
|
||||||
}).then(async res => await res.json()).then(sendResponse).catch(console.error)
|
})
|
||||||
return true
|
chrome.sidePanel.setPanelBehavior({
|
||||||
} else if (event.type === 'syncGet') { // sync.get
|
openPanelOnActionClick: false,
|
||||||
chrome.storage.sync.get(event.keys, data => {
|
})
|
||||||
sendResponse(data)
|
}
|
||||||
})
|
|
||||||
return true
|
const methods: {
|
||||||
} else if (event.type === 'syncSet') { // sync.set
|
[K in AllExtensionMessages['method']]: (params: Extract<AllExtensionMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
|
||||||
chrome.storage.sync.set(event.items).catch(console.error)
|
} = {
|
||||||
} else if (event.type === 'syncRemove') { // sync.remove
|
CLOSE_SIDE_PANEL: async (params, context) => {
|
||||||
chrome.storage.sync.remove(event.keys).catch(console.error)
|
closeSidePanel()
|
||||||
} else if (event.type === 'addTask') {
|
},
|
||||||
|
GET_TAB_ID: async (params, context) => {
|
||||||
|
return context.tabId
|
||||||
|
},
|
||||||
|
ADD_TASK: async (params, context) => {
|
||||||
// 新建任务
|
// 新建任务
|
||||||
const task: Task = {
|
const task: Task = {
|
||||||
id: v4(),
|
id: v4(),
|
||||||
startTime: Date.now(),
|
startTime: Date.now(),
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
def: event.taskDef,
|
def: params.taskDef,
|
||||||
}
|
}
|
||||||
tasksMap.set(task.id, task)
|
tasksMap.set(task.id, task)
|
||||||
|
|
||||||
// 立即触发任务
|
// 立即触发任务
|
||||||
handleTask(task).catch(console.error)
|
handleTask(task).catch(console.error)
|
||||||
|
|
||||||
|
return task
|
||||||
|
},
|
||||||
|
GET_TASK: async (params, context) => {
|
||||||
// 返回任务信息
|
// 返回任务信息
|
||||||
sendResponse(task)
|
const taskId = params.taskId
|
||||||
} else if (event.type === 'getTask') {
|
|
||||||
// 返回任务信息
|
|
||||||
const taskId = event.taskId
|
|
||||||
const task = tasksMap.get(taskId)
|
const task = tasksMap.get(taskId)
|
||||||
if (task == null) {
|
if (task == null) {
|
||||||
sendResponse({
|
return {
|
||||||
code: 'not_found',
|
code: 'not_found',
|
||||||
})
|
}
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检测删除缓存
|
// 检测删除缓存
|
||||||
@@ -62,11 +68,57 @@ chrome.runtime.onMessage.addListener((event, sender, sendResponse) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 返回任务
|
// 返回任务
|
||||||
sendResponse({
|
return {
|
||||||
code: 'ok',
|
code: 'ok',
|
||||||
task,
|
task,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
SHOW_FLAG: async (params, context) => {
|
||||||
|
await setBadgeOk(context.tabId!, params.show)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
// 初始化backgroundMessage
|
||||||
|
const extensionMessaging = new ExtensionMessaging(DEFAULT_USE_PORT)
|
||||||
|
extensionMessaging.init(methods)
|
||||||
|
|
||||||
|
chrome.runtime.onMessage.addListener((event: any, sender: chrome.runtime.MessageSender, sendResponse: (result: any) => void) => {
|
||||||
|
// debug((sender.tab != null) ? `tab ${sender.tab.url ?? ''} => ` : 'extension => ', event)
|
||||||
|
|
||||||
|
// legacy
|
||||||
|
if (event.type === 'syncGet') { // sync.get
|
||||||
|
chrome.storage.sync.get(event.keys, data => {
|
||||||
|
sendResponse(data)
|
||||||
})
|
})
|
||||||
|
return true
|
||||||
|
} else if (event.type === 'syncSet') { // sync.set
|
||||||
|
chrome.storage.sync.set(event.items).catch(console.error)
|
||||||
|
} else if (event.type === 'syncRemove') { // sync.remove
|
||||||
|
chrome.storage.sync.remove(event.keys).catch(console.error)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 点击扩展图标
|
||||||
|
chrome.action.onClicked.addListener(async (tab) => {
|
||||||
|
chrome.storage.sync.get(STORAGE_ENV, (envDatas) => {
|
||||||
|
const envDataStr = envDatas[STORAGE_ENV]
|
||||||
|
const envData = envDataStr ? JSON.parse(envDataStr) : {}
|
||||||
|
if (envData.sidePanel) {
|
||||||
|
chrome.sidePanel.setOptions({
|
||||||
|
enabled: true,
|
||||||
|
tabId: tab.id!,
|
||||||
|
path: '/sidepanel.html?tabId=' + tab.id,
|
||||||
|
})
|
||||||
|
chrome.sidePanel.setPanelBehavior({
|
||||||
|
openPanelOnActionClick: true,
|
||||||
|
})
|
||||||
|
chrome.sidePanel.open({
|
||||||
|
tabId: tab.id!,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
closeSidePanel()
|
||||||
|
extensionMessaging.sendMessage(false, tab.id!, TAG_TARGET_INJECT, 'TOGGLE_DISPLAY').catch(console.error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
initTaskService()
|
initTaskService()
|
||||||
|
@@ -1,256 +0,0 @@
|
|||||||
const {TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID} = require("../const");
|
|
||||||
var totalHeight = TOTAL_HEIGHT_DEF
|
|
||||||
|
|
||||||
const getVideoElement = () => {
|
|
||||||
const videoWrapper = document.getElementById('bilibili-player')
|
|
||||||
return videoWrapper.querySelector('video')
|
|
||||||
}
|
|
||||||
|
|
||||||
const timerIframe = setInterval(function () {
|
|
||||||
var danmukuBox = document.getElementById('danmukuBox')
|
|
||||||
if (danmukuBox) {
|
|
||||||
clearInterval(timerIframe)
|
|
||||||
|
|
||||||
//延迟插入iframe(插入太快,网络较差时容易出现b站网页刷新,原因暂时未知,可能b站的某种机制?)
|
|
||||||
setTimeout(() => {
|
|
||||||
var vKey = ''
|
|
||||||
for (const key in danmukuBox?.dataset) {
|
|
||||||
if (key.startsWith('v-')) {
|
|
||||||
vKey = key
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const iframe = document.createElement('iframe')
|
|
||||||
iframe.id = IFRAME_ID
|
|
||||||
iframe.src = chrome.runtime.getURL('index.html')
|
|
||||||
iframe.style = 'border: none; width: 100%; height: 44px;'
|
|
||||||
iframe.allow = 'clipboard-read; clipboard-write;'
|
|
||||||
if (vKey) {
|
|
||||||
iframe.dataset[vKey] = danmukuBox?.dataset[vKey]
|
|
||||||
}
|
|
||||||
//insert before first child
|
|
||||||
danmukuBox?.insertBefore(iframe, danmukuBox?.firstChild)
|
|
||||||
|
|
||||||
console.debug('iframe inserted')
|
|
||||||
}, 1500)
|
|
||||||
}
|
|
||||||
}, 1000)
|
|
||||||
|
|
||||||
let aid = 0
|
|
||||||
let title = ''
|
|
||||||
let pages = []
|
|
||||||
let pagesMap = {}
|
|
||||||
|
|
||||||
let lastAidOrBvid = null
|
|
||||||
const refreshVideoInfo = async () => {
|
|
||||||
const iframe = document.getElementById(IFRAME_ID)
|
|
||||||
if (!iframe) return
|
|
||||||
|
|
||||||
// fix: https://github.com/IndieKKY/bilibili-subtitle/issues/5
|
|
||||||
// 处理稍后再看的url( https://www.bilibili.com/list/watchlater?bvid=xxx&oid=xxx )
|
|
||||||
const pathSearchs = {}
|
|
||||||
location.search.slice(1).replace(/([^=&]*)=([^=&]*)/g, (matchs, a, b, c) => pathSearchs[a] = b)
|
|
||||||
|
|
||||||
// bvid
|
|
||||||
let aidOrBvid = pathSearchs.bvid // 默认为稍后再看
|
|
||||||
if (!aidOrBvid) {
|
|
||||||
let path = location.pathname
|
|
||||||
if (path.endsWith('/')) {
|
|
||||||
path = path.slice(0, -1)
|
|
||||||
}
|
|
||||||
const paths = path.split('/')
|
|
||||||
aidOrBvid = paths[paths.length - 1]
|
|
||||||
}
|
|
||||||
|
|
||||||
if (aidOrBvid !== lastAidOrBvid) {
|
|
||||||
// console.debug('refreshVideoInfo')
|
|
||||||
|
|
||||||
lastAidOrBvid = aidOrBvid
|
|
||||||
if (aidOrBvid) {
|
|
||||||
//aid,pages
|
|
||||||
let cid
|
|
||||||
let subtitles
|
|
||||||
if (aidOrBvid.toLowerCase().startsWith('av')) {//avxxx
|
|
||||||
aid = 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)
|
|
||||||
cid = pages[0].cid
|
|
||||||
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 => {
|
|
||||||
subtitles = res.data.subtitle.subtitles
|
|
||||||
})
|
|
||||||
} else {//bvxxx
|
|
||||||
await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${aidOrBvid}`, {credentials: 'include'}).then(res => res.json()).then(async res => {
|
|
||||||
title = res.data.title
|
|
||||||
aid = res.data.aid
|
|
||||||
cid = res.data.cid
|
|
||||||
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 => {
|
|
||||||
subtitles = res.data.subtitle.subtitles
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
//pagesMap
|
|
||||||
pagesMap = {}
|
|
||||||
pages.forEach(page => {
|
|
||||||
pagesMap[page.page + ''] = page
|
|
||||||
})
|
|
||||||
|
|
||||||
console.debug('refreshVideoInfo: ', aid, cid, pages, subtitles)
|
|
||||||
|
|
||||||
//send setVideoInfo
|
|
||||||
iframe.contentWindow.postMessage({
|
|
||||||
type: 'setVideoInfo',
|
|
||||||
url: location.origin + location.pathname,
|
|
||||||
title,
|
|
||||||
aid,
|
|
||||||
pages,
|
|
||||||
infos: subtitles,
|
|
||||||
}, '*')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let lastAid = null
|
|
||||||
let lastCid = null
|
|
||||||
const refreshSubtitles = () => {
|
|
||||||
const iframe = document.getElementById(IFRAME_ID)
|
|
||||||
if (!iframe) return
|
|
||||||
|
|
||||||
const urlSearchParams = new URLSearchParams(window.location.search)
|
|
||||||
const p = urlSearchParams.get('p') || 1
|
|
||||||
const page = pagesMap[p]
|
|
||||||
if (!page) return
|
|
||||||
const cid = page.cid
|
|
||||||
|
|
||||||
if (aid !== lastAid || cid !== lastCid) {
|
|
||||||
console.debug('refreshSubtitles', aid, cid)
|
|
||||||
|
|
||||||
lastAid = aid
|
|
||||||
lastCid = cid
|
|
||||||
if (aid && cid) {
|
|
||||||
fetch(`https://api.bilibili.com/x/player/v2?aid=${aid}&cid=${cid}`, {
|
|
||||||
credentials: 'include',
|
|
||||||
})
|
|
||||||
.then(res => res.json())
|
|
||||||
.then(res => {
|
|
||||||
// console.log('refreshSubtitles: ', aid, cid, res)
|
|
||||||
iframe.contentWindow.postMessage({
|
|
||||||
type: 'setInfos',
|
|
||||||
infos: res.data.subtitle.subtitles
|
|
||||||
}, '*')
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 监听消息
|
|
||||||
window.addEventListener("message", (event) => {
|
|
||||||
const {data} = event
|
|
||||||
|
|
||||||
if (data.type === 'fold') {
|
|
||||||
const iframe = document.getElementById(IFRAME_ID)
|
|
||||||
iframe.style.height = (data.fold ? HEADER_HEIGHT : totalHeight) + 'px'
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.type === 'move') {
|
|
||||||
const video = getVideoElement()
|
|
||||||
if (video) {
|
|
||||||
video.currentTime = data.time
|
|
||||||
if (data.togglePause) {
|
|
||||||
video.paused ? video.play() : video.pause()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//刷新视频信息
|
|
||||||
if (data.type === 'refreshVideoInfo') {
|
|
||||||
refreshVideoInfo().catch(console.error)
|
|
||||||
}
|
|
||||||
//刷新字幕
|
|
||||||
if (data.type === 'refreshSubtitles') {
|
|
||||||
refreshSubtitles()
|
|
||||||
}
|
|
||||||
if (data.type === 'getSubtitle') {
|
|
||||||
let url = data.info.subtitle_url
|
|
||||||
if (url.startsWith('http://')) {
|
|
||||||
url = url.replace('http://', 'https://')
|
|
||||||
}
|
|
||||||
fetch(url).then(res => res.json()).then(res => {
|
|
||||||
event.source.postMessage({
|
|
||||||
data: {
|
|
||||||
info: data.info,
|
|
||||||
data: res,
|
|
||||||
}, type: 'setSubtitle'
|
|
||||||
}, '*')
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.type === 'getCurrentTime') {
|
|
||||||
const video = getVideoElement()
|
|
||||||
if (video) {
|
|
||||||
event.source.postMessage({
|
|
||||||
data: {
|
|
||||||
currentTime: video.currentTime
|
|
||||||
}, type: 'setCurrentTime'
|
|
||||||
}, '*')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.type === 'getSettings') {
|
|
||||||
const videoElement = getVideoElement()
|
|
||||||
totalHeight = videoElement ? Math.min(Math.max(videoElement.offsetHeight, TOTAL_HEIGHT_MIN), TOTAL_HEIGHT_MAX) : TOTAL_HEIGHT_DEF
|
|
||||||
event.source.postMessage({
|
|
||||||
data: {
|
|
||||||
noVideo: !videoElement,
|
|
||||||
totalHeight,
|
|
||||||
}, type: 'setSettings'
|
|
||||||
}, '*')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.type === 'downloadAudio') {
|
|
||||||
const html = document.getElementsByTagName('html')[0].innerHTML
|
|
||||||
const playInfo = JSON.parse(html.match(/window.__playinfo__=(.+?)<\/script/)[1])
|
|
||||||
const audioUrl = playInfo.data.dash.audio[0].baseUrl
|
|
||||||
|
|
||||||
fetch(audioUrl).then(res => res.blob()).then(blob => {
|
|
||||||
const a = document.createElement('a')
|
|
||||||
a.href = URL.createObjectURL(blob)
|
|
||||||
a.download = `${title}.m4s`
|
|
||||||
a.click()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.type === 'updateTransResult') {
|
|
||||||
const trans = data.result??''
|
|
||||||
let text = document.getElementById('trans-result-text')
|
|
||||||
if (text) {
|
|
||||||
text.innerHTML = trans
|
|
||||||
} else {
|
|
||||||
const container = document.getElementsByClassName('bpx-player-subtitle-panel-wrap')?.[0]
|
|
||||||
if (container) {
|
|
||||||
const div = document.createElement('div')
|
|
||||||
div.style.display = 'flex'
|
|
||||||
div.style.justifyContent = 'center'
|
|
||||||
div.style.margin = '2px'
|
|
||||||
text = document.createElement('text')
|
|
||||||
text.id = 'trans-result-text'
|
|
||||||
text.innerHTML = trans
|
|
||||||
text.style.fontSize = '1rem'
|
|
||||||
text.style.padding = '5px'
|
|
||||||
text.style.color = 'white'
|
|
||||||
text.style.background = 'rgba(0, 0, 0, 0.4)'
|
|
||||||
div.append(text)
|
|
||||||
|
|
||||||
container.append(div)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
text && (text.style.display = trans ? 'block' : 'none')
|
|
||||||
}
|
|
||||||
}, false);
|
|
||||||
|
|
||||||
setInterval(() => {
|
|
||||||
refreshVideoInfo().catch(console.error)
|
|
||||||
refreshSubtitles()
|
|
||||||
}, 1000)
|
|
@@ -1,4 +1,4 @@
|
|||||||
import {DEFAULT_SERVER_URL_OPENAI} from '../const'
|
import {DEFAULT_SERVER_URL_OPENAI} from '../consts/const'
|
||||||
|
|
||||||
const getServerUrl = (serverUrl?: string) => {
|
const getServerUrl = (serverUrl?: string) => {
|
||||||
if (!serverUrl) {
|
if (!serverUrl) {
|
||||||
@@ -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()
|
|
||||||
}
|
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
import {TASK_EXPIRE_TIME} from '../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}`)
|
||||||
|
25
src/components/ApiKeyReminder.tsx
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import React from 'react'
|
||||||
|
import { useAppSelector } from '../hooks/redux'
|
||||||
|
import { openOptionsPage } from '../utils/chromeUtils'
|
||||||
|
|
||||||
|
const ApiKeyReminder: React.FC = () => {
|
||||||
|
const apiKey = useAppSelector(state => state.env.envData.apiKey)
|
||||||
|
|
||||||
|
if (apiKey) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-between p-2 bg-yellow-100 text-yellow-800 text-sm rounded-md">
|
||||||
|
<span>请先设置API密钥以使用总结及翻译功能</span>
|
||||||
|
<button
|
||||||
|
className="px-2 py-1 bg-yellow-200 hover:bg-yellow-300 rounded text-xs font-medium transition-colors"
|
||||||
|
onClick={openOptionsPage}
|
||||||
|
>
|
||||||
|
设置 →
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ApiKeyReminder
|
70
src/components/Ask.tsx
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import {AiOutlineCloseCircle, BsDashSquare, BsPlusSquare, FaQuestion} from 'react-icons/all'
|
||||||
|
import classNames from 'classnames'
|
||||||
|
import Markdown from '../components/Markdown'
|
||||||
|
import React, {useCallback} from 'react'
|
||||||
|
import {delAskInfo, mergeAskInfo, setTempData} from '../redux/envReducer'
|
||||||
|
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import useTranslate from '../hooks/useTranslate'
|
||||||
|
|
||||||
|
const Ask = (props: {
|
||||||
|
ask: AskInfo
|
||||||
|
}) => {
|
||||||
|
const {ask} = props
|
||||||
|
const dispatch = useAppDispatch()
|
||||||
|
const envData = useAppSelector(state => state.env.envData)
|
||||||
|
const fontSize = useAppSelector(state => state.env.envData.fontSize)
|
||||||
|
const segments = useAppSelector(state => state.env.segments)
|
||||||
|
const {addAskTask} = useTranslate()
|
||||||
|
|
||||||
|
const onRegenerate = useCallback(() => {
|
||||||
|
const apiKey = envData.apiKey
|
||||||
|
if (apiKey) {
|
||||||
|
if (segments != null && segments.length > 0) {
|
||||||
|
addAskTask(ask.id, segments[0], ask.question).catch(console.error)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
toast.error('请先在选项页面设置ApiKey!')
|
||||||
|
}
|
||||||
|
}, [addAskTask, ask.id, ask.question, envData.apiKey, segments])
|
||||||
|
|
||||||
|
const onAskFold = useCallback(() => {
|
||||||
|
dispatch(mergeAskInfo({
|
||||||
|
id: ask.id,
|
||||||
|
fold: !ask.fold
|
||||||
|
}))
|
||||||
|
}, [ask, dispatch])
|
||||||
|
|
||||||
|
const onClose = useCallback(() => {
|
||||||
|
dispatch(delAskInfo(ask.id))
|
||||||
|
}, [ask, dispatch])
|
||||||
|
|
||||||
|
return <div className='shadow bg-base-200 my-0.5 mx-1.5 p-1.5 rounded flex flex-col justify-center items-center'>
|
||||||
|
<div className='w-full relative flex justify-center min-h-[20px]'>
|
||||||
|
<div className='absolute left-0 top-0 bottom-0 text-xs select-none flex-center desc'>
|
||||||
|
{ask.fold
|
||||||
|
? <BsPlusSquare className='cursor-pointer' onClick={onAskFold}/> :
|
||||||
|
<BsDashSquare className='cursor-pointer' onClick={onAskFold}/>}
|
||||||
|
</div>
|
||||||
|
<button className='absolute right-0 top-0 bottom-0 btn btn-ghost btn-xs btn-circle text-base-content/75' onClick={onClose}>
|
||||||
|
<AiOutlineCloseCircle/>
|
||||||
|
</button>
|
||||||
|
<div className="tabs">
|
||||||
|
<a className="tab tab-lifted tab-xs tab-disabled cursor-default"></a>
|
||||||
|
<a className='tab tab-lifted tab-xs tab-active'><FaQuestion/>提问</a>
|
||||||
|
<a className="tab tab-lifted tab-xs tab-disabled cursor-default"></a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{!ask.fold && ask.question && <div className='text-sm font-medium max-w-[90%]'>{ask.question}</div>}
|
||||||
|
{!ask.fold && ask.content &&
|
||||||
|
<div className={classNames('font-medium max-w-[90%] mt-1', fontSize === 'large' ? 'text-sm' : 'text-xs')}>
|
||||||
|
<Markdown content={ask.content}/>
|
||||||
|
</div>}
|
||||||
|
{!ask.fold && <button disabled={ask.status !== 'done'}
|
||||||
|
className={classNames('btn btn-link btn-xs', ask.status === 'pending' && 'loading')}
|
||||||
|
onClick={onRegenerate}>{ask.status === 'pending' ? '生成中' : '重新生成'}</button>}
|
||||||
|
{!ask.fold && ask.error && <div className='text-xs text-error'>{ask.error}</div>}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Ask
|
425
src/components/Body.tsx
Normal file
@@ -0,0 +1,425 @@
|
|||||||
|
import React, { useCallback, useEffect, useMemo, useRef } from 'react'
|
||||||
|
import {
|
||||||
|
addAskInfo,
|
||||||
|
mergeAskInfo,
|
||||||
|
setAutoScroll,
|
||||||
|
setAutoTranslate,
|
||||||
|
setCheckAutoScroll,
|
||||||
|
setFoldAll,
|
||||||
|
setNeedScroll,
|
||||||
|
setSearchText,
|
||||||
|
setSegmentFold,
|
||||||
|
setTempData
|
||||||
|
} from '../redux/envReducer'
|
||||||
|
import { useAppDispatch, useAppSelector } from '../hooks/redux'
|
||||||
|
import {
|
||||||
|
AiOutlineAim,
|
||||||
|
AiOutlineCloseCircle,
|
||||||
|
FaRegArrowAltCircleDown,
|
||||||
|
IoWarning,
|
||||||
|
MdExpand,
|
||||||
|
RiTranslate
|
||||||
|
} from 'react-icons/all'
|
||||||
|
import classNames from 'classnames'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import SegmentCard from './SegmentCard'
|
||||||
|
import {
|
||||||
|
ASK_ENABLED_DEFAULT,
|
||||||
|
DEFAULT_USE_PORT,
|
||||||
|
HEADER_HEIGHT,
|
||||||
|
PAGE_SETTINGS,
|
||||||
|
SEARCH_BAR_HEIGHT,
|
||||||
|
SUMMARIZE_ALL_THRESHOLD,
|
||||||
|
TITLE_HEIGHT
|
||||||
|
} from '../consts/const'
|
||||||
|
import { FaClipboardList } from 'react-icons/fa'
|
||||||
|
import useTranslate from '../hooks/useTranslate'
|
||||||
|
import { openUrl } from '@kky002/kky-util'
|
||||||
|
import useKeyService from '../hooks/useKeyService'
|
||||||
|
import Ask from './Ask'
|
||||||
|
import { v4 } from 'uuid'
|
||||||
|
import RateExtension from '../components/RateExtension'
|
||||||
|
import ApiKeyReminder from './ApiKeyReminder'
|
||||||
|
import { useMessaging } from '@kky002/kky-message'
|
||||||
|
|
||||||
|
const Body = () => {
|
||||||
|
const dispatch = useAppDispatch()
|
||||||
|
const inputting = useAppSelector(state => state.env.inputting)
|
||||||
|
const noVideo = useAppSelector(state => state.env.noVideo)
|
||||||
|
const autoTranslate = useAppSelector(state => state.env.autoTranslate)
|
||||||
|
const autoScroll = useAppSelector(state => state.env.autoScroll)
|
||||||
|
const segments = useAppSelector(state => state.env.segments)
|
||||||
|
const foldAll = useAppSelector(state => state.env.foldAll)
|
||||||
|
const envData = useAppSelector(state => state.env.envData)
|
||||||
|
const compact = useAppSelector(state => state.env.tempData.compact)
|
||||||
|
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
|
||||||
|
const translateEnable = useAppSelector(state => state.env.envData.translateEnable)
|
||||||
|
const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable)
|
||||||
|
const { addSummarizeTask, addAskTask } = useTranslate()
|
||||||
|
// const infos = useAppSelector(state => state.env.infos)
|
||||||
|
const bodyRef = useRef<any>()
|
||||||
|
const curOffsetTop = useAppSelector(state => state.env.curOffsetTop)
|
||||||
|
const checkAutoScroll = useAppSelector(state => state.env.checkAutoScroll)
|
||||||
|
const needScroll = useAppSelector(state => state.env.needScroll)
|
||||||
|
const totalHeight = useAppSelector(state => state.env.totalHeight)
|
||||||
|
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
|
||||||
|
// const title = useAppSelector(state => state.env.title)
|
||||||
|
// const fontSize = useAppSelector(state => state.env.envData.fontSize)
|
||||||
|
const searchText = useAppSelector(state => state.env.searchText)
|
||||||
|
const asks = useAppSelector(state => state.env.asks)
|
||||||
|
const {disconnected} = useMessaging(DEFAULT_USE_PORT)
|
||||||
|
// const recommendIdx = useMemo(() => random(0, 3), [])
|
||||||
|
const showSearchInput = useMemo(() => {
|
||||||
|
return (segments != null && segments.length > 0) && (envData.searchEnabled ? envData.searchEnabled : (envData.askEnabled ?? ASK_ENABLED_DEFAULT))
|
||||||
|
}, [envData.askEnabled, envData.searchEnabled, segments])
|
||||||
|
const searchPlaceholder = useMemo(() => {
|
||||||
|
let placeholder = ''
|
||||||
|
if (envData.searchEnabled) {
|
||||||
|
if (envData.askEnabled ?? ASK_ENABLED_DEFAULT) {
|
||||||
|
placeholder = '搜索或提问字幕内容(按Enter提问)'
|
||||||
|
} else {
|
||||||
|
placeholder = '搜索字幕内容'
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (envData.askEnabled ?? ASK_ENABLED_DEFAULT) {
|
||||||
|
placeholder = '提问字幕内容'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return placeholder
|
||||||
|
}, [envData.askEnabled, envData.searchEnabled])
|
||||||
|
|
||||||
|
const normalCallback = useCallback(() => {
|
||||||
|
dispatch(setTempData({
|
||||||
|
compact: false
|
||||||
|
}))
|
||||||
|
}, [dispatch])
|
||||||
|
|
||||||
|
const compactCallback = useCallback(() => {
|
||||||
|
dispatch(setTempData({
|
||||||
|
compact: true
|
||||||
|
}))
|
||||||
|
}, [dispatch])
|
||||||
|
|
||||||
|
const posCallback = useCallback(() => {
|
||||||
|
dispatch(setNeedScroll(true))
|
||||||
|
}, [dispatch])
|
||||||
|
|
||||||
|
const onSummarizeAll = useCallback(() => {
|
||||||
|
const apiKey = envData.apiKey
|
||||||
|
if (!apiKey) {
|
||||||
|
toast.error('请先在选项页面设置ApiKey!')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const segments_ = []
|
||||||
|
for (const segment of segments ?? []) {
|
||||||
|
const summary = segment.summaries[curSummaryType]
|
||||||
|
if (!summary || summary.status === 'init' || (summary.status === 'done' && summary.error)) {
|
||||||
|
segments_.push(segment)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (segments_.length === 0) {
|
||||||
|
toast.error('没有可总结的段落!')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (segments_.length < SUMMARIZE_ALL_THRESHOLD || confirm(`确定总结${segments_.length}个段落?`)) {
|
||||||
|
for (const segment of segments_) {
|
||||||
|
addSummarizeTask(curSummaryType, segment).catch(console.error)
|
||||||
|
}
|
||||||
|
toast.success(`已添加${segments_.length}个总结任务!`)
|
||||||
|
}
|
||||||
|
}, [addSummarizeTask, curSummaryType, envData.apiKey, segments])
|
||||||
|
|
||||||
|
const onFoldAll = useCallback(() => {
|
||||||
|
dispatch(setFoldAll(!foldAll))
|
||||||
|
for (const ask of asks) {
|
||||||
|
dispatch(mergeAskInfo({
|
||||||
|
id: ask.id,
|
||||||
|
fold: !foldAll
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
for (const segment of segments ?? []) {
|
||||||
|
dispatch(setSegmentFold({
|
||||||
|
segmentStartIdx: segment.startIdx,
|
||||||
|
fold: !foldAll
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}, [asks, dispatch, foldAll, segments])
|
||||||
|
|
||||||
|
const toggleAutoTranslateCallback = useCallback(() => {
|
||||||
|
const apiKey = envData.apiKey
|
||||||
|
if (apiKey) {
|
||||||
|
dispatch(setAutoTranslate(!autoTranslate))
|
||||||
|
} else {
|
||||||
|
toast.error('请先在选项页面设置ApiKey!')
|
||||||
|
}
|
||||||
|
}, [autoTranslate, dispatch, envData.apiKey])
|
||||||
|
|
||||||
|
const onEnableAutoScroll = useCallback(() => {
|
||||||
|
dispatch(setAutoScroll(true))
|
||||||
|
dispatch(setNeedScroll(true))
|
||||||
|
}, [dispatch])
|
||||||
|
|
||||||
|
const onWheel = useCallback(() => {
|
||||||
|
if (autoScroll) {
|
||||||
|
dispatch(setAutoScroll(false))
|
||||||
|
}
|
||||||
|
}, [autoScroll, dispatch])
|
||||||
|
|
||||||
|
// const onCopy = useCallback(() => {
|
||||||
|
// const [success, content] = getSummarize(title, segments, curSummaryType)
|
||||||
|
// if (success) {
|
||||||
|
// navigator.clipboard.writeText(content).then(() => {
|
||||||
|
// toast.success('复制成功')
|
||||||
|
// }).catch(console.error)
|
||||||
|
// }
|
||||||
|
// }, [curSummaryType, segments, title])
|
||||||
|
|
||||||
|
const onSearchTextChange = useCallback((e: any) => {
|
||||||
|
const searchText = e.target.value
|
||||||
|
dispatch(setSearchText(searchText))
|
||||||
|
}, [dispatch])
|
||||||
|
|
||||||
|
const onClearSearchText = useCallback(() => {
|
||||||
|
dispatch(setSearchText(''))
|
||||||
|
}, [dispatch])
|
||||||
|
|
||||||
|
const onAsk = useCallback(() => {
|
||||||
|
if ((envData.askEnabled ?? ASK_ENABLED_DEFAULT) && searchText) {
|
||||||
|
const apiKey = envData.apiKey
|
||||||
|
if (apiKey) {
|
||||||
|
if (segments != null && segments.length > 0) {
|
||||||
|
const id = v4()
|
||||||
|
addAskTask(id, segments[0], searchText).catch(console.error)
|
||||||
|
// 添加ask
|
||||||
|
dispatch(addAskInfo({
|
||||||
|
id,
|
||||||
|
question: searchText,
|
||||||
|
status: 'pending',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
toast.error('请先在选项页面设置ApiKey!')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [addAskTask, dispatch, envData.apiKey, envData.askEnabled, searchText, segments])
|
||||||
|
|
||||||
|
// service
|
||||||
|
useKeyService()
|
||||||
|
|
||||||
|
// 自动滚动
|
||||||
|
useEffect(() => {
|
||||||
|
if (checkAutoScroll && curOffsetTop && autoScroll && !needScroll) {
|
||||||
|
if (bodyRef.current.scrollTop <= curOffsetTop - bodyRef.current.offsetTop - (totalHeight - 160) + (floatKeyPointsSegIdx != null ? 100 : 0) ||
|
||||||
|
bodyRef.current.scrollTop >= curOffsetTop - bodyRef.current.offsetTop - 40 - 10
|
||||||
|
) {
|
||||||
|
dispatch(setNeedScroll(true))
|
||||||
|
dispatch(setCheckAutoScroll(false))
|
||||||
|
console.debug('need scroll')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [autoScroll, checkAutoScroll, curOffsetTop, dispatch, floatKeyPointsSegIdx, needScroll, totalHeight])
|
||||||
|
|
||||||
|
return <div className='relative'>
|
||||||
|
{/* title */}
|
||||||
|
<div className='absolute top-1 left-6 flex-center gap-1'>
|
||||||
|
<AiOutlineAim className='cursor-pointer' onClick={posCallback} title='滚动到视频位置' />
|
||||||
|
{segments != null && segments.length > 0 &&
|
||||||
|
<MdExpand className={classNames('cursor-pointer', foldAll ? 'text-accent' : '')} onClick={onFoldAll}
|
||||||
|
title='展开/折叠全部' />}
|
||||||
|
</div>
|
||||||
|
<div className='flex justify-center'>
|
||||||
|
<div className='tabs'>
|
||||||
|
<a className={classNames('tab tab-sm tab-bordered', !compact && 'tab-active')}
|
||||||
|
onClick={normalCallback}>列表视图</a>
|
||||||
|
<a className={classNames('tab tab-sm tab-bordered', compact && 'tab-active')}
|
||||||
|
onClick={compactCallback}>文章视图</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='absolute top-1 right-6'>
|
||||||
|
{translateEnable && <div className='tooltip tooltip-left cursor-pointer' data-tip='点击切换自动翻译'
|
||||||
|
onClick={toggleAutoTranslateCallback}>
|
||||||
|
<RiTranslate className={autoTranslate ? 'text-accent' : ''} />
|
||||||
|
</div>}
|
||||||
|
{summarizeEnable &&
|
||||||
|
<div className='tooltip tooltip-left cursor-pointer z-[100] ml-2' data-tip='总结全部' onClick={onSummarizeAll}>
|
||||||
|
<FaClipboardList />
|
||||||
|
</div>}
|
||||||
|
{noVideo && <div className='tooltip tooltip-left ml-2' data-tip='当前浏览器不支持视频跳转'>
|
||||||
|
<IoWarning className='text-warning' />
|
||||||
|
</div>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* search */}
|
||||||
|
{showSearchInput && <div className='px-2 py-1 flex flex-col relative'>
|
||||||
|
<input type='text' className='input input-xs bg-base-200' placeholder={searchPlaceholder} value={searchText} onChange={onSearchTextChange} onKeyDown={e => {
|
||||||
|
// enter
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
if (!inputting) {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
onAsk()
|
||||||
|
dispatch(setSearchText(''))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}} />
|
||||||
|
{searchText && <button className='absolute top-1 right-2 btn btn-ghost btn-xs btn-circle text-base-content/75' onClick={onClearSearchText}><AiOutlineCloseCircle /></button>}
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{disconnected && <div className='flex flex-col justify-center items-center gap-2 text-sm bg-red-400 rounded mx-2'>
|
||||||
|
<span className='flex items-center gap-1 text-white'><AiOutlineCloseCircle className='text-white' />已断开连接</span>
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{/* auto scroll btn */}
|
||||||
|
{!autoScroll && <div
|
||||||
|
className='absolute z-[999] top-[96px] right-6 tooltip tooltip-left cursor-pointer rounded-full bg-primary/25 hover:bg-primary/75 text-primary-content p-1.5 text-xl'
|
||||||
|
data-tip='开启自动滚动'
|
||||||
|
onClick={onEnableAutoScroll}>
|
||||||
|
<FaRegArrowAltCircleDown className={autoScroll ? 'text-accent' : ''} />
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{/* body */}
|
||||||
|
<div ref={bodyRef} onWheel={onWheel}
|
||||||
|
className={classNames('flex flex-col gap-1.5 overflow-y-auto select-text scroll-smooth', floatKeyPointsSegIdx != null && 'pb-[100px]')}
|
||||||
|
style={{
|
||||||
|
height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT - (showSearchInput ? SEARCH_BAR_HEIGHT : 0)}px`
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* asks */}
|
||||||
|
{asks.map(ask => <Ask key={ask.id} ask={ask} />)}
|
||||||
|
|
||||||
|
{/* segments */}
|
||||||
|
{segments?.map((segment, segmentIdx) => <SegmentCard key={segment.startIdx} segment={segment}
|
||||||
|
segmentIdx={segmentIdx} bodyRef={bodyRef} />)}
|
||||||
|
|
||||||
|
{/* tip */}
|
||||||
|
<div className='text-sm font-semibold text-center'>快捷键提示</div>
|
||||||
|
<ul className='list-disc text-sm desc pl-5'>
|
||||||
|
<li>单击字幕跳转,双击字幕跳转+切换暂停。</li>
|
||||||
|
<li>alt+单击字幕复制单条字幕。</li>
|
||||||
|
<li>上下方向键来移动当前字幕(可先点击字幕使焦点在字幕列表内)。</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<ApiKeyReminder />
|
||||||
|
|
||||||
|
{/* <div className='flex flex-col items-center text-center pt-1 pb-2'> */}
|
||||||
|
{/* <div className='font-semibold text-accent'>💡<span className='underline underline-offset-4'>提示</span>💡</div> */}
|
||||||
|
{/* <div className='text-sm desc px-2'>可以尝试将<span className='text-amber-600 font-semibold'>概览</span>生成的内容粘贴到<span */}
|
||||||
|
{/* className='text-secondary/75 font-semibold'>视频评论</span>里,发布后看看有什么效果🥳 */}
|
||||||
|
{/* </div> */}
|
||||||
|
{/* {(segments?.length ?? 0) > 0 && <button className='mt-1.5 btn btn-xs btn-info' */}
|
||||||
|
{/* onClick={onCopy}>点击复制生成的{SUMMARIZE_TYPES[curSummaryType].name}<RiFileCopy2Line/> */}
|
||||||
|
{/* </button>} */}
|
||||||
|
{/* </div> */}
|
||||||
|
<div className='flex flex-col'>
|
||||||
|
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
|
||||||
|
<div className='font-semibold text-accent flex items-center gap-1'><img src='/bibigpt.png'
|
||||||
|
alt='BibiGPT logo'
|
||||||
|
className='w-8 h-8'/>BibiGPT
|
||||||
|
</div>
|
||||||
|
<div className='text-sm px-2 desc'>这是<span className='text-amber-600 font-semibold text-base'>网页</span>版的字幕列表,支持<span
|
||||||
|
className='font-semibold'>任意</span>视频提取字幕总结(包括没有字幕的视频)
|
||||||
|
</div>
|
||||||
|
<div className='flex gap-2'>
|
||||||
|
<a title='BibiGPT' href='https://bibigpt.co/r/bilibili'
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
openUrl('https://bibigpt.co/r/bilibili')
|
||||||
|
}} className='link text-sm text-accent'>✨ BibiGPT ✨</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
|
||||||
|
<div className='font-semibold text-accent flex items-center gap-1'><img src='/youtube-caption.png'
|
||||||
|
alt='youtube caption logo'
|
||||||
|
className='w-8 h-8' />YouTube Caption
|
||||||
|
</div>
|
||||||
|
<div className='text-sm px-2 desc'>这是<span className='text-amber-600 font-semibold text-base'>YouTube</span>版的字幕列表
|
||||||
|
</div>
|
||||||
|
<div className='flex gap-2'>
|
||||||
|
<a title='Chrome商店' href='https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf'
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
|
||||||
|
}} className='link text-sm text-accent'>Chrome商店</a>
|
||||||
|
<a title='Edge商店'
|
||||||
|
href='https://microsoftedge.microsoft.com/addons/detail/galeejdehabppfgooagmkclpppnbccpc'
|
||||||
|
onClick={e => {
|
||||||
|
e.preventDefault()
|
||||||
|
openUrl('https://microsoftedge.microsoft.com/addons/detail/galeejdehabppfgooagmkclpppnbccpc')
|
||||||
|
}} className='link text-sm text-accent'>Edge商店</a>
|
||||||
|
<a title='Crx搜搜(国内可访问)'
|
||||||
|
href='https://www.crxsoso.com/webstore/detail/fiaeclpicddpifeflpmlgmbjgaedladf'
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
openUrl('https://www.crxsoso.com/webstore/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
|
||||||
|
}} className='link text-sm text-accent'>Crx搜搜(国内可访问)</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* <div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'> */}
|
||||||
|
{/* <div className='font-semibold text-accent flex items-center gap-1'><img src='/my-article-summarizer.png' */}
|
||||||
|
{/* alt='My Article Summarizer logo' */}
|
||||||
|
{/* className='w-8 h-8'/>My Article Summarizer */}
|
||||||
|
{/* </div> */}
|
||||||
|
{/* <div className='text-sm px-2 desc'>网页文章总结(有每日免费额度,无需apikey)。</div> */}
|
||||||
|
{/* <div className='flex gap-2'> */}
|
||||||
|
{/* <a title='Chrome商店' href='https://chromewebstore.google.com/detail/my-article-summarizer/nanlpakfialleijdidafldapoifndngn' */}
|
||||||
|
{/* onClick={(e) => { */}
|
||||||
|
{/* e.preventDefault() */}
|
||||||
|
{/* openUrl('https://chromewebstore.google.com/detail/my-article-summarizer/nanlpakfialleijdidafldapoifndngn') */}
|
||||||
|
{/* }} className='link text-sm text-accent'>Chrome商店</a> */}
|
||||||
|
{/* <a title='Crx搜搜(国内可访问)' */}
|
||||||
|
{/* href='https://www.crxsoso.com/webstore/detail/nanlpakfialleijdidafldapoifndngn' */}
|
||||||
|
{/* onClick={(e) => { */}
|
||||||
|
{/* e.preventDefault() */}
|
||||||
|
{/* openUrl('https://www.crxsoso.com/webstore/detail/nanlpakfialleijdidafldapoifndngn') */}
|
||||||
|
{/* }} className='link text-sm text-accent'>Crx搜搜(国内可访问)</a> */}
|
||||||
|
{/* </div> */}
|
||||||
|
{/* </div> */}
|
||||||
|
</div>
|
||||||
|
<div className='p-2'><RateExtension /></div>
|
||||||
|
</div>
|
||||||
|
{/* recommend */}
|
||||||
|
{/* <div className='p-0.5' style={{ */}
|
||||||
|
{/* height: `${RECOMMEND_HEIGHT}px` */}
|
||||||
|
{/* }}> */}
|
||||||
|
{/* {recommendIdx === 0 && <div className='flex items-center gap-1.5 rounded shadow-sm bg-base-200/10'> */}
|
||||||
|
{/* <a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => { */}
|
||||||
|
{/* e.preventDefault() */}
|
||||||
|
{/* openUrl('https://bibigpt.co/r/bilibili') */}
|
||||||
|
{/* }}><img src='/bibigpt.png' */}
|
||||||
|
{/* alt='BibiGPT logo' */}
|
||||||
|
{/* className='w-8 h-8'/>✨ BibiGPT ✨</a> */}
|
||||||
|
{/* <span className='text-sm desc'>支持任意视频的网页版总结。</span> */}
|
||||||
|
{/* </div>} */}
|
||||||
|
{/* {recommendIdx === 1 && <div className='flex items-center gap-1 rounded shadow-sm bg-base-200/10'> */}
|
||||||
|
{/* <a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => { */}
|
||||||
|
{/* e.preventDefault() */}
|
||||||
|
{/* openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf') */}
|
||||||
|
{/* }}><img src='/youtube-caption.png' */}
|
||||||
|
{/* alt='youtube caption logo' */}
|
||||||
|
{/* className='w-8 h-8'/>YouTube Caption</a> */}
|
||||||
|
{/* <span className='text-sm desc'>YouTube版的字幕列表。</span> */}
|
||||||
|
{/* </div>} */}
|
||||||
|
{/* {recommendIdx === 2 && <div className='flex items-center gap-1 rounded shadow-sm bg-base-200/10'> */}
|
||||||
|
{/* <a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => { */}
|
||||||
|
{/* e.preventDefault() */}
|
||||||
|
{/* openUrl('https://chromewebstore.google.com/detail/nanlpakfialleijdidafldapoifndngn') */}
|
||||||
|
{/* }}><img src='/my-article-summarizer.png' */}
|
||||||
|
{/* alt='My Article Summarizer logo' */}
|
||||||
|
{/* className='w-8 h-8'/>My Article Summarizer</a> */}
|
||||||
|
{/* <span className='text-sm desc'>网页文章总结。</span> */}
|
||||||
|
{/* </div>} */}
|
||||||
|
{/* {recommendIdx === 3 && <div className='flex items-center gap-1 rounded shadow-sm bg-base-200/10'> */}
|
||||||
|
{/* <a className='link link-accent link-hover font-semibold text-sm flex items-center' onClick={(e) => { */}
|
||||||
|
{/* e.preventDefault() */}
|
||||||
|
{/* openUrl('https://api.openai-up.com/register?aff=varM') */}
|
||||||
|
{/* }}><img src='/openai-up.ico' */}
|
||||||
|
{/* alt='Openai Up logo' */}
|
||||||
|
{/* className='w-8 h-8'/>Openai代理</a> */}
|
||||||
|
{/* <span className='text-sm desc flex items-center'>目前价格不到官方的6折<FaGripfire */}
|
||||||
|
{/* className='text-amber-600'/></span> */}
|
||||||
|
{/* </div>} */}
|
||||||
|
{/* </div> */}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Body
|
@@ -1,6 +1,6 @@
|
|||||||
import React, {useMemo} from 'react'
|
import React, {useMemo} from 'react'
|
||||||
import {useAppSelector} from '../hooks/redux'
|
import {useAppSelector} from '../hooks/redux'
|
||||||
import {getDisplay, getTransText} from '../util/biz_util'
|
import {getDisplay, getTransText} from '../utils/bizUtil'
|
||||||
import classNames from 'classnames'
|
import classNames from 'classnames'
|
||||||
|
|
||||||
const CompactSegmentItem = (props: {
|
const CompactSegmentItem = (props: {
|
43
src/components/DebateChat.tsx
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import { useAppSelector } from '@/hooks/redux'
|
||||||
|
import React from 'react'
|
||||||
|
|
||||||
|
const DebateChat: React.FC<DebateProps> = ({ messages }) => {
|
||||||
|
const fontSize = useAppSelector(state => state.env.envData.fontSize)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
<div className="flex-1 overflow-y-auto p-4">
|
||||||
|
{messages.map((message, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className={`flex mb-4 ${
|
||||||
|
message.side === 'pro' ? 'justify-start' : 'justify-end'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`max-w-[85%] rounded-2xl p-3 shadow-md relative ${
|
||||||
|
message.side === 'pro'
|
||||||
|
? 'bg-blue-100 text-blue-800 ml-2'
|
||||||
|
: 'bg-green-100 text-green-800 mr-2'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<p className={`${fontSize === 'large' ? 'text-sm' : 'text-xs'} font-bold mb-1`}>
|
||||||
|
{message.side === 'pro' ? '正方' : '反方'}
|
||||||
|
</p>
|
||||||
|
<p className={fontSize === 'large' ? 'text-sm' : 'text-xs'}>{message.content}</p>
|
||||||
|
<div
|
||||||
|
className={`absolute w-4 h-4 ${
|
||||||
|
message.side === 'pro'
|
||||||
|
? 'bg-blue-100 -left-2 top-2 rounded-bl-full'
|
||||||
|
: 'bg-green-100 -right-2 top-2 rounded-br-full'
|
||||||
|
}`}
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default DebateChat
|
@@ -5,7 +5,7 @@ import {find, remove} from 'lodash-es'
|
|||||||
import {setCurFetched, setCurInfo, setData, setInfos, setUploadedTranscript} from '../redux/envReducer'
|
import {setCurFetched, setCurInfo, setData, setInfos, setUploadedTranscript} from '../redux/envReducer'
|
||||||
import MoreBtn from './MoreBtn'
|
import MoreBtn from './MoreBtn'
|
||||||
import classNames from 'classnames'
|
import classNames from 'classnames'
|
||||||
import {parseTranscript} from '../util/biz_util'
|
import {parseTranscript} from '../utils/bizUtil'
|
||||||
|
|
||||||
const Header = (props: {
|
const Header = (props: {
|
||||||
foldCallback: () => void
|
foldCallback: () => void
|
||||||
@@ -16,6 +16,7 @@ const Header = (props: {
|
|||||||
const curInfo = useAppSelector(state => state.env.curInfo)
|
const curInfo = useAppSelector(state => state.env.curInfo)
|
||||||
const fold = useAppSelector(state => state.env.fold)
|
const fold = useAppSelector(state => state.env.fold)
|
||||||
const uploadedTranscript = useAppSelector(state => state.env.uploadedTranscript)
|
const uploadedTranscript = useAppSelector(state => state.env.uploadedTranscript)
|
||||||
|
const envData = useAppSelector(state => state.env.envData)
|
||||||
|
|
||||||
const upload = useCallback(() => {
|
const upload = useCallback(() => {
|
||||||
const input = document.createElement('input')
|
const input = document.createElement('input')
|
||||||
@@ -76,8 +77,13 @@ const Header = (props: {
|
|||||||
upload()
|
upload()
|
||||||
}, [upload])
|
}, [upload])
|
||||||
|
|
||||||
return <div className='rounded-[6px] bg-[#f1f2f3] dark:bg-base-100 h-[44px] flex justify-between items-center cursor-pointer' onClick={foldCallback}>
|
return <div className='rounded-[6px] bg-[#f1f2f3] dark:bg-base-100 h-[44px] flex justify-between items-center cursor-pointer' onClick={() => {
|
||||||
|
if (!envData.sidePanel) {
|
||||||
|
foldCallback()
|
||||||
|
}
|
||||||
|
}}>
|
||||||
<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>
|
||||||
@@ -91,7 +97,7 @@ const Header = (props: {
|
|||||||
{infos?.map((item: any) => <option key={item.id} value={item.subtitle_url}>{item.lan_doc}</option>)}
|
{infos?.map((item: any) => <option key={item.id} value={item.subtitle_url}>{item.lan_doc}</option>)}
|
||||||
<option key='upload' value='upload'>上传(vtt/srt)</option>
|
<option key='upload' value='upload'>上传(vtt/srt)</option>
|
||||||
</select>}
|
</select>}
|
||||||
<IoIosArrowUp className={classNames('shrink-0 desc transform ease-in duration-300', fold?'rotate-180':'')}/>
|
{!envData.sidePanel && <IoIosArrowUp className={classNames('shrink-0 desc transform ease-in duration-300', fold?'rotate-180':'')}/>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
@@ -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,
|
||||||
@@ -11,13 +9,15 @@ import {
|
|||||||
import Popover from '../components/Popover'
|
import Popover from '../components/Popover'
|
||||||
import {Placement} from '@popperjs/core/lib/enums'
|
import {Placement} from '@popperjs/core/lib/enums'
|
||||||
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||||
import {setEnvData, setPage, setTempData} from '../redux/envReducer'
|
import {setEnvData, setTempData} from '../redux/envReducer'
|
||||||
import {EventBusContext} from '../Router'
|
import {EventBusContext} from '../Router'
|
||||||
import {EVENT_EXPAND, PAGE_SETTINGS} from '../const'
|
import {EVENT_EXPAND} from '../consts/const'
|
||||||
import {formatSrtTime, formatTime, formatVttTime} from '../util/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 '../util/biz_util'
|
import {getSummarize} from '../utils/bizUtil'
|
||||||
|
import dayjs from 'dayjs'
|
||||||
|
import { useMessage } from '@/hooks/useMessageService'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
placement: Placement
|
placement: Placement
|
||||||
@@ -68,33 +68,39 @@ 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(!!envData.sidePanel)
|
||||||
|
|
||||||
const downloadCallback = useCallback((download: boolean) => {
|
const downloadCallback = useCallback((download: boolean) => {
|
||||||
if (data == null) {
|
if (data == null) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let s, fileName
|
let fileName = title
|
||||||
|
let s, suffix
|
||||||
|
const time = ctime ? dayjs(ctime * 1000).format('YYYY-MM-DD HH:mm:ss') : '' // 2024-05-01 12:00:00
|
||||||
if (!downloadType || downloadType === 'text') {
|
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'
|
||||||
}
|
}
|
||||||
fileName = 'download.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'
|
||||||
}
|
}
|
||||||
fileName = 'download.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 + ', '
|
||||||
}
|
}
|
||||||
s = s.substring(0, s.length - 1) // remove last ','
|
s = s.substring(0, s.length - 1) // remove last ','
|
||||||
fileName = 'download.txt'
|
suffix = 'txt'
|
||||||
} else if (downloadType === 'srt') {
|
} else if (downloadType === 'srt') {
|
||||||
/**
|
/**
|
||||||
* 1
|
* 1
|
||||||
@@ -113,7 +119,7 @@ const MoreBtn = (props: Props) => {
|
|||||||
s += ss
|
s += ss
|
||||||
}
|
}
|
||||||
s = s.substring(0, s.length - 1)// remove last '\n'
|
s = s.substring(0, s.length - 1)// remove last '\n'
|
||||||
fileName = 'download.srt'
|
suffix = 'srt'
|
||||||
} else if (downloadType === 'vtt') {
|
} else if (downloadType === 'vtt') {
|
||||||
/**
|
/**
|
||||||
* WEBVTT title
|
* WEBVTT title
|
||||||
@@ -134,34 +140,33 @@ const MoreBtn = (props: Props) => {
|
|||||||
s += ss
|
s += ss
|
||||||
}
|
}
|
||||||
s = s.substring(0, s.length - 1)// remove last '\n'
|
s = s.substring(0, s.length - 1)// remove last '\n'
|
||||||
fileName = 'download.vtt'
|
suffix = 'vtt'
|
||||||
} else if (downloadType === 'json') {
|
} else if (downloadType === 'json') {
|
||||||
s = JSON.stringify(data)
|
s = JSON.stringify(data)
|
||||||
fileName = 'download.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
|
||||||
fileName = '总结.txt'
|
fileName += ' - 总结'
|
||||||
|
suffix = 'txt'
|
||||||
} else {
|
} else {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (download) {
|
if (download) {
|
||||||
downloadText(s, fileName)
|
downloadText(s, fileName+'.'+suffix)
|
||||||
} else {
|
} else {
|
||||||
navigator.clipboard.writeText(s).then(() => {
|
navigator.clipboard.writeText(s).then(() => {
|
||||||
toast.success('复制成功')
|
toast.success('复制成功')
|
||||||
}).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(() => {
|
||||||
window.parent.postMessage({
|
sendInject(null, 'DOWNLOAD_AUDIO', {})
|
||||||
type: 'downloadAudio',
|
}, [sendInject])
|
||||||
}, '*')
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const selectCallback = useCallback((e: any) => {
|
const selectCallback = useCallback((e: any) => {
|
||||||
dispatch(setTempData({
|
dispatch(setTempData({
|
||||||
@@ -243,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()
|
||||||
@@ -262,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() */}
|
||||||
@@ -286,13 +291,24 @@ const MoreBtn = (props: Props) => {
|
|||||||
{/* </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) => {
|
||||||
dispatch(setPage(PAGE_SETTINGS))
|
chrome.runtime.openOptionsPage()
|
||||||
setMoreVisible(false)
|
setMoreVisible(false)
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
}}>
|
}}>
|
||||||
<IoMdSettings className='w-[20px] h-[20px] text-primary/75 bg-white rounded-sm p-0.5'/>
|
<IoMdSettings className='w-[20px] h-[20px] text-primary/75 bg-white rounded-sm p-0.5'/>
|
||||||
设置
|
选项
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
{/* 官网 */}
|
||||||
|
<li className='hover:bg-accent'>
|
||||||
|
<a className='flex items-center' onClick={(e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
openUrl('https://www.bibijun.cc')
|
||||||
|
}}>
|
||||||
|
<img alt='哔哔君' src='/favicon-128x128.png' className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/>
|
||||||
|
🏠 哔哔君官网
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
@@ -1,7 +1,7 @@
|
|||||||
import React, {useMemo} from 'react'
|
import React, {useMemo} from 'react'
|
||||||
import {formatTime} from '../util/util'
|
import {formatTime} from '../utils/util'
|
||||||
import {useAppSelector} from '../hooks/redux'
|
import {useAppSelector} from '../hooks/redux'
|
||||||
import {getDisplay, getTransText} from '../util/biz_util'
|
import {getDisplay, getTransText} from '../utils/bizUtil'
|
||||||
import classNames from 'classnames'
|
import classNames from 'classnames'
|
||||||
|
|
||||||
const NormalSegmentItem = (props: {
|
const NormalSegmentItem = (props: {
|
58
src/components/RateExtension.tsx
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import React, { useState } from 'react'
|
||||||
|
import { FaStar } from 'react-icons/fa'
|
||||||
|
import { IoMdClose } from 'react-icons/io'
|
||||||
|
import { setTempData } from '../redux/envReducer'
|
||||||
|
import { useAppDispatch, useAppSelector } from '../hooks/redux'
|
||||||
|
import { openUrl } from '@kky002/kky-util'
|
||||||
|
import { isEdgeBrowser } from '../utils/util'
|
||||||
|
|
||||||
|
const RateExtension: React.FC = () => {
|
||||||
|
const dispatch = useAppDispatch()
|
||||||
|
const [isHovered, setIsHovered] = useState(false)
|
||||||
|
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
|
||||||
|
|
||||||
|
const handleRateClick = () => {
|
||||||
|
dispatch(setTempData({
|
||||||
|
reviewed: true
|
||||||
|
}))
|
||||||
|
// Chrome Web Store URL for your extension
|
||||||
|
if (isEdgeBrowser()) {
|
||||||
|
openUrl('https://microsoftedge.microsoft.com/addons/detail/lignnlhlpiefmcjkdkmfjdckhlaiajan')
|
||||||
|
} else {
|
||||||
|
openUrl('https://chromewebstore.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp/reviews')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reviewed === true || reviewed === undefined) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative bg-gradient-to-r from-primary to-secondary text-primary-content p-4 rounded-lg shadow-lg text-sm transition-all duration-300 ease-in-out hover:shadow-xl">
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
dispatch(setTempData({
|
||||||
|
reviewed: true
|
||||||
|
}))
|
||||||
|
}}
|
||||||
|
className="absolute top-2 right-2 text-primary-content opacity-70 hover:opacity-100 transition-opacity"
|
||||||
|
>
|
||||||
|
<IoMdClose size={20} />
|
||||||
|
</button>
|
||||||
|
<h3 className="text-lg font-bold mb-2 animate-pulse">喜欢这个扩展吗?</h3>
|
||||||
|
<p className="mb-3">如果觉得有用,请给我们评分!</p>
|
||||||
|
<button
|
||||||
|
onClick={handleRateClick}
|
||||||
|
onMouseEnter={() => setIsHovered(true)}
|
||||||
|
onMouseLeave={() => setIsHovered(false)}
|
||||||
|
className="btn btn-accent btn-sm gap-2 transition-all duration-300 ease-in-out hover:scale-105"
|
||||||
|
>
|
||||||
|
<FaStar className={`inline-block text-yellow-300 ${isHovered ? 'animate-spin' : ''}`} />
|
||||||
|
去评分
|
||||||
|
<span className="transition-transform duration-300 ease-in-out transform inline-block">
|
||||||
|
{isHovered ? '🚀' : '→'}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default RateExtension
|
@@ -1,17 +1,19 @@
|
|||||||
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, setPage, 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 '../const'
|
import {SUMMARIZE_THRESHOLD, SUMMARIZE_TYPES} from '../consts/const'
|
||||||
import useTranslate from '../hooks/useTranslate'
|
import useTranslate from '../hooks/useTranslate'
|
||||||
import {BsDashSquare, BsPlusSquare, CgFileDocument, 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'
|
||||||
import {getLastTime, getSummaryStr, isSummaryEmpty, parseStrTimeToSeconds} from '../util/biz_util'
|
import {getLastTime, getSummaryStr, isSummaryEmpty, parseStrTimeToSeconds} from '../utils/bizUtil'
|
||||||
import {useInViewport} from 'ahooks'
|
import {useInViewport} from 'ahooks'
|
||||||
import SegmentItem from './SegmentItem'
|
import SegmentItem from './SegmentItem'
|
||||||
import {stopPopFunc} from '../util/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,14 +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 {
|
||||||
dispatch(setPage(PAGE_SETTINGS))
|
toast.error('请先在选项页面设置ApiKey!')
|
||||||
toast.error('需要先设置ApiKey!')
|
|
||||||
}
|
}
|
||||||
}, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segment])
|
}, [addSummarizeTask, curSummaryType, envData.apiKey, segment])
|
||||||
|
|
||||||
const onCopy = useCallback(() => {
|
const onCopy = useCallback(() => {
|
||||||
if (summary != null) {
|
if (summary != null) {
|
||||||
@@ -107,6 +108,15 @@ const Summarize = (props: {
|
|||||||
<div className={classNames('font-medium max-w-[90%]', fontSize === 'large' ? 'text-sm' : 'text-xs')}>
|
<div className={classNames('font-medium max-w-[90%]', fontSize === 'large' ? 'text-sm' : 'text-xs')}>
|
||||||
{summary.content.summary}
|
{summary.content.summary}
|
||||||
</div>}
|
</div>}
|
||||||
|
{summary?.type === 'question' && (summary.content != null) &&
|
||||||
|
<div className={classNames('max-w-[90%] flex flex-col gap-1', fontSize === 'large' ? 'text-sm' : 'text-xs')}>
|
||||||
|
{summary.content.map((question: any, idx: number) => <div key={idx}>
|
||||||
|
<h2 className={classNames('font-semibold underline', fontSize === 'large' ? 'text-sm' : 'text-xs')}>{question.q}</h2>
|
||||||
|
<div className={classNames('font-normal', fontSize === 'large' ? 'text-sm' : 'text-xs')}>{question.a}</div>
|
||||||
|
</div>)}
|
||||||
|
</div>}
|
||||||
|
{summary?.type === 'debate' && (summary.content != null) &&
|
||||||
|
<DebateChat messages={summary.content} />}
|
||||||
</div>
|
</div>
|
||||||
<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>}
|
||||||
@@ -138,7 +148,6 @@ const SegmentCard = (props: {
|
|||||||
const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable)
|
const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable)
|
||||||
const summarizeFloat = useAppSelector(state => state.env.envData.summarizeFloat)
|
const summarizeFloat = useAppSelector(state => state.env.envData.summarizeFloat)
|
||||||
const fold = useAppSelector(state => state.env.fold)
|
const fold = useAppSelector(state => state.env.fold)
|
||||||
const page = useAppSelector(state => state.env.page)
|
|
||||||
const compact = useAppSelector(state => state.env.tempData.compact)
|
const compact = useAppSelector(state => state.env.tempData.compact)
|
||||||
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
|
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
|
||||||
const showCurrent = useMemo(() => curIdx != null && segment.startIdx <= curIdx && curIdx <= segment.endIdx, [curIdx, segment.endIdx, segment.startIdx])
|
const showCurrent = useMemo(() => curIdx != null && segment.startIdx <= curIdx && curIdx <= segment.endIdx, [curIdx, segment.endIdx, segment.startIdx])
|
||||||
@@ -161,7 +170,7 @@ const SegmentCard = (props: {
|
|||||||
// 检测设置floatKeyPointsSegIdx
|
// 检测设置floatKeyPointsSegIdx
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (summarizeFloat) { // 已启用
|
if (summarizeFloat) { // 已启用
|
||||||
if (!fold && page === PAGE_MAIN && showCurrent) { // 当前Card有控制权
|
if (!fold && showCurrent) { // 当前Card有控制权
|
||||||
if (!inViewport && (summary != null) && !isSummaryEmpty(summary)) {
|
if (!inViewport && (summary != null) && !isSummaryEmpty(summary)) {
|
||||||
dispatch(setFloatKeyPointsSegIdx(segment.startIdx))
|
dispatch(setFloatKeyPointsSegIdx(segment.startIdx))
|
||||||
} else {
|
} else {
|
||||||
@@ -169,7 +178,7 @@ const SegmentCard = (props: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [dispatch, fold, inViewport, page, segment.startIdx, showCurrent, summarizeFloat, summary])
|
}, [dispatch, fold, inViewport, segment.startIdx, showCurrent, summarizeFloat, summary])
|
||||||
|
|
||||||
const onSelBrief = useCallback(() => {
|
const onSelBrief = useCallback(() => {
|
||||||
dispatch(setTempData({
|
dispatch(setTempData({
|
||||||
@@ -189,8 +198,20 @@ const SegmentCard = (props: {
|
|||||||
}))
|
}))
|
||||||
}, [dispatch])
|
}, [dispatch])
|
||||||
|
|
||||||
|
const onSelQuestion = useCallback(() => {
|
||||||
|
dispatch(setTempData({
|
||||||
|
curSummaryType: 'question'
|
||||||
|
}))
|
||||||
|
}, [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'>
|
||||||
@@ -203,6 +224,8 @@ const SegmentCard = (props: {
|
|||||||
<a className={classNames('tab tab-lifted tab-xs', curSummaryType === 'brief' && 'tab-active')} onClick={onSelBrief}><CgFileDocument/>总结</a>
|
<a className={classNames('tab tab-lifted tab-xs', curSummaryType === 'brief' && 'tab-active')} onClick={onSelBrief}><CgFileDocument/>总结</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 === '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 === '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
|
@@ -23,7 +23,7 @@ const SegmentItem = (props: {
|
|||||||
const searchResult = useAppSelector(state => state.env.searchResult)
|
const searchResult = useAppSelector(state => state.env.searchResult)
|
||||||
const display = useMemo(() => {
|
const display = useMemo(() => {
|
||||||
if (searchText) {
|
if (searchText) {
|
||||||
return searchResult.has(item.idx) ? 'inline' : 'none'
|
return searchResult[item.idx+''] ? 'inline' : 'none'
|
||||||
} else {
|
} else {
|
||||||
return 'inline'
|
return 'inline'
|
||||||
}
|
}
|
@@ -1,3 +1,7 @@
|
|||||||
|
export const DEFAULT_USE_PORT = false
|
||||||
|
|
||||||
|
export const EVENT_EXPAND = 'expand'
|
||||||
|
|
||||||
export const APP_DOM_ID = 'bilibili-subtitle'
|
export const APP_DOM_ID = 'bilibili-subtitle'
|
||||||
|
|
||||||
export const IFRAME_ID = 'bilibili-subtitle-iframe'
|
export const IFRAME_ID = 'bilibili-subtitle-iframe'
|
||||||
@@ -8,6 +12,8 @@ export const STORAGE_TEMP = 'bilibili-subtitle_temp'
|
|||||||
export const PROMPT_TYPE_TRANSLATE = 'translate'
|
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_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 = [{
|
||||||
@@ -22,6 +28,12 @@ export const PROMPT_TYPES = [{
|
|||||||
}, {
|
}, {
|
||||||
name: '总结',
|
name: '总结',
|
||||||
type: PROMPT_TYPE_SUMMARIZE_BRIEF,
|
type: PROMPT_TYPE_SUMMARIZE_BRIEF,
|
||||||
|
}, {
|
||||||
|
name: '问题',
|
||||||
|
type: PROMPT_TYPE_SUMMARIZE_QUESTION,
|
||||||
|
}, {
|
||||||
|
name: '辩论',
|
||||||
|
type: PROMPT_TYPE_SUMMARIZE_DEBATE,
|
||||||
}, {
|
}, {
|
||||||
name: '提问',
|
name: '提问',
|
||||||
type: PROMPT_TYPE_ASK,
|
type: PROMPT_TYPE_ASK,
|
||||||
@@ -46,6 +58,18 @@ export const SUMMARIZE_TYPES = {
|
|||||||
downloadName: '💡视频要点💡',
|
downloadName: '💡视频要点💡',
|
||||||
promptType: PROMPT_TYPE_SUMMARIZE_KEYPOINT,
|
promptType: PROMPT_TYPE_SUMMARIZE_KEYPOINT,
|
||||||
},
|
},
|
||||||
|
question: {
|
||||||
|
name: '问题',
|
||||||
|
desc: '常见问题',
|
||||||
|
downloadName: '💡常见问题💡',
|
||||||
|
promptType: PROMPT_TYPE_SUMMARIZE_QUESTION,
|
||||||
|
},
|
||||||
|
debate: {
|
||||||
|
name: '辩论',
|
||||||
|
desc: '辩论',
|
||||||
|
downloadName: '💡辩论💡',
|
||||||
|
promptType: PROMPT_TYPE_SUMMARIZE_DEBATE,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PROMPT_DEFAULTS = {
|
export const PROMPT_DEFAULTS = {
|
||||||
@@ -124,6 +148,82 @@ The video's subtitles:
|
|||||||
'''
|
'''
|
||||||
{{segment}}
|
{{segment}}
|
||||||
'''`,
|
'''`,
|
||||||
|
[PROMPT_TYPE_SUMMARIZE_QUESTION]: `You are a helpful assistant that skilled at extracting questions from video subtitle.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The video's title: '''{{title}}'''.
|
||||||
|
The video's subtitles:
|
||||||
|
|
||||||
|
'''
|
||||||
|
{{segment}}
|
||||||
|
'''
|
||||||
|
|
||||||
|
## Command
|
||||||
|
|
||||||
|
Accurately extract key questions and their corresponding answers from the video subtitles based on the actual content provided. The number of questions should be between 3 and 5.
|
||||||
|
|
||||||
|
- Identify questions as sentences starting with interrogative words (e.g., "What", "How", "Why") and extract the following sentences that directly answer these questions.
|
||||||
|
- Include only those questions and answers that are relevant to the main points of the video, and ensure they cover different aspects of the video's content.
|
||||||
|
- If an answer spans multiple non-consecutive parts of the subtitles, concatenate them into a coherent response without adding any information not present in the subtitles.
|
||||||
|
- In cases where the number of potential Q&As exceeds 5, prioritize the most informative and directly answered ones.
|
||||||
|
- If clear questions and answers are not available in the subtitles, refrain from creating them and instead note the absence of direct Q&As.
|
||||||
|
- Answer in language '{{language}}'.
|
||||||
|
- Format the output in markdown json format, as specified.
|
||||||
|
|
||||||
|
## Output format
|
||||||
|
|
||||||
|
Provide an example to illustrate the expected output:
|
||||||
|
|
||||||
|
\`\`\`json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"q": "What is the main theme of the video?",
|
||||||
|
"a": "The main theme of the video is explained as..."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"q": "How is the topic developed?",
|
||||||
|
"a": "The topic is developed through various examples, including..."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
\`\`\`
|
||||||
|
`,
|
||||||
|
[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}}'.
|
||||||
|
|
||||||
@@ -139,8 +239,6 @@ Answer:
|
|||||||
`,
|
`,
|
||||||
}
|
}
|
||||||
|
|
||||||
export const EVENT_EXPAND = 'expand'
|
|
||||||
|
|
||||||
export const TASK_EXPIRE_TIME = 15*60*1000
|
export const TASK_EXPIRE_TIME = 15*60*1000
|
||||||
|
|
||||||
export const PAGE_MAIN = 'main'
|
export const PAGE_MAIN = 'main'
|
||||||
@@ -170,26 +268,23 @@ 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 MODELS = [{
|
export const MODELS = [{
|
||||||
code: 'gpt-3.5-turbo',
|
code: 'gpt-4o-mini',
|
||||||
name: 'gpt-3.5-turbo',
|
name: 'gpt-4o-mini',
|
||||||
tokens: 4096,
|
tokens: 128000,
|
||||||
}, {
|
}, {
|
||||||
code: 'gpt-3.5-turbo-0125',
|
code: 'gpt-3.5-turbo-0125',
|
||||||
name: 'gpt-3.5-turbo-0125',
|
name: 'gpt-3.5-turbo-0125',
|
||||||
tokens: 16385,
|
tokens: 16385,
|
||||||
}, {
|
|
||||||
code: 'gpt-3.5-turbo-1106',
|
|
||||||
name: 'gpt-3.5-turbo-1106',
|
|
||||||
tokens: 16385,
|
|
||||||
}, {
|
}, {
|
||||||
code: 'custom',
|
code: 'custom',
|
||||||
name: '自定义',
|
name: '自定义',
|
||||||
}]
|
}]
|
||||||
export const GEMINI_TOKENS = 32768
|
export const MODEL_DEFAULT = MODELS[0].code
|
||||||
export const MODEL_DEFAULT = MODELS[1].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) {
|
||||||
MODEL_MAP[model.code] = model
|
MODEL_MAP[model.code] = model
|
||||||
@@ -198,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',
|
||||||
@@ -231,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) {
|
@@ -1,864 +0,0 @@
|
|||||||
{
|
|
||||||
"font_size": 0.4,
|
|
||||||
"font_color": "#FFFFFF",
|
|
||||||
"background_alpha": 0.5,
|
|
||||||
"background_color": "#9C27B0",
|
|
||||||
"Stroke": "none",
|
|
||||||
"type": "AIsubtitle",
|
|
||||||
"lang": "zh",
|
|
||||||
"version": "a1.3.0.2",
|
|
||||||
"body": [
|
|
||||||
{
|
|
||||||
"from": 0.666,
|
|
||||||
"to": 1.799,
|
|
||||||
"location": 0,
|
|
||||||
"content": "各位听众朋友大家好"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 1.8,
|
|
||||||
"to": 4.3,
|
|
||||||
"location": 0,
|
|
||||||
"content": "欢迎来到旧世代电台我是Lunmos"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 4.4,
|
|
||||||
"to": 5.466,
|
|
||||||
"location": 0,
|
|
||||||
"content": "我们这期呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 5.466,
|
|
||||||
"to": 6.966,
|
|
||||||
"location": 0,
|
|
||||||
"content": "来聊一个真正的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 6.966,
|
|
||||||
"to": 9.766,
|
|
||||||
"location": 0,
|
|
||||||
"content": "我觉得可能是新旧世代"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 10.3,
|
|
||||||
"to": 12.333,
|
|
||||||
"location": 0,
|
|
||||||
"content": "分界线的这么一件事情"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 12.733,
|
|
||||||
"to": 15.133,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那首先呢还是来一个思维实验"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 15.2,
|
|
||||||
"to": 17.5,
|
|
||||||
"location": 0,
|
|
||||||
"content": "上期其实我们也已经提到了"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 17.5,
|
|
||||||
"to": 19.7,
|
|
||||||
"location": 0,
|
|
||||||
"content": "就是一个上世纪末的人"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 19.7,
|
|
||||||
"to": 22.4,
|
|
||||||
"location": 0,
|
|
||||||
"content": "如果穿越到了2023年的现在"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 22.733,
|
|
||||||
"to": 24.766,
|
|
||||||
"location": 0,
|
|
||||||
"content": "我们已经发展了20多年的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 24.8,
|
|
||||||
"to": 26.3,
|
|
||||||
"location": 0,
|
|
||||||
"content": "这么一个21世纪"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 26.333,
|
|
||||||
"to": 27.766,
|
|
||||||
"location": 0,
|
|
||||||
"content": "就在此时此刻"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 28,
|
|
||||||
"to": 28.8,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那么"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 29.7,
|
|
||||||
"to": 31.966,
|
|
||||||
"location": 0,
|
|
||||||
"content": "你问他他会被什么东西"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 32.4,
|
|
||||||
"to": 34.533,
|
|
||||||
"location": 0,
|
|
||||||
"content": "所吓尿所吓到"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 35.4,
|
|
||||||
"to": 35.933,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那当然了"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 35.933,
|
|
||||||
"to": 37.133,
|
|
||||||
"location": 0,
|
|
||||||
"content": "看过上期电台的朋友"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 37.133,
|
|
||||||
"to": 39.099,
|
|
||||||
"location": 0,
|
|
||||||
"content": "已经知道我想说的那个答案了"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 39.1,
|
|
||||||
"to": 41.3,
|
|
||||||
"location": 0,
|
|
||||||
"content": "不妨我们可以先来试试"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 41.466,
|
|
||||||
"to": 42.966,
|
|
||||||
"location": 0,
|
|
||||||
"content": "感觉一下其他方面"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 42.966,
|
|
||||||
"to": 45.599,
|
|
||||||
"location": 0,
|
|
||||||
"content": "我们有哪些地方发展的还算可以"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 46.133,
|
|
||||||
"to": 47.599,
|
|
||||||
"location": 0,
|
|
||||||
"content": "比如说航空航天"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 47.6,
|
|
||||||
"to": 51.066,
|
|
||||||
"location": 0,
|
|
||||||
"content": "他会被现在的航空航天科技所震惊吗"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 51.066,
|
|
||||||
"to": 52.199,
|
|
||||||
"location": 0,
|
|
||||||
"content": "我觉得"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 52.6,
|
|
||||||
"to": 53.366,
|
|
||||||
"location": 0,
|
|
||||||
"content": "不见得对吧"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 53.366,
|
|
||||||
"to": 55.966,
|
|
||||||
"location": 0,
|
|
||||||
"content": "现在虽然说有了一些可回收的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 55.966,
|
|
||||||
"to": 57.499,
|
|
||||||
"location": 0,
|
|
||||||
"content": "航空航天的一些"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 57.733,
|
|
||||||
"to": 59.599,
|
|
||||||
"location": 0,
|
|
||||||
"content": "科技虽然说有了一些"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 59.6,
|
|
||||||
"to": 61,
|
|
||||||
"location": 0,
|
|
||||||
"content": "当时人们可能没太"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 61,
|
|
||||||
"to": 62.466,
|
|
||||||
"location": 0,
|
|
||||||
"content": "见到的一些科技路线"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 62.466,
|
|
||||||
"to": 63.266,
|
|
||||||
"location": 0,
|
|
||||||
"content": "但是"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 63.966,
|
|
||||||
"to": 64.733,
|
|
||||||
"location": 0,
|
|
||||||
"content": "总体上来说"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 64.733,
|
|
||||||
"to": 65.099,
|
|
||||||
"location": 0,
|
|
||||||
"content": "还是"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 65.1,
|
|
||||||
"to": 67.8,
|
|
||||||
"location": 0,
|
|
||||||
"content": "现在的人被那个时候吓得还差不多"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 67.8,
|
|
||||||
"to": 69.666,
|
|
||||||
"location": 0,
|
|
||||||
"content": "上个时期的美苏争霸时期"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 69.666,
|
|
||||||
"to": 71.299,
|
|
||||||
"location": 0,
|
|
||||||
"content": "人们是有意愿在"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 71.566,
|
|
||||||
"to": 73.866,
|
|
||||||
"location": 0,
|
|
||||||
"content": "航空航天的科技上去点科技术的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 73.866,
|
|
||||||
"to": 76.133,
|
|
||||||
"location": 0,
|
|
||||||
"content": "无论是为意志形态服务宣传也好"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 76.133,
|
|
||||||
"to": 76.933,
|
|
||||||
"location": 0,
|
|
||||||
"content": "还是为了"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 77.1,
|
|
||||||
"to": 78.9,
|
|
||||||
"location": 0,
|
|
||||||
"content": "真实可能存在的一种"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 79.133,
|
|
||||||
"to": 79.666,
|
|
||||||
"location": 0,
|
|
||||||
"content": "更高的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 79.666,
|
|
||||||
"to": 82.666,
|
|
||||||
"location": 0,
|
|
||||||
"content": "所谓说更高维度的战争的形态也好"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 82.866,
|
|
||||||
"to": 84.766,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那么人类愿意去倾斜资源"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 84.766,
|
|
||||||
"to": 86.966,
|
|
||||||
"location": 0,
|
|
||||||
"content": "去让那些在这些科技中"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 87.466,
|
|
||||||
"to": 90.266,
|
|
||||||
"location": 0,
|
|
||||||
"content": "引领了发展进步的人成为英雄"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 90.266,
|
|
||||||
"to": 91.399,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那么这样"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 91.4,
|
|
||||||
"to": 91.9,
|
|
||||||
"location": 0,
|
|
||||||
"content": "才能够"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 91.9,
|
|
||||||
"to": 94.533,
|
|
||||||
"location": 0,
|
|
||||||
"content": "如愿以偿的得到他们想要的结果"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 96.066,
|
|
||||||
"to": 97.466,
|
|
||||||
"location": 0,
|
|
||||||
"content": "好航空航天不太行"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 97.466,
|
|
||||||
"to": 100.666,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那么我们引以为豪的移动互联网"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 100.666,
|
|
||||||
"to": 101.666,
|
|
||||||
"location": 0,
|
|
||||||
"content": "社交网络"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 101.666,
|
|
||||||
"to": 103.366,
|
|
||||||
"location": 0,
|
|
||||||
"content": "这个你觉得可以吗"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 103.366,
|
|
||||||
"to": 104.766,
|
|
||||||
"location": 0,
|
|
||||||
"content": "我觉得也不太行对吧"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 104.766,
|
|
||||||
"to": 106.999,
|
|
||||||
"location": 0,
|
|
||||||
"content": "我们甚至很多现代人都觉得"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 107.566,
|
|
||||||
"to": 108.699,
|
|
||||||
"location": 0,
|
|
||||||
"content": "从这些移动互联网"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 108.7,
|
|
||||||
"to": 110.966,
|
|
||||||
"location": 0,
|
|
||||||
"content": "从这些社交网络中涉及到的东西"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 110.966,
|
|
||||||
"to": 113.366,
|
|
||||||
"location": 0,
|
|
||||||
"content": "不一定是一个什么那么好的东西"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 113.366,
|
|
||||||
"to": 114.466,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那么他呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 114.466,
|
|
||||||
"to": 116.133,
|
|
||||||
"location": 0,
|
|
||||||
"content": "当然也会觉得很新奇"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 116.366,
|
|
||||||
"to": 118.266,
|
|
||||||
"location": 0,
|
|
||||||
"content": "但是他不会觉得这是一件"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 118.7,
|
|
||||||
"to": 121.133,
|
|
||||||
"location": 0,
|
|
||||||
"content": "多么真正的了不起的事情"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 121.133,
|
|
||||||
"to": 122.866,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那无非就是把以前的摩尔定律"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 122.866,
|
|
||||||
"to": 123.999,
|
|
||||||
"location": 0,
|
|
||||||
"content": "继续进行下去"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 124,
|
|
||||||
"to": 126.266,
|
|
||||||
"location": 0,
|
|
||||||
"content": "然后不断的缩小计算机的体积"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 126.866,
|
|
||||||
"to": 127.266,
|
|
||||||
"location": 0,
|
|
||||||
"content": "最终呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 127.266,
|
|
||||||
"to": 129.533,
|
|
||||||
"location": 0,
|
|
||||||
"content": "总会能够实现的这么一件事对吧"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 129.533,
|
|
||||||
"to": 130.733,
|
|
||||||
"location": 0,
|
|
||||||
"content": "手机能上网"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 130.733,
|
|
||||||
"to": 132.266,
|
|
||||||
"location": 0,
|
|
||||||
"content": "无线网络如此之发达"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 132.4,
|
|
||||||
"to": 134.466,
|
|
||||||
"location": 0,
|
|
||||||
"content": "也是一个基础设施的扩展"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 134.466,
|
|
||||||
"to": 136.599,
|
|
||||||
"location": 0,
|
|
||||||
"content": "基础设施的扩张所能实现的事"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 136.7,
|
|
||||||
"to": 139.166,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那么人们其实并不会太折服于"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 139.166,
|
|
||||||
"to": 140.899,
|
|
||||||
"location": 0,
|
|
||||||
"content": "使用大规模基础建设"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 140.9,
|
|
||||||
"to": 143.166,
|
|
||||||
"location": 0,
|
|
||||||
"content": "就能够实现的某件事情"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 143.166,
|
|
||||||
"to": 145.966,
|
|
||||||
"location": 0,
|
|
||||||
"content": "因为人们总会预期未来"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 146.466,
|
|
||||||
"to": 147.333,
|
|
||||||
"location": 0,
|
|
||||||
"content": "未来的某一天"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 147.333,
|
|
||||||
"to": 150.699,
|
|
||||||
"location": 0,
|
|
||||||
"content": "或慢或快的总会出现那么一个时代的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 150.7,
|
|
||||||
"to": 152.466,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那就比如说大航海时代的人"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 152.733,
|
|
||||||
"to": 153.799,
|
|
||||||
"location": 0,
|
|
||||||
"content": "他们也会想"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 153.8,
|
|
||||||
"to": 156.5,
|
|
||||||
"location": 0,
|
|
||||||
"content": "未来的航路海运可能会非常的发达"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 156.5,
|
|
||||||
"to": 158.733,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那未来可能遍地都是像阿姆斯特丹"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 158.733,
|
|
||||||
"to": 160.299,
|
|
||||||
"location": 0,
|
|
||||||
"content": "像伦敦这样的港口"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 160.666,
|
|
||||||
"to": 161.799,
|
|
||||||
"location": 0,
|
|
||||||
"content": "虽然现在不是这样"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 161.8,
|
|
||||||
"to": 162.166,
|
|
||||||
"location": 0,
|
|
||||||
"content": "但是"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 162.166,
|
|
||||||
"to": 164.866,
|
|
||||||
"location": 0,
|
|
||||||
"content": "处在他们能想象的社会发展的极限"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 165,
|
|
||||||
"to": 166.333,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那我们也提到过游戏"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 166.333,
|
|
||||||
"to": 168.533,
|
|
||||||
"location": 0,
|
|
||||||
"content": "但也就像有朋友在弹幕中提到的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 168.533,
|
|
||||||
"to": 170.599,
|
|
||||||
"location": 0,
|
|
||||||
"content": "想想时之笛是什么年代的游戏"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 170.6,
|
|
||||||
"to": 171.3,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那现在呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 171.3,
|
|
||||||
"to": 174.066,
|
|
||||||
"location": 0,
|
|
||||||
"content": "甚至还在很多的游戏排行榜中"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 174.066,
|
|
||||||
"to": 174.899,
|
|
||||||
"location": 0,
|
|
||||||
"content": "排在第一"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 175.3,
|
|
||||||
"to": 176.8,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那你想让那个时候的人"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 176.8,
|
|
||||||
"to": 178.933,
|
|
||||||
"location": 0,
|
|
||||||
"content": "真正折服于现在的游戏呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 179.466,
|
|
||||||
"to": 180.599,
|
|
||||||
"location": 0,
|
|
||||||
"content": "也没有那么容易对吧"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 180.6,
|
|
||||||
"to": 181.7,
|
|
||||||
"location": 0,
|
|
||||||
"content": "在图形学上"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 181.866,
|
|
||||||
"to": 182.399,
|
|
||||||
"location": 0,
|
|
||||||
"content": "我们也提到"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 182.4,
|
|
||||||
"to": 183.3,
|
|
||||||
"location": 0,
|
|
||||||
"content": "图形学的发展"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 183.3,
|
|
||||||
"to": 185.4,
|
|
||||||
"location": 0,
|
|
||||||
"content": "是不断把离线变成实时的过程"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 185.666,
|
|
||||||
"to": 187.333,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那么他们见过离线的东西"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 187.333,
|
|
||||||
"to": 188.299,
|
|
||||||
"location": 0,
|
|
||||||
"content": "他们可以预测"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 188.3,
|
|
||||||
"to": 191.4,
|
|
||||||
"location": 0,
|
|
||||||
"content": "这样的离线动画在将来会变成实时"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 191.6,
|
|
||||||
"to": 193.166,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那所以呢也不会觉得"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 193.666,
|
|
||||||
"to": 194.899,
|
|
||||||
"location": 0,
|
|
||||||
"content": "超出认知对吧"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 195.466,
|
|
||||||
"to": 196.933,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那比如说生物医疗呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 196.966,
|
|
||||||
"to": 198.899,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那虽然说可以说有不少的进"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 198.9,
|
|
||||||
"to": 199.566,
|
|
||||||
"location": 0,
|
|
||||||
"content": "展但还"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 199.566,
|
|
||||||
"to": 201.733,
|
|
||||||
"location": 0,
|
|
||||||
"content": "是建立在去完善20世纪"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 201.733,
|
|
||||||
"to": 203.066,
|
|
||||||
"location": 0,
|
|
||||||
"content": "这样一个科学大厦"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 203.066,
|
|
||||||
"to": 204.566,
|
|
||||||
"location": 0,
|
|
||||||
"content": "生物大厦的基础上"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 204.566,
|
|
||||||
"to": 205.866,
|
|
||||||
"location": 0,
|
|
||||||
"content": "对他进行了一些完善"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 206.2,
|
|
||||||
"to": 208.166,
|
|
||||||
"location": 0,
|
|
||||||
"content": "你要说那些折磨着现代人的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 208.166,
|
|
||||||
"to": 209.399,
|
|
||||||
"location": 0,
|
|
||||||
"content": "各种各样的疾病"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 209.466,
|
|
||||||
"to": 210.733,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那个时候没有攻克的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 210.733,
|
|
||||||
"to": 213.366,
|
|
||||||
"location": 0,
|
|
||||||
"content": "现在有多少是被真正攻克了的呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 213.366,
|
|
||||||
"to": 215.133,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那其实也很少对吧"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 215.266,
|
|
||||||
"to": 217.733,
|
|
||||||
"location": 0,
|
|
||||||
"content": "甚至可能我们连他的致病机理"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 217.733,
|
|
||||||
"to": 219.499,
|
|
||||||
"location": 0,
|
|
||||||
"content": "还没有完全的搞清楚"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 220.466,
|
|
||||||
"to": 221.699,
|
|
||||||
"location": 0,
|
|
||||||
"content": "其他可能还有一些比如"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 221.933,
|
|
||||||
"to": 223.199,
|
|
||||||
"location": 0,
|
|
||||||
"content": "像可控核聚变"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 223.2,
|
|
||||||
"to": 225.533,
|
|
||||||
"location": 0,
|
|
||||||
"content": "想更高效的电池技术这些"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 226.3,
|
|
||||||
"to": 228.766,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那就是目前可能还在发展的地方"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 228.766,
|
|
||||||
"to": 229.899,
|
|
||||||
"location": 0,
|
|
||||||
"content": "怎么怎么说呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 229.9,
|
|
||||||
"to": 230.733,
|
|
||||||
"location": 0,
|
|
||||||
"content": "就是到他"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 230.733,
|
|
||||||
"to": 233.166,
|
|
||||||
"location": 0,
|
|
||||||
"content": "真正的出现了可以使用的成果之后呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 233.166,
|
|
||||||
"to": 235.866,
|
|
||||||
"location": 0,
|
|
||||||
"content": "我们才能够去拿下来"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 235.866,
|
|
||||||
"to": 238.533,
|
|
||||||
"location": 0,
|
|
||||||
"content": "让那些旧世代人的那些人"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 238.533,
|
|
||||||
"to": 239.599,
|
|
||||||
"location": 0,
|
|
||||||
"content": "感到比较的震惊"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 239.6,
|
|
||||||
"to": 239.9,
|
|
||||||
"location": 0,
|
|
||||||
"content": "但是"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 239.9,
|
|
||||||
"to": 243.266,
|
|
||||||
"location": 0,
|
|
||||||
"content": "现在可能还没到那个完成的时间点吧"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 244.4,
|
|
||||||
"to": 245.133,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那么延续了"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 245.133,
|
|
||||||
"to": 247.466,
|
|
||||||
"location": 0,
|
|
||||||
"content": "上个世纪的第三次科技革命中的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 247.466,
|
|
||||||
"to": 249.366,
|
|
||||||
"location": 0,
|
|
||||||
"content": "计算机软硬件的发展呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 249.566,
|
|
||||||
"to": 251.599,
|
|
||||||
"location": 0,
|
|
||||||
"content": "其实惊喜也没有那么多"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 251.6,
|
|
||||||
"to": 253.766,
|
|
||||||
"location": 0,
|
|
||||||
"content": "就上世纪的那些互联网应用"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 253.9,
|
|
||||||
"to": 256.133,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那很多时候其实已经挺好用了"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 256.266,
|
|
||||||
"to": 257.733,
|
|
||||||
"location": 0,
|
|
||||||
"content": "论坛是上世纪的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 257.8,
|
|
||||||
"to": 260.133,
|
|
||||||
"location": 0,
|
|
||||||
"content": "那么i m软件是上世纪的"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 260.133,
|
|
||||||
"to": 261.066,
|
|
||||||
"location": 0,
|
|
||||||
"content": "现在的互联网呢"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 261.066,
|
|
||||||
"to": 264.766,
|
|
||||||
"location": 0,
|
|
||||||
"content": "是把他更多的做的是大规模是吧是吧"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 264.766,
|
|
||||||
"to": 267.499,
|
|
||||||
"location": 0,
|
|
||||||
"content": "越来越多的人纳入到了这个体系中"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 267.5,
|
|
||||||
"to": 269.566,
|
|
||||||
"location": 0,
|
|
||||||
"content": "所产生的这么一个规模效应"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"from": 269.933,
|
|
||||||
"to": 272.399,
|
|
||||||
"location": 0,
|
|
||||||
"content": "就当年操作系统能完成能做的事情呢"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
@@ -1,22 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"time": "00:10",
|
|
||||||
"emoji": "👍",
|
|
||||||
"key": "人们喜欢短。"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time": "01:00",
|
|
||||||
"emoji": "👍",
|
|
||||||
"key": "晶体智力和流体智力"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time": "03:00",
|
|
||||||
"emoji": "👍",
|
|
||||||
"key": "外向成长是围绕外界展开的成长活动,以输出为输入可以带来正向反馈。"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time": "05:00",
|
|
||||||
"emoji": "👍",
|
|
||||||
"key": "制定学习计划时,要专注打造自己的外向晶体和木子,即找到清晰的输出点,搜刮对应的项目和参考,借鉴晶体。"
|
|
||||||
}
|
|
||||||
]
|
|
@@ -1,14 +1,39 @@
|
|||||||
import {useEffect} from 'react'
|
import {useEffect} from 'react'
|
||||||
import {useMemoizedFn} from 'ahooks/es'
|
import {useMemoizedFn} from 'ahooks/es'
|
||||||
import {useAppSelector} from './redux'
|
import {useAppDispatch, useAppSelector} from './redux'
|
||||||
import useSubtitle from './useSubtitle'
|
import useSubtitle from './useSubtitle'
|
||||||
|
import {setInputting} from '../redux/envReducer'
|
||||||
|
|
||||||
const useKeyService = () => {
|
const useKeyService = () => {
|
||||||
|
const dispatch = useAppDispatch()
|
||||||
|
const inputting = useAppSelector(state => state.env.inputting)
|
||||||
const curIdx = useAppSelector(state => state.env.curIdx)
|
const curIdx = useAppSelector(state => state.env.curIdx)
|
||||||
const data = useAppSelector(state => state.env.data)
|
const data = useAppSelector(state => state.env.data)
|
||||||
const {move} = useSubtitle()
|
const {move} = useSubtitle()
|
||||||
|
|
||||||
|
// 输入中
|
||||||
|
useEffect(() => {
|
||||||
|
const onInputtingStart = (e: CompositionEvent) => {
|
||||||
|
dispatch(setInputting(true))
|
||||||
|
}
|
||||||
|
const onInputtingEnd = (e: CompositionEvent) => {
|
||||||
|
dispatch(setInputting(false))
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('compositionstart', onInputtingStart)
|
||||||
|
document.addEventListener('compositionend', onInputtingEnd)
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('compositionstart', onInputtingStart)
|
||||||
|
document.removeEventListener('compositionend', onInputtingEnd)
|
||||||
|
}
|
||||||
|
}, [dispatch])
|
||||||
|
|
||||||
const onKeyDown = useMemoizedFn((e: KeyboardEvent) => {
|
const onKeyDown = useMemoizedFn((e: KeyboardEvent) => {
|
||||||
|
// 当前在输入中(如中文输入法)
|
||||||
|
if (inputting) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// 有按其他控制键时,不触发
|
// 有按其他控制键时,不触发
|
||||||
if (e.ctrlKey || e.metaKey || e.shiftKey) {
|
if (e.ctrlKey || e.metaKey || e.shiftKey) {
|
||||||
return
|
return
|
||||||
|
35
src/hooks/useMessageService.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { setAuthor, setCtime, setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
|
||||||
|
import { useAppDispatch, useAppSelector } from './redux'
|
||||||
|
import { AllAPPMessages, AllExtensionMessages, AllInjectMessages } from '@/message-typings'
|
||||||
|
import { useMessaging, useMessagingService } from '@kky002/kky-message'
|
||||||
|
import { useMemoizedFn } from 'ahooks'
|
||||||
|
|
||||||
|
const useMessageService = () => {
|
||||||
|
const dispatch = useAppDispatch()
|
||||||
|
const envData = useAppSelector((state) => state.env.envData)
|
||||||
|
|
||||||
|
// methods
|
||||||
|
const methodsFunc: () => {
|
||||||
|
[K in AllAPPMessages['method']]: (params: Extract<AllAPPMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
|
||||||
|
} = useMemoizedFn(() => ({
|
||||||
|
SET_INFOS: async (params, context: MethodContext) => {
|
||||||
|
dispatch(setInfos(params.infos))
|
||||||
|
dispatch(setCurInfo(undefined))
|
||||||
|
dispatch(setCurFetched(false))
|
||||||
|
dispatch(setData(undefined))
|
||||||
|
},
|
||||||
|
SET_VIDEO_INFO: async (params, context: MethodContext) => {
|
||||||
|
dispatch(setInfos(params.infos))
|
||||||
|
dispatch(setUrl(params.url))
|
||||||
|
dispatch(setTitle(params.title))
|
||||||
|
dispatch(setCtime(params.ctime))
|
||||||
|
dispatch(setAuthor(params.author))
|
||||||
|
console.debug('video title: ', params.title)
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
useMessagingService(!!envData.sidePanel, methodsFunc)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default useMessageService
|
||||||
|
export const useMessage = useMessaging<AllExtensionMessages, AllInjectMessages>
|
@@ -1,7 +1,7 @@
|
|||||||
import {useAppDispatch, useAppSelector} from './redux'
|
import {useAppDispatch, useAppSelector} from './redux'
|
||||||
import {useEffect, useMemo} from 'react'
|
import {useEffect, useMemo} from 'react'
|
||||||
import {setSearchResult, setSearchText, } from '../redux/envReducer'
|
import {setSearchResult, setSearchText, } from '../redux/envReducer'
|
||||||
import {Search} from '../util/search'
|
import {Search} from '../utils/search'
|
||||||
|
|
||||||
interface Document {
|
interface Document {
|
||||||
idx: number
|
idx: number
|
||||||
@@ -42,14 +42,14 @@ const useSearchService = () => {
|
|||||||
|
|
||||||
// search text
|
// search text
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const searchResult: Set<number> = new Set()
|
const searchResult: Record<string, boolean> = {}
|
||||||
|
|
||||||
if (envData.searchEnabled && searchText) {
|
if (envData.searchEnabled && searchText) {
|
||||||
// @ts-expect-error
|
// @ts-expect-error
|
||||||
const documents: Document[] | undefined = search(searchText)
|
const documents: Document[] | undefined = search(searchText)
|
||||||
if (documents != null) {
|
if (documents != null) {
|
||||||
for (const document of documents) {
|
for (const document of documents) {
|
||||||
searchResult.add(document.idx)
|
searchResult[''+document.idx] = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,13 +1,26 @@
|
|||||||
import {useAppDispatch} from './redux'
|
import {useAppDispatch, useAppSelector} from './redux'
|
||||||
import React, {useCallback} from 'react'
|
import React, {useCallback} from 'react'
|
||||||
import {setNeedScroll} from '../redux/envReducer'
|
import {setNeedScroll, setReviewAction, setTempData} from '../redux/envReducer'
|
||||||
|
import { useMessage } from './useMessageService'
|
||||||
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 reviewAction = useAppSelector(state => state.env.reviewAction)
|
||||||
|
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
|
||||||
|
const {sendInject} = useMessage(!!envData.sidePanel)
|
||||||
|
|
||||||
const move = useCallback((time: number, togglePause: boolean) => {
|
const move = useCallback((time: number, togglePause: boolean) => {
|
||||||
window.parent.postMessage({type: 'move', time, togglePause}, '*')
|
sendInject(null, 'MOVE', {time, togglePause})
|
||||||
}, [])
|
|
||||||
|
// review action
|
||||||
|
if (reviewed === undefined && !reviewAction) {
|
||||||
|
dispatch(setReviewAction(true))
|
||||||
|
dispatch(setTempData({
|
||||||
|
reviewActions: (reviewActions ?? 0) + 1
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}, [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'})
|
||||||
|
@@ -4,20 +4,20 @@ import {
|
|||||||
setCurFetched,
|
setCurFetched,
|
||||||
setCurIdx,
|
setCurIdx,
|
||||||
setCurInfo,
|
setCurInfo,
|
||||||
setCurrentTime,
|
|
||||||
setData,
|
setData,
|
||||||
setInfos,
|
|
||||||
setNoVideo,
|
setNoVideo,
|
||||||
setSegmentFold,
|
setSegmentFold,
|
||||||
setSegments,
|
setSegments,
|
||||||
setTitle,
|
|
||||||
setTotalHeight,
|
setTotalHeight,
|
||||||
setUrl,
|
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} from '../const'
|
import {EVENT_EXPAND, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../consts/const'
|
||||||
import {useInterval} from 'ahooks'
|
import {useAsyncEffect, useInterval} from 'ahooks'
|
||||||
import {getModelMaxTokens, getWholeText} from '../util/biz_util'
|
import {getModelMaxTokens, getWholeText} from '../utils/bizUtil'
|
||||||
|
import { useMessage } from './useMessageService'
|
||||||
|
import { setCurrentTime } from '../redux/currentTimeReducer'
|
||||||
|
import { RootState } from '../store'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Service是单例,类似后端的服务概念
|
* Service是单例,类似后端的服务概念
|
||||||
@@ -29,65 +29,28 @@ 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)
|
||||||
const transResults = useAppSelector(state => state.env.transResults)
|
const transResults = useAppSelector(state => state.env.transResults)
|
||||||
const hideOnDisableAutoTranslate = useAppSelector(state => state.env.envData.hideOnDisableAutoTranslate)
|
const hideOnDisableAutoTranslate = useAppSelector(state => state.env.envData.hideOnDisableAutoTranslate)
|
||||||
const autoTranslate = useAppSelector(state => state.env.autoTranslate)
|
const autoTranslate = useAppSelector(state => state.env.autoTranslate)
|
||||||
|
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
|
||||||
|
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
|
||||||
|
const {sendInject} = useMessage(!!envData.sidePanel)
|
||||||
|
|
||||||
// 监听消息
|
// 如果reviewActions达到15次,则设置reviewed为false
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const listener = (event: MessageEvent) => {
|
if (reviewed === undefined && reviewActions && reviewActions >= 15) {
|
||||||
const data = event.data
|
dispatch(setTempData({
|
||||||
|
reviewed: false
|
||||||
if (data.type === 'setVideoInfo') {
|
}))
|
||||||
dispatch(setInfos(data.infos))
|
|
||||||
dispatch(setUrl(data.url))
|
|
||||||
dispatch(setTitle(data.title))
|
|
||||||
console.debug('video title: ', data.title)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.type === 'setInfos') {
|
|
||||||
dispatch(setInfos(data.infos))
|
|
||||||
dispatch(setCurInfo(undefined))
|
|
||||||
dispatch(setCurFetched(false))
|
|
||||||
dispatch(setData(undefined))
|
|
||||||
// console.log('setInfos', data.infos)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.type === 'setSubtitle') {
|
|
||||||
const data_ = data.data.data
|
|
||||||
data_?.body?.forEach((item: TranscriptItem, idx: number) => {
|
|
||||||
item.idx = idx
|
|
||||||
})
|
|
||||||
// dispatch(setCurInfo(data.data.info))
|
|
||||||
dispatch(setCurFetched(true))
|
|
||||||
dispatch(setData(data_))
|
|
||||||
// console.log('setSubtitle', data.data)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.type === 'setCurrentTime') {
|
|
||||||
dispatch(setCurrentTime(data.data.currentTime))
|
|
||||||
}
|
|
||||||
if (data.type === 'setSettings') {
|
|
||||||
dispatch(setNoVideo(data.data.noVideo))
|
|
||||||
if (data.data.totalHeight) {
|
|
||||||
dispatch(setTotalHeight(Math.min(Math.max(data.data.totalHeight, TOTAL_HEIGHT_MIN), TOTAL_HEIGHT_MAX)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}, [reviewActions, dispatch, reviewed])
|
||||||
window.addEventListener('message', listener)
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('message', listener)
|
|
||||||
}
|
|
||||||
}, [dispatch, eventBus])
|
|
||||||
|
|
||||||
// 有数据时自动展开
|
// 有数据时自动展开
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -100,40 +63,70 @@ const useSubtitleService = () => {
|
|||||||
|
|
||||||
// 当前未展示 & (未折叠 | 自动展开) & 有列表 => 展示第一个
|
// 当前未展示 & (未折叠 | 自动展开) & 有列表 => 展示第一个
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!curInfo && (!fold || (envReady && envData.autoExpand)) && (infos != null) && infos.length > 0) {
|
let autoExpand = envData.autoExpand
|
||||||
|
// 如果显示在侧边栏,则自动展开
|
||||||
|
if (envData.sidePanel) {
|
||||||
|
autoExpand = true
|
||||||
|
}
|
||||||
|
if (!curInfo && (!fold || (envReady && autoExpand)) && (infos != null) && infos.length > 0) {
|
||||||
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) {
|
||||||
window.parent.postMessage({type: 'getSubtitle', info: curInfo}, '*')
|
sendInject(null, 'GET_SUBTITLE', {info: curInfo}).then(data => {
|
||||||
}
|
data?.body?.forEach((item: TranscriptItem, idx: number) => {
|
||||||
}, [curFetched, curInfo])
|
item.idx = idx
|
||||||
|
})
|
||||||
|
// dispatch(setCurInfo(data.data.info))
|
||||||
|
dispatch(setCurFetched(true))
|
||||||
|
dispatch(setData(data))
|
||||||
|
|
||||||
useEffect(() => {
|
console.debug('subtitle', data)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}, [curFetched, curInfo, dispatch, sendInject])
|
||||||
|
|
||||||
|
useAsyncEffect(async () => {
|
||||||
// 初始获取列表
|
// 初始获取列表
|
||||||
window.parent.postMessage({type: 'refreshVideoInfo'}, '*')
|
if (envReady) {
|
||||||
// 初始获取设置信息
|
sendInject(null, 'REFRESH_VIDEO_INFO', {force: true})
|
||||||
window.parent.postMessage({type: 'getSettings'}, '*')
|
}
|
||||||
}, [])
|
}, [envReady, sendInject])
|
||||||
|
|
||||||
|
useAsyncEffect(async () => {
|
||||||
|
// 更新设置信息
|
||||||
|
sendInject(null, 'GET_VIDEO_ELEMENT_INFO', {}).then(info => {
|
||||||
|
dispatch(setNoVideo(info.noVideo))
|
||||||
|
if (envData.sidePanel) {
|
||||||
|
// get screen height
|
||||||
|
dispatch(setTotalHeight(window.innerHeight))
|
||||||
|
} else {
|
||||||
|
dispatch(setTotalHeight(Math.min(Math.max(info.totalHeight, TOTAL_HEIGHT_MIN), TOTAL_HEIGHT_MAX)))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}, [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(() => {
|
||||||
@@ -160,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)
|
||||||
|
|
||||||
@@ -202,25 +191,30 @@ const useSubtitleService = () => {
|
|||||||
dispatch(setSegments(segments))
|
dispatch(setSegments(segments))
|
||||||
}, [data?.body, dispatch, envData])
|
}, [data?.body, dispatch, envData])
|
||||||
|
|
||||||
// 每秒更新当前视频时间
|
// 每0.5秒更新当前视频时间
|
||||||
useInterval(() => {
|
useInterval(() => {
|
||||||
window.parent.postMessage({type: 'getCurrentTime'}, '*')
|
sendInject(null, 'GET_VIDEO_STATUS', {}).then(status => {
|
||||||
|
// 只有当时间发生显著变化时才更新状态(差异大于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) {
|
||||||
window.parent.postMessage({type: 'updateTransResult'}, '*')
|
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) {
|
||||||
window.parent.postMessage({type: 'updateTransResult', result: transResult.data}, '*')
|
sendInject(null, 'UPDATE_TRANS_RESULT', {result: transResult.data})
|
||||||
} else {
|
} else {
|
||||||
window.parent.postMessage({type: 'updateTransResult'}, '*')
|
sendInject(null, 'HIDE_TRANS', {})
|
||||||
}
|
}
|
||||||
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, transResults])
|
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, sendInject, transResults])
|
||||||
}
|
}
|
||||||
|
|
||||||
export default useSubtitleService
|
export default useSubtitleService
|
||||||
|
@@ -4,14 +4,14 @@ import {
|
|||||||
addTaskId,
|
addTaskId,
|
||||||
addTransResults,
|
addTransResults,
|
||||||
delTaskId,
|
delTaskId,
|
||||||
setAskContent,
|
mergeAskInfo,
|
||||||
setAskError,
|
|
||||||
setAskStatus,
|
|
||||||
setLastSummarizeTime,
|
setLastSummarizeTime,
|
||||||
setLastTransTime,
|
setLastTransTime,
|
||||||
setSummaryContent,
|
setSummaryContent,
|
||||||
setSummaryError,
|
setSummaryError,
|
||||||
setSummaryStatus
|
setSummaryStatus,
|
||||||
|
setReviewAction,
|
||||||
|
setTempData
|
||||||
} from '../redux/envReducer'
|
} from '../redux/envReducer'
|
||||||
import {
|
import {
|
||||||
LANGUAGE_DEFAULT,
|
LANGUAGE_DEFAULT,
|
||||||
@@ -24,12 +24,12 @@ import {
|
|||||||
SUMMARIZE_TYPES,
|
SUMMARIZE_TYPES,
|
||||||
TRANSLATE_COOLDOWN,
|
TRANSLATE_COOLDOWN,
|
||||||
TRANSLATE_FETCH_DEFAULT,
|
TRANSLATE_FETCH_DEFAULT,
|
||||||
} from '../const'
|
} from '../consts/const'
|
||||||
import toast from 'react-hot-toast'
|
import toast from 'react-hot-toast'
|
||||||
import {useMemoizedFn} from 'ahooks/es'
|
import {useMemoizedFn} from 'ahooks/es'
|
||||||
import {extractJsonArray, extractJsonObject, getModel} from '../util/biz_util'
|
import {extractJsonArray, extractJsonObject, getModel} from '../utils/bizUtil'
|
||||||
import {formatTime} from '../util/util'
|
import {formatTime} from '../utils/util'
|
||||||
|
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)
|
||||||
@@ -40,7 +40,10 @@ const useTranslate = () => {
|
|||||||
const language = LANGUAGES_MAP[envData.language??LANGUAGE_DEFAULT]
|
const language = LANGUAGES_MAP[envData.language??LANGUAGE_DEFAULT]
|
||||||
const summarizeLanguage = LANGUAGES_MAP[envData.summarizeLanguage??SUMMARIZE_LANGUAGE_DEFAULT]
|
const summarizeLanguage = LANGUAGES_MAP[envData.summarizeLanguage??SUMMARIZE_LANGUAGE_DEFAULT]
|
||||||
const title = useAppSelector(state => state.env.title)
|
const title = useAppSelector(state => state.env.title)
|
||||||
|
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
|
||||||
|
const reviewAction = useAppSelector(state => state.env.reviewAction)
|
||||||
|
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
|
||||||
|
const {sendExtension} = useMessage(!!envData.sidePanel)
|
||||||
/**
|
/**
|
||||||
* 获取下一个需要翻译的行
|
* 获取下一个需要翻译的行
|
||||||
* 会检测冷却
|
* 会检测冷却
|
||||||
@@ -85,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: [
|
||||||
{
|
{
|
||||||
@@ -117,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,
|
||||||
}
|
}
|
||||||
@@ -132,13 +119,21 @@ const useTranslate = () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
dispatch(addTransResults(result))
|
dispatch(addTransResults(result))
|
||||||
const task = await chrome.runtime.sendMessage({type: 'addTask', 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
|
||||||
|
if (reviewed === undefined && !reviewAction) {
|
||||||
|
dispatch(setReviewAction(true))
|
||||||
|
dispatch(setTempData({
|
||||||
|
reviewActions: (reviewActions ?? 0) + 1
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
if (segment.text.length >= SUMMARIZE_THRESHOLD) {
|
if (segment.text.length >= SUMMARIZE_THRESHOLD) {
|
||||||
let subtitles = ''
|
let subtitles = ''
|
||||||
for (const item of segment.items) {
|
for (const item of segment.items) {
|
||||||
@@ -154,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: [
|
||||||
{
|
{
|
||||||
@@ -188,18 +168,17 @@ 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 chrome.runtime.sendMessage({type: 'addTask', 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 (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) {
|
||||||
let prompt: string = envData.prompts?.[PROMPT_TYPE_ASK]??PROMPT_DEFAULTS[PROMPT_TYPE_ASK]
|
let prompt: string = envData.prompts?.[PROMPT_TYPE_ASK]??PROMPT_DEFAULTS[PROMPT_TYPE_ASK]
|
||||||
// replace params
|
// replace params
|
||||||
@@ -209,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: [
|
||||||
{
|
{
|
||||||
@@ -242,15 +206,18 @@ const useTranslate = () => {
|
|||||||
type: 'ask',
|
type: 'ask',
|
||||||
// startIdx: segment.startIdx,
|
// startIdx: segment.startIdx,
|
||||||
apiKey: envData.apiKey,
|
apiKey: envData.apiKey,
|
||||||
geminiApiKey: envData.geminiApiKey,
|
askId: id,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.debug('addAskTask', taskDef)
|
console.debug('addAskTask', taskDef)
|
||||||
dispatch(setAskStatus({status: 'pending'}))
|
dispatch(mergeAskInfo({
|
||||||
const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef})
|
id,
|
||||||
|
status: 'pending'
|
||||||
|
}))
|
||||||
|
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} = {}
|
||||||
@@ -304,19 +271,23 @@ const useTranslate = () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const handleAsk = useMemoizedFn((task: Task, content?: string) => {
|
const handleAsk = useMemoizedFn((task: Task, content?: string) => {
|
||||||
dispatch(setAskContent({content}))
|
dispatch(mergeAskInfo({
|
||||||
dispatch(setAskStatus({status: 'done'}))
|
id: task.def.extra.askId,
|
||||||
dispatch(setAskError({error: task.error}))
|
content,
|
||||||
|
status: 'done',
|
||||||
|
error: task.error,
|
||||||
|
}))
|
||||||
|
|
||||||
console.debug('setAsk', content, task.error)
|
console.debug('setAsk', content, task.error)
|
||||||
})
|
})
|
||||||
|
|
||||||
const getTask = useCallback(async (taskId: string) => {
|
const getTask = useCallback(async (taskId: string) => {
|
||||||
const taskResp = await chrome.runtime.sendMessage({type: 'getTask', 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) {
|
||||||
@@ -336,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}
|
||||||
}
|
}
|
||||||
|
382
src/inject/inject.ts
Normal file
@@ -0,0 +1,382 @@
|
|||||||
|
import { TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID, STORAGE_ENV, DEFAULT_USE_PORT } from '@/consts/const'
|
||||||
|
import { AllExtensionMessages, AllInjectMessages, AllAPPMessages } from '@/message-typings'
|
||||||
|
import { InjectMessaging } from '@kky002/kky-message'
|
||||||
|
|
||||||
|
const debug = (...args: any[]) => {
|
||||||
|
console.debug('[Inject]', ...args)
|
||||||
|
}
|
||||||
|
|
||||||
|
(async function () {
|
||||||
|
// 如果路径不是/video或/list,则不注入
|
||||||
|
if (!location.pathname.startsWith('/video') && !location.pathname.startsWith('/list')) {
|
||||||
|
debug('Not inject')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取envData
|
||||||
|
const envDataStr = (await chrome.storage.sync.get(STORAGE_ENV))[STORAGE_ENV]
|
||||||
|
let sidePanel: boolean | null = null
|
||||||
|
let manualInsert: boolean | null = null
|
||||||
|
if (envDataStr) {
|
||||||
|
try {
|
||||||
|
const envData = JSON.parse(envDataStr)
|
||||||
|
debug('envData: ', envData)
|
||||||
|
|
||||||
|
sidePanel = envData.sidePanel
|
||||||
|
manualInsert = envData.manualInsert
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error parsing envData:', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const runtime: {
|
||||||
|
injectMessaging: InjectMessaging<AllExtensionMessages, AllInjectMessages, AllAPPMessages>
|
||||||
|
// lastV?: string | null
|
||||||
|
// lastVideoInfo?: VideoInfo
|
||||||
|
|
||||||
|
fold: boolean
|
||||||
|
|
||||||
|
videoElement?: HTMLVideoElement
|
||||||
|
videoElementHeight: number
|
||||||
|
|
||||||
|
showTrans: boolean
|
||||||
|
curTrans?: string
|
||||||
|
} = {
|
||||||
|
injectMessaging: new InjectMessaging(DEFAULT_USE_PORT),
|
||||||
|
fold: true,
|
||||||
|
videoElementHeight: TOTAL_HEIGHT_DEF,
|
||||||
|
showTrans: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
const getVideoElement = () => {
|
||||||
|
const videoWrapper = document.getElementById('bilibili-player')
|
||||||
|
return videoWrapper?.querySelector('video') as HTMLVideoElement | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return if changed
|
||||||
|
*/
|
||||||
|
const refreshVideoElement = () => {
|
||||||
|
const newVideoElement = getVideoElement()
|
||||||
|
const newVideoElementHeight = (newVideoElement != null) ? (Math.min(Math.max(newVideoElement.offsetHeight, TOTAL_HEIGHT_MIN), TOTAL_HEIGHT_MAX)) : TOTAL_HEIGHT_DEF
|
||||||
|
if (newVideoElement === runtime.videoElement && Math.abs(newVideoElementHeight - runtime.videoElementHeight) < 1) {
|
||||||
|
return false
|
||||||
|
} else {
|
||||||
|
runtime.videoElement = newVideoElement
|
||||||
|
runtime.videoElementHeight = newVideoElementHeight
|
||||||
|
// update iframe height
|
||||||
|
updateIframeHeight()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const createIframe = () => {
|
||||||
|
var danmukuBox = document.getElementById('danmukuBox')
|
||||||
|
if (danmukuBox) {
|
||||||
|
var vKey = ''
|
||||||
|
for (const key in danmukuBox?.dataset) {
|
||||||
|
if (key.startsWith('v-')) {
|
||||||
|
vKey = key
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const iframe = document.createElement('iframe')
|
||||||
|
iframe.id = IFRAME_ID
|
||||||
|
iframe.src = chrome.runtime.getURL('index.html')
|
||||||
|
iframe.style.border = 'none'
|
||||||
|
iframe.style.width = '100%'
|
||||||
|
iframe.style.height = '44px'
|
||||||
|
iframe.style.marginBottom = '3px'
|
||||||
|
iframe.allow = 'clipboard-read; clipboard-write;'
|
||||||
|
|
||||||
|
if (vKey) {
|
||||||
|
iframe.dataset[vKey] = danmukuBox?.dataset[vKey]
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert before first child
|
||||||
|
danmukuBox?.insertBefore(iframe, danmukuBox?.firstChild)
|
||||||
|
|
||||||
|
// show badge
|
||||||
|
runtime.injectMessaging.sendExtension('SHOW_FLAG', {
|
||||||
|
show: true
|
||||||
|
})
|
||||||
|
|
||||||
|
debug('iframe inserted')
|
||||||
|
|
||||||
|
return iframe
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sidePanel && !manualInsert) {
|
||||||
|
const timerIframe = setInterval(function () {
|
||||||
|
var danmukuBox = document.getElementById('danmukuBox')
|
||||||
|
if (danmukuBox) {
|
||||||
|
clearInterval(timerIframe)
|
||||||
|
|
||||||
|
// 延迟插入iframe(插入太快,网络较差时容易出现b站网页刷新,原因暂时未知,可能b站的某种机制?)
|
||||||
|
setTimeout(createIframe, 1500)
|
||||||
|
}
|
||||||
|
}, 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
let aid: number | null = null
|
||||||
|
let ctime: number | null = null
|
||||||
|
let author: string | undefined
|
||||||
|
let title = ''
|
||||||
|
let pages: any[] = []
|
||||||
|
let pagesMap: Record<string, any> = {}
|
||||||
|
|
||||||
|
let lastAidOrBvid: string | null = null
|
||||||
|
const refreshVideoInfo = async (force: boolean = false) => {
|
||||||
|
if (force) {
|
||||||
|
lastAidOrBvid = null
|
||||||
|
}
|
||||||
|
if (!sidePanel) {
|
||||||
|
const iframe = document.getElementById(IFRAME_ID) as HTMLIFrameElement | undefined
|
||||||
|
if (!iframe) return
|
||||||
|
}
|
||||||
|
|
||||||
|
// fix: https://github.com/IndieKKY/bilibili-subtitle/issues/5
|
||||||
|
// 处理稍后再看的url( https://www.bilibili.com/list/watchlater?bvid=xxx&oid=xxx )
|
||||||
|
const pathSearchs: Record<string, string> = {}
|
||||||
|
// eslint-disable-next-line no-return-assign
|
||||||
|
location.search.slice(1).replace(/([^=&]*)=([^=&]*)/g, (matchs, a, b, c) => pathSearchs[a] = b)
|
||||||
|
|
||||||
|
// bvid
|
||||||
|
let aidOrBvid = pathSearchs.bvid // 默认为稍后再看
|
||||||
|
if (!aidOrBvid) {
|
||||||
|
let path = location.pathname
|
||||||
|
if (path.endsWith('/')) {
|
||||||
|
path = path.slice(0, -1)
|
||||||
|
}
|
||||||
|
const paths = path.split('/')
|
||||||
|
aidOrBvid = paths[paths.length - 1]
|
||||||
|
}
|
||||||
|
|
||||||
|
if (aidOrBvid !== lastAidOrBvid) {
|
||||||
|
// console.debug('refreshVideoInfo')
|
||||||
|
|
||||||
|
lastAidOrBvid = aidOrBvid
|
||||||
|
if (aidOrBvid) {
|
||||||
|
// aid,pages
|
||||||
|
let cid: string | undefined
|
||||||
|
let subtitles
|
||||||
|
if (aidOrBvid.toLowerCase().startsWith('av')) { // avxxx
|
||||||
|
aid = parseInt(aidOrBvid.slice(2))
|
||||||
|
pages = await fetch(`https://api.bilibili.com/x/player/pagelist?aid=${aid}`, { credentials: 'include' }).then(async res => await res.json()).then(res => res.data)
|
||||||
|
cid = pages[0].cid
|
||||||
|
ctime = pages[0].ctime
|
||||||
|
author = pages[0].owner?.name
|
||||||
|
title = pages[0].part
|
||||||
|
await fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid}&cid=${cid!}`, { credentials: 'include' }).then(async res => await res.json()).then(res => {
|
||||||
|
subtitles = res.data.subtitle.subtitles
|
||||||
|
})
|
||||||
|
} else { // bvxxx
|
||||||
|
await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${aidOrBvid}`, { credentials: 'include' }).then(async res => await res.json()).then(async res => {
|
||||||
|
title = res.data.title
|
||||||
|
aid = res.data.aid
|
||||||
|
cid = res.data.cid
|
||||||
|
ctime = res.data.ctime
|
||||||
|
author = res.data.owner?.name
|
||||||
|
pages = res.data.pages
|
||||||
|
})
|
||||||
|
await fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid!}&cid=${cid!}`, { credentials: 'include' }).then(async res => await res.json()).then(res => {
|
||||||
|
subtitles = res.data.subtitle.subtitles
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// pagesMap
|
||||||
|
pagesMap = {}
|
||||||
|
pages.forEach(page => {
|
||||||
|
pagesMap[page.page + ''] = page
|
||||||
|
})
|
||||||
|
|
||||||
|
debug('refreshVideoInfo: ', aid, cid, pages, subtitles)
|
||||||
|
|
||||||
|
// send setVideoInfo
|
||||||
|
runtime.injectMessaging.sendApp(!!sidePanel, 'SET_VIDEO_INFO', {
|
||||||
|
url: location.origin + location.pathname,
|
||||||
|
title,
|
||||||
|
aid,
|
||||||
|
ctime,
|
||||||
|
author,
|
||||||
|
pages,
|
||||||
|
infos: subtitles,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let lastAid: number | null = null
|
||||||
|
let lastCid: number | null = null
|
||||||
|
const refreshSubtitles = () => {
|
||||||
|
if (!sidePanel) {
|
||||||
|
const iframe = document.getElementById(IFRAME_ID) as HTMLIFrameElement | undefined
|
||||||
|
if (!iframe) return
|
||||||
|
}
|
||||||
|
|
||||||
|
const urlSearchParams = new URLSearchParams(window.location.search)
|
||||||
|
const p = urlSearchParams.get('p') || 1
|
||||||
|
const page = pagesMap[p]
|
||||||
|
if (!page) return
|
||||||
|
const cid: number | null = page.cid
|
||||||
|
|
||||||
|
if (aid !== lastAid || cid !== lastCid) {
|
||||||
|
debug('refreshSubtitles', aid, cid)
|
||||||
|
|
||||||
|
lastAid = aid
|
||||||
|
lastCid = cid
|
||||||
|
if (aid && cid) {
|
||||||
|
fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid}&cid=${cid}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
})
|
||||||
|
.then(async res => await res.json())
|
||||||
|
.then(res => {
|
||||||
|
// remove elements with empty subtitle_url
|
||||||
|
res.data.subtitle.subtitles = res.data.subtitle.subtitles.filter((item: any) => item.subtitle_url)
|
||||||
|
if (res.data.subtitle.subtitles.length > 0) {
|
||||||
|
runtime.injectMessaging.sendApp(!!sidePanel, 'SET_INFOS', {
|
||||||
|
infos: res.data.subtitle.subtitles
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateIframeHeight = () => {
|
||||||
|
const iframe = document.getElementById(IFRAME_ID) as HTMLIFrameElement | undefined
|
||||||
|
if (iframe != null) {
|
||||||
|
iframe.style.height = (runtime.fold ? HEADER_HEIGHT : runtime.videoElementHeight) + 'px'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const methods: {
|
||||||
|
[K in AllInjectMessages['method']]: (params: Extract<AllInjectMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
|
||||||
|
} = {
|
||||||
|
TOGGLE_DISPLAY: async (params) => {
|
||||||
|
const iframe = document.getElementById(IFRAME_ID) as HTMLIFrameElement | undefined
|
||||||
|
if (iframe != null) {
|
||||||
|
iframe.style.display = iframe.style.display === 'none' ? 'block' : 'none'
|
||||||
|
runtime.injectMessaging.sendExtension('SHOW_FLAG', {
|
||||||
|
show: iframe.style.display !== 'none'
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
createIframe()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
FOLD: async (params) => {
|
||||||
|
runtime.fold = params.fold
|
||||||
|
updateIframeHeight()
|
||||||
|
},
|
||||||
|
MOVE: async (params) => {
|
||||||
|
const video = getVideoElement()
|
||||||
|
if (video != null) {
|
||||||
|
video.currentTime = params.time
|
||||||
|
if (params.togglePause) {
|
||||||
|
video.paused ? video.play() : video.pause()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
GET_SUBTITLE: async (params) => {
|
||||||
|
let url = params.info.subtitle_url
|
||||||
|
if (url.startsWith('http://')) {
|
||||||
|
url = url.replace('http://', 'https://')
|
||||||
|
}
|
||||||
|
return await fetch(url).then(async res => await res.json())
|
||||||
|
},
|
||||||
|
GET_VIDEO_STATUS: async (params) => {
|
||||||
|
const video = getVideoElement()
|
||||||
|
if (video != null) {
|
||||||
|
return {
|
||||||
|
paused: video.paused,
|
||||||
|
currentTime: video.currentTime
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
GET_VIDEO_ELEMENT_INFO: async (params) => {
|
||||||
|
refreshVideoElement()
|
||||||
|
return {
|
||||||
|
noVideo: runtime.videoElement == null,
|
||||||
|
totalHeight: runtime.videoElementHeight,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
REFRESH_VIDEO_INFO: async (params) => {
|
||||||
|
refreshVideoInfo(params.force)
|
||||||
|
},
|
||||||
|
UPDATE_TRANS_RESULT: async (params) => {
|
||||||
|
runtime.showTrans = true
|
||||||
|
runtime.curTrans = params?.result
|
||||||
|
|
||||||
|
let text = document.getElementById('trans-result-text')
|
||||||
|
if (text) {
|
||||||
|
text.innerHTML = runtime.curTrans ?? ''
|
||||||
|
} else {
|
||||||
|
const container = document.getElementsByClassName('bpx-player-subtitle-panel-wrap')?.[0]
|
||||||
|
if (container) {
|
||||||
|
const div = document.createElement('div')
|
||||||
|
div.style.display = 'flex'
|
||||||
|
div.style.justifyContent = 'center'
|
||||||
|
div.style.margin = '2px'
|
||||||
|
text = document.createElement('text')
|
||||||
|
text.id = 'trans-result-text'
|
||||||
|
text.innerHTML = runtime.curTrans ?? ''
|
||||||
|
text.style.fontSize = '1rem'
|
||||||
|
text.style.padding = '5px'
|
||||||
|
text.style.color = 'white'
|
||||||
|
text.style.background = 'rgba(0, 0, 0, 0.4)'
|
||||||
|
div.append(text)
|
||||||
|
|
||||||
|
container.append(div)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
text && (text.style.display = runtime.curTrans ? 'block' : 'none')
|
||||||
|
},
|
||||||
|
HIDE_TRANS: async (params) => {
|
||||||
|
runtime.showTrans = false
|
||||||
|
runtime.curTrans = undefined
|
||||||
|
|
||||||
|
const text = document.getElementById('trans-result-text')
|
||||||
|
if (text) {
|
||||||
|
text.style.display = 'none'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
PLAY: async (params) => {
|
||||||
|
const { play } = params
|
||||||
|
const video = getVideoElement()
|
||||||
|
if (video != null) {
|
||||||
|
if (play) {
|
||||||
|
await video.play()
|
||||||
|
} else {
|
||||||
|
video.pause()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
DOWNLOAD_AUDIO: async (params) => {
|
||||||
|
const html = document.getElementsByTagName('html')[0].innerHTML
|
||||||
|
const playInfo = JSON.parse(html.match(/window.__playinfo__=(.+?)<\/script/)?.[1] ?? '{}')
|
||||||
|
const audioUrl = playInfo.data.dash.audio[0].baseUrl
|
||||||
|
|
||||||
|
fetch(audioUrl).then(async res => await res.blob()).then(blob => {
|
||||||
|
const a = document.createElement('a')
|
||||||
|
a.href = URL.createObjectURL(blob)
|
||||||
|
a.download = `${title}.m4s`
|
||||||
|
a.click()
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化injectMessage
|
||||||
|
runtime.injectMessaging.init(methods)
|
||||||
|
|
||||||
|
setInterval(() => {
|
||||||
|
if (!sidePanel) {
|
||||||
|
const iframe = document.getElementById(IFRAME_ID) as HTMLIFrameElement | undefined
|
||||||
|
if (!iframe || iframe.style.display === 'none') return
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshVideoInfo().catch(console.error)
|
||||||
|
refreshSubtitles()
|
||||||
|
}, 1000)
|
||||||
|
})()
|
87
src/message-typings.d.ts
vendored
Normal 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
|
53
src/pages/MainPage.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import React, {useCallback, useContext, useEffect} from 'react'
|
||||||
|
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||||
|
import Header from '../components/Header'
|
||||||
|
import Body from '../components/Body'
|
||||||
|
import useSubtitleService from '../hooks/useSubtitleService'
|
||||||
|
import {EVENT_EXPAND} from '../consts/const'
|
||||||
|
import {EventBusContext} from '../Router'
|
||||||
|
import useTranslateService from '../hooks/useTranslateService'
|
||||||
|
import {setTheme} from '../utils/bizUtil'
|
||||||
|
import useSearchService from '../hooks/useSearchService'
|
||||||
|
import {setFold} from '../redux/envReducer'
|
||||||
|
import { useMessage } from '@/hooks/useMessageService'
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const dispatch = useAppDispatch()
|
||||||
|
const fold = useAppSelector(state => state.env.fold)
|
||||||
|
const envData = useAppSelector(state => state.env.envData)
|
||||||
|
const eventBus = useContext(EventBusContext)
|
||||||
|
const totalHeight = useAppSelector(state => state.env.totalHeight)
|
||||||
|
const {sendInject} = useMessage(!!envData.sidePanel)
|
||||||
|
|
||||||
|
const foldCallback = useCallback(() => {
|
||||||
|
dispatch(setFold(!fold))
|
||||||
|
sendInject(null, 'FOLD', {fold: !fold})
|
||||||
|
}, [dispatch, fold, sendInject])
|
||||||
|
|
||||||
|
// handle event
|
||||||
|
eventBus.useSubscription((event: any) => {
|
||||||
|
if (event.type === EVENT_EXPAND) {
|
||||||
|
if (fold) {
|
||||||
|
foldCallback()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// theme改变时,设置主题
|
||||||
|
useEffect(() => {
|
||||||
|
setTheme(envData.theme)
|
||||||
|
}, [envData.theme])
|
||||||
|
|
||||||
|
useSubtitleService()
|
||||||
|
useTranslateService()
|
||||||
|
useSearchService()
|
||||||
|
|
||||||
|
return <div className='select-none w-full' style={{
|
||||||
|
height: fold?undefined:`${totalHeight}px`,
|
||||||
|
}}>
|
||||||
|
<Header foldCallback={foldCallback}/>
|
||||||
|
{!fold && <Body/>}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App
|
@@ -1,18 +1,17 @@
|
|||||||
import React, {PropsWithChildren, useCallback, useMemo, useState} from 'react'
|
import React, {PropsWithChildren, useCallback, useMemo, useState} from 'react'
|
||||||
import {setEnvData, setPage} 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,
|
||||||
MODEL_DEFAULT,
|
MODEL_DEFAULT,
|
||||||
MODEL_MAP,
|
MODEL_MAP,
|
||||||
|
MODEL_TIP,
|
||||||
MODELS,
|
MODELS,
|
||||||
PAGE_MAIN,
|
|
||||||
PROMPT_DEFAULTS,
|
PROMPT_DEFAULTS,
|
||||||
PROMPT_TYPES,
|
PROMPT_TYPES,
|
||||||
SUMMARIZE_LANGUAGE_DEFAULT,
|
SUMMARIZE_LANGUAGE_DEFAULT,
|
||||||
@@ -21,22 +20,29 @@ import {
|
|||||||
TRANSLATE_FETCH_MIN,
|
TRANSLATE_FETCH_MIN,
|
||||||
TRANSLATE_FETCH_STEP,
|
TRANSLATE_FETCH_STEP,
|
||||||
WORDS_RATE,
|
WORDS_RATE,
|
||||||
} from '../const'
|
} from '../consts/const'
|
||||||
import {FaGripfire, IoWarning} from 'react-icons/all'
|
import {IoWarning} from 'react-icons/all'
|
||||||
import classNames from 'classnames'
|
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 { 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-xs' 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: {
|
||||||
@@ -45,19 +51,24 @@ 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 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 Settings = () => {
|
const OptionsPage = () => {
|
||||||
const dispatch = useAppDispatch()
|
const dispatch = useAppDispatch()
|
||||||
const envData = useAppSelector(state => state.env.envData)
|
const envData = useAppSelector(state => state.env.envData)
|
||||||
|
const {sendExtension} = useMessage(false)
|
||||||
|
const {value: sidePanelValue, onChange: setSidePanelValue} = useEventChecked(envData.sidePanel)
|
||||||
|
const {value: autoInsertValue, onChange: setAutoInsertValue} = useEventChecked(!envData.manualInsert)
|
||||||
const {value: autoExpandValue, onChange: setAutoExpandValue} = useEventChecked(envData.autoExpand)
|
const {value: autoExpandValue, onChange: setAutoExpandValue} = useEventChecked(envData.autoExpand)
|
||||||
// const {value: autoScrollValue, onChange: setAutoScrollValue} = useEventChecked(envData.autoScroll)
|
// const {value: autoScrollValue, onChange: setAutoScrollValue} = useEventChecked(envData.autoScroll)
|
||||||
const {value: translateEnableValue, onChange: setTranslateEnableValue} = useEventChecked(envData.translateEnable)
|
const {value: translateEnableValue, onChange: setTranslateEnableValue} = useEventChecked(envData.translateEnable)
|
||||||
@@ -68,7 +79,6 @@ const Settings = () => {
|
|||||||
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})
|
||||||
@@ -77,14 +87,10 @@ const Settings = () => {
|
|||||||
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)
|
||||||
const [moreFold, {toggle: toggleMoreFold}] = useBoolean(true)
|
|
||||||
const [promptsFold, {toggle: togglePromptsFold}] = useBoolean(true)
|
const [promptsFold, {toggle: togglePromptsFold}] = useBoolean(true)
|
||||||
const fold = useAppSelector(state => state.env.fold)
|
|
||||||
const totalHeight = useAppSelector(state => state.env.totalHeight)
|
|
||||||
const [promptsValue, setPromptsValue] = useState<{[key: string]: string}>(envData.prompts??{})
|
const [promptsValue, setPromptsValue] = useState<{[key: string]: string}>(envData.prompts??{})
|
||||||
// const wordsList = useMemo(() => {
|
// const wordsList = useMemo(() => {
|
||||||
// const list = []
|
// const list = []
|
||||||
@@ -101,11 +107,8 @@ const Settings = () => {
|
|||||||
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)
|
||||||
@@ -113,14 +116,14 @@ const Settings = () => {
|
|||||||
|
|
||||||
const onSave = useCallback(() => {
|
const onSave = useCallback(() => {
|
||||||
dispatch(setEnvData({
|
dispatch(setEnvData({
|
||||||
|
sidePanel: sidePanelValue,
|
||||||
|
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,
|
||||||
@@ -137,13 +140,17 @@ const Settings = () => {
|
|||||||
cnSearchEnabled: cnSearchEnabledValue,
|
cnSearchEnabled: cnSearchEnabledValue,
|
||||||
askEnabled: askEnabledValue,
|
askEnabled: askEnabledValue,
|
||||||
}))
|
}))
|
||||||
dispatch(setPage(PAGE_MAIN))
|
|
||||||
toast.success('保存成功')
|
toast.success('保存成功')
|
||||||
}, [dispatch, autoExpandValue, aiTypeValue, apiKeyValue, serverUrlValue, modelValue, customModelValue, customModelTokensValue, geminiApiKeyValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue, askEnabledValue])
|
sendExtension(null, 'CLOSE_SIDE_PANEL')
|
||||||
|
// 3秒后关闭
|
||||||
|
setTimeout(() => {
|
||||||
|
window.close()
|
||||||
|
}, 3000)
|
||||||
|
}, [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(() => {
|
||||||
dispatch(setPage(PAGE_MAIN))
|
window.close()
|
||||||
}, [dispatch])
|
}, [])
|
||||||
|
|
||||||
const onFetchAmountChange = useCallback((e: any) => {
|
const onFetchAmountChange = useCallback((e: any) => {
|
||||||
setFetchAmountValue(parseInt(e.target.value))
|
setFetchAmountValue(parseInt(e.target.value))
|
||||||
@@ -185,126 +192,93 @@ const Settings = () => {
|
|||||||
setFontSizeValue('large')
|
setFontSizeValue('large')
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const onSelOpenai = useCallback(() => {
|
return (
|
||||||
setAiTypeValue('openai')
|
<div className='container mx-auto max-w-3xl p-4'>
|
||||||
}, [])
|
<OptionCard title="通用配置">
|
||||||
|
<FormItem title='侧边栏' htmlFor='sidePanel' tip='字幕列表是否显示在侧边栏'>
|
||||||
const onSelGemini = useCallback(() => {
|
<input id='sidePanel' type='checkbox' className='toggle toggle-primary' checked={sidePanelValue}
|
||||||
setAiTypeValue('gemini')
|
onChange={setSidePanelValue}/>
|
||||||
}, [])
|
</FormItem>
|
||||||
|
{!sidePanelValue && <FormItem title='自动插入' htmlFor='autoInsert' tip='是否自动插入字幕列表(可以手动点击扩展图标插入)'>
|
||||||
return <div className='text-sm overflow-y-auto' style={{
|
<input id='autoInsert' type='checkbox' className='toggle toggle-primary' checked={autoInsertValue}
|
||||||
height: fold?undefined:`${totalHeight-HEADER_HEIGHT}px`,
|
onChange={setAutoInsertValue}/>
|
||||||
}}>
|
</FormItem>}
|
||||||
<div className="flex flex-col gap-3 p-2">
|
{!sidePanelValue && <FormItem title='自动展开' htmlFor='autoExpand' tip='是否视频有字幕时自动展开字幕列表'>
|
||||||
<Section title='通用配置'>
|
|
||||||
<FormItem title='自动展开' htmlFor='autoExpand' tip='是否视频有字幕时自动展开字幕列表'>
|
|
||||||
<input id='autoExpand' type='checkbox' className='toggle toggle-primary' checked={autoExpandValue}
|
<input id='autoExpand' type='checkbox' className='toggle toggle-primary' checked={autoExpandValue}
|
||||||
onChange={setAutoExpandValue}/>
|
onChange={setAutoExpandValue}/>
|
||||||
</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'
|
||||||
|
rel="noreferrer">点击访问</a></div>
|
||||||
|
<div>服务器地址:<a className='link link-primary'
|
||||||
|
onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_GEMINI)}
|
||||||
|
rel='noreferrer'>点击设置</a></div>
|
||||||
|
<div className='flex justify-center font-semibold'>【第三方国内代理】</div>
|
||||||
|
<div>代理网址:<a className='link link-primary' href='https://api.kksj.org/register?aff=ucVc'
|
||||||
target='_blank'
|
target='_blank'
|
||||||
rel="noreferrer">点击访问</a></div>
|
rel="noreferrer">点击访问</a></div>
|
||||||
<div>服务器地址:<a className='link link-primary'
|
<div>服务器地址:<a className='link link-primary'
|
||||||
onClick={() => setServerUrlValue('https://api.openai-up.com')}
|
onClick={() => setServerUrlValue('https://api.kksj.org')}
|
||||||
rel='noreferrer'>点击设置</a></div>
|
rel='noreferrer'>点击设置</a></div>
|
||||||
<div className='text-amber-600 flex justify-center items-center'><FaGripfire/>目前价格不到官方价格的6折<FaGripfire/></div>
|
<div className='text-amber-600 flex justify-center items-center'><FaGripfire/>目前0.9人民币可充值1美元(约官方价格1/8)<FaGripfire/></div>
|
||||||
|
<div className='text-amber-600 flex justify-center items-center'><FaGripfire/>国内可访问,无需🪜<FaGripfire/></div>
|
||||||
</div>
|
</div>
|
||||||
</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-sm'>
|
||||||
|
{MODEL_TIP}
|
||||||
|
</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}/>
|
||||||
</FormItem>}
|
</FormItem>}
|
||||||
{modelValue === 'custom' && <FormItem title='Token上限' htmlFor='customModelTokens'>
|
{modelValue === 'custom' && <FormItem title='Token上限' htmlFor='customModelTokens'>
|
||||||
<input id='customModelTokens' type='number' className='input input-sm input-bordered w-full' placeholder={''+CUSTOM_MODEL_TOKENS}
|
<input id='customModelTokens' type='number' className='input input-sm input-bordered w-full'
|
||||||
value={customModelTokensValue} onChange={e => setCustomModelTokensValue(e.target.value?parseInt(e.target.value):undefined)}/>
|
placeholder={'' + CUSTOM_MODEL_TOKENS}
|
||||||
|
value={customModelTokensValue}
|
||||||
|
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='提示词配置'>
|
|
||||||
{PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div>
|
|
||||||
<div>{item.name}</div>
|
|
||||||
<div className='link text-xs' onClick={() => {
|
|
||||||
setPromptsValue({
|
|
||||||
...promptsValue,
|
|
||||||
// @ts-expect-error
|
|
||||||
[item.type]: PROMPT_DEFAULTS[item.type] ?? ''
|
|
||||||
})
|
|
||||||
}}>点击填充默认
|
|
||||||
</div>
|
|
||||||
</div>} htmlFor={`prompt-${item.type}`}>
|
|
||||||
<textarea id={`prompt-${item.type}`} className='mt-2 textarea input-bordered w-full'
|
|
||||||
placeholder='留空使用默认提示词' value={promptsValue[item.type] ?? ''} onChange={(e) => {
|
|
||||||
setPromptsValue({
|
|
||||||
...promptsValue,
|
|
||||||
[item.type]: e.target.value
|
|
||||||
})
|
|
||||||
}}/>
|
|
||||||
</FormItem>)}
|
|
||||||
</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 Settings = () => {
|
|||||||
<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 Settings = () => {
|
|||||||
<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,21 +358,47 @@ const Settings = () => {
|
|||||||
<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>
|
||||||
<div className='flex justify-center gap-5'>
|
|
||||||
<button className='btn btn-primary btn-sm' onClick={onSave}>保存</button>
|
<OptionCard title='提示词配置'>
|
||||||
<button className='btn btn-sm' onClick={onCancel}>取消</button>
|
<div className='flex justify-center'>
|
||||||
|
<a className='text-sm link link-primary' onClick={togglePromptsFold}>点击{promptsFold ? '展开' : '折叠'}</a>
|
||||||
|
</div>
|
||||||
|
{!promptsFold && PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div>
|
||||||
|
<div>{item.name}</div>
|
||||||
|
<div className='link text-sm' onClick={() => {
|
||||||
|
setPromptsValue({
|
||||||
|
...promptsValue,
|
||||||
|
// @ts-expect-error
|
||||||
|
[item.type]: PROMPT_DEFAULTS[item.type] ?? ''
|
||||||
|
})
|
||||||
|
}}>点击填充默认
|
||||||
|
</div>
|
||||||
|
</div>} htmlFor={`prompt-${item.type}`}>
|
||||||
|
<textarea id={`prompt-${item.type}`} className='mt-2 textarea input-bordered w-full'
|
||||||
|
placeholder='留空使用默认提示词' value={promptsValue[item.type] ?? ''} onChange={(e) => {
|
||||||
|
setPromptsValue({
|
||||||
|
...promptsValue,
|
||||||
|
[item.type]: e.target.value
|
||||||
|
})
|
||||||
|
}}/>
|
||||||
|
</FormItem>)}
|
||||||
|
</OptionCard>
|
||||||
|
|
||||||
|
<div className='flex flex-col justify-center items-center gap-5 mt-6'>
|
||||||
|
<button className='btn btn-primary btn-wide' onClick={onSave}>保存</button>
|
||||||
|
<button className='btn btn-wide' onClick={onCancel}>取消</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default Settings
|
export default OptionsPage
|
23
src/redux/currentTimeReducer.ts
Normal 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
|
@@ -1,7 +1,6 @@
|
|||||||
import {createSlice, PayloadAction} from '@reduxjs/toolkit'
|
import {createSlice, PayloadAction} from '@reduxjs/toolkit'
|
||||||
import {find} from 'lodash-es'
|
import {find, findIndex} from 'lodash-es'
|
||||||
import {getDevData} from '../util/biz_util'
|
import {DEFAULT_SERVER_URL_OPENAI, TOTAL_HEIGHT_DEF} from '../consts/const'
|
||||||
import {DEFAULT_SERVER_URL_OPENAI, TOTAL_HEIGHT_DEF} from '../const'
|
|
||||||
|
|
||||||
interface EnvState {
|
interface EnvState {
|
||||||
envData: EnvData
|
envData: EnvData
|
||||||
@@ -10,9 +9,10 @@ interface EnvState {
|
|||||||
tempData: TempData
|
tempData: TempData
|
||||||
tempReady: boolean
|
tempReady: boolean
|
||||||
|
|
||||||
|
path?: 'app' | 'options'
|
||||||
|
|
||||||
fold: boolean // fold app
|
fold: boolean // fold app
|
||||||
foldAll?: boolean // fold all segments
|
foldAll?: boolean // fold all segments
|
||||||
page?: string
|
|
||||||
autoTranslate?: boolean
|
autoTranslate?: boolean
|
||||||
autoScroll?: boolean
|
autoScroll?: boolean
|
||||||
checkAutoScroll?: boolean
|
checkAutoScroll?: boolean
|
||||||
@@ -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,21 +31,26 @@ 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
|
||||||
lastSummarizeTime?: number
|
lastSummarizeTime?: number
|
||||||
|
|
||||||
// ask
|
// ask
|
||||||
askFold?: boolean
|
asks: AskInfo[]
|
||||||
askQuestion?: string
|
|
||||||
askStatus: SummaryStatus
|
/**
|
||||||
askError?: string
|
* 是否输入中(中文)
|
||||||
askContent?: string
|
*/
|
||||||
|
inputting: boolean
|
||||||
|
|
||||||
searchText: string
|
searchText: string
|
||||||
searchResult: Set<number>
|
searchResult: Record<string, boolean>
|
||||||
|
|
||||||
|
// 当前视频是否计算过操作
|
||||||
|
reviewAction: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const initialState: EnvState = {
|
const initialState: EnvState = {
|
||||||
@@ -61,18 +65,21 @@ const initialState: EnvState = {
|
|||||||
tempData: {
|
tempData: {
|
||||||
curSummaryType: 'overview',
|
curSummaryType: 'overview',
|
||||||
},
|
},
|
||||||
askStatus: 'init',
|
|
||||||
totalHeight: TOTAL_HEIGHT_DEF,
|
totalHeight: TOTAL_HEIGHT_DEF,
|
||||||
autoScroll: true,
|
autoScroll: true,
|
||||||
currentTime: import.meta.env.VITE_ENV === 'web-dev' ? 30 : undefined,
|
|
||||||
envReady: false,
|
envReady: false,
|
||||||
tempReady: false,
|
tempReady: false,
|
||||||
fold: true,
|
fold: true,
|
||||||
data: import.meta.env.VITE_ENV === 'web-dev' ? getDevData() : undefined,
|
|
||||||
transResults: {},
|
transResults: {},
|
||||||
|
|
||||||
|
inputting: false,
|
||||||
|
|
||||||
searchText: '',
|
searchText: '',
|
||||||
searchResult: new Set(),
|
searchResult: {},
|
||||||
|
|
||||||
|
asks: [],
|
||||||
|
|
||||||
|
reviewAction: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
export const slice = createSlice({
|
export const slice = createSlice({
|
||||||
@@ -94,13 +101,19 @@ export const slice = createSlice({
|
|||||||
...action.payload,
|
...action.payload,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
setReviewAction: (state, action: PayloadAction<boolean>) => {
|
||||||
|
state.reviewAction = action.payload
|
||||||
|
},
|
||||||
|
setPath: (state, action: PayloadAction<'app' | 'options' | undefined>) => {
|
||||||
|
state.path = action.payload
|
||||||
|
},
|
||||||
setTempReady: (state) => {
|
setTempReady: (state) => {
|
||||||
state.tempReady = true
|
state.tempReady = true
|
||||||
},
|
},
|
||||||
setSearchText: (state, action: PayloadAction<string>) => {
|
setSearchText: (state, action: PayloadAction<string>) => {
|
||||||
state.searchText = action.payload
|
state.searchText = action.payload
|
||||||
},
|
},
|
||||||
setSearchResult: (state, action: PayloadAction<Set<number>>) => {
|
setSearchResult: (state, action: PayloadAction<Record<string, boolean>>) => {
|
||||||
state.searchResult = action.payload
|
state.searchResult = action.payload
|
||||||
},
|
},
|
||||||
setFloatKeyPointsSegIdx: (state, action: PayloadAction<number | undefined>) => {
|
setFloatKeyPointsSegIdx: (state, action: PayloadAction<number | undefined>) => {
|
||||||
@@ -109,9 +122,6 @@ export const slice = createSlice({
|
|||||||
setFoldAll: (state, action: PayloadAction<boolean>) => {
|
setFoldAll: (state, action: PayloadAction<boolean>) => {
|
||||||
state.foldAll = action.payload
|
state.foldAll = action.payload
|
||||||
},
|
},
|
||||||
setPage: (state, action: PayloadAction<string | undefined>) => {
|
|
||||||
state.page = action.payload
|
|
||||||
},
|
|
||||||
setTotalHeight: (state, action: PayloadAction<number>) => {
|
setTotalHeight: (state, action: PayloadAction<number>) => {
|
||||||
state.totalHeight = action.payload
|
state.totalHeight = action.payload
|
||||||
},
|
},
|
||||||
@@ -204,26 +214,20 @@ export const slice = createSlice({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
setAskFold: (state, action: PayloadAction<boolean>) => {
|
addAskInfo: (state, action: PayloadAction<AskInfo>) => {
|
||||||
state.askFold = action.payload
|
state.asks.push(action.payload)
|
||||||
},
|
},
|
||||||
setAskQuestion: (state, action: PayloadAction<string | undefined>) => {
|
delAskInfo: (state, action: PayloadAction<string>) => {
|
||||||
state.askQuestion = action.payload
|
state.asks = state.asks.filter(ask => ask.id !== action.payload)
|
||||||
},
|
},
|
||||||
setAskContent: (state, action: PayloadAction<{
|
mergeAskInfo: (state, action: PayloadAction<PartialOfAskInfo>) => {
|
||||||
content?: any
|
const idx = findIndex(state.asks, {id: action.payload.id})
|
||||||
}>) => {
|
if (idx >= 0) {
|
||||||
state.askContent = action.payload.content
|
state.asks[idx] = {
|
||||||
},
|
...state.asks[idx],
|
||||||
setAskStatus: (state, action: PayloadAction<{
|
...action.payload,
|
||||||
status: SummaryStatus
|
}
|
||||||
}>) => {
|
}
|
||||||
state.askStatus = action.payload.status
|
|
||||||
},
|
|
||||||
setAskError: (state, action: PayloadAction<{
|
|
||||||
error?: string
|
|
||||||
}>) => {
|
|
||||||
state.askError = action.payload.error
|
|
||||||
},
|
},
|
||||||
setSegmentFold: (state, action: PayloadAction<{
|
setSegmentFold: (state, action: PayloadAction<{
|
||||||
segmentStartIdx: number
|
segmentStartIdx: number
|
||||||
@@ -258,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
|
||||||
},
|
},
|
||||||
@@ -288,16 +295,15 @@ export const slice = createSlice({
|
|||||||
setFold: (state, action: PayloadAction<boolean>) => {
|
setFold: (state, action: PayloadAction<boolean>) => {
|
||||||
state.fold = action.payload
|
state.fold = action.payload
|
||||||
},
|
},
|
||||||
|
setInputting: (state, action: PayloadAction<boolean>) => {
|
||||||
|
state.inputting = action.payload
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
export const {
|
export const {
|
||||||
|
setPath,
|
||||||
setUrl,
|
setUrl,
|
||||||
setAskFold,
|
|
||||||
setAskQuestion,
|
|
||||||
setAskStatus,
|
|
||||||
setAskError,
|
|
||||||
setAskContent,
|
|
||||||
setTempReady,
|
setTempReady,
|
||||||
setTempData,
|
setTempData,
|
||||||
setUploadedTranscript,
|
setUploadedTranscript,
|
||||||
@@ -313,7 +319,6 @@ export const {
|
|||||||
setTitle,
|
setTitle,
|
||||||
setSegments,
|
setSegments,
|
||||||
setLastSummarizeTime,
|
setLastSummarizeTime,
|
||||||
setPage,
|
|
||||||
setLastTransTime,
|
setLastTransTime,
|
||||||
clearTransResults,
|
clearTransResults,
|
||||||
addTransResults,
|
addTransResults,
|
||||||
@@ -323,11 +328,11 @@ export const {
|
|||||||
setAutoTranslate,
|
setAutoTranslate,
|
||||||
setAutoScroll,
|
setAutoScroll,
|
||||||
setNoVideo,
|
setNoVideo,
|
||||||
|
setReviewAction,
|
||||||
setNeedScroll,
|
setNeedScroll,
|
||||||
setCurIdx,
|
setCurIdx,
|
||||||
setEnvData,
|
setEnvData,
|
||||||
setEnvReady,
|
setEnvReady,
|
||||||
setCurrentTime,
|
|
||||||
setInfos,
|
setInfos,
|
||||||
setCurInfo,
|
setCurInfo,
|
||||||
setCurFetched,
|
setCurFetched,
|
||||||
@@ -335,6 +340,12 @@ export const {
|
|||||||
setFold,
|
setFold,
|
||||||
setSearchText,
|
setSearchText,
|
||||||
setSearchResult,
|
setSearchResult,
|
||||||
|
setInputting,
|
||||||
|
addAskInfo,
|
||||||
|
delAskInfo,
|
||||||
|
mergeAskInfo,
|
||||||
|
setCtime,
|
||||||
|
setAuthor,
|
||||||
} = slice.actions
|
} = slice.actions
|
||||||
|
|
||||||
export default slice.reducer
|
export default slice.reducer
|
||||||
|
@@ -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,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
38
src/typings.d.ts
vendored
@@ -1,16 +1,22 @@
|
|||||||
|
interface MethodContext {
|
||||||
|
from: 'extension' | 'inject' | 'app'
|
||||||
|
event: any
|
||||||
|
tabId?: number
|
||||||
|
// sender?: chrome.runtime.MessageSender | null
|
||||||
|
}
|
||||||
|
|
||||||
interface EnvData {
|
interface EnvData {
|
||||||
|
sidePanel?: 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
|
||||||
@@ -40,10 +46,12 @@ interface TempData {
|
|||||||
curSummaryType: SummaryType
|
curSummaryType: SummaryType
|
||||||
downloadType?: string
|
downloadType?: string
|
||||||
compact?: boolean // 是否紧凑视图
|
compact?: boolean // 是否紧凑视图
|
||||||
|
reviewActions?: number // 点击或总结行为达到一定次数后,显示评分(一个视频最多只加1次)
|
||||||
|
reviewed?: boolean // 是否点击过评分,undefined: 不显示;true: 已点击;false: 未点击(需要显示)
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TaskDef {
|
interface TaskDef {
|
||||||
type: 'chatComplete' | 'geminiChatComplete'
|
type: 'chatComplete'
|
||||||
serverUrl?: string
|
serverUrl?: string
|
||||||
data: any
|
data: any
|
||||||
extra?: any
|
extra?: any
|
||||||
@@ -105,6 +113,17 @@ interface Summary {
|
|||||||
content?: any
|
content?: any
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface AskInfo {
|
||||||
|
id: string
|
||||||
|
fold?: boolean
|
||||||
|
question: string
|
||||||
|
status: SummaryStatus
|
||||||
|
error?: string
|
||||||
|
content?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type PartialOfAskInfo = Partial<PartOfAskInfo>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 概览
|
* 概览
|
||||||
*/
|
*/
|
||||||
@@ -129,4 +148,13 @@ interface BriefSummary extends Summary {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SummaryStatus = 'init' | 'pending' | 'done'
|
type SummaryStatus = 'init' | 'pending' | 'done'
|
||||||
type SummaryType = 'overview' | 'keypoint' | 'brief'
|
type SummaryType = 'overview' | 'keypoint' | 'brief' | 'question' | 'debate'
|
||||||
|
|
||||||
|
interface DebateMessage {
|
||||||
|
side: 'pro' | 'con'
|
||||||
|
content: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DebateProps {
|
||||||
|
messages: DebateMessage[]
|
||||||
|
}
|
||||||
|
@@ -1,43 +0,0 @@
|
|||||||
import {SyntheticEvent} from 'react'
|
|
||||||
|
|
||||||
export const formatTime = (time: number) => {
|
|
||||||
if (!time) return '00:00'
|
|
||||||
|
|
||||||
const minutes = Math.floor(time / 60)
|
|
||||||
const seconds = Math.floor(time % 60)
|
|
||||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param time 2.82
|
|
||||||
*/
|
|
||||||
export const formatSrtTime = (time: number) => {
|
|
||||||
if (!time) return '00:00:00,000'
|
|
||||||
|
|
||||||
const hours = Math.floor(time / 60 / 60)
|
|
||||||
const minutes = Math.floor(time / 60 % 60)
|
|
||||||
const seconds = Math.floor(time % 60)
|
|
||||||
const ms = Math.floor((time % 1) * 1000)
|
|
||||||
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')},${ms.toString().padStart(3, '0')}`
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param time 2.82
|
|
||||||
*/
|
|
||||||
export const formatVttTime = (time: number) => {
|
|
||||||
if (!time) return '00:00:00.000'
|
|
||||||
|
|
||||||
const hours = Math.floor(time / 60 / 60)
|
|
||||||
const minutes = Math.floor(time / 60 % 60)
|
|
||||||
const seconds = Math.floor(time % 60)
|
|
||||||
const ms = Math.floor((time % 1) * 1000)
|
|
||||||
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`
|
|
||||||
}
|
|
||||||
|
|
||||||
export const preventFunc = (e: SyntheticEvent) => {
|
|
||||||
e.preventDefault()
|
|
||||||
}
|
|
||||||
|
|
||||||
export const stopPopFunc = (e: SyntheticEvent) => {
|
|
||||||
e.stopPropagation()
|
|
||||||
}
|
|
@@ -1,8 +1,10 @@
|
|||||||
import devData from '../data/data.json'
|
import {APP_DOM_ID, CUSTOM_MODEL_TOKENS, MODEL_DEFAULT, MODEL_MAP, SUMMARIZE_TYPES} from '../consts/const'
|
||||||
import {APP_DOM_ID, CUSTOM_MODEL_TOKENS, MODEL_DEFAULT, MODEL_MAP, SUMMARIZE_TYPES} from '../const'
|
|
||||||
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[]) => {
|
||||||
|
console.debug('[APP]', ...args)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取译文
|
* 获取译文
|
||||||
@@ -66,18 +68,6 @@ export const getTimeDisplay = (seconds: number) => {
|
|||||||
return `${h < 10 ? '0' : ''}${h}:${m < 10 ? '0' : ''}${m}:${s < 10 ? '0' : ''}${s}`
|
return `${h < 10 ? '0' : ''}${h}:${m < 10 ? '0' : ''}${m}:${s < 10 ? '0' : ''}${s}`
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getDevData = () => {
|
|
||||||
// add idx
|
|
||||||
const body = devData.body.map((item, idx) => ({
|
|
||||||
...item,
|
|
||||||
idx,
|
|
||||||
}))
|
|
||||||
return {
|
|
||||||
...devData,
|
|
||||||
body,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const isSummaryEmpty = (summary: Summary) => {
|
export const isSummaryEmpty = (summary: Summary) => {
|
||||||
if (summary.type === 'overview') {
|
if (summary.type === 'overview') {
|
||||||
const content: OverviewItem[] = summary.content??[]
|
const content: OverviewItem[] = summary.content??[]
|
||||||
@@ -88,6 +78,12 @@ export const isSummaryEmpty = (summary: Summary) => {
|
|||||||
} else if (summary.type === 'brief') {
|
} else if (summary.type === 'brief') {
|
||||||
const content: string[] = summary.content??''
|
const content: string[] = summary.content??''
|
||||||
return content.length === 0
|
return content.length === 0
|
||||||
|
} else if (summary.type === 'question') {
|
||||||
|
const content: any[] = summary.content??[]
|
||||||
|
return content.length === 0
|
||||||
|
} else if (summary.type === 'debate') {
|
||||||
|
const content: Array<{ side: string, content: string }> = summary.content ?? []
|
||||||
|
return content.length === 0
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -109,6 +105,16 @@ export const getSummaryStr = (summary: Summary) => {
|
|||||||
summary: ''
|
summary: ''
|
||||||
}
|
}
|
||||||
s += content.summary + '\n'
|
s += content.summary + '\n'
|
||||||
|
} else if (summary.type === 'question') {
|
||||||
|
const content: Array<{ q: string, a: string }> = summary.content ?? []
|
||||||
|
s += content.map(item => {
|
||||||
|
return item.q + '\n' + item.a + '\n'
|
||||||
|
}).join('\n')
|
||||||
|
} else if (summary.type === 'debate') {
|
||||||
|
const content: Array<{ side: string, content: string }> = summary.content ?? []
|
||||||
|
s += content.map(item => {
|
||||||
|
return (item.side === 'pro'?'正方:':'反方:') + item.content + '\n'
|
||||||
|
}).join('\n')
|
||||||
}
|
}
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
@@ -189,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'
|
7
src/utils/chromeUtils.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
export const openOptionsPage = () => {
|
||||||
|
if (chrome.runtime.openOptionsPage) {
|
||||||
|
chrome.runtime.openOptionsPage()
|
||||||
|
} else {
|
||||||
|
window.open(chrome.runtime.getURL('options.html'))
|
||||||
|
}
|
||||||
|
}
|
@@ -1,6 +1,6 @@
|
|||||||
import * as JsSearch from 'js-search'
|
import * as JsSearch from 'js-search'
|
||||||
import {uniq} from 'lodash-es'
|
import {uniq} from 'lodash-es'
|
||||||
import {getWords, getWordsPinyin} from './pinyin_util'
|
import {getWords, getWordsPinyin} from './pinyinUtil'
|
||||||
|
|
||||||
const tokenize = (maxLength: number, content: string, options?: SearchOptions) => {
|
const tokenize = (maxLength: number, content: string, options?: SearchOptions) => {
|
||||||
const result: string[] = []
|
const result: string[] = []
|
75
src/utils/util.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import {SyntheticEvent} from 'react'
|
||||||
|
|
||||||
|
export const isEdgeBrowser = () => {
|
||||||
|
const userAgent = navigator.userAgent.toLowerCase()
|
||||||
|
return userAgent.includes('edg/') && !userAgent.includes('edge/')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将总秒数格式化为 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 totalSeconds = Math.floor(time);
|
||||||
|
|
||||||
|
// 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
|
||||||
|
*/
|
||||||
|
export const formatSrtTime = (time: number) => {
|
||||||
|
if (!time) return '00:00:00,000'
|
||||||
|
|
||||||
|
const hours = Math.floor(time / 60 / 60)
|
||||||
|
const minutes = Math.floor(time / 60 % 60)
|
||||||
|
const seconds = Math.floor(time % 60)
|
||||||
|
const ms = Math.floor((time % 1) * 1000)
|
||||||
|
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')},${ms.toString().padStart(3, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param time 2.82
|
||||||
|
*/
|
||||||
|
export const formatVttTime = (time: number) => {
|
||||||
|
if (!time) return '00:00:00.000'
|
||||||
|
|
||||||
|
const hours = Math.floor(time / 60 / 60)
|
||||||
|
const minutes = Math.floor(time / 60 % 60)
|
||||||
|
const seconds = Math.floor(time % 60)
|
||||||
|
const ms = Math.floor((time % 1) * 1000)
|
||||||
|
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const preventFunc = (e: SyntheticEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const stopPopFunc = (e: SyntheticEvent) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
}
|
@@ -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'),
|
||||||
|
@@ -17,7 +17,10 @@
|
|||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
"types": [
|
"types": [
|
||||||
"@types/chrome"
|
"@types/chrome"
|
||||||
]
|
],
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"include": ["src"],
|
"include": ["src"],
|
||||||
"references": [{ "path": "./tsconfig.node.json" }]
|
"references": [{ "path": "./tsconfig.node.json" }]
|
||||||
|
@@ -6,5 +6,5 @@
|
|||||||
"allowSyntheticDefaultImports": true,
|
"allowSyntheticDefaultImports": true,
|
||||||
"resolveJsonModule": true
|
"resolveJsonModule": true
|
||||||
},
|
},
|
||||||
"include": ["vite.config.ts", "manifest.json"]
|
"include": ["vite.config.ts", "manifest.config.ts"]
|
||||||
}
|
}
|
||||||
|
@@ -2,24 +2,33 @@ import {defineConfig, PluginOption} from 'vite'
|
|||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
import {visualizer} from "rollup-plugin-visualizer";
|
import {visualizer} from "rollup-plugin-visualizer";
|
||||||
import {crx} from '@crxjs/vite-plugin'
|
import {crx} from '@crxjs/vite-plugin'
|
||||||
|
import path from "path"
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import manifest from './manifest.json'
|
import manifest from './manifest.config'
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default ({mode}) => {
|
export default () => {
|
||||||
const plugins = [
|
|
||||||
react(),
|
|
||||||
visualizer() as PluginOption,
|
|
||||||
]
|
|
||||||
// @ts-ignore
|
|
||||||
if (mode === 'production_chrome') {
|
|
||||||
plugins.push(crx({
|
|
||||||
manifest,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
return defineConfig({
|
return defineConfig({
|
||||||
base: '/',
|
base: '/',
|
||||||
plugins,
|
build: {
|
||||||
|
rollupOptions: {
|
||||||
|
input: {
|
||||||
|
index: 'index.html',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': path.resolve(__dirname, './src'),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
plugins: [
|
||||||
|
react(),
|
||||||
|
crx({
|
||||||
|
manifest,
|
||||||
|
}),
|
||||||
|
visualizer() as PluginOption,
|
||||||
|
],
|
||||||
css: {
|
css: {
|
||||||
modules: {
|
modules: {
|
||||||
localsConvention: "camelCase"
|
localsConvention: "camelCase"
|
||||||
|
@@ -1,66 +0,0 @@
|
|||||||
// vite.config.ts
|
|
||||||
import { defineConfig } from "vite";
|
|
||||||
import react from "@vitejs/plugin-react";
|
|
||||||
import { visualizer } from "rollup-plugin-visualizer";
|
|
||||||
import { crx } from "@crxjs/vite-plugin";
|
|
||||||
|
|
||||||
// manifest.json
|
|
||||||
var manifest_default = {
|
|
||||||
name: "\u54D4\u54E9\u54D4\u54E9\u5B57\u5E55\u5217\u8868",
|
|
||||||
description: "\u663E\u793AB\u7AD9\u89C6\u9891\u7684\u5B57\u5E55\u5217\u8868,\u53EF\u70B9\u51FB\u8DF3\u8F6C\u4E0E\u4E0B\u8F7D\u5B57\u5E55,\u5E76\u652F\u6301\u7FFB\u8BD1\u548C\u603B\u7ED3\u5B57\u5E55!",
|
|
||||||
version: "1.7.11",
|
|
||||||
manifest_version: 3,
|
|
||||||
permissions: [
|
|
||||||
"storage"
|
|
||||||
],
|
|
||||||
background: {
|
|
||||||
service_worker: "src/chrome/background.ts"
|
|
||||||
},
|
|
||||||
content_scripts: [
|
|
||||||
{
|
|
||||||
matches: ["https://www.bilibili.com/video/*", "https://www.bilibili.com/list/*"],
|
|
||||||
js: ["src/chrome/content-script.cjs"]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
icons: {
|
|
||||||
"16": "favicon-16x16.png",
|
|
||||||
"32": "favicon-32x32.png",
|
|
||||||
"48": "favicon-48x48.png",
|
|
||||||
"128": "favicon-128x128.png"
|
|
||||||
},
|
|
||||||
action: {
|
|
||||||
default_popup: "index.html",
|
|
||||||
default_icon: {
|
|
||||||
"16": "favicon-16x16.png",
|
|
||||||
"32": "favicon-32x32.png",
|
|
||||||
"48": "favicon-48x48.png",
|
|
||||||
"128": "favicon-128x128.png"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// vite.config.ts
|
|
||||||
var vite_config_default = ({ mode }) => {
|
|
||||||
const plugins = [
|
|
||||||
react(),
|
|
||||||
visualizer()
|
|
||||||
];
|
|
||||||
if (mode === "production_chrome") {
|
|
||||||
plugins.push(crx({
|
|
||||||
manifest: manifest_default
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
return defineConfig({
|
|
||||||
base: "/",
|
|
||||||
plugins,
|
|
||||||
css: {
|
|
||||||
modules: {
|
|
||||||
localsConvention: "camelCase"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
export {
|
|
||||||
vite_config_default as default
|
|
||||||
};
|
|
||||||
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvZmVuZ3l1ZXhpYW5nL2RhdGEvcHJvamVjdC9iaWxpYmlsaS1zdWJ0aXRsZVwiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9maWxlbmFtZSA9IFwiL1VzZXJzL2Zlbmd5dWV4aWFuZy9kYXRhL3Byb2plY3QvYmlsaWJpbGktc3VidGl0bGUvdml0ZS5jb25maWcudHNcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfaW1wb3J0X21ldGFfdXJsID0gXCJmaWxlOi8vL1VzZXJzL2Zlbmd5dWV4aWFuZy9kYXRhL3Byb2plY3QvYmlsaWJpbGktc3VidGl0bGUvdml0ZS5jb25maWcudHNcIjtpbXBvcnQge2RlZmluZUNvbmZpZywgUGx1Z2luT3B0aW9ufSBmcm9tICd2aXRlJ1xuaW1wb3J0IHJlYWN0IGZyb20gJ0B2aXRlanMvcGx1Z2luLXJlYWN0J1xuaW1wb3J0IHt2aXN1YWxpemVyfSBmcm9tIFwicm9sbHVwLXBsdWdpbi12aXN1YWxpemVyXCI7XG5pbXBvcnQge2NyeH0gZnJvbSAnQGNyeGpzL3ZpdGUtcGx1Z2luJ1xuLy8gQHRzLWlnbm9yZVxuaW1wb3J0IG1hbmlmZXN0IGZyb20gJy4vbWFuaWZlc3QuanNvbidcblxuLy8gaHR0cHM6Ly92aXRlanMuZGV2L2NvbmZpZy9cbmV4cG9ydCBkZWZhdWx0ICh7bW9kZX0pID0+IHtcbiAgY29uc3QgcGx1Z2lucyA9IFtcbiAgICByZWFjdCgpLFxuICAgIHZpc3VhbGl6ZXIoKSBhcyBQbHVnaW5PcHRpb24sXG4gIF1cbiAgLy8gQHRzLWlnbm9yZVxuICBpZiAobW9kZSA9PT0gJ3Byb2R1Y3Rpb25fY2hyb21lJykge1xuICAgIHBsdWdpbnMucHVzaChjcngoe1xuICAgICAgbWFuaWZlc3QsXG4gICAgfSkpXG4gIH1cbiAgcmV0dXJuIGRlZmluZUNvbmZpZyh7XG4gICAgYmFzZTogJy8nLFxuICAgIHBsdWdpbnMsXG4gICAgY3NzOiB7XG4gICAgICBtb2R1bGVzOiB7XG4gICAgICAgIGxvY2Fsc0NvbnZlbnRpb246IFwiY2FtZWxDYXNlXCJcbiAgICAgIH1cbiAgICB9XG4gIH0pXG59XG4iXSwKICAibWFwcGluZ3MiOiAiO0FBQXdVLFNBQVEsb0JBQWlDO0FBQ2pYLE9BQU8sV0FBVztBQUNsQixTQUFRLGtCQUFpQjtBQUN6QixTQUFRLFdBQVU7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBS2xCLElBQU8sc0JBQVEsQ0FBQyxFQUFDLEtBQUksTUFBTTtBQUN6QixRQUFNLFVBQVU7QUFBQSxJQUNkLE1BQU07QUFBQSxJQUNOLFdBQVc7QUFBQSxFQUNiO0FBRUEsTUFBSSxTQUFTLHFCQUFxQjtBQUNoQyxZQUFRLEtBQUssSUFBSTtBQUFBLE1BQ2Y7QUFBQSxJQUNGLENBQUMsQ0FBQztBQUFBLEVBQ0o7QUFDQSxTQUFPLGFBQWE7QUFBQSxJQUNsQixNQUFNO0FBQUEsSUFDTjtBQUFBLElBQ0EsS0FBSztBQUFBLE1BQ0gsU0FBUztBQUFBLFFBQ1Asa0JBQWtCO0FBQUEsTUFDcEI7QUFBQSxJQUNGO0FBQUEsRUFDRixDQUFDO0FBQ0g7IiwKICAibmFtZXMiOiBbXQp9Cg==
|
|