一分钟搭建影视站,支持Docker等部署方式
dplayer替换成artplayer (#507)
ykq00720d913b927a2
diff --git a/js/app.js b/js/app.jsindex d09d2c7..ea3a71a 100644--- a/js/app.js+++ b/js/app.js@@ -971,7 +971,10 @@ async function showDetails(id, vod_name, sourceCode) {apiParams = '&source=' + sourceCode;}- const response = await fetch('/api/detail?id=' + encodeURIComponent(id) + apiParams);+ // Add a timestamp to prevent caching+ const timestamp = new Date().getTime();+ const cacheBuster = `&_t=${timestamp}`;+ const response = await fetch(`/api/detail?id=${encodeURIComponent(id)}${apiParams}${cacheBuster}`);const data = await response.json();@@ -1081,8 +1084,8 @@ function playVideo(url, vod_name, sourceCode, episodeIndex = 0) {console.error('保存播放状态失败:', e);}- // 在新窗口/标签页中打开播放页面- window.open(watchUrl, '_blank');+ // 在当前标签页中打开播放页面+ window.location.href = watchUrl;}// 弹出播放器页面@@ -1502,14 +1505,4 @@ function saveStringAsFile(content, fileName) {window.URL.revokeObjectURL(url);}-// app.js 或路由文件中-const authMiddleware = require('./middleware/auth');-const config = require('./config');--// 对所有请求启用鉴权(按需调整作用范围)-if (config.auth.enabled) {- app.use(authMiddleware);-}--// 或者针对特定路由-app.use('/api', authMiddleware);+// 移除Node.js的require语句,因为这是在浏览器环境中运行的diff --git a/js/player.js b/js/player.jsindex eb58891..ae6a2e2 100644--- a/js/player.js+++ b/js/player.js@@ -90,6 +90,31 @@ window.addEventListener('load', function() {// 全局变量let currentVideoTitle = '';let currentEpisodeIndex = 0;+let art = null; // 用于 ArtPlayer 实例++// 自定义M3U8 Loader用于过滤广告+class CustomHlsJsLoader extends Hls.DefaultConfig.loader {+ constructor(config) {+ super(config);+ const load = this.load.bind(this);+ this.load = function(context, config, callbacks) {+ // 拦截manifest和level请求+ if (context.type === 'manifest' || context.type === 'level') {+ const onSuccess = callbacks.onSuccess;+ callbacks.onSuccess = function(response, stats, context) {+ // 如果是m3u8文件,处理内容以移除广告分段+ if (response.data && typeof response.data === 'string') {+ // 过滤掉广告段 - 实现更精确的广告过滤逻辑+ response.data = filterAdsFromM3U8(response.data, true);+ }+ return onSuccess(response, stats, context);+ };+ }+ // 执行原始load方法+ load(context, config, callbacks);+ };+ }+}let currentEpisodes = [];let episodesReversed = false;let dp = null;@@ -350,366 +375,296 @@ function showShortcutHint(text, direction) {// 初始化播放器function initPlayer(videoUrl, sourceCode) {- if (!videoUrl) return;-- // 配置HLS.js选项- const hlsConfig = {- debug: false,- loader: adFilteringEnabled ? CustomHlsJsLoader : Hls.DefaultConfig.loader,- enableWorker: true,- lowLatencyMode: false,- backBufferLength: 90,- maxBufferLength: 30,- maxMaxBufferLength: 60,- maxBufferSize: 30 * 1000 * 1000,- maxBufferHole: 0.5,- fragLoadingMaxRetry: 6,- fragLoadingMaxRetryTimeout: 64000,- fragLoadingRetryDelay: 1000,- manifestLoadingMaxRetry: 3,- manifestLoadingRetryDelay: 1000,- levelLoadingMaxRetry: 4,- levelLoadingRetryDelay: 1000,- startLevel: -1,- abrEwmaDefaultEstimate: 500000,- abrBandWidthFactor: 0.95,- abrBandWidthUpFactor: 0.7,- abrMaxWithRealBitrate: true,- stretchShortVideoTrack: true,- appendErrorMaxRetry: 5, // 增加尝试次数- liveSyncDurationCount: 3,- liveDurationInfinity: false- };+ // 立即移除所有加载指示器+ document.querySelectorAll('.player-loading-container, .art-loading, #loading').forEach(el => {+ if (el && el.parentNode) {+ el.parentNode.removeChild(el);+ }+ });- // 创建DPlayer实例- dp = new DPlayer({- container: document.getElementById('player'),- autoplay: true,- theme: '#00ccff',- preload: 'auto',- loop: false,- lang: 'zh-cn',- hotkey: true, // 启用键盘控制,包括空格暂停/播放、方向键控制进度和音量- mutex: true,- volume: 0.7,- screenshot: true, // 启用截图功能- preventClickToggle: false, // 允许点击视频切换播放/暂停- airplay: true, // 在Safari中启用AirPlay功能- chromecast: true, // 启用Chromecast投屏功能- contextmenu: [ // 自定义右键菜单- {- text: '关于 LibreTV',- link: 'https://github.com/LibreSpark/LibreTV'- },- {- text: '问题反馈',- click: (player) => {- window.open('https://github.com/LibreSpark/LibreTV/issues', '_blank');- }- }- ],- video: {+ if (!videoUrl) {+ showError('视频链接无效');+ return;+ }++ // 隐藏错误提示+ document.getElementById('error').style.display = 'none';++ // 显示加载指示器+ const loadingElement = document.getElementById('loading');+ if (loadingElement) {+ loadingElement.style.display = 'flex';+ }++ // 根据源代码调整处理逻辑+ const sourceInfo = findSourceInfoByCode(sourceCode);+ const displayName = sourceInfo ? sourceInfo.name : '未知来源';+ console.log(`正在从 ${displayName} 加载视频...`);++ // 记录当前视频URL+ currentVideoUrl = videoUrl;++ // 使用ArtPlayer API加载视频+ if (window.playerAPI && typeof window.playerAPI.loadVideo === 'function') {+ // 准备视频数据+ const videoData = {+ videoId: getVideoId(),+ currentEpisode: currentEpisodeIndex,+ title: currentVideoTitle,url: videoUrl,- type: 'hls',- pic: 'image/nomedia.png', // 设置视频封面图- customType: {- hls: function(video, player) {- // 清理之前的HLS实例- if (currentHls && currentHls.destroy) {- try {- currentHls.destroy();- } catch (e) {- console.warn('销毁旧HLS实例出错:', e);- }- }-- // 创建新的HLS实例- const hls = new Hls(hlsConfig);- currentHls = hls;-- // 跟踪是否已经显示错误- let errorDisplayed = false;- // 跟踪是否有错误发生- let errorCount = 0;- // 跟踪视频是否开始播放- let playbackStarted = false;- // 跟踪视频是否出现bufferAppendError- let bufferAppendErrorCount = 0;-- // 监听视频播放事件- video.addEventListener('playing', function() {- playbackStarted = true;- document.getElementById('loading').style.display = 'none';- document.getElementById('error').style.display = 'none';- });-- // 监听视频进度事件- video.addEventListener('timeupdate', function() {- if (video.currentTime > 1) {- // 视频进度超过1秒,隐藏错误(如果存在)- document.getElementById('error').style.display = 'none';- }- });-- hls.loadSource(video.src);- hls.attachMedia(video);-- // enable airplay, from https://github.com/video-dev/hls.js/issues/5989- // 检查是否已存在source元素,如果存在则更新,不存在则创建- let sourceElement = video.querySelector('source');- if (sourceElement) {- // 更新现有source元素的URL- sourceElement.src = videoUrl;- } else {- // 创建新的source元素- sourceElement = document.createElement('source');- sourceElement.src = videoUrl;- video.appendChild(sourceElement);- }- video.disableRemotePlayback = false;-- hls.on(Hls.Events.MANIFEST_PARSED, function() {- video.play().catch(e => {- console.warn('自动播放被阻止:', e);- });- });-- hls.on(Hls.Events.ERROR, function(event, data) {- console.log('HLS事件:', event, '数据:', data);-- // 增加错误计数- errorCount++;-- // 处理bufferAppendError- if (data.details === 'bufferAppendError') {- bufferAppendErrorCount++;- console.warn(`bufferAppendError 发生 ${bufferAppendErrorCount} 次`);-- // 如果视频已经开始播放,则忽略这个错误- if (playbackStarted) {- console.log('视频已在播放中,忽略bufferAppendError');- return;- }-- // 如果出现多次bufferAppendError但视频未播放,尝试恢复- if (bufferAppendErrorCount >= 3) {- hls.recoverMediaError();- }- }-- // 如果是致命错误,且视频未播放- if (data.fatal && !playbackStarted) {- console.error('致命HLS错误:', data);-- // 尝试恢复错误- switch(data.type) {- case Hls.ErrorTypes.NETWORK_ERROR:- console.log("尝试恢复网络错误");- hls.startLoad();- break;- case Hls.ErrorTypes.MEDIA_ERROR:- console.log("尝试恢复媒体错误");- hls.recoverMediaError();- break;- default:- // 仅在多次恢复尝试后显示错误- if (errorCount > 3 && !errorDisplayed) {- errorDisplayed = true;- showError('视频加载失败,可能是格式不兼容或源不可用');- }- break;- }- }- });-- // 监听分段加载事件- hls.on(Hls.Events.FRAG_LOADED, function() {- document.getElementById('loading').style.display = 'none';- });-- // 监听级别加载事件- hls.on(Hls.Events.LEVEL_LOADED, function() {- document.getElementById('loading').style.display = 'none';- });- }+ poster: '',+ // 添加自定义HLS配置+ customHLS: {+ enableWorker: true,+ debug: false,+ // 其他HLS.js配置...}+ };++ // 使用ArtPlayer API加载视频+ window.playerAPI.loadVideo(videoData)+ .then(artPlayer => {+ art = artPlayer;+ // 隐藏加载动画+ if (loadingElement) {+ loadingElement.style.display = 'none';+ }+ // 设置ArtPlayer事件处理+ setupArtPlayerEvents();+ // 添加到历史记录+ saveToHistory();+ // 启动定期保存播放进度+ startProgressSaveInterval();+ })+ .catch(error => {+ console.error('加载视频失败:', error);+ showError('视频加载失败: ' + (error.message || '未知错误'));+ });+ } else {+ console.error('ArtPlayer API不可用');+ showError('播放器加载失败: ArtPlayer API不可用');}+}++// 设置ArtPlayer事件处理+function setupArtPlayerEvents() {+ if (!art) return;++ // 事件映射 - 将ArtPlayer事件映射到原DPlayer事件处理函数++ // 视频加载完成事件+ art.on('ready', function() {+ const loadingElement = document.getElementById('loading');+ if (loadingElement) {+ loadingElement.style.display = 'none';+ }+ videoHasEnded = false; // 视频加载时重置结束标志++ // 检查是否需要恢复播放进度+ restorePlaybackPosition();++ // 设置进度条点击监听+ setupProgressBarPreciseClicks();++ // 启动长按两倍速功能+ setupLongPressSpeedControl();});- // 全屏模式下锁定横屏- dp.on('fullscreen', () => {++ // 错误处理+ art.on('error', function(error) {+ // 如果正在切换视频,忽略错误+ if (window.isSwitchingVideo) {+ console.log('正在切换视频,忽略错误');+ return;+ }++ console.error('播放器错误:', error);++ // 隐藏所有加载指示器+ const loadingElements = document.querySelectorAll('#loading, .player-loading-container');+ loadingElements.forEach(el => {+ if (el) el.style.display = 'none';+ });++ showError('视频播放失败: ' + (error.message || '未知错误'));+ });++ // 视频播放结束事件+ art.on('video:ended', function() {+ videoHasEnded = true;+ console.log('视频播放结束');++ // 如果自动播放下一集开启,且确实有下一集+ if (autoplayEnabled && currentEpisodeIndex < currentEpisodes.length - 1) {+ console.log('自动播放下一集...');+ setTimeout(() => playNextEpisode(), 1500);+ }+ });++ // 全屏模式处理+ art.on('fullscreen', function() {if (window.screen.orientation && window.screen.orientation.lock) {window.screen.orientation.lock('landscape').then(() => {console.log('屏幕已锁定为横向模式');}).catch((error) => {- console.warn('无法锁定屏幕方向,请手动旋转设备:', error);+ console.warn('无法锁定屏幕方向:', error);});- } else {- console.warn('当前浏览器不支持锁定屏幕方向,请手动旋转设备。');}});- // 全屏取消时解锁屏幕方向- dp.on('fullscreen_cancel', () => {++ // 退出全屏模式+ art.on('fullscreen_cancel', function() {if (window.screen.orientation && window.screen.orientation.unlock) {window.screen.orientation.unlock();}});-- dp.on('loadedmetadata', function() {- document.getElementById('loading').style.display = 'none';- videoHasEnded = false; // 视频加载时重置结束标志+}- // 优先使用URL传递的position参数- const urlParams = new URLSearchParams(window.location.search);- const savedPosition = parseInt(urlParams.get('position') || '0');-- if (savedPosition > 10 && dp && dp.video && dp.video.duration > 0 && savedPosition < dp.video.duration - 2) {- // 如果URL中有有效的播放位置参数,直接使用它- dp.seek(savedPosition);- showPositionRestoreHint(savedPosition);- } else {- // 否则尝试从本地存储恢复播放进度- try {- const progressKey = 'videoProgress_' + currentVideoUrl; // Use currentVideoUrl for unique key- const progressStr = localStorage.getItem(progressKey);- if (progressStr && dp && dp.video && dp.video.duration > 0) {- const progress = JSON.parse(progressStr);- if (- progress &&- typeof progress.position === 'number' &&- progress.position > 10 &&- progress.position < dp.video.duration - 2- ) {- dp.seek(progress.position);- showPositionRestoreHint(progress.position);- }+// 恢复播放进度+function restorePlaybackPosition() {+ if (!art || !art.duration) return;++ // 优先使用URL传递的position参数+ const urlParams = new URLSearchParams(window.location.search);+ const savedPosition = parseInt(urlParams.get('position') || '0');++ if (savedPosition > 10 && savedPosition < art.duration - 2) {+ // 如果URL中有有效的播放位置参数,直接使用它+ art.currentTime = savedPosition;+ showPositionRestoreHint(savedPosition);+ } else {+ // 否则尝试从本地存储恢复播放进度+ try {+ const progressKey = 'videoProgress_' + getVideoId();+ const progressStr = localStorage.getItem(progressKey);+ if (progressStr && art.duration > 0) {+ const progress = JSON.parse(progressStr);+ if (+ progress &&+ typeof progress.position === 'number' &&+ progress.position > 10 &&+ progress.position < art.duration - 2+ ) {+ art.currentTime = progress.position;+ showPositionRestoreHint(progress.position);}- } catch (e) {- // ignore}+ } catch (e) {+ console.error('恢复播放进度失败:', e);}-- // 视频加载成功后重新设置进度条点击监听- setupProgressBarPreciseClicks();-- // 视频加载成功后,在稍微延迟后将其添加到观看历史- setTimeout(saveToHistory, 3000);-- // 启动定期保存播放进度- startProgressSaveInterval();- });-- dp.on('error', function() {- // 如果正在切换视频,忽略错误- if (window.isSwitchingVideo) {- console.log('正在切换视频,忽略错误');- return;- }-- // 检查视频是否已经在播放- if (dp.video && dp.video.currentTime > 1) {- console.log('发生错误,但视频已在播放中,忽略');- return;- }- showError('视频播放失败,请检查视频源或网络连接');- });-- // 添加移动端长按两倍速播放功能- setupLongPressSpeedControl();+ }+}+ // Note: fullscreen_cancel is already handled in setupArtPlayerEvents+// Simple implementation of findSourceInfoByCode+function findSourceInfoByCode(code) {+ // This is a basic implementation - adjust as needed+ return { name: code || '未知来源' };+}+// 添加seeking和seeked事件监听器,以检测用户是否在拖动进度条- dp.on('seeking', function() {- isUserSeeking = true;- videoHasEnded = false; // 重置视频结束标志-- // 如果是用户通过点击进度条设置的位置,确保准确跳转- if (userClickedPosition !== null && dp.video) {- // 确保用户的点击位置被正确应用,避免自动跳至视频末尾- const clickedTime = userClickedPosition;+ if (art && art.on) {+ art.on('seeking', function() {+ isUserSeeking = true;+ videoHasEnded = false; // 重置视频结束标志- // 防止跳转到视频结尾- if (Math.abs(dp.video.duration - clickedTime) < 0.5) {- // 如果点击的位置非常接近结尾,稍微减少一点时间- dp.video.currentTime = Math.max(0, clickedTime - 0.5);- } else {- dp.video.currentTime = clickedTime;+ // 如果是用户通过点击进度条设置的位置,确保准确跳转+ if (userClickedPosition !== null && art.video) {+ // 确保用户的点击位置被正确应用,避免自动跳至视频末尾+ const clickedTime = userClickedPosition;++ // 防止跳转到视频结尾+ if (Math.abs(art.video.duration - clickedTime) < 0.5) {+ // 如果点击的位置非常接近结尾,稍微减少一点时间+ art.video.currentTime = Math.max(0, clickedTime - 0.5);+ } else {+ art.video.currentTime = clickedTime;+ }++ // 清除记录的位置+ setTimeout(() => {+ userClickedPosition = null;+ }, 200);+ }+ });++ // 改进seeked事件处理+ art.on('seeked', function() {+ // 如果视频跳转到了非常接近结尾的位置(小于0.3秒),且不是自然播放到此处+ if (art.video && art.video.duration > 0) {+ const timeFromEnd = art.video.duration - art.video.currentTime;+ if (timeFromEnd < 0.3 && isUserSeeking) {+ // 将播放时间往回移动一点点,避免触发结束事件+ art.video.currentTime = Math.max(0, art.video.currentTime - 1);+ }}- // 清除记录的位置+ // 延迟重置seeking标志,以便于区分自然播放结束和用户拖拽setTimeout(() => {- userClickedPosition = null;+ isUserSeeking = false;}, 200);- }- });-- // 改进seeked事件处理- dp.on('seeked', function() {- // 如果视频跳转到了非常接近结尾的位置(小于0.3秒),且不是自然播放到此处- if (dp.video && dp.video.duration > 0) {- const timeFromEnd = dp.video.duration - dp.video.currentTime;- if (timeFromEnd < 0.3 && isUserSeeking) {- // 将播放时间往回移动一点点,避免触发结束事件- dp.video.currentTime = Math.max(0, dp.video.currentTime - 1);- }- }-- // 延迟重置seeking标志,以便于区分自然播放结束和用户拖拽- setTimeout(() => {- isUserSeeking = false;- }, 200);- });-- // 修改视频结束事件监听器,添加额外检查- dp.on('ended', function() {- videoHasEnded = true; // 标记视频已自然结束-- // 视频已播放完,清除播放进度记录- clearVideoProgress();+ });- // 如果启用了自动连播,并且有下一集可播放,则自动播放下一集- if (autoplayEnabled && currentEpisodeIndex < currentEpisodes.length - 1) {- console.log('视频播放结束,自动播放下一集');- // 稍长延迟以确保所有事件处理完成- setTimeout(() => {- // 确认不是因为用户拖拽导致的假结束事件- if (videoHasEnded && !isUserSeeking) {- playNextEpisode();- videoHasEnded = false; // 重置标志- }- }, 1000);- } else {- console.log('视频播放结束,无下一集或未启用自动连播');- }- });+ // 修改视频结束事件监听器,添加额外检查+ art.on('ended', function() {+ videoHasEnded = true; // 标记视频已自然结束++ // 视频已播放完,清除播放进度记录+ clearVideoProgress();++ // 如果启用了自动连播,并且有下一集可播放,则自动播放下一集+ if (autoplayEnabled && currentEpisodeIndex < currentEpisodes.length - 1) {+ console.log('视频播放结束,自动播放下一集');+ // 稍长延迟以确保所有事件处理完成+ setTimeout(() => {+ // 确认不是因为用户拖拽导致的假结束事件+ if (videoHasEnded && !isUserSeeking) {+ playNextEpisode();+ videoHasEnded = false; // 重置标志+ }+ }, 1000);+ } else {+ console.log('视频播放结束,无下一集或未启用自动连播');+ }+ });+ }// 添加事件监听以检测近视频末尾的点击拖动- dp.on('timeupdate', function() {- if (dp.video && dp.duration > 0) {- // 如果视频接近结尾但不是自然播放到结尾,重置自然结束标志- if (isUserSeeking && dp.video.currentTime > dp.video.duration * 0.95) {- videoHasEnded = false;+ if (art) {+ art.on('timeupdate', function() {+ if (art.video && art.duration > 0) {+ // 如果视频接近结尾但不是自然播放到结尾,重置自然结束标志+ if (isUserSeeking && art.video.currentTime > art.video.duration * 0.95) {+ videoHasEnded = false;+ }}- }- });+ });- // 添加双击全屏支持- dp.on('playing', () => {- // 绑定双击事件到视频容器- dp.video.addEventListener('dblclick', () => {- dp.fullScreen.toggle();+ // 添加双击全屏支持+ art.on('playing', () => {+ // 绑定双击事件到视频容器+ if (art.video) {+ art.video.addEventListener('dblclick', () => {+ if (art.fullScreen && typeof art.fullScreen.toggle === 'function') {+ art.fullScreen.toggle();+ }+ });+ }});- });+ }// 10秒后如果仍在加载,但不立即显示错误setTimeout(function() {// 如果视频已经播放开始,则不显示错误- if (dp && dp.video && dp.video.currentTime > 0) {+ if (art && art.video && art.video.currentTime > 0) {return;}- if (document.getElementById('loading').style.display !== 'none') {- document.getElementById('loading').innerHTML = `+ const loadingElement = document.getElementById('loading');+ if (loadingElement && loadingElement.style.display !== 'none') {+ loadingElement.innerHTML = `<div class="loading-spinner"></div><div>视频加载时间较长,请耐心等待...</div><div style="font-size: 12px; color: #aaa; margin-top: 10px;">如长时间无响应,请尝试其他视频源</div>@@ -720,44 +675,27 @@ function initPlayer(videoUrl, sourceCode) {// 绑定原生全屏:DPlayer 触发全屏时调用 requestFullscreen(function(){const fsContainer = document.getElementById('playerContainer');- dp.on('fullscreen', () => {- if (fsContainer.requestFullscreen) {- fsContainer.requestFullscreen().catch(err => console.warn('原生全屏失败:', err));- }- });- dp.on('fullscreen_cancel', () => {- if (document.fullscreenElement) {- document.exitFullscreen();+ if (art && art.on && fsContainer) {+ try {+ art.on('fullscreen', () => {+ if (fsContainer.requestFullscreen) {+ fsContainer.requestFullscreen().catch(err => console.warn('原生全屏失败:', err));+ }+ });+ art.on('fullscreen_cancel', () => {+ if (document.fullscreenElement) {+ document.exitFullscreen();+ }+ });+ } catch (e) {+ console.warn('绑定全屏事件时出错:', e);}- });+ }})();-}-// 自定义M3U8 Loader用于过滤广告-class CustomHlsJsLoader extends Hls.DefaultConfig.loader {- constructor(config) {- super(config);- const load = this.load.bind(this);- this.load = function(context, config, callbacks) {- // 拦截manifest和level请求- if (context.type === 'manifest' || context.type === 'level') {- const onSuccess = callbacks.onSuccess;- callbacks.onSuccess = function(response, stats, context) {- // 如果是m3u8文件,处理内容以移除广告分段- if (response.data && typeof response.data === 'string') {- // 过滤掉广告段 - 实现更精确的广告过滤逻辑- response.data = filterAdsFromM3U8(response.data, true);- }- return onSuccess(response, stats, context);- };- }- // 执行原始load方法- load(context, config, callbacks);- };- }-}-// M3U8清单广告过滤函数++// 过滤可疑的广告内容function filterAdsFromM3U8(m3u8Content, strictMode = false) {if (!m3u8Content) return '';@@ -781,14 +719,16 @@ function filterAdsFromM3U8(m3u8Content, strictMode = false) {// 显示错误function showError(message) {// 在视频已经播放的情况下不显示错误- if (dp && dp.video && dp.video.currentTime > 1) {+ if (art && art.video && art.video.currentTime > 1) {console.log('忽略错误:', message);return;}-- document.getElementById('loading').style.display = 'none';- document.getElementById('error').style.display = 'flex';- document.getElementById('error-message').textContent = message;+ const loadingEl = document.getElementById('loading');+ if (loadingEl) loadingEl.style.display = 'none';+ const errorEl = document.getElementById('error');+ if (errorEl) errorEl.style.display = 'flex';+ const errorMsgEl = document.getElementById('error-message');+ if (errorMsgEl) errorMsgEl.textContent = message;}// 更新集数信息@@ -868,7 +808,7 @@ function playEpisode(index) {}// 保存当前播放进度(如果正在播放)- if (dp && dp.video && !dp.video.paused && !videoHasEnded) {+ if (art && art.video && !art.video.paused && !videoHasEnded) {saveCurrentProgress();}@@ -878,121 +818,31 @@ function playEpisode(index) {progressSaveInterval = null;}- // 首先隐藏之前可能显示的错误- document.getElementById('error').style.display = 'none';- // 显示加载指示器- document.getElementById('loading').style.display = 'flex';- document.getElementById('loading').innerHTML = `- <div class="loading-spinner"></div>- <div>正在加载视频...</div>- `;+ // 获取 sourceCode+ const urlParams2 = new URLSearchParams(window.location.search);+ const sourceCode = urlParams2.get('source_code');+ // 准备切换剧集的URLconst url = currentEpisodes[index];- // 更新全局URL记录- currentVideoUrl = url;- currentEpisodeIndex = index;- videoHasEnded = false; // 重置视频结束标志-- // 新增:清除之前的播放位置记录,确保切换选集后从头开始播放- clearVideoProgress();-- // 获取当前URL的所有参数const currentUrl = new URL(window.location.href);const urlParams = currentUrl.searchParams;- const sourceName = urlParams.get('source') || '';- const sourceCode = urlParams.get('source_code') || '';- const videoId = urlParams.get('id') || '';- const returnUrl = urlParams.get('returnUrl') || '';- // 构建新的URL,保持查询参数但更新index和url+ // 构建新的URL参数const newUrl = new URL(window.location.origin + window.location.pathname);// 保留所有原始参数for(const [key, value] of urlParams.entries()) {newUrl.searchParams.set(key, value);}+// 更新需要变更的参数newUrl.searchParams.set('index', index);newUrl.searchParams.set('url', url);- // 移除position参数,确保不会从记录的位置开始播放+ // 确保不会从记录的位置开始播放newUrl.searchParams.delete('position');- // 使用replaceState更新URL,这样不会增加浏览历史记录- window.history.replaceState({}, '', newUrl);-- // 更新播放器- if (dp) {- try {- // 检测是否为Safari浏览器或iOS设备- const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);- const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;-- if (isSafari || isIOS) {- // Safari或iOS设备:完全重新初始化播放器- console.log('检测到Safari或iOS设备,重新初始化播放器');-- // 标记正在切换视频,避免错误处理- window.isSwitchingVideo = true;-- // 如果存在旧的播放器实例,先销毁它- if (dp && dp.destroy) {- try {- dp.destroy();- } catch (e) {- console.warn('销毁旧播放器实例出错:', e);- }- }-- // 重新初始化播放器- initPlayer(url, sourceCode);-- // 延迟重置标记- setTimeout(() => {- window.isSwitchingVideo = false;- }, 1000);- } else {- // 其他浏览器使用正常的switchVideo方法- if (dp.video) {- // 更新source元素- const sources = dp.video.querySelectorAll('source');- sources.forEach(source => source.src = url);- }-- dp.switchVideo({- url: url,- type: 'hls'- });- }-- // 确保播放开始- if (dp) {- const playPromise = dp.play();- if (playPromise !== undefined) {- playPromise.catch(error => {- console.warn('播放失败,尝试重新初始化:', error);- // 如果切换视频失败,重新初始化播放器- initPlayer(url, sourceCode);- });- }- }- } catch (e) {- console.error('切换视频出错,尝试重新初始化:', e);- // 如果出错,重新初始化播放器- initPlayer(url, sourceCode);- }- } else {- initPlayer(url, sourceCode);- }-- // 更新UI- updateEpisodeInfo();- updateButtonStates();- renderEpisodes();-- // 重置用户点击位置记录- userClickedPosition = null;-- // 三秒后保存到历史记录- setTimeout(() => saveToHistory(), 3000);+ // 使用页面重载方式切换剧集,这将完全清理所有资源+ window.location.href = newUrl.toString();+ return;}// 播放上一集@@ -1052,7 +902,7 @@ function updateOrderButton() {function setupProgressBarPreciseClicks() {// 查找DPlayer的进度条元素const progressBar = document.querySelector('.dplayer-bar-wrap');- if (!progressBar || !dp || !dp.video) return;+ if (!progressBar || !art || !art.video) return;// 移除可能存在的旧事件监听器progressBar.removeEventListener('mousedown', handleProgressBarClick);@@ -1069,14 +919,14 @@ function setupProgressBarPreciseClicks() {// 处理进度条点击function handleProgressBarClick(e) {- if (!dp || !dp.video) return;+ if (!art || !art.video) return;// 计算点击位置相对于进度条的比例const rect = e.currentTarget.getBoundingClientRect();const percentage = (e.clientX - rect.left) / rect.width;// 计算点击位置对应的视频时间- const duration = dp.video.duration;+ const duration = art.video.duration;let clickTime = percentage * duration;// 处理视频接近结尾的情况@@ -1096,18 +946,18 @@ function handleProgressBarClick(e) {e.stopPropagation();// 直接设置视频时间- dp.seek(clickTime);+ art.seek(clickTime);}// 处理移动端触摸事件function handleProgressBarTouch(e) {- if (!dp || !dp.video || !e.touches[0]) return;+ if (!art || !art.video || !e.touches[0]) return;const touch = e.touches[0];const rect = e.currentTarget.getBoundingClientRect();const percentage = (touch.clientX - rect.left) / rect.width;- const duration = dp.video.duration;+ const duration = art.video.duration;let clickTime = percentage * duration;// 处理视频接近结尾的情况@@ -1121,7 +971,7 @@ function handleProgressBarTouch(e) {console.log(`进度条触摸: ${percentage.toFixed(4)}, 时间: ${clickTime.toFixed(2)}/${duration.toFixed(2)}`);e.stopPropagation();- dp.seek(clickTime);+ art.seek(clickTime);}// 在播放器初始化后添加视频到历史记录@@ -1141,9 +991,9 @@ function saveToHistory() {let currentPosition = 0;let videoDuration = 0;- if (dp && dp.video) {- currentPosition = dp.video.currentTime;- videoDuration = dp.video.duration;+ if (art && art.video) {+ currentPosition = art.video.currentTime;+ videoDuration = art.video.duration;}// 构建要保存的视频信息对象@@ -1268,9 +1118,9 @@ function startProgressSaveInterval() {// 保存当前播放进度function saveCurrentProgress() {- if (!dp || !dp.video) return;- const currentTime = dp.video.currentTime;- const duration = dp.video.duration;+ if (!art || !art.video) return;+ const currentTime = art.video.currentTime;+ const duration = art.video.duration;if (!duration || currentTime < 1) return;// 在localStorage中保存进度@@ -1315,7 +1165,7 @@ function saveCurrentProgress() {// 设置移动端长按两倍速播放功能function setupLongPressSpeedControl() {- if (!dp || !dp.video) return;+ if (!art || !art.video) return;const playerElement = document.getElementById('player');let longPressTimer = null;@@ -1346,24 +1196,24 @@ function setupLongPressSpeedControl() {// 触摸开始事件playerElement.addEventListener('touchstart', function(e) {// 检查视频是否正在播放,如果没有播放则不触发长按功能- if (dp.video.paused) {+ if (art.video.paused) {return; // 视频暂停时不触发长按功能}// 保存原始播放速度- originalPlaybackRate = dp.video.playbackRate;+ originalPlaybackRate = art.video.playbackRate;// 设置长按计时器longPressTimer = setTimeout(() => {// 再次检查视频是否仍在播放- if (dp.video.paused) {+ if (art.video.paused) {clearTimeout(longPressTimer);longPressTimer = null;return;}// 长按超过500ms,设置为3倍速- dp.video.playbackRate = 3.0;+ art.video.playbackRate = 3.0;isLongPress = true;showSpeedHint(3.0);@@ -1382,7 +1232,7 @@ function setupLongPressSpeedControl() {// 如果是长按状态,恢复原始播放速度if (isLongPress) {- dp.video.playbackRate = originalPlaybackRate;+ art.video.playbackRate = originalPlaybackRate;isLongPress = false;showSpeedHint(originalPlaybackRate);@@ -1402,7 +1252,7 @@ function setupLongPressSpeedControl() {// 如果是长按状态,恢复原始播放速度if (isLongPress) {- dp.video.playbackRate = originalPlaybackRate;+ art.video.playbackRate = originalPlaybackRate;isLongPress = false;}});@@ -1415,9 +1265,9 @@ function setupLongPressSpeedControl() {}, { passive: false });// 视频暂停时取消长按状态- dp.video.addEventListener('pause', function() {+ art.video.addEventListener('pause', function() {if (isLongPress) {- dp.video.playbackRate = originalPlaybackRate;+ art.video.playbackRate = originalPlaybackRate;isLongPress = false;}diff --git a/player.html b/player.htmlindex 57d8849..8d7b793 100644--- a/player.html+++ b/player.html@@ -15,16 +15,146 @@<script src="js/version-check.js"></script><link rel="stylesheet" href="css/styles.css"><link rel="stylesheet" href="css/player.css">++ <!-- Add optimized player loading styles -->+ <style>+ /* Critical header and navigation styles */+ .player-header {+ position: relative;+ z-index: 2147483647 !important;+ pointer-events: auto !important;+ }++ /* Critical loading styles to prevent FOUC */+ .player-placeholder {+ width: 100% !important;+ height: auto !important;+ aspect-ratio: 16/9 !important;+ background-color: #1f2937 !important;+ position: relative !important;+ display: block !important;+ border-radius: 8px !important;+ overflow: hidden !important;+ }++ .player-loading-container {+ width: 100% !important;+ height: 0 !important;+ padding-bottom: 56.25% !important;+ position: relative !important;+ background-color: #1f2937 !important;+ border-radius: 8px !important;+ overflow: hidden !important;+ display: block !important;+ }++ .player-loading-overlay {+ position: absolute !important;+ top: 0 !important;+ left: 0 !important;+ width: 100% !important;+ height: 100% !important;+ display: flex !important;+ flex-direction: column !important;+ align-items: center !important;+ justify-content: center !important;+ background-color: rgba(17, 24, 39, 0.7) !important;+ }++ .player-loading-spinner {+ width: 48px !important;+ height: 48px !important;+ border-radius: 50% !important;+ position: relative !important;+ margin-bottom: 16px !important;+ }++ /* Critical styles for loading text */+ .player-loading-text,+ .player-loading-overlay div:nth-child(2),+ div.player-loading-text {+ display: block !important;+ visibility: visible !important;+ opacity: 1 !important;+ color: #f9fafb !important;+ font-size: 16px !important;+ font-weight: 500 !important;+ margin-bottom: 8px !important;+ text-align: center !important;+ font-family: system-ui, -apple-system, sans-serif !important;+ line-height: 1.4 !important;+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;+ pointer-events: none !important;+ z-index: 100 !important;+ background: transparent !important;+ max-width: 90% !important;+ }++ @keyframes player-spinner-rotate {+ to { transform: rotate(360deg); }+ }++ @keyframes spin {+ 0% { transform: rotate(0deg); }+ 100% { transform: rotate(360deg); }+ }++ /* ArtPlayer specific styles */+ .art-video-player, .art-video-player video {+ width: 100% !important;+ height: 100% !important;+ min-height: 150px !important;+ max-height: 100vh !important;+ background: #000 !important;+ object-fit: contain !important;+ position: relative !important;+ display: block !important;+ }++ /* Fix for Chrome-specific issues */+ @media screen and (-webkit-min-device-pixel-ratio: 0) {+ .art-video-player video {+ transform: translateZ(0) !important;+ will-change: transform !important;+ }++ /* Force visibility of video element */+ .art-video-player.art-playing video {+ visibility: visible !important;+ opacity: 1 !important;+ }+ }++ .player-header-fixed {+ position: fixed !important;+ top: 0;+ left: 0;+ width: 100vw;+ z-index: 2147483647 !important;+ pointer-events: auto !important;+ background: #111;+ }+ #homeButton { pointer-events: auto !important; }+ body { padding-top: 72px; }+ </style>++ <!-- Loading indicator has been removed as requested -->+ <script>+ // Loading indicator initialization removed+ </script>+ <meta http-equiv="Cache-Control" content="no-store, must-revalidate">+ <meta http-equiv="Pragma" content="no-cache">+ <meta http-equiv="Expires" content="0"></head><body>- <header class="bg-[#111] p-4 flex items-center border-b border-[#333] gap-2 player-header">+ <header class="player-header-fixed p-4 flex items-center border-b border-[#333] gap-2"><div class="flex items-center min-w-0">- <a href="/" class="flex items-center min-w-0">+ <button id="homeButton" type="button" class="flex items-center min-w-0 cursor-pointer" style="background:none;border:none;padding:0;"><svg class="w-8 h-8 mr-2 text-[#00ccff] logo-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg><h1 class="text-xl font-bold gradient-text logo-text">LibreTV</h1>- </a>+ </button></div><h2 id="videoTitle" class="text-xl font-semibold flex-1 text-center overflow-x-auto whitespace-nowrap truncate custom-title-scroll"></h2><a href="#" id="goBack" onclick="goBack(event)" class="px-4 py-2 bg-[#222] hover:bg-[#333] border border-[#333] rounded-lg transition-colors flex items-center min-w-0 home-btn">@@ -58,8 +188,14 @@<!-- 视频播放区 --><div id="playerContainer" class="player-container"><div class="relative">- <div id="player"></div>- <div class="loading-container" id="loading">+ <div id="player" class="player-placeholder" style="width: 100%; height: auto; aspect-ratio: 16/9; background-color: #1f2937; position: relative; display: block;">+ <!-- Initial loading state before JavaScript loads -->+ <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; color: white;">+ <div style="width: 48px; height: 48px; border: 4px solid rgba(255, 255, 255, 0.1); border-radius: 50%; border-top-color: #f97316; margin: 0 auto 16px; animation: spin 1s linear infinite;"></div>+ <div style="font-size: 16px; font-weight: 500;" id="loading-title">正在加载视频...</div>+ </div>+ </div>+ <div class="loading-container" id="loading" style="display: none;"><div class="loading-spinner"></div><div>正在加载视频...</div></div>@@ -188,11 +324,371 @@</script><script src="libs/hls.min.js" crossorigin="anonymous"></script>- <script src="libs/DPlayer.min.js" crossorigin="anonymous"></script>+ <script src="https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.js" crossorigin="anonymous"></script><script src="js/config.js"></script><script src="js/password.js"></script><script src="js/ui.js"></script>+ <!-- Replace player.js with ArtPlayer implementation -->+ <script>+ // Global variables+ const rateKey = 'vodg-playback-rate';+ const cacheKey = 'vod-play-progress';+ let playbackTimeUpdated = Date.now();+ let videoId = null;+ let currentEpisode = null;++ // Configure player settings+ function initArtPlayer(videoUrl, videoTitle, posterUrl) {+ // 彻底清理 player 容器和所有 video 元素+ const playerContainer = document.getElementById('player');+ if (playerContainer) {+ // 暂停并移除所有 video 元素+ const videos = playerContainer.querySelectorAll('video');+ videos.forEach(v => {+ try { v.pause(); } catch(e){}+ v.src = '';+ v.remove();+ });+ // 清空容器+ playerContainer.innerHTML = '';+ }+ // 销毁旧实例+ if (art) {+ art.destroy(true);+ art = null;+ }++ // Get stored playback rate+ const storedRate = parseFloat(localStorage.getItem(rateKey) || '1');+ const playbackRate = (storedRate > 0 && storedRate < 5) ? storedRate : 1;++ // Determine if we need to use the m3u8 custom type+ const type = videoUrl.endsWith('.m3u8') ? 'customHls' : 'auto';++ // Create new ArtPlayer instance+ art = new Artplayer({+ container: '#player',+ url: videoUrl,+ type: type,+ title: videoTitle,+ poster: posterUrl,+ posterScaling: 'contain',+ volume: 0.8,+ isLive: false,+ muted: false,+ autoplay: true,+ pip: true,+ autoSize: true,+ autoMini: true,+ screenshot: true,+ setting: true,+ loop: false,+ flip: true,+ playbackRate: true,+ aspectRatio: true,+ fullscreen: true,+ fullscreenWeb: false,+ subtitleOffset: true,+ miniProgressBar: true,+ mutex: true,+ backdrop: true,+ playsInline: true,+ autoPlayback: false,+ airplay: true,+ theme: '#23ade5',+ lang: navigator.language.toLowerCase(),+ moreVideoAttr: {+ crossOrigin: 'anonymous',+ },+ customType: {+ customHls: function(video, url) {+ if (Hls.isSupported()) {+ const hls = new Hls({+ maxBufferLength: 60,+ maxMaxBufferLength: 90,+ maxBufferSize: 100 * 1000 * 1000,+ maxBufferHole: 1,+ lowLatencyMode: false,+ manifestLoadingMaxRetry: 6,+ levelLoadingMaxRetry: 6,+ fragLoadingMaxRetry: 6,+ fragLoadingMaxRetryTimeout: 10000+ });++ hls.loadSource(url);+ hls.attachMedia(video);++ hls.on(Hls.Events.ERROR, function(event, data) {+ if (data.fatal) {+ switch (data.type) {+ case Hls.ErrorTypes.NETWORK_ERROR:+ // HLS network error+ hls.startLoad();+ break;+ case Hls.ErrorTypes.MEDIA_ERROR:+ // HLS media error+ hls.recoverMediaError();+ break;+ default:+ // HLS fatal error+ showError('视频流加载失败: ' + data.details);+ break;+ }+ }+ });+ } else if (video.canPlayType('application/vnd.apple.mpegurl')) {+ video.src = url;+ }+ }+ }+ });++ // Hide loading animation when player is ready+ art.on('ready', () => {+ // Force video element to be visible+ const video = art.template.$video;+ if (video) {+ video.style.display = 'block';+ video.style.visibility = 'visible';+ video.style.opacity = '1';+ video.style.zIndex = '2';++ // Force hardware acceleration+ video.style.transform = 'translateZ(0)';+ video.style.backfaceVisibility = 'hidden';+ }++ // Hide loading indicator+ const loadingContainer = document.querySelector('.player-loading-container');+ if (loadingContainer) {+ loadingContainer.style.display = 'none';+ }++ // Hide default loading+ const loading = document.getElementById('loading');+ if (loading) {+ loading.style.display = 'none';+ }++ // Set player aspect ratio (16:9 for most videos)+ document.getElementById('player').style.aspectRatio = '16/9';+ });++ // Error handling+ art.on('error', (error) => {+ showError('播放器加载失败: ' + (error.message || '未知错误'));+ });++ // Auto-play next episode when current one ends+ art.on('video:ended', () => {+ try {+ removePlayProgressRate();+ // Check if autoplay is enabled+ const autoplayToggle = document.getElementById('autoplayToggle');+ if (autoplayToggle && autoplayToggle.checked) {+ playNextEpisode();+ }+ } catch (error) {+ console.error('Error in video:ended event:', error);+ }+ });++ // Update playback progress+ art.on('video:timeupdate', () => {+ try {+ updatePlayProgressRate(art.currentTime, art.duration);+ } catch (error) {+ console.error('Error in video:timeupdate event:', error);+ }+ });++ // Handle duration change to seek to saved position+ let seeked = false;+ art.on('video:durationchange', () => {+ try {+ if (!seeked && art.duration > 0) {+ seeked = true;+ // Seek to saved position+ art.currentTime = getSeekTime(art.duration);+ // Set saved playback rate+ if (playbackRate > 0 && playbackRate < 5) {+ art.playbackRate = playbackRate;+ }+ }+ } catch (error) {+ console.error('Error in video:durationchange event:', error);+ }+ });++ // Store playback rate when changed+ art.on('video:ratechange', () => {+ try {+ if (art.playbackRate > 0) {+ localStorage.setItem(rateKey, art.playbackRate);+ }+ } catch (error) {+ console.error('Error in video:ratechange event:', error);+ }+ });++ // Fix for Chrome - ensure video is visible when playing+ art.on('play', () => {+ const video = art.template.$video;+ if (video) {+ // Force redraw of video element+ video.style.display = 'none';+ setTimeout(() => {+ video.style.display = 'block';+ video.style.visibility = 'visible';+ video.style.opacity = '1';+ }, 50);+ }+ });++ // Set window.art as a global reference+ window.art = art;+ return art;+ }++ // Show error message+ function showError(message) {+ const errorContainer = document.getElementById('error');+ const errorMessage = document.getElementById('error-message');+ if (errorContainer && errorMessage) {+ errorMessage.textContent = message || '视频加载失败';+ errorContainer.style.display = 'flex';+ }+ }++ // Progress caching functions+ function getPlayCache() {+ let cache = localStorage.getItem(cacheKey);+ if (cache && typeof cache == 'string') {+ try {+ cache = JSON.parse(cache);+ } catch {+ cache = {};+ }+ } else {+ cache = {};+ }+ if (!cache[videoId] || typeof cache[videoId] != 'object') {+ cache[videoId] = {};+ }+ if (!cache[videoId][currentEpisode] || typeof cache[videoId][currentEpisode] != 'object') {+ cache[videoId][currentEpisode] = {};+ }+ return cache;+ }++ function getPlaybackCache() {+ const cache = getPlayCache()[videoId][currentEpisode];+ if (!cache.playProgressRate) {+ cache.playProgressRate = 0;+ }+ return cache;+ }++ function updatePlayProgressRate(currTime, duration) {+ const now = Date.now();+ if (playbackTimeUpdated + 1000 < now && currTime > 2) {+ playbackTimeUpdated = now;+ const playProgressRate = currTime / duration;+ if (playProgressRate > 0 && playProgressRate <= 1) {+ const cache = getPlayCache();+ cache[videoId][currentEpisode].playProgressRate = playProgressRate;+ cache[videoId][currentEpisode].updated = now;+ localStorage.setItem(cacheKey, JSON.stringify(cache));+ }+ }+ }++ function removePlayProgressRate() {+ const cache = getPlayCache();+ delete cache[videoId][currentEpisode];+ if (Object.keys(cache[videoId]).length == 0) {+ delete cache[videoId];+ }+ localStorage.setItem(cacheKey, JSON.stringify(cache));+ }++ function getSeekTime(duration) {+ return Math.max(Math.min(Math.max(getPlaybackCache().playProgressRate, 0), 1) * duration - 2, 0);+ }++ // Load M3U8 with proxy handling if needed+ async function loadM3u8Url(url) {+ if (!url.endsWith('.m3u8')) {+ return url;+ }+ try {+ // Custom m3u8 processing logic can be added here if needed+ // For now, just return the URL as-is+ return url;+ } catch (error) {+ console.error('Error processing m3u8:', error);+ return url;+ }+ }++ // Initialize player with video data+ async function loadVideo(data) {+ try {+ // Set global variables+ videoId = data.videoId;+ currentEpisode = data.currentEpisode;+ const videoTitle = data.title || document.getElementById('videoTitle').textContent;+ document.getElementById('videoTitle').textContent = videoTitle;+ // Update loading title+ const loadingTitle = document.getElementById('loading-title');+ if (loadingTitle) {+ loadingTitle.textContent = videoTitle;+ }++ // Process video URL (handle m3u8 if needed)+ let videoUrl = data.url;+ if (videoUrl.endsWith('.m3u8')) {+ videoUrl = await loadM3u8Url(videoUrl);+ }++ // Initialize player+ document.getElementById('error').style.display = 'none';+ return initArtPlayer(videoUrl, videoTitle, data.poster || '');+ } catch (error) {+ console.error('Error loading video:', error);+ showError('视频加载失败: ' + error.message);+ return null;+ }+ }++ // Expose functions to be used by other scripts+ window.playerAPI = {+ loadVideo: loadVideo,+ showError: showError+ };++ // Clean up outdated cache entries+ (function cleanupCache() {+ try {+ const now = Date.now();+ const cache = JSON.parse(localStorage.getItem(cacheKey) || '{}');+ for (const vid in cache) {+ for (const ep in cache[vid]) {+ if (cache[vid][ep].updated < now - 86400000 * 92) {+ delete cache[vid][ep];+ }+ }+ if (Object.keys(cache[vid]).length == 0) {+ delete cache[vid];+ }+ }+ localStorage.setItem(cacheKey, JSON.stringify(cache));+ } catch (error) {+ console.error('Error cleaning up cache:', error);+ }+ })();+ </script><script src="js/player.js"></script><script>@@ -201,58 +697,156 @@// 注入服务器端环境变量 (将由服务器端替换)// PASSWORD 变量将在这里被服务器端注入- window.__ENV__.PASSWORD = "{{PASSWORD}}"; // 改进返回上一页功能+ window.__ENV__.PASSWORD = "{{PASSWORD}}";++ // 直接导航到首页的备份方法,强制清理和导航+ function directNavigateHome() {+ console.log('Direct home navigation triggered');+ try {+ // 停止所有音频和视频+ document.querySelectorAll('video, audio').forEach(media => {+ try {+ media.pause();+ media.muted = true;+ media.src = '';+ } catch (e) {}+ });++ // 关闭播放器+ if (window.dp && typeof window.dp.destroy === 'function') {+ try { window.dp.destroy(true); } catch(e) {}+ }++ // 清除事件处理程序+ window.onbeforeunload = null;++ // 立即导航+ setTimeout(() => { window.location.replace('/'); }, 0);+ } catch(e) {+ // 如果出错,直接导航+ window.location.href = '/';+ }+ return false; // 阻止默认点击事件+ }++ // 页面加载完成后初始化事件监听+ document.addEventListener('DOMContentLoaded', function() {+ // 使用事件委托处理首页按钮点击+ document.body.addEventListener('click', function(event) {+ const homeButton = event.target.closest('#homeButton');+ if (homeButton) {+ event.preventDefault();+ event.stopPropagation();+ try {+ if (window.playerAPI && window.playerAPI.destroy) {+ window.playerAPI.destroy();+ }+ } catch (e) {}+ // 多重兜底跳转+ try {+ window.location.href = '/';+ } catch (e) {+ try {+ window.location.replace('/');+ } catch (e2) {+ window.location.assign('/');+ }+ }+ return false;+ }+ });+ });++ // 改进返回上一页功能function goBack(event) {// 防止默认链接行为- if (event) event.preventDefault();-- // 1. 优先检查URL参数中的returnUrl- const urlParams = new URLSearchParams(window.location.search);- const returnUrl = urlParams.get('returnUrl');-- if (returnUrl) {- // 如果URL中有returnUrl参数,优先使用- window.location.href = decodeURIComponent(returnUrl);- return;- }-- // 2. 检查localStorage中保存的lastPageUrl- const lastPageUrl = localStorage.getItem('lastPageUrl');- if (lastPageUrl && lastPageUrl !== window.location.href) {- window.location.href = lastPageUrl;- return;- }-- // 3. 检查是否是从搜索页面进入的播放器- const referrer = document.referrer;-- // 检查 referrer 是否包含搜索参数- if (referrer && (referrer.includes('/s=') || referrer.includes('?s='))) {- // 如果是从搜索页面来的,返回到搜索页面- window.location.href = referrer;- return;+ if (event) {+ event.preventDefault();+ event.stopPropagation();}- // 4. 如果是在iframe中打开的,尝试关闭iframe- if (window.self !== window.top) {- try {- // 尝试调用父窗口的关闭播放器函数- window.parent.closeVideoPlayer && window.parent.closeVideoPlayer();+ // 1. 优先检查URL参数中的returnUrl+ try {+ const urlParams = new URLSearchParams(window.location.search);+ const returnUrl = urlParams.get('returnUrl');++ if (returnUrl) {+ // 如果URL中有returnUrl参数,优先使用+ window.location.href = decodeURIComponent(returnUrl);+ return;+ }++ // 2. 检查localStorage中保存的lastPageUrl+ const lastPageUrl = localStorage.getItem('lastPageUrl');+ if (lastPageUrl && lastPageUrl !== window.location.href) {+ window.location.href = lastPageUrl;+ return;+ }++ // 3. 检查是否是从搜索页面进入的播放器+ const referrer = document.referrer;++ // 检查 referrer 是否包含搜索参数+ if (referrer && (referrer.includes('/s=') || referrer.includes('?s='))) {+ // 如果是从搜索页面来的,返回到搜索页面+ window.location.href = referrer;return;+ }++ // 4. 如果是在iframe中打开的,尝试关闭iframe+ if (window.self !== window.top) {+ try {+ // 尝试调用父窗口的关闭播放器函数+ window.parent.closeVideoPlayer && window.parent.closeVideoPlayer();+ return;+ } catch (e) {+ console.error('调用父窗口closeVideoPlayer失败:', e);+ }+ }++ // 5. 尝试使用history.back(),如果失败则回退到首页+ try {+ const historyLength = window.history.length;+ if (historyLength > 1) {+ window.history.back();+ // 设置超时,如果3秒后仍然在当前页面,则跳转到首页+ setTimeout(() => {+ if (window.location.href === window.location.href) {+ window.location.href = '/';+ }+ }, 3000);+ return;+ }} catch (e) {- console.error('调用父窗口closeVideoPlayer失败:', e);+ console.error('使用history.back()失败:', e);}- }-- // 5. 无法确定上一页,则返回首页- if (!referrer || referrer === '') {++ // 6. 以上都不满足,导航到首页+ window.location.href = '/';++ } catch (e) {+ console.error('处理返回操作时出错:', e);+ // 出现错误时直接导航到首页window.location.href = '/';- return;}-- // 6. 以上都不满足,使用默认行为:返回上一页- window.history.back();}++ // Fix: Force reload if page is restored from bfcache (history navigation)+ window.addEventListener('pageshow', function(event) {+ if (event.persisted) {+ window.location.reload();+ }+ });+ // Force hard navigation for home button+ document.addEventListener('DOMContentLoaded', function() {+ var homeBtn = document.getElementById('homeButton');+ if (homeBtn) {+ homeBtn.addEventListener('click', function(e) {+ e.preventDefault();+ window.location.replace('/');+ });+ }+ });</script></body></html>