You've already forked bilibili-subtitle
Compare commits
25 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
af80b8a51c | ||
![]() |
404ab904cc | ||
![]() |
d53884269a | ||
![]() |
e4693cde6a | ||
![]() |
fea22fae61 | ||
![]() |
d5b5b5d374 | ||
![]() |
17d4e60de0 | ||
![]() |
2cd633cbd4 | ||
![]() |
3ad198948f | ||
![]() |
774cc2726d | ||
![]() |
4765244638 | ||
![]() |
b0107c4959 | ||
![]() |
e900b11f05 | ||
![]() |
194df8525c | ||
![]() |
28bb3dbb96 | ||
![]() |
640f6d89fd | ||
![]() |
338e3145f2 | ||
![]() |
e2121e83bd | ||
![]() |
7583b05289 | ||
![]() |
ae60303a15 | ||
![]() |
5bcedf0c9d | ||
![]() |
d4e5e407a4 | ||
![]() |
ce2a2da6f5 | ||
![]() |
368f5d721c | ||
![]() |
21e2ca958c |
@@ -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"
|
||||
|
10
README.md
10
README.md
@@ -21,7 +21,6 @@
|
||||
|
||||
- [chrome商店](https://chrome.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp)
|
||||
- [edge商店](https://microsoftedge.microsoft.com/addons/detail/lignnlhlpiefmcjkdkmfjdckhlaiajan)
|
||||
- [firefox商店](https://addons.mozilla.org/zh-CN/firefox/addon/bilibili-subtitle)
|
||||
|
||||
## 使用说明
|
||||
|
||||
@@ -46,13 +45,14 @@ github: [IndieKKY](https://github.com/IndieKKY)
|
||||
node版本:18.15.0
|
||||
包管理器:pnpm
|
||||
|
||||
- 本地调试:`pnpm run dev`,然后加载`dist`目录。
|
||||
- 打生产包:`pnpm run build`,然后加载`dist`目录。
|
||||
- 本地调试:`pnpm run dev`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
|
||||
- 打生产包:`pnpm run build`,然后浏览器扩展管理页面,开启开发者模式,再加载已解压的扩展程序,选择`dist`目录。
|
||||
|
||||
注:`./push.sh`是作者自用脚本,可以忽略。
|
||||
|
||||
提示:本地edge开发调试可能有问题,会报csp错误!本地开发调试推荐用chrome。
|
||||
构建后应该正常,关键是fix.cjs里将use_dynamic_url设置为false的这个操作。
|
||||
提示:最新版浏览器安全方面有更新,开发调试可能有问题,会报csp错误!
|
||||
暂时的解决办法是`pnpm run dev`运行起来后,手动将`dist/manifest.json`文件里的web_accessible_resources里的use_dynamic_url都修改为false,然后浏览器扩展管理页面点击重载一下,就能正常(是@crxjs/vite-plugin依赖的问题,这个依赖很长时间没更新了,这个bug也没修复,暂时没发现更好的解决办法)。
|
||||
构建后正常,关键是fix.cjs里将use_dynamic_url设置为false的这个操作。
|
||||
|
||||
## 贡献指南
|
||||
|
||||
|
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "bilibili-subtitle",
|
||||
"version": "1.11.13",
|
||||
"version": "1.14.0",
|
||||
"type": "module",
|
||||
"description": "哔哩哔哩字幕列表",
|
||||
"main": "index.js",
|
||||
@@ -15,6 +15,7 @@
|
||||
"dependencies": {
|
||||
"@crxjs/vite-plugin": "^1.0.14",
|
||||
"@kky002/kky-hooks": "^1.2.1",
|
||||
"@kky002/kky-message": "^0.2.1",
|
||||
"@kky002/kky-ui": "^1.0.9",
|
||||
"@kky002/kky-util": "^1.13.13",
|
||||
"@logto/react": "1.0.0-beta.13",
|
||||
|
57
pnpm-lock.yaml
generated
57
pnpm-lock.yaml
generated
@@ -14,6 +14,9 @@ importers:
|
||||
'@kky002/kky-hooks':
|
||||
specifier: ^1.2.1
|
||||
version: 1.2.1
|
||||
'@kky002/kky-message':
|
||||
specifier: ^0.2.1
|
||||
version: 0.2.1
|
||||
'@kky002/kky-ui':
|
||||
specifier: ^1.0.9
|
||||
version: 1.0.9
|
||||
@@ -310,6 +313,10 @@ packages:
|
||||
resolution: {integrity: sha512-eR8Lo9hnDS7tqkO7NsV+mKvCmv5boaXFSZ70DnfhcgiEne8hv9oCEd36Klw74EtizEqLsy4YnW8UWwpBVolHZA==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@babel/runtime@7.26.9':
|
||||
resolution: {integrity: sha512-aA63XwOkcl4xxQa3HjPMqOP6LiK0ZDv3mUPYEFXkpHbaFjtGggE1A61FjFzJnB+p7/oy2gA8E+rcBNl/zC1tMg==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@babel/template@7.25.7':
|
||||
resolution: {integrity: sha512-wRwtAgI3bAS+JGU2upWNL9lSlDcRCqD05BZ1n3X2ONLH1WilFP6O1otQjeMK/1g0pvYcXC7b/qVUB1keofjtZA==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
@@ -390,6 +397,9 @@ packages:
|
||||
'@kky002/kky-hooks@1.2.1':
|
||||
resolution: {integrity: sha512-AJM2gm75TtkZqOPd/WX0+4h/dfjSb8HlDQLwAJsYIHRNw8MQUKu32Ih6OxhKL2l9pdPsuj+S9/lBc4Cwu4tP+Q==}
|
||||
|
||||
'@kky002/kky-message@0.2.1':
|
||||
resolution: {integrity: sha512-LIg4T89t3TmjflepZeOPH/OMN3xxwLE0AxnfDycTlCpjHAiuvm/Aj3IIHLfzqbz5azRaGNu2ZcUsrUdb2jAtiQ==}
|
||||
|
||||
'@kky002/kky-ui@1.0.9':
|
||||
resolution: {integrity: sha512-pepfRcLfC1eIQ1lsSJLWNr4PgdLqFLuvQMlitJy7W668yZ7qu8yAHSjg8A20R7HB4mFkJ+B96WETalOar1e/kA==}
|
||||
|
||||
@@ -654,6 +664,12 @@ packages:
|
||||
peerDependencies:
|
||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0
|
||||
|
||||
ahooks@3.8.4:
|
||||
resolution: {integrity: sha512-39wDEw2ZHvypaT14EpMMk4AzosHWt0z9bulY0BeDsvc9PqJEV+Kjh/4TZfftSsotBMq52iYIOFPd3PR56e0ZJg==}
|
||||
engines: {node: '>=8.0.0'}
|
||||
peerDependencies:
|
||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0
|
||||
|
||||
ajv@6.12.6:
|
||||
resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==}
|
||||
|
||||
@@ -1560,6 +1576,10 @@ packages:
|
||||
js-cookie@2.2.1:
|
||||
resolution: {integrity: sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ==}
|
||||
|
||||
js-cookie@3.0.5:
|
||||
resolution: {integrity: sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==}
|
||||
engines: {node: '>=14'}
|
||||
|
||||
js-search@2.0.0:
|
||||
resolution: {integrity: sha512-lJ8KzjlwcelIWuAdKyzsXv45W6OIwRpayzc7XmU8mzgWadg5UVOKVmnq/tXudddEB9Ceic3tVaGu6QOK/eebhg==}
|
||||
|
||||
@@ -2048,6 +2068,9 @@ packages:
|
||||
react-fast-compare@3.2.0:
|
||||
resolution: {integrity: sha512-rtGImPZ0YyLrscKI9xTpV8psd6I8VAtjKCzQDlzyDvqJA8XOW78TXYQwNRNd8g8JZnDu8q9Fu/1v4HPAVwVdHA==}
|
||||
|
||||
react-fast-compare@3.2.2:
|
||||
resolution: {integrity: sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==}
|
||||
|
||||
react-hot-toast@2.4.0:
|
||||
resolution: {integrity: sha512-qnnVbXropKuwUpriVVosgo8QrB+IaPJCpL8oBI6Ov84uvHZ5QQcTp2qg6ku2wNfgJl6rlQXJIQU5q+5lmPOutA==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -2135,6 +2158,9 @@ packages:
|
||||
regenerator-runtime@0.13.9:
|
||||
resolution: {integrity: sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==}
|
||||
|
||||
regenerator-runtime@0.14.1:
|
||||
resolution: {integrity: sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==}
|
||||
|
||||
regexp.prototype.flags@1.4.3:
|
||||
resolution: {integrity: sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -2696,6 +2722,10 @@ snapshots:
|
||||
dependencies:
|
||||
regenerator-runtime: 0.13.9
|
||||
|
||||
'@babel/runtime@7.26.9':
|
||||
dependencies:
|
||||
regenerator-runtime: 0.14.1
|
||||
|
||||
'@babel/template@7.25.7':
|
||||
dependencies:
|
||||
'@babel/code-frame': 7.25.7
|
||||
@@ -2816,6 +2846,14 @@ snapshots:
|
||||
lodash-es: 4.17.21
|
||||
react: 18.2.0
|
||||
|
||||
'@kky002/kky-message@0.2.1':
|
||||
dependencies:
|
||||
'@kky002/kky-util': 1.13.13
|
||||
ahooks: 3.8.4(react@18.2.0)
|
||||
lodash-es: 4.17.21
|
||||
qs: 6.11.0
|
||||
react: 18.2.0
|
||||
|
||||
'@kky002/kky-ui@1.0.9':
|
||||
dependencies:
|
||||
react: 18.2.0
|
||||
@@ -3138,6 +3176,19 @@ snapshots:
|
||||
screenfull: 5.2.0
|
||||
tslib: 2.5.0
|
||||
|
||||
ahooks@3.8.4(react@18.2.0):
|
||||
dependencies:
|
||||
'@babel/runtime': 7.26.9
|
||||
dayjs: 1.11.13
|
||||
intersection-observer: 0.12.2
|
||||
js-cookie: 3.0.5
|
||||
lodash: 4.17.21
|
||||
react: 18.2.0
|
||||
react-fast-compare: 3.2.2
|
||||
resize-observer-polyfill: 1.5.1
|
||||
screenfull: 5.2.0
|
||||
tslib: 2.5.0
|
||||
|
||||
ajv@6.12.6:
|
||||
dependencies:
|
||||
fast-deep-equal: 3.1.3
|
||||
@@ -4076,6 +4127,8 @@ snapshots:
|
||||
|
||||
js-cookie@2.2.1: {}
|
||||
|
||||
js-cookie@3.0.5: {}
|
||||
|
||||
js-search@2.0.0: {}
|
||||
|
||||
js-tokens@4.0.0: {}
|
||||
@@ -4698,6 +4751,8 @@ snapshots:
|
||||
|
||||
react-fast-compare@3.2.0: {}
|
||||
|
||||
react-fast-compare@3.2.2: {}
|
||||
|
||||
react-hot-toast@2.4.0(csstype@3.1.2)(react-dom@18.2.0(react@18.2.0))(react@18.2.0):
|
||||
dependencies:
|
||||
goober: 2.1.12(csstype@3.1.2)
|
||||
@@ -4790,6 +4845,8 @@ snapshots:
|
||||
|
||||
regenerator-runtime@0.13.9: {}
|
||||
|
||||
regenerator-runtime@0.14.1: {}
|
||||
|
||||
regexp.prototype.flags@1.4.3:
|
||||
dependencies:
|
||||
call-bind: 1.0.2
|
||||
|
@@ -8,7 +8,7 @@ import OptionsPage from './pages/OptionsPage'
|
||||
import {handleJson} from '@kky002/kky-util'
|
||||
import {useLocalStorage} from '@kky002/kky-hooks'
|
||||
import {Toaster} from 'react-hot-toast'
|
||||
import useMessagingService from './hooks/useMessageService'
|
||||
import useMessageService from './hooks/useMessageService'
|
||||
import MainPage from './pages/MainPage'
|
||||
|
||||
function App() {
|
||||
@@ -44,7 +44,7 @@ function App() {
|
||||
useLocalStorage<TempData>('chrome_client', STORAGE_TEMP, savedTempData, onLoadTemp)
|
||||
|
||||
// services
|
||||
useMessagingService()
|
||||
useMessageService()
|
||||
|
||||
return <div>
|
||||
<Toaster position={path === 'app'?'bottom-center':'top-center'}/>
|
||||
|
@@ -1,8 +1,8 @@
|
||||
import {v4} from 'uuid'
|
||||
import {handleTask, initTaskService, tasksMap} from './taskService'
|
||||
import { STORAGE_ENV} from '@/consts/const'
|
||||
import ExtensionMessaging from '@/messaging/layer2/ExtensionMessaging'
|
||||
import { TAG_TARGET_INJECT } from '@/messaging/const'
|
||||
import { DEFAULT_USE_PORT, STORAGE_ENV} from '@/consts/const'
|
||||
import { AllExtensionMessages } from '@/message-typings'
|
||||
import { ExtensionMessaging, TAG_TARGET_INJECT } from '@kky002/kky-message'
|
||||
|
||||
const setBadgeOk = async (tabId: number, ok: boolean) => {
|
||||
await chrome.action.setBadgeText({
|
||||
@@ -34,6 +34,9 @@ const methods: {
|
||||
CLOSE_SIDE_PANEL: async (params, context) => {
|
||||
closeSidePanel()
|
||||
},
|
||||
GET_TAB_ID: async (params, context) => {
|
||||
return context.tabId
|
||||
},
|
||||
ADD_TASK: async (params, context) => {
|
||||
// 新建任务
|
||||
const task: Task = {
|
||||
@@ -75,7 +78,7 @@ const methods: {
|
||||
},
|
||||
}
|
||||
// 初始化backgroundMessage
|
||||
const extensionMessaging = new ExtensionMessaging()
|
||||
const extensionMessaging = new ExtensionMessaging(DEFAULT_USE_PORT)
|
||||
extensionMessaging.init(methods)
|
||||
|
||||
chrome.runtime.onMessage.addListener((event: any, sender: chrome.runtime.MessageSender, sendResponse: (result: any) => void) => {
|
||||
@@ -89,14 +92,12 @@ chrome.runtime.onMessage.addListener((event: any, sender: chrome.runtime.Message
|
||||
return true
|
||||
} else if (event.type === 'syncSet') { // sync.set
|
||||
chrome.storage.sync.set(event.items).catch(console.error)
|
||||
return
|
||||
} else if (event.type === 'syncRemove') { // sync.remove
|
||||
chrome.storage.sync.remove(event.keys).catch(console.error)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
//点击扩展图标
|
||||
// 点击扩展图标
|
||||
chrome.action.onClicked.addListener(async (tab) => {
|
||||
chrome.storage.sync.get(STORAGE_ENV, (envDatas) => {
|
||||
const envDataStr = envDatas[STORAGE_ENV]
|
||||
@@ -115,7 +116,7 @@ chrome.action.onClicked.addListener(async (tab) => {
|
||||
})
|
||||
} else {
|
||||
closeSidePanel()
|
||||
extensionMessaging.broadcastMessageExact([tab.id!], [TAG_TARGET_INJECT], 'TOGGLE_DISPLAY').catch(console.error)
|
||||
extensionMessaging.sendMessage(false, tab.id!, TAG_TARGET_INJECT, 'TOGGLE_DISPLAY').catch(console.error)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
@@ -7,13 +7,21 @@ const getServerUrl = (serverUrl?: string) => {
|
||||
if (serverUrl.endsWith('/')) {
|
||||
serverUrl = serverUrl.slice(0, -1)
|
||||
}
|
||||
//如果serverUrl以https://generativelanguage.googleapis.com开头,则直接返回
|
||||
if (serverUrl.toLowerCase().startsWith('https://generativelanguage.googleapis.com')) {
|
||||
return serverUrl
|
||||
}
|
||||
//如果serverUrl不以/vxxx结尾,则添加/v1
|
||||
if (!/\/v\d+$/.test(serverUrl.toLowerCase())) {
|
||||
serverUrl += '/v1'
|
||||
}
|
||||
return serverUrl
|
||||
}
|
||||
|
||||
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',
|
||||
@@ -28,16 +36,3 @@ export const handleChatCompleteTask = async (task: Task) => {
|
||||
throw new Error(`${task.resp.error.code as string??''} ${task.resp.error.message as string ??''}`)
|
||||
}
|
||||
}
|
||||
|
||||
export const handleGeminiChatCompleteTask = async (task: Task) => {
|
||||
const data = task.def.data
|
||||
const resp = await fetch('https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-goog-api-key': task.def.extra.geminiApiKey,
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
task.resp = await resp.json()
|
||||
}
|
||||
|
@@ -1,5 +1,5 @@
|
||||
import {TASK_EXPIRE_TIME} from '../consts/const'
|
||||
import {handleChatCompleteTask, handleGeminiChatCompleteTask} from './openaiService'
|
||||
import {handleChatCompleteTask} from './openaiService'
|
||||
|
||||
export const tasksMap = new Map<string, Task>()
|
||||
|
||||
@@ -11,9 +11,6 @@ export const handleTask = async (task: Task) => {
|
||||
case 'chatComplete':
|
||||
await handleChatCompleteTask(task)
|
||||
break
|
||||
case 'geminiChatComplete':
|
||||
await handleGeminiChatCompleteTask(task)
|
||||
break
|
||||
default:
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
throw new Error(`任务类型不支持: ${task.def.type}`)
|
||||
|
@@ -1,14 +1,12 @@
|
||||
import React from 'react';
|
||||
import { useAppSelector } from '../hooks/redux';
|
||||
import { openOptionsPage } from '../utils/chromeUtils';
|
||||
import React from 'react'
|
||||
import { useAppSelector } from '../hooks/redux'
|
||||
import { openOptionsPage } from '../utils/chromeUtils'
|
||||
|
||||
const ApiKeyReminder: React.FC = () => {
|
||||
const apiKey = useAppSelector(state => state.env.envData.apiKey);
|
||||
const geminiApiKey = useAppSelector(state => state.env.envData.geminiApiKey);
|
||||
const aiType = useAppSelector(state => state.env.envData.aiType);
|
||||
const apiKey = useAppSelector(state => state.env.envData.apiKey)
|
||||
|
||||
if ((aiType === 'gemini' && geminiApiKey) || (aiType !== 'gemini' && apiKey)) {
|
||||
return null;
|
||||
if (apiKey) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -21,7 +19,7 @@ const ApiKeyReminder: React.FC = () => {
|
||||
设置 →
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
)
|
||||
}
|
||||
|
||||
export default ApiKeyReminder;
|
||||
export default ApiKeyReminder
|
||||
|
@@ -18,7 +18,7 @@ const Ask = (props: {
|
||||
const {addAskTask} = useTranslate()
|
||||
|
||||
const onRegenerate = useCallback(() => {
|
||||
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (apiKey) {
|
||||
if (segments != null && segments.length > 0) {
|
||||
addAskTask(ask.id, segments[0], ask.question).catch(console.error)
|
||||
@@ -26,7 +26,7 @@ const Ask = (props: {
|
||||
} else {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
}
|
||||
}, [addAskTask, ask.id, ask.question, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
|
||||
}, [addAskTask, ask.id, ask.question, envData.apiKey, segments])
|
||||
|
||||
const onAskFold = useCallback(() => {
|
||||
dispatch(mergeAskInfo({
|
||||
|
@@ -25,6 +25,7 @@ import toast from 'react-hot-toast'
|
||||
import SegmentCard from './SegmentCard'
|
||||
import {
|
||||
ASK_ENABLED_DEFAULT,
|
||||
DEFAULT_USE_PORT,
|
||||
HEADER_HEIGHT,
|
||||
PAGE_SETTINGS,
|
||||
SEARCH_BAR_HEIGHT,
|
||||
@@ -39,7 +40,7 @@ import Ask from './Ask'
|
||||
import { v4 } from 'uuid'
|
||||
import RateExtension from '../components/RateExtension'
|
||||
import ApiKeyReminder from './ApiKeyReminder'
|
||||
import useMessaging from '@/messaging/layer2/useMessaging'
|
||||
import { useMessaging } from '@kky002/kky-message'
|
||||
|
||||
const Body = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
@@ -66,7 +67,7 @@ const Body = () => {
|
||||
// const fontSize = useAppSelector(state => state.env.envData.fontSize)
|
||||
const searchText = useAppSelector(state => state.env.searchText)
|
||||
const asks = useAppSelector(state => state.env.asks)
|
||||
const {disconnected} = useMessaging()
|
||||
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))
|
||||
@@ -104,7 +105,7 @@ const Body = () => {
|
||||
}, [dispatch])
|
||||
|
||||
const onSummarizeAll = useCallback(() => {
|
||||
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (!apiKey) {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
return
|
||||
@@ -126,7 +127,7 @@ const Body = () => {
|
||||
}
|
||||
toast.success(`已添加${segments_.length}个总结任务!`)
|
||||
}
|
||||
}, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
|
||||
}, [addSummarizeTask, curSummaryType, envData.apiKey, segments])
|
||||
|
||||
const onFoldAll = useCallback(() => {
|
||||
dispatch(setFoldAll(!foldAll))
|
||||
@@ -145,13 +146,13 @@ const Body = () => {
|
||||
}, [asks, dispatch, foldAll, segments])
|
||||
|
||||
const toggleAutoTranslateCallback = useCallback(() => {
|
||||
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (apiKey) {
|
||||
dispatch(setAutoTranslate(!autoTranslate))
|
||||
} else {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
}
|
||||
}, [autoTranslate, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey])
|
||||
}, [autoTranslate, dispatch, envData.apiKey])
|
||||
|
||||
const onEnableAutoScroll = useCallback(() => {
|
||||
dispatch(setAutoScroll(true))
|
||||
@@ -184,7 +185,7 @@ const Body = () => {
|
||||
|
||||
const onAsk = useCallback(() => {
|
||||
if ((envData.askEnabled ?? ASK_ENABLED_DEFAULT) && searchText) {
|
||||
const apiKey = envData.aiType === 'gemini' ? envData.geminiApiKey : envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (apiKey) {
|
||||
if (segments != null && segments.length > 0) {
|
||||
const id = v4()
|
||||
@@ -200,7 +201,7 @@ const Body = () => {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
}
|
||||
}
|
||||
}, [addAskTask, dispatch, envData.aiType, envData.apiKey, envData.askEnabled, envData.geminiApiKey, searchText, segments])
|
||||
}, [addAskTask, dispatch, envData.apiKey, envData.askEnabled, searchText, segments])
|
||||
|
||||
// service
|
||||
useKeyService()
|
||||
|
@@ -1,8 +1,8 @@
|
||||
import { useAppSelector } from '@/hooks/redux';
|
||||
import React from 'react';
|
||||
import { useAppSelector } from '@/hooks/redux'
|
||||
import React from 'react'
|
||||
|
||||
const DebateChat: React.FC<DebateProps> = ({ messages }) => {
|
||||
const fontSize = useAppSelector(state => state.env.envData.fontSize)
|
||||
const fontSize = useAppSelector(state => state.env.envData.fontSize)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
@@ -37,7 +37,7 @@ const DebateChat: React.FC<DebateProps> = ({ messages }) => {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
)
|
||||
}
|
||||
|
||||
export default DebateChat;
|
||||
export default DebateChat
|
||||
|
@@ -1,8 +1,6 @@
|
||||
import React, {MouseEvent, useCallback, useContext, useRef, useState} from 'react'
|
||||
import {MouseEvent, useCallback, useContext, useRef, useState} from 'react'
|
||||
import {useClickAway} from 'ahooks'
|
||||
import {
|
||||
AiFillWechat,
|
||||
BsFillChatDotsFill,
|
||||
FiMoreVertical,
|
||||
ImDownload3,
|
||||
IoMdSettings,
|
||||
@@ -18,8 +16,8 @@ import {formatSrtTime, formatTime, formatVttTime} from '../utils/util'
|
||||
import {downloadText, openUrl} from '@kky002/kky-util'
|
||||
import toast from 'react-hot-toast'
|
||||
import {getSummarize} from '../utils/bizUtil'
|
||||
import { useMessage } from '@/hooks/message'
|
||||
import dayjs from 'dayjs';
|
||||
import dayjs from 'dayjs'
|
||||
import { useMessage } from '@/hooks/useMessageService'
|
||||
|
||||
interface Props {
|
||||
placement: Placement
|
||||
@@ -70,11 +68,11 @@ const MoreBtn = (props: Props) => {
|
||||
const segments = useAppSelector(state => state.env.segments)
|
||||
const url = useAppSelector(state => state.env.url)
|
||||
const title = useAppSelector(state => state.env.title)
|
||||
const ctime = useAppSelector(state => state.env.ctime) //时间戳,单位s
|
||||
const ctime = useAppSelector(state => state.env.ctime) // 时间戳,单位s
|
||||
const author = useAppSelector(state => state.env.author)
|
||||
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
|
||||
|
||||
const {sendInject} = useMessage()
|
||||
const {sendInject} = useMessage(!!envData.sidePanel)
|
||||
|
||||
const downloadCallback = useCallback((download: boolean) => {
|
||||
if (data == null) {
|
||||
@@ -83,7 +81,7 @@ const MoreBtn = (props: Props) => {
|
||||
|
||||
let fileName = title
|
||||
let s, suffix
|
||||
let time = ctime ? dayjs(ctime * 1000).format('YYYY-MM-DD HH:mm:ss') : '' // 2024-05-01 12:00:00
|
||||
const time = ctime ? dayjs(ctime * 1000).format('YYYY-MM-DD HH:mm:ss') : '' // 2024-05-01 12:00:00
|
||||
if (!downloadType || downloadType === 'text') {
|
||||
s = `${title??'无标题'}\n${url??'无链接'}\n${author??'无作者'} ${time}\n\n`
|
||||
for (const item of data.body) {
|
||||
@@ -164,11 +162,11 @@ const MoreBtn = (props: Props) => {
|
||||
}).catch(console.error)
|
||||
}
|
||||
setMoreVisible(false)
|
||||
}, [curSummaryType, data, downloadType, segments, title, url])
|
||||
}, [author, ctime, curSummaryType, data, downloadType, segments, title, url])
|
||||
|
||||
const downloadAudioCallback = useCallback(() => {
|
||||
sendInject('DOWNLOAD_AUDIO', {})
|
||||
}, [])
|
||||
sendInject(null, 'DOWNLOAD_AUDIO', {})
|
||||
}, [sendInject])
|
||||
|
||||
const selectCallback = useCallback((e: any) => {
|
||||
dispatch(setTempData({
|
||||
|
@@ -1,14 +1,14 @@
|
||||
import React, { useState } from 'react';
|
||||
import { FaStar } from 'react-icons/fa';
|
||||
import { IoMdClose } from 'react-icons/io';
|
||||
import { setTempData } from '../redux/envReducer';
|
||||
import { useAppDispatch, useAppSelector } from '../hooks/redux';
|
||||
import { openUrl } from '@kky002/kky-util';
|
||||
import { isEdgeBrowser } from '../utils/util';
|
||||
import React, { useState } from 'react'
|
||||
import { FaStar } from 'react-icons/fa'
|
||||
import { IoMdClose } from 'react-icons/io'
|
||||
import { setTempData } from '../redux/envReducer'
|
||||
import { useAppDispatch, useAppSelector } from '../hooks/redux'
|
||||
import { openUrl } from '@kky002/kky-util'
|
||||
import { isEdgeBrowser } from '../utils/util'
|
||||
|
||||
const RateExtension: React.FC = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const [isHovered, setIsHovered] = useState(false)
|
||||
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
|
||||
|
||||
const handleRateClick = () => {
|
||||
@@ -21,9 +21,9 @@ const RateExtension: React.FC = () => {
|
||||
} else {
|
||||
openUrl('https://chromewebstore.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp/reviews')
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (reviewed === true || reviewed === undefined) return null;
|
||||
if (reviewed === true || reviewed === undefined) return null
|
||||
|
||||
return (
|
||||
<div className="relative bg-gradient-to-r from-primary to-secondary text-primary-content p-4 rounded-lg shadow-lg text-sm transition-all duration-300 ease-in-out hover:shadow-xl">
|
||||
@@ -52,7 +52,7 @@ const RateExtension: React.FC = () => {
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
)
|
||||
}
|
||||
|
||||
export default RateExtension;
|
||||
export default RateExtension
|
||||
|
@@ -1,9 +1,9 @@
|
||||
import React, {MutableRefObject, useCallback, useEffect, useMemo, useRef} from 'react'
|
||||
import {MutableRefObject, useCallback, useEffect, useMemo, useRef} from 'react'
|
||||
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||
import {setFloatKeyPointsSegIdx, setSegmentFold, setTempData} from '../redux/envReducer'
|
||||
import {setFloatKeyPointsSegIdx, setNeedScroll, setSegmentFold, setTempData} from '../redux/envReducer'
|
||||
import classNames from 'classnames'
|
||||
import {FaClipboardList, FaComments} from 'react-icons/fa'
|
||||
import {PAGE_MAIN, PAGE_SETTINGS, SUMMARIZE_THRESHOLD, SUMMARIZE_TYPES} from '../consts/const'
|
||||
import {SUMMARIZE_THRESHOLD, SUMMARIZE_TYPES} from '../consts/const'
|
||||
import useTranslate from '../hooks/useTranslate'
|
||||
import {BsDashSquare, BsPlusSquare, CgFileDocument, FaQuestion, GrOverview, RiFileCopy2Line} from 'react-icons/all'
|
||||
import toast from 'react-hot-toast'
|
||||
@@ -13,6 +13,7 @@ import SegmentItem from './SegmentItem'
|
||||
import {stopPopFunc} from '../utils/util'
|
||||
import useSubtitle from '../hooks/useSubtitle'
|
||||
import DebateChat from './DebateChat'
|
||||
import { RootState } from '../store'
|
||||
|
||||
const SummarizeItemOverview = (props: {
|
||||
segment: Segment
|
||||
@@ -25,7 +26,7 @@ const SummarizeItemOverview = (props: {
|
||||
|
||||
const {move} = useSubtitle()
|
||||
const time = parseStrTimeToSeconds(overviewItem.time)
|
||||
const currentTime = useAppSelector(state => state.env.currentTime)
|
||||
const currentTime = useAppSelector((state: RootState) => state.currentTime.currentTime)
|
||||
const isIn = useMemo(() => {
|
||||
if (currentTime != null) {
|
||||
// check in current segment
|
||||
@@ -73,13 +74,13 @@ const Summarize = (props: {
|
||||
const {addSummarizeTask} = useTranslate()
|
||||
|
||||
const onGenerate = useCallback(() => {
|
||||
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
|
||||
const apiKey = envData.apiKey
|
||||
if (apiKey) {
|
||||
addSummarizeTask(curSummaryType, segment).catch(console.error)
|
||||
} else {
|
||||
toast.error('请先在选项页面设置ApiKey!')
|
||||
}
|
||||
}, [addSummarizeTask, curSummaryType, envData.aiType, envData.apiKey, envData.geminiApiKey, segment])
|
||||
}, [addSummarizeTask, curSummaryType, envData.apiKey, segment])
|
||||
|
||||
const onCopy = useCallback(() => {
|
||||
if (summary != null) {
|
||||
@@ -158,6 +159,7 @@ const SegmentCard = (props: {
|
||||
}
|
||||
return undefined
|
||||
}, [curSummaryType, segment.summaries])
|
||||
const {move} = useSubtitle()
|
||||
|
||||
const onFold = useCallback(() => {
|
||||
dispatch(setSegmentFold({
|
||||
@@ -166,6 +168,21 @@ const SegmentCard = (props: {
|
||||
}))
|
||||
}, [dispatch, segment.fold, segment.startIdx])
|
||||
|
||||
const onChapterClick = useCallback(() => {
|
||||
if (segment.items && segment.items.length > 0) {
|
||||
// 展开当前segment
|
||||
if (segment.fold) {
|
||||
dispatch(setSegmentFold({
|
||||
segmentStartIdx: segment.startIdx,
|
||||
fold: false
|
||||
}))
|
||||
}
|
||||
|
||||
const firstItem = segment.items[0]
|
||||
move(firstItem.from, false)
|
||||
}
|
||||
}, [dispatch, move, segment.fold, segment.items, segment.startIdx])
|
||||
|
||||
// 检测设置floatKeyPointsSegIdx
|
||||
useEffect(() => {
|
||||
if (summarizeFloat) { // 已启用
|
||||
@@ -211,6 +228,10 @@ const SegmentCard = (props: {
|
||||
|
||||
return <div
|
||||
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')}>
|
||||
{/* 章节标题 */}
|
||||
{segment.chapterTitle && <div className='text-center py-1 px-2 bg-primary/10 rounded text-sm font-semibold text-primary border-b border-primary/20 cursor-pointer hover:bg-primary/20 transition-colors' onClick={onChapterClick}>
|
||||
{segment.chapterTitle}
|
||||
</div>}
|
||||
<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'>
|
||||
|
@@ -1,3 +1,5 @@
|
||||
export const DEFAULT_USE_PORT = false
|
||||
|
||||
export const EVENT_EXPAND = 'expand'
|
||||
|
||||
export const APP_DOM_ID = 'bilibili-subtitle'
|
||||
@@ -186,7 +188,7 @@ Provide an example to illustrate the expected output:
|
||||
]
|
||||
\`\`\`
|
||||
`,
|
||||
[PROMPT_TYPE_SUMMARIZE_DEBATE]: `You are a helpful assistant skilled at generating debates based on video subtitles.
|
||||
[PROMPT_TYPE_SUMMARIZE_DEBATE]: `You are a helpful assistant skilled at generating debates based on video subtitles.
|
||||
|
||||
## Context
|
||||
|
||||
@@ -266,6 +268,7 @@ export const SUMMARIZE_LANGUAGE_DEFAULT = 'cn'
|
||||
export const SUMMARIZE_ALL_THRESHOLD = 5
|
||||
export const ASK_ENABLED_DEFAULT = true
|
||||
export const DEFAULT_SERVER_URL_OPENAI = 'https://api.openai.com'
|
||||
export const DEFAULT_SERVER_URL_GEMINI = 'https://generativelanguage.googleapis.com/v1beta/openai/'
|
||||
export const CUSTOM_MODEL_TOKENS = 16385
|
||||
|
||||
export const MODEL_TIP = '推荐gpt-4o-mini,能力强,价格低,token上限大'
|
||||
@@ -281,7 +284,6 @@ export const MODELS = [{
|
||||
code: 'custom',
|
||||
name: '自定义',
|
||||
}]
|
||||
export const GEMINI_TOKENS = 32768
|
||||
export const MODEL_DEFAULT = MODELS[0].code
|
||||
export const MODEL_MAP: {[key: string]: typeof MODELS[number]} = {}
|
||||
for (const model of MODELS) {
|
||||
|
@@ -1,3 +0,0 @@
|
||||
import useMessaging from "@/messaging/layer2/useMessaging";
|
||||
|
||||
export const useMessage = useMessaging<AllExtensionMessages, AllInjectMessages>
|
@@ -1,15 +1,17 @@
|
||||
import { setAuthor, setCtime, setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
|
||||
import { useMemo } from 'react'
|
||||
import { useAppDispatch } from './redux'
|
||||
import useMessagingService from '@/messaging/layer2/useMessagingService'
|
||||
import { setAuthor, setChapters, setCtime, setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
|
||||
import { useAppDispatch, useAppSelector } from './redux'
|
||||
import { AllAPPMessages, AllExtensionMessages, AllInjectMessages } from '@/message-typings'
|
||||
import { useMessaging, useMessagingService } from '@kky002/kky-message'
|
||||
import { useMemoizedFn } from 'ahooks'
|
||||
|
||||
const useMessageService = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
//methods
|
||||
const methods: {
|
||||
const envData = useAppSelector((state) => state.env.envData)
|
||||
|
||||
// methods
|
||||
const methodsFunc: () => {
|
||||
[K in AllAPPMessages['method']]: (params: Extract<AllAPPMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
|
||||
} = useMemo(() => ({
|
||||
} = useMemoizedFn(() => ({
|
||||
SET_INFOS: async (params, context: MethodContext) => {
|
||||
dispatch(setInfos(params.infos))
|
||||
dispatch(setCurInfo(undefined))
|
||||
@@ -17,6 +19,7 @@ const useMessageService = () => {
|
||||
dispatch(setData(undefined))
|
||||
},
|
||||
SET_VIDEO_INFO: async (params, context: MethodContext) => {
|
||||
dispatch(setChapters(params.chapters))
|
||||
dispatch(setInfos(params.infos))
|
||||
dispatch(setUrl(params.url))
|
||||
dispatch(setTitle(params.title))
|
||||
@@ -24,9 +27,10 @@ const useMessageService = () => {
|
||||
dispatch(setAuthor(params.author))
|
||||
console.debug('video title: ', params.title)
|
||||
},
|
||||
}), [dispatch])
|
||||
}))
|
||||
|
||||
useMessagingService(methods)
|
||||
useMessagingService(!!envData.sidePanel, methodsFunc)
|
||||
}
|
||||
|
||||
export default useMessageService
|
||||
export default useMessageService
|
||||
export const useMessage = useMessaging<AllExtensionMessages, AllInjectMessages>
|
||||
|
@@ -1,25 +1,26 @@
|
||||
import {useAppDispatch, useAppSelector} from './redux'
|
||||
import React, {useCallback} from 'react'
|
||||
import {setNeedScroll, setReviewAction, setTempData} from '../redux/envReducer'
|
||||
import { useMessage } from './message'
|
||||
import { useMessage } from './useMessageService'
|
||||
const useSubtitle = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
|
||||
const reviewAction = useAppSelector(state => state.env.reviewAction)
|
||||
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
|
||||
const {sendInject} = useMessage()
|
||||
|
||||
const move = useCallback((time: number, togglePause: boolean) => {
|
||||
sendInject('MOVE', {time, togglePause})
|
||||
const {sendInject} = useMessage(!!envData.sidePanel)
|
||||
|
||||
//review action
|
||||
const move = useCallback((time: number, togglePause: boolean) => {
|
||||
sendInject(null, 'MOVE', {time, togglePause})
|
||||
|
||||
// review action
|
||||
if (reviewed === undefined && !reviewAction) {
|
||||
dispatch(setReviewAction(true))
|
||||
dispatch(setTempData({
|
||||
reviewActions: (reviewActions ?? 0) + 1
|
||||
}))
|
||||
}
|
||||
}, [dispatch, reviewAction, reviewActions, reviewed])
|
||||
}, [dispatch, reviewAction, reviewActions, reviewed, sendInject])
|
||||
|
||||
const scrollIntoView = useCallback((ref: React.RefObject<HTMLDivElement>) => {
|
||||
ref.current?.scrollIntoView({behavior: 'smooth', block: 'center'})
|
||||
|
@@ -4,22 +4,20 @@ import {
|
||||
setCurFetched,
|
||||
setCurIdx,
|
||||
setCurInfo,
|
||||
setCurrentTime,
|
||||
setData,
|
||||
setInfos,
|
||||
setNoVideo,
|
||||
setSegmentFold,
|
||||
setSegments,
|
||||
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 '../consts/const'
|
||||
import {EVENT_EXPAND, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../consts/const'
|
||||
import {useAsyncEffect, useInterval} from 'ahooks'
|
||||
import {getModelMaxTokens, getWholeText} from '../utils/bizUtil'
|
||||
import { useMessage } from './message'
|
||||
import { useMessage } from './useMessageService'
|
||||
import { setCurrentTime } from '../redux/currentTimeReducer'
|
||||
import { RootState } from '../store'
|
||||
|
||||
/**
|
||||
* Service是单例,类似后端的服务概念
|
||||
@@ -31,10 +29,11 @@ const useSubtitleService = () => {
|
||||
const curFetched = useAppSelector(state => state.env.curFetched)
|
||||
const fold = useAppSelector(state => state.env.fold)
|
||||
const envReady = useAppSelector(state => state.env.envReady)
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
const data = useAppSelector(state => state.env.data)
|
||||
const currentTime = useAppSelector(state => state.env.currentTime)
|
||||
const curIdx = useAppSelector(state => state.env.curIdx)
|
||||
const envData = useAppSelector((state: RootState) => state.env.envData)
|
||||
const data = useAppSelector((state: RootState) => state.env.data)
|
||||
const chapters = useAppSelector((state: RootState) => state.env.chapters)
|
||||
const currentTime = useAppSelector((state: RootState) => state.currentTime.currentTime)
|
||||
const curIdx = useAppSelector((state: RootState) => state.env.curIdx)
|
||||
const eventBus = useContext(EventBusContext)
|
||||
const needScroll = useAppSelector(state => state.env.needScroll)
|
||||
const segments = useAppSelector(state => state.env.segments)
|
||||
@@ -43,9 +42,9 @@ const useSubtitleService = () => {
|
||||
const autoTranslate = useAppSelector(state => state.env.autoTranslate)
|
||||
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
|
||||
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
|
||||
const {sendInject} = useMessage()
|
||||
const {sendInject} = useMessage(!!envData.sidePanel)
|
||||
|
||||
//如果reviewActions达到15次,则设置reviewed为false
|
||||
// 如果reviewActions达到15次,则设置reviewed为false
|
||||
useEffect(() => {
|
||||
if (reviewed === undefined && reviewActions && reviewActions >= 15) {
|
||||
dispatch(setTempData({
|
||||
@@ -74,11 +73,11 @@ const useSubtitleService = () => {
|
||||
dispatch(setCurInfo(infos[0]))
|
||||
dispatch(setCurFetched(false))
|
||||
}
|
||||
}, [curInfo, dispatch, envData.autoExpand, envReady, fold, infos])
|
||||
}, [curInfo, dispatch, envData.autoExpand, envReady, fold, infos, envData.sidePanel])
|
||||
// 获取
|
||||
useEffect(() => {
|
||||
if (curInfo && !curFetched) {
|
||||
sendInject('GET_SUBTITLE', {info: curInfo}).then(data => {
|
||||
sendInject(null, 'GET_SUBTITLE', {info: curInfo}).then(data => {
|
||||
data?.body?.forEach((item: TranscriptItem, idx: number) => {
|
||||
item.idx = idx
|
||||
})
|
||||
@@ -86,44 +85,49 @@ const useSubtitleService = () => {
|
||||
dispatch(setCurFetched(true))
|
||||
dispatch(setData(data))
|
||||
|
||||
console.log('subtitle', data)
|
||||
console.debug('subtitle', data)
|
||||
})
|
||||
}
|
||||
}, [curFetched, curInfo])
|
||||
}, [curFetched, curInfo, dispatch, sendInject])
|
||||
|
||||
useAsyncEffect(async () => {
|
||||
// 初始获取列表
|
||||
sendInject('REFRESH_VIDEO_INFO', {force: true})
|
||||
}, [])
|
||||
if (envReady) {
|
||||
sendInject(null, 'REFRESH_VIDEO_INFO', {force: true})
|
||||
}
|
||||
}, [envReady, sendInject])
|
||||
|
||||
useAsyncEffect(async () => {
|
||||
// 更新设置信息
|
||||
sendInject('GET_VIDEO_ELEMENT_INFO', {}).then(info => {
|
||||
sendInject(null, 'GET_VIDEO_ELEMENT_INFO', {}).then(info => {
|
||||
dispatch(setNoVideo(info.noVideo))
|
||||
if (envData.sidePanel) {
|
||||
// get screen height
|
||||
dispatch(setTotalHeight(window.innerHeight))
|
||||
}else {
|
||||
} else {
|
||||
dispatch(setTotalHeight(Math.min(Math.max(info.totalHeight, TOTAL_HEIGHT_MIN), TOTAL_HEIGHT_MAX)))
|
||||
}
|
||||
})
|
||||
}, [envData.sidePanel, infos])
|
||||
}, [envData.sidePanel, infos, sendInject])
|
||||
|
||||
// 更新当前位置
|
||||
useEffect(() => {
|
||||
let curIdx
|
||||
let newCurIdx
|
||||
if (((data?.body) != null) && currentTime) {
|
||||
for (let i=0; i<data.body.length; i++) {
|
||||
const item = data.body[i]
|
||||
if (item.from && currentTime < item.from) {
|
||||
break
|
||||
} else {
|
||||
curIdx = i
|
||||
newCurIdx = i
|
||||
}
|
||||
}
|
||||
}
|
||||
dispatch(setCurIdx(curIdx))
|
||||
}, [currentTime, data?.body, dispatch])
|
||||
// 只有当索引发生变化时才更新状态
|
||||
if (newCurIdx !== curIdx) {
|
||||
dispatch(setCurIdx(newCurIdx))
|
||||
}
|
||||
}, [currentTime, data?.body, dispatch, curIdx])
|
||||
|
||||
// 需要滚动 => segment自动展开
|
||||
useEffect(() => {
|
||||
@@ -150,33 +154,83 @@ const useSubtitleService = () => {
|
||||
if (envData.summarizeEnable) { // 分段
|
||||
let size = envData.words
|
||||
if (!size) { // 默认
|
||||
if (envData.aiType === 'gemini') {
|
||||
size = GEMINI_TOKENS*WORDS_RATE
|
||||
} else {
|
||||
size = getModelMaxTokens(envData)*WORDS_RATE
|
||||
}
|
||||
size = getModelMaxTokens(envData)*WORDS_RATE
|
||||
}
|
||||
size = Math.max(size, WORDS_MIN)
|
||||
|
||||
segments = []
|
||||
let transcriptItems: TranscriptItem[] = []
|
||||
let totalLength = 0
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
transcriptItems.push(item)
|
||||
totalLength += item.content.length
|
||||
if (totalLength >= size || i === items.length-1) { // new segment or last
|
||||
// add
|
||||
segments.push({
|
||||
items: transcriptItems,
|
||||
startIdx: transcriptItems[0].idx,
|
||||
endIdx: transcriptItems[transcriptItems.length - 1].idx,
|
||||
text: getWholeText(transcriptItems.map(item => item.content)),
|
||||
summaries: {},
|
||||
|
||||
// 如果有章节信息,按章节分割
|
||||
if (chapters && chapters.length > 0) {
|
||||
for (let chapterIdx = 0; chapterIdx < chapters.length; chapterIdx++) {
|
||||
const chapter = chapters[chapterIdx]
|
||||
const nextChapter = chapters[chapterIdx + 1]
|
||||
|
||||
// 找到属于当前章节的字幕项
|
||||
const chapterItems = items.filter(item => {
|
||||
const itemTime = item.from
|
||||
return itemTime >= chapter.from && (nextChapter ? itemTime < nextChapter.from : true)
|
||||
})
|
||||
// reset
|
||||
transcriptItems = []
|
||||
totalLength = 0
|
||||
|
||||
if (chapterItems.length === 0) continue
|
||||
|
||||
// 如果章节内容过长,需要进一步分割
|
||||
const chapterText = getWholeText(chapterItems.map(item => item.content))
|
||||
if (chapterText.length <= size) {
|
||||
// 章节内容不长,作为一个segment
|
||||
segments.push({
|
||||
items: chapterItems,
|
||||
startIdx: chapterItems[0].idx,
|
||||
endIdx: chapterItems[chapterItems.length - 1].idx,
|
||||
text: chapterText,
|
||||
chapterTitle: chapter.content,
|
||||
summaries: {},
|
||||
})
|
||||
} else {
|
||||
// 章节内容过长,需要分割成多个segment
|
||||
let transcriptItems: TranscriptItem[] = []
|
||||
let totalLength = 0
|
||||
for (let i = 0; i < chapterItems.length; i++) {
|
||||
const item = chapterItems[i]
|
||||
transcriptItems.push(item)
|
||||
totalLength += item.content.length
|
||||
if (totalLength >= size || i === chapterItems.length - 1) {
|
||||
segments.push({
|
||||
items: transcriptItems,
|
||||
startIdx: transcriptItems[0].idx,
|
||||
endIdx: transcriptItems[transcriptItems.length - 1].idx,
|
||||
text: getWholeText(transcriptItems.map(item => item.content)),
|
||||
chapterTitle: chapter.content,
|
||||
summaries: {},
|
||||
})
|
||||
// reset
|
||||
transcriptItems = []
|
||||
totalLength = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 没有章节信息,按原来的逻辑分割
|
||||
let transcriptItems: TranscriptItem[] = []
|
||||
let totalLength = 0
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
transcriptItems.push(item)
|
||||
totalLength += item.content.length
|
||||
if (totalLength >= size || i === items.length-1) { // new segment or last
|
||||
// add
|
||||
segments.push({
|
||||
items: transcriptItems,
|
||||
startIdx: transcriptItems[0].idx,
|
||||
endIdx: transcriptItems[transcriptItems.length - 1].idx,
|
||||
text: getWholeText(transcriptItems.map(item => item.content)),
|
||||
summaries: {},
|
||||
})
|
||||
// reset
|
||||
transcriptItems = []
|
||||
totalLength = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
} else { // 都放一个分段
|
||||
@@ -190,29 +244,32 @@ const useSubtitleService = () => {
|
||||
}
|
||||
}
|
||||
dispatch(setSegments(segments))
|
||||
}, [data?.body, dispatch, envData])
|
||||
}, [data?.body, dispatch, envData, chapters])
|
||||
|
||||
// 每0.5秒更新当前视频时间
|
||||
useInterval(() => {
|
||||
sendInject('GET_VIDEO_STATUS', {}).then(status => {
|
||||
dispatch(setCurrentTime(status.currentTime))
|
||||
sendInject(null, 'GET_VIDEO_STATUS', {}).then(status => {
|
||||
// 只有当时间发生显著变化时才更新状态(差异大于0.1秒),避免不必要的重新渲染
|
||||
if (currentTime == null || Math.abs(status.currentTime - currentTime) > 0.1) {
|
||||
dispatch(setCurrentTime(status.currentTime))
|
||||
}
|
||||
})
|
||||
}, 500)
|
||||
|
||||
// show translated text in the video
|
||||
useEffect(() => {
|
||||
if (hideOnDisableAutoTranslate && !autoTranslate) {
|
||||
sendInject('HIDE_TRANS', {})
|
||||
sendInject(null, 'HIDE_TRANS', {})
|
||||
return
|
||||
}
|
||||
|
||||
const transResult = curIdx?transResults[curIdx]:undefined
|
||||
if (transResult?.code === '200' && transResult.data) {
|
||||
sendInject('UPDATE_TRANS_RESULT', {result: transResult.data})
|
||||
sendInject(null, 'UPDATE_TRANS_RESULT', {result: transResult.data})
|
||||
} else {
|
||||
sendInject('HIDE_TRANS', {})
|
||||
sendInject(null, 'HIDE_TRANS', {})
|
||||
}
|
||||
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, transResults])
|
||||
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, sendInject, transResults])
|
||||
}
|
||||
|
||||
export default useSubtitleService
|
||||
|
@@ -29,7 +29,7 @@ import toast from 'react-hot-toast'
|
||||
import {useMemoizedFn} from 'ahooks/es'
|
||||
import {extractJsonArray, extractJsonObject, getModel} from '../utils/bizUtil'
|
||||
import {formatTime} from '../utils/util'
|
||||
import { useMessage } from './message'
|
||||
import { useMessage } from './useMessageService'
|
||||
const useTranslate = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
const data = useAppSelector(state => state.env.data)
|
||||
@@ -43,7 +43,7 @@ const useTranslate = () => {
|
||||
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
|
||||
const reviewAction = useAppSelector(state => state.env.reviewAction)
|
||||
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
|
||||
const {sendExtension} = useMessage()
|
||||
const {sendExtension} = useMessage(!!envData.sidePanel)
|
||||
/**
|
||||
* 获取下一个需要翻译的行
|
||||
* 会检测冷却
|
||||
@@ -88,24 +88,9 @@ const useTranslate = () => {
|
||||
prompt = prompt.replaceAll('{{subtitles}}', lineStr)
|
||||
|
||||
const taskDef: TaskDef = {
|
||||
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
|
||||
type: 'chatComplete',
|
||||
serverUrl: envData.serverUrl,
|
||||
data: envData.aiType === 'gemini'
|
||||
?{
|
||||
contents: [
|
||||
{
|
||||
parts: [
|
||||
{
|
||||
text: prompt
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
generationConfig: {
|
||||
maxOutputTokens: 2048
|
||||
}
|
||||
}
|
||||
:{
|
||||
data: {
|
||||
model: getModel(envData),
|
||||
messages: [
|
||||
{
|
||||
@@ -120,7 +105,6 @@ const useTranslate = () => {
|
||||
extra: {
|
||||
type: 'translate',
|
||||
apiKey: envData.apiKey,
|
||||
geminiApiKey: envData.geminiApiKey,
|
||||
startIdx,
|
||||
size: lines.length,
|
||||
}
|
||||
@@ -135,14 +119,14 @@ const useTranslate = () => {
|
||||
}
|
||||
})
|
||||
dispatch(addTransResults(result))
|
||||
const task = await sendExtension('ADD_TASK', {taskDef})
|
||||
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
|
||||
dispatch(addTaskId(task.id))
|
||||
}
|
||||
}
|
||||
}, [data?.body, envData, language.name, title, dispatch])
|
||||
}, [data?.body, envData, language.name, title, dispatch, sendExtension])
|
||||
|
||||
const addSummarizeTask = useCallback(async (type: SummaryType, segment: Segment) => {
|
||||
//review action
|
||||
// review action
|
||||
if (reviewed === undefined && !reviewAction) {
|
||||
dispatch(setReviewAction(true))
|
||||
dispatch(setTempData({
|
||||
@@ -165,24 +149,9 @@ const useTranslate = () => {
|
||||
prompt = prompt.replaceAll('{{segment}}', segment.text)
|
||||
|
||||
const taskDef: TaskDef = {
|
||||
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
|
||||
type: 'chatComplete',
|
||||
serverUrl: envData.serverUrl,
|
||||
data: envData.aiType === 'gemini'
|
||||
?{
|
||||
contents: [
|
||||
{
|
||||
parts: [
|
||||
{
|
||||
text: prompt
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
generationConfig: {
|
||||
maxOutputTokens: 2048
|
||||
}
|
||||
}
|
||||
:{
|
||||
data: {
|
||||
model: getModel(envData),
|
||||
messages: [
|
||||
{
|
||||
@@ -199,16 +168,15 @@ const useTranslate = () => {
|
||||
summaryType: type,
|
||||
startIdx: segment.startIdx,
|
||||
apiKey: envData.apiKey,
|
||||
geminiApiKey: envData.geminiApiKey,
|
||||
}
|
||||
}
|
||||
console.debug('addSummarizeTask', taskDef)
|
||||
dispatch(setSummaryStatus({segmentStartIdx: segment.startIdx, type, status: 'pending'}))
|
||||
dispatch(setLastSummarizeTime(Date.now()))
|
||||
const task = await sendExtension('ADD_TASK', {taskDef})
|
||||
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
|
||||
dispatch(addTaskId(task.id))
|
||||
}
|
||||
}, [dispatch, envData, summarizeLanguage.name, title])
|
||||
}, [dispatch, envData, reviewAction, reviewActions, reviewed, sendExtension, summarizeLanguage.name, title])
|
||||
|
||||
const addAskTask = useCallback(async (id: string, segment: Segment, question: string) => {
|
||||
if (segment.text.length >= SUMMARIZE_THRESHOLD) {
|
||||
@@ -220,24 +188,9 @@ const useTranslate = () => {
|
||||
prompt = prompt.replaceAll('{{question}}', question)
|
||||
|
||||
const taskDef: TaskDef = {
|
||||
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
|
||||
type: 'chatComplete',
|
||||
serverUrl: envData.serverUrl,
|
||||
data: envData.aiType === 'gemini'
|
||||
?{
|
||||
contents: [
|
||||
{
|
||||
parts: [
|
||||
{
|
||||
text: prompt
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
generationConfig: {
|
||||
maxOutputTokens: 2048
|
||||
}
|
||||
}
|
||||
:{
|
||||
data: {
|
||||
model: getModel(envData),
|
||||
messages: [
|
||||
{
|
||||
@@ -253,7 +206,6 @@ const useTranslate = () => {
|
||||
type: 'ask',
|
||||
// startIdx: segment.startIdx,
|
||||
apiKey: envData.apiKey,
|
||||
geminiApiKey: envData.geminiApiKey,
|
||||
askId: id,
|
||||
}
|
||||
}
|
||||
@@ -262,10 +214,10 @@ const useTranslate = () => {
|
||||
id,
|
||||
status: 'pending'
|
||||
}))
|
||||
const task = await sendExtension('ADD_TASK', {taskDef})
|
||||
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
|
||||
dispatch(addTaskId(task.id))
|
||||
}
|
||||
}, [dispatch, envData, summarizeLanguage.name, title])
|
||||
}, [dispatch, envData, sendExtension, summarizeLanguage.name, title])
|
||||
|
||||
const handleTranslate = useMemoizedFn((task: Task, content: string) => {
|
||||
let map: {[key: string]: string} = {}
|
||||
@@ -330,12 +282,12 @@ const useTranslate = () => {
|
||||
})
|
||||
|
||||
const getTask = useCallback(async (taskId: string) => {
|
||||
const taskResp = await sendExtension('GET_TASK', {taskId})
|
||||
const taskResp = await sendExtension(null, 'GET_TASK', {taskId})
|
||||
if (taskResp.code === 'ok') {
|
||||
console.debug('getTask', taskResp.task)
|
||||
const task: Task = taskResp.task
|
||||
const taskType: string | undefined = task.def.extra?.type
|
||||
const content = envData.aiType === 'gemini'?task.resp?.candidates[0]?.content?.parts[0]?.text?.trim():task.resp?.choices?.[0]?.message?.content?.trim()
|
||||
const content = task.resp?.choices?.[0]?.message?.content?.trim()
|
||||
if (task.status === 'done') {
|
||||
// 异常提示
|
||||
if (task.error) {
|
||||
@@ -355,7 +307,7 @@ const useTranslate = () => {
|
||||
} else {
|
||||
dispatch(delTaskId(taskId))
|
||||
}
|
||||
}, [dispatch, envData.aiType, handleAsk, handleSummarize, handleTranslate])
|
||||
}, [dispatch, handleAsk, handleSummarize, handleTranslate, sendExtension])
|
||||
|
||||
return {getFetch, getTask, addTask, addSummarizeTask, addAskTask}
|
||||
}
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import { TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID, STORAGE_ENV } from '@/consts/const'
|
||||
import InjectMessaging from '@/messaging/layer2/InjectMessaging'
|
||||
import { TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID, STORAGE_ENV, DEFAULT_USE_PORT } from '@/consts/const'
|
||||
import { AllExtensionMessages, AllInjectMessages, AllAPPMessages } from '@/message-typings'
|
||||
import { InjectMessaging } from '@kky002/kky-message'
|
||||
|
||||
const debug = (...args: any[]) => {
|
||||
console.debug('[Inject]', ...args)
|
||||
@@ -12,7 +13,7 @@ const debug = (...args: any[]) => {
|
||||
return
|
||||
}
|
||||
|
||||
//读取envData
|
||||
// 读取envData
|
||||
const envDataStr = (await chrome.storage.sync.get(STORAGE_ENV))[STORAGE_ENV]
|
||||
let sidePanel: boolean | null = null
|
||||
let manualInsert: boolean | null = null
|
||||
@@ -41,7 +42,7 @@ const debug = (...args: any[]) => {
|
||||
showTrans: boolean
|
||||
curTrans?: string
|
||||
} = {
|
||||
injectMessaging: new InjectMessaging(),
|
||||
injectMessaging: new InjectMessaging(DEFAULT_USE_PORT),
|
||||
fold: true,
|
||||
videoElementHeight: TOTAL_HEIGHT_DEF,
|
||||
showTrans: false,
|
||||
@@ -93,7 +94,7 @@ const debug = (...args: any[]) => {
|
||||
iframe.dataset[vKey] = danmukuBox?.dataset[vKey]
|
||||
}
|
||||
|
||||
//insert before first child
|
||||
// insert before first child
|
||||
danmukuBox?.insertBefore(iframe, danmukuBox?.firstChild)
|
||||
|
||||
// show badge
|
||||
@@ -113,7 +114,7 @@ const debug = (...args: any[]) => {
|
||||
if (danmukuBox) {
|
||||
clearInterval(timerIframe)
|
||||
|
||||
//延迟插入iframe(插入太快,网络较差时容易出现b站网页刷新,原因暂时未知,可能b站的某种机制?)
|
||||
// 延迟插入iframe(插入太快,网络较差时容易出现b站网页刷新,原因暂时未知,可能b站的某种机制?)
|
||||
setTimeout(createIframe, 1500)
|
||||
}
|
||||
}, 1000)
|
||||
@@ -139,6 +140,7 @@ const debug = (...args: any[]) => {
|
||||
// fix: https://github.com/IndieKKY/bilibili-subtitle/issues/5
|
||||
// 处理稍后再看的url( https://www.bilibili.com/list/watchlater?bvid=xxx&oid=xxx )
|
||||
const pathSearchs: Record<string, string> = {}
|
||||
// eslint-disable-next-line no-return-assign
|
||||
location.search.slice(1).replace(/([^=&]*)=([^=&]*)/g, (matchs, a, b, c) => pathSearchs[a] = b)
|
||||
|
||||
// bvid
|
||||
@@ -157,21 +159,37 @@ const debug = (...args: any[]) => {
|
||||
|
||||
lastAidOrBvid = aidOrBvid
|
||||
if (aidOrBvid) {
|
||||
//aid,pages
|
||||
let cid
|
||||
// aid,pages
|
||||
let cid: string | undefined
|
||||
/**
|
||||
* [
|
||||
{
|
||||
"type": 2,
|
||||
"from": 0,
|
||||
"to": 152, //单位秒
|
||||
"content": "发现美",
|
||||
"imgUrl": "http://i0.hdslb.com/bfs/vchapter/29168372111_0.jpg",
|
||||
"logoUrl": "",
|
||||
"team_type": "",
|
||||
"team_name": ""
|
||||
}
|
||||
]
|
||||
*/
|
||||
let chapters: any[] = []
|
||||
let subtitles
|
||||
if (aidOrBvid.toLowerCase().startsWith('av')) {//avxxx
|
||||
if (aidOrBvid.toLowerCase().startsWith('av')) { // avxxx
|
||||
aid = parseInt(aidOrBvid.slice(2))
|
||||
pages = await fetch(`https://api.bilibili.com/x/player/pagelist?aid=${aid}`, { credentials: 'include' }).then(res => res.json()).then(res => res.data)
|
||||
pages = await fetch(`https://api.bilibili.com/x/player/pagelist?aid=${aid}`, { credentials: 'include' }).then(async res => await res.json()).then(res => res.data)
|
||||
cid = pages[0].cid
|
||||
ctime = pages[0].ctime
|
||||
author = pages[0].owner?.name
|
||||
title = pages[0].part
|
||||
await fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid}&cid=${cid}`, { credentials: 'include' }).then(res => res.json()).then(res => {
|
||||
await fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid}&cid=${cid!}`, { credentials: 'include' }).then(async res => await res.json()).then(res => {
|
||||
chapters = res.data.view_points ?? []
|
||||
subtitles = res.data.subtitle.subtitles
|
||||
})
|
||||
} else {//bvxxx
|
||||
await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${aidOrBvid}`, { credentials: 'include' }).then(res => res.json()).then(async res => {
|
||||
} else { // bvxxx
|
||||
await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${aidOrBvid}`, { credentials: 'include' }).then(async res => await res.json()).then(async res => {
|
||||
title = res.data.title
|
||||
aid = res.data.aid
|
||||
cid = res.data.cid
|
||||
@@ -179,12 +197,16 @@ const debug = (...args: any[]) => {
|
||||
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(res => res.json()).then(res => {
|
||||
await fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid!}&cid=${cid!}`, { credentials: 'include' }).then(async res => await res.json()).then(res => {
|
||||
chapters = res.data.view_points ?? []
|
||||
subtitles = res.data.subtitle.subtitles
|
||||
})
|
||||
}
|
||||
|
||||
//pagesMap
|
||||
//筛选chapters里type为2的
|
||||
chapters = chapters.filter(chapter => chapter.type === 2)
|
||||
|
||||
// pagesMap
|
||||
pagesMap = {}
|
||||
pages.forEach(page => {
|
||||
pagesMap[page.page + ''] = page
|
||||
@@ -192,14 +214,15 @@ const debug = (...args: any[]) => {
|
||||
|
||||
debug('refreshVideoInfo: ', aid, cid, pages, subtitles)
|
||||
|
||||
//send setVideoInfo
|
||||
runtime.injectMessaging.sendApp('SET_VIDEO_INFO', {
|
||||
// send setVideoInfo
|
||||
runtime.injectMessaging.sendApp(!!sidePanel, 'SET_VIDEO_INFO', {
|
||||
url: location.origin + location.pathname,
|
||||
title,
|
||||
aid,
|
||||
ctime,
|
||||
author,
|
||||
pages,
|
||||
chapters,
|
||||
infos: subtitles,
|
||||
})
|
||||
}
|
||||
@@ -218,7 +241,7 @@ const debug = (...args: any[]) => {
|
||||
const p = urlSearchParams.get('p') || 1
|
||||
const page = pagesMap[p]
|
||||
if (!page) return
|
||||
const cid = page.cid
|
||||
const cid: number | null = page.cid
|
||||
|
||||
if (aid !== lastAid || cid !== lastCid) {
|
||||
debug('refreshSubtitles', aid, cid)
|
||||
@@ -229,12 +252,12 @@ const debug = (...args: any[]) => {
|
||||
fetch(`https://api.bilibili.com/x/player/wbi/v2?aid=${aid}&cid=${cid}`, {
|
||||
credentials: 'include',
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(async res => await res.json())
|
||||
.then(res => {
|
||||
//remove elements with empty subtitle_url
|
||||
// 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('SET_INFOS', {
|
||||
runtime.injectMessaging.sendApp(!!sidePanel, 'SET_INFOS', {
|
||||
infos: res.data.subtitle.subtitles
|
||||
})
|
||||
}
|
||||
@@ -282,7 +305,7 @@ const debug = (...args: any[]) => {
|
||||
if (url.startsWith('http://')) {
|
||||
url = url.replace('http://', 'https://')
|
||||
}
|
||||
return await fetch(url).then(res => res.json())
|
||||
return await fetch(url).then(async res => await res.json())
|
||||
},
|
||||
GET_VIDEO_STATUS: async (params) => {
|
||||
const video = getVideoElement()
|
||||
@@ -335,7 +358,7 @@ const debug = (...args: any[]) => {
|
||||
runtime.showTrans = false
|
||||
runtime.curTrans = undefined
|
||||
|
||||
let text = document.getElementById('trans-result-text')
|
||||
const text = document.getElementById('trans-result-text')
|
||||
if (text) {
|
||||
text.style.display = 'none'
|
||||
}
|
||||
@@ -356,7 +379,7 @@ const debug = (...args: any[]) => {
|
||||
const playInfo = JSON.parse(html.match(/window.__playinfo__=(.+?)<\/script/)?.[1] ?? '{}')
|
||||
const audioUrl = playInfo.data.dash.audio[0].baseUrl
|
||||
|
||||
fetch(audioUrl).then(res => res.blob()).then(blob => {
|
||||
fetch(audioUrl).then(async res => await res.blob()).then(blob => {
|
||||
const a = document.createElement('a')
|
||||
a.href = URL.createObjectURL(blob)
|
||||
a.download = `${title}.m4s`
|
||||
|
164
src/message-typings.d.ts
vendored
164
src/message-typings.d.ts
vendored
@@ -1,89 +1,87 @@
|
||||
//extension
|
||||
import {ExtensionMessage, InjectMessage, AppMessage} from '@kky002/kky-message'
|
||||
|
||||
// extension
|
||||
interface ExtensionCloseSidePanelMessage extends ExtensionMessage {
|
||||
method: 'CLOSE_SIDE_PANEL';
|
||||
}
|
||||
|
||||
interface ExtensionAddTaskMessage extends ExtensionMessage<{ taskDef: TaskDef }, Task> {
|
||||
method: 'ADD_TASK';
|
||||
}
|
||||
|
||||
interface ExtensionGetTaskMessage extends ExtensionMessage<{ taskId: string }, {
|
||||
code: 'ok'
|
||||
task: Task
|
||||
} | {
|
||||
code: 'not_found'
|
||||
}> {
|
||||
method: 'GET_TASK';
|
||||
}
|
||||
|
||||
interface ExtensionShowFlagMessage extends ExtensionMessage<{ show: boolean }> {
|
||||
method: 'SHOW_FLAG';
|
||||
}
|
||||
|
||||
type AllExtensionMessages = ExtensionCloseSidePanelMessage | ExtensionAddTaskMessage | ExtensionGetTaskMessage | ExtensionShowFlagMessage
|
||||
|
||||
method: 'CLOSE_SIDE_PANEL'
|
||||
}
|
||||
|
||||
interface ExtensionAddTaskMessage extends ExtensionMessage<{ taskDef: TaskDef }, Task> {
|
||||
method: 'ADD_TASK'
|
||||
}
|
||||
|
||||
interface ExtensionGetTaskMessage extends ExtensionMessage<{ taskId: string }, {
|
||||
code: 'ok'
|
||||
task: Task
|
||||
} | {
|
||||
code: 'not_found'
|
||||
}> {
|
||||
method: 'GET_TASK'
|
||||
}
|
||||
|
||||
//inject
|
||||
interface InjectToggleDisplayMessage extends InjectMessage<{}> {
|
||||
method: 'TOGGLE_DISPLAY';
|
||||
}
|
||||
|
||||
interface InjectFoldMessage extends InjectMessage<{ fold: boolean }> {
|
||||
method: 'FOLD';
|
||||
}
|
||||
|
||||
interface InjectMoveMessage extends InjectMessage<{ time: number, togglePause: boolean }> {
|
||||
method: 'MOVE';
|
||||
}
|
||||
|
||||
interface InjectGetSubtitleMessage extends InjectMessage<{ info: any }> {
|
||||
method: 'GET_SUBTITLE';
|
||||
}
|
||||
|
||||
interface InjectGetVideoStatusMessage extends InjectMessage<{}> {
|
||||
method: 'GET_VIDEO_STATUS';
|
||||
}
|
||||
|
||||
interface InjectGetVideoElementInfoMessage extends InjectMessage<{}> {
|
||||
method: 'GET_VIDEO_ELEMENT_INFO';
|
||||
}
|
||||
|
||||
interface InjectRefreshVideoInfoMessage extends InjectMessage<{ force: boolean }> {
|
||||
method: 'REFRESH_VIDEO_INFO';
|
||||
}
|
||||
|
||||
interface InjectUpdateTransResultMessage extends InjectMessage<{ result: string }> {
|
||||
method: 'UPDATE_TRANS_RESULT';
|
||||
}
|
||||
|
||||
interface InjectHideTransMessage extends InjectMessage<{}> {
|
||||
method: 'HIDE_TRANS';
|
||||
}
|
||||
|
||||
interface InjectPlayMessage extends InjectMessage<{ play: boolean }> {
|
||||
method: 'PLAY';
|
||||
}
|
||||
|
||||
interface InjectDownloadAudioMessage extends InjectMessage<{}> {
|
||||
method: 'DOWNLOAD_AUDIO';
|
||||
}
|
||||
|
||||
type AllInjectMessages = InjectToggleDisplayMessage | InjectFoldMessage | InjectMoveMessage | InjectGetSubtitleMessage | InjectGetVideoStatusMessage | InjectGetVideoElementInfoMessage | InjectRefreshVideoInfoMessage | InjectUpdateTransResultMessage | InjectHideTransMessage | InjectPlayMessage | InjectDownloadAudioMessage
|
||||
|
||||
interface ExtensionShowFlagMessage extends ExtensionMessage<{ show: boolean }> {
|
||||
method: 'SHOW_FLAG'
|
||||
}
|
||||
|
||||
interface ExtensionGetTabIdMessage extends ExtensionMessage<{ show: boolean }> {
|
||||
method: 'GET_TAB_ID'
|
||||
}
|
||||
|
||||
|
||||
//app
|
||||
interface AppSetInfosMessage extends AppMessage<{ infos: any }> {
|
||||
method: 'SET_INFOS';
|
||||
}
|
||||
|
||||
interface AppSetVideoInfoMessage extends AppMessage<{ url: string, title: string, aid: number | null, ctime: number | null, author?: string, pages: any, infos: any }> {
|
||||
method: 'SET_VIDEO_INFO';
|
||||
}
|
||||
|
||||
type AllAPPMessages = AppSetInfosMessage | AppSetVideoInfoMessage
|
||||
|
||||
|
||||
export type AllExtensionMessages = ExtensionGetTabIdMessage | ExtensionCloseSidePanelMessage | ExtensionAddTaskMessage | ExtensionGetTaskMessage | ExtensionShowFlagMessage
|
||||
|
||||
// inject
|
||||
interface InjectToggleDisplayMessage extends InjectMessage<{}> {
|
||||
method: 'TOGGLE_DISPLAY'
|
||||
}
|
||||
|
||||
interface InjectFoldMessage extends InjectMessage<{ fold: boolean }> {
|
||||
method: 'FOLD'
|
||||
}
|
||||
|
||||
interface InjectMoveMessage extends InjectMessage<{ time: number, togglePause: boolean }> {
|
||||
method: 'MOVE'
|
||||
}
|
||||
|
||||
interface InjectGetSubtitleMessage extends InjectMessage<{ info: any }> {
|
||||
method: 'GET_SUBTITLE'
|
||||
}
|
||||
|
||||
interface InjectGetVideoStatusMessage extends InjectMessage<{}> {
|
||||
method: 'GET_VIDEO_STATUS'
|
||||
}
|
||||
|
||||
interface InjectGetVideoElementInfoMessage extends InjectMessage<{}> {
|
||||
method: 'GET_VIDEO_ELEMENT_INFO'
|
||||
}
|
||||
|
||||
interface InjectRefreshVideoInfoMessage extends InjectMessage<{ force: boolean }> {
|
||||
method: 'REFRESH_VIDEO_INFO'
|
||||
}
|
||||
|
||||
interface InjectUpdateTransResultMessage extends InjectMessage<{ result: string }> {
|
||||
method: 'UPDATE_TRANS_RESULT'
|
||||
}
|
||||
|
||||
interface InjectHideTransMessage extends InjectMessage<{}> {
|
||||
method: 'HIDE_TRANS'
|
||||
}
|
||||
|
||||
interface InjectPlayMessage extends InjectMessage<{ play: boolean }> {
|
||||
method: 'PLAY'
|
||||
}
|
||||
|
||||
interface InjectDownloadAudioMessage extends InjectMessage<{}> {
|
||||
method: 'DOWNLOAD_AUDIO'
|
||||
}
|
||||
|
||||
export type AllInjectMessages = InjectToggleDisplayMessage | InjectFoldMessage | InjectMoveMessage | InjectGetSubtitleMessage | InjectGetVideoStatusMessage | InjectGetVideoElementInfoMessage | InjectRefreshVideoInfoMessage | InjectUpdateTransResultMessage | InjectHideTransMessage | InjectPlayMessage | InjectDownloadAudioMessage
|
||||
|
||||
// app
|
||||
interface AppSetInfosMessage extends AppMessage<{ infos: any }> {
|
||||
method: 'SET_INFOS'
|
||||
}
|
||||
|
||||
interface AppSetVideoInfoMessage extends AppMessage<{ url: string, title: string, aid: number | null, ctime: number | null, author?: string, pages: any, chapters: any, infos: any }> {
|
||||
method: 'SET_VIDEO_INFO'
|
||||
}
|
||||
|
||||
export type AllAPPMessages = AppSetInfosMessage | AppSetVideoInfoMessage
|
||||
|
@@ -1,38 +0,0 @@
|
||||
## 消息通信库封装
|
||||
此消息通信库设计为通用的,后面可能会提取到单独的项目中。
|
||||
|
||||
### 消息端
|
||||
|
||||
一共分3个端:
|
||||
|
||||
1. 扩展端(`background.ts`):扩展后台服务,整个浏览器最多一个实例。
|
||||
2. 注入端(`inject.ts`):会注入到网页中运行,可以访问网页元素,每个网页可能n个实例(看注入的次数),但多个实例一般是不必要的,所以尽量控制在一个实例。
|
||||
3. 应用端(`App.tsx`):会放入iframe中,然后iframe元素添加到网页上,每个iframe一个实例;或者options.html选项页面也是应用实例;或者sidepanel.html页面也是应用实例。
|
||||
|
||||
### 消息协议
|
||||
|
||||
协议分两层:
|
||||
|
||||
1. (底层)一层协议为`Layer1Protocol`,内部封装了port,支持双向通信(发送与接收)
|
||||
2. (高层)二层协议分3个部分,基于一层协议:
|
||||
1. `ExtensionMessaging`:扩展端的
|
||||
2. `InjectMessaging`:注入端端
|
||||
3. `useMessagingService`与`useMessaging`:应用端的
|
||||
|
||||
### 通信方向
|
||||
|
||||
通信分为6个方向:
|
||||
|
||||
1. 扩展端 --> 注入端
|
||||
2. 扩展端 --> 应用端
|
||||
3. 注入端 --> 扩展端
|
||||
4. 注入端 --> 应用端
|
||||
5. 应用端 --> 注入端
|
||||
6. 应用端 --> 扩展端
|
||||
|
||||
应用端与注入端通信实现方式:通过扩展端中转。
|
||||
|
||||
### 通信流程
|
||||
|
||||
1. 注入端:通过port连接扩展端,然后发送握手信息(里面包含了此端的一些信息)
|
||||
2. 应用端:同注入端。
|
@@ -1,16 +0,0 @@
|
||||
// 请求信息
|
||||
export type L2ReqMsg = {
|
||||
from: 'extension' | 'inject' | 'app'
|
||||
method: string
|
||||
params?: any
|
||||
}
|
||||
|
||||
// 响应信息
|
||||
export type L2ResMsg<L2Res = any> = {
|
||||
code: number
|
||||
msg?: string
|
||||
data?: L2Res
|
||||
}
|
||||
|
||||
export const TAG_TARGET_INJECT = 'target:inject'
|
||||
export const TAG_TARGET_APP = 'target:app'
|
@@ -1,116 +0,0 @@
|
||||
// 请求信息
|
||||
type ReqMsg<L1Req = any, L1Res = any> = {
|
||||
id: string
|
||||
// 类型
|
||||
type: 'req' | 'res'
|
||||
// 请求
|
||||
req?: L1Req
|
||||
// 响应
|
||||
res?: RespMsg<L1Res>
|
||||
}
|
||||
|
||||
// 响应信息
|
||||
type RespMsg<T = any> = {
|
||||
code: number
|
||||
data?: T
|
||||
msg?: string
|
||||
}
|
||||
|
||||
// 处理函数
|
||||
type Handler<L1Req = any, L1Res = any> = (req: L1Req) => Promise<L1Res>
|
||||
|
||||
// 创建一个 Layer1Protocol 类,用于持久监听 port 并通过消息 ID 处理响应,支持超时
|
||||
class Layer1Protocol<L1Req = any, L1Res = any> {
|
||||
private port: chrome.runtime.Port
|
||||
private timeout: number
|
||||
private requests: Map<string, { resolve: (value: L1Res) => void, reject: (reason?: any) => void, timer: number }>
|
||||
private handler: Handler<L1Req, L1Res>
|
||||
public disconnected: boolean = false
|
||||
|
||||
constructor(handler: Handler<L1Req, L1Res>, port: chrome.runtime.Port, autoDispose = true, timeout = 30000) { // 默认超时 30 秒
|
||||
this.port = port;
|
||||
this.timeout = timeout;
|
||||
this.requests = new Map();
|
||||
this.handler = handler
|
||||
|
||||
// 开始监听
|
||||
this.port.onMessage.addListener(this._messageListener);
|
||||
if (autoDispose) {
|
||||
this.port.onDisconnect.addListener(this.dispose);
|
||||
}
|
||||
}
|
||||
|
||||
// 生成唯一 ID(简单示例,可以使用更复杂的生成策略)
|
||||
private _generateUniqueId() {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
|
||||
private _messageListener = (msg: ReqMsg<L1Req, L1Res>) => {
|
||||
const { id, type, req, res } = msg;
|
||||
if (type === 'req') {
|
||||
this.handler(req!).then(res => {
|
||||
const response: RespMsg<L1Res> = {
|
||||
code: 200,
|
||||
data: res
|
||||
}
|
||||
this.port.postMessage({ id, type: 'res', res: response });
|
||||
}).catch(error => {//业务错误
|
||||
const response: RespMsg<L1Res> = {
|
||||
code: 500,
|
||||
msg: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
this.port.postMessage({ id, type: 'res', res: response });
|
||||
});
|
||||
} else if (type === 'res') {
|
||||
if (this.requests.has(id)) {
|
||||
const { resolve, reject, timer } = this.requests.get(id)!;
|
||||
// 清除超时定时器
|
||||
clearTimeout(timer);
|
||||
// 移除消息 ID
|
||||
this.requests.delete(id);
|
||||
// 通过 ID 找到对应的 Promise 并 resolve
|
||||
if (res!.code === 200) {
|
||||
resolve(res!.data!);
|
||||
} else {//业务错误
|
||||
reject(new Error(`${res!.code}: ${res!.msg || 'Unknown error'}`));
|
||||
}
|
||||
} else {
|
||||
console.error('unknown response message id: ', id)
|
||||
}
|
||||
} else {//语法格式错误
|
||||
console.error('unknown message type: ', type)
|
||||
}
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.disconnected = true
|
||||
this.port.onMessage.removeListener(this._messageListener);
|
||||
if (this.port.onDisconnect) {
|
||||
this.port.onDisconnect.removeListener(this.dispose);
|
||||
}
|
||||
this.requests.forEach(({ timer }) => clearTimeout(timer));
|
||||
this.requests.clear();
|
||||
}
|
||||
|
||||
// 使用 Promise 发送消息并等待响应,支持超时
|
||||
sendMessage(req: L1Req): Promise<L1Res> {
|
||||
const id = this._generateUniqueId();
|
||||
|
||||
return new Promise<L1Res>((resolve, reject) => {
|
||||
// 设置一个超时定时器
|
||||
const timer = setTimeout(() => {
|
||||
// 超时后执行 reject 并从 Map 中删除
|
||||
this.requests.delete(id);
|
||||
reject(new Error(`Request timed out after ${this.timeout / 1000} seconds`));
|
||||
}, this.timeout);
|
||||
|
||||
// 将 resolve 和 timer 函数与消息 ID 绑定,存入 Map
|
||||
this.requests.set(id, { resolve, reject, timer });
|
||||
|
||||
// 发送消息,并附带 ID
|
||||
this.port.postMessage({ id, type: 'req', req });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Layer1Protocol
|
@@ -1,134 +0,0 @@
|
||||
import Layer1Protocol from '../layer1/Layer1Protocol'
|
||||
import { L2ReqMsg, L2ResMsg } from '../const'
|
||||
|
||||
type PortContext<L2ReqMsg, L2ResMsg> = {
|
||||
id: string
|
||||
name: string //暂时没什么用
|
||||
port: chrome.runtime.Port
|
||||
l1protocol: Layer1Protocol<L2ReqMsg, L2ResMsg>
|
||||
ready: boolean
|
||||
|
||||
tabId?: number // 所属tab
|
||||
tags?: string[] // 标签,用来筛选消息发送目标
|
||||
}
|
||||
|
||||
type L2MethodHandler<M extends ExtensionMessage, K, L2ReqMsg, L2ResMsg> = (params: Extract<M, { method: K }>['params'], context: MethodContext, portContext: PortContext<L2ReqMsg, L2ResMsg>) => Promise<any>
|
||||
type L2MethodHandlers<M extends ExtensionMessage, L2ReqMsg, L2ResMsg> = {
|
||||
[K in M['method']]: L2MethodHandler<M, K, L2ReqMsg, L2ResMsg>
|
||||
}
|
||||
|
||||
class ExtensionMessaging<M extends ExtensionMessage, AllInjectMessagesType extends InjectMessage, AllAPPMessagesType extends AppMessage> {
|
||||
portIdToPort: Map<string, PortContext<L2ReqMsg, L2ResMsg>> = new Map()
|
||||
methods?: L2MethodHandlers<M, L2ReqMsg, L2ResMsg>
|
||||
|
||||
debug = (...args: any[]) => {
|
||||
console.debug('[Extension Messaging]', ...args)
|
||||
}
|
||||
|
||||
init = (methods: L2MethodHandlers<M, L2ReqMsg, L2ResMsg>) => {
|
||||
const innerMethods: L2MethodHandlers<MessagingExtensionMessages, L2ReqMsg, L2ResMsg> = {
|
||||
_HANDSHAKE: async (params, context: MethodContext, portContext: PortContext<L2ReqMsg, L2ResMsg>) => {
|
||||
const tags = params.tags
|
||||
let tabId = params.tabId
|
||||
|
||||
//get current tabId
|
||||
if (tabId == null) {
|
||||
const tabs = await chrome.tabs.query({
|
||||
active: true,
|
||||
currentWindow: true,
|
||||
})
|
||||
tabId = tabs[0]?.id
|
||||
}
|
||||
|
||||
portContext.tabId = tabId
|
||||
portContext.tags = tags
|
||||
portContext.ready = true
|
||||
},
|
||||
_ROUTE: async (params, context: MethodContext) => {
|
||||
return this.broadcastMessageExact([context.tabId!], params.tags, params.method as any, params.params)
|
||||
},
|
||||
}
|
||||
|
||||
this.methods = { ...innerMethods, ...methods }
|
||||
|
||||
chrome.runtime.onConnect.addListener((port: chrome.runtime.Port) => {
|
||||
this.debug('onConnect', port)
|
||||
|
||||
const id = crypto.randomUUID()
|
||||
const name = port.name
|
||||
// 创建消息处理器
|
||||
const l1protocol = new Layer1Protocol<L2ReqMsg, L2ResMsg>(async (req: L2ReqMsg) => {
|
||||
const { tabId } = portContext
|
||||
const method = this.methods?.[req.method as keyof typeof this.methods]
|
||||
// console.log('msg>>>', tabId, req, method != null)
|
||||
if (method != null) {
|
||||
return method(req.params, {
|
||||
from: req.from,
|
||||
event: req,
|
||||
tabId,
|
||||
// sender: portContext.port.sender,
|
||||
}, portContext).then((data) => ({
|
||||
code: 200,
|
||||
data,
|
||||
})).catch((err) => {
|
||||
console.error(err)
|
||||
return {
|
||||
code: 500,
|
||||
msg: err.message,
|
||||
}
|
||||
})
|
||||
} else {
|
||||
return {
|
||||
code: 501,
|
||||
msg: 'Unknown method: ' + req.method,
|
||||
}
|
||||
}
|
||||
}, port)
|
||||
// 创建portContext
|
||||
const portContext: PortContext<L2ReqMsg, L2ResMsg> = { id, name, port, l1protocol, ready: false }
|
||||
this.portIdToPort.set(id, portContext)
|
||||
|
||||
// 监听断开连接
|
||||
port.onDisconnect.addListener(() => {
|
||||
this.debug('onDisconnect', id)
|
||||
this.portIdToPort.delete(id)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
//tags 如果为null,则不检查tags,如果为空数组,则不会发送消息
|
||||
//返回:最后一个响应(因此如果只发送给一个tab,则返回的是该tab的响应)
|
||||
broadcastMessageExact = async <M extends AllInjectMessagesType | AllAPPMessagesType, K extends M['method']>(tabIds: number[], tags: string[] | null, method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
|
||||
// 如果tags为空数组,则不会发送消息
|
||||
if (tags != null && tags.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
let res: L2ResMsg | undefined
|
||||
for (const portContext of this.portIdToPort.values()) {
|
||||
//check tabId
|
||||
if (tabIds.includes(portContext.tabId!)) {
|
||||
//check tags
|
||||
if (tags == null || tags.some(tag => portContext.tags?.includes(tag))) {
|
||||
try {
|
||||
res = await portContext.l1protocol.sendMessage({ method, params, from: 'extension' })
|
||||
} catch (e) {
|
||||
console.error('send message to port error', portContext.id, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return res?.data
|
||||
}
|
||||
|
||||
broadcastMessage = async <M extends AllInjectMessagesType | AllAPPMessagesType, K extends M['method']>(ignoreTabIds: number[] | undefined | null, tags: string[], method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
|
||||
const tabs = await chrome.tabs.query({
|
||||
discarded: false,
|
||||
})
|
||||
const tabIds: number[] = tabs.map(tab => tab.id).filter(tabId => tabId != null) as number[]
|
||||
const filteredTabIds: number[] = tabIds.filter(tabId => !ignoreTabIds?.includes(tabId))
|
||||
return await this.broadcastMessageExact(filteredTabIds, tags, method, params)
|
||||
}
|
||||
}
|
||||
|
||||
export default ExtensionMessaging
|
@@ -1,103 +0,0 @@
|
||||
import Layer1Protocol from '../layer1/Layer1Protocol'
|
||||
import { L2ReqMsg, L2ResMsg, TAG_TARGET_APP, TAG_TARGET_INJECT } from '../const'
|
||||
|
||||
class InjectMessaging<AllExtensionMessagesType extends ExtensionMessage, AllInjectMessagesType extends InjectMessage, AllAPPMessagesType extends AppMessage> {
|
||||
port?: chrome.runtime.Port
|
||||
l1protocol?: Layer1Protocol<L2ReqMsg, L2ResMsg>
|
||||
//类实例
|
||||
methods?: {
|
||||
[K in AllInjectMessagesType['method']]: (params: Extract<AllInjectMessagesType, { method: K }>['params'], context: MethodContext) => Promise<any>
|
||||
}
|
||||
|
||||
debug = (...args: any[]) => {
|
||||
console.debug('[Inject Messaging]', ...args)
|
||||
}
|
||||
|
||||
messageHandler = async (req: L2ReqMsg): Promise<L2ResMsg> => {
|
||||
this.debug(`[${req.from}] ${req.method}`, JSON.stringify(req))
|
||||
|
||||
// check event target
|
||||
// if (req.target !== MESSAGE_TARGET_INJECT) return Promise.resolve({
|
||||
// success: false,
|
||||
// code: 501,
|
||||
// message: 'Target Error: ' + req.target,
|
||||
// })
|
||||
|
||||
const method = this.methods?.[req.method as keyof typeof this.methods]
|
||||
if (method != null) {
|
||||
return method(req.params, {
|
||||
from: req.from,
|
||||
event: req,
|
||||
// sender,
|
||||
}).then(data => {
|
||||
// debug(`${source} <= `, event.method, JSON.stringify(data))
|
||||
return {
|
||||
code: 200,
|
||||
data,
|
||||
}
|
||||
}).catch(err => {
|
||||
console.error(err)
|
||||
let msg
|
||||
if (err instanceof Error) {
|
||||
msg = err.message
|
||||
} else if (typeof err === 'string') {
|
||||
msg = err
|
||||
} else {
|
||||
msg = 'error: ' + JSON.stringify(err)
|
||||
}
|
||||
return {
|
||||
code: 500,
|
||||
msg,
|
||||
}
|
||||
})
|
||||
} else {
|
||||
return {
|
||||
code: 501,
|
||||
msg: 'Unknown method: ' + req.method,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init(methods: {
|
||||
[K in AllInjectMessagesType['method']]: (params: Extract<AllInjectMessagesType, { method: K }>['params'], context: MethodContext) => Promise<any>
|
||||
}) {
|
||||
this.methods = methods
|
||||
this.port = chrome.runtime.connect({
|
||||
name: 'bilibili-inject',
|
||||
})
|
||||
this.l1protocol = new Layer1Protocol<L2ReqMsg, L2ResMsg>(this.messageHandler, this.port)
|
||||
//握手
|
||||
this.l1protocol.sendMessage({
|
||||
from: 'inject',
|
||||
method: '_HANDSHAKE',
|
||||
params: {
|
||||
tags: [TAG_TARGET_INJECT],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
sendExtension = async <M extends AllExtensionMessagesType | MessagingExtensionMessages, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
|
||||
return await this.l1protocol!.sendMessage({
|
||||
from: 'inject',
|
||||
method,
|
||||
params: params ?? {},
|
||||
}).then((res) => {
|
||||
if (res.code === 200) {
|
||||
return res.data
|
||||
} else {
|
||||
throw new Error(res.msg)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
sendApp = async <M extends AllAPPMessagesType, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
|
||||
return this.sendExtension('_ROUTE' as any, {
|
||||
tags: [TAG_TARGET_APP],
|
||||
method,
|
||||
params,
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default InjectMessaging
|
@@ -1,44 +0,0 @@
|
||||
import { msgWaiter } from './useMessagingService'
|
||||
import { useCallback, useState } from 'react'
|
||||
import Layer1Protocol from '../layer1/Layer1Protocol'
|
||||
import { L2ReqMsg, L2ResMsg, TAG_TARGET_INJECT } from '../const'
|
||||
|
||||
const useMessaging = <AllExtensionMessagesType extends ExtensionMessage, AllInjectMessagesType extends InjectMessage>() => {
|
||||
const [disconnected, setDisconnected] = useState(false)
|
||||
|
||||
const sendExtension = useCallback(async <M extends AllExtensionMessagesType | MessagingExtensionMessages, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
|
||||
// wait
|
||||
const pmh = await msgWaiter.wait() as Layer1Protocol<L2ReqMsg, L2ResMsg>
|
||||
if (pmh.disconnected) {
|
||||
setDisconnected(true)
|
||||
throw new Error('disconnected')
|
||||
}
|
||||
// send message
|
||||
const res = await pmh.sendMessage({
|
||||
from: 'app',
|
||||
method,
|
||||
params: params ?? {},
|
||||
})
|
||||
if (res.code === 200) {
|
||||
return res.data
|
||||
} else {
|
||||
throw new Error(res.msg)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const sendInject = useCallback(async <M extends AllInjectMessagesType, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
|
||||
return await sendExtension('_ROUTE' as any, {
|
||||
tags: [TAG_TARGET_INJECT],
|
||||
method,
|
||||
params: params ?? {},
|
||||
})
|
||||
}, [])
|
||||
|
||||
return {
|
||||
sendExtension,
|
||||
sendInject,
|
||||
disconnected
|
||||
}
|
||||
}
|
||||
|
||||
export default useMessaging
|
@@ -1,93 +0,0 @@
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import { Waiter } from '@kky002/kky-util'
|
||||
import Layer1Protocol from '../layer1/Layer1Protocol'
|
||||
import { L2ReqMsg, L2ResMsg, TAG_TARGET_APP } from '../const'
|
||||
|
||||
const debug = (...args: any[]) => {
|
||||
console.debug('[App Messaging]', ...args)
|
||||
}
|
||||
|
||||
let l1protocolInit: boolean = false
|
||||
let l1protocol: Layer1Protocol<L2ReqMsg, L2ResMsg> | undefined
|
||||
// let postInjectMessage: (method: string, params: PostMessagePayload) => Promise<PostMessageResponse> | undefined
|
||||
|
||||
export const msgWaiter = new Waiter<Layer1Protocol<L2ReqMsg, L2ResMsg>>(() => ({
|
||||
finished: l1protocolInit,
|
||||
data: l1protocol!,
|
||||
}), 100, 15000)
|
||||
|
||||
const useMessagingService = <AllAPPMessagesType extends AppMessage>(methods?: {
|
||||
[K in AllAPPMessagesType['method']]: (params: Extract<AllAPPMessagesType, { method: K }>['params'], context: MethodContext) => Promise<any>
|
||||
}) => {
|
||||
const messageHandler = useCallback(async (req: L2ReqMsg): Promise<L2ResMsg> => {
|
||||
debug(`[${req.from}] ${req.method}`, JSON.stringify(req))
|
||||
|
||||
// // check event target
|
||||
// if (req.target !== MESSAGE_TARGET_APP) return {
|
||||
// code: 501,
|
||||
// msg: 'Target Error: ' + req.target,
|
||||
// }
|
||||
|
||||
const method = methods?.[req.method as keyof typeof methods]
|
||||
if (method != null) {
|
||||
return method(req.params, {
|
||||
from: req.from,
|
||||
event: req,
|
||||
}).then(data => {
|
||||
// debug(`${source} <= `, event.method, JSON.stringify(data))
|
||||
return {
|
||||
code: 200,
|
||||
data,
|
||||
}
|
||||
}).catch(err => {
|
||||
console.error(err)
|
||||
let msg
|
||||
if (err instanceof Error) {
|
||||
msg = err.message
|
||||
} else if (typeof err === 'string') {
|
||||
msg = err
|
||||
} else {
|
||||
msg = 'error: ' + JSON.stringify(err)
|
||||
}
|
||||
return {
|
||||
code: 500,
|
||||
msg,
|
||||
}
|
||||
})
|
||||
} else {
|
||||
return {
|
||||
code: 501,
|
||||
msg: 'Unknown method: ' + req.method,
|
||||
}
|
||||
}
|
||||
}, [methods])
|
||||
|
||||
const port = useMemo(() => {
|
||||
return chrome.runtime.connect({
|
||||
name: 'bilibili-app',
|
||||
})
|
||||
}, [])
|
||||
l1protocol = useMemo(() => {
|
||||
if (messageHandler && port) {
|
||||
const pmh = new Layer1Protocol<L2ReqMsg, L2ResMsg>(messageHandler, port)
|
||||
|
||||
//get tabId from url params
|
||||
let tabIdStr = window.location.search.split('tabId=')[1]
|
||||
let tabId = tabIdStr ? parseInt(tabIdStr) : undefined
|
||||
// 初始化
|
||||
pmh.sendMessage({
|
||||
from: 'app',
|
||||
method: '_HANDSHAKE',
|
||||
params: {
|
||||
tabId,
|
||||
tags: [TAG_TARGET_APP],
|
||||
},
|
||||
})
|
||||
l1protocolInit = true
|
||||
|
||||
return pmh
|
||||
}
|
||||
}, [messageHandler, port])
|
||||
}
|
||||
|
||||
export default useMessagingService
|
28
src/messaging/messaging-typings.d.ts
vendored
28
src/messaging/messaging-typings.d.ts
vendored
@@ -1,28 +0,0 @@
|
||||
interface Message<T = any, R = any> {
|
||||
method: string
|
||||
params: T
|
||||
return: R
|
||||
}
|
||||
|
||||
interface ExtensionMessage<T = any, R = any> extends Message<T, R> {
|
||||
}
|
||||
|
||||
interface InjectMessage<T = any, R = any> extends Message<T, R> {
|
||||
}
|
||||
|
||||
interface AppMessage<T = any, R = any> extends Message<T, R> {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
interface ExtensionHandshakeMessage extends ExtensionMessage<{ tabId?: number, tags: string[] }> {
|
||||
method: '_HANDSHAKE';
|
||||
}
|
||||
|
||||
interface ExtensionRouteMessage extends ExtensionMessage<{ tags: string[], method: string, params: any }> {
|
||||
method: '_ROUTE';
|
||||
}
|
||||
|
||||
type MessagingExtensionMessages = ExtensionHandshakeMessage | ExtensionRouteMessage
|
@@ -9,19 +9,19 @@ import useTranslateService from '../hooks/useTranslateService'
|
||||
import {setTheme} from '../utils/bizUtil'
|
||||
import useSearchService from '../hooks/useSearchService'
|
||||
import {setFold} from '../redux/envReducer'
|
||||
import { useMessage } from '@/hooks/message'
|
||||
import { useMessage } from '@/hooks/useMessageService'
|
||||
|
||||
function App() {
|
||||
const dispatch = useAppDispatch()
|
||||
const fold = useAppSelector(state => state.env.fold)
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
const eventBus = useContext(EventBusContext)
|
||||
const totalHeight = useAppSelector(state => state.env.totalHeight)
|
||||
const {sendInject} = useMessage()
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
|
||||
const {sendInject} = useMessage(!!envData.sidePanel)
|
||||
|
||||
const foldCallback = useCallback(() => {
|
||||
dispatch(setFold(!fold))
|
||||
sendInject('FOLD', {fold: !fold})
|
||||
sendInject(null, 'FOLD', {fold: !fold})
|
||||
}, [dispatch, fold, sendInject])
|
||||
|
||||
// handle event
|
||||
|
@@ -4,8 +4,8 @@ import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||
import {
|
||||
ASK_ENABLED_DEFAULT,
|
||||
CUSTOM_MODEL_TOKENS,
|
||||
DEFAULT_SERVER_URL_GEMINI,
|
||||
DEFAULT_SERVER_URL_OPENAI,
|
||||
GEMINI_TOKENS,
|
||||
LANGUAGE_DEFAULT,
|
||||
LANGUAGES,
|
||||
MODEL_DEFAULT,
|
||||
@@ -26,11 +26,11 @@ import classNames from 'classnames'
|
||||
import toast from 'react-hot-toast'
|
||||
import {useBoolean, useEventTarget} from 'ahooks'
|
||||
import {useEventChecked} from '@kky002/kky-hooks'
|
||||
import { useMessage } from '@/hooks/message'
|
||||
import { FaChevronDown, FaChevronUp, FaGripfire } from 'react-icons/fa'
|
||||
import { useMessage } from '@/hooks/useMessageService'
|
||||
|
||||
const OptionCard = ({ title, children, defaultExpanded = true }: { title: React.ReactNode; children: React.ReactNode; defaultExpanded?: boolean }) => {
|
||||
const [isExpanded, setIsExpanded] = useState(defaultExpanded);
|
||||
const OptionCard = ({ title, children, defaultExpanded = true }: { title: React.ReactNode, children: React.ReactNode, defaultExpanded?: boolean }) => {
|
||||
const [isExpanded, setIsExpanded] = useState(defaultExpanded)
|
||||
|
||||
return (
|
||||
<div className="card bg-base-200 shadow-xl mb-4">
|
||||
@@ -42,8 +42,8 @@ const OptionCard = ({ title, children, defaultExpanded = true }: { title: React.
|
||||
{isExpanded && <div className="mt-4">{children}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
)
|
||||
}
|
||||
|
||||
const FormItem = (props: {
|
||||
title: ShowElement
|
||||
@@ -66,7 +66,7 @@ const FormItem = (props: {
|
||||
const OptionsPage = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
const {sendExtension} = useMessage()
|
||||
const {sendExtension} = useMessage(false)
|
||||
const {value: sidePanelValue, onChange: setSidePanelValue} = useEventChecked(envData.sidePanel)
|
||||
const {value: autoInsertValue, onChange: setAutoInsertValue} = useEventChecked(!envData.manualInsert)
|
||||
const {value: autoExpandValue, onChange: setAutoExpandValue} = useEventChecked(envData.autoExpand)
|
||||
@@ -79,7 +79,6 @@ const OptionsPage = () => {
|
||||
const {value: summarizeFloatValue, onChange: setSummarizeFloatValue} = useEventChecked(envData.summarizeFloat)
|
||||
const [apiKeyValue, { onChange: onChangeApiKeyValue }] = useEventTarget({initialValue: envData.apiKey??''})
|
||||
const [serverUrlValue, setServerUrlValue] = useState(envData.serverUrl)
|
||||
const [geminiApiKeyValue, { onChange: onChangeGeminiApiKeyValue }] = useEventTarget({initialValue: envData.geminiApiKey??''})
|
||||
const [languageValue, { onChange: onChangeLanguageValue }] = useEventTarget({initialValue: envData.language??LANGUAGE_DEFAULT})
|
||||
const [modelValue, { onChange: onChangeModelValue }] = useEventTarget({initialValue: envData.model??MODEL_DEFAULT})
|
||||
const [customModelValue, { onChange: onChangeCustomModelValue }] = useEventTarget({initialValue: envData.customModel})
|
||||
@@ -88,7 +87,6 @@ const OptionsPage = () => {
|
||||
const [hideOnDisableAutoTranslateValue, setHideOnDisableAutoTranslateValue] = useState(envData.hideOnDisableAutoTranslate)
|
||||
const [themeValue, setThemeValue] = useState(envData.theme)
|
||||
const [fontSizeValue, setFontSizeValue] = useState(envData.fontSize)
|
||||
const [aiTypeValue, setAiTypeValue] = useState(envData.aiType)
|
||||
const [transDisplayValue, setTransDisplayValue] = useState(envData.transDisplay)
|
||||
const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words)
|
||||
const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT)
|
||||
@@ -109,11 +107,8 @@ const OptionsPage = () => {
|
||||
return list
|
||||
}, [])
|
||||
const apiKeySetted = useMemo(() => {
|
||||
if (aiTypeValue === 'gemini') {
|
||||
return !!geminiApiKeyValue
|
||||
}
|
||||
return !!apiKeyValue
|
||||
}, [aiTypeValue, apiKeyValue, geminiApiKeyValue])
|
||||
}, [apiKeyValue])
|
||||
|
||||
const onChangeHideOnDisableAutoTranslate = useCallback((e: any) => {
|
||||
setHideOnDisableAutoTranslateValue(e.target.checked)
|
||||
@@ -124,13 +119,11 @@ const OptionsPage = () => {
|
||||
sidePanel: sidePanelValue,
|
||||
manualInsert: !autoInsertValue,
|
||||
autoExpand: autoExpandValue,
|
||||
aiType: aiTypeValue,
|
||||
apiKey: apiKeyValue,
|
||||
serverUrl: serverUrlValue,
|
||||
model: modelValue,
|
||||
customModel: customModelValue,
|
||||
customModelTokens: customModelTokensValue,
|
||||
geminiApiKey: geminiApiKeyValue,
|
||||
translateEnable: translateEnableValue,
|
||||
language: languageValue,
|
||||
hideOnDisableAutoTranslate: hideOnDisableAutoTranslateValue,
|
||||
@@ -148,12 +141,12 @@ const OptionsPage = () => {
|
||||
askEnabled: askEnabledValue,
|
||||
}))
|
||||
toast.success('保存成功')
|
||||
sendExtension('CLOSE_SIDE_PANEL')
|
||||
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])
|
||||
}, [dispatch, sendExtension, sidePanelValue, autoInsertValue, autoExpandValue, apiKeyValue, serverUrlValue, modelValue, customModelValue, customModelTokensValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue, askEnabledValue])
|
||||
|
||||
const onCancel = useCallback(() => {
|
||||
window.close()
|
||||
@@ -199,14 +192,6 @@ const OptionsPage = () => {
|
||||
setFontSizeValue('large')
|
||||
}, [])
|
||||
|
||||
const onSelOpenai = useCallback(() => {
|
||||
setAiTypeValue('openai')
|
||||
}, [])
|
||||
|
||||
const onSelGemini = useCallback(() => {
|
||||
setAiTypeValue('gemini')
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className='container mx-auto max-w-3xl p-4'>
|
||||
<OptionCard title="通用配置">
|
||||
@@ -235,32 +220,32 @@ const OptionsPage = () => {
|
||||
<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-sm', (!aiTypeValue || aiTypeValue === 'openai')?'btn-active':'')}>OpenAI</button>
|
||||
<button onClick={onSelGemini} className={classNames('btn btn-sm', aiTypeValue === 'gemini'?'btn-active':'')}>Gemini</button>
|
||||
</div>
|
||||
</FormItem>
|
||||
</OptionCard>
|
||||
|
||||
<OptionCard title="AI 配置">
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='ApiKey' htmlFor='apiKey'>
|
||||
{<FormItem title='ApiKey' htmlFor='apiKey'>
|
||||
<input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx'
|
||||
value={apiKeyValue} onChange={onChangeApiKeyValue}/>
|
||||
</FormItem>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='服务器' htmlFor='serverUrl'>
|
||||
{<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>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <div>
|
||||
{<div>
|
||||
<div className='desc text-sm text-center'>
|
||||
<div className='flex justify-center font-semibold'>【官方地址】</div>
|
||||
<div className='flex justify-center font-semibold'>【OpenAI官方地址】</div>
|
||||
<div>官方网址:<a className='link link-primary' href='https://platform.openai.com/' target='_blank'
|
||||
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'>【Gemini官方地址】</div>
|
||||
<div>官方网址:<a className='link link-primary' href='https://aistudio.google.com/apikey' target='_blank'
|
||||
rel="noreferrer">点击访问</a></div>
|
||||
<div>服务器地址:<a className='link link-primary'
|
||||
onClick={() => setServerUrlValue(DEFAULT_SERVER_URL_GEMINI)}
|
||||
rel='noreferrer'>点击设置</a></div>
|
||||
<div className='flex justify-center font-semibold'>【第三方国内代理】</div>
|
||||
<div>代理网址:<a className='link link-primary' href='https://api.kksj.org/register?aff=ucVc'
|
||||
target='_blank'
|
||||
@@ -272,13 +257,13 @@ const OptionsPage = () => {
|
||||
<div className='text-amber-600 flex justify-center items-center'><FaGripfire/>国内可访问,无需🪜<FaGripfire/></div>
|
||||
</div>
|
||||
</div>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='模型选择' htmlFor='modelSel' tip='注意,不同模型有不同价格与token限制'>
|
||||
{<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>}
|
||||
{(!aiTypeValue || aiTypeValue === 'openai') && <div className='desc text-sm'>
|
||||
{<div className='desc text-sm'>
|
||||
{MODEL_TIP}
|
||||
</div>}
|
||||
{modelValue === 'custom' && <FormItem title='模型名' htmlFor='customModel'>
|
||||
@@ -291,20 +276,6 @@ const OptionsPage = () => {
|
||||
value={customModelTokensValue}
|
||||
onChange={e => setCustomModelTokensValue(e.target.value ? parseInt(e.target.value) : undefined)}/>
|
||||
</FormItem>}
|
||||
{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>}
|
||||
{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>
|
||||
</div>}
|
||||
</OptionCard>
|
||||
|
||||
<OptionCard title={<div className='flex items-center'>
|
||||
@@ -372,7 +343,7 @@ const OptionsPage = () => {
|
||||
</div>
|
||||
</FormItem>
|
||||
<div className='desc text-sm'>
|
||||
当前选择的模型的分段字数上限是<span className='font-semibold font-mono'>{aiTypeValue === 'gemini'?GEMINI_TOKENS:(MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知')}</span>
|
||||
当前选择的模型的分段字数上限是<span className='font-semibold font-mono'>{MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知'}</span>
|
||||
(太接近上限总结会报错)
|
||||
</div>
|
||||
</OptionCard>
|
||||
@@ -430,4 +401,4 @@ const OptionsPage = () => {
|
||||
)
|
||||
}
|
||||
|
||||
export default OptionsPage
|
||||
export default OptionsPage
|
||||
|
23
src/redux/currentTimeReducer.ts
Normal file
23
src/redux/currentTimeReducer.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
|
||||
interface CurrentTimeState {
|
||||
currentTime?: number
|
||||
}
|
||||
|
||||
const initialState: CurrentTimeState = {
|
||||
currentTime: undefined
|
||||
}
|
||||
|
||||
export const slice = createSlice({
|
||||
name: 'currentTime',
|
||||
initialState,
|
||||
reducers: {
|
||||
setCurrentTime: (state, action: PayloadAction<number | undefined>) => {
|
||||
state.currentTime = action.payload
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const { setCurrentTime } = slice.actions
|
||||
|
||||
export default slice.reducer
|
@@ -23,7 +23,7 @@ interface EnvState {
|
||||
totalHeight: number
|
||||
curIdx?: number // 从0开始
|
||||
needScroll?: boolean
|
||||
currentTime?: number
|
||||
chapters?: Chapter[]
|
||||
infos?: any[]
|
||||
curInfo?: any
|
||||
curFetched?: boolean
|
||||
@@ -50,7 +50,7 @@ interface EnvState {
|
||||
searchText: string
|
||||
searchResult: Record<string, boolean>
|
||||
|
||||
//当前视频是否计算过操作
|
||||
// 当前视频是否计算过操作
|
||||
reviewAction: boolean
|
||||
}
|
||||
|
||||
@@ -263,9 +263,6 @@ export const slice = createSlice({
|
||||
setNeedScroll: (state, action: PayloadAction<boolean>) => {
|
||||
state.needScroll = action.payload
|
||||
},
|
||||
setCurrentTime: (state, action: PayloadAction<number | undefined>) => {
|
||||
state.currentTime = action.payload
|
||||
},
|
||||
setUrl: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.url = action.payload
|
||||
},
|
||||
@@ -278,6 +275,9 @@ export const slice = createSlice({
|
||||
setAuthor: (state, action: PayloadAction<string | undefined>) => {
|
||||
state.author = action.payload
|
||||
},
|
||||
setChapters: (state, action: PayloadAction<Chapter[]>) => {
|
||||
state.chapters = action.payload
|
||||
},
|
||||
setInfos: (state, action: PayloadAction<any[]>) => {
|
||||
state.infos = action.payload
|
||||
},
|
||||
@@ -337,7 +337,6 @@ export const {
|
||||
setCurIdx,
|
||||
setEnvData,
|
||||
setEnvReady,
|
||||
setCurrentTime,
|
||||
setInfos,
|
||||
setCurInfo,
|
||||
setCurFetched,
|
||||
@@ -351,6 +350,7 @@ export const {
|
||||
mergeAskInfo,
|
||||
setCtime,
|
||||
setAuthor,
|
||||
setChapters,
|
||||
} = slice.actions
|
||||
|
||||
export default slice.reducer
|
||||
|
@@ -1,9 +1,11 @@
|
||||
import {configureStore} from '@reduxjs/toolkit'
|
||||
import envReducer from './redux/envReducer'
|
||||
import currentTimeReducer from './redux/currentTimeReducer'
|
||||
|
||||
const store = configureStore({
|
||||
reducer: {
|
||||
env: envReducer,
|
||||
currentTime: currentTimeReducer,
|
||||
},
|
||||
})
|
||||
|
||||
|
20
src/typings.d.ts
vendored
20
src/typings.d.ts
vendored
@@ -7,19 +7,16 @@ interface MethodContext {
|
||||
|
||||
interface EnvData {
|
||||
sidePanel?: boolean
|
||||
manualInsert?: boolean //是否手动插入字幕列表
|
||||
manualInsert?: boolean // 是否手动插入字幕列表
|
||||
autoExpand?: boolean
|
||||
flagDot?: boolean
|
||||
|
||||
aiType?: 'openai' | 'gemini'
|
||||
// openai
|
||||
apiKey?: string
|
||||
serverUrl?: string
|
||||
model?: string
|
||||
customModel?: string
|
||||
customModelTokens?: number
|
||||
// gemini
|
||||
geminiApiKey?: string
|
||||
|
||||
translateEnable?: boolean
|
||||
language?: string
|
||||
@@ -54,7 +51,7 @@ interface TempData {
|
||||
}
|
||||
|
||||
interface TaskDef {
|
||||
type: 'chatComplete' | 'geminiChatComplete'
|
||||
type: 'chatComplete'
|
||||
serverUrl?: string
|
||||
data: any
|
||||
extra?: any
|
||||
@@ -91,12 +88,19 @@ interface TranscriptItem {
|
||||
idx: number
|
||||
}
|
||||
|
||||
interface Chapter {
|
||||
from: number
|
||||
to: number
|
||||
content: string // 标题
|
||||
}
|
||||
|
||||
interface Segment {
|
||||
items: TranscriptItem[]
|
||||
startIdx: number // 从1开始
|
||||
endIdx: number
|
||||
text: string
|
||||
fold?: boolean
|
||||
chapterTitle?: string // 章节标题
|
||||
summaries: {
|
||||
[type: string]: Summary
|
||||
}
|
||||
@@ -154,10 +158,10 @@ type SummaryStatus = 'init' | 'pending' | 'done'
|
||||
type SummaryType = 'overview' | 'keypoint' | 'brief' | 'question' | 'debate'
|
||||
|
||||
interface DebateMessage {
|
||||
side: 'pro' | 'con';
|
||||
content: string;
|
||||
side: 'pro' | 'con'
|
||||
content: string
|
||||
}
|
||||
|
||||
interface DebateProps {
|
||||
messages: DebateMessage[];
|
||||
messages: DebateMessage[]
|
||||
}
|
||||
|
@@ -115,7 +115,7 @@ export const getSummaryStr = (summary: Summary) => {
|
||||
s += content.map(item => {
|
||||
return (item.side === 'pro'?'正方:':'反方:') + item.content + '\n'
|
||||
}).join('\n')
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -195,12 +195,56 @@ export const getSummarize = (title: string | undefined, segments: Segment[] | un
|
||||
}
|
||||
|
||||
/**
|
||||
* @param time '03:10'
|
||||
* 将 MM:SS 或 HH:MM:SS 格式的时间字符串转换为总秒数。
|
||||
* @param time '03:10' 或 '01:03:10' 格式的时间字符串
|
||||
* @returns number 总秒数,如果格式无效则返回 0 或 NaN (根据下面选择)。
|
||||
* 建议添加更严格的错误处理,例如抛出错误。
|
||||
*/
|
||||
export const parseStrTimeToSeconds = (time: string): number => {
|
||||
const parts = time.split(':')
|
||||
return parseInt(parts[0]) * 60 + parseInt(parts[1])
|
||||
}
|
||||
// 1. 基本输入验证 (可选但推荐)
|
||||
if (!time || typeof time !== 'string') {
|
||||
console.warn(`Invalid input type for time: ${typeof time}`);
|
||||
return 0; // 或者 return NaN;
|
||||
}
|
||||
|
||||
const parts = time.split(':');
|
||||
const partCount = parts.length;
|
||||
|
||||
let hours = 0;
|
||||
let minutes = 0;
|
||||
let seconds = 0;
|
||||
|
||||
try {
|
||||
if (partCount === 2) {
|
||||
// 格式: MM:SS
|
||||
minutes = parseInt(parts[0]);
|
||||
seconds = parseInt(parts[1]);
|
||||
} else if (partCount === 3) {
|
||||
// 格式: HH:MM:SS
|
||||
hours = parseInt(parts[0]);
|
||||
minutes = parseInt(parts[1]);
|
||||
seconds = parseInt(parts[2]);
|
||||
} else {
|
||||
// 格式无效
|
||||
console.warn(`Invalid time format: "${time}". Expected MM:SS or HH:MM:SS.`);
|
||||
return 0; // 或者 return NaN;
|
||||
}
|
||||
|
||||
// 2. 验证解析出的部分是否为有效数字
|
||||
if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
|
||||
console.warn(`Invalid numeric values in time string: "${time}"`);
|
||||
return 0; // 或者 return NaN;
|
||||
}
|
||||
|
||||
// 3. 计算总秒数
|
||||
return hours * 3600 + minutes * 60 + seconds;
|
||||
|
||||
} catch (error) {
|
||||
// 捕获潜在的错误 (虽然在此逻辑中不太可能,但以防万一)
|
||||
console.error(`Error parsing time string: "${time}"`, error);
|
||||
return 0; // 或者 return NaN;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @param time '00:04:11,599' or '00:04:11.599' or '04:11,599' or '04:11.599'
|
||||
|
@@ -1,7 +1,7 @@
|
||||
export const openOptionsPage = () => {
|
||||
if (chrome.runtime.openOptionsPage) {
|
||||
chrome.runtime.openOptionsPage();
|
||||
chrome.runtime.openOptionsPage()
|
||||
} else {
|
||||
window.open(chrome.runtime.getURL('options.html'));
|
||||
window.open(chrome.runtime.getURL('options.html'))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@@ -1,17 +1,44 @@
|
||||
import {SyntheticEvent} from 'react'
|
||||
|
||||
export const isEdgeBrowser = () => {
|
||||
const userAgent = navigator.userAgent.toLowerCase();
|
||||
return userAgent.includes('edg/') && !userAgent.includes('edge/');
|
||||
const userAgent = navigator.userAgent.toLowerCase()
|
||||
return userAgent.includes('edg/') && !userAgent.includes('edge/')
|
||||
}
|
||||
|
||||
export const formatTime = (time: number) => {
|
||||
if (!time) return '00:00'
|
||||
/**
|
||||
* 将总秒数格式化为 MM:SS 或 HH:MM:SS 格式的字符串。
|
||||
* 如果时间小于 1 小时,则使用 MM:SS 格式。
|
||||
* 如果时间大于或等于 1 小时,则使用 HH:MM:SS 格式。
|
||||
*
|
||||
* @param time 总秒数 (number)
|
||||
* @returns string 格式化后的时间字符串 ('MM:SS' 或 'HH:MM:SS')
|
||||
*/
|
||||
export const formatTime = (time: number): string => {
|
||||
// 1. 输入验证和处理 0 或负数的情况
|
||||
if (typeof time !== 'number' || isNaN(time) || time <= 0) {
|
||||
return '00:00'; // 对于无效输入、0 或负数,返回 '00:00'
|
||||
}
|
||||
|
||||
const minutes = Math.floor(time / 60)
|
||||
const seconds = Math.floor(time % 60)
|
||||
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
|
||||
}
|
||||
// 取整确保我们处理的是整数秒
|
||||
const totalSeconds = Math.floor(time);
|
||||
|
||||
// 2. 计算小时、分钟和秒
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
|
||||
// 3. 格式化各个部分,确保是两位数 (例如 0 -> '00', 5 -> '05', 10 -> '10')
|
||||
const formattedSeconds = seconds.toString().padStart(2, '0');
|
||||
const formattedMinutes = minutes.toString().padStart(2, '0');
|
||||
|
||||
// 4. 根据是否有小时来决定最终格式
|
||||
if (hours > 0) {
|
||||
const formattedHours = hours.toString().padStart(2, '0');
|
||||
return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
|
||||
} else {
|
||||
return `${formattedMinutes}:${formattedSeconds}`;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @param time 2.82
|
||||
|
@@ -3,7 +3,11 @@ module.exports = {
|
||||
darkMode: 'class',
|
||||
content: ["./src/**/*.{js,ts,jsx,tsx}"],
|
||||
theme: {
|
||||
extend: {},
|
||||
extend: {
|
||||
fontSize: {
|
||||
xs: '13px',
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
require('tailwind-scrollbar-hide'),
|
||||
|
Reference in New Issue
Block a user