diff --git a/CHANGELOG.md b/CHANGELOG.md index cafe9b4..37a0ab4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,32 @@ 本文档记录 KatelyaTV 项目的重要更新和功能变更。 +## [fixed131] - 2026-11-14 + +### ✨ 重做(相关推荐:本站片源按元数据匹配,点击直达实际片源) +- **数据源换成本站已有片源,不再走豆瓣推荐接口**:新增 `/api/related` 接口 + (`src/app/api/related/route.ts`),用当前片的 **主演 / 导演** 名称全站搜索本站资源站拿到候选池, + 再对前 12 个候选取详情,按 **主演、导演、语言、地区、类型** 五项元数据重合度打分, + 排除自己/同名/豆瓣同 ID,同名跨源去重后取前 10 返回(`score` + `reasons` 标注重合依据)。 +- **点击直达实际片源**:相关推荐卡片 `href` 改为 `/play?source=<源>&id=<条目ID>&title=...` + (`src/components/VideoMetaExtra.tsx`),带 source+id 进播放页后 **直接取该条详情开播, + 不再做标题搜索**(`src/app/play/page.tsx` 直达模式)——彻底解决「按 title 找片对不上」的问题; + 同名源随后台补搜填充「换源」面板,不阻塞开播;该 id 失效时自动回退标题搜索。 +- **推荐规则显示在「相关推荐」旁**:标题右侧常驻说明「按主演 / 导演 / 语言 / 地区 / 类型匹配 · 本站片源直达」, + 每张卡片下方还显示年份 · 源站与重合依据(如「导演:叶伟信 · 主演:甄子丹」,悬停看全量)。 +- `/api/related` 加入 middleware 白名单(与 `/api/search`、`/api/detail` 同级),接口 10 分钟内存缓存。 + +### 验证 +- 《叶问》(甄子丹/叶伟信/香港/剧情,动作) → 10 条全部同导演同主演:叶问2/叶问4、杀破狼、龙虎门、导火线、叶问3 等,耗时 12.7s。 +- 返回条目逐条 `source+id` 直取 `/api/detail` 均返回可播 m3u8(如叶问2 → c1.rrcdnbf2.com/.../index.m3u8);`/play?source=&id=` HTTP 200。 +- 构建产物确认播放页 chunk 含「本站片源直达」文案与 `/api/related` 调用。 + +### 🔄 保持不变 +- 登录/注册鉴权、豆瓣评分/短评(仅推荐改成本站数据)、TVBox 配置(fixed128)、首页最新港剧(fixed127)、首访 IPv6 线路门。 + +### 镜像 +- katelyatv:fixed131(内网 + 腾讯云双推,latest 同步) + ## [fixed130] - 2026-11-14 ### ✨ 优化(相关推荐) diff --git a/Dockerfile b/Dockerfile index 0757764..c4061f3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -35,7 +35,7 @@ RUN find ./src -type f -name "route.ts" -print0 \ ENV DOCKER_ENV=true # 海报走站内 /api/image-proxy(浏览器直连豆瓣图被拦导致全裂) ENV NEXT_PUBLIC_IMAGE_PROXY=/api/image-proxy -ENV NEXT_PUBLIC_SITE_VERSION=fixed129 +ENV NEXT_PUBLIC_SITE_VERSION=fixed131 ENV NEXT_PUBLIC_ENABLE_REGISTER=true # For Docker builds, force dynamic rendering to read runtime environment variables. @@ -56,7 +56,7 @@ ENV HOSTNAME=0.0.0.0 ENV PORT=3000 ENV DOCKER_ENV=true ENV NEXT_PUBLIC_IMAGE_PROXY=/api/image-proxy -ENV NEXT_PUBLIC_SITE_VERSION=fixed129 +ENV NEXT_PUBLIC_SITE_VERSION=fixed131 ENV NEXT_PUBLIC_ENABLE_REGISTER=true # 从构建器中复制 standalone 输出 diff --git a/README.md b/README.md index d424e15..643c40d 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,7 @@ docker compose -f docker-compose.redis.yml down ## 📋 更新日志 +- **v-fixed131**:相关推荐重做——数据改为**本站已有片源**,新增 `/api/related` 按 **主演/导演/语言/地区/类型** 五项元数据匹配打分(豆瓣推荐接口不再用于推荐);卡片点击带 `source+id` **直达实际片源开播**(播放页直达模式不再按标题搜索,杜绝片源对不上);「相关推荐」标题旁常驻显示匹配规则「按主演 / 导演 / 语言 / 地区 / 类型匹配 · 本站片源直达」,卡片下标注重合依据 - **v-fixed130**:详情页「相关推荐」标题旁显示推荐规则说明「豆瓣相似影片推荐 · 取前10」(数据来自豆瓣官方推荐接口,取前 10 条相似影片) - **v-fixed129**:详情页「相关推荐」点击改为直接打开影片详情并播放(`/play?title=`,原为跳搜索页 `/search?q=`);播放页标题匹配加兜底(精确匹配不到时放宽到双向包含,避免点进去报「未找到匹配结果」) diff --git a/src/app/api/related/route.ts b/src/app/api/related/route.ts new file mode 100644 index 0000000..cb9ad45 --- /dev/null +++ b/src/app/api/related/route.ts @@ -0,0 +1,268 @@ +import { NextResponse } from 'next/server'; + +import { getAvailableApiSites, getCacheTime, type ApiSite } from '@/lib/config'; +import { addCorsHeaders, handleOptionsRequest } from '@/lib/cors'; +import { searchFromApi, getDetailFromApi } from '@/lib/downstream'; +import type { SearchResult } from '@/lib/types'; + +export const runtime = 'edge'; + +// 处理OPTIONS预检请求 +export async function OPTIONS() { + return handleOptionsRequest(); +} + +// --------------------------------------------------------------------------- +// 相关推荐:只在本站已有片源里找,按「主演 / 导演 / 语言 / 地区 / 类型」匹配, +// 返回可直接播放的 source+id(点击进 /play?source=&id= 直达,不走标题搜索)。 +// --------------------------------------------------------------------------- + +interface RelatedItem { + source: string; + source_name: string; + id: string; + title: string; + poster: string; + year: string; + score: number; + reasons: string[]; +} + +// edge 实例内的短 TTL 缓存,避免同一部片反复全站搜索 +const cache = new Map(); +const CACHE_TTL = 10 * 60 * 1000; + +// 拆分人名/地区/语言/类型串(、,,/;| 和空白分隔) +function splitNames(raw: string, max: number): string[] { + if (!raw) return []; + const parts = raw + .split(/[、,,/;;|]+|\s+/) + .map((x) => x.trim()) + .filter((x) => x.length >= 2); + const seen = new Set(); + const out: string[] = []; + for (const p of parts) { + if (!seen.has(p)) { + seen.add(p); + out.push(p); + } + if (out.length >= max) break; + } + return out; +} + +function normTitle(x: string): string { + return x + .replace(/[\s·::\-—\[\]【]()()、\/]/g, '') + .toLowerCase(); +} + +// 双向包含式重叠("中国香港" 与 "香港" 互认) +function overlap(self: string[], cand: string[]): string[] { + return self.filter( + (a) => a.length >= 2 && cand.some((b) => b.includes(a) || a.includes(b)) + ); +} + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const title = searchParams.get('title') || ''; + const actor = searchParams.get('actor') || ''; + const director = searchParams.get('director') || ''; + const area = searchParams.get('area') || ''; + const lang = searchParams.get('lang') || ''; + const genre = searchParams.get('genre') || ''; + const isTvRaw = searchParams.get('isTv'); // '1' | '0' | null + const doubanId = searchParams.get('doubanId') || ''; + const selfSource = searchParams.get('selfSource') || ''; + const selfId = searchParams.get('selfId') || ''; + + const respond = async (items: RelatedItem[]) => { + const cacheTime = await getCacheTime(); + const response = NextResponse.json( + { items }, + { + 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}`, + }, + } + ); + return addCorsHeaders(response); + }; + + const dirs = splitNames(director, 2); + const acts = splitNames(actor, 3); + // 没有主演/导演就没有匹配依据 → 不出相关推荐 + if (!title || (dirs.length === 0 && acts.length === 0)) { + return respond([]); + } + + const cacheKey = [ + title, actor, director, area, lang, genre, isTvRaw, doubanId, selfSource, selfId, + ].join('|'); + const hit = cache.get(cacheKey); + if (hit && Date.now() - hit.ts < CACHE_TTL) { + return respond(hit.items); + } + + try { + const sites = await getAvailableApiSites(true); // 与搜索一致:过滤成人源 + if (!sites || sites.length === 0) return respond([]); + + // 1) 按 导演名/演员名 全站搜索,得到「本站已有」的候选池(带来源强度) + const keywords: { kw: string; dir: boolean }[] = [ + ...dirs.map((k) => ({ kw: k, dir: true })), + ...acts.map((k) => ({ kw: k, dir: false })), + ]; + const prov = new Map< + string, + { dir: number; act: number; sample: SearchResult } + >(); + await Promise.all( + keywords.map(async ({ kw, dir }) => { + const batches = await Promise.all( + sites.map((site) => + searchFromApi(site, kw).catch(() => [] as SearchResult[]) + ) + ); + for (const r of batches.flat()) { + if (!r || !r.id || !r.source) continue; + const key = `${r.source}:${r.id}`; + const cur = prov.get(key) || { dir: 0, act: 0, sample: r }; + if (dir) cur.dir += 1; + else cur.act += 1; + if (!cur.sample.episodes?.length && r.episodes?.length) { + cur.sample = r; + } + prov.set(key, cur); + } + }) + ); + + const selfTitle = normTitle(title); + const selfKey = selfSource && selfId ? `${selfSource}:${selfId}` : ''; + const doubanNum = parseInt(doubanId, 10); + + // 2) 初筛:必须可播放、不是本条目、不是同名 + const pool: { r: SearchResult; dir: number; act: number }[] = []; + prov.forEach((v, key) => { + const r = v.sample; + if (key === selfKey) return; + if (!r.episodes || r.episodes.length === 0) return; + if (selfTitle && normTitle(r.title) === selfTitle) return; + if (doubanNum && r.douban_id === doubanNum) return; + pool.push({ r, dir: v.dir, act: v.act }); + }); + if (pool.length === 0) return respond([]); + + // 3) 按来源强度排序,取前 12 补全元数据(主演/导演/地区/语言 只在详情里有) + pool.sort((a, b) => b.dir * 2 + b.act - (a.dir * 2 + a.act)); + const top = pool.slice(0, 12); + const siteMap = new Map( + sites.map((s) => [s.key, s] as [string, ApiSite]) + ); + const enriched = await Promise.all( + top.map(async (c) => { + const site = siteMap.get(c.r.source); + if (!site) return { ...c, detail: null as SearchResult | null }; + try { + const d = await getDetailFromApi(site, c.r.id); + return { ...c, detail: d || null }; + } catch { + return { ...c, detail: null }; + } + }) + ); + + // 4) 打分:主演/导演/地区/语言/类型 越多重合分越高 + const selfActs = splitNames(actor, 12); + const selfDirs = splitNames(director, 6); + const selfArea = splitNames(area, 4); + const selfLang = splitNames(lang, 4); + const selfGenre = splitNames(genre, 8); + const isTv = isTvRaw === '1' || isTvRaw === '0' ? isTvRaw === '1' : null; + + const items: RelatedItem[] = []; + const seenTitles = new Set(); + + for (const c of enriched) { + const meta = c.detail || c.r; + const candActs = splitNames(meta.actor || c.r.actor || '', 12); + const candDirs = splitNames(meta.director || c.r.director || '', 8); + const candArea = splitNames(meta.area || '', 4); + const candLang = splitNames(meta.lang || '', 4); + const candGenre = splitNames(meta.class || c.r.class || '', 8); + + const sharedActor = overlap(selfActs, candActs); + const sharedDir = overlap(selfDirs, candDirs); + const areaHit = overlap(selfArea, candArea); + const langHit = overlap(selfLang, candLang); + const genreHit = overlap(selfGenre, candGenre); + + const hasMeta = + candActs.length + candDirs.length + candArea.length + candLang.length > 0; + const kindHit = + isTv === null + ? 0 + : (isTv && c.r.episodes.length > 1) || + (!isTv && c.r.episodes.length <= 1) + ? 1 + : 0; + + const score = + sharedDir.length * 5 + + Math.min(sharedActor.length, 3) * 3 + + Math.min(areaHit.length, 2) * 2 + + Math.min(langHit.length, 2) * 2 + + Math.min(genreHit.length, 3) + + Math.min(c.dir, 2) * 2 + + Math.min(c.act, 3) + + (isTv === null ? 0 : kindHit * 2); + + // 证据:有任一元数据重合,或该候选本来就是按导演/演员名搜出来的 + const evidence = hasMeta + ? sharedDir.length > 0 || + sharedActor.length > 0 || + areaHit.length > 0 || + langHit.length > 0 || + genreHit.length > 0 || + c.dir > 0 + : c.dir > 0 || c.act > 0; + if (!evidence || score < 3) continue; + + const reasons: string[] = []; + if (sharedDir.length) reasons.push(`导演:${sharedDir[0]}`); + sharedActor.slice(0, 2).forEach((a) => reasons.push(`主演:${a}`)); + if (areaHit.length) reasons.push(`地区:${areaHit[0]}`); + if (langHit.length) reasons.push(`语言:${langHit[0]}`); + if (genreHit.length) reasons.push(`类型:${genreHit.slice(0, 2).join('/')}`); + + const nt = normTitle(c.r.title); + if (seenTitles.has(nt)) continue; // 同名去重(跨源只留分数最高的一条) + seenTitles.add(nt); + + items.push({ + source: c.r.source, + source_name: c.r.source_name || '', + id: c.r.id, + title: c.r.title, + poster: c.r.poster || '', + year: c.r.year || '', + score, + reasons: reasons.slice(0, 4), + }); + } + + items.sort((a, b) => b.score - a.score); + const finalItems = items.slice(0, 10); + + if (cache.size > 100) cache.clear(); + cache.set(cacheKey, { ts: Date.now(), items: finalItems }); + + return respond(finalItems); + } catch { + return respond([]); + } +} diff --git a/src/app/play/page.tsx b/src/app/play/page.tsx index df441e9..1ec9df0 100644 --- a/src/app/play/page.tsx +++ b/src/app/play/page.tsx @@ -580,7 +580,27 @@ function PlayPageClient() { : '🔍 正在搜索播放源...' ); - let sourcesInfo = await fetchSourcesData(searchTitle || videoTitle); + // 直达模式:带 source+id 且无搜索词、无优选要求 → 直接取该条详情开播, + // 不做标题搜索(按标题找片容易对错片);同名源随后台补搜,供「换源」面板使用 + const directMode = + !!currentSource && !!currentId && !searchTitle && !needPrefer; + let directSucceeded = false; + let sourcesInfo: SearchResult[] = []; + if (directMode) { + const direct = await fetchSourceDetail( + currentSource as string, + currentId as string + ); + if (direct.length) { + sourcesInfo = direct; + directSucceeded = true; + } else { + // 该 source+id 已失效 → 回退标题搜索 + sourcesInfo = await fetchSourcesData(searchTitle || videoTitle); + } + } else { + sourcesInfo = await fetchSourcesData(searchTitle || videoTitle); + } if ( currentSource && currentId && @@ -644,6 +664,26 @@ function PlayPageClient() { newUrl.searchParams.delete('prefer'); window.history.replaceState({}, '', newUrl.toString()); + // 直达模式:后台补搜同名源填充「换源」面板(不阻塞开播,不做标题匹配) + if (directSucceeded && videoTitleRef.current) { + const directItem = sourcesInfo[0]; + fetchSourcesData(videoTitleRef.current) + .then((rest) => { + setAvailableSources((prev) => { + const list = prev.length ? prev : rest; + const seen = new Set(list.map((x) => `${x.source}:${x.id}`)); + const extras = rest.filter((x) => !seen.has(`${x.source}:${x.id}`)); + const hasDirect = list.some( + (x) => x.source === directItem.source && x.id === directItem.id + ); + return hasDirect + ? [...list, ...extras] + : [directItem, ...list, ...extras]; + }); + }) + .catch(() => {}); + } + setLoadingStage('ready'); setLoadingMessage('✨ 准备就绪,即将开始播放...'); @@ -1747,7 +1787,11 @@ function PlayPageClient() { doubanId={detail.douban_id} area={detail.area} lang={detail.lang} + genre={detail.class} + isTv={(detail.episodes?.length || 0) > 1} desc={detail.desc} + selfSource={currentSource} + selfId={currentId} /> )} diff --git a/src/components/VideoMetaExtra.tsx b/src/components/VideoMetaExtra.tsx index 2ab50ac..5145f4a 100644 --- a/src/components/VideoMetaExtra.tsx +++ b/src/components/VideoMetaExtra.tsx @@ -24,8 +24,11 @@ export default function VideoMetaExtra({ doubanId, area, lang, + genre, isTv, desc, + selfSource, + selfId, }: { title: string; actor?: string; @@ -36,13 +39,18 @@ export default function VideoMetaExtra({ doubanId?: number; area?: string; lang?: string; + genre?: string; isTv?: boolean; desc?: string; + /** 当前条目所属源与 id,用于相关推荐排除自己 */ + selfSource?: string; + selfId?: string; }) { const [comments, setComments] = useState([]); const [loading, setLoading] = useState(false); const [dbDetail, setDbDetail] = useState(null); const [related, setRelated] = useState([]); + const [relatedLoading, setRelatedLoading] = useState(false); useEffect(() => { if (!doubanId) return; @@ -64,18 +72,47 @@ export default function VideoMetaExtra({ if (alive && d?.code === 1) setDbDetail(d); }) .catch(() => {}); - // 相关推荐 - fetch(`/api/douban-related?id=${encodeURIComponent(String(doubanId))}&type=${isTv ? 'tv' : 'movie'}`) - .then((r) => r.json()) - .then((d) => { - if (alive && d?.code === 1) setRelated(d.list || []); - }) - .catch(() => {}); return () => { alive = false; }; }, [doubanId]); + // 相关推荐:本站片源,按 主演/导演/语言/地区/类型 匹配(不走豆瓣推荐接口) + useEffect(() => { + if (!title || (!actor && !director)) { + setRelated([]); + return; + } + let alive = true; + setRelatedLoading(true); + const params = new URLSearchParams({ + title, + actor: actor || '', + director: director || '', + area: area || '', + lang: lang || '', + genre: genre || '', + doubanId: String(doubanId || ''), + selfSource: selfSource || '', + selfId: selfId || '', + }); + if (isTv !== undefined) params.set('isTv', isTv ? '1' : '0'); + fetch(`/api/related?${params.toString()}`) + .then((r) => r.json()) + .then((d) => { + if (alive) setRelated(Array.isArray(d?.items) ? d.items : []); + }) + .catch(() => { + if (alive) setRelated([]); + }) + .finally(() => { + if (alive) setRelatedLoading(false); + }); + return () => { + alive = false; + }; + }, [title, actor, director, area, lang, genre, isTv, doubanId, selfSource, selfId]); + const actors = (actor || (dbDetail?.actors || []).join(',')) .split(/[,,、\/|]/) .map((s: string) => s.trim()) @@ -208,35 +245,60 @@ export default function VideoMetaExtra({ ))} - {related.length > 0 && ( + {/* 相关推荐:本站片源按元数据匹配,点击直达该条片源 */} + {(related.length > 0 || relatedLoading) && (
-
+
相关推荐 - 豆瓣相似影片推荐 · 取前10 -
-
- {related.map((r: any) => ( - - {r.poster ? ( - {r.title} - ) : null} -
{r.title}
- {r.rating > 0 && ( -
{r.rating.toFixed(1)}
- )} -
- ))} + + 按主演 / 导演 / 语言 / 地区 / 类型匹配 · 本站片源直达 +
+ {relatedLoading && related.length === 0 && ( + )}
diff --git a/src/middleware.ts b/src/middleware.ts index d20d556..20214fd 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -174,6 +174,7 @@ function shouldSkipAuth(pathname: string): boolean { '/api/douban-comments', '/api/douban-detail', '/api/douban-related', + '/api/related', ]; return skipPaths.some((path) => pathname.startsWith(path)); @@ -182,6 +183,6 @@ function shouldSkipAuth(pathname: string): boolean { // 配置middleware匹配规则 export const config = { matcher: [ - '/((?!_next/static|_next/image|favicon.ico|login|warning|hls.min.js|mpegts.min.js|api/login|api/register|api/logout|api/cron|api/server-config|api/search|api/detail|api/image-proxy|api/license-config|api/douban-comments|api/douban-detail|api/douban-related).*)', + '/((?!_next/static|_next/image|favicon.ico|login|warning|hls.min.js|mpegts.min.js|api/login|api/register|api/logout|api/cron|api/server-config|api/search|api/detail|api/image-proxy|api/license-config|api/douban-comments|api/douban-detail|api/douban-related|api/related).*)', ], };