- In Firefox WebExtension content scripts, window is the webpage DOM window and does not expose extension APIs for security - Access global browser/chrome identifiers directly via typeof checks - Wrap background message dispatch in try-catch to prevent uncaught exceptions from blocking in-page modal display
439 lines
14 KiB
JavaScript
439 lines
14 KiB
JavaScript
// app.js - Logic for Magnetflix Page
|
|
const browserAPI = typeof browser !== "undefined" ? browser : (typeof chrome !== "undefined" ? chrome : null);
|
|
|
|
// State
|
|
let selectedMovie = null;
|
|
let searchDebounceTimer = null;
|
|
let currentSearchAbortController = null;
|
|
|
|
// DOM Elements
|
|
const magnetInput = document.getElementById("magnet-input");
|
|
const btnClearMagnet = document.getElementById("btn-clear-magnet");
|
|
const magnetLockBadge = document.getElementById("magnet-lock-badge");
|
|
const sectionMagnet = document.getElementById("section-magnet");
|
|
|
|
const movieInput = document.getElementById("movie-input");
|
|
const searchSpinner = document.getElementById("search-spinner");
|
|
const movieLockBadge = document.getElementById("movie-lock-badge");
|
|
const sectionMovie = document.getElementById("section-movie");
|
|
const movieSearchContainer = document.getElementById("movie-search-container");
|
|
const resultsContainer = document.getElementById("results-container");
|
|
const resultsList = document.getElementById("results-list");
|
|
const noResults = document.getElementById("no-results");
|
|
|
|
const selectedMovieContainer = document.getElementById("selected-movie-container");
|
|
const selectedPoster = document.getElementById("selected-poster");
|
|
const selectedTitle = document.getElementById("selected-title");
|
|
const selectedYear = document.getElementById("selected-year");
|
|
const selectedImdbId = document.getElementById("selected-imdbid");
|
|
const selectedType = document.getElementById("selected-type");
|
|
const selectedStars = document.getElementById("selected-stars");
|
|
const btnChangeMovie = document.getElementById("btn-change-movie");
|
|
|
|
const sectionAction = document.getElementById("section-action");
|
|
const btnSend = document.getElementById("btn-send");
|
|
const responseBox = document.getElementById("response-box");
|
|
const responseIcon = document.getElementById("response-icon");
|
|
const responseTitle = document.getElementById("response-title");
|
|
const responseBody = document.getElementById("response-body");
|
|
|
|
// Initialize on page load
|
|
document.addEventListener("DOMContentLoaded", () => {
|
|
initMagnetField();
|
|
initMovieSearch();
|
|
initActions();
|
|
});
|
|
|
|
// 1. Magnet Link Initialization
|
|
function initMagnetField() {
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
const magnetParam = urlParams.get("magnet");
|
|
|
|
if (magnetParam) {
|
|
magnetInput.value = magnetParam;
|
|
} else if (browserAPI && browserAPI.storage && browserAPI.storage.local) {
|
|
browserAPI.storage.local.get(["lastMagnet"], (res) => {
|
|
if (res && res.lastMagnet) {
|
|
magnetInput.value = res.lastMagnet;
|
|
}
|
|
});
|
|
}
|
|
|
|
btnClearMagnet.addEventListener("click", () => {
|
|
if (!magnetInput.readOnly) {
|
|
magnetInput.value = "";
|
|
magnetInput.focus();
|
|
}
|
|
});
|
|
}
|
|
|
|
// 2. Dynamic Movie Search
|
|
function initMovieSearch() {
|
|
movieInput.addEventListener("input", (e) => {
|
|
const query = e.target.value.trim();
|
|
|
|
if (searchDebounceTimer) {
|
|
clearTimeout(searchDebounceTimer);
|
|
}
|
|
|
|
if (!query) {
|
|
resultsContainer.classList.add("hidden");
|
|
noResults.classList.add("hidden");
|
|
searchSpinner.classList.add("hidden");
|
|
return;
|
|
}
|
|
|
|
// Debounce search by 250ms for responsive typing
|
|
searchSpinner.classList.remove("hidden");
|
|
searchDebounceTimer = setTimeout(async () => {
|
|
await performMovieSearch(query);
|
|
}, 250);
|
|
});
|
|
|
|
btnChangeMovie.addEventListener("click", () => {
|
|
unlockSections();
|
|
});
|
|
}
|
|
|
|
// Search IMDb suggestion API
|
|
async function performMovieSearch(query) {
|
|
if (currentSearchAbortController) {
|
|
currentSearchAbortController.abort();
|
|
}
|
|
currentSearchAbortController = new AbortController();
|
|
const { signal } = currentSearchAbortController;
|
|
|
|
try {
|
|
const results = await searchIMDb(query, signal);
|
|
searchSpinner.classList.add("hidden");
|
|
|
|
if (results.length === 0) {
|
|
resultsList.innerHTML = "";
|
|
resultsContainer.classList.add("hidden");
|
|
noResults.classList.remove("hidden");
|
|
} else {
|
|
noResults.classList.add("hidden");
|
|
renderSearchResults(results);
|
|
}
|
|
} catch (err) {
|
|
if (err.name !== "AbortError") {
|
|
console.error("IMDb Search Error:", err);
|
|
searchSpinner.classList.add("hidden");
|
|
}
|
|
}
|
|
}
|
|
|
|
// Query IMDb Suggestion APIs with multi-strategy fallback
|
|
async function searchIMDb(query, signal) {
|
|
const cleanQ = query.trim();
|
|
if (!cleanQ) return [];
|
|
|
|
const isTtId = /^tt\d+$/i.test(cleanQ);
|
|
const endpoints = [];
|
|
|
|
const firstChar = cleanQ.charAt(0).toLowerCase();
|
|
endpoints.push(`https://v3.sg.media-imdb.com/suggestion/x/${encodeURIComponent(cleanQ.toLowerCase())}.json`);
|
|
endpoints.push(`https://v3.sg.media-imdb.com/suggestion/${firstChar}/${encodeURIComponent(cleanQ.toLowerCase().replace(/\s+/g, "_"))}.json`);
|
|
|
|
if (isTtId) {
|
|
const digits = cleanQ.slice(2);
|
|
// Standard IMDb 7-digit zero-padding
|
|
if (digits.length < 7) {
|
|
const paddedId = "tt" + digits.padStart(7, "0");
|
|
endpoints.push(`https://v3.sg.media-imdb.com/suggestion/t/${encodeURIComponent(paddedId)}.json`);
|
|
endpoints.push(`https://v3.sg.media-imdb.com/suggestion/x/${encodeURIComponent(paddedId)}.json`);
|
|
} else {
|
|
endpoints.push(`https://v3.sg.media-imdb.com/suggestion/t/${encodeURIComponent(cleanQ)}.json`);
|
|
}
|
|
}
|
|
|
|
const seen = new Set();
|
|
const results = [];
|
|
|
|
for (const url of endpoints) {
|
|
try {
|
|
const resp = await fetch(url, { signal, headers: { "Accept": "application/json" } });
|
|
if (!resp.ok) continue;
|
|
const data = await resp.json();
|
|
|
|
if (Array.isArray(data.d)) {
|
|
for (const item of data.d) {
|
|
// Accept feature films, movies, series, or video titles
|
|
if (item.id && !seen.has(item.id)) {
|
|
seen.add(item.id);
|
|
results.push({
|
|
id: item.id,
|
|
title: item.l || item.id,
|
|
year: item.y || item.tl || "N/A",
|
|
type: item.q || item.qid || "Movie",
|
|
stars: item.s || "",
|
|
imageUrl: item.i ? item.i.imageUrl : null
|
|
});
|
|
if (results.length >= 5) break;
|
|
}
|
|
}
|
|
}
|
|
} catch (e) {
|
|
if (e.name === "AbortError") throw e;
|
|
}
|
|
if (results.length >= 5) break;
|
|
}
|
|
|
|
return results.slice(0, 5);
|
|
}
|
|
|
|
// Render the 5 matching results
|
|
function renderSearchResults(results) {
|
|
resultsList.innerHTML = "";
|
|
|
|
results.forEach((movie) => {
|
|
const li = document.createElement("li");
|
|
li.className = "result-item";
|
|
|
|
const posterWrap = document.createElement("div");
|
|
posterWrap.className = "result-poster-wrap";
|
|
|
|
if (movie.imageUrl) {
|
|
const img = document.createElement("img");
|
|
img.src = movie.imageUrl;
|
|
img.alt = movie.title;
|
|
img.className = "result-poster";
|
|
img.loading = "lazy";
|
|
img.onerror = () => {
|
|
posterWrap.innerHTML = '<span class="result-poster-fallback">🎬</span>';
|
|
};
|
|
posterWrap.appendChild(img);
|
|
} else {
|
|
posterWrap.innerHTML = '<span class="result-poster-fallback">🎬</span>';
|
|
}
|
|
|
|
const content = document.createElement("div");
|
|
content.className = "result-content";
|
|
|
|
const titleRow = document.createElement("div");
|
|
titleRow.className = "result-title-row";
|
|
const titleSpan = document.createElement("span");
|
|
titleSpan.className = "result-title";
|
|
titleSpan.textContent = movie.title;
|
|
titleRow.appendChild(titleSpan);
|
|
|
|
if (movie.year) {
|
|
const yearSpan = document.createElement("span");
|
|
yearSpan.className = "result-year";
|
|
yearSpan.textContent = `(${movie.year})`;
|
|
titleRow.appendChild(yearSpan);
|
|
}
|
|
|
|
const metaRow = document.createElement("div");
|
|
metaRow.className = "result-meta-row";
|
|
const imdbSpan = document.createElement("span");
|
|
imdbSpan.className = "meta-tag imdb-tag";
|
|
imdbSpan.textContent = movie.id;
|
|
|
|
const typeSpan = document.createElement("span");
|
|
typeSpan.className = "meta-tag type-tag";
|
|
typeSpan.textContent = movie.type;
|
|
|
|
metaRow.appendChild(imdbSpan);
|
|
metaRow.appendChild(typeSpan);
|
|
|
|
content.appendChild(titleRow);
|
|
content.appendChild(metaRow);
|
|
|
|
if (movie.stars) {
|
|
const stars = document.createElement("div");
|
|
stars.className = "result-stars";
|
|
stars.textContent = movie.stars;
|
|
content.appendChild(stars);
|
|
}
|
|
|
|
const selectAction = document.createElement("div");
|
|
selectAction.className = "result-select-action";
|
|
selectAction.innerHTML = "Select →";
|
|
|
|
li.appendChild(posterWrap);
|
|
li.appendChild(content);
|
|
li.appendChild(selectAction);
|
|
|
|
li.addEventListener("click", () => {
|
|
selectMovie(movie);
|
|
});
|
|
|
|
resultsList.appendChild(li);
|
|
});
|
|
|
|
resultsContainer.classList.remove("hidden");
|
|
}
|
|
|
|
// 3. Selection & Fixing State
|
|
function selectMovie(movie) {
|
|
selectedMovie = movie;
|
|
|
|
// Lock Section 1 (Magnet Link)
|
|
magnetInput.readOnly = true;
|
|
sectionMagnet.classList.add("is-fixed");
|
|
magnetLockBadge.classList.remove("hidden");
|
|
|
|
// Lock Section 2 (Movie)
|
|
sectionMovie.classList.add("is-fixed");
|
|
movieLockBadge.classList.remove("hidden");
|
|
movieSearchContainer.classList.add("hidden");
|
|
|
|
// Display selected movie details
|
|
selectedTitle.textContent = movie.title;
|
|
selectedYear.textContent = movie.year ? `Year: ${movie.year}` : "";
|
|
selectedImdbId.textContent = movie.id;
|
|
selectedType.textContent = movie.type || "Movie";
|
|
selectedStars.textContent = movie.stars ? `Cast: ${movie.stars}` : "";
|
|
|
|
if (movie.imageUrl) {
|
|
selectedPoster.src = movie.imageUrl;
|
|
selectedPoster.classList.remove("hidden");
|
|
} else {
|
|
selectedPoster.classList.add("hidden");
|
|
}
|
|
|
|
selectedMovieContainer.classList.remove("hidden");
|
|
|
|
// Show Section Action & SEND Button
|
|
sectionAction.classList.remove("hidden");
|
|
hideResponseBox();
|
|
}
|
|
|
|
// Unlock sections if user wants to change movie
|
|
function unlockSections() {
|
|
selectedMovie = null;
|
|
|
|
magnetInput.readOnly = false;
|
|
sectionMagnet.classList.remove("is-fixed");
|
|
magnetLockBadge.classList.add("hidden");
|
|
|
|
sectionMovie.classList.remove("is-fixed");
|
|
movieLockBadge.classList.add("hidden");
|
|
selectedMovieContainer.classList.add("hidden");
|
|
movieSearchContainer.classList.remove("hidden");
|
|
|
|
sectionAction.classList.add("hidden");
|
|
hideResponseBox();
|
|
|
|
movieInput.focus();
|
|
}
|
|
|
|
// 4. FastAPI SEND Action
|
|
function initActions() {
|
|
btnSend.addEventListener("click", async () => {
|
|
const magnetValue = magnetInput.value.trim();
|
|
|
|
if (!magnetValue) {
|
|
showResponse(false, "Missing Magnet Link", "Please provide a valid magnet link before sending.");
|
|
return;
|
|
}
|
|
|
|
if (!selectedMovie || !selectedMovie.id) {
|
|
showResponse(false, "No Movie Selected", "Please select a movie from the IMDb results.");
|
|
return;
|
|
}
|
|
|
|
// Prepare payload
|
|
const payload = {
|
|
magnet: magnetValue,
|
|
imdbid: selectedMovie.id
|
|
};
|
|
|
|
// Button loading state
|
|
btnSend.disabled = true;
|
|
btnSend.querySelector(".btn-send-text").textContent = "SENDING TO FASTAPI...";
|
|
|
|
try {
|
|
// Send directly to FastAPI endpoint
|
|
const response = await fetch("http://localhost:8000/download", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json"
|
|
},
|
|
body: JSON.stringify(payload)
|
|
});
|
|
|
|
const data = await response.json().catch(() => ({}));
|
|
|
|
if (response.ok) {
|
|
showResponse(
|
|
true,
|
|
"Download Triggered Successfully!",
|
|
JSON.stringify(data, null, 2)
|
|
);
|
|
} else {
|
|
const errorDetail = data.detail
|
|
? (typeof data.detail === "object" ? JSON.stringify(data.detail, null, 2) : data.detail)
|
|
: response.statusText;
|
|
showResponse(
|
|
false,
|
|
`FastAPI Returned Error ${response.status}`,
|
|
errorDetail || "Unknown error from server."
|
|
);
|
|
}
|
|
} catch (err) {
|
|
// If direct fetch fails (e.g. server down or CORS), try background script
|
|
if (browserAPI && browserAPI.runtime && browserAPI.runtime.sendMessage) {
|
|
browserAPI.runtime.sendMessage(
|
|
{
|
|
action: "send_download",
|
|
magnet: payload.magnet,
|
|
imdbid: payload.imdbid
|
|
},
|
|
(bgRes) => {
|
|
if (bgRes && bgRes.success) {
|
|
showResponse(
|
|
true,
|
|
"Download Triggered Successfully! (via Background)",
|
|
JSON.stringify(bgRes.data, null, 2)
|
|
);
|
|
} else {
|
|
const msg = bgRes ? bgRes.error : err.message;
|
|
showResponse(
|
|
false,
|
|
"Connection to FastAPI Failed",
|
|
`${msg}\n\nMake sure your FastAPI server is running on http://localhost:8000:\ncd dummy_api && uvicorn dummy_api.main:app --port 8000`
|
|
);
|
|
}
|
|
}
|
|
);
|
|
} else {
|
|
showResponse(
|
|
false,
|
|
"Connection to FastAPI Failed",
|
|
`${err.message}\n\nMake sure your FastAPI server is running on http://localhost:8000:\ncd dummy_api && uvicorn dummy_api.main:app --port 8000`
|
|
);
|
|
}
|
|
} finally {
|
|
btnSend.disabled = false;
|
|
btnSend.querySelector(".btn-send-text").textContent = "SEND";
|
|
}
|
|
});
|
|
}
|
|
|
|
function showResponse(isSuccess, title, body) {
|
|
responseBox.classList.remove("hidden", "success", "error");
|
|
responseBox.classList.add(isSuccess ? "success" : "error");
|
|
|
|
responseIcon.textContent = isSuccess ? "✅" : "⚠️";
|
|
responseTitle.textContent = title;
|
|
responseBody.textContent = body;
|
|
responseBox.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
|
}
|
|
|
|
function hideResponseBox() {
|
|
responseBox.classList.add("hidden");
|
|
responseBody.textContent = "";
|
|
}
|
|
|
|
function escapeHTML(str) {
|
|
if (!str) return "";
|
|
return String(str)
|
|
.replace(/&/g, "&")
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">")
|
|
.replace(/"/g, """)
|
|
.replace(/'/g, "'");
|
|
}
|