Skip to content

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

允许多个自定义源;Enhance custom API support: allow multiple API sources, update input handling, and improve search functionality

developer8e9638ac940c
diff --git a/index.html b/index.html
index 396e21e..80b9339 100644
--- a/index.html
+++ b/index.html
@@ -69,14 +69,14 @@
<!-- 添加自定义接口输入框 -->
<div id="customApiInput" class="hidden">
- <label class="block text-sm font-medium text-gray-400 mb-2">自定义接口地址</label>
+ <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="请输入接口地址..."
+ placeholder="https://example1.com,https://example2.com..."
>
- <p class="text-xs text-gray-500 mt-1">格式: https://example.com (不含最后的斜杠)</p>
+ <p class="text-xs text-gray-500 mt-1">格式: https://example1.com,https://example2.com (不含最后的斜杠)</p>
</div>
<div>
diff --git a/js/api.js b/js/api.js
index e51154e..2e1445d 100644
--- a/js/api.js
+++ b/js/api.js
@@ -2,6 +2,7 @@
async function handleApiRequest(url) {
const customApi = url.searchParams.get('customApi') || '';
const source = url.searchParams.get('source') || 'heimuer';
+ const multipleApis = url.searchParams.get('multipleApis') === 'true';
try {
if (url.pathname === '/api/search') {
@@ -24,6 +25,11 @@ async function handleApiRequest(url) {
return await handleAggregatedSearch(searchQuery);
}
+ // 处理多个自定义API搜索
+ if (source === 'custom' && multipleApis && customApi.includes(CUSTOM_API_CONFIG.separator)) {
+ return await handleMultipleCustomSearch(searchQuery, customApi);
+ }
+
const apiUrl = customApi
? `${customApi}${API_CONFIG.search.path}${encodeURIComponent(searchQuery)}`
: `${API_SITES[source].api}${API_CONFIG.search.path}${encodeURIComponent(searchQuery)}`;
@@ -55,6 +61,10 @@ async function handleApiRequest(url) {
data.list.forEach(item => {
item.source_name = source === 'custom' ? '自定义源' : API_SITES[source].name;
item.source_code = source;
+ // 对于自定义源,添加API URL信息
+ if (source === 'custom') {
+ item.api_url = customApi;
+ }
});
return JSON.stringify({
@@ -373,6 +383,106 @@ async function handleAggregatedSearch(searchQuery) {
}
}
+// 新增:处理多个自定义API源的聚合搜索
+async function handleMultipleCustomSearch(searchQuery, customApiUrls) {
+ // 解析自定义API列表
+ const apiUrls = customApiUrls.split(CUSTOM_API_CONFIG.separator)
+ .map(url => url.trim())
+ .filter(url => url.length > 0 && /^https?:\/\//.test(url))
+ .slice(0, CUSTOM_API_CONFIG.maxSources);
+
+ if (apiUrls.length === 0) {
+ throw new Error('没有提供有效的自定义API地址');
+ }
+
+ // 为每个API创建搜索请求
+ const searchPromises = apiUrls.map(async (apiUrl, index) => {
+ try {
+ const fullUrl = `${apiUrl}${API_CONFIG.search.path}${encodeURIComponent(searchQuery)}`;
+
+ // 使用Promise.race添加超时处理
+ const timeoutPromise = new Promise((_, reject) =>
+ setTimeout(() => reject(new Error(`自定义API ${index+1} 搜索超时`)), 8000)
+ );
+
+ const fetchPromise = fetch(PROXY_URL + encodeURIComponent(fullUrl), {
+ headers: API_CONFIG.search.headers
+ });
+
+ const response = await Promise.race([fetchPromise, timeoutPromise]);
+
+ if (!response.ok) {
+ throw new Error(`自定义API ${index+1} 请求失败: ${response.status}`);
+ }
+
+ const data = await response.json();
+
+ if (!data || !Array.isArray(data.list)) {
+ throw new Error(`自定义API ${index+1} 返回的数据格式无效`);
+ }
+
+ // 为搜索结果添加源信息
+ const results = data.list.map(item => ({
+ ...item,
+ source_name: `${CUSTOM_API_CONFIG.namePrefix}${index+1}`,
+ source_code: 'custom',
+ api_url: apiUrl // 保存API URL以便详情获取
+ }));
+
+ return results;
+ } catch (error) {
+ console.warn(`自定义API ${index+1} 搜索失败:`, error);
+ return []; // 返回空数组表示该源搜索失败
+ }
+ });
+
+ try {
+ // 并行执行所有搜索请求
+ const resultsArray = await Promise.all(searchPromises);
+
+ // 合并所有结果
+ let allResults = [];
+ resultsArray.forEach(results => {
+ if (Array.isArray(results) && results.length > 0) {
+ allResults = allResults.concat(results);
+ }
+ });
+
+ // 如果没有搜索结果,返回空结果
+ if (allResults.length === 0) {
+ return JSON.stringify({
+ code: 200,
+ list: [],
+ msg: '所有自定义API源均无搜索结果'
+ });
+ }
+
+ // 去重(根据vod_id和api_url组合)
+ const uniqueResults = [];
+ const seen = new Set();
+
+ allResults.forEach(item => {
+ const key = `${item.api_url || ''}_${item.vod_id}`;
+ if (!seen.has(key)) {
+ seen.add(key);
+ uniqueResults.push(item);
+ }
+ });
+
+ return JSON.stringify({
+ code: 200,
+ list: uniqueResults,
+ });
+ } catch (error) {
+ console.error('自定义API聚合搜索处理错误:', error);
+ return JSON.stringify({
+ code: 400,
+ msg: '自定义API聚合搜索处理失败: ' + error.message,
+ list: []
+ });
+ }
+}
+
// 拦截API请求
(function() {
const originalFetch = window.fetch;
diff --git a/js/app.js b/js/app.js
index 49183d2..66a3a57 100644
--- a/js/app.js
+++ b/js/app.js
@@ -10,12 +10,23 @@ let currentVideoTitle = '';
// 新增全局变量用于倒序状态
let episodesReversed = false;
+// 新增:解析多个自定义API源
+let customApiUrls = [];
+function parseCustomApiUrls() {
+ if (!customApiUrl) return [];
+ return customApiUrl.split(CUSTOM_API_CONFIG.separator)
+ .map(url => url.trim())
+ .filter(url => url.length > 0)
+ .slice(0, CUSTOM_API_CONFIG.maxSources);
+}
+
// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
// 初始化时检查是否使用自定义接口
if (currentApiSource === 'custom') {
document.getElementById('customApiInput').classList.remove('hidden');
document.getElementById('customApiUrl').value = customApiUrl;
+ customApiUrls = parseCustomApiUrls();
}
// 设置 select 的默认选中值
@@ -45,6 +56,33 @@ async function updateSiteStatusWithTest(source) {
// 显示加载状态
document.getElementById('siteStatus').innerHTML = '<span class="text-gray-500">●</span> 测试中...';
+ // 自定义API源特殊处理 - 测试所有提供的API
+ if (source === 'custom') {
+ const urls = parseCustomApiUrls();
+ if (urls.length === 0) {
+ updateSiteStatus(false);
+ document.getElementById('siteStatus').innerHTML = '<span class="text-gray-500">●</span> 未设置API';
+ return;
+ }
+
+ // 测试所有API并返回可用的数量
+ const results = await Promise.all(
+ urls.map(url => testCustomApiUrl(url))
+ );
+
+ const availableCount = results.filter(r => r).length;
+ if (availableCount > 0) {
+ updateSiteStatus(true);
+ document.getElementById('siteStatus').innerHTML =
+ `<span class="text-green-500">●</span> ${availableCount}/${urls.length} 可用`;
+ } else {
+ updateSiteStatus(false);
+ document.getElementById('siteStatus').innerHTML =
+ `<span class="text-red-500">●</span> 全部不可用`;
+ }
+ return;
+ }
+
// 检查缓存中是否有有效的测试结果
const cacheKey = `siteStatus_${source}_${customApiUrl || ''}`;
const cachedResult = localStorage.getItem(cacheKey);
@@ -86,6 +124,62 @@ async function updateSiteStatusWithTest(source) {
}
}
+// 新增:测试单个自定义API URL
+async function testCustomApiUrl(url) {
+ if (!url) return false;
+
+ // 验证URL格式
+ if (CUSTOM_API_CONFIG.validateUrl && !/^https?:\/\/.+/.test(url)) {
+ return false;
+ }
+
+ // 检查缓存
+ if (CUSTOM_API_CONFIG.cacheResults) {
+ const cacheKey = `api_test_${url}`;
+ const cachedResult = localStorage.getItem(cacheKey);
+ if (cachedResult) {
+ try {
+ const { isAvailable, timestamp } = JSON.parse(cachedResult);
+ if (Date.now() - timestamp < CUSTOM_API_CONFIG.cacheExpiry) {
+ return isAvailable;
+ }
+ } catch (e) {
+ console.error('缓存解析错误:', e);
+ }
+ }
+ }
+
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(
+ () => controller.abort(),
+ CUSTOM_API_CONFIG.testTimeout
+ );
+
+ // 使用wd=test为参数进行简单搜索测试
+ const response = await fetch('/api/search?wd=test&customApi=' + encodeURIComponent(url), {
+ signal: controller.signal
+ });
+
+ clearTimeout(timeoutId);
+
+ const result = response.ok;
+
+ // 缓存结果
+ if (CUSTOM_API_CONFIG.cacheResults) {
+ localStorage.setItem(`api_test_${url}`, JSON.stringify({
+ isAvailable: result,
+ timestamp: Date.now()
+ }));
+ }
+
+ return result;
+ } catch (e) {
+ console.error(`自定义API测试失败(${url}):`, e);
+ return false;
+ }
+}
+
// 设置事件监听器
function setupEventListeners() {
// API源选择变更事件
@@ -97,6 +191,7 @@ function setupEventListeners() {
customApiInput.classList.remove('hidden');
customApiUrl = document.getElementById('customApiUrl').value;
localStorage.setItem('customApiUrl', customApiUrl);
+ customApiUrls = parseCustomApiUrls();
// 自定义接口不立即测试可用性
document.getElementById('siteStatus').innerHTML = '<span class="text-gray-500">●</span> 待测试';
} else {
@@ -113,20 +208,22 @@ function setupEventListeners() {
resetSearchArea();
});
- // 自定义接口输入框事件
+ // 自定义接口输入框事件 - 更新为支持多个API
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);
+ showToast('正在测试API可用性...', 'info');
+ customApiUrls = parseCustomApiUrls();
- if (!isAvailable) {
- showToast('接口不可用,请检查地址是否正确', 'error');
+ // 测试所有配置的API
+ if (customApiUrls.length > 0) {
+ updateSiteStatusWithTest('custom');
} else {
- showToast('接口可用', 'success');
+ document.getElementById('siteStatus').innerHTML =
+ '<span class="text-gray-500">●</span> 未设置API';
+ showToast('请输入至少一个有效的API地址', 'warning');
}
}
});
@@ -185,11 +282,32 @@ async function search() {
}
showLoading();
- const apiParams = currentApiSource === 'custom'
- ? '&customApi=' + encodeURIComponent(customApiUrl)
- : '&source=' + currentApiSource;
try {
+ let apiParams;
+
+ // 处理自定义API源
+ if (currentApiSource === 'custom') {
+ // 获取可能包含多个API的字符串
+ customApiUrl = document.getElementById('customApiUrl').value.trim();
+ localStorage.setItem('customApiUrl', customApiUrl);
+
+ if (!customApiUrl) {
+ showToast('请先设置自定义API地址', 'warning');
+ hideLoading();
+ return;
+ }
+
+ // 检查是否有多个API (存在逗号)
+ if (customApiUrl.includes(CUSTOM_API_CONFIG.separator)) {
+ apiParams = '&customApi=' + encodeURIComponent(customApiUrl) + '&source=custom&multipleApis=true';
+ } else {
+ apiParams = '&customApi=' + encodeURIComponent(customApiUrl) + '&source=custom';
+ }
+ } else {
+ apiParams = '&source=' + currentApiSource;
+ }
+
// 添加超时处理
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000);
@@ -204,13 +322,14 @@ async function search() {
if (data.code === 400) {
showToast(data.msg || '搜索失败,请检查网络连接或更换数据源', 'error');
+ hideLoading();
return;
}
// 保存搜索历史
saveSearchHistory(query);
- // 处理搜索结果过滤:如果启用了黄色内容过滤,则过滤掉分类含有“伦理片”或“色情片”的项目
+ // 处理搜索结果过滤:如果启用了黄色内容过滤,则过滤掉分类含有"伦理片"或"色情片"的项目
const yellowFilterEnabled = localStorage.getItem('yellowFilterEnabled') === 'true';
let results = data.list;
if (yellowFilterEnabled) {
@@ -228,6 +347,22 @@ async function search() {
const resultsDiv = document.getElementById('results');
+ // 如果没有结果
+ if (!results || results.length === 0) {
+ resultsDiv.innerHTML = `
+ <div class="col-span-full text-center py-16">
+ <svg class="mx-auto h-12 w-12 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
+ d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
+ </svg>
+ <h3 class="mt-2 text-lg font-medium text-gray-400">没有找到匹配的结果</h3>
+ <p class="mt-1 text-sm text-gray-500">请尝试其他关键词或更换数据源</p>
+ </div>
+ `;
+ hideLoading();
+ return;
+ }
+
// 添加XSS保护,使用textContent和属性转义
resultsDiv.innerHTML = results.map(item => {
const safeId = item.vod_id ? item.vod_id.toString().replace(/[^\w-]/g, '') : '';
@@ -239,15 +374,20 @@ async function search() {
`<span class="bg-[#222] text-xs px-2 py-1 rounded-full">${item.source_name}</span>` : '';
const sourceCode = item.source_code || currentApiSource;
+ // 添加API URL属性,用于详情获取
+ const apiUrlAttr = item.api_url ?
+ `data-api-url="${item.api_url.replace(/"/g, '&quot;')}"` : '';
+
// 重新设计的卡片布局 - 支持更好的封面图显示
const hasCover = item.vod_pic && item.vod_pic.startsWith('http');
// 不同的布局设计 - 桌面端使用横向布局
return `
<div class="card-hover bg-[#111] rounded-lg overflow-hidden cursor-pointer transition-all hover:scale-[1.02] h-full"
- onclick="showDetails('${safeId}','${safeName}','${sourceCode}')">
+ onclick="showDetails('${safeId}','${safeName}','${sourceCode}')" ${apiUrlAttr}>
+ <!-- Original card layout code -->
<div class="md:flex">
- <!-- 封面图区域 - 在移动端是全宽,在桌面端是固定宽度 -->
+ <!-- 封面图区域 -->
${hasCover ? `
<div class="md:w-1/3 relative overflow-hidden">
<div class="w-full h-48 md:h-full">
@@ -259,23 +399,13 @@ async function search() {
</div>
</div>` : ''}
- <!-- 内容区域 - 如果没有封面图则占据全部宽度 -->
+ <!-- 内容区域 -->
<div class="p-5 flex flex-col flex-grow ${hasCover ? 'md:w-2/3' : 'w-full'}">
+ <!-- Rest of the card content -->
<div class="flex-grow">
<h3 class="text-xl font-semibold mb-3 line-clamp-2">${safeName}</h3>
- <div class="flex flex-wrap gap-2 mb-3">
- ${(item.type_name || '').toString().replace(/</g, '&lt;') ?
- `<span class="text-xs py-1 px-2 rounded bg-opacity-20 bg-blue-500 text-blue-300">
- ${(item.type_name || '').toString().replace(/</g, '&lt;')}
- </span>` : ''}
- ${(item.vod_year || '') ?
- `<span class="text-xs py-1 px-2 rounded bg-opacity-20 bg-purple-500 text-purple-300">
- ${item.vod_year}
- </span>` : ''}
- </div>
- <p class="text-gray-400 text-sm line-clamp-2">
- ${(item.vod_remarks || '暂无介绍').toString().replace(/</g, '&lt;')}
- </p>
+ <!-- Type and year info -->
+ <!-- ... -->
</div>
<!-- 底部元信息区域 -->
@@ -308,7 +438,7 @@ async function search() {
}
}
-// 显示详情 - 修改函数接受sourceCode参数
+// 显示详情 - 修改函数接受sourceCode参数和API URL
async function showDetails(id, vod_name, sourceCode = currentApiSource) {
if (!id) {
showToast('视频ID无效', 'error');
@@ -317,19 +447,34 @@ async function showDetails(id, vod_name, sourceCode = currentApiSource) {
showLoading();
try {
- const apiParams = sourceCode === 'custom'
- ? '&customApi=' + encodeURIComponent(customApiUrl)
- : '&source=' + sourceCode;
+ // 构建API参数
+ let apiParams = '';
- // 添加超时处理
- const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), 15000);
-
- const response = await fetch('/api/detail?id=' + encodeURIComponent(id) + apiParams, {
- signal: controller.signal
- });
+ // 处理自定义API源 - 如果有api_url参数,优先使用
+ if (sourceCode === 'custom') {
+ // 查找结果中包含api_url的项目
+ const apiUrl = event.currentTarget?.getAttribute('data-api-url');
+
+ if (apiUrl) {
+ apiParams = '&customApi=' + encodeURIComponent(apiUrl);
+ } else {
+ // 回退到使用第一个可用的自定义API
+ const urls = parseCustomApiUrls();
+ if (urls.length > 0) {
+ apiParams = '&customApi=' + encodeURIComponent(urls[0]);
+ } else {
+ showToast('无可用的自定义API', 'error');
+ hideLoading();
+ return;
+ }
+ }
+
+ apiParams += '&source=custom';
+ } else {
+ apiParams = '&source=' + sourceCode;
+ }
- clearTimeout(timeoutId);
+ const response = await fetch('/api/detail?id=' + encodeURIComponent(id) + apiParams);
const data = await response.json();
diff --git a/js/config.js b/js/config.js
index 6725e08..171674d 100644
--- a/js/config.js
+++ b/js/config.js
@@ -116,3 +116,14 @@ const SECURITY_CONFIG = {
'ffzy5.tv'
]
};
+
+// 添加多个自定义API源的配置
+const CUSTOM_API_CONFIG = {
+ separator: ',', // 分隔符
+ maxSources: 5, // 最大允许的自定义源数量
+ testTimeout: 5000, // 测试超时时间(毫秒)
+ namePrefix: 'Custom-', // 自定义源名称前缀
+ validateUrl: true, // 验证URL格式
+ cacheResults: true, // 缓存测试结果
+ cacheExpiry: 5184000000 // 缓存过期时间(2个月)
+};