You've already forked bilibili-subtitle
fix消息通信
This commit is contained in:
@@ -15,6 +15,7 @@
|
||||
"dependencies": {
|
||||
"@crxjs/vite-plugin": "^1.0.14",
|
||||
"@kky002/kky-hooks": "^1.2.1",
|
||||
"@kky002/kky-message": "^0.0.7",
|
||||
"@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.0.7
|
||||
version: 0.0.7
|
||||
'@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.0.7':
|
||||
resolution: {integrity: sha512-0qyamYhR+TT79TMbTL4frKTdOZZIObdvbDbmIT1Wu2GafxsIg249FxnW65ERqPNCZ+w5eNCK121EB11+txNFHQ==}
|
||||
|
||||
'@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.0.7':
|
||||
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
|
||||
|
@@ -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({
|
||||
@@ -75,7 +75,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) => {
|
||||
@@ -115,7 +115,7 @@ chrome.action.onClicked.addListener(async (tab) => {
|
||||
})
|
||||
} else {
|
||||
closeSidePanel()
|
||||
extensionMessaging.broadcastMessageExact([tab.id!], [TAG_TARGET_INJECT], 'TOGGLE_DISPLAY').catch(console.error)
|
||||
extensionMessaging.sendMessage(null, tab.id!, TAG_TARGET_INJECT, 'TOGGLE_DISPLAY').catch(console.error)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
@@ -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))
|
||||
|
@@ -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,
|
||||
@@ -13,13 +11,13 @@ import {Placement} from '@popperjs/core/lib/enums'
|
||||
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||
import {setEnvData, setTempData} from '../redux/envReducer'
|
||||
import {EventBusContext} from '../Router'
|
||||
import {EVENT_EXPAND} from '../consts/const'
|
||||
import {DEFAULT_USE_PORT, EVENT_EXPAND} from '../consts/const'
|
||||
import {formatSrtTime, formatTime, formatVttTime} from '../utils/util'
|
||||
import {downloadText, openUrl} from '@kky002/kky-util'
|
||||
import toast from 'react-hot-toast'
|
||||
import {getSummarize} from '../utils/bizUtil'
|
||||
import { useMessage } from '@/hooks/message'
|
||||
import dayjs from 'dayjs';
|
||||
import { useMessage } from '@/hooks/useMessageService'
|
||||
|
||||
interface Props {
|
||||
placement: Placement
|
||||
@@ -74,7 +72,7 @@ const MoreBtn = (props: Props) => {
|
||||
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) {
|
||||
@@ -167,7 +165,7 @@ const MoreBtn = (props: Props) => {
|
||||
}, [curSummaryType, data, downloadType, segments, title, url])
|
||||
|
||||
const downloadAudioCallback = useCallback(() => {
|
||||
sendInject('DOWNLOAD_AUDIO', {})
|
||||
sendInject(null, 'DOWNLOAD_AUDIO', {})
|
||||
}, [])
|
||||
|
||||
const selectCallback = useCallback((e: any) => {
|
||||
|
@@ -1,9 +1,9 @@
|
||||
import React, {MutableRefObject, useCallback, useEffect, useMemo, useRef} from 'react'
|
||||
import {MutableRefObject, useCallback, useEffect, useMemo, useRef} from 'react'
|
||||
import {useAppDispatch, useAppSelector} from '../hooks/redux'
|
||||
import {setFloatKeyPointsSegIdx, setSegmentFold, setTempData} from '../redux/envReducer'
|
||||
import classNames from 'classnames'
|
||||
import {FaClipboardList, 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'
|
||||
|
@@ -1,3 +1,5 @@
|
||||
export const DEFAULT_USE_PORT = false
|
||||
|
||||
export const EVENT_EXPAND = 'expand'
|
||||
|
||||
export const APP_DOM_ID = 'bilibili-subtitle'
|
||||
|
@@ -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 { AllAPPMessages, AllExtensionMessages, AllInjectMessages } from '@/message-typings'
|
||||
import { DEFAULT_USE_PORT } from '@/consts/const'
|
||||
import { useMessaging, useMessagingService } from '@kky002/kky-message'
|
||||
import { useMemoizedFn } from 'ahooks'
|
||||
|
||||
const useMessageService = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
//methods
|
||||
const 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))
|
||||
@@ -24,9 +26,10 @@ const useMessageService = () => {
|
||||
dispatch(setAuthor(params.author))
|
||||
console.debug('video title: ', params.title)
|
||||
},
|
||||
}), [dispatch])
|
||||
}))
|
||||
|
||||
useMessagingService(methods)
|
||||
useMessagingService(DEFAULT_USE_PORT, methodsFunc)
|
||||
}
|
||||
|
||||
export default useMessageService
|
||||
export default useMessageService
|
||||
export const useMessage = useMessaging<AllExtensionMessages, AllInjectMessages>
|
@@ -1,16 +1,17 @@
|
||||
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 {sendInject} = useMessage(!!envData.sidePanel)
|
||||
|
||||
const move = useCallback((time: number, togglePause: boolean) => {
|
||||
sendInject('MOVE', {time, togglePause})
|
||||
sendInject(null, 'MOVE', {time, togglePause})
|
||||
|
||||
//review action
|
||||
if (reviewed === undefined && !reviewAction) {
|
||||
|
@@ -19,7 +19,7 @@ import {EventBusContext} from '../Router'
|
||||
import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../consts/const'
|
||||
import {useAsyncEffect, useInterval} from 'ahooks'
|
||||
import {getModelMaxTokens, getWholeText} from '../utils/bizUtil'
|
||||
import { useMessage } from './message'
|
||||
import { useMessage } from './useMessageService'
|
||||
|
||||
/**
|
||||
* Service是单例,类似后端的服务概念
|
||||
@@ -43,7 +43,7 @@ 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
|
||||
useEffect(() => {
|
||||
@@ -78,7 +78,7 @@ const useSubtitleService = () => {
|
||||
// 获取
|
||||
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
|
||||
})
|
||||
@@ -93,12 +93,12 @@ const useSubtitleService = () => {
|
||||
|
||||
useAsyncEffect(async () => {
|
||||
// 初始获取列表
|
||||
sendInject('REFRESH_VIDEO_INFO', {force: true})
|
||||
sendInject(null, 'REFRESH_VIDEO_INFO', {force: true})
|
||||
}, [])
|
||||
|
||||
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
|
||||
@@ -194,7 +194,7 @@ const useSubtitleService = () => {
|
||||
|
||||
// 每0.5秒更新当前视频时间
|
||||
useInterval(() => {
|
||||
sendInject('GET_VIDEO_STATUS', {}).then(status => {
|
||||
sendInject(null, 'GET_VIDEO_STATUS', {}).then(status => {
|
||||
dispatch(setCurrentTime(status.currentTime))
|
||||
})
|
||||
}, 500)
|
||||
@@ -202,15 +202,15 @@ const useSubtitleService = () => {
|
||||
// show translated text in the video
|
||||
useEffect(() => {
|
||||
if (hideOnDisableAutoTranslate && !autoTranslate) {
|
||||
sendInject('HIDE_TRANS', {})
|
||||
sendInject(null, 'HIDE_TRANS', {})
|
||||
return
|
||||
}
|
||||
|
||||
const transResult = curIdx?transResults[curIdx]:undefined
|
||||
if (transResult?.code === '200' && transResult.data) {
|
||||
sendInject('UPDATE_TRANS_RESULT', {result: transResult.data})
|
||||
sendInject(null, 'UPDATE_TRANS_RESULT', {result: transResult.data})
|
||||
} else {
|
||||
sendInject('HIDE_TRANS', {})
|
||||
sendInject(null, 'HIDE_TRANS', {})
|
||||
}
|
||||
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, transResults])
|
||||
}
|
||||
|
@@ -29,7 +29,7 @@ import toast from 'react-hot-toast'
|
||||
import {useMemoizedFn} from 'ahooks/es'
|
||||
import {extractJsonArray, extractJsonObject, getModel} from '../utils/bizUtil'
|
||||
import {formatTime} from '../utils/util'
|
||||
import { useMessage } from './message'
|
||||
import { useMessage } from './useMessageService'
|
||||
const useTranslate = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
const data = useAppSelector(state => state.env.data)
|
||||
@@ -43,7 +43,7 @@ const useTranslate = () => {
|
||||
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
|
||||
const reviewAction = useAppSelector(state => state.env.reviewAction)
|
||||
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
|
||||
const {sendExtension} = useMessage()
|
||||
const {sendExtension} = useMessage(!!envData.sidePanel)
|
||||
/**
|
||||
* 获取下一个需要翻译的行
|
||||
* 会检测冷却
|
||||
@@ -135,7 +135,7 @@ const useTranslate = () => {
|
||||
}
|
||||
})
|
||||
dispatch(addTransResults(result))
|
||||
const task = await sendExtension('ADD_TASK', {taskDef})
|
||||
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
|
||||
dispatch(addTaskId(task.id))
|
||||
}
|
||||
}
|
||||
@@ -205,7 +205,7 @@ const useTranslate = () => {
|
||||
console.debug('addSummarizeTask', taskDef)
|
||||
dispatch(setSummaryStatus({segmentStartIdx: segment.startIdx, type, status: 'pending'}))
|
||||
dispatch(setLastSummarizeTime(Date.now()))
|
||||
const task = await sendExtension('ADD_TASK', {taskDef})
|
||||
const task = await sendExtension(null, 'ADD_TASK', {taskDef})
|
||||
dispatch(addTaskId(task.id))
|
||||
}
|
||||
}, [dispatch, envData, summarizeLanguage.name, title])
|
||||
@@ -262,7 +262,7 @@ 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])
|
||||
@@ -330,7 +330,7 @@ const useTranslate = () => {
|
||||
})
|
||||
|
||||
const getTask = useCallback(async (taskId: string) => {
|
||||
const taskResp = await sendExtension('GET_TASK', {taskId})
|
||||
const taskResp = await sendExtension(null, 'GET_TASK', {taskId})
|
||||
if (taskResp.code === 'ok') {
|
||||
console.debug('getTask', taskResp.task)
|
||||
const task: Task = taskResp.task
|
||||
|
@@ -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)
|
||||
@@ -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,
|
||||
@@ -193,7 +194,7 @@ const debug = (...args: any[]) => {
|
||||
debug('refreshVideoInfo: ', aid, cid, pages, subtitles)
|
||||
|
||||
//send setVideoInfo
|
||||
runtime.injectMessaging.sendApp('SET_VIDEO_INFO', {
|
||||
runtime.injectMessaging.sendApp(!!sidePanel, 'SET_VIDEO_INFO', {
|
||||
url: location.origin + location.pathname,
|
||||
title,
|
||||
aid,
|
||||
@@ -234,7 +235,7 @@ const debug = (...args: any[]) => {
|
||||
//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
|
||||
})
|
||||
}
|
||||
|
165
src/message-typings.d.ts
vendored
165
src/message-typings.d.ts
vendored
@@ -1,89 +1,90 @@
|
||||
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';
|
||||
}
|
||||
|
||||
interface ExtensionShowFlagMessage extends ExtensionMessage<{ show: boolean }> {
|
||||
method: 'SHOW_FLAG';
|
||||
}
|
||||
|
||||
export type AllExtensionMessages = 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';
|
||||
}
|
||||
|
||||
type AllInjectMessages = InjectToggleDisplayMessage | InjectFoldMessage | InjectMoveMessage | InjectGetSubtitleMessage | InjectGetVideoStatusMessage | InjectGetVideoElementInfoMessage | InjectRefreshVideoInfoMessage | InjectUpdateTransResultMessage | InjectHideTransMessage | InjectPlayMessage | InjectDownloadAudioMessage
|
||||
|
||||
|
||||
//inject
|
||||
interface InjectToggleDisplayMessage extends InjectMessage<{}> {
|
||||
method: 'TOGGLE_DISPLAY';
|
||||
}
|
||||
|
||||
interface InjectFoldMessage extends InjectMessage<{ fold: boolean }> {
|
||||
method: 'FOLD';
|
||||
}
|
||||
|
||||
interface InjectMoveMessage extends InjectMessage<{ time: number, togglePause: boolean }> {
|
||||
method: 'MOVE';
|
||||
}
|
||||
|
||||
interface InjectGetSubtitleMessage extends InjectMessage<{ info: any }> {
|
||||
method: 'GET_SUBTITLE';
|
||||
}
|
||||
|
||||
interface InjectGetVideoStatusMessage extends InjectMessage<{}> {
|
||||
method: 'GET_VIDEO_STATUS';
|
||||
}
|
||||
|
||||
interface InjectGetVideoElementInfoMessage extends InjectMessage<{}> {
|
||||
method: 'GET_VIDEO_ELEMENT_INFO';
|
||||
}
|
||||
|
||||
interface InjectRefreshVideoInfoMessage extends InjectMessage<{ force: boolean }> {
|
||||
method: 'REFRESH_VIDEO_INFO';
|
||||
}
|
||||
|
||||
interface InjectUpdateTransResultMessage extends InjectMessage<{ result: string }> {
|
||||
method: 'UPDATE_TRANS_RESULT';
|
||||
}
|
||||
|
||||
interface InjectHideTransMessage extends InjectMessage<{}> {
|
||||
method: 'HIDE_TRANS';
|
||||
}
|
||||
|
||||
interface InjectPlayMessage extends InjectMessage<{ play: boolean }> {
|
||||
method: 'PLAY';
|
||||
}
|
||||
|
||||
interface InjectDownloadAudioMessage extends InjectMessage<{}> {
|
||||
method: 'DOWNLOAD_AUDIO';
|
||||
}
|
||||
|
||||
export type AllInjectMessages = InjectToggleDisplayMessage | InjectFoldMessage | InjectMoveMessage | InjectGetSubtitleMessage | InjectGetVideoStatusMessage | InjectGetVideoElementInfoMessage | InjectRefreshVideoInfoMessage | InjectUpdateTransResultMessage | InjectHideTransMessage | InjectPlayMessage | InjectDownloadAudioMessage
|
||||
|
||||
|
||||
|
||||
//app
|
||||
interface AppSetInfosMessage extends AppMessage<{ infos: any }> {
|
||||
method: 'SET_INFOS';
|
||||
}
|
||||
|
||||
interface AppSetVideoInfoMessage extends AppMessage<{ url: string, title: string, aid: number | null, ctime: number | null, author?: string, pages: any, infos: any }> {
|
||||
method: 'SET_VIDEO_INFO';
|
||||
}
|
||||
|
||||
type AllAPPMessages = AppSetInfosMessage | AppSetVideoInfoMessage
|
||||
|
||||
|
||||
|
||||
|
||||
//app
|
||||
interface AppSetInfosMessage extends AppMessage<{ infos: any }> {
|
||||
method: 'SET_INFOS';
|
||||
}
|
||||
|
||||
interface AppSetVideoInfoMessage extends AppMessage<{ url: string, title: string, aid: number | null, ctime: number | null, author?: string, pages: any, infos: any }> {
|
||||
method: 'SET_VIDEO_INFO';
|
||||
}
|
||||
|
||||
export type AllAPPMessages = AppSetInfosMessage | AppSetVideoInfoMessage
|
||||
|
||||
|
@@ -1,38 +0,0 @@
|
||||
## 消息通信库封装
|
||||
此消息通信库设计为通用的,后面可能会提取到单独的项目中。
|
||||
|
||||
### 消息端
|
||||
|
||||
一共分3个端:
|
||||
|
||||
1. 扩展端(`background.ts`):扩展后台服务,整个浏览器最多一个实例。
|
||||
2. 注入端(`inject.ts`):会注入到网页中运行,可以访问网页元素,每个网页可能n个实例(看注入的次数),但多个实例一般是不必要的,所以尽量控制在一个实例。
|
||||
3. 应用端(`App.tsx`):会放入iframe中,然后iframe元素添加到网页上,每个iframe一个实例;或者options.html选项页面也是应用实例;或者sidepanel.html页面也是应用实例。
|
||||
|
||||
### 消息协议
|
||||
|
||||
协议分两层:
|
||||
|
||||
1. (底层)一层协议为`Layer1Protocol`,内部封装了port,支持双向通信(发送与接收)
|
||||
2. (高层)二层协议分3个部分,基于一层协议:
|
||||
1. `ExtensionMessaging`:扩展端的
|
||||
2. `InjectMessaging`:注入端端
|
||||
3. `useMessagingService`与`useMessaging`:应用端的
|
||||
|
||||
### 通信方向
|
||||
|
||||
通信分为6个方向:
|
||||
|
||||
1. 扩展端 --> 注入端
|
||||
2. 扩展端 --> 应用端
|
||||
3. 注入端 --> 扩展端
|
||||
4. 注入端 --> 应用端
|
||||
5. 应用端 --> 注入端
|
||||
6. 应用端 --> 扩展端
|
||||
|
||||
应用端与注入端通信实现方式:通过扩展端中转。
|
||||
|
||||
### 通信流程
|
||||
|
||||
1. 注入端:通过port连接扩展端,然后发送握手信息(里面包含了此端的一些信息)
|
||||
2. 应用端:同注入端。
|
@@ -1,16 +0,0 @@
|
||||
// 请求信息
|
||||
export type L2ReqMsg = {
|
||||
from: 'extension' | 'inject' | 'app'
|
||||
method: string
|
||||
params?: any
|
||||
}
|
||||
|
||||
// 响应信息
|
||||
export type L2ResMsg<L2Res = any> = {
|
||||
code: number
|
||||
msg?: string
|
||||
data?: L2Res
|
||||
}
|
||||
|
||||
export const TAG_TARGET_INJECT = 'target:inject'
|
||||
export const TAG_TARGET_APP = 'target:app'
|
@@ -1,122 +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 });
|
||||
|
||||
try {
|
||||
this.port.postMessage({ id, type: 'req', req });
|
||||
} catch (error) {
|
||||
clearTimeout(timer);
|
||||
this.requests.delete(id);
|
||||
this.dispose();
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
@@ -26,8 +26,8 @@ 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);
|
||||
@@ -66,7 +66,7 @@ const FormItem = (props: {
|
||||
const OptionsPage = () => {
|
||||
const dispatch = useAppDispatch()
|
||||
const envData = useAppSelector(state => state.env.envData)
|
||||
const {sendExtension} = useMessage()
|
||||
const {sendExtension} = useMessage(false)
|
||||
const {value: sidePanelValue, onChange: setSidePanelValue} = useEventChecked(envData.sidePanel)
|
||||
const {value: autoInsertValue, onChange: setAutoInsertValue} = useEventChecked(!envData.manualInsert)
|
||||
const {value: autoExpandValue, onChange: setAutoExpandValue} = useEventChecked(envData.autoExpand)
|
||||
@@ -148,7 +148,7 @@ const OptionsPage = () => {
|
||||
askEnabled: askEnabledValue,
|
||||
}))
|
||||
toast.success('保存成功')
|
||||
sendExtension('CLOSE_SIDE_PANEL')
|
||||
sendExtension(null, 'CLOSE_SIDE_PANEL')
|
||||
// 3秒后关闭
|
||||
setTimeout(() => {
|
||||
window.close()
|
||||
|
Reference in New Issue
Block a user