(function () { const initialDataElement = document.getElementById("initial-dashboard-data"); const initialData = initialDataElement ? JSON.parse(initialDataElement.textContent || "{}") : {}; const state = { torrents: Array.isArray(initialData.torrents) ? initialData.torrents : [], stats: initialData.stats || {}, events: Array.isArray(initialData.events) ? initialData.events : [], system: initialData.system || {}, activeFilter: "all", searchTerm: "", currentPage: 1, }; const TORRENTS_PER_PAGE = 5; const elements = { toastContainer: document.getElementById("toast-container"), eventList: document.getElementById("event-list"), torrentList: document.getElementById("torrent-list"), torrentListSection: document.getElementById("torrent-list-section"), torrentPagination: document.getElementById("torrent-pagination"), torrentCount: document.getElementById("torrent-count"), versionValue: document.getElementById("version-value"), connectionStatus: document.getElementById("connection-status"), savePath: document.getElementById("save-path"), searchInput: document.getElementById("search-input"), filterTabs: document.getElementById("filter-tabs"), summaryTotal: document.getElementById("summary-total"), summaryLeech: document.getElementById("summary-leech"), summarySeeding: document.getElementById("summary-seeding"), summaryPaused: document.getElementById("summary-paused"), summaryAllTimeDownload: document.getElementById("summary-all-time-download"), summaryAllTimeUpload: document.getElementById("summary-all-time-upload"), openAddModal: document.getElementById("open-add-modal"), addModal: document.getElementById("add-modal"), addModalClose: document.getElementById("add-modal-close"), addTabMagnet: document.getElementById("add-tab-magnet"), addTabFile: document.getElementById("add-tab-file"), addTabAria2: document.getElementById("add-tab-aria2"), addPanelMagnet: document.getElementById("add-panel-magnet"), addPanelFile: document.getElementById("add-panel-file"), addPanelAria2: document.getElementById("add-panel-aria2"), magnetForm: document.getElementById("magnet-form"), torrentUploadForm: document.getElementById("torrent-upload-form"), aria2Form: document.getElementById("aria2-form"), torrentFileInput: document.getElementById("torrent-file-input"), torrentFileName: document.getElementById("torrent-file-name"), deleteModal: document.getElementById("delete-modal"), deleteModalText: document.getElementById("delete-modal-text"), deleteWithFiles: document.getElementById("delete-with-files"), modalClose: document.getElementById("modal-close"), modalCancel: document.getElementById("modal-cancel"), modalConfirm: document.getElementById("modal-confirm"), torrentFileSelectionModal: document.getElementById("torrent-file-selection-modal"), torrentFileSelectionClose: document.getElementById("torrent-file-selection-close"), torrentFileSelectionText: document.getElementById("torrent-file-selection-text"), torrentFileSelectionLoading: document.getElementById("torrent-file-selection-loading"), torrentFileSelectionStorageWarning: document.getElementById("torrent-file-selection-storage-warning"), torrentFileSelectionActions: document.getElementById("torrent-file-selection-actions"), torrentFileSelectionCount: document.getElementById("torrent-file-selection-count"), torrentFileSelectionAll: document.getElementById("torrent-file-selection-all"), torrentFileSelectionNone: document.getElementById("torrent-file-selection-none"), torrentFileSelectionList: document.getElementById("torrent-file-selection-list"), torrentFileSelectionCancel: document.getElementById("torrent-file-selection-cancel"), torrentFileSelectionConfirm: document.getElementById("torrent-file-selection-confirm"), folderUploadModal: document.getElementById("folder-upload-modal"), folderUploadText: document.getElementById("folder-upload-text"), folderUploadClose: document.getElementById("folder-upload-close"), folderUploadCancel: document.getElementById("folder-upload-cancel"), folderUploadConfirm: document.getElementById("folder-upload-confirm"), rawUploadDescription: document.getElementById("raw-upload-description"), rcloneConfigModal: document.getElementById("rclone-config-modal"), rcloneConfigTitle: document.getElementById("rclone-config-title"), rcloneConfigText: document.getElementById("rclone-config-text"), rcloneConfigUrlSection: document.getElementById("rclone-config-url-section"), rcloneConfigUrl: document.getElementById("rclone-config-url"), rcloneConfigHelp: document.getElementById("rclone-config-help"), rcloneConfigRefresh: document.getElementById("rclone-config-refresh"), rcloneRemoteSection: document.getElementById("rclone-remote-section"), rcloneRemoteLoading: document.getElementById("rclone-remote-loading"), rcloneRemoteList: document.getElementById("rclone-remote-list"), rcloneRemoteEmpty: document.getElementById("rclone-remote-empty"), rcloneConfigClose: document.getElementById("rclone-config-close"), rcloneConfigCancel: document.getElementById("rclone-config-cancel"), rcloneConfigSave: document.getElementById("rclone-config-save"), speedtestButton: document.getElementById("speedtest-button"), }; let pendingDelete = null; let pendingFolderUpload = null; let pendingRcloneUpload = null; let rcloneModalMode = "config"; let selectedRcloneRemote = ""; let pendingTorrentFileSelection = null; let torrentFileSelectionPollTimer = null; let selectedFolderUploadMode = "zip"; const dismissedStatusMessages = new Set(); const seenEventKeys = new Set((state.events || []).map(eventKey)); const inFlightTorrentActions = new Map(); const optimisticTorrentStates = new Map(); function escapeHtml(value) { return String(value ?? "").replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'", }[char])); } function formatBytes(value) { let size = Math.max(0, Number(value || 0)); const units = ["B", "KB", "MB", "GB", "TB"]; for (const unit of units) { if (size < 1024 || unit === units[units.length - 1]) { return `${size.toFixed(1)} ${unit}`; } size /= 1024; } return `${size.toFixed(1)} TB`; } function normalizeStateLabel(label) { return String(label || "").trim().toLowerCase(); } function statusMessageKey(torrent) { return `${torrent.hash || ""}::${torrent.status_message || ""}`; } function isStatusMessageDismissed(torrent) { if (!torrent.status_message) { return false; } return dismissedStatusMessages.has(statusMessageKey(torrent)); } function dismissStatusMessage(torrentHash, message) { dismissedStatusMessages.add(`${torrentHash || ""}::${message || ""}`); } function statusTone(torrent) { if (torrent.gofile_uploading) { return { dotClass: "bg-violet", dotStyle: "background-color: #9b8cff;", text: "text-violet", pillClass: "text-violet", pillStyle: "background-color: rgba(155, 140, 255, 0.18); box-shadow: inset 0 0 0 1px rgba(155, 140, 255, 0.22);", label: torrent.upload_provider || torrent.state_label || "Uploading", }; } if (torrent.task_kind === "aria2") { const aria2Label = normalizeStateLabel(torrent.state_label); if (aria2Label.includes("complete")) { return { dotClass: "bg-emerald-300", dotStyle: "background-color: #6ee7b7;", text: "text-emerald-300", pillClass: "text-emerald-200", pillStyle: "background-color: rgba(110, 231, 183, 0.18); box-shadow: inset 0 0 0 1px rgba(110, 231, 183, 0.22);", label: torrent.state_label || "Completed", }; } if (aria2Label.includes("fail") || aria2Label.includes("cancel")) { return { dotClass: "bg-rose", dotStyle: "background-color: #ff6b9d;", text: "text-rose", pillClass: "text-rose-200", pillStyle: "background-color: rgba(255, 107, 157, 0.18); box-shadow: inset 0 0 0 1px rgba(255, 107, 157, 0.22);", label: torrent.state_label || "Aria2", }; } return { dotClass: "bg-sky-300", dotStyle: "background-color: #7dd3fc;", text: "text-sky-200", pillClass: "text-sky-100", pillStyle: "background-color: rgba(125, 211, 252, 0.16); box-shadow: inset 0 0 0 1px rgba(125, 211, 252, 0.22);", label: torrent.state_label || "Aria2 Download", }; } const label = normalizeStateLabel(torrent.state_label); if (label.includes("download")) { return { dotClass: "bg-neon", dotStyle: "background-color: #20e6c0;", text: "text-neon", pillClass: "text-neon", pillStyle: "background-color: rgba(32, 230, 192, 0.18); box-shadow: inset 0 0 0 1px rgba(32, 230, 192, 0.22);", label: torrent.state_label || "Downloading", }; } if (label.includes("seed") || label.includes("upload")) { return { dotClass: "bg-lime", dotStyle: "background-color: #9cf7a6;", text: "text-lime", pillClass: "text-lime", pillStyle: "background-color: rgba(156, 247, 166, 0.2); box-shadow: inset 0 0 0 1px rgba(156, 247, 166, 0.26);", label: torrent.state_label || "Seeding", }; } if (label.includes("pause")) { return { dotClass: "bg-stone-400", dotStyle: "background-color: #a8a29e;", text: "text-stone-300", pillClass: "text-stone-300", pillStyle: "background-color: rgba(255, 255, 255, 0.06); box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08);", label: torrent.state_label || "Paused", }; } if (label.includes("complete")) { return { dotClass: "bg-emerald-300", dotStyle: "background-color: #6ee7b7;", text: "text-emerald-300", pillClass: "text-emerald-200", pillStyle: "background-color: rgba(110, 231, 183, 0.18); box-shadow: inset 0 0 0 1px rgba(110, 231, 183, 0.22);", label: torrent.state_label || "Complete", }; } if (label.includes("error") || label.includes("stalled") || label.includes("missing")) { return { dotClass: "bg-rose", dotStyle: "background-color: #ff6b9d;", text: "text-rose", pillClass: "text-rose-200", pillStyle: "background-color: rgba(255, 107, 157, 0.18); box-shadow: inset 0 0 0 1px rgba(255, 107, 157, 0.22);", label: torrent.state_label || "Attention", }; } return { dotClass: "bg-amber", dotStyle: "background-color: #f7c84b;", text: "text-amber", pillClass: "text-amber-100", pillStyle: "background-color: rgba(247, 200, 75, 0.18); box-shadow: inset 0 0 0 1px rgba(247, 200, 75, 0.22);", label: torrent.state_label || "Idle", }; } function formatMetricValue(value) { return escapeHtml(value || "-"); } function metricBadge({ icon, label, value, tone = "default", span = "normal", accentClass = "" }) { const toneConfig = { default: { className: "text-stone-200", labelClassName: "text-stone-400", style: "background-color: rgba(255, 255, 255, 0.04); box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.06);", }, muted: { className: "text-stone-300", labelClassName: "text-stone-400", style: "background-color: rgba(10, 14, 22, 0.62); box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04);", }, }; const config = toneConfig[tone] || toneConfig.default; const spanClass = span === "full" ? "col-span-2" : ""; return `
${escapeHtml(label)} ${escapeHtml(value)}
`; } function getInFlightTorrentAction(hash) { return inFlightTorrentActions.get(hash) || null; } function setInFlightTorrentAction(hash, action) { inFlightTorrentActions.set(hash, action); } function clearInFlightTorrentAction(hash) { inFlightTorrentActions.delete(hash); } function setOptimisticTorrentState(hash, action) { optimisticTorrentStates.set(hash, action); } function clearOptimisticTorrentState(hash) { optimisticTorrentStates.delete(hash); } function getOptimisticTorrentState(hash) { return optimisticTorrentStates.get(hash) || null; } function applyOptimisticTorrentAction(action, hash) { const torrent = (state.torrents || []).find((item) => item.hash === hash); if (!torrent) { return; } if (torrent.task_kind === "aria2") { if (action === "pause") { torrent.state = "paused"; torrent.state_label = "Paused"; torrent.can_pause = false; torrent.can_resume = true; torrent.dlspeed = "0 B/s"; torrent.status_message = ""; } if (action === "resume") { torrent.state = "downloading"; torrent.state_label = "Aria2 Download"; torrent.can_pause = !torrent.gofile_uploading; torrent.can_resume = false; torrent.status_message = ""; } updateSummary(state.stats, state.torrents); renderTorrents(); return; } const progress = Number(torrent.progress || 0); const isComplete = progress >= 100; if (action === "pause") { torrent.state = isComplete ? "pausedUP" : "pausedDL"; torrent.state_label = "Paused"; torrent.can_pause = false; torrent.can_resume = true; torrent.dlspeed = "0 B/s"; torrent.upspeed = "0 B/s"; torrent.status_message = ""; if (torrent.display_speed_label === "Up") { torrent.display_speed = "0 B/s"; } } if (action === "resume") { torrent.state = isComplete ? "uploading" : "downloading"; torrent.state_label = isComplete ? "Checking" : "Downloading"; torrent.can_pause = !torrent.gofile_uploading; torrent.can_resume = false; torrent.status_message = ""; torrent.display_speed_label = isComplete ? "Up" : "Down"; if (isComplete) { torrent.display_speed = "0 B/s"; } } updateSummary(state.stats, state.torrents); renderTorrents(); } function reconcileOptimisticTorrentState(nextTorrents) { nextTorrents.forEach((torrent) => { const optimisticAction = getOptimisticTorrentState(torrent.hash); if (!optimisticAction) { return; } if (torrent.task_kind === "aria2") { const rawState = String(torrent.state || ""); if (optimisticAction === "pause") { if (rawState === "paused") { clearOptimisticTorrentState(torrent.hash); return; } torrent.state = "paused"; torrent.state_label = "Paused"; torrent.can_pause = false; torrent.can_resume = true; torrent.dlspeed = "0 B/s"; torrent.status_message = ""; } if (optimisticAction === "resume") { if (rawState !== "paused") { clearOptimisticTorrentState(torrent.hash); return; } torrent.state = "downloading"; torrent.state_label = "Aria2 Download"; torrent.can_pause = !torrent.gofile_uploading; torrent.can_resume = false; torrent.status_message = ""; } return; } const rawState = String(torrent.state || ""); if (optimisticAction === "pause") { const serverPaused = ["pausedDL", "pausedUP"].includes(rawState); if (serverPaused) { clearOptimisticTorrentState(torrent.hash); return; } torrent.state = Number(torrent.progress || 0) >= 100 ? "pausedUP" : "pausedDL"; torrent.state_label = "Paused"; torrent.can_pause = false; torrent.can_resume = true; torrent.dlspeed = "0 B/s"; torrent.upspeed = "0 B/s"; torrent.status_message = ""; torrent.display_speed = "0 B/s"; torrent.display_speed_label = Number(torrent.progress || 0) >= 100 ? "Up" : "Down"; if (torrent.display_speed_label === "Up") { torrent.display_speed = "0 B/s"; } } if (optimisticAction === "resume") { const serverResumed = !["pausedDL", "pausedUP"].includes(rawState); if (serverResumed) { clearOptimisticTorrentState(torrent.hash); return; } const isComplete = Number(torrent.progress || 0) >= 100; torrent.state = isComplete ? "uploading" : "downloading"; torrent.state_label = isComplete ? "Checking" : "Downloading"; torrent.can_pause = !torrent.gofile_uploading; torrent.can_resume = false; torrent.status_message = ""; torrent.display_speed_label = isComplete ? "Up" : "Down"; if (isComplete) { torrent.display_speed = "0 B/s"; } } }); } function getTorrentCounts(torrents) { const counts = { total: torrents.length, leech: 0, seeding: 0, paused: 0, completed: 0, }; torrents.forEach((torrent) => { const label = normalizeStateLabel(torrent.state_label); const rawState = String(torrent.state || "").trim(); const isDownloadingState = ["downloading", "metaDL", "stalledDL", "forcedMetaDL", "forcedDL"].includes(rawState); const isSeedingState = ["uploading", "stalledUP", "forcedUP", "pausedUP", "queuedUP", "checkingUP"].includes(rawState); if (isDownloadingState) { counts.leech += 1; } if (isSeedingState) { counts.seeding += 1; } if (label.includes("pause")) { counts.paused += 1; } if ((Number(torrent.progress) || 0) >= 100 || label.includes("complete")) { counts.completed += 1; } }); return counts; } function matchesFilter(torrent) { const label = normalizeStateLabel(torrent.state_label); const progress = Number(torrent.progress || 0); const rawState = String(torrent.state || "").trim(); const isSeedingState = ["uploading", "stalledUP", "forcedUP", "pausedUP", "queuedUP", "checkingUP"].includes(rawState); if (state.activeFilter === "all") { return true; } if (state.activeFilter === "downloading") { return label.includes("download"); } if (state.activeFilter === "seeding") { return label.includes("seed") || isSeedingState || torrent.display_speed_label === "Seed Upload"; } if (state.activeFilter === "paused") { return label.includes("pause"); } if (state.activeFilter === "completed") { return progress >= 100 || label.includes("complete"); } if (state.activeFilter === "uploading") { return !!torrent.gofile_uploading; } if (state.activeFilter === "aria2") { return torrent.task_kind === "aria2"; } return true; } function matchesSearch(torrent) { if (!state.searchTerm) { return true; } const haystack = [ torrent.name, torrent.state_label, torrent.gofile_status, torrent.gofile_link, ].join(" ").toLowerCase(); return haystack.includes(state.searchTerm); } function filteredTorrents() { return state.torrents.filter((torrent) => matchesFilter(torrent) && matchesSearch(torrent)); } function getTotalPages(totalItems) { return Math.max(1, Math.ceil(totalItems / TORRENTS_PER_PAGE)); } function clampCurrentPage(totalItems) { const totalPages = getTotalPages(totalItems); state.currentPage = Math.min(Math.max(state.currentPage, 1), totalPages); return totalPages; } function getVisiblePageNumbers(totalPages) { if (totalPages <= 5) { return Array.from({ length: totalPages }, (_, index) => index + 1); } if (state.currentPage <= 3) { return [1, 2, 3, 4, totalPages]; } if (state.currentPage >= totalPages - 2) { return [1, totalPages - 3, totalPages - 2, totalPages - 1, totalPages]; } return [1, state.currentPage - 1, state.currentPage, state.currentPage + 1, totalPages]; } function renderPagination(totalItems) { if (!elements.torrentPagination) { return; } const totalPages = clampCurrentPage(totalItems); if (totalItems <= TORRENTS_PER_PAGE) { elements.torrentPagination.innerHTML = ""; return; } const visiblePages = getVisiblePageNumbers(totalPages); const seen = new Set(); const pageButtons = visiblePages.filter((page) => { if (seen.has(page)) { return false; } seen.add(page); return true; }).map((page) => { const active = page === state.currentPage; const className = active ? "border-neon/30 bg-neon/12 text-neon" : "border-white/10 bg-white/[0.03] text-stone-300 hover:border-white/20 hover:text-white"; return ` `; }).join(""); const firstDisabledClass = state.currentPage === 1 ? "opacity-40 cursor-not-allowed" : ""; const lastDisabledClass = state.currentPage === totalPages ? "opacity-40 cursor-not-allowed" : ""; const firstDisabledAttr = state.currentPage === 1 ? "disabled" : ""; const lastDisabledAttr = state.currentPage === totalPages ? "disabled" : ""; elements.torrentPagination.innerHTML = `
${pageButtons}
`; } function scrollToTorrentListTop() { const target = elements.torrentListSection || elements.torrentList; if (!target) { return; } target.scrollIntoView({ behavior: "smooth", block: "start", }); } function eventKey(event) { return `${event.created_at || ""}:${event.level || ""}:${event.message || ""}`; } function toastVariantForEvent(event) { if (event.level === "error") { return "error"; } if (event.level === "warning") { return "warning"; } return "success"; } function renderEvents(events, options = {}) { const nextEvents = Array.isArray(events) ? events : []; if (options.toastNew) { nextEvents.slice().reverse().forEach((event) => { const key = eventKey(event); if (seenEventKeys.has(key)) { return; } seenEventKeys.add(key); if (event.message) { showToast(event.message, toastVariantForEvent(event)); } }); } else { nextEvents.forEach((event) => seenEventKeys.add(eventKey(event))); } if (!elements.eventList) { return; } elements.eventList.innerHTML = ""; } function showToast(message, variant = "success") { if (!elements.toastContainer) { return; } const styles = variant === "error" ? "border-rose-500/30 bg-rose-500/15 text-rose-50" : variant === "warning" ? "border-amber-500/30 bg-amber-500/15 text-amber-50" : "border-emerald-500/30 bg-emerald-500/15 text-emerald-50"; const icon = variant === "error" ? "fa-circle-xmark" : variant === "warning" ? "fa-triangle-exclamation" : "fa-circle-check"; const toast = document.createElement("div"); toast.className = `pointer-events-auto rounded-2xl border px-4 py-3 text-sm shadow-2xl shadow-black/30 backdrop-blur transition duration-300 ${styles}`; toast.innerHTML = `
${escapeHtml(message)}
`; elements.toastContainer.appendChild(toast); const closeToast = () => { toast.classList.add("translate-x-4", "opacity-0"); setTimeout(() => toast.remove(), 220); }; toast.querySelector("[data-toast-close]")?.addEventListener("click", closeToast); setTimeout(closeToast, 3200); } function actionButtons(torrent) { const buttons = []; const inFlightAction = getInFlightTorrentAction(torrent.hash); if (inFlightAction && (inFlightAction === "pause" || inFlightAction === "resume")) { const isPause = inFlightAction === "pause"; buttons.push(` `); } else if (torrent.can_pause) { buttons.push(` `); } else if (torrent.can_resume) { buttons.push(` `); } buttons.push(` `); if (torrent.can_cancel_gofile_upload) { buttons.push(` `); } if (torrent.can_gofile_upload) { buttons.push(` `); } if (torrent.can_pixeldrain_upload) { buttons.push(` `); } if (torrent.can_rclone_upload) { const rcloneReady = torrent.rclone_config_ready ? "true" : "false"; const rcloneTone = torrent.rclone_config_ready ? "border-lime/20 bg-lime/10 text-lime hover:bg-lime/15" : "border-amber/20 bg-amber/10 text-amber-100 hover:bg-amber/15"; buttons.push(` `); } return buttons.join(""); } function renderUploadBlock(torrent) { if (!torrent.gofile_link) { return ""; } return `

Remote upload complete

${escapeHtml(torrent.upload_provider || "Remote Upload")} link siap dipakai.

Open link
${escapeHtml(torrent.gofile_link)}
`; } function renderTorrent(torrent) { const tone = statusTone(torrent); const progress = Math.max(0, Math.min(Number(torrent.progress || 0), 100)); const stateLabel = normalizeStateLabel(torrent.state_label); const isAria2 = torrent.task_kind === "aria2"; const isComplete = progress >= 100 || stateLabel.includes("complete"); const isDownloading = stateLabel.includes("download"); const isSeeding = stateLabel.includes("seed"); const progressClass = torrent.gofile_uploading ? "h-2 rounded-full bg-[linear-gradient(90deg,rgba(155,140,255,0.95),rgba(32,230,192,0.92))] shadow-[0_0_18px_rgba(155,140,255,0.16)] transition-all duration-700" : "h-2 rounded-full bg-[linear-gradient(90deg,rgba(32,230,192,0.95),rgba(156,247,166,0.95))] shadow-[0_0_18px_rgba(32,230,192,0.18)] transition-all duration-700"; const shouldShowStatusMessage = torrent.status_message && !isStatusMessageDismissed(torrent); const statusMessage = shouldShowStatusMessage ? `
${escapeHtml(torrent.status_message)}
` : ""; const endpointMeta = isAria2 ? `ARIA2` : torrent.gofile_endpoint ? `${escapeHtml(torrent.gofile_endpoint)}` : ""; const statusIconName = torrent.gofile_uploading ? "fa-cloud-arrow-up" : isAria2 ? "fa-link" : isSeeding ? "fa-arrow-up" : isDownloading ? "fa-arrow-down" : "fa-circle"; const statusIconTone = torrent.gofile_uploading ? "bg-violet/10 text-violet" : isAria2 ? "bg-sky-400/10 text-sky-200" : isSeeding ? "bg-lime/10 text-lime" : isDownloading ? "bg-neon/10 text-neon" : "bg-white/[0.04] text-stone-300"; const sizeLabel = torrent.has_file_selection ? "Selected" : "Size"; const primaryBadges = isAria2 ? [ metricBadge({ icon: "fa-box-archive", label: "Size", value: torrent.total_size || "-", tone: "muted" }), metricBadge({ icon: "fa-download", label: "Downloaded", value: torrent.downloaded || "-", tone: "muted" }), metricBadge({ icon: "fa-arrow-down", label: "Down", value: torrent.dlspeed || "-", tone: "muted", accentClass: "text-neon" }), ].join("") : [ metricBadge({ icon: "fa-box-archive", label: sizeLabel, value: torrent.total_size || "-", tone: "muted" }), metricBadge({ icon: "fa-download", label: "Downloaded", value: torrent.downloaded || "-", tone: "muted" }), metricBadge({ icon: "fa-upload", label: "Uploaded", value: torrent.uploaded || "-", tone: "muted" }), metricBadge({ icon: "fa-arrow-down", label: "Down", value: torrent.dlspeed || "-", tone: "muted", accentClass: "text-neon" }), metricBadge({ icon: "fa-arrow-up", label: "Up", value: torrent.upspeed || "-", tone: "muted", accentClass: "text-lime" }), metricBadge({ icon: "fa-chart-simple", label: "Ratio", value: torrent.ratio || "-", tone: "muted" }), ].join(""); const peerBadges = isAria2 ? (!isComplete ? metricBadge({ icon: "fa-clock", label: "ETA", value: torrent.eta || "-", tone: "muted", span: "full" }) : "") : [ metricBadge({ icon: "fa-seedling", label: "Seed", value: torrent.num_seeds ?? 0, tone: "muted" }), metricBadge({ icon: "fa-users", label: "Peer", value: `${torrent.num_seeds ?? 0} / ${torrent.num_leechs ?? 0}`, tone: "muted" }), !isComplete ? metricBadge({ icon: "fa-clock", label: "ETA", value: torrent.eta || "-", tone: "muted", span: "full" }) : "", ].join(""); const peerMetrics = peerBadges ? `
${peerBadges}
` : ""; return `

${escapeHtml(torrent.name)}

${escapeHtml(tone.label)} ${endpointMeta}
${escapeHtml(torrent.progress_label || "Progress")} ${progress}%
${statusMessage}
${primaryBadges}
${peerMetrics}
${actionButtons(torrent)}
${renderUploadBlock(torrent)}
`; } function renderEmptyState() { const hasSearch = !!state.searchTerm || state.activeFilter !== "all"; const title = hasSearch ? "Tidak ada hasil yang cocok" : "Belum ada torrent aktif"; const subtitle = hasSearch ? "Coba ubah keyword pencarian atau filter status yang sedang aktif." : "Gunakan tombol Add untuk menambahkan magnet link atau file torrent, lalu queue akan muncul di sini."; elements.torrentList.innerHTML = `

${title}

${subtitle}

`; if (elements.torrentPagination) { elements.torrentPagination.innerHTML = ""; } } function updateSummary(stats, torrents) { const counts = getTorrentCounts(torrents); elements.summaryTotal.textContent = String(stats.torrent_count ?? counts.total); elements.summaryLeech.textContent = String(stats.total_leechs ?? counts.leech); elements.summarySeeding.textContent = String(stats.total_seeds ?? counts.seeding); elements.summaryPaused.textContent = String(counts.paused); elements.summaryAllTimeDownload.textContent = String(stats.all_time_download ?? "0 B"); elements.summaryAllTimeUpload.textContent = String(stats.all_time_upload ?? "0 B"); if (elements.torrentCount) { elements.torrentCount.textContent = `${filteredTorrents().length} item`; } } function updateConnection(isConnected, versionText) { elements.connectionStatus.className = isConnected ? "inline-flex min-w-0 items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-medium text-emerald-300" : "inline-flex min-w-0 items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-medium text-rose-300"; elements.connectionStatus.innerHTML = isConnected ? 'Online' : 'Offline'; elements.versionValue.textContent = String(versionText || "-").replace(/^v/i, ""); } function updateSystemInfo(system) { state.system = system || {}; const location = system.location || {}; const speedtest = system.speedtest || {}; const result = speedtest.result || {}; document.getElementById("system-os").textContent = system.os || "-"; document.getElementById("system-cpu").textContent = system.cpu || "-"; document.getElementById("system-cpu-usage").textContent = `${system.cpu_usage || "-"} / ${system.cpu_cores || 0} core`; document.getElementById("system-ram").textContent = `${system.ram_used || "-"} / ${system.ram_total || "-"}`; document.getElementById("system-ram-percent").textContent = system.ram_percent || "-"; document.getElementById("system-storage").textContent = `${system.storage_used || "-"} / ${system.storage_total || "-"}`; document.getElementById("system-storage-percent").textContent = system.storage_percent || "-"; document.getElementById("system-location").textContent = `${location.city || "-"}, ${location.region || "-"}, ${location.country || "-"}`; document.getElementById("system-timezone").textContent = location.timezone || "-"; document.getElementById("system-org").textContent = location.org || "-"; document.getElementById("system-ip").textContent = location.ip || "-"; document.getElementById("speedtest-status").textContent = speedtest.status || "Belum dijalankan."; document.getElementById("speedtest-download").textContent = result.download || "-"; document.getElementById("speedtest-upload").textContent = result.upload || "-"; document.getElementById("speedtest-ping").textContent = result.ping || "-"; elements.speedtestButton.disabled = !!speedtest.running; elements.speedtestButton.classList.toggle("opacity-60", !!speedtest.running); } function renderFilterTabs() { elements.filterTabs.querySelectorAll("[data-filter]").forEach((button) => { const active = button.dataset.filter === state.activeFilter; button.dataset.active = active ? "true" : "false"; button.className = active ? "filter-chip font-display rounded-2xl border border-neon/30 bg-neon/12 px-4 py-2 text-sm font-semibold text-neon transition hover:bg-neon/20" : "filter-chip font-display rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-2 text-sm font-semibold text-stone-300 transition hover:border-white/20 hover:text-white"; }); } function renderTorrents() { const torrents = filteredTorrents(); if (!torrents.length) { renderEmptyState(); return; } const totalPages = clampCurrentPage(torrents.length); const startIndex = (state.currentPage - 1) * TORRENTS_PER_PAGE; const pageItems = torrents.slice(startIndex, startIndex + TORRENTS_PER_PAGE); elements.torrentList.innerHTML = pageItems.map(renderTorrent).join(""); renderPagination(torrents.length, totalPages); } function renderDashboard() { renderEvents(state.events); renderFilterTabs(); updateSummary(state.stats, state.torrents); updateSystemInfo(state.system); elements.savePath.textContent = state.stats.download_path || "-"; renderTorrents(); } function showModal(modal) { modal.classList.remove("hidden"); modal.classList.add("flex"); } function hideModal(modal) { modal.classList.add("hidden"); modal.classList.remove("flex"); } function openAddModal() { syncTorrentFileName(); showModal(elements.addModal); showAddTab("magnet"); } function closeAddModal() { hideModal(elements.addModal); } function showAddTab(tab) { const isMagnet = tab === "magnet"; const isFile = tab === "file"; const isAria2 = tab === "aria2"; elements.addTabMagnet.dataset.active = isMagnet ? "true" : "false"; elements.addTabFile.dataset.active = isFile ? "true" : "false"; elements.addTabAria2.dataset.active = isAria2 ? "true" : "false"; elements.addTabMagnet.className = isMagnet ? "add-tab font-display rounded-[14px] border border-white/10 bg-neon px-3 py-2 text-sm font-semibold text-ink transition" : "add-tab font-display rounded-[14px] border border-transparent bg-transparent px-3 py-2 text-sm font-semibold text-stone-400 transition hover:text-white"; elements.addTabFile.className = isFile ? "add-tab font-display rounded-[14px] border border-white/10 bg-neon px-3 py-2 text-sm font-semibold text-ink transition" : "add-tab font-display rounded-[14px] border border-transparent bg-transparent px-3 py-2 text-sm font-semibold text-stone-400 transition hover:text-white"; elements.addTabAria2.className = isAria2 ? "add-tab font-display rounded-[14px] border border-white/10 bg-neon px-3 py-2 text-sm font-semibold text-ink transition" : "add-tab font-display rounded-[14px] border border-transparent bg-transparent px-3 py-2 text-sm font-semibold text-stone-400 transition hover:text-white"; elements.addPanelMagnet.classList.toggle("hidden", !isMagnet); elements.addPanelFile.classList.toggle("hidden", !isFile); elements.addPanelAria2.classList.toggle("hidden", !isAria2); } function syncTorrentFileName() { if (!elements.torrentFileName) { return; } const selectedFile = elements.torrentFileInput?.files?.[0]; elements.torrentFileName.textContent = selectedFile ? selectedFile.name : "Belum ada file dipilih"; } function openDeleteModal(hash, name) { pendingDelete = { hash, name }; elements.deleteWithFiles.checked = false; elements.deleteModalText.textContent = `Hapus torrent "${name}" dari daftar?`; showModal(elements.deleteModal); } function closeDeleteModal() { pendingDelete = null; hideModal(elements.deleteModal); } function openFolderUploadModal(action, hash, provider, rawEnabled, remote = "") { pendingFolderUpload = { action, hash, provider, rawEnabled, remote }; selectedFolderUploadMode = "zip"; elements.folderUploadText.textContent = `Torrent ini berisi folder. Pilih cara upload ke ${provider}.`; elements.rawUploadDescription.textContent = rawEnabled ? "Upload file satu per satu tanpa zip." : "Mode raw tidak tersedia untuk pilihan ini."; document.querySelectorAll(".folder-upload-choice").forEach((button) => { const mode = button.dataset.uploadMode; const disabled = mode === "raw" && !rawEnabled; button.disabled = disabled; button.classList.toggle("opacity-40", disabled); button.classList.toggle("cursor-not-allowed", disabled); if (mode === "zip") { button.classList.add("border-neon/20", "bg-neon/10"); } else { button.classList.remove("border-neon/20", "bg-neon/10"); button.classList.add("border-white/10", "bg-white/[0.03]"); } }); showModal(elements.folderUploadModal); } function closeFolderUploadModal() { pendingFolderUpload = null; selectedFolderUploadMode = "zip"; hideModal(elements.folderUploadModal); } function setRcloneModalMode(mode) { rcloneModalMode = mode; const isRemoteMode = mode === "remote"; elements.rcloneConfigTitle.textContent = isRemoteMode ? "Pilih remote" : "Set raw URL"; elements.rcloneConfigUrlSection.classList.toggle("hidden", isRemoteMode); elements.rcloneConfigHelp.textContent = isRemoteMode ? "Remote diambil langsung dari rclone.conf yang aktif." : "URL akan divalidasi dengan `rclone listremotes` sebelum upload dimulai."; elements.rcloneRemoteSection.classList.toggle("hidden", !isRemoteMode); elements.rcloneConfigSave.textContent = isRemoteMode ? "Upload ke remote" : "Simpan & lanjutkan"; } function renderRcloneRemoteList(remotes, selectedRemote = "") { const remoteNames = Array.isArray(remotes) ? remotes.filter(Boolean) : []; selectedRcloneRemote = selectedRemote || remoteNames[0] || ""; elements.rcloneRemoteLoading.classList.add("hidden"); elements.rcloneRemoteList.classList.toggle("hidden", remoteNames.length === 0); elements.rcloneRemoteEmpty.classList.toggle("hidden", remoteNames.length > 0); if (!remoteNames.length) { elements.rcloneRemoteList.innerHTML = ""; elements.rcloneRemoteEmpty.textContent = "Tidak ada remote aktif di rclone.conf."; return; } elements.rcloneRemoteList.innerHTML = remoteNames.map((remote) => { const active = remote === selectedRcloneRemote; const tone = active ? "border-lime/30 bg-lime/10 text-lime" : "border-white/10 bg-white/[0.03] text-stone-200 hover:bg-white/[0.06]"; return ` `; }).join(""); } async function loadRcloneRemoteOptions(errorMessage = "") { setRcloneModalMode("remote"); selectedRcloneRemote = ""; elements.rcloneConfigText.textContent = "Memuat daftar remote dari rclone.conf..."; elements.rcloneRemoteLoading.classList.remove("hidden"); elements.rcloneRemoteList.classList.add("hidden"); elements.rcloneRemoteEmpty.classList.add("hidden"); try { const response = await fetch("/api/rclone/config", { method: "GET", headers: { Accept: "application/json" }, }); const payload = await response.json(); const summary = payload.rclone || {}; const remotes = Array.isArray(summary.remotes) ? summary.remotes : []; if (!response.ok || !payload.success || !summary.available || !remotes.length) { setRcloneModalMode("config"); elements.rcloneConfigText.textContent = errorMessage ? `rclone.conf belum siap: ${errorMessage}` : `rclone.conf belum siap: ${summary.error || payload.message || "remote tidak ditemukan."}`; return; } elements.rcloneConfigText.textContent = "Pilih remote tujuan upload dari rclone.conf."; renderRcloneRemoteList(remotes, summary.selected_remote || remotes[0]); } catch (error) { setRcloneModalMode("config"); elements.rcloneConfigText.textContent = errorMessage ? `rclone.conf belum siap: ${errorMessage}` : "Gagal membaca daftar remote rclone."; } } function openRcloneConfigModal(uploadRequest = null, errorMessage = "") { pendingRcloneUpload = uploadRequest; selectedRcloneRemote = ""; setRcloneModalMode("remote"); elements.rcloneConfigUrl.value = ""; showModal(elements.rcloneConfigModal); loadRcloneRemoteOptions(errorMessage); } function closeRcloneConfigModal() { pendingRcloneUpload = null; selectedRcloneRemote = ""; hideModal(elements.rcloneConfigModal); } async function confirmRcloneRemoteSelection() { const remote = String(selectedRcloneRemote || "").trim(); if (!remote) { showToast("Pilih remote rclone dulu.", "error"); return; } const uploadRequest = pendingRcloneUpload; closeRcloneConfigModal(); await refreshTorrents(); if (!uploadRequest) { return; } if (uploadRequest.isFolder) { openFolderUploadModal(uploadRequest.action, uploadRequest.hash, `rclone (${remote})`, uploadRequest.rawEnabled, remote); return; } await triggerTorrentAction(uploadRequest.action, uploadRequest.hash, null, remote); } async function saveRcloneConfigUrl() { if (rcloneModalMode === "remote") { elements.rcloneConfigSave.disabled = true; try { await confirmRcloneRemoteSelection(); } finally { elements.rcloneConfigSave.disabled = false; } return; } const configUrl = String(elements.rcloneConfigUrl.value || "").trim(); if (!configUrl) { showToast("Raw URL rclone.conf wajib diisi.", "error"); return; } elements.rcloneConfigSave.disabled = true; try { const response = await fetch("/api/rclone/config", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ config_url: configUrl }), }); const payload = await response.json(); if (!response.ok || !payload.success) { showToast(payload.message || "rclone.conf belum valid.", "error"); return; } showToast(payload.message || "rclone.conf valid."); const uploadRequest = pendingRcloneUpload; await refreshTorrents(); const remotes = Array.isArray(payload.rclone?.remotes) ? payload.rclone.remotes : []; if (uploadRequest && remotes.length) { setRcloneModalMode("remote"); elements.rcloneConfigText.textContent = "Pilih remote tujuan upload dari rclone.conf."; renderRcloneRemoteList(remotes, payload.rclone?.selected_remote || remotes[0]); return; } closeRcloneConfigModal(); } finally { elements.rcloneConfigSave.disabled = false; } } function stopTorrentFileSelectionPolling() { if (torrentFileSelectionPollTimer) { window.clearInterval(torrentFileSelectionPollTimer); torrentFileSelectionPollTimer = null; } } function updateTorrentFileSelectionCount() { if (!elements.torrentFileSelectionCount || !elements.torrentFileSelectionList) { return; } const checkedBoxes = Array.from(elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]:checked")); const checkedCount = checkedBoxes.length; elements.torrentFileSelectionCount.textContent = String(checkedCount); if (!elements.torrentFileSelectionStorageWarning) { return; } const selectedBytes = checkedBoxes.reduce((total, checkbox) => total + Number(checkbox.dataset.sizeBytes || 0), 0); const availableBytes = Number(pendingTorrentFileSelection?.storageAvailableBytes || 0); const selectedSize = formatBytes(selectedBytes); const availableSize = pendingTorrentFileSelection?.storageAvailable || formatBytes(availableBytes); if (availableBytes > 0 && selectedBytes > availableBytes) { elements.torrentFileSelectionStorageWarning.textContent = `Storage tidak cukup. Pilihan saat ini ${selectedSize}, tersedia ${availableSize}. Kurangi pilihan atau bersihkan storage dulu.`; elements.torrentFileSelectionStorageWarning.classList.remove("hidden"); return; } if (pendingTorrentFileSelection?.storageWarning) { elements.torrentFileSelectionStorageWarning.textContent = pendingTorrentFileSelection.storageWarning; elements.torrentFileSelectionStorageWarning.classList.remove("hidden"); return; } elements.torrentFileSelectionStorageWarning.textContent = ""; elements.torrentFileSelectionStorageWarning.classList.add("hidden"); } function renderTorrentFileSelectionFiles(files) { const torrentFiles = Array.isArray(files) ? files : []; if (!elements.torrentFileSelectionList) { return; } elements.torrentFileSelectionList.innerHTML = torrentFiles.map((file) => ` `).join(""); updateTorrentFileSelectionCount(); } function setTorrentFileSelectionLoading(isLoading, message) { elements.torrentFileSelectionText.textContent = message || ""; elements.torrentFileSelectionLoading.classList.toggle("hidden", !isLoading); elements.torrentFileSelectionStorageWarning.classList.add("hidden"); elements.torrentFileSelectionActions.classList.toggle("hidden", isLoading); elements.torrentFileSelectionList.classList.toggle("hidden", isLoading); elements.torrentFileSelectionConfirm.disabled = isLoading; } function closeTorrentFileSelectionModal() { stopTorrentFileSelectionPolling(); pendingTorrentFileSelection = null; hideModal(elements.torrentFileSelectionModal); } async function pollTorrentFileSelection() { if (!pendingTorrentFileSelection?.hash) { return; } try { const response = await fetch(`/api/torrents/${pendingTorrentFileSelection.hash}/files`, { headers: { Accept: "application/json" }, cache: "no-store", }); const payload = await response.json(); if (!response.ok || !payload.success) { showToast(payload.message || "Gagal mengambil daftar file torrent.", "error"); return; } if (payload.selection_pending && !payload.metadata_ready) { setTorrentFileSelectionLoading(true, payload.message || "Metadata torrent masih diambil..."); return; } if (!payload.selection_required) { showToast(payload.message || "Torrent dimulai."); closeTorrentFileSelectionModal(); await refreshTorrents(); return; } pendingTorrentFileSelection.files = Array.isArray(payload.files) ? payload.files : []; pendingTorrentFileSelection.storageAvailableBytes = Number(payload.storage_available_bytes || 0); pendingTorrentFileSelection.storageAvailable = payload.storage_available || ""; pendingTorrentFileSelection.storageWarning = payload.storage_warning || ""; setTorrentFileSelectionLoading(false, payload.message || "Pilih file yang ingin didownload."); renderTorrentFileSelectionFiles(pendingTorrentFileSelection.files); stopTorrentFileSelectionPolling(); await refreshTorrents(); } catch (error) { showToast("Gagal mengambil metadata torrent.", "error"); } } function openTorrentFileSelectionModal(payload) { const torrentHash = payload.torrent_hash; if (!torrentHash) { return; } pendingTorrentFileSelection = { hash: torrentHash, files: Array.isArray(payload.files) ? payload.files : [], storageAvailableBytes: Number(payload.storage_available_bytes || 0), storageAvailable: payload.storage_available || "", storageWarning: payload.storage_warning || "", }; elements.torrentFileSelectionList.innerHTML = ""; showModal(elements.torrentFileSelectionModal); if (payload.selection_pending) { setTorrentFileSelectionLoading(true, payload.message || "Metadata torrent masih diambil..."); stopTorrentFileSelectionPolling(); torrentFileSelectionPollTimer = window.setInterval(pollTorrentFileSelection, 1600); pollTorrentFileSelection(); return; } setTorrentFileSelectionLoading(false, payload.message || "Pilih file yang ingin didownload."); renderTorrentFileSelectionFiles(pendingTorrentFileSelection.files); } async function confirmTorrentFileSelection() { if (!pendingTorrentFileSelection?.hash) { return; } const selectedIds = Array.from(elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]:checked")) .map((checkbox) => Number(checkbox.value)); if (!selectedIds.length) { showToast("Pilih minimal satu file.", "error"); return; } const selectedBytes = Array.from(elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]:checked")) .reduce((total, checkbox) => total + Number(checkbox.dataset.sizeBytes || 0), 0); const availableBytes = Number(pendingTorrentFileSelection.storageAvailableBytes || 0); if (availableBytes > 0 && selectedBytes > availableBytes) { updateTorrentFileSelectionCount(); showToast("Storage tidak cukup untuk file yang dipilih.", "error"); return; } elements.torrentFileSelectionConfirm.disabled = true; try { const response = await fetch(`/api/torrents/${pendingTorrentFileSelection.hash}/files/selection`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ selected_file_ids: selectedIds }), }); const payload = await response.json(); if (!response.ok || !payload.success) { showToast(payload.message || "Gagal menerapkan seleksi file.", response.status === 507 ? "warning" : "error"); return; } showToast(payload.message || "Seleksi file diterapkan."); closeTorrentFileSelectionModal(); await refreshTorrents(); } finally { elements.torrentFileSelectionConfirm.disabled = false; } } async function cancelTorrentFileSelection() { if (!pendingTorrentFileSelection?.hash) { closeTorrentFileSelectionModal(); return; } const torrentHash = pendingTorrentFileSelection.hash; elements.torrentFileSelectionCancel.disabled = true; try { const response = await fetch(`/api/torrents/${torrentHash}?with_files=false`, { method: "DELETE", headers: { Accept: "application/json" }, }); const payload = await response.json(); if (!response.ok || !payload.success) { showToast(payload.message || "Gagal membatalkan torrent.", "error"); return; } showToast("Torrent dibatalkan."); closeTorrentFileSelectionModal(); await refreshTorrents(); } finally { elements.torrentFileSelectionCancel.disabled = false; } } async function refreshSystem() { const response = await fetch("/api/system", { headers: { Accept: "application/json" }, cache: "no-store", }); if (!response.ok) { throw new Error("System request failed"); } const data = await response.json(); updateSystemInfo(data.system || {}); } async function refreshTorrents() { try { const response = await fetch("/api/torrents", { headers: { Accept: "application/json" }, cache: "no-store", }); if (!response.ok) { throw new Error("Request failed"); } const data = await response.json(); state.torrents = Array.isArray(data.torrents) ? data.torrents : []; reconcileOptimisticTorrentState(state.torrents); state.stats = data.stats || {}; state.events = Array.isArray(data.events) ? data.events : []; updateConnection(true, state.stats.version || "-"); renderEvents(state.events, { toastNew: true }); updateSummary(state.stats, state.torrents); elements.savePath.textContent = state.stats.download_path || "-"; renderTorrents(); await refreshSystem(); } catch (error) { updateConnection(false, "unreachable"); } } function delay(ms) { return new Promise((resolve) => window.setTimeout(resolve, ms)); } async function waitForTorrentListMutation(previousHashes, attempts = 6, intervalMs = 1200) { for (let attempt = 0; attempt < attempts; attempt += 1) { await refreshTorrents(); const currentHashes = new Set((state.torrents || []).map((torrent) => torrent.hash)); let changed = currentHashes.size !== previousHashes.size; if (!changed) { for (const hash of currentHashes) { if (!previousHashes.has(hash)) { changed = true; break; } } } if (changed) { return true; } await delay(intervalMs); } return false; } async function triggerTorrentAction(action, hash, mode = null, remote = null) { const method = action === "delete" ? "DELETE" : "POST"; const params = new URLSearchParams(); if (mode) { params.set("mode", mode); } if (action === "upload-rclone" && remote) { params.set("remote", remote); } const query = params.toString() ? `?${params.toString()}` : ""; const target = action === "delete" ? `/api/torrents/${hash}?with_files=${elements.deleteWithFiles.checked}` : action === "upload-gofile" ? `/api/torrents/${hash}/upload-gofile${query}` : action === "upload-pixeldrain" ? `/api/torrents/${hash}/upload-pixeldrain${query}` : action === "upload-rclone" ? `/api/torrents/${hash}/upload-rclone${query}` : action === "cancel-gofile" ? `/api/torrents/${hash}/cancel-gofile` : `/api/torrents/${hash}/${action}`; if (action === "pause" || action === "resume") { setInFlightTorrentAction(hash, action); renderTorrents(); } let response; let payload; try { response = await fetch(target, { method, headers: { Accept: "application/json" }, }); payload = await response.json(); } finally { if (action === "pause" || action === "resume") { clearInFlightTorrentAction(hash); } } if (!response.ok || !payload.success) { if (action === "pause" || action === "resume") { clearOptimisticTorrentState(hash); await refreshTorrents(); } const rcloneMessage = String(payload.message || "").toLowerCase(); const shouldPickRcloneRemote = action === "upload-rclone" && ( payload.rclone || rcloneMessage.includes("rclone belum siap") || rcloneMessage.includes("rclone.conf") || rcloneMessage.includes("remote rclone") ); if (shouldPickRcloneRemote) { openRcloneConfigModal({ action, hash, isFolder: false }, payload.message || ""); return; } showToast(payload.message || "Aksi torrent gagal.", "error"); return; } if (action === "delete") { closeDeleteModal(); } if (action === "upload-gofile") { showToast(payload.message || "Upload GoFile dimulai."); } else if (action === "upload-pixeldrain") { showToast(payload.message || "Upload PixelDrain dimulai."); } else if (action === "upload-rclone") { showToast(payload.message || "Upload rclone dimulai."); } else if (action === "cancel-gofile") { showToast(payload.message || "Pembatalan upload diproses.", "warning"); } else { showToast(payload.message || "Aksi berhasil diproses."); } if (action === "pause" || action === "resume") { setOptimisticTorrentState(hash, action); applyOptimisticTorrentAction(action, hash); } await refreshTorrents(); } async function startSpeedtest() { const response = await fetch("/api/system/speedtest", { method: "POST", headers: { Accept: "application/json" }, }); const payload = await response.json(); if (!response.ok || !payload.success) { showToast(payload.message || "Gagal memulai speedtest.", "error"); return; } showToast(payload.message || "Speedtest dimulai."); await refreshSystem(); } async function submitFormWithToast(form, successMessage) { const submitButton = form.querySelector('button[type="submit"]'); submitButton.disabled = true; submitButton.classList.add("opacity-70"); const previousHashes = new Set((state.torrents || []).map((torrent) => torrent.hash)); try { const response = await fetch(form.action, { method: form.method || "POST", body: new FormData(form), headers: { Accept: "application/json", "X-Requested-With": "XMLHttpRequest", }, }); const payload = await response.json(); if (!response.ok || !payload.success) { showToast(payload.message || "Aksi gagal diproses.", response.status === 507 ? "warning" : "error"); return; } form.reset(); syncTorrentFileName(); closeAddModal(); if (payload.selection_required || payload.selection_pending) { showToast(payload.storage_warning || payload.message || "Pilih file torrent sebelum download dimulai.", "warning"); openTorrentFileSelectionModal(payload); await refreshTorrents(); return; } showToast(payload.message || successMessage); const appeared = await waitForTorrentListMutation(previousHashes); if (!appeared) { await refreshTorrents(); } } finally { submitButton.disabled = false; submitButton.classList.remove("opacity-70"); } } elements.searchInput?.addEventListener("input", (event) => { state.searchTerm = String(event.target.value || "").trim().toLowerCase(); state.currentPage = 1; updateSummary(state.stats, state.torrents); renderTorrents(); }); elements.filterTabs?.addEventListener("click", (event) => { const button = event.target.closest("[data-filter]"); if (!button) { return; } state.activeFilter = button.dataset.filter || "all"; state.currentPage = 1; renderFilterTabs(); updateSummary(state.stats, state.torrents); renderTorrents(); }); elements.torrentPagination?.addEventListener("click", (event) => { const pageButton = event.target.closest("[data-page]"); if (pageButton) { state.currentPage = Number(pageButton.dataset.page || 1); renderTorrents(); scrollToTorrentListTop(); return; } const navButton = event.target.closest("[data-page-nav]"); if (!navButton || navButton.disabled) { return; } const totalPages = getTotalPages(filteredTorrents().length); const action = navButton.dataset.pageNav; if (action === "first") { state.currentPage = 1; } else if (action === "prev") { state.currentPage = Math.max(1, state.currentPage - 1); } else if (action === "next") { state.currentPage = Math.min(totalPages, state.currentPage + 1); } else if (action === "last") { state.currentPage = totalPages; } renderTorrents(); scrollToTorrentListTop(); }); elements.torrentList?.addEventListener("click", async (event) => { const button = event.target.closest("[data-action]"); if (!button) { return; } const action = button.dataset.action; if (action === "delete") { openDeleteModal( button.dataset.hash, button.dataset.name || button.closest("article")?.querySelector("h3")?.textContent || "torrent ini", ); return; } if (action === "dismiss-status-message") { dismissStatusMessage(button.dataset.hash, button.dataset.message || ""); renderTorrents(); return; } if (action === "upload-rclone") { openRcloneConfigModal( { action, hash: button.dataset.hash, isFolder: button.dataset.isFolder === "true", rawEnabled: button.dataset.rawEnabled === "true", }, button.dataset.rcloneReady === "true" ? "" : button.dataset.rcloneError || "", ); return; } if ((action === "upload-gofile" || action === "upload-pixeldrain") && button.dataset.isFolder === "true") { openFolderUploadModal( action, button.dataset.hash, button.dataset.provider || "provider ini", button.dataset.rawEnabled === "true", ); return; } if (action === "copy-link") { try { await navigator.clipboard.writeText(button.dataset.link || ""); showToast("Link berhasil disalin."); } catch (error) { showToast("Gagal menyalin link.", "error"); } return; } button.disabled = true; try { await triggerTorrentAction(action, button.dataset.hash); } finally { button.disabled = false; } }); elements.openAddModal?.addEventListener("click", openAddModal); elements.addModalClose?.addEventListener("click", closeAddModal); document.querySelectorAll("[data-close-add-modal]").forEach((button) => { button.addEventListener("click", closeAddModal); }); elements.addTabMagnet?.addEventListener("click", () => showAddTab("magnet")); elements.addTabFile?.addEventListener("click", () => showAddTab("file")); elements.addTabAria2?.addEventListener("click", () => showAddTab("aria2")); elements.torrentFileInput?.addEventListener("change", syncTorrentFileName); elements.magnetForm?.addEventListener("submit", async (event) => { event.preventDefault(); await submitFormWithToast(elements.magnetForm, "Magnet link berhasil ditambahkan."); }); elements.torrentUploadForm?.addEventListener("submit", async (event) => { event.preventDefault(); await submitFormWithToast(elements.torrentUploadForm, "File torrent berhasil diunggah."); }); elements.aria2Form?.addEventListener("submit", async (event) => { event.preventDefault(); await submitFormWithToast(elements.aria2Form, "Aria2 link berhasil ditambahkan."); }); elements.modalClose?.addEventListener("click", closeDeleteModal); elements.modalCancel?.addEventListener("click", closeDeleteModal); elements.deleteModal?.addEventListener("click", (event) => { if (event.target === elements.deleteModal) { closeDeleteModal(); } }); elements.modalConfirm?.addEventListener("click", async () => { if (!pendingDelete) { return; } elements.modalConfirm.disabled = true; try { await triggerTorrentAction("delete", pendingDelete.hash); } finally { elements.modalConfirm.disabled = false; } }); elements.torrentFileSelectionList?.addEventListener("change", (event) => { if (event.target.closest("[data-file-selection-checkbox]")) { updateTorrentFileSelectionCount(); } }); elements.torrentFileSelectionAll?.addEventListener("click", () => { elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]").forEach((checkbox) => { checkbox.checked = true; }); updateTorrentFileSelectionCount(); }); elements.torrentFileSelectionNone?.addEventListener("click", () => { elements.torrentFileSelectionList.querySelectorAll("[data-file-selection-checkbox]").forEach((checkbox) => { checkbox.checked = false; }); updateTorrentFileSelectionCount(); }); elements.torrentFileSelectionConfirm?.addEventListener("click", confirmTorrentFileSelection); elements.torrentFileSelectionCancel?.addEventListener("click", cancelTorrentFileSelection); elements.torrentFileSelectionClose?.addEventListener("click", cancelTorrentFileSelection); elements.torrentFileSelectionModal?.addEventListener("click", (event) => { if (event.target === elements.torrentFileSelectionModal) { cancelTorrentFileSelection(); } }); elements.folderUploadClose?.addEventListener("click", closeFolderUploadModal); elements.folderUploadCancel?.addEventListener("click", closeFolderUploadModal); elements.folderUploadModal?.addEventListener("click", (event) => { if (event.target === elements.folderUploadModal) { closeFolderUploadModal(); } }); document.querySelectorAll(".folder-upload-choice").forEach((button) => { button.addEventListener("click", () => { if (button.disabled) { return; } selectedFolderUploadMode = button.dataset.uploadMode || "zip"; document.querySelectorAll(".folder-upload-choice").forEach((choice) => { const active = choice.dataset.uploadMode === selectedFolderUploadMode; if (active) { choice.classList.add("border-neon/20", "bg-neon/10"); choice.classList.remove("border-white/10", "bg-white/[0.03]"); } else { choice.classList.remove("border-neon/20", "bg-neon/10"); choice.classList.add("border-white/10", "bg-white/[0.03]"); } }); }); }); elements.folderUploadConfirm?.addEventListener("click", async () => { if (!pendingFolderUpload) { return; } elements.folderUploadConfirm.disabled = true; try { await triggerTorrentAction( pendingFolderUpload.action, pendingFolderUpload.hash, selectedFolderUploadMode, pendingFolderUpload.remote || null, ); closeFolderUploadModal(); } finally { elements.folderUploadConfirm.disabled = false; } }); elements.rcloneConfigClose?.addEventListener("click", closeRcloneConfigModal); elements.rcloneConfigCancel?.addEventListener("click", closeRcloneConfigModal); elements.rcloneConfigSave?.addEventListener("click", saveRcloneConfigUrl); elements.rcloneConfigRefresh?.addEventListener("click", () => { loadRcloneRemoteOptions(); }); elements.rcloneRemoteList?.addEventListener("click", (event) => { const button = event.target.closest("[data-rclone-remote]"); if (!button) { return; } selectedRcloneRemote = button.dataset.rcloneRemote || ""; const remotes = Array.from(elements.rcloneRemoteList.querySelectorAll("[data-rclone-remote]")).map((item) => item.dataset.rcloneRemote || ""); renderRcloneRemoteList(remotes, selectedRcloneRemote); }); elements.rcloneConfigUrl?.addEventListener("keydown", (event) => { if (event.key === "Enter") { event.preventDefault(); saveRcloneConfigUrl(); } }); elements.rcloneConfigModal?.addEventListener("click", (event) => { if (event.target === elements.rcloneConfigModal) { closeRcloneConfigModal(); } }); elements.speedtestButton?.addEventListener("click", startSpeedtest); elements.addModal?.addEventListener("click", (event) => { if (event.target === elements.addModal) { closeAddModal(); } }); showAddTab("magnet"); syncTorrentFileName(); renderDashboard(); refreshTorrents(); setInterval(refreshTorrents, 3000); })();