夸克网盘转存

This commit is contained in:
mtvpls
2026-04-07 16:58:22 +08:00
parent 4bed01e7a3
commit 9b707c1a17
10 changed files with 1132 additions and 7 deletions
+85
View File
@@ -0,0 +1,85 @@
/* eslint-disable no-console */
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig, setCachedConfig } from '@/lib/config';
import { db } from '@/lib/db';
import {
assertQuarkCookieHeaderSafe,
normalizeQuarkCookie,
validateQuarkCookieReadable,
} from '@/lib/quark.client';
export const runtime = 'nodejs';
function requireOwner(username: string | undefined) {
return username === process.env.USERNAME;
}
export async function POST(request: NextRequest) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (storageType === 'localstorage') {
return NextResponse.json(
{ error: '不支持本地存储进行管理员配置' },
{ status: 400 }
);
}
try {
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo?.username) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
if (!requireOwner(authInfo.username)) {
const userInfo = await db.getUserInfoV2(authInfo.username);
if (!userInfo || userInfo.role !== 'admin' || userInfo.banned) {
return NextResponse.json({ error: '权限不足' }, { status: 401 });
}
}
const body = await request.json();
const { action, Quark } = body;
const adminConfig = await getConfig();
if (action === 'save') {
const normalizedCookie = Quark?.Cookie ? assertQuarkCookieHeaderSafe(Quark.Cookie) : '';
adminConfig.NetDiskConfig = adminConfig.NetDiskConfig || {};
adminConfig.NetDiskConfig.Quark = {
Enabled: Boolean(Quark?.Enabled),
Cookie: normalizedCookie,
SavePath: Quark?.SavePath || '/',
PlayTempSavePath: Quark?.PlayTempSavePath || '/',
OpenListTempPath: Quark?.OpenListTempPath || '/',
};
await db.saveAdminConfig(adminConfig);
await setCachedConfig(adminConfig);
return NextResponse.json({ success: true, message: '保存成功' });
}
if (action === 'validate') {
if (!Quark?.Cookie) {
return NextResponse.json({ error: '请先填写夸克 Cookie' }, { status: 400 });
}
await validateQuarkCookieReadable(normalizeQuarkCookie(Quark.Cookie));
return NextResponse.json({
success: true,
message: '夸克cookie正常',
});
}
return NextResponse.json({ error: '未知操作' }, { status: 400 });
} catch (error) {
console.error('[Admin NetDisk] 操作失败:', error);
return NextResponse.json(
{ error: error instanceof Error ? error.message : '操作失败' },
{ status: 500 }
);
}
}
+67
View File
@@ -0,0 +1,67 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config';
import { createQuarkInstantPlayFolder } from '@/lib/quark.client';
import { base58Encode } from '@/lib/utils';
export const runtime = 'nodejs';
function joinPath(...parts: string[]) {
const joined = parts
.filter(Boolean)
.join('/')
.replace(/\/+/g, '/');
return joined.startsWith('/') ? joined : `/${joined}`;
}
export async function POST(request: NextRequest) {
try {
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo?.username) {
return NextResponse.json({ error: '未登录' }, { status: 401 });
}
const { shareUrl, passcode, title } = await request.json();
if (!shareUrl) {
return NextResponse.json({ error: '分享链接不能为空' }, { status: 400 });
}
const config = await getConfig();
const quarkConfig = config.NetDiskConfig?.Quark;
if (!quarkConfig?.Enabled || !quarkConfig.Cookie) {
return NextResponse.json({ error: '夸克网盘未配置或未启用' }, { status: 400 });
}
const result = await createQuarkInstantPlayFolder(quarkConfig.Cookie, {
shareUrl,
passcode,
playTempSavePath: quarkConfig.PlayTempSavePath,
title,
});
if (!result.folderName) {
throw new Error('未生成临时播放目录');
}
const openlistFolderPath = joinPath(
quarkConfig.OpenListTempPath,
result.folderName
);
return NextResponse.json({
success: true,
source: 'quark-temp',
id: base58Encode(openlistFolderPath),
title: title || result.folderName,
openlistFolderPath,
...result,
});
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : '立即播放失败' },
{ status: 500 }
);
}
}
+44
View File
@@ -0,0 +1,44 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
import { getConfig } from '@/lib/config';
import { transferQuarkShare } from '@/lib/quark.client';
export const runtime = 'nodejs';
export async function POST(request: NextRequest) {
try {
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo?.username) {
return NextResponse.json({ error: '未登录' }, { status: 401 });
}
const { shareUrl, passcode } = await request.json();
if (!shareUrl) {
return NextResponse.json({ error: '分享链接不能为空' }, { status: 400 });
}
const config = await getConfig();
const quarkConfig = config.NetDiskConfig?.Quark;
if (!quarkConfig?.Enabled || !quarkConfig.Cookie) {
return NextResponse.json({ error: '夸克网盘未配置或未启用' }, { status: 400 });
}
const result = await transferQuarkShare(quarkConfig.Cookie, {
shareUrl,
passcode,
savePath: quarkConfig.SavePath,
});
return NextResponse.json({
success: true,
...result,
});
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : '转存失败' },
{ status: 500 }
);
}
}
+122 -5
View File
@@ -29,6 +29,7 @@ export async function GET(request: NextRequest) {
const id = searchParams.get('id');
const sourceCode = searchParams.get('source');
const fileName = searchParams.get('fileName'); // 小雅源:用户点击的文件名
const title = searchParams.get('title');
if (!id || !sourceCode) {
return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
@@ -274,6 +275,124 @@ export async function GET(request: NextRequest) {
}
}
if (sourceCode === 'quark-temp') {
try {
const config = await getConfig();
const openListConfig = config.OpenListConfig;
if (
!openListConfig ||
!openListConfig.Enabled ||
!openListConfig.URL ||
!openListConfig.Username ||
!openListConfig.Password
) {
throw new Error('OpenList 未配置或未启用');
}
const { base58Decode } = await import('@/lib/utils');
const { OpenListClient } = await import('@/lib/openlist.client');
const { parseVideoFileName } = await import('@/lib/video-parser');
const folderPath = base58Decode(id);
if (!folderPath) {
throw new Error('无效的临时播放目录');
}
const client = new OpenListClient(
openListConfig.URL,
openListConfig.Username,
openListConfig.Password
);
const videoExtensions = ['.mp4', '.mkv', '.avi', '.m3u8', '.flv', '.ts', '.mov', '.wmv', '.webm', '.rmvb', '.rm', '.mpg', '.mpeg', '.3gp', '.f4v', '.m4v', '.vob'];
const collectFiles = async (currentPath: string): Promise<Array<{ path: string; name: string }>> => {
const allFiles: Array<{ path: string; name: string }> = [];
let currentPage = 1;
const pageSize = 100;
let hasMore = true;
while (hasMore) {
const response = await client.listDirectory(currentPath, currentPage, pageSize);
if (response.code !== 200) {
throw new Error('读取临时目录失败');
}
for (const item of response.data.content) {
const itemPath = `${currentPath}${currentPath.endsWith('/') ? '' : '/'}${item.name}`;
if (item.is_dir) {
const nested = await collectFiles(itemPath);
allFiles.push(...nested);
} else if (
!item.name.startsWith('.') &&
videoExtensions.some((ext) => item.name.toLowerCase().endsWith(ext))
) {
allFiles.push({
path: itemPath,
name: item.name,
});
}
}
hasMore = !(
response.data.content.length < pageSize ||
currentPage * pageSize >= response.data.total
);
currentPage += 1;
}
return allFiles;
};
const files = await collectFiles(folderPath);
if (files.length === 0) {
throw new Error('临时播放目录中没有视频文件');
}
const episodes = files
.map((file, index) => {
const parsed = parseVideoFileName(file.name);
const fileDir = file.path.substring(0, file.path.lastIndexOf('/')) || '/';
return {
fileName: file.name,
fileDir,
episode: parsed.episode || index + 1,
title:
parsed.title ||
(parsed.episode ? `${parsed.episode}` : file.name),
isOVA: parsed.isOVA,
};
})
.sort((a, b) => {
if (a.isOVA && !b.isOVA) return 1;
if (!a.isOVA && b.isOVA) return -1;
return a.episode !== b.episode
? a.episode - b.episode
: a.fileName.localeCompare(b.fileName);
});
return NextResponse.json({
source: 'quark-temp',
source_name: '夸克临时播放',
id,
title: title || folderPath.split('/').filter(Boolean).pop() || '夸克临时播放',
poster: '',
year: '',
douban_id: 0,
desc: `临时播放目录:${folderPath}`,
episodes: episodes.map((ep) => `/api/openlist/play?folder=${encodeURIComponent(ep.fileDir)}&fileName=${encodeURIComponent(ep.fileName)}`),
episodes_titles: episodes.map((ep) => ep.title),
proxyMode: false,
});
} catch (error) {
return NextResponse.json(
{ error: (error as Error).message },
{ status: 500 }
);
}
}
// 特殊处理 openlist 源 - 直接调用 /api/detail
if (sourceCode === 'openlist') {
try {
@@ -340,8 +459,9 @@ export async function GET(request: NextRequest) {
let currentPage = 1;
const pageSize = 100;
let total = 0;
let hasMore = true;
while (true) {
while (hasMore) {
const listResponse = await client.listDirectory(folderPath, currentPage, pageSize);
if (listResponse.code !== 200) {
@@ -351,10 +471,7 @@ export async function GET(request: NextRequest) {
total = listResponse.data.total;
allFiles.push(...listResponse.data.content);
if (allFiles.length >= total) {
break;
}
hasMore = allFiles.length < total;
currentPage++;
}