音乐openlist缓存
This commit is contained in:
@@ -35,6 +35,7 @@ import {
|
||||
FolderOpen,
|
||||
Globe,
|
||||
Mail,
|
||||
Music,
|
||||
Palette,
|
||||
Settings,
|
||||
Tv,
|
||||
@@ -353,9 +354,6 @@ interface SiteConfig {
|
||||
OIDCClientId?: string;
|
||||
OIDCClientSecret?: string;
|
||||
OIDCButtonText?: string;
|
||||
TuneHubEnabled?: boolean;
|
||||
TuneHubBaseUrl?: string;
|
||||
TuneHubApiKey?: string;
|
||||
}
|
||||
|
||||
// 视频源数据类型
|
||||
@@ -6745,6 +6743,312 @@ const ThemeConfigComponent = ({
|
||||
);
|
||||
};
|
||||
|
||||
// 音乐配置组件
|
||||
const MusicConfigComponent = ({
|
||||
config,
|
||||
refreshConfig,
|
||||
}: {
|
||||
config: AdminConfig | null;
|
||||
refreshConfig: () => Promise<void>;
|
||||
}) => {
|
||||
const { alertModal, showAlert, hideAlert } = useAlertModal();
|
||||
const { isLoading, withLoading } = useLoadingState();
|
||||
|
||||
const [musicSettings, setMusicSettings] = useState({
|
||||
TuneHubEnabled: false,
|
||||
TuneHubBaseUrl: 'https://tunehub.sayqz.com/api',
|
||||
TuneHubApiKey: '',
|
||||
OpenListCacheEnabled: false,
|
||||
OpenListCacheURL: '',
|
||||
OpenListCacheUsername: '',
|
||||
OpenListCachePassword: '',
|
||||
OpenListCachePath: '/music-cache',
|
||||
});
|
||||
|
||||
// 从配置加载音乐设置
|
||||
useEffect(() => {
|
||||
if (config?.MusicConfig) {
|
||||
setMusicSettings({
|
||||
TuneHubEnabled: config.MusicConfig.TuneHubEnabled ?? false,
|
||||
TuneHubBaseUrl: config.MusicConfig.TuneHubBaseUrl ?? 'https://tunehub.sayqz.com/api',
|
||||
TuneHubApiKey: config.MusicConfig.TuneHubApiKey ?? '',
|
||||
OpenListCacheEnabled: config.MusicConfig.OpenListCacheEnabled ?? false,
|
||||
OpenListCacheURL: config.MusicConfig.OpenListCacheURL ?? '',
|
||||
OpenListCacheUsername: config.MusicConfig.OpenListCacheUsername ?? '',
|
||||
OpenListCachePassword: config.MusicConfig.OpenListCachePassword ?? '',
|
||||
OpenListCachePath: config.MusicConfig.OpenListCachePath ?? '/music-cache',
|
||||
});
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
const handleSave = async () => {
|
||||
await withLoading('saveMusicConfig', async () => {
|
||||
try {
|
||||
const resp = await fetch('/api/admin/music', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...musicSettings }),
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const data = await resp.json().catch(() => ({}));
|
||||
throw new Error(data.error || '保存失败');
|
||||
}
|
||||
|
||||
showAlert({ type: 'success', title: '保存成功', message: '音乐配置已更新', timer: 2000 });
|
||||
await refreshConfig();
|
||||
} catch (error: any) {
|
||||
showAlert({ type: 'error', title: '保存失败', message: error.message || '未知错误', showConfirm: true });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='space-y-6'>
|
||||
{/* TuneHub 音乐配置 */}
|
||||
<div className='space-y-4'>
|
||||
<h3 className='text-sm font-semibold text-gray-900 dark:text-gray-100'>
|
||||
TuneHub 音乐配置
|
||||
</h3>
|
||||
|
||||
{/* 开启音乐功能 */}
|
||||
<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={() =>
|
||||
setMusicSettings((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 ${
|
||||
musicSettings.TuneHubEnabled
|
||||
? buttonStyles.toggleOn
|
||||
: buttonStyles.toggleOff
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full ${
|
||||
buttonStyles.toggleThumb
|
||||
} transition-transform ${
|
||||
musicSettings.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={musicSettings.TuneHubBaseUrl}
|
||||
onChange={(e) =>
|
||||
setMusicSettings((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={musicSettings.TuneHubApiKey}
|
||||
onChange={(e) =>
|
||||
setMusicSettings((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>
|
||||
|
||||
{/* OpenList 缓存配置 */}
|
||||
<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'>
|
||||
OpenList 缓存配置
|
||||
</h3>
|
||||
|
||||
{/* 开启 OpenList 缓存 */}
|
||||
<div>
|
||||
<div className='flex items-center justify-between'>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
|
||||
开启 OpenList 缓存
|
||||
</label>
|
||||
<button
|
||||
type='button'
|
||||
onClick={() =>
|
||||
setMusicSettings((prev) => ({
|
||||
...prev,
|
||||
OpenListCacheEnabled: !prev.OpenListCacheEnabled,
|
||||
}))
|
||||
}
|
||||
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 ${
|
||||
musicSettings.OpenListCacheEnabled
|
||||
? buttonStyles.toggleOn
|
||||
: buttonStyles.toggleOff
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-4 w-4 transform rounded-full ${
|
||||
buttonStyles.toggleThumb
|
||||
} transition-transform ${
|
||||
musicSettings.OpenListCacheEnabled
|
||||
? buttonStyles.toggleThumbOn
|
||||
: buttonStyles.toggleThumbOff
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
|
||||
开启后将音乐解析结果(播放链接、歌词、元信息)和音频文件缓存到 OpenList,减少 API 调用次数并支持离线播放
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* OpenList URL */}
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
|
||||
OpenList 服务器地址
|
||||
</label>
|
||||
<input
|
||||
type='text'
|
||||
placeholder='https://your-openlist-server.com'
|
||||
value={musicSettings.OpenListCacheURL}
|
||||
onChange={(e) =>
|
||||
setMusicSettings((prev) => ({
|
||||
...prev,
|
||||
OpenListCacheURL: 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'>
|
||||
OpenList 服务器的完整地址(例如:https://your-openlist-server.com)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* OpenList 用户名 */}
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
|
||||
OpenList 用户名
|
||||
</label>
|
||||
<input
|
||||
type='text'
|
||||
placeholder='admin'
|
||||
value={musicSettings.OpenListCacheUsername}
|
||||
onChange={(e) =>
|
||||
setMusicSettings((prev) => ({
|
||||
...prev,
|
||||
OpenListCacheUsername: 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'
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* OpenList 密码 */}
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
|
||||
OpenList 密码
|
||||
</label>
|
||||
<input
|
||||
type='password'
|
||||
placeholder='••••••••'
|
||||
value={musicSettings.OpenListCachePassword}
|
||||
onChange={(e) =>
|
||||
setMusicSettings((prev) => ({
|
||||
...prev,
|
||||
OpenListCachePassword: 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'>
|
||||
用于登录 OpenList 并获取访问权限
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* OpenList 缓存目录 */}
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
|
||||
缓存目录路径
|
||||
</label>
|
||||
<input
|
||||
type='text'
|
||||
placeholder='/music-cache'
|
||||
value={musicSettings.OpenListCachePath}
|
||||
onChange={(e) =>
|
||||
setMusicSettings((prev) => ({
|
||||
...prev,
|
||||
OpenListCachePath: 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'>
|
||||
音乐缓存在 OpenList 中的存储目录(例如:/music-cache)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className='flex justify-end'>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={isLoading('saveMusicConfig')}
|
||||
className={`px-4 py-2 ${
|
||||
isLoading('saveMusicConfig')
|
||||
? buttonStyles.disabled
|
||||
: buttonStyles.success
|
||||
} rounded-lg transition-colors`}
|
||||
>
|
||||
{isLoading('saveMusicConfig') ? '保存中…' : '保存'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 弹窗 */}
|
||||
<AlertModal
|
||||
isOpen={alertModal.isOpen}
|
||||
onClose={hideAlert}
|
||||
type={alertModal.type}
|
||||
title={alertModal.title}
|
||||
message={alertModal.message}
|
||||
timer={alertModal.timer}
|
||||
showConfirm={alertModal.showConfirm}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 新增站点配置组件
|
||||
const SiteConfigComponent = ({
|
||||
config,
|
||||
@@ -6793,9 +7097,6 @@ const SiteConfigComponent = ({
|
||||
OIDCClientId: '',
|
||||
OIDCClientSecret: '',
|
||||
OIDCButtonText: '',
|
||||
TuneHubEnabled: false,
|
||||
TuneHubBaseUrl: 'https://tunehub.sayqz.com/api',
|
||||
TuneHubApiKey: '',
|
||||
});
|
||||
|
||||
// 豆瓣数据源相关状态
|
||||
@@ -7672,93 +7973,6 @@ 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
|
||||
@@ -11354,6 +11568,7 @@ function AdminPageClient() {
|
||||
liveSource: false,
|
||||
webLive: false,
|
||||
siteConfig: false,
|
||||
musicConfig: false,
|
||||
registrationConfig: false,
|
||||
categoryConfig: false,
|
||||
configFile: false,
|
||||
@@ -11639,6 +11854,21 @@ function AdminPageClient() {
|
||||
<SiteConfigComponent config={config} refreshConfig={fetchConfig} />
|
||||
</CollapsibleTab>
|
||||
|
||||
{/* 音乐配置标签 */}
|
||||
<CollapsibleTab
|
||||
title='音乐配置'
|
||||
icon={
|
||||
<Music
|
||||
size={20}
|
||||
className='text-gray-600 dark:text-gray-400'
|
||||
/>
|
||||
}
|
||||
isExpanded={expandedTabs.musicConfig}
|
||||
onToggle={() => toggleTab('musicConfig')}
|
||||
>
|
||||
<MusicConfigComponent config={config} refreshConfig={fetchConfig} />
|
||||
</CollapsibleTab>
|
||||
|
||||
{/* 注册配置标签 */}
|
||||
<CollapsibleTab
|
||||
title='注册配置'
|
||||
|
||||
108
src/app/api/admin/music/route.ts
Normal file
108
src/app/api/admin/music/route.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any,no-console */
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
|
||||
if (storageType === 'localstorage') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: '不支持本地存储进行管理员配置',
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo || !authInfo.username) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
const username = authInfo.username;
|
||||
|
||||
const {
|
||||
TuneHubEnabled,
|
||||
TuneHubBaseUrl,
|
||||
TuneHubApiKey,
|
||||
OpenListCacheEnabled,
|
||||
OpenListCacheURL,
|
||||
OpenListCacheUsername,
|
||||
OpenListCachePassword,
|
||||
OpenListCachePath,
|
||||
} = body as {
|
||||
TuneHubEnabled?: boolean;
|
||||
TuneHubBaseUrl?: string;
|
||||
TuneHubApiKey?: string;
|
||||
OpenListCacheEnabled?: boolean;
|
||||
OpenListCacheURL?: string;
|
||||
OpenListCacheUsername?: string;
|
||||
OpenListCachePassword?: string;
|
||||
OpenListCachePath?: string;
|
||||
};
|
||||
|
||||
// 参数校验
|
||||
if (
|
||||
(TuneHubEnabled !== undefined && typeof TuneHubEnabled !== 'boolean') ||
|
||||
(TuneHubBaseUrl !== undefined && typeof TuneHubBaseUrl !== 'string') ||
|
||||
(TuneHubApiKey !== undefined && typeof TuneHubApiKey !== 'string') ||
|
||||
(OpenListCacheEnabled !== undefined && typeof OpenListCacheEnabled !== 'boolean') ||
|
||||
(OpenListCacheURL !== undefined && typeof OpenListCacheURL !== 'string') ||
|
||||
(OpenListCacheUsername !== undefined && typeof OpenListCacheUsername !== 'string') ||
|
||||
(OpenListCachePassword !== undefined && typeof OpenListCachePassword !== 'string') ||
|
||||
(OpenListCachePath !== undefined && typeof OpenListCachePath !== 'string')
|
||||
) {
|
||||
return NextResponse.json({ error: '参数格式错误' }, { status: 400 });
|
||||
}
|
||||
|
||||
const adminConfig = await getConfig();
|
||||
|
||||
// 权限校验 - 使用v2用户系统
|
||||
if (username !== process.env.USERNAME) {
|
||||
const userInfo = await db.getUserInfoV2(username);
|
||||
if (!userInfo || userInfo.role !== 'admin' || userInfo.banned) {
|
||||
return NextResponse.json({ error: '权限不足' }, { status: 401 });
|
||||
}
|
||||
}
|
||||
|
||||
// 更新缓存中的音乐配置
|
||||
adminConfig.MusicConfig = {
|
||||
TuneHubEnabled,
|
||||
TuneHubBaseUrl,
|
||||
TuneHubApiKey,
|
||||
OpenListCacheEnabled,
|
||||
OpenListCacheURL,
|
||||
OpenListCacheUsername,
|
||||
OpenListCachePassword,
|
||||
OpenListCachePath,
|
||||
};
|
||||
|
||||
// 写入数据库
|
||||
await db.saveAdminConfig(adminConfig);
|
||||
|
||||
return NextResponse.json(
|
||||
{ ok: true },
|
||||
{
|
||||
headers: {
|
||||
'Cache-Control': 'no-store', // 不缓存结果
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('更新音乐配置失败:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: '更新音乐配置失败',
|
||||
details: (error as Error).message,
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -69,9 +69,6 @@ export async function POST(request: NextRequest) {
|
||||
OIDCClientSecret,
|
||||
OIDCButtonText,
|
||||
OIDCMinTrustLevel,
|
||||
TuneHubEnabled,
|
||||
TuneHubBaseUrl,
|
||||
TuneHubApiKey,
|
||||
} = body as {
|
||||
SiteName: string;
|
||||
Announcement: string;
|
||||
@@ -113,9 +110,6 @@ export async function POST(request: NextRequest) {
|
||||
OIDCClientSecret?: string;
|
||||
OIDCButtonText?: string;
|
||||
OIDCMinTrustLevel?: number;
|
||||
TuneHubEnabled?: boolean;
|
||||
TuneHubBaseUrl?: string;
|
||||
TuneHubApiKey?: string;
|
||||
};
|
||||
|
||||
// 参数校验
|
||||
@@ -156,10 +150,7 @@ 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') ||
|
||||
(TuneHubEnabled !== undefined && typeof TuneHubEnabled !== 'boolean') ||
|
||||
(TuneHubBaseUrl !== undefined && typeof TuneHubBaseUrl !== 'string') ||
|
||||
(TuneHubApiKey !== undefined && typeof TuneHubApiKey !== 'string')
|
||||
(OIDCMinTrustLevel !== undefined && typeof OIDCMinTrustLevel !== 'number')
|
||||
) {
|
||||
return NextResponse.json({ error: '参数格式错误' }, { status: 400 });
|
||||
}
|
||||
@@ -216,9 +207,6 @@ export async function POST(request: NextRequest) {
|
||||
OIDCClientSecret,
|
||||
OIDCButtonText,
|
||||
OIDCMinTrustLevel,
|
||||
TuneHubEnabled,
|
||||
TuneHubBaseUrl,
|
||||
TuneHubApiKey,
|
||||
};
|
||||
|
||||
// 写入数据库
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { OpenListClient } from '@/lib/openlist.client';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
@@ -13,19 +14,193 @@ const serverCache = {
|
||||
CACHE_DURATION: 24 * 60 * 60 * 1000, // 24小时缓存
|
||||
};
|
||||
|
||||
// 正在下载的音频任务追踪(防止重复下载)
|
||||
const downloadingTasks = new Map<string, Promise<void>>();
|
||||
|
||||
// 获取 TuneHub 配置
|
||||
async function getTuneHubConfig() {
|
||||
const config = await getConfig();
|
||||
const siteConfig = config?.SiteConfig;
|
||||
const musicConfig = config?.MusicConfig;
|
||||
|
||||
const enabled = siteConfig?.TuneHubEnabled ?? false;
|
||||
const enabled = musicConfig?.TuneHubEnabled ?? false;
|
||||
const baseUrl =
|
||||
siteConfig?.TuneHubBaseUrl ||
|
||||
musicConfig?.TuneHubBaseUrl ||
|
||||
process.env.TUNEHUB_BASE_URL ||
|
||||
'https://tunehub.sayqz.com/api';
|
||||
const apiKey = siteConfig?.TuneHubApiKey || process.env.TUNEHUB_API_KEY || '';
|
||||
const apiKey = musicConfig?.TuneHubApiKey || process.env.TUNEHUB_API_KEY || '';
|
||||
|
||||
return { enabled, baseUrl, apiKey };
|
||||
return { enabled, baseUrl, apiKey, musicConfig };
|
||||
}
|
||||
|
||||
// 获取 OpenList 客户端
|
||||
async function getOpenListClient(): Promise<OpenListClient | null> {
|
||||
const config = await getConfig();
|
||||
const musicConfig = config?.MusicConfig;
|
||||
|
||||
console.log('[Music OpenList] 配置检查:', {
|
||||
enabled: musicConfig?.OpenListCacheEnabled,
|
||||
hasURL: !!musicConfig?.OpenListCacheURL,
|
||||
hasUsername: !!musicConfig?.OpenListCacheUsername,
|
||||
hasPassword: !!musicConfig?.OpenListCachePassword,
|
||||
});
|
||||
|
||||
if (!musicConfig?.OpenListCacheEnabled) {
|
||||
console.warn('[Music OpenList] OpenList 缓存未启用');
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = musicConfig.OpenListCacheURL;
|
||||
const username = musicConfig.OpenListCacheUsername;
|
||||
const password = musicConfig.OpenListCachePassword;
|
||||
|
||||
if (!url || !username || !password) {
|
||||
console.warn('[Music OpenList] 配置不完整,跳过 OpenList 缓存');
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log('[Music OpenList] 创建 OpenList 客户端:', url);
|
||||
return new OpenListClient(url, username, password);
|
||||
}
|
||||
|
||||
// 异步下载音频文件并上传到 OpenList
|
||||
async function cacheAudioToOpenList(
|
||||
openListClient: OpenListClient,
|
||||
audioUrl: string,
|
||||
platform: string,
|
||||
songId: string,
|
||||
quality: string,
|
||||
cachePath: string
|
||||
): Promise<void> {
|
||||
const taskKey = `${platform}-${songId}-${quality}`;
|
||||
|
||||
// 检查是否已经有任务在下载
|
||||
const existingTask = downloadingTasks.get(taskKey);
|
||||
if (existingTask) {
|
||||
console.log('[Music Cache] 该音频正在下载中,跳过重复任务:', taskKey);
|
||||
return existingTask;
|
||||
}
|
||||
|
||||
// 创建下载任务
|
||||
const downloadTask = (async () => {
|
||||
try {
|
||||
const audioPath = `${cachePath}/${platform}/audio/${songId}-${quality}.mp3`;
|
||||
|
||||
console.log('[Music Cache] 开始下载音频:', audioUrl);
|
||||
const audioResponse = await fetch(audioUrl);
|
||||
|
||||
if (!audioResponse.ok) {
|
||||
console.error('[Music Cache] 下载音频失败:', audioResponse.status);
|
||||
return;
|
||||
}
|
||||
|
||||
const audioBuffer = await audioResponse.arrayBuffer();
|
||||
const audioBlob = Buffer.from(audioBuffer);
|
||||
|
||||
console.log('[Music Cache] 音频下载完成,大小:', audioBlob.length, 'bytes');
|
||||
console.log('[Music Cache] 开始上传到 OpenList:', audioPath);
|
||||
|
||||
// OpenList 的 uploadFile 方法需要字符串,但我们需要上传二进制文件
|
||||
// 使用 PUT 方法直接上传
|
||||
const token = await (openListClient as any).getToken();
|
||||
console.log('[Music Cache] 获取到 Token,开始上传请求');
|
||||
|
||||
const uploadResponse = await fetch(`${(openListClient as any).baseURL}/api/fs/put`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Authorization': token,
|
||||
'Content-Type': 'audio/mpeg',
|
||||
'File-Path': encodeURIComponent(audioPath),
|
||||
'As-Task': 'false',
|
||||
},
|
||||
body: audioBlob,
|
||||
});
|
||||
|
||||
console.log('[Music Cache] 上传响应状态:', uploadResponse.status);
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
const errorText = await uploadResponse.text();
|
||||
console.error('[Music Cache] 上传音频失败:', uploadResponse.status, errorText);
|
||||
return;
|
||||
}
|
||||
|
||||
const responseData = await uploadResponse.json();
|
||||
console.log('[Music Cache] 上传响应数据:', responseData);
|
||||
console.log('[Music Cache] 音频成功缓存到 OpenList:', audioPath);
|
||||
} catch (error) {
|
||||
console.error('[Music Cache] 缓存音频到 OpenList 失败:', error);
|
||||
} finally {
|
||||
// 任务完成后从追踪中移除
|
||||
downloadingTasks.delete(taskKey);
|
||||
}
|
||||
})();
|
||||
|
||||
// 将任务添加到追踪
|
||||
downloadingTasks.set(taskKey, downloadTask);
|
||||
|
||||
return downloadTask;
|
||||
}
|
||||
|
||||
// 检查并替换音频 URL 为 OpenList URL
|
||||
async function replaceAudioUrlsWithOpenList(
|
||||
data: any,
|
||||
openListClient: OpenListClient | null,
|
||||
platform: string,
|
||||
quality: string,
|
||||
cachePath: string
|
||||
): Promise<any> {
|
||||
if (!openListClient || !data?.data) {
|
||||
console.log('[Music Cache] 跳过音频替换:', { hasClient: !!openListClient, hasData: !!data?.data });
|
||||
return data;
|
||||
}
|
||||
|
||||
// TuneHub 返回的数据结构是 { code: 0, data: { data: [...], total: 1 } }
|
||||
// 需要提取内层的 data 数组
|
||||
const songsData = data.data.data || data.data;
|
||||
const songs = Array.isArray(songsData) ? songsData : [songsData];
|
||||
|
||||
console.log('[Music Cache] 开始处理', songs.length, '首歌曲');
|
||||
|
||||
for (const song of songs) {
|
||||
if (!song?.id || !song?.url) {
|
||||
console.log('[Music Cache] 跳过无效歌曲:', song);
|
||||
continue;
|
||||
}
|
||||
|
||||
const audioPath = `${cachePath}/${platform}/audio/${song.id}-${quality}.mp3`;
|
||||
|
||||
try {
|
||||
// 检查 OpenList 是否有这个音频文件
|
||||
const fileResponse = await openListClient.getFile(audioPath);
|
||||
|
||||
if (fileResponse.code === 200 && fileResponse.data?.raw_url) {
|
||||
console.log('[Music Cache] 使用 OpenList 缓存的音频:', audioPath);
|
||||
song.url = fileResponse.data.raw_url;
|
||||
song.cached = true; // 标记为已缓存
|
||||
} else {
|
||||
// OpenList 返回非200,说明文件不存在,开始下载
|
||||
console.log('[Music Cache] OpenList 无缓存(code:', fileResponse.code, '),异步下载音频');
|
||||
song.cached = false;
|
||||
|
||||
// 异步上传,不阻塞响应
|
||||
cacheAudioToOpenList(openListClient, song.url, platform, song.id, quality, cachePath)
|
||||
.catch(error => {
|
||||
console.error('[Music Cache] 异步缓存音频失败:', error);
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// getFile 抛出异常,也说明文件不存在或网络错误
|
||||
console.log('[Music Cache] 检查 OpenList 音频缓存失败:', error);
|
||||
song.cached = false;
|
||||
|
||||
// 即使检查失败,也尝试下载
|
||||
cacheAudioToOpenList(openListClient, song.url, platform, song.id, quality, cachePath)
|
||||
.catch(err => {
|
||||
console.error('[Music Cache] 异步缓存音频失败:', err);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
// 通用请求处理函数
|
||||
@@ -392,13 +567,49 @@ export async function POST(request: NextRequest) {
|
||||
const qualityKey = quality || '320k';
|
||||
const idsKey = Array.isArray(ids) ? ids.join(',') : ids;
|
||||
const cacheKey = `parse-${platform}-${idsKey}-${qualityKey}`;
|
||||
const cached = serverCache.proxyRequests.get(cacheKey);
|
||||
|
||||
// 1. 先检查内存缓存
|
||||
const cached = serverCache.proxyRequests.get(cacheKey);
|
||||
if (cached && Date.now() - cached.timestamp < serverCache.CACHE_DURATION) {
|
||||
console.log('[Music Cache] 从内存缓存返回');
|
||||
return NextResponse.json(cached.data);
|
||||
}
|
||||
|
||||
// 2. 检查 OpenList 缓存
|
||||
const openListClient = await getOpenListClient();
|
||||
const config = await getConfig();
|
||||
const cachePath = config?.MusicConfig?.OpenListCachePath || '/music-cache';
|
||||
|
||||
console.log('[Music Cache] OpenList 客户端状态:', openListClient ? '已创建' : '未创建');
|
||||
console.log('[Music Cache] 缓存路径:', cachePath);
|
||||
|
||||
if (openListClient) {
|
||||
try {
|
||||
const openListPath = `${cachePath}/${platform}/${idsKey}-${qualityKey}.json`;
|
||||
console.log('[Music Cache] 尝试从 OpenList 读取:', openListPath);
|
||||
|
||||
const fileResponse = await openListClient.getFile(openListPath);
|
||||
if (fileResponse.code === 200 && fileResponse.data?.raw_url) {
|
||||
// 下载缓存文件
|
||||
const cacheResponse = await fetch(fileResponse.data.raw_url);
|
||||
if (cacheResponse.ok) {
|
||||
const cachedData = await cacheResponse.json();
|
||||
console.log('[Music Cache] 从 OpenList 缓存返回');
|
||||
|
||||
// 更新内存缓存
|
||||
serverCache.proxyRequests.set(cacheKey, { data: cachedData, timestamp: Date.now() });
|
||||
|
||||
return NextResponse.json(cachedData);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('[Music Cache] OpenList 缓存未命中或读取失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 调用 TuneHub API 解析
|
||||
try {
|
||||
console.log('[Music Cache] 调用 TuneHub API 解析');
|
||||
const response = await proxyRequest(`${baseUrl}/v1/parse`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -424,10 +635,32 @@ export async function POST(request: NextRequest) {
|
||||
});
|
||||
}
|
||||
|
||||
// 缓存成功的解析结果
|
||||
// 4. 缓存成功的解析结果到内存
|
||||
serverCache.proxyRequests.set(cacheKey, { data, timestamp: Date.now() });
|
||||
|
||||
return NextResponse.json(data);
|
||||
// 5. 检查并替换音频 URL 为 OpenList URL(如果已缓存)
|
||||
// 同时异步下载未缓存的音频
|
||||
const finalData = await replaceAudioUrlsWithOpenList(
|
||||
data,
|
||||
openListClient,
|
||||
platform,
|
||||
qualityKey,
|
||||
cachePath
|
||||
);
|
||||
|
||||
// 6. 缓存解析结果到 OpenList(异步,不阻塞响应)
|
||||
if (openListClient) {
|
||||
const jsonPath = `${cachePath}/${platform}/${idsKey}-${qualityKey}.json`;
|
||||
openListClient.uploadFile(jsonPath, JSON.stringify(finalData, null, 2))
|
||||
.then(() => {
|
||||
console.log('[Music Cache] 成功缓存解析结果到 OpenList:', jsonPath);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('[Music Cache] 缓存解析结果到 OpenList 失败:', error);
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(finalData);
|
||||
} catch (error) {
|
||||
console.error('解析歌曲失败:', error);
|
||||
return NextResponse.json({
|
||||
|
||||
@@ -136,7 +136,7 @@ export default async function RootLayout({
|
||||
// 自定义去广告代码版本号
|
||||
customAdFilterVersion = config.SiteConfig?.CustomAdFilterVersion || 0;
|
||||
// TuneHub音乐功能配置
|
||||
tuneHubEnabled = config.SiteConfig?.TuneHubEnabled || false;
|
||||
tuneHubEnabled = config.MusicConfig?.TuneHubEnabled || false;
|
||||
// 检查是否启用了 OpenList 功能
|
||||
openListEnabled = !!(
|
||||
config.OpenListConfig?.Enabled &&
|
||||
|
||||
@@ -56,10 +56,6 @@ 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: {
|
||||
@@ -240,6 +236,18 @@ export interface AdminConfig {
|
||||
from: string; // 发件人邮箱
|
||||
};
|
||||
};
|
||||
MusicConfig?: {
|
||||
// TuneHub音乐配置
|
||||
TuneHubEnabled?: boolean; // 启用音乐功能
|
||||
TuneHubBaseUrl?: string; // TuneHub API地址
|
||||
TuneHubApiKey?: string; // TuneHub API Key
|
||||
// OpenList缓存配置
|
||||
OpenListCacheEnabled?: boolean; // 启用OpenList缓存
|
||||
OpenListCacheURL?: string; // OpenList服务器地址
|
||||
OpenListCacheUsername?: string; // OpenList用户名
|
||||
OpenListCachePassword?: string; // OpenList密码
|
||||
OpenListCachePath?: string; // OpenList缓存目录路径
|
||||
};
|
||||
}
|
||||
|
||||
export interface AdminConfigResult {
|
||||
|
||||
@@ -542,6 +542,20 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
|
||||
}
|
||||
}
|
||||
|
||||
// 确保音乐配置存在
|
||||
if (!adminConfig.MusicConfig) {
|
||||
adminConfig.MusicConfig = {
|
||||
TuneHubEnabled: false,
|
||||
TuneHubBaseUrl: 'https://tunehub.sayqz.com/api',
|
||||
TuneHubApiKey: '',
|
||||
OpenListCacheEnabled: false,
|
||||
OpenListCacheURL: '',
|
||||
OpenListCacheUsername: '',
|
||||
OpenListCachePassword: '',
|
||||
OpenListCachePath: '/music-cache',
|
||||
};
|
||||
}
|
||||
|
||||
return adminConfig;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user