// background.js —— 后台服务,处理右键菜单和 qBittorrent API 调用 chrome.runtime.onInstalled.addListener(() => { chrome.contextMenus.create({ id: "sendToQbLink", title: "发送到 qBittorrent", contexts: ["link"] }); chrome.contextMenus.create({ id: "sendToQbPage", title: "发送选中链接到 qBittorrent", contexts: ["selection"] }); }); chrome.contextMenus.onClicked.addListener((info, tab) => { let url = null; if (info.menuItemId === "sendToQbLink" && info.linkUrl) { url = info.linkUrl; } else if (info.menuItemId === "sendToQbPage" && info.selectionText) { // 从选中文本里提取第一个 magnet: 或 .torrent 链接 const m = info.selectionText.match(/(magnet:\?[^"\s]+|https?:\/\/[^\s"']+\.torrent)/i); if (m) url = m[1]; } if (url) { sendToQb(url); } else { notify("没找到有效的种子链接"); } }); // 接收来自 content.js / popup.js 的消息 chrome.runtime.onMessage.addListener((msg) => { if (msg && msg.type === "sendTorrent" && msg.url) { sendToQb(msg.url); } }); async function sendToQb(url) { const cfg = await chrome.storage.local.get([ "qbUrl", "qbUser", "qbPass", "savePath" ]); const base = (cfg.qbUrl || "http://127.0.0.1:8080").replace(/\/+$/, ""); const user = cfg.qbUser || "dijian"; const pass = cfg.qbPass || ""; try { // 1. 登录 const login = new URLSearchParams(); login.append("username", user); login.append("password", pass); const loginResp = await fetch(base + "/api/v2/auth/login", { method: "POST", body: login, credentials: "include" }); const loginText = await loginResp.text(); if (loginText !== "Ok.") { notify("qB 登录失败: " + loginText); return; } // 2. 添加种子 if (url.startsWith("magnet:")) { const form = new URLSearchParams(); form.append("urls", url); if (cfg.savePath) form.append("savepath", cfg.savePath); const resp = await fetch(base + "/api/v2/torrents/add", { method: "POST", body: form, credentials: "include" }); const text = await resp.text(); notify(text.includes("Ok") ? "磁力链接已发送 ✓" : "添加失败: " + text); } else { const fileResp = await fetch(url, { credentials: "include" }); const blob = await fileResp.blob(); const form = new FormData(); form.append("torrents", blob, "torrent.torrent"); if (cfg.savePath) form.append("savepath", cfg.savePath); const resp = await fetch(base + "/api/v2/torrents/add", { method: "POST", body: form, credentials: "include" }); const text = await resp.text(); notify(text.includes("Ok") ? "种子已发送 ✓" : "添加失败: " + text); } } catch (e) { notify("错误: " + e.message); } } function notify(msg) { chrome.notifications.create({ type: "basic", iconUrl: "icon.png", title: "Send to qBittorrent", message: msg }); }