refactor: 使用新版推介影片接口,將寫法調整為 Composition API

This commit is contained in:
Hakadao
2022-12-20 23:57:05 +08:00
parent d425d778f6
commit 4dcbd71983
4 changed files with 161 additions and 208 deletions

View File

@@ -1,12 +1,19 @@
import browser from 'webextension-polyfill'
import { APP_URL } from '.'
import { API_URL, APP_URL } from '.'
export const setupVideosAPIs = () => {
browser.runtime.onMessage.addListener((message) => {
/** Recommend Videos */
// if (message.contentScriptQuery === 'getRecommendVideos') {
// // https://github.com/indefined/UserScripts/blob/master/bilibiliHome/bilibiliHome.API.md#%E8%8E%B7%E5%8F%96%E9%A6%96%E9%A1%B5%E5%86%85%E5%AE%B9
// const url = `${APP_URL}/x/feed/index?build=1&idx=${message.idx}&appkey=27eb53fc9058f8c3&access_key=${message.accessKey}`
// return fetch(url)
// .then(response => response.json())
// .then(data => data)
// .catch(error => console.error(error))
// }
if (message.contentScriptQuery === 'getRecommendVideos') {
// https://github.com/indefined/UserScripts/blob/master/bilibiliHome/bilibiliHome.API.md#%E8%8E%B7%E5%8F%96%E9%A6%96%E9%A1%B5%E5%86%85%E5%AE%B9
const url = `${APP_URL}/x/feed/index?build=1&idx=${message.idx}&appkey=27eb53fc9058f8c3&access_key=${message.accessKey}`
const url = `${API_URL}/x/web-interface/index/top/feed/rcmd?fresh_idx=${message.refreshIdx}&feed_version=V1&fresh_type=4&ps=30&plat=1`
return fetch(url)
.then(response => response.json())
.then(data => data)

View File

@@ -1,23 +1,11 @@
<script lang="ts" setup>
import type { Video } from './types'
import { accessKey, language } from '~/logic/index'
import { calcCurrentTime, calcTimeSince, numFormatter } from '~/utils'
import { LanguageType } from '~/enums/appEnums'
defineProps<{
cover: string
duration: number
mid: number
title: string
authorAvatar: string
param: string
viewCount: number
channelName: string
// Created time
ctime: number
dislikeReasons: Array<{ reason_id: number; reason_name: string }>
goto: string
tid: number
tag: { tag_id: number; tag_name: string }
videoData: Video
}>()
const isDislike = ref<boolean>(false)
@@ -32,60 +20,60 @@ function gotoVideo(param: string) {
window.open(`/video/av${param}`)
}
function submitDislike(
reasonID: number,
goto: string,
id: string,
mid: number,
rid: number,
tagID: number,
) {
browser.runtime
.sendMessage({
contentScriptQuery: 'submitDislike',
accessKey: accessKey.value,
reasonID,
goto,
id,
mid,
rid,
tagID,
})
.then((res) => {
if (res.code === 0) {
isDislike.value = true
dislikeReasonId.value = reasonID
}
})
}
// function submitDislike(
// reasonID: number,
// goto: string,
// id: string,
// mid: number,
// rid: number,
// tagID: number,
// ) {
// browser.runtime
// .sendMessage({
// contentScriptQuery: 'submitDislike',
// accessKey: accessKey.value,
// reasonID,
// goto,
// id,
// mid,
// rid,
// tagID,
// })
// .then((res) => {
// if (res.code === 0) {
// isDislike.value = true
// dislikeReasonId.value = reasonID
// }
// })
// }
function undoDislike(
reasonID: number,
goto: string,
id: string,
mid: number,
rid: number,
tagID: number,
) {
browser.runtime
.sendMessage({
contentScriptQuery: 'undoDislike',
accessKey,
reasonID,
goto,
id,
mid,
rid,
tagID,
})
.then((res) => {
if (res.code === 0) {
isDislike.value = false
dislikeReasonId.value = null
showPopCtrl.value = false
}
})
}
// function undoDislike(
// reasonID: number,
// goto: string,
// id: string,
// mid: number,
// rid: number,
// tagID: number,
// ) {
// browser.runtime
// .sendMessage({
// contentScriptQuery: 'undoDislike',
// accessKey,
// reasonID,
// goto,
// id,
// mid,
// rid,
// tagID,
// })
// .then((res) => {
// if (res.code === 0) {
// isDislike.value = false
// dislikeReasonId.value = null
// showPopCtrl.value = false
// }
// })
// }
</script>
<template>
@@ -115,7 +103,7 @@ function undoDislike(
style="aspect-ratio: 16/9"
>
{{ $t('home.video_removed') }}
<button
<!-- <button
text="$bew-theme-color base"
font="bold"
m="t-4"
@@ -131,12 +119,12 @@ function undoDislike(
"
>
{{ $t('common.undo') }}
</button>
</button> -->
</div>
</template>
<template v-else>
<a :href="`/video/av${param}`" target="_blank">
<a :href="`/video/${videoData.bvid}`" target="_blank">
<div
class="aspect-video"
w="full"
@@ -155,7 +143,7 @@ function undoDislike(
text="!white xs"
bg="black opacity-60"
>
{{ calcCurrentTime(duration) }}
{{ calcCurrentTime(videoData.duration) }}
</div>
<div
@@ -169,7 +157,7 @@ function undoDislike(
>
<!-- Video cover -->
<img
:src="`${cover.replace('http:', '')}@672w_378h_1c`"
:src="`${videoData.pic.replace('http:', '')}@672w_378h_1c`"
loading="lazy"
class="aspect-auto"
w="full"
@@ -184,7 +172,7 @@ function undoDislike(
<!-- Shadow of the video cover -->
<img
:src="`${cover.replace('http:', '')}@672w_378h_1c`"
:src="`${videoData.pic.replace('http:', '')}@672w_378h_1c`"
loading="lazy"
class="aspect-video"
w="full"
@@ -211,10 +199,13 @@ function undoDislike(
object="center cover"
bg="$bew-fill-3"
cursor="pointer"
@click="gotoChannel(mid)"
@click="gotoChannel(videoData.owner.mid)"
>
<img
:src="`${`${authorAvatar}`.replace('http:', '')}@60w_60h_1c`"
:src="`${`${videoData.owner.face}`.replace(
'http:',
'',
)}@60w_60h_1c`"
width="48"
height="48"
loading="lazy"
@@ -225,7 +216,6 @@ function undoDislike(
<div flex="~" justify="between" w="full" pos="relative">
<h3
class="video-title"
:title="title"
cursor="pointer"
text="lg overflow-ellipsis space-normal $bew-text-1"
h="max-13"
@@ -235,12 +225,12 @@ function undoDislike(
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
"
@click="gotoVideo(param)"
@click="gotoVideo(videoData.bvid)"
>
{{ title }}
{{ videoData.title }}
</h3>
<div
<!-- <div
id="dislike-control-btn"
class="icon-btn"
p="t-0.15rem x-2"
@@ -250,7 +240,7 @@ function undoDislike(
@click.stop="showPopCtrl = !showPopCtrl"
>
<tabler:dots-vertical text="lg" />
</div>
</div> -->
<!-- dislike control -->
<template v-if="showPopCtrl">
@@ -263,7 +253,8 @@ function undoDislike(
@click="showPopCtrl = false"
/>
<div
<!-- dislike reason popup -->
<!-- <div
pos="absolute top-9 right-0"
p="2"
z="30"
@@ -302,26 +293,26 @@ function undoDislike(
{{ reason.reason_name }}
</li>
</ul>
</div>
</div> -->
</template>
</div>
<div
class="channel-name"
text="base $bew-text-2"
m="t-2"
@click="gotoChannel(mid)"
@click="gotoChannel(videoData.owner.mid)"
>
{{ channelName }}
{{ videoData.owner.name }}
</div>
<div class="video-info" text="base $bew-text-2">
{{ numFormatter(viewCount)
{{ numFormatter(videoData.stat.view)
}}{{
language === LanguageType.English
? ` ${$t('common.view', viewCount)}`
: $t('common.view', viewCount)
? ` ${$t('common.view', videoData.stat.view)}`
: $t('common.view', videoData.stat.view)
}}
<span class="text-xs font-light"></span>
{{ calcTimeSince(ctime * 1000)
{{ calcTimeSince(videoData.pubdate * 1000)
}}{{
language === LanguageType.English
? ` ${$t('common.ago')}`

View File

@@ -0,0 +1,19 @@
export interface Video {
id: number
bvid: string
owner: {
face: string
mid: number
name: string
}
pic: string
pubdate: number
stat: {
danmaku: number
like: number
view: number
}
title: string
uri: string
duration: number
}

View File

@@ -1,139 +1,75 @@
<script lang="ts">
<script setup lang="ts">
import { accessKey, language } from '~/logic/index'
import { calcCurrentTime, calcTimeSince, numFormatter } from '~/utils'
import { LanguageType } from '~/enums/appEnums'
import type { Video } from '~/components/VideoCard/types'
export default defineComponent({
data() {
return {
videoList: [] as any[],
isLoading: true,
numFormatter,
calcTimeSince,
calcCurrentTime,
MAX_LIMIT: 150 as const,
accessKey,
LanguageType,
language,
const videoList = reactive<Video[]>([])
const isLoading = ref<boolean>(false)
let refreshIdx = 1
onMounted(() => {
getRecommendVideos(refreshIdx)
window.onscroll = async () => {
if (window.innerHeight + window.scrollY >= document.body.scrollHeight - 20) {
if (isLoading.value)
return
isLoading.value = true
refreshIdx++
await getRecommendVideos(refreshIdx)
isLoading.value = false
}
},
mounted() {
// need to wait for accessKey to be loaded, otherwise the accessKey will be undefined
setTimeout(() => {
this.getRecommendVideos()
this.getRecommendVideos()
}, 2000)
window.onscroll = async () => {
if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {
if (!this.isLoading)
return
if (this.videoList.length <= this.MAX_LIMIT - 20) {
await this.getRecommendVideos(
this.videoList[this.videoList.length - 1]?.idx,
)
await this.getRecommendVideos(
this.videoList[this.videoList.length - 1]?.idx,
)
}
else {
this.isLoading = false
}
}
}
},
methods: {
async getRecommendVideos(idx?: number) {
const response = await browser.runtime.sendMessage({
contentScriptQuery: 'getRecommendVideos',
idx,
accessKey: this.accessKey,
})
if (response.code === 0) {
const resData = [] as any[]
response.data.forEach((item: any) => {
// remove ad videos
if (!item.ad_cb)
resData.push(item)
})
// when videoList has length property, it means it is the first time to load
if (!this.videoList.length) {
this.videoList = resData
}
else {
// else we concat the new data to the old data
this.videoList = this.videoList.concat(resData)
}
}
},
onRefresh() {
this.isLoading = true
this.videoList = []
},
onEnter(el: Element, done: () => void) {
const element = el as HTMLElement
element.style.transitionDelay = '0.1s'
done()
},
},
}
})
async function getRecommendVideos(idx?: number) {
const response = await browser.runtime.sendMessage({
contentScriptQuery: 'getRecommendVideos',
refreshIdx: idx,
})
if (response.code === 0) {
const resData = [] as Video[]
response.data.item.forEach((item: Video) => {
resData.push(item)
})
// when videoList has length property, it means it is the first time to load
if (!videoList.length) {
Object.assign(videoList, resData)
}
else {
// else we concat the new data to the old data
Object.assign(videoList, videoList.concat(resData))
}
}
}
function onEnter(el: Element, done: () => void) {
const element = el as HTMLElement
element.style.transitionDelay = '0.1s'
done()
}
</script>
<template>
<div
m="lg:x-22 <lg:x-16 b-0 t-0"
grid="~ xl:cols-4 lg:cols-3 md:cols-2 gap-4"
grid="~ 2xl:cols-5 xl:cols-4 lg:cols-3 md:cols-2 gap-4"
>
<TransitionGroup name="list" @enter="onEnter">
<VideoCard
v-for="(video) in videoList"
:key="video.idx"
:cover="video.cover"
:duration="video.duration"
:mid="video.mid"
:title="video.title"
:author-avatar="video.face"
:param="video.param"
:view-count="video.play"
:channel-name="video.name"
:ctime="video.ctime"
:dislike-reasons="video.dislike_reasons"
:goto="video.goto"
:tid="video.tid"
:tag="video.tag"
v-for="video in videoList"
:key="video.id"
:video-data="video"
/>
</TransitionGroup>
</div>
<loading v-if="isLoading" />
<div
v-if="!isLoading"
style="height: 100px"
w="full"
p="y-8"
flex="~"
items="center"
justify="center"
>
<button
style="box-shadow: var(--bew-shadow-1)"
bg="!$bew-theme-color"
w="60px"
h="60px"
text="white 2xl"
rounded="full"
flex="~"
justify="center"
items="center"
@click="onRefresh"
>
<tabler:refresh />
</button>
</div>
</template>
<style lang="scss" scoped>