Spaces:
Paused
Paused
Upload 7 files
Browse files- .dockerignore +5 -0
- .gitignore +4 -0
- Dockerfile +34 -0
- app.py +860 -0
- docker-compose.yml +23 -0
- entrypoint.sh +41 -0
- requirements.txt +6 -0
.dockerignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
downloads/
|
| 3 |
+
uploads/
|
| 4 |
+
monitor_state.json
|
| 5 |
+
.git/
|
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
uploads/
|
| 3 |
+
downloads/
|
| 4 |
+
monitor_state.json
|
Dockerfile
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
|
| 3 |
+
ENV PYTHONUNBUFFERED=1 \
|
| 4 |
+
QBT_PROFILE=/config \
|
| 5 |
+
QBITTORRENT_HOST=127.0.0.1 \
|
| 6 |
+
QBITTORRENT_PORT=8080 \
|
| 7 |
+
QBITTORRENT_SAVE_PATH=/downloads \
|
| 8 |
+
PORT=5000
|
| 9 |
+
|
| 10 |
+
RUN apt-get update \
|
| 11 |
+
&& apt-get install -y --no-install-recommends qbittorrent-nox ca-certificates bash tini \
|
| 12 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 13 |
+
|
| 14 |
+
RUN useradd -m -u 1000 qbittorrent
|
| 15 |
+
|
| 16 |
+
WORKDIR /app
|
| 17 |
+
|
| 18 |
+
COPY requirements.txt .
|
| 19 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 20 |
+
|
| 21 |
+
COPY app.py .
|
| 22 |
+
COPY templates ./templates
|
| 23 |
+
COPY qbittorrent/config/qBittorrent.conf /defaults/qBittorrent.conf
|
| 24 |
+
COPY entrypoint.sh /entrypoint.sh
|
| 25 |
+
|
| 26 |
+
RUN mkdir -p /app/uploads /config /downloads /defaults \
|
| 27 |
+
&& chown -R qbittorrent:qbittorrent /app /config /downloads /defaults /entrypoint.sh \
|
| 28 |
+
&& chmod +x /entrypoint.sh
|
| 29 |
+
|
| 30 |
+
USER qbittorrent
|
| 31 |
+
|
| 32 |
+
EXPOSE 5000
|
| 33 |
+
|
| 34 |
+
ENTRYPOINT ["/usr/bin/tini", "--", "/entrypoint.sh"]
|
app.py
ADDED
|
@@ -0,0 +1,860 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import platform
|
| 4 |
+
import shutil
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from flask import Flask, flash, jsonify, redirect, render_template, request, url_for
|
| 10 |
+
import psutil
|
| 11 |
+
import qbittorrentapi
|
| 12 |
+
import requests
|
| 13 |
+
from requests_toolbelt.multipart.encoder import MultipartEncoder, MultipartEncoderMonitor
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 17 |
+
UPLOAD_DIR = BASE_DIR / "uploads"
|
| 18 |
+
STATE_FILE = BASE_DIR / "monitor_state.json"
|
| 19 |
+
STATE_LOCK = threading.Lock()
|
| 20 |
+
UPLOAD_DIR.mkdir(exist_ok=True)
|
| 21 |
+
|
| 22 |
+
ACTIVE_DOWNLOAD_STATES = {"downloading", "metaDL", "stalledDL", "forcedMetaDL", "forcedDL"}
|
| 23 |
+
PAUSED_STATES = {"pausedDL", "pausedUP"}
|
| 24 |
+
FAILED_STATES = {"error", "missingFiles", "unknown"}
|
| 25 |
+
STUCK_TIMEOUT_MINUTES = int(os.getenv("TORRENT_STUCK_TIMEOUT_MINUTES", "5"))
|
| 26 |
+
STUCK_TIMEOUT_SECONDS = STUCK_TIMEOUT_MINUTES * 60
|
| 27 |
+
MAX_EVENTS = 12
|
| 28 |
+
SYSTEM_INFO_CACHE_SECONDS = 900
|
| 29 |
+
LOCATION_CACHE_SECONDS = 3600
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class GofileUploadCancelled(Exception):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def env(name: str, default: str) -> str:
|
| 37 |
+
return os.getenv(name, default)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
GOFILE_UPLOAD_URL = env("GOFILE_UPLOAD_URL", "https://upload.gofile.io/uploadfile")
|
| 41 |
+
GOFILE_API_TOKEN = env("GOFILE_API_TOKEN", "")
|
| 42 |
+
IP_LOCATION_API_URL = env("IP_LOCATION_API_URL", "https://ipapi.co/json/")
|
| 43 |
+
CLOUDFLARE_DOWNLOAD_URL = env("CLOUDFLARE_DOWNLOAD_URL", "https://speed.cloudflare.com/__down")
|
| 44 |
+
CLOUDFLARE_UPLOAD_URL = env("CLOUDFLARE_UPLOAD_URL", "https://speed.cloudflare.com/__up")
|
| 45 |
+
WEB_PORT = int(env("PORT", "5000"))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
app = Flask(__name__)
|
| 49 |
+
app.config["SECRET_KEY"] = env("FLASK_SECRET_KEY", "dev-secret")
|
| 50 |
+
app.config["MAX_CONTENT_LENGTH"] = 100 * 1024 * 1024
|
| 51 |
+
|
| 52 |
+
DOWNLOAD_PATH = env("QBITTORRENT_SAVE_PATH", "/downloads")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_client() -> qbittorrentapi.Client:
|
| 56 |
+
username = env("QBITTORRENT_USERNAME", "")
|
| 57 |
+
password = env("QBITTORRENT_PASSWORD", "")
|
| 58 |
+
client = qbittorrentapi.Client(
|
| 59 |
+
host=env("QBITTORRENT_HOST", "127.0.0.1"),
|
| 60 |
+
port=int(env("QBITTORRENT_PORT", "8080")),
|
| 61 |
+
username=username,
|
| 62 |
+
password=password,
|
| 63 |
+
)
|
| 64 |
+
if username and password:
|
| 65 |
+
client.auth_log_in()
|
| 66 |
+
return client
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def format_size(value: int | None) -> str:
|
| 70 |
+
if value in (None, 0):
|
| 71 |
+
return "0 B"
|
| 72 |
+
|
| 73 |
+
size = float(value)
|
| 74 |
+
units = ["B", "KB", "MB", "GB", "TB"]
|
| 75 |
+
for unit in units:
|
| 76 |
+
if size < 1024 or unit == units[-1]:
|
| 77 |
+
return f"{size:.1f} {unit}"
|
| 78 |
+
size /= 1024
|
| 79 |
+
return f"{size:.1f} TB"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def format_speed(value: int | None) -> str:
|
| 83 |
+
return f"{format_size(value)}/s"
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def format_mbps(bits_per_second: float | None) -> str:
|
| 87 |
+
if not bits_per_second:
|
| 88 |
+
return "0 Mbps"
|
| 89 |
+
return f"{bits_per_second / 1_000_000:.2f} Mbps"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def progress_percent(progress: float | None) -> int:
|
| 93 |
+
if progress is None:
|
| 94 |
+
return 0
|
| 95 |
+
return round(progress * 100)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def format_duration(seconds: float) -> str:
|
| 99 |
+
seconds = max(0, int(seconds))
|
| 100 |
+
if seconds < 60:
|
| 101 |
+
return f"{seconds} detik"
|
| 102 |
+
if seconds < 3600:
|
| 103 |
+
return f"{seconds // 60} menit"
|
| 104 |
+
return f"{seconds // 3600} jam"
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def human_eta(seconds: float | int | None) -> str:
|
| 108 |
+
if seconds is None:
|
| 109 |
+
return "-"
|
| 110 |
+
|
| 111 |
+
total_seconds = int(seconds)
|
| 112 |
+
if total_seconds <= 0:
|
| 113 |
+
return "-"
|
| 114 |
+
|
| 115 |
+
if total_seconds < 60:
|
| 116 |
+
return f"{total_seconds} seconds left"
|
| 117 |
+
|
| 118 |
+
minutes = total_seconds // 60
|
| 119 |
+
if total_seconds < 3600:
|
| 120 |
+
return f"{minutes} minute left" if minutes == 1 else f"{minutes} minutes left"
|
| 121 |
+
|
| 122 |
+
hours = total_seconds // 3600
|
| 123 |
+
remaining_minutes = (total_seconds % 3600) // 60
|
| 124 |
+
if remaining_minutes == 0:
|
| 125 |
+
return f"{hours} hour left" if hours == 1 else f"{hours} hours left"
|
| 126 |
+
|
| 127 |
+
hour_label = "hour" if hours == 1 else "hours"
|
| 128 |
+
minute_label = "minute" if remaining_minutes == 1 else "minutes"
|
| 129 |
+
return f"{hours} {hour_label} {remaining_minutes} {minute_label} left"
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def load_monitor_state() -> dict:
|
| 133 |
+
with STATE_LOCK:
|
| 134 |
+
if not STATE_FILE.exists():
|
| 135 |
+
return {"torrents": {}, "events": [], "system": {}, "speedtest": {"running": False}}
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
data = json.loads(STATE_FILE.read_text(encoding="utf-8"))
|
| 139 |
+
except (json.JSONDecodeError, OSError):
|
| 140 |
+
return {"torrents": {}, "events": [], "system": {}, "speedtest": {"running": False}}
|
| 141 |
+
|
| 142 |
+
data.setdefault("torrents", {})
|
| 143 |
+
data.setdefault("events", [])
|
| 144 |
+
data.setdefault("system", {})
|
| 145 |
+
data.setdefault("speedtest", {"running": False})
|
| 146 |
+
return data
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def save_monitor_state(state: dict) -> None:
|
| 150 |
+
with STATE_LOCK:
|
| 151 |
+
temp_file = STATE_FILE.with_suffix(".tmp")
|
| 152 |
+
temp_file.write_text(json.dumps(state, ensure_ascii=True, indent=2), encoding="utf-8")
|
| 153 |
+
temp_file.replace(STATE_FILE)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def update_state(mutator):
|
| 157 |
+
state = load_monitor_state()
|
| 158 |
+
mutator(state)
|
| 159 |
+
save_monitor_state(state)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def add_event(state: dict, level: str, message: str) -> None:
|
| 163 |
+
state.setdefault("events", []).insert(
|
| 164 |
+
0,
|
| 165 |
+
{
|
| 166 |
+
"level": level,
|
| 167 |
+
"message": message,
|
| 168 |
+
"created_at": int(time.time()),
|
| 169 |
+
},
|
| 170 |
+
)
|
| 171 |
+
state["events"] = state["events"][:MAX_EVENTS]
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def state_label(raw_state: str) -> str:
|
| 175 |
+
mapping = {
|
| 176 |
+
"downloading": "Downloading",
|
| 177 |
+
"stalledDL": "Stalled",
|
| 178 |
+
"metaDL": "Fetching Metadata",
|
| 179 |
+
"pausedDL": "Paused",
|
| 180 |
+
"pausedUP": "Paused",
|
| 181 |
+
"uploading": "Seeding",
|
| 182 |
+
"stalledUP": "Seeding",
|
| 183 |
+
"queuedDL": "Queued",
|
| 184 |
+
"queuedUP": "Queued",
|
| 185 |
+
"checkingUP": "Checking",
|
| 186 |
+
"checkingDL": "Checking",
|
| 187 |
+
"forcedDL": "Forced Download",
|
| 188 |
+
"forcedMetaDL": "Forced Metadata",
|
| 189 |
+
"forcedUP": "Uploading",
|
| 190 |
+
"error": "Error",
|
| 191 |
+
"missingFiles": "Missing Files",
|
| 192 |
+
}
|
| 193 |
+
return mapping.get(raw_state, raw_state)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def status_badge(raw_state: str) -> str:
|
| 197 |
+
if raw_state in FAILED_STATES:
|
| 198 |
+
return "border-rose-500/30 bg-rose-500/10 text-rose-200"
|
| 199 |
+
if raw_state in ACTIVE_DOWNLOAD_STATES:
|
| 200 |
+
return "border-amber-500/30 bg-amber-500/10 text-amber-100"
|
| 201 |
+
if raw_state in PAUSED_STATES:
|
| 202 |
+
return "border-stone-500/30 bg-stone-500/10 text-stone-200"
|
| 203 |
+
return "border-emerald-500/30 bg-emerald-500/10 text-emerald-100"
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def effective_state_label(torrent, state_entry: dict | None = None) -> str:
|
| 207 |
+
if state_entry and state_entry.get("gofile_uploading"):
|
| 208 |
+
return "GoFile Upload"
|
| 209 |
+
|
| 210 |
+
raw_state = getattr(torrent, "state", "")
|
| 211 |
+
progress = float(getattr(torrent, "progress", 0) or 0)
|
| 212 |
+
upspeed = int(getattr(torrent, "upspeed", 0) or 0)
|
| 213 |
+
|
| 214 |
+
if progress >= 1:
|
| 215 |
+
if raw_state in {"uploading", "stalledUP", "forcedUP"}:
|
| 216 |
+
return "Uploading" if upspeed > 0 else "Complete"
|
| 217 |
+
if raw_state in {"pausedUP", "queuedUP", "checkingUP"}:
|
| 218 |
+
return "Complete"
|
| 219 |
+
|
| 220 |
+
return state_label(raw_state)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def effective_status_badge(torrent, state_entry: dict | None = None) -> str:
|
| 224 |
+
if state_entry and state_entry.get("gofile_uploading"):
|
| 225 |
+
return "border-sky-500/30 bg-sky-500/10 text-sky-100"
|
| 226 |
+
|
| 227 |
+
raw_state = getattr(torrent, "state", "")
|
| 228 |
+
progress = float(getattr(torrent, "progress", 0) or 0)
|
| 229 |
+
upspeed = int(getattr(torrent, "upspeed", 0) or 0)
|
| 230 |
+
|
| 231 |
+
if progress >= 1 and raw_state in {"uploading", "stalledUP", "forcedUP", "pausedUP", "queuedUP", "checkingUP"}:
|
| 232 |
+
if upspeed > 0 and raw_state in {"uploading", "forcedUP"}:
|
| 233 |
+
return "border-sky-500/30 bg-sky-500/10 text-sky-100"
|
| 234 |
+
return "border-emerald-500/30 bg-emerald-500/10 text-emerald-100"
|
| 235 |
+
|
| 236 |
+
return status_badge(raw_state)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def serialize_event(event: dict) -> dict:
|
| 240 |
+
return {
|
| 241 |
+
"level": event.get("level", "info"),
|
| 242 |
+
"message": event.get("message", ""),
|
| 243 |
+
"created_at": event.get("created_at", 0),
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def serialize_torrent(torrent, state_entry: dict | None = None) -> dict:
|
| 248 |
+
eta_value = getattr(torrent, "eta", None)
|
| 249 |
+
state_entry = state_entry or {}
|
| 250 |
+
status_message = state_entry.get("status_message", "")
|
| 251 |
+
content_path = Path(getattr(torrent, "content_path", "") or "")
|
| 252 |
+
gofile_uploading = bool(state_entry.get("gofile_uploading"))
|
| 253 |
+
gofile_progress = int(state_entry.get("gofile_progress", 0) or 0)
|
| 254 |
+
gofile_eta_seconds = int(state_entry.get("gofile_eta_seconds", 0) or 0)
|
| 255 |
+
display_progress = gofile_progress if gofile_uploading else progress_percent(getattr(torrent, "progress", 0))
|
| 256 |
+
progress_label = "GoFile Upload" if gofile_uploading else "Progress"
|
| 257 |
+
gofile_speed = state_entry.get("gofile_speed", "")
|
| 258 |
+
eta_text = human_eta(gofile_eta_seconds) if gofile_uploading else human_eta(eta_value)
|
| 259 |
+
display_speed = gofile_speed if gofile_uploading else format_speed(getattr(torrent, "dlspeed", 0))
|
| 260 |
+
|
| 261 |
+
can_gofile_upload = (
|
| 262 |
+
bool(content_path)
|
| 263 |
+
and content_path.exists()
|
| 264 |
+
and content_path.is_file()
|
| 265 |
+
and progress_percent(getattr(torrent, "progress", 0)) >= 100
|
| 266 |
+
and not gofile_uploading
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
return {
|
| 270 |
+
"hash": torrent.hash,
|
| 271 |
+
"name": torrent.name,
|
| 272 |
+
"state": torrent.state,
|
| 273 |
+
"state_label": effective_state_label(torrent, state_entry),
|
| 274 |
+
"state_badge": effective_status_badge(torrent, state_entry),
|
| 275 |
+
"total_size": format_size(getattr(torrent, "total_size", 0)),
|
| 276 |
+
"downloaded": format_size(getattr(torrent, "downloaded", 0)),
|
| 277 |
+
"dlspeed": format_speed(getattr(torrent, "dlspeed", 0)),
|
| 278 |
+
"upspeed": format_speed(getattr(torrent, "upspeed", 0)),
|
| 279 |
+
"display_speed": display_speed,
|
| 280 |
+
"progress": display_progress,
|
| 281 |
+
"progress_label": progress_label,
|
| 282 |
+
"num_seeds": getattr(torrent, "num_seeds", 0),
|
| 283 |
+
"num_leechs": getattr(torrent, "num_leechs", 0),
|
| 284 |
+
"eta": eta_text,
|
| 285 |
+
"status_message": status_message,
|
| 286 |
+
"can_pause": torrent.state not in PAUSED_STATES and torrent.state not in FAILED_STATES and not gofile_uploading,
|
| 287 |
+
"can_resume": torrent.state in PAUSED_STATES,
|
| 288 |
+
"can_gofile_upload": can_gofile_upload,
|
| 289 |
+
"gofile_link": state_entry.get("gofile_link", ""),
|
| 290 |
+
"gofile_status": state_entry.get("gofile_status", ""),
|
| 291 |
+
"gofile_uploading": gofile_uploading,
|
| 292 |
+
"gofile_speed": gofile_speed,
|
| 293 |
+
"gofile_eta": human_eta(gofile_eta_seconds) if gofile_uploading else "-",
|
| 294 |
+
"can_copy_link": bool(state_entry.get("gofile_link")),
|
| 295 |
+
"can_cancel_gofile_upload": gofile_uploading,
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def update_torrent_entry(torrent_hash: str, **fields) -> None:
|
| 300 |
+
def mutator(state: dict):
|
| 301 |
+
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
|
| 302 |
+
entry.update(fields)
|
| 303 |
+
|
| 304 |
+
update_state(mutator)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def clear_gofile_runtime_fields(entry: dict) -> None:
|
| 308 |
+
entry["gofile_uploading"] = False
|
| 309 |
+
entry["gofile_progress"] = 0
|
| 310 |
+
entry["gofile_speed"] = ""
|
| 311 |
+
entry["gofile_eta_seconds"] = 0
|
| 312 |
+
entry["gofile_cancel_requested"] = False
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def evaluate_torrent_health(client, torrents: list, state: dict) -> bool:
|
| 316 |
+
now = time.time()
|
| 317 |
+
torrent_state = state.setdefault("torrents", {})
|
| 318 |
+
active_hashes = {torrent.hash for torrent in torrents}
|
| 319 |
+
changed = False
|
| 320 |
+
|
| 321 |
+
for hash_value in list(torrent_state.keys()):
|
| 322 |
+
if hash_value not in active_hashes:
|
| 323 |
+
entry = torrent_state[hash_value]
|
| 324 |
+
if entry.get("gofile_uploading"):
|
| 325 |
+
continue
|
| 326 |
+
del torrent_state[hash_value]
|
| 327 |
+
changed = True
|
| 328 |
+
|
| 329 |
+
for torrent in torrents:
|
| 330 |
+
entry = torrent_state.setdefault(
|
| 331 |
+
torrent.hash,
|
| 332 |
+
{
|
| 333 |
+
"name": torrent.name,
|
| 334 |
+
"last_progress": float(getattr(torrent, "progress", 0) or 0),
|
| 335 |
+
"last_downloaded": int(getattr(torrent, "downloaded", 0) or 0),
|
| 336 |
+
"last_progress_at": now,
|
| 337 |
+
"status_message": "",
|
| 338 |
+
"gofile_progress": 0,
|
| 339 |
+
"gofile_uploading": False,
|
| 340 |
+
"gofile_speed": "",
|
| 341 |
+
"gofile_status": "",
|
| 342 |
+
"gofile_link": "",
|
| 343 |
+
},
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
entry["name"] = torrent.name
|
| 347 |
+
current_progress = float(getattr(torrent, "progress", 0) or 0)
|
| 348 |
+
current_downloaded = int(getattr(torrent, "downloaded", 0) or 0)
|
| 349 |
+
current_speed = int(getattr(torrent, "dlspeed", 0) or 0)
|
| 350 |
+
previous_progress = float(entry.get("last_progress", 0))
|
| 351 |
+
previous_downloaded = int(entry.get("last_downloaded", 0))
|
| 352 |
+
|
| 353 |
+
if current_downloaded > previous_downloaded or current_progress > previous_progress or current_speed > 0:
|
| 354 |
+
entry["last_progress"] = current_progress
|
| 355 |
+
entry["last_downloaded"] = current_downloaded
|
| 356 |
+
entry["last_progress_at"] = now
|
| 357 |
+
if entry.get("status_message") and not entry.get("gofile_uploading"):
|
| 358 |
+
entry["status_message"] = ""
|
| 359 |
+
changed = True
|
| 360 |
+
|
| 361 |
+
idle_for = now - float(entry.get("last_progress_at", now))
|
| 362 |
+
status_message = entry.get("status_message", "")
|
| 363 |
+
|
| 364 |
+
if entry.get("gofile_uploading"):
|
| 365 |
+
status_message = f"Sedang upload ke GoFile... {entry.get('gofile_progress', 0)}%"
|
| 366 |
+
if entry.get("gofile_speed"):
|
| 367 |
+
status_message += f" ({entry['gofile_speed']})"
|
| 368 |
+
if entry.get("gofile_eta_seconds"):
|
| 369 |
+
status_message += f" · {human_eta(entry['gofile_eta_seconds'])}"
|
| 370 |
+
elif torrent.state in FAILED_STATES:
|
| 371 |
+
status_message = "Torrent gagal diproses. Cek file torrent atau sumber tracker."
|
| 372 |
+
elif torrent.state in PAUSED_STATES:
|
| 373 |
+
status_message = "Torrent sedang dijeda manual."
|
| 374 |
+
elif torrent.state in ACTIVE_DOWNLOAD_STATES and current_speed == 0:
|
| 375 |
+
if idle_for >= STUCK_TIMEOUT_SECONDS:
|
| 376 |
+
if torrent.num_seeds <= 0:
|
| 377 |
+
reason = f"{torrent.name} dibatalkan otomatis karena tidak ada seed selama {format_duration(idle_for)}."
|
| 378 |
+
else:
|
| 379 |
+
reason = f"{torrent.name} dibatalkan otomatis karena tidak ada progres selama {format_duration(idle_for)}."
|
| 380 |
+
client.torrents_delete(delete_files=False, torrent_hashes=torrent.hash)
|
| 381 |
+
add_event(state, "error", reason)
|
| 382 |
+
torrent_state.pop(torrent.hash, None)
|
| 383 |
+
changed = True
|
| 384 |
+
continue
|
| 385 |
+
|
| 386 |
+
remaining = max(0, STUCK_TIMEOUT_SECONDS - int(idle_for))
|
| 387 |
+
if torrent.num_seeds <= 0 and torrent.num_leechs <= 0:
|
| 388 |
+
status_message = f"Seed dan peer tidak ada. Auto cancel dalam {format_duration(remaining)}."
|
| 389 |
+
elif torrent.num_seeds <= 0:
|
| 390 |
+
status_message = f"Seed tidak tersedia. Menunggu sampai {format_duration(remaining)} sebelum auto cancel."
|
| 391 |
+
else:
|
| 392 |
+
status_message = f"Torrent belum bergerak selama {format_duration(idle_for)}. Auto cancel dalam {format_duration(remaining)}."
|
| 393 |
+
elif float(getattr(torrent, "progress", 0) or 0) >= 1:
|
| 394 |
+
if int(getattr(torrent, "upspeed", 0) or 0) > 0:
|
| 395 |
+
status_message = f"Torrent selesai dan sedang upload dengan kecepatan {format_speed(getattr(torrent, 'upspeed', 0))}."
|
| 396 |
+
elif entry.get("gofile_link"):
|
| 397 |
+
status_message = entry.get("gofile_status") or "Upload GoFile selesai."
|
| 398 |
+
else:
|
| 399 |
+
status_message = "Torrent selesai diunduh."
|
| 400 |
+
|
| 401 |
+
if entry.get("status_message") != status_message:
|
| 402 |
+
entry["status_message"] = status_message
|
| 403 |
+
changed = True
|
| 404 |
+
|
| 405 |
+
if entry.get("last_progress") != current_progress or entry.get("last_downloaded") != current_downloaded:
|
| 406 |
+
entry["last_progress"] = current_progress
|
| 407 |
+
entry["last_downloaded"] = current_downloaded
|
| 408 |
+
changed = True
|
| 409 |
+
|
| 410 |
+
return changed
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def fetch_location_info(state: dict) -> dict:
|
| 414 |
+
cached = state.setdefault("system", {}).get("location", {})
|
| 415 |
+
now = int(time.time())
|
| 416 |
+
if cached and now - int(cached.get("fetched_at", 0)) < LOCATION_CACHE_SECONDS:
|
| 417 |
+
return cached
|
| 418 |
+
|
| 419 |
+
try:
|
| 420 |
+
response = requests.get(IP_LOCATION_API_URL, timeout=10)
|
| 421 |
+
response.raise_for_status()
|
| 422 |
+
data = response.json()
|
| 423 |
+
location = {
|
| 424 |
+
"ip": data.get("ip", "-"),
|
| 425 |
+
"city": data.get("city", "-"),
|
| 426 |
+
"region": data.get("region", "-"),
|
| 427 |
+
"country": data.get("country_name", data.get("country", "-")),
|
| 428 |
+
"org": data.get("org", "-"),
|
| 429 |
+
"timezone": data.get("timezone", "-"),
|
| 430 |
+
"fetched_at": now,
|
| 431 |
+
}
|
| 432 |
+
except requests.RequestException:
|
| 433 |
+
location = {
|
| 434 |
+
"ip": "-",
|
| 435 |
+
"city": "-",
|
| 436 |
+
"region": "-",
|
| 437 |
+
"country": "-",
|
| 438 |
+
"org": "unavailable",
|
| 439 |
+
"timezone": "-",
|
| 440 |
+
"fetched_at": now,
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
state.setdefault("system", {})["location"] = location
|
| 444 |
+
return location
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def get_system_info() -> dict:
|
| 448 |
+
state = load_monitor_state()
|
| 449 |
+
cached = state.setdefault("system", {}).get("snapshot", {})
|
| 450 |
+
now = int(time.time())
|
| 451 |
+
|
| 452 |
+
if cached and now - int(cached.get("fetched_at", 0)) < SYSTEM_INFO_CACHE_SECONDS:
|
| 453 |
+
snapshot = cached
|
| 454 |
+
else:
|
| 455 |
+
disk = shutil.disk_usage(DOWNLOAD_PATH)
|
| 456 |
+
memory = psutil.virtual_memory()
|
| 457 |
+
snapshot = {
|
| 458 |
+
"os": f"{platform.system()} {platform.release()}",
|
| 459 |
+
"cpu": platform.processor() or platform.machine() or "Unknown CPU",
|
| 460 |
+
"cpu_cores": psutil.cpu_count(logical=True) or 0,
|
| 461 |
+
"cpu_usage": f"{psutil.cpu_percent(interval=0.2):.0f}%",
|
| 462 |
+
"ram_total": format_size(memory.total),
|
| 463 |
+
"ram_used": format_size(memory.used),
|
| 464 |
+
"ram_percent": f"{memory.percent:.0f}%",
|
| 465 |
+
"storage_total": format_size(disk.total),
|
| 466 |
+
"storage_used": format_size(disk.used),
|
| 467 |
+
"storage_percent": f"{(disk.used / disk.total) * 100:.0f}%" if disk.total else "0%",
|
| 468 |
+
"hostname": platform.node() or "-",
|
| 469 |
+
"fetched_at": now,
|
| 470 |
+
}
|
| 471 |
+
state.setdefault("system", {})["snapshot"] = snapshot
|
| 472 |
+
save_monitor_state(state)
|
| 473 |
+
|
| 474 |
+
location = fetch_location_info(state)
|
| 475 |
+
save_monitor_state(state)
|
| 476 |
+
speedtest = state.get("speedtest", {"running": False})
|
| 477 |
+
|
| 478 |
+
return {
|
| 479 |
+
**snapshot,
|
| 480 |
+
"location": location,
|
| 481 |
+
"speedtest": speedtest,
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def run_speedtest_background() -> None:
|
| 486 |
+
def set_speedtest_state(**fields):
|
| 487 |
+
def mutator(state: dict):
|
| 488 |
+
speedtest = state.setdefault("speedtest", {})
|
| 489 |
+
speedtest.update(fields)
|
| 490 |
+
|
| 491 |
+
update_state(mutator)
|
| 492 |
+
|
| 493 |
+
try:
|
| 494 |
+
set_speedtest_state(running=True, status="Running speedtest...", result={})
|
| 495 |
+
|
| 496 |
+
ping_samples = []
|
| 497 |
+
for _ in range(3):
|
| 498 |
+
start = time.perf_counter()
|
| 499 |
+
response = requests.get(CLOUDFLARE_DOWNLOAD_URL, params={"bytes": 0}, timeout=15)
|
| 500 |
+
response.raise_for_status()
|
| 501 |
+
ping_samples.append((time.perf_counter() - start) * 1000)
|
| 502 |
+
|
| 503 |
+
download_bytes = 25_000_000
|
| 504 |
+
start = time.perf_counter()
|
| 505 |
+
response = requests.get(CLOUDFLARE_DOWNLOAD_URL, params={"bytes": download_bytes}, timeout=120)
|
| 506 |
+
response.raise_for_status()
|
| 507 |
+
total_download = len(response.content)
|
| 508 |
+
elapsed = max(time.perf_counter() - start, 0.001)
|
| 509 |
+
download_bps = (total_download * 8) / elapsed
|
| 510 |
+
|
| 511 |
+
payload = os.urandom(10_000_000)
|
| 512 |
+
start = time.perf_counter()
|
| 513 |
+
response = requests.post(CLOUDFLARE_UPLOAD_URL, data=payload, timeout=120)
|
| 514 |
+
response.raise_for_status()
|
| 515 |
+
elapsed = max(time.perf_counter() - start, 0.001)
|
| 516 |
+
upload_bps = (len(payload) * 8) / elapsed
|
| 517 |
+
|
| 518 |
+
result = {
|
| 519 |
+
"download": format_mbps(download_bps),
|
| 520 |
+
"upload": format_mbps(upload_bps),
|
| 521 |
+
"ping": f"{sum(ping_samples) / len(ping_samples):.0f} ms",
|
| 522 |
+
"tested_at": int(time.time()),
|
| 523 |
+
}
|
| 524 |
+
set_speedtest_state(running=False, status="Speedtest selesai.", result=result)
|
| 525 |
+
except requests.RequestException as exc:
|
| 526 |
+
set_speedtest_state(running=False, status=f"Speedtest gagal: {exc}", result={})
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def get_dashboard_data() -> tuple[list[dict], dict]:
|
| 530 |
+
client = get_client()
|
| 531 |
+
state = load_monitor_state()
|
| 532 |
+
raw_torrents = list(client.torrents_info(sort="added_on", reverse=True))
|
| 533 |
+
state_changed = evaluate_torrent_health(client, raw_torrents, state)
|
| 534 |
+
|
| 535 |
+
if state_changed:
|
| 536 |
+
save_monitor_state(state)
|
| 537 |
+
raw_torrents = list(client.torrents_info(sort="added_on", reverse=True))
|
| 538 |
+
|
| 539 |
+
version = client.app.version
|
| 540 |
+
torrents = [serialize_torrent(torrent, state.get("torrents", {}).get(torrent.hash)) for torrent in raw_torrents]
|
| 541 |
+
stats = {
|
| 542 |
+
"connected": True,
|
| 543 |
+
"download_path": DOWNLOAD_PATH,
|
| 544 |
+
"version": version,
|
| 545 |
+
"torrent_count": len(torrents),
|
| 546 |
+
"downloading": sum(1 for item in raw_torrents if item.state in ACTIVE_DOWNLOAD_STATES),
|
| 547 |
+
}
|
| 548 |
+
system_info = get_system_info()
|
| 549 |
+
return torrents, {
|
| 550 |
+
"stats": stats,
|
| 551 |
+
"events": [serialize_event(event) for event in state.get("events", [])],
|
| 552 |
+
"system_info": system_info,
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def action_response(message: str, ok: bool = True, status_code: int = 200, **extra):
|
| 557 |
+
payload = {"success": ok, "message": message}
|
| 558 |
+
payload.update(extra)
|
| 559 |
+
return jsonify(payload), status_code
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def start_gofile_upload_background(torrent_hash: str, torrent_name: str, file_path: Path) -> None:
|
| 563 |
+
def worker():
|
| 564 |
+
try:
|
| 565 |
+
headers = {}
|
| 566 |
+
if GOFILE_API_TOKEN:
|
| 567 |
+
headers["Authorization"] = f"Bearer {GOFILE_API_TOKEN}"
|
| 568 |
+
|
| 569 |
+
with file_path.open("rb") as handle:
|
| 570 |
+
encoder = MultipartEncoder(fields={"file": (file_path.name, handle)})
|
| 571 |
+
started_at = time.perf_counter()
|
| 572 |
+
last_update = 0.0
|
| 573 |
+
|
| 574 |
+
def callback(monitor):
|
| 575 |
+
nonlocal last_update
|
| 576 |
+
current_state = load_monitor_state()
|
| 577 |
+
current_entry = current_state.setdefault("torrents", {}).setdefault(torrent_hash, {})
|
| 578 |
+
if current_entry.get("gofile_cancel_requested"):
|
| 579 |
+
raise GofileUploadCancelled("Upload GoFile dibatalkan.")
|
| 580 |
+
|
| 581 |
+
now = time.perf_counter()
|
| 582 |
+
if now - last_update < 0.4 and monitor.bytes_read < encoder.len:
|
| 583 |
+
return
|
| 584 |
+
last_update = now
|
| 585 |
+
percent = round((monitor.bytes_read / encoder.len) * 100) if encoder.len else 0
|
| 586 |
+
elapsed = max(now - started_at, 0.001)
|
| 587 |
+
speed = monitor.bytes_read / elapsed
|
| 588 |
+
remaining_bytes = max(0, encoder.len - monitor.bytes_read)
|
| 589 |
+
eta_seconds = int(remaining_bytes / speed) if speed > 0 else 0
|
| 590 |
+
|
| 591 |
+
update_state(
|
| 592 |
+
lambda state: state.setdefault("torrents", {}).setdefault(torrent_hash, {}).update(
|
| 593 |
+
{
|
| 594 |
+
"gofile_uploading": True,
|
| 595 |
+
"gofile_progress": percent,
|
| 596 |
+
"gofile_speed": format_speed(speed),
|
| 597 |
+
"gofile_eta_seconds": eta_seconds,
|
| 598 |
+
"gofile_status": f"Sedang upload ke GoFile... {percent}%",
|
| 599 |
+
"status_message": f"Sedang upload ke GoFile... {percent}% ({format_speed(speed)}) · {human_eta(eta_seconds)}",
|
| 600 |
+
}
|
| 601 |
+
)
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
monitor = MultipartEncoderMonitor(encoder, callback)
|
| 605 |
+
headers["Content-Type"] = monitor.content_type
|
| 606 |
+
response = requests.post(GOFILE_UPLOAD_URL, headers=headers, data=monitor, timeout=3600)
|
| 607 |
+
|
| 608 |
+
response.raise_for_status()
|
| 609 |
+
payload = response.json()
|
| 610 |
+
data = payload.get("data", {})
|
| 611 |
+
download_page = data.get("downloadPage")
|
| 612 |
+
if not download_page:
|
| 613 |
+
raise ValueError("Respons GoFile tidak mengandung downloadPage.")
|
| 614 |
+
|
| 615 |
+
def success_mutator(state: dict):
|
| 616 |
+
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
|
| 617 |
+
clear_gofile_runtime_fields(entry)
|
| 618 |
+
entry["gofile_link"] = download_page
|
| 619 |
+
entry["gofile_status"] = f"Upload GoFile berhasil: {download_page}"
|
| 620 |
+
entry["status_message"] = "Upload GoFile selesai. Link siap disalin."
|
| 621 |
+
add_event(state, "info", f"{torrent_name} berhasil diupload ke GoFile.")
|
| 622 |
+
|
| 623 |
+
update_state(success_mutator)
|
| 624 |
+
except GofileUploadCancelled:
|
| 625 |
+
def cancel_mutator(state: dict):
|
| 626 |
+
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
|
| 627 |
+
clear_gofile_runtime_fields(entry)
|
| 628 |
+
entry["gofile_status"] = "Upload GoFile dibatalkan."
|
| 629 |
+
entry["status_message"] = "Upload GoFile dibatalkan."
|
| 630 |
+
add_event(state, "warning", f"Upload GoFile dibatalkan untuk {torrent_name}.")
|
| 631 |
+
|
| 632 |
+
update_state(cancel_mutator)
|
| 633 |
+
except (requests.RequestException, ValueError) as exc:
|
| 634 |
+
def error_mutator(state: dict):
|
| 635 |
+
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
|
| 636 |
+
clear_gofile_runtime_fields(entry)
|
| 637 |
+
entry["gofile_status"] = f"Upload GoFile gagal: {exc}"
|
| 638 |
+
entry["status_message"] = f"Upload GoFile gagal: {exc}"
|
| 639 |
+
add_event(state, "error", f"Upload GoFile gagal untuk {torrent_name}: {exc}")
|
| 640 |
+
|
| 641 |
+
update_state(error_mutator)
|
| 642 |
+
|
| 643 |
+
thread = threading.Thread(target=worker, daemon=True)
|
| 644 |
+
thread.start()
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
@app.route("/", methods=["GET"])
|
| 648 |
+
def index():
|
| 649 |
+
try:
|
| 650 |
+
torrents, payload = get_dashboard_data()
|
| 651 |
+
stats = payload["stats"]
|
| 652 |
+
events = payload["events"]
|
| 653 |
+
system_info = payload["system_info"]
|
| 654 |
+
except qbittorrentapi.APIConnectionError as exc:
|
| 655 |
+
torrents = []
|
| 656 |
+
events = []
|
| 657 |
+
stats = {
|
| 658 |
+
"connected": False,
|
| 659 |
+
"download_path": "-",
|
| 660 |
+
"version": "unreachable",
|
| 661 |
+
"torrent_count": 0,
|
| 662 |
+
"downloading": 0,
|
| 663 |
+
}
|
| 664 |
+
system_info = get_system_info()
|
| 665 |
+
flash(f"Gagal terhubung ke qBittorrent: {exc}", "error")
|
| 666 |
+
except qbittorrentapi.LoginFailed as exc:
|
| 667 |
+
torrents = []
|
| 668 |
+
events = []
|
| 669 |
+
stats = {
|
| 670 |
+
"connected": False,
|
| 671 |
+
"download_path": "-",
|
| 672 |
+
"version": "login failed",
|
| 673 |
+
"torrent_count": 0,
|
| 674 |
+
"downloading": 0,
|
| 675 |
+
}
|
| 676 |
+
system_info = get_system_info()
|
| 677 |
+
flash(f"Login qBittorrent gagal: {exc}", "error")
|
| 678 |
+
|
| 679 |
+
return render_template("index.html", torrents=torrents, stats=stats, events=events, system_info=system_info)
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
@app.route("/api/torrents", methods=["GET"])
|
| 683 |
+
def torrents_api():
|
| 684 |
+
try:
|
| 685 |
+
torrents, payload = get_dashboard_data()
|
| 686 |
+
return jsonify(
|
| 687 |
+
{
|
| 688 |
+
"success": True,
|
| 689 |
+
"stats": payload["stats"],
|
| 690 |
+
"events": payload["events"],
|
| 691 |
+
"torrents": torrents,
|
| 692 |
+
}
|
| 693 |
+
)
|
| 694 |
+
except (qbittorrentapi.APIConnectionError, qbittorrentapi.LoginFailed, qbittorrentapi.APIError) as exc:
|
| 695 |
+
return jsonify({"success": False, "error": str(exc) or "Gagal mengambil data torrent."}), 503
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
@app.route("/api/system", methods=["GET"])
|
| 699 |
+
def system_api():
|
| 700 |
+
return jsonify({"success": True, "system": get_system_info()})
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
@app.route("/api/system/speedtest", methods=["POST"])
|
| 704 |
+
def system_speedtest():
|
| 705 |
+
state = load_monitor_state()
|
| 706 |
+
if state.get("speedtest", {}).get("running"):
|
| 707 |
+
return action_response("Speedtest sedang berjalan.", ok=False, status_code=409)
|
| 708 |
+
|
| 709 |
+
update_state(lambda current: current.setdefault("speedtest", {}).update({"running": True, "status": "Memulai speedtest...", "result": {}}))
|
| 710 |
+
threading.Thread(target=run_speedtest_background, daemon=True).start()
|
| 711 |
+
return action_response("Speedtest dimulai.")
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
@app.route("/api/torrents/<torrent_hash>/pause", methods=["POST"])
|
| 715 |
+
def pause_torrent(torrent_hash: str):
|
| 716 |
+
try:
|
| 717 |
+
client = get_client()
|
| 718 |
+
client.torrents_pause(torrent_hashes=torrent_hash)
|
| 719 |
+
state = load_monitor_state()
|
| 720 |
+
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
|
| 721 |
+
entry["status_message"] = "Torrent sedang dijeda manual."
|
| 722 |
+
save_monitor_state(state)
|
| 723 |
+
return action_response("Torrent dijeda.")
|
| 724 |
+
except qbittorrentapi.APIError as exc:
|
| 725 |
+
return action_response(f"Gagal pause torrent: {exc}", ok=False, status_code=400)
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
@app.route("/api/torrents/<torrent_hash>/resume", methods=["POST"])
|
| 729 |
+
def resume_torrent(torrent_hash: str):
|
| 730 |
+
try:
|
| 731 |
+
client = get_client()
|
| 732 |
+
client.torrents_resume(torrent_hashes=torrent_hash)
|
| 733 |
+
state = load_monitor_state()
|
| 734 |
+
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
|
| 735 |
+
entry["last_progress_at"] = time.time()
|
| 736 |
+
entry["status_message"] = ""
|
| 737 |
+
save_monitor_state(state)
|
| 738 |
+
return action_response("Torrent dilanjutkan.")
|
| 739 |
+
except qbittorrentapi.APIError as exc:
|
| 740 |
+
return action_response(f"Gagal melanjutkan torrent: {exc}", ok=False, status_code=400)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
@app.route("/api/torrents/<torrent_hash>", methods=["DELETE"])
|
| 744 |
+
def delete_torrent(torrent_hash: str):
|
| 745 |
+
delete_files = request.args.get("with_files", "false").lower() == "true"
|
| 746 |
+
try:
|
| 747 |
+
client = get_client()
|
| 748 |
+
client.torrents_delete(delete_files=delete_files, torrent_hashes=torrent_hash)
|
| 749 |
+
state = load_monitor_state()
|
| 750 |
+
state.setdefault("torrents", {}).pop(torrent_hash, None)
|
| 751 |
+
if delete_files:
|
| 752 |
+
add_event(state, "warning", f"Torrent dengan hash {torrent_hash[:8]} dihapus beserta file hasil download.")
|
| 753 |
+
message = "Torrent dan file hasil download dihapus."
|
| 754 |
+
else:
|
| 755 |
+
add_event(state, "warning", f"Torrent dengan hash {torrent_hash[:8]} dihapus manual dari daftar.")
|
| 756 |
+
message = "Torrent dihapus dari daftar."
|
| 757 |
+
save_monitor_state(state)
|
| 758 |
+
return action_response(message)
|
| 759 |
+
except qbittorrentapi.APIError as exc:
|
| 760 |
+
return action_response(f"Gagal menghapus torrent: {exc}", ok=False, status_code=400)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
@app.route("/api/torrents/<torrent_hash>/upload-gofile", methods=["POST"])
|
| 764 |
+
def upload_torrent_to_gofile(torrent_hash: str):
|
| 765 |
+
try:
|
| 766 |
+
client = get_client()
|
| 767 |
+
torrents = client.torrents_info(torrent_hashes=torrent_hash)
|
| 768 |
+
if not torrents:
|
| 769 |
+
return action_response("Torrent tidak ditemukan.", ok=False, status_code=404)
|
| 770 |
+
|
| 771 |
+
torrent = torrents[0]
|
| 772 |
+
progress = float(getattr(torrent, "progress", 0) or 0)
|
| 773 |
+
if progress < 1:
|
| 774 |
+
return action_response("Upload ke GoFile hanya tersedia setelah download selesai.", ok=False, status_code=400)
|
| 775 |
+
|
| 776 |
+
content_path = Path(getattr(torrent, "content_path", "") or "")
|
| 777 |
+
if not content_path.exists():
|
| 778 |
+
return action_response("File hasil download tidak ditemukan di storage.", ok=False, status_code=404)
|
| 779 |
+
if content_path.is_dir():
|
| 780 |
+
return action_response("Upload GoFile saat ini hanya mendukung torrent single-file.", ok=False, status_code=400)
|
| 781 |
+
|
| 782 |
+
state = load_monitor_state()
|
| 783 |
+
entry = state.setdefault("torrents", {}).setdefault(torrent_hash, {})
|
| 784 |
+
if entry.get("gofile_uploading"):
|
| 785 |
+
return action_response("Upload GoFile masih berjalan.", ok=False, status_code=409)
|
| 786 |
+
|
| 787 |
+
entry["gofile_uploading"] = True
|
| 788 |
+
entry["gofile_progress"] = 0
|
| 789 |
+
entry["gofile_speed"] = ""
|
| 790 |
+
entry["gofile_eta_seconds"] = 0
|
| 791 |
+
entry["gofile_cancel_requested"] = False
|
| 792 |
+
entry["gofile_status"] = "Sedang upload ke GoFile..."
|
| 793 |
+
entry["status_message"] = "Sedang upload ke GoFile..."
|
| 794 |
+
save_monitor_state(state)
|
| 795 |
+
|
| 796 |
+
start_gofile_upload_background(torrent_hash, torrent.name, content_path)
|
| 797 |
+
return action_response("Upload ke GoFile dimulai.")
|
| 798 |
+
except qbittorrentapi.APIError as exc:
|
| 799 |
+
return action_response(f"Gagal memulai upload GoFile: {exc}", ok=False, status_code=502)
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
@app.route("/api/torrents/<torrent_hash>/cancel-gofile", methods=["POST"])
|
| 803 |
+
def cancel_gofile_upload(torrent_hash: str):
|
| 804 |
+
state = load_monitor_state()
|
| 805 |
+
entry = state.setdefault("torrents", {}).get(torrent_hash)
|
| 806 |
+
if not entry or not entry.get("gofile_uploading"):
|
| 807 |
+
return action_response("Upload GoFile tidak sedang berjalan.", ok=False, status_code=409)
|
| 808 |
+
|
| 809 |
+
entry["gofile_cancel_requested"] = True
|
| 810 |
+
entry["status_message"] = "Membatalkan upload GoFile..."
|
| 811 |
+
save_monitor_state(state)
|
| 812 |
+
return action_response("Pembatalan upload GoFile diproses.")
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
@app.route("/add-magnet", methods=["POST"])
|
| 816 |
+
def add_magnet():
|
| 817 |
+
magnet = request.form.get("magnet_link", "").strip()
|
| 818 |
+
if not magnet:
|
| 819 |
+
flash("Magnet link wajib diisi.", "error")
|
| 820 |
+
return redirect(url_for("index"))
|
| 821 |
+
|
| 822 |
+
try:
|
| 823 |
+
client = get_client()
|
| 824 |
+
client.torrents_add(urls=magnet, savepath=DOWNLOAD_PATH)
|
| 825 |
+
flash("Magnet link berhasil ditambahkan.", "success")
|
| 826 |
+
except qbittorrentapi.APIError as exc:
|
| 827 |
+
flash(f"Gagal menambahkan magnet link: {exc}", "error")
|
| 828 |
+
|
| 829 |
+
return redirect(url_for("index"))
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
@app.route("/upload-torrent", methods=["POST"])
|
| 833 |
+
def upload_torrent():
|
| 834 |
+
torrent_file = request.files.get("torrent_file")
|
| 835 |
+
if torrent_file is None or torrent_file.filename == "":
|
| 836 |
+
flash("Silakan pilih file torrent.", "error")
|
| 837 |
+
return redirect(url_for("index"))
|
| 838 |
+
|
| 839 |
+
if not torrent_file.filename.lower().endswith(".torrent"):
|
| 840 |
+
flash("File harus berekstensi .torrent.", "error")
|
| 841 |
+
return redirect(url_for("index"))
|
| 842 |
+
|
| 843 |
+
destination = UPLOAD_DIR / Path(torrent_file.filename).name
|
| 844 |
+
torrent_file.save(destination)
|
| 845 |
+
|
| 846 |
+
try:
|
| 847 |
+
client = get_client()
|
| 848 |
+
with destination.open("rb") as handle:
|
| 849 |
+
client.torrents_add(torrent_files=handle, savepath=DOWNLOAD_PATH)
|
| 850 |
+
flash("File torrent berhasil diunggah.", "success")
|
| 851 |
+
except qbittorrentapi.APIError as exc:
|
| 852 |
+
flash(f"Gagal menambahkan file torrent: {exc}", "error")
|
| 853 |
+
finally:
|
| 854 |
+
destination.unlink(missing_ok=True)
|
| 855 |
+
|
| 856 |
+
return redirect(url_for("index"))
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
if __name__ == "__main__":
|
| 860 |
+
app.run(host="0.0.0.0", port=WEB_PORT, debug=False)
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
app:
|
| 3 |
+
build:
|
| 4 |
+
context: .
|
| 5 |
+
dockerfile: Dockerfile
|
| 6 |
+
container_name: torrent-app
|
| 7 |
+
environment:
|
| 8 |
+
FLASK_SECRET_KEY: change-me
|
| 9 |
+
PORT: 5000
|
| 10 |
+
QBITTORRENT_HOST: 127.0.0.1
|
| 11 |
+
QBITTORRENT_PORT: 8080
|
| 12 |
+
QBITTORRENT_USERNAME: admin
|
| 13 |
+
QBITTORRENT_PASSWORD: adminadmin
|
| 14 |
+
QBITTORRENT_SAVE_PATH: /downloads
|
| 15 |
+
QBT_PROFILE: /config
|
| 16 |
+
ports:
|
| 17 |
+
- "5000:5000"
|
| 18 |
+
- "6881:6881"
|
| 19 |
+
- "6881:6881/udp"
|
| 20 |
+
volumes:
|
| 21 |
+
- ./downloads:/downloads
|
| 22 |
+
- ./qbittorrent/config:/config
|
| 23 |
+
restart: unless-stopped
|
entrypoint.sh
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
CONFIG_DIR="${QBT_PROFILE:-/config}"
|
| 5 |
+
DOWNLOAD_DIR="${QBITTORRENT_SAVE_PATH:-/downloads}"
|
| 6 |
+
DEFAULT_CONFIG="/defaults/qBittorrent.conf"
|
| 7 |
+
WEB_PORT="${PORT:-5000}"
|
| 8 |
+
|
| 9 |
+
mkdir -p "$CONFIG_DIR" "$DOWNLOAD_DIR" "$DOWNLOAD_DIR/incomplete"
|
| 10 |
+
|
| 11 |
+
if [[ ! -f "$CONFIG_DIR/qBittorrent.conf" ]]; then
|
| 12 |
+
cp "$DEFAULT_CONFIG" "$CONFIG_DIR/qBittorrent.conf"
|
| 13 |
+
fi
|
| 14 |
+
|
| 15 |
+
shutdown() {
|
| 16 |
+
if [[ -n "${WEB_PID:-}" ]] && kill -0 "$WEB_PID" 2>/dev/null; then
|
| 17 |
+
kill "$WEB_PID" 2>/dev/null || true
|
| 18 |
+
fi
|
| 19 |
+
if [[ -n "${QBT_PID:-}" ]] && kill -0 "$QBT_PID" 2>/dev/null; then
|
| 20 |
+
kill "$QBT_PID" 2>/dev/null || true
|
| 21 |
+
fi
|
| 22 |
+
wait || true
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
trap shutdown SIGINT SIGTERM
|
| 26 |
+
|
| 27 |
+
qbittorrent-nox --profile="$CONFIG_DIR" &
|
| 28 |
+
QBT_PID=$!
|
| 29 |
+
|
| 30 |
+
gunicorn \
|
| 31 |
+
--bind "0.0.0.0:${WEB_PORT}" \
|
| 32 |
+
--workers "${GUNICORN_WORKERS:-2}" \
|
| 33 |
+
--threads "${GUNICORN_THREADS:-4}" \
|
| 34 |
+
--timeout "${GUNICORN_TIMEOUT:-120}" \
|
| 35 |
+
app:app &
|
| 36 |
+
WEB_PID=$!
|
| 37 |
+
|
| 38 |
+
wait -n "$QBT_PID" "$WEB_PID"
|
| 39 |
+
EXIT_CODE=$?
|
| 40 |
+
shutdown
|
| 41 |
+
exit "$EXIT_CODE"
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Flask==3.1.1
|
| 2 |
+
qbittorrent-api==2025.7.0
|
| 3 |
+
requests==2.33.1
|
| 4 |
+
psutil==7.1.0
|
| 5 |
+
requests-toolbelt==1.0.0
|
| 6 |
+
gunicorn==23.0.0
|