Compare commits
136 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
194df8525c | ||
![]() |
28bb3dbb96 | ||
![]() |
640f6d89fd | ||
![]() |
338e3145f2 | ||
![]() |
e2121e83bd | ||
![]() |
7583b05289 | ||
![]() |
ae60303a15 | ||
![]() |
5bcedf0c9d | ||
![]() |
d4e5e407a4 | ||
![]() |
ce2a2da6f5 | ||
![]() |
368f5d721c | ||
![]() |
21e2ca958c | ||
![]() |
149653ffac | ||
![]() |
f977b5e238 | ||
![]() |
c13ef4597b | ||
![]() |
65026f62af | ||
![]() |
bcff8b4f90 | ||
![]() |
ee1eaf9e08 | ||
![]() |
cc732de8e6 | ||
![]() |
cccf7e6149 | ||
![]() |
30dc724ebb | ||
![]() |
51a7e998b9 | ||
![]() |
556ccef4b2 | ||
![]() |
42b719fb98 | ||
![]() |
fa66445466 | ||
![]() |
d711b2abf8 | ||
![]() |
47fcb1de11 | ||
![]() |
be3d3624bc | ||
![]() |
910b1ce6d9 | ||
![]() |
0a6bda667e | ||
![]() |
5a0a123af9 | ||
![]() |
b481b8a55a | ||
![]() |
3cede8650d | ||
![]() |
69e0497081 | ||
![]() |
8776186486 | ||
![]() |
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
|
||||
|
||||
VITE_ENV=chrome
|
||||
VITE_ENV=chrome
|
@@ -4,3 +4,4 @@ node_modules/
|
||||
postcss.config.cjs
|
||||
vite.config.ts
|
||||
vite-env.d.ts
|
||||
manifest.config.ts
|
@@ -25,9 +25,12 @@ module.exports = {
|
||||
"@typescript-eslint/no-empty-interface": "warn",
|
||||
"@typescript-eslint/no-unused-vars": "warn",
|
||||
"@typescript-eslint/strict-boolean-expressions": "warn",
|
||||
"@typescript-eslint/prefer-nullish-coalescing": "off",
|
||||
"@typescript-eslint/no-non-null-assertion": "warn",
|
||||
"@typescript-eslint/object-curly-spacing": "off",
|
||||
"@typescript-eslint/no-misused-promises": "off",
|
||||
"@typescript-eslint/space-infix-ops": "off",
|
||||
"@typescript-eslint/no-floating-promises": "off",
|
||||
"operator-linebreak": "off",
|
||||
"@typescript-eslint/space-before-function-paren": "off",
|
||||
"@typescript-eslint/comma-dangle": "off"
|
||||
|
28
README.md
@@ -21,20 +21,20 @@
|
||||
|
||||
- [chrome商店](https://chrome.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp)
|
||||
- [edge商店](https://microsoftedge.microsoft.com/addons/detail/lignnlhlpiefmcjkdkmfjdckhlaiajan)
|
||||
- [firefox商店](https://addons.mozilla.org/zh-CN/firefox/addon/bilibili-subtitle)
|
||||
|
||||
## 使用说明
|
||||
|
||||
安装扩展后,在哔哩哔哩网站观看视频时,视频右侧会显示字幕列表面板。
|
||||
|
||||
### 使用本地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)
|
||||
|
||||
## 问题反馈
|
||||
@@ -45,8 +45,14 @@ github: [IndieKKY](https://github.com/IndieKKY)
|
||||
node版本:18.15.0
|
||||
包管理器:pnpm
|
||||
|
||||
本地开发时,`pnpm run dev`可以开启本地调试,但只能调试部分功能;
|
||||
`pnpm run build_chrome`可以构建项目,然后浏览器扩展中加载`dist`目录即可,此方式可以调试完整功能,但不是很方便,从改代码到构建完看到效果耗时比较长(取决于你的电脑性能)。
|
||||
- 本地调试:`pnpm run dev`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
|
||||
- 打生产包:`pnpm run build`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
|
||||
|
||||
注:`./push.sh`是作者自用脚本,可以忽略。
|
||||
|
||||
提示:最新版浏览器安全方面有更新,开发调试可能有问题,会报csp错误!
|
||||
暂时的解决办法是`pnpm run dev`运行起来后,手动将`dist/manifest.json`文件里的web_accessible_resources里的use_dynamic_url都修改为false,然后浏览器扩展管理页面点击重载一下,就能正常(是@crxjs/vite-plugin依赖的问题,这个依赖很长时间没更新了,这个bug也没修复,暂时没发现更好的解决办法)。
|
||||
构建后正常,关键是fix.cjs里将use_dynamic_url设置为false的这个操作。
|
||||
|
||||
## 贡献指南
|
||||
|
||||
@@ -62,7 +68,3 @@ node版本:18.15.0
|
||||
## 许可证
|
||||
|
||||
该项目采用 **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>
|
||||
<html lang="zh" data-theme="light">
|
||||
<head>
|
||||
<title>bilibili-subtitle - 哔哩哔哩字幕</title>
|
||||
<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">
|
||||
@@ -11,6 +11,6 @@
|
||||
<meta name="keywords" content="哔哩哔哩,b站,字幕" />
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
<script type="module" src="/src/Main.tsx"></script>
|
||||
</body>
|
||||
</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,
|
||||
"name": "bilibili-subtitle",
|
||||
"version": "1.9.2",
|
||||
"version": "1.12.1",
|
||||
"type": "module",
|
||||
"description": "哔哩哔哩字幕列表",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build -m production_chrome",
|
||||
"build_chrome": "pnpm run build && node fixChrome.cjs",
|
||||
"build_firefox": "pnpm run build && node fixFirefox.cjs",
|
||||
"build": "tsc && vite build && node fix.cjs",
|
||||
"fix": "eslint --fix --quiet ."
|
||||
},
|
||||
"author": "IndieKKY",
|
||||
@@ -17,8 +15,9 @@
|
||||
"dependencies": {
|
||||
"@crxjs/vite-plugin": "^1.0.14",
|
||||
"@kky002/kky-hooks": "^1.2.1",
|
||||
"@kky002/kky-message": "^0.2.1",
|
||||
"@kky002/kky-ui": "^1.0.9",
|
||||
"@kky002/kky-util": "^1.4.2",
|
||||
"@kky002/kky-util": "^1.13.13",
|
||||
"@logto/react": "1.0.0-beta.13",
|
||||
"@popperjs/core": "^2.11.6",
|
||||
"@reduxjs/toolkit": "^1.8.5",
|
||||
@@ -26,6 +25,7 @@
|
||||
"ahooks": "^3.7.1",
|
||||
"classnames": "^2.3.2",
|
||||
"daisyui": "^2.42.1",
|
||||
"dayjs": "^1.11.13",
|
||||
"js-search": "^2.0.0",
|
||||
"less": "^4.1.3",
|
||||
"lodash-es": "^4.17.21",
|
||||
@@ -48,9 +48,10 @@
|
||||
"devDependencies": {
|
||||
"@tailwindcss/line-clamp": "^0.4.2",
|
||||
"@tailwindcss/typography": "^0.5.8",
|
||||
"@types/chrome": "^0.0.203",
|
||||
"@types/chrome": "^0.0.277",
|
||||
"@types/js-search": "^1.4.0",
|
||||
"@types/lodash-es": "^4.17.6",
|
||||
"@types/node": "^20.8.10",
|
||||
"@types/pako": "^2.0.0",
|
||||
"@types/qs": "^6.9.7",
|
||||
"@types/react": "^18.0.20",
|
||||
@@ -59,7 +60,7 @@
|
||||
"@types/uuid": "^8.3.4",
|
||||
"@typescript-eslint/eslint-plugin": "^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",
|
||||
"eslint": "8.22.0",
|
||||
"eslint-config-standard": "^17.0.0",
|
||||
@@ -73,6 +74,6 @@
|
||||
"rollup-plugin-visualizer": "^5.8.3",
|
||||
"tailwindcss": "^3.2.4",
|
||||
"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
|
||||
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"
|
||||
|
||||
# build
|
||||
pnpm run build_chrome
|
||||
pnpm run build
|
||||
# zip dist
|
||||
rm -f dist.zip
|
||||
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 {useAppDispatch, useAppSelector} from './hooks/redux'
|
||||
import {setEnvData, setEnvReady, setFold, setPage, setTempData, setTempReady} from './redux/envReducer'
|
||||
import Header from './biz/Header'
|
||||
import Body from './biz/Body'
|
||||
import useSubtitleService from './hooks/useSubtitleService'
|
||||
import {setEnvData, setEnvReady, setTempData, setTempReady} from './redux/envReducer'
|
||||
import {cloneDeep} from 'lodash-es'
|
||||
import {EVENT_EXPAND, PAGE_MAIN, PAGE_SETTINGS, STORAGE_ENV, STORAGE_TEMP} from './const'
|
||||
import {EventBusContext} from './Router'
|
||||
import useTranslateService from './hooks/useTranslateService'
|
||||
import Settings from './biz/Settings'
|
||||
import classNames from 'classnames'
|
||||
import {STORAGE_ENV, STORAGE_TEMP} from './consts/const'
|
||||
import OptionsPage from './pages/OptionsPage'
|
||||
import {handleJson} from '@kky002/kky-util'
|
||||
import {useLocalStorage} from '@kky002/kky-hooks'
|
||||
import {Toaster} from 'react-hot-toast'
|
||||
import {setTheme} from './util/biz_util'
|
||||
import useSearchService from './hooks/useSearchService'
|
||||
import useMessageService from './hooks/useMessageService'
|
||||
import MainPage from './pages/MainPage'
|
||||
|
||||
function App() {
|
||||
const dispatch = useAppDispatch()
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
const tempData = useAppSelector(state => state.env.tempData)
|
||||
const fold = useAppSelector(state => state.env.fold)
|
||||
const eventBus = useContext(EventBusContext)
|
||||
const page = useAppSelector(state => state.env.page)
|
||||
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()
|
||||
}
|
||||
}
|
||||
})
|
||||
const path = useAppSelector(state => state.env.path)
|
||||
const envReady = useAppSelector(state => state.env.envReady)
|
||||
const tempReady = useAppSelector(state => state.env.tempReady)
|
||||
|
||||
// env数据
|
||||
const savedEnvData = useMemo(() => {
|
||||
@@ -65,23 +43,13 @@ function App() {
|
||||
}, [dispatch])
|
||||
useLocalStorage<TempData>('chrome_client', STORAGE_TEMP, savedTempData, onLoadTemp)
|
||||
|
||||
// theme改变时,设置主题
|
||||
useEffect(() => {
|
||||
setTheme(envData.theme)
|
||||
}, [envData.theme])
|
||||
|
||||
// services
|
||||
useSubtitleService()
|
||||
useTranslateService()
|
||||
useSearchService()
|
||||
useMessageService()
|
||||
|
||||
return <div className={classNames('select-none', import.meta.env.VITE_ENV === 'web-dev'?'w-[350px]':'w-full')} style={{
|
||||
height: fold?undefined:`${totalHeight}px`,
|
||||
}}>
|
||||
<Header foldCallback={foldCallback}/>
|
||||
{!fold && page === PAGE_MAIN && <Body/>}
|
||||
{!fold && page === PAGE_SETTINGS && <Settings/>}
|
||||
<Toaster position='bottom-center'/>
|
||||
return <div>
|
||||
<Toaster position={path === 'app'?'bottom-center':'top-center'}/>
|
||||
{path === 'app' && <MainPage/>}
|
||||
{path === 'options' && envReady && tempReady && <OptionsPage/>}
|
||||
</div>
|
||||
}
|
||||
|
||||
|
@@ -1,15 +1,20 @@
|
||||
import App from './App'
|
||||
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)
|
||||
|
||||
const map: { [key: string]: string } = {
|
||||
'/options.html': 'options',
|
||||
'/sidepanel.html': 'app',
|
||||
// '/close': 'close',
|
||||
}
|
||||
|
||||
const Router = () => {
|
||||
const path = map[window.location.pathname] ?? 'app'
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
if (path === 'close') {
|
||||
window.close()
|
||||
@@ -18,8 +23,12 @@ const Router = () => {
|
||||
// 事件总线
|
||||
const eventBus = useEventEmitter()
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(setPath(path as 'app' | 'options'))
|
||||
}, [dispatch, path])
|
||||
|
||||
return <EventBusContext.Provider value={eventBus}>
|
||||
{path === 'app' && <App/>}
|
||||
{(path === 'app' || path === 'options') && <App/>}
|
||||
</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 {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'
|
||||
|
||||
/**
|
||||
* 消息处理入口
|
||||
* 注意:需要异步sendResponse时返回true
|
||||
*/
|
||||
chrome.runtime.onMessage.addListener((event, sender, sendResponse) => {
|
||||
console.debug('收到请求: ', event)
|
||||
if (event.type === 'p') { // 发出http请求
|
||||
const {url, options} = event
|
||||
// 发出请求
|
||||
fetch('http://localhost:27081/oproxy/p', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
url,
|
||||
options,
|
||||
}),
|
||||
}).then(async res => await res.json()).then(sendResponse).catch(console.error)
|
||||
return true
|
||||
} else 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)
|
||||
} else if (event.type === 'addTask') {
|
||||
const setBadgeOk = async (tabId: number, ok: boolean) => {
|
||||
await chrome.action.setBadgeText({
|
||||
text: ok ? '✓' : '',
|
||||
tabId,
|
||||
})
|
||||
await chrome.action.setBadgeBackgroundColor({
|
||||
color: '#3245e8',
|
||||
tabId,
|
||||
})
|
||||
await chrome.action.setBadgeTextColor({
|
||||
color: '#ffffff',
|
||||
tabId,
|
||||
})
|
||||
}
|
||||
|
||||
const closeSidePanel = async () => {
|
||||
chrome.sidePanel.setOptions({
|
||||
enabled: false,
|
||||
})
|
||||
chrome.sidePanel.setPanelBehavior({
|
||||
openPanelOnActionClick: false,
|
||||
})
|
||||
}
|
||||
|
||||
const methods: {
|
||||
[K in AllExtensionMessages['method']]: (params: Extract<AllExtensionMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
|
||||
} = {
|
||||
CLOSE_SIDE_PANEL: async (params, context) => {
|
||||
closeSidePanel()
|
||||
},
|
||||
GET_TAB_ID: async (params, context) => {
|
||||
return context.tabId
|
||||
},
|
||||
ADD_TASK: async (params, context) => {
|
||||
// 新建任务
|
||||
const task: Task = {
|
||||
id: v4(),
|
||||
startTime: Date.now(),
|
||||
status: 'pending',
|
||||
def: event.taskDef,
|
||||
def: params.taskDef,
|
||||
}
|
||||
tasksMap.set(task.id, task)
|
||||
|
||||
// 立即触发任务
|
||||
handleTask(task).catch(console.error)
|
||||
|
||||
return task
|
||||
},
|
||||
GET_TASK: async (params, context) => {
|
||||
// 返回任务信息
|
||||
sendResponse(task)
|
||||
} else if (event.type === 'getTask') {
|
||||
// 返回任务信息
|
||||
const taskId = event.taskId
|
||||
const taskId = params.taskId
|
||||
const task = tasksMap.get(taskId)
|
||||
if (task == null) {
|
||||
sendResponse({
|
||||
return {
|
||||
code: 'not_found',
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 检测删除缓存
|
||||
@@ -62,11 +68,57 @@ chrome.runtime.onMessage.addListener((event, sender, sendResponse) => {
|
||||
}
|
||||
|
||||
// 返回任务
|
||||
sendResponse({
|
||||
return {
|
||||
code: 'ok',
|
||||
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()
|
||||
|
@@ -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) => {
|
||||
if (!serverUrl) {
|
||||
@@ -7,13 +7,17 @@ const getServerUrl = (serverUrl?: string) => {
|
||||
if (serverUrl.endsWith('/')) {
|
||||
serverUrl = serverUrl.slice(0, -1)
|
||||
}
|
||||
//如果serverUrl不以/vxxx结尾,则添加/v1
|
||||
if (!/\/v\d+$/.test(serverUrl.toLowerCase())) {
|
||||
serverUrl += '/v1'
|
||||
}
|
||||
return serverUrl
|
||||
}
|
||||
|
||||
export const handleChatCompleteTask = async (task: Task) => {
|
||||
const data = task.def.data
|
||||
const serverUrl = getServerUrl(task.def.serverUrl)
|
||||
const resp = await fetch(`${serverUrl}/v1/chat/completions`, {
|
||||
const resp = await fetch(`${serverUrl}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import {TASK_EXPIRE_TIME} from '../const'
|
||||
import {TASK_EXPIRE_TIME} from '../consts/const'
|
||||
import {handleChatCompleteTask, handleGeminiChatCompleteTask} from './openaiService'
|
||||
|
||||
export const tasksMap = new Map<string, Task>()
|
||||
|
27
src/components/ApiKeyReminder.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import React from 'react'
|
||||
import { useAppSelector } from '../hooks/redux'
|
||||
import { openOptionsPage } from '../utils/chromeUtils'
|
||||
|
||||
const ApiKeyReminder: React.FC = () => {
|
||||
const apiKey = useAppSelector(state => state.env.envData.apiKey)
|
||||
const geminiApiKey = useAppSelector(state => state.env.envData.geminiApiKey)
|
||||
const aiType = useAppSelector(state => state.env.envData.aiType)
|
||||
|
||||
if ((aiType === 'gemini' && geminiApiKey) || (aiType !== 'gemini' && 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.aiType === 'gemini'?envData.geminiApiKey: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.aiType, envData.apiKey, envData.geminiApiKey, 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.aiType === 'gemini' ? envData.geminiApiKey : 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.aiType, envData.apiKey, envData.geminiApiKey, 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.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey
|
||||
if (apiKey) {
|
||||
dispatch(setAutoTranslate(!autoTranslate))
|
||||
} else {
|
||||
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) {
|
||||
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.aiType, envData.apiKey, envData.askEnabled, envData.geminiApiKey, 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 {useAppSelector} from '../hooks/redux'
|
||||
import {getDisplay, getTransText} from '../util/biz_util'
|
||||
import {getDisplay, getTransText} from '../utils/bizUtil'
|
||||
import classNames from 'classnames'
|
||||
|
||||
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 MoreBtn from './MoreBtn'
|
||||
import classNames from 'classnames'
|
||||
import {parseTranscript} from '../util/biz_util'
|
||||
import {parseTranscript} from '../utils/bizUtil'
|
||||
|
||||
const Header = (props: {
|
||||
foldCallback: () => void
|
||||
@@ -16,6 +16,7 @@ const Header = (props: {
|
||||
const curInfo = useAppSelector(state => state.env.curInfo)
|
||||
const fold = useAppSelector(state => state.env.fold)
|
||||
const uploadedTranscript = useAppSelector(state => state.env.uploadedTranscript)
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
|
||||
const upload = useCallback(() => {
|
||||
const input = document.createElement('input')
|
||||
@@ -76,8 +77,13 @@ const Header = (props: {
|
||||
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'>
|
||||
{/* <img src="bibijun.png" alt="Logo" className="w-auto h-6 ml-2 mr-1" /> */}
|
||||
<span className='shrink-0 text-[15px] font-medium pl-[16px] pr-[14px]'>字幕列表</span>
|
||||
<MoreBtn placement={'right-start'}/>
|
||||
</div>
|
||||
@@ -91,7 +97,7 @@ const Header = (props: {
|
||||
{infos?.map((item: any) => <option key={item.id} value={item.subtitle_url}>{item.lan_doc}</option>)}
|
||||
<option key='upload' value='upload'>上传(vtt/srt)</option>
|
||||
</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>
|
||||
}
|
@@ -1,8 +1,6 @@
|
||||
import React, {MouseEvent, useCallback, useContext, useRef, useState} from 'react'
|
||||
import {MouseEvent, useCallback, useContext, useRef, useState} from 'react'
|
||||
import {useClickAway} from 'ahooks'
|
||||
import {
|
||||
AiFillWechat,
|
||||
BsFillChatDotsFill,
|
||||
FiMoreVertical,
|
||||
ImDownload3,
|
||||
IoMdSettings,
|
||||
@@ -11,13 +9,15 @@ import {
|
||||
import Popover from '../components/Popover'
|
||||
import {Placement} from '@popperjs/core/lib/enums'
|
||||
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||
import {setEnvData, setPage, setTempData} from '../redux/envReducer'
|
||||
import {setEnvData, setTempData} from '../redux/envReducer'
|
||||
import {EventBusContext} from '../Router'
|
||||
import {EVENT_EXPAND, PAGE_SETTINGS} from '../const'
|
||||
import {formatSrtTime, formatTime, formatVttTime} from '../util/util'
|
||||
import {EVENT_EXPAND} from '../consts/const'
|
||||
import {formatSrtTime, formatTime, formatVttTime} from '../utils/util'
|
||||
import {downloadText, openUrl} from '@kky002/kky-util'
|
||||
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 {
|
||||
placement: Placement
|
||||
@@ -68,33 +68,39 @@ const MoreBtn = (props: Props) => {
|
||||
const segments = useAppSelector(state => state.env.segments)
|
||||
const url = useAppSelector(state => state.env.url)
|
||||
const title = useAppSelector(state => state.env.title)
|
||||
const ctime = useAppSelector(state => state.env.ctime) // 时间戳,单位s
|
||||
const author = useAppSelector(state => state.env.author)
|
||||
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
|
||||
|
||||
const {sendInject} = useMessage(!!envData.sidePanel)
|
||||
|
||||
const downloadCallback = useCallback((download: boolean) => {
|
||||
if (data == null) {
|
||||
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') {
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
|
||||
for (const item of data.body) {
|
||||
s += item.content + '\n'
|
||||
}
|
||||
fileName = 'download.txt'
|
||||
suffix = 'txt'
|
||||
} else if (downloadType === 'textWithTime') {
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
|
||||
for (const item of data.body) {
|
||||
s += formatTime(item.from) + ' ' + item.content + '\n'
|
||||
}
|
||||
fileName = 'download.txt'
|
||||
suffix = 'txt'
|
||||
} else if (downloadType === 'article') {
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
|
||||
for (const item of data.body) {
|
||||
s += item.content + ', '
|
||||
}
|
||||
s = s.substring(0, s.length - 1) // remove last ','
|
||||
fileName = 'download.txt'
|
||||
suffix = 'txt'
|
||||
} else if (downloadType === 'srt') {
|
||||
/**
|
||||
* 1
|
||||
@@ -113,7 +119,7 @@ const MoreBtn = (props: Props) => {
|
||||
s += ss
|
||||
}
|
||||
s = s.substring(0, s.length - 1)// remove last '\n'
|
||||
fileName = 'download.srt'
|
||||
suffix = 'srt'
|
||||
} else if (downloadType === 'vtt') {
|
||||
/**
|
||||
* WEBVTT title
|
||||
@@ -134,34 +140,33 @@ const MoreBtn = (props: Props) => {
|
||||
s += ss
|
||||
}
|
||||
s = s.substring(0, s.length - 1)// remove last '\n'
|
||||
fileName = 'download.vtt'
|
||||
suffix = 'vtt'
|
||||
} else if (downloadType === 'json') {
|
||||
s = JSON.stringify(data)
|
||||
fileName = 'download.json'
|
||||
suffix = 'json'
|
||||
} else if (downloadType === 'summarize') {
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n\n`
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
|
||||
const [success, content] = getSummarize(title, segments, curSummaryType)
|
||||
if (!success) return
|
||||
s += content
|
||||
fileName = '总结.txt'
|
||||
fileName += ' - 总结'
|
||||
suffix = 'txt'
|
||||
} else {
|
||||
return
|
||||
}
|
||||
if (download) {
|
||||
downloadText(s, fileName)
|
||||
downloadText(s, fileName+'.'+suffix)
|
||||
} else {
|
||||
navigator.clipboard.writeText(s).then(() => {
|
||||
toast.success('复制成功')
|
||||
}).catch(console.error)
|
||||
}
|
||||
setMoreVisible(false)
|
||||
}, [curSummaryType, data, downloadType, segments, title, url])
|
||||
}, [author, ctime, curSummaryType, data, downloadType, segments, title, url])
|
||||
|
||||
const downloadAudioCallback = useCallback(() => {
|
||||
window.parent.postMessage({
|
||||
type: 'downloadAudio',
|
||||
}, '*')
|
||||
}, [])
|
||||
sendInject(null, 'DOWNLOAD_AUDIO', {})
|
||||
}, [sendInject])
|
||||
|
||||
const selectCallback = useCallback((e: any) => {
|
||||
dispatch(setTempData({
|
||||
@@ -243,7 +248,7 @@ const MoreBtn = (props: Props) => {
|
||||
下载音频(m4s)
|
||||
</a>
|
||||
</li>
|
||||
<li className='hover:bg-accent'>
|
||||
{/* <li className='hover:bg-accent'>
|
||||
<a className='flex items-center' onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
@@ -262,7 +267,7 @@ const MoreBtn = (props: Props) => {
|
||||
<AiFillWechat className='w-[20px] h-[20px] text-primary/75 bg-white rounded-sm p-0.5'/>
|
||||
微信公众号(IndieKKY)
|
||||
</a>
|
||||
</li>
|
||||
</li> */}
|
||||
{/* <li className='hover:bg-accent'> */}
|
||||
{/* <a className='flex items-center' onClick={(e) => { */}
|
||||
{/* e.preventDefault() */}
|
||||
@@ -286,13 +291,24 @@ const MoreBtn = (props: Props) => {
|
||||
{/* </li> */}
|
||||
<li className='hover:bg-accent'>
|
||||
<a className='flex items-center' onClick={(e) => {
|
||||
dispatch(setPage(PAGE_SETTINGS))
|
||||
chrome.runtime.openOptionsPage()
|
||||
setMoreVisible(false)
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
}}>
|
||||
<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>
|
||||
</li>
|
||||
</ul>
|
@@ -1,7 +1,7 @@
|
||||
import React, {useMemo} from 'react'
|
||||
import {formatTime} from '../util/util'
|
||||
import {formatTime} from '../utils/util'
|
||||
import {useAppSelector} from '../hooks/redux'
|
||||
import {getDisplay, getTransText} from '../util/biz_util'
|
||||
import {getDisplay, getTransText} from '../utils/bizUtil'
|
||||
import classNames from 'classnames'
|
||||
|
||||
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,18 @@
|
||||
import React, {MutableRefObject, useCallback, useEffect, useMemo, useRef} from 'react'
|
||||
import {MutableRefObject, useCallback, useEffect, useMemo, useRef} from 'react'
|
||||
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||
import {setFloatKeyPointsSegIdx, setPage, setSegmentFold, setTempData} from '../redux/envReducer'
|
||||
import {setFloatKeyPointsSegIdx, setSegmentFold, setTempData} from '../redux/envReducer'
|
||||
import classNames from 'classnames'
|
||||
import {FaClipboardList} from 'react-icons/fa'
|
||||
import {PAGE_MAIN, PAGE_SETTINGS, SUMMARIZE_THRESHOLD, SUMMARIZE_TYPES} from '../const'
|
||||
import {FaClipboardList, FaComments} from 'react-icons/fa'
|
||||
import {SUMMARIZE_THRESHOLD, SUMMARIZE_TYPES} from '../consts/const'
|
||||
import useTranslate from '../hooks/useTranslate'
|
||||
import {BsDashSquare, BsPlusSquare, CgFileDocument, GrOverview, RiFileCopy2Line} from 'react-icons/all'
|
||||
import {BsDashSquare, BsPlusSquare, CgFileDocument, FaQuestion, GrOverview, RiFileCopy2Line} from 'react-icons/all'
|
||||
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 SegmentItem from './SegmentItem'
|
||||
import {stopPopFunc} from '../util/util'
|
||||
import {stopPopFunc} from '../utils/util'
|
||||
import useSubtitle from '../hooks/useSubtitle'
|
||||
import DebateChat from './DebateChat'
|
||||
|
||||
const SummarizeItemOverview = (props: {
|
||||
segment: Segment
|
||||
@@ -76,10 +77,9 @@ const Summarize = (props: {
|
||||
if (apiKey) {
|
||||
addSummarizeTask(curSummaryType, segment).catch(console.error)
|
||||
} else {
|
||||
dispatch(setPage(PAGE_SETTINGS))
|
||||
toast.error('需要先设置ApiKey!')
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
}
|
||||
}, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segment])
|
||||
}, [addSummarizeTask, curSummaryType, envData.aiType, envData.apiKey, envData.geminiApiKey, segment])
|
||||
|
||||
const onCopy = useCallback(() => {
|
||||
if (summary != null) {
|
||||
@@ -107,6 +107,15 @@ const Summarize = (props: {
|
||||
<div className={classNames('font-medium max-w-[90%]', fontSize === 'large' ? 'text-sm' : 'text-xs')}>
|
||||
{summary.content.summary}
|
||||
</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 className='flex flex-col justify-center items-center'>
|
||||
{segment.text.length < SUMMARIZE_THRESHOLD && <div className='desc-lighter text-xs'>文字过短,无法总结.</div>}
|
||||
@@ -138,7 +147,6 @@ const SegmentCard = (props: {
|
||||
const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable)
|
||||
const summarizeFloat = useAppSelector(state => state.env.envData.summarizeFloat)
|
||||
const fold = useAppSelector(state => state.env.fold)
|
||||
const page = useAppSelector(state => state.env.page)
|
||||
const compact = useAppSelector(state => state.env.tempData.compact)
|
||||
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
|
||||
const showCurrent = useMemo(() => curIdx != null && segment.startIdx <= curIdx && curIdx <= segment.endIdx, [curIdx, segment.endIdx, segment.startIdx])
|
||||
@@ -161,7 +169,7 @@ const SegmentCard = (props: {
|
||||
// 检测设置floatKeyPointsSegIdx
|
||||
useEffect(() => {
|
||||
if (summarizeFloat) { // 已启用
|
||||
if (!fold && page === PAGE_MAIN && showCurrent) { // 当前Card有控制权
|
||||
if (!fold && showCurrent) { // 当前Card有控制权
|
||||
if (!inViewport && (summary != null) && !isSummaryEmpty(summary)) {
|
||||
dispatch(setFloatKeyPointsSegIdx(segment.startIdx))
|
||||
} else {
|
||||
@@ -169,7 +177,7 @@ const SegmentCard = (props: {
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [dispatch, fold, inViewport, page, segment.startIdx, showCurrent, summarizeFloat, summary])
|
||||
}, [dispatch, fold, inViewport, segment.startIdx, showCurrent, summarizeFloat, summary])
|
||||
|
||||
const onSelBrief = useCallback(() => {
|
||||
dispatch(setTempData({
|
||||
@@ -189,8 +197,20 @@ const SegmentCard = (props: {
|
||||
}))
|
||||
}, [dispatch])
|
||||
|
||||
const onSelQuestion = useCallback(() => {
|
||||
dispatch(setTempData({
|
||||
curSummaryType: 'question'
|
||||
}))
|
||||
}, [dispatch])
|
||||
|
||||
const onSelDebate = useCallback(() => {
|
||||
dispatch(setTempData({
|
||||
curSummaryType: 'debate'
|
||||
}))
|
||||
}, [dispatch])
|
||||
|
||||
return <div
|
||||
className={classNames('border border-base-300 bg-base-200/25 rounded flex flex-col m-1.5 p-1.5 gap-1 shadow', showCurrent && 'shadow-primary')}>
|
||||
className={classNames('border border-base-300 bg-base-200/25 rounded flex flex-col m-1.5 p-1.5 gap-1', showCurrent && 'shadow shadow-md')}>
|
||||
<div className='relative flex justify-center min-h-[20px]'>
|
||||
{segments != null && segments.length > 0 &&
|
||||
<div className='absolute left-0 top-0 bottom-0 text-xs select-none flex-center desc'>
|
||||
@@ -203,6 +223,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 === 'overview' && 'tab-active')} onClick={onSelOverview}><GrOverview/>概览</a>
|
||||
<a className={classNames('tab tab-lifted tab-xs', curSummaryType === 'keypoint' && 'tab-active')} onClick={onSelKeypoint}><FaClipboardList/>要点</a>
|
||||
<a className={classNames('tab tab-lifted tab-xs', curSummaryType === 'question' && 'tab-active')} onClick={onSelQuestion}><FaQuestion/>问题</a>
|
||||
<a className={classNames('tab tab-lifted tab-xs', curSummaryType === 'debate' && 'tab-active')} onClick={onSelDebate}><FaComments/>辩论</a>
|
||||
<a className="tab tab-lifted tab-xs tab-disabled cursor-default"></a>
|
||||
</div>}
|
||||
<div
|
@@ -23,7 +23,7 @@ const SegmentItem = (props: {
|
||||
const searchResult = useAppSelector(state => state.env.searchResult)
|
||||
const display = useMemo(() => {
|
||||
if (searchText) {
|
||||
return searchResult.has(item.idx) ? 'inline' : 'none'
|
||||
return searchResult[item.idx+''] ? 'inline' : 'none'
|
||||
} else {
|
||||
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 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_SUMMARIZE_OVERVIEW = 'summarize_overview'
|
||||
export const PROMPT_TYPE_SUMMARIZE_KEYPOINT = 'summarize_keypoint'
|
||||
export const PROMPT_TYPE_SUMMARIZE_QUESTION = 'summarize_question'
|
||||
export const PROMPT_TYPE_SUMMARIZE_DEBATE = 'summarize_debate'
|
||||
export const PROMPT_TYPE_SUMMARIZE_BRIEF = 'summarize_brief'
|
||||
export const PROMPT_TYPE_ASK = 'ask'
|
||||
export const PROMPT_TYPES = [{
|
||||
@@ -22,6 +28,12 @@ export const PROMPT_TYPES = [{
|
||||
}, {
|
||||
name: '总结',
|
||||
type: PROMPT_TYPE_SUMMARIZE_BRIEF,
|
||||
}, {
|
||||
name: '问题',
|
||||
type: PROMPT_TYPE_SUMMARIZE_QUESTION,
|
||||
}, {
|
||||
name: '辩论',
|
||||
type: PROMPT_TYPE_SUMMARIZE_DEBATE,
|
||||
}, {
|
||||
name: '提问',
|
||||
type: PROMPT_TYPE_ASK,
|
||||
@@ -46,6 +58,18 @@ export const SUMMARIZE_TYPES = {
|
||||
downloadName: '💡视频要点💡',
|
||||
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 = {
|
||||
@@ -124,6 +148,82 @@ The video's subtitles:
|
||||
'''
|
||||
{{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.
|
||||
Answer in language '{{language}}'.
|
||||
|
||||
@@ -139,8 +239,6 @@ Answer:
|
||||
`,
|
||||
}
|
||||
|
||||
export const EVENT_EXPAND = 'expand'
|
||||
|
||||
export const TASK_EXPIRE_TIME = 15*60*1000
|
||||
|
||||
export const PAGE_MAIN = 'main'
|
||||
@@ -172,24 +270,21 @@ export const ASK_ENABLED_DEFAULT = true
|
||||
export const DEFAULT_SERVER_URL_OPENAI = 'https://api.openai.com'
|
||||
export const CUSTOM_MODEL_TOKENS = 16385
|
||||
|
||||
export const MODEL_TIP = '推荐gpt-4o-mini,能力强,价格低,token上限大'
|
||||
export const MODELS = [{
|
||||
code: 'gpt-3.5-turbo',
|
||||
name: 'gpt-3.5-turbo',
|
||||
tokens: 4096,
|
||||
code: 'gpt-4o-mini',
|
||||
name: 'gpt-4o-mini',
|
||||
tokens: 128000,
|
||||
}, {
|
||||
code: 'gpt-3.5-turbo-0125',
|
||||
name: 'gpt-3.5-turbo-0125',
|
||||
tokens: 16385,
|
||||
}, {
|
||||
code: 'gpt-3.5-turbo-1106',
|
||||
name: 'gpt-3.5-turbo-1106',
|
||||
tokens: 16385,
|
||||
}, {
|
||||
code: 'custom',
|
||||
name: '自定义',
|
||||
}]
|
||||
export const GEMINI_TOKENS = 32768
|
||||
export const MODEL_DEFAULT = MODELS[1].code
|
||||
export const MODEL_DEFAULT = MODELS[0].code
|
||||
export const MODEL_MAP: {[key: string]: typeof MODELS[number]} = {}
|
||||
for (const model of MODELS) {
|
||||
MODEL_MAP[model.code] = model
|
||||
@@ -198,6 +293,9 @@ for (const model of MODELS) {
|
||||
export const LANGUAGES = [{
|
||||
code: 'en',
|
||||
name: 'English',
|
||||
}, {
|
||||
code: 'ja',
|
||||
name: '日本語',
|
||||
}, {
|
||||
code: 'ena',
|
||||
name: 'American English',
|
||||
@@ -231,6 +329,39 @@ export const LANGUAGES = [{
|
||||
}, {
|
||||
code: 'Italian',
|
||||
name: 'Italiano',
|
||||
}, {
|
||||
code: 'ko',
|
||||
name: '한국어',
|
||||
}, {
|
||||
code: 'hi',
|
||||
name: 'हिन्दी',
|
||||
}, {
|
||||
code: 'tr',
|
||||
name: 'Türkçe',
|
||||
}, {
|
||||
code: 'nl',
|
||||
name: 'Nederlands',
|
||||
}, {
|
||||
code: 'pl',
|
||||
name: 'Polski',
|
||||
}, {
|
||||
code: 'sv',
|
||||
name: 'Svenska',
|
||||
}, {
|
||||
code: 'vi',
|
||||
name: 'Tiếng Việt',
|
||||
}, {
|
||||
code: 'th',
|
||||
name: 'ไทย',
|
||||
}, {
|
||||
code: 'id',
|
||||
name: 'Bahasa Indonesia',
|
||||
}, {
|
||||
code: 'el',
|
||||
name: 'Ελληνικά',
|
||||
}, {
|
||||
code: 'he',
|
||||
name: 'עברית',
|
||||
}]
|
||||
export const LANGUAGES_MAP: {[key: string]: typeof LANGUAGES[number]} = {}
|
||||
for (const language of LANGUAGES) {
|
@@ -1,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 {useMemoizedFn} from 'ahooks/es'
|
||||
import {useAppSelector} from './redux'
|
||||
import {useAppDispatch, useAppSelector} from './redux'
|
||||
import useSubtitle from './useSubtitle'
|
||||
import {setInputting} from '../redux/envReducer'
|
||||
|
||||
const useKeyService = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
const inputting = useAppSelector(state => state.env.inputting)
|
||||
const curIdx = useAppSelector(state => state.env.curIdx)
|
||||
const data = useAppSelector(state => state.env.data)
|
||||
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) => {
|
||||
// 当前在输入中(如中文输入法)
|
||||
if (inputting) {
|
||||
return
|
||||
}
|
||||
|
||||
// 有按其他控制键时,不触发
|
||||
if (e.ctrlKey || e.metaKey || e.shiftKey) {
|
||||
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 {useEffect, useMemo} from 'react'
|
||||
import {setSearchResult, setSearchText, } from '../redux/envReducer'
|
||||
import {Search} from '../util/search'
|
||||
import {Search} from '../utils/search'
|
||||
|
||||
interface Document {
|
||||
idx: number
|
||||
@@ -42,14 +42,14 @@ const useSearchService = () => {
|
||||
|
||||
// search text
|
||||
useEffect(() => {
|
||||
const searchResult: Set<number> = new Set()
|
||||
const searchResult: Record<string, boolean> = {}
|
||||
|
||||
if (envData.searchEnabled && searchText) {
|
||||
// @ts-expect-error
|
||||
const documents: Document[] | undefined = search(searchText)
|
||||
if (documents != null) {
|
||||
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 {setNeedScroll} from '../redux/envReducer'
|
||||
|
||||
import {setNeedScroll, setReviewAction, setTempData} from '../redux/envReducer'
|
||||
import { useMessage } from './useMessageService'
|
||||
const useSubtitle = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
|
||||
const reviewAction = useAppSelector(state => state.env.reviewAction)
|
||||
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
|
||||
const {sendInject} = useMessage(!!envData.sidePanel)
|
||||
|
||||
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>) => {
|
||||
ref.current?.scrollIntoView({behavior: 'smooth', block: 'center'})
|
||||
|
@@ -13,11 +13,13 @@ import {
|
||||
setTitle,
|
||||
setTotalHeight,
|
||||
setUrl,
|
||||
setTempData,
|
||||
} from '../redux/envReducer'
|
||||
import {EventBusContext} from '../Router'
|
||||
import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../const'
|
||||
import {useInterval} from 'ahooks'
|
||||
import {getModelMaxTokens, getWholeText} from '../util/biz_util'
|
||||
import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../consts/const'
|
||||
import {useAsyncEffect, useInterval} from 'ahooks'
|
||||
import {getModelMaxTokens, getWholeText} from '../utils/bizUtil'
|
||||
import { useMessage } from './useMessageService'
|
||||
|
||||
/**
|
||||
* Service是单例,类似后端的服务概念
|
||||
@@ -39,55 +41,18 @@ const useSubtitleService = () => {
|
||||
const transResults = useAppSelector(state => state.env.transResults)
|
||||
const hideOnDisableAutoTranslate = useAppSelector(state => state.env.envData.hideOnDisableAutoTranslate)
|
||||
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(() => {
|
||||
const listener = (event: MessageEvent) => {
|
||||
const data = event.data
|
||||
|
||||
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)))
|
||||
}
|
||||
}
|
||||
if (reviewed === undefined && reviewActions && reviewActions >= 15) {
|
||||
dispatch(setTempData({
|
||||
reviewed: false
|
||||
}))
|
||||
}
|
||||
|
||||
window.addEventListener('message', listener)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('message', listener)
|
||||
}
|
||||
}, [dispatch, eventBus])
|
||||
}, [reviewActions, dispatch, reviewed])
|
||||
|
||||
// 有数据时自动展开
|
||||
useEffect(() => {
|
||||
@@ -100,24 +65,51 @@ const useSubtitleService = () => {
|
||||
|
||||
// 当前未展示 & (未折叠 | 自动展开) & 有列表 => 展示第一个
|
||||
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(setCurFetched(false))
|
||||
}
|
||||
}, [curInfo, dispatch, envData.autoExpand, envReady, fold, infos])
|
||||
}, [curInfo, dispatch, envData.autoExpand, envReady, fold, infos, envData.sidePanel])
|
||||
// 获取
|
||||
useEffect(() => {
|
||||
if (curInfo && !curFetched) {
|
||||
window.parent.postMessage({type: 'getSubtitle', info: curInfo}, '*')
|
||||
}
|
||||
}, [curFetched, curInfo])
|
||||
sendInject(null, 'GET_SUBTITLE', {info: curInfo}).then(data => {
|
||||
data?.body?.forEach((item: TranscriptItem, idx: number) => {
|
||||
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'}, '*')
|
||||
// 初始获取设置信息
|
||||
window.parent.postMessage({type: 'getSettings'}, '*')
|
||||
}, [])
|
||||
if (envReady) {
|
||||
sendInject(null, 'REFRESH_VIDEO_INFO', {force: true})
|
||||
}
|
||||
}, [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(() => {
|
||||
@@ -202,25 +194,27 @@ const useSubtitleService = () => {
|
||||
dispatch(setSegments(segments))
|
||||
}, [data?.body, dispatch, envData])
|
||||
|
||||
// 每秒更新当前视频时间
|
||||
// 每0.5秒更新当前视频时间
|
||||
useInterval(() => {
|
||||
window.parent.postMessage({type: 'getCurrentTime'}, '*')
|
||||
sendInject(null, 'GET_VIDEO_STATUS', {}).then(status => {
|
||||
dispatch(setCurrentTime(status.currentTime))
|
||||
})
|
||||
}, 500)
|
||||
|
||||
// show translated text in the video
|
||||
useEffect(() => {
|
||||
if (hideOnDisableAutoTranslate && !autoTranslate) {
|
||||
window.parent.postMessage({type: 'updateTransResult'}, '*')
|
||||
sendInject(null, 'HIDE_TRANS', {})
|
||||
return
|
||||
}
|
||||
|
||||
const transResult = curIdx?transResults[curIdx]:undefined
|
||||
if (transResult?.code === '200' && transResult.data) {
|
||||
window.parent.postMessage({type: 'updateTransResult', result: transResult.data}, '*')
|
||||
sendInject(null, 'UPDATE_TRANS_RESULT', {result: transResult.data})
|
||||
} else {
|
||||
window.parent.postMessage({type: 'updateTransResult'}, '*')
|
||||
sendInject(null, 'HIDE_TRANS', {})
|
||||
}
|
||||
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, transResults])
|
||||
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, sendInject, transResults])
|
||||
}
|
||||
|
||||
export default useSubtitleService
|
||||
|
@@ -4,14 +4,14 @@ import {
|
||||
addTaskId,
|
||||
addTransResults,
|
||||
delTaskId,
|
||||
setAskContent,
|
||||
setAskError,
|
||||
setAskStatus,
|
||||
mergeAskInfo,
|
||||
setLastSummarizeTime,
|
||||
setLastTransTime,
|
||||
setSummaryContent,
|
||||
setSummaryError,
|
||||
setSummaryStatus
|
||||
setSummaryStatus,
|
||||
setReviewAction,
|
||||
setTempData
|
||||
} from '../redux/envReducer'
|
||||
import {
|
||||
LANGUAGE_DEFAULT,
|
||||
@@ -24,12 +24,12 @@ import {
|
||||
SUMMARIZE_TYPES,
|
||||
TRANSLATE_COOLDOWN,
|
||||
TRANSLATE_FETCH_DEFAULT,
|
||||
} from '../const'
|
||||
} from '../consts/const'
|
||||
import toast from 'react-hot-toast'
|
||||
import {useMemoizedFn} from 'ahooks/es'
|
||||
import {extractJsonArray, extractJsonObject, getModel} from '../util/biz_util'
|
||||
import {formatTime} from '../util/util'
|
||||
|
||||
import {extractJsonArray, extractJsonObject, getModel} from '../utils/bizUtil'
|
||||
import {formatTime} from '../utils/util'
|
||||
import { useMessage } from './useMessageService'
|
||||
const useTranslate = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
const data = useAppSelector(state => state.env.data)
|
||||
@@ -40,7 +40,10 @@ const useTranslate = () => {
|
||||
const language = LANGUAGES_MAP[envData.language??LANGUAGE_DEFAULT]
|
||||
const summarizeLanguage = LANGUAGES_MAP[envData.summarizeLanguage??SUMMARIZE_LANGUAGE_DEFAULT]
|
||||
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)
|
||||
/**
|
||||
* 获取下一个需要翻译的行
|
||||
* 会检测冷却
|
||||
@@ -132,13 +135,21 @@ const useTranslate = () => {
|
||||
}
|
||||
})
|
||||
dispatch(addTransResults(result))
|
||||
const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef})
|
||||
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
|
||||
dispatch(addTaskId(task.id))
|
||||
}
|
||||
}
|
||||
}, [data?.body, envData, language.name, title, dispatch])
|
||||
}, [data?.body, envData, language.name, title, dispatch, sendExtension])
|
||||
|
||||
const addSummarizeTask = useCallback(async (type: SummaryType, segment: Segment) => {
|
||||
// review action
|
||||
if (reviewed === undefined && !reviewAction) {
|
||||
dispatch(setReviewAction(true))
|
||||
dispatch(setTempData({
|
||||
reviewActions: (reviewActions ?? 0) + 1
|
||||
}))
|
||||
}
|
||||
|
||||
if (segment.text.length >= SUMMARIZE_THRESHOLD) {
|
||||
let subtitles = ''
|
||||
for (const item of segment.items) {
|
||||
@@ -194,12 +205,12 @@ const useTranslate = () => {
|
||||
console.debug('addSummarizeTask', taskDef)
|
||||
dispatch(setSummaryStatus({segmentStartIdx: segment.startIdx, type, status: 'pending'}))
|
||||
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, 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) {
|
||||
let prompt: string = envData.prompts?.[PROMPT_TYPE_ASK]??PROMPT_DEFAULTS[PROMPT_TYPE_ASK]
|
||||
// replace params
|
||||
@@ -243,14 +254,18 @@ const useTranslate = () => {
|
||||
// startIdx: segment.startIdx,
|
||||
apiKey: envData.apiKey,
|
||||
geminiApiKey: envData.geminiApiKey,
|
||||
askId: id,
|
||||
}
|
||||
}
|
||||
console.debug('addAskTask', taskDef)
|
||||
dispatch(setAskStatus({status: 'pending'}))
|
||||
const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef})
|
||||
dispatch(mergeAskInfo({
|
||||
id,
|
||||
status: 'pending'
|
||||
}))
|
||||
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
|
||||
dispatch(addTaskId(task.id))
|
||||
}
|
||||
}, [dispatch, envData, summarizeLanguage.name, title])
|
||||
}, [dispatch, envData, sendExtension, summarizeLanguage.name, title])
|
||||
|
||||
const handleTranslate = useMemoizedFn((task: Task, content: string) => {
|
||||
let map: {[key: string]: string} = {}
|
||||
@@ -304,14 +319,18 @@ const useTranslate = () => {
|
||||
})
|
||||
|
||||
const handleAsk = useMemoizedFn((task: Task, content?: string) => {
|
||||
dispatch(setAskContent({content}))
|
||||
dispatch(setAskStatus({status: 'done'}))
|
||||
dispatch(setAskError({error: task.error}))
|
||||
dispatch(mergeAskInfo({
|
||||
id: task.def.extra.askId,
|
||||
content,
|
||||
status: 'done',
|
||||
error: task.error,
|
||||
}))
|
||||
|
||||
console.debug('setAsk', content, task.error)
|
||||
})
|
||||
|
||||
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') {
|
||||
console.debug('getTask', taskResp.task)
|
||||
const task: Task = taskResp.task
|
||||
@@ -336,7 +355,7 @@ const useTranslate = () => {
|
||||
} else {
|
||||
dispatch(delTaskId(taskId))
|
||||
}
|
||||
}, [dispatch, envData.aiType, handleAsk, handleSummarize, handleTranslate])
|
||||
}, [dispatch, envData.aiType, handleAsk, handleSummarize, handleTranslate, sendExtension])
|
||||
|
||||
return {getFetch, getTask, addTask, addSummarizeTask, addAskTask}
|
||||
}
|
||||
|
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)
|
||||
})()
|
@@ -4,7 +4,7 @@ import './index.less'
|
||||
import store from './store'
|
||||
import {Provider} from 'react-redux'
|
||||
import Router from './Router'
|
||||
import {APP_DOM_ID} from './const'
|
||||
import { APP_DOM_ID } from './consts/const'
|
||||
|
||||
const body = document.querySelector('body')
|
||||
const app = document.createElement('div')
|
||||
|
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 {setEnvData, setPage} from '../redux/envReducer'
|
||||
import {setEnvData} from '../redux/envReducer'
|
||||
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||
import {
|
||||
ASK_ENABLED_DEFAULT,
|
||||
CUSTOM_MODEL_TOKENS,
|
||||
DEFAULT_SERVER_URL_OPENAI,
|
||||
GEMINI_TOKENS,
|
||||
HEADER_HEIGHT,
|
||||
LANGUAGE_DEFAULT,
|
||||
LANGUAGES,
|
||||
MODEL_DEFAULT,
|
||||
MODEL_MAP,
|
||||
MODEL_TIP,
|
||||
MODELS,
|
||||
PAGE_MAIN,
|
||||
PROMPT_DEFAULTS,
|
||||
PROMPT_TYPES,
|
||||
SUMMARIZE_LANGUAGE_DEFAULT,
|
||||
@@ -21,22 +20,29 @@ import {
|
||||
TRANSLATE_FETCH_MIN,
|
||||
TRANSLATE_FETCH_STEP,
|
||||
WORDS_RATE,
|
||||
} from '../const'
|
||||
import {FaGripfire, IoWarning} from 'react-icons/all'
|
||||
} from '../consts/const'
|
||||
import {IoWarning} from 'react-icons/all'
|
||||
import classNames from 'classnames'
|
||||
import toast from 'react-hot-toast'
|
||||
import {useBoolean, useEventTarget} from 'ahooks'
|
||||
import {useEventChecked} from '@kky002/kky-hooks'
|
||||
import { FaChevronDown, FaChevronUp, FaGripfire } from 'react-icons/fa'
|
||||
import { useMessage } from '@/hooks/useMessageService'
|
||||
|
||||
const Section = (props: {
|
||||
title: ShowElement
|
||||
htmlFor?: string
|
||||
} & PropsWithChildren) => {
|
||||
const {title, htmlFor, children} = props
|
||||
return <div className='flex flex-col gap-1'>
|
||||
<label className='font-medium desc-lighter text-xs' htmlFor={htmlFor}>{title}</label>
|
||||
<div className='flex flex-col gap-1 rounded py-2 px-2 bg-base-200/75'>{children}</div>
|
||||
</div>
|
||||
const OptionCard = ({ title, children, defaultExpanded = true }: { title: React.ReactNode, children: React.ReactNode, defaultExpanded?: boolean }) => {
|
||||
const [isExpanded, setIsExpanded] = useState(defaultExpanded)
|
||||
|
||||
return (
|
||||
<div className="card bg-base-200 shadow-xl mb-4">
|
||||
<div className="card-body p-4">
|
||||
<h2 className="card-title flex justify-between cursor-pointer" onClick={() => setIsExpanded(!isExpanded)}>
|
||||
{title}
|
||||
{isExpanded ? <FaChevronUp /> : <FaChevronDown />}
|
||||
</h2>
|
||||
{isExpanded && <div className="mt-4">{children}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const FormItem = (props: {
|
||||
@@ -45,19 +51,24 @@ const FormItem = (props: {
|
||||
htmlFor?: string
|
||||
} & PropsWithChildren) => {
|
||||
const {title, tip, htmlFor, children} = props
|
||||
return <div className='flex items-center gap-2'>
|
||||
<div className={classNames('basis-3/12 flex-center', tip && 'tooltip tooltip-right z-[100] underline underline-offset-2 decoration-dashed')} data-tip={tip}>
|
||||
<label className='font-medium desc' htmlFor={htmlFor}>{title}</label>
|
||||
return (
|
||||
<div className='flex items-center gap-4 mb-2'>
|
||||
<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 className='basis-9/12 flex items-center'>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const Settings = () => {
|
||||
const OptionsPage = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
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: autoScrollValue, onChange: setAutoScrollValue} = useEventChecked(envData.autoScroll)
|
||||
const {value: translateEnableValue, onChange: setTranslateEnableValue} = useEventChecked(envData.translateEnable)
|
||||
@@ -81,10 +92,7 @@ const Settings = () => {
|
||||
const [transDisplayValue, setTransDisplayValue] = useState(envData.transDisplay)
|
||||
const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words)
|
||||
const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT)
|
||||
const [moreFold, {toggle: toggleMoreFold}] = 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 wordsList = useMemo(() => {
|
||||
// const list = []
|
||||
@@ -113,6 +121,8 @@ const Settings = () => {
|
||||
|
||||
const onSave = useCallback(() => {
|
||||
dispatch(setEnvData({
|
||||
sidePanel: sidePanelValue,
|
||||
manualInsert: !autoInsertValue,
|
||||
autoExpand: autoExpandValue,
|
||||
aiType: aiTypeValue,
|
||||
apiKey: apiKeyValue,
|
||||
@@ -137,13 +147,17 @@ const Settings = () => {
|
||||
cnSearchEnabled: cnSearchEnabledValue,
|
||||
askEnabled: askEnabledValue,
|
||||
}))
|
||||
dispatch(setPage(PAGE_MAIN))
|
||||
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, aiTypeValue, apiKeyValue, serverUrlValue, modelValue, customModelValue, customModelTokensValue, geminiApiKeyValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue, askEnabledValue])
|
||||
|
||||
const onCancel = useCallback(() => {
|
||||
dispatch(setPage(PAGE_MAIN))
|
||||
}, [dispatch])
|
||||
window.close()
|
||||
}, [])
|
||||
|
||||
const onFetchAmountChange = useCallback((e: any) => {
|
||||
setFetchAmountValue(parseInt(e.target.value))
|
||||
@@ -193,118 +207,107 @@ const Settings = () => {
|
||||
setAiTypeValue('gemini')
|
||||
}, [])
|
||||
|
||||
return <div className='text-sm overflow-y-auto' style={{
|
||||
height: fold?undefined:`${totalHeight-HEADER_HEIGHT}px`,
|
||||
}}>
|
||||
<div className="flex flex-col gap-3 p-2">
|
||||
<Section title='通用配置'>
|
||||
<FormItem title='自动展开' htmlFor='autoExpand' tip='是否视频有字幕时自动展开字幕列表'>
|
||||
return (
|
||||
<div className='container mx-auto max-w-3xl p-4'>
|
||||
<OptionCard title="通用配置">
|
||||
<FormItem title='侧边栏' htmlFor='sidePanel' tip='字幕列表是否显示在侧边栏'>
|
||||
<input id='sidePanel' type='checkbox' className='toggle toggle-primary' checked={sidePanelValue}
|
||||
onChange={setSidePanelValue}/>
|
||||
</FormItem>
|
||||
{!sidePanelValue && <FormItem title='自动插入' htmlFor='autoInsert' tip='是否自动插入字幕列表(可以手动点击扩展图标插入)'>
|
||||
<input id='autoInsert' type='checkbox' className='toggle toggle-primary' checked={autoInsertValue}
|
||||
onChange={setAutoInsertValue}/>
|
||||
</FormItem>}
|
||||
{!sidePanelValue && <FormItem title='自动展开' htmlFor='autoExpand' tip='是否视频有字幕时自动展开字幕列表'>
|
||||
<input id='autoExpand' type='checkbox' className='toggle toggle-primary' checked={autoExpandValue}
|
||||
onChange={setAutoExpandValue}/>
|
||||
</FormItem>
|
||||
</FormItem>}
|
||||
<FormItem title='主题'>
|
||||
<div className="btn-group">
|
||||
<button onClick={onSelTheme1} className={classNames('btn btn-xs 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={onSelTheme3} className={classNames('btn btn-xs no-animation', themeValue === 'dark'?'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-sm no-animation', themeValue === 'light'?'btn-active':'')}>浅色</button>
|
||||
<button onClick={onSelTheme3} className={classNames('btn btn-sm no-animation', themeValue === 'dark'?'btn-active':'')}>深色</button>
|
||||
</div>
|
||||
</FormItem>
|
||||
<FormItem title='字体大小'>
|
||||
<div className="btn-group">
|
||||
<button onClick={onSelFontSize1} className={classNames('btn btn-xs 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={onSelFontSize1} className={classNames('btn btn-sm no-animation', (!fontSizeValue || fontSizeValue === 'normal')?'btn-active':'')}>普通</button>
|
||||
<button onClick={onSelFontSize2} className={classNames('btn btn-sm no-animation', fontSizeValue === 'large'?'btn-active':'')}>加大</button>
|
||||
</div>
|
||||
</FormItem>
|
||||
<FormItem title='AI类型' tip='OPENAI质量更高'>
|
||||
<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>
|
||||
<button onClick={onSelOpenai} className={classNames('btn btn-sm', (!aiTypeValue || aiTypeValue === 'openai')?'btn-active':'')}>OpenAI</button>
|
||||
<button onClick={onSelGemini} className={classNames('btn btn-sm', aiTypeValue === 'gemini'?'btn-active':'')}>Gemini</button>
|
||||
</div>
|
||||
</FormItem>
|
||||
</Section>
|
||||
</OptionCard>
|
||||
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <Section title='openai配置'>
|
||||
<FormItem title='ApiKey' htmlFor='apiKey'>
|
||||
<OptionCard title="AI 配置">
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='ApiKey' htmlFor='apiKey'>
|
||||
<input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx'
|
||||
value={apiKeyValue} onChange={onChangeApiKeyValue}/>
|
||||
</FormItem>
|
||||
<FormItem title='服务器' htmlFor='serverUrl'>
|
||||
</FormItem>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='服务器' htmlFor='serverUrl'>
|
||||
<input id='serverUrl' type='text' className='input input-sm input-bordered w-full'
|
||||
placeholder={DEFAULT_SERVER_URL_OPENAI} value={serverUrlValue}
|
||||
onChange={e => setServerUrlValue(e.target.value)}/>
|
||||
</FormItem>
|
||||
<div>
|
||||
<div className='desc text-xs text-center'>
|
||||
</FormItem>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <div>
|
||||
<div className='desc text-sm text-center'>
|
||||
<div className='flex justify-center font-semibold'>【官方地址】</div>
|
||||
<div>官方网址:<a className='link link-primary' href='https://platform.openai.com/' target='_blank'
|
||||
rel="noreferrer">点击访问</a></div>
|
||||
<div>服务器地址:<a className='link link-primary'
|
||||
onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_OPENAI)}
|
||||
rel='noreferrer'>点击设置</a></div>
|
||||
<div className='flex justify-center font-semibold'>【第三方代理】</div>
|
||||
<div>代理网址:<a className='link link-primary' href='https://api.openai-up.com/register?aff=varM'
|
||||
<div className='flex justify-center font-semibold'>【第三方国内代理】</div>
|
||||
<div>代理网址:<a className='link link-primary' href='https://api.kksj.org/register?aff=ucVc'
|
||||
target='_blank'
|
||||
rel="noreferrer">点击访问</a></div>
|
||||
<div>服务器地址:<a className='link link-primary'
|
||||
onClick={() => setServerUrlValue('https://api.openai-up.com')}
|
||||
onClick={() => setServerUrlValue('https://api.kksj.org')}
|
||||
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>
|
||||
<FormItem title='模型选择' htmlFor='modelSel' tip='注意,不同模型有不同价格与token限制'>
|
||||
</div>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='模型选择' htmlFor='modelSel' tip='注意,不同模型有不同价格与token限制'>
|
||||
<select id='modelSel' className="select select-sm select-bordered" value={modelValue}
|
||||
onChange={onChangeModelValue}>
|
||||
{MODELS.map(model => <option key={model.code} value={model.code}>{model.name}</option>)}
|
||||
</select>
|
||||
</FormItem>
|
||||
</FormItem>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <div className='desc text-sm'>
|
||||
{MODEL_TIP}
|
||||
</div>}
|
||||
{modelValue === 'custom' && <FormItem title='模型名' htmlFor='customModel'>
|
||||
<input id='customModel' type='text' className='input input-sm input-bordered w-full' placeholder='llama2'
|
||||
value={customModelValue} onChange={onChangeCustomModelValue}/>
|
||||
</FormItem>}
|
||||
{modelValue === 'custom' && <FormItem title='Token上限' htmlFor='customModelTokens'>
|
||||
<input id='customModelTokens' type='number' className='input input-sm input-bordered w-full' placeholder={''+CUSTOM_MODEL_TOKENS}
|
||||
value={customModelTokensValue} onChange={e => setCustomModelTokensValue(e.target.value?parseInt(e.target.value):undefined)}/>
|
||||
<input id='customModelTokens' type='number' className='input input-sm input-bordered w-full'
|
||||
placeholder={'' + CUSTOM_MODEL_TOKENS}
|
||||
value={customModelTokensValue}
|
||||
onChange={e => setCustomModelTokensValue(e.target.value ? parseInt(e.target.value) : undefined)}/>
|
||||
</FormItem>}
|
||||
</Section>}
|
||||
|
||||
{aiTypeValue === 'gemini' && <Section title='gemini配置'>
|
||||
<FormItem title='ApiKey' htmlFor='geminiApiKey'>
|
||||
{aiTypeValue === 'gemini' && <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> (目前免费)
|
||||
</FormItem>}
|
||||
{aiTypeValue === 'gemini' && <div>
|
||||
<div className='desc text-sm'>
|
||||
<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-sm text-error flex items-center'><IoWarning className='text-sm text-warning'/>谷歌模型安全要求比较高,有些视频可能无法生成总结!
|
||||
</div>
|
||||
<div className='text-xs text-error flex items-center'><IoWarning className='text-sm text-warning'/>谷歌模型安全要求比较高,有些视频可能无法生成总结!</div>
|
||||
</div>
|
||||
</div>
|
||||
</Section>}
|
||||
</div>}
|
||||
</OptionCard>
|
||||
|
||||
<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'>
|
||||
<OptionCard title={<div className='flex items-center'>
|
||||
翻译配置
|
||||
{!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
|
||||
<IoWarning className='text-sm text-warning'/>
|
||||
@@ -323,24 +326,24 @@ const Settings = () => {
|
||||
<FormItem title='翻译条数' tip='每次翻译条数'>
|
||||
<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} />
|
||||
<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>)}
|
||||
</div>
|
||||
</div>
|
||||
</FormItem>
|
||||
<FormItem title='翻译显示'>
|
||||
<div className="btn-group">
|
||||
<button onClick={onSel1} className={classNames('btn btn-xs 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={onSel3} className={classNames('btn btn-xs no-animation', transDisplayValue === 'target'?'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-sm no-animation', transDisplayValue === 'targetPrimary'?'btn-active':'')}>翻译为主</button>
|
||||
<button onClick={onSel3} className={classNames('btn btn-sm no-animation', transDisplayValue === 'target'?'btn-active':'')}>仅翻译</button>
|
||||
</div>
|
||||
</FormItem>
|
||||
<FormItem title='隐藏翻译' tip='取消自动翻译时,隐藏已翻译内容' htmlFor='hideOnDisableAutoTranslate'>
|
||||
<input id='hideOnDisableAutoTranslate' type='checkbox' className='toggle toggle-primary' checked={hideOnDisableAutoTranslateValue}
|
||||
onChange={onChangeHideOnDisableAutoTranslate}/>
|
||||
</FormItem>
|
||||
</Section>
|
||||
<Section title={<div className='flex items-center'>
|
||||
</OptionCard>
|
||||
<OptionCard title={<div className='flex items-center'>
|
||||
总结配置
|
||||
{!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
|
||||
<IoWarning className='text-sm text-warning'/>
|
||||
@@ -363,17 +366,17 @@ const Settings = () => {
|
||||
<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 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>)} */}
|
||||
{/* </div> */}
|
||||
</div>
|
||||
</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>
|
||||
(太接近上限总结会报错)
|
||||
</div>
|
||||
</Section>
|
||||
<Section title={<div className='flex items-center'>
|
||||
</OptionCard>
|
||||
<OptionCard title={<div className='flex items-center'>
|
||||
搜索配置
|
||||
</div>}>
|
||||
<FormItem title='启用搜索' htmlFor='searchEnabled' tip='是否启用字幕搜索功能'>
|
||||
@@ -384,21 +387,47 @@ const Settings = () => {
|
||||
<input id='cnSearchEnabled' type='checkbox' className='toggle toggle-primary' checked={cnSearchEnabledValue}
|
||||
onChange={setCnSearchEnabledValue}/>
|
||||
</FormItem>
|
||||
</Section>
|
||||
<Section title={<div className='flex items-center'>
|
||||
</OptionCard>
|
||||
<OptionCard title={<div className='flex items-center'>
|
||||
提问配置
|
||||
</div>}>
|
||||
<FormItem title='启用提问' htmlFor='askEnabled' tip='是否启用字幕提问功能'>
|
||||
<input id='askEnabled' type='checkbox' className='toggle toggle-primary' checked={askEnabledValue}
|
||||
onChange={setAskEnabledValue}/>
|
||||
</FormItem>
|
||||
</Section>
|
||||
<div className='flex justify-center gap-5'>
|
||||
<button className='btn btn-primary btn-sm' onClick={onSave}>保存</button>
|
||||
<button className='btn btn-sm' onClick={onCancel}>取消</button>
|
||||
</OptionCard>
|
||||
|
||||
<OptionCard title='提示词配置'>
|
||||
<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>
|
||||
)
|
||||
}
|
||||
|
||||
export default Settings
|
||||
export default OptionsPage
|
@@ -1,7 +1,6 @@
|
||||
import {createSlice, PayloadAction} from '@reduxjs/toolkit'
|
||||
import {find} from 'lodash-es'
|
||||
import {getDevData} from '../util/biz_util'
|
||||
import {DEFAULT_SERVER_URL_OPENAI, TOTAL_HEIGHT_DEF} from '../const'
|
||||
import {find, findIndex} from 'lodash-es'
|
||||
import {DEFAULT_SERVER_URL_OPENAI, TOTAL_HEIGHT_DEF} from '../consts/const'
|
||||
|
||||
interface EnvState {
|
||||
envData: EnvData
|
||||
@@ -10,9 +9,10 @@ interface EnvState {
|
||||
tempData: TempData
|
||||
tempReady: boolean
|
||||
|
||||
path?: 'app' | 'options'
|
||||
|
||||
fold: boolean // fold app
|
||||
foldAll?: boolean // fold all segments
|
||||
page?: string
|
||||
autoTranslate?: boolean
|
||||
autoScroll?: boolean
|
||||
checkAutoScroll?: boolean
|
||||
@@ -32,21 +32,26 @@ interface EnvState {
|
||||
segments?: Segment[]
|
||||
url?: string
|
||||
title?: string
|
||||
|
||||
ctime?: number | null
|
||||
author?: string
|
||||
taskIds?: string[]
|
||||
transResults: { [key: number]: TransResult }
|
||||
lastTransTime?: number
|
||||
lastSummarizeTime?: number
|
||||
|
||||
// ask
|
||||
askFold?: boolean
|
||||
askQuestion?: string
|
||||
askStatus: SummaryStatus
|
||||
askError?: string
|
||||
askContent?: string
|
||||
asks: AskInfo[]
|
||||
|
||||
/**
|
||||
* 是否输入中(中文)
|
||||
*/
|
||||
inputting: boolean
|
||||
|
||||
searchText: string
|
||||
searchResult: Set<number>
|
||||
searchResult: Record<string, boolean>
|
||||
|
||||
// 当前视频是否计算过操作
|
||||
reviewAction: boolean
|
||||
}
|
||||
|
||||
const initialState: EnvState = {
|
||||
@@ -61,18 +66,21 @@ const initialState: EnvState = {
|
||||
tempData: {
|
||||
curSummaryType: 'overview',
|
||||
},
|
||||
askStatus: 'init',
|
||||
totalHeight: TOTAL_HEIGHT_DEF,
|
||||
autoScroll: true,
|
||||
currentTime: import.meta.env.VITE_ENV === 'web-dev' ? 30 : undefined,
|
||||
envReady: false,
|
||||
tempReady: false,
|
||||
fold: true,
|
||||
data: import.meta.env.VITE_ENV === 'web-dev' ? getDevData() : undefined,
|
||||
transResults: {},
|
||||
|
||||
inputting: false,
|
||||
|
||||
searchText: '',
|
||||
searchResult: new Set(),
|
||||
searchResult: {},
|
||||
|
||||
asks: [],
|
||||
|
||||
reviewAction: false,
|
||||
}
|
||||
|
||||
export const slice = createSlice({
|
||||
@@ -94,13 +102,19 @@ export const slice = createSlice({
|
||||
...action.payload,
|
||||
}
|
||||
},
|
||||
setReviewAction: (state, action: PayloadAction<boolean>) => {
|
||||
state.reviewAction = action.payload
|
||||
},
|
||||
setPath: (state, action: PayloadAction<'app' | 'options' | undefined>) => {
|
||||
state.path = action.payload
|
||||
},
|
||||
setTempReady: (state) => {
|
||||
state.tempReady = true
|
||||
},
|
||||
setSearchText: (state, action: PayloadAction<string>) => {
|
||||
state.searchText = action.payload
|
||||
},
|
||||
setSearchResult: (state, action: PayloadAction<Set<number>>) => {
|
||||
setSearchResult: (state, action: PayloadAction<Record<string, boolean>>) => {
|
||||
state.searchResult = action.payload
|
||||
},
|
||||
setFloatKeyPointsSegIdx: (state, action: PayloadAction<number | undefined>) => {
|
||||
@@ -109,9 +123,6 @@ export const slice = createSlice({
|
||||
setFoldAll: (state, action: PayloadAction<boolean>) => {
|
||||
state.foldAll = action.payload
|
||||
},
|
||||
setPage: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.page = action.payload
|
||||
},
|
||||
setTotalHeight: (state, action: PayloadAction<number>) => {
|
||||
state.totalHeight = action.payload
|
||||
},
|
||||
@@ -204,26 +215,20 @@ export const slice = createSlice({
|
||||
}
|
||||
}
|
||||
},
|
||||
setAskFold: (state, action: PayloadAction<boolean>) => {
|
||||
state.askFold = action.payload
|
||||
addAskInfo: (state, action: PayloadAction<AskInfo>) => {
|
||||
state.asks.push(action.payload)
|
||||
},
|
||||
setAskQuestion: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.askQuestion = action.payload
|
||||
delAskInfo: (state, action: PayloadAction<string>) => {
|
||||
state.asks = state.asks.filter(ask => ask.id !== action.payload)
|
||||
},
|
||||
setAskContent: (state, action: PayloadAction<{
|
||||
content?: any
|
||||
}>) => {
|
||||
state.askContent = action.payload.content
|
||||
},
|
||||
setAskStatus: (state, action: PayloadAction<{
|
||||
status: SummaryStatus
|
||||
}>) => {
|
||||
state.askStatus = action.payload.status
|
||||
},
|
||||
setAskError: (state, action: PayloadAction<{
|
||||
error?: string
|
||||
}>) => {
|
||||
state.askError = action.payload.error
|
||||
mergeAskInfo: (state, action: PayloadAction<PartialOfAskInfo>) => {
|
||||
const idx = findIndex(state.asks, {id: action.payload.id})
|
||||
if (idx >= 0) {
|
||||
state.asks[idx] = {
|
||||
...state.asks[idx],
|
||||
...action.payload,
|
||||
}
|
||||
}
|
||||
},
|
||||
setSegmentFold: (state, action: PayloadAction<{
|
||||
segmentStartIdx: number
|
||||
@@ -267,6 +272,12 @@ export const slice = createSlice({
|
||||
setTitle: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.title = action.payload
|
||||
},
|
||||
setCtime: (state, action: PayloadAction<number | null | undefined>) => {
|
||||
state.ctime = action.payload
|
||||
},
|
||||
setAuthor: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.author = action.payload
|
||||
},
|
||||
setInfos: (state, action: PayloadAction<any[]>) => {
|
||||
state.infos = action.payload
|
||||
},
|
||||
@@ -288,16 +299,15 @@ export const slice = createSlice({
|
||||
setFold: (state, action: PayloadAction<boolean>) => {
|
||||
state.fold = action.payload
|
||||
},
|
||||
setInputting: (state, action: PayloadAction<boolean>) => {
|
||||
state.inputting = action.payload
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export const {
|
||||
setPath,
|
||||
setUrl,
|
||||
setAskFold,
|
||||
setAskQuestion,
|
||||
setAskStatus,
|
||||
setAskError,
|
||||
setAskContent,
|
||||
setTempReady,
|
||||
setTempData,
|
||||
setUploadedTranscript,
|
||||
@@ -313,7 +323,6 @@ export const {
|
||||
setTitle,
|
||||
setSegments,
|
||||
setLastSummarizeTime,
|
||||
setPage,
|
||||
setLastTransTime,
|
||||
clearTransResults,
|
||||
addTransResults,
|
||||
@@ -323,6 +332,7 @@ export const {
|
||||
setAutoTranslate,
|
||||
setAutoScroll,
|
||||
setNoVideo,
|
||||
setReviewAction,
|
||||
setNeedScroll,
|
||||
setCurIdx,
|
||||
setEnvData,
|
||||
@@ -335,6 +345,12 @@ export const {
|
||||
setFold,
|
||||
setSearchText,
|
||||
setSearchResult,
|
||||
setInputting,
|
||||
addAskInfo,
|
||||
delAskInfo,
|
||||
mergeAskInfo,
|
||||
setCtime,
|
||||
setAuthor,
|
||||
} = slice.actions
|
||||
|
||||
export default slice.reducer
|
||||
|
33
src/typings.d.ts
vendored
@@ -1,4 +1,13 @@
|
||||
interface MethodContext {
|
||||
from: 'extension' | 'inject' | 'app'
|
||||
event: any
|
||||
tabId?: number
|
||||
// sender?: chrome.runtime.MessageSender | null
|
||||
}
|
||||
|
||||
interface EnvData {
|
||||
sidePanel?: boolean
|
||||
manualInsert?: boolean // 是否手动插入字幕列表
|
||||
autoExpand?: boolean
|
||||
flagDot?: boolean
|
||||
|
||||
@@ -40,6 +49,8 @@ interface TempData {
|
||||
curSummaryType: SummaryType
|
||||
downloadType?: string
|
||||
compact?: boolean // 是否紧凑视图
|
||||
reviewActions?: number // 点击或总结行为达到一定次数后,显示评分(一个视频最多只加1次)
|
||||
reviewed?: boolean // 是否点击过评分,undefined: 不显示;true: 已点击;false: 未点击(需要显示)
|
||||
}
|
||||
|
||||
interface TaskDef {
|
||||
@@ -105,6 +116,17 @@ interface Summary {
|
||||
content?: any
|
||||
}
|
||||
|
||||
interface AskInfo {
|
||||
id: string
|
||||
fold?: boolean
|
||||
question: string
|
||||
status: SummaryStatus
|
||||
error?: string
|
||||
content?: string
|
||||
}
|
||||
|
||||
type PartialOfAskInfo = Partial<PartOfAskInfo>
|
||||
|
||||
/**
|
||||
* 概览
|
||||
*/
|
||||
@@ -129,4 +151,13 @@ interface BriefSummary extends Summary {
|
||||
}
|
||||
|
||||
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,8 +1,10 @@
|
||||
import devData from '../data/data.json'
|
||||
import {APP_DOM_ID, CUSTOM_MODEL_TOKENS, MODEL_DEFAULT, MODEL_MAP, SUMMARIZE_TYPES} from '../const'
|
||||
import {APP_DOM_ID, CUSTOM_MODEL_TOKENS, MODEL_DEFAULT, MODEL_MAP, SUMMARIZE_TYPES} from '../consts/const'
|
||||
import {isDarkMode} from '@kky002/kky-util'
|
||||
import toast from 'react-hot-toast'
|
||||
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}`
|
||||
}
|
||||
|
||||
export const getDevData = () => {
|
||||
// add idx
|
||||
const body = devData.body.map((item, idx) => ({
|
||||
...item,
|
||||
idx,
|
||||
}))
|
||||
return {
|
||||
...devData,
|
||||
body,
|
||||
}
|
||||
}
|
||||
|
||||
export const isSummaryEmpty = (summary: Summary) => {
|
||||
if (summary.type === 'overview') {
|
||||
const content: OverviewItem[] = summary.content??[]
|
||||
@@ -88,6 +78,12 @@ export const isSummaryEmpty = (summary: Summary) => {
|
||||
} else if (summary.type === 'brief') {
|
||||
const content: string[] = summary.content??''
|
||||
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
|
||||
}
|
||||
@@ -109,6 +105,16 @@ export const getSummaryStr = (summary: Summary) => {
|
||||
summary: ''
|
||||
}
|
||||
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
|
||||
}
|
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 {uniq} from 'lodash-es'
|
||||
import {getWords, getWordsPinyin} from './pinyin_util'
|
||||
import {getWords, getWordsPinyin} from './pinyinUtil'
|
||||
|
||||
const tokenize = (maxLength: number, content: string, options?: SearchOptions) => {
|
||||
const result: string[] = []
|
@@ -1,5 +1,10 @@
|
||||
import {SyntheticEvent} from 'react'
|
||||
|
||||
export const isEdgeBrowser = () => {
|
||||
const userAgent = navigator.userAgent.toLowerCase()
|
||||
return userAgent.includes('edg/') && !userAgent.includes('edge/')
|
||||
}
|
||||
|
||||
export const formatTime = (time: number) => {
|
||||
if (!time) return '00:00'
|
||||
|
@@ -3,7 +3,11 @@ module.exports = {
|
||||
darkMode: 'class',
|
||||
content: ["./src/**/*.{js,ts,jsx,tsx}"],
|
||||
theme: {
|
||||
extend: {},
|
||||
extend: {
|
||||
fontSize: {
|
||||
xs: '13px',
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
require('tailwind-scrollbar-hide'),
|
||||
|
@@ -17,7 +17,10 @@
|
||||
"jsx": "react-jsx",
|
||||
"types": [
|
||||
"@types/chrome"
|
||||
]
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
|
@@ -6,5 +6,5 @@
|
||||
"allowSyntheticDefaultImports": 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 {visualizer} from "rollup-plugin-visualizer";
|
||||
import {crx} from '@crxjs/vite-plugin'
|
||||
import path from "path"
|
||||
// @ts-ignore
|
||||
import manifest from './manifest.json'
|
||||
import manifest from './manifest.config'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default ({mode}) => {
|
||||
const plugins = [
|
||||
react(),
|
||||
visualizer() as PluginOption,
|
||||
]
|
||||
// @ts-ignore
|
||||
if (mode === 'production_chrome') {
|
||||
plugins.push(crx({
|
||||
manifest,
|
||||
}))
|
||||
}
|
||||
export default () => {
|
||||
return defineConfig({
|
||||
base: '/',
|
||||
plugins,
|
||||
build: {
|
||||
rollupOptions: {
|
||||
input: {
|
||||
index: 'index.html',
|
||||
},
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
}
|
||||
},
|
||||
plugins: [
|
||||
react(),
|
||||
crx({
|
||||
manifest,
|
||||
}),
|
||||
visualizer() as PluginOption,
|
||||
],
|
||||
css: {
|
||||
modules: {
|
||||
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==
|