Files
netflex/tools/mock_server.py
Tamas Csikel af4e21ee6f
Some checks failed
release / release (push) Failing after 18m38s
Netflex 0.1.2: new screens, and an ARM build for the Raspberry Pi
- Pages from the web app: search, my list, anime hub and anime details,
  settings; the home and detail screens moved under src/screens on the
  shared page model (src/page.rs, ui/page.slint).
- package.sh --arm cross-compiles support.bluefox.netflex-<version>-aarch64.tar.zst,
  which Fennec OS on ARM installs (docs/store.md). The release CI builds
  both: the GStreamer dev packages of amd64 and arm64 can't be installed
  together, so it swaps them between the two builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:33:29 +01:00

572 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""A stand-in Netflex server for developing the TV app without one.
Real catalog data (Cinemeta, artwork through /api/img) on the same API the
app uses; sign-in with any user name and the password "netflex"; playback
streams a local video file with range requests.
python3 tools/mock_server.py [--port 7880] [--video test.mkv]
NETFLEX_SERVER=http://localhost:7880 cargo run
Standard library only. Not a real server: no torrents, no nCore.
"""
import argparse
import json
import os
import re
import threading
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
CATALOGS = "https://cinemeta-catalogs.strem.io/top/catalog"
CINEMETA = "https://v3-cinemeta.strem.io"
TOKEN = "dev-token"
GENRES = ["Action", "Comedy", "Drama", "Thriller", "Sci-Fi", "Animation", "Crime", "Horror", "Romance", "Documentary"]
GENRE_HU = {"Action": "Akció", "Comedy": "Vígjáték", "Drama": "Dráma", "Thriller": "Thriller", "Sci-Fi": "Sci-fi",
"Animation": "Animáció", "Crime": "Krimi", "Horror": "Horror", "Romance": "Romantikus", "Documentary": "Dokumentum"}
cache = {}
cache_lock = threading.Lock()
my_list = {}
progress = {}
VIDEO = None
ANILIST = "https://graphql.anilist.co"
ANIME_FIELDS = """id idMal title { romaji english native } coverImage { extraLarge color } bannerImage format status episodes
season seasonYear averageScore genres description duration studios(isMain: true) { nodes { name } }
nextAiringEpisode { episode airingAt }"""
anime_progress = {}
anime_list = {}
settings = {"subtitleLang": "hu", "autoNext": True, "autoSkipIntro": False, "transcode": "auto"}
anime_prefs = {"preferredResolution": 1080, "preferredGroups": ["SubsPlease"], "preferDub": False, "subtitleLang": "en"}
seed_rules = {"minSeedHours": 72, "minRatio": 1.0, "marginHours": 2, "marginRatio": 0.05, "requireNcoreConfirmation": True,
"maxDiskGB": 500, "seasonPackMode": "whole", "maxActiveDownloads": 3}
source_prefs = {"language": "dub", "maxResolution": 1080, "maxSize": 0, "allowHdr": False}
crawl = {"latest": True}
tmdb = {"on": False}
users = [{"id": 1, "username": "dev", "name": "Dev", "isAdmin": True, "sessions": 2, "lastSeenAt": "2026-10-25T10:00:00Z"},
{"id": 2, "username": "anna", "name": "Anna", "isAdmin": False, "sessions": 1, "lastSeenAt": "2026-10-24T19:30:00Z"}]
vpn = {"enabled": True, "pf": True}
torrents = [
{"infoHash": "a" * 40, "name": "Dune.Part.Two.2024.1080p.WEB-DL.HUN.ENG", "size": 6.1e9, "state": "seeding", "keep": False,
"completedAt": "2026-10-23T18:00:00Z", "seedingSeconds": 140000, "ratio": 0.62, "eligibleAt": "2026-10-26T20:00:00Z",
"ncoreCheckedAt": "2026-10-25T09:00:00Z", "ncoreFound": True, "ncoreRemainingSeconds": 120000, "ncoreHnr": False,
"live": {"progress": 1, "downloadSpeed": 0, "uploadSpeed": 420000}, "inUse": False, "pausedForPlayback": False},
{"infoHash": "b" * 40, "name": "The.Office.US.S02.1080p.WEB-DL.HUN", "size": 18e9, "state": "downloading", "keep": False,
"seedingSeconds": 0, "ratio": 0.0, "live": {"progress": 0.41, "downloadSpeed": 5.2e6, "uploadSpeed": 80000}, "inUse": True,
"pausedForPlayback": False},
]
def anilist(query, variables):
key = json.dumps([query, variables], sort_keys=True)
with cache_lock:
if key in cache:
return cache[key]
req = urllib.request.Request(ANILIST, data=json.dumps({"query": query, "variables": variables}).encode(),
headers={"Content-Type": "application/json", "Accept": "application/json", "User-Agent": "netflex-mock"})
with urllib.request.urlopen(req, timeout=20) as r:
value = json.loads(r.read())["data"]
with cache_lock:
cache[key] = value
return value
def anime(m):
cover = m.get("coverImage") or {}
return {"id": m["id"], "idMal": m.get("idMal"), "title": m["title"], "coverImage": cover.get("extraLarge"),
"coverColor": cover.get("color"), "bannerImage": m.get("bannerImage"), "format": m.get("format"),
"status": m.get("status"), "episodes": m.get("episodes"), "season": m.get("season"), "seasonYear": m.get("seasonYear"),
"averageScore": m.get("averageScore"), "genres": m.get("genres") or [], "description": m.get("description"),
"duration": m.get("duration"), "studios": [n["name"] for n in ((m.get("studios") or {}).get("nodes") or [])],
"nextAiringEpisode": m.get("nextAiringEpisode")}
def anime_page(sort, page=1, search=None, genres=None, season=None, year=None):
args = {"sort": [sort], "page": page}
q = "query($sort:[MediaSort],$page:Int"
f = "type: ANIME, sort: $sort, isAdult: false"
if search:
q += ",$search:String"
f += ", search: $search"
args["search"] = search
if genres:
q += ",$genres:[String]"
f += ", genre_in: $genres"
args["genres"] = genres
if season:
q += ",$season:MediaSeason,$year:Int"
f += ", season: $season, seasonYear: $year"
args["season"] = season
args["year"] = year
q += f"){{ Page(page:$page, perPage:30) {{ pageInfo {{ hasNextPage total }} media({f}) {{ {ANIME_FIELDS} }} }} }}"
d = anilist(q, args)["Page"]
return {"items": [anime(m) for m in d["media"]], "page": page, "hasNextPage": d["pageInfo"]["hasNextPage"], "total": d["pageInfo"]["total"]}
def anime_detail(i):
rel = "relations { edges { relationType node { id title { romaji english native } format episodes seasonYear coverImage { extraLarge } } } }"
return anilist(f"query($id:Int){{ Media(id:$id, type: ANIME) {{ {ANIME_FIELDS} {rel} }} }}", {"id": i})["Media"]
def aired(m):
n = m.get("nextAiringEpisode")
return (n["episode"] - 1) if n else (m.get("episodes") or 1)
def fetch(url, binary=False):
with cache_lock:
if url in cache:
return cache[url]
req = urllib.request.Request(url, headers={"User-Agent": "netflex-mock"})
with urllib.request.urlopen(req, timeout=20) as r:
data = r.read()
value = data if binary else json.loads(data)
with cache_lock:
cache[url] = value
return value
def ctype(t):
return "series" if t == "tv" else "movie"
def summary(t, m):
year_label = m.get("releaseInfo") or m.get("year")
year = None
try:
year = int(str(year_label or m.get("released") or "")[:4])
except ValueError:
pass
try:
rating = float(m.get("imdbRating") or 0) or None
except ValueError:
rating = None
return {
"type": "tv" if m.get("type") == "series" else ("movie" if m.get("type") == "movie" else t),
"id": m.get("imdb_id") or m.get("id"),
"tmdbId": None,
"title": m.get("name") or "Névtelen",
"originalTitle": None,
"overview": m.get("description"),
"poster": m.get("poster"),
"backdrop": m.get("background"),
"logo": m.get("logo"),
"year": year,
"yearLabel": str(year_label).replace("-", "–") if year_label else None,
"rating": rating,
"genres": m.get("genres") or m.get("genre") or [],
}
def catalog(t, genre=None, skip=0):
path = f"{CATALOGS}/{ctype(t)}/top"
extra = []
if genre:
extra.append("genre=" + urllib.parse.quote(genre))
if skip:
extra.append(f"skip={skip}")
url = path + ("/" + "&".join(extra) if extra else "") + ".json"
metas = fetch(url).get("metas", [])
return [summary(t, m) for m in metas]
def episodes(m):
out = []
for v in m.get("videos") or []:
try:
s, e = int(v.get("season")), int(v.get("episode") or v.get("number"))
except (TypeError, ValueError):
continue
out.append({"season": s, "episode": e, "name": v.get("name") or v.get("title"),
"overview": v.get("overview") or v.get("description"),
"airDate": (v.get("released") or v.get("firstAired") or "")[:10] or None,
"runtime": None, "still": v.get("thumbnail"), "rating": None})
return sorted(out, key=lambda x: (x["season"], x["episode"]))
def detail(t, id_):
m = fetch(f"{CINEMETA}/meta/{ctype(t)}/{id_}.json").get("meta") or {}
eps = episodes(m)
seasons = sorted({e["season"] for e in eps if e["season"] > 0})
d = summary(t, m)
try:
runtime = int(re.sub(r"\D", "", str(m.get("runtime") or "")) or 0) or None
except ValueError:
runtime = None
d.update({
"runtime": runtime, "tagline": None, "status": m.get("status"),
"cast": (m.get("cast") or [])[:15], "directors": m.get("director") or [], "trailerKey": None,
"seasons": [{"number": n, "name": f"{n}. évad", "episodeCount": sum(1 for e in eps if e["season"] == n),
"airedCount": sum(1 for e in eps if e["season"] == n), "airDate": None, "poster": None} for n in seasons],
"numberOfSeasons": len(seasons) if t == "tv" else None,
"lastEpisodeToAir": None, "nextEpisodeToAir": None, "huSource": None,
})
return d, eps
class Handler(BaseHTTPRequestHandler):
server_version = "netflex-mock"
def log_message(self, fmt, *args):
print("mock:", self.command, self.path.split("?")[0], fmt % args if "%" in fmt else "")
def authed(self, q):
auth = self.headers.get("Authorization", "")
return auth == f"Bearer {TOKEN}" or q.get("token", [""])[0] == TOKEN
def send_json(self, value, status=200):
body = json.dumps(value).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def body(self):
n = int(self.headers.get("Content-Length") or 0)
return json.loads(self.rfile.read(n) or b"{}") if n else {}
def do_GET(self):
self.route("GET")
def do_POST(self):
self.route("POST")
def do_PUT(self):
self.route("PUT")
def do_DELETE(self):
self.route("DELETE")
def do_HEAD(self):
self.route("HEAD")
def route(self, method):
url = urllib.parse.urlparse(self.path)
q = urllib.parse.parse_qs(url.query)
p = url.path
try:
if p == "/api/auth/status":
return self.send_json({"setupRequired": False, "user": {"id": 1, "username": "dev", "name": "Dev", "isAdmin": True} if self.authed(q) else None})
if p == "/api/auth/login" and method == "POST":
b = self.body()
if b.get("password") != "netflex":
return self.send_json({"error": "Hibás felhasználónév vagy jelszó"}, 401)
return self.send_json({"token": TOKEN, "user": {"id": 1, "username": b.get("username", "dev"), "name": "Dev", "isAdmin": True}})
if not self.authed(q):
return self.send_json({"error": "Bejelentkezés szükséges", "code": "unauthenticated"}, 401)
r = self.account(method, p) or self.anime(method, p, q)
if r is not None:
return r
if p == "/api/img":
return self.image(q.get("u", [""])[0])
if p.startswith("/api/stream/"):
return self.stream(method)
if p == "/api/settings":
return self.send_json({"subtitleLang": "hu", "autoNext": True})
if p == "/api/home":
movies, series = catalog("movie")[:20], catalog("tv")[:20]
cont = [{"title": series[0], "season": 1, "episode": 2, "position": 900, "duration": 2700, "updatedAt": ""},
{"title": movies[3], "season": None, "episode": None, "position": 3100, "duration": 7200, "updatedAt": ""}]
return self.send_json({"rows": [{"id": "popular-movie", "title": "Népszerű filmek", "items": movies},
{"id": "popular-tv", "title": "Népszerű sorozatok", "items": series},
{"id": "featured-movie", "title": "Kiemelt filmek", "items": catalog("movie", skip=20)[:20]}],
"continueWatching": cont})
if p == "/api/genres":
return self.send_json([{"id": g, "name": GENRE_HU[g]} for g in GENRES])
if p == "/api/browse":
t = q.get("type", ["movie"])[0]
page = int(q.get("page", ["1"])[0])
items = catalog(t, q.get("genre", [None])[0], skip=(page - 1) * 50)
return self.send_json({"page": page, "hasMore": len(items) >= 50, "items": items})
if p == "/api/search":
term = urllib.parse.quote(q.get("q", [""])[0])
items = []
for t in ("movie", "tv"):
metas = fetch(f"{CINEMETA}/catalog/{ctype(t)}/top/search={term}.json").get("metas", [])
items += [summary(t, m) for m in metas[:16]]
return self.send_json({"page": 1, "hasMore": False, "items": items})
m = re.fullmatch(r"/api/title/(movie|tv)/([^/]+)", p)
if m:
return self.send_json(detail(m[1], m[2])[0])
m = re.fullmatch(r"/api/title/tv/([^/]+)/season/(\d+)", p)
if m:
eps = [e for e in detail("tv", m[1])[1] if e["season"] == int(m[2])]
return self.send_json({"number": int(m[2]), "name": f"{m[2]}. évad", "episodes": eps})
m = re.fullmatch(r"/api/progress/(movie|tv)/([^/]+)", p)
if m:
return self.send_json(progress.get(f"{m[1]}:{m[2]}", []))
if p == "/api/progress" and method == "PUT":
b = self.body()
key = f"{b['type']}:{b['titleId']}"
rows = [r for r in progress.get(key, []) if not (r["season"] == b.get("season", 0) and r["episode"] == b.get("episode", 0))]
dur = b.get("duration")
rows.append({"season": b.get("season", 0), "episode": b.get("episode", 0), "position": b["position"], "duration": dur,
"completed": bool(dur and b["position"] / dur >= 0.92), "infoHash": None, "fileIndex": None})
progress[key] = rows
return self.send_json({"ok": True})
if p == "/api/lists/status":
return self.send_json({k: {"listed": True, "watchedEpisodes": 0, "watched": False} for k in my_list})
if p == "/api/lists/mine":
return self.send_json([{"title": v, "addedAt": None, "lastWatchedAt": None, "watchedEpisodes": 0} for v in my_list.values()])
m = re.fullmatch(r"/api/lists/mine/(movie|tv)/([^/]+)", p)
if m:
if method == "PUT":
my_list[f"{m[1]}:{m[2]}"] = summary(m[1], fetch(f"{CINEMETA}/meta/{ctype(m[1])}/{m[2]}.json").get("meta") or {})
else:
my_list.pop(f"{m[1]}:{m[2]}", None)
return self.send_json({"ok": True})
if p.startswith("/api/sources/"):
return self.send_json({"imdbId": None, "searchedBy": "imdb", "candidates": [
{"torrent": {"id": 1, "name": "Mock.Release.2024.1080p.WEB-DL.HUN.ENG", "category": "hd_hun", "size": 4.2e9, "seeders": 42,
"leechers": 1, "uploadedAt": None, "imdbId": None, "imdbRating": None, "freeleech": False},
"parsed": {}, "score": 1, "reasons": [], "pack": False, "local": "seeding"}]})
if p == "/api/play/start":
return self.send_json({"infoHash": "0" * 40, "fileIndex": 0, "fileName": os.path.basename(VIDEO or "none.mkv"), "size": 1})
m = re.fullmatch(r"/api/media/[0-9a-f]{40}/\d+/probe", p)
if m:
if not VIDEO:
return self.send_json({"error": "A mock szervernek nincs videója (--video)"}, 422)
return self.send_json({"durationSec": None, "tracks": [], "audioLangs": [], "subtitleLangs": [], "englishDub": False,
"hungarianDub": False, "attachments": [], "fileName": os.path.basename(VIDEO),
"fileSize": os.path.getsize(VIDEO), "local": True, "audioDelayMs": 0})
if re.fullmatch(r"/api/media/[0-9a-f]{40}/\d+/audio-delay", p):
return self.send_json({"audioDelayMs": self.body().get("ms", 0)})
if p.startswith("/api/torrent/"):
return self.send_json({"ready": True, "fileProgress": 1, "downloadSpeed": 0})
return self.send_json({"error": "Nem található"}, 404)
except Exception as e: # noqa: BLE001 - a dev tool: report everything
print("mock: error", p, e)
return self.send_json({"error": f"mock: {e}"}, 502)
def j(self, value, status=200):
self.send_json(value, status)
return True
def account(self, method, p):
"""Settings, users, sessions and the admin's server setup."""
j = self.j
if p == "/api/health":
return j({"ok": True, "vpn": "vpn" if vpn["enabled"] else "blocked"})
if p == "/api/settings":
if method == "PUT":
settings.update(self.body())
return j(settings)
if p == "/api/auth/sessions":
return j([{"id": 1, "device": "Fennec OS TV", "ip": "192.168.1.20", "createdAt": "2026-10-01T10:00:00Z", "lastSeenAt": "2026-10-25T10:00:00Z", "current": True},
{"id": 2, "device": "Chrome · Windows", "ip": "192.168.1.11", "createdAt": "2026-09-12T10:00:00Z", "lastSeenAt": "2026-10-20T21:00:00Z", "current": False}])
if p.startswith("/api/auth/sessions/") or p == "/api/auth/logout":
return j({"ok": True})
if p == "/api/users":
if method == "POST":
b = self.body()
users.append({"id": len(users) + 1, "username": b["username"], "name": b.get("name") or b["username"], "isAdmin": False, "sessions": 0, "lastSeenAt": None})
return j({"ok": True})
return j(users)
m = re.fullmatch(r"/api/users/(\d+)(/password)?", p)
if m:
if method == "DELETE":
users[:] = [u for u in users if u["id"] != int(m[1])]
return j({"ok": True})
if p == "/api/config":
return j({"seedRules": seed_rules, "seedRuleDefaults": {**seed_rules, "minSeedHours": 72, "minRatio": 1.0},
"sourcePrefs": source_prefs, "crawl": crawl, "tmdbConfigured": tmdb["on"]})
targets = {"/api/config/seed-rules": seed_rules, "/api/config/source-prefs": source_prefs, "/api/config/crawl": crawl}
if p in targets:
targets[p].update(self.body())
return j({"ok": True})
if p == "/api/config/tmdb-key":
tmdb["on"] = bool(self.body().get("key"))
return j({"ok": True})
if re.fullmatch(r"/api/ncore/torrents/\d+/languages", p):
return j({"audio": ["hu", "en"], "subs": ["hu", "en"], "found": True})
if p.startswith("/api/ncore"):
return j({"configured": True, "username": "devuser", "loggedIn": True, "hasPasskey": True, "circuit": {"state": "ok"},
"minIntervalMs": 2500, "lastRequestAt": "2026-10-25T09:58:00Z", "latestCrawl": {"lastRun": "2026-10-25T09:30:00Z"}})
if p.startswith("/api/vpn"):
if p == "/api/vpn" and method == "PUT":
b = self.body()
if "enabled" in b:
vpn["enabled"] = b["enabled"]
if "portForwarding" in b:
vpn["pf"] = b["portForwarding"]
on = vpn["enabled"]
check = {"ok": True, "checkedAt": "2026-10-25T09:55:00Z", "publicIp": {"ip": "185.10.20.31", "country": "HU", "city": "Budapest", "org": "Proton AG"},
"realIp": "84.1.2.3", "ipChanged": True, "routeDevice": "wg0", "dnsServers": ["10.2.0.1"], "dnsThroughTunnel": True}
return j({"supported": True, "settings": {"enabled": on}, "state": "connected" if on else "off",
"profile": {"name": "proton-hu-12.conf", "importedAt": "2026-09-01T12:00:00Z", "server": "185.10.20.30:51820", "addresses": ["10.2.0.2/32"]},
"check": check if on else None,
"tunnel": {"interface": "wg0", "lastHandshake": "2026-10-25T09:59:00Z", "transfer": {"rx": 52e9, "tx": 31e9}} if on else None,
"traffic": {"path": "vpn" if on else "blocked", "reason": None if on else "A VPN ki van kapcsolva."},
"portForwarding": {"enabled": vpn["pf"], "port": 51413 if vpn["pf"] and on else None, "gateway": "10.2.0.1", "lastRenewal": "2026-10-25T09:59:30Z"}})
if p == "/api/torrents":
return j({"rules": seed_rules, "engine": {"ready": True}, "seedKeeper": {"lastActivityAt": "2026-10-25T09:00:00Z"}, "diskUsed": 24e9, "items": torrents})
m = re.fullmatch(r"/api/torrents/([0-9a-f]{40})(/keep)?", p)
if m and m[2]:
for t in torrents:
if t["infoHash"] == m[1]:
t["keep"] = self.body().get("keep", False)
return j({"ok": True})
if m and method == "DELETE":
torrents[:] = [t for t in torrents if t["infoHash"] != m[1]]
return j({"ok": True})
if p == "/api/torrents/check":
return j({"ok": True})
if p == "/api/continue":
return j([])
if p == "/api/history":
return j([{"title": v, "addedAt": None, "lastWatchedAt": None, "watchedEpisodes": 2} for v in my_list.values()])
if re.fullmatch(r"/api/progress/(movie|tv)/([^/]+)/watched", p):
return j({"ok": True})
return None
def anime(self, method, p, q):
"""Anime: real AniList data, made-up nyaa releases."""
j = self.j
if p == "/api/anime/home":
trending = anime_page("TRENDING_DESC")["items"]
popular = anime_page("POPULARITY_DESC")["items"]
season = anime_page("POPULARITY_DESC", season="FALL", year=2026)["items"]
cont = [{"anime": trending[0], "episode": 3, "position": 400, "duration": 1420}] if trending else []
return j({"rows": [{"id": "season", "title": "Ősz 2026", "items": season}, {"id": "trending", "title": "Felkapott", "items": trending},
{"id": "popular", "title": "Mindenkori kedvencek", "items": popular}],
"continueWatching": cont, "season": {"season": "FALL", "year": 2026}, "source": "anilist"})
if p == "/api/anime/browse":
sorts = {"popularity": "POPULARITY_DESC", "score": "SCORE_DESC", "trending": "TRENDING_DESC", "newest": "START_DATE_DESC",
"relevance": "SEARCH_MATCH", "title": "TITLE_ROMAJI"}
sort = sorts.get(q.get("sort", ["popularity"])[0], "POPULARITY_DESC")
genres = [x for x in q.get("genres", [""])[0].split(",") if x]
return j(anime_page(sort, int(q.get("page", ["1"])[0]), q.get("search", [None])[0], genres or None))
if p == "/api/anime/taxonomy":
return j({"genres": ["Action", "Adventure", "Comedy", "Drama", "Fantasy", "Romance", "Sci-Fi", "Slice of Life", "Sports", "Mystery"],
"tags": [{"name": "Isekai", "category": "Theme", "description": ""}, {"name": "Mecha", "category": "Theme", "description": ""}]})
if p == "/api/anime/prefs":
if method == "PUT":
anime_prefs.update(self.body())
return j(anime_prefs)
if p == "/api/anime/torrents":
return j({"graceSeconds": 900, "items": [{"infoHash": "c" * 40, "name": "[SubsPlease] Frieren - 03 (1080p).mkv", "size": 1.4e9, "episode": 3,
"inUse": False, "lastUsedAt": "2026-10-25T09:40:00Z"}]})
if p == "/api/anime/library":
return j([{"anime": v} for v in anime_list.values()])
if p == "/api/anime/progress":
b = self.body()
rows = [r for r in anime_progress.get(b["animeId"], []) if r["episode"] != b["episode"]]
dur = b.get("duration")
rows.append({"episode": b["episode"], "position": b["position"], "duration": dur, "completed": bool(dur and b["position"] / dur >= 0.9)})
anime_progress[b["animeId"]] = rows
return j({"ok": True})
if p == "/api/anime/play/start":
return j({"infoHash": "1" * 40, "fileIndex": 0, "fileName": os.path.basename(VIDEO or "none.mkv")})
if re.fullmatch(r"/api/anime/torrents/[0-9a-f]{40}/keepalive", p):
return j({"ok": True})
m = re.fullmatch(r"/api/anime/(\d+)(/[a-z]+)?(/\d+/skip)?", p)
if not m:
return None
i, sub = int(m[1]), m[2] or ""
if sub == "/list":
if method == "PUT":
anime_list[i] = anime(anime_detail(i))
else:
anime_list.pop(i, None)
return j({"ok": True})
if sub == "/watched":
return j({"ok": True})
if sub == "/progress":
return j(anime_progress.get(i, []))
d = anime_detail(i)
if sub == "":
a = anime(d)
a["mal"] = {"score": (d.get("averageScore") or 0) / 10, "scoredBy": 120000, "rank": 50}
return j(a)
if sub == "/franchise":
edges = [e for e in d["relations"]["edges"] if e["relationType"] in ("PREQUEL", "SEQUEL") and e["node"]["format"] in ("TV", "MOVIE", "ONA")]
out = [{"id": d["id"], "title": d["title"], "format": d["format"], "episodes": d.get("episodes"), "seasonYear": d.get("seasonYear"),
"coverImage": d["coverImage"]["extraLarge"], "seasonNumber": 1 if edges else None, "current": True}]
for n, e in enumerate(edges):
x = e["node"]
out.append({"id": x["id"], "title": x["title"], "format": x["format"], "episodes": x.get("episodes"), "seasonYear": x.get("seasonYear"),
"coverImage": (x.get("coverImage") or {}).get("extraLarge"), "seasonNumber": n + 2 if x["format"] != "MOVIE" else None})
return j(out)
if sub == "/episodes" and m[3]:
return j([{"type": "op", "start": 85, "end": 175, "episodeLength": 1420}, {"type": "ed", "start": 1300, "end": 1390, "episodeLength": 1420}])
if sub == "/episodes":
n = aired(d)
return j({"aired": n, "total": d.get("episodes"),
"episodes": [{"number": k, "title": f"{k}. epizód", "overview": "Egy rész leírása.", "runtime": d.get("duration")} for k in range(1, n + 1)]})
if sub == "/releases":
n = aired(d)
groups = [("SubsPlease", 1080), ("Erai-raws", 1080), ("ToonsHub", 2160)]
name = d["title"]["romaji"]
eps = [{"number": k, "sources": [{"infoHash": f"{k:040x}", "nyaaId": k * 10 + n2, "torrentTitle": f"[{g}] {name} - {k:02d} ({r}p).mkv", "group": g,
"resolution": r, "seeders": 300 - 40 * n2, "isBatch": False, "sizeBytes": 1.4e9 * (2 if r > 1080 else 1)}
for n2, (g, r) in enumerate(groups)]} for k in range(1, n + 1)]
return j({"queries": [name], "groups": [{"key": f"{g}|{r}", "episodes": list(range(1, n + 1)), "lang": {"englishDub": g == "ToonsHub"}} for g, r in groups],
"selectedGroup": "SubsPlease|1080", "episodes": eps})
return None
def image(self, u):
if not u.startswith("https://"):
return self.send_json({"error": "bad url"}, 400)
data = fetch(u, binary=True)
self.send_response(200)
self.send_header("Content-Type", "image/jpeg" if data[:2] == b"\xff\xd8" else "image/png")
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "public, max-age=31536000")
self.end_headers()
self.wfile.write(data)
def stream(self, method):
if not VIDEO:
return self.send_json({"error": "no video"}, 404)
size = os.path.getsize(VIDEO)
start, end = 0, size - 1
rng = re.match(r"bytes=(\d*)-(\d*)", self.headers.get("Range", ""))
if rng:
if rng[1] == "" and rng[2]:
start = max(0, size - int(rng[2]))
else:
start = int(rng[1] or 0)
if rng[2]:
end = min(int(rng[2]), size - 1)
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
else:
self.send_response(200)
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Type", "video/x-matroska")
self.send_header("Content-Length", str(end - start + 1))
self.end_headers()
if method == "HEAD":
return
with open(VIDEO, "rb") as f:
f.seek(start)
left = end - start + 1
try:
while left > 0:
chunk = f.read(min(1 << 16, left))
if not chunk:
break
self.wfile.write(chunk)
left -= len(chunk)
except (BrokenPipeError, ConnectionResetError):
pass
def main():
global VIDEO
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--port", type=int, default=7880)
ap.add_argument("--video", help="a local video file to stream for every title")
args = ap.parse_args()
VIDEO = args.video
print(f"mock Netflex on http://localhost:{args.port} (password: netflex)")
ThreadingHTTPServer(("0.0.0.0", args.port), Handler).serve_forever()
if __name__ == "__main__":
main()