夸克增加多线程播放
This commit is contained in:
@@ -3937,6 +3937,7 @@ const NetDiskConfigComponent = ({
|
||||
const [cookie, setCookie] = useState('');
|
||||
const [savePath, setSavePath] = useState('/');
|
||||
const [quarkPlayMode, setQuarkPlayMode] = useState<'direct_first' | 'transcode_first'>('transcode_first');
|
||||
const [quarkMultiThreadPlayback, setQuarkMultiThreadPlayback] = useState(false);
|
||||
const [mobileEnabled, setMobileEnabled] = useState(false);
|
||||
const [mobileAuthorization, setMobileAuthorization] = useState('');
|
||||
const [baiduEnabled, setBaiduEnabled] = useState(false);
|
||||
@@ -3961,6 +3962,7 @@ const NetDiskConfigComponent = ({
|
||||
setCookie(quark?.Cookie || '');
|
||||
setSavePath(quark?.SavePath || '/');
|
||||
setQuarkPlayMode(quark?.PlayMode === 'direct_first' ? 'direct_first' : 'transcode_first');
|
||||
setQuarkMultiThreadPlayback(Boolean(quark?.MultiThreadPlayback));
|
||||
setMobileEnabled(mobile?.Enabled || false);
|
||||
setMobileAuthorization(mobile?.Authorization || '');
|
||||
setBaiduEnabled(config?.NetDiskConfig?.Baidu?.Enabled || false);
|
||||
@@ -3991,6 +3993,7 @@ const NetDiskConfigComponent = ({
|
||||
Cookie: cookie,
|
||||
SavePath: savePath,
|
||||
PlayMode: quarkPlayMode,
|
||||
MultiThreadPlayback: quarkMultiThreadPlayback,
|
||||
},
|
||||
Mobile: {
|
||||
Enabled: mobileEnabled,
|
||||
@@ -4327,6 +4330,27 @@ const NetDiskConfigComponent = ({
|
||||
</p>
|
||||
</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'>
|
||||
开启后,代理会把播放器请求的 Range 拆分并发拉取。
|
||||
</p>
|
||||
</div>
|
||||
<label className='relative inline-flex items-center cursor-pointer'>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={quarkMultiThreadPlayback}
|
||||
onChange={(e) => setQuarkMultiThreadPlayback(e.target.checked)}
|
||||
disabled={!enabled}
|
||||
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-disabled:opacity-50 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 className='flex gap-3'>
|
||||
<button
|
||||
onClick={handleValidate}
|
||||
|
||||
@@ -80,6 +80,7 @@ export async function POST(request: NextRequest) {
|
||||
Cookie: normalizedCookie,
|
||||
SavePath: Quark?.SavePath || '/',
|
||||
PlayMode: Quark?.PlayMode === 'direct_first' ? 'direct_first' : 'transcode_first',
|
||||
MultiThreadPlayback: Boolean(Quark?.MultiThreadPlayback),
|
||||
};
|
||||
adminConfig.NetDiskConfig.Mobile = {
|
||||
Enabled: Boolean(Mobile?.Enabled),
|
||||
|
||||
@@ -1,12 +1,149 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getAuthInfoFromCookie } from '@/lib/auth';
|
||||
import { ensureQuarkPlayFolder, getQuarkPlayHeaders, getQuarkPlayUrls, saveQuarkShareFile } from '@/lib/netdisk/quark.client';
|
||||
import { createQuarkMultiThreadStream } from '@/lib/netdisk/quark-multithread-proxy';
|
||||
import {
|
||||
ensureQuarkPlayFolder,
|
||||
getQuarkPlayHeaders,
|
||||
getQuarkPlayUrls,
|
||||
probeQuarkPlayRange,
|
||||
saveQuarkShareFile,
|
||||
} from '@/lib/netdisk/quark.client';
|
||||
import { refreshQuarkNetdiskSession } from '@/lib/netdisk/quark-session-cache';
|
||||
import { resolveQuarkSession } from '@/lib/netdisk/quark-session-resolver';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
const QUARK_PC_UA =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) quark-cloud-drive/2.5.20 Chrome/100.0.4896.160 Electron/18.3.5.4-b478491100 Safari/537.36 Channel/pckk_other_ch';
|
||||
|
||||
async function pipeUpstream(response: Response, range: string | null) {
|
||||
const responseHeaders = new Headers();
|
||||
const copyHeaders = ['content-type', 'content-length', 'content-range', 'accept-ranges', 'etag', 'last-modified'];
|
||||
copyHeaders.forEach((name) => {
|
||||
const value = response.headers.get(name);
|
||||
if (value) responseHeaders.set(name, value);
|
||||
});
|
||||
responseHeaders.set('Cache-Control', 'private, no-store');
|
||||
|
||||
const { readable, writable } = new TransformStream();
|
||||
const reader = response.body!.getReader();
|
||||
|
||||
void (async () => {
|
||||
const writer = writable.getWriter();
|
||||
try {
|
||||
let streamDone = false;
|
||||
while (!streamDone) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
streamDone = true;
|
||||
} else {
|
||||
await writer.write(value);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
try {
|
||||
await reader.cancel();
|
||||
} catch {
|
||||
void 0;
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch {
|
||||
void 0;
|
||||
}
|
||||
try {
|
||||
await writer.close();
|
||||
} catch {
|
||||
void 0;
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return new Response(readable, {
|
||||
status: range && response.headers.get('content-range') ? 206 : response.status,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
function getPassthroughHeaders(request: NextRequest) {
|
||||
const passthroughHeaderNames = [
|
||||
'accept',
|
||||
'accept-language',
|
||||
'accept-encoding',
|
||||
'connection',
|
||||
'sec-fetch-dest',
|
||||
'sec-fetch-mode',
|
||||
'sec-fetch-site',
|
||||
];
|
||||
const passthroughHeaders: Record<string, string> = {};
|
||||
for (const name of passthroughHeaderNames) {
|
||||
const value = request.headers.get(name);
|
||||
if (value) passthroughHeaders[name] = value;
|
||||
}
|
||||
return passthroughHeaders;
|
||||
}
|
||||
|
||||
function buildHeaderProfiles(request: NextRequest, cookie: string) {
|
||||
const passthroughHeaders = getPassthroughHeaders(request);
|
||||
return [
|
||||
{
|
||||
name: 'quark-empty-ua',
|
||||
headers: {
|
||||
...passthroughHeaders,
|
||||
...getQuarkPlayHeaders(cookie),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'quark-api-ua',
|
||||
headers: {
|
||||
...passthroughHeaders,
|
||||
cookie,
|
||||
referer: 'https://pan.quark.cn/',
|
||||
'user-agent': QUARK_PC_UA,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'quark-no-ua',
|
||||
headers: {
|
||||
...passthroughHeaders,
|
||||
cookie,
|
||||
referer: 'https://pan.quark.cn/',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'browser-origin',
|
||||
headers: {
|
||||
...passthroughHeaders,
|
||||
cookie,
|
||||
origin: 'https://pan.quark.cn',
|
||||
referer: 'https://pan.quark.cn/',
|
||||
'user-agent':
|
||||
request.headers.get('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',
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function parseRequestedRange(range: string | null): { start: number; end?: number } | null {
|
||||
if (!range) return null;
|
||||
const match = /^bytes=(\d+)-(\d*)$/i.exec(range.trim());
|
||||
if (!match) return null;
|
||||
return {
|
||||
start: Number(match[1]),
|
||||
end: match[2] ? Number(match[2]) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function buildRangeHeaders(start: number, end: number, total: number) {
|
||||
return {
|
||||
'Content-Range': `bytes ${start}-${end}/${total}`,
|
||||
'Content-Length': String(end - start + 1),
|
||||
};
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const authInfo = getAuthInfoFromCookie(request);
|
||||
@@ -27,7 +164,7 @@ export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({ error: '无效的 episodeIndex' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { session, cookie, savePath, playMode } = await resolveQuarkSession(id);
|
||||
const { session, cookie, savePath, playMode, multiThreadPlayback } = await resolveQuarkSession(id);
|
||||
const file = session.files[episodeIndex];
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: '播放文件不存在' }, { status: 404 });
|
||||
@@ -54,7 +191,19 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
refreshQuarkNetdiskSession(id);
|
||||
|
||||
const playUrls = await getQuarkPlayUrls(cookie, savedFileId, playMode);
|
||||
session.playUrlCaches = session.playUrlCaches || {};
|
||||
const playUrlCacheKey = `${savedFileId}:${playMode}`;
|
||||
const cachedPlayUrls = session.playUrlCaches[playUrlCacheKey];
|
||||
const playUrls =
|
||||
cachedPlayUrls && cachedPlayUrls.expiresAt > Date.now()
|
||||
? cachedPlayUrls.urls
|
||||
: await getQuarkPlayUrls(cookie, savedFileId, playMode);
|
||||
if (!cachedPlayUrls || cachedPlayUrls.expiresAt <= Date.now()) {
|
||||
session.playUrlCaches[playUrlCacheKey] = {
|
||||
urls: playUrls,
|
||||
expiresAt: Date.now() + 5 * 60 * 1000,
|
||||
};
|
||||
}
|
||||
const selected = playUrls.find((item) => item.name === quality) || playUrls[0];
|
||||
const candidates = selected
|
||||
? [
|
||||
@@ -67,172 +216,69 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
|
||||
const range = request.headers.get('range');
|
||||
const passthroughHeaderNames = [
|
||||
'accept',
|
||||
'accept-language',
|
||||
'accept-encoding',
|
||||
'connection',
|
||||
'sec-fetch-dest',
|
||||
'sec-fetch-mode',
|
||||
'sec-fetch-site',
|
||||
];
|
||||
const passthroughHeaders: Record<string, string> = {};
|
||||
for (const name of passthroughHeaderNames) {
|
||||
const value = request.headers.get(name);
|
||||
if (value) passthroughHeaders[name] = value;
|
||||
}
|
||||
let lastStatus = 500;
|
||||
|
||||
try {
|
||||
let upstream: Response | null = null;
|
||||
let lastStatus = 500;
|
||||
const headerProfiles = [
|
||||
{
|
||||
name: 'quark-empty-ua',
|
||||
headers: {
|
||||
...passthroughHeaders,
|
||||
...getQuarkPlayHeaders(cookie),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'quark-api-ua',
|
||||
headers: {
|
||||
...passthroughHeaders,
|
||||
cookie,
|
||||
referer: 'https://pan.quark.cn/',
|
||||
'user-agent':
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) quark-cloud-drive/2.5.20 Chrome/100.0.4896.160 Electron/18.3.5.4-b478491100 Safari/537.36 Channel/pckk_other_ch',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'quark-no-ua',
|
||||
headers: {
|
||||
...passthroughHeaders,
|
||||
cookie,
|
||||
referer: 'https://pan.quark.cn/',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'browser-origin',
|
||||
headers: {
|
||||
...passthroughHeaders,
|
||||
cookie,
|
||||
origin: 'https://pan.quark.cn',
|
||||
referer: 'https://pan.quark.cn/',
|
||||
'user-agent':
|
||||
request.headers.get('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',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
for (const profile of headerProfiles) {
|
||||
const abortController = new AbortController();
|
||||
const timeoutId = setTimeout(() => abortController.abort(), 300000);
|
||||
|
||||
try {
|
||||
const requestHeaders = {
|
||||
...profile.headers,
|
||||
...(range ? { Range: range } : {}),
|
||||
};
|
||||
const response = await fetch(candidate.url, {
|
||||
headers: requestHeaders,
|
||||
cache: 'no-store',
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
if (response.ok && response.body) {
|
||||
upstream = response;
|
||||
if (candidate.url !== selected.url) {
|
||||
console.warn(`[quark] fallback play url used: ${selected.name} -> ${candidate.name}`);
|
||||
}
|
||||
if (profile.name !== 'quark-empty-ua') {
|
||||
console.warn(`[quark] fallback header profile used: ${profile.name}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
lastStatus = response.status || 500;
|
||||
const errorText = await response.text().catch(() => '');
|
||||
console.warn(
|
||||
`[quark] play url failed: ${candidate.name} / ${profile.name} (${lastStatus}) ${errorText.slice(0, 200)}`
|
||||
);
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId);
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw error;
|
||||
}
|
||||
console.warn(`[quark] play url request failed: ${candidate.name} / ${profile.name}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
if (upstream) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!upstream) {
|
||||
return NextResponse.json(
|
||||
{ error: `夸克视频代理失败 (${lastStatus})` },
|
||||
{ status: lastStatus }
|
||||
);
|
||||
}
|
||||
|
||||
const response = upstream as Response & { body: ReadableStream<Uint8Array> };
|
||||
const responseHeaders = new Headers();
|
||||
const copyHeaders = ['content-type', 'content-length', 'content-range', 'accept-ranges', 'etag', 'last-modified'];
|
||||
copyHeaders.forEach((name) => {
|
||||
const value = response.headers.get(name);
|
||||
if (value) responseHeaders.set(name, value);
|
||||
});
|
||||
responseHeaders.set('Cache-Control', 'private, no-store');
|
||||
|
||||
const { readable, writable } = new TransformStream();
|
||||
const reader = response.body.getReader();
|
||||
|
||||
void (async () => {
|
||||
const writer = writable.getWriter();
|
||||
for (const candidate of candidates) {
|
||||
for (const profile of buildHeaderProfiles(request, cookie)) {
|
||||
try {
|
||||
let streamDone = false;
|
||||
while (!streamDone) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
streamDone = true;
|
||||
} else {
|
||||
await writer.write(value);
|
||||
const requestedRange = parseRequestedRange(range);
|
||||
const probeRange =
|
||||
multiThreadPlayback && requestedRange
|
||||
? `bytes=${requestedRange.start}-${requestedRange.start}`
|
||||
: range || undefined;
|
||||
const probed = await probeQuarkPlayRange(candidate.url, profile.headers, probeRange);
|
||||
if (probed?.response.body) {
|
||||
if (multiThreadPlayback && requestedRange && probed.window) {
|
||||
const trunkEnd = Math.min(
|
||||
requestedRange.end ?? requestedRange.start + 8 * 1024 * 1024 - 1,
|
||||
requestedRange.start + 8 * 1024 * 1024 - 1,
|
||||
probed.window.total - 1
|
||||
);
|
||||
const window = {
|
||||
start: requestedRange.start,
|
||||
end: trunkEnd,
|
||||
total: probed.window.total,
|
||||
};
|
||||
const responseHeaders = new Headers();
|
||||
const copyHeaders = ['content-type', 'content-length', 'content-range', 'accept-ranges', 'etag', 'last-modified'];
|
||||
copyHeaders.forEach((name) => {
|
||||
const value = probed.response.headers.get(name);
|
||||
if (value) responseHeaders.set(name, value);
|
||||
});
|
||||
responseHeaders.set('Cache-Control', 'private, no-store');
|
||||
const rangeHeaders = buildRangeHeaders(window.start, window.end, window.total);
|
||||
responseHeaders.set('Content-Range', rangeHeaders['Content-Range']);
|
||||
responseHeaders.set('Content-Length', rangeHeaders['Content-Length']);
|
||||
try {
|
||||
await probed.response.body.cancel();
|
||||
} catch {
|
||||
void 0;
|
||||
}
|
||||
return createQuarkMultiThreadStream({
|
||||
url: candidate.url,
|
||||
headers: profile.headers,
|
||||
window,
|
||||
contentHeaders: responseHeaders,
|
||||
status: 206,
|
||||
});
|
||||
}
|
||||
|
||||
return pipeUpstream(probed.response, range);
|
||||
}
|
||||
} catch {
|
||||
try {
|
||||
await reader.cancel();
|
||||
} catch {
|
||||
void 0;
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch {
|
||||
void 0;
|
||||
}
|
||||
try {
|
||||
await writer.close();
|
||||
} catch {
|
||||
void 0;
|
||||
|
||||
lastStatus = probed?.response.status || lastStatus;
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return NextResponse.json({ error: '夸克网盘代理超时' }, { status: 504 });
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return new Response(readable, {
|
||||
status: range && response.headers.get('content-range') ? 206 : response.status,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return NextResponse.json({ error: '夸克网盘代理超时' }, { status: 504 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: `夸克视频代理失败 (${lastStatus})` },
|
||||
{ status: lastStatus }
|
||||
);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : '夸克网盘代理失败' },
|
||||
|
||||
@@ -153,6 +153,7 @@ export interface AdminConfig {
|
||||
Cookie: string;
|
||||
SavePath: string;
|
||||
PlayMode?: 'direct_first' | 'transcode_first';
|
||||
MultiThreadPlayback?: boolean;
|
||||
};
|
||||
Mobile?: {
|
||||
Enabled: boolean;
|
||||
|
||||
@@ -725,6 +725,7 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
|
||||
Cookie: '',
|
||||
SavePath: '/',
|
||||
PlayMode: 'transcode_first',
|
||||
MultiThreadPlayback: false,
|
||||
},
|
||||
Mobile: {
|
||||
Enabled: false,
|
||||
@@ -763,11 +764,15 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
|
||||
Cookie: '',
|
||||
SavePath: '/',
|
||||
PlayMode: 'transcode_first',
|
||||
MultiThreadPlayback: false,
|
||||
};
|
||||
}
|
||||
if (!adminConfig.NetDiskConfig.Quark.PlayMode) {
|
||||
adminConfig.NetDiskConfig.Quark.PlayMode = 'transcode_first';
|
||||
}
|
||||
if (adminConfig.NetDiskConfig.Quark.MultiThreadPlayback === undefined) {
|
||||
adminConfig.NetDiskConfig.Quark.MultiThreadPlayback = false;
|
||||
}
|
||||
|
||||
if (!adminConfig.NetDiskConfig.Mobile) {
|
||||
adminConfig.NetDiskConfig.Mobile = {
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { QuarkRangeWindow } from './quark.client';
|
||||
|
||||
const DEFAULT_CHUNK_SIZE = 1024 * 1024;
|
||||
const DEFAULT_CONCURRENCY = 8;
|
||||
const DEFAULT_CHUNK_RETRIES = 2;
|
||||
const RETRY_BASE_DELAY_MS = 300;
|
||||
|
||||
function buildRangeHeader(start: number, end: number) {
|
||||
return `bytes=${start}-${end}`;
|
||||
}
|
||||
|
||||
function splitRange(start: number, end: number, chunkSize = DEFAULT_CHUNK_SIZE) {
|
||||
const chunks: Array<{ index: number; start: number; end: number }> = [];
|
||||
let index = 0;
|
||||
for (let cursor = start; cursor <= end; cursor += chunkSize) {
|
||||
chunks.push({
|
||||
index,
|
||||
start: cursor,
|
||||
end: Math.min(cursor + chunkSize - 1, end),
|
||||
});
|
||||
index += 1;
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function isAbortError(error: unknown) {
|
||||
return (
|
||||
error instanceof Error &&
|
||||
(error.name === 'AbortError' || error.message.includes('aborted'))
|
||||
);
|
||||
}
|
||||
|
||||
function waitForRetry(ms: number, signal: AbortSignal) {
|
||||
if (signal.aborted) {
|
||||
throw new DOMException('Aborted', 'AbortError');
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
|
||||
const onAbort = () => {
|
||||
clearTimeout(timeoutId);
|
||||
reject(new DOMException('Aborted', 'AbortError'));
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchChunkOnce(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
chunk: { start: number; end: number },
|
||||
signal: AbortSignal
|
||||
) {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
...headers,
|
||||
Range: buildRangeHeader(chunk.start, chunk.end),
|
||||
},
|
||||
cache: 'no-store',
|
||||
signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
try {
|
||||
await response.body?.cancel();
|
||||
} catch {
|
||||
void 0;
|
||||
}
|
||||
throw new Error(`chunk request failed (${response.status})`);
|
||||
}
|
||||
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
async function fetchChunk(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
chunk: { start: number; end: number },
|
||||
signal: AbortSignal,
|
||||
retries = DEFAULT_CHUNK_RETRIES
|
||||
) {
|
||||
let lastError: unknown;
|
||||
|
||||
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
||||
try {
|
||||
return await fetchChunkOnce(url, headers, chunk, signal);
|
||||
} catch (error) {
|
||||
if (isAbortError(error) || attempt >= retries) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
lastError = error;
|
||||
await waitForRetry(RETRY_BASE_DELAY_MS * 2 ** attempt, signal);
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError instanceof Error ? lastError : new Error('chunk request failed');
|
||||
}
|
||||
|
||||
export function createQuarkMultiThreadStream(input: {
|
||||
url: string;
|
||||
headers: Record<string, string>;
|
||||
window: QuarkRangeWindow;
|
||||
contentHeaders: Headers;
|
||||
status: number;
|
||||
}) {
|
||||
const { url, headers, window, contentHeaders, status } = input;
|
||||
const chunks = splitRange(window.start, window.end);
|
||||
const abortController = new AbortController();
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
const results = new Map<number, Uint8Array>();
|
||||
let nextFetch = 0;
|
||||
let active = 0;
|
||||
let failed = false;
|
||||
|
||||
const done = new Promise<void>((resolve, reject) => {
|
||||
const launch = () => {
|
||||
if (failed) return;
|
||||
if (results.size >= chunks.length) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
while (active < DEFAULT_CONCURRENCY && nextFetch < chunks.length) {
|
||||
const chunk = chunks[nextFetch];
|
||||
nextFetch += 1;
|
||||
active += 1;
|
||||
|
||||
fetchChunk(url, headers, chunk, abortController.signal)
|
||||
.then((data) => {
|
||||
results.set(chunk.index, data);
|
||||
if (results.size >= chunks.length) {
|
||||
resolve();
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isAbortError(error)) {
|
||||
return;
|
||||
}
|
||||
failed = true;
|
||||
reject(error);
|
||||
})
|
||||
.finally(() => {
|
||||
active -= 1;
|
||||
launch();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
launch();
|
||||
});
|
||||
|
||||
await done;
|
||||
for (let index = 0; index < chunks.length; index += 1) {
|
||||
const data = results.get(index);
|
||||
if (!data) {
|
||||
throw new Error(`chunk missing (${index})`);
|
||||
}
|
||||
controller.enqueue(data);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
cancel() {
|
||||
abortController.abort();
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
status,
|
||||
headers: contentHeaders,
|
||||
});
|
||||
}
|
||||
@@ -8,6 +8,12 @@ export interface QuarkNetdiskSessionFile {
|
||||
pdirFid?: string;
|
||||
}
|
||||
|
||||
export interface QuarkPlayUrlCacheItem {
|
||||
name: string;
|
||||
url: string;
|
||||
priority: number;
|
||||
}
|
||||
|
||||
export interface QuarkNetdiskSession {
|
||||
id: string;
|
||||
provider: 'quark';
|
||||
@@ -18,6 +24,7 @@ export interface QuarkNetdiskSession {
|
||||
shareToken: string;
|
||||
files: QuarkNetdiskSessionFile[];
|
||||
savedFileIds: Record<string, string>;
|
||||
playUrlCaches: Record<string, { urls: QuarkPlayUrlCacheItem[]; expiresAt: number }>;
|
||||
playFolderFid?: string;
|
||||
playFolderPath?: string;
|
||||
createdAt: number;
|
||||
@@ -82,6 +89,7 @@ export function createQuarkNetdiskSession(input: {
|
||||
shareToken: input.shareToken,
|
||||
files: input.files,
|
||||
savedFileIds: {},
|
||||
playUrlCaches: {},
|
||||
createdAt: now,
|
||||
expiresAt: now + TTL_MS,
|
||||
};
|
||||
@@ -107,4 +115,3 @@ export function refreshQuarkNetdiskSession(id: string): QuarkNetdiskSession | nu
|
||||
sessionStore.set(id, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
|
||||
@@ -41,5 +41,6 @@ export async function resolveQuarkSession(id: string) {
|
||||
cookie: quarkConfig.Cookie,
|
||||
savePath: quarkConfig.SavePath || '/',
|
||||
playMode,
|
||||
multiThreadPlayback: Boolean(quarkConfig.MultiThreadPlayback),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ export interface QuarkShareVideoListResult {
|
||||
}
|
||||
|
||||
export type QuarkPlayMode = 'direct_first' | 'transcode_first';
|
||||
export type QuarkRangeWindow = { start: number; end: number; total: number };
|
||||
|
||||
const VIDEO_EXTENSIONS = [
|
||||
'.mp4',
|
||||
@@ -809,3 +810,42 @@ export async function getQuarkPlayUrls(
|
||||
|
||||
return deduped;
|
||||
}
|
||||
|
||||
function parseContentRangeHeader(contentRange: string | null): QuarkRangeWindow | null {
|
||||
if (!contentRange) return null;
|
||||
const match = contentRange.match(/^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i);
|
||||
if (!match) return null;
|
||||
const start = Number(match[1]);
|
||||
const end = Number(match[2]);
|
||||
const total = Number(match[3]);
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end) || !Number.isFinite(total)) return null;
|
||||
return { start, end, total };
|
||||
}
|
||||
|
||||
export async function probeQuarkPlayRange(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
range?: string
|
||||
): Promise<{ response: Response; window: QuarkRangeWindow | null } | null> {
|
||||
const abortController = new AbortController();
|
||||
const timeoutId = setTimeout(() => abortController.abort(), 300000);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
...headers,
|
||||
...(range ? { Range: range } : {}),
|
||||
},
|
||||
cache: 'no-store',
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const window = parseContentRangeHeader(response.headers.get('content-range'));
|
||||
return { response, window };
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user