Files
MoonTVPlus/src/app/api/search/route.ts

217 lines
7.7 KiB
TypeScript
Raw Normal View History

2025-08-12 21:50:58 +08:00
/* eslint-disable @typescript-eslint/no-explicit-any,no-console */
2025-08-20 19:37:36 +08:00
import { NextRequest, NextResponse } from 'next/server';
2025-08-12 21:50:58 +08:00
2025-08-20 19:39:00 +08:00
import { getAuthInfoFromCookie } from '@/lib/auth';
2025-08-20 19:37:36 +08:00
import { getAvailableApiSites, getCacheTime, getConfig } from '@/lib/config';
2025-08-12 21:50:58 +08:00
import { searchFromApi } from '@/lib/downstream';
import { yellowWords } from '@/lib/yellow';
2025-08-18 23:04:27 +08:00
export const runtime = 'nodejs';
2025-08-12 21:50:58 +08:00
2025-08-20 19:37:36 +08:00
export async function GET(request: NextRequest) {
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo || !authInfo.username) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
2025-08-12 21:50:58 +08:00
const { searchParams } = new URL(request.url);
const query = searchParams.get('q');
if (!query) {
const cacheTime = await getCacheTime();
return NextResponse.json(
{ results: [] },
{
headers: {
'Cache-Control': `public, max-age=${cacheTime}, s-maxage=${cacheTime}`,
'CDN-Cache-Control': `public, s-maxage=${cacheTime}`,
'Vercel-CDN-Cache-Control': `public, s-maxage=${cacheTime}`,
'Netlify-Vary': 'query',
},
}
);
}
const config = await getConfig();
2025-08-20 19:37:36 +08:00
const apiSites = await getAvailableApiSites(authInfo.username);
2025-08-12 21:50:58 +08:00
// 检查是否配置了 OpenList
const hasOpenList = !!(
config.OpenListConfig?.Enabled &&
config.OpenListConfig?.URL &&
config.OpenListConfig?.Username &&
config.OpenListConfig?.Password
);
2026-01-08 00:14:07 +08:00
// 获取所有启用的 Emby 源
const { embyManager } = await import('@/lib/emby-manager');
const embySourcesMap = await embyManager.getAllClients();
const embySources = Array.from(embySourcesMap.values());
2026-01-03 01:04:38 +08:00
2026-01-08 00:14:07 +08:00
console.log('[Search] Emby sources count:', embySources.length);
console.log('[Search] Emby sources:', embySources.map(s => ({ key: s.config.key, name: s.config.name })));
// 为每个 Emby 源创建搜索 Promise全部并发无限制
const embyPromises = embySources.map(({ client, config: embyConfig }) =>
Promise.race([
(async () => {
try {
const searchResult = await client.getItems({
searchTerm: query,
IncludeItemTypes: 'Movie,Series',
Recursive: true,
Fields: 'Overview,ProductionYear',
Limit: 50,
});
// 如果只有一个Emby源保持旧格式向后兼容
const sourceValue = embySources.length === 1 ? 'emby' : `emby_${embyConfig.key}`;
const sourceName = embySources.length === 1 ? 'Emby' : embyConfig.name;
return searchResult.Items.map((item) => ({
id: item.Id,
source: sourceValue,
source_name: sourceName,
title: item.Name,
poster: client.getImageUrl(item.Id, 'Primary'),
episodes: [],
episodes_titles: [],
year: item.ProductionYear?.toString() || '',
desc: item.Overview || '',
type_name: item.Type === 'Movie' ? '电影' : '电视剧',
douban_id: 0,
}));
} catch (error) {
console.error(`[Search] 搜索 ${embyConfig.name} 失败:`, error);
return [];
}
})(),
new Promise<any[]>((_, reject) =>
setTimeout(() => reject(new Error(`${embyConfig.name} timeout`)), 20000)
),
]).catch((error) => {
console.error(`[Search] 搜索 ${embyConfig.name} 超时:`, error);
return [];
})
);
2026-01-05 14:24:16 +08:00
// 搜索 OpenList如果配置了- 异步带超时
const openlistPromise = hasOpenList
? Promise.race([
(async () => {
try {
const { getCachedMetaInfo, setCachedMetaInfo } = await import('@/lib/openlist-cache');
const { getTMDBImageUrl } = await import('@/lib/tmdb.search');
const { db } = await import('@/lib/db');
2026-01-10 10:25:14 +08:00
let metaInfo = getCachedMetaInfo();
if (!metaInfo) {
const metainfoJson = await db.getGlobalValue('video.metainfo');
if (metainfoJson) {
metaInfo = JSON.parse(metainfoJson);
if (metaInfo) {
2026-01-10 10:25:14 +08:00
setCachedMetaInfo(metaInfo);
}
2026-01-05 14:24:16 +08:00
}
}
if (metaInfo && metaInfo.folders) {
return Object.entries(metaInfo.folders)
.filter(([folderName, info]: [string, any]) => {
const matchFolder = folderName.toLowerCase().includes(query.toLowerCase());
const matchTitle = info.title.toLowerCase().includes(query.toLowerCase());
return matchFolder || matchTitle;
})
.map(([folderName, info]: [string, any]) => ({
id: folderName,
source: 'openlist',
source_name: '私人影库',
title: info.title,
poster: getTMDBImageUrl(info.poster_path),
episodes: [],
episodes_titles: [],
year: info.release_date.split('-')[0] || '',
desc: info.overview,
type_name: info.media_type === 'movie' ? '电影' : '电视剧',
douban_id: 0,
}));
}
return [];
} catch (error) {
console.error('[Search] 搜索 OpenList 失败:', error);
return [];
2026-01-05 14:24:16 +08:00
}
})(),
new Promise<any[]>((_, reject) =>
setTimeout(() => reject(new Error('OpenList timeout')), 20000)
),
]).catch((error) => {
console.error('[Search] 搜索 OpenList 超时:', error);
2026-01-05 14:24:16 +08:00
return [];
})
: Promise.resolve([]);
2025-08-12 21:50:58 +08:00
// 添加超时控制和错误处理,避免慢接口拖累整体响应
const searchPromises = apiSites.map((site) =>
Promise.race([
searchFromApi(site, query),
new Promise((_, reject) =>
2025-08-21 00:01:03 +08:00
setTimeout(() => reject(new Error(`${site.name} timeout`)), 20000)
2025-08-12 21:50:58 +08:00
),
]).catch((err) => {
console.warn(`搜索失败 ${site.name}:`, err.message);
return []; // 返回空数组而不是抛出错误
})
);
try {
2026-01-08 00:14:07 +08:00
const allResults = await Promise.all([
2026-01-05 14:24:16 +08:00
openlistPromise,
2026-01-08 00:14:07 +08:00
...embyPromises,
2026-01-05 14:24:16 +08:00
...searchPromises,
]);
2026-01-08 00:14:07 +08:00
// 分离结果:第一个是 openlist接下来是 emby 结果,最后是 api 结果
2026-01-08 23:05:50 +08:00
// 添加安全检查,确保即使某个结果处理出错也不影响其他结果
const openlistResults = Array.isArray(allResults[0]) ? allResults[0] : [];
2026-01-08 00:14:07 +08:00
const embyResultsArray = allResults.slice(1, 1 + embyPromises.length);
const apiResults = allResults.slice(1 + embyPromises.length);
2026-01-08 23:05:50 +08:00
// 合并所有 Emby 结果,添加安全检查
const embyResults = embyResultsArray.filter(Array.isArray).flat();
const apiResultsFlat = apiResults.filter(Array.isArray).flat();
let flattenedResults = [...openlistResults, ...embyResults, ...apiResultsFlat];
2025-08-12 21:50:58 +08:00
if (!config.SiteConfig.DisableYellowFilter) {
flattenedResults = flattenedResults.filter((result) => {
const typeName = result.type_name || '';
return !yellowWords.some((word: string) => typeName.includes(word));
});
}
const cacheTime = await getCacheTime();
if (flattenedResults.length === 0) {
// no cache if empty
return NextResponse.json({ results: [] }, { status: 200 });
}
2025-08-12 21:50:58 +08:00
return NextResponse.json(
{ results: flattenedResults },
{
headers: {
'Cache-Control': `public, max-age=${cacheTime}, s-maxage=${cacheTime}`,
'CDN-Cache-Control': `public, s-maxage=${cacheTime}`,
'Vercel-CDN-Cache-Control': `public, s-maxage=${cacheTime}`,
'Netlify-Vary': 'query',
},
}
);
} catch (error) {
2026-01-08 23:05:50 +08:00
console.error('[Search] 搜索结果处理失败:', error);
2025-08-12 21:50:58 +08:00
return NextResponse.json({ error: '搜索失败' }, { status: 500 });
}
}