mirror of
https://gh-proxy.org/https://github.com/tiajinsha/JKVideo
synced 2026-07-08 07:28:37 +08:00
1
This commit is contained in:
@@ -1,12 +1,35 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { getVideoDetail, getPlayUrl } from '../services/bilibili';
|
||||
import type { VideoItem } from '../services/types';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import type { VideoItem, PlayUrlResponse } from '../services/types';
|
||||
|
||||
export function useVideoDetail(bvid: string) {
|
||||
const [video, setVideo] = useState<VideoItem | null>(null);
|
||||
const [streamUrl, setStreamUrl] = useState<string | null>(null);
|
||||
const [playData, setPlayData] = useState<PlayUrlResponse | null>(null);
|
||||
const [qualities, setQualities] = useState<{ qn: number; desc: string }[]>([]);
|
||||
const [currentQn, setCurrentQn] = useState<number>(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const cidRef = useRef<number>(0);
|
||||
const isLoggedIn = useAuthStore(s => s.isLoggedIn);
|
||||
|
||||
async function fetchPlayData(cid: number, qn: number, updateList = false) {
|
||||
const data = await getPlayUrl(bvid, cid, qn);
|
||||
setPlayData(data);
|
||||
setCurrentQn(data.quality);
|
||||
if (updateList && data.accept_quality?.length) {
|
||||
setQualities(
|
||||
data.accept_quality.map((q, i) => ({
|
||||
qn: q,
|
||||
desc: data.accept_description?.[i] ?? String(q),
|
||||
}))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function changeQuality(qn: number) {
|
||||
await fetchPlayData(cidRef.current, qn);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchData() {
|
||||
@@ -15,8 +38,8 @@ export function useVideoDetail(bvid: string) {
|
||||
const detail = await getVideoDetail(bvid);
|
||||
setVideo(detail);
|
||||
const cid = detail.pages?.[0]?.cid ?? detail.cid;
|
||||
const playData = await getPlayUrl(bvid, cid);
|
||||
setStreamUrl(playData.durl[0]?.url ?? null);
|
||||
cidRef.current = cid;
|
||||
await fetchPlayData(cid, 120, true);
|
||||
} catch (e: any) {
|
||||
setError(e.message ?? 'Load failed');
|
||||
} finally {
|
||||
@@ -26,5 +49,12 @@ export function useVideoDetail(bvid: string) {
|
||||
if (bvid) fetchData();
|
||||
}, [bvid]);
|
||||
|
||||
return { video, streamUrl, loading, error };
|
||||
// 登录状态变化时重新拉取清晰度列表(登录后可能获得更高画质)
|
||||
useEffect(() => {
|
||||
if (cidRef.current) {
|
||||
fetchPlayData(cidRef.current, 120, true).catch(() => {});
|
||||
}
|
||||
}, [isLoggedIn]);
|
||||
|
||||
return { video, playData, loading, error, qualities, currentQn, changeQuality };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user