一分钟搭建影视站,支持Docker等部署方式
feat(player): 支持片头片尾标记与自动跳过
hein.hpq207c8f0993c4
diff --git a/README.md b/README.mdindex 99572f3..b1a5895 100644--- a/README.md+++ b/README.md@@ -17,7 +17,7 @@ LibreTV Next.js 迁移版:免费在线视频聚合搜索与观看平台。基- **聚合搜索**:多采集站服务端并行搜索- **跨源同名聚合**:同名影片合并为一张卡片,展开即可比较和选择各来源-- **HLS 播放**:ArtPlayer + hls.js,广告分片过滤、自动连播、倍速、快捷键、移动端长按 3 倍速+- **HLS 播放**:ArtPlayer + hls.js,广告分片过滤、片头片尾标记与自动跳过、自动连播、倍速、快捷键、移动端长按 3 倍速- **直播 / IPTV**:M3U 订阅解析,`/live` 页面按分组浏览、搜索频道并站内播放(HLS + HTTP-FLV),支持 XMLTV 节目单(EPG)与频道收藏;直播流经专用长连接代理(`/api/live/stream`)转发- **进度同步**:播放进度与观看历史存于本机 IndexedDB,精确到秒的续播- **换源测速**:跨源搜索同名资源并测速排序,一键切换保留集数位置@@ -107,7 +107,7 @@ PASSWORD=your-password npm start # 监听 80801. **添加点播源**:设置 → 源管理 → 点播源 → 添加 API,填入 Apple CMS 采集站地址(如 `https://example.com/api.php/provide/vod`),可选填详情页地址(部分源需要爬详情页提取播放地址)。2. **搜索**:勾选点播源后输入片名;搜索通过服务端聚合,个别源失败不影响整体结果。-3. **播放**:详情弹窗选择剧集进入 `/watch`;支持快捷键(空格/←→/↑↓/F/Alt+←→)、移动端长按 3 倍速、自动连播、换源测速。观看/暂停时后续分片自动缓存到本地(设置可关),播放页可「下载本集」(TS/MP4)离线观看。+3. **播放**:详情弹窗选择剧集进入 `/watch`;支持快捷键(空格/←→/↑↓/F/Alt+←→)、移动端长按 3 倍速、自动连播、换源测速。观看/暂停时后续分片自动缓存到本地(设置可关),播放页可「下载本集」(TS/MP4)离线观看。播放页「片头片尾」可记录片头结束/片尾开始,之后同剧各集与同名资源自动跳过(设置可分别关闭自动跳,仍保留手动按钮)。4. **进度与历史**:自动保存在本设备 IndexedDB,仅定位信息入库,播放时自动同步最新剧集。5. **配置迁移**:设置 → 数据 → 配置导入导出(兼容旧版 LibreTV-Settings JSON 的历史记录迁移)。diff --git a/src/app/watch/page.tsx b/src/app/watch/page.tsxindex 46190fe..a5e0c9e 100644--- a/src/app/watch/page.tsx+++ b/src/app/watch/page.tsx@@ -17,6 +17,9 @@ const PlayerShell = dynamic(() => import('@/components/player-shell').then((m) =});import { EmptyState, LoadingState, Spinner } from '@/components/states';import { SwitchSourceModal } from '@/components/switch-source';+import { SkipMarkPanel } from '@/components/skip-mark-panel';+import { skipMarkKey } from '@/lib/skip-marks';+import type { PlayerSkipApi } from '@/components/player-shell';import { enqueueDownload } from '@/components/download-manager';import { Icon } from '@/components/icon';import { useAuth } from '@/components/auth';@@ -59,6 +62,9 @@ function WatchContent() {const [reversed, setReversed] = useState(false);const [switchOpen, setSwitchOpen] = useState(false);+ const [skipPanelOpen, setSkipPanelOpen] = useState(false);+ // 播放器对外暴露的精确时间读取接口(「记录当前」用),随播放器卸载置空+ const playerApiRef = useRef<PlayerSkipApi | null>(null);const source = resolveSource(store, sourceKey, {url: searchParams.get('sourceUrl') || undefined,@@ -90,6 +96,15 @@ function WatchContent() {return indexParam;}, [episodes, indexParam]);+ // 片头片尾标记按剧名记忆:换集不变,换源到同名资源也能命中。+ // 标题缺失(直连链接)时退回 source:vodId,至少保证本源本片可用。+ const skipMarkFallback = `${sourceKey}:${vodId || currentUrl}`;+ const markKey = useMemo(+ () => skipMarkKey(videoTitle, skipMarkFallback),+ [videoTitle, skipMarkFallback]+ );+ const skipMark = store.skipMarks[markKey];+const goEpisode = useCallback((index: number) => {const sp = new URLSearchParams(searchParams.toString());@@ -242,6 +257,10 @@ function WatchContent() {title={videoTitle}adFilter={store.adFilter}autoplayNext={store.autoplayNext}+ skipMark={skipMark}+ autoSkipIntro={store.autoSkipIntro}+ autoSkipOutro={store.autoSkipOutro}+ onPlayerApi={(api) => { playerApiRef.current = api; }}episodeKey={`${sourceKey}:${vodId}:${currentIndex}`}nextUrl={currentIndex + 1 < episodes.length ? episodes[currentIndex + 1] : undefined}nextEpisodeKey={currentIndex + 1 < episodes.length ? `${sourceKey}:${vodId}:${currentIndex + 1}` : undefined}@@ -290,6 +309,13 @@ function WatchContent() {>下一集</button>+ <button+ className="btn-ghost btn-sm"+ aria-expanded={skipPanelOpen}+ onClick={() => setSkipPanelOpen((v) => !v)}+ >+ 片头片尾+ </button><label className="flex items-center gap-1.5 text-xs text-muted ml-auto cursor-pointer"><inputtype="checkbox"@@ -300,6 +326,17 @@ function WatchContent() {自动连播</label></div>++ {skipPanelOpen && (+ <SkipMarkPanel+ markKey={markKey}+ getPlayerClock={() => {+ const api = playerApiRef.current;+ if (!api) return null;+ return { currentTime: api.getCurrentTime(), duration: api.getDuration() };+ }}+ />+ )}</div>{/* 剧集侧栏 */}diff --git a/src/components/player-shell.tsx b/src/components/player-shell.tsxindex da23834..af6e531 100644--- a/src/components/player-shell.tsx+++ b/src/components/player-shell.tsx@@ -13,6 +13,12 @@ import {import { loadCacheSettings } from '@/lib/video-cache';import { formatTime } from '@/lib/utils';import { prefersTouchPointer } from '@/lib/touch-pointer';+import {+ hasCrossedOutro,+ isIntroActive,+ resolveSkipWindow,+ type SkipMark,+} from '@/lib/skip-marks';import {ART_DEFAULT_CONTROL_HIDE_MS,DESKTOP_CONTROL_HIDE_MS,@@ -29,11 +35,25 @@ import {* 重建 <video> 元素,触发「黑屏有声」的渲染竞态。*/+/** 暴露给播放页的读取接口:「记录当前」需要比 5s 节流进度回调更精确的位置 */+export interface PlayerSkipApi {+ getCurrentTime(): number;+ getDuration(): number;+}+interface PlayerShellProps {url: string;title: string;adFilter: boolean;autoplayNext: boolean;+ /** 当前剧的片头片尾标记(父级按归一化剧名查好后传入,换集/换源不变) */+ skipMark?: SkipMark;+ /** 命中片头标记时自动跳到片头结束 */+ autoSkipIntro: boolean;+ /** 连续播放越过片尾标记时自动结束本集 */+ autoSkipOutro: boolean;+ /** 播放器创建/销毁时回调,供播放页读取精确播放位置 */+ onPlayerApi?: (api: PlayerSkipApi | null) => void;/** 剧集标识 `${source}:${vodId}:${episodeIndex}`(片段缓存按集淘汰的分组键) */episodeKey?: string;/** 下一集 m3u8 地址:当前集预取完成后预热下一集前 7 分钟 */@@ -64,6 +84,10 @@ export function PlayerShell({title,adFilter,autoplayNext,+ skipMark,+ autoSkipIntro,+ autoSkipOutro,+ onPlayerApi,episodeKey,nextUrl,nextEpisodeKey,@@ -90,12 +114,14 @@ export function PlayerShell({// 始终持有最新 props/回调,避免重建播放器const propsRef = useRef({- url, title, adFilter, autoplayNext, episodeKey, nextUrl, nextEpisodeKey,+ url, title, adFilter, autoplayNext, skipMark, autoSkipIntro, autoSkipOutro, onPlayerApi,+ episodeKey, nextUrl, nextEpisodeKey,getRestorePosition, onTimeUpdate, onEnded, onPause, onQuality, onRequestSwitchSource,onPrevEpisode, onNextEpisode, hasPrevEpisode, hasNextEpisode,});propsRef.current = {- url, title, adFilter, autoplayNext, episodeKey, nextUrl, nextEpisodeKey,+ url, title, adFilter, autoplayNext, skipMark, autoSkipIntro, autoSkipOutro, onPlayerApi,+ episodeKey, nextUrl, nextEpisodeKey,getRestorePosition, onTimeUpdate, onEnded, onPause, onQuality, onRequestSwitchSource,onPrevEpisode, onNextEpisode, hasPrevEpisode, hasNextEpisode,};@@ -124,6 +150,14 @@ export function PlayerShell({const recoveryRef = useRef<PlaybackRecovery | null>(null);// 自然播完标记,卸载时不回写进度(避免覆盖「已看完」记录)const endedRef = useRef(false);+ // 片头/片尾:每集各只处理一次,换集时重置(见 loadEpisode)+ const introHandledRef = useRef(false);+ const outroHandledRef = useRef(false);+ // 上一次 timeupdate 的位置:用于区分「连续播放越过片尾」与「拖动进度条」+ const lastSampleRef = useRef(0);+ // 跳过按钮提示;用 ref 比较,避免 timeupdate 每 250ms 触发重渲染+ const [skipPrompt, setSkipPrompt] = useState<'intro' | 'outro' | null>(null);+ const skipPromptRef = useRef<'intro' | 'outro' | null>(null);const showHint = (text: string) => {setHint(text);@@ -179,6 +213,44 @@ export function PlayerShell({});};+ /** 切换提示状态;相同值直接返回,避免 timeupdate 高频 setState */+ const updateSkipPrompt = (next: 'intro' | 'outro' | null) => {+ if (skipPromptRef.current === next) return;+ skipPromptRef.current = next;+ setSkipPrompt(next);+ };++ /** 跳到片头结束并续跑预取;同步 lastSampleRef,避免下一拍被误判为「连续越过片尾」 */+ const skipTo = (seconds: number) => {+ const art = artRef.current;+ if (!art || !Number.isFinite(seconds) || seconds < 0) return;+ try {+ art.currentTime = seconds;+ } catch {+ /* 媒体尚未就绪时忽略,下一次 timeupdate 会再次判定 */+ }+ lastSampleRef.current = seconds;+ ensurePrefetch(currentMediaUrlRef.current, seconds);+ };++ /**+ * 跳过片尾:与自然播完共用 onEnded 链路(清进度 + 依 autoplayNext 连播下一集)。+ * endedRef 置 true 同时阻止 video:ended 重复回调,也避免卸载时把片尾进度回写。+ */+ const finishBySkip = () => {+ const art = artRef.current;+ outroHandledRef.current = true;+ endedRef.current = true;+ updateSkipPrompt(null);+ try {+ art?.pause();+ } catch {+ /* 忽略 */+ }+ showHint('已跳过片尾');+ propsRef.current.onEnded?.();+ };+/*** 初始化/切换 HLS。allowProxyFallback:直连致命网络错误(CORS/防盗链/分片被拒)时,* 自动改走同源 cookie 鉴权的 /api/proxy 重试一次。@@ -310,6 +382,12 @@ export function PlayerShell({videoErrorRetryUsedRef.current = false;restoredRef.current = false;lastPrefetchEnsureRef.current = 0;+ // 片头/片尾按集重置:上一集已处理过不意味新一集也处理过+ introHandledRef.current = false;+ outroHandledRef.current = false;+ lastSampleRef.current = 0;+ endedRef.current = false;+ updateSkipPrompt(null);recoveryRef.current = new PlaybackRecovery();// 换集时清掉上一集的预取窗口,避免带宽被旧集占用getVideoPrefetcher().stop();@@ -337,6 +415,9 @@ export function PlayerShell({restoredRef.current = false;recoveryRef.current = new PlaybackRecovery();endedRef.current = false;+ introHandledRef.current = false;+ outroHandledRef.current = false;+ lastSampleRef.current = 0;let lastSave = 0;@@ -394,6 +475,18 @@ export function PlayerShell({});artRef.current = art;+ // 播放页「记录当前」需要精确时间:不能依赖 5s 节流的 onTimeUpdate+ propsRef.current.onPlayerApi?.({+ getCurrentTime: () => {+ const current = artRef.current?.currentTime;+ return typeof current === 'number' && Number.isFinite(current) ? current : 0;+ },+ getDuration: () => {+ const duration = artRef.current?.duration;+ return typeof duration === 'number' && Number.isFinite(duration) ? duration : 0;+ },+ });+/*** 读解码后的真实分辨率。* 单码率 m3u8 / mp4 直链的清单里没有画质字段,服务端无论如何探测不到,@@ -451,12 +544,70 @@ export function PlayerShell({// loader 读取的 key 不一致,缓存永不命中且直连 fetch 白耗流量ensurePrefetch(currentMediaUrlRef.current, art.currentTime);}++ // —— 片头 / 片尾跳过 ——+ const p = propsRef.current;+ const current = art.currentTime;+ const duration = art.duration;+ const previous = lastSampleRef.current;+ lastSampleRef.current = current;+ const window = resolveSkipWindow(p.skipMark, duration);++ // 片头:一旦自然越过或已自动跳转,本集不再处理;用户之后拖回片头也不会被反复拉扯。+ // 必须等进度恢复完成(restoredRef)且已真正开始播放,否则会先跳到片头结束、+ // 再被 restoreAndStart 拉回断点处。+ if (window.introEnd !== undefined && !introHandledRef.current) {+ if (current >= window.introEnd) {+ introHandledRef.current = true;+ } else if (+ p.autoSkipIntro &&+ restoredRef.current &&+ playbackStartedRef.current &&+ isIntroActive(current, window)+ ) {+ introHandledRef.current = true;+ skipTo(window.introEnd);+ showHint('已跳过片头');+ }+ }++ // 片尾:只认连续播放越过边界;拖动进度条、刚写入标记、进度恢复造成的大跳变+ // 都不自动结束,只显示按钮由用户决定。+ if (window.outroStart !== undefined && !outroHandledRef.current) {+ if (current >= duration - 0.5) {+ outroHandledRef.current = true;+ } else if (+ p.autoSkipOutro &&+ playbackStartedRef.current &&+ hasCrossedOutro(previous, current, window)+ ) {+ finishBySkip();+ return;+ }+ }++ const introActive =+ window.introEnd !== undefined && !introHandledRef.current && isIntroActive(current, window);+ const outroActive =+ window.outroStart !== undefined && !outroHandledRef.current && current >= window.outroStart;+ updateSkipPrompt(introActive ? 'intro' : outroActive ? 'outro' : null);});art.on('video:seeked', () => {ensurePrefetch(currentMediaUrlRef.current, art.currentTime);+ // seek 是用户主动行为:拉平采样基准,避免下一拍被误判为「连续越过片尾」。+ // 暂停中 seek 不会触发 timeupdate,这里也同步刷新按钮的显隐。+ const current = art.currentTime;+ lastSampleRef.current = current;+ const window = resolveSkipWindow(propsRef.current.skipMark, art.duration);+ const introActive =+ window.introEnd !== undefined && !introHandledRef.current && isIntroActive(current, window);+ const outroActive =+ window.outroStart !== undefined && !outroHandledRef.current && current >= window.outroStart;+ updateSkipPrompt(introActive ? 'intro' : outroActive ? 'outro' : null);});art.on('video:pause', () => {- propsRef.current.onPause?.(art.currentTime, art.duration);+ // 跳过片尾会主动 pause:此时已按「看完」处理,不能再把片尾位置写回进度+ if (!endedRef.current) propsRef.current.onPause?.(art.currentTime, art.duration);// 暂停 = 预取黄金窗口:解除限速并无限铺满整集(用户主动行为,带宽占用可接受)// waiting 触发的限速在此解除,否则黄金窗口会被 500ms 轮询冻结getVideoPrefetcher().setThrottled(false);@@ -470,7 +621,10 @@ export function PlayerShell({getVideoPrefetcher().setThrottled(false);});art.on('video:ended', () => {+ // finishBySkip 已经手动走过结束链路:这里不能重复触发 onEnded+ if (endedRef.current) return;endedRef.current = true;+ updateSkipPrompt(null);propsRef.current.onEnded?.();});@@ -573,7 +727,7 @@ export function PlayerShell({// 卸载与页面隐藏时保存进度const saveOnHide = () => {- if (document.visibilityState === 'hidden') {+ if (document.visibilityState === 'hidden' && !endedRef.current) {propsRef.current.onPause?.(art.currentTime, art.duration);}};@@ -606,6 +760,8 @@ export function PlayerShell({hlsRef.current = null;recoveryRef.current?.dispose();getVideoPrefetcher().stop();+ // 播放页可能仍持有读取接口:销毁前显式置空,避免「记录当前」读到已销毁实例+ propsRef.current.onPlayerApi?.(null);art.destroy();artRef.current = null;};@@ -627,6 +783,23 @@ export function PlayerShell({});}, [hasPrevEpisode, hasNextEpisode, url]);+ // —— 标记变化:重置片尾采样基准并立即刷新提示 ——+ // 刚记录「片尾开始」时当前时间恰好等于新边界,若沿用上一拍采样会被判成+ // 「连续越过」而当场结束本集;把基准拉平后本集只保留手动按钮,下一集才自动跳。+ // 顺带覆盖暂停中修改标记的场景(没有 timeupdate 也要让按钮即时出现/消失)。+ useEffect(() => {+ const art = artRef.current;+ if (!art) return;+ const current = art.currentTime;+ lastSampleRef.current = Number.isFinite(current) ? current : 0;+ const window = resolveSkipWindow(skipMark, art.duration);+ const introActive =+ window.introEnd !== undefined && !introHandledRef.current && isIntroActive(current, window);+ const outroActive =+ window.outroStart !== undefined && !outroHandledRef.current && current >= window.outroStart;+ updateSkipPrompt(introActive ? 'intro' : outroActive ? 'outro' : null);+ }, [skipMark]);+// —— 换集:仅切换 HLS 源,不重建播放器(保留网页全屏等状态) ——const firstUrlRef = useRef(true);useEffect(() => {@@ -661,6 +834,30 @@ export function PlayerShell({}}/>)}+ {!error && skipPrompt && (+ <button+ type="button"+ className="absolute bottom-16 left-1/2 -translate-x-1/2 z-10 rounded-full bg-black/70 px-4 py-2 text-sm text-white transition-colors hover:bg-black/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"+ onClick={() => {+ if (skipPrompt === 'intro') {+ // 用当前这集的有效窗口取目标位置:持久化标记可能已越界/损坏+ const window = resolveSkipWindow(propsRef.current.skipMark, artRef.current?.duration ?? 0);+ if (window.introEnd === undefined) {+ updateSkipPrompt(null);+ return;+ }+ introHandledRef.current = true;+ skipTo(window.introEnd);+ updateSkipPrompt(null);+ showHint('已跳过片头');+ return;+ }+ finishBySkip();+ }}+ >+ {skipPrompt === 'intro' ? '跳过片头' : '跳过片尾'}+ </button>+ )}{error && (<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-black/80"><p className="text-danger text-sm">{error}</p>diff --git a/src/components/skip-mark-panel.tsx b/src/components/skip-mark-panel.tsxnew file mode 100644index 0000000..484c9e5--- /dev/null+++ b/src/components/skip-mark-panel.tsx@@ -0,0 +1,106 @@+'use client';++import { useAppStore } from '@/lib/store';+import { validateIntroEnd, validateOutroStart } from '@/lib/skip-marks';+import { formatTime } from '@/lib/utils';+import { useToast } from './toast';++/**+ * 播放页的片头/片尾标记面板。+ *+ * 采集站不提供片头片尾元数据,边界只能由用户在看的时候标记一次,+ * 之后同剧各集与同名资源自动套用。面板只负责「记录当前 / 清除」两个动作,+ * 真正的跳过判定在 player-shell.tsx,存储与校验在 lib/skip-marks.ts。+ */++interface PlayerClock {+ currentTime: number;+ duration: number;+}++type MotionField = 'introEnd' | 'outroStart';++const ROWS: { field: MotionField; label: string; hint: string }[] = [+ { field: 'introEnd', label: '片头结束', hint: '正片开始的位置' },+ { field: 'outroStart', label: '片尾开始', hint: '片尾曲开始的位置' },+];++export function SkipMarkPanel({+ markKey,+ getPlayerClock,+}: {+ /** 已归一化的标记键(watch 页按剧名计算) */+ markKey: string;+ /** 读取播放器当前时间;播放器未就绪时返回 null */+ getPlayerClock: () => PlayerClock | null;+}) {+ const mark = useAppStore((s) => s.skipMarks[markKey]);+ const setSkipMark = useAppStore((s) => s.setSkipMark);+ const { toast } = useToast();++ const record = (field: MotionField) => {+ const clock = getPlayerClock();+ if (!clock || clock.currentTime <= 0) {+ toast('播放器尚未就绪,请稍后再试', 'warning');+ return;+ }+ // 保留 0.1s:显示按秒取整,但跳转位置不因取整而漂移+ const value = Math.round(clock.currentTime * 10) / 10;+ const error =+ field === 'introEnd'+ ? validateIntroEnd(value, clock.duration, mark)+ : validateOutroStart(value, clock.duration, mark);+ if (error) {+ toast(error, 'error');+ return;+ }+ setSkipMark(markKey, { [field]: value });+ toast(+ `已将${field === 'introEnd' ? '片头结束' : '片尾开始'}设为 ${formatTime(value)}`,+ 'success'+ );+ };++ const clear = (field: MotionField) => {+ setSkipMark(markKey, { [field]: null });+ toast(`已清除${field === 'introEnd' ? '片头' : '片尾'}标记`, 'info');+ };++ return (+ <div className="mt-3 rounded-lg border border-line bg-surface-raised p-3">+ <div className="space-y-2">+ {ROWS.map(({ field, label, hint }) => {+ const value = mark?.[field];+ return (+ <div key={field} className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex items-baseline gap-2 min-w-0">+ <span className="text-sm text-content">{label}</span>+ <span className="text-xs text-faint">{hint}</span>+ <span className="text-xs font-mono text-muted">+ {value !== undefined ? formatTime(value) : '未设置'}+ </span>+ </div>+ <div className="flex items-center gap-1.5">+ <button type="button" className="btn-ghost btn-sm" onClick={() => record(field)}>+ 记录当前+ </button>+ <button+ type="button"+ className="btn-ghost btn-sm"+ disabled={value === undefined}+ onClick={() => clear(field)}+ >+ 清除+ </button>+ </div>+ </div>+ );+ })}+ </div>+ <p className="mt-2.5 text-[11px] text-faint leading-relaxed">+ 标记按剧名记忆,对本剧所有剧集与同名资源生效;命中时播放器底部显示「跳过片头/片尾」按钮,+ 自动跳过可在「设置 → 播放与过滤」中关闭。+ </p>+ </div>+ );+}diff --git a/src/components/source-manager.tsx b/src/components/source-manager.tsxindex f9aeabd..f6a886e 100644--- a/src/components/source-manager.tsx+++ b/src/components/source-manager.tsx@@ -558,6 +558,9 @@ function VodSourceRow({function PlaybackPanel() {const store = useAppStore();+ const { toast } = useToast();+ const [clearMarksOpen, setClearMarksOpen] = useState(false);+ const markCount = Object.keys(store.skipMarks).length;return (<section><SectionTitle title="播放与过滤" />@@ -574,7 +577,46 @@ function PlaybackPanel() {checked={store.autoplayNext}onChange={(v) => store.updateSettings({ autoplayNext: v })}/>+ <ToggleRow+ label="自动跳过片头"+ description="命中片头标记时自动跳到片头结束位置;关闭后仍显示「跳过片头」按钮(标记在播放页「片头片尾」中设置)"+ checked={store.autoSkipIntro}+ onChange={(v) => store.updateSettings({ autoSkipIntro: v })}+ />+ <ToggleRow+ label="自动跳过片尾"+ description="到达片尾标记时自动结束本集(开启自动连播则继续下一集);关闭后仍显示「跳过片尾」按钮"+ checked={store.autoSkipOutro}+ onChange={(v) => store.updateSettings({ autoSkipOutro: v })}+ /></div>++ {markCount > 0 && (+ <div className="flex items-center justify-between gap-3 pt-3 mt-3 border-t border-line">+ <div className="min-w-0">+ <div className="text-sm text-content">片头片尾标记</div>+ <div className="text-xs text-faint">已记录 {markCount} 部;在播放页「片头片尾」中设置</div>+ </div>+ <button className="btn-ghost btn-sm shrink-0" onClick={() => setClearMarksOpen(true)}>+ 清除全部+ </button>+ </div>+ )}++ <ConfirmDialog+ open={clearMarksOpen}+ danger+ title="清除全部片头片尾标记?"+ message={`将删除已记录的 ${markCount} 部剧的片头片尾标记,之后播放不再自动跳过;可重新在播放页标记。`}+ confirmLabel="清除全部"+ onCancel={() => setClearMarksOpen(false)}+ onConfirm={() => {+ store.clearAllSkipMarks();+ setClearMarksOpen(false);+ toast('已清除全部片头片尾标记', 'success');+ }}+ />+<VideoCachePanel /></section>);diff --git a/src/lib/skip-marks.test.ts b/src/lib/skip-marks.test.tsnew file mode 100644index 0000000..a8e1f4b--- /dev/null+++ b/src/lib/skip-marks.test.ts@@ -0,0 +1,153 @@+import { describe, expect, it } from 'vitest';+import {+ MAX_CONTINUOUS_STEP_SECONDS,+ MIN_MARK_GAP_SECONDS,+ hasCrossedOutro,+ isIntroActive,+ resolveSkipWindow,+ skipMarkKey,+ validateIntroEnd,+ validateOutroStart,+ type SkipMark,+} from './skip-marks';++const mark = (introEnd?: number, outroStart?: number): SkipMark => ({+ introEnd,+ outroStart,+ updatedAt: 0,+});++describe('skipMarkKey', () => {+ it('空白、标点、大小写归一后指向同一个标记', () => {+ expect(skipMarkKey('摔跤吧!爸爸', 'a:1')).toBe(skipMarkKey(' 摔跤吧!爸爸 ', 'b:2'));+ expect(skipMarkKey('Hello, World!', 'a:1')).toBe(skipMarkKey('hello world', 'b:2'));+ });++ it('同剧换源共享标记:标题相同、兜底键不同也得到同一个键', () => {+ expect(skipMarkKey('庆余年', 'custom_0:123')).toBe(skipMarkKey('庆余年', 'sub_ab_1:456'));+ });++ it('标题缺失或为占位文案时退回 source:vod 兜底键', () => {+ expect(skipMarkKey(undefined, 'custom_0:123')).toBe('f:custom_0:123');+ expect(skipMarkKey('', 'custom_0:123')).toBe('f:custom_0:123');+ expect(skipMarkKey('未知视频', 'custom_0:123')).toBe('f:custom_0:123');+ });++ it('不同的剧不会互相串标记', () => {+ expect(skipMarkKey('庆余年', 'a')).not.toBe(skipMarkKey('庆余年2', 'a'));+ });+});++describe('resolveSkipWindow', () => {+ it('合法标记原样返回', () => {+ expect(resolveSkipWindow(mark(45, 1200), 2400)).toEqual({ introEnd: 45, outroStart: 1200 });+ });++ it('无标记、时长缺失或非有限时返回空窗口', () => {+ expect(resolveSkipWindow(undefined, 2400)).toEqual({});+ expect(resolveSkipWindow(mark(45, 1200), 0)).toEqual({});+ expect(resolveSkipWindow(mark(45, 1200), Number.NaN)).toEqual({});+ expect(resolveSkipWindow(mark(45, 1200), Number.POSITIVE_INFINITY)).toEqual({});+ });++ it('越界/过小的字段被逐项剔除', () => {+ // 片头 >= 总时长 - 2、片尾 >= 总时长 - 2、片头 < 3、片尾 < 5+ expect(resolveSkipWindow(mark(2399), 2400)).toEqual({});+ expect(resolveSkipWindow(mark(undefined, 2399), 2400)).toEqual({});+ expect(resolveSkipWindow(mark(2), 2400)).toEqual({});+ expect(resolveSkipWindow(mark(undefined, 4), 2400)).toEqual({});+ });++ it('片头与片尾间隔不足时保留片头、丢弃片尾', () => {+ expect(resolveSkipWindow(mark(45, 45 + MIN_MARK_GAP_SECONDS - 1), 2400)).toEqual({ introEnd: 45 });+ expect(resolveSkipWindow(mark(45, 45 + MIN_MARK_GAP_SECONDS), 2400)).toEqual({+ introEnd: 45,+ outroStart: 45 + MIN_MARK_GAP_SECONDS,+ });+ });++ it('损坏的持久化数据(负数/NaN)不会抛错', () => {+ expect(resolveSkipWindow(mark(-5, Number.NaN), 2400)).toEqual({});+ });+});++describe('isIntroActive', () => {+ const window = { introEnd: 45 };++ it('片头区间内为真,收尾余量内为假', () => {+ expect(isIntroActive(0, window)).toBe(true);+ expect(isIntroActive(43.5, window)).toBe(true);+ expect(isIntroActive(44.5, window)).toBe(false);+ expect(isIntroActive(45, window)).toBe(false);+ expect(isIntroActive(46, window)).toBe(false);+ });++ it('没有片头标记或位置非法时为假', () => {+ expect(isIntroActive(10, {})).toBe(false);+ expect(isIntroActive(Number.NaN, window)).toBe(false);+ expect(isIntroActive(-1, window)).toBe(false);+ });+});++describe('hasCrossedOutro', () => {+ const window = { outroStart: 1200 };++ it('连续小步前进越过片尾起点才触发', () => {+ expect(hasCrossedOutro(1199.5, 1200.25, window)).toBe(true);+ expect(hasCrossedOutro(1200.2, 1201, window)).toBe(false); // 已经越过+ expect(hasCrossedOutro(1199.5, 1199.9, window)).toBe(false); // 尚未到达+ expect(hasCrossedOutro(1201, 1200.5, window)).toBe(false); // 倒退+ });++ it('大跨度拖动/进度恢复不触发自动跳', () => {+ expect(hasCrossedOutro(0, 1300, window)).toBe(false);+ expect(hasCrossedOutro(1190, 1200 + MAX_CONTINUOUS_STEP_SECONDS, window)).toBe(false);+ expect(+ hasCrossedOutro(1200 - MAX_CONTINUOUS_STEP_SECONDS / 2, 1200 + MAX_CONTINUOUS_STEP_SECONDS / 2, window)+ ).toBe(true);+ });++ it('没有片尾标记或时间非法时为假', () => {+ expect(hasCrossedOutro(1199, 1201, {})).toBe(false);+ expect(hasCrossedOutro(Number.NaN, 1201, window)).toBe(false);+ expect(hasCrossedOutro(1199, Number.NaN, window)).toBe(false);+ });+});++describe('validateIntroEnd', () => {+ it('接受合理值', () => {+ expect(validateIntroEnd(30, 2400)).toBeNull();+ expect(validateIntroEnd(MIN_MARK_GAP_SECONDS, 0, mark(undefined, MIN_MARK_GAP_SECONDS * 2))).toBeNull();+ });++ it('拒绝过早、非法与贴近结尾的值', () => {+ expect(validateIntroEnd(Number.NaN, 2400)).not.toBeNull();+ expect(validateIntroEnd(0, 2400)).not.toBeNull();+ expect(validateIntroEnd(2, 2400)).not.toBeNull();+ expect(validateIntroEnd(2399, 2400)).not.toBeNull();+ });++ it('与已有片尾标记间隔不足时拒绝', () => {+ expect(validateIntroEnd(30, 2400, mark(undefined, 35))).toContain(String(MIN_MARK_GAP_SECONDS));+ expect(validateIntroEnd(25, 2400, mark(undefined, 35))).toBeNull();+ });+});++describe('validateOutroStart', () => {+ it('接受合理值', () => {+ expect(validateOutroStart(1200, 2400)).toBeNull();+ expect(validateOutroStart(MIN_MARK_GAP_SECONDS + 5, 0, mark(5))).toBeNull();+ });++ it('拒绝过早、非法与贴近结尾的值', () => {+ expect(validateOutroStart(Number.NaN, 2400)).not.toBeNull();+ expect(validateOutroStart(0, 2400)).not.toBeNull();+ expect(validateOutroStart(4, 2400)).not.toBeNull();+ expect(validateOutroStart(2399, 2400)).not.toBeNull();+ });++ it('与已有片头标记间隔不足时拒绝', () => {+ expect(validateOutroStart(35, 2400, mark(30))).toContain(String(MIN_MARK_GAP_SECONDS));+ expect(validateOutroStart(40, 2400, mark(30))).toBeNull();+ });+});diff --git a/src/lib/skip-marks.ts b/src/lib/skip-marks.tsnew file mode 100644index 0000000..b4f12ce--- /dev/null+++ b/src/lib/skip-marks.ts@@ -0,0 +1,141 @@+import { normalizeTitle } from './cms-parser';++/**+ * 片头/片尾跳过:标记的归一化、校验与「当前是否命中」判定。+ *+ * 采集站的详情接口不提供片头片尾元数据(vod_play_url 只有分集地址),+ * 因此边界只能由用户手动标记一次、按剧名记住,后续各集与同名资源自动套用。+ * 本模块只做纯计算,播放器接入与 UI 见 player-shell.tsx / skip-mark-panel.tsx。+ */++/** 一条剧的跳过标记;时间单位为秒(播放时间轴,与广告过滤后的时间轴一致) */+export interface SkipMark {+ /** 片头结束位置(正片开始) */+ introEnd?: number;+ /** 片尾开始位置(正片结束、片尾曲开始) */+ outroStart?: number;+ /** 最近一次修改时间(epoch ms),便于后续做清理/展示 */+ updatedAt: number;+}++/** 某集经过时长校验后的有效跳过窗口;非法字段会被剔除 */+export interface SkipWindow {+ introEnd?: number;+ outroStart?: number;+}++/** 片头结束与片尾开始之间至少保留的正片时长:贴太近说明两个标记至少有一个错了 */+export const MIN_MARK_GAP_SECONDS = 10;+/** 片头结束的合法下限:刚起播时误点不会写入无意义标记 */+export const MIN_INTRO_SECONDS = 3;+/** 片尾开始的合法下限 */+export const MIN_OUTRO_SECONDS = 5;+/** 标记至少要比总时长提前的秒数,贴着结尾的标记没有跳过价值 */+export const END_GUARD_SECONDS = 2;+/** 片头提示的收尾余量:距片头结束不足 1s 时不再打扰 */+export const INTRO_PROMPT_GUARD_SECONDS = 1;+/** 两次 timeupdate 之间超过该秒数视为 seek,不使用「连续越过」判定 */+export const MAX_CONTINUOUS_STEP_SECONDS = 10;++/** 播放页在拿不到真实标题时使用的占位文案(与 watch/page.tsx 保持一致) */+const UNKNOWN_TITLE = '未知视频';++function isValidTime(value: unknown): value is number {+ return typeof value === 'number' && Number.isFinite(value) && value > 0;+}++/**+ * 标记的存储键。+ * - 有标题时按归一化标题:同剧各集、换源后的同名资源共享同一份标记;+ * - 标题缺失/占位文案时退回 `${sourceKey}:${vodId}`,至少保证本源本片可用。+ * 前缀区分两类键,避免真实标题恰好长成兜底键的形态而串数据。+ */+export function skipMarkKey(title: string | undefined, fallback: string): string {+ const normalized = normalizeTitle(title ?? '');+ if (!normalized || normalized === normalizeTitle(UNKNOWN_TITLE)) {+ return `f:${fallback}`;+ }+ return `t:${normalized}`;+}++/**+ * 把持久化标记裁剪成当前这集可用的窗口。+ *+ * 必须是「读取侧」校验:标记按剧共享,不同集/不同源的时长可能不同,+ * 旧标记完全可能越界;损坏的持久化数据也不应让播放报错。+ * 片头与片尾冲突(间隔不足)时保留片头、丢弃片尾——片头通常更早也更稳定。+ */+export function resolveSkipWindow(mark: SkipMark | undefined, duration: number): SkipWindow {+ if (!mark || !Number.isFinite(duration) || duration <= 0) return {};++ const introEnd =+ isValidTime(mark.introEnd) &&+ mark.introEnd >= MIN_INTRO_SECONDS &&+ mark.introEnd <= duration - END_GUARD_SECONDS+ ? mark.introEnd+ : undefined;++ let outroStart =+ isValidTime(mark.outroStart) &&+ mark.outroStart >= MIN_OUTRO_SECONDS &&+ mark.outroStart <= duration - END_GUARD_SECONDS+ ? mark.outroStart+ : undefined;++ if (introEnd !== undefined && outroStart !== undefined && outroStart - introEnd < MIN_MARK_GAP_SECONDS) {+ outroStart = undefined;+ }++ return {+ ...(introEnd !== undefined ? { introEnd } : {}),+ ...(outroStart !== undefined ? { outroStart } : {}),+ };+}++/** 当前是否仍处于片头(用于显示「跳过片头」按钮) */+export function isIntroActive(position: number, window: SkipWindow): boolean {+ const { introEnd } = window;+ if (introEnd === undefined || !Number.isFinite(position)) return false;+ return position >= 0 && position < introEnd - INTRO_PROMPT_GUARD_SECONDS;+}++/**+ * 是否在连续播放中越过了片尾起点。+ * 只认小步前进:用户拖动进度条、刚写入标记、以及进度恢复造成的大跳变+ * 都不应触发自动结束;这些场景仍会显示按钮,由用户自己决定。+ */+export function hasCrossedOutro(previous: number, current: number, window: SkipWindow): boolean {+ const { outroStart } = window;+ if (outroStart === undefined) return false;+ if (!Number.isFinite(previous) || !Number.isFinite(current)) return false;+ const step = current - previous;+ return previous < outroStart && current >= outroStart && step > 0 && step <= MAX_CONTINUOUS_STEP_SECONDS;+}++/** 校验「片头结束」;duration 未知(<=0)时只做相对校验。返回错误文案或 null */+export function validateIntroEnd(value: number, duration: number, mark?: SkipMark): string | null {+ if (!isValidTime(value)) return '片头结束时间无效';+ if (value < MIN_INTRO_SECONDS) return '请播放几秒后再记录片头结束';+ if (Number.isFinite(duration) && duration > 0 && value > duration - END_GUARD_SECONDS) {+ return '片头结束不能接近视频末尾';+ }+ const outroStart = mark?.outroStart;+ if (isValidTime(outroStart) && value > outroStart - MIN_MARK_GAP_SECONDS) {+ return `片头结束需早于片尾开始至少 ${MIN_MARK_GAP_SECONDS} 秒`;+ }+ return null;+}++/** 校验「片尾开始」;规则与 validateIntroEnd 对称 */+export function validateOutroStart(value: number, duration: number, mark?: SkipMark): string | null {+ if (!isValidTime(value)) return '片尾开始时间无效';+ if (value < MIN_OUTRO_SECONDS) return '请播放到片尾附近再记录片尾开始';+ if (Number.isFinite(duration) && duration > 0 && value > duration - END_GUARD_SECONDS) {+ return '片尾开始需早于视频结束';+ }+ const introEnd = mark?.introEnd;+ if (isValidTime(introEnd) && value < introEnd + MIN_MARK_GAP_SECONDS) {+ return `片尾开始需晚于片头结束至少 ${MIN_MARK_GAP_SECONDS} 秒`;+ }+ return null;+}diff --git a/src/lib/store.test.ts b/src/lib/store.test.tsindex e2c38d2..5ecd799 100644--- a/src/lib/store.test.ts+++ b/src/lib/store.test.ts@@ -25,6 +25,7 @@ beforeEach(() => {liveFavorites: [],liveRecent: [],yellowFilter: false,+ skipMarks: {},});});@@ -390,3 +391,48 @@ describe('订阅整体开关', () => {expect(isInDisabledSubscription(store(), 'manual_0')).toBe(false);});});++describe('片头片尾标记', () => {+ beforeEach(() => {+ useAppStore.setState({ skipMarks: {} });+ });++ it('写入、合并字段并刷新 updatedAt', () => {+ store().setSkipMark('t:abc', { introEnd: 45 });+ expect(store().skipMarks['t:abc']?.introEnd).toBe(45);+ const firstUpdatedAt = store().skipMarks['t:abc']?.updatedAt ?? 0;+ expect(firstUpdatedAt).toBeGreaterThan(0);++ store().setSkipMark('t:abc', { outroStart: 1200 });+ expect(store().skipMarks['t:abc']).toMatchObject({ introEnd: 45, outroStart: 1200 });+ expect(store().skipMarks['t:abc']?.updatedAt).toBeGreaterThanOrEqual(firstUpdatedAt);+ });++ it('字段传 null 只清该字段,两个字段都清后删除整条', () => {+ store().setSkipMark('t:abc', { introEnd: 45, outroStart: 1200 });++ store().setSkipMark('t:abc', { introEnd: null });+ expect(store().skipMarks['t:abc']?.introEnd).toBeUndefined();+ expect(store().skipMarks['t:abc']?.outroStart).toBe(1200);++ store().setSkipMark('t:abc', { outroStart: null });+ expect(store().skipMarks['t:abc']).toBeUndefined();+ });++ it('对不存在的键写入空 patch 不会创建空壳条目', () => {+ store().setSkipMark('t:missing', { introEnd: null });+ expect(store().skipMarks).toEqual({});+ });++ it('clearSkipMark 只删指定条目,clearAllSkipMarks 清空全部', () => {+ store().setSkipMark('t:a', { introEnd: 20 });+ store().setSkipMark('t:b', { outroStart: 200 });++ store().clearSkipMark('t:a');+ expect(store().skipMarks).not.toHaveProperty('t:a');+ expect(store().skipMarks).toHaveProperty('t:b');++ store().clearAllSkipMarks();+ expect(store().skipMarks).toEqual({});+ });+});diff --git a/src/lib/store.ts b/src/lib/store.tsindex 826e882..5a77c38 100644--- a/src/lib/store.ts+++ b/src/lib/store.ts@@ -3,6 +3,7 @@import { create } from 'zustand';import { createJSONStorage, persist } from 'zustand/middleware';import type { QualityEntry, SourceConfig, LiveSourceConfig, SourceSearchOutcome } from './types';+import type { SkipMark } from './skip-marks';import { isQualityEntryFresh, mergeQualityEntries, qualityKey } from './quality';import { clearLiveProbeResultsDb, loadLiveProbeResults, saveLiveProbeResults } from './db';import { PERSIST_KEY, createThrottledStorage } from './persist-storage';@@ -23,6 +24,12 @@ export interface AppSettings {/** 用户是否在设置中主动选择过推荐数据源;为 false 时部署者的 DEFAULT_RECOMMEND_SOURCE 默认值可生效 */recommendSourceTouched: boolean;autoplayNext: boolean;+ /** 片头/片尾标记:按归一化剧名持久化,详见 lib/skip-marks.ts */+ skipMarks: Record<string, SkipMark>;+ /** 命中片头标记时自动跳到片头结束位置 */+ autoSkipIntro: boolean;+ /** 到达片尾标记时自动结束本集;是否连播下一集仍由 autoplayNext 决定 */+ autoSkipOutro: boolean;imageProxyMode: 'direct' | 'proxy' | 'custom';/** 用户是否在设置中主动选择过封面图加载方式;为 false 时部署者的 DEFAULT_IMAGE_MODE 默认值可生效 */imageProxyModeTouched: boolean;@@ -260,6 +267,12 @@ interface AppState extends AppSettings {* 播放时的 videoHeight 才是真实分辨率,实测一旦拿到就覆盖探测结果。*/setQuality: (entries: Record<string, QualityEntry>) => void;+ /** 写入/更新一部剧的片头片尾标记;字段传 null 表示清除该字段 */+ setSkipMark: (key: string, patch: { introEnd?: number | null; outroStart?: number | null }) => void;+ /** 清除单部剧的片头片尾标记 */+ clearSkipMark: (key: string) => void;+ /** 清除全部片头片尾标记(设置面板的「清除全部」入口) */+ clearAllSkipMarks: () => void;markEnvSubsSeen: (urls: string[]) => void;updateSettings: (patch: Partial<Omit<AppSettings, 'customAPIs' | 'selectedKeys'>>) => void;}@@ -305,6 +318,10 @@ export const useAppStore = create<AppState>()(recommendSource: 'hot-list',recommendSourceTouched: false,autoplayNext: true,+ skipMarks: {},+ // 自动跳过默认开启,但只有用户真正标记过片头/片尾才生效+ autoSkipIntro: true,+ autoSkipOutro: true,// 直连优先:豆瓣封面有公共镜像 + 内置代理两级兜底(见 buildImageCandidates),// 默认省服务器流量;老用户保持已持久化的选择不受影响。// 部署者可用 DEFAULT_IMAGE_MODE=proxy 下发内置代理优先(最稳定,吃服务器流量)@@ -723,6 +740,38 @@ export const useAppStore = create<AppState>()(set({ qualityMap: mergeQualityEntries(get().qualityMap, entries) });},+ setSkipMark: (key, patch) => {+ const marks = get().skipMarks;+ const prev = marks[key];+ const next: SkipMark = { ...prev, updatedAt: Date.now() };+ if ('introEnd' in patch) {+ if (patch.introEnd == null) delete next.introEnd;+ else next.introEnd = patch.introEnd;+ }+ if ('outroStart' in patch) {+ if (patch.outroStart == null) delete next.outroStart;+ else next.outroStart = patch.outroStart;+ }+ // 两个字段都清空后整条删除,持久化快照里不留空壳条目+ if (next.introEnd === undefined && next.outroStart === undefined) {+ if (!prev) return;+ const rest = { ...marks };+ delete rest[key];+ set({ skipMarks: rest });+ return;+ }+ set({ skipMarks: { ...marks, [key]: next } });+ },++ clearSkipMark: (key) => {+ if (!get().skipMarks[key]) return;+ const rest = { ...get().skipMarks };+ delete rest[key];+ set({ skipMarks: rest });+ },++ clearAllSkipMarks: () => set({ skipMarks: {} }),+updateSettings: (patch) => {// 用户主动修改推荐数据源 / 封面图加载方式时打上「已选择」标记:此后部署者的// DEFAULT_RECOMMEND_SOURCE / DEFAULT_IMAGE_MODE 默认值不再覆盖该用户的选择@@ -756,12 +805,19 @@ export const useAppStore = create<AppState>()(storage: createJSONStorage(createThrottledStorage),// v1:直播源新增归属字段、最近观看新增 sourceUrl。// v2:直播源归属改为多引用(fromSubscription 单值 → fromSubscriptions 数组)。+ // v3:新增片头片尾标记与自动跳过开关(旧快照缺字段时补默认值)。// 此前未声明 version 的存量数据会被视为 v0 并走 migrate 补齐。- version: 2,+ version: 3,migrate: (persisted, version) => {const state = { ...((persisted ?? {}) as Partial<AppState>) };if (!Array.isArray(state.liveRecent)) state.liveRecent = [];if (!Array.isArray(state.liveSubscriptions)) state.liveSubscriptions = [];+ // 片头片尾标记必须是非数组对象;损坏的数据不能带进内存,否则读取时会抛错+ if (!state.skipMarks || typeof state.skipMarks !== 'object' || Array.isArray(state.skipMarks)) {+ state.skipMarks = {};+ }+ if (typeof state.autoSkipIntro !== 'boolean') state.autoSkipIntro = true;+ if (typeof state.autoSkipOutro !== 'boolean') state.autoSkipOutro = true;if (version < 2) {state.liveSubscriptions = state.liveSubscriptions.map((s) => {const legacy = s as LiveSubscription & { fromSubscription?: unknown };@@ -803,6 +859,9 @@ export const useAppStore = create<AppState>()(recommendSource: s.recommendSource,recommendSourceTouched: s.recommendSourceTouched,autoplayNext: s.autoplayNext,+ skipMarks: s.skipMarks,+ autoSkipIntro: s.autoSkipIntro,+ autoSkipOutro: s.autoSkipOutro,imageProxyMode: s.imageProxyMode,imageProxyModeTouched: s.imageProxyModeTouched,customImageProxy: s.customImageProxy,