diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d6cb201a..d4085e03 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -54,3 +54,12 @@ jobs: with: name: BewlyBewly Zip path: extension + + - name: Build Extension + run: pnpm build-firefox + + - name: Upload Zip + uses: actions/upload-artifact@v3 + with: + name: BewlyBewly Zip + path: extension-firefox diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index d0584e26..8f08052e 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -19,6 +19,6 @@ jobs: token: ${{ secrets.RELEASE_TOKEN }} release-type: node package-name: release-please-action - release-as: 0.16.1 + release-as: 0.16.2 signoff: 'github-actions <41898282+github-actions[bot]@users.noreply.github.com>' changelog-types: '[{"type":"types","section":"Types","hidden":false},{"type":"revert","section":"Reverts","hidden":false},{"type":"feat","section":"Features","hidden":false},{"type":"fix","section":"Bug Fixes","hidden":false},{"type":"improvement","section":"Feature Improvements","hidden":false},{"type":"docs","section":"Docs","hidden":false},{"type":"i18n","section":"I18n","hidden":true},{"type":"style","section":"Style Changes","hidden":false},{"type":"ci","section":"CI","hidden":false},{"type":"chore","section":"Miscellaneous","hidden":true},{"type":"contributor","section":"New Contributors","hidden":false},{"type":"notice","section":"Notices","hidden":false}]' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fa5fed69..ede790ed 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -36,15 +36,21 @@ jobs: run: pnpm install - name: Build - run: pnpm build + run: | + pnpm build + pnpm build-firefox - name: Build Extension - run: pnpm pack:zip + run: | + pnpm pack:zip + pnpm pack:zip-firefox - name: Upload assets to a Release uses: meeDamian/github-release@v2.0.3 with: - files: extension.zip + files: | + extension.zip + extension-firefox.zip token: ${{ secrets.RELEASE_TOKEN }} allow_override: true gzip: false diff --git a/.vscode/settings.json b/.vscode/settings.json index 2fa133da..f6e7dd54 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,6 @@ { "cSpell.words": [ + "WATCHLATER", "bewly", "bilibili", "unocss", diff --git a/assets/rules.json b/assets/rules.json index ca397ae6..9c30657d 100644 --- a/assets/rules.json +++ b/assets/rules.json @@ -20,7 +20,8 @@ "condition": { "domainType": "thirdParty", "urlFilter": "||api.bilibili.com", - "resourceTypes": ["xmlhttprequest"] + "resourceTypes": ["xmlhttprequest"], + "requestMethods": ["post"] } }, { @@ -44,7 +45,8 @@ "condition": { "domainType": "thirdParty", "urlFilter": "||passport.bilibili.com", - "resourceTypes": ["xmlhttprequest"] + "resourceTypes": ["xmlhttprequest"], + "requestMethods": ["post"] } } ] diff --git a/src/background/messageListeners/anime.ts b/src/background/messageListeners/anime.ts index 4c38742d..4e5d1455 100644 --- a/src/background/messageListeners/anime.ts +++ b/src/background/messageListeners/anime.ts @@ -1,57 +1,68 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { - // get popular anime list - if (message.contentScriptQuery === 'getPopularAnimeList') { - const url - = 'https://api.bilibili.com/pgc/web/rank/list?season_type=1&day=3' - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } +const API_ANIME: APIMAP = { // https://github.com/SocialSisterYi/bilibili-API-collect/blob/36e250090800793b41b223b55eefdcbb9391b53e/user/space.md#%E6%9F%A5%E8%AF%A2%E7%94%A8%E6%88%B7%E8%BF%BD%E7%95%AA%E8%BF%BD%E5%89%A7%E6%98%8E%E7%BB%86 - else if (message.contentScriptQuery === 'getAnimeWatchList') { - const url = `https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=0&pn=${message.pn}&ps=${message.ps}&vmid=${message.vmid}` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } - else if (message.contentScriptQuery === 'getRecommendAnimeList') { - const url = `https://api.bilibili.com/pgc/page/web/v3/feed?name=anime&coursor=${ - message.coursor ?? '' - }` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getPopularAnimeList: { + url: 'https://api.bilibili.com/pgc/web/rank/list', + _fetch: { + method: 'get', + }, + params: { + season_type: 1, + day: 3, + }, + afterHandle: AHS.J_D, + }, + // https://github.com/SocialSisterYi/bilibili-API-collect/blob/36e250090800793b41b223b55eefdcbb9391b53e/user/space.md#%E6%9F%A5%E8%AF%A2%E7%94%A8%E6%88%B7%E8%BF%BD%E7%95%AA%E8%BF%BD%E5%89%A7%E6%98%8E%E7%BB%86 + getAnimeWatchList: { + url: 'https://api.bilibili.com/x/space/bangumi/follow/list', + _fetch: { + method: 'get', + }, + params: { + pn: 1, + ps: 15, + type: 1, + follow_status: 0, + vmid: '', + }, + afterHandle: AHS.J_D, + }, + getRecommendAnimeList: { + url: 'https://api.bilibili.com/pgc/page/web/v3/feed', + _fetch: { + method: 'get', + }, + params: { + coursor: '', + name: 'anime', + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/bangumi/timeline.md#%E7%95%AA%E5%89%A7%E6%88%96%E5%BD%B1%E8%A7%86%E6%97%B6%E9%97%B4%E7%BA%BF - else if (message.contentScriptQuery === 'getAnimeTimeTable') { - const url - = 'https://api.bilibili.com/pgc/web/timeline?types=1&before=6&after=6' - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } - else if (message.contentScriptQuery === 'getAnimeDetail') { - const url = 'https://api.bilibili.com/pgc/view/web/season?ep_id=234406' - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } - // TODO: https://api.bilibili.com/pgc/season/index/condition?season_type=1&type=1 + getAnimeTimeTable: { + url: 'https://api.bilibili.com/pgc/web/timeline', + _fetch: { + method: 'get', + }, + params: { + types: 1, + before: 6, + after: 6, + }, + afterHandle: AHS.J_D, + }, + getAnimeDetail: { + url: 'https://api.bilibili.com/pgc/view/web/season', + _fetch: { + method: 'get', + }, + params: { + // ep_id: '234406', + }, + afterHandle: AHS.J_D, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupAnimeMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_ANIME diff --git a/src/background/messageListeners/auth.ts b/src/background/messageListeners/auth.ts index a8391386..b50caa3f 100644 --- a/src/background/messageListeners/auth.ts +++ b/src/background/messageListeners/auth.ts @@ -1,70 +1,59 @@ -import browser from 'webextension-polyfill' +// 由于 sendResponse 复杂, 所以使用自定义的函数 +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any, sender: any, sendResponse: any) { - if (message.contentScriptQuery === 'getAccessKey') { - const url = message.confirmUri - fetch(url) - .then(response => sendResponse({ accessKey: `${response.url}`.match(/access_key=([0-9a-z]{32})/)![1] })) - .catch(error => console.error(error)) - return true - } - else if (message.contentScriptQuery === 'logout') { - const url = `https://passport.bilibili.com/login/exit/v2?biliCSRF=${message.biliCSRF}` - fetch(url, { - method: 'POST', - body: JSON.stringify({ - biliCSRF: message.biliJct, - }), - }) - .then(response => response.json()) - .then(data => sendResponse(data)) - .catch(error => console.error(error)) - } - else if (message.contentScriptQuery === 'getLoginQRCode') { - const url = 'https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code' - fetch(url, { - method: 'POST', +const API_AUTH: APIMAP = { + // biliJct 似乎没有使用 + logout: { + url: 'https://passport.bilibili.com/login/exit/v2', + _fetch: { + method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }, - body: new URLSearchParams({ - appkey: '4409e2ce8ffd12b8', - local_id: '0', - ts: '0', - sign: 'e134154ed6add881d28fbdf68653cd9c', - }), - }) - .then(response => response.json()) - .then(data => sendResponse(data)) - .catch(error => console.error(error)) - } - else if (message.contentScriptQuery === 'qrCodeLogin') { - const url = 'https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code' - fetch(url, { - method: 'POST', + body: { + biliCSRF: '', + // biliJct: '', + }, + }, + params: { + biliCSRF: '', + }, + afterHandle: AHS.J_S, + }, + getLoginQRCode: { + url: 'https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code', + _fetch: { + method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }, - body: new URLSearchParams({ - appkey: '4409e2ce8ffd12b8', - auth_code: message.authCode, - local_id: '0', - ts: '0', - sign: 'e134154ed6add881d28fbdf68653cd9c', - }), - }) - .then(response => response.json()) - .then(data => sendResponse(data)) - .catch(error => console.error(error)) - } + }, + params: { + appkey: '4409e2ce8ffd12b8', + local_id: '0', + ts: '0', + sign: 'e134154ed6add881d28fbdf68653cd9c', + }, + afterHandle: AHS.J_S, + }, + qrCodeLogin: { + url: 'https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code', + _fetch: { + method: 'post', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', + }, + }, + params: { + appkey: '4409e2ce8ffd12b8', + auth_code: '', + local_id: '0', + ts: '0', + sign: 'e134154ed6add881d28fbdf68653cd9c', + }, + afterHandle: AHS.J_S, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupAuthMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_AUTH diff --git a/src/background/messageListeners/favorite.ts b/src/background/messageListeners/favorite.ts index 38f7bcbf..069067a0 100644 --- a/src/background/messageListeners/favorite.ts +++ b/src/background/messageListeners/favorite.ts @@ -1,48 +1,49 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { +const API_FAVORITE: APIMAP = { // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/fav/info.md#%E8%8E%B7%E5%8F%96%E6%8C%87%E5%AE%9A%E7%94%A8%E6%88%B7%E5%88%9B%E5%BB%BA%E7%9A%84%E6%89%80%E6%9C%89%E6%94%B6%E8%97%8F%E5%A4%B9%E4%BF%A1%E6%81%AF - if (message.contentScriptQuery === 'getFavoriteCategories') { - const url = `https://api.bilibili.com/x/v3/fav/folder/created/list-all?up_mid=${message.mid}&jsonp=jsonp` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getFavoriteCategories: { + url: 'https://api.bilibili.com/x/v3/fav/folder/created/list-all', + _fetch: { + method: 'get', + }, + params: { + up_mid: '', + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/fav/list.md#%E8%8E%B7%E5%8F%96%E6%94%B6%E8%97%8F%E5%A4%B9%E5%86%85%E5%AE%B9%E6%98%8E%E7%BB%86%E5%88%97%E8%A1%A8 - else if (message.contentScriptQuery === 'getFavoriteResources') { - const url = `https://api.bilibili.com/x/v3/fav/resource/list?media_id=${message.mediaId}&pn=${message.pageNum}&ps=20&keyword=${message.keyword}&order=mtime&type=0&tid=0&platform=web&jsonp=jsonp` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getFavoriteResources: { + url: 'https://api.bilibili.com/x/v3/fav/resource/list', + _fetch: { + method: 'get', + }, + params: { + media_id: '', + pn: 1, + ps: 20, + keyword: '', + order: 'mtime', + type: 0, + tid: 0, + platform: 'web', + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/fav/action.md#%E6%89%B9%E9%87%8F%E5%88%A0%E9%99%A4%E5%86%85%E5%AE%B9 - else if (message.contentScriptQuery === 'patchDelFavoriteResources') { - const url = 'https://api.bilibili.com/x/v3/fav/resource/batch-del' - return fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', - }, - body: new URLSearchParams({ - resources: message.resources, - media_id: message.mediaId, - csrf: message.csrf, - }), - }) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + patchDelFavoriteResources: { + url: 'https://api.bilibili.com/x/v3/fav/resource/batch-del', + _fetch: { + method: 'post', + }, + params: { + resources: '', + media_id: '', + csrf: '', + }, + afterHandle: AHS.J_D, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupFavoriteMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_FAVORITE diff --git a/src/background/messageListeners/history.ts b/src/background/messageListeners/history.ts index b438ad9d..1a42bd92 100644 --- a/src/background/messageListeners/history.ts +++ b/src/background/messageListeners/history.ts @@ -1,81 +1,85 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { +const API_HISTORY: APIMAP = { // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/history.md#%E8%8E%B7%E5%8F%96%E5%8E%86%E5%8F%B2%E8%AE%B0%E5%BD%95%E5%88%97%E8%A1%A8_web%E7%AB%AF - if (message.contentScriptQuery === 'getHistoryList') { - const url = `https://api.bilibili.com/x/web-interface/history/cursor?ps=20&type=${message.type}&view_at=${message.viewAt}` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } - else if (message.contentScriptQuery === 'searchHistoryList') { - const url = `https://api.bilibili.com/x/web-goblin/history/search?pn=${message.pn}&keyword=${message.keyword}&business=all` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getHistoryList: { + url: 'https://api.bilibili.com/x/web-interface/history/cursor', + _fetch: { + method: 'get', + }, + params: { + ps: 20, + type: '', + view_at: '', + }, + afterHandle: AHS.J_D, + }, + searchHistoryList: { + url: 'https://api.bilibili.com/x/web-goblin/history/search', + _fetch: { + method: 'get', + }, + params: { + pn: 1, + keyword: '', + business: 'all', + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/history.md#%E5%88%A0%E9%99%A4%E5%8E%86%E5%8F%B2%E8%AE%B0%E5%BD%95 - else if (message.contentScriptQuery === 'deleteHistoryItem') { - const url = 'https://api.bilibili.com/x/v2/history/delete' - return fetch(url, { - method: 'POST', + deleteHistoryItem: { + url: 'https://api.bilibili.com/x/v2/history/delete', + _fetch: { + method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }, - body: new URLSearchParams({ - kid: message.kid, - csrf: message.csrf, - }), - }) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + body: { + aid: '', + csrf: '', + }, + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/history.md#%E6%B8%85%E7%A9%BA%E5%8E%86%E5%8F%B2%E8%AE%B0%E5%BD%95 - else if (message.contentScriptQuery === 'clearAllHistory') { - const url = 'https://api.bilibili.com/x/v2/history/clear' - return fetch(url, { - method: 'POST', - body: new URLSearchParams({ - csrf: message.csrf, - }), - }) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + clearAllHistory: { + url: 'https://api.bilibili.com/x/v2/history/clear', + _fetch: { + method: 'post', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', + }, + body: { + csrf: '', + }, + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/history.md#%E6%9F%A5%E8%AF%A2%E5%8E%86%E5%8F%B2%E8%AE%B0%E5%BD%95%E5%81%9C%E7%94%A8%E7%8A%B6%E6%80%81 - else if (message.contentScriptQuery === 'getHistoryPauseStatus') { - const url = 'https://api.bilibili.com/x/v2/history/shadow' - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getHistoryPauseStatus: { + url: 'https://api.bilibili.com/x/v2/history/shadow', + _fetch: { + method: 'get', + }, + params: {}, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/history.md#%E5%81%9C%E7%94%A8%E5%8E%86%E5%8F%B2%E8%AE%B0%E5%BD%95 - else if (message.contentScriptQuery === 'setHistoryPauseStatus') { - const url = 'https://api.bilibili.com/x/v2/history/shadow/set' - return fetch(url, { - method: 'POST', - body: new URLSearchParams({ - switch: message.switch, - csrf: message.csrf, - }), - }) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + setHistoryPauseStatus: { + url: 'https://api.bilibili.com/x/v2/history/shadow/set', + _fetch: { + method: 'post', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', + }, + body: { + switch: '', + csrf: '', + }, + }, + afterHandle: AHS.J_D, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupHistoryMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_HISTORY diff --git a/src/background/messageListeners/index.ts b/src/background/messageListeners/index.ts index d2888651..16ce931d 100644 --- a/src/background/messageListeners/index.ts +++ b/src/background/messageListeners/index.ts @@ -1,25 +1,23 @@ -import { setupAnimeMsgLstnr } from './anime' -import { setupAuthMsgLstnr } from './auth' -import { setupVideoMsgLstnr } from './video' -import { setupUserMsgLstnr } from './user' -import { setupSearchMsgLstnr } from './search' -import { setupNotificationMsgLstnr } from './notification' -import { setupMomentMsgLstnr } from './moment' -import { setupHistoryMsgLstnr } from './history' -import { setupFavoriteMsgLstnr } from './favorite' -import { setupWatchLaterMsgLstnr } from './watchLater' -import { setupRankingMsgLstnr } from './ranking' +import browser from 'webextension-polyfill' +import { apiListenerFactory } from '../utils' + +import API_AUTH from './auth' +import API_ANIME from './anime' +import API_HISTORY from './history' +import API_FAVORITE from './favorite' +import API_MOMENT from './moment' +import API_NOTIFICATION from './notification' +import API_RANKING from './ranking' +import API_SEARCH from './search' +import API_USER from './user' +import API_VIDEO from './video' +import API_WATCHLATER from './watchLater' export function setupAllMsgLstnrs() { - setupAuthMsgLstnr() - setupVideoMsgLstnr() - setupUserMsgLstnr() - setupSearchMsgLstnr() - setupNotificationMsgLstnr() - setupMomentMsgLstnr() - setupHistoryMsgLstnr() - setupFavoriteMsgLstnr() - setupAnimeMsgLstnr() - setupWatchLaterMsgLstnr() - setupRankingMsgLstnr() + // Merge all API objects into one + const FullAPI = Object.assign({}, API_AUTH, API_ANIME, API_HISTORY, API_FAVORITE, API_MOMENT, API_NOTIFICATION, API_RANKING, API_SEARCH, API_USER, API_VIDEO, API_WATCHLATER) + // Create a message listener for each API + const handleMessage = apiListenerFactory(FullAPI) + browser.runtime.onMessage.removeListener(handleMessage) + browser.runtime.onMessage.addListener(handleMessage) } diff --git a/src/background/messageListeners/moment.ts b/src/background/messageListeners/moment.ts index 17653b6b..05eb1672 100644 --- a/src/background/messageListeners/moment.ts +++ b/src/background/messageListeners/moment.ts @@ -1,74 +1,62 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { - if (message.contentScriptQuery === 'getTopBarNewMomentsCount') { - const url = 'https://api.bilibili.com/x/web-interface/dynamic/entrance' - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } +const API_MOMENT: APIMAP = { + getTopBarNewMomentsCount: { + url: 'https://api.bilibili.com/x/web-interface/dynamic/entrance', + _fetch: { + method: 'get', + }, + params: {}, + afterHandle: AHS.J_D, + }, + getTopBarNewMoments: { + url: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_new', + _fetch: { + method: 'get', + }, + params: { + uid: '', + type_list: '268435455', + }, + afterHandle: AHS.J_D, + }, + getTopbarHistoryMoments: { + url: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_history', + _fetch: { + method: 'get', + }, + params: { + uid: '', + type_list: '268435455', + offset_dynamic_id: '', + }, + afterHandle: AHS.J_D, + }, + getTopbarLiveMoments: { + url: 'https://api.live.bilibili.com/xlive/web-ucenter/v1/xfetter/FeedList', + _fetch: { + method: 'get', + }, + params: { + page: 1, + pagesize: 10, + }, + afterHandle: AHS.J_D, + }, + getMoments: { + url: 'https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all', + _fetch: { + method: 'get', + }, + params: { + type: 268435455, + offset: 0, + update_baseline: 0, + }, + afterHandle: AHS.J_D, + }, - // v2 get moment list - // else if (message.contentScriptQuery === 'getTopBarNewMoments') { - // // type: video | article - // const url = `https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/nav?type=${message.type}&update_baseline=${message.updateBaseline}` - // return fetch(url) - // .then(response => response.json()) - // .then(data => (data)) - // .catch(error => console.error(error)) - // } - // else if (message.contentScriptQuery === 'getTopbarLiveMoments') { - // const url = `https://api.live.bilibili.com/xlive/web-ucenter/v1/xfetter/FeedList?page=${message.page}&pagesize=10` - // return fetch(url) - // .then(response => response.json()) - // .then(data => (data)) - // .catch(error => console.error(error)) - // } - - else if (message.contentScriptQuery === 'getTopBarNewMoments') { - const url = `https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_new?uid=${message.uid} - &type_list=${message.typeList}` - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } - - else if (message.contentScriptQuery === 'getTopbarHistoryMoments') { - const url = `https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/dynamic_history?uid=${message.uid} - &type_list=${message.typeList} - &offset_dynamic_id=${message.offsetDynamicID}` - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } - - else if (message.contentScriptQuery === 'getTopbarLiveMoments') { - const url = `https://api.live.bilibili.com/xlive/web-ucenter/v1/xfetter/FeedList?page=${message.page}&pagesize=${message.pageSize}` - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } - - // https://socialsisteryi.github.io/bilibili-API-collect/docs/dynamic/all.html#%E8%8E%B7%E5%8F%96%E5%8A%A8%E6%80%81%E5%88%97%E8%A1%A8 - else if (message.contentScriptQuery === 'getMoments') { - const url = `https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all?timezone_offset=-480&type=${message.type}&offset=${message.offset}&update_baseline=${message.updateBaseline}` - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupMomentMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_MOMENT diff --git a/src/background/messageListeners/notification.ts b/src/background/messageListeners/notification.ts index 0c35c94f..ad98a9dc 100644 --- a/src/background/messageListeners/notification.ts +++ b/src/background/messageListeners/notification.ts @@ -1,29 +1,30 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { - if (message.contentScriptQuery === 'getUnreadMsg') { - const url = 'https://api.bilibili.com/x/msgfeed/unread?build=0&mobi_app=web' - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } - - else if (message.contentScriptQuery === 'getUnreadDm') { - const url = 'https://api.vc.bilibili.com/session_svr/v1/session_svr/single_unread?build=0&mobi_app=web&unread_type=0' - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } +const API_NOTIFICATION: APIMAP = { + getUnreadMsg: { + url: 'https://api.bilibili.com/x/msgfeed/unread', + _fetch: { + method: 'get', + }, + params: { + build: 0, + mobi_app: 'web', + }, + afterHandle: AHS.J_D, + }, + getUnreadDm: { + url: 'https://api.vc.bilibili.com/session_svr/v1/session_svr/single_unread', + _fetch: { + method: 'get', + }, + params: { + build: 0, + mobi_app: 'web', + unread_type: 0, + }, + afterHandle: AHS.J_D, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupNotificationMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_NOTIFICATION diff --git a/src/background/messageListeners/ranking.ts b/src/background/messageListeners/ranking.ts index a17d68db..615d553f 100644 --- a/src/background/messageListeners/ranking.ts +++ b/src/background/messageListeners/ranking.ts @@ -1,29 +1,30 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { +const API_RANKING: APIMAP = { // https://github.com/SocialSisterYi/bilibili-API-collect/blob/7873a79022a5606e2391d93b411a05576a0df111/docs/video_ranking/ranking.md#%E8%8E%B7%E5%8F%96%E5%88%86%E5%8C%BA%E8%A7%86%E9%A2%91%E6%8E%92%E8%A1%8C%E6%A6%9C%E5%88%97%E8%A1%A8 - if (message.contentScriptQuery === 'getRankingVideos') { - const url = `https://api.bilibili.com/x/web-interface/ranking/v2?rid=${message.rid ?? 0}&type=${message.type ?? 'all'}` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } - else if (message.contentScriptQuery === 'getRankingPgc') { - const url = `https://api.bilibili.com/pgc/web/rank/list?day=3&season_type=${message.seasonType}` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getRankingVideos: { + url: 'https://api.bilibili.com/x/web-interface/ranking/v2', + _fetch: { + method: 'get', + }, + params: { + rid: 0, + type: 'all', + }, + afterHandle: AHS.J_D, + }, + getRankingPgc: { + url: 'https://api.bilibili.com/pgc/web/rank/list', + _fetch: { + method: 'get', + }, + params: { + season_type: 1, + day: 3, + }, + afterHandle: AHS.J_D, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupRankingMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_RANKING diff --git a/src/background/messageListeners/search.ts b/src/background/messageListeners/search.ts index 07993af1..b2aa4387 100644 --- a/src/background/messageListeners/search.ts +++ b/src/background/messageListeners/search.ts @@ -1,21 +1,18 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { - if (message.contentScriptQuery === 'getSearchSuggestion') { - const url = `https://s.search.bilibili.com/main/suggest?term=${message.term}&highlight=` - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } +const API_SEARCH: APIMAP = { + getSearchSuggestion: { + url: 'https://s.search.bilibili.com/main/suggest', + _fetch: { + method: 'get', + }, + params: { + term: '', + highlight: '', + }, + afterHandle: AHS.J_D, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupSearchMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_SEARCH diff --git a/src/background/messageListeners/user.ts b/src/background/messageListeners/user.ts index 84823077..64a31bf9 100644 --- a/src/background/messageListeners/user.ts +++ b/src/background/messageListeners/user.ts @@ -1,30 +1,22 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { +const API_USER: APIMAP = { // https://github.com/SocialSisterYi/bilibili-API-collect/blob/e379d904c2753fa30e9083f59016f07e89d19467/docs/login/login_info.md#%E5%AF%BC%E8%88%AA%E6%A0%8F%E7%94%A8%E6%88%B7%E4%BF%A1%E6%81%AF - if (message.contentScriptQuery === 'getUserInfo') { - const url = 'https://api.bilibili.com/x/web-interface/nav' - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } - - else if (message.contentScriptQuery === 'getUserStat') { - const url = 'https://api.bilibili.com/x/web-interface/nav/stat' - return fetch(url) - .then(response => response.json()) - .then(data => (data)) - .catch(error => console.error(error)) - } + getUserInfo: { + url: 'https://api.bilibili.com/x/web-interface/nav', + _fetch: { + method: 'get', + }, + afterHandle: AHS.J_D, + }, + getUserStat: { + url: 'https://api.bilibili.com/x/web-interface/nav/stat', + _fetch: { + method: 'get', + }, + afterHandle: AHS.J_D, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupUserMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_USER diff --git a/src/background/messageListeners/video.ts b/src/background/messageListeners/video.ts index 8b081b1f..d1a52416 100644 --- a/src/background/messageListeners/video.ts +++ b/src/background/messageListeners/video.ts @@ -1,127 +1,134 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { - /** Submit a video that is not of interest */ - if (message.contentScriptQuery === 'dislikeVideo') { - // https://github.com/indefined/UserScripts/blob/master/bilibiliHome/bilibiliHome.API.md#%E6%8F%90%E4%BA%A4%E4%B8%8D%E5%96%9C%E6%AC%A2 - const url = `https://app.bilibili.com/x/feed/dislike?access_key=${message.access_key}` - + `&goto=${message.goto}` - + `&id=${message.id}` - + `&idx=${message.idx}` - // + `&mid=${message.mid}` - + `&reason_id=${message.reason_id}` - // + `&rid=${message.rid}` - // + `&tag_id=${message.tagId}` - + `&device=${message.device}` - + `&mobi_app=${message.mobi_app}` - + `&build=${message.build}` - + `&sign=${message.sign}` - + `&appkey=${message.appkey}` - - // // remove url empty spaces - // url = url.replace(/\s+/g, '') - - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } - - /** Undo a video that is not of interest */ - else if (message.contentScriptQuery === 'undoDislikeVideo') { - // https://github.com/indefined/UserScripts/blob/master/bilibiliHome/bilibiliHome.API.md#%E6%92%A4%E9%94%80%E4%B8%8D%E5%96%9C%E6%AC%A2 - const url = `https://app.bilibili.com/x/feed/dislike/cancel?access_key=${message.access_key}` - + `&goto=${message.goto}` - + `&id=${message.id}` - + `&idx=${message.idx}` - // + `&mid=${message.mid}` - + `&reason_id=${message.reason_id}` - // + `&rid=${message.rid}` - // + `&tag_id=${message.tagId}` - + `&device=${message.device}` - + `&mobi_app=${message.mobi_app}` - + `&build=${message.build}` - + `&sign=${message.sign}` - + `&appkey=${message.appkey}` - - // // remove url empty spaces - // url = url.replace(/\s+/g, '') - - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } - - if (message.contentScriptQuery === 'getRecommendVideos') { - const url = `https://api.bilibili.com/x/web-interface/index/top/feed/rcmd?fresh_idx=${message.refreshIdx}&feed_version=V2&fresh_type=4&ps=30&plat=1` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } - else if (message.contentScriptQuery === 'getAppRecommendVideos') { - // const url = `https://app.bilibili.com/x/feed/index?build=1&idx=${message.idx}&appkey=27eb53fc9058f8c3&access_key=${message.accessKey}` - const url = `https://app.bilibili.com/x/v2/feed/index?build=74800100&device=pad&mobi_app=iphone&c_locate=${message.cLocate}&s_locale=${message.sLocale}&idx=${message.idx}&appkey=${message.appkey}&access_key=${message.accessKey}` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } - else if (message.contentScriptQuery === 'dislikeVideo') { - const url = `https://api.bilibili.com/x/feed/dislike?access_key=${message.accessKey}&appkey=${message.appkey}&feedback_id=${message.feedbackId}&reason_id=${message.reasonId}` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } +const API_VIDEO: APIMAP = { + getRecommendVideos: { + url: 'https://api.bilibili.com/x/web-interface/index/top/feed/rcmd', + _fetch: { + method: 'get', + }, + params: { + fresh_idx: 0, + feed_version: 'V2', + fresh_type: 4, + ps: 30, + plat: 1, + }, + afterHandle: AHS.J_D, + }, + getAppRecommendVideos: { + url: 'https://app.bilibili.com/x/v2/feed/index', + _fetch: { + method: 'get', + }, + params: { + build: 74800100, + device: 'pad', + mobi_app: 'iphone', + c_locate: 'CN', + s_locale: 'zh-CN', + idx: 0, + appkey: '27eb53fc9058f8c3', + access_key: '', + }, + afterHandle: AHS.J_D, + }, + // https://github.com/indefined/UserScripts/blob/master/bilibiliHome/bilibiliHome.API.md#%E6%8F%90%E4%BA%A4%E4%B8%8D%E5%96%9C%E6%AC%A2 + dislikeVideo: { + url: 'https://app.bilibili.com/x/feed/dislike', + _fetch: { + method: 'get', + }, + params: { + access_key: '', + goto: '', + id: 0, + idx: 0, + reason_id: 1, + device: '', + mobi_app: '', + build: 0, + appkey: '', + sign: '', + }, + afterHandle: AHS.J_D, + }, + // https://github.com/indefined/UserScripts/blob/master/bilibiliHome/bilibiliHome.API.md#%E6%92%A4%E9%94%80%E4%B8%8D%E5%96%9C%E6%AC%A2 + undoDislikeVideo: { + url: 'https://app.bilibili.com/x/feed/dislike/cancel', + _fetch: { + method: 'get', + }, + params: { + access_key: '', + goto: '', + id: 0, + idx: 0, + reason_id: 1, + device: '', + mobi_app: '', + build: 0, + sign: '', + appkey: '', + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/video/info.md#%E8%8E%B7%E5%8F%96%E8%A7%86%E9%A2%91%E8%B6%85%E8%AF%A6%E7%BB%86%E4%BF%A1%E6%81%AFweb%E7%AB%AF - else if (message.contentScriptQuery === 'getVideoInfo') { - const url = `https://api.bilibili.com/x/web-interface/view/detail?${ - message.aid ? `aid=${message.aid}` : `bvid=${message.bvid}` - }` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getVideoInfo: { + url: 'https://api.bilibili.com/x/web-interface/view/detail', + _fetch: { + method: 'get', + }, + params: { + aid: '', + bvid: '', + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/comment/list.md#%E8%8E%B7%E5%8F%96%E8%AF%84%E8%AE%BA%E5%8C%BA%E6%98%8E%E7%BB%86_%E7%BF%BB%E9%A1%B5%E5%8A%A0%E8%BD%BD - else if (message.contentScriptQuery === 'getVideoComments') { - const url = `https://api.bilibili.com/x/v2/reply?csrf=${ - message.csrf - }&type=1&oid=${message.oid}&sort=${message.sort ?? 0}&nohot=${ - message.nohot ?? 0 - }&pn=${message.pn ?? 1}&ps=${message.ps ?? 20}` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getVideoComments: { + url: 'https://api.bilibili.com/x/v2/reply', + _fetch: { + method: 'get', + }, + params: { + csrf: '', + type: 1, + oid: '', + sort: 0, + nohot: 0, + pn: 1, + ps: 20, + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/def57d7a70ed1f39080069ba0f40648ce6ce2b90/docs/video_ranking/popular.md#%E8%8E%B7%E5%8F%96%E5%BD%93%E5%89%8D%E7%83%AD%E9%97%A8%E8%A7%86%E9%A2%91%E5%88%97%E8%A1%A8 - else if (message.contentScriptQuery === 'getPopularVideos') { - const url = `https://api.bilibili.com/x/web-interface/popular?pn=${message.pn ?? 1}&ps=${message.ps ?? 20}` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getPopularVideos: { + url: 'https://api.bilibili.com/x/web-interface/popular', + _fetch: { + method: 'get', + }, + params: { + pn: 1, + ps: 20, + }, + afterHandle: AHS.J_D, + }, // https://socialsisteryi.github.io/bilibili-API-collect/docs/video/videostream_url.html#%E8%8E%B7%E5%8F%96%E8%A7%86%E9%A2%91%E6%B5%81%E5%9C%B0%E5%9D%80-web%E7%AB%AF - else if (message.contentScriptQuery === 'getVideoPreview') { - const url = `https://api.bilibili.com/x/player/wbi/playurl?qn=${message.qn ?? 32}&fnver=${message.fnver ?? 0}&fnval=${message.fnval ?? 1} - &bvid=${message.bvid}&cid=${message.cid}&voice_balance=1&gaia_source=pre-load&web_location=1315873&from_client=BROWSER` - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getVideoPreview: { + url: 'https://api.bilibili.com/x/player/wbi/playurl', + _fetch: { + method: 'get', + }, + params: { + qn: 32, + fnver: 0, + fnval: 1, + bvid: '', + cid: '', + }, + afterHandle: AHS.J_D, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupVideoMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_VIDEO diff --git a/src/background/messageListeners/watchLater.ts b/src/background/messageListeners/watchLater.ts index ab9e6b1d..bc53389a 100644 --- a/src/background/messageListeners/watchLater.ts +++ b/src/background/messageListeners/watchLater.ts @@ -1,64 +1,62 @@ -import browser from 'webextension-polyfill' +import type { APIMAP } from '../utils' +import { AHS } from '../utils' -function handleMessage(message: any) { +const API_WATCHLATER: APIMAP = { // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/toview.md#%E8%A7%86%E9%A2%91%E6%B7%BB%E5%8A%A0%E7%A8%8D%E5%90%8E%E5%86%8D%E7%9C%8B - if (message.contentScriptQuery === 'saveToWatchLater') { - const url = 'https://api.bilibili.com/x/v2/history/toview/add' - return fetch(url, { - method: 'POST', - body: new URLSearchParams({ - csrf: message.csrf, - aid: message.aid, - }), - }) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + saveToWatchLater: { + url: 'https://api.bilibili.com/x/v2/history/toview/add', + _fetch: { + method: 'post', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', + }, + body: { + aid: '', + csrf: '', + }, + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/toview.md#%E5%88%A0%E9%99%A4%E7%A8%8D%E5%90%8E%E5%86%8D%E7%9C%8B%E8%A7%86%E9%A2%91 - else if (message.contentScriptQuery === 'removeFromWatchLater') { - const url = `https://api.bilibili.com/x/v2/history/toview/del?${message.aid ? `aid=${message.aid}` : ''}` - return fetch(url, { - method: 'POST', - body: new URLSearchParams({ - csrf: message.csrf, - // aid: message.aid, - viewed: message.viewed, - }), - }) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + removeFromWatchLater: { + url: 'https://api.bilibili.com/x/v2/history/toview/del', + _fetch: { + method: 'post', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', + }, + body: { + viewed: '', + csrf: '', + }, + }, + params: { + aid: '', + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/toview.md#%E8%8E%B7%E5%8F%96%E7%A8%8D%E5%90%8E%E5%86%8D%E7%9C%8B%E8%A7%86%E9%A2%91%E5%88%97%E8%A1%A8 - else if (message.contentScriptQuery === 'getAllWatchLaterList') { - const url = 'https://api.bilibili.com/x/v2/history/toview' - return fetch(url) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + getAllWatchLaterList: { + url: 'https://api.bilibili.com/x/v2/history/toview', + _fetch: { + method: 'get', + }, + afterHandle: AHS.J_D, + }, // https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/history&toview/toview.md#%E6%B8%85%E7%A9%BA%E7%A8%8D%E5%90%8E%E5%86%8D%E7%9C%8B%E8%A7%86%E9%A2%91%E5%88%97%E8%A1%A8 - else if (message.contentScriptQuery === 'clearAllWatchLater') { - const url = 'https://api.bilibili.com/x/v2/history/toview/clear' - return fetch(url, { - method: 'POST', - body: new URLSearchParams({ - csrf: message.csrf, - }), - }) - .then(response => response.json()) - .then(data => data) - .catch(error => console.error(error)) - } + clearAllWatchLater: { + url: 'https://api.bilibili.com/x/v2/history/toview/clear', + _fetch: { + method: 'post', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', + }, + body: { + csrf: '', + }, + }, + afterHandle: AHS.J_D, + }, } -function handleConnect() { - browser.runtime.onMessage.removeListener(handleMessage) - browser.runtime.onMessage.addListener(handleMessage) -} - -export function setupWatchLaterMsgLstnr() { - browser.runtime.onConnect.removeListener(handleConnect) - browser.runtime.onConnect.addListener(handleConnect) -} +export default API_WATCHLATER diff --git a/src/background/msg.define.ts b/src/background/msg.define.ts new file mode 100644 index 00000000..d697cbd8 --- /dev/null +++ b/src/background/msg.define.ts @@ -0,0 +1,82 @@ +// 这个文件不要引用其他文件,我怕打包时候会把引用的部分也打包成两分 +// en: This file should not reference other files, I am afraid that the referenced part will also be packaged into two parts when packaging + +enum AUTH { + LOGOUT = 'logout', + GET_LOGIN_QR_CODE = 'getLoginQRCode', + QR_CODE_LOGIN = 'qrCodeLogin', +} +enum ANIME { + GET = 'getAnime', + GET_WATCH_LIST = 'getAnimeWatchList', + GET_RECOMMEND_LIST = 'getRecommendAnimeList', + GET_TIME_TABLE = 'getAnimeTimeTable', + GET_DETAIL = 'getAnimeDetail', +} +enum FAVORITE { + GET_FAVORITE_CATEGORIES = 'getFavoriteCategories', + GET_FAVORITE_RESOURCES = 'getFavoriteResources', + PATCH_DEL_FAVORITE_RESOURCES = 'patchDelFavoriteResources', +} +enum HISTORY { + GET_HISTORY_LIST = 'getHistoryList', + SEARCH_HISTORY_LIST = 'searchHistoryList', + DELETE_HISTORY_ITEM = 'deleteHistoryItem', + CLEAR_ALL_HISTORY = 'clearAllHistory', + GET_HISTORY_PAUSE_STATUS = 'getHistoryPauseStatus', + SET_HISTORY_PAUSE_STATUS = 'setHistory', +} +enum MOMENT { + GET_TOP_BAR_NEW_MOMENTS_COUNT = 'getTopBarNewMomentsCount', + GET_TOP_BAR_NEW_MOMENTS = 'getTopBarNewMoments', + GET_TOP_BAR_HISTORY_MOMENTS = 'getTopbarHistoryMoments', + GET_TOP_BAR_LIVE_MOMENTS = 'getTopbarLiveMoments', + GET_MOMENTS = 'getMoments', +} +enum NOTIFICATION { + GET_UNREAD_MSG = 'getUnreadMsg', + GET_UNREAD_DM = 'getUnreadDm', +} +enum RANKING { + GET_RANKING_VIDEOS = 'getRankingVideos', + GET_RANKING_PGC = 'getRankingPgc', +} +enum SEARCH { + GET_SEARCH_SUGGESTION = 'getSearchSuggestion', +} +enum USER { + GET_USER_INFO = 'getUserInfo', + GET_USER_STAT = 'getUserStat', +} +enum VIDEO { + GET_RECOMMEND_VIDEOS = 'getRecommendVideos', + GET_APP_RECOMMEND_VIDEOS = 'getAppRecommendVideos', + DISLIKE_VIDEO = 'dislikeVideo', + UNDO_DISLIKE_VIDEO = 'undoDislikeVideo', + GET_VIDEO_INFO = 'getVideoInfo', + GET_VIDEO_COMMENTS = 'getVideoComments', + GET_POPULAR_VIDEOS = 'getPopularVideos', + GET_VIDEO_PREVIEW = 'getVideoPreview', +} +enum WATCHLATER { + SAVE_TO_WATCHLATER = 'saveToWatchLater', + REMOVE_FROM_WATCHLATER = 'removeFromWatchLater', + GET_ALL_WATCHLATER_LIST = 'getAllWatchLaterList', + CLEAR_ALL_WATCHLATER = 'clearAllWatchLater', +} + +const API = { + AUTH, + ANIME, + FAVORITE, + HISTORY, + MOMENT, + NOTIFICATION, + RANKING, + SEARCH, + USER, + VIDEO, + WATCHLATER, +} + +export default API diff --git a/src/background/utils.ts b/src/background/utils.ts new file mode 100644 index 00000000..8196f9d4 --- /dev/null +++ b/src/background/utils.ts @@ -0,0 +1,132 @@ +// 对于fetch的常见后处理 +// 1. 直接返回data +// 2. json化后返回data + +type FetchAfterHandler = ((data: Response) => Promise) | ((data: any) => any) + +function toJsonHandler(data: Response): Promise { + return data.json() +} +function toData(data: Promise): Promise { + return data +} + +// if need sendResponse, use this +// return a FetchAfterHandler function +function sendResponseHandler(sendResponse: Function) { + return (data: any) => sendResponse(data) +} + +// 定义后处理流 +const AHS: { + J_D: FetchAfterHandler[] + J_S: FetchAfterHandler[] + S: FetchAfterHandler[] +} = { + J_D: [toJsonHandler, toData], + J_S: [toJsonHandler, sendResponseHandler], + S: [sendResponseHandler], +} + +interface Message { + contentScriptQuery: string + [key: string]: any +} + +interface _FETCH { + method: string + headers?: { + [key: string]: any + } + body?: any +} + +interface API { + url: string + _fetch: _FETCH + params?: { + [key: string]: any + } + afterHandle: ((response: Response) => Response | Promise)[] +} +// 重载API 可以为函数 +type APIFunction = (message: Message, sender?: any, sendResponse?: Function) => any +type APIType = API | APIFunction +interface APIMAP { + [key: string]: APIType +} +// 工厂函数API_LISTENER_FACTORY +function apiListenerFactory(API_MAP: APIMAP) { + return (message: Message, sender?: any, sendResponse?: Function) => { + const contentScriptQuery = message.contentScriptQuery + // 检测是否有contentScriptQuery + if (!contentScriptQuery || !API_MAP[contentScriptQuery]) + return console.error('no contentScriptQuery') + if (API_MAP[contentScriptQuery] instanceof Function) + return (API_MAP[contentScriptQuery] as APIFunction)(message, sender, sendResponse) + + try { + let { contentScriptQuery, ...rest } = message + // rest above two part body or params + rest = rest || {} + + let { _fetch, url, params = {}, afterHandle } = API_MAP[contentScriptQuery] as API + const { method, headers, body } = _fetch as _FETCH + const isGET = method.toLocaleLowerCase() === 'get' + // merge params and body + const targetParams = Object.assign({}, params) + let targetBody = Object.assign({}, body) + Object.keys(rest).forEach((key) => { + if (body && body[key] !== undefined) + targetBody[key] = rest[key] + else + targetParams[key] = rest[key] + }) + + // generate params + if (Object.keys(targetParams).length) { + const urlParams = new URLSearchParams() + for (const key in targetParams) + targetParams[key] && urlParams.append(key, targetParams[key]) + url += `?${urlParams.toString()}` + } + // generate body + if (!isGET) { + targetBody = (headers && headers['Content-Type'] && headers['Content-Type'].includes('application/x-www-form-urlencoded')) + ? new URLSearchParams(targetBody) + : JSON.stringify(targetBody) + } + // get cant take body + const fetchOpt = { method, headers } + !isGET && Object.assign(fetchOpt, { body: targetBody }) + + // fetch and after handle + let baseFunc = fetch(url, fetchOpt) + afterHandle.forEach((func) => { + if (func.name === sendResponseHandler.name && sendResponse) + // sendResponseHandler 是一个特殊的后处理函数,需要传入sendResponse + baseFunc = baseFunc.then(sendResponseHandler(sendResponse)) + else + baseFunc = baseFunc.then(func) + }) + baseFunc.catch(console.error) + return baseFunc + } + catch (e) { + console.error(e) + } + } +} + +export { + FetchAfterHandler, + toJsonHandler, + toData, + sendResponseHandler, + AHS, + Message, + _FETCH, + API, + APIMAP, + apiListenerFactory, +} diff --git a/src/components/SearchBar/SearchBar.vue b/src/components/SearchBar/SearchBar.vue index 74a48b7b..c0387361 100644 --- a/src/components/SearchBar/SearchBar.vue +++ b/src/components/SearchBar/SearchBar.vue @@ -8,6 +8,7 @@ import { getSearchHistory, removeSearchHistory, } from './searchHistoryProvider' +import API from '~/background/msg.define' defineProps<{ darkenOnFocus?: boolean @@ -53,7 +54,7 @@ function handleInput() { if (keyword.value.length > 0) { browser.runtime .sendMessage({ - contentScriptQuery: 'getSearchSuggestion', + contentScriptQuery: API.SEARCH.GET_SEARCH_SUGGESTION, term: keyword.value, }) .then((res: SuggestionResponse) => { diff --git a/src/components/TopBar/TopBar.vue b/src/components/TopBar/TopBar.vue index be662f34..dab3e72e 100644 --- a/src/components/TopBar/TopBar.vue +++ b/src/components/TopBar/TopBar.vue @@ -11,6 +11,7 @@ import { updateInterval } from './notify' import { getUserID, isHomePage } from '~/utils/main' import { settings } from '~/logic' import emitter from '~/utils/mitt' +import API from '~/background/msg.define' // import { useTopBarStore } from '~/stores/topBarStore' @@ -224,7 +225,7 @@ async function getUserInfo() { try { const res = await browser.runtime .sendMessage({ - contentScriptQuery: 'getUserInfo', + contentScriptQuery: API.USER.GET_USER_INFO, }) if (res.code === 0) { diff --git a/src/components/TopBar/components/FavoritesPop.vue b/src/components/TopBar/components/FavoritesPop.vue index 511d8446..691315ee 100644 --- a/src/components/TopBar/components/FavoritesPop.vue +++ b/src/components/TopBar/components/FavoritesPop.vue @@ -4,6 +4,7 @@ import { onMounted, reactive, ref, watch } from 'vue' import type { FavoriteCategory, FavoriteResource } from '../types' import { getUserID, isHomePage, removeHttpFromUrl, smoothScrollToTop } from '~/utils/main' import { calcCurrentTime } from '~/utils/dataFormatter' +import API from '~/background/msg.define' const favoriteCategories = reactive>([]) const favoriteResources = reactive>([]) @@ -67,8 +68,8 @@ onMounted(async () => { async function getFavoriteCategories() { await browser.runtime .sendMessage({ - contentScriptQuery: 'getFavoriteCategories', - mid: getUserID(), + contentScriptQuery: API.FAVORITE.GET_FAVORITE_CATEGORIES, + up_mid: getUserID(), }) .then((res) => { if (res.code === 0) { @@ -86,9 +87,9 @@ function getFavoriteResources() { isLoading.value = true browser.runtime .sendMessage({ - contentScriptQuery: 'getFavoriteResources', - mediaId: activatedMediaId.value, - pageNum: currentPageNum.value, + contentScriptQuery: API.FAVORITE.GET_FAVORITE_RESOURCES, + media_id: activatedMediaId.value, + pn: currentPageNum.value, keyword: '', }) .then((res) => { diff --git a/src/components/TopBar/components/HistoryPop.vue b/src/components/TopBar/components/HistoryPop.vue index 61509957..4d00d120 100644 --- a/src/components/TopBar/components/HistoryPop.vue +++ b/src/components/TopBar/components/HistoryPop.vue @@ -7,6 +7,7 @@ import type { HistoryItem } from '../types' import { HistoryType } from '../types' import { isHomePage, removeHttpFromUrl, smoothScrollToTop } from '~/utils/main' import { calcCurrentTime } from '~/utils/dataFormatter' +import API from '~/background/msg.define' const { t } = useI18n() @@ -137,15 +138,15 @@ function getHistoryUrl(item: HistoryItem) { /** * Get history list * @param {HistoryType} type - * @param {number} viewAt Last viewed timestamp + * @param {number} view_at Last viewed timestamp */ -function getHistoryList(type: HistoryType, viewAt = 0 as number) { +function getHistoryList(type: HistoryType, view_at = 0 as number) { isLoading.value = true browser.runtime .sendMessage({ - contentScriptQuery: 'getHistoryList', + contentScriptQuery: API.HISTORY.GET_HISTORY_LIST, type, - viewAt, + view_at, }) .then((res) => { if (res.code === 0) { diff --git a/src/components/TopBar/components/MomentsPop.vue b/src/components/TopBar/components/MomentsPop.vue index 0bbabc5d..9a96a3c3 100644 --- a/src/components/TopBar/components/MomentsPop.vue +++ b/src/components/TopBar/components/MomentsPop.vue @@ -7,6 +7,7 @@ import { MomentType } from '../types' import type { MomentItem } from '../types' import { getCSRF, getUserID, isHomePage, smoothScrollToTop } from '~/utils/main' import { calcTimeSince } from '~/utils/dataFormatter' +import API from '~/background/msg.define' const { t } = useI18n() @@ -89,14 +90,14 @@ function onClickTab(tabId: number) { }) } -function getTopBarNewMoments(typeList: number[]) { +function getTopBarNewMoments(type_list: number[]) { moments.length = 0 isLoading.value = true browser.runtime .sendMessage({ - contentScriptQuery: 'getTopBarNewMoments', + contentScriptQuery: API.MOMENT.GET_TOP_BAR_NEW_MOMENTS, uid: getUserID(), - typeList, + type_list, }) .then((res) => { if (res.code === 0) { @@ -125,14 +126,14 @@ function getTopBarNewMoments(typeList: number[]) { }) } -function getTopbarHistoryMoments(typeList: number[]) { +function getTopbarHistoryMoments(type_list: number[]) { isLoading.value = true browser.runtime .sendMessage({ - contentScriptQuery: 'getTopbarHistoryMoments', + contentScriptQuery: API.MOMENT.GET_TOP_BAR_HISTORY_MOMENTS, uid: getUserID(), - typeList, - offsetDynamicID: moments[moments.length - 1].dynamic_id_str, + type_list, + offset_dynamic_id: moments[moments.length - 1].dynamic_id_str, }) .then((res) => { if (res.code === 0) { @@ -155,9 +156,9 @@ function getTopbarLiveMoments(page: number) { isLoading.value = true browser.runtime .sendMessage({ - contentScriptQuery: 'getTopbarLiveMoments', + contentScriptQuery: API.MOMENT.GET_TOP_BAR_LIVE_MOMENTS, page, - pageSize: 10, + pagesize: 10, }) .then((res) => { if (res.code === 0) { @@ -202,7 +203,7 @@ function pushItemIntoMoments(item: any) { face: item.desc.user_profile.info.face, aid: card.aid, bvid: item.desc.bvid, - url: card.short_link_v2, + url: card.short_link_v2 || `https://www.bilibili.com/video/${item.desc.bvid}`, ctime: card.ctime, title: card.title, cover: card.pic, @@ -248,7 +249,7 @@ function toggleWatchLater(aid: number) { if (!isInWatchLater) { browser.runtime.sendMessage({ - contentScriptQuery: 'saveToWatchLater', + contentScriptQuery: API.WATCHLATER.SAVE_TO_WATCHLATER, aid, csrf: getCSRF(), }) @@ -259,7 +260,7 @@ function toggleWatchLater(aid: number) { } else { browser.runtime.sendMessage({ - contentScriptQuery: 'removeFromWatchLater', + contentScriptQuery: API.WATCHLATER.REMOVE_FROM_WATCHLATER, aid, csrf: getCSRF(), }) diff --git a/src/components/TopBar/components/NotificationsPop.vue b/src/components/TopBar/components/NotificationsPop.vue index 96ffd09b..aefa3c43 100644 --- a/src/components/TopBar/components/NotificationsPop.vue +++ b/src/components/TopBar/components/NotificationsPop.vue @@ -1,6 +1,7 @@