Files
TTDownloader/browser/chrome/logic.mjs
T

121 lines
7.2 KiB
JavaScript

export const DEFAULTS = Object.freeze({auto: false, sites: '', extensions: ''});
export function httpUrl(value) {
try { const u = new URL(value); if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password) return ''; u.hash = ''; return u.href; } catch { return ''; }
}
export function eligible(item, config, observed, now = Date.now()) {
if (!config.auto || item.state !== 'in_progress' || item.paused || item.incognito || item.byExtensionId || (item.danger && item.danger !== 'safe')) return false;
const url = httpUrl(item.finalUrl || item.url);
if (!url || !observed || observed.method !== 'GET' || now - observed.time > 15000) return false;
const parsed = new URL(url);
const sites = config.sites.split(/[\s,]+/).filter(Boolean).map(s => s.toLowerCase());
if (sites.length && !sites.some(s => s.startsWith('*.') ? parsed.hostname.endsWith(s.slice(1)) : parsed.hostname === s)) return false;
const types = config.extensions.toLowerCase().split(/[\s,]+/).filter(Boolean).map(s => s.startsWith('.') ? s : '.' + s);
const name = (item.filename || parsed.pathname).toLowerCase();
return !types.length || types.some(type => name.endsWith(type));
}
export function linkReferrer(source, target) {
const from = httpUrl(source), to = httpUrl(target); if (!from || !to) return '';
const a = new URL(from), b = new URL(to);
if (a.protocol === 'https:' && b.protocol === 'http:') return '';
return a.origin === b.origin ? a.href : a.origin + '/';
}
export function requestFor(url, referrer = '', filename = '') {
const normalized = httpUrl(url); if (!normalized) throw new Error('仅支持不含账号密码的 HTTP/HTTPS 下载地址');
return {action: 'add', confirmation: 'required', request_id: crypto.randomUUID(), method: 'GET', url: normalized,
referrer: httpUrl(referrer), filename: filename.split(/[\\/]/).pop().slice(0, 240), user_agent: navigator.userAgent};
}
const key = id => `pending_${id}`;
const save = (api, record) => api.storage.local.set({[key(record.id)]: record});
const remove = (api, id) => api.storage.local.remove(key(id));
const current = async (api, id) => (await api.downloads.search({id}))[0];
async function restore(api, record, message) {
record.phase = 'resume';
try { await save(api, record); } catch {} // Recovery must still resume when storage is temporarily unavailable.
try {
const item = await current(api, record.id);
if (item?.state === 'in_progress' && item.paused) await api.downloads.resume(record.id);
try { await remove(api, record.id); } catch {}
return {status: 'fallback', message: message + ';已保留或恢复浏览器下载'};
} catch {
return {status: 'recovery_pending', message: message + ';恢复失败,已保留恢复记录,请在浏览器下载页继续下载'};
}
}
async function finish(api, record) {
try {
const item = await current(api, record.id);
if (item?.state === 'in_progress' && !item.paused) {
await remove(api, record.id);
return {status: 'warning', message: '桌面已接收任务,但浏览器下载已被恢复;请检查是否重复下载'};
}
if (item?.state === 'in_progress') await api.downloads.cancel(record.id);
await remove(api, record.id);
return {status: 'accepted', message: '已交给 TTDownloader,任务编号 ' + record.task_id};
} catch {
return {status: 'recovery_pending', message: '桌面已接收任务,浏览器取消失败,将继续重试'};
}
}
const acknowledged = (reply, request) => reply?.status === 'accepted' && reply.request_id === request.request_id
&& typeof reply.task_id === 'string' && /^[1-9][0-9]{0,18}$/.test(reply.task_id);
async function abandon(api, record, sendNative) {
try {
const reply = await sendNative({action: 'cancel', request_id: record.request.request_id});
if (acknowledged(reply, record.request)) {
record.phase = 'cancel'; record.task_id = reply.task_id;
try { await save(api, record); } catch {} // The existing request journal still permits an idempotent retry.
return finish(api, record);
}
if (reply?.status === 'awaiting_confirmation' && reply.request_id === record.request.request_id) {
record.phase = 'confirming'; try { await save(api, record); } catch {}
return {status: 'awaiting_confirmation', message: reply.message};
}
} catch {} // If the client disappeared, preserve the browser's original download.
return restore(api, record, '接管未完成,请检查客户端添加窗口');
}
export async function handoff(api, item, request, sendNative, saved = null) {
const record = saved || {id: item.id, request, phase: 'pause', created: Date.now(), original: httpUrl(item.finalUrl || item.url)};
if (record.phase === 'cancel') return finish(api, record);
if (record.phase === 'resume') return restore(api, record, '继续恢复浏览器下载');
try {
// Journal intent before pausing, so a service-worker restart cannot strand a paused task.
await save(api, record);
if (!item.paused) await api.downloads.pause(item.id);
const confirming = record.phase === 'confirming';
if (!confirming) record.phase = 'sending';
await save(api, record);
const reply = await sendNative(confirming ? {action: 'query', request_id: request.request_id} : record.request);
if (reply?.status === 'awaiting_confirmation' && reply.request_id === request.request_id) {
record.phase = 'confirming'; await save(api, record);
return {status: 'awaiting_confirmation', message: reply.message || '请在客户端确认添加任务;取消后将恢复浏览器下载'};
}
if (!acknowledged(reply, request))
return restore(api, record, reply?.message || '桌面未确认接管');
record.phase = 'cancel'; record.task_id = reply.task_id;
try { await save(api, record); } catch {}
return finish(api, record);
} catch (error) {
if (record.phase === 'sending' || record.phase === 'confirming') return abandon(api, record, sendNative);
return restore(api, record, error.message || '本地通信失败,结果未确认');
}
}
export async function recover(api, sendNative, auto) {
const values = await api.storage.local.get(null), outcomes = [];
for (const record of Object.values(values).filter(v => v && v.request && Number.isInteger(v.id) && v.phase)) {
const item = await current(api, record.id);
if (!item || httpUrl(item.finalUrl || item.url) !== record.original || item.state !== 'in_progress') {
if (record.phase === 'confirming' || record.phase === 'sending') outcomes.push(await abandon(api, record, sendNative));
else await remove(api, record.id);
continue;
}
if (record.phase === 'confirming' && (!item.paused || !auto || Date.now() - record.created > 120000)) {
outcomes.push(await abandon(api, record, sendNative)); continue;
}
if (record.phase === 'sending' && (!item.paused || !auto || Date.now() - record.created > 120000)) {
outcomes.push(await abandon(api, record, sendNative)); continue;
}
if (record.phase === 'cancel') outcomes.push(await finish(api, record));
else if (!auto || Date.now() - record.created > 120000 || record.phase === 'resume') outcomes.push(await restore(api, record, '接管未完成'));
else outcomes.push(await handoff(api, item, record.request, sendNative, record));
}
return outcomes;
}