- Persist captured magnet links in extension local storage - Update browser action badge indicator upon capturing links - Manage opening the pairing app tab with URI parameters - Provide fallback fetch proxy for dispatching downloads to FastAPI
72 lines
2.3 KiB
JavaScript
72 lines
2.3 KiB
JavaScript
// Background script for Magnetflix extension
|
|
const browserAPI = window.browser || window.chrome;
|
|
|
|
// Listen for messages from content scripts and popups
|
|
browserAPI.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
if (request.action === "magnet_captured") {
|
|
// Store latest captured magnet link
|
|
browserAPI.storage.local.set(
|
|
{
|
|
lastMagnet: request.magnet,
|
|
lastCapturedAt: Date.now()
|
|
},
|
|
() => {
|
|
if (browserAPI.browserAction && browserAPI.browserAction.setBadgeText) {
|
|
browserAPI.browserAction.setBadgeText({ text: "🧲" });
|
|
browserAPI.browserAction.setBadgeBackgroundColor({ color: "#e50914" });
|
|
}
|
|
}
|
|
);
|
|
sendResponse({ status: "stored" });
|
|
return true;
|
|
}
|
|
|
|
if (request.action === "open_app") {
|
|
const magnetParam = request.magnet ? encodeURIComponent(request.magnet) : "";
|
|
const targetUrl = browserAPI.runtime.getURL(`app.html${magnetParam ? `?magnet=${magnetParam}` : ""}`);
|
|
|
|
// Clear badge when opening app
|
|
if (browserAPI.browserAction && browserAPI.browserAction.setBadgeText) {
|
|
browserAPI.browserAction.setBadgeText({ text: "" });
|
|
}
|
|
|
|
browserAPI.tabs.create({ url: targetUrl });
|
|
sendResponse({ status: "opened" });
|
|
return true;
|
|
}
|
|
|
|
if (request.action === "send_download") {
|
|
// Background fetch in case of origin/CORS or persistent background tasks
|
|
fetch("http://localhost:8000/download", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json"
|
|
},
|
|
body: JSON.stringify({
|
|
magnet: request.magnet,
|
|
imdbid: request.imdbid
|
|
})
|
|
})
|
|
.then(async (response) => {
|
|
const data = await response.json().catch(() => ({}));
|
|
if (!response.ok) {
|
|
sendResponse({
|
|
success: false,
|
|
status: response.status,
|
|
error: data.detail || response.statusText || "Server error"
|
|
});
|
|
} else {
|
|
sendResponse({ success: true, data });
|
|
}
|
|
})
|
|
.catch((error) => {
|
|
sendResponse({
|
|
success: false,
|
|
error: error.message || "Failed to connect to FastAPI at http://localhost:8000"
|
|
});
|
|
});
|
|
|
|
return true; // Keep message channel open for async response
|
|
}
|
|
});
|