123云盘播放
This commit is contained in:
@@ -3711,6 +3711,9 @@ const NetDiskConfigComponent = ({
|
||||
const [tianyiEnabled, setTianyiEnabled] = useState(false);
|
||||
const [tianyiAccount, setTianyiAccount] = useState('');
|
||||
const [tianyiPassword, setTianyiPassword] = useState('');
|
||||
const [pan123Enabled, setPan123Enabled] = useState(false);
|
||||
const [pan123Account, setPan123Account] = useState('');
|
||||
const [pan123Password, setPan123Password] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const quark = config?.NetDiskConfig?.Quark;
|
||||
@@ -3725,6 +3728,9 @@ const NetDiskConfigComponent = ({
|
||||
setTianyiEnabled(config?.NetDiskConfig?.Tianyi?.Enabled || false);
|
||||
setTianyiAccount(config?.NetDiskConfig?.Tianyi?.Account || '');
|
||||
setTianyiPassword(config?.NetDiskConfig?.Tianyi?.Password || '');
|
||||
setPan123Enabled(config?.NetDiskConfig?.Pan123?.Enabled || false);
|
||||
setPan123Account(config?.NetDiskConfig?.Pan123?.Account || '');
|
||||
setPan123Password(config?.NetDiskConfig?.Pan123?.Password || '');
|
||||
}, [config]);
|
||||
|
||||
const handleSave = async () => {
|
||||
@@ -3752,6 +3758,11 @@ const NetDiskConfigComponent = ({
|
||||
Account: tianyiAccount,
|
||||
Password: tianyiPassword,
|
||||
},
|
||||
Pan123: {
|
||||
Enabled: pan123Enabled,
|
||||
Account: pan123Account,
|
||||
Password: pan123Password,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -3878,6 +3889,35 @@ const NetDiskConfigComponent = ({
|
||||
});
|
||||
};
|
||||
|
||||
const handleValidatePan123 = async () => {
|
||||
await withLoading('validatePan123NetDisk', async () => {
|
||||
try {
|
||||
const response = await fetch('/api/admin/netdisk', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: 'validate',
|
||||
provider: 'pan123',
|
||||
Pan123: {
|
||||
Account: pan123Account,
|
||||
Password: pan123Password,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || '校验失败');
|
||||
}
|
||||
|
||||
showSuccess(data.message || '123网盘账号密码可用', 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'>
|
||||
@@ -4144,6 +4184,78 @@ const NetDiskConfigComponent = ({
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<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'>
|
||||
123网盘
|
||||
</summary>
|
||||
<div className='mt-4 space-y-4'>
|
||||
<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'>
|
||||
启用123网盘
|
||||
</h3>
|
||||
<p className='text-xs text-gray-500 dark:text-gray-400 mt-1'>
|
||||
开启后,网盘搜索中的123网盘资源会显示“立即播放”按钮
|
||||
</p>
|
||||
</div>
|
||||
<label className='relative inline-flex items-center cursor-pointer'>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={pan123Enabled}
|
||||
onChange={(e) => setPan123Enabled(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-teal-300 dark:peer-focus:ring-teal-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-teal-600"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
|
||||
账号
|
||||
</label>
|
||||
<input
|
||||
type='text'
|
||||
value={pan123Account}
|
||||
onChange={(e) => setPan123Account(e.target.value)}
|
||||
disabled={!pan123Enabled}
|
||||
placeholder='输入123网盘账号'
|
||||
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-teal-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='password'
|
||||
value={pan123Password}
|
||||
onChange={(e) => setPan123Password(e.target.value)}
|
||||
disabled={!pan123Enabled}
|
||||
placeholder='输入123网盘密码'
|
||||
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-teal-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='flex gap-3'>
|
||||
<button
|
||||
onClick={handleValidatePan123}
|
||||
disabled={!pan123Enabled || !pan123Account || !pan123Password || isLoading('validatePan123NetDisk')}
|
||||
className={buttonStyles.primary}
|
||||
>
|
||||
{isLoading('validatePan123NetDisk') ? '校验中...' : '校验123网盘账号密码'}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={isLoading('saveNetDisk')}
|
||||
className={buttonStyles.success}
|
||||
>
|
||||
{isLoading('saveNetDisk') ? '保存中...' : '保存配置'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<AlertModal
|
||||
isOpen={alertModal.isOpen}
|
||||
onClose={hideAlert}
|
||||
|
||||
@@ -10,6 +10,11 @@ import {
|
||||
assertMobileAuthorizationHeaderSafe,
|
||||
normalizeMobileAuthorization,
|
||||
} from '@/lib/netdisk/mobile.client';
|
||||
import {
|
||||
normalizePan123Account,
|
||||
normalizePan123Password,
|
||||
validatePan123Credentials,
|
||||
} from '@/lib/netdisk/pan123.client';
|
||||
import {
|
||||
assertQuarkCookieHeaderSafe,
|
||||
normalizeQuarkCookie,
|
||||
@@ -46,7 +51,7 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { action, Quark, Mobile, Baidu, Tianyi, provider } = body;
|
||||
const { action, Quark, Mobile, Baidu, Tianyi, Pan123, provider } = body;
|
||||
const adminConfig = await getConfig();
|
||||
|
||||
if (action === 'save') {
|
||||
@@ -57,6 +62,8 @@ export async function POST(request: NextRequest) {
|
||||
const normalizedBaiduCookie = Baidu?.Cookie ? assertBaiduCookieHeaderSafe(Baidu.Cookie) : '';
|
||||
const normalizedTianyiAccount = Tianyi?.Account ? normalizeTianyiAccount(Tianyi.Account) : '';
|
||||
const normalizedTianyiPassword = Tianyi?.Password ? normalizeTianyiPassword(Tianyi.Password) : '';
|
||||
const normalizedPan123Account = Pan123?.Account ? normalizePan123Account(Pan123.Account) : '';
|
||||
const normalizedPan123Password = Pan123?.Password ? normalizePan123Password(Pan123.Password) : '';
|
||||
|
||||
adminConfig.NetDiskConfig = adminConfig.NetDiskConfig || {};
|
||||
adminConfig.NetDiskConfig.Quark = {
|
||||
@@ -77,6 +84,11 @@ export async function POST(request: NextRequest) {
|
||||
Account: normalizedTianyiAccount,
|
||||
Password: normalizedTianyiPassword,
|
||||
};
|
||||
adminConfig.NetDiskConfig.Pan123 = {
|
||||
Enabled: Boolean(Pan123?.Enabled),
|
||||
Account: normalizedPan123Account,
|
||||
Password: normalizedPan123Password,
|
||||
};
|
||||
|
||||
await db.saveAdminConfig(adminConfig);
|
||||
await setCachedConfig(adminConfig);
|
||||
@@ -119,6 +131,19 @@ export async function POST(request: NextRequest) {
|
||||
message: '天翼云盘账号密码可用',
|
||||
});
|
||||
}
|
||||
if (provider === 'pan123') {
|
||||
if (!Pan123?.Account || !Pan123?.Password) {
|
||||
return NextResponse.json({ error: '请先填写123网盘账号和密码' }, { status: 400 });
|
||||
}
|
||||
await validatePan123Credentials(
|
||||
normalizePan123Account(Pan123.Account),
|
||||
normalizePan123Password(Pan123.Password)
|
||||
);
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '123网盘账号密码可用',
|
||||
});
|
||||
}
|
||||
|
||||
if (!Quark?.Cookie) {
|
||||
return NextResponse.json({ error: '请先填写夸克 Cookie' }, { status: 400 });
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { listPan123ShareVideos } from '@/lib/netdisk/pan123.client';
|
||||
import { createPan123NetdiskSession } from '@/lib/netdisk/pan123-session-cache';
|
||||
import { NETDISK_123_SOURCE } from '@/lib/netdisk/source';
|
||||
import { hasFeaturePermission } from '@/lib/permissions';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo?.username) {
|
||||
return NextResponse.json({ error: '未登录' }, { status: 401 });
|
||||
}
|
||||
if (!(await hasFeaturePermission(authInfo.username, 'netdisk_temp_play'))) {
|
||||
return NextResponse.json({ error: '无权限使用临时播放' }, { status: 403 });
|
||||
}
|
||||
|
||||
const { shareUrl, passcode, title } = await request.json();
|
||||
if (!shareUrl) {
|
||||
return NextResponse.json({ error: '分享链接不能为空' }, { status: 400 });
|
||||
}
|
||||
|
||||
const config = await getConfig();
|
||||
const pan123Config = config.NetDiskConfig?.Pan123;
|
||||
if (!pan123Config?.Enabled || !pan123Config.Account || !pan123Config.Password) {
|
||||
return NextResponse.json({ error: '123网盘未配置或未启用' }, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await listPan123ShareVideos(shareUrl, passcode || '');
|
||||
const session = createPan123NetdiskSession({
|
||||
title: title || result.title,
|
||||
shareUrl,
|
||||
passcode,
|
||||
files: result.files,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
source: NETDISK_123_SOURCE,
|
||||
id: session.id,
|
||||
title: title || result.title,
|
||||
totalFiles: result.files.length,
|
||||
expiresAt: session.expiresAt,
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : '立即播放失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { getPan123PlayInfo, listPan123ShareVideos } from '@/lib/netdisk/pan123.client';
|
||||
import {
|
||||
createPan123NetdiskSession,
|
||||
getPan123NetdiskSession,
|
||||
parsePan123NetdiskId,
|
||||
refreshPan123NetdiskSession,
|
||||
} from '@/lib/netdisk/pan123-session-cache';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
if (!authInfo?.username) {
|
||||
return NextResponse.json({ error: '未授权' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const sessionId = searchParams.get('id') || searchParams.get('session');
|
||||
const episodeIndexRaw = searchParams.get('episodeIndex');
|
||||
const format = searchParams.get('format');
|
||||
const quality = searchParams.get('quality') || '';
|
||||
if (!sessionId || episodeIndexRaw == null) {
|
||||
return NextResponse.json({ error: '缺少参数' }, { status: 400 });
|
||||
}
|
||||
|
||||
const episodeIndex = Number.parseInt(episodeIndexRaw, 10);
|
||||
if (!Number.isInteger(episodeIndex) || episodeIndex < 0) {
|
||||
return NextResponse.json({ error: '无效的 episodeIndex' }, { status: 400 });
|
||||
}
|
||||
|
||||
const config = await getConfig();
|
||||
const pan123Config = config.NetDiskConfig?.Pan123;
|
||||
if (!pan123Config?.Enabled || !pan123Config.Account || !pan123Config.Password) {
|
||||
return NextResponse.json({ error: '123网盘未配置或未启用' }, { status: 400 });
|
||||
}
|
||||
|
||||
let session = refreshPan123NetdiskSession(sessionId) || getPan123NetdiskSession(sessionId);
|
||||
if (!session) {
|
||||
const payload = parsePan123NetdiskId(sessionId);
|
||||
const result = await listPan123ShareVideos(payload.shareUrl, payload.passcode || '');
|
||||
session = createPan123NetdiskSession({
|
||||
title: result.title,
|
||||
shareUrl: payload.shareUrl,
|
||||
passcode: payload.passcode,
|
||||
files: result.files,
|
||||
});
|
||||
}
|
||||
|
||||
const file = session.files[episodeIndex];
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: '播放文件不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
const playInfo = await getPan123PlayInfo(file, pan123Config.Account, pan123Config.Password);
|
||||
refreshPan123NetdiskSession(sessionId);
|
||||
const selectedUrl = playInfo.qualities.find((item) => item.name === quality)?.url || playInfo.url;
|
||||
|
||||
if (format === 'json') {
|
||||
return NextResponse.json({
|
||||
url: selectedUrl,
|
||||
headers: {},
|
||||
qualities: playInfo.qualities,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.redirect(selectedUrl);
|
||||
} catch (error) {
|
||||
console.error('[netdisk-123][play] error', error);
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : '获取播放地址失败' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,13 @@ import {
|
||||
parseTianyiNetdiskId,
|
||||
refreshTianyiNetdiskSession,
|
||||
} from '@/lib/netdisk/tianyi-session-cache';
|
||||
import { LEGACY_QUARK_TEMP_SOURCE, NETDISK_BAIDU_SOURCE, NETDISK_MOBILE_SOURCE, NETDISK_QUARK_SOURCE, NETDISK_TIANYI_SOURCE, normalizeNetdiskSource } from '@/lib/netdisk/source';
|
||||
import {
|
||||
createPan123NetdiskSession,
|
||||
getPan123NetdiskSession,
|
||||
parsePan123NetdiskId,
|
||||
refreshPan123NetdiskSession,
|
||||
} from '@/lib/netdisk/pan123-session-cache';
|
||||
import { LEGACY_QUARK_TEMP_SOURCE, NETDISK_123_SOURCE, NETDISK_BAIDU_SOURCE, NETDISK_MOBILE_SOURCE, NETDISK_QUARK_SOURCE, NETDISK_TIANYI_SOURCE, normalizeNetdiskSource } from '@/lib/netdisk/source';
|
||||
import {
|
||||
executeSavedSourceScript,
|
||||
normalizeScriptDetailResult,
|
||||
@@ -40,6 +46,30 @@ import {
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
function formatNetdiskEpisodeTitle(parsed: {
|
||||
season?: number;
|
||||
episode?: number;
|
||||
}, fallback: string) {
|
||||
if (parsed.season && parsed.episode) {
|
||||
const season = String(Math.trunc(parsed.season)).padStart(2, '0');
|
||||
const episodeValue = parsed.episode;
|
||||
const episode =
|
||||
Number.isInteger(episodeValue)
|
||||
? String(Math.trunc(episodeValue)).padStart(2, '0')
|
||||
: String(episodeValue);
|
||||
return `S${season}E${episode}`;
|
||||
}
|
||||
|
||||
if (parsed.episode) {
|
||||
const episodeValue = parsed.episode;
|
||||
return Number.isInteger(episodeValue)
|
||||
? `第${Math.trunc(episodeValue)}集`
|
||||
: `第${episodeValue}集`;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 source 和 id 直接获取视频详情
|
||||
* 这个API专门用于play页面快速获取当前源的详情
|
||||
@@ -327,16 +357,14 @@ export async function GET(request: NextRequest) {
|
||||
const { parseVideoFileName } = await import('@/lib/video-parser');
|
||||
const parsedFiles = mobileSession.files.map((file, index) => {
|
||||
const parsed = parseVideoFileName(file.name);
|
||||
return {
|
||||
...file,
|
||||
originalIndex: index,
|
||||
sortEpisode: parsed.episode || index + 1,
|
||||
isOVA: parsed.isOVA,
|
||||
displayTitle:
|
||||
parsed.title ||
|
||||
(parsed.episode ? `第${parsed.episode}集` : file.name),
|
||||
};
|
||||
}).sort((a, b) => {
|
||||
return {
|
||||
...file,
|
||||
originalIndex: index,
|
||||
sortEpisode: parsed.episode || index + 1,
|
||||
isOVA: parsed.isOVA,
|
||||
displayTitle: formatNetdiskEpisodeTitle(parsed, file.name),
|
||||
};
|
||||
}).sort((a, b) => {
|
||||
if (a.isOVA && !b.isOVA) return 1;
|
||||
if (!a.isOVA && b.isOVA) return -1;
|
||||
return a.sortEpisode !== b.sortEpisode
|
||||
@@ -407,8 +435,7 @@ export async function GET(request: NextRequest) {
|
||||
originalIndex: index,
|
||||
sortEpisode: parsed.episode || index + 1,
|
||||
isOVA: parsed.isOVA,
|
||||
displayTitle:
|
||||
parsed.title || (parsed.episode ? `第${parsed.episode}集` : file.name),
|
||||
displayTitle: formatNetdiskEpisodeTitle(parsed, file.name),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => {
|
||||
@@ -485,8 +512,7 @@ export async function GET(request: NextRequest) {
|
||||
originalIndex: index,
|
||||
sortEpisode: parsed.episode || index + 1,
|
||||
isOVA: parsed.isOVA,
|
||||
displayTitle:
|
||||
parsed.title || (parsed.episode ? `第${parsed.episode}集` : file.name),
|
||||
displayTitle: formatNetdiskEpisodeTitle(parsed, file.name),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => {
|
||||
@@ -520,6 +546,75 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
if (sourceCode === NETDISK_123_SOURCE) {
|
||||
try {
|
||||
const config = await getConfig();
|
||||
const pan123Config = config.NetDiskConfig?.Pan123;
|
||||
if (!pan123Config?.Enabled || !pan123Config.Account || !pan123Config.Password) {
|
||||
throw new Error('123网盘未配置或未启用');
|
||||
}
|
||||
|
||||
let session = refreshPan123NetdiskSession(id) || getPan123NetdiskSession(id);
|
||||
if (!session) {
|
||||
const payload = parsePan123NetdiskId(id);
|
||||
const { listPan123ShareVideos } = await import('@/lib/netdisk/pan123.client');
|
||||
const result = await listPan123ShareVideos(payload.shareUrl, payload.passcode || '');
|
||||
session = createPan123NetdiskSession({
|
||||
title: title || result.title,
|
||||
shareUrl: payload.shareUrl,
|
||||
passcode: payload.passcode,
|
||||
files: result.files,
|
||||
});
|
||||
}
|
||||
if (!session) {
|
||||
throw new Error('123网盘播放信息恢复失败');
|
||||
}
|
||||
|
||||
const pan123Session = session;
|
||||
const { parseVideoFileName } = await import('@/lib/video-parser');
|
||||
const parsedFiles = pan123Session.files
|
||||
.map((file, index) => {
|
||||
const parsed = parseVideoFileName(file.fileName);
|
||||
return {
|
||||
...file,
|
||||
originalIndex: index,
|
||||
sortEpisode: parsed.episode || index + 1,
|
||||
isOVA: parsed.isOVA,
|
||||
displayTitle: formatNetdiskEpisodeTitle(parsed, file.fileName),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => {
|
||||
if (a.isOVA && !b.isOVA) return 1;
|
||||
if (!a.isOVA && b.isOVA) return -1;
|
||||
return a.sortEpisode !== b.sortEpisode
|
||||
? a.sortEpisode - b.sortEpisode
|
||||
: a.fileName.localeCompare(b.fileName, 'zh-Hans-CN', { numeric: true, sensitivity: 'base' });
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
source: NETDISK_123_SOURCE,
|
||||
source_name: '123网盘',
|
||||
id: pan123Session.id,
|
||||
title: title || pan123Session.title,
|
||||
poster: '',
|
||||
year: '',
|
||||
douban_id: 0,
|
||||
desc: `123网盘分享:${pan123Session.shareUrl}`,
|
||||
episodes: parsedFiles.map((file) => (
|
||||
`/api/netdisk/123/play?id=${encodeURIComponent(pan123Session.id)}&episodeIndex=${file.originalIndex}`
|
||||
)),
|
||||
episodes_titles: parsedFiles.map((file) => file.displayTitle),
|
||||
proxyMode: false,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[netdisk-123][source-detail] error', error);
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (sourceCode === NETDISK_QUARK_SOURCE || sourceCode === LEGACY_QUARK_TEMP_SOURCE) {
|
||||
try {
|
||||
const config = await getConfig();
|
||||
@@ -555,7 +650,7 @@ export async function GET(request: NextRequest) {
|
||||
originalIndex: index,
|
||||
fileName: file.name,
|
||||
episode: parsed.episode || index + 1,
|
||||
title: parsed.title || (parsed.episode ? `第${parsed.episode}集` : file.name),
|
||||
title: formatNetdiskEpisodeTitle(parsed, file.name),
|
||||
isOVA: parsed.isOVA,
|
||||
};
|
||||
})
|
||||
|
||||
+120
-8
@@ -24,6 +24,7 @@ import HttpWarningDialog from '@/components/HttpWarningDialog';
|
||||
import PageLayout from '@/components/PageLayout';
|
||||
import ScrollableRow from '@/components/ScrollableRow';
|
||||
import { useSite } from '@/components/SiteProvider';
|
||||
import Toast, { ToastProps } from '@/components/Toast';
|
||||
import VideoCard from '@/components/VideoCard';
|
||||
|
||||
// 首页模块配置接口
|
||||
@@ -70,20 +71,129 @@ function HomeClient() {
|
||||
const [mangaEnabled, setMangaEnabled] = useState(false);
|
||||
const [showDirectPlayDialog, setShowDirectPlayDialog] = useState(false);
|
||||
const [directPlayUrl, setDirectPlayUrl] = useState('');
|
||||
const [directPlaySubmitting, setDirectPlaySubmitting] = useState(false);
|
||||
const [toast, setToast] = useState<ToastProps | null>(null);
|
||||
|
||||
const detectNetdiskLink = (url: string): {
|
||||
provider: 'quark' | 'mobile' | 'baidu' | 'tianyi' | '123';
|
||||
shareUrl: string;
|
||||
passcode?: string;
|
||||
} | null => {
|
||||
const trimmed = url.trim();
|
||||
|
||||
const pickPasscode = (...values: Array<string | undefined>) =>
|
||||
values.map((item) => item?.trim()).find(Boolean);
|
||||
|
||||
const inlinePasscode = (text: string) =>
|
||||
pickPasscode(
|
||||
text.match(/(?:提取码|访问码|密码)\s*[::=]?\s*([a-zA-Z0-9]{4,8})/i)?.[1],
|
||||
text.match(/[?&](?:pwd|passcode|accessCode)=([^&\s]+)/i)?.[1]
|
||||
);
|
||||
|
||||
if (/https:\/\/(?:www\.)?123(?:684|865|912|pan)\.(?:com|cn)\/s\//i.test(trimmed)) {
|
||||
return {
|
||||
provider: '123',
|
||||
shareUrl: trimmed,
|
||||
passcode: pickPasscode(
|
||||
trimmed.match(/[?&]pwd=([^&]+)/i)?.[1],
|
||||
inlinePasscode(trimmed)
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (/https:\/\/cloud\.189\.cn\/(web\/share\?code=|t\/)/i.test(trimmed) || /https:\/\/h5\.cloud\.189\.cn\/share\.html#\/t\//i.test(trimmed)) {
|
||||
return {
|
||||
provider: 'tianyi',
|
||||
shareUrl: trimmed,
|
||||
passcode: pickPasscode(
|
||||
trimmed.match(/[?&]pwd=([^&]+)/i)?.[1],
|
||||
inlinePasscode(trimmed)
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (/pan\.baidu\.com\/(s\/|wap\/init\?surl=)/i.test(trimmed)) {
|
||||
return {
|
||||
provider: 'baidu',
|
||||
shareUrl: trimmed,
|
||||
passcode: pickPasscode(
|
||||
trimmed.match(/[?&](?:pwd|accessCode)=([^&]+)/i)?.[1],
|
||||
inlinePasscode(trimmed)
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (/https:\/\/pan\.quark\.cn\/s\//i.test(trimmed)) {
|
||||
return {
|
||||
provider: 'quark',
|
||||
shareUrl: trimmed,
|
||||
passcode: pickPasscode(
|
||||
trimmed.match(/[?&](?:pwd|passcode)=([^&]+)/i)?.[1],
|
||||
inlinePasscode(trimmed)
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (/https:\/\/(?:yun|caiyun)\.139\.com\//i.test(trimmed)) {
|
||||
return { provider: 'mobile', shareUrl: trimmed };
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const handleDirectPlay = () => {
|
||||
setDirectPlayUrl('');
|
||||
setShowDirectPlayDialog(true);
|
||||
};
|
||||
|
||||
const submitDirectPlay = () => {
|
||||
const submitDirectPlay = async () => {
|
||||
const trimmed = directPlayUrl.trim();
|
||||
if (!trimmed) return;
|
||||
const encoded = base58Encode(trimmed);
|
||||
if (!encoded) return;
|
||||
setShowDirectPlayDialog(false);
|
||||
setDirectPlayUrl('');
|
||||
router.push(`/play?source=directplay&id=${encodeURIComponent(encoded)}`);
|
||||
setDirectPlaySubmitting(true);
|
||||
try {
|
||||
const netdisk = detectNetdiskLink(trimmed);
|
||||
if (netdisk) {
|
||||
const source =
|
||||
netdisk.provider === 'mobile'
|
||||
? 'netdisk-mobile'
|
||||
: netdisk.provider === 'baidu'
|
||||
? 'netdisk-baidu'
|
||||
: netdisk.provider === 'tianyi'
|
||||
? 'netdisk-tianyi'
|
||||
: netdisk.provider === '123'
|
||||
? 'netdisk-123'
|
||||
: 'netdisk-quark';
|
||||
const id = base58Encode(
|
||||
JSON.stringify({
|
||||
shareUrl: netdisk.shareUrl,
|
||||
passcode: netdisk.passcode || '',
|
||||
})
|
||||
);
|
||||
if (!id) {
|
||||
throw new Error('网盘链接编码失败');
|
||||
}
|
||||
const targetUrl = `/play?source=${encodeURIComponent(source)}&id=${encodeURIComponent(id)}&title=${encodeURIComponent('网盘直链播放')}`;
|
||||
setShowDirectPlayDialog(false);
|
||||
setDirectPlayUrl('');
|
||||
window.location.assign(targetUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
const encoded = base58Encode(trimmed);
|
||||
if (!encoded) return;
|
||||
const targetUrl = `/play?source=directplay&id=${encodeURIComponent(encoded)}`;
|
||||
setShowDirectPlayDialog(false);
|
||||
setDirectPlayUrl('');
|
||||
window.location.assign(targetUrl);
|
||||
} catch (error) {
|
||||
setToast({
|
||||
message: error instanceof Error ? error.message : '播放失败',
|
||||
type: 'error',
|
||||
onClose: () => setToast(null),
|
||||
});
|
||||
} finally {
|
||||
setDirectPlaySubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadHomeLayoutSettings = () => {
|
||||
@@ -759,16 +869,18 @@ function HomeClient() {
|
||||
</button>
|
||||
<button
|
||||
onClick={submitDirectPlay}
|
||||
disabled={!directPlayUrl.trim()}
|
||||
disabled={!directPlayUrl.trim() || directPlaySubmitting}
|
||||
className='px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed'
|
||||
>
|
||||
开始播放
|
||||
{directPlaySubmitting ? '处理中...' : '开始播放'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{toast && <Toast {...toast} />}
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2504,6 +2504,7 @@ function PlayPageClient() {
|
||||
const isSpecialLazyPlayUrl =
|
||||
isXiaoyaLazyPlayUrl ||
|
||||
newUrl.startsWith('/api/openlist/play') ||
|
||||
newUrl.startsWith('/api/netdisk/123/play') ||
|
||||
newUrl.startsWith('/api/netdisk/quark/play') ||
|
||||
newUrl.startsWith('/api/netdisk/baidu/play') ||
|
||||
newUrl.startsWith('/api/source-script/play');
|
||||
|
||||
@@ -170,6 +170,8 @@ export default function PansouSearch({
|
||||
? '/api/netdisk/baidu/instant-play'
|
||||
: cloudType === 'tianyi'
|
||||
? '/api/netdisk/tianyi/instant-play'
|
||||
: cloudType === '123'
|
||||
? '/api/netdisk/123/instant-play'
|
||||
: '/api/netdisk/quark/instant-play';
|
||||
const response = await fetch(instantPlayApi, {
|
||||
method: 'POST',
|
||||
@@ -189,7 +191,7 @@ export default function PansouSearch({
|
||||
}
|
||||
|
||||
router.push(
|
||||
`/play?source=${encodeURIComponent(data.source || (cloudType === 'mobile' ? 'netdisk-mobile' : cloudType === 'baidu' ? 'netdisk-baidu' : cloudType === 'tianyi' ? 'netdisk-tianyi' : 'netdisk-quark'))}&id=${encodeURIComponent(data.id)}&title=${encodeURIComponent(data.title || keyword)}`
|
||||
`/play?source=${encodeURIComponent(data.source || (cloudType === 'mobile' ? 'netdisk-mobile' : cloudType === 'baidu' ? 'netdisk-baidu' : cloudType === 'tianyi' ? 'netdisk-tianyi' : cloudType === '123' ? 'netdisk-123' : 'netdisk-quark'))}&id=${encodeURIComponent(data.id)}&title=${encodeURIComponent(data.title || keyword)}`
|
||||
);
|
||||
} catch (err: any) {
|
||||
setToast({
|
||||
@@ -347,7 +349,7 @@ export default function PansouSearch({
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<div className='flex items-center gap-1 flex-shrink-0'>
|
||||
{(cloudType === 'quark' || cloudType === 'mobile' || cloudType === 'baidu' || cloudType === 'tianyi') && (
|
||||
{(cloudType === 'quark' || cloudType === 'mobile' || cloudType === 'baidu' || cloudType === 'tianyi' || cloudType === '123') && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => handleNetdiskInstantPlay(cloudType, link)}
|
||||
|
||||
@@ -165,6 +165,11 @@ export interface AdminConfig {
|
||||
Account: string;
|
||||
Password: string;
|
||||
};
|
||||
Pan123?: {
|
||||
Enabled: boolean;
|
||||
Account: string;
|
||||
Password: string;
|
||||
};
|
||||
};
|
||||
AIConfig?: {
|
||||
Enabled: boolean; // 是否启用AI问片功能
|
||||
|
||||
@@ -683,6 +683,11 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
|
||||
Account: '',
|
||||
Password: '',
|
||||
},
|
||||
Pan123: {
|
||||
Enabled: false,
|
||||
Account: '',
|
||||
Password: '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -716,6 +721,14 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
|
||||
};
|
||||
}
|
||||
|
||||
if (!adminConfig.NetDiskConfig.Pan123) {
|
||||
adminConfig.NetDiskConfig.Pan123 = {
|
||||
Enabled: false,
|
||||
Account: '',
|
||||
Password: '',
|
||||
};
|
||||
}
|
||||
|
||||
// 确保音乐配置存在
|
||||
if (!adminConfig.MusicConfig) {
|
||||
adminConfig.MusicConfig = {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { base58Decode, base58Encode } from '@/lib/utils';
|
||||
|
||||
import type { Pan123ShareVideoFile } from './pan123.client';
|
||||
|
||||
export interface Pan123NetdiskSession {
|
||||
id: string;
|
||||
provider: 'pan123';
|
||||
title: string;
|
||||
shareUrl: string;
|
||||
passcode?: string;
|
||||
files: Pan123ShareVideoFile[];
|
||||
createdAt: number;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
const TTL_MS = 30 * 60 * 1000;
|
||||
const sessionStore = new Map<string, Pan123NetdiskSession>();
|
||||
|
||||
export function buildPan123NetdiskId(input: { shareUrl: string; passcode?: string }) {
|
||||
return base58Encode(JSON.stringify({ shareUrl: input.shareUrl, passcode: input.passcode || '' }));
|
||||
}
|
||||
|
||||
export function parsePan123NetdiskId(id: string): { shareUrl: string; passcode?: string } {
|
||||
try {
|
||||
const decoded = base58Decode(id);
|
||||
const parsed = JSON.parse(decoded);
|
||||
if (!parsed?.shareUrl || typeof parsed.shareUrl !== 'string') {
|
||||
throw new Error('invalid 123 netdisk id');
|
||||
}
|
||||
return {
|
||||
shareUrl: parsed.shareUrl,
|
||||
passcode: typeof parsed.passcode === 'string' ? parsed.passcode : '',
|
||||
};
|
||||
} catch {
|
||||
throw new Error('无效的123网盘播放 ID');
|
||||
}
|
||||
}
|
||||
|
||||
function pruneExpiredSessions() {
|
||||
const now = Date.now();
|
||||
for (const [key, value] of Array.from(sessionStore.entries())) {
|
||||
if (value.expiresAt <= now) sessionStore.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
export function createPan123NetdiskSession(input: {
|
||||
title: string;
|
||||
shareUrl: string;
|
||||
passcode?: string;
|
||||
files: Pan123ShareVideoFile[];
|
||||
}) {
|
||||
pruneExpiredSessions();
|
||||
const now = Date.now();
|
||||
const id = buildPan123NetdiskId({ shareUrl: input.shareUrl, passcode: input.passcode });
|
||||
const session: Pan123NetdiskSession = {
|
||||
id,
|
||||
provider: 'pan123',
|
||||
title: input.title,
|
||||
shareUrl: input.shareUrl,
|
||||
passcode: input.passcode,
|
||||
files: input.files,
|
||||
createdAt: now,
|
||||
expiresAt: now + TTL_MS,
|
||||
};
|
||||
sessionStore.set(id, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
export function getPan123NetdiskSession(id: string): Pan123NetdiskSession | null {
|
||||
pruneExpiredSessions();
|
||||
const session = sessionStore.get(id);
|
||||
if (!session) return null;
|
||||
if (session.expiresAt <= Date.now()) {
|
||||
sessionStore.delete(id);
|
||||
return null;
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
export function refreshPan123NetdiskSession(id: string): Pan123NetdiskSession | null {
|
||||
const session = getPan123NetdiskSession(id);
|
||||
if (!session) return null;
|
||||
session.expiresAt = Date.now() + TTL_MS;
|
||||
sessionStore.set(id, session);
|
||||
return session;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { getConfig } from '@/lib/config';
|
||||
|
||||
import { listPan123ShareVideos } from './pan123.client';
|
||||
import {
|
||||
createPan123NetdiskSession,
|
||||
getPan123NetdiskSession,
|
||||
parsePan123NetdiskId,
|
||||
refreshPan123NetdiskSession,
|
||||
} from './pan123-session-cache';
|
||||
|
||||
export async function resolvePan123Session(id: string) {
|
||||
const config = await getConfig();
|
||||
const pan123Config = config.NetDiskConfig?.Pan123;
|
||||
if (!pan123Config?.Enabled || !pan123Config.Account || !pan123Config.Password) {
|
||||
throw new Error('123网盘未配置或未启用');
|
||||
}
|
||||
|
||||
let session = refreshPan123NetdiskSession(id) || getPan123NetdiskSession(id);
|
||||
if (!session) {
|
||||
const payload = parsePan123NetdiskId(id);
|
||||
const result = await listPan123ShareVideos(payload.shareUrl, payload.passcode || '');
|
||||
session = createPan123NetdiskSession({
|
||||
title: result.title,
|
||||
shareUrl: payload.shareUrl,
|
||||
passcode: payload.passcode,
|
||||
files: result.files,
|
||||
});
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
throw new Error('123网盘播放信息恢复失败');
|
||||
}
|
||||
|
||||
return {
|
||||
session,
|
||||
account: pan123Config.Account,
|
||||
password: pan123Config.Password,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
export interface Pan123ShareVideoFile {
|
||||
shareKey: string;
|
||||
fileId: string;
|
||||
s3KeyFlag: string;
|
||||
size: number;
|
||||
etag: string;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
export interface Pan123ShareListResult {
|
||||
title: string;
|
||||
files: Pan123ShareVideoFile[];
|
||||
}
|
||||
|
||||
const SHARE_API_BASE = 'https://www.123684.com/b/api/share/';
|
||||
const VIDEO_API_BASE = 'https://www.123684.com/b/api/video/';
|
||||
const LOGIN_URL = 'https://login.123pan.com/api/user/sign_in';
|
||||
const LOGIN_TTL_MS = 30 * 60 * 1000;
|
||||
const SHARE_PAGE_TIMEOUT_MS = 15000;
|
||||
const MAX_TRAVERSE_NODES = 2000;
|
||||
const MAX_TRAVERSE_DEPTH = 20;
|
||||
const VIDEO_EXTENSIONS = [
|
||||
'.mp4', '.mkv', '.avi', '.mov', '.flv', '.wmv', '.m3u8', '.ts', '.rmvb', '.rm', '.mpeg', '.mpg', '.m4v', '.webm',
|
||||
];
|
||||
|
||||
const authStore = new Map<string, { token: string; expiresAt: number }>();
|
||||
|
||||
function makeCacheKey(account: string, password: string) {
|
||||
return `${account}\n${password}`;
|
||||
}
|
||||
|
||||
function pruneAuthStore() {
|
||||
const now = Date.now();
|
||||
for (const [key, value] of Array.from(authStore.entries())) {
|
||||
if (value.expiresAt <= now) authStore.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
function baseHeaders(): HeadersInit {
|
||||
return {
|
||||
'User-Agent':
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
|
||||
'Content-Type': 'application/json;charset=UTF-8',
|
||||
};
|
||||
}
|
||||
|
||||
function isPan123VideoFile(name: string) {
|
||||
const lower = name.toLowerCase();
|
||||
return VIDEO_EXTENSIONS.some((ext) => lower.endsWith(ext));
|
||||
}
|
||||
|
||||
function shouldTreatAsPlayableFile(item: any) {
|
||||
const fileName = String(item?.FileName || '');
|
||||
const category = Number(item?.Category);
|
||||
if (category === 0) return false;
|
||||
if (isPan123VideoFile(fileName)) return true;
|
||||
if (category === 2) return true;
|
||||
// 某些 123 分享返回的 Category 不稳定,只要不是目录且有文件标识,就作为候选文件
|
||||
return Boolean(item?.FileId && fileName);
|
||||
}
|
||||
|
||||
function decodeJwtExp(token: string): number | null {
|
||||
try {
|
||||
const [, payload] = token.split('.');
|
||||
if (!payload) return null;
|
||||
const json = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
||||
return typeof json.exp === 'number' ? json.exp * 1000 : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function assertSafe(value: string, label: string) {
|
||||
const normalized = value.trim();
|
||||
for (let i = 0; i < normalized.length; i += 1) {
|
||||
if (normalized.charCodeAt(i) > 255) {
|
||||
throw new Error(`${label} 含有非法字符,请检查是否包含中文标点或说明文字`);
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function normalizePan123Account(value: string) {
|
||||
return assertSafe(value, '123网盘账号');
|
||||
}
|
||||
|
||||
export function normalizePan123Password(value: string) {
|
||||
return assertSafe(value, '123网盘密码');
|
||||
}
|
||||
|
||||
export function parsePan123ShareUrl(url: string, passcode = ''): { shareKey: string; sharePwd: string } {
|
||||
let panUrl = decodeURIComponent(url.trim()).replace(/[#.,,/\s]+$/, '');
|
||||
let sharePwd = passcode || '';
|
||||
|
||||
try {
|
||||
const parsed = new URL(panUrl);
|
||||
if (!sharePwd) {
|
||||
sharePwd = parsed.searchParams.get('pwd') || parsed.searchParams.get('password') || '';
|
||||
}
|
||||
panUrl = `${parsed.origin}${parsed.pathname}`;
|
||||
} catch {
|
||||
// ignore url parse error, continue with regex fallback
|
||||
}
|
||||
|
||||
const pwdMatch = panUrl.match(/[;,,\s]+[\u63d0\u53d6\u7801::\s]*([a-zA-Z0-9]{4})/);
|
||||
if (!sharePwd && pwdMatch?.[1]) {
|
||||
sharePwd = pwdMatch[1];
|
||||
panUrl = panUrl.substring(0, pwdMatch.index);
|
||||
} else if (!sharePwd && panUrl.includes('?')) {
|
||||
sharePwd = panUrl.slice(-4);
|
||||
panUrl = panUrl.split('?')[0];
|
||||
} else if (!sharePwd && panUrl.includes('码')) {
|
||||
sharePwd = panUrl.slice(-4);
|
||||
const firstChinese = panUrl.match(/[\u4e00-\u9fa5]/);
|
||||
if (firstChinese?.index != null) {
|
||||
panUrl = panUrl.slice(0, firstChinese.index);
|
||||
}
|
||||
}
|
||||
|
||||
const regex = /https:\/\/(www\.)?123(684|865|912|pan)\.(com|cn)\/s\/([^\\/]+)/;
|
||||
const matches = regex.exec(panUrl);
|
||||
if (!matches?.[4]) {
|
||||
throw new Error('无法解析123网盘分享链接');
|
||||
}
|
||||
const shareKey = matches[4];
|
||||
return { shareKey, sharePwd };
|
||||
}
|
||||
|
||||
async function parseJsonResponse<T = any>(response: Response): Promise<T> {
|
||||
const text = await response.text();
|
||||
try {
|
||||
return JSON.parse(text) as T;
|
||||
} catch {
|
||||
throw new Error(`123网盘接口返回异常:${text.slice(0, 200)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number) {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
return await fetch(url, {
|
||||
...init,
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearPan123AuthCache(account: string, password: string) {
|
||||
authStore.delete(makeCacheKey(normalizePan123Account(account), normalizePan123Password(password)));
|
||||
}
|
||||
|
||||
async function loginPan123(account: string, password: string): Promise<string> {
|
||||
const safeAccount = normalizePan123Account(account);
|
||||
const safePassword = normalizePan123Password(password);
|
||||
const cacheKey = makeCacheKey(safeAccount, safePassword);
|
||||
pruneAuthStore();
|
||||
const cached = authStore.get(cacheKey);
|
||||
if (cached && cached.expiresAt > Date.now()) return cached.token;
|
||||
|
||||
const response = await fetch(LOGIN_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...baseHeaders(),
|
||||
'App-Version': '43',
|
||||
Referer:
|
||||
'https://login.123pan.com/centerlogin?redirect_url=https%3A%2F%2Fwww.123684.com&source_page=website',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
passport: safeAccount,
|
||||
password: safePassword,
|
||||
remember: true,
|
||||
}),
|
||||
cache: 'no-store',
|
||||
});
|
||||
const data = await parseJsonResponse<any>(response);
|
||||
const token = String(data?.data?.token || '');
|
||||
if (!response.ok || !token) {
|
||||
throw new Error(data?.message || data?.msg || '123网盘登录失败');
|
||||
}
|
||||
|
||||
const exp = decodeJwtExp(token);
|
||||
authStore.set(cacheKey, {
|
||||
token,
|
||||
expiresAt: exp && exp > Date.now() ? exp : Date.now() + LOGIN_TTL_MS,
|
||||
});
|
||||
return token;
|
||||
}
|
||||
|
||||
async function fetchSharePage(
|
||||
shareKey: string,
|
||||
sharePwd: string,
|
||||
next: string | number = 0,
|
||||
parentFileId = 0,
|
||||
depth = 0
|
||||
): Promise<any> {
|
||||
const query = new URLSearchParams({
|
||||
limit: '100',
|
||||
next: String(next),
|
||||
orderBy: 'file_name',
|
||||
orderDirection: 'asc',
|
||||
shareKey,
|
||||
SharePwd: sharePwd || '',
|
||||
ParentFileId: String(parentFileId),
|
||||
Page: '1',
|
||||
});
|
||||
const url = `${SHARE_API_BASE}get?${query.toString()}`;
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetchWithTimeout(
|
||||
url,
|
||||
{
|
||||
headers: baseHeaders(),
|
||||
cache: 'no-store',
|
||||
},
|
||||
SHARE_PAGE_TIMEOUT_MS
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw new Error(`123网盘目录请求超时(parentFileId=${parentFileId}, next=${next}, depth=${depth})`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const data = await parseJsonResponse<any>(response);
|
||||
if (!response.ok) {
|
||||
throw new Error(data?.message || data?.msg || `123网盘接口请求失败 (${response.status})`);
|
||||
}
|
||||
return data?.data || null;
|
||||
}
|
||||
|
||||
async function collectPan123FilesRecursive(
|
||||
shareKey: string,
|
||||
sharePwd: string,
|
||||
parentFileId = 0,
|
||||
fileNameState?: { value: string },
|
||||
state?: {
|
||||
visitedNodes: number;
|
||||
seenFolderIds: Set<string>;
|
||||
seenFileIds: Set<string>;
|
||||
seenPageKeys: Set<string>;
|
||||
},
|
||||
depth = 0
|
||||
): Promise<Pan123ShareVideoFile[]> {
|
||||
const files: Pan123ShareVideoFile[] = [];
|
||||
let next: string | number = 0;
|
||||
let hasMore = true;
|
||||
const traverseState = state || {
|
||||
visitedNodes: 0,
|
||||
seenFolderIds: new Set<string>(),
|
||||
seenFileIds: new Set<string>(),
|
||||
seenPageKeys: new Set<string>(),
|
||||
};
|
||||
const parentFolderKey = String(parentFileId);
|
||||
|
||||
if (depth > MAX_TRAVERSE_DEPTH) {
|
||||
throw new Error(`123网盘目录层级过深,已超过限制(${MAX_TRAVERSE_DEPTH})`);
|
||||
}
|
||||
|
||||
if (depth > 0) {
|
||||
if (traverseState.seenFolderIds.has(parentFolderKey)) {
|
||||
return files;
|
||||
}
|
||||
traverseState.seenFolderIds.add(parentFolderKey);
|
||||
}
|
||||
|
||||
while (hasMore) {
|
||||
const pageKey = `${parentFolderKey}:${String(next)}`;
|
||||
if (traverseState.seenPageKeys.has(pageKey)) {
|
||||
break;
|
||||
}
|
||||
traverseState.seenPageKeys.add(pageKey);
|
||||
|
||||
const data: any = await fetchSharePage(shareKey, sharePwd, next, parentFileId, depth);
|
||||
if (!data) break;
|
||||
|
||||
const infoList = Array.isArray(data.InfoList) ? data.InfoList : [];
|
||||
traverseState.visitedNodes += infoList.length;
|
||||
if (traverseState.visitedNodes > MAX_TRAVERSE_NODES) {
|
||||
throw new Error(`123网盘遍历节点过多,已超过限制(${MAX_TRAVERSE_NODES})`);
|
||||
}
|
||||
const childFolders: Array<string | number> = [];
|
||||
const queuedChildFolderIds = new Set<string>();
|
||||
|
||||
infoList.forEach((item: any) => {
|
||||
const fileName = String(item.FileName || '');
|
||||
const itemFileId = String(item.FileId || '');
|
||||
if (fileNameState && !fileNameState.value) {
|
||||
fileNameState.value = fileName;
|
||||
}
|
||||
|
||||
if (Number(item.Category) === 0) {
|
||||
if (!itemFileId) return;
|
||||
if (traverseState.seenFolderIds.has(itemFileId) || queuedChildFolderIds.has(itemFileId)) {
|
||||
return;
|
||||
}
|
||||
queuedChildFolderIds.add(itemFileId);
|
||||
childFolders.push(itemFileId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldTreatAsPlayableFile(item)) {
|
||||
if (!itemFileId) return;
|
||||
if (traverseState.seenFileIds.has(itemFileId)) {
|
||||
return;
|
||||
}
|
||||
traverseState.seenFileIds.add(itemFileId);
|
||||
files.push({
|
||||
shareKey,
|
||||
fileId: itemFileId,
|
||||
s3KeyFlag: String(item.S3KeyFlag || ''),
|
||||
size: Number(item.Size || 0),
|
||||
etag: String(item.Etag || ''),
|
||||
fileName,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const nestedFiles = await Promise.all(
|
||||
childFolders.map((folderId) =>
|
||||
collectPan123FilesRecursive(
|
||||
shareKey,
|
||||
sharePwd,
|
||||
Number(folderId),
|
||||
fileNameState,
|
||||
traverseState,
|
||||
depth + 1
|
||||
)
|
||||
)
|
||||
);
|
||||
files.push(...nestedFiles.flat());
|
||||
|
||||
const nextCursor: string | number | null | undefined = data.Next;
|
||||
if (nextCursor === undefined || nextCursor === null || nextCursor === '' || nextCursor === -1 || nextCursor === '0' || nextCursor === 0) {
|
||||
hasMore = false;
|
||||
} else {
|
||||
next = nextCursor;
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
export async function listPan123ShareVideos(shareUrl: string, passcode = ''): Promise<Pan123ShareListResult> {
|
||||
const { shareKey, sharePwd } = parsePan123ShareUrl(shareUrl, passcode);
|
||||
const fileNameState = { value: '' };
|
||||
const files = (await collectPan123FilesRecursive(shareKey, sharePwd, 0, fileNameState))
|
||||
.filter((file) => file.fileId)
|
||||
.sort((a, b) => a.fileName.localeCompare(b.fileName, 'zh-Hans-CN', { numeric: true, sensitivity: 'base' }));
|
||||
|
||||
if (files.length === 0) {
|
||||
throw new Error('123网盘分享中没有视频文件');
|
||||
}
|
||||
|
||||
return {
|
||||
title: fileNameState.value || (files.length === 1 ? files[0].fileName.replace(/\.[^.]+$/, '') : '123网盘立即播放'),
|
||||
files,
|
||||
};
|
||||
}
|
||||
|
||||
function decodePan123DownloadUrl(downloadUrl: string) {
|
||||
const query = downloadUrl.split('?')[1] || '';
|
||||
const params = new URLSearchParams(query);
|
||||
const encoded = params.get('params') || '';
|
||||
if (!encoded) return downloadUrl;
|
||||
return Buffer.from(encoded, 'base64').toString('utf8');
|
||||
}
|
||||
|
||||
export async function getPan123PlayInfo(
|
||||
file: Pan123ShareVideoFile,
|
||||
account: string,
|
||||
password: string
|
||||
): Promise<{ url: string; qualities: Array<{ name: string; url: string }> }> {
|
||||
let lastError: unknown;
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const token = await loginPan123(account, password);
|
||||
try {
|
||||
const downloadResp = await fetch(`${SHARE_API_BASE}download/info`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...baseHeaders(),
|
||||
Authorization: `Bearer ${token}`,
|
||||
platform: 'android',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
ShareKey: file.shareKey,
|
||||
FileID: file.fileId,
|
||||
S3KeyFlag: file.s3KeyFlag,
|
||||
Size: file.size,
|
||||
Etag: file.etag,
|
||||
}),
|
||||
cache: 'no-store',
|
||||
});
|
||||
const downloadData = await parseJsonResponse<any>(downloadResp);
|
||||
if (!downloadResp.ok) {
|
||||
throw new Error(downloadData?.message || downloadData?.msg || `123网盘播放接口请求失败 (${downloadResp.status})`);
|
||||
}
|
||||
|
||||
const rawUrl = String(downloadData?.data?.DownloadURL || '');
|
||||
const originalUrl = rawUrl ? decodePan123DownloadUrl(rawUrl) : '';
|
||||
|
||||
const transcodeResp = await fetch(
|
||||
`${VIDEO_API_BASE}play/info?${new URLSearchParams({
|
||||
etag: file.etag,
|
||||
size: String(file.size),
|
||||
from: '1',
|
||||
shareKey: file.shareKey,
|
||||
}).toString()}`,
|
||||
{
|
||||
headers: {
|
||||
...baseHeaders(),
|
||||
Authorization: `Bearer ${token}`,
|
||||
platform: 'android',
|
||||
},
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
const transcodeData = await parseJsonResponse<any>(transcodeResp);
|
||||
const qualities = Array.isArray(transcodeData?.data?.video_play_info)
|
||||
? transcodeData.data.video_play_info
|
||||
.filter((item: any) => item?.url)
|
||||
.sort((a: any, b: any) => Number(b.height || 0) - Number(a.height || 0))
|
||||
.map((item: any) => ({
|
||||
name: String(item.resolution || '转码'),
|
||||
url: String(item.url),
|
||||
}))
|
||||
: [];
|
||||
|
||||
const allQualities = [
|
||||
...(originalUrl ? [{ name: '原画', url: originalUrl }] : []),
|
||||
...qualities,
|
||||
];
|
||||
const url = allQualities[0]?.url;
|
||||
if (!url) {
|
||||
throw new Error('未获取到123网盘播放地址');
|
||||
}
|
||||
return { url, qualities: allQualities };
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
clearPan123AuthCache(account, password);
|
||||
}
|
||||
}
|
||||
throw lastError instanceof Error ? lastError : new Error('未获取到123网盘播放地址');
|
||||
}
|
||||
|
||||
export async function validatePan123Credentials(account: string, password: string): Promise<void> {
|
||||
await loginPan123(account, password);
|
||||
}
|
||||
@@ -3,8 +3,9 @@ export const NETDISK_QUARK_SOURCE = 'netdisk-quark';
|
||||
export const NETDISK_MOBILE_SOURCE = 'netdisk-mobile';
|
||||
export const NETDISK_BAIDU_SOURCE = 'netdisk-baidu';
|
||||
export const NETDISK_TIANYI_SOURCE = 'netdisk-tianyi';
|
||||
export const NETDISK_123_SOURCE = 'netdisk-123';
|
||||
|
||||
export type NetdiskProvider = 'quark' | 'mobile' | 'baidu' | 'tianyi';
|
||||
export type NetdiskProvider = 'quark' | 'mobile' | 'baidu' | 'tianyi' | '123';
|
||||
|
||||
export function normalizeNetdiskSource(source?: string | null): string {
|
||||
if (!source) return '';
|
||||
@@ -14,7 +15,7 @@ export function normalizeNetdiskSource(source?: string | null): string {
|
||||
|
||||
export function isNetdiskSource(source?: string | null): boolean {
|
||||
const normalized = normalizeNetdiskSource(source);
|
||||
return normalized === NETDISK_QUARK_SOURCE || normalized === NETDISK_MOBILE_SOURCE || normalized === NETDISK_BAIDU_SOURCE || normalized === NETDISK_TIANYI_SOURCE;
|
||||
return normalized === NETDISK_QUARK_SOURCE || normalized === NETDISK_MOBILE_SOURCE || normalized === NETDISK_BAIDU_SOURCE || normalized === NETDISK_TIANYI_SOURCE || normalized === NETDISK_123_SOURCE;
|
||||
}
|
||||
|
||||
export function getNetdiskProvider(source?: string | null): NetdiskProvider | null {
|
||||
@@ -23,6 +24,7 @@ export function getNetdiskProvider(source?: string | null): NetdiskProvider | nu
|
||||
if (normalized === NETDISK_MOBILE_SOURCE) return 'mobile';
|
||||
if (normalized === NETDISK_BAIDU_SOURCE) return 'baidu';
|
||||
if (normalized === NETDISK_TIANYI_SOURCE) return 'tianyi';
|
||||
if (normalized === NETDISK_123_SOURCE) return '123';
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -41,3 +43,7 @@ export function isNetdiskBaiduSource(source?: string | null): boolean {
|
||||
export function isNetdiskTianyiSource(source?: string | null): boolean {
|
||||
return normalizeNetdiskSource(source) === NETDISK_TIANYI_SOURCE;
|
||||
}
|
||||
|
||||
export function isNetdisk123Source(source?: string | null): boolean {
|
||||
return normalizeNetdiskSource(source) === NETDISK_123_SOURCE;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user