mirror of
https://github.com/MoonTechLab/LunaTV.git
synced 2026-02-15 20:34:41 +08:00
first commit
This commit is contained in:
86
src/app/api/search/one/route.ts
Normal file
86
src/app/api/search/one/route.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { getCacheTime, getConfig } from '@/lib/config';
|
||||
import { searchFromApi } from '@/lib/downstream';
|
||||
import { yellowWords } from '@/lib/yellow';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
// OrionTV 兼容接口
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const query = searchParams.get('q');
|
||||
const resourceId = searchParams.get('resourceId');
|
||||
|
||||
if (!query || !resourceId) {
|
||||
const cacheTime = await getCacheTime();
|
||||
return NextResponse.json(
|
||||
{ result: null, error: '缺少必要参数: q 或 resourceId' },
|
||||
{
|
||||
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();
|
||||
const apiSites = config.SourceConfig.filter((site) => !site.disabled);
|
||||
|
||||
try {
|
||||
// 根据 resourceId 查找对应的 API 站点
|
||||
const targetSite = apiSites.find((site) => site.key === resourceId);
|
||||
if (!targetSite) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `未找到指定的视频源: ${resourceId}`,
|
||||
result: null,
|
||||
},
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const results = await searchFromApi(targetSite, query);
|
||||
let result = results.filter((r) => r.title === query);
|
||||
if (!config.SiteConfig.DisableYellowFilter) {
|
||||
result = result.filter((result) => {
|
||||
const typeName = result.type_name || '';
|
||||
return !yellowWords.some((word: string) => typeName.includes(word));
|
||||
});
|
||||
}
|
||||
const cacheTime = await getCacheTime();
|
||||
|
||||
if (result.length === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: '未找到结果',
|
||||
result: null,
|
||||
},
|
||||
{ status: 404 }
|
||||
);
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{ results: result },
|
||||
{
|
||||
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) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: '搜索失败',
|
||||
result: null,
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
24
src/app/api/search/resources/route.ts
Normal file
24
src/app/api/search/resources/route.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { getAvailableApiSites, getCacheTime } from '@/lib/config';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
// OrionTV 兼容接口
|
||||
export async function GET() {
|
||||
try {
|
||||
const apiSites = await getAvailableApiSites();
|
||||
const cacheTime = await getCacheTime();
|
||||
|
||||
return NextResponse.json(apiSites, {
|
||||
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) {
|
||||
return NextResponse.json({ error: '获取资源失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
74
src/app/api/search/route.ts
Normal file
74
src/app/api/search/route.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any,no-console */
|
||||
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { getCacheTime, getConfig } from '@/lib/config';
|
||||
import { searchFromApi } from '@/lib/downstream';
|
||||
import { yellowWords } from '@/lib/yellow';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
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();
|
||||
const apiSites = config.SourceConfig.filter((site) => !site.disabled);
|
||||
|
||||
// 添加超时控制和错误处理,避免慢接口拖累整体响应
|
||||
const searchPromises = apiSites.map((site) =>
|
||||
Promise.race([
|
||||
searchFromApi(site, query),
|
||||
new Promise((_, reject) =>
|
||||
setTimeout(() => reject(new Error(`${site.name} timeout`)), 20000)
|
||||
),
|
||||
]).catch((err) => {
|
||||
console.warn(`搜索失败 ${site.name}:`, err.message);
|
||||
return []; // 返回空数组而不是抛出错误
|
||||
})
|
||||
);
|
||||
|
||||
try {
|
||||
const results = await Promise.allSettled(searchPromises);
|
||||
const successResults = results
|
||||
.filter((result) => result.status === 'fulfilled')
|
||||
.map((result) => (result as PromiseFulfilledResult<any>).value);
|
||||
let flattenedResults = successResults.flat();
|
||||
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();
|
||||
|
||||
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) {
|
||||
return NextResponse.json({ error: '搜索失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
137
src/app/api/search/suggestions/route.ts
Normal file
137
src/app/api/search/suggestions/route.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any,no-console */
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { searchFromApi } from '@/lib/downstream';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// 从 cookie 获取用户信息
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const config = await getConfig();
|
||||
if (config.UserConfig.Users) {
|
||||
// 检查用户是否被封禁
|
||||
const user = config.UserConfig.Users.find(
|
||||
(u) => u.username === authInfo.username
|
||||
);
|
||||
if (user && user.banned) {
|
||||
return NextResponse.json({ error: '用户已被封禁' }, { status: 401 });
|
||||
}
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const query = searchParams.get('q')?.trim();
|
||||
|
||||
if (!query) {
|
||||
return NextResponse.json({ suggestions: [] });
|
||||
}
|
||||
|
||||
// 生成建议
|
||||
const suggestions = await generateSuggestions(query);
|
||||
|
||||
// 从配置中获取缓存时间,如果没有配置则使用默认值300秒(5分钟)
|
||||
const cacheTime = config.SiteConfig.SiteInterfaceCacheTime || 300;
|
||||
|
||||
return NextResponse.json(
|
||||
{ suggestions },
|
||||
{
|
||||
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) {
|
||||
console.error('获取搜索建议失败', error);
|
||||
return NextResponse.json({ error: '获取搜索建议失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function generateSuggestions(query: string): Promise<
|
||||
Array<{
|
||||
text: string;
|
||||
type: 'exact' | 'related' | 'suggestion';
|
||||
score: number;
|
||||
}>
|
||||
> {
|
||||
const queryLower = query.toLowerCase();
|
||||
|
||||
const config = await getConfig();
|
||||
const apiSites = config.SourceConfig.filter((site: any) => !site.disabled);
|
||||
let realKeywords: string[] = [];
|
||||
|
||||
if (apiSites.length > 0) {
|
||||
// 取第一个可用的数据源进行搜索
|
||||
const firstSite = apiSites[0];
|
||||
const results = await searchFromApi(firstSite, query);
|
||||
|
||||
realKeywords = Array.from(
|
||||
new Set(
|
||||
results
|
||||
.map((r: any) => r.title)
|
||||
.filter(Boolean)
|
||||
.flatMap((title: string) => title.split(/[ -::·、-]/))
|
||||
.filter(
|
||||
(w: string) => w.length > 1 && w.toLowerCase().includes(queryLower)
|
||||
)
|
||||
)
|
||||
).slice(0, 8);
|
||||
}
|
||||
|
||||
// 根据关键词与查询的匹配程度计算分数,并动态确定类型
|
||||
const realSuggestions = realKeywords.map((word) => {
|
||||
const wordLower = word.toLowerCase();
|
||||
const queryWords = queryLower.split(/[ -::·、-]/);
|
||||
|
||||
// 计算匹配分数:完全匹配得分更高
|
||||
let score = 1.0;
|
||||
if (wordLower === queryLower) {
|
||||
score = 2.0; // 完全匹配
|
||||
} else if (
|
||||
wordLower.startsWith(queryLower) ||
|
||||
wordLower.endsWith(queryLower)
|
||||
) {
|
||||
score = 1.8; // 前缀或后缀匹配
|
||||
} else if (queryWords.some((qw) => wordLower.includes(qw))) {
|
||||
score = 1.5; // 包含查询词
|
||||
}
|
||||
|
||||
// 根据匹配程度确定类型
|
||||
let type: 'exact' | 'related' | 'suggestion' = 'related';
|
||||
if (score >= 2.0) {
|
||||
type = 'exact';
|
||||
} else if (score >= 1.5) {
|
||||
type = 'related';
|
||||
} else {
|
||||
type = 'suggestion';
|
||||
}
|
||||
|
||||
return {
|
||||
text: word,
|
||||
type,
|
||||
score,
|
||||
};
|
||||
});
|
||||
|
||||
// 按分数降序排列,相同分数按类型优先级排列
|
||||
const sortedSuggestions = realSuggestions.sort((a, b) => {
|
||||
if (a.score !== b.score) {
|
||||
return b.score - a.score; // 分数高的在前
|
||||
}
|
||||
// 分数相同时,按类型优先级:exact > related > suggestion
|
||||
const typePriority = { exact: 3, related: 2, suggestion: 1 };
|
||||
return typePriority[b.type] - typePriority[a.type];
|
||||
});
|
||||
|
||||
return sortedSuggestions;
|
||||
}
|
||||
Reference in New Issue
Block a user