From 8c4bae9ea48d4c13c3448522121f34f820b26fb4 Mon Sep 17 00:00:00 2001 From: Stephen Zhou Date: Thu, 25 Apr 2024 16:39:27 +0800 Subject: [PATCH] refactor: like `rpc` api call (#660) (#662) Co-authored-by: star knight <64941905+starknt@users.noreply.github.com> Co-authored-by: hakadao --- src/background/msg.define.ts | 17 +++--- src/components/SearchBar/SearchBar.vue | 10 ++-- src/components/TopBar/TopBar.vue | 20 ++----- .../TopBar/components/FavoritesPop.vue | 23 ++++---- .../TopBar/components/HistoryPop.vue | 14 ++--- .../TopBar/components/MomentsPop.vue | 24 +++----- .../TopBar/components/NotificationsPop.vue | 53 ++++++++---------- .../TopBar/components/UserPanelPop.vue | 10 +--- .../TopBar/components/WatchLaterPop.vue | 8 +-- src/components/VideoCard/VideoCard.vue | 12 ++-- src/composables/api.ts | 52 +++++++++++++++++ src/contentScripts/views/Anime/Anime.vue | 26 ++++----- .../views/Anime/components/AnimeTimeTable.vue | 7 +-- .../views/Favorites/Favorites.vue | 25 ++++----- src/contentScripts/views/History/History.vue | 56 +++++++------------ .../views/Home/components/Following.vue | 6 +- .../views/Home/components/ForYou.vue | 15 ++--- .../views/Home/components/Ranking.vue | 8 +-- .../Home/components/SubscribedSeries.vue | 6 +- .../views/Home/components/Trending.vue | 6 +- src/contentScripts/views/Video/Video.vue | 8 +-- .../views/WatchLater/WatchLater.vue | 31 ++++------ 22 files changed, 200 insertions(+), 237 deletions(-) create mode 100644 src/composables/api.ts diff --git a/src/background/msg.define.ts b/src/background/msg.define.ts index 6ac8b803..99943e2e 100644 --- a/src/background/msg.define.ts +++ b/src/background/msg.define.ts @@ -7,11 +7,12 @@ enum AUTH { QR_CODE_LOGIN = 'qrCodeLogin', } enum ANIME { - GET = 'getAnime', - GET_WATCH_LIST = 'getAnimeWatchList', - GET_RECOMMEND_LIST = 'getRecommendAnimeList', - GET_TIME_TABLE = 'getAnimeTimeTable', - GET_DETAIL = 'getAnimeDetail', + GET_ANIME = 'getAnime', + GET_ANIME_WATCH_LIST = 'getAnimeWatchList', + GET_RECOMMEND_ANIME_LIST = 'getRecommendAnimeList', + GET_ANIME_TIME_TABLE = 'getAnimeTimeTable', + GET_ANIME_DETAIL = 'getAnimeDetail', + GET_POPULAR_ANIME_LIST = 'getPopularAnimeList', } enum FAVORITE { GET_FAVORITE_CATEGORIES = 'getFavoriteCategories', @@ -58,10 +59,10 @@ enum VIDEO { GET_VIDEO_PREVIEW = 'getVideoPreview', } enum WATCHLATER { - SAVE_TO_WATCHLATER = 'saveToWatchLater', - REMOVE_FROM_WATCHLATER = 'removeFromWatchLater', + SAVE_TO_WATCH_LATER = 'saveToWatchLater', + REMOVE_FROM_WATCH_LATER = 'removeFromWatchLater', GET_ALL_WATCHLATER_LIST = 'getAllWatchLaterList', - CLEAR_ALL_WATCHLATER = 'clearAllWatchLater', + CLEAR_ALL_WATCH_LATER = 'clearAllWatchLater', } const API = { diff --git a/src/components/SearchBar/SearchBar.vue b/src/components/SearchBar/SearchBar.vue index 5b11eebc..650bc359 100644 --- a/src/components/SearchBar/SearchBar.vue +++ b/src/components/SearchBar/SearchBar.vue @@ -8,7 +8,6 @@ import { getSearchHistory, removeSearchHistory, } from './searchHistoryProvider' -import API from '~/background/msg.define' import { findLeafActiveElement } from '~/utils/element' defineProps<{ @@ -17,6 +16,7 @@ defineProps<{ focusedCharacter?: string }>() +const api = useApiClient() const keywordRef = ref() const isFocus = ref(false) const keyword = ref('') @@ -57,11 +57,9 @@ onKeyStroke('Escape', (e: KeyboardEvent) => { function handleInput() { selectedIndex.value = -1 if (keyword.value.length > 0) { - browser.runtime - .sendMessage({ - contentScriptQuery: API.SEARCH.GET_SEARCH_SUGGESTION, - term: keyword.value, - }) + api.search.getSearchSuggestion({ + term: keyword.value, + }) .then((res: SuggestionResponse) => { if (!res || (res && res.code !== 0)) return diff --git a/src/components/TopBar/TopBar.vue b/src/components/TopBar/TopBar.vue index 03bfa226..e5440d61 100644 --- a/src/components/TopBar/TopBar.vue +++ b/src/components/TopBar/TopBar.vue @@ -11,7 +11,6 @@ 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' @@ -63,7 +62,7 @@ const popupVisible = reactive({ upload: false, more: false, }) - +const api = useApiClient() const isLogin = ref(false) const unReadMessage = reactive>( {}, @@ -281,10 +280,7 @@ function handleScroll() { async function getUserInfo() { try { - const res = await browser.runtime - .sendMessage({ - contentScriptQuery: API.USER.GET_USER_INFO, - }) + const res = await api.user.getUserInfo() if (res.code === 0) { isLogin.value = true @@ -309,9 +305,7 @@ async function getUnreadMessageCount() { try { let res - res = await browser.runtime.sendMessage({ - contentScriptQuery: 'getUnreadMsg', - }) + res = await useApiClient().NOTIFICATION.getUnreadMsg() if (res.code === 0) { Object.assign(unReadMessage, res.data) Object.entries(unReadMessage).forEach(([key, value]) => { @@ -322,9 +316,7 @@ async function getUnreadMessageCount() { }) } - res = await browser.runtime.sendMessage({ - contentScriptQuery: 'getUnreadDm', - }) + res = await useApiClient().NOTIFICATION.getUnreadDm() if (res.code === 0) { Object.assign(unReadDm, res.data) if (typeof unReadDm.follow_unread === 'number') @@ -346,9 +338,7 @@ async function getTopBarNewMomentsCount() { let result = 0 try { - const res = await browser.runtime.sendMessage({ - contentScriptQuery: 'getTopBarNewMomentsCount', - }) + const res = await useApiClient().MOMENT.getTopBarNewMomentsCount() if (res.code === 0) { if (typeof res.data.update_info.item.count === 'number') result = res.data.update_info.item.count diff --git a/src/components/TopBar/components/FavoritesPop.vue b/src/components/TopBar/components/FavoritesPop.vue index 71be4434..a9e7c549 100644 --- a/src/components/TopBar/components/FavoritesPop.vue +++ b/src/components/TopBar/components/FavoritesPop.vue @@ -4,7 +4,8 @@ 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 api = useApiClient() const favoriteCategories = reactive>([]) const favoriteResources = reactive>([]) @@ -66,11 +67,9 @@ onMounted(async () => { }) async function getFavoriteCategories() { - await browser.runtime - .sendMessage({ - contentScriptQuery: API.FAVORITE.GET_FAVORITE_CATEGORIES, - up_mid: getUserID(), - }) + await api.favorite.getFavoriteCategories({ + up_mid: getUserID(), + }) .then((res) => { if (res.code === 0) { Object.assign(favoriteCategories, res.data.list) @@ -85,13 +84,11 @@ async function getFavoriteCategories() { */ function getFavoriteResources() { isLoading.value = true - browser.runtime - .sendMessage({ - contentScriptQuery: API.FAVORITE.GET_FAVORITE_RESOURCES, - media_id: activatedMediaId.value, - pn: currentPageNum.value, - keyword: '', - }) + api.favorite.getFavoriteResources({ + media_id: activatedMediaId.value, + pn: currentPageNum.value, + keyword: '', + }) .then((res) => { if (res.code === 0) { if (Array.isArray(res.data.medias) && res.data.medias.length > 0) diff --git a/src/components/TopBar/components/HistoryPop.vue b/src/components/TopBar/components/HistoryPop.vue index 2876c2e9..57b766de 100644 --- a/src/components/TopBar/components/HistoryPop.vue +++ b/src/components/TopBar/components/HistoryPop.vue @@ -8,10 +8,8 @@ import { calcCurrentTime } from '~/utils/dataFormatter' import { Business } from '~/models/history/history' import type { List as HistoryItem, HistoryResult } from '~/models/history/history' -import API from '~/background/msg.define' - const { t } = useI18n() - +const api = useApiClient() const historys = reactive>([]) const historyTabs = reactive([ { @@ -141,12 +139,10 @@ function getHistoryUrl(item: HistoryItem) { */ function getHistoryList(type: Business, view_at = 0 as number) { isLoading.value = true - browser.runtime - .sendMessage({ - contentScriptQuery: API.HISTORY.GET_HISTORY_LIST, - type, - view_at, - }) + api.history.getHistoryList({ + type, + view_at, + }) .then((res: HistoryResult) => { if (res.code === 0) { if (Array.isArray(res.data.list) && res.data.list.length > 0) diff --git a/src/components/TopBar/components/MomentsPop.vue b/src/components/TopBar/components/MomentsPop.vue index 9d8b4d0d..688a07c4 100644 --- a/src/components/TopBar/components/MomentsPop.vue +++ b/src/components/TopBar/components/MomentsPop.vue @@ -7,7 +7,6 @@ import { onMounted, reactive, ref, watch } from 'vue' import type { TopBarMomentResult } from '~/models/moment/topBarMoment' import type { TopBarLiveMomentResult } from '~/models/moment/topBarLiveMoment' import { getCSRF, isHomePage, smoothScrollToTop } from '~/utils/main' -import API from '~/background/msg.define' type MomentType = 'video' | 'live' | 'article' interface MomentTab { type: MomentType, name: any } @@ -23,6 +22,7 @@ interface MomentCard { } const { t } = useI18n() +const api = useApiClient() const moments = reactive([]) const addedWatchLaterList = reactive([]) @@ -103,8 +103,7 @@ function checkIfHasNewMomentsThenUpdateMoments() { if (selectedMomentTab.value.type === 'live') return - browser.runtime.sendMessage({ - contentScriptQuery: API.MOMENT.GET_TOP_BAR_MOMENTS, + api.MOMENT.getTopBarMoments({ type: selectedMomentTab.value.type, update_baseline: momentUpdateBaseline.value || undefined, }) @@ -145,8 +144,7 @@ function getTopBarMoments() { if (isLoading.value) return isLoading.value = true - browser.runtime.sendMessage({ - contentScriptQuery: API.MOMENT.GET_TOP_BAR_MOMENTS, + api.moment.getTopBarMoments({ type: selectedMomentTab.value.type, update_baseline: momentUpdateBaseline.value || undefined, offset: momentOffset.value || undefined, @@ -193,12 +191,10 @@ function isNewMoment(index: number) { function getTopBarLiveMoments() { isLoading.value = true - browser.runtime - .sendMessage({ - contentScriptQuery: API.MOMENT.GET_TOP_BAR_LIVE_MOMENTS, - page: livePage.value, - pagesize: 10, - }) + api.moment.getTopBarLiveMoments({ + page: livePage.value, + pagesize: 10, + }) .then((res: TopBarLiveMomentResult) => { if (res.code === 0) { const { list, pagesize } = res.data @@ -235,8 +231,7 @@ function toggleWatchLater(aid: number) { const isInWatchLater = addedWatchLaterList.includes(aid) if (!isInWatchLater) { - browser.runtime.sendMessage({ - contentScriptQuery: API.WATCHLATER.SAVE_TO_WATCHLATER, + api.watchlater.saveToWatchLater({ aid, csrf: getCSRF(), }) @@ -246,8 +241,7 @@ function toggleWatchLater(aid: number) { }) } else { - browser.runtime.sendMessage({ - contentScriptQuery: API.WATCHLATER.REMOVE_FROM_WATCHLATER, + api.watchlater.removeFromWatchLater({ aid, csrf: getCSRF(), }) diff --git a/src/components/TopBar/components/NotificationsPop.vue b/src/components/TopBar/components/NotificationsPop.vue index 3277e43e..e3704526 100644 --- a/src/components/TopBar/components/NotificationsPop.vue +++ b/src/components/TopBar/components/NotificationsPop.vue @@ -1,10 +1,9 @@ diff --git a/src/components/TopBar/components/UserPanelPop.vue b/src/components/TopBar/components/UserPanelPop.vue index d0b14570..0f2a7103 100644 --- a/src/components/TopBar/components/UserPanelPop.vue +++ b/src/components/TopBar/components/UserPanelPop.vue @@ -4,13 +4,13 @@ import type { UserInfo, UserStat } from '../types' import { revokeAccessKey } from '~/utils/authProvider' import { getCSRF, getUserID, isHomePage } from '~/utils/main' import { numFormatter } from '~/utils/dataFormatter' -import API from '~/background/msg.define' defineProps<{ userInfo: UserInfo }>() const { t } = useI18n() +const api = useApiClient() const mid = computed(() => { return getUserID() @@ -30,10 +30,7 @@ const otherLinks = computed((): { name: string, url: string }[] => { const userStat = reactive({} as UserStat) onMounted(() => { - browser.runtime - .sendMessage({ - contentScriptQuery: API.USER.GET_USER_STAT, - }) + api.user.getUserStat() .then((res) => { if (res.code === 0) Object.assign(userStat, res.data) @@ -42,8 +39,7 @@ onMounted(() => { async function logout() { revokeAccessKey() - browser.runtime.sendMessage({ - contentScriptQuery: API.AUTH.LOGOUT, + api.auth.logout({ biliCSRF: getCSRF(), }).then(() => { location.reload() diff --git a/src/components/TopBar/components/WatchLaterPop.vue b/src/components/TopBar/components/WatchLaterPop.vue index 982f0454..84ef5e65 100644 --- a/src/components/TopBar/components/WatchLaterPop.vue +++ b/src/components/TopBar/components/WatchLaterPop.vue @@ -3,11 +3,10 @@ import { onMounted, reactive, ref } from 'vue' import { calcCurrentTime } from '~/utils/dataFormatter' import type { List as VideoItem, WatchLaterResult } from '~/models/video/watchLater' import { isHomePage, removeHttpFromUrl } from '~/utils/main' -import API from '~/background/msg.define' +const api = useApiClient() const watchLaterList = reactive([]) const isLoading = ref() - const viewAllUrl = computed((): string => { return 'https://www.bilibili.com/watchlater/#/list' }) @@ -35,10 +34,7 @@ function getAllWatchLaterList() { isLoading.value = true watchLaterList.length = 0 - browser.runtime - .sendMessage({ - contentScriptQuery: API.WATCHLATER.GET_ALL_WATCHLATER_LIST, - }) + api.watchlater.getAllWatchlaterList() .then((res: WatchLaterResult) => { if (res.code === 0) Object.assign(watchLaterList, res.data.list) diff --git a/src/components/VideoCard/VideoCard.vue b/src/components/VideoCard/VideoCard.vue index 24a8c57b..c6491b7e 100644 --- a/src/components/VideoCard/VideoCard.vue +++ b/src/components/VideoCard/VideoCard.vue @@ -4,7 +4,6 @@ import { getCSRF, removeHttpFromUrl } from '~/utils/main' import { calcCurrentTime, calcTimeSince, numFormatter } from '~/utils/dataFormatter' import type { VideoPreviewResult } from '~/models/video/videoPreview' import { settings } from '~/logic' -import API from '~/background/msg.define' interface Props { id: number @@ -53,6 +52,8 @@ const emit = defineEmits<{ (e: 'tellUsWhy'): void }>() +const api = useApiClient() + const videoUrl = computed(() => { if (props.bvid || props.aid) return `https://www.bilibili.com/video/${props.bvid ?? `av${props.aid}`}` @@ -90,8 +91,7 @@ const previewVideoUrl = ref('') watch(() => isHover.value, (newValue) => { if (props.showPreview && settings.value.enableVideoPreview) { if (newValue && !previewVideoUrl.value && props.cid) { - browser.runtime.sendMessage({ - contentScriptQuery: API.VIDEO.GET_VIDEO_PREVIEW, + api.video.getVideoPreview({ bvid: props.bvid, cid: props.cid, }).then((res: VideoPreviewResult) => { @@ -104,8 +104,7 @@ watch(() => isHover.value, (newValue) => { function toggleWatchLater() { if (!isInWatchLater.value) { - browser.runtime.sendMessage({ - contentScriptQuery: API.WATCHLATER.SAVE_TO_WATCHLATER, + api.watchlater.saveToWatchLater({ aid: props.id, csrf: getCSRF(), }) @@ -115,8 +114,7 @@ function toggleWatchLater() { }) } else { - browser.runtime.sendMessage({ - contentScriptQuery: API.WATCHLATER.REMOVE_FROM_WATCHLATER, + api.watchlater.removeFromWatchLater({ aid: props.id, csrf: getCSRF(), }) diff --git a/src/composables/api.ts b/src/composables/api.ts new file mode 100644 index 00000000..821778da --- /dev/null +++ b/src/composables/api.ts @@ -0,0 +1,52 @@ +import type API from '~/background/msg.define' + +type CamelCase = S extends `${infer P1}_${infer P2}${infer P3}` + ? `${Lowercase}${Uppercase}${CamelCase}` + : Lowercase + +type APIFunction = { + [K in keyof T as CamelCase]: { + [P in keyof T[K] as CamelCase]: (options?: object) => Promise + } +} + +// eslint-disable-next-line ts/no-unsafe-declaration-merging +export interface APIClient extends APIFunction { + +} + +// eslint-disable-next-line ts/no-unsafe-declaration-merging +export class APIClient { + private readonly cache = new Map() + + constructor() { + // @ts-expect-error ignore + return new Proxy({}, { + get: (_, namespace) => { // namespace + if (this.cache.has(namespace)) { + return this.cache.get(namespace) + } + else { + const api = new Proxy({}, { + get(_, p) { + return (options?: object) => { + return browser.runtime.sendMessage({ + contentScriptQuery: p, + ...options, + }) + } + }, + }) + this.cache.set(namespace, api) + return api + } + }, + }) + } +} + +const api = new APIClient() + +export function useApiClient() { + return api +} diff --git a/src/contentScripts/views/Anime/Anime.vue b/src/contentScripts/views/Anime/Anime.vue index f72ac70c..9b54c07f 100644 --- a/src/contentScripts/views/Anime/Anime.vue +++ b/src/contentScripts/views/Anime/Anime.vue @@ -6,6 +6,7 @@ import type { List as WatchListItem, WatchListResult } from '~/models/anime/watc import type { List as PopularAnimeItem, PopularAnimeResult } from '~/models/anime/popular' import type { ItemSubItem as RecommendationItem, RecommendationResult } from '~/models/anime/recommendation' +const api = useApiClient() const animeWatchList = reactive([]) const recommendAnimeList = reactive([]) const popularAnimeList = reactive([]) @@ -58,13 +59,11 @@ function initPageAction() { function getAnimeWatchList() { isLoadingAnimeWatchList.value = true - browser.runtime - .sendMessage({ - contentScriptQuery: 'getAnimeWatchList', - vmid: getUserID() ?? 0, - pn: 1, - ps: 30, - }) + api.anime.getWatchList({ + vmid: getUserID() ?? 0, + pn: 1, + ps: 30, + }) .then((response: WatchListResult) => { const { code, @@ -81,11 +80,9 @@ function getAnimeWatchList() { function getRecommendAnimeList() { isLoadingRecommendAnime.value = true - browser.runtime - .sendMessage({ - contentScriptQuery: 'getRecommendAnimeList', - coursor: cursor.value, - }) + api.anime.getRecommendAnimeList({ + coursor: cursor.value, + }) .then((response: RecommendationResult) => { const { code, @@ -109,10 +106,7 @@ function getRecommendAnimeList() { function getPopularAnimeList() { isLoadingPopularAnime.value = true - browser.runtime - .sendMessage({ - contentScriptQuery: 'getPopularAnimeList', - }) + api.anime.getPopularAnimeList() .then((response: PopularAnimeResult) => { const { code, diff --git a/src/contentScripts/views/Anime/components/AnimeTimeTable.vue b/src/contentScripts/views/Anime/components/AnimeTimeTable.vue index 2063e022..0075c01c 100644 --- a/src/contentScripts/views/Anime/components/AnimeTimeTable.vue +++ b/src/contentScripts/views/Anime/components/AnimeTimeTable.vue @@ -6,7 +6,7 @@ import { removeHttpFromUrl } from '~/utils/main' import type { Result as TimetableItem, TimetableResult } from '~/models/anime/timeTable' const { t } = useI18n() - +const api = useApiClient() const animeTimeTable = reactive([]) const animeTimeTableWrap = ref() as Ref @@ -32,10 +32,7 @@ function refreshAnimeTimeTable() { } function getAnimeTimeTable() { - browser.runtime - .sendMessage({ - contentScriptQuery: 'getAnimeTimeTable', - }) + api.anime.getAnimeTimeTable() .then((res: TimetableResult) => { const { code, result } = res if (code === 0) diff --git a/src/contentScripts/views/Favorites/Favorites.vue b/src/contentScripts/views/Favorites/Favorites.vue index 9fcfc7d9..618f9245 100644 --- a/src/contentScripts/views/Favorites/Favorites.vue +++ b/src/contentScripts/views/Favorites/Favorites.vue @@ -6,9 +6,9 @@ import emitter from '~/utils/mitt' import { settings } from '~/logic' import type { Media as FavoriteItem, FavoritesResult } from '~/models/video/favorite' import type { List as CategoryItem, FavoritesCategoryResult } from '~/models/video/favoriteCategory' -import API from '~/background/msg.define' const { t } = useI18n() +const api = useApiClient() const favoriteCategories = reactive([]) const favoriteResources = reactive([]) @@ -73,11 +73,9 @@ function initPageAction() { } async function getFavoriteCategories() { - await browser.runtime - .sendMessage({ - contentScriptQuery: API.FAVORITE.GET_FAVORITE_CATEGORIES, - up_mid: getUserID(), - }) + await api.favorite.getFavoriteCategories({ + up_mid: getUserID(), + }) .then((res: FavoritesCategoryResult) => { if (res.code === 0) { Object.assign(favoriteCategories, res.data.list) @@ -108,13 +106,11 @@ async function getFavoriteResources( isFullPageLoading.value = true isLoading.value = true try { - const res: FavoritesResult = await browser.runtime - .sendMessage({ - contentScriptQuery: API.FAVORITE.GET_FAVORITE_RESOURCES, - media_id, - pn, - keyword, - }) + const res: FavoritesResult = await api.favorite.getFavoriteResources({ + media_id, + pn, + keyword, + }) if (res.code === 0) { activatedCategoryCover.value = res.data.info.cover @@ -158,8 +154,7 @@ function jumpToLoginPage() { } function handleUnfavorite(favoriteResource: FavoriteResource) { - browser.runtime.sendMessage({ - contentScriptQuery: API.FAVORITE.PATCH_DEL_FAVORITE_RESOURCES, + api.favorite.patchDelFavoriteResources({ resources: `${favoriteResource.id}:${favoriteResource.type}`, media_id: selectedCategory.value?.id, csrf: getCSRF(), diff --git a/src/contentScripts/views/History/History.vue b/src/contentScripts/views/History/History.vue index 8ef3da7e..7e535b13 100644 --- a/src/contentScripts/views/History/History.vue +++ b/src/contentScripts/views/History/History.vue @@ -7,10 +7,9 @@ import { calcCurrentTime } from '~/utils/dataFormatter' import { Business } from '~/models/history/history' import type { List as HistoryItem, HistoryResult } from '~/models/history/history' import type { List as HistorySearchItem, HistorySearchResult } from '~/models/video/historySearch' -import API from '~/background/msg.define' const { t } = useI18n() - +const api = useApiClient() const isLoading = ref() const noMoreContent = ref(false) const historyList = reactive>([]) @@ -56,15 +55,13 @@ function initPageAction() { */ function getHistoryList() { isLoading.value = true - browser.runtime - .sendMessage({ - contentScriptQuery: API.HISTORY.GET_HISTORY_LIST, - type: 'all', - view_at: + api.history.getHistoryList({ + type: 'all', + view_at: historyList.length > 0 ? historyList[historyList.length - 1].view_at : 0, - }) + }) .then((res: HistoryResult) => { if (res.code === 0) { if (Array.isArray(res.data.list) && res.data.list.length > 0) @@ -84,12 +81,10 @@ function getHistoryList() { function searchHistoryList() { isLoading.value = true - browser.runtime - .sendMessage({ - contentScriptQuery: API.HISTORY.SEARCH_HISTORY_LIST, - pn: currentPageNum.value++, - keyword: keyword.value, - }) + api.history.searchHistoryList({ + pn: currentPageNum.value++, + keyword: keyword.value, + }) .then((res: HistorySearchResult) => { if (res.code === 0) { if (historyList.length !== 0 && res.data.list.length < 20) { @@ -118,12 +113,10 @@ function handleSearch() { } function deleteHistoryItem(index: number, historyItem: HistoryItem) { - browser.runtime - .sendMessage({ - contentScriptQuery: API.HISTORY.DELETE_HISTORY_ITEM, - kid: `${historyItem.history.business}_${historyItem.history.oid}`, - csrf: getCSRF(), - }) + api.history.deleteHistoryItem({ + kid: `${historyItem.history.business}_${historyItem.history.oid}`, + csrf: getCSRF(), + }) .then((res) => { if (res.code === 0) historyList.splice(index, 1) @@ -169,10 +162,7 @@ function getHistoryItemCover(item: HistoryItem) { } function getHistoryPauseStatus() { - browser.runtime - .sendMessage({ - contentScriptQuery: API.HISTORY.GET_HISTORY_PAUSE_STATUS, - }) + api.history.getHistoryPauseStatus() .then((res) => { if (res.code === 0) historyStatus.value = res.data @@ -180,12 +170,10 @@ function getHistoryPauseStatus() { } function setHistoryPauseStatus(isPause: boolean) { - browser.runtime - .sendMessage({ - contentScriptQuery: API.HISTORY.SET_HISTORY_PAUSE_STATUS, - csrf: getCSRF(), - switch: isPause, - }) + api.history.setHistoryPauseStatus({ + csrf: getCSRF(), + switch: isPause, + }) .then((res) => { if (res.code === 0) getHistoryPauseStatus() @@ -193,11 +181,9 @@ function setHistoryPauseStatus(isPause: boolean) { } function clearAllHistory() { - browser.runtime - .sendMessage({ - contentScriptQuery: API.HISTORY.CLEAR_ALL_HISTORY, - csrf: getCSRF(), - }) + api.history.clearAllHistory({ + csrf: getCSRF(), + }) .then((res) => { if (res.code === 0) historyList.length = 0 diff --git a/src/contentScripts/views/Home/components/Following.vue b/src/contentScripts/views/Home/components/Following.vue index 58793303..eb9655fb 100644 --- a/src/contentScripts/views/Home/components/Following.vue +++ b/src/contentScripts/views/Home/components/Following.vue @@ -2,7 +2,6 @@ import type { Ref } from 'vue' import type { GridLayout } from '~/logic' import type { DataItem as MomentItem, MomentResult } from '~/models/moment/moment' -import API from '~/background/msg.define' const props = defineProps<{ gridLayout: GridLayout @@ -21,6 +20,8 @@ const gridValue = computed((): string => { return '~ cols-1 gap-4' }) +const api = useApiClient() + const videoList = reactive([]) const isLoading = ref(false) const needToLoginFirst = ref(false) @@ -82,8 +83,7 @@ async function getFollowedUsersVideos() { emit('beforeLoading') isLoading.value = true try { - const response: MomentResult = await browser.runtime.sendMessage({ - contentScriptQuery: API.MOMENT.GET_MOMENTS, + const response: MomentResult = await api.moment.getMoments({ type: 'video', offset: offset.value, update_baseline: updateBaseline.value, diff --git a/src/contentScripts/views/Home/components/ForYou.vue b/src/contentScripts/views/Home/components/ForYou.vue index 8cd77b2f..c061d023 100644 --- a/src/contentScripts/views/Home/components/ForYou.vue +++ b/src/contentScripts/views/Home/components/ForYou.vue @@ -8,7 +8,6 @@ import type { Item as VideoItem, forYouResult } from '~/models/video/forYou' import type { GridLayout } from '~/logic' import { accessKey, settings } from '~/logic' import { LanguageType } from '~/enums/appEnums' -import API from '~/background/msg.define' import { TVAppKey, getTvSign } from '~/utils/authProvider' import { isVerticalVideo } from '~/utils/uriParse' @@ -30,7 +29,7 @@ const gridValue = computed((): string => { }) const toast = useToast() - +const api = useApiClient() const videoList = reactive([]) const appVideoList = reactive([]) const isLoading = ref(true) @@ -140,8 +139,7 @@ async function getRecommendVideos() { emit('beforeLoading') isLoading.value = true try { - const response: forYouResult = await browser.runtime.sendMessage({ - contentScriptQuery: API.VIDEO.GET_RECOMMEND_VIDEOS, + const response: forYouResult = await api.video.getRecommendVideos({ fresh_idx: refreshIdx.value++, }) @@ -180,8 +178,7 @@ async function getAppRecommendVideos() { emit('beforeLoading') isLoading.value = true try { - const response: AppForYouResult = await browser.runtime.sendMessage({ - contentScriptQuery: API.VIDEO.GET_APP_RECOMMEND_VIDEOS, + const response: AppForYouResult = await api.video.getAppRecommendVideos({ access_key: accessKey.value, s_locale: settings.value.language === LanguageType.Mandarin_TW || settings.value.language === LanguageType.Cantonese ? 'zh-Hant_TW' : 'zh-Hans_CN', c_locale: settings.value.language === LanguageType.Mandarin_TW || settings.value.language === LanguageType.Cantonese ? 'zh-Hant_TW' : 'zh-Hans_CN', @@ -300,8 +297,7 @@ function handleAppDislike() { appkey: TVAppKey.appkey, } - browser.runtime.sendMessage({ - contentScriptQuery: API.VIDEO.DISLIKE_VIDEO, + api.video.dislikeVideo({ ...params, sign: getTvSign(params), }) @@ -336,8 +332,7 @@ function handleAppUndoDislike(video: AppVideoItem) { appkey: TVAppKey.appkey, } - browser.runtime.sendMessage({ - contentScriptQuery: API.VIDEO.UNDO_DISLIKE_VIDEO, + api.video.undoDislikeVideo({ ...params, sign: getTvSign(params), }).then((res) => { diff --git a/src/contentScripts/views/Home/components/Ranking.vue b/src/contentScripts/views/Home/components/Ranking.vue index b24fd265..62dc9e7d 100644 --- a/src/contentScripts/views/Home/components/Ranking.vue +++ b/src/contentScripts/views/Home/components/Ranking.vue @@ -6,7 +6,6 @@ import type { List as RankingPgcItem, RankingPgcResult } from '~/models/video/ra import type { GridLayout } from '~/logic' import { settings } from '~/logic' import emitter from '~/utils/mitt' -import API from '~/background/msg.define' const props = defineProps<{ gridLayout: GridLayout @@ -18,6 +17,7 @@ const emit = defineEmits<{ }>() const { t } = useI18n() +const api = useApiClient() const { handleBackToTop, handlePageRefresh } = useBewlyApp() const gridValue = computed((): string => { @@ -129,8 +129,7 @@ function getRankingVideos() { videoList.length = 0 emit('beforeLoading') isLoading.value = true - browser.runtime.sendMessage({ - contentScriptQuery: API.RANKING.GET_RANKING_VIDEOS, + api.ranking.getRankingVideos({ rid: activatedRankingType.value.rid, type: 'type' in activatedRankingType.value ? activatedRankingType.value.type : 'all', }).then((response: RankingResult) => { @@ -147,8 +146,7 @@ function getRankingVideos() { function getRankingPgc() { PgcList.length = 0 isLoading.value = true - browser.runtime.sendMessage({ - contentScriptQuery: API.RANKING.GET_RANKING_PGC, + api.ranking.getRankingPgc({ season_type: activatedRankingType.value.seasonType, }).then((response: RankingPgcResult) => { if (response.code === 0) diff --git a/src/contentScripts/views/Home/components/SubscribedSeries.vue b/src/contentScripts/views/Home/components/SubscribedSeries.vue index f4f5537f..3ad196d7 100644 --- a/src/contentScripts/views/Home/components/SubscribedSeries.vue +++ b/src/contentScripts/views/Home/components/SubscribedSeries.vue @@ -2,7 +2,6 @@ import type { Ref } from 'vue' import type { GridLayout } from '~/logic' import type { DataItem as MomentItem, MomentResult } from '~/models/moment/moment' -import API from '~/background/msg.define' const props = defineProps<{ gridLayout: GridLayout @@ -20,7 +19,7 @@ const gridValue = computed((): string => { return '~ cols-1 xl:cols-2 gap-4' return '~ cols-1 gap-4' }) - +const api = useApiClient() const momentList = reactive([]) const isLoading = ref(false) const needToLoginFirst = ref(false) @@ -86,8 +85,7 @@ async function getFollowedUsersVideos() { emit('beforeLoading') isLoading.value = true try { - const response: MomentResult = await browser.runtime.sendMessage({ - contentScriptQuery: API.MOMENT.GET_MOMENTS, + const response: MomentResult = await api.moment.getMoments({ type: 'pgc', offset: offset.value, update_baseline: updateBaseline.value, diff --git a/src/contentScripts/views/Home/components/Trending.vue b/src/contentScripts/views/Home/components/Trending.vue index e6d50a78..6d002a38 100644 --- a/src/contentScripts/views/Home/components/Trending.vue +++ b/src/contentScripts/views/Home/components/Trending.vue @@ -2,7 +2,6 @@ import type { Ref } from 'vue' import type { GridLayout } from '~/logic' import type { TrendingResult, List as VideoItem } from '~/models/video/trending' -import API from '~/background/msg.define' const props = defineProps<{ gridLayout: GridLayout @@ -20,7 +19,7 @@ const gridValue = computed((): string => { return '~ cols-1 xl:cols-2 gap-4' return '~ cols-1 gap-4' }) - +const api = useApiClient() const videoList = reactive([]) const isLoading = ref(false) const containerRef = ref() as Ref @@ -66,8 +65,7 @@ async function getTrendingVideos() { emit('beforeLoading') isLoading.value = true try { - const response: TrendingResult = await browser.runtime.sendMessage({ - contentScriptQuery: API.VIDEO.GET_POPULAR_VIDEOS, + const response: TrendingResult = await api.video.getPopularVideos({ pn: pn.value++, ps: 30, }) diff --git a/src/contentScripts/views/Video/Video.vue b/src/contentScripts/views/Video/Video.vue index 1f3159b0..d4fcc16a 100644 --- a/src/contentScripts/views/Video/Video.vue +++ b/src/contentScripts/views/Video/Video.vue @@ -5,6 +5,7 @@ import type { Comment, UserCardInfo, VideoInfo } from './types' import { getCSRF, removeHttpFromUrl } from '~/utils/main' import { calcTimeSince, numFormatter } from '~/utils/dataFormatter' +const api = useApiClient() const videoContent = ref() as Ref // const commentContent = ref() as Ref const danmukuContent = ref() as Ref @@ -71,9 +72,9 @@ async function getVideoInfo() { let res if (isBV) - res = await browser.runtime.sendMessage({ contentScriptQuery: 'getVideoInfo', videoId }) + res = await api.video.getVideoInfo({ videoId }) else - res = await browser.runtime.sendMessage({ contentScriptQuery: 'getVideoInfo', aid: videoId.replace('av', '') }) + res = await api.video.getVideoInfo({ aid: videoId.replace('av', '') }) if (res.code === 0) { Object.assign(videoInfo, res.data.View) Object.assign(userCardInfo, res.data.Card) @@ -134,8 +135,7 @@ async function getVideoInfo() { // } function getVideoComments() { - browser.runtime.sendMessage({ - contentScriptQuery: 'getVideoComments', + api.video.getVideoComments({ csrf: getCSRF(), oid: videoInfo.aid, pn: 1, diff --git a/src/contentScripts/views/WatchLater/WatchLater.vue b/src/contentScripts/views/WatchLater/WatchLater.vue index 9fedfbf1..b7aeefe0 100644 --- a/src/contentScripts/views/WatchLater/WatchLater.vue +++ b/src/contentScripts/views/WatchLater/WatchLater.vue @@ -4,10 +4,9 @@ import { useI18n } from 'vue-i18n' import { getCSRF, openLinkToNewTab, removeHttpFromUrl } from '~/utils/main' import { calcCurrentTime } from '~/utils/dataFormatter' import type { List as VideoItem, WatchLaterResult } from '~/models/video/watchLater' -import API from '~/background/msg.define' const { t } = useI18n() - +const api = useApiClient() const isLoading = ref() const noMoreContent = ref() const watchLaterList = reactive([]) @@ -34,10 +33,7 @@ function initPageAction() { function getAllWatchLaterList() { isLoading.value = true watchLaterList.length = 0 - browser.runtime - .sendMessage({ - contentScriptQuery: API.WATCHLATER.GET_ALL_WATCHLATER_LIST, - }) + api.watchlater.getAllWatchlaterList() .then((res: WatchLaterResult) => { if (res.code === 0) Object.assign(watchLaterList, res.data.list) @@ -47,12 +43,10 @@ function getAllWatchLaterList() { } function deleteWatchLaterItem(index: number, aid: number) { - browser.runtime - .sendMessage({ - contentScriptQuery: API.WATCHLATER.REMOVE_FROM_WATCHLATER, - aid, - csrf: getCSRF(), - }) + api.watchlater.removeFromWatchLater({ + aid, + csrf: getCSRF(), + }) .then((res) => { if (res.code === 0) watchLaterList.splice(index, 1) @@ -65,8 +59,7 @@ function handleClearAllWatchLater() { ) if (result) { isLoading.value = true - browser.runtime.sendMessage({ - contentScriptQuery: API.WATCHLATER.CLEAR_ALL_WATCHLATER, + api.watchlater.clearAllWatchLater({ csrf: getCSRF(), }).then((res) => { if (res.code === 0) @@ -82,12 +75,10 @@ function handleRemoveWatchedVideos() { t('watch_later.remove_watched_videos_confirm'), ) if (result) { - browser.runtime - .sendMessage({ - contentScriptQuery: API.WATCHLATER.REMOVE_FROM_WATCHLATER, - viewed: true, - csrf: getCSRF(), - }) + api.watchlater.removeFromWatchLater({ + viewed: true, + csrf: getCSRF(), + }) .then((res) => { if (res.code === 0) getAllWatchLaterList()