feat: refactor code, sort search result

This commit is contained in:
shinya
2025-07-04 13:35:46 +08:00
parent 4988ac7207
commit faf5340b4b
9 changed files with 511 additions and 420 deletions

View File

@@ -1,3 +1,8 @@
import { getApiSites } from '@/lib/config';
import { SearchResult } from '@/lib/types';
import { getDetailFromApi, searchFromApi } from './downstream';
export interface VideoDetail {
id: string;
title: string;
@@ -16,7 +21,6 @@ interface FetchVideoDetailOptions {
source: string;
id: string;
fallbackTitle?: string;
fallbackYear?: string;
}
/**
@@ -28,24 +32,35 @@ export async function fetchVideoDetail({
source,
id,
fallbackTitle = '',
fallbackYear = '',
}: FetchVideoDetailOptions): Promise<VideoDetail> {
// 优先通过搜索接口查找精确匹配
const apiSites = getApiSites();
const apiSite = apiSites.find((site) => site.key === source);
if (!apiSite) {
throw new Error('无效的API来源');
}
if (fallbackTitle) {
try {
const searchResp = await fetch(
`/api/search?q=${encodeURIComponent(fallbackTitle.trim())}`
const searchData = await searchFromApi(apiSite, fallbackTitle.trim());
const exactMatch = searchData.find(
(item: SearchResult) =>
item.source.toString() === source.toString() &&
item.id.toString() === id.toString()
);
if (searchResp.ok) {
const searchData = await searchResp.json();
const exactMatch = searchData.results.find(
(item: VideoDetail) =>
item.source.toString() === source.toString() &&
item.id.toString() === id.toString()
);
if (exactMatch) {
return exactMatch as VideoDetail;
}
if (exactMatch) {
return {
id: exactMatch.id,
title: exactMatch.title,
poster: exactMatch.poster,
episodes: exactMatch.episodes,
source: exactMatch.source,
source_name: exactMatch.source_name,
class: exactMatch.class,
year: exactMatch.year,
desc: exactMatch.desc,
type_name: exactMatch.type_name,
douban_id: exactMatch.douban_id,
} as VideoDetail;
}
} catch (error) {
// do nothing
@@ -53,22 +68,18 @@ export async function fetchVideoDetail({
}
// 调用 /api/detail 接口
const response = await fetch(`/api/detail?source=${source}&id=${id}`);
if (!response.ok) {
throw new Error('获取详情失败');
}
const data = await response.json();
const detail = await getDetailFromApi(apiSite, id);
return {
id: data?.videoInfo?.id || id,
title: data?.videoInfo?.title.trim() || fallbackTitle.trim(),
poster: data?.videoInfo?.cover || '',
episodes: data?.episodes || [],
source: data?.videoInfo?.source || source,
source_name: data?.videoInfo?.source_name || '',
class: data?.videoInfo?.remarks || '',
year: data?.videoInfo?.year || fallbackYear || '',
desc: data?.videoInfo?.desc || '',
type_name: data?.videoInfo?.type || '',
} as VideoDetail;
id: detail.videoInfo.id,
title: detail.videoInfo.title,
poster: detail.videoInfo.cover || '',
episodes: detail.episodes,
source: detail.videoInfo.source,
source_name: detail.videoInfo.source_name,
class: detail.videoInfo.remarks,
year: detail.videoInfo.year || '',
desc: detail.videoInfo.desc,
type_name: detail.videoInfo.type,
};
}