接入tunehub

This commit is contained in:
mtvpls
2026-02-01 15:36:33 +08:00
parent 74dc91d59e
commit 19be34c6fe
7 changed files with 1548 additions and 2 deletions

View File

@@ -353,6 +353,9 @@ interface SiteConfig {
OIDCClientId?: string;
OIDCClientSecret?: string;
OIDCButtonText?: string;
TuneHubEnabled?: boolean;
TuneHubBaseUrl?: string;
TuneHubApiKey?: string;
}
// 视频源数据类型
@@ -6790,6 +6793,9 @@ const SiteConfigComponent = ({
OIDCClientId: '',
OIDCClientSecret: '',
OIDCButtonText: '',
TuneHubEnabled: false,
TuneHubBaseUrl: 'https://tunehub.sayqz.com/api',
TuneHubApiKey: '',
});
// 豆瓣数据源相关状态
@@ -7666,6 +7672,93 @@ const SiteConfigComponent = ({
</div>
</div>
{/* TuneHub 音乐配置 */}
<div className='space-y-4 pt-4 border-t border-gray-200 dark:border-gray-700'>
<h3 className='text-sm font-semibold text-gray-900 dark:text-gray-100'>
TuneHub
</h3>
{/* 开启 TuneHub */}
<div>
<div className='flex items-center justify-between'>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
</label>
<button
type='button'
onClick={() =>
setSiteSettings((prev) => ({
...prev,
TuneHubEnabled: !prev.TuneHubEnabled,
}))
}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 ${
siteSettings.TuneHubEnabled
? buttonStyles.toggleOn
: buttonStyles.toggleOff
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full ${
buttonStyles.toggleThumb
} transition-transform ${
siteSettings.TuneHubEnabled
? buttonStyles.toggleThumbOn
: buttonStyles.toggleThumbOff
}`}
/>
</button>
</div>
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
QQ音乐
</p>
</div>
{/* TuneHub Base URL */}
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
TuneHub API
</label>
<input
type='text'
placeholder='https://tunehub.sayqz.com/api'
value={siteSettings.TuneHubBaseUrl}
onChange={(e) =>
setSiteSettings((prev) => ({
...prev,
TuneHubBaseUrl: e.target.value,
}))
}
className='w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-green-500 focus:border-transparent'
/>
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
TuneHub API https://tunehub.sayqz.com/api。也可以通过环境变量 TUNEHUB_BASE_URL 配置
</p>
</div>
{/* TuneHub API Key */}
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
TuneHub API Key
</label>
<input
type='password'
placeholder='th_your_api_key_here'
value={siteSettings.TuneHubApiKey}
onChange={(e) =>
setSiteSettings((prev) => ({
...prev,
TuneHubApiKey: e.target.value,
}))
}
className='w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-green-500 focus:border-transparent'
/>
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
API Key Key TUNEHUB_API_KEY
</p>
</div>
</div>
{/* 操作按钮 */}
<div className='flex justify-end'>
<button

View File

@@ -69,6 +69,9 @@ export async function POST(request: NextRequest) {
OIDCClientSecret,
OIDCButtonText,
OIDCMinTrustLevel,
TuneHubEnabled,
TuneHubBaseUrl,
TuneHubApiKey,
} = body as {
SiteName: string;
Announcement: string;
@@ -110,6 +113,9 @@ export async function POST(request: NextRequest) {
OIDCClientSecret?: string;
OIDCButtonText?: string;
OIDCMinTrustLevel?: number;
TuneHubEnabled?: boolean;
TuneHubBaseUrl?: string;
TuneHubApiKey?: string;
};
// 参数校验
@@ -150,7 +156,10 @@ export async function POST(request: NextRequest) {
(OIDCClientId !== undefined && typeof OIDCClientId !== 'string') ||
(OIDCClientSecret !== undefined && typeof OIDCClientSecret !== 'string') ||
(OIDCButtonText !== undefined && typeof OIDCButtonText !== 'string') ||
(OIDCMinTrustLevel !== undefined && typeof OIDCMinTrustLevel !== 'number')
(OIDCMinTrustLevel !== undefined && typeof OIDCMinTrustLevel !== 'number') ||
(TuneHubEnabled !== undefined && typeof TuneHubEnabled !== 'boolean') ||
(TuneHubBaseUrl !== undefined && typeof TuneHubBaseUrl !== 'string') ||
(TuneHubApiKey !== undefined && typeof TuneHubApiKey !== 'string')
) {
return NextResponse.json({ error: '参数格式错误' }, { status: 400 });
}
@@ -207,6 +216,9 @@ export async function POST(request: NextRequest) {
OIDCClientSecret,
OIDCButtonText,
OIDCMinTrustLevel,
TuneHubEnabled,
TuneHubBaseUrl,
TuneHubApiKey,
};
// 写入数据库

343
src/app/api/music/route.ts Normal file
View File

@@ -0,0 +1,343 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { NextRequest, NextResponse } from 'next/server';
import { getConfig } from '@/lib/config';
export const runtime = 'nodejs';
// 服务器端内存缓存
const serverCache = {
methodConfigs: new Map<string, { data: any; timestamp: number }>(),
proxyRequests: new Map<string, { data: any; timestamp: number }>(),
CACHE_DURATION: 24 * 60 * 60 * 1000, // 24小时缓存
};
// 获取 TuneHub 配置
async function getTuneHubConfig() {
const config = await getConfig();
const siteConfig = config?.SiteConfig;
const enabled = siteConfig?.TuneHubEnabled ?? false;
const baseUrl =
siteConfig?.TuneHubBaseUrl ||
process.env.TUNEHUB_BASE_URL ||
'https://tunehub.sayqz.com/api';
const apiKey = siteConfig?.TuneHubApiKey || process.env.TUNEHUB_API_KEY || '';
return { enabled, baseUrl, apiKey };
}
// 通用请求处理函数
async function proxyRequest(
url: string,
options: RequestInit = {}
): Promise<Response> {
try {
const response = await fetch(url, {
...options,
headers: {
...options.headers,
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
},
});
return response;
} catch (error) {
console.error('TuneHub API 请求失败:', error);
throw error;
}
}
// GET 请求处理
export async function GET(request: NextRequest) {
try {
const { enabled, baseUrl } = await getTuneHubConfig();
if (!enabled) {
return NextResponse.json(
{ error: '音乐功能未开启' },
{ status: 403 }
);
}
const { searchParams } = new URL(request.url);
const action = searchParams.get('action');
if (!action) {
return NextResponse.json(
{ error: '缺少 action 参数' },
{ status: 400 }
);
}
// 处理不同的 action
switch (action) {
case 'methods': {
// 获取所有平台方法
const cacheKey = 'methods-all';
const cached = serverCache.methodConfigs.get(cacheKey);
if (cached && Date.now() - cached.timestamp < serverCache.CACHE_DURATION) {
console.log('使用缓存: methods');
return NextResponse.json(cached.data);
}
const response = await proxyRequest(`${baseUrl}/v1/methods`);
const data = await response.json();
serverCache.methodConfigs.set(cacheKey, {
data,
timestamp: Date.now(),
});
return NextResponse.json(data);
}
case 'platform-methods': {
// 获取指定平台的方法
const platform = searchParams.get('platform');
if (!platform) {
return NextResponse.json(
{ error: '缺少 platform 参数' },
{ status: 400 }
);
}
const cacheKey = `platform-methods-${platform}`;
const cached = serverCache.methodConfigs.get(cacheKey);
if (cached && Date.now() - cached.timestamp < serverCache.CACHE_DURATION) {
console.log(`使用缓存: platform-methods-${platform}`);
return NextResponse.json(cached.data);
}
const response = await proxyRequest(`${baseUrl}/v1/methods/${platform}`);
const data = await response.json();
serverCache.methodConfigs.set(cacheKey, {
data,
timestamp: Date.now(),
});
return NextResponse.json(data);
}
case 'method-config': {
// 获取指定平台指定方法的配置
const platform = searchParams.get('platform');
const func = searchParams.get('function');
if (!platform || !func) {
return NextResponse.json(
{ error: '缺少 platform 或 function 参数' },
{ status: 400 }
);
}
const cacheKey = `method-config-${platform}-${func}`;
const cached = serverCache.methodConfigs.get(cacheKey);
if (cached && Date.now() - cached.timestamp < serverCache.CACHE_DURATION) {
console.log(`使用缓存: method-config-${platform}-${func}`);
return NextResponse.json(cached.data);
}
const response = await proxyRequest(
`${baseUrl}/v1/methods/${platform}/${func}`
);
const data = await response.json();
serverCache.methodConfigs.set(cacheKey, {
data,
timestamp: Date.now(),
});
return NextResponse.json(data);
}
case 'proxy': {
// 代理上游平台请求(用于方法下发后的实际请求)
const targetUrl = searchParams.get('url');
if (!targetUrl) {
return NextResponse.json(
{ error: '缺少 url 参数' },
{ status: 400 }
);
}
// 使用完整 URL 作为缓存键
const cacheKey = `proxy-${targetUrl}`;
const cached = serverCache.proxyRequests.get(cacheKey);
if (cached && Date.now() - cached.timestamp < serverCache.CACHE_DURATION) {
console.log(`使用缓存: proxy request`);
return NextResponse.json(cached.data);
}
// 获取其他查询参数
const params = new URLSearchParams();
searchParams.forEach((value, key) => {
if (key !== 'action' && key !== 'url') {
params.append(key, value);
}
});
const fullUrl = params.toString()
? `${targetUrl}?${params.toString()}`
: targetUrl;
const response = await proxyRequest(fullUrl);
const data = await response.json();
serverCache.proxyRequests.set(cacheKey, {
data,
timestamp: Date.now(),
});
return NextResponse.json(data);
}
default:
return NextResponse.json(
{ error: '不支持的 action' },
{ status: 400 }
);
}
} catch (error) {
console.error('音乐 API 错误:', error);
return NextResponse.json(
{
error: '请求失败',
details: (error as Error).message,
},
{ status: 500 }
);
}
}
// POST 请求处理(用于解析歌曲)
export async function POST(request: NextRequest) {
try {
const { enabled, baseUrl, apiKey } = await getTuneHubConfig();
if (!enabled) {
return NextResponse.json(
{ error: '音乐功能未开启' },
{ status: 403 }
);
}
const body = await request.json();
const { action } = body;
if (!action) {
return NextResponse.json(
{ error: '缺少 action 参数' },
{ status: 400 }
);
}
switch (action) {
case 'parse': {
// 解析歌曲(需要 API Key
if (!apiKey) {
return NextResponse.json(
{
code: -1,
error: '未配置 TuneHub API Key',
message: '未配置 TuneHub API Key'
},
{ status: 403 }
);
}
const { platform, ids, quality } = body;
if (!platform || !ids) {
return NextResponse.json(
{
code: -1,
error: '缺少 platform 或 ids 参数',
message: '缺少 platform 或 ids 参数'
},
{ status: 400 }
);
}
try {
const response = await proxyRequest(`${baseUrl}/v1/parse`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey,
},
body: JSON.stringify({
platform,
ids,
quality: quality || '320k',
}),
});
const data = await response.json();
console.log('TuneHub 解析响应:', data);
// 如果 TuneHub 返回错误,包装成统一格式
if (!response.ok || data.code !== 0) {
return NextResponse.json({
code: data.code || -1,
message: data.message || data.error || '解析失败',
error: data.error || data.message || '解析失败',
});
}
return NextResponse.json(data);
} catch (error) {
console.error('解析歌曲失败:', error);
return NextResponse.json({
code: -1,
message: '解析请求失败',
error: (error as Error).message,
});
}
}
case 'proxy-post': {
// 代理 POST 请求到上游平台
const { url, data: postData, headers } = body;
if (!url) {
return NextResponse.json(
{ error: '缺少 url 参数' },
{ status: 400 }
);
}
const response = await proxyRequest(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(postData),
});
const responseData = await response.json();
return NextResponse.json(responseData);
}
default:
return NextResponse.json(
{ error: '不支持的 action' },
{ status: 400 }
);
}
} catch (error) {
console.error('音乐 API 错误:', error);
return NextResponse.json(
{
error: '请求失败',
details: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -86,6 +86,7 @@ export default async function RootLayout({
let enableMovieRequest = true;
let webLiveEnabled = false;
let customAdFilterVersion = 0;
let tuneHubEnabled = false;
let customCategories = [] as {
name: string;
type: 'movie' | 'tv';
@@ -134,6 +135,8 @@ export default async function RootLayout({
webLiveEnabled = config.WebLiveEnabled ?? false;
// 自定义去广告代码版本号
customAdFilterVersion = config.SiteConfig?.CustomAdFilterVersion || 0;
// TuneHub音乐功能配置
tuneHubEnabled = config.SiteConfig?.TuneHubEnabled || false;
// 检查是否启用了 OpenList 功能
openListEnabled = !!(
config.OpenListConfig?.Enabled &&
@@ -191,6 +194,7 @@ export default async function RootLayout({
ENABLE_MOVIE_REQUEST: enableMovieRequest,
WEB_LIVE_ENABLED: webLiveEnabled,
CUSTOM_AD_FILTER_VERSION: customAdFilterVersion,
TUNEHUB_ENABLED: tuneHubEnabled,
FESTIVE_EFFECT_ENABLED:
process.env.FESTIVE_EFFECT_ENABLED === 'true',
};

1069
src/app/music/page.tsx Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,7 @@
'use client';
import { Bot, ChevronRight, Link as LinkIcon, ListVideo } from 'lucide-react';
import { Bot, ChevronRight, Link as LinkIcon, ListVideo, Music } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Suspense, useEffect, useState } from 'react';
@@ -66,6 +66,7 @@ function HomeClient() {
const [aiEnabled, setAiEnabled] = useState(false);
const [aiDefaultMessageNoVideo, setAiDefaultMessageNoVideo] = useState('你好我是MoonTVPlus的AI影视助手。想看什么电影或剧集需要推荐吗');
const [sourceSearchEnabled, setSourceSearchEnabled] = useState(true);
const [musicEnabled, setMusicEnabled] = useState(false);
const [showDirectPlayDialog, setShowDirectPlayDialog] = useState(false);
const [directPlayUrl, setDirectPlayUrl] = useState('');
@@ -148,6 +149,14 @@ function HomeClient() {
}
}, []);
// 检查音乐功能是否启用
useEffect(() => {
if (typeof window !== 'undefined') {
const enabled = (window as any).RUNTIME_CONFIG?.TUNEHUB_ENABLED === true;
setMusicEnabled(enabled);
}
}, []);
// 检查公告弹窗状态
useEffect(() => {
if (typeof window !== 'undefined' && announcement) {
@@ -593,6 +602,18 @@ function HomeClient() {
<LinkIcon size={18} />
</button>
{/* 音乐视听入口 */}
{musicEnabled && (
<Link href='/music'>
<button
className='p-2 rounded-lg text-green-500 hover:text-green-600 transition-colors'
title='音乐视听'
>
<Music size={20} />
</button>
</Link>
)}
{/* 源站寻片入口 */}
{sourceSearchEnabled && (
<Link href='/source-search'>

View File

@@ -56,6 +56,10 @@ export interface AdminConfig {
OIDCClientSecret?: string; // OIDC Client Secret
OIDCButtonText?: string; // OIDC登录按钮文字
OIDCMinTrustLevel?: number; // 最低信任等级仅LinuxDo网站有效为0时不判断
// TuneHub音乐配置
TuneHubEnabled?: boolean; // 启用音乐功能
TuneHubBaseUrl?: string; // TuneHub API地址
TuneHubApiKey?: string; // TuneHub API Key
};
UserConfig: {
Users: {