Files
moon-i2p/extensions/firefox-i2p-torrent/start.js
T
nandi 7139a64544
check / check (macos-latest) (push) Failing after 27s
check / check (windows-latest) (push) Failing after 26s
check / check (ubuntu-latest) (push) Failing after 30s
feat: add built-in Moon I2P start page to Firefox and Android
- Firefox extension: add start.html/css/js as homepage and new-tab page (manifest bumped to 0.1.5, .xpi rebuilt). Shows router readiness, tunnel/NetDB/DHT tiles, torrents, and a .i2p/magnet address bar.
- openManager message now accepts an optional hash and reuses any open manager tab.
- Android: default page is file:///android_asset/start.html, backed by a MoonI2pStart JS bridge (status, torrents, open URL, diagnostics, copy .b32). Blocks file: navigation from the WebView.
- RouterService: add fetchLocalApiJsonOrNull for bounded local API reads.
- Built-in .i2p destinations reordered (NotBob, Postman first); README updated to match.
2026-11-28 20:24:28 -08:00

282 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
function normalizeNavigationInput(raw) {
const trimmed = String(raw || "").trim();
if (!trimmed) {
return { kind: "empty" };
}
if (/^magnet:/i.test(trimmed)) {
return { kind: "magnet", value: trimmed };
}
if (/\s/.test(trimmed)) {
return {
kind: "invalid",
error: "Enter a .i2p domain (e.g. notbob.i2p), .b32.i2p address, or magnet: link.",
};
}
if (/^https?:\/\//i.test(trimmed)) {
return { kind: "url", value: trimmed };
}
if (!/[./:]/.test(trimmed)) {
return { kind: "url", value: "http://" + trimmed + ".i2p/" };
}
return { kind: "url", value: "http://" + trimmed };
}
if (typeof module !== "undefined" && module.exports) {
module.exports = { normalizeNavigationInput };
}
if (typeof document !== "undefined" && typeof browser !== "undefined") {
const $ = (id) => document.getElementById(id);
function fmtBytes(n) {
if (!n || n <= 0) return "0 B";
const units = ["B", "KiB", "MiB", "GiB"];
let u = 0;
let v = n;
while (v >= 1024 && u < units.length - 1) {
v /= 1024;
u++;
}
return `${v.toFixed(u === 0 ? 0 : 1)} ${units[u]}`;
}
function escapeHtml(s) {
return String(s || "").replace(/[&<>"']/g, (c) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
})[c]);
}
function setNavMsg(text, isErr = false) {
const el = $("nav-msg");
if (!el) return;
el.textContent = text;
el.className = isErr ? "msg err" : "msg";
}
async function copyTextToClipboard(text) {
if (navigator.clipboard && navigator.clipboard.writeText) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (_e) {
// Fall through to textarea + execCommand fallback
}
}
const ta = document.createElement("textarea");
ta.value = text;
ta.setAttribute("readonly", "");
ta.style.position = "fixed";
ta.style.top = "-9999px";
ta.style.left = "-9999px";
document.body.appendChild(ta);
ta.select();
let ok = false;
try {
ok = document.execCommand("copy");
} finally {
document.body.removeChild(ta);
}
return ok;
}
let currentB32 = "";
let copyTimer = null;
let refreshInFlight = false;
async function refreshStatus() {
if (refreshInFlight || document.hidden) return;
refreshInFlight = true;
try {
const st = await browser.runtime.sendMessage({ type: "getState" });
if (!st) return;
const cfg = st.settings || {};
const rs = st.routerStatus || {};
const torrents = Array.isArray(st.torrents) ? st.torrents : [];
const dhtNodes = (st.dht && Array.isArray(st.dht.nodes) ? st.dht.nodes.length : 0);
const proxyAddr = `${cfg.proxyHost || "127.0.0.1"}:${cfg.proxyPort || 4444}`;
const proxyEnabled = cfg.proxyEnabled !== false;
$("proxy-pill").textContent = proxyEnabled ? `Proxy: ${proxyAddr}` : `Proxy Disabled (${proxyAddr})`;
$("proxy-pill").className = proxyEnabled ? "pill online" : "pill offline";
$("footer-proxy").textContent = `Proxy: ${proxyAddr} (${proxyEnabled ? "enabled" : "disabled"})`;
const pill = $("status-pill");
const startBtn = $("start-router-btn");
const banner = $("warmup-banner");
const bannerTitle = $("warmup-title");
const bannerDetail = $("warmup-detail");
if (!rs.ok) {
pill.textContent = "Offline";
pill.className = "pill offline";
startBtn.style.display = "";
banner.className = "warmup-banner is-offline";
bannerTitle.textContent = "moon-i2p router is offline or starting";
bannerDetail.textContent = "Click Start Router above or wait for the bundled router to finish launching.";
$("tile-tunnels-val").textContent = "--";
$("tile-tunnels-sub").textContent = "Router unreachable";
$("tile-netdb-val").textContent = "--";
$("tile-netdb-sub").textContent = "-- floodfills";
$("tile-dht-val").textContent = "--";
$("tile-dht-sub").textContent = "Proto 17 / 18";
currentB32 = "";
$("footer-b32").textContent = "--";
$("footer-b32").title = "--";
} else {
startBtn.style.display = "none";
const inTunnels = Number(rs.inbound_tunnels || 0);
const outTunnels = Number(rs.outbound_tunnels || 0);
const routers = Number(rs.netdb_routers || 0);
const floodfills = Number(rs.netdb_floodfills || 0);
const dhtInfo = rs.dht || {};
const dhtCount = Number(dhtInfo.routing_table_nodes ?? dhtNodes ?? 0);
$("tile-tunnels-val").textContent = `${inTunnels}in / ${outTunnels}out`;
$("tile-tunnels-sub").textContent = inTunnels > 0 && outTunnels > 0 ? "Tunnels established" : "Building client tunnels";
$("tile-netdb-val").textContent = `${routers}`;
$("tile-netdb-sub").textContent = `${floodfills} floodfills`;
$("tile-dht-val").textContent = `${dhtCount} nodes`;
$("tile-dht-sub").textContent = `${dhtInfo.queries_sent || 0} sent / ${dhtInfo.peers_discovered || 0} peers`;
currentB32 = rs.torrent_b32 || "";
$("footer-b32").textContent = currentB32 || "--";
$("footer-b32").title = currentB32 || "--";
if (inTunnels === 0 || outTunnels === 0) {
pill.textContent = "Bootstrapping...";
pill.className = "pill booting";
banner.className = "warmup-banner is-booting";
bannerTitle.textContent = "Bootstrapping I2P tunnels (typically 15–30s)...";
bannerDetail.textContent = `NetDB has ${routers} peers (${floodfills} floodfills), ${inTunnels}in/${outTunnels}out tunnels built. .i2p sites will load once tunnels come up.`;
} else {
pill.textContent = rs.public_mode ? "Public Online" : "I2P Ready";
pill.className = "pill online";
banner.className = "warmup-banner is-ready";
bannerTitle.textContent = "I2P tunnels active and ready";
bannerDetail.textContent = `${inTunnels} inbound / ${outTunnels} outbound tunnels · ${routers} NetDB peers · Ready to browse .i2p and download torrents.`;
}
}
const activeCount = torrents.filter((t) => !t.completed && !t.paused).length;
$("tile-torrents-val").textContent = `${torrents.length} total`;
$("tile-torrents-sub").textContent = activeCount > 0 ? `${activeCount} downloading · Open manager` : "Open manager";
const tCard = $("active-torrents-card");
const tList = $("active-torrents-list");
$("active-torrents-count").textContent = String(torrents.length);
if (torrents.length === 0) {
tCard.style.display = "none";
tList.innerHTML = "";
} else {
tCard.style.display = "";
tList.innerHTML = torrents
.slice(0, 6)
.map((t) => {
const pct = Math.max(0, Math.min(100, Number(t.progress_pct || 0)));
return `
<div class="torrent-item">
<div class="row" style="justify-content:space-between;">
<strong>${escapeHtml(t.name)}</strong>
<span class="pill ${t.completed ? "online" : ""}">${escapeHtml(t.state)} · ${pct}%</span>
</div>
<div class="progress-track"><div class="progress-fill" style="width:${pct}%"></div></div>
<div style="color:var(--muted);font-size:11px;">
${fmtBytes(t.downloaded_bytes)} / ${fmtBytes(t.total_length)} · ${t.connected_peers || 0}/${t.known_peers || 0} peers
</div>
</div>
`;
})
.join("");
}
} catch (_e) {
// Ignore transient polling errors while background wakes up
} finally {
refreshInFlight = false;
}
}
document.addEventListener("DOMContentLoaded", () => {
$("nav-form").addEventListener("submit", async (e) => {
e.preventDefault();
const parsed = normalizeNavigationInput($("nav-input").value);
if (parsed.kind === "empty") {
setNavMsg("");
return;
}
if (parsed.kind === "invalid") {
setNavMsg(parsed.error, true);
return;
}
if (parsed.kind === "magnet") {
setNavMsg("Submitting magnet URI to moon-i2p...");
const res = await browser.runtime.sendMessage({ type: "addMagnet", uri: parsed.value });
if (res && res.ok) {
$("nav-input").value = "";
setNavMsg(`Added magnet ${(res.info_hash || "").slice(0, 12)}...`);
await browser.runtime.sendMessage({ type: "openManager" });
} else {
setNavMsg(`Magnet failed: ${(res && res.error) || "router offline"}`, true);
}
return;
}
setNavMsg("");
window.location.href = parsed.value;
});
const openManager = () => browser.runtime.sendMessage({ type: "openManager" });
$("open-manager-btn").addEventListener("click", openManager);
$("torrents-tile").addEventListener("click", openManager);
$("open-manager-btn-2").addEventListener("click", openManager);
$("open-diag-btn").addEventListener("click", () =>
browser.runtime.sendMessage({ type: "openManager", hash: "#diagnostics-card" })
);
$("start-router-btn").addEventListener("click", async () => {
setNavMsg("Starting moon-i2p router via native host...");
const res = await browser.runtime.sendMessage({ type: "startRouter" });
if (res && res.ok) {
setNavMsg("Router starting (waiting for API & tunnels)...");
} else {
setNavMsg(`Failed to start router: ${(res && res.error) || "unavailable"}`, true);
}
setTimeout(() => refreshStatus(), 700);
});
$("copy-b32-btn").addEventListener("click", async () => {
if (!currentB32) {
setNavMsg("Router has not published a .b32.i2p address yet.", true);
return;
}
const btn = $("copy-b32-btn");
const ok = await copyTextToClipboard(currentB32);
if (ok) {
btn.textContent = "Copied!";
if (copyTimer) clearTimeout(copyTimer);
copyTimer = setTimeout(() => {
btn.textContent = "Copy .b32";
copyTimer = null;
}, 1500);
} else {
setNavMsg("Clipboard copy blocked by browser.", true);
}
});
document.addEventListener("visibilitychange", () => {
if (!document.hidden) {
refreshStatus();
}
});
refreshStatus();
setInterval(() => refreshStatus(), 2000);
});
}