夸克网盘转存

This commit is contained in:
mtvpls
2026-04-07 16:58:22 +08:00
parent 4bed01e7a3
commit 9b707c1a17
10 changed files with 1132 additions and 7 deletions
+226
View File
@@ -30,6 +30,7 @@ import {
CheckCircle,
ChevronDown,
ChevronUp,
Cloud,
Database,
ExternalLink,
FileText,
@@ -3499,6 +3500,219 @@ const OpenListConfigComponent = ({
);
};
const NetDiskConfigComponent = ({
config,
refreshConfig,
}: {
config: AdminConfig | null;
refreshConfig: () => Promise<void>;
}) => {
const { alertModal, showAlert, hideAlert } = useAlertModal();
const { isLoading, withLoading } = useLoadingState();
const [enabled, setEnabled] = useState(false);
const [cookie, setCookie] = useState('');
const [savePath, setSavePath] = useState('/');
const [playTempSavePath, setPlayTempSavePath] = useState('/');
const [openListTempPath, setOpenListTempPath] = useState('/');
useEffect(() => {
const quark = config?.NetDiskConfig?.Quark;
setEnabled(quark?.Enabled || false);
setCookie(quark?.Cookie || '');
setSavePath(quark?.SavePath || '/');
setPlayTempSavePath(quark?.PlayTempSavePath || '/');
setOpenListTempPath(quark?.OpenListTempPath || '/');
}, [config]);
const handleSave = async () => {
await withLoading('saveNetDisk', async () => {
const response = await fetch('/api/admin/netdisk', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'save',
Quark: {
Enabled: enabled,
Cookie: cookie,
SavePath: savePath,
PlayTempSavePath: playTempSavePath,
OpenListTempPath: openListTempPath,
},
}),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || '保存失败');
}
showSuccess('保存成功', showAlert);
await refreshConfig();
});
};
const handleValidate = async () => {
await withLoading('validateNetDisk', async () => {
try {
const response = await fetch('/api/admin/netdisk', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'validate',
Quark: {
Cookie: cookie,
SavePath: savePath,
PlayTempSavePath: playTempSavePath,
},
}),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || '校验失败');
}
showSuccess(data.message || '夸克 Cookie 可读', showAlert);
} catch (error) {
showError(error instanceof Error ? error.message : '校验失败', showAlert);
throw error;
}
});
};
return (
<div className='space-y-6'>
<details className='pt-4 border-t border-gray-200 dark:border-gray-700'>
<summary className='text-sm font-semibold text-gray-900 dark:text-gray-100 cursor-pointer'>
</summary>
<div className='mt-4 space-y-4'>
<div className='bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4'>
<div className='flex items-center gap-2 mb-2'>
<Cloud className='w-5 h-5 text-blue-600 dark:text-blue-400' />
<span className='text-sm font-medium text-blue-800 dark:text-blue-300'>
</span>
</div>
<div className='text-sm text-blue-700 dark:text-blue-400 space-y-1'>
<p> </p>
<p> OpenList </p>
<p> OpenList </p>
</div>
</div>
<div className='flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700'>
<div>
<h3 className='text-sm font-medium text-gray-900 dark:text-gray-100'>
</h3>
<p className='text-xs text-gray-500 dark:text-gray-400 mt-1'>
</p>
</div>
<label className='relative inline-flex items-center cursor-pointer'>
<input
type='checkbox'
checked={enabled}
onChange={(e) => setEnabled(e.target.checked)}
className='sr-only peer'
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
</label>
</div>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
Cookie
</label>
<textarea
value={cookie}
onChange={(e) => setCookie(e.target.value)}
disabled={!enabled}
rows={5}
placeholder='粘贴夸克网盘 Cookie'
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-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed'
/>
</div>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
</label>
<input
type='text'
value={savePath}
onChange={(e) => setSavePath(e.target.value)}
disabled={!enabled}
placeholder='/影视/正式转存'
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-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed'
/>
</div>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
</label>
<input
type='text'
value={playTempSavePath}
onChange={(e) => setPlayTempSavePath(e.target.value)}
disabled={!enabled}
placeholder='/影视/.play-temp'
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-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed'
/>
</div>
<div>
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
OpenList
</label>
<input
type='text'
value={openListTempPath}
onChange={(e) => setOpenListTempPath(e.target.value)}
disabled={!enabled}
placeholder='/Quark/影视/.play-temp'
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-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed'
/>
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
OpenList 访
</p>
</div>
<div className='flex gap-3'>
<button
onClick={handleValidate}
disabled={!enabled || !cookie || isLoading('validateNetDisk')}
className={buttonStyles.primary}
>
{isLoading('validateNetDisk') ? '校验中...' : '校验夸克配置'}
</button>
<button
onClick={handleSave}
disabled={isLoading('saveNetDisk')}
className={buttonStyles.success}
>
{isLoading('saveNetDisk') ? '保存中...' : '保存配置'}
</button>
</div>
</div>
</details>
<AlertModal
isOpen={alertModal.isOpen}
onClose={hideAlert}
type={alertModal.type}
title={alertModal.title}
message={alertModal.message}
timer={alertModal.timer}
showConfirm={alertModal.showConfirm}
onConfirm={alertModal.onConfirm}
/>
</div>
);
};
// Emby 媒体库配置组件 - 多源管理版本
const EmbyConfigComponent = ({
config,
@@ -12732,6 +12946,7 @@ function AdminPageClient() {
sourceScriptLab: false,
mediaLibrary: false,
openListConfig: false,
netDiskConfig: false,
embyConfig: false,
xiaoyaConfig: false,
animeSubscription: false,
@@ -13210,6 +13425,17 @@ function AdminPageClient() {
>
<AnimeSubscriptionComponent config={config} refreshConfig={fetchConfig} />
</CollapsibleTab>
<CollapsibleTab
title='网盘配置'
icon={
<Cloud size={20} className='text-gray-600 dark:text-gray-400' />
}
isExpanded={expandedTabs.netDiskConfig}
onToggle={() => toggleTab('netDiskConfig')}
>
<NetDiskConfigComponent config={config} refreshConfig={fetchConfig} />
</CollapsibleTab>
</div>
</CollapsibleTab>
+85
View File
@@ -0,0 +1,85 @@
/* eslint-disable no-console */
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig, setCachedConfig } from '@/lib/config';
import { db } from '@/lib/db';
import {
assertQuarkCookieHeaderSafe,
normalizeQuarkCookie,
validateQuarkCookieReadable,
} from '@/lib/quark.client';
export const runtime = 'nodejs';
function requireOwner(username: string | undefined) {
return username === process.env.USERNAME;
}
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 authInfo = getAuthInfoFromCookie(request);
if (!authInfo?.username) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
if (!requireOwner(authInfo.username)) {
const userInfo = await db.getUserInfoV2(authInfo.username);
if (!userInfo || userInfo.role !== 'admin' || userInfo.banned) {
return NextResponse.json({ error: '权限不足' }, { status: 401 });
}
}
const body = await request.json();
const { action, Quark } = body;
const adminConfig = await getConfig();
if (action === 'save') {
const normalizedCookie = Quark?.Cookie ? assertQuarkCookieHeaderSafe(Quark.Cookie) : '';
adminConfig.NetDiskConfig = adminConfig.NetDiskConfig || {};
adminConfig.NetDiskConfig.Quark = {
Enabled: Boolean(Quark?.Enabled),
Cookie: normalizedCookie,
SavePath: Quark?.SavePath || '/',
PlayTempSavePath: Quark?.PlayTempSavePath || '/',
OpenListTempPath: Quark?.OpenListTempPath || '/',
};
await db.saveAdminConfig(adminConfig);
await setCachedConfig(adminConfig);
return NextResponse.json({ success: true, message: '保存成功' });
}
if (action === 'validate') {
if (!Quark?.Cookie) {
return NextResponse.json({ error: '请先填写夸克 Cookie' }, { status: 400 });
}
await validateQuarkCookieReadable(normalizeQuarkCookie(Quark.Cookie));
return NextResponse.json({
success: true,
message: '夸克cookie正常',
});
}
return NextResponse.json({ error: '未知操作' }, { status: 400 });
} catch (error) {
console.error('[Admin NetDisk] 操作失败:', error);
return NextResponse.json(
{ error: error instanceof Error ? error.message : '操作失败' },
{ status: 500 }
);
}
}
+67
View File
@@ -0,0 +1,67 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config';
import { createQuarkInstantPlayFolder } from '@/lib/quark.client';
import { base58Encode } from '@/lib/utils';
export const runtime = 'nodejs';
function joinPath(...parts: string[]) {
const joined = parts
.filter(Boolean)
.join('/')
.replace(/\/+/g, '/');
return joined.startsWith('/') ? joined : `/${joined}`;
}
export async function POST(request: NextRequest) {
try {
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo?.username) {
return NextResponse.json({ error: '未登录' }, { status: 401 });
}
const { shareUrl, passcode, title } = await request.json();
if (!shareUrl) {
return NextResponse.json({ error: '分享链接不能为空' }, { status: 400 });
}
const config = await getConfig();
const quarkConfig = config.NetDiskConfig?.Quark;
if (!quarkConfig?.Enabled || !quarkConfig.Cookie) {
return NextResponse.json({ error: '夸克网盘未配置或未启用' }, { status: 400 });
}
const result = await createQuarkInstantPlayFolder(quarkConfig.Cookie, {
shareUrl,
passcode,
playTempSavePath: quarkConfig.PlayTempSavePath,
title,
});
if (!result.folderName) {
throw new Error('未生成临时播放目录');
}
const openlistFolderPath = joinPath(
quarkConfig.OpenListTempPath,
result.folderName
);
return NextResponse.json({
success: true,
source: 'quark-temp',
id: base58Encode(openlistFolderPath),
title: title || result.folderName,
openlistFolderPath,
...result,
});
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : '立即播放失败' },
{ status: 500 }
);
}
}
+44
View File
@@ -0,0 +1,44 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config';
import { transferQuarkShare } from '@/lib/quark.client';
export const runtime = 'nodejs';
export async function POST(request: NextRequest) {
try {
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo?.username) {
return NextResponse.json({ error: '未登录' }, { status: 401 });
}
const { shareUrl, passcode } = await request.json();
if (!shareUrl) {
return NextResponse.json({ error: '分享链接不能为空' }, { status: 400 });
}
const config = await getConfig();
const quarkConfig = config.NetDiskConfig?.Quark;
if (!quarkConfig?.Enabled || !quarkConfig.Cookie) {
return NextResponse.json({ error: '夸克网盘未配置或未启用' }, { status: 400 });
}
const result = await transferQuarkShare(quarkConfig.Cookie, {
shareUrl,
passcode,
savePath: quarkConfig.SavePath,
});
return NextResponse.json({
success: true,
...result,
});
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : '转存失败' },
{ status: 500 }
);
}
}
+122 -5
View File
@@ -29,6 +29,7 @@ export async function GET(request: NextRequest) {
const id = searchParams.get('id');
const sourceCode = searchParams.get('source');
const fileName = searchParams.get('fileName'); // 小雅源:用户点击的文件名
const title = searchParams.get('title');
if (!id || !sourceCode) {
return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
@@ -274,6 +275,124 @@ export async function GET(request: NextRequest) {
}
}
if (sourceCode === 'quark-temp') {
try {
const config = await getConfig();
const openListConfig = config.OpenListConfig;
if (
!openListConfig ||
!openListConfig.Enabled ||
!openListConfig.URL ||
!openListConfig.Username ||
!openListConfig.Password
) {
throw new Error('OpenList 未配置或未启用');
}
const { base58Decode } = await import('@/lib/utils');
const { OpenListClient } = await import('@/lib/openlist.client');
const { parseVideoFileName } = await import('@/lib/video-parser');
const folderPath = base58Decode(id);
if (!folderPath) {
throw new Error('无效的临时播放目录');
}
const client = new OpenListClient(
openListConfig.URL,
openListConfig.Username,
openListConfig.Password
);
const videoExtensions = ['.mp4', '.mkv', '.avi', '.m3u8', '.flv', '.ts', '.mov', '.wmv', '.webm', '.rmvb', '.rm', '.mpg', '.mpeg', '.3gp', '.f4v', '.m4v', '.vob'];
const collectFiles = async (currentPath: string): Promise<Array<{ path: string; name: string }>> => {
const allFiles: Array<{ path: string; name: string }> = [];
let currentPage = 1;
const pageSize = 100;
let hasMore = true;
while (hasMore) {
const response = await client.listDirectory(currentPath, currentPage, pageSize);
if (response.code !== 200) {
throw new Error('读取临时目录失败');
}
for (const item of response.data.content) {
const itemPath = `${currentPath}${currentPath.endsWith('/') ? '' : '/'}${item.name}`;
if (item.is_dir) {
const nested = await collectFiles(itemPath);
allFiles.push(...nested);
} else if (
!item.name.startsWith('.') &&
videoExtensions.some((ext) => item.name.toLowerCase().endsWith(ext))
) {
allFiles.push({
path: itemPath,
name: item.name,
});
}
}
hasMore = !(
response.data.content.length < pageSize ||
currentPage * pageSize >= response.data.total
);
currentPage += 1;
}
return allFiles;
};
const files = await collectFiles(folderPath);
if (files.length === 0) {
throw new Error('临时播放目录中没有视频文件');
}
const episodes = files
.map((file, index) => {
const parsed = parseVideoFileName(file.name);
const fileDir = file.path.substring(0, file.path.lastIndexOf('/')) || '/';
return {
fileName: file.name,
fileDir,
episode: parsed.episode || index + 1,
title:
parsed.title ||
(parsed.episode ? `${parsed.episode}` : file.name),
isOVA: parsed.isOVA,
};
})
.sort((a, b) => {
if (a.isOVA && !b.isOVA) return 1;
if (!a.isOVA && b.isOVA) return -1;
return a.episode !== b.episode
? a.episode - b.episode
: a.fileName.localeCompare(b.fileName);
});
return NextResponse.json({
source: 'quark-temp',
source_name: '夸克临时播放',
id,
title: title || folderPath.split('/').filter(Boolean).pop() || '夸克临时播放',
poster: '',
year: '',
douban_id: 0,
desc: `临时播放目录:${folderPath}`,
episodes: episodes.map((ep) => `/api/openlist/play?folder=${encodeURIComponent(ep.fileDir)}&fileName=${encodeURIComponent(ep.fileName)}`),
episodes_titles: episodes.map((ep) => ep.title),
proxyMode: false,
});
} catch (error) {
return NextResponse.json(
{ error: (error as Error).message },
{ status: 500 }
);
}
}
// 特殊处理 openlist 源 - 直接调用 /api/detail
if (sourceCode === 'openlist') {
try {
@@ -340,8 +459,9 @@ export async function GET(request: NextRequest) {
let currentPage = 1;
const pageSize = 100;
let total = 0;
let hasMore = true;
while (true) {
while (hasMore) {
const listResponse = await client.listDirectory(folderPath, currentPage, pageSize);
if (listResponse.code !== 200) {
@@ -351,10 +471,7 @@ export async function GET(request: NextRequest) {
total = listResponse.data.total;
allFiles.push(...listResponse.data.content);
if (allFiles.length >= total) {
break;
}
hasMore = allFiles.length < total;
currentPage++;
}
+4
View File
@@ -1413,6 +1413,7 @@ function PlayPageClient() {
!isM3u8LikeUrl(videoUrl) &&
(
detail.source === 'openlist' ||
detail.source === 'quark-temp' ||
detail.source === 'xiaoya' ||
detail.source.startsWith('emby')
)
@@ -9161,6 +9162,7 @@ function PlayPageClient() {
// 特殊源使用 tmdb,其他使用 cms(通过 doubanId
// 如果有豆瓣ID且不为0,传入doubanId
detail.source === 'openlist' ||
detail.source === 'quark-temp' ||
detail.source?.startsWith('emby') ||
detail.source === 'xiaoya'
? undefined
@@ -9171,6 +9173,7 @@ function PlayPageClient() {
tmdbId={
// 特殊源使用 tmdb
detail.source === 'openlist' ||
detail.source === 'quark-temp' ||
detail.source?.startsWith('emby') ||
detail.source === 'xiaoya'
? detail.tmdb_id
@@ -9182,6 +9185,7 @@ function PlayPageClient() {
// 非特殊源使用 cms 数据
// 但如果有豆瓣ID且不为0,则不传入cmsData,优先使用豆瓣数据
detail.source !== 'openlist' &&
detail.source !== 'quark-temp' &&
!detail.source?.startsWith('emby') &&
detail.source !== 'xiaoya' &&
!(detail.douban_id && detail.douban_id !== 0)