新增 Chrome 下载接管扩展与 C++ 本地通信组件

实现链接右键发送、手动地址输入和默认关闭的可选 GET 自动接管,支持站点与文件类型过滤。通过 Native Messaging 和当前用户命名管道在任务入库后确认接管,失败恢复浏览器下载并持久化交接状态。保存请求编号、Referer 与 User-Agent,补充本地注册入口、集成包说明及扩展/stdio/IPC/HTTP 回归测试。
This commit is contained in:
tongtong committed 2026-11-16 15:44:44 +08:00
1 parent 6c810c3b4f
commit 028fec64be
41 files changed
+1081 -18

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
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;
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 ok = ['accepted', 'ready'].includes(result.status);
await chrome.action.setBadgeText({text: 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; });
return result;
}
function native(request) {
return new Promise((resolve, reject) => {
let port, timer, finished = false;
const done = (error, value) => { if (finished) return; finished = true; clearTimeout(timer); port?.disconnect(); error ? reject(error) : resolve(value); };
try {
port = chrome.runtime.connectNative(HOST);
port.onMessage.addListener(reply => {
if (reply?.request_id !== request.request_id) return done(new Error('本地响应编号不匹配,请检查桌面任务列表'));
done(null, reply);
});
port.onDisconnect.addListener(() => done(new Error('本地组件未连接:' + (chrome.runtime.lastError?.message || '通信中断') + ';请检查注册和桌面客户端')));
timer = setTimeout(() => done(new Error('本地通信超时,请检查桌面任务列表')), 30000);
port.postMessage(request);
} catch (error) { done(error); }
});
}
const requestObserver = details => {
const url = httpUrl(details.url); if (!url) return;
observed.set(url, {method: details.method, time: Date.now()});
if (observed.size > 512) observed.delete(observed.keys().next().value);
};
async function configure() {
if (chrome.webRequest?.onBeforeRequest.hasListener(requestObserver)) chrome.webRequest.onBeforeRequest.removeListener(requestObserver);
const allowed = await chrome.permissions.contains({permissions: ['webRequest'], origins: ['http://*/*', 'https://*/*']});
const settings = await config();
if (settings.auto && !allowed) { await chrome.storage.local.set({config: {...settings, auto: false}}); await status({status: 'error', message: '站点权限未授予或已撤销,自动接管已停用'}); }
if (settings.auto && allowed) chrome.webRequest.onBeforeRequest.addListener(requestObserver, {urls: ['http://*/*', 'https://*/*']});
else observed.clear();
}
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); })()
.catch(error => status({status: 'error', message: '恢复下载状态失败:' + error.message})).finally(() => { recovery = null; });
return recovery;
}
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.removeAll(() => chrome.contextMenus.create({id: 'send', title: '使用 TTDownloader 下载', contexts: ['link'], targetUrlPatterns: ['http://*/*', 'https://*/*']}));
chrome.alarms.create('recover', {periodInMinutes: 1}); configure().catch(console.error);
});
chrome.runtime.onStartup.addListener(() => { configure().catch(console.error); restorePending(); });
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.contextMenus.onClicked.addListener(async info => {
if (info.menuItemId !== 'send') return;
try { await status(await native(requestFor(info.linkUrl, linkReferrer(info.pageUrl, info.linkUrl)))); }
catch (error) { await status({status: 'error', message: error.message}); }
});
chrome.downloads.onCreated.addListener(async item => {
if (recovery) await recovery;
const url = httpUrl(item.finalUrl || item.url);
if (!eligible(item, await config(), observed.get(url) || observed.get(httpUrl(item.url))) || busy.has(item.id)) return;
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); }
});
chrome.runtime.onMessage.addListener((message, sender, respond) => {
if (sender.id !== chrome.runtime.id || !sender.url?.startsWith(chrome.runtime.getURL(''))) return;
(async () => {
try {
if (message.action === 'ping') return await status(await native({action: 'ping', request_id: crypto.randomUUID()}));
if (message.action === 'send') return await status(await native(requestFor(message.url)));
return {status: 'error', message: '不支持的操作'};
} catch (error) { return status({status: 'error', message: error.message}); }
})().then(respond);
return true;
});
// Register synchronously so MV3 can deliver the first request after a worker restart.
try { chrome.webRequest?.onBeforeRequest.addListener(requestObserver, {urls: ['http://*/*', 'https://*/*']}); } catch {}
chrome.alarms.create('recover', {periodInMinutes: 1});
configure().catch(console.error);
restorePending();
Binary file not shown.

After

Width:  |  Height:  |  Size: 491 B

+88
View File
@@ -0,0 +1,88 @@
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', 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: '桌面已接收任务,浏览器取消失败,将继续重试'};
}
}
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);
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))
return restore(api, record, reply?.message || '桌面未确认接管');
record.phase = 'cancel'; record.task_id = reply.task_id; await save(api, record);
return finish(api, record);
} catch (error) {
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') { await remove(api, record.id); continue; }
if (record.phase === 'sending' && !item.paused) {
await remove(api, record.id); outcomes.push({status: 'warning', message: '浏览器下载已恢复,已停止重复接管;请核对桌面任务列表'}); 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;
}
+34
View File
@@ -0,0 +1,34 @@
{
"manifest_version": 3,
"name": "TTDownloader 下载接管",
"description": "将主动发起的 HTTP/HTTPS 下载交给 TTDownloader,自动接管默认关闭。",
"version": "0.1.0",
"minimum_chrome_version": "109",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvbbxlyA8oQYALtekWYplS8AuRDPyQmQX51/zpbfYT10Zpsbs+8yd0/l4aP9ByJyjs0N3oI0EsFcA6FPqWK+/SPDeMqZiyxSiIGzcy+zCjYiKelUSzBz80gayXk6R509YV2GKbpt9LOliK92GQy+bacblVScXtqKqmjrubTo+WplRXnPjS0pv2Kx7saSyX10ajjsOTmg1kNaN3x1tCbkOSXR+46idt5VC78sSvixfqwdD0tIqcH7TI6jN0t3nvQakFgfYlcjAgAJrC1PYZdoZMAT2dOjyXV73Bf2y7NHvRQtkDj37Cm88AOH6FncvME7zUbiGrfmZx+ik+rdBQHUULQIDAQAB",
"permissions": [
"nativeMessaging",
"contextMenus",
"storage",
"downloads",
"alarms",
"notifications"
],
"optional_permissions": [
"webRequest"
],
"optional_host_permissions": [
"http://*/*",
"https://*/*"
],
"background": {
"service_worker": "background.js",
"type": "module"
},
"action": {
"default_popup": "popup.html",
"default_title": "TTDownloader"
},
"icons": {
"128": "icon.png"
}
}
+1
View File
@@ -0,0 +1 @@
body{width:340px;margin:18px;font:14px "Microsoft YaHei",sans-serif;color:#273449;background:#f0f3f8}h1{font-size:20px}form{border-top:1px solid #bbc8d8;margin-top:16px;padding-top:14px}label{display:block;margin:10px 0 6px}input:not([type=checkbox]),textarea{box-sizing:border-box;width:100%;padding:8px;border:1px solid #9aabc0;border-radius:3px}button{padding:8px 12px;margin-top:8px;border:1px solid #307ef3;color:#245cb0;background:transparent;border-radius:3px;cursor:pointer}button:disabled{opacity:.5;cursor:wait}#status{overflow-wrap:anywhere;white-space:pre-line}.note{color:#64748b;font-size:12px;line-height:1.6}
+5
View File
@@ -0,0 +1,5 @@
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>TTDownloader</title><link rel="stylesheet" href="popup.css">
<body><h1>TTDownloader</h1><p id="status" role="status">正在读取状态…</p><button id="ping">检查桌面连接</button>
<form id="send"><label for="url">下载地址</label><input id="url" type="url" placeholder="https://…" required><button>交给 TTDownloader</button></form>
<form id="settings"><label><input id="auto" type="checkbox"> 自动接管已确认的 GET 下载</label><label for="sites">站点规则(留空表示全部)</label><textarea id="sites" placeholder="example.com, *.example.org"></textarea><label for="extensions">文件类型(留空表示全部)</label><input id="extensions" placeholder=".zip, .exe, .mp4"><button>保存接管设置</button></form>
<p class="note">也可右键点击链接发送。自动接管默认关闭;失败会恢复浏览器下载。首版不接管 POST、blob、登录 Cookie 或无法确认方法的下载。</p><script type="module" src="popup.js"></script></body></html>
+25
View File
@@ -0,0 +1,25 @@
import {DEFAULTS} from './logic.mjs';
const el = id => document.getElementById(id);
const cfg = {...DEFAULTS, ...(await chrome.storage.local.get('config')).config};
for (const field of ['sites', 'extensions']) el(field).value = cfg[field];
el('auto').checked = cfg.auto;
const show = result => { el('status').textContent = result?.message || '尚无接管记录;可先检查桌面连接。'; };
show((await chrome.storage.local.get('lastResult')).lastResult);
chrome.storage.onChanged.addListener(changes => { if (changes.lastResult) show(changes.lastResult.newValue); });
async function send(message, button) {
button.disabled = true;
try { show(await chrome.runtime.sendMessage(message)); } catch (error) { show({message: error.message}); }
finally { button.disabled = false; }
}
el('ping').onclick = event => send({action: 'ping'}, event.target);
el('send').onsubmit = event => { event.preventDefault(); send({action: 'send', url: el('url').value}, event.submitter); };
el('settings').onsubmit = async event => {
event.preventDefault();
try {
if (el('auto').checked && !(await chrome.permissions.request({permissions: ['webRequest'], origins: ['http://*/*', 'https://*/*']}))) {
el('auto').checked = false; return show({message: '未授权站点访问,自动接管保持关闭。'});
}
await chrome.storage.local.set({config: {auto: el('auto').checked, sites: el('sites').value.trim(), extensions: el('extensions').value.trim()}});
show({message: '接管设置已保存。'});
} catch (error) { show({message: error.message}); }
};