夸克网盘转存
This commit is contained in:
@@ -30,6 +30,7 @@ import {
|
|||||||
CheckCircle,
|
CheckCircle,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
ChevronUp,
|
ChevronUp,
|
||||||
|
Cloud,
|
||||||
Database,
|
Database,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
FileText,
|
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 媒体库配置组件 - 多源管理版本
|
// Emby 媒体库配置组件 - 多源管理版本
|
||||||
const EmbyConfigComponent = ({
|
const EmbyConfigComponent = ({
|
||||||
config,
|
config,
|
||||||
@@ -12732,6 +12946,7 @@ function AdminPageClient() {
|
|||||||
sourceScriptLab: false,
|
sourceScriptLab: false,
|
||||||
mediaLibrary: false,
|
mediaLibrary: false,
|
||||||
openListConfig: false,
|
openListConfig: false,
|
||||||
|
netDiskConfig: false,
|
||||||
embyConfig: false,
|
embyConfig: false,
|
||||||
xiaoyaConfig: false,
|
xiaoyaConfig: false,
|
||||||
animeSubscription: false,
|
animeSubscription: false,
|
||||||
@@ -13210,6 +13425,17 @@ function AdminPageClient() {
|
|||||||
>
|
>
|
||||||
<AnimeSubscriptionComponent config={config} refreshConfig={fetchConfig} />
|
<AnimeSubscriptionComponent config={config} refreshConfig={fetchConfig} />
|
||||||
</CollapsibleTab>
|
</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>
|
</div>
|
||||||
</CollapsibleTab>
|
</CollapsibleTab>
|
||||||
|
|
||||||
|
|||||||
@@ -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 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,6 +29,7 @@ export async function GET(request: NextRequest) {
|
|||||||
const id = searchParams.get('id');
|
const id = searchParams.get('id');
|
||||||
const sourceCode = searchParams.get('source');
|
const sourceCode = searchParams.get('source');
|
||||||
const fileName = searchParams.get('fileName'); // 小雅源:用户点击的文件名
|
const fileName = searchParams.get('fileName'); // 小雅源:用户点击的文件名
|
||||||
|
const title = searchParams.get('title');
|
||||||
|
|
||||||
if (!id || !sourceCode) {
|
if (!id || !sourceCode) {
|
||||||
return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
|
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
|
// 特殊处理 openlist 源 - 直接调用 /api/detail
|
||||||
if (sourceCode === 'openlist') {
|
if (sourceCode === 'openlist') {
|
||||||
try {
|
try {
|
||||||
@@ -340,8 +459,9 @@ export async function GET(request: NextRequest) {
|
|||||||
let currentPage = 1;
|
let currentPage = 1;
|
||||||
const pageSize = 100;
|
const pageSize = 100;
|
||||||
let total = 0;
|
let total = 0;
|
||||||
|
let hasMore = true;
|
||||||
|
|
||||||
while (true) {
|
while (hasMore) {
|
||||||
const listResponse = await client.listDirectory(folderPath, currentPage, pageSize);
|
const listResponse = await client.listDirectory(folderPath, currentPage, pageSize);
|
||||||
|
|
||||||
if (listResponse.code !== 200) {
|
if (listResponse.code !== 200) {
|
||||||
@@ -351,10 +471,7 @@ export async function GET(request: NextRequest) {
|
|||||||
total = listResponse.data.total;
|
total = listResponse.data.total;
|
||||||
allFiles.push(...listResponse.data.content);
|
allFiles.push(...listResponse.data.content);
|
||||||
|
|
||||||
if (allFiles.length >= total) {
|
hasMore = allFiles.length < total;
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
currentPage++;
|
currentPage++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1413,6 +1413,7 @@ function PlayPageClient() {
|
|||||||
!isM3u8LikeUrl(videoUrl) &&
|
!isM3u8LikeUrl(videoUrl) &&
|
||||||
(
|
(
|
||||||
detail.source === 'openlist' ||
|
detail.source === 'openlist' ||
|
||||||
|
detail.source === 'quark-temp' ||
|
||||||
detail.source === 'xiaoya' ||
|
detail.source === 'xiaoya' ||
|
||||||
detail.source.startsWith('emby')
|
detail.source.startsWith('emby')
|
||||||
)
|
)
|
||||||
@@ -9161,6 +9162,7 @@ function PlayPageClient() {
|
|||||||
// 特殊源使用 tmdb,其他使用 cms(通过 doubanId)
|
// 特殊源使用 tmdb,其他使用 cms(通过 doubanId)
|
||||||
// 如果有豆瓣ID且不为0,传入doubanId
|
// 如果有豆瓣ID且不为0,传入doubanId
|
||||||
detail.source === 'openlist' ||
|
detail.source === 'openlist' ||
|
||||||
|
detail.source === 'quark-temp' ||
|
||||||
detail.source?.startsWith('emby') ||
|
detail.source?.startsWith('emby') ||
|
||||||
detail.source === 'xiaoya'
|
detail.source === 'xiaoya'
|
||||||
? undefined
|
? undefined
|
||||||
@@ -9171,6 +9173,7 @@ function PlayPageClient() {
|
|||||||
tmdbId={
|
tmdbId={
|
||||||
// 特殊源使用 tmdb
|
// 特殊源使用 tmdb
|
||||||
detail.source === 'openlist' ||
|
detail.source === 'openlist' ||
|
||||||
|
detail.source === 'quark-temp' ||
|
||||||
detail.source?.startsWith('emby') ||
|
detail.source?.startsWith('emby') ||
|
||||||
detail.source === 'xiaoya'
|
detail.source === 'xiaoya'
|
||||||
? detail.tmdb_id
|
? detail.tmdb_id
|
||||||
@@ -9182,6 +9185,7 @@ function PlayPageClient() {
|
|||||||
// 非特殊源使用 cms 数据
|
// 非特殊源使用 cms 数据
|
||||||
// 但如果有豆瓣ID且不为0,则不传入cmsData,优先使用豆瓣数据
|
// 但如果有豆瓣ID且不为0,则不传入cmsData,优先使用豆瓣数据
|
||||||
detail.source !== 'openlist' &&
|
detail.source !== 'openlist' &&
|
||||||
|
detail.source !== 'quark-temp' &&
|
||||||
!detail.source?.startsWith('emby') &&
|
!detail.source?.startsWith('emby') &&
|
||||||
detail.source !== 'xiaoya' &&
|
detail.source !== 'xiaoya' &&
|
||||||
!(detail.douban_id && detail.douban_id !== 0)
|
!(detail.douban_id && detail.douban_id !== 0)
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { AlertCircle, Copy, ExternalLink, Loader2, RefreshCw } from 'lucide-react';
|
import { AlertCircle, Copy, ExternalLink, Loader2, RefreshCw } from 'lucide-react';
|
||||||
import { useEffect, useState, useCallback } from 'react';
|
import { useRouter } from 'next/navigation';
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
|
||||||
import { PansouLink, PansouSearchResult } from '@/lib/pansou.client';
|
import { PansouLink, PansouSearchResult } from '@/lib/pansou.client';
|
||||||
|
|
||||||
@@ -51,11 +52,14 @@ export default function PansouSearch({
|
|||||||
triggerSearch,
|
triggerSearch,
|
||||||
onError,
|
onError,
|
||||||
}: PansouSearchProps) {
|
}: PansouSearchProps) {
|
||||||
|
const router = useRouter();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [results, setResults] = useState<PansouSearchResult | null>(null);
|
const [results, setResults] = useState<PansouSearchResult | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [copiedUrl, setCopiedUrl] = useState<string | null>(null);
|
const [copiedUrl, setCopiedUrl] = useState<string | null>(null);
|
||||||
const [selectedType, setSelectedType] = useState<string>('all'); // 'all' 表示显示全部
|
const [selectedType, setSelectedType] = useState<string>('all'); // 'all' 表示显示全部
|
||||||
|
const [transferingUrl, setTransferingUrl] = useState<string | null>(null);
|
||||||
|
const [playingUrl, setPlayingUrl] = useState<string | null>(null);
|
||||||
|
|
||||||
// 提取搜索函数,以便在重试时调用
|
// 提取搜索函数,以便在重试时调用
|
||||||
const searchPansou = useCallback(async () => {
|
const searchPansou = useCallback(async () => {
|
||||||
@@ -118,6 +122,63 @@ export default function PansouSearch({
|
|||||||
window.open(url, '_blank', 'noopener,noreferrer');
|
window.open(url, '_blank', 'noopener,noreferrer');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleQuarkTransfer = async (link: PansouLink) => {
|
||||||
|
try {
|
||||||
|
setTransferingUrl(link.url);
|
||||||
|
const response = await fetch('/api/quark/transfer', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
shareUrl: link.url,
|
||||||
|
passcode: link.password || '',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data.error || '转存失败');
|
||||||
|
}
|
||||||
|
|
||||||
|
window.alert(`转存成功,已保存到:${data.targetPath}`);
|
||||||
|
} catch (err: any) {
|
||||||
|
window.alert(err?.message || '转存失败');
|
||||||
|
} finally {
|
||||||
|
setTransferingUrl(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleQuarkInstantPlay = async (link: PansouLink) => {
|
||||||
|
try {
|
||||||
|
setPlayingUrl(link.url);
|
||||||
|
const response = await fetch('/api/quark/instant-play', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
shareUrl: link.url,
|
||||||
|
passcode: link.password || '',
|
||||||
|
title: link.note || keyword,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data.error || '立即播放失败');
|
||||||
|
}
|
||||||
|
|
||||||
|
router.push(
|
||||||
|
`/play?source=quark-temp&id=${encodeURIComponent(data.id)}&title=${encodeURIComponent(data.title || keyword)}`
|
||||||
|
);
|
||||||
|
} catch (err: any) {
|
||||||
|
window.alert(err?.message || '立即播放失败');
|
||||||
|
} finally {
|
||||||
|
setPlayingUrl(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<div className='flex items-center justify-center py-12'>
|
<div className='flex items-center justify-center py-12'>
|
||||||
@@ -196,7 +257,6 @@ export default function PansouSearch({
|
|||||||
</button>
|
</button>
|
||||||
{typeStats.map(({ type, count }) => {
|
{typeStats.map(({ type, count }) => {
|
||||||
const typeName = CLOUD_TYPE_NAMES[type] || type;
|
const typeName = CLOUD_TYPE_NAMES[type] || type;
|
||||||
const typeColor = CLOUD_TYPE_COLORS[type] || CLOUD_TYPE_COLORS.others;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
@@ -263,6 +323,26 @@ export default function PansouSearch({
|
|||||||
|
|
||||||
{/* 操作按钮 */}
|
{/* 操作按钮 */}
|
||||||
<div className='flex items-center gap-1 flex-shrink-0'>
|
<div className='flex items-center gap-1 flex-shrink-0'>
|
||||||
|
{cloudType === 'quark' && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={() => handleQuarkInstantPlay(link)}
|
||||||
|
disabled={playingUrl === link.url}
|
||||||
|
className='px-2 py-1 rounded-md bg-green-600 hover:bg-green-700 text-white text-xs transition-colors disabled:opacity-60'
|
||||||
|
title='立即播放'
|
||||||
|
>
|
||||||
|
{playingUrl === link.url ? '处理中...' : '立即播放'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleQuarkTransfer(link)}
|
||||||
|
disabled={transferingUrl === link.url}
|
||||||
|
className='px-2 py-1 rounded-md bg-purple-600 hover:bg-purple-700 text-white text-xs transition-colors disabled:opacity-60'
|
||||||
|
title='转存到配置目录'
|
||||||
|
>
|
||||||
|
{transferingUrl === link.url ? '转存中...' : '转存'}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() => handleCopy(
|
onClick={() => handleCopy(
|
||||||
link.password ? `${link.url}\n提取码: ${link.password}` : link.url,
|
link.password ? `${link.url}\n提取码: ${link.password}` : link.url,
|
||||||
|
|||||||
@@ -143,6 +143,15 @@ export interface AdminConfig {
|
|||||||
ScanMode?: 'torrent' | 'name' | 'hybrid'; // 扫描模式:torrent=种子库匹配,name=名字匹配,hybrid=混合模式(默认)
|
ScanMode?: 'torrent' | 'name' | 'hybrid'; // 扫描模式:torrent=种子库匹配,name=名字匹配,hybrid=混合模式(默认)
|
||||||
DisableVideoPreview?: boolean; // 禁用预览视频,直接返回直连链接
|
DisableVideoPreview?: boolean; // 禁用预览视频,直接返回直连链接
|
||||||
};
|
};
|
||||||
|
NetDiskConfig?: {
|
||||||
|
Quark?: {
|
||||||
|
Enabled: boolean;
|
||||||
|
Cookie: string;
|
||||||
|
SavePath: string;
|
||||||
|
PlayTempSavePath: string;
|
||||||
|
OpenListTempPath: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
AIConfig?: {
|
AIConfig?: {
|
||||||
Enabled: boolean; // 是否启用AI问片功能
|
Enabled: boolean; // 是否启用AI问片功能
|
||||||
Provider: 'openai' | 'claude' | 'custom'; // AI服务提供商
|
Provider: 'openai' | 'claude' | 'custom'; // AI服务提供商
|
||||||
|
|||||||
@@ -618,6 +618,28 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!adminConfig.NetDiskConfig) {
|
||||||
|
adminConfig.NetDiskConfig = {
|
||||||
|
Quark: {
|
||||||
|
Enabled: false,
|
||||||
|
Cookie: '',
|
||||||
|
SavePath: '/',
|
||||||
|
PlayTempSavePath: '/',
|
||||||
|
OpenListTempPath: '/',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!adminConfig.NetDiskConfig.Quark) {
|
||||||
|
adminConfig.NetDiskConfig.Quark = {
|
||||||
|
Enabled: false,
|
||||||
|
Cookie: '',
|
||||||
|
SavePath: '/',
|
||||||
|
PlayTempSavePath: '/',
|
||||||
|
OpenListTempPath: '/',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// 确保音乐配置存在
|
// 确保音乐配置存在
|
||||||
if (!adminConfig.MusicConfig) {
|
if (!adminConfig.MusicConfig) {
|
||||||
adminConfig.MusicConfig = {
|
adminConfig.MusicConfig = {
|
||||||
|
|||||||
@@ -0,0 +1,471 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-explicit-any, no-console */
|
||||||
|
|
||||||
|
const QUARK_SHARE_API_BASE = 'https://drive-h.quark.cn/1/clouddrive';
|
||||||
|
const QUARK_DRIVE_API_BASE = 'https://drive-pc.quark.cn/1/clouddrive';
|
||||||
|
const QUARK_QUERY = 'pr=ucpro&fr=pc';
|
||||||
|
|
||||||
|
export interface QuarkShareLinkInfo {
|
||||||
|
pwdId: string;
|
||||||
|
passcode: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QuarkShareItem {
|
||||||
|
fid: string;
|
||||||
|
fileName: string;
|
||||||
|
dir: boolean;
|
||||||
|
shareFidToken?: string;
|
||||||
|
pdirFid?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QuarkTransferTaskResult {
|
||||||
|
taskId?: string;
|
||||||
|
fileCount: number;
|
||||||
|
targetPath: string;
|
||||||
|
folderName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const VIDEO_EXTENSIONS = [
|
||||||
|
'.mp4',
|
||||||
|
'.mkv',
|
||||||
|
'.avi',
|
||||||
|
'.m3u8',
|
||||||
|
'.flv',
|
||||||
|
'.ts',
|
||||||
|
'.mov',
|
||||||
|
'.wmv',
|
||||||
|
'.webm',
|
||||||
|
'.rmvb',
|
||||||
|
'.rm',
|
||||||
|
'.mpg',
|
||||||
|
'.mpeg',
|
||||||
|
'.3gp',
|
||||||
|
'.f4v',
|
||||||
|
'.m4v',
|
||||||
|
'.vob',
|
||||||
|
];
|
||||||
|
|
||||||
|
function buildApiUrl(base: string, path: string, query = '') {
|
||||||
|
const normalizedPath = path.startsWith('/') ? path : `/${path}`;
|
||||||
|
return `${base}${normalizedPath}?${QUARK_QUERY}${query ? `&${query}` : ''}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getHeaders(cookie: string): HeadersInit {
|
||||||
|
return {
|
||||||
|
'content-type': 'application/json',
|
||||||
|
cookie,
|
||||||
|
origin: 'https://pan.quark.cn',
|
||||||
|
referer: 'https://pan.quark.cn/',
|
||||||
|
'user-agent':
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeQuarkCookie(cookie: string): string {
|
||||||
|
return cookie
|
||||||
|
.replace(/;/g, ';')
|
||||||
|
.replace(/:/g, ':')
|
||||||
|
.replace(/,/g, ',')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertQuarkCookieHeaderSafe(cookie: string): string {
|
||||||
|
const normalized = normalizeQuarkCookie(cookie);
|
||||||
|
for (let i = 0; i < normalized.length; i += 1) {
|
||||||
|
if (normalized.charCodeAt(i) > 255) {
|
||||||
|
throw new Error('夸克 Cookie 含有非法字符,请确认没有中文标点、中文空格或说明文字');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePath(path: string): string {
|
||||||
|
const trimmed = path.trim();
|
||||||
|
if (!trimmed || trimmed === '/') return '/';
|
||||||
|
return `/${trimmed.replace(/^\/+|\/+$/g, '')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function joinPath(...parts: string[]) {
|
||||||
|
const joined = parts
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('/')
|
||||||
|
.replace(/\/+/g, '/');
|
||||||
|
return normalizePath(joined);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeFolderName(name: string) {
|
||||||
|
return (name || 'quark-temp')
|
||||||
|
.replace(/[<>:"/\\|?*]/g, ' ')
|
||||||
|
.replace(/[\r\n\t]/g, ' ')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim()
|
||||||
|
.slice(0, 80);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function parseJson(response: Response) {
|
||||||
|
const text = await response.text();
|
||||||
|
try {
|
||||||
|
return JSON.parse(text);
|
||||||
|
} catch {
|
||||||
|
throw new Error(`夸克接口返回异常:${text.slice(0, 200)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureOk(data: any, fallbackMessage: string) {
|
||||||
|
if (data?.code === 0 || data?.code === 200 || data?.status === 200) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new Error(data?.message || data?.msg || fallbackMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseQuarkShareUrl(url: string, passcode = ''): QuarkShareLinkInfo {
|
||||||
|
const parsed = new URL(url);
|
||||||
|
const pwdId =
|
||||||
|
parsed.pathname.match(/\/s\/([A-Za-z0-9_-]+)/)?.[1] ||
|
||||||
|
parsed.searchParams.get('pwd_id') ||
|
||||||
|
'';
|
||||||
|
|
||||||
|
if (!pwdId) {
|
||||||
|
throw new Error('无法解析夸克分享链接');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
pwdId,
|
||||||
|
passcode:
|
||||||
|
passcode ||
|
||||||
|
parsed.searchParams.get('pwd') ||
|
||||||
|
parsed.searchParams.get('passcode') ||
|
||||||
|
'',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchShareToken(cookie: string, share: QuarkShareLinkInfo) {
|
||||||
|
const response = await fetch(
|
||||||
|
buildApiUrl(QUARK_SHARE_API_BASE, '/share/sharepage/token'),
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
headers: getHeaders(cookie),
|
||||||
|
body: JSON.stringify({
|
||||||
|
pwd_id: share.pwdId,
|
||||||
|
passcode: share.passcode,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const data = await parseJson(response);
|
||||||
|
ensureOk(data, '获取夸克分享 token 失败');
|
||||||
|
|
||||||
|
const stoken =
|
||||||
|
data?.data?.stoken ||
|
||||||
|
data?.data?.share_token ||
|
||||||
|
data?.data?.token;
|
||||||
|
|
||||||
|
if (!stoken) {
|
||||||
|
throw new Error('夸克分享 token 缺失');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
stoken,
|
||||||
|
shareTitle: data?.data?.title || '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchShareFolderItems(
|
||||||
|
cookie: string,
|
||||||
|
pwdId: string,
|
||||||
|
stoken: string,
|
||||||
|
pdirFid = '0'
|
||||||
|
): Promise<QuarkShareItem[]> {
|
||||||
|
const query = new URLSearchParams({
|
||||||
|
pwd_id: pwdId,
|
||||||
|
stoken,
|
||||||
|
pdir_fid: pdirFid,
|
||||||
|
_page: '1',
|
||||||
|
_size: '200',
|
||||||
|
_fetch_banner: '0',
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
buildApiUrl(QUARK_SHARE_API_BASE, '/share/sharepage/detail', query.toString()),
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
headers: getHeaders(cookie),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const data = await parseJson(response);
|
||||||
|
ensureOk(data, '获取夸克分享详情失败');
|
||||||
|
|
||||||
|
const list = data?.data?.list || [];
|
||||||
|
return list.map((item: any) => ({
|
||||||
|
fid: String(item.fid || item.file_id || ''),
|
||||||
|
fileName: String(item.file_name || item.name || ''),
|
||||||
|
dir: Boolean(item.dir || item.is_dir || item.file_type === 0),
|
||||||
|
shareFidToken:
|
||||||
|
item.share_fid_token || item.fid_token || item.share_token || undefined,
|
||||||
|
pdirFid: String(item.pdir_fid || pdirFid || '0'),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchDriveFolderItems(
|
||||||
|
cookie: string,
|
||||||
|
pdirFid = '0'
|
||||||
|
): Promise<any[]> {
|
||||||
|
const query = new URLSearchParams({
|
||||||
|
pdir_fid: pdirFid,
|
||||||
|
_page: '1',
|
||||||
|
_size: '200',
|
||||||
|
_sort: 'file_type:asc,file_name:asc',
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
buildApiUrl(QUARK_DRIVE_API_BASE, '/file/sort', query.toString()),
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
headers: getHeaders(cookie),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const data = await parseJson(response);
|
||||||
|
ensureOk(data, '获取夸克目录列表失败');
|
||||||
|
return data?.data?.list || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function validateQuarkCookieReadable(cookie: string): Promise<void> {
|
||||||
|
const safeCookie = assertQuarkCookieHeaderSafe(cookie);
|
||||||
|
await fetchDriveFolderItems(safeCookie, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createDriveFolder(
|
||||||
|
cookie: string,
|
||||||
|
parentFid: string,
|
||||||
|
folderName: string
|
||||||
|
) {
|
||||||
|
const response = await fetch(buildApiUrl(QUARK_DRIVE_API_BASE, '/file'), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: getHeaders(cookie),
|
||||||
|
body: JSON.stringify({
|
||||||
|
pdir_fid: parentFid,
|
||||||
|
file_name: folderName,
|
||||||
|
dir_path: '',
|
||||||
|
dir_init_lock: false,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await parseJson(response);
|
||||||
|
ensureOk(data, `创建夸克目录失败:${folderName}`);
|
||||||
|
|
||||||
|
const fid =
|
||||||
|
data?.data?.fid ||
|
||||||
|
data?.data?.file_id ||
|
||||||
|
data?.metadata?.fid;
|
||||||
|
|
||||||
|
if (!fid) {
|
||||||
|
throw new Error(`夸克目录创建成功但未返回 fid:${folderName}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return String(fid);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ensureQuarkDrivePath(
|
||||||
|
cookie: string,
|
||||||
|
inputPath: string
|
||||||
|
): Promise<{ fid: string; path: string }> {
|
||||||
|
const normalized = normalizePath(inputPath);
|
||||||
|
if (normalized === '/') {
|
||||||
|
return { fid: '0', path: normalized };
|
||||||
|
}
|
||||||
|
|
||||||
|
const segments = normalized.split('/').filter(Boolean);
|
||||||
|
let currentFid = '0';
|
||||||
|
let currentPath = '';
|
||||||
|
|
||||||
|
for (const segment of segments) {
|
||||||
|
const items = await fetchDriveFolderItems(cookie, currentFid);
|
||||||
|
const existed = items.find(
|
||||||
|
(item: any) =>
|
||||||
|
Boolean(item.dir || item.is_dir) &&
|
||||||
|
String(item.file_name || item.name || '') === segment
|
||||||
|
);
|
||||||
|
|
||||||
|
currentPath = joinPath(currentPath, segment);
|
||||||
|
|
||||||
|
if (existed) {
|
||||||
|
currentFid = String(existed.fid || existed.file_id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentFid = await createDriveFolder(cookie, currentFid, segment);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
fid: currentFid,
|
||||||
|
path: currentPath || '/',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function collectShareItemsRecursive(
|
||||||
|
cookie: string,
|
||||||
|
pwdId: string,
|
||||||
|
stoken: string,
|
||||||
|
pdirFid = '0'
|
||||||
|
): Promise<QuarkShareItem[]> {
|
||||||
|
const items = await fetchShareFolderItems(cookie, pwdId, stoken, pdirFid);
|
||||||
|
const result: QuarkShareItem[] = [];
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
if (item.dir) {
|
||||||
|
const children = await collectShareItemsRecursive(
|
||||||
|
cookie,
|
||||||
|
pwdId,
|
||||||
|
stoken,
|
||||||
|
item.fid
|
||||||
|
);
|
||||||
|
result.push(...children);
|
||||||
|
} else {
|
||||||
|
result.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isVideoFile(fileName: string) {
|
||||||
|
const lower = fileName.toLowerCase();
|
||||||
|
return VIDEO_EXTENSIONS.some((ext) => lower.endsWith(ext));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitSaveTask(
|
||||||
|
cookie: string,
|
||||||
|
share: QuarkShareLinkInfo,
|
||||||
|
stoken: string,
|
||||||
|
toPdirFid: string,
|
||||||
|
items: QuarkShareItem[]
|
||||||
|
) {
|
||||||
|
if (items.length === 0) {
|
||||||
|
throw new Error('没有可保存的文件');
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
buildApiUrl(QUARK_SHARE_API_BASE, '/share/sharepage/save'),
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
headers: getHeaders(cookie),
|
||||||
|
body: JSON.stringify({
|
||||||
|
pwd_id: share.pwdId,
|
||||||
|
stoken,
|
||||||
|
pdir_fid: '0',
|
||||||
|
to_pdir_fid: toPdirFid,
|
||||||
|
scene: 'link',
|
||||||
|
filelist: items.map((item) => item.fid),
|
||||||
|
fid_list: items.map((item) => item.fid),
|
||||||
|
fid_token_list: items.map((item) => item.shareFidToken || ''),
|
||||||
|
share_fid_token_list: items.map((item) => item.shareFidToken || ''),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const data = await parseJson(response);
|
||||||
|
ensureOk(data, '提交夸克转存任务失败');
|
||||||
|
return data?.data?.task_id ? String(data.data.task_id) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pollTask(cookie: string, taskId: string) {
|
||||||
|
for (let i = 0; i < 25; i += 1) {
|
||||||
|
const query = new URLSearchParams({
|
||||||
|
task_id: taskId,
|
||||||
|
retry_index: String(i),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await fetch(buildApiUrl(QUARK_SHARE_API_BASE, '/task', query.toString()), {
|
||||||
|
method: 'GET',
|
||||||
|
headers: getHeaders(cookie),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await parseJson(response);
|
||||||
|
ensureOk(data, '查询夸克任务状态失败');
|
||||||
|
|
||||||
|
const task = data?.data || {};
|
||||||
|
if (
|
||||||
|
task?.status === 2 ||
|
||||||
|
task?.status === 'finished' ||
|
||||||
|
task?.status === 'success' ||
|
||||||
|
task?.finished_at
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
task?.status === -1 ||
|
||||||
|
task?.status === 'failed' ||
|
||||||
|
task?.err_code
|
||||||
|
) {
|
||||||
|
throw new Error(task?.message || task?.err_msg || '夸克任务执行失败');
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1200));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('夸克任务处理超时');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function transferQuarkShare(
|
||||||
|
cookie: string,
|
||||||
|
input: {
|
||||||
|
shareUrl: string;
|
||||||
|
passcode?: string;
|
||||||
|
savePath: string;
|
||||||
|
}
|
||||||
|
): Promise<QuarkTransferTaskResult> {
|
||||||
|
const safeCookie = assertQuarkCookieHeaderSafe(cookie);
|
||||||
|
const share = parseQuarkShareUrl(input.shareUrl, input.passcode);
|
||||||
|
const { stoken } = await fetchShareToken(safeCookie, share);
|
||||||
|
const topLevelItems = await fetchShareFolderItems(safeCookie, share.pwdId, stoken, '0');
|
||||||
|
const target = await ensureQuarkDrivePath(safeCookie, input.savePath);
|
||||||
|
const taskId = await submitSaveTask(safeCookie, share, stoken, target.fid, topLevelItems);
|
||||||
|
|
||||||
|
if (taskId) {
|
||||||
|
await pollTask(safeCookie, taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
taskId,
|
||||||
|
fileCount: topLevelItems.length,
|
||||||
|
targetPath: target.path,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createQuarkInstantPlayFolder(
|
||||||
|
cookie: string,
|
||||||
|
input: {
|
||||||
|
shareUrl: string;
|
||||||
|
passcode?: string;
|
||||||
|
playTempSavePath: string;
|
||||||
|
title?: string;
|
||||||
|
}
|
||||||
|
): Promise<QuarkTransferTaskResult> {
|
||||||
|
const safeCookie = assertQuarkCookieHeaderSafe(cookie);
|
||||||
|
const share = parseQuarkShareUrl(input.shareUrl, input.passcode);
|
||||||
|
const { stoken, shareTitle } = await fetchShareToken(safeCookie, share);
|
||||||
|
const allItems = await collectShareItemsRecursive(safeCookie, share.pwdId, stoken, '0');
|
||||||
|
const videoItems = allItems.filter((item) => !item.dir && isVideoFile(item.fileName));
|
||||||
|
|
||||||
|
if (videoItems.length === 0) {
|
||||||
|
throw new Error('分享中没有可播放的视频文件');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tempRoot = await ensureQuarkDrivePath(safeCookie, input.playTempSavePath);
|
||||||
|
const folderName = `${sanitizeFolderName(input.title || shareTitle || 'quark-temp')}_${Date.now()}`;
|
||||||
|
const folderFid = await createDriveFolder(safeCookie, tempRoot.fid, folderName);
|
||||||
|
const taskId = await submitSaveTask(safeCookie, share, stoken, folderFid, videoItems);
|
||||||
|
|
||||||
|
if (taskId) {
|
||||||
|
await pollTask(safeCookie, taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
taskId,
|
||||||
|
fileCount: videoItems.length,
|
||||||
|
targetPath: joinPath(tempRoot.path, folderName),
|
||||||
|
folderName,
|
||||||
|
};
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user