Add browser download confirmation and parameterized client startup

This commit is contained in:
tongtong committed 2026-11-20 18:41:05 +08:00
1 parent 028fec64be
commit 3cf197a98c
25 files changed
+568 -46

No files matched your search

+19 -6
View File
@@ -1,15 +1,20 @@
import {DEFAULTS, httpUrl, eligible, linkReferrer, requestFor, handoff, recover} from './logic.mjs';
const HOST = 'com.ttstd.ttdownloader';
const observed = new Map(), busy = new Set();
let recovery = null;
let recovery = null, pollTimer = null;
function pollConfirmation() {
if (pollTimer) return;
pollTimer = setTimeout(() => { pollTimer = null; restorePending(); }, 1500);
}
const config = async () => ({...DEFAULTS, ...(await chrome.storage.local.get('config')).config});
async function status(result) {
await chrome.storage.local.set({lastResult: {...result, time: Date.now()}});
const waiting = result.status === 'awaiting_confirmation';
const ok = ['accepted', 'ready'].includes(result.status);
await chrome.action.setBadgeText({text: ok ? 'OK' : '!'});
await chrome.action.setBadgeText({text: waiting ? '…' : ok ? 'OK' : '!'});
await chrome.action.setBadgeBackgroundColor({color: ok ? '#247a48' : '#af4d00'});
await chrome.action.setTitle({title: 'TTDownloader:' + result.message});
if (!ok && result.status !== 'duplicate') chrome.notifications.create({type: 'basic', iconUrl: 'icon.png', title: 'TTDownloader 下载接管', message: result.message}, () => { void chrome.runtime.lastError; });
if (!ok && !waiting && result.status !== 'duplicate') chrome.notifications.create({type: 'basic', iconUrl: 'icon.png', title: 'TTDownloader 下载接管', message: result.message}, () => { void chrome.runtime.lastError; });
return result;
}
function native(request) {
@@ -43,7 +48,12 @@ async function configure() {
}
async function restorePending() {
if (recovery || busy.size) return recovery;
recovery = (async () => { for (const outcome of await recover(chrome, native, (await config()).auto)) await status(outcome); })()
recovery = (async () => {
for (const outcome of await recover(chrome, native, (await config()).auto)) {
await status(outcome);
if (outcome.status === 'awaiting_confirmation') pollConfirmation();
}
})()
.catch(error => status({status: 'error', message: '恢复下载状态失败:' + error.message})).finally(() => { recovery = null; });
return recovery;
}
@@ -55,7 +65,10 @@ chrome.runtime.onStartup.addListener(() => { configure().catch(console.error); r
chrome.alarms.onAlarm.addListener(alarm => { if (alarm.name === 'recover') restorePending(); });
chrome.permissions.onAdded.addListener(() => configure().catch(console.error));
chrome.permissions.onRemoved.addListener(() => configure().catch(console.error));
chrome.storage.onChanged.addListener(changes => { if (changes.config) { configure().catch(console.error); restorePending(); } });
chrome.storage.onChanged.addListener(changes => {
if (changes.config) { configure().catch(console.error); restorePending(); }
if (Object.entries(changes).some(([key, change]) => key.startsWith('pending_') && change.newValue?.phase === 'confirming')) pollConfirmation();
});
chrome.contextMenus.onClicked.addListener(async info => {
if (info.menuItemId !== 'send') return;
try { await status(await native(requestFor(info.linkUrl, linkReferrer(info.pageUrl, info.linkUrl)))); }
@@ -68,7 +81,7 @@ chrome.downloads.onCreated.addListener(async item => {
busy.add(item.id);
try { await status(await handoff(chrome, item, requestFor(url, item.referrer, item.filename || ''), native)); }
catch (error) { await status({status: 'error', message: '接管失败,请在下载页检查任务:' + error.message}); }
finally { busy.delete(item.id); }
finally { busy.delete(item.id); pollConfirmation(); }
});
chrome.runtime.onMessage.addListener((message, sender, respond) => {
if (sender.id !== chrome.runtime.id || !sender.url?.startsWith(chrome.runtime.getURL(''))) return;
+40 -8
View File
@@ -21,7 +21,7 @@ export function linkReferrer(source, target) {
}
export function requestFor(url, referrer = '', filename = '') {
const normalized = httpUrl(url); if (!normalized) throw new Error('仅支持不含账号密码的 HTTP/HTTPS 下载地址');
return {action: 'add', request_id: crypto.randomUUID(), method: 'GET', url: normalized,
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}`;
@@ -54,6 +54,23 @@ async function finish(api, record) {
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);
@@ -62,13 +79,21 @@ export async function handoff(api, item, request, sendNative, saved = null) {
// 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);
record.phase = 'sending'; await save(api, record);
const reply = await sendNative(record.request);
if (reply?.status !== 'accepted' || reply.request_id !== request.request_id || typeof reply.task_id !== 'string' || !/^[1-9][0-9]{0,18}$/.test(reply.task_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; await save(api, record);
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 || '本地通信失败,结果未确认');
}
}
@@ -76,9 +101,16 @@ 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') { await remove(api, record.id); continue; }
if (record.phase === 'sending' && !item.paused) {
await remove(api, record.id); outcomes.push({status: 'warning', message: '浏览器下载已恢复,已停止重复接管;请核对桌面任务列表'}); continue;
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, '接管未完成'));
+1 -1
View File
@@ -2,7 +2,7 @@
"manifest_version": 3,
"name": "TTDownloader 下载接管",
"description": "将主动发起的 HTTP/HTTPS 下载交给 TTDownloader,自动接管默认关闭。",
"version": "0.1.0",
"version": "0.2.0",
"minimum_chrome_version": "109",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvbbxlyA8oQYALtekWYplS8AuRDPyQmQX51/zpbfYT10Zpsbs+8yd0/l4aP9ByJyjs0N3oI0EsFcA6FPqWK+/SPDeMqZiyxSiIGzcy+zCjYiKelUSzBz80gayXk6R509YV2GKbpt9LOliK92GQy+bacblVScXtqKqmjrubTo+WplRXnPjS0pv2Kx7saSyX10ajjsOTmg1kNaN3x1tCbkOSXR+46idt5VC78sSvixfqwdD0tIqcH7TI6jN0t3nvQakFgfYlcjAgAJrC1PYZdoZMAT2dOjyXV73Bf2y7NHvRQtkDj37Cm88AOH6FncvME7zUbiGrfmZx+ik+rdBQHUULQIDAQAB",
"permissions": [