Skip to content

一分钟搭建影视站,支持Docker等部署方式

fix(player): 同名剧不会被替代 & 实时刷新剧集列表 (#528)

ykq007c316c71a747a
diff --git a/js/app.js b/js/app.js
index 53eef88..d903e56 100644
--- a/js/app.js
+++ b/js/app.js
@@ -1008,7 +1008,7 @@ async function showDetails(id, vod_name, sourceCode) {
episodesReversed = false; // 默认正序
modalContent.innerHTML = `
<div class="flex justify-end mb-2">
- <button onclick="toggleEpisodeOrder('${sourceCode}')" class="px-4 py-1 bg-[#222] hover:bg-[#333] border border-[#333] rounded-lg transition-colors flex items-center space-x-1">
+ <button onclick="toggleEpisodeOrder('${sourceCode}', '${id}')" class="px-4 py-1 bg-[#222] hover:bg-[#333] border border-[#333] rounded-lg transition-colors flex items-center space-x-1">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v3.586L7.707 9.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 10.586V7z" clip-rule="evenodd" />
</svg>
@@ -1021,7 +1021,7 @@ async function showDetails(id, vod_name, sourceCode) {
</button>
</div>
<div id="episodesGrid" class="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
- ${renderEpisodes(vod_name, sourceCode)}
+ ${renderEpisodes(vod_name, sourceCode, id)}
</div>
`;
} else {
@@ -1038,7 +1038,7 @@ async function showDetails(id, vod_name, sourceCode) {
}
// 更新播放视频函数,修改为使用/watch路径而不是直接打开player.html
-function playVideo(url, vod_name, sourceCode, episodeIndex = 0) {
+function playVideo(url, vod_name, sourceCode, episodeIndex = 0, vodId = '') {
// 密码保护校验
if (window.isPasswordProtected && window.isPasswordVerified) {
if (window.isPasswordProtected() && !window.isPasswordVerified()) {
@@ -1046,30 +1046,17 @@ function playVideo(url, vod_name, sourceCode, episodeIndex = 0) {
return;
}
}
- if (!url) {
- showToast('视频地址无效', 'error');
- return;
- }
// 获取当前路径作为返回页面
let currentPath = window.location.href;
- // 如果有ID参数,也传递过去
- let videoId = '';
- try {
- // 尝试从URL中提取id参数(如果存在)
- const urlObj = new URL(url);
- videoId = urlObj.searchParams.get('id') || '';
- } catch (e) {
- // 忽略错误
- console.log('解析视频URL获取ID失败:', e);
- }
-
// 构建播放页面URL,使用watch.html作为中间跳转页
- let watchUrl = `watch.html?id=${videoId}&source=${sourceCode || ''}&url=${encodeURIComponent(url)}&index=${episodeIndex}&title=${encodeURIComponent(vod_name || '')}`;
+ let watchUrl = `watch.html?id=${vodId || ''}&source=${sourceCode || ''}&url=${encodeURIComponent(url)}&index=${episodeIndex}&title=${encodeURIComponent(vod_name || '')}`;
// 添加返回URL参数
- watchUrl += `&back=${encodeURIComponent(currentPath)}`;
+ if (currentPath.includes('index.html') || currentPath.endsWith('/')) {
+ watchUrl += `&back=${encodeURIComponent(currentPath)}`;
+ }
// 保存当前状态到localStorage
try {
@@ -1156,13 +1143,13 @@ function handlePlayerError() {
}
// 辅助函数用于渲染剧集按钮(使用当前的排序状态)
-function renderEpisodes(vodName, sourceCode) {
+function renderEpisodes(vodName, sourceCode, vodId) {
const episodes = episodesReversed ? [...currentEpisodes].reverse() : currentEpisodes;
return episodes.map((episode, index) => {
// 根据倒序状态计算真实的剧集索引
const realIndex = episodesReversed ? currentEpisodes.length - 1 - index : index;
return `
- <button id="episode-${realIndex}" onclick="playVideo('${episode}','${vodName.replace(/"/g, '&quot;')}', '${sourceCode}', ${realIndex})"
+ <button id="episode-${realIndex}" onclick="playVideo('${episode}','${vodName.replace(/"/g, '&quot;')}', '${sourceCode}', ${realIndex}, '${vodId}')"
class="px-4 py-2 bg-[#222] hover:bg-[#333] border border-[#333] rounded-lg transition-colors text-center episode-btn">
第${realIndex + 1}集
</button>
@@ -1182,16 +1169,16 @@ function copyLinks() {
}
// 切换排序状态的函数
-function toggleEpisodeOrder(sourceCode) {
+function toggleEpisodeOrder(sourceCode, vodId) {
episodesReversed = !episodesReversed;
// 重新渲染剧集区域,使用 currentVideoTitle 作为视频标题
const episodesGrid = document.getElementById('episodesGrid');
if (episodesGrid) {
- episodesGrid.innerHTML = renderEpisodes(currentVideoTitle, sourceCode);
+ episodesGrid.innerHTML = renderEpisodes(currentVideoTitle, sourceCode, vodId);
}
// 更新按钮文本和箭头方向
- const toggleBtn = document.querySelector(`button[onclick="toggleEpisodeOrder('${sourceCode}')"]`);
+ const toggleBtn = document.querySelector(`button[onclick="toggleEpisodeOrder('${sourceCode}', '${vodId}')"]`);
if (toggleBtn) {
toggleBtn.querySelector('span').textContent = episodesReversed ? '正序排列' : '倒序排列';
const arrowIcon = toggleBtn.querySelector('svg');
@@ -1355,100 +1342,6 @@ async function importConfig() {
});
}
-// 从URL导入配置
-async function importConfigFromUrl() {
- // 创建模态框元素
- let modal = document.getElementById('importUrlModal');
- if (modal) {
- document.body.removeChild(modal);
- }
-
- modal = document.createElement('div');
- modal.id = 'importUrlModal';
- modal.className = 'fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-40';
-
- modal.innerHTML = `
- <div class="bg-[#191919] rounded-lg p-6 max-w-md w-full max-h-[90vh] overflow-y-auto relative">
- <button id="closeUrlModal" class="absolute top-4 right-4 text-gray-400 hover:text-white text-xl">&times;</button>
-
- <h3 class="text-xl font-bold mb-4">从URL导入配置</h3>
-
- <div class="mb-4">
- <input type="text" id="configUrl" placeholder="输入配置文件URL"
- class="w-full px-3 py-2 bg-[#222] border border-[#333] rounded-lg text-white focus:outline-none focus:ring-1 focus:ring-blue-500">
- </div>
-
- <div class="flex justify-end space-x-2">
- <button id="confirmUrlImport" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">导入</button>
- <button id="cancelUrlImport" class="bg-[#444] hover:bg-[#555] text-white px-4 py-2 rounded">取消</button>
- </div>
- </div>`;
-
- document.body.appendChild(modal);
-
- // 关闭按钮事件
- document.getElementById('closeUrlModal').addEventListener('click', () => {
- document.body.removeChild(modal);
- });
-
- // 取消按钮事件
- document.getElementById('cancelUrlImport').addEventListener('click', () => {
- document.body.removeChild(modal);
- });
-
- // 确认导入按钮事件
- document.getElementById('confirmUrlImport').addEventListener('click', async () => {
- const url = document.getElementById('configUrl').value.trim();
- if (!url) {
- showToast('请输入配置文件URL', 'warning');
- return;
- }
-
- if (!url.startsWith('http://') && !url.startsWith('https://')) {
- showToast('URL必须以http://或https://开头', 'warning');
- return;
- }
-
- showLoading('正在从URL导入配置...');
-
- try {
- // 获取配置文件
- const response = await fetch(PROXY_URL + encodeURIComponent(url));
- if (!response.ok) throw '获取配置文件失败';
-
- const config = await response.json();
- if (config.name !== 'LibreTV-Settings') throw '配置文件格式不正确';
-
- // 验证哈希
- const dataHash = await sha256(JSON.stringify(config.data));
- if (dataHash !== config.hash) throw '配置文件哈希值不匹配';
-
- // 导入配置
- for (let item in config.data) {
- localStorage.setItem(item, config.data[item]);
- }
-
- showToast('配置文件导入成功,3 秒后自动刷新本页面。', 'success');
- setTimeout(() => {
- window.location.reload();
- }, 3000);
- } catch (error) {
- const message = typeof error === 'string' ? error : '导入配置失败';
- showToast(`从URL导入配置出错 (${message})`, 'error');
- } finally {
- hideLoading();
- document.body.removeChild(modal);
- }
- });
-
- // 点击模态框外部关闭
- modal.addEventListener('click', (e) => {
- if (e.target === modal) {
- document.body.removeChild(modal);
- }
- });
-}
-
// 配置文件导出功能
async function exportConfig() {
// 存储配置数据
diff --git a/js/player.js b/js/player.js
index 36a09a0..11ac3cf 100644
--- a/js/player.js
+++ b/js/player.js
@@ -110,7 +110,7 @@ document.addEventListener('passwordVerified', () => {
// 初始化页面内容
function initializePageContent() {
- console.log(window.location.href);
+
// 解析URL参数
const urlParams = new URLSearchParams(window.location.search);
let videoUrl = urlParams.get('url');
@@ -122,7 +122,6 @@ function initializePageContent() {
// 解决历史记录问题:检查URL是否是player.html开头的链接
// 如果是,说明这是历史记录重定向,需要解析真实的视频URL
if (videoUrl && videoUrl.includes('player.html')) {
- console.log('检测到历史记录重定向URL:', videoUrl);
try {
// 尝试从嵌套URL中提取真实的视频链接
const nestedUrlParams = new URLSearchParams(videoUrl.split('?')[1]);
@@ -135,7 +134,6 @@ function initializePageContent() {
if (nestedVideoUrl) {
videoUrl = nestedVideoUrl;
- console.log('已修正为真实视频URL:', videoUrl);
// 更新当前URL参数
const url = new URL(window.location.href);
@@ -150,13 +148,10 @@ function initializePageContent() {
}
// 替换当前URL
window.history.replaceState({}, '', url);
- console.log('从嵌套URL提取参数:', { position: nestedPosition, index: nestedIndex });
} else {
- console.warn('无法从重定向URL中提取视频链接');
showError('历史记录链接无效,请返回首页重新访问');
}
} catch (e) {
- console.error('解析嵌套URL出错:', e);
}
}
@@ -185,17 +180,15 @@ function initializePageContent() {
if (episodesList) {
// 如果URL中有集数数据,优先使用它
currentEpisodes = JSON.parse(decodeURIComponent(episodesList));
- console.log('从URL恢复集数信息:', currentEpisodes.length);
+
} else {
// 否则从localStorage获取
currentEpisodes = JSON.parse(localStorage.getItem('currentEpisodes') || '[]');
- console.log('从localStorage恢复集数信息:', currentEpisodes.length);
+
}
// 检查集数索引是否有效,如果无效则调整为0
if (index < 0 || (currentEpisodes.length > 0 && index >= currentEpisodes.length)) {
- console.warn(`无效的剧集索引 ${index},调整为范围内的值`);
-
// 如果索引太大,则使用最大有效索引
if (index >= currentEpisodes.length && currentEpisodes.length > 0) {
index = currentEpisodes.length - 1;
@@ -214,7 +207,6 @@ function initializePageContent() {
episodesReversed = localStorage.getItem('episodesReversed') === 'true';
} catch (e) {
- console.error('获取集数信息失败:', e);
currentEpisodes = [];
currentEpisodeIndex = 0;
episodesReversed = false;
@@ -402,8 +394,6 @@ function initPlayer(videoUrl) {
return
}
- console.log('初始化播放器:', videoUrl);
-
// 销毁旧实例
if (art) {
art.destroy();
@@ -480,7 +470,6 @@ function initPlayer(videoUrl) {
try {
currentHls.destroy();
} catch (e) {
- console.warn('销毁旧HLS实例出错:', e);
}
}
@@ -531,24 +520,18 @@ function initPlayer(videoUrl) {
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;
}
@@ -560,16 +543,12 @@ function initPlayer(videoUrl) {
// 如果是致命错误,且视频未播放
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:
@@ -601,10 +580,8 @@ function initPlayer(videoUrl) {
if (window.screen.orientation && window.screen.orientation.lock) {
window.screen.orientation.lock('landscape')
.then(() => {
- console.log('屏幕已锁定为横向模式');
})
.catch((error) => {
- console.warn('无法锁定屏幕方向:', error);
});
}
});
@@ -638,7 +615,6 @@ function initPlayer(videoUrl) {
}
}
} catch (e) {
- console.error('恢复播放进度失败:', e);
}
}
@@ -656,12 +632,9 @@ function initPlayer(videoUrl) {
art.on('video:error', function (error) {
// 如果正在切换视频,忽略错误
if (window.isSwitchingVideo) {
- console.log('正在切换视频,忽略错误');
return;
}
- console.error('播放器错误:', error);
-
// 隐藏所有加载指示器
const loadingElements = document.querySelectorAll('#loading, .player-loading-container');
loadingElements.forEach(el => {
@@ -682,7 +655,6 @@ function initPlayer(videoUrl) {
// 如果自动播放下一集开启,且确实有下一集
if (autoplayEnabled && currentEpisodeIndex < currentEpisodes.length - 1) {
- console.log('自动播放下一集...');
// 稍长延迟以确保所有事件处理完成
setTimeout(() => {
// 确认不是因为用户拖拽导致的假结束事件
@@ -690,7 +662,6 @@ function initPlayer(videoUrl) {
videoHasEnded = false; // 重置标志
}, 1000);
} else {
- console.log('视频播放结束,无下一集或未启用自动连播');
}
});
@@ -772,7 +743,6 @@ function filterAdsFromM3U8(m3u8Content, strictMode = false) {
function showError(message) {
// 在视频已经播放的情况下不显示错误
if (art && art.video && art.video.currentTime > 1) {
- console.log('忽略错误:', message);
return;
}
const loadingEl = document.getElementById('loading');
@@ -854,8 +824,6 @@ function renderEpisodes() {
function playEpisode(index) {
// 确保index在有效范围内
if (index < 0 || index >= currentEpisodes.length) {
- console.error(`无效的剧集索引: ${index}, 当前剧集数量: ${currentEpisodes.length}`);
- showToast(`无效的剧集索引: ${index + 1},当前剧集总数: ${currentEpisodes.length}`);
return;
}
@@ -870,14 +838,14 @@ 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>
- `;
+ // 首先隐藏之前可能显示的错误
+ 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);
@@ -983,71 +951,63 @@ function setupProgressBarPreciseClicks() {
progressBar.removeEventListener('touchstart', handleProgressBarTouch);
progressBar.addEventListener('touchstart', handleProgressBarTouch);
- console.log('进度条精确点击监听器已设置');
-}
-
-// 处理进度条点击
-function handleProgressBarClick(e) {
- if (!art || !art.video) return;
-
- // 计算点击位置相对于进度条的比例
- const rect = e.currentTarget.getBoundingClientRect();
- const percentage = (e.clientX - rect.left) / rect.width;
+ // 处理进度条点击
+ function handleProgressBarClick(e) {
+ if (!art || !art.video) return;
- // 计算点击位置对应的视频时间
- const duration = art.video.duration;
- let clickTime = percentage * duration;
+ // 计算点击位置相对于进度条的比例
+ const rect = e.currentTarget.getBoundingClientRect();
+ const percentage = (e.clientX - rect.left) / rect.width;
- // 处理视频接近结尾的情况
- if (duration - clickTime < 1) {
- // 如果点击位置非常接近结尾,稍微往前移一点
- clickTime = Math.min(clickTime, duration - 1.5);
- console.log(`进度条点击接近结尾,调整时间为 ${clickTime.toFixed(2)}/${duration.toFixed(2)}`);
- }
+ // 计算点击位置对应的视频时间
+ const duration = art.video.duration;
+ let clickTime = percentage * duration;
- // 记录用户点击的位置
- userClickedPosition = clickTime;
+ // 处理视频接近结尾的情况
+ if (duration - clickTime < 1) {
+ // 如果点击位置非常接近结尾,稍微往前移一点
+ clickTime = Math.min(clickTime, duration - 1.5);
- // 输出调试信息
- console.log(`进度条点击: ${percentage.toFixed(4)}, 时间: ${clickTime.toFixed(2)}/${duration.toFixed(2)}`);
+ }
- // 阻止默认事件传播,避免DPlayer内部逻辑将视频跳至末尾
- e.stopPropagation();
+ // 记录用户点击的位置
+ userClickedPosition = clickTime;
- // 直接设置视频时间
- art.seek(clickTime);
-}
+ // 阻止默认事件传播,避免DPlayer内部逻辑将视频跳至末尾
+ e.stopPropagation();
-// 处理移动端触摸事件
-function handleProgressBarTouch(e) {
- if (!art || !art.video || !e.touches[0]) return;
+ // 直接设置视频时间
+ art.seek(clickTime);
+ }
- const touch = e.touches[0];
- const rect = e.currentTarget.getBoundingClientRect();
- const percentage = (touch.clientX - rect.left) / rect.width;
+ // 处理移动端触摸事件
+ function handleProgressBarTouch(e) {
+ if (!art || !art.video || !e.touches[0]) return;
- const duration = art.video.duration;
- let clickTime = percentage * duration;
+ const touch = e.touches[0];
+ const rect = e.currentTarget.getBoundingClientRect();
+ const percentage = (touch.clientX - rect.left) / rect.width;
- // 处理视频接近结尾的情况
- if (duration - clickTime < 1) {
- clickTime = Math.min(clickTime, duration - 1.5);
- }
+ const duration = art.video.duration;
+ let clickTime = percentage * duration;
- // 记录用户点击的位置
- userClickedPosition = clickTime;
+ // 处理视频接近结尾的情况
+ if (duration - clickTime < 1) {
+ clickTime = Math.min(clickTime, duration - 1.5);
+ }
- console.log(`进度条触摸: ${percentage.toFixed(4)}, 时间: ${clickTime.toFixed(2)}/${duration.toFixed(2)}`);
+ // 记录用户点击的位置
+ userClickedPosition = clickTime;
- e.stopPropagation();
- art.seek(clickTime);
+ e.stopPropagation();
+ art.seek(clickTime);
+ }
}
// 在播放器初始化后添加视频到历史记录
function saveToHistory() {
// 确保 currentEpisodes 非空且有当前视频URL
if (!currentEpisodes || currentEpisodes.length === 0 || !currentVideoUrl) {
- console.warn('没有可用的剧集列表或视频URL,无法保存完整的历史记录');
return;
}
@@ -1055,6 +1015,7 @@ function saveToHistory() {
const urlParams = new URLSearchParams(window.location.search);
const sourceName = urlParams.get('source') || '';
const sourceCode = urlParams.get('source_code') || '';
+ const id_from_params = urlParams.get('id'); // Get video ID from player URL (passed as 'id')
// 获取当前播放进度
let currentPosition = 0;
@@ -1065,58 +1026,72 @@ function saveToHistory() {
videoDuration = art.video.duration;
}
+ // Define a show identifier: Prioritize sourceName_id, fallback to first episode URL or current video URL
+ let show_identifier_for_video_info;
+ if (sourceName && id_from_params) {
+ show_identifier_for_video_info = `${sourceName}_${id_from_params}`;
+ } else {
+ show_identifier_for_video_info = (currentEpisodes && currentEpisodes.length > 0) ? currentEpisodes[0] : currentVideoUrl;
+ }
+
// 构建要保存的视频信息对象
const videoInfo = {
title: currentVideoTitle,
- // 直接保存原始视频链接,而非播放页面链接
- directVideoUrl: currentVideoUrl,
- // 完整的播放器URL
- url: `player.html?url=${encodeURIComponent(currentVideoUrl)}&title=${encodeURIComponent(currentVideoTitle)}&source=${encodeURIComponent(sourceName)}&source_code=${encodeURIComponent(sourceCode)}&index=${currentEpisodeIndex}&position=${Math.floor(currentPosition || 0)}`,
+ directVideoUrl: currentVideoUrl, // Current episode's direct URL
+ url: `player.html?url=${encodeURIComponent(currentVideoUrl)}&title=${encodeURIComponent(currentVideoTitle)}&source=${encodeURIComponent(sourceName)}&source_code=${encodeURIComponent(sourceCode)}&id=${encodeURIComponent(id_from_params || '')}&index=${currentEpisodeIndex}&position=${Math.floor(currentPosition || 0)}`,
episodeIndex: currentEpisodeIndex,
sourceName: sourceName,
+ vod_id: id_from_params || '', // Store the ID from params as vod_id in history item
+ sourceCode: sourceCode,
+ showIdentifier: show_identifier_for_video_info, // Identifier for the show/series
timestamp: Date.now(),
- // 添加播放进度信息
playbackPosition: currentPosition,
duration: videoDuration,
- // 重要:保存完整的集数列表,确保进行深拷贝
episodes: currentEpisodes && currentEpisodes.length > 0 ? [...currentEpisodes] : []
};
-
+
try {
- // 获取现有历史记录
const history = JSON.parse(localStorage.getItem('viewingHistory') || '[]');
- // 检查是否已经存在相同标题的记录(同一视频的不同集数)
- const existingIndex = history.findIndex(item => item.title === videoInfo.title);
+ // 检查是否已经存在相同的系列记录 (基于标题、来源和 showIdentifier)
+ const existingIndex = history.findIndex(item =>
+ item.title === videoInfo.title &&
+ item.sourceName === videoInfo.sourceName &&
+ item.showIdentifier === videoInfo.showIdentifier
+ );
+
if (existingIndex !== -1) {
- // 存在则更新现有记录的集数、时间戳和URL
- history[existingIndex].episodeIndex = currentEpisodeIndex;
- history[existingIndex].timestamp = Date.now();
- history[existingIndex].sourceName = sourceName;
- // 更新原始视频URL
- history[existingIndex].directVideoUrl = currentVideoUrl;
+ // 存在则更新现有记录的当前集数、时间戳、播放进度和URL等
+ const existingItem = history[existingIndex];
+ existingItem.episodeIndex = videoInfo.episodeIndex;
+ existingItem.timestamp = videoInfo.timestamp;
+ existingItem.sourceName = videoInfo.sourceName; // Should be consistent, but update just in case
+ existingItem.sourceCode = videoInfo.sourceCode;
+ existingItem.vod_id = videoInfo.vod_id;
+
+ // Update URLs to reflect the current episode being watched
+ existingItem.directVideoUrl = videoInfo.directVideoUrl; // Current episode's direct URL
+ existingItem.url = videoInfo.url; // Player link for the current episode
+
// 更新播放进度信息
- history[existingIndex].playbackPosition = currentPosition > 10 ? currentPosition : history[existingIndex].playbackPosition;
- history[existingIndex].duration = videoDuration || history[existingIndex].duration;
- // 更新完整URL,确保带有正确的视频链接
- history[existingIndex].url = videoInfo.url;
- // 更新集数列表(如果有且与当前不同)
- if (currentEpisodes && currentEpisodes.length > 0) {
- // 检查是否需要更新集数数据(针对不同长度的集数列表)
- if (!history[existingIndex].episodes ||
- !Array.isArray(history[existingIndex].episodes) ||
- history[existingIndex].episodes.length !== currentEpisodes.length) {
- history[existingIndex].episodes = [...currentEpisodes]; // 深拷贝
- console.log(`更新 "${currentVideoTitle}" 的剧集数据: ${currentEpisodes.length}集`);
+ existingItem.playbackPosition = videoInfo.playbackPosition > 10 ? videoInfo.playbackPosition : (existingItem.playbackPosition || 0);
+ existingItem.duration = videoInfo.duration || existingItem.duration;
+
+ // 更新集数列表(如果新的集数列表与存储的不同,例如集数增加了)
+ if (videoInfo.episodes && videoInfo.episodes.length > 0) {
+ if (!existingItem.episodes ||
+ !Array.isArray(existingItem.episodes) ||
+ existingItem.episodes.length !== videoInfo.episodes.length ||
+ !videoInfo.episodes.every((ep, i) => ep === existingItem.episodes[i])) { // Basic check for content change
+ existingItem.episodes = [...videoInfo.episodes]; // Deep copy
}
}
-
+
// 移到最前面
const updatedItem = history.splice(existingIndex, 1)[0];
history.unshift(updatedItem);
} else {
// 添加新记录到最前面
- console.log(`创建新的历史记录: "${currentVideoTitle}", ${currentEpisodes.length}集`);
history.unshift(videoInfo);
}
@@ -1124,9 +1099,7 @@ function saveToHistory() {
if (history.length > 50) history.splice(50);
localStorage.setItem('viewingHistory', JSON.stringify(history));
- console.log('成功保存历史记录');
} catch (e) {
- console.error('保存观看历史失败:', e);
}
}
@@ -1148,7 +1121,6 @@ function showPositionRestoreHint(position) {
if (playerContainer) { // Check if playerContainer exists
playerContainer.appendChild(hint);
} else {
- console.warn("Player container not found for position hint.");
return; // Exit if container not found
}
@@ -1187,7 +1159,6 @@ function startProgressSaveInterval() {
// 保存当前播放进度
function saveCurrentProgress() {
- console.log('保存当前播放进度');
if (!art || !art.video) return;
const currentTime = art.video.currentTime;
const duration = art.video.duration;
@@ -1226,10 +1197,8 @@ function saveCurrentProgress() {
}
}
} catch (e) {
- console.log('同步更新 viewingHistory 中的进度失败', e);
}
} catch (e) {
- console.error('保存播放进度失败', e);
}
}
@@ -1353,9 +1322,7 @@ function clearVideoProgress() {
const progressKey = `videoProgress_${getVideoId()}`;
try {
localStorage.removeItem(progressKey);
- console.log('已清除播放进度记录');
} catch (e) {
- console.error('清除播放进度记录失败', e);
}
}
@@ -1395,4 +1362,4 @@ function closeEmbeddedPlayer() {
console.error('尝试关闭嵌入式播放器失败:', e);
}
return false;
-}
\ No newline at end of file
+}
diff --git a/js/ui.js b/js/ui.js
index 4429ddd..7ad0b18 100644
--- a/js/ui.js
+++ b/js/ui.js
@@ -482,104 +482,150 @@ function deleteHistoryItem(encodedUrl) {
}
// 从历史记录播放
-function playFromHistory(url, title, episodeIndex, playbackPosition = 0) {
+async function playFromHistory(url, title, episodeIndex, playbackPosition = 0) {
+ // console.log('[playFromHistory in ui.js] Called with:', { url, title, episodeIndex, playbackPosition }); // Log 1
try {
- // 尝试从localStorage获取当前视频的集数信息
let episodesList = [];
-
- // 检查viewingHistory,查找匹配的项以获取其集数数据
+ let historyItem = null; // To store the full history item
+
+ // 检查viewingHistory,查找匹配的项
const historyRaw = localStorage.getItem('viewingHistory');
if (historyRaw) {
const history = JSON.parse(historyRaw);
- // 根据标题查找匹配的历史记录
- const historyItem = history.find(item => item.title === title);
-
- // 如果找到了匹配的历史记录,尝试获取该条目的集数数据
+ historyItem = history.find(item => item.url === url);
+ // console.log('[playFromHistory in ui.js] Found historyItem:', historyItem ? JSON.parse(JSON.stringify(historyItem)) : null); // Log 2 (stringify/parse for deep copy)
+ if (historyItem) {
+ // console.log('[playFromHistory in ui.js] historyItem.vod_id:', historyItem.vod_id, 'historyItem.sourceName:', historyItem.sourceName); // Log 3
+ }
+
if (historyItem && historyItem.episodes && Array.isArray(historyItem.episodes)) {
- episodesList = historyItem.episodes;
- console.log(`从历史记录找到视频 ${title} 的集数数据:`, episodesList.length);
+ episodesList = historyItem.episodes; // Default to stored episodes
+ // console.log(`从历史记录找到视频 "${title}" 的集数数据 (默认):`, episodesList.length);
}
}
-
+
+ // Attempt to fetch fresh episode list if we have the necessary info
+ if (historyItem && historyItem.vod_id && historyItem.sourceName) {
+ // console.log(`[playFromHistory in ui.js] Attempting to fetch details for vod_id: ${historyItem.vod_id}, sourceName: ${historyItem.sourceName}`); // Log 4
+ try {
+ // Construct the API URL for detail fetching
+ // historyItem.sourceName is used as the sourceCode here
+ // Add a cache buster timestamp
+ const timestamp = new Date().getTime();
+ const apiUrl = `/api/detail?id=${encodeURIComponent(historyItem.vod_id)}&source=${encodeURIComponent(historyItem.sourceName)}&_t=${timestamp}`;
+
+ const response = await fetch(apiUrl);
+ if (!response.ok) {
+ throw new Error(`API request failed with status ${response.status}`);
+ }
+ const videoDetails = await response.json();
+
+ if (videoDetails && videoDetails.episodes && videoDetails.episodes.length > 0) {
+ episodesList = videoDetails.episodes;
+ // console.log(`成功获取 "${title}" 最新剧集列表:`, episodesList.length, "集");
+ // Optionally, update the history item in localStorage with the fresh episodes
+ if (historyItem) {
+ historyItem.episodes = [...episodesList]; // Deep copy
+ const history = JSON.parse(historyRaw); // Re-parse to ensure we have the latest version
+ const idx = history.findIndex(item => item.url === url);
+ if (idx !== -1) {
+ history[idx] = { ...history[idx], ...historyItem }; // Merge, ensuring other properties are kept
+ localStorage.setItem('viewingHistory', JSON.stringify(history));
+ // console.log("观看历史中的剧集列表已更新。");
+ }
+ }
+ } else {
+ // console.log(`未能获取 "${title}" 的最新剧集列表,或列表为空。将使用已存储的剧集。`);
+ }
+ } catch (fetchError) {
+ // console.error(`获取 "${title}" 最新剧集列表失败:`, fetchError, "将使用已存储的剧集。");
+ }
+ } else if (historyItem) {
+ // console.log(`历史记录项 "${title}" 缺少 vod_id 或 sourceName,无法刷新剧集列表。将使用已存储的剧集。`);
+ }
+
+
// 如果在历史记录中没找到,尝试使用上一个会话的集数数据
if (episodesList.length === 0) {
try {
const storedEpisodes = JSON.parse(localStorage.getItem('currentEpisodes') || '[]');
if (storedEpisodes.length > 0) {
episodesList = storedEpisodes;
- console.log(`使用localStorage中的集数数据:`, episodesList.length);
+ // console.log(`使用localStorage中的集数数据:`, episodesList.length);
}
} catch (e) {
- console.error('解析currentEpisodes失败:', e);
+ // console.error('解析currentEpisodes失败:', e);
}
}
-
- // 将剧集列表保存到localStorage,避免过长的URL
+
+ // 将剧集列表保存到localStorage,播放器页面会读取它
if (episodesList.length > 0) {
localStorage.setItem('currentEpisodes', JSON.stringify(episodesList));
- console.log(`已将剧集列表保存到localStorage,共 ${episodesList.length} 集`);
+ // console.log(`已将剧集列表保存到localStorage,共 ${episodesList.length} 集`);
}
-
+
// 保存当前页面URL作为返回地址
- // 优先使用 location.origin + location.pathname + location.search,避免 hash 干扰
let currentPath;
if (window.location.pathname.startsWith('/player.html') || window.location.pathname.startsWith('/watch.html')) {
- // 如果当前在 player/watch 页面,优先取 localStorage.lastPageUrl 或回退到首页
currentPath = localStorage.getItem('lastPageUrl') || '/';
} else {
currentPath = window.location.origin + window.location.pathname + window.location.search;
}
localStorage.setItem('lastPageUrl', currentPath);
-
+
// 构造播放器URL
let playerUrl;
-
- // 检查URL是否是嵌套的player.html链接
+ const sourceNameForUrl = historyItem ? historyItem.sourceName : (new URLSearchParams(new URL(url, window.location.origin).search)).get('source');
+ const sourceCodeForUrl = historyItem ? historyItem.sourceCode || historyItem.sourceName : (new URLSearchParams(new URL(url, window.location.origin).search)).get('source_code');
+ const idForUrl = historyItem ? historyItem.vod_id : '';
+
+
if (url.includes('player.html') || url.includes('watch.html')) {
- console.log('检测到嵌套播放链接,解析真实URL');
+ // console.log('检测到嵌套播放链接,解析真实URL');
try {
const nestedUrl = new URL(url, window.location.origin);
const nestedParams = nestedUrl.searchParams;
const realVideoUrl = nestedParams.get('url') || url;
-
- // 构造更干净的播放链接
+
playerUrl = `player.html?url=${encodeURIComponent(realVideoUrl)}&title=${encodeURIComponent(title)}&index=${episodeIndex}&position=${Math.floor(playbackPosition || 0)}&returnUrl=${encodeURIComponent(currentPath)}`;
-
- // 如果有source和source_code,也添加
- const source = nestedParams.get('source');
- const sourceCode = nestedParams.get('source_code');
- if (source) playerUrl += `&source=${encodeURIComponent(source)}`;
- if (sourceCode) playerUrl += `&source_code=${encodeURIComponent(sourceCode)}`;
+ if (sourceNameForUrl) playerUrl += `&source=${encodeURIComponent(sourceNameForUrl)}`;
+ if (sourceCodeForUrl) playerUrl += `&source_code=${encodeURIComponent(sourceCodeForUrl)}`;
+ if (idForUrl) playerUrl += `&id=${encodeURIComponent(idForUrl)}`;
+
+
} catch (e) {
- console.error('解析嵌套URL出错:', e);
- // fallback到简单URL
+ // console.error('解析嵌套URL出错:', e);
playerUrl = `player.html?url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}&index=${episodeIndex}&position=${Math.floor(playbackPosition || 0)}&returnUrl=${encodeURIComponent(currentPath)}`;
+ if (sourceNameForUrl) playerUrl += `&source=${encodeURIComponent(sourceNameForUrl)}`;
+ if (sourceCodeForUrl) playerUrl += `&source_code=${encodeURIComponent(sourceCodeForUrl)}`;
+ if (idForUrl) playerUrl += `&id=${encodeURIComponent(idForUrl)}`;
}
- } else if (url.includes('?')) {
- // URL已有参数,添加索引和位置参数
+ } else {
+ // This case should ideally not happen if 'url' is always a player.html link from history
+ // console.warn("Playing from history with a non-player.html URL structure. This might be an issue.");
const playUrl = new URL(url, window.location.origin);
if (!playUrl.searchParams.has('index') && episodeIndex > 0) {
playUrl.searchParams.set('index', episodeIndex);
}
playUrl.searchParams.set('position', Math.floor(playbackPosition || 0).toString());
- // 添加返回URL
playUrl.searchParams.set('returnUrl', encodeURIComponent(currentPath));
+ if (sourceNameForUrl) playUrl.searchParams.set('source', sourceNameForUrl);
+ if (sourceCodeForUrl) playUrl.searchParams.set('source_code', sourceCodeForUrl);
+ if (idForUrl) playUrl.searchParams.set('id', idForUrl);
playerUrl = playUrl.toString();
- } else {
- // 原始URL,构造player页面链接
- playerUrl = `player.html?url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}&index=${episodeIndex}&position=${Math.floor(playbackPosition || 0)}&returnUrl=${encodeURIComponent(currentPath)}`;
}
showVideoPlayer(playerUrl);
} catch (e) {
- console.error('从历史记录播放失败:', e);
- // 回退到原始简单URL
+ // console.error('从历史记录播放失败:', e);
const simpleUrl = `player.html?url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}&index=${episodeIndex}`;
showVideoPlayer(simpleUrl);
}
}
// 添加观看历史 - 确保每个视频标题只有一条记录
+// IMPORTANT: videoInfo passed to this function should include a 'showIdentifier' property
+// (ideally `${sourceName}_${vod_id}`), 'sourceName', and 'vod_id'.
function addToViewingHistory(videoInfo) {
// 密码保护校验
if (window.isPasswordProtected && window.isPasswordVerified) {
@@ -590,61 +636,65 @@ function addToViewingHistory(videoInfo) {
}
try {
const history = getViewingHistory();
+
+ // Ensure videoInfo has a showIdentifier
+ if (!videoInfo.showIdentifier) {
+ if (videoInfo.sourceName && videoInfo.vod_id) {
+ videoInfo.showIdentifier = `${videoInfo.sourceName}_${videoInfo.vod_id}`;
+ } else {
+ // Fallback if critical IDs are missing for the preferred identifier
+ videoInfo.showIdentifier = (videoInfo.episodes && videoInfo.episodes.length > 0) ? videoInfo.episodes[0] : videoInfo.directVideoUrl;
+ // console.warn(`addToViewingHistory: videoInfo for "${videoInfo.title}" was missing sourceName or vod_id for preferred showIdentifier. Generated fallback: ${videoInfo.showIdentifier}`);
+ }
+ }
- // 检查是否已经存在相同标题的记录(同一视频的不同集数)
- const existingIndex = history.findIndex(item => item.title === videoInfo.title);
+ const existingIndex = history.findIndex(item =>
+ item.title === videoInfo.title &&
+ item.sourceName === videoInfo.sourceName &&
+ item.showIdentifier === videoInfo.showIdentifier // Strict check using the determined showIdentifier
+ );
+
if (existingIndex !== -1) {
- // 存在则更新现有记录的集数和时间戳
+ // Exact match with showIdentifier: Update existing series entry
const existingItem = history[existingIndex];
existingItem.episodeIndex = videoInfo.episodeIndex;
existingItem.timestamp = Date.now();
-
- // 确保来源信息保留
- if (videoInfo.sourceName && !existingItem.sourceName) {
- existingItem.sourceName = videoInfo.sourceName;
- }
-
- // 更新播放进度信息,仅当新进度有效且大于10秒时
- if (videoInfo.playbackPosition && videoInfo.playbackPosition > 10) {
- existingItem.playbackPosition = videoInfo.playbackPosition;
- existingItem.duration = videoInfo.duration || existingItem.duration;
- }
-
- // 更新URL,确保能够跳转到正确的集数
- existingItem.url = videoInfo.url;
-
- // 重要:确保episodes数据与当前视频匹配
- // 只有当videoInfo中包含有效的episodes数据时才更新
+ existingItem.sourceName = videoInfo.sourceName || existingItem.sourceName;
+ existingItem.sourceCode = videoInfo.sourceCode || existingItem.sourceCode;
+ existingItem.vod_id = videoInfo.vod_id || existingItem.vod_id;
+ existingItem.directVideoUrl = videoInfo.directVideoUrl || existingItem.directVideoUrl;
+ existingItem.url = videoInfo.url || existingItem.url;
+ existingItem.playbackPosition = videoInfo.playbackPosition > 10 ? videoInfo.playbackPosition : (existingItem.playbackPosition || 0);
+ existingItem.duration = videoInfo.duration || existingItem.duration;
+
if (videoInfo.episodes && Array.isArray(videoInfo.episodes) && videoInfo.episodes.length > 0) {
- // 如果传入的集数数据与当前保存的不同,则更新
if (!existingItem.episodes ||
!Array.isArray(existingItem.episodes) ||
- existingItem.episodes.length !== videoInfo.episodes.length) {
- console.log(`更新 "${videoInfo.title}" 的剧集数据: ${videoInfo.episodes.length}集`);
- existingItem.episodes = [...videoInfo.episodes]; // 使用深拷贝
+ existingItem.episodes.length !== videoInfo.episodes.length ||
+ !videoInfo.episodes.every((ep, i) => ep === existingItem.episodes[i])) {
+ existingItem.episodes = [...videoInfo.episodes];
+ // console.log(`更新 (addToViewingHistory) "${videoInfo.title}" 的剧集数据: ${videoInfo.episodes.length}集`);
}
}
- // 移到最前面
history.splice(existingIndex, 1);
history.unshift(existingItem);
+ // console.log(`更新历史记录 (addToViewingHistory): "${videoInfo.title}", 第 ${videoInfo.episodeIndex !== undefined ? videoInfo.episodeIndex + 1 : 'N/A'} 集`);
} else {
- // 添加新记录到最前面,确保包含剧集数据
+ // No exact match: Add as a new entry
const newItem = {
- ...videoInfo,
+ ...videoInfo, // Includes the showIdentifier we ensured is present
timestamp: Date.now()
};
- // 确保episodes字段是一个数组
if (videoInfo.episodes && Array.isArray(videoInfo.episodes)) {
- newItem.episodes = [...videoInfo.episodes]; // 使用深拷贝
- console.log(`保存新视频 "${videoInfo.title}" 的剧集数据: ${videoInfo.episodes.length}集`);
+ newItem.episodes = [...videoInfo.episodes];
} else {
- // 如果没有提供episodes,初始化为空数组
newItem.episodes = [];
}
history.unshift(newItem);
+ // console.log(`创建新的历史记录 (addToViewingHistory): "${videoInfo.title}", Episode: ${videoInfo.episodeIndex !== undefined ? videoInfo.episodeIndex + 1 : 'N/A'}`);
}
// 限制历史记录数量为50条
@@ -656,7 +706,7 @@ function addToViewingHistory(videoInfo) {
// 保存到本地存储
localStorage.setItem('viewingHistory', JSON.stringify(history));
} catch (e) {
- console.error('保存观看历史失败:', e);
+ // console.error('保存观看历史失败:', e);
}
}
@@ -667,7 +717,7 @@ function clearViewingHistory() {
loadViewingHistory(); // 重新加载空的历史记录
showToast('观看历史已清空', 'success');
} catch (e) {
- console.error('清除观看历史失败:', e);
+ // console.error('清除观看历史失败:', e);
showToast('清除观看历史失败', 'error');
}
}
diff --git a/js/watch.js b/js/watch.js
index 0dfddf9..ae7b4ad 100644
--- a/js/watch.js
+++ b/js/watch.js
@@ -72,12 +72,6 @@ window.onload = function() {
localStorage.setItem('searchPageUrl', returnUrl);
}
- // 这是调试代码,可以帮助识别问题,可选择保留或删除
- console.log('传递给player.html的参数:');
- playerUrlObj.searchParams.forEach((value, key) => {
- console.log(`- ${key}: ${value}`);
- });
-
// 获取最终的URL字符串
const finalPlayerUrl = playerUrlObj.toString();