feat: add non-blocking NTCP2 sends and Firefox settings sync
- NTCP2: queue outbound data frames and flush them without blocking (send_blocks_nb, send_i2np_nb, flush_nonblocking) - NTCP2: bound write_all with a deadline and set TCP keepalive and user timeout on peer sockets - Firefox extension 0.1.3: save settings as a patch, keep unsaved form fields from being overwritten on refresh, add timeouts to router API calls, and honor the interceptTorrents toggle in the content script
This commit is contained in:
1 parent
82aaa9f11e
commit
9aa15f9ae8
18 files changed
+1323
-239
No files matched your search
Binary file not shown.
@@ -22,36 +22,38 @@ async function loadSettings() {
|
||||
async function syncFromNativeEnv(force = false) {
|
||||
const st = await nativeCommand("status");
|
||||
if (st && st.appimage && (!syncedAppImageEnv || force)) {
|
||||
let changed = false;
|
||||
const patch = {};
|
||||
if (st.env_proxy_host && st.env_proxy_host !== cachedSettings.proxyHost) {
|
||||
cachedSettings.proxyHost = st.env_proxy_host;
|
||||
changed = true;
|
||||
patch.proxyHost = st.env_proxy_host;
|
||||
}
|
||||
if (st.env_proxy_port > 0 && st.env_proxy_port !== Number(cachedSettings.proxyPort)) {
|
||||
cachedSettings.proxyPort = st.env_proxy_port;
|
||||
changed = true;
|
||||
patch.proxyPort = st.env_proxy_port;
|
||||
}
|
||||
if (st.env_api_host && st.env_api_host !== cachedSettings.apiHost) {
|
||||
cachedSettings.apiHost = st.env_api_host;
|
||||
changed = true;
|
||||
patch.apiHost = st.env_api_host;
|
||||
}
|
||||
if (st.env_api_port > 0 && st.env_api_port !== Number(cachedSettings.apiPort)) {
|
||||
cachedSettings.apiPort = st.env_api_port;
|
||||
changed = true;
|
||||
patch.apiPort = st.env_api_port;
|
||||
}
|
||||
if (st.env_download_dir && !cachedSettings.downloadDir) {
|
||||
cachedSettings.downloadDir = st.env_download_dir;
|
||||
changed = true;
|
||||
patch.downloadDir = st.env_download_dir;
|
||||
}
|
||||
syncedAppImageEnv = true;
|
||||
if (changed) {
|
||||
await browser.storage.local.set(cachedSettings);
|
||||
if (Object.keys(patch).length > 0) {
|
||||
cachedSettings = { ...cachedSettings, ...patch };
|
||||
await browser.storage.local.set(patch);
|
||||
}
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
loadSettings().then(() => syncFromNativeEnv());
|
||||
let startupCompleted = false;
|
||||
const startupReady = loadSettings()
|
||||
.then(() => syncFromNativeEnv())
|
||||
.catch(() => null)
|
||||
.finally(() => {
|
||||
startupCompleted = true;
|
||||
});
|
||||
|
||||
browser.storage.onChanged.addListener((changes, area) => {
|
||||
if (area !== "local") return;
|
||||
@@ -69,26 +71,33 @@ function isLoopbackHost(hostname) {
|
||||
);
|
||||
}
|
||||
|
||||
function resolveProxyForRequest(requestInfo) {
|
||||
try {
|
||||
const url = new URL(requestInfo.url);
|
||||
const host = url.hostname.toLowerCase();
|
||||
if (isLoopbackHost(host)) {
|
||||
return { type: "direct" };
|
||||
}
|
||||
if (cachedSettings.proxyEnabled && host.endsWith(".i2p")) {
|
||||
return {
|
||||
type: "http",
|
||||
host: cachedSettings.proxyHost || "127.0.0.1",
|
||||
port: Number(cachedSettings.proxyPort) || 4444,
|
||||
};
|
||||
}
|
||||
} catch (_e) {
|
||||
// Fall through to direct
|
||||
}
|
||||
return { type: "direct" };
|
||||
}
|
||||
|
||||
// Route *.i2p URLs through moon-i2p HTTP proxy; never proxy loopback API calls.
|
||||
browser.proxy.onRequest.addListener(
|
||||
(requestInfo) => {
|
||||
try {
|
||||
const url = new URL(requestInfo.url);
|
||||
const host = url.hostname.toLowerCase();
|
||||
if (isLoopbackHost(host)) {
|
||||
return { type: "direct" };
|
||||
}
|
||||
if (cachedSettings.proxyEnabled && host.endsWith(".i2p")) {
|
||||
return {
|
||||
type: "http",
|
||||
host: cachedSettings.proxyHost || "127.0.0.1",
|
||||
port: Number(cachedSettings.proxyPort) || 4444,
|
||||
};
|
||||
}
|
||||
} catch (_e) {
|
||||
// Fall through to direct
|
||||
if (!startupCompleted && !syncedAppImageEnv) {
|
||||
return startupReady.then(() => resolveProxyForRequest(requestInfo));
|
||||
}
|
||||
return { type: "direct" };
|
||||
return resolveProxyForRequest(requestInfo);
|
||||
},
|
||||
{ urls: ["<all_urls>"] }
|
||||
);
|
||||
@@ -99,26 +108,37 @@ function apiBaseUrl() {
|
||||
return `http://${host}:${port}`;
|
||||
}
|
||||
|
||||
async function apiJson(path, method = "GET", bodyObj = null) {
|
||||
async function apiJson(path, method = "GET", bodyObj = null, timeoutMs = 3000) {
|
||||
const headers = {};
|
||||
const opts = { method, headers, cache: "no-store" };
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
const opts = { method, headers, cache: "no-store", signal: controller.signal };
|
||||
if (method === "POST") {
|
||||
headers["X-Moon-I2P"] = "1";
|
||||
headers["Content-Type"] = "application/json";
|
||||
opts.body = JSON.stringify(bodyObj || {});
|
||||
}
|
||||
const resp = await fetch(`${apiBaseUrl()}${path}`, opts);
|
||||
const text = await resp.text();
|
||||
let data = null;
|
||||
try {
|
||||
data = JSON.parse(text);
|
||||
} catch (_e) {
|
||||
data = { ok: resp.ok, raw: text };
|
||||
const resp = await fetch(`${apiBaseUrl()}${path}`, opts);
|
||||
const text = await resp.text();
|
||||
let data = null;
|
||||
try {
|
||||
data = JSON.parse(text);
|
||||
} catch (_e) {
|
||||
data = { ok: resp.ok, raw: text };
|
||||
}
|
||||
if (!resp.ok && data && !data.error) {
|
||||
data.error = `HTTP ${resp.status}`;
|
||||
}
|
||||
return data;
|
||||
} catch (err) {
|
||||
if (err && err.name === "AbortError") {
|
||||
throw new Error(`Router API timeout (${timeoutMs}ms)`);
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
if (!resp.ok && data && !data.error) {
|
||||
data.error = `HTTP ${resp.status}`;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes) {
|
||||
@@ -132,10 +152,15 @@ function bytesToBase64(bytes) {
|
||||
|
||||
async function addTorrentBytes(uint8Bytes) {
|
||||
const b64 = bytesToBase64(uint8Bytes);
|
||||
return apiJson("/api/torrents/add", "POST", {
|
||||
torrent_b64: b64,
|
||||
download_dir: cachedSettings.downloadDir || "",
|
||||
});
|
||||
return apiJson(
|
||||
"/api/torrents/add",
|
||||
"POST",
|
||||
{
|
||||
torrent_b64: b64,
|
||||
download_dir: cachedSettings.downloadDir || "",
|
||||
},
|
||||
15000
|
||||
);
|
||||
}
|
||||
|
||||
async function addTorrentFromUrl(urlStr) {
|
||||
@@ -167,9 +192,9 @@ async function gatherFullState() {
|
||||
await loadSettings();
|
||||
const nativeStatus = await syncFromNativeEnv();
|
||||
const [routerStatus, torrents, dht] = await Promise.all([
|
||||
apiJson("/api/status").catch((e) => ({ ok: false, error: String(e) })),
|
||||
apiJson("/api/torrents").catch(() => ({ ok: false, torrents: [] })),
|
||||
apiJson("/api/dht/nodes").catch(() => ({ ok: false, nodes: [] })),
|
||||
apiJson("/api/status", "GET", null, 2500).catch((e) => ({ ok: false, error: String(e) })),
|
||||
apiJson("/api/torrents", "GET", null, 2500).catch(() => ({ ok: false, torrents: [] })),
|
||||
apiJson("/api/dht/nodes", "GET", null, 2500).catch(() => ({ ok: false, nodes: [] })),
|
||||
]);
|
||||
return {
|
||||
settings: cachedSettings,
|
||||
@@ -202,12 +227,22 @@ browser.downloads.onCreated.addListener(async (item) => {
|
||||
browser.runtime.onMessage.addListener(async (msg) => {
|
||||
await loadSettings();
|
||||
switch (msg?.type) {
|
||||
case "getSettings":
|
||||
return { ok: true, settings: cachedSettings };
|
||||
case "getState":
|
||||
return gatherFullState();
|
||||
case "saveSettings": {
|
||||
const next = { ...cachedSettings, ...(msg.settings || {}) };
|
||||
await browser.storage.local.set(next);
|
||||
cachedSettings = next;
|
||||
const incoming = msg.settings || {};
|
||||
const patch = {};
|
||||
for (const key of Object.keys(DEFAULT_SETTINGS)) {
|
||||
if (incoming[key] !== undefined) {
|
||||
patch[key] = incoming[key];
|
||||
}
|
||||
}
|
||||
if (Object.keys(patch).length > 0) {
|
||||
await browser.storage.local.set(patch);
|
||||
cachedSettings = { ...cachedSettings, ...patch };
|
||||
}
|
||||
return { ok: true, settings: cachedSettings };
|
||||
}
|
||||
case "startRouter":
|
||||
@@ -215,10 +250,15 @@ browser.runtime.onMessage.addListener(async (msg) => {
|
||||
case "stopRouter":
|
||||
return nativeCommand("stop_router");
|
||||
case "addMagnet":
|
||||
return apiJson("/api/torrents/magnet", "POST", {
|
||||
uri: msg.uri || "",
|
||||
download_dir: cachedSettings.downloadDir || "",
|
||||
});
|
||||
return apiJson(
|
||||
"/api/torrents/magnet",
|
||||
"POST",
|
||||
{
|
||||
uri: msg.uri || "",
|
||||
download_dir: cachedSettings.downloadDir || "",
|
||||
},
|
||||
15000
|
||||
);
|
||||
case "addTorrentUrl":
|
||||
try {
|
||||
return await addTorrentFromUrl(msg.url);
|
||||
@@ -226,21 +266,31 @@ browser.runtime.onMessage.addListener(async (msg) => {
|
||||
return { ok: false, error: String(e) };
|
||||
}
|
||||
case "addTorrentB64":
|
||||
return apiJson("/api/torrents/add", "POST", {
|
||||
torrent_b64: msg.torrentB64 || "",
|
||||
download_dir: cachedSettings.downloadDir || "",
|
||||
});
|
||||
return apiJson(
|
||||
"/api/torrents/add",
|
||||
"POST",
|
||||
{
|
||||
torrent_b64: msg.torrentB64 || "",
|
||||
download_dir: cachedSettings.downloadDir || "",
|
||||
},
|
||||
15000
|
||||
);
|
||||
case "pauseTorrent":
|
||||
return apiJson("/api/torrents/pause", "POST", { info_hash: msg.infoHash });
|
||||
return apiJson("/api/torrents/pause", "POST", { info_hash: msg.infoHash }, 10000);
|
||||
case "resumeTorrent":
|
||||
return apiJson("/api/torrents/resume", "POST", { info_hash: msg.infoHash });
|
||||
return apiJson("/api/torrents/resume", "POST", { info_hash: msg.infoHash }, 10000);
|
||||
case "removeTorrent":
|
||||
return apiJson("/api/torrents/remove", "POST", { info_hash: msg.infoHash });
|
||||
return apiJson("/api/torrents/remove", "POST", { info_hash: msg.infoHash }, 10000);
|
||||
case "bootstrapDht":
|
||||
return apiJson("/api/dht/bootstrap", "POST", {
|
||||
b32: msg.b32 || "",
|
||||
port: Number(msg.port) || 6881,
|
||||
});
|
||||
return apiJson(
|
||||
"/api/dht/bootstrap",
|
||||
"POST",
|
||||
{
|
||||
b32: msg.b32 || "",
|
||||
port: Number(msg.port) || 6881,
|
||||
},
|
||||
10000
|
||||
);
|
||||
case "openManager": {
|
||||
const url = browser.runtime.getURL("manager.html");
|
||||
const existing = await browser.tabs.query({ url });
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
"use strict";
|
||||
|
||||
(function () {
|
||||
let interceptTorrents = true;
|
||||
if (browser.storage && browser.storage.local) {
|
||||
browser.storage.local
|
||||
.get({ interceptTorrents: true })
|
||||
.then((res) => {
|
||||
interceptTorrents = !!res.interceptTorrents;
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
if (browser.storage && browser.storage.onChanged) {
|
||||
browser.storage.onChanged.addListener((changes, area) => {
|
||||
if (area === "local" && Object.prototype.hasOwnProperty.call(changes, "interceptTorrents")) {
|
||||
interceptTorrents = !!changes.interceptTorrents.newValue;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function showToast(text, isError) {
|
||||
let el = document.getElementById("moon-i2p-torrent-toast");
|
||||
if (!el) {
|
||||
@@ -33,6 +50,9 @@
|
||||
document.addEventListener(
|
||||
"click",
|
||||
async (ev) => {
|
||||
if (!interceptTorrents) {
|
||||
return;
|
||||
}
|
||||
if (ev.button !== 0 || ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 2,
|
||||
"name": "Moon I2P Torrent & Proxy",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"description": "Route .i2p browsing through moon-i2p and manage I2P BitTorrent + I2P DHT torrents from Firefox.",
|
||||
"icons": {
|
||||
"48": "icon.svg",
|
||||
|
||||
@@ -40,88 +40,152 @@ function bytesToBase64(bytes) {
|
||||
return btoa(bin);
|
||||
}
|
||||
|
||||
let settingsPopulated = false;
|
||||
const DEFAULT_SETTINGS = {
|
||||
proxyEnabled: true,
|
||||
proxyHost: "127.0.0.1",
|
||||
proxyPort: 4444,
|
||||
apiHost: "127.0.0.1",
|
||||
apiPort: 4445,
|
||||
downloadDir: "",
|
||||
interceptTorrents: true,
|
||||
};
|
||||
|
||||
async function refresh() {
|
||||
const st = await browser.runtime.sendMessage({ type: "getState" });
|
||||
const cfg = st.settings || {};
|
||||
const rs = st.routerStatus || {};
|
||||
const ns = st.nativeStatus || {};
|
||||
const dht = st.dht || {};
|
||||
let currentSettings = { ...DEFAULT_SETTINGS };
|
||||
const dirtyFields = new Set();
|
||||
let refreshInFlight = false;
|
||||
let refreshPending = false;
|
||||
let initialSettingsPromise = null;
|
||||
|
||||
$("proxy-enabled").checked = !!cfg.proxyEnabled;
|
||||
$("proxy-addr").textContent = `${cfg.proxyHost || "127.0.0.1"}:${cfg.proxyPort || 4444}`;
|
||||
|
||||
if (!settingsPopulated) {
|
||||
settingsPopulated = true;
|
||||
$("cfg-proxy-port").value = cfg.proxyPort || 4444;
|
||||
$("cfg-api-port").value = cfg.apiPort || 4445;
|
||||
$("cfg-dl-dir").value = cfg.downloadDir || "";
|
||||
$("cfg-intercept").checked = !!cfg.interceptTorrents;
|
||||
function parsePort(raw, fallback) {
|
||||
const s = String(raw ?? "").trim();
|
||||
if (!s) return fallback;
|
||||
const n = Number(s);
|
||||
if (Number.isInteger(n) && n >= 1 && n <= 65535) {
|
||||
return n;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const pill = $("router-pill");
|
||||
const startBtn = $("start-router-btn");
|
||||
const stopBtn = $("stop-router-btn");
|
||||
if (rs.ok) {
|
||||
pill.textContent = rs.public_mode ? "Public Online" : "Online";
|
||||
pill.className = "pill online";
|
||||
startBtn.style.display = "none";
|
||||
stopBtn.style.display = ns.managed_running ? "" : "none";
|
||||
$("net-summary").textContent = `${rs.netdb_routers || 0} peers · ${rs.inbound_tunnels || 0}in/${rs.outbound_tunnels || 0}out`;
|
||||
$("torrent-b32").textContent = rs.torrent_b32 || "--";
|
||||
const d = rs.dht || {};
|
||||
$("dht-summary").textContent = `${d.routing_table_nodes || 0} nodes (UDP-over-I2CP ${d.query_port || 6881}/${d.reply_port || 6882})`;
|
||||
$("dht-node-id").textContent = d.node_id_hex || "--";
|
||||
$("dht-stats").textContent = `${d.queries_sent || 0} / ${d.responses_recv || 0} / ${d.peers_discovered || 0}`;
|
||||
} else {
|
||||
pill.textContent = "Offline";
|
||||
pill.className = "pill offline";
|
||||
startBtn.style.display = "";
|
||||
stopBtn.style.display = "none";
|
||||
$("net-summary").textContent = "Router unreachable";
|
||||
$("torrent-b32").textContent = "--";
|
||||
function applySettingsToUi(cfg) {
|
||||
currentSettings = { ...currentSettings, ...(cfg || {}) };
|
||||
$("proxy-enabled").checked = !!currentSettings.proxyEnabled;
|
||||
$("proxy-addr").textContent = `${currentSettings.proxyHost || "127.0.0.1"}:${currentSettings.proxyPort || 4444}`;
|
||||
if (!dirtyFields.has("proxyPort")) {
|
||||
$("cfg-proxy-port").value = currentSettings.proxyPort || 4444;
|
||||
}
|
||||
|
||||
const nodesEl = $("dht-nodes-list");
|
||||
if (nodesEl) {
|
||||
const nodes = dht.nodes || [];
|
||||
nodesEl.innerHTML =
|
||||
nodes.length === 0
|
||||
? "<span class='stat-label'>No DHT nodes yet. Bootstrap above or connect to a peer.</span>"
|
||||
: nodes
|
||||
.map(
|
||||
(n) =>
|
||||
`<div class="node-row">${escapeHtml(n.b32)}:${n.port} (${escapeHtml((n.node_id_hex || "").slice(0, 12))}...)</div>`
|
||||
)
|
||||
.join("");
|
||||
if (!dirtyFields.has("apiPort")) {
|
||||
$("cfg-api-port").value = currentSettings.apiPort || 4445;
|
||||
}
|
||||
if (!dirtyFields.has("downloadDir")) {
|
||||
$("cfg-dl-dir").value = currentSettings.downloadDir || "";
|
||||
}
|
||||
if (!dirtyFields.has("interceptTorrents")) {
|
||||
$("cfg-intercept").checked = !!currentSettings.interceptTorrents;
|
||||
}
|
||||
}
|
||||
|
||||
const list = st.torrents || [];
|
||||
$("torrent-count").textContent = String(list.length);
|
||||
const tEl = $("torrents-list");
|
||||
if (list.length === 0) {
|
||||
tEl.innerHTML = "<div class='stat-label'>No active torrents. Paste a magnet link or drop a .torrent file above.</div>";
|
||||
} else {
|
||||
tEl.innerHTML = list
|
||||
.map((t) => {
|
||||
const pct = Number(t.progress_pct || 0);
|
||||
const toggleLabel = t.paused ? "Resume" : "Pause";
|
||||
const toggleType = t.paused ? "resumeTorrent" : "pauseTorrent";
|
||||
const infTxt = t.inflight_blocks > 0 ? ` (+${t.inflight_blocks} blks)` : "";
|
||||
const trackerHtml = t.last_tracker_status
|
||||
? `<div style="color:var(--muted);font-size:11px;">Tracker: ${escapeHtml(t.last_tracker_status)}</div>`
|
||||
: "";
|
||||
const peers = Array.isArray(t.peers) ? t.peers : [];
|
||||
const peersHtml = peers.length
|
||||
? `<div style="color:var(--muted);font-size:11px;font-family:monospace;line-height:1.4;">${peers
|
||||
async function loadSettingsFast() {
|
||||
let cfg = null;
|
||||
try {
|
||||
if (browser.storage && browser.storage.local) {
|
||||
cfg = await browser.storage.local.get(DEFAULT_SETTINGS);
|
||||
} else {
|
||||
const res = await browser.runtime.sendMessage({ type: "getSettings" });
|
||||
cfg = res && res.settings ? res.settings : null;
|
||||
}
|
||||
} catch (_e) {
|
||||
try {
|
||||
const res = await browser.runtime.sendMessage({ type: "getSettings" });
|
||||
cfg = res && res.settings ? res.settings : null;
|
||||
} catch (_e2) {
|
||||
cfg = null;
|
||||
}
|
||||
}
|
||||
if (cfg) {
|
||||
applySettingsToUi(cfg);
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh(force = false) {
|
||||
if (refreshInFlight) {
|
||||
if (force) {
|
||||
refreshPending = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
refreshInFlight = true;
|
||||
try {
|
||||
const st = await browser.runtime.sendMessage({ type: "getState" });
|
||||
if (!st) return;
|
||||
const cfg = st.settings || {};
|
||||
const rs = st.routerStatus || {};
|
||||
const ns = st.nativeStatus || {};
|
||||
const dht = st.dht || {};
|
||||
|
||||
applySettingsToUi(cfg);
|
||||
|
||||
const pill = $("router-pill");
|
||||
const startBtn = $("start-router-btn");
|
||||
const stopBtn = $("stop-router-btn");
|
||||
if (rs.ok) {
|
||||
pill.textContent = rs.public_mode ? "Public Online" : "Online";
|
||||
pill.className = "pill online";
|
||||
startBtn.style.display = "none";
|
||||
stopBtn.style.display = ns.managed_running ? "" : "none";
|
||||
$("net-summary").textContent = `${rs.netdb_routers || 0} peers · ${rs.inbound_tunnels || 0}in/${rs.outbound_tunnels || 0}out`;
|
||||
$("torrent-b32").textContent = rs.torrent_b32 || "--";
|
||||
const d = rs.dht || {};
|
||||
$("dht-summary").textContent = `${d.routing_table_nodes || 0} nodes (UDP-over-I2CP ${d.query_port || 6881}/${d.reply_port || 6882})`;
|
||||
$("dht-node-id").textContent = d.node_id_hex || "--";
|
||||
$("dht-stats").textContent = `${d.queries_sent || 0} / ${d.responses_recv || 0} / ${d.peers_discovered || 0}`;
|
||||
} else {
|
||||
pill.textContent = "Offline";
|
||||
pill.className = "pill offline";
|
||||
startBtn.style.display = "";
|
||||
stopBtn.style.display = "none";
|
||||
$("net-summary").textContent = "Router unreachable";
|
||||
$("torrent-b32").textContent = "--";
|
||||
}
|
||||
|
||||
const nodesEl = $("dht-nodes-list");
|
||||
if (nodesEl) {
|
||||
const nodes = dht.nodes || [];
|
||||
nodesEl.innerHTML =
|
||||
nodes.length === 0
|
||||
? "<span class='stat-label'>No DHT nodes yet. Bootstrap above or connect to a peer.</span>"
|
||||
: nodes
|
||||
.map(
|
||||
(p) =>
|
||||
`<div>peer ${escapeHtml(p.b32)}${p.client ? ` [${escapeHtml(p.client)}]` : ""} · st=${escapeHtml(String(p.state ?? ""))} ${p.choking ? "choked" : "unchoked"} · ${p.pieces || 0} pcs · inf=${p.in_flight || 0} · blks=${p.blocks_recv || 0}</div>`
|
||||
(n) =>
|
||||
`<div class="node-row">${escapeHtml(n.b32)}:${n.port} (${escapeHtml((n.node_id_hex || "").slice(0, 12))}...)</div>`
|
||||
)
|
||||
.join("")}</div>`
|
||||
: "";
|
||||
return `
|
||||
.join("");
|
||||
}
|
||||
|
||||
const list = st.torrents || [];
|
||||
$("torrent-count").textContent = String(list.length);
|
||||
const tEl = $("torrents-list");
|
||||
if (list.length === 0) {
|
||||
tEl.innerHTML = "<div class='stat-label'>No active torrents. Paste a magnet link or drop a .torrent file above.</div>";
|
||||
} else {
|
||||
tEl.innerHTML = list
|
||||
.map((t) => {
|
||||
const pct = Number(t.progress_pct || 0);
|
||||
const toggleLabel = t.paused ? "Resume" : "Pause";
|
||||
const toggleType = t.paused ? "resumeTorrent" : "pauseTorrent";
|
||||
const infTxt = t.inflight_blocks > 0 ? ` (+${t.inflight_blocks} blks)` : "";
|
||||
const trackerHtml = t.last_tracker_status
|
||||
? `<div style="color:var(--muted);font-size:11px;">Tracker: ${escapeHtml(t.last_tracker_status)}</div>`
|
||||
: "";
|
||||
const peers = Array.isArray(t.peers) ? t.peers : [];
|
||||
const peersHtml = peers.length
|
||||
? `<div style="color:var(--muted);font-size:11px;font-family:monospace;line-height:1.4;">${peers
|
||||
.map(
|
||||
(p) =>
|
||||
`<div>peer ${escapeHtml(p.b32)}${p.client ? ` [${escapeHtml(p.client)}]` : ""} · st=${escapeHtml(String(p.state ?? ""))} ${p.choking ? "choked" : "unchoked"} · ${p.pieces || 0} pcs · inf=${p.in_flight || 0} · blks=${p.blocks_recv || 0}</div>`
|
||||
)
|
||||
.join("")}</div>`
|
||||
: "";
|
||||
return `
|
||||
<div class="torrent-item" data-ih="${escapeHtml(t.info_hash)}">
|
||||
<div class="row" style="justify-content:space-between;">
|
||||
<strong>${escapeHtml(t.name)}</strong>
|
||||
@@ -140,12 +204,45 @@ async function refresh() {
|
||||
${t.error ? `<div class="msg err">${escapeHtml(t.error)}</div>` : ""}
|
||||
</div>
|
||||
`;
|
||||
})
|
||||
.join("");
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
} catch (_e) {
|
||||
// Ignore transient runtime errors during refresh
|
||||
} finally {
|
||||
refreshInFlight = false;
|
||||
if (refreshPending) {
|
||||
refreshPending = false;
|
||||
refresh(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
for (const [id, field] of [
|
||||
["cfg-proxy-port", "proxyPort"],
|
||||
["cfg-api-port", "apiPort"],
|
||||
["cfg-dl-dir", "downloadDir"],
|
||||
["cfg-intercept", "interceptTorrents"],
|
||||
]) {
|
||||
const el = $(id);
|
||||
if (el) {
|
||||
el.addEventListener("input", () => dirtyFields.add(field));
|
||||
el.addEventListener("change", () => dirtyFields.add(field));
|
||||
}
|
||||
}
|
||||
|
||||
if (browser.storage && browser.storage.onChanged) {
|
||||
browser.storage.onChanged.addListener((changes, area) => {
|
||||
if (area !== "local") return;
|
||||
const patch = {};
|
||||
for (const [key, val] of Object.entries(changes)) {
|
||||
patch[key] = val.newValue;
|
||||
}
|
||||
applySettingsToUi(patch);
|
||||
});
|
||||
}
|
||||
|
||||
if ($("open-manager-btn")) {
|
||||
$("open-manager-btn").addEventListener("click", () =>
|
||||
browser.runtime.sendMessage({ type: "openManager" })
|
||||
@@ -157,7 +254,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
type: "saveSettings",
|
||||
settings: { proxyEnabled: e.target.checked },
|
||||
});
|
||||
refresh();
|
||||
refresh(true);
|
||||
});
|
||||
|
||||
$("start-router-btn").addEventListener("click", async () => {
|
||||
@@ -168,13 +265,13 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
} else {
|
||||
setMsg(`Failed to start router: ${(res && res.error) || "run just extension"}`, true);
|
||||
}
|
||||
setTimeout(refresh, 700);
|
||||
setTimeout(() => refresh(true), 700);
|
||||
});
|
||||
|
||||
$("stop-router-btn").addEventListener("click", async () => {
|
||||
await browser.runtime.sendMessage({ type: "stopRouter" });
|
||||
setMsg("Stopped router.");
|
||||
setTimeout(refresh, 400);
|
||||
setTimeout(() => refresh(true), 400);
|
||||
});
|
||||
|
||||
$("bootstrap-form").addEventListener("submit", async (e) => {
|
||||
@@ -184,7 +281,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
if (!b32) return;
|
||||
const res = await browser.runtime.sendMessage({ type: "bootstrapDht", b32, port });
|
||||
setMsg(res && res.ok ? `Sent DHT ping to ${res.b32}:${res.port}` : `DHT error: ${res?.error || "failed"}`, !res?.ok);
|
||||
refresh();
|
||||
refresh(true);
|
||||
});
|
||||
|
||||
$("magnet-form").addEventListener("submit", async (e) => {
|
||||
@@ -198,7 +295,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
} else {
|
||||
setMsg(`Magnet failed: ${res?.error || "router offline"}`, true);
|
||||
}
|
||||
refresh();
|
||||
refresh(true);
|
||||
});
|
||||
|
||||
const dz = $("dropzone");
|
||||
@@ -211,7 +308,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
torrentB64: bytesToBase64(buf),
|
||||
});
|
||||
setMsg(res && res.ok ? `Added ${file.name} (${res.info_hash.slice(0, 12)}...)` : `Add failed: ${res?.error}`, !res?.ok);
|
||||
refresh();
|
||||
refresh(true);
|
||||
};
|
||||
dz.addEventListener("click", () => fileIn.click());
|
||||
fileIn.addEventListener("change", () => handleFile(fileIn.files[0]));
|
||||
@@ -233,24 +330,41 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
type: btn.dataset.act,
|
||||
infoHash: btn.dataset.ih,
|
||||
});
|
||||
refresh();
|
||||
refresh(true);
|
||||
});
|
||||
|
||||
$("settings-form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
await browser.runtime.sendMessage({
|
||||
type: "saveSettings",
|
||||
settings: {
|
||||
proxyPort: Number($("cfg-proxy-port").value) || 4444,
|
||||
apiPort: Number($("cfg-api-port").value) || 4445,
|
||||
downloadDir: $("cfg-dl-dir").value.trim(),
|
||||
interceptTorrents: $("cfg-intercept").checked,
|
||||
},
|
||||
});
|
||||
setMsg("Settings saved.");
|
||||
refresh();
|
||||
if (initialSettingsPromise) {
|
||||
await initialSettingsPromise;
|
||||
}
|
||||
const nextSettings = {
|
||||
proxyPort: dirtyFields.has("proxyPort")
|
||||
? parsePort($("cfg-proxy-port").value, currentSettings.proxyPort || 4444)
|
||||
: (currentSettings.proxyPort || 4444),
|
||||
apiPort: dirtyFields.has("apiPort")
|
||||
? parsePort($("cfg-api-port").value, currentSettings.apiPort || 4445)
|
||||
: (currentSettings.apiPort || 4445),
|
||||
downloadDir: dirtyFields.has("downloadDir")
|
||||
? $("cfg-dl-dir").value.trim()
|
||||
: (currentSettings.downloadDir || ""),
|
||||
interceptTorrents: $("cfg-intercept").checked,
|
||||
};
|
||||
try {
|
||||
const res = await browser.runtime.sendMessage({
|
||||
type: "saveSettings",
|
||||
settings: nextSettings,
|
||||
});
|
||||
dirtyFields.clear();
|
||||
applySettingsToUi((res && res.settings) || nextSettings);
|
||||
setMsg("Settings saved.");
|
||||
refresh(true);
|
||||
} catch (err) {
|
||||
setMsg(`Failed to save settings: ${err}`, true);
|
||||
}
|
||||
});
|
||||
|
||||
refresh();
|
||||
setInterval(refresh, 2000);
|
||||
initialSettingsPromise = loadSettingsFast();
|
||||
refresh(false);
|
||||
setInterval(() => refresh(false), 2000);
|
||||
});
|
||||
Reference in new issue
Block a user