Skip to content

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

feat: Add initial implementation of LibreTV platform with video search and playback features

developer66d988ebe942
diff --git a/css/styles.css b/css/styles.css
new file mode 100644
index 0000000..538ca9d
--- /dev/null
+++ b/css/styles.css
@@ -0,0 +1,76 @@
+.page-bg {
+ background: #000;
+ min-height: 100vh;
+ background-image:
+ radial-gradient(circle at 25px 25px, rgba(255, 255, 255, 0.2) 2%, transparent 0%),
+ radial-gradient(circle at 75px 75px, rgba(255, 255, 255, 0.2) 2%, transparent 0%);
+ background-size: 100px 100px;
+}
+
+.card-hover {
+ transition: all 0.3s ease;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+}
+
+.card-hover:hover {
+ border-color: rgba(255, 255, 255, 0.5);
+ transform: translateY(-2px);
+}
+
+.gradient-text {
+ background: linear-gradient(to right, #fff, #999);
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+}
+
+.settings-panel {
+ transform: translateX(100%);
+ transition: transform 0.3s ease;
+}
+
+.settings-panel.show {
+ transform: translateX(0);
+}
+
+/* 自定义滚动条样式 */
+::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+}
+
+::-webkit-scrollbar-track {
+ background: #111;
+ border-radius: 4px;
+}
+
+::-webkit-scrollbar-thumb {
+ background: #333;
+ border-radius: 4px;
+ transition: all 0.3s ease;
+}
+
+::-webkit-scrollbar-thumb:hover {
+ background: #444;
+}
+
+/* Firefox 滚动条样式 */
+* {
+ scrollbar-width: thin;
+ scrollbar-color: #333 #111;
+}
+
+/* 最近搜索记录标签样式 */
+.search-tag {
+ background-color: #222;
+ color: #fff;
+ padding: 0.5rem 1rem;
+ border-radius: 0.5rem;
+ font-size: 0.875rem;
+ transition: all 0.3s ease;
+ border: 1px solid #333;
+}
+
+.search-tag:hover {
+ background-color: #333;
+ border-color: #555;
+}
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..4060769
--- /dev/null
+++ b/index.html
@@ -0,0 +1,182 @@
+<!DOCTYPE html>
+<html lang="zh">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>LibreTV - 免费在线视频搜索与观看平台</title>
+ <meta name="description" content="LibreTV是一个免费的在线视频搜索平台,提供来自多个视频源的内容搜索与观看服务,无需注册即可使用。">
+ <meta name="keywords" content="在线视频,免费视频,视频搜索,电影,电视剧,LibreTV">
+ <meta name="author" content="LibreTV Team">
+ <meta name="robots" content="index, follow">
+
+ <!-- Open Graph / Facebook -->
+ <meta property="og:type" content="website">
+ <meta property="og:url" content="https://libretv.is-an.org/">
+ <meta property="og:title" content="LibreTV - 免费在线视频搜索与观看平台">
+ <meta property="og:description" content="搜索并观看来自多个视频源的内容,支持多种设备,无需注册即可使用。">
+ <meta property="og:image" content="https://images.icon-icons.com/38/PNG/512/retrotv_5520.png">
+
+ <!-- Twitter -->
+ <meta property="twitter:card" content="summary_large_image">
+ <meta property="twitter:url" content="https://libretv.is-an.org/">
+ <meta property="twitter:title" content="LibreTV - 免费在线视频搜索与观看平台">
+ <meta property="twitter:description" content="搜索并观看来自多个视频源的内容,支持多种设备,无需注册即可使用。">
+ <meta property="twitter:image" content="https://images.icon-icons.com/38/PNG/512/retrotv_5520.png">
+
+ <!-- Favicon -->
+ <link rel="icon" href="https://images.icon-icons.com/38/PNG/512/retrotv_5520.png">
+ <link rel="apple-touch-icon" href="https://images.icon-icons.com/38/PNG/512/retrotv_5520.png">
+
+ <!-- Canonical URL -->
+ <link rel="canonical" href="https://libretv.is-an.org/">
+
+ <script src="https://cdn.tailwindcss.com"></script>
+ <link rel="stylesheet" href="css/styles.css">
+</head>
+<body class="page-bg text-white">
+ <div class="fixed top-4 right-4 z-50 flex items-center space-x-4">
+ <button onclick="toggleSettings(event)" class="bg-[#222] hover:bg-[#333] border border-[#333] hover:border-white rounded-lg px-4 py-2 transition-colors" aria-label="打开设置">
+ <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
+ </svg>
+ </button>
+ </div>
+
+ <!-- 设置面板 -->
+ <div id="settingsPanel" class="settings-panel fixed right-0 top-0 h-full w-80 bg-[#111] border-l border-[#333] p-6 z-40" aria-label="设置面板" aria-hidden="true">
+ <div class="flex justify-between items-center mb-6">
+ <h3 class="text-xl font-bold gradient-text">设置</h3>
+ <button onclick="toggleSettings()" class="text-gray-400 hover:text-white" aria-label="关闭设置">&times;</button>
+ </div>
+ <div class="space-y-4">
+ <div>
+ <label class="block text-sm font-medium text-gray-400 mb-2">选择采集站点</label>
+ <select id="apiSource" class="w-full bg-[#222] border border-[#333] text-white px-3 py-2 rounded-lg focus:outline-none focus:border-white transition-colors">
+ <option value="heimuer">黑莓影视 (heimuer)</option>
+ <option value="ffzy">非凡影视 (ffzy)</option>
+ <option value="sllzy">360影视 (sllzy)</option>
+ <option value="custom">自定义接口</option>
+ </select>
+ </div>
+
+ <!-- 添加自定义接口输入框 -->
+ <div id="customApiInput" class="hidden">
+ <label class="block text-sm font-medium text-gray-400 mb-2">自定义接口地址</label>
+ <input
+ type="text"
+ id="customApiUrl"
+ class="w-full bg-[#222] border border-[#333] text-white px-3 py-2 rounded-lg focus:outline-none focus:border-white transition-colors"
+ placeholder="请输入接口地址..."
+ >
+ </div>
+
+ <div class="mt-4">
+ <p class="text-xs text-gray-500">当前站点代码:
+ <span id="currentCode" class="text-white"></span>
+ <span id="siteStatus" class="ml-2"></span>
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div class="container mx-auto px-4 py-8 flex flex-col h-screen">
+ <div class="flex-1 flex flex-col">
+ <!-- 网站标志和口号 -->
+ <header class="text-center mb-2">
+ <div class="flex justify-center items-center mb-4">
+ <svg class="w-10 h-10 mr-2" 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-5xl font-bold gradient-text">LibreTV</h1>
+ </div>
+ <p class="text-gray-400 mb-8">自由观影,畅享精彩</p>
+ </header>
+
+ <!-- 搜索区域:默认居中 -->
+ <div id="searchArea" class="flex-1 flex flex-col items-center justify-center">
+ <h2 class="text-3xl font-bold gradient-text mb-8">视频搜索</h2>
+ <div class="w-full max-w-2xl">
+ <div class="flex">
+ <input type="text"
+ id="searchInput"
+ class="w-full bg-[#111] border border-[#333] text-white px-6 py-4 rounded-l-lg focus:outline-none focus:border-white transition-colors"
+ placeholder="搜索你喜欢的视频..."
+ aria-label="视频搜索框">
+ <button onclick="search()"
+ class="px-8 py-4 bg-white text-black font-medium rounded-r-lg hover:bg-gray-200 transition-colors"
+ aria-label="搜索按钮">
+ 搜索
+ </button>
+ </div>
+
+ <!-- 添加最近搜索记录部分 -->
+ <div id="recentSearches" class="mt-4 flex flex-wrap gap-2" aria-label="最近搜索记录">
+ <!-- 这里会动态插入最近的搜索记录 -->
+ </div>
+ <!-- 添加清除历史按钮 -->
+ <div id="clearHistoryBtn" class="mt-2 text-center">
+ <button onclick="clearSearchHistory()" class="text-gray-500 text-xs hover:text-white transition-colors" aria-label="清除搜索历史">
+ 清除搜索历史
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- 搜索结果:初始隐藏 -->
+ <div id="resultsArea" class="w-full hidden">
+ <div id="results" class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- 详情模态框 -->
+ <div id="modal" class="fixed inset-0 bg-black/95 hidden flex items-center justify-center">
+ <div class="bg-[#111] p-8 rounded-lg w-11/12 max-w-4xl border border-[#333] max-h-[90vh] flex flex-col">
+ <div class="flex justify-between items-center mb-6 flex-none">
+ <h2 id="modalTitle" class="text-2xl font-bold gradient-text"></h2>
+ <button onclick="closeModal()" class="text-gray-400 hover:text-white text-2xl transition-colors">&times;</button>
+ </div>
+ <div id="modalContent" class="overflow-auto flex-1 min-h-0">
+ <div class="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- 错误提示框 -->
+ <div id="toast" class="fixed top-4 left-1/2 -translate-x-1/2 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg transform transition-all duration-300 opacity-0 -translate-y-full">
+ <p id="toastMessage"></p>
+ </div>
+
+ <!-- 添加 loading 提示框 -->
+ <div id="loading" class="fixed inset-0 bg-black/80 hidden items-center justify-center z-50">
+ <div class="bg-[#111] p-8 rounded-lg border border-[#333] flex items-center space-x-4">
+ <div class="w-8 h-8 border-4 border-white border-t-transparent rounded-full animate-spin"></div>
+ <p class="text-white text-lg">加载中...</p>
+ </div>
+ </div>
+
+ <!-- JSON-LD 结构化数据 -->
+ <script type="application/ld+json">
+ {
+ "@context": "https://schema.org",
+ "@type": "WebSite",
+ "name": "LibreTV",
+ "url": "https://libretv.is-an.org/",
+ "description": "免费在线视频搜索与观看平台",
+ "potentialAction": {
+ "@type": "SearchAction",
+ "target": "https://libretv.is-an.org/?s={search_term_string}",
+ "query-input": "required name=search_term_string"
+ }
+ }
+ </script>
+
+ <script src="js/config.js"></script>
+ <script src="js/ui.js"></script>
+ <script src="js/api.js"></script>
+ <script src="js/app.js"></script>
+</body>
+</html>
\ No newline at end of file
diff --git a/js/api.js b/js/api.js
new file mode 100644
index 0000000..2b0e60a
--- /dev/null
+++ b/js/api.js
@@ -0,0 +1,216 @@
+// 改进的API请求处理函数
+async function handleApiRequest(url) {
+ const customApi = url.searchParams.get('customApi') || '';
+ const source = url.searchParams.get('source') || 'heimuer';
+
+ try {
+ if (url.pathname === '/api/search') {
+ const searchQuery = url.searchParams.get('wd');
+ if (!searchQuery) {
+ throw new Error('缺少搜索参数');
+ }
+
+ // 验证API和source的有效性
+ if (source === 'custom' && !customApi) {
+ throw new Error('使用自定义API时必须提供API地址');
+ }
+
+ if (!API_SITES[source] && source !== 'custom') {
+ throw new Error('无效的API来源');
+ }
+
+ const apiUrl = customApi
+ ? `${customApi}${API_CONFIG.search.path}${encodeURIComponent(searchQuery)}`
+ : `${API_SITES[source].api}${API_CONFIG.search.path}${encodeURIComponent(searchQuery)}`;
+
+ // 添加超时处理
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 10000);
+
+ try {
+ const response = await fetch(PROXY_URL + encodeURIComponent(apiUrl), {
+ headers: API_CONFIG.search.headers,
+ signal: controller.signal
+ });
+
+ clearTimeout(timeoutId);
+
+ if (!response.ok) {
+ throw new Error(`API请求失败: ${response.status}`);
+ }
+
+ const data = await response.json();
+
+ // 检查JSON格式的有效性
+ if (!data || !Array.isArray(data.list)) {
+ throw new Error('API返回的数据格式无效');
+ }
+
+ return JSON.stringify({
+ code: 200,
+ list: data.list || [],
+ });
+ } catch (fetchError) {
+ clearTimeout(timeoutId);
+ throw fetchError;
+ }
+ }
+
+ if (url.pathname === '/api/detail') {
+ const id = url.searchParams.get('id');
+ if (!id) {
+ throw new Error('缺少视频ID参数');
+ }
+
+ // 验证ID格式 - 只允许数字和有限的特殊字符
+ if (!/^[\w-]+$/.test(id)) {
+ throw new Error('无效的视频ID格式');
+ }
+
+ // 验证API和source的有效性
+ if (source === 'custom' && !customApi) {
+ throw new Error('使用自定义API时必须提供API地址');
+ }
+
+ if (!API_SITES[source] && source !== 'custom') {
+ throw new Error('无效的API来源');
+ }
+
+ const detailUrl = customApi
+ ? `${customApi}${API_CONFIG.detail.path}${id}.html`
+ : `${API_SITES[source].detail}${API_CONFIG.detail.path}${id}.html`;
+
+ // 添加超时处理
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 10000);
+
+ try {
+ const response = await fetch(PROXY_URL + encodeURIComponent(detailUrl), {
+ headers: API_CONFIG.detail.headers,
+ signal: controller.signal
+ });
+
+ clearTimeout(timeoutId);
+
+ if (!response.ok) {
+ throw new Error(`详情请求失败: ${response.status}`);
+ }
+
+ const html = await response.text();
+ if (!html || html.length < 100) {
+ throw new Error('获取到的详情内容无效');
+ }
+
+ const matches = html.match(M3U8_PATTERN) || [];
+
+ // 改进的URL清理
+ const cleanUrls = matches.map(link => {
+ try {
+ // 去除各种引号和前缀
+ let cleanLink = link.replace(/^\$/, '')
+ .replace(/^["']+/, '')
+ .replace(/["']+$/, '');
+
+ // 处理可能嵌在括号中的URL
+ if (cleanLink.includes('(') && cleanLink.includes(')')) {
+ cleanLink = cleanLink.split(')')[0].split('(').pop();
+ }
+
+ // 确保链接是http或https开头
+ return (cleanLink.startsWith('http://') || cleanLink.startsWith('https://')) ? cleanLink : '';
+ } catch (e) {
+ return '';
+ }
+ }).filter(link => link); // 过滤掉空URL
+
+ return JSON.stringify({
+ code: 200,
+ episodes: cleanUrls,
+ detailUrl: detailUrl,
+ });
+ } catch (fetchError) {
+ clearTimeout(timeoutId);
+ throw fetchError;
+ }
+ }
+
+ throw new Error('未知的API路径');
+ } catch (error) {
+ console.error('API处理错误:', error);
+ return JSON.stringify({
+ code: 400,
+ msg: error.message || '请求处理失败',
+ list: [],
+ episodes: [],
+ });
+ }
+}
+
+// 拦截API请求
+(function() {
+ const originalFetch = window.fetch;
+
+ window.fetch = async function(input, init) {
+ const requestUrl = typeof input === 'string' ? new URL(input, window.location.origin) : input.url;
+
+ if (requestUrl.pathname.startsWith('/api/')) {
+ try {
+ const data = await handleApiRequest(requestUrl);
+ return new Response(data, {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Access-Control-Allow-Origin': '*',
+ },
+ });
+ } catch (error) {
+ return new Response(JSON.stringify({
+ code: 500,
+ msg: '服务器内部错误',
+ }), {
+ status: 500,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+ }
+ }
+
+ // 非API请求使用原始fetch
+ return originalFetch.apply(this, arguments);
+ };
+})();
+
+async function testSiteAvailability(source) {
+ try {
+ // 避免传递空的自定义URL
+ const apiParams = source === 'custom' && customApiUrl
+ ? '&customApi=' + encodeURIComponent(customApiUrl)
+ : source === 'custom'
+ ? '' // 如果是custom但没有URL,返回空字符串
+ : '&source=' + source;
+
+ // 如果是custom但没有URL,直接返回false
+ if (source === 'custom' && !customApiUrl) {
+ return false;
+ }
+
+ // 使用更简单的测试查询
+ const response = await fetch('/api/search?wd=test' + apiParams, {
+ // 添加超时
+ signal: AbortSignal.timeout(5000)
+ });
+
+ // 检查响应状态
+ if (!response.ok) {
+ return false;
+ }
+
+ const data = await response.json();
+
+ // 检查API响应的有效性
+ return data && data.code !== 400 && Array.isArray(data.list);
+ } catch (error) {
+ console.error('站点可用性测试失败:', error);
+ return false;
+ }
+}
diff --git a/js/app.js b/js/app.js
new file mode 100644
index 0000000..9dae85b
--- /dev/null
+++ b/js/app.js
@@ -0,0 +1,413 @@
+// 全局变量
+let currentApiSource = localStorage.getItem('currentApiSource') || 'heimuer';
+let customApiUrl = localStorage.getItem('customApiUrl') || '';
+
+// 页面初始化
+document.addEventListener('DOMContentLoaded', function() {
+ // 初始化时检查是否使用自定义接口
+ if (currentApiSource === 'custom') {
+ document.getElementById('customApiInput').classList.remove('hidden');
+ document.getElementById('customApiUrl').value = customApiUrl;
+ }
+
+ // 设置 select 的默认选中值
+ document.getElementById('apiSource').value = currentApiSource;
+
+ // 初始化显示当前站点代码
+ document.getElementById('currentCode').textContent = currentApiSource;
+
+ // 初始化显示当前站点状态(使用优化后的测试函数)
+ updateSiteStatusWithTest(currentApiSource);
+
+ // 渲染搜索历史
+ renderSearchHistory();
+
+ // 设置事件监听器
+ setupEventListeners();
+});
+
+// 带有超时和缓存的站点可用性测试
+async function updateSiteStatusWithTest(source) {
+ // 显示加载状态
+ document.getElementById('siteStatus').innerHTML = '<span class="text-gray-500">●</span> 测试中...';
+
+ // 检查缓存中是否有有效的测试结果
+ const cacheKey = `siteStatus_${source}_${customApiUrl || ''}`;
+ const cachedResult = localStorage.getItem(cacheKey);
+
+ if (cachedResult) {
+ try {
+ const { isAvailable, timestamp } = JSON.parse(cachedResult);
+ // 缓存有效期为1小时
+ if (Date.now() - timestamp < 3600000) {
+ updateSiteStatus(isAvailable);
+ return;
+ }
+ } catch (e) {
+ // 忽略解析错误,继续测试
+ console.error('缓存数据解析错误:', e);
+ }
+ }
+
+ // 使用 Promise.race 添加超时处理
+ try {
+ const timeoutPromise = new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('测试超时')), 8000)
+ );
+
+ const testPromise = testSiteAvailability(source);
+ const isAvailable = await Promise.race([testPromise, timeoutPromise]);
+
+ // 更新UI状态
+ updateSiteStatus(isAvailable);
+
+ // 缓存测试结果
+ localStorage.setItem(cacheKey, JSON.stringify({
+ isAvailable,
+ timestamp: Date.now()
+ }));
+ } catch (error) {
+ console.error('站点测试错误:', error);
+ updateSiteStatus(false);
+ }
+}
+
+// 设置事件监听器
+function setupEventListeners() {
+ // API源选择变更事件
+ document.getElementById('apiSource').addEventListener('change', async function(e) {
+ currentApiSource = e.target.value;
+ const customApiInput = document.getElementById('customApiInput');
+
+ if (currentApiSource === 'custom') {
+ customApiInput.classList.remove('hidden');
+ customApiUrl = document.getElementById('customApiUrl').value;
+ localStorage.setItem('customApiUrl', customApiUrl);
+ // 自定义接口不立即测试可用性
+ document.getElementById('siteStatus').innerHTML = '<span class="text-gray-500">●</span> 待测试';
+ } else {
+ customApiInput.classList.add('hidden');
+ // 非自定义接口立即测试可用性
+ showToast('正在测试站点可用性...', 'info');
+ updateSiteStatusWithTest(currentApiSource);
+ }
+
+ localStorage.setItem('currentApiSource', currentApiSource);
+ document.getElementById('currentCode').textContent = currentApiSource;
+
+ // 清理搜索结果并重置搜索区域
+ resetSearchArea();
+ });
+
+ // 自定义接口输入框事件
+ document.getElementById('customApiUrl').addEventListener('blur', async function(e) {
+ customApiUrl = e.target.value;
+ localStorage.setItem('customApiUrl', customApiUrl);
+
+ if (currentApiSource === 'custom' && customApiUrl) {
+ showToast('正在测试接口可用性...', 'info');
+ const isAvailable = await testSiteAvailability('custom');
+ updateSiteStatus(isAvailable);
+
+ if (!isAvailable) {
+ showToast('接口不可用,请检查地址是否正确', 'error');
+ } else {
+ showToast('接口可用', 'success');
+ }
+ }
+ });
+
+ // 回车搜索
+ document.getElementById('searchInput').addEventListener('keypress', function(e) {
+ if (e.key === 'Enter') {
+ search();
+ }
+ });
+
+ // 点击外部关闭设置面板
+ document.addEventListener('click', function(e) {
+ const panel = document.getElementById('settingsPanel');
+ const settingsButton = document.querySelector('button[onclick="toggleSettings(event)"]');
+
+ if (!panel.contains(e.target) && !settingsButton.contains(e.target) && panel.classList.contains('show')) {
+ panel.classList.remove('show');
+ }
+ });
+}
+
+// 重置搜索区域
+function resetSearchArea() {
+ // 清理搜索结果
+ document.getElementById('results').innerHTML = '';
+ document.getElementById('searchInput').value = '';
+
+ // 恢复搜索区域的样式
+ document.getElementById('searchArea').classList.add('flex-1');
+ document.getElementById('searchArea').classList.remove('mb-8');
+ document.getElementById('resultsArea').classList.add('hidden');
+}
+
+// 搜索功能
+async function search() {
+ const query = document.getElementById('searchInput').value.trim();
+
+ if (!query) {
+ showToast('请输入搜索内容', 'info');
+ return;
+ }
+
+ showLoading();
+ const apiParams = currentApiSource === 'custom'
+ ? '&customApi=' + encodeURIComponent(customApiUrl)
+ : '&source=' + currentApiSource;
+
+ try {
+ // 添加超时处理
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 15000);
+
+ const response = await fetch('/api/search?wd=' + encodeURIComponent(query) + apiParams, {
+ signal: controller.signal
+ });
+
+ clearTimeout(timeoutId);
+
+ const data = await response.json();
+
+ if (data.code === 400) {
+ showToast(data.msg || '搜索失败,请检查网络连接或更换数据源', 'error');
+ return;
+ }
+
+ // 保存搜索历史
+ saveSearchHistory(query);
+
+ // 显示结果区域,调整搜索区域
+ document.getElementById('searchArea').classList.remove('flex-1');
+ document.getElementById('searchArea').classList.add('mb-8');
+ document.getElementById('resultsArea').classList.remove('hidden');
+
+ const resultsDiv = document.getElementById('results');
+
+ if (!data.list || data.list.length === 0) {
+ resultsDiv.innerHTML = '<div class="col-span-full text-center text-gray-400 py-8">没有找到相关内容</div>';
+ return;
+ }
+
+ // 添加XSS保护,使用textContent和属性转义
+ resultsDiv.innerHTML = data.list.map(item => {
+ const safeId = item.vod_id ? item.vod_id.toString().replace(/[^\w-]/g, '') : '';
+ const safeName = (item.vod_name || '').toString()
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+
+ return `
+ <div class="card-hover bg-[#111] rounded-lg overflow-hidden cursor-pointer p-6 h-fit"
+ onclick="showDetails('${safeId}','${safeName}')">
+ <h3 class="text-xl font-semibold mb-3">${safeName}</h3>
+ <p class="text-gray-400 text-sm mb-2">${(item.type_name || '').toString().replace(/</g, '&lt;')}</p>
+ <p class="text-gray-400 text-sm">${(item.vod_remarks || '').toString().replace(/</g, '&lt;')}</p>
+ </div>
+ `;
+ }).join('');
+ } catch (error) {
+ console.error('搜索错误:', error);
+ if (error.name === 'AbortError') {
+ showToast('搜索请求超时,请检查网络连接', 'error');
+ } else {
+ showToast('搜索请求失败,请稍后重试', 'error');
+ }
+ } finally {
+ hideLoading();
+ }
+}
+
+// 显示详情
+async function showDetails(id, vod_name) {
+ if (!id) {
+ showToast('视频ID无效', 'error');
+ return;
+ }
+
+ showLoading();
+ try {
+ const apiParams = currentApiSource === 'custom'
+ ? '&customApi=' + encodeURIComponent(customApiUrl)
+ : '&source=' + currentApiSource;
+
+ // 添加超时处理
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 15000);
+
+ const response = await fetch('/api/detail?id=' + encodeURIComponent(id) + apiParams, {
+ signal: controller.signal
+ });
+
+ clearTimeout(timeoutId);
+
+ const data = await response.json();
+
+ const modal = document.getElementById('modal');
+ const modalTitle = document.getElementById('modalTitle');
+ const modalContent = document.getElementById('modalContent');
+
+ modalTitle.textContent = vod_name || '未知视频';
+
+ if (data.episodes && data.episodes.length > 0) {
+ // 安全处理集数URL
+ const safeEpisodes = data.episodes.map(url => {
+ try {
+ // 确保URL是有效的并且是http或https开头
+ return url && (url.startsWith('http://') || url.startsWith('https://'))
+ ? url.replace(/"/g, '&quot;')
+ : '';
+ } catch (e) {
+ return '';
+ }
+ }).filter(url => url); // 过滤掉空URL
+
+ if (safeEpisodes.length === 0) {
+ modalContent.innerHTML = '<p class="text-center text-gray-400 py-8">没有找到可用的播放链接</p>';
+ } else {
+ modalContent.innerHTML = `
+ <div class="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8 gap-2">
+ ${safeEpisodes.map((episode, index) => `
+ <button onclick="playVideo('${episode}','${vod_name.replace(/"/g, '&quot;')}')"
+ class="px-4 py-2 bg-[#222] hover:bg-[#333] border border-[#333] hover:border-white rounded-lg transition-colors text-center">
+ 第${index + 1}集
+ </button>
+ `).join('')}
+ </div>
+ `;
+ }
+ } else {
+ modalContent.innerHTML = '<p class="text-center text-gray-400 py-8">没有找到可播放的视频</p>';
+ }
+
+ modal.classList.remove('hidden');
+ } catch (error) {
+ console.error('获取详情错误:', error);
+ if (error.name === 'AbortError') {
+ showToast('获取详情超时,请检查网络连接', 'error');
+ } else {
+ showToast('获取详情失败,请稍后重试', 'error');
+ }
+ } finally {
+ hideLoading();
+ }
+}
+
+// 播放视频
+function playVideo(url, vod_name) {
+ if (!url) {
+ showToast('无效的视频链接', 'error');
+ return;
+ }
+
+ showLoading();
+ const modalContent = document.getElementById('modalContent');
+ const modalTitle = document.getElementById('modalTitle');
+ let episodeNumber = '1';
+
+ try {
+ // 获取当前点击的按钮中的集数
+ if (event && event.target) {
+ episodeNumber = event.target.textContent.replace(/[^0-9]/g, '') || '1';
+ }
+
+ // 安全处理URL和标题
+ const safeUrl = encodeURIComponent(url);
+ const safeTitle = vod_name ? vod_name.replace(/</g, '&lt;').replace(/>/g, '&gt;') : '未知视频';
+
+ // 更新标题显示
+ modalTitle.textContent = safeTitle + " - 第" + episodeNumber + "集";
+
+ // 先移除现有的视频播放器(如果存在)
+ const existingPlayer = modalContent.querySelector('.video-player');
+ if (existingPlayer) {
+ existingPlayer.remove();
+ }
+
+ // 当前HTML内容
+ const currentHtml = modalContent.innerHTML;
+
+ // 如果是第一次播放,保存集数列表
+ if (!modalContent.querySelector('.episodes-list')) {
+ modalContent.innerHTML = `
+ <div class="space-y-6">
+ <div class="video-player">
+ <iframe
+ src="${HOPLAYER_URL}?url=${safeUrl}&autoplay=true"
+ width="100%"
+ height="600"
+ frameborder="0"
+ scrolling="no"
+ allowfullscreen="true"
+ onload="hideLoading()"
+ onerror="handlePlayerError()">
+ </iframe>
+ </div>
+ <div class="episodes-list mt-6">
+ ${currentHtml}
+ </div>
+ </div>
+ `;
+ } else {
+ // 如果已经有集数列表,只更新视频播放器
+ const episodesList = modalContent.querySelector('.episodes-list');
+ if (episodesList) {
+ modalContent.innerHTML = `
+ <div class="space-y-6">
+ <div class="video-player">
+ <iframe
+ src="${HOPLAYER_URL}?url=${safeUrl}&autoplay=true"
+ width="100%"
+ height="600"
+ frameborder="0"
+ scrolling="no"
+ allowfullscreen="true"
+ onload="hideLoading()"
+ onerror="handlePlayerError()">
+ </iframe>
+ </div>
+ <div class="episodes-list mt-6">
+ ${episodesList.innerHTML}
+ </div>
+ </div>
+ `;
+ } else {
+ // 如果找不到episodes-list元素,重新创建
+ modalContent.innerHTML = `
+ <div class="space-y-6">
+ <div class="video-player">
+ <iframe
+ src="${HOPLAYER_URL}?url=${safeUrl}&autoplay=true"
+ width="100%"
+ height="600"
+ frameborder="0"
+ scrolling="no"
+ allowfullscreen="true"
+ onload="hideLoading()"
+ onerror="handlePlayerError()">
+ </iframe>
+ </div>
+ <div class="episodes-list mt-6">
+ ${currentHtml}
+ </div>
+ </div>
+ `;
+ }
+ }
+ } catch (error) {
+ console.error('播放器加载错误:', error);
+ hideLoading();
+ showToast('视频播放加载失败,请检查链接或稍后重试', 'error');
+ }
+}
+
+// 处理播放器加载错误
+function handlePlayerError() {
+ hideLoading();
+ showToast('视频播放加载失败,请尝试其他视频源', 'error');
+}
diff --git a/js/config.js b/js/config.js
new file mode 100644
index 0000000..ff9746a
--- /dev/null
+++ b/js/config.js
@@ -0,0 +1,83 @@
+// 全局常量配置
+const PROXY_URL = 'https://proxy.mengze.vip/proxy/';
+const HOPLAYER_URL = 'https://hoplayer.com/index.html';
+const SEARCH_HISTORY_KEY = 'videoSearchHistory';
+const MAX_HISTORY_ITEMS = 5;
+
+// 网站信息配置
+const SITE_CONFIG = {
+ name: 'LibreTV',
+ url: 'https://libretv.is-an.org',
+ description: '免费在线视频搜索与观看平台',
+ logo: 'https://images.icon-icons.com/38/PNG/512/retrotv_5520.png',
+ version: '1.0.0'
+};
+
+// API站点配置
+const API_SITES = {
+ heimuer: {
+ api: 'https://json.heimuer.xyz',
+ name: '黑木耳',
+ detail: 'https://heimuer.tv',
+ },
+ ffzy: {
+ api: 'http://ffzy5.tv',
+ name: '非凡影视',
+ detail: 'http://ffzy5.tv',
+ },
+ sllzy: {
+ api: 'http://360zy.com',
+ name: '360影视',
+ detail: 'http://360zy.com',
+ },
+};
+
+// 抽象API请求配置
+const API_CONFIG = {
+ search: {
+ path: '/api.php/provide/vod/?ac=list&wd=',
+ headers: {
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
+ 'Accept': 'application/json'
+ }
+ },
+ detail: {
+ path: '/index.php/vod/detail/id/',
+ headers: {
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
+ }
+ }
+};
+
+// 优化后的正则表达式模式
+const M3U8_PATTERN = /\$https?:\/\/[^"'\s]+?\.m3u8/g;
+
+// 增加视频播放相关配置
+const PLAYER_CONFIG = {
+ autoplay: true,
+ allowFullscreen: true,
+ width: '100%',
+ height: '600',
+ timeout: 15000 // 播放器加载超时时间
+};
+
+// 增加错误信息本地化
+const ERROR_MESSAGES = {
+ NETWORK_ERROR: '网络连接错误,请检查网络设置',
+ TIMEOUT_ERROR: '请求超时,服务器响应时间过长',
+ API_ERROR: 'API接口返回错误,请尝试更换数据源',
+ PLAYER_ERROR: '播放器加载失败,请尝试其他视频源',
+ UNKNOWN_ERROR: '发生未知错误,请刷新页面重试'
+};
+
+// 添加进一步安全设置
+const SECURITY_CONFIG = {
+ enableXSSProtection: true, // 是否启用XSS保护
+ sanitizeUrls: true, // 是否清理URL
+ maxQueryLength: 100, // 最大搜索长度
+ allowedApiDomains: [ // 允许的API域名
+ 'heimuer.xyz',
+ 'ffzy5.tv',
+ '360zy.com'
+ ]
+};
diff --git a/js/ui.js b/js/ui.js
new file mode 100644
index 0000000..82aff8a
--- /dev/null
+++ b/js/ui.js
@@ -0,0 +1,217 @@
+// UI相关函数
+function toggleSettings(e) {
+ // 阻止事件冒泡,防止触发document的点击事件
+ e && e.stopPropagation();
+ const panel = document.getElementById('settingsPanel');
+ panel.classList.toggle('show');
+}
+
+// 改进的Toast显示函数 - 支持队列显示多个Toast
+const toastQueue = [];
+let isShowingToast = false;
+
+function showToast(message, type = 'error') {
+ // 将新的toast添加到队列
+ toastQueue.push({ message, type });
+
+ // 如果当前没有显示中的toast,则开始显示
+ if (!isShowingToast) {
+ showNextToast();
+ }
+}
+
+function showNextToast() {
+ if (toastQueue.length === 0) {
+ isShowingToast = false;
+ return;
+ }
+
+ isShowingToast = true;
+ const { message, type } = toastQueue.shift();
+
+ const toast = document.getElementById('toast');
+ const toastMessage = document.getElementById('toastMessage');
+
+ const bgColors = {
+ 'error': 'bg-red-500',
+ 'success': 'bg-green-500',
+ 'info': 'bg-blue-500',
+ 'warning': 'bg-yellow-500'
+ };
+
+ const bgColor = bgColors[type] || bgColors.error;
+ toast.className = `fixed top-4 left-1/2 -translate-x-1/2 px-6 py-3 rounded-lg shadow-lg transform transition-all duration-300 ${bgColor} text-white`;
+ toastMessage.textContent = message;
+
+ // 显示提示
+ toast.style.opacity = '1';
+ toast.style.transform = 'translateX(-50%) translateY(0)';
+
+ // 3秒后自动隐藏
+ setTimeout(() => {
+ toast.style.opacity = '0';
+ toast.style.transform = 'translateX(-50%) translateY(-100%)';
+
+ // 等待动画完成后显示下一个toast
+ setTimeout(() => {
+ showNextToast();
+ }, 300);
+ }, 3000);
+}
+
+// 添加显示/隐藏 loading 的函数
+let loadingTimeoutId = null;
+
+function showLoading(message = '加载中...') {
+ // 清除任何现有的超时
+ if (loadingTimeoutId) {
+ clearTimeout(loadingTimeoutId);
+ }
+
+ const loading = document.getElementById('loading');
+ const messageEl = loading.querySelector('p');
+ messageEl.textContent = message;
+ loading.style.display = 'flex';
+
+ // 设置30秒后自动关闭loading,防止无限loading
+ loadingTimeoutId = setTimeout(() => {
+ hideLoading();
+ showToast('操作超时,请稍后重试', 'warning');
+ }, 30000);
+}
+
+function hideLoading() {
+ // 清除超时
+ if (loadingTimeoutId) {
+ clearTimeout(loadingTimeoutId);
+ loadingTimeoutId = null;
+ }
+
+ const loading = document.getElementById('loading');
+ loading.style.display = 'none';
+}
+
+function updateSiteStatus(isAvailable) {
+ const statusEl = document.getElementById('siteStatus');
+ if (isAvailable) {
+ statusEl.innerHTML = '<span class="text-green-500">●</span> 可用';
+ } else {
+ statusEl.innerHTML = '<span class="text-red-500">●</span> 不可用';
+ }
+}
+
+function closeModal() {
+ document.getElementById('modal').classList.add('hidden');
+ // 清除 iframe 内容
+ document.getElementById('modalContent').innerHTML = '';
+}
+
+// 获取搜索历史的增强版本 - 支持新旧格式
+function getSearchHistory() {
+ try {
+ const data = localStorage.getItem(SEARCH_HISTORY_KEY);
+ if (!data) return [];
+
+ const parsed = JSON.parse(data);
+
+ // 检查是否是数组
+ if (!Array.isArray(parsed)) return [];
+
+ // 支持旧格式(字符串数组)和新格式(对象数组)
+ return parsed.map(item => {
+ if (typeof item === 'string') {
+ return { text: item, timestamp: 0 };
+ }
+ return item;
+ }).filter(item => item && item.text);
+ } catch (e) {
+ console.error('获取搜索历史出错:', e);
+ return [];
+ }
+}
+
+// 保存搜索历史的增强版本 - 添加时间戳和最大数量限制
+function saveSearchHistory(query) {
+ if (!query || !query.trim()) return;
+
+ // 清理输入,防止XSS
+ query = query.trim().substring(0, 50).replace(/</g, '&lt;').replace(/>/g, '&gt;');
+
+ let history = getSearchHistory();
+
+ // 删除已存在的相同项
+ history = history.filter(item =>
+ typeof item === 'object' ? item.text !== query : item !== query
+ );
+
+ // 新项添加到开头,包含时间戳
+ history.unshift({
+ text: query,
+ timestamp: Date.now()
+ });
+
+ // 限制历史记录数量
+ if (history.length > MAX_HISTORY_ITEMS) {
+ history = history.slice(0, MAX_HISTORY_ITEMS);
+ }
+
+ try {
+ localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(history));
+ } catch (e) {
+ console.error('保存搜索历史失败:', e);
+ // 如果存储失败(可能是localStorage已满),尝试清理旧数据
+ try {
+ localStorage.removeItem(SEARCH_HISTORY_KEY);
+ localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(history.slice(0, 3)));
+ } catch (e2) {
+ console.error('再次保存搜索历史失败:', e2);
+ }
+ }
+
+ renderSearchHistory();
+}
+
+// 渲染最近搜索历史的增强版本
+function renderSearchHistory() {
+ const historyContainer = document.getElementById('recentSearches');
+ if (!historyContainer) return;
+
+ const history = getSearchHistory();
+
+ if (history.length === 0) {
+ historyContainer.innerHTML = '';
+ return;
+ }
+
+ historyContainer.innerHTML = '<div class="text-gray-500 w-full mb-2">最近搜索:</div>';
+
+ history.forEach(item => {
+ const tag = document.createElement('button');
+ tag.className = 'search-tag';
+ tag.textContent = item.text;
+
+ // 添加时间提示(如果有时间戳)
+ if (item.timestamp) {
+ const date = new Date(item.timestamp);
+ tag.title = `搜索于: ${date.toLocaleString()}`;
+ }
+
+ tag.onclick = function() {
+ document.getElementById('searchInput').value = item.text;
+ search();
+ };
+ historyContainer.appendChild(tag);
+ });
+}
+
+// 增加清除搜索历史功能
+function clearSearchHistory() {
+ try {
+ localStorage.removeItem(SEARCH_HISTORY_KEY);
+ renderSearchHistory();
+ showToast('搜索历史已清除', 'success');
+ } catch (e) {
+ console.error('清除搜索历史失败:', e);
+ showToast('清除搜索历史失败', 'error');
+ }
+}
diff --git a/robots.txt b/robots.txt
new file mode 100644
index 0000000..e3e2099
--- /dev/null
+++ b/robots.txt
@@ -0,0 +1,6 @@
+User-agent: *
+Allow: /
+Disallow: /js/
+Disallow: /css/
+
+Sitemap: https://libretv.is-an.org/sitemap.xml
diff --git a/sitemap.xml b/sitemap.xml
new file mode 100644
index 0000000..ca73bc5
--- /dev/null
+++ b/sitemap.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
+ <url>
+ <loc>https://libretv.is-an.org/</loc>
+ <lastmod>2023-08-01</lastmod>
+ <changefreq>weekly</changefreq>
+ <priority>1.0</priority>
+ </url>
+ <url>
+ <loc>https://libretv.is-an.org/about.html</loc>
+ <lastmod>2023-08-01</lastmod>
+ <changefreq>monthly</changefreq>
+ <priority>0.8</priority>
+ </url>
+ <url>
+ <loc>https://libretv.is-an.org/privacy.html</loc>
+ <lastmod>2023-08-01</lastmod>
+ <changefreq>monthly</changefreq>
+ <priority>0.5</priority>
+ </url>
+</urlset>