Compare commits

...
1 Commits
Author SHA1 Message Date
4DBug f37985b4c8 push 2026-10-27 05:49:38 -05:00
109 changed files with 22810 additions and 6143 deletions

No files matched your search

+2 -1
View File
@@ -1,2 +1,3 @@
node_modules/
result/
result*
config.json
+12
View File
@@ -0,0 +1,12 @@
{
"tmdbKey": "YOUR_TMDB_API_KEY",
"enabledProviders": [],
"disabledProviders": ["torrentio"],
"timeoutMs": 20000,
"filters": {
"minQuality": "any",
"audioCodec": "any",
"subtitles": "any",
"subtitleLang": ""
}
}
-15
View File
@@ -1,15 +0,0 @@
{
"tmdbKey": "ac014b130a8e6344c91dff4e68b18d47",
"enabledProviders": [
"cineby",
"videasy",
"vidfast"
],
"timeoutMs": 30000,
"filters": {
"minQuality": "any",
"audioCodec": "any",
"subtitles": "any",
"subtitleLang": ""
}
}
+223
View File
@@ -0,0 +1,223 @@
# bug tv v5 — API & module contract
This is the single source of truth every workstream codes against. If you need to
deviate, keep the deviation backwards compatible and note it at the bottom of this file.
## Runtime
- Node 22+, CommonJS in `src/` (providers are CommonJS). No TypeScript, no bundler.
- npm deps allowed: `cheerio-without-node-native`, `crypto-js` (providers), `undici`
(keep-alive agent), `webtorrent` (torrents). `ffmpeg`/`ffprobe` come from PATH
(`cfg.remux.ffmpeg` / `cfg.remux.ffprobe`).
- Static site in `web/` is vanilla ES modules (`<script type="module">`), no build step.
## Server wiring (already written — `src/server.js`)
- Each `src/routes/<name>.js` exports `{ routes: [{ method, path, handler(req, res, ctx) }], init?(cfg) }`.
`path` is an exact string or a RegExp; capture groups → `ctx.params` (URI-decoded).
`ctx = { cfg, url, params }`. Loaded modules: `health providers streams proxy torrent remux subs openapi`.
- Helpers in `src/http.js`: `send(req,res,status,body,type,extraHeaders)` (auto br/gzip for text >1KB),
`json(req,res,status,obj)`, `error(req,res,status,msg,extra)`, `sse(req,res)` → `{event(name,data), close(), closed}`, `CORS` headers object.
- `src/sign.js`: `sign(obj) → token`, `verify(token) → obj|null` (HMAC, URL-safe, no `/`).
- `src/config.js` `loadConfig()` → cfg:
```
{ host, port, tmdbKey, enabledProviders: [..] ([] = all), disabledProviders: [..] (default ["torrentio"]), providerSettings: {..} (→ global.SCRAPER_SETTINGS),
timeoutMs, workers (0 = auto, min(cpus,4)), cacheTtlSec, secret,
torrent: { enable, cacheDir, maxSizeGB }, remux: { enable, ffmpeg, ffprobe },
filters: { minQuality, audioCodec, subtitles, subtitleLang } }
```
Config file path: `$BUG_TV_CONFIG` or `./config.json`.
## Signed URL formats (owned by media workstream, consumed by scrape workstream)
All are relative to the API base; the client resolves them against its configured base.
| Purpose | URL | Token payload |
|---|---|---|
| proxy (any http media, playlists, keys, segments) | `/v1/p/<token>/<path-and-query-of-upstream>` | `{ o: "https://upstream.origin", h: {headers} }` |
| remux (mkv/avi/etc → fragmented MP4) | `/v1/remux/<token>?start=<sec>` | `{ u: "absolute upstream url", h: {headers} }` |
| remux probe | `/v1/remux/<token>/probe` → `{ duration, video:{codec,width,height}, audio:[{index,codec,lang,channels}], subtitles:[{index,codec,lang,title}] }` | same |
| torrent stream | `/v1/torrent/<token>/stream?start=<sec>` | `{ m: "magnet:…", s?: season, e?: episode, f?: fileIdx }` |
| torrent status | `/v1/torrent/<token>/status` → `{ ready, name, file:{idx,name,size,container,remux}, peers, downSpeed, progress, buffered }` | same |
| torrent files | `/v1/torrent/<token>/files` → `{ files:[{idx,name,size}] }` | same |
| subtitles → VTT | `/v1/subs/<token>` (always `text/vtt`; SRT/ASS converted) | `{ u, h }` |
Proxy rules: path-based so relative URIs inside m3u8 resolve to the same token naturally;
only absolute/cross-origin URIs inside playlists are rewritten (new token). Range requests are
passed through. Playlists may be cached ~5s; segments are never buffered in memory (stream pipe).
Remux responses set header `X-Bug-Tv-Offset: <start>` so the player can offset its clock;
seeking = reload with `?start=`. Torrent `/stream` range-serves browser-native files (mp4/webm) and
remuxes others (honouring `?start=`); `status.file.remux` tells the client which mode it is.
`src/media/playback.js` (media workstream) exports
`playbackFor(stream) → { kind, url, fallback?, status? }` and `subtitleUrl(sub, headers) → string`,
called by the scrape workstream during normalization:
- `kind`: `"hls" | "file" | "remux" | "torrent"`
- `hls`/`file`: if the stream needs no headers beyond User-Agent, `url` = raw upstream URL (direct
play, zero server cost) and `fallback` = proxy URL; otherwise `url` = proxy URL, no fallback.
- `remux`: types mkv/avi/other non-browser containers → `url` = remux URL.
- `torrent`: `magnet:` URLs (or `infoHash`) → `url` = torrent stream URL, `status` = status URL.
## Endpoints
### `GET /v1/streams?tmdb=<id>&type=movie|tv&season=&episode=&providers=a,b`
Default response is **SSE**. Events, in order:
- `meta` → `{ tmdb, type, season, episode, providers: [names], timeoutMs, cached: [names] }`
- `streams` (0..n, one per provider that returned something) → `{ provider, ms, streams: [Stream] }`
- `provider` (one per provider) → `{ name, status: "ok"|"empty"|"error"|"timeout", ms, count, error? }`
- `done` → `{ total, ms }` then the connection closes.
Cached provider results are emitted immediately. Client disconnect aborts outstanding scrapes
whose results won't be cached (scrapes still in flight are allowed to finish into the cache).
`?format=json` or `Accept: application/json` (without `text/event-stream`) → aggregated:
`{ tmdb_id, type, season, episode, total, streams: [Stream], providerErrors: {name: msg} }`.
**Stream**:
```
{ id, // stable hash of provider+url
provider, name, title,
quality, // "1080p" | "2160p" | "" …
pixels, // 2160|1080|720|480|null (parsed from quality, else name/title)
audio, // aac|ac3|dts|opus|flac|mp3|multi|null
type, // m3u8|mp4|webm|mkv|avi|magnet|other
size, // bytes (number) or 0
sizeText, // human string if provider only gave text
language, // "" if unknown
seeds, // number|null (torrents)
subtitles: [{ url /* /v1/subs/… */, lang, label }],
playback: { kind, url, fallback?, status? } }
```
Ordering within an event: pixels desc, then provider health score.
### `GET /v1/prefetch?<same params as streams>` → `202 { queued: [names] }`
Starts the scrape in the background to fill the cache (used for next episode).
### `GET /v1/providers`
`{ defaults: [names], providers: [{ id, name, enabled, types, formats, language, logo, health: { ok, fail, timeouts, avgMs, p90Ms } }] }`
(metadata from `providers/manifest.json`).
### `GET /healthz` → `{ ok: true }`
### `GET /` Swagger UI, `GET /api.json` OpenAPI spec (`src/routes/openapi.js`).
## Scrape internals (scrape workstream)
- Worker pool (`worker_threads`), providers `require()`d once per worker at boot.
- `global.SCRAPER_SETTINGS = cfg.providerSettings` in every worker.
- Fetch shim in workers: any `api.themoviedb.org/3/...` request is answered from a cache keyed by
path+query minus `api_key` (seeded by the main thread with details + external_ids for the current
title, shared cache for everything else); per-fetch timeout; all fetches of a job abort when the job
is cancelled; keep-alive undici dispatcher.
- Adaptive per-provider budget from health stats (p90 × 1.5, clamped to [3s, cfg.timeoutMs]).
- Result cache per `(provider, tmdb, type, season, episode)` for `cfg.cacheTtlSec`; in-flight dedupe.
## Web (frontend workstreams)
ES modules under `web/js/`. Shared modules (owned by the UI-shell workstream; exports are frozen
as listed — add, don't rename):
- `config.js`: `getBase(), setBase(v), getTmdbKey(), setTmdbKey(v), getProviders(), setProviders(list), resolveUrl(relOrAbs)` (resolves API-relative URLs against `getBase()`).
- `storage.js`: resume — `resume.get(key), resume.save(record), resume.remove(key), resume.list(), resume.latestPerShow(), keyFor({type,tmdbId,season,episode})` (record shape as in v4, key `bug-tv.resume.v1` kept);
my list — `myList.has(type,id), myList.toggle(item), myList.all()`;
prefs — `prefs.get(name, fallback), prefs.set(name, value)` (subtitle lang, volume, autoplay-next, …).
- `tmdb.js` (direct browser → TMDB, cached in memory): `trending(type, window), popular(type), topRated(type), discover(type, params), details(type, id)` (append `images,credits,similar,recommendations,external_ids`), `season(tvId, n), search(q)`, image helpers `img(path, size)`.
- `router.js`: history router; `navigate(path)`, routes:
`/` home, `/title/:type/:id` title page, `/watch/:type/:id[/:season/:episode]` player, `/search?q=`,
`/list` my list, `/settings`. Static hosting fallback: `404.html` = copy of `index.html`, and hash
fallback (`#/title/…`) must work when served from `file://` or a host without rewrites.
- `ui/` components return DOM nodes (no innerHTML with untrusted strings without escaping).
Player workstream owns `web/js/api.js` (bug-tv server client: `streams(params, {onMeta,onStreams,onProvider,onDone}) → { close() }` over `EventSource`, `providers()`, `prefetch(params)`),
`web/js/views/watch.js`, `web/js/ui/player.js`, and `web/css/player.css`.
## Deviations
### Media workstream (B)
- `playbackFor(stream, ctx?)` takes an optional second arg `{ season, episode }` (stored as `s`/`e` in the
torrent token). Also accepts `stream.infoHash` (magnet built with default trackers) and `stream.fileIdx` (→ `f`).
`type: "other"` is sniffed by URL extension (.m3u8 → hls, .mp4/.webm/.m4v/.mov → file, else remux).
Extra exports: `proxyUrl(absUrl, headers)`, `remuxUrl(absUrl, headers)`, `magnetFor(stream)`.
Tokens use `src/sign.js`, so `playbackFor` must run where `sign.init(cfg.secret)` was called (main thread,
or init sign in the worker with the same secret).
- Rewritten playlist URIs are emitted as *relative* paths (`../../<token>/path`) so they work when the API
is mounted under a path prefix. Root-relative (`/x.ts`) and `../` URIs are rewritten too, and every URI
is rewritten when the upstream redirected.
- Added (additive): `GET /v1/torrent/<token>/raw` (range-serves the chosen file whatever its container;
ffmpeg reads this over loopback for torrent remuxing, so `?start=` uses real input seeking), and
`GET /v1/torrent/<token>/probe` (same shape as remux probe).
- `/status` adds `infoHash`, `bufferedBytes` and `error`; `buffered` = fraction of the file downloaded
contiguously from byte 0; `progress` = fraction of the chosen file downloaded. Before metadata arrives
`/status` returns immediately with `ready:false` (never blocks). `/files`/`/stream` wait up to 45s and
return 504 on timeout, but the torrent keeps fetching metadata in the background (retry succeeds).
- Remux probe adds `container`, `video.profile/pixFmt`, `audio[].title/default`. `?audio=<stream index>`
selects the audio track (absolute ffprobe index). HEVC is tagged `hvc1`. 503 when more than
`cfg.remux.maxProcs` (default 4) ffmpeg processes run.
- `/v1/subs/<token>` also accepts a trailing `.vtt`.
- New optional config keys: `allowPrivateTargets` (default false; lets proxy/subs/remux reach
private/loopback hosts — testing only), `remux.maxProcs`. Env `BUG_TV_WEBTORRENT` overrides the
webtorrent module specifier (testing).
- Legacy `GET /proxy/media?url=&h=<json>` kept (unsigned, SSRF-guarded); its playlists rewrite every URI
to `../v1/p/<token>/…`.
- Media stats for the health route: `require('./media/stats').mediaStats()`.
### Player workstream (D)
- `api.streams(params, handlers)` also takes `onError(err)`; `params.providers` (array) overrides
`config.getProviders()`. If EventSource errors before the first event, it falls back to
`?format=json` and replays the result as meta/streams/provider/done. A drop mid-stream counts as `done`,
so EventSource does not reconnect and replay the scrape.
- `views/watch.js` also exports `update(params)`. Switching episodes in place calls
`router.navigate('/watch/tv/:id/:s/:e', { replace: true })` (keeping the query string). The router then
calls `update()`, which returns true for the same title, so the view is not re-rendered.
- Prefs names follow `storage.js`, not the task text: `subtitleLang` (not `subLang`; "" = off), plus
`subtitleSize` (`s|m|l|xl`), `volume`, `muted`, `autoplayNext`, and `lastProvider`
(`{ "<type>:<id>": providerName }`, which adds a ranking bonus).
- Subtitles are fetched with `fetch()` and attached as blob-URL `<track>`s, so `<video>` needs no
`crossorigin` and direct non-CORS media still plays. Non-WEBVTT bodies get a minimal SRT→VTT fix
client-side. With remux the cues are shifted by the `?start=` offset.
- Torrent remux duration comes from `/v1/torrent/<token>/probe` (status URL with `/status` replaced by
`/probe`), or from `status.file.duration` / `status.duration` when present.
- Remux audio tracks come from the probe's `audio[]`. Switching a track reloads with
`?start=<t>&audio=<ffprobe index>`.
- Resume records also carry `backdrop` and `still`, as documented in `storage.js`. The save/delete rules
are unchanged from v4: skip if t < 10s, delete when t ≥ 95% or less than 15s remain, throttle to 3s,
and force a save on pause, seek, pagehide and visibility change.
### Scrape workstream (A)
- `/v1/streams` (and `/v1/prefetch`) accept the v4 filter params `minQuality` (`720`/`720p`/…),
`audioCodec`, `subtitles` (`any|required|lang`) and `subtitleLang`. They override `cfg.filters`.
`fresh=1` ignores cached provider results, but in-flight scrapes are still joined (used by `scripts/bench.js`).
`id=` is accepted as an alias of `tmdb=`.
- SSE `provider` events carry `cached: true` and `ms: 0` for results served from the cache. Providers that
are unknown or whose manifest `supportedTypes` lacks the type get an immediate `error`
(`"unknown provider"`) or `empty` (`"tv not supported"`) event. `count` is the count after filtering.
- `done` adds `debug: { tmdb: { calls, local, remote, network } }`:
- `calls`: TMDB requests the providers made.
- `local`: requests answered from the worker cache.
- `remote`: requests answered by the main-thread cache.
- `network`: real TMDB fetches made during the request. This is a global counter delta, so it is approximate when requests run concurrently.
- `meta.timeoutMs` is the largest adaptive budget among the providers being scraped (0 when everything was cached).
- JSON mode adds `providers: { name: { status, ms, count, cached? } }` and `ms`. `total` = number of streams
returned (after filters).
- Stream records omit raw `url`/`headers` (use `playback`). Streams with no playable `playback` are dropped.
`quality` is `""` when unknown. `id` = 12-char base64url SHA-1 of provider + url, so a season-pack magnet keeps
the same id across episodes.
- Client disconnect never aborts scrapes. Each scrape finishes within its own budget and lands in the cache.
- Result cache TTL: `ok` → `cacheTtlSec`; `empty` → min(5 min, `cacheTtlSec`); `error`/`timeout` are not cached.
- `GET /v1/providers` adds `description` and `health.{empty,budgetMs}` per provider, plus a top-level
`stats: { tmdb, pool, results }`. `POST /v1/prefetch` behaves like `GET`. `queued` lists only providers
that were not already cached.
- Legacy `GET /streams` keeps the v4 JSON shape (raw `url`, `headers`, v4 subtitle objects, `matched`,
`loadErrors`). Legacy `GET /providers` returns `{ all, enabled }`.
- Workers resolve DNS through c-ares (`dns.Resolver`, cached, with 30s negative caching for
ENOTFOUND/ETIMEOUT) instead of getaddrinfo. The scrape module also sets `UV_THREADPOOL_SIZE=24` if it is
unset. This matters: dead provider domains were exhausting libuv's 4-thread getaddrinfo pool and stalling every
other provider by 5–10s.
- Env `BUG_TV_DEBUG_PROVIDERS=1` shows provider console output, prefixed `[w<thread> <provider>]`. It is
silent by default. The optional `cfg.providersDir` overrides the providers directory used by workers (for tests).
- Health stats are kept in memory only, with no persistence.
- `X-Bug-Tv-Offset` is the *actual* start of the remux (the keyframe at/before `?start=`, found with a
parallel ffprobe), so it can be a little smaller than the requested `start`; the player should use the
header value, not its own requested value.
- Dependency note: `webtorrent@2.8.5` crashes on every `add()` with the currently resolved
`uint8-util@2.3.x` (`arr2hex(string)` in `Torrent._onTorrentId`). `webtorrent@^3.0.21` fixes it and is
API-compatible with `src/media/torrent.js` (tested); package.json should bump to it.
### Integration
- `/v1/remux/<token>/probe?start=<sec>` and `/v1/torrent/<token>/probe?start=<sec>` add `keyframe`: the time the remux really starts at. The player uses it as its clock offset because a `<video>` element can't read `X-Bug-Tv-Offset`.
- Extensionless stream URLs are sniffed by their first 1 KB (`src/media/sniff.js`) and typed m3u8/mp4/webm/mkv before `playbackFor` runs.
- The Swagger UI moved to `src/public/index.html`, `mod/` and `rest/` are removed, and webtorrent is bumped to ^3.0.21.
Generated
+4 -4
View File
@@ -2,16 +2,16 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1787631388,
"narHash": "sha256-vMiXptXarfSdJb1Gkc+FYVOAibuBRj7qxGa8z68q1Uw=",
"lastModified": 1792773339,
"narHash": "sha256-rZLrzrC6i+jnTAlvPZHogKDulY7WWDEv9hJeHieO7Zw=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "ac6b2166e7a9375683b8e98f860f273222337b16",
"rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixpkgs-unstable",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
+58 -206
View File
@@ -1,228 +1,80 @@
{
inputs.nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
description = "bug.tv: multi-provider stream finder API + web frontend";
outputs = { nixpkgs, ... }:
inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
outputs =
{ self, nixpkgs, ... }:
let
lib = nixpkgs.lib;
inherit (nixpkgs) lib;
systems = [ "x86_64-linux" "aarch64-linux" ];
pkgsFor = system: nixpkgs.legacyPackages.${system};
appFor = pkgs:
let
src = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
./rest
./mod
./providers
./package.json
./package-lock.json
];
};
npmDeps = pkgs.fetchNpmDeps {
name = "bug-tv-npm-deps";
inherit src;
hash = "sha256-XzEx5eCnlY99OzURnVNcZalYg69APIT/LCchklPlHJg=";
};
in
pkgs.stdenvNoCC.mkDerivation {
pname = "bug-tv";
version = "0.1.0";
inherit src npmDeps;
nativeBuildInputs = [ pkgs.nodejs pkgs.npmHooks.npmConfigHook ];
dontConfigure = true;
dontBuild = true;
installPhase = ''
mkdir -p $out/lib/bug-tv $out/bin
cp -r rest mod providers package.json node_modules $out/lib/bug-tv/
printf '%s\n' \
'#!${pkgs.bash}/bin/bash' \
"exec ${pkgs.nodejs}/bin/node \"$out/lib/bug-tv/rest/server.js\" \"\$@\"" \
> $out/bin/bug-tv
chmod 755 $out/bin/bug-tv
'';
};
forAllSystems = f: lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
in
{
packages = lib.genAttrs systems (system: {
default = appFor (pkgsFor system);
packages = forAllSystems (pkgs: rec {
api = pkgs.callPackage ./nix/package.nix { };
# web.override { apiBase = "https://..."; }
web = pkgs.callPackage ./nix/web.nix { };
default = api;
});
devShells = lib.genAttrs systems (system: {
default =
let pkgs = pkgsFor system;
in pkgs.mkShell {
packages = [ pkgs.nodejs pkgs.nodejs-npm ];
};
apps = forAllSystems (pkgs: {
default = {
type = "app";
program = lib.getExe self.packages.${pkgs.stdenv.hostPlatform.system}.api;
meta.description = "Run the bug.tv API (reads ./config.json or $BUG_TV_CONFIG)";
};
});
nixosModules.default =
{ config, lib, pkgs, ... }:
devShells = forAllSystems (pkgs: {
default = pkgs.mkShell {
packages = [ pkgs.nodejs pkgs.ffmpeg-headless ];
};
});
formatter = forAllSystems (pkgs: pkgs.nixfmt);
checks = forAllSystems (
pkgs:
let
cfg = config.services."bug-tv";
baseFilters = {
minQuality = cfg.filters.minQuality;
audioCodec = cfg.filters.audioCodec;
subtitles = cfg.filters.subtitles;
subtitleLang = cfg.filters.subtitleLang;
};
baseConfig = {
tmdbKey = cfg.tmdbApiKey;
enabledProviders = cfg.providers;
timeoutMs = cfg.timeoutMs;
apiHost = cfg.host;
apiPort = cfg.port;
filters = baseFilters;
};
mergedConfig =
(baseConfig // (lib.removeAttrs cfg.extraConfig [ "filters" ]))
// lib.optionalAttrs (cfg.extraConfig ? "filters") { filters = baseFilters // cfg.extraConfig.filters; };
configJson = pkgs.writeText "bug-tv-config.json" (builtins.toJSON mergedConfig);
app = pkgs.runCommand "bug-tv" { preferLocalBuild = true; } ''
mkdir -p $out
for path in rest mod providers package.json node_modules; do
cp -a ${cfg.package}/lib/bug-tv/''${path} $out/
done
cp ${configJson} $out/config.json
mkdir -p $out/bin
printf '%s\n' \
'#!${pkgs.bash}/bin/bash' \
"exec ${pkgs.nodejs}/bin/node \"$out/rest/server.js\" \"\$@\"" \
> $out/bin/bug-tv
chmod 755 $out/bin/bug-tv
'';
inherit (self.packages.${pkgs.stdenv.hostPlatform.system}) api web;
in
{
options.services."bug-tv" = lib.mkOption {
default = { };
type = lib.types.submodule {
options = {
enable = lib.mkEnableOption "the bug.tv multi-provider stream finder API";
inherit api web;
package = lib.mkOption {
description = "The bug-tv package to run.";
type = lib.types.package;
};
port = lib.mkOption {
description = "TCP port to listen on.";
type = lib.types.port;
default = 8789;
};
host = lib.mkOption {
description = "Interface to bind.";
type = lib.types.str;
default = "0.0.0.0";
};
tmdbApiKey = lib.mkOption {
description = "TMDB API key used for search and details lookups.";
type = lib.types.str;
default = "";
};
providers = lib.mkOption {
description = "Providers enabled by default when none are requested.";
type = lib.types.listOf lib.types.str;
default = [ "cineby" ];
};
timeoutMs = lib.mkOption {
description = "Per-provider scrape timeout in milliseconds.";
type = lib.types.int;
default = 30000;
};
filters = lib.mkOption {
description = "Default stream filters.";
default = { };
type = lib.types.submodule {
options = {
minQuality = lib.mkOption {
description = "Minimum quality (e.g. 1080p, or any).";
type = lib.types.str;
default = "any";
};
audioCodec = lib.mkOption {
description = "Required audio codec, or any.";
type = lib.types.str;
default = "any";
};
subtitles = lib.mkOption {
description = "Subtitle requirement (any/required/none).";
type = lib.types.str;
default = "any";
};
subtitleLang = lib.mkOption {
description = "Required subtitle language, empty for any.";
type = lib.types.str;
default = "";
};
};
};
};
extraConfig = lib.mkOption {
description = "Extra keys merged into the generated config.json.";
type = lib.types.attrsOf lib.types.json;
default = { };
};
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
smoke =
pkgs.runCommand "bug-tv-smoke"
{
assertion = cfg.tmdbApiKey != "";
message = "services.bug-tv.tmdbApiKey must be set";
nativeBuildInputs = [ pkgs.nodejs pkgs.curl pkgs.findutils ];
}
{
assertion = cfg.providers != [ ];
message = "services.bug-tv.providers must not be empty";
}
];
''
cd ${api}/lib/bug-tv
find src -name '*.js' -print0 | xargs -0 -n1 node --check
users.users."bug-tv" = {
isSystemUser = true;
group = "bug-tv";
};
port=$((20000 + RANDOM % 20000))
cat > $TMPDIR/config.json <<JSON
{ "tmdbKey": "dummy", "host": "127.0.0.1", "port": $port }
JSON
export HOME=$TMPDIR BUG_TV_CONFIG=$TMPDIR/config.json BUG_TV_CACHE_DIR=$TMPDIR/cache
users.groups."bug-tv" = { };
${lib.getExe api} > $TMPDIR/server.log 2>&1 &
pid=$!
ok=
for _ in $(seq 60); do
if curl -fsS "http://127.0.0.1:$port/healthz"; then ok=1; break; fi
kill -0 $pid 2>/dev/null || break
sleep 0.5
done
kill $pid 2>/dev/null || true
cat $TMPDIR/server.log
[ -n "$ok" ] || { echo "server did not answer /healthz"; exit 1; }
touch $out
'';
}
);
systemd.services."bug-tv" = {
description = "bug.tv stream finder API";
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
User = "bug-tv";
Group = "bug-tv";
ExecStart = "${app}/bin/bug-tv";
Restart = "always";
RestartSec = 5;
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = true;
LockPersonality = true;
};
};
};
};
nixosModules.default = import ./nix/module.nix self;
nixosModules.bug-tv = self.nixosModules.default;
};
}
-40
View File
@@ -1,40 +0,0 @@
const fs = require('fs');
const path = require('path');
const CONFIG_PATH = path.join(__dirname, '..', 'config.json');
const DEFAULTS = {
tmdbKey: '',
enabledProviders: ['videasy', 'vidfast'],
timeoutMs: 30000,
apiHost: '0.0.0.0',
apiPort: 8789,
filters: {
minQuality: 'any',
audioCodec: 'any',
subtitles: 'any',
subtitleLang: '',
},
};
function loadConfig() {
let cfg = { ...DEFAULTS, filters: { ...DEFAULTS.filters } };
if (fs.existsSync(CONFIG_PATH)) {
const saved = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
cfg = { ...cfg, ...saved, filters: { ...cfg.filters, ...(saved.filters || {}) } };
} else {
saveConfig(cfg);
}
if (!cfg.tmdbKey && process.env.TMDB_API_KEY) cfg.tmdbKey = process.env.TMDB_API_KEY;
if (!cfg.tmdbKey) {
console.error('No TMDB API key found. Set "tmdbKey" in config.json or the TMDB_API_KEY env var.');
process.exit(1);
}
return cfg;
}
function saveConfig(cfg) {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2) + '\n');
}
module.exports = { loadConfig, saveConfig, CONFIG_PATH };
-37
View File
@@ -1,37 +0,0 @@
const QUALITY_MIN = { any: 0, '480': 480, '720': 720, '1080': 1080, '2160': 2160 };
const AUDIO_OPTIONS = ['any', 'aac', 'ac3', 'dts', 'opus', 'mp3', 'flac', 'multi'];
const SUBTITLE_OPTIONS = ['any', 'required', 'lang'];
function langCode(lang) {
return String(lang || '').toLowerCase().replace(/[^a-z]/g, '').slice(0, 2);
}
function hasSubtitleLang(streams_subtitles, wanted) {
const want = langCode(wanted);
if (!want) return true;
return streams_subtitles.some((s) => {
const code = langCode(s.language) || langCode(s.name);
return code === want;
});
}
function applyFilters(streams, filters) {
const minPixels = QUALITY_MIN[filters.minQuality] ?? 0;
return streams.filter((s) => {
if (minPixels > 0 && (s.pixels == null || s.pixels < minPixels)) return false;
if (filters.audioCodec && filters.audioCodec !== 'any' && s.audio !== filters.audioCodec) return false;
if (filters.subtitles && filters.subtitles !== 'any') {
if (s.subtitles.length === 0) return false;
if (filters.subtitles === 'lang' && filters.subtitleLang && !hasSubtitleLang(s.subtitles, filters.subtitleLang)) return false;
}
return true;
});
}
function rankStreams(streams) {
return streams
.slice()
.sort((a, b) => (b.pixels || 0) - (a.pixels || 0) || a.provider.localeCompare(b.provider));
}
module.exports = { applyFilters, rankStreams, QUALITY_MIN, AUDIO_OPTIONS, SUBTITLE_OPTIONS };
-37
View File
@@ -1,37 +0,0 @@
const fs = require('fs');
const path = require('path');
const PROVIDERS_DIR = path.join(__dirname, '..', 'providers');
function listAll() {
return fs
.readdirSync(PROVIDERS_DIR)
.filter((f) => f.endsWith('.js'))
.map((f) => f.slice(0, -3))
.sort();
}
function loadProviders(names) {
const providers = [];
const loadErrors = {};
for (const name of names) {
const file = path.join(PROVIDERS_DIR, `${name}.js`);
if (!fs.existsSync(file)) {
loadErrors[name] = 'not found';
continue;
}
try {
const mod = require(file);
if (typeof mod.getStreams !== 'function') {
loadErrors[name] = 'does not export getStreams()';
continue;
}
providers.push({ name, getStreams: mod.getStreams });
} catch (err) {
loadErrors[name] = err.message.split('\n')[0];
}
}
return { providers, loadErrors };
}
module.exports = { listAll, loadProviders, PROVIDERS_DIR };
-91
View File
@@ -1,91 +0,0 @@
function qualityToPixels(q) {
if (!q) return null;
const s = String(q).toLowerCase();
if (/2160|4k|uhd/.test(s)) return 2160;
const m = s.match(/(\d{3,4})\s*p/);
if (m) {
const n = parseInt(m[1], 10);
return n >= 1440 ? 2160 : n;
}
if (/1080|full\s?hd|fhd/.test(s)) return 1080;
if (/720/.test(s)) return 720;
if (/480/.test(s)) return 480;
return null;
}
function detectAudio(text) {
const t = ` ${String(text || '').toLowerCase()} `;
if (/\bdts\b|dts-?hd/.test(t)) return 'dts';
if (/e-?ac3|dd\+|ac-?3|dolby digital/.test(t)) return 'ac3';
if (/\baac\b/.test(t)) return 'aac';
if (/\bopus\b/.test(t)) return 'opus';
if (/\bflac\b|lossless/.test(t)) return 'flac';
if (/\bmp3\b/.test(t)) return 'mp3';
if (/dual-?audio|multi-?audio|original audio|multi audio/.test(t)) return 'multi';
return null;
}
function extOf(text) {
const m = String(text || '').toLowerCase().split(/[?#]/)[0].match(/\.([a-z0-9]{2,5})$/);
return m ? m[1] : '';
}
function streamType(url, name) {
const u = String(url || '');
const n = String(name || '').toLowerCase();
if (/^magnet:/i.test(u)) return 'magnet';
if (/m3u8/i.test(u)) return 'm3u8';
const ext = extOf(u) || extOf(n);
if (ext === 'mkv' || /\.mkv\b/.test(n)) return 'mkv';
if (ext === 'mp4' || ext === 'm4v' || ext === 'mov' || /\.mp4\b/.test(n)) return 'mp4';
if (ext === 'avi' || /\.avi\b/.test(n)) return 'avi';
if (ext === 'webm') return 'webm';
if (ext === 'ts' || ext === 'm4a') return 'other';
return ext || 'other';
}
function normalizeSubtitles(subs) {
if (!Array.isArray(subs)) return [];
return subs
.filter((s) => s && typeof s.url === 'string' && s.url.length > 0)
.map((s) => ({
url: s.url,
language: s.language || s.id || s.lang || '',
name: s.name || '',
}));
}
function normalize(raw, providerName) {
const text = [raw.name, raw.title, raw.description].filter(Boolean).join(' ');
const pixels = qualityToPixels(raw.quality) ?? qualityToPixels(`${raw.name || ''} ${raw.title || ''}`);
return {
provider: providerName,
serverName: raw._serverName || '',
name: raw.name || raw.title || 'stream',
title: raw.title || '',
description: raw.description || '',
url: raw.url,
quality: raw.quality || (pixels ? `${pixels}p` : ''),
pixels,
audio: detectAudio(text),
type: streamType(raw.url, raw.name || raw.title),
subtitles: normalizeSubtitles(raw.subtitles),
size: typeof raw.size === 'number' ? raw.size : 0,
headers: raw.headers && typeof raw.headers === 'object' ? raw.headers : {},
is4k: !!raw._is4k || pixels === 2160,
};
}
function formatBytes(n) {
if (!n || n <= 0) return '';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
let v = n;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
return `${v.toFixed(v >= 100 || i === 0 ? 0 : 1)}${units[i]}`;
}
module.exports = { normalize, qualityToPixels, detectAudio, formatBytes };
-56
View File
@@ -1,56 +0,0 @@
function withTimeout(promise, ms, label) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
promise.then(
(v) => {
clearTimeout(timer);
resolve(v);
},
(e) => {
clearTimeout(timer);
reject(e);
}
);
});
}
function toStreamArray(raw, providerName) {
let arr = Array.isArray(raw) ? raw : raw && typeof raw === 'object' && raw.url ? [raw] : [];
return arr
.filter((s) => s && typeof s === 'object' && typeof s.url === 'string' && s.url.length > 0)
.map((s) => ({ ...s, _provider: s._provider || providerName }));
}
async function scrapeAll(providers, media, timeoutMs) {
const settled = await Promise.allSettled(
providers.map(async (p) => {
const raw = await withTimeout(
Promise.resolve().then(() =>
p.getStreams(String(media.id), media.type, media.seasonId ?? null, media.episodeId ?? null)
),
timeoutMs,
p.name
);
return toStreamArray(raw, p.name);
})
);
const streams = [];
const errors = {};
settled.forEach((r, i) => {
if (r.status === 'fulfilled') streams.push(...r.value);
else errors[providers[i].name] = (r.reason && r.reason.message) || String(r.reason);
});
const seen = new Set();
const unique = [];
for (const s of streams) {
const key = `${s._provider}|${s.url}|${s.quality || ''}|${s.name || s.title || ''}`;
if (seen.has(key)) continue;
seen.add(key);
unique.push(s);
}
return { streams: unique, errors };
}
module.exports = { scrapeAll, withTimeout };
-43
View File
@@ -1,43 +0,0 @@
const BASE = 'https://api.themoviedb.org/3';
async function get(pathname, key) {
const sep = pathname.includes('?') ? '&' : '?';
const res = await fetch(`${BASE}${pathname}${sep}api_key=${encodeURIComponent(key)}`);
if (!res.ok) throw new Error(`TMDB HTTP ${res.status} for ${pathname}`);
return res.json();
}
function search(query, key) {
return get(
`/search/multi?query=${encodeURIComponent(query)}&include_adult=false&language=en-US&page=1`,
key
).then((r) =>
(r.results || []).filter((m) => m.media_type === 'movie' || m.media_type === 'tv').slice(0, 15)
);
}
function trending(mediaType, timeWindow, key) {
const type = ['movie', 'tv', 'all'].includes(mediaType) ? mediaType : 'all';
const window_ = timeWindow === 'day' ? 'day' : 'week';
return get(`/trending/${type}/${window_}?language=en-US`, key).then((r) =>
(r.results || []).slice(0, 20)
);
}
function getSeasons(tvId, key) {
return get(`/tv/${tvId}?language=en-US`, key).then((r) =>
(r.seasons || []).filter((s) => s.season_number > 0 && (s.episode_count || 0) > 0)
);
}
function getEpisodes(tvId, seasonNumber, key) {
return get(`/tv/${tvId}/season/${seasonNumber}?language=en-US`, key).then((r) =>
(r.episodes || []).slice().sort((a, b) => a.episode_number - b.episode_number)
);
}
function details(type, id, key) {
return get(`/${type}/${id}?language=en-US&append_to_response=images`, key);
}
module.exports = { search, trending, getSeasons, getEpisodes, details };
+275
View File
@@ -0,0 +1,275 @@
self:
{
config,
lib,
pkgs,
...
}:
let
inherit (lib) mkOption mkEnableOption types;
cfg = config.services.bug-tv;
system = pkgs.stdenv.hostPlatform.system;
credDir = "/run/credentials/bug-tv.service";
appConfig = lib.recursiveUpdate (
{
inherit (cfg) host port timeoutMs workers cacheTtlSec providerSettings;
enabledProviders = cfg.providers;
inherit (cfg) disabledProviders;
torrent = { inherit (cfg.torrent) enable maxSizeGB; };
remux = { inherit (cfg.remux) enable; };
filters = cfg.filters;
}
// (
if cfg.tmdbApiKeyFile != null then
{ tmdbKeyFile = "${credDir}/tmdb"; }
else
{ tmdbKey = cfg.tmdbApiKey; }
)
// lib.optionalAttrs (cfg.secretFile != null) { secretFile = "${credDir}/secret"; }
) cfg.extraConfig;
configFile = pkgs.writeText "bug-tv-config.json" (builtins.toJSON appConfig);
hardening = {
DynamicUser = true;
NoNewPrivileges = true;
PrivateTmp = true;
PrivateDevices = true;
ProtectSystem = "strict";
ProtectHome = true;
ProtectHostname = true;
ProtectClock = true;
ProtectProc = "invisible";
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectKernelLogs = true;
ProtectControlGroups = true;
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" "AF_NETLINK" ];
RestrictNamespaces = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
LockPersonality = true;
MemoryDenyWriteExecute = false; # node's JIT
SystemCallArchitectures = "native";
CapabilityBoundingSet = "";
AmbientCapabilities = "";
UMask = "0077";
Restart = "always";
RestartSec = 5;
};
in
{
options.services.bug-tv = {
enable = mkEnableOption "the bug.tv multi-provider stream finder API";
package = mkOption {
type = types.package;
default = self.packages.${system}.api;
defaultText = lib.literalExpression "bug-tv.packages.\${system}.api";
description = "The bug-tv API package.";
};
host = mkOption {
type = types.str;
default = "0.0.0.0";
description = "Interface the API binds to.";
};
port = mkOption {
type = types.port;
default = 8789;
description = "API TCP port.";
};
tmdbApiKey = mkOption {
type = types.str;
default = "";
description = "TMDB API key. Ends up world-readable in the Nix store; prefer tmdbApiKeyFile.";
};
tmdbApiKeyFile = mkOption {
type = types.nullOr types.path;
default = null;
example = "/run/secrets/tmdb";
description = "File holding the TMDB API key (passed via systemd LoadCredential). Takes precedence over tmdbApiKey.";
};
secretFile = mkOption {
type = types.nullOr types.path;
default = null;
description = "File holding the token-signing secret, so proxy/remux URLs survive restarts. Random per boot when null.";
};
providers = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Providers used when a request names none. Empty means every bundled provider except `disabledProviders`.";
};
disabledProviders = mkOption {
type = types.listOf types.str;
default = [ "torrentio" ];
description = "Providers left out of the default set when `providers` is empty (torrent/magnet sources by default).";
};
providerSettings = mkOption {
type = types.attrsOf types.json;
default = { };
description = "Per-provider settings (config key providerSettings).";
};
timeoutMs = mkOption {
type = types.ints.positive;
default = 20000;
description = "Per-provider scrape timeout in milliseconds.";
};
workers = mkOption {
type = types.ints.unsigned;
default = 0;
description = "Scrape worker count (0 = automatic).";
};
cacheTtlSec = mkOption {
type = types.ints.unsigned;
default = 1800;
description = "Result cache TTL in seconds.";
};
torrent = {
enable = mkOption {
type = types.bool;
default = true;
description = "Whether to stream torrents (cached under /var/cache/bug-tv/torrents).";
};
maxSizeGB = mkOption {
type = types.ints.positive;
default = 20;
description = "Torrent cache size limit in GB.";
};
};
remux.enable = mkOption {
type = types.bool;
default = true;
description = "Whether to enable ffmpeg remuxing.";
};
filters = mkOption {
default = { };
description = "Default stream filters.";
type = types.submodule {
options = {
minQuality = mkOption {
type = types.str;
default = "any";
description = "Minimum quality (e.g. 1080p, or any).";
};
audioCodec = mkOption {
type = types.str;
default = "any";
description = "Required audio codec, or any.";
};
subtitles = mkOption {
type = types.str;
default = "any";
description = "Subtitle requirement (any/required/none).";
};
subtitleLang = mkOption {
type = types.str;
default = "";
description = "Required subtitle language, empty for any.";
};
};
};
};
extraConfig = mkOption {
type = types.attrsOf types.json;
default = { };
description = "Extra keys recursively merged last into the generated config.json.";
};
web = {
enable = mkEnableOption "the bug.tv static web frontend (static-web-server)";
port = mkOption {
type = types.port;
default = 8790;
description = "Web frontend TCP port (binds to services.bug-tv.host).";
};
apiBase = mkOption {
type = types.str;
default = "https://api-tv.bug.tools";
description = "API base URL baked into the frontend.";
};
package = mkOption {
type = types.package;
default = self.packages.${system}.web.override { inherit (cfg.web) apiBase; };
defaultText = lib.literalExpression "bug-tv.packages.\${system}.web.override { inherit (cfg.web) apiBase; }";
description = "The web frontend package (a directory of static files).";
};
};
};
config = lib.mkMerge [
(lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.tmdbApiKey != "" || cfg.tmdbApiKeyFile != null;
message = "services.bug-tv: set tmdbApiKey or tmdbApiKeyFile";
}
];
systemd.services.bug-tv = {
description = "bug.tv stream finder API";
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
environment = {
BUG_TV_CONFIG = toString configFile;
BUG_TV_CACHE_DIR = "/var/cache/bug-tv/torrents";
NODE_ENV = "production";
};
serviceConfig = hardening // {
ExecStart = lib.getExe cfg.package;
CacheDirectory = "bug-tv";
WorkingDirectory = "/var/cache/bug-tv";
LoadCredential =
lib.optional (cfg.tmdbApiKeyFile != null) "tmdb:${toString cfg.tmdbApiKeyFile}"
++ lib.optional (cfg.secretFile != null) "secret:${toString cfg.secretFile}";
};
};
})
(lib.mkIf cfg.web.enable {
systemd.services.bug-tv-web = {
description = "bug.tv web frontend";
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
serviceConfig = hardening // {
ExecStart = lib.escapeShellArgs [
(lib.getExe pkgs.static-web-server)
"--host" cfg.host
"--port" (toString cfg.web.port)
"--root" "${cfg.web.package}"
"--page-fallback" "${cfg.web.package}/index.html"
"--compression" "true"
"--health" "true"
"--log-level" "info"
];
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
MemoryDenyWriteExecute = true;
};
};
})
];
}
+62
View File
@@ -0,0 +1,62 @@
{
lib,
buildNpmPackage,
importNpmLock,
nodejs,
ffmpeg-headless,
makeWrapper,
}:
let
root = ../.;
src = lib.fileset.toSource {
inherit root;
fileset = lib.fileset.unions [
../src
../providers
../package.json
../package-lock.json
];
};
pkgJson = lib.importJSON ../package.json;
in
assert lib.assertMsg (lib.versionAtLeast nodejs.version "22") "bug-tv needs node >= 22";
buildNpmPackage {
pname = "bug-tv";
inherit (pkgJson) version;
inherit src nodejs;
# no lockfile hash to keep in sync: deps are fetched per-package from package-lock.json
npmDeps = importNpmLock { npmRoot = src; };
npmConfigHook = importNpmLock.npmConfigHook;
# webtorrent's optional native deps (bufferutil, utf-8-validate, node-datachannel) are not needed
npmFlags = [ "--ignore-scripts" ];
dontNpmBuild = true;
nativeBuildInputs = [ makeWrapper ];
installPhase = ''
runHook preInstall
mkdir -p $out/lib/bug-tv
cp -r src providers node_modules package.json $out/lib/bug-tv/
makeWrapper ${lib.getExe nodejs} $out/bin/bug-tv \
--add-flags $out/lib/bug-tv/src/server.js \
--prefix PATH : ${lib.makeBinPath [ ffmpeg-headless ]}
runHook postInstall
'';
meta = {
description = pkgJson.description;
homepage = "https://git.bug.tools/bug/tv";
mainProgram = "bug-tv";
platforms = lib.platforms.linux;
};
}
+42
View File
@@ -0,0 +1,42 @@
{
lib,
stdenvNoCC,
# baked into <meta name="bug-tv-api" content="..."> of every top-level page
apiBase ? "https://api-tv.bug.tools",
}:
let
sedExpr = ''s#(<meta[[:space:]]+name="bug-tv-api"[[:space:]]+content=")[^"]*(")#\1${
lib.escape [ "\\" "&" "#" ] apiBase
}\2#'';
in
stdenvNoCC.mkDerivation {
pname = "bug-tv-web";
version = (lib.importJSON ../package.json).version;
src = ../web;
dontConfigure = true;
dontBuild = true;
installPhase = ''
runHook preInstall
cp -r . $out
chmod -R u+w $out
# no-op on pages without the tag
for page in $out/*.html; do
sed -i -E ${lib.escapeShellArg sedExpr} "$page"
done
runHook postInstall
'';
passthru = { inherit apiBase; };
meta = {
description = "bug.tv static web frontend (API: ${apiBase})";
platforms = lib.platforms.all;
};
}
+2434 -5
View File
File diff suppressed because it is too large. Load diff
+12 -6
View File
@@ -1,15 +1,21 @@
{
"name": "bug-tv",
"version": "0.1.0",
"version": "5.0.0",
"private": true,
"description": "Multi-provider stream finder with TMDB search and REST API",
"main": "rest/server.js",
"description": "Multi-provider stream finder: progressive SSE scraping, media proxy, torrent + remux playback",
"main": "src/server.js",
"engines": {
"node": ">=22"
},
"scripts": {
"start": "node rest/server.js",
"api": "node rest/server.js"
"start": "node src/server.js",
"bench": "node scripts/bench.js",
"sync-providers": "node scripts/sync-providers.js"
},
"dependencies": {
"cheerio-without-node-native": "^0.20.2",
"crypto-js": "^4.2.0"
"crypto-js": "^4.2.0",
"undici": "^7.0.0",
"webtorrent": "^3.0.21"
}
}
+490 -1
View File
@@ -1 +1,490 @@
const _0x242fc1=_0x35c1;(function(_0x3e594b,_0x19aec9){const _0x2b9eba={_0x4ee093:0x117,_0x57b392:0x10b,_0x2e0f2c:0x114},_0x33e261=_0x35c1,_0x165159=_0x3e594b();while(!![]){try{const _0x333e0c=parseInt(_0x33e261(_0x2b9eba._0x4ee093))/0x1+-parseInt(_0x33e261(0xf3))/0x2+-parseInt(_0x33e261(0xc3))/0x3*(parseInt(_0x33e261(0xea))/0x4)+parseInt(_0x33e261(0x122))/0x5*(parseInt(_0x33e261(_0x2b9eba._0x57b392))/0x6)+-parseInt(_0x33e261(_0x2b9eba._0x2e0f2c))/0x7+parseInt(_0x33e261(0xc5))/0x8*(parseInt(_0x33e261(0xc9))/0x9)+parseInt(_0x33e261(0xdd))/0xa;if(_0x333e0c===_0x19aec9)break;else _0x165159['push'](_0x165159['shift']());}catch(_0x4f1033){_0x165159['push'](_0x165159['shift']());}}}(_0x4846,0x1bbe8));var __create=Object[_0x242fc1(0x123)],__defProp=Object[_0x242fc1(0xf1)],__defProps=Object[_0x242fc1(0x107)],__getOwnPropDesc=Object['getOwnPropertyDescriptor'],__getOwnPropDescs=Object[_0x242fc1(0xd1)],__getOwnPropNames=Object['getOwnPropertyNames'],__getOwnPropSymbols=Object['getOwnPropertySymbols'],__getProtoOf=Object['getPrototypeOf'],__hasOwnProp=Object['prototype']['hasOwnProperty'],__propIsEnum=Object['prototype']['propertyIsEnumerable'],__defNormalProp=(_0x4e72ae,_0x3282fc,_0x221b73)=>_0x3282fc in _0x4e72ae?__defProp(_0x4e72ae,_0x3282fc,{'enumerable':!![],'configurable':!![],'writable':!![],'value':_0x221b73}):_0x4e72ae[_0x3282fc]=_0x221b73,__spreadValues=(_0x4d6a07,_0x5914a3)=>{const _0x22aeaf=_0x242fc1;for(var _0x32fca5 in _0x5914a3||(_0x5914a3={}))if(__hasOwnProp['call'](_0x5914a3,_0x32fca5))__defNormalProp(_0x4d6a07,_0x32fca5,_0x5914a3[_0x32fca5]);if(__getOwnPropSymbols)for(var _0x32fca5 of __getOwnPropSymbols(_0x5914a3)){if(__propIsEnum[_0x22aeaf(0xf8)](_0x5914a3,_0x32fca5))__defNormalProp(_0x4d6a07,_0x32fca5,_0x5914a3[_0x32fca5]);}return _0x4d6a07;},__spreadProps=(_0x52825b,_0xd74939)=>__defProps(_0x52825b,__getOwnPropDescs(_0xd74939)),__copyProps=(_0x4cbd15,_0x15a416,_0x5eab40,_0x1f3bf3)=>{const _0x3b3296={_0x4e968b:0xf2,_0x370629:0xf8},_0x4410db=_0x242fc1;if(_0x15a416&&typeof _0x15a416===_0x4410db(_0x3b3296._0x4e968b)||typeof _0x15a416==='function'){for(let _0x1989d1 of __getOwnPropNames(_0x15a416))if(!__hasOwnProp[_0x4410db(_0x3b3296._0x370629)](_0x4cbd15,_0x1989d1)&&_0x1989d1!==_0x5eab40)__defProp(_0x4cbd15,_0x1989d1,{'get':()=>_0x15a416[_0x1989d1],'enumerable':!(_0x1f3bf3=__getOwnPropDesc(_0x15a416,_0x1989d1))||_0x1f3bf3['enumerable']});}return _0x4cbd15;},__toESM=(_0x39ed5c,_0x3259c6,_0x27c5fe)=>(_0x27c5fe=_0x39ed5c!=null?__create(__getProtoOf(_0x39ed5c)):{},__copyProps(_0x3259c6||!_0x39ed5c||!_0x39ed5c['__esModule']?__defProp(_0x27c5fe,'default',{'value':_0x39ed5c,'enumerable':!![]}):_0x27c5fe,_0x39ed5c)),__async=(_0x4c12ba,_0x33dc1c,_0x14776b)=>{const _0x5f32e6={_0x30a4f4:0x129};return new Promise((_0x1a2e5a,_0x54d7fb)=>{const _0x2d4df6=_0x35c1;var _0x269212=_0x4db031=>{try{_0x4492b0(_0x14776b['next'](_0x4db031));}catch(_0x343140){_0x54d7fb(_0x343140);}},_0x46683d=_0xbc53a0=>{try{_0x4492b0(_0x14776b['throw'](_0xbc53a0));}catch(_0x328dfc){_0x54d7fb(_0x328dfc);}},_0x4492b0=_0x1c8fe3=>_0x1c8fe3[_0x2d4df6(0xc4)]?_0x1a2e5a(_0x1c8fe3[_0x2d4df6(0x100)]):Promise[_0x2d4df6(0xcf)](_0x1c8fe3[_0x2d4df6(0x100)])[_0x2d4df6(0xe5)](_0x269212,_0x46683d);_0x4492b0((_0x14776b=_0x14776b[_0x2d4df6(0x104)](_0x4c12ba,_0x33dc1c))[_0x2d4df6(_0x5f32e6._0x30a4f4)]());});},import_cheerio_without_node_native=__toESM(require(_0x242fc1(0x102))),PROVIDER_NAME=_0x242fc1(0xce),BASE_URL='https://4khdhub.one',TMDB_URL=_0x242fc1(0x111),TMDB_KEY='439c478a771f35c05022f9feabcca01c',USER_AGENT=_0x242fc1(0x12f),HEADERS={'User-Agent':USER_AGENT,'Referer':BASE_URL+'/'};function getInvertedSortTag(_0x368260,_0x392912=0xf423f){const _0x3fca6c={_0x4f6a2d:0xf5},_0xe3375f=_0x242fc1,_0x2c6b4d=Math[_0xe3375f(0xf6)](0x0,parseInt(_0x368260,0xa)||0x0),_0x1aaba3=Math[_0xe3375f(0xf6)](0x0,_0x392912-_0x2c6b4d),_0x5cc5d7=_0x1aaba3[_0xe3375f(0xc6)](0x2)[_0xe3375f(_0x3fca6c._0x4f6a2d)](0x14,'0');return _0x5cc5d7[_0xe3375f(0xf9)]('')['map'](_0x3fbe34=>_0x3fbe34==='1'?'\ufeff':'​')['join']('');}function resolveSettings(_0x1910f8){const _0x1c8f73={_0x4dea26:0xda,_0xd7994c:0xbf,_0x58a36a:0xd0,_0x13172f:0xde,_0x42cca7:0x108,_0x10b3c2:0xf2,_0xe839ba:0xe0,_0x4a0d2e:0x108},_0x552eb6=_0x242fc1;let _0x34e00e={'sortBy':_0x552eb6(_0x1c8f73._0x4dea26)};try{let _0x1ec629=_0x1910f8;!_0x1ec629&&typeof globalThis!==_0x552eb6(_0x1c8f73._0xd7994c)&&(_0x1ec629=globalThis['SCRAPER_SETTINGS']||globalThis[_0x552eb6(_0x1c8f73._0x58a36a)]||globalThis['settings']);!_0x1ec629&&typeof global!=='undefined'&&(_0x1ec629=global['SCRAPER_SETTINGS']||global['SETTINGS']||global['settings']);!_0x1ec629&&typeof window!=='undefined'&&(_0x1ec629=window[_0x552eb6(_0x1c8f73._0x13172f)]||window[_0x552eb6(_0x1c8f73._0x58a36a)]||window['settings']);if(_0x1ec629){var _0x269144=_0x1ec629[_0x552eb6(_0x1c8f73._0x42cca7)]||_0x1ec629['sort_by']||_0x1ec629[_0x552eb6(0xf4)]||'';typeof _0x269144===_0x552eb6(_0x1c8f73._0x10b3c2)&&_0x269144!==null&&(_0x269144=_0x269144[_0x552eb6(0x100)]||_0x269144[_0x552ebLine truncated
"use strict";
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
var BASE_URL = "https://4khdhub.click";
var TMDB_API_KEY = "439c478a771f35c05022f9feabcca01c";
var USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";
var DOMAINS_URL = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json";
var domainCache = { url: BASE_URL, ts: 0 };
function fetchLatestDomain() {
return __async(this, null, function* () {
const now = Date.now();
if (now - domainCache.ts < 36e5)
return domainCache.url;
try {
const response = yield fetch(DOMAINS_URL);
const data = yield response.json();
if (data && data["4khdhub"]) {
domainCache.url = data["4khdhub"];
domainCache.ts = now;
}
} catch (e) {
}
return domainCache.url;
});
}
function fetchText(_0) {
return __async(this, arguments, function* (url, options = {}) {
const retries = options.retries !== void 0 ? options.retries : 2;
const delay = options.delay !== void 0 ? options.delay : 1e3;
for (let i = 0; i <= retries; i++) {
try {
const response = yield fetch(url, {
headers: __spreadValues({
"User-Agent": USER_AGENT
}, options.headers)
});
return yield response.text();
} catch (err) {
console.log(`[4KHDHub] Request failed for ${url}: ${err.message}${i < retries ? `, retrying (${i + 1}/${retries})...` : ""}`);
}
if (i < retries) {
yield new Promise((r) => setTimeout(r, delay * Math.pow(2, i)));
}
}
return null;
});
}
function getTmdbDetails(tmdbId, type) {
return __async(this, null, function* () {
const isSeries = type === "series" || type === "tv";
const endpoint = isSeries ? "tv" : "movie";
const url = `https://api.themoviedb.org/3/${endpoint}/${tmdbId}?api_key=${TMDB_API_KEY}`;
console.log(`[4KHDHub] Fetching TMDB details from: ${url}`);
try {
const response = yield fetch(url);
const data = yield response.json();
if (isSeries) {
return {
title: data.name,
year: data.first_air_date ? parseInt(data.first_air_date.split("-")[0]) : 0
};
} else {
return {
title: data.title,
year: data.release_date ? parseInt(data.release_date.split("-")[0]) : 0
};
}
} catch (error) {
console.log(`[4KHDHub] TMDB request failed: ${error.message}`);
return null;
}
});
}
function atob(input) {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
let str = String(input).replace(/=+$/, "");
if (str.length % 4 === 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
let output = "";
for (let bc = 0, bs, buffer, i = 0; buffer = str.charAt(i++); ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) {
buffer = chars.indexOf(buffer);
}
return output;
}
function rot13Cipher(str) {
return str.replace(/[a-zA-Z]/g, function(c) {
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
});
}
function levenshteinDistance(s, t) {
if (s === t)
return 0;
const n = s.length;
const m = t.length;
if (n === 0)
return m;
if (m === 0)
return n;
const d = [];
for (let i = 0; i <= n; i++) {
d[i] = [];
d[i][0] = i;
}
for (let j = 0; j <= m; j++) {
d[0][j] = j;
}
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
const cost = s.charAt(i - 1) === t.charAt(j - 1) ? 0 : 1;
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
}
}
return d[n][m];
}
function parseBytes(val) {
if (typeof val === "number")
return val;
if (!val)
return 0;
const match = val.match(/^([0-9.]+)\s*([a-zA-Z]+)$/);
if (!match)
return 0;
const num = parseFloat(match[1]);
const unit = match[2].toLowerCase();
let multiplier = 1;
if (unit.indexOf("k") === 0)
multiplier = 1024;
else if (unit.indexOf("m") === 0)
multiplier = 1024 * 1024;
else if (unit.indexOf("g") === 0)
multiplier = 1024 * 1024 * 1024;
else if (unit.indexOf("t") === 0)
multiplier = 1024 * 1024 * 1024 * 1024;
return num * multiplier;
}
function formatBytes(val) {
if (val === 0)
return "0 B";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB", "TB"];
let i = Math.floor(Math.log(val) / Math.log(k));
if (i < 0)
i = 0;
return parseFloat((val / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}
var cheerio = require("cheerio-without-node-native");
function fetchPageUrl(name, year, isSeries) {
return __async(this, null, function* () {
const domain = yield fetchLatestDomain();
const searchUrl = `${domain}/?s=${encodeURIComponent(name + " " + year)}`;
console.log(`[4KHDHub] Search Request URL: ${searchUrl}`);
const html = yield fetchText(searchUrl);
if (!html) {
console.log("[4KHDHub] Search failed: No HTML response");
return null;
}
const $ = cheerio.load(html);
const targetType = isSeries ? "Series" : "Movies";
console.log(`[4KHDHub] Parsing search results for type: ${targetType}`);
const matchingCards = $(".movie-card").filter((_, el) => {
const hasFormat = $(el).find(`.movie-card-format:contains("${targetType}")`).length > 0;
if (!hasFormat) {
}
return hasFormat;
}).filter((_, el) => {
const metaText = $(el).find(".movie-card-meta").text();
const movieCardYear = parseInt(metaText);
const yearMatch = !isNaN(movieCardYear) && Math.abs(movieCardYear - year) <= 1;
if (!yearMatch) {
console.log(`[4KHDHub] Skip: Year mismatch (${movieCardYear} vs ${year}) - ${$(el).find(".movie-card-title").text().trim()}`);
}
return yearMatch;
}).filter((_, el) => {
const movieCardTitle = $(el).find(".movie-card-title").text().replace(/\[.*?]/g, "").trim();
const distance = levenshteinDistance(movieCardTitle.toLowerCase(), name.toLowerCase());
const match = distance < 5;
console.log(`[4KHDHub] Checking: "${movieCardTitle}" (Dist: ${distance}) vs "${name}"`);
return match;
}).map((_, el) => {
let href = $(el).attr("href");
if (href && !href.startsWith("http")) {
href = domain + (href.startsWith("/") ? "" : "/") + href;
}
return href;
}).get();
if (matchingCards.length === 0) {
console.log("[4KHDHub] No matching cards found after filtering");
} else {
console.log(`[4KHDHub] Found ${matchingCards.length} matching cards`);
}
return matchingCards.length > 0 ? matchingCards[0] : null;
});
}
var cheerio2 = require("cheerio-without-node-native");
function resolveRedirectUrl(redirectUrl) {
return __async(this, null, function* () {
if (redirectUrl.includes("hubcloud.") || redirectUrl.includes("hubdrive.")) {
return redirectUrl;
}
const redirectHtml = yield fetchText(redirectUrl);
if (!redirectHtml)
return redirectUrl;
try {
const redirectDataMatch = redirectHtml.match(/'o','(.*?)'/);
if (!redirectDataMatch)
return redirectUrl;
const step1 = atob(redirectDataMatch[1]);
const step2 = atob(step1);
const step3 = rot13Cipher(step2);
const step4 = atob(step3);
const redirectData = JSON.parse(step4);
if (redirectData && redirectData.o) {
return atob(redirectData.o);
}
} catch (e) {
console.log(`[4KHDHub] Error resolving redirect: ${e.message}`);
}
return redirectUrl;
});
}
function extractSourceResults($, el) {
return __async(this, null, function* () {
const localHtml = $(el).html();
const sizeMatch = localHtml.match(/([\d.]+ ?[GM]B)/);
const heightMatch = localHtml.match(/\d{3,}p/);
const title = $(el).find(".file-title, .episode-file-title").text().trim();
let height = heightMatch ? parseInt(heightMatch[0]) : 0;
if (height === 0 && (title.includes("4K") || title.includes("4k") || localHtml.includes("4K") || localHtml.includes("4k"))) {
height = 2160;
}
const meta = {
bytes: sizeMatch ? parseBytes(sizeMatch[1]) : 0,
height,
title
};
const hblinksLink = $(el).find("a").filter((_, a) => {
const href = $(a).attr("href") || "";
return href.includes("hblinks") || href.includes("hubstream.dad");
}).attr("href");
if (hblinksLink) {
return { url: new URL(hblinksLink, BASE_URL).toString(), meta, extractor: "hblinks" };
}
const hubCloudLink = $(el).find("a").filter((_, a) => {
const text = $(a).text();
const href = $(a).attr("href") || "";
return text.includes("HubCloud") || href.includes("hubcloud.") || href.includes("hubcloud/");
}).attr("href");
if (hubCloudLink) {
const resolved = yield resolveRedirectUrl(hubCloudLink);
return { url: resolved, meta };
}
const hubDriveLink = $(el).find("a").filter((_, a) => {
const text = $(a).text();
const href = $(a).attr("href") || "";
return text.includes("HubDrive") || href.includes("hubdrive.") || href.includes("hubdrive/");
}).attr("href");
if (hubDriveLink) {
const resolvedDrive = yield resolveRedirectUrl(hubDriveLink);
if (resolvedDrive) {
const hubDriveHtml = yield fetchText(resolvedDrive);
if (hubDriveHtml) {
const $2 = cheerio2.load(hubDriveHtml);
const innerCloudLink = $2('a:contains("HubCloud")').attr("href") || $2("a").filter((_, a) => {
const text = $2(a).text();
const href = $2(a).attr("href") || "";
return text.includes("HubCloud") || href.includes("hubcloud.") || href.includes("hubcloud/");
}).attr("href");
if (innerCloudLink) {
return { url: innerCloudLink, meta };
}
}
}
}
return null;
});
}
function extractHubCloud(hubCloudUrl, baseMeta) {
return __async(this, null, function* () {
if (!hubCloudUrl)
return [];
const redirectHtml = yield fetchText(hubCloudUrl, { headers: { Referer: hubCloudUrl } });
if (!redirectHtml)
return [];
const redirectUrlMatch = redirectHtml.match(/var url ?= ?'(.*?)'/);
if (!redirectUrlMatch)
return [];
const finalLinksUrl = redirectUrlMatch[1];
const linksHtml = yield fetchText(finalLinksUrl, { headers: { Referer: hubCloudUrl } });
if (!linksHtml)
return [];
const $ = cheerio2.load(linksHtml);
const results = [];
const sizeText = $("#size").text();
const titleText = $("title").text().trim();
const currentMeta = __spreadProps(__spreadValues({}, baseMeta), {
bytes: parseBytes(sizeText) || baseMeta.bytes,
title: titleText || baseMeta.title
});
$("a").each((_, el) => {
const text = $(el).text().trim();
const href = $(el).attr("href");
if (!href)
return;
if (text.includes("10Gbps") || text.includes("PixelServer") || href.includes("hubcloud.cx")) {
results.push({
source: "HubCloud 10Gbps",
url: href,
meta: currentMeta
});
} else if (text.includes("Download File") || href.includes("r2.dev")) {
results.push({
source: "Direct R2",
url: href,
meta: currentMeta
});
} else if (text.includes("ZipDisk") || href.includes("workers.dev")) {
results.push({
source: "ZipDisk Server",
url: href,
meta: currentMeta
});
} else if (text.includes("FSL")) {
results.push({
source: "FSL",
url: href,
meta: currentMeta
});
}
});
return results;
});
}
function extractHblinks(hblinksUrl, baseMeta, depth = 0) {
return __async(this, null, function* () {
if (!hblinksUrl || depth > 2)
return [];
try {
const html = yield fetchText(hblinksUrl, { headers: { Referer: hblinksUrl } });
if (!html)
return [];
const $ = cheerio2.load(html);
const links = [...new Set($("h3 a, h5 a, div.entry-content p a, div.entry-content a").map((_, el) => $(el).attr("href")).get().filter(Boolean))];
const results = [];
for (const rawLink of links) {
try {
const absoluteLink = new URL(rawLink, hblinksUrl).toString();
const resolvedLink = yield resolveRedirectUrl(absoluteLink);
const link = resolvedLink || absoluteLink;
const hostname = new URL(link).hostname.toLowerCase();
if (hostname.includes("hblinks") || hostname.includes("hubstream.dad")) {
const nestedResults = yield extractHblinks(link, baseMeta, depth + 1);
results.push(...nestedResults);
} else if (hostname.includes("hubcloud")) {
const cloudResults = yield extractHubCloud(link, baseMeta);
results.push(...cloudResults);
} else if (hostname.includes("hubdrive")) {
const driveHtml = yield fetchText(link, { headers: { Referer: hblinksUrl } });
if (driveHtml) {
const $drive = cheerio2.load(driveHtml);
const cloudLink = $drive("a").filter((_, a) => {
const text = $drive(a).text();
const href = $drive(a).attr("href") || "";
return text.includes("HubCloud") || href.includes("hubcloud.") || href.includes("hubcloud/");
}).attr("href");
if (cloudLink) {
const absoluteCloudLink = new URL(cloudLink, link).toString();
const cloudResults = yield extractHubCloud(absoluteCloudLink, baseMeta);
results.push(...cloudResults);
}
}
} else if (/\.(m3u8|mpd|mp4|mkv)(?:$|\?)/i.test(link)) {
results.push({ source: "Hblinks Direct", url: link, meta: baseMeta });
}
} catch (e) {
}
}
return results;
} catch (e) {
return [];
}
});
}
var cheerio3 = require("cheerio-without-node-native");
function getStreams(tmdbId, type, season, episode) {
return __async(this, null, function* () {
const tmdbDetails = yield getTmdbDetails(tmdbId, type);
if (!tmdbDetails)
return [];
const { title, year } = tmdbDetails;
console.log(`[4KHDHub] Search: ${title} (${year})`);
const isSeries = type === "series" || type === "tv";
const pageUrl = yield fetchPageUrl(title, year, isSeries);
if (!pageUrl) {
console.log("[4KHDHub] Page not found");
return [];
}
console.log(`[4KHDHub] Found page: ${pageUrl}`);
const html = yield fetchText(pageUrl);
if (!html)
return [];
const $ = cheerio3.load(html);
const itemsToProcess = [];
if (isSeries && season && episode) {
const seasonStr = "S" + String(season).padStart(2, "0");
const episodeStr = "Episode-" + String(episode).padStart(2, "0");
$(".episode-item").each((_, el) => {
if ($(".episode-title", el).text().includes(seasonStr)) {
const downloadItems = $(".episode-download-item", el).filter((_2, item) => $(item).text().includes(episodeStr));
downloadItems.each((_2, item) => {
itemsToProcess.push(item);
});
}
});
} else {
$(".download-item").each((_, el) => {
itemsToProcess.push(el);
});
}
console.log(`[4KHDHub] Processing ${itemsToProcess.length} items`);
const streamPromises = itemsToProcess.map((item) => __async(this, null, function* () {
try {
const sourceResult = yield extractSourceResults($, item);
if (sourceResult && sourceResult.url) {
console.log(`[4KHDHub] Extracting from ${sourceResult.extractor === "hblinks" ? "Hblinks" : "HubCloud"}: ${sourceResult.url}`);
let extractedLinks;
if (sourceResult.extractor === "hblinks") {
extractedLinks = yield extractHblinks(sourceResult.url, sourceResult.meta);
} else {
extractedLinks = yield extractHubCloud(sourceResult.url, sourceResult.meta);
}
return extractedLinks.map((link) => ({
name: `4KHDHub - ${link.source}${sourceResult.meta.height ? ` ${sourceResult.meta.height}p` : ""}`,
title: `${link.meta.title}
${formatBytes(link.meta.bytes || 0)}`,
url: link.url,
quality: sourceResult.meta.height ? `${sourceResult.meta.height}p` : void 0,
behaviorHints: {
bingeGroup: `4khdhub-${link.source}`
}
}));
}
return [];
} catch (err) {
console.log(`[4KHDHub] Item processing error: ${err.message}`);
return [];
}
}));
const results = yield Promise.all(streamPromises);
return results.reduce((acc, val) => acc.concat(val), []);
});
}
module.exports = { getStreams };
+695
View File
@@ -0,0 +1,695 @@
/**
* animedekho - Built from src/animedekho/
* Generated: 2026-09-22T20:41:44.640Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/animedekho/index.js
var import_cheerio_without_node_native2 = __toESM(require("cheerio-without-node-native"));
// src/animedekho/constants.js
var MAIN_URL = "https://animedekho.app";
var TMDB_API_KEY = "1865f43a0549ca50d341dd9ab8b29f49";
var TMDB_BASE_URL = "https://api.themoviedb.org/3";
var USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
var HEADERS = {
"User-Agent": USER_AGENT,
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.5"
};
// src/animedekho/utils.js
function fetchTmdbDetails(tmdbId, mediaType) {
return __async(this, null, function* () {
var _a;
const endpoint = mediaType === "movie" ? "movie" : "tv";
const url = `${TMDB_BASE_URL}/${endpoint}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`;
try {
const res = yield fetch(url, { headers: HEADERS });
if (!res.ok)
return null;
const data = yield res.json();
return {
title: mediaType === "movie" ? data.title || data.original_title : data.name || data.original_name,
year: parseInt((data.release_date || data.first_air_date || "").substring(0, 4)) || null,
imdbId: ((_a = data.external_ids) == null ? void 0 : _a.imdb_id) || null
};
} catch (e) {
return null;
}
});
}
function cleanTitle(str) {
return (str || "").toLowerCase().replace(/[^a-z0-9\s]/g, "").replace(/\s+/g, " ").trim();
}
function titleSimilarity(a, b) {
const cleanA = cleanTitle(a);
const cleanB = cleanTitle(b);
if (!cleanA || !cleanB)
return 0;
if (cleanA === cleanB)
return 1;
if (cleanA.includes(cleanB) || cleanB.includes(cleanA))
return 0.8;
const wordsA = new Set(cleanA.split(" "));
const wordsB = new Set(cleanB.split(" "));
let intersection = 0;
for (const w of wordsA) {
if (wordsB.has(w))
intersection++;
}
return intersection * 2 / (wordsA.size + wordsB.size);
}
function unpack(code) {
try {
const match = code.match(/}\((['"])([\s\S]*?)\1,\s*(\d+),\s*(\d+),\s*(['"])([\s\S]*?)\5\.split\((['"])\|\7\)/);
if (match) {
let [_, quote1, p, a, c, quote2, kStr] = match;
p = p.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
const radix = parseInt(a);
let count = parseInt(c);
const k = kStr.split("|");
const e = (c2) => (c2 < radix ? "" : e(parseInt(c2 / radix))) + ((c2 = c2 % radix) > 35 ? String.fromCharCode(c2 + 29) : c2.toString(36));
const d = {};
while (count--)
d[e(count)] = k[count] || e(count);
return p.replace(/\b\w+\b/g, (w) => d[w]);
}
} catch (e) {
}
return code;
}
function isRealStreamUrl(url) {
if (!url || typeof url !== "string")
return false;
if (!url.startsWith("http://") && !url.startsWith("https://"))
return false;
const lowercase = url.toLowerCase();
if (lowercase.includes("/embed/") || lowercase.includes("/embed-") || lowercase.includes("/e/") || lowercase.includes("/play.php") || lowercase.includes("/player.php") || lowercase.includes("abyssplayer.com") || lowercase.includes("short.icu") || lowercase.includes("cloudy.upns.one") || lowercase.includes("vidcloud.upns.ink") || lowercase.includes("filesforever.link") || lowercase.includes("strmup.to") || lowercase.includes("emturbovid.com") || lowercase.includes("animedekho.app") || lowercase.includes("animesalt.cx") || lowercase.includes("youtube.com") || lowercase.includes("youtu.be") || lowercase.includes("vimeo.com") || lowercase.includes(".html") || lowercase.includes(".htm") || lowercase.includes(".php") || lowercase.includes("#")) {
return false;
}
const isHls = lowercase.includes(".m3u8");
const isMp4 = lowercase.includes(".mp4") || lowercase.includes("/sora/") || lowercase.includes("/stream/");
return isHls || isMp4 || lowercase.includes(".mkv") || lowercase.includes(".mpd");
}
function isPlayableStream(stream) {
return __async(this, null, function* () {
if (!isRealStreamUrl(stream == null ? void 0 : stream.url))
return false;
try {
const headers = __spreadProps(__spreadValues({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
}, stream.headers || {}), {
"Range": "bytes=0-10"
});
const res = yield fetch(stream.url, {
headers,
signal: AbortSignal.timeout(3e3)
});
if (!res.ok && res.status !== 206)
return false;
const contentType = res.headers.get("content-type") || "";
if (contentType.includes("text/html"))
return false;
return true;
} catch (e) {
return false;
}
});
}
// src/animedekho/extractors.js
var import_cheerio_without_node_native = __toESM(require("cheerio-without-node-native"));
function extractStreamRuby(url) {
return __async(this, null, function* () {
try {
const cleanedUrl = url.replace("/e/", "/");
const res = yield fetch(cleanedUrl, {
headers: __spreadProps(__spreadValues({}, HEADERS), {
"X-Requested-With": "XMLHttpRequest",
"Referer": cleanedUrl
})
});
if (!res.ok)
return null;
const html = yield res.text();
let m3u8 = null;
const packedMatch = html.match(/eval\(function\(p,a,c,k,e,d\)[\s\S]*?\.split\(['"]\|['"]\)\)/);
if (packedMatch) {
const unpacked = unpack(packedMatch[0]);
const match = unpacked.match(/file\s*:\s*["'](https?:\/\/[^"']+\.m3u8[^"']*)["']/);
if (match)
m3u8 = match[1];
}
if (!m3u8) {
const directMatch = html.match(/file\s*:\s*["'](https?:\/\/[^"']+\.m3u8[^"']*)["']/);
if (directMatch)
m3u8 = directMatch[1];
}
if (!m3u8)
return null;
const origin = new URL(cleanedUrl).origin;
return {
name: "AnimeDekho [StreamRuby] (Auto M3U8)",
url: m3u8,
quality: "720p",
headers: {
"Origin": origin,
"Referer": `${cleanedUrl}/`,
"User-Agent": HEADERS["User-Agent"]
},
type: "m3u8"
};
} catch (e) {
return null;
}
});
}
function extractVidmoly(url) {
return __async(this, null, function* () {
try {
const res = yield fetch(url, {
headers: __spreadProps(__spreadValues({}, HEADERS), {
"Referer": "https://animedekho.app/"
})
});
if (!res.ok)
return null;
const html = yield res.text();
const match = html.match(/file\s*:\s*["'](https?:\/\/[^"'\s]+\.m3u8[^"'\s]*)["']/);
if (!match || !match[1])
return null;
const origin = new URL(url).origin;
return {
name: "AnimeDekho [Vidmoly] (Auto M3U8)",
url: match[1],
quality: "1080p",
headers: {
"Referer": `${origin}/`,
"Origin": origin,
"User-Agent": HEADERS["User-Agent"]
},
type: "m3u8"
};
} catch (e) {
return null;
}
});
}
function extractAbyss(url, langName = "Default") {
return __async(this, null, function* () {
var _a;
try {
const cleanUrl = url.replace("https://short.icu", "https://abyssplayer.com");
const reqHeaders = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36",
"Origin": "https://playhydrax.com",
"Referer": "https://playhydrax.com/"
};
const res = yield fetch(cleanUrl, { headers: reqHeaders });
if (!res.ok)
return [];
const html = yield res.text();
const match = html.match(/const\s+datas\s*=\s*"([^"]*)"/);
if (!match || !match[1])
return [];
const decRes = yield fetch("https://enc-dec.app/api/dec-abyss", {
method: "POST",
headers: __spreadProps(__spreadValues({}, reqHeaders), {
"Content-Type": "application/json"
}),
body: JSON.stringify({ text: match[1] })
});
if (!decRes.ok)
return [];
const decData = yield decRes.json();
const sources = ((_a = decData == null ? void 0 : decData.result) == null ? void 0 : _a.sources) || [];
return sources.filter((s) => s && s.url && s.status).map((s) => {
const codec = (s.codec || "MP4").toUpperCase();
const quality = s.type || "720p";
return {
name: `AnimeDekho [${langName}] (${codec} ${quality})`,
url: s.url,
quality,
headers: {
"Referer": "https://playhydrax.com/",
"Origin": "https://playhydrax.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
},
type: s.url.includes(".m3u8") ? "m3u8" : "mp4"
};
});
} catch (e) {
return [];
}
});
}
function extractAwsStream(url) {
return __async(this, null, function* () {
try {
const hash = url.split("/").filter(Boolean).pop();
if (!hash)
return null;
const origin = new URL(url).origin;
const res = yield fetch(url, { headers: HEADERS });
if (!res.ok)
return null;
const html = yield res.text();
const postUrl = `${origin}/player/index.php?data=${hash}&do=getVideo`;
const postRes = yield fetch(postUrl, {
method: "POST",
headers: __spreadProps(__spreadValues({}, HEADERS), {
"x-requested-with": "XMLHttpRequest",
"Origin": origin,
"Referer": url,
"Content-Type": "application/x-www-form-urlencoded"
}),
body: `hash=${encodeURIComponent(hash)}&r=${encodeURIComponent(origin)}`
});
if (!postRes.ok)
return null;
const json = yield postRes.json();
const m3u8 = json == null ? void 0 : json.videoSource;
if (!m3u8)
return null;
let subtitle = null;
const packedMatch = html.match(/eval\(function\(p,a,c,k,e,d\)[\s\S]*?\.split\(['"]\|['"]\)\)/);
if (packedMatch) {
const unpacked = unpack(packedMatch[0]);
const subMatch = unpacked.match(/"kind":\s*"captions"\s*,\s*"file":\s*"(https?:\/\/[^"]+)"/);
if (subMatch) {
subtitle = subMatch[1].replace(/\\/g, "");
}
}
return {
name: "AnimeDekho [AWSStream] (Auto M3U8)",
url: m3u8,
quality: "1080p",
headers: {
"Referer": `${origin}/`,
"Origin": origin,
"User-Agent": HEADERS["User-Agent"]
},
subtitles: subtitle ? [{ lang: "English", url: subtitle }] : [],
type: "m3u8"
};
} catch (e) {
return null;
}
});
}
function extractStreamWish(url) {
return __async(this, null, function* () {
try {
const embedUrl = url.includes("/e/") ? url : url.includes("/embed/") ? url : url.replace("/f/", "/e/");
const res = yield fetch(embedUrl, { headers: HEADERS });
if (!res.ok)
return null;
const html = yield res.text();
const packedMatch = html.match(/eval\(function\(p,a,c,k,e,d\)[\s\S]*?\.split\(['"]\|['"]\)\)/);
if (packedMatch) {
const unpacked = unpack(packedMatch[0]);
const fileMatch = unpacked.match(/file\s*:\s*["'](https?:\/\/[^"'\s]+\.m3u8(?:\?[^"'\s]*)?)["']/);
if (fileMatch) {
const origin = new URL(embedUrl).origin;
return {
name: "AnimeDekho [StreamWish] (Auto M3U8)",
url: fileMatch[1],
quality: "720p",
headers: {
"Referer": `${origin}/`,
"Origin": origin,
"User-Agent": HEADERS["User-Agent"]
},
type: "m3u8"
};
}
}
} catch (e) {
}
return null;
});
}
function extractBlakite(url) {
return __async(this, null, function* () {
var _a;
try {
const id = url.split("/").filter(Boolean).pop();
const tmdbMatch = url.match(/embed\/([^/]+)/);
const tmdbId = tmdbMatch ? tmdbMatch[1] : "";
const apiUrl = `https://blakiteapi.xyz/api/get.php?id=${id}&tmdbId=${tmdbId}`;
const res = yield fetch(apiUrl, { headers: HEADERS });
if (!res.ok)
return null;
const json = yield res.json();
if (!(json == null ? void 0 : json.success) || !((_a = json == null ? void 0 : json.data) == null ? void 0 : _a.dataId))
return null;
const dataId = json.data.dataId;
const format = json.data.format || "mp4";
const quality = json.data.quality || "720p";
const streamUrl = `https://blakiteapi.xyz/stream/${dataId}.${format}`;
return {
name: `AnimeDekho [Blakite] (${quality})`,
url: streamUrl,
quality,
headers: {
"Referer": "https://blakiteapi.xyz/",
"User-Agent": HEADERS["User-Agent"]
},
type: format.toLowerCase().includes("m3u8") ? "m3u8" : "mp4"
};
} catch (e) {
return null;
}
});
}
function extractVidStack(url) {
return __async(this, null, function* () {
try {
const hash = url.split("#").pop().split("/").pop();
if (!hash)
return null;
const origin = new URL(url).origin;
const res = yield fetch(`${origin}/api/v1/video?id=${hash}`, {
headers: HEADERS
});
if (!res.ok)
return null;
const text = (yield res.text()).trim();
const match = text.match(/https?:\/\/[^"'\s]+\.m3u8[^"'\s]*/);
if (!match)
return null;
return {
name: "AnimeDekho [VidStack] (Auto M3U8)",
url: match[0],
quality: "720p",
headers: {
"Referer": `${origin}/`,
"User-Agent": HEADERS["User-Agent"]
},
type: "m3u8"
};
} catch (e) {
return null;
}
});
}
// src/animedekho/index.js
function searchAnimeDekho(query) {
return __async(this, null, function* () {
try {
const url = `${MAIN_URL}/?s=${encodeURIComponent(query)}`;
const res = yield fetch(url, { headers: HEADERS });
if (!res.ok)
return [];
const html = yield res.text();
const $ = import_cheerio_without_node_native2.default.load(html);
const results = [];
$("ul[data-results] li article, article.post, article").each((_, el) => {
const title = $(el).find("header h2, h2").text().trim();
const href = $(el).find("a.lnk-blk, a").first().attr("href");
if (title && href) {
results.push({ title, href });
}
});
return results;
} catch (e) {
return [];
}
});
}
function getStreams(tmdbId, mediaType, seasonNum = 1, episodeNum = 1) {
return __async(this, null, function* () {
try {
const details = yield fetchTmdbDetails(tmdbId, mediaType);
if (!details || !details.title)
return [];
let results = yield searchAnimeDekho(details.title);
if (results.length === 0) {
const cleaned = cleanTitle(details.title);
if (cleaned && cleaned !== details.title.toLowerCase()) {
results = yield searchAnimeDekho(cleaned);
}
}
if (results.length === 0)
return [];
let bestMatch = null;
let highestSim = 0;
for (const item of results) {
const sim = titleSimilarity(details.title, item.title);
if (sim > highestSim) {
highestSim = sim;
bestMatch = item;
}
}
if (!bestMatch || highestSim < 0.2) {
bestMatch = results[0];
}
let targetUrl = bestMatch.href;
const mediaTypeVal = mediaType === "movie" ? 1 : 2;
if (mediaType === "tv") {
const seriesRes = yield fetch(bestMatch.href, {
headers: __spreadProps(__spreadValues({}, HEADERS), {
"Cookie": "toronites_server=vidstream"
})
});
if (!seriesRes.ok)
return [];
const seriesHtml = yield seriesRes.text();
const $series = import_cheerio_without_node_native2.default.load(seriesHtml);
let targetEpUrl = null;
const epElements = $series("ul.seasons-lst li");
epElements.each((_, el) => {
const epText = $series(el).find("h3.title").text().trim();
const epHref = $series(el).find("a").first().attr("href");
if (epText && epHref) {
const sMatch = epText.match(/S(\d+)[\s-]*E(\d+)/i) || epText.match(/(\d+)x(\d+)/i);
if (sMatch) {
const s = parseInt(sMatch[1]);
const e = parseInt(sMatch[2]);
if (s === seasonNum && e === episodeNum) {
targetEpUrl = epHref;
}
} else if (epText.includes(`E${episodeNum}`) || epText.includes(`Episode ${episodeNum}`)) {
if (seasonNum === 1)
targetEpUrl = epHref;
}
}
});
if (!targetEpUrl && epElements.length >= episodeNum && seasonNum === 1) {
targetEpUrl = $series(epElements[episodeNum - 1]).find("a").first().attr("href");
}
if (targetEpUrl) {
targetUrl = targetEpUrl;
}
}
const pageRes = yield fetch(targetUrl, {
headers: __spreadProps(__spreadValues({}, HEADERS), {
"Cookie": "toronites_server=vidstream"
})
});
if (!pageRes.ok)
return [];
const pageHtml = yield pageRes.text();
const $page = import_cheerio_without_node_native2.default.load(pageHtml);
const iframeUrls = /* @__PURE__ */ new Set();
const serverPromises = [];
$page("iframe.serversel[src], iframe[src]").each((_, el) => {
const src = $page(el).attr("src");
if (src && !src.startsWith("about:") && !src.startsWith("javascript:")) {
const fullSrc = src.startsWith("//") ? `https:${src}` : src.startsWith("http") ? src : `${MAIN_URL}${src}`;
if (fullSrc.includes("animedekho.app/embed/")) {
serverPromises.push(
fetch(fullSrc, { headers: HEADERS }).then((r) => __async(this, null, function* () {
if (!r.ok)
return;
const h = yield r.text();
const $inner = import_cheerio_without_node_native2.default.load(h);
$inner("iframe[src]").each((_2, iEl) => {
const iSrc = $inner(iEl).attr("src");
if (iSrc && !iSrc.startsWith("about:"))
iframeUrls.add(iSrc);
});
})).catch(() => {
})
);
} else {
iframeUrls.add(fullSrc);
}
}
});
yield Promise.allSettled(serverPromises);
const bodyClass = $page("body").attr("class") || "";
const termMatch = bodyClass.match(/(?:term|postid)-(\d+)/);
if (termMatch && termMatch[1]) {
const termId = termMatch[1];
const trdekhoPromises = [];
for (let i = 0; i <= 10; i++) {
const trUrl = `${MAIN_URL}/?trdekho=${i}&trid=${termId}&trtype=${mediaTypeVal}`;
trdekhoPromises.push(
fetch(trUrl, { headers: HEADERS }).then((r) => __async(this, null, function* () {
if (!r.ok)
return;
const h = yield r.text();
const $tr = import_cheerio_without_node_native2.default.load(h);
const iSrc = $tr("iframe").attr("src");
if (iSrc && !iSrc.startsWith("about:")) {
const full = iSrc.startsWith("//") ? `https:${iSrc}` : iSrc.startsWith("http") ? iSrc : `${MAIN_URL}${iSrc}`;
iframeUrls.add(full);
}
})).catch(() => {
})
);
}
yield Promise.allSettled(trdekhoPromises);
}
const streams = [];
const extractPromises = [];
for (const iframeUrl of iframeUrls) {
if (iframeUrl.includes("rubystm.com") || iframeUrl.includes("streamruby")) {
extractPromises.push(
extractStreamRuby(iframeUrl).then((s) => {
if (s)
streams.push(s);
})
);
} else if (iframeUrl.includes("vidmoly")) {
extractPromises.push(
extractVidmoly(iframeUrl).then((s) => {
if (s)
streams.push(s);
})
);
} else if (iframeUrl.includes("abyssplayer.com") || iframeUrl.includes("short.icu")) {
extractPromises.push(
extractAbyss(iframeUrl, "Default").then((res) => {
if (Array.isArray(res))
streams.push(...res);
})
);
} else if (iframeUrl.includes("as-cdn") || iframeUrl.includes("awstream") || iframeUrl.includes("zephyrflick")) {
extractPromises.push(
extractAwsStream(iframeUrl).then((s) => {
if (s)
streams.push(s);
})
);
} else if (iframeUrl.includes("filesforever.link") || iframeUrl.includes("cdnwish") || iframeUrl.includes("multimovies") || iframeUrl.includes("streamwish")) {
extractPromises.push(
extractStreamWish(iframeUrl).then((s) => {
if (s)
streams.push(s);
})
);
} else if (iframeUrl.includes("blakiteapi.xyz")) {
extractPromises.push(
extractBlakite(iframeUrl).then((s) => {
if (s)
streams.push(s);
})
);
} else if (iframeUrl.includes("cloudy.upns.one") || iframeUrl.includes("vidcloud.upns.ink")) {
extractPromises.push(
extractVidStack(iframeUrl).then((s) => {
if (s)
streams.push(s);
})
);
}
}
yield Promise.allSettled(extractPromises);
const seenUrls = /* @__PURE__ */ new Set();
const candidateStreams = [];
for (const s of streams) {
if (s && s.url && !seenUrls.has(s.url) && isRealStreamUrl(s.url)) {
seenUrls.add(s.url);
candidateStreams.push({
name: s.name || "AnimeDekho",
title: mediaType === "movie" ? details.title : `${details.title} - S${seasonNum}E${episodeNum}`,
url: s.url,
quality: s.quality || "Auto",
headers: s.headers,
subtitles: s.subtitles || [],
provider: "animedekho",
type: s.type || "m3u8"
});
}
}
const probeResults = yield Promise.all(
candidateStreams.map((s) => __async(this, null, function* () {
return { stream: s, playable: yield isPlayableStream(s) };
}))
);
let finalStreams = probeResults.filter((r) => r.playable).map((r) => r.stream);
if (finalStreams.length === 0)
finalStreams = candidateStreams;
const qualityOrder = { "1080p": 4, "720p": 3, "480p": 2, "360p": 1, "Auto": 0 };
return finalStreams.sort((a, b) => {
var _a, _b;
return ((_a = qualityOrder[b.quality]) != null ? _a : 0) - ((_b = qualityOrder[a.quality]) != null ? _b : 0);
});
} catch (e) {
return [];
}
});
}
module.exports = { getStreams };
+593 -1
View File
@@ -1 +1,593 @@
const _0x1d73f4=_0x3e95;(function(_0x59e55d,_0x1dbedb){const _0x18c825=_0x3e95,_0x510f3b=_0x59e55d();while(!![]){try{const _0x3d1169=parseInt(_0x18c825(0x1be))/0x1+parseInt(_0x18c825(0x1ba))/0x2*(parseInt(_0x18c825(0x1e5))/0x3)+-parseInt(_0x18c825(0x202))/0x4*(-parseInt(_0x18c825(0x1ec))/0x5)+-parseInt(_0x18c825(0x1f7))/0x6*(-parseInt(_0x18c825(0x1cb))/0x7)+parseInt(_0x18c825(0x1b7))/0x8+parseInt(_0x18c825(0x1d8))/0x9*(-parseInt(_0x18c825(0x1d1))/0xa)+parseInt(_0x18c825(0x213))/0xb*(-parseInt(_0x18c825(0x1f8))/0xc);if(_0x3d1169===_0x1dbedb)break;else _0x510f3b['push'](_0x510f3b['shift']());}catch(_0x15a0de){_0x510f3b['push'](_0x510f3b['shift']());}}}(_0x131e,0x6e357));var __create=Object[_0x1d73f4(0x1d3)],__defProp=Object[_0x1d73f4(0x1d6)],__defProps=Object[_0x1d73f4(0x1a9)],__getOwnPropDesc=Object['getOwnPropertyDescriptor'],__getOwnPropDescs=Object[_0x1d73f4(0x20e)],__getOwnPropNames=Object[_0x1d73f4(0x1fd)],__getOwnPropSymbols=Object[_0x1d73f4(0x1f2)],__getProtoOf=Object[_0x1d73f4(0x1ed)],__hasOwnProp=Object[_0x1d73f4(0x1dd)]['hasOwnProperty'],__propIsEnum=Object['prototype']['propertyIsEnumerable'],__defNormalProp=(_0x537b5d,_0x312257,_0x145bab)=>_0x312257 in _0x537b5d?__defProp(_0x537b5d,_0x312257,{'enumerable':!![],'configurable':!![],'writable':!![],'value':_0x145bab}):_0x537b5d[_0x312257]=_0x145bab,__spreadValues=(_0x454d4c,_0x10c821)=>{const _0x1d55b3=_0x1d73f4;for(var _0x5ca226 in _0x10c821||(_0x10c821={}))if(__hasOwnProp[_0x1d55b3(0x214)](_0x10c821,_0x5ca226))__defNormalProp(_0x454d4c,_0x5ca226,_0x10c821[_0x5ca226]);if(__getOwnPropSymbols)for(var _0x5ca226 of __getOwnPropSymbols(_0x10c821)){if(__propIsEnum['call'](_0x10c821,_0x5ca226))__defNormalProp(_0x454d4c,_0x5ca226,_0x10c821[_0x5ca226]);}return _0x454d4c;},__spreadProps=(_0x3a8cb0,_0x2a9c46)=>__defProps(_0x3a8cb0,__getOwnPropDescs(_0x2a9c46)),__objRest=(_0x267409,_0x2a986e)=>{const _0x1f55b1=_0x1d73f4;var _0x4078ae={};for(var _0x37e51c in _0x267409)if(__hasOwnProp[_0x1f55b1(0x214)](_0x267409,_0x37e51c)&&_0x2a986e[_0x1f55b1(0x1ea)](_0x37e51c)<0x0)_0x4078ae[_0x37e51c]=_0x267409[_0x37e51c];if(_0x267409!=null&&__getOwnPropSymbols)for(var _0x37e51c of __getOwnPropSymbols(_0x267409)){if(_0x2a986e[_0x1f55b1(0x1ea)](_0x37e51c)<0x0&&__propIsEnum[_0x1f55b1(0x214)](_0x267409,_0x37e51c))_0x4078ae[_0x37e51c]=_0x267409[_0x37e51c];}return _0x4078ae;},__copyProps=(_0x257f25,_0x2649d8,_0xdbf521,_0x41706a)=>{const _0x4bd517=_0x1d73f4;if(_0x2649d8&&typeof _0x2649d8===_0x4bd517(0x212)||typeof _0x2649d8===_0x4bd517(0x1cf)){for(let _0x5e4956 of __getOwnPropNames(_0x2649d8))if(!__hasOwnProp[_0x4bd517(0x214)](_0x257f25,_0x5e4956)&&_0x5e4956!==_0xdbf521)__defProp(_0x257f25,_0x5e4956,{'get':()=>_0x2649d8[_0x5e4956],'enumerable':!(_0x41706a=__getOwnPropDesc(_0x2649d8,_0x5e4956))||_0x41706a[_0x4bd517(0x1c6)]});}return _0x257f25;},__toESM=(_0x55ba45,_0x23f426,_0x31a83c)=>(_0x31a83c=_0x55ba45!=null?__create(__getProtoOf(_0x55ba45)):{},__copyProps(_0x23f426||!_0x55ba45||!_0x55ba45['__esModule']?__defProp(_0x31a83c,_0x1d73f4(0x1b4),{'value':_0x55ba45,'enumerable':!![]}):_0x31a83c,_0x55ba45)),__async=(_0x1abd7c,_0x51d469,_0x4db3b0)=>{return new Promise((_0x1cb0f7,_0x58ba9a)=>{const _0x5006dd=_0x3e95;var _0x16f488=_0x2becae=>{const _0x4f80c0=_0x3e95;try{_0x3ddc4b(_0x4db3b0[_0x4f80c0(0x1b0)](_0x2becae));}catch(_0x4fff13){_0x58ba9a(_0x4fff13);}},_0x446bda=_0x2a96d8=>{try{_0x3ddc4b(_0x4db3b0['throw'](_0x2a96d8));}catch(_0x4ee400){_0x58ba9a(_0x4ee400);}},_0x3ddc4b=_0x28cd85=>_0x28cd85['done']?_0x1cb0f7(_0x28cd85[_0x5006dd(0x1ae)]):Promise[_0x5006dd(0x1ca)](_0x28cd85[_0x5006dd(0x1ae)])[_0x5006dd(0x1f6)](_0x16f488,_0x446bda);_0x3ddc4b((_0x4db3b0=_0x4db3b0[_0x5006dd(0x1fb)](_0x1abd7c,_0x51d469))[_0x5006dd(0x1b0)]());});},import_cheerio_without_node_native=__toESM(require(_0x1d73f4(0x1ff))),MAIN_URL=_0x1d73f4(0x207),PROXY_URL=_0x1d73f4(0x1c1),HEADERS={'User-Agent':'Mozilla/5.0\x20(Windows\x20NT\x2010.0;\x20Win64;\x20x64)\x20Chrome/120.0.0.0\x20Safari/537.36','Cookie':_0x1d73f4(0x201),'Referer':_0x1d73f4(0x1e1)};function fetchText(_0x53d5e8){return __async(this,arguments,function*(_0x3a9d6b,_0x3f7815={}){const _0x22182a=_0x3e95,_0x263547=_0x3f7815,{useProxy:useProxy=!![]}=_0x263547,_0x5368ce=__objRest(_0x263547,[_0x22182a(0x20a)]),_0x3553fa=_0x3a9d6b[_0x22182a(0x1e3)](_0x22182a(0x1cd))?_0x3a9d6b:''+MAIN_URL+_0x3a9d6b,_0x23e259=useProxy?''+PROXY_URL+encodeURIComponent(_0x3553fa):_0x3553fa,_0x53e991=yield fetch(_0x23e259,__spreadValues({'headers':HEADERS},_0x5368ce));if(!_0x53e991['ok'])throw new Error('HTTP\x20'+_0x53e991[_0x22182a(0x1fc)]+_0x22182a(0x1c5)+_0x3553fa);return yield _0x53e991[_0x22182a(0x210)]();});}function fetchJson(_0xbe08be){return __async(this,arguments,function*(_0x290be1,_0x1fec65={}){const _0x6a80f1=_0x3e95,_0x562e16=yield fetchText(_0x290be1,_0x1fec65);return JSON[_0x6a80f1(0x1bd)](_0x562e16);});}function getImdbId(_0x34ed2f,_0x226466){return __async(this,null,function*(){const _0x404dbd=_0x3e95;try{const _0x42212d=_0x404dbd(0x1e6)+(_0x226466==='tv'?'tv':'movieLine truncated
/**
* animepahe - Built from src/animepahe/
* Generated: 2026-09-22T10:30:55.503Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/animepahe/index.js
var import_cheerio_without_node_native = __toESM(require("cheerio-without-node-native"));
// src/animepahe/constants.js
var ANIMEPAHE_DOMAINS = [
"https://animepahe.pw",
"https://animepahe.com",
"https://animepahe.org"
];
var MAIN_URL = "https://animepahe.pw";
var TMDB_API_KEY = "439c478a771f35c05022f9feabcca01c";
var USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36";
var HEADERS = {
"User-Agent": USER_AGENT,
"Accept": "application/json, text/plain, */*",
"Referer": `${MAIN_URL}/`
};
// src/animepahe/utils.js
var activeDomain = MAIN_URL;
function fetchText(_0) {
return __async(this, arguments, function* (url, options = {}) {
const isAbsolute = url.startsWith("http");
const urlsToTry = isAbsolute ? [url] : ANIMEPAHE_DOMAINS.map((d) => `${d}${url.startsWith("/") ? "" : "/"}${url}`);
let lastError = null;
for (const tryUrl of urlsToTry) {
try {
const isPaheUrl = tryUrl.includes("animepahe.");
const mergedHeaders = __spreadValues(__spreadProps(__spreadValues({}, HEADERS), {
"Referer": `${activeDomain}/`
}), options.headers || {});
let response = yield fetch(tryUrl, __spreadValues({
headers: mergedHeaders,
cfKiller: isPaheUrl,
skipSizeCheck: true
}, options));
if ((response.status === 403 || response.status === 503) && typeof Cloudflare !== "undefined" && Cloudflare.solve) {
try {
const solvedHeaders = yield Cloudflare.solve(tryUrl);
if (solvedHeaders["Cookie"])
mergedHeaders["Cookie"] = solvedHeaders["Cookie"];
if (solvedHeaders["User-Agent"])
mergedHeaders["User-Agent"] = solvedHeaders["User-Agent"];
response = yield fetch(tryUrl, __spreadValues({
headers: mergedHeaders,
skipSizeCheck: true
}, options));
} catch (_) {
}
}
if (response.ok) {
if (!isAbsolute) {
const match = tryUrl.match(/^(https?:\/\/[^\/]+)/);
if (match)
activeDomain = match[1];
}
return yield response.text();
}
lastError = new Error(`HTTP ${response.status} on ${tryUrl}`);
} catch (e) {
lastError = e;
}
}
throw lastError || new Error(`Failed to fetch: ${url}`);
});
}
function fetchJson(_0) {
return __async(this, arguments, function* (url, options = {}) {
const text = yield fetchText(url, options);
return JSON.parse(text);
});
}
function getImdbId(tmdbId, mediaType) {
return __async(this, null, function* () {
try {
const url = `https://api.themoviedb.org/3/${mediaType === "tv" ? "tv" : "movie"}/${tmdbId}/external_ids?api_key=${TMDB_API_KEY}`;
const res = yield fetch(url);
const data = yield res.json();
return data.imdb_id;
} catch (_) {
return null;
}
});
}
function resolveMapping(imdbId, season, episode) {
return __async(this, null, function* () {
try {
const url = `https://id-mapping-api-malid.hf.space/api/resolve?id=${imdbId}&s=${season}&e=${episode}`;
const res = yield fetch(url);
if (!res.ok)
return null;
return yield res.json();
} catch (_) {
return null;
}
});
}
function getMalTitle(malId) {
return __async(this, null, function* () {
var _a, _b;
try {
const res = yield fetch(`https://api.jikan.moe/v4/anime/${malId}`);
if (!res.ok)
return null;
const data = yield res.json();
return ((_a = data.data) == null ? void 0 : _a.title) || ((_b = data.data) == null ? void 0 : _b.title_english);
} catch (_) {
return null;
}
});
}
function searchAnime(query, page = 1) {
return __async(this, null, function* () {
const timeSuffix = Math.floor(Date.now() / 1e3) + page * 3;
const url = `/api?m=search&q=${encodeURIComponent(query + " " + timeSuffix)}&page=${page}`;
return yield fetchJson(url);
});
}
function extractQuality(text) {
const match = text.match(/(\d{3,4}p)/);
return match ? match[1] : "720p";
}
// src/animepahe/extractors.js
function unpack(code) {
try {
const match = code.match(/}\((['"])([\s\S]*?)\1,\s*(\d+),\s*(\d+),\s*(['"])([\s\S]*?)\5\.split\((['"])\|\7\)/);
if (match) {
let [_, quote1, p, a, c, quote2, kStr] = match;
p = p.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
a = parseInt(a, 10);
c = parseInt(c, 10);
const k = kStr.split("|");
const e = (c2) => (c2 < a ? "" : e(parseInt(c2 / a, 10))) + ((c2 = c2 % a) > 35 ? String.fromCharCode(c2 + 29) : c2.toString(36));
const d = {};
while (c--)
d[e(c)] = k[c] || e(c);
return p.replace(/\b\w+\b/g, (w) => d[w] !== void 0 ? d[w] : w);
}
} catch (_) {
}
return code;
}
function extractKwik(url) {
return __async(this, null, function* () {
try {
const res = yield fetch(url, {
headers: __spreadProps(__spreadValues({}, HEADERS), {
"Referer": `${MAIN_URL}/`,
"User-Agent": USER_AGENT
}),
cfKiller: true,
skipSizeCheck: true
});
const finalUrl = res.url || url;
const html = yield res.text();
const scripts = html.match(/<script.*?>([\s\S]*?)<\/script>/g) || [];
const matches = [];
for (const script of scripts) {
if (script.includes("eval(function(p,a,c,k,e,d)")) {
let pos = 0;
while (true) {
const start = script.indexOf("eval(function(p,a,c,k,e,d)", pos);
if (start === -1)
break;
const end = script.indexOf(".split('|')", start);
if (end === -1)
break;
const closeParen = script.indexOf("))", end);
if (closeParen === -1)
break;
matches.push(script.substring(start, closeParen + 2));
pos = closeParen + 2;
}
}
}
for (const scriptContent of matches) {
const unpacked = unpack(scriptContent);
const srcMatch = unpacked.match(/(?:const\s+)?source\s*=\s*\\?['"]([^\\'"]+)\\?['"]/);
if (srcMatch) {
const streamUrl = srcMatch[1];
const titleMatch = html.match(/<title>([\s\S]*?)<\/title>/);
const title = titleMatch ? titleMatch[1].trim() : "video";
const fileName = title.endsWith(".mp4") ? title : `${title}.mp4`;
let mp4Url = null;
if (streamUrl.includes("/stream/")) {
const urlParts = streamUrl.replace("/stream/", "/mp4/").split("/");
urlParts.pop();
const mp4Base = urlParts.join("/");
mp4Url = `${mp4Base}?file=${encodeURIComponent(fileName)}`;
}
return {
m3u8: streamUrl,
mp4: mp4Url,
headers: {
"Referer": finalUrl,
"Origin": "https://kwik.cx",
"User-Agent": USER_AGENT
}
};
}
}
} catch (_) {
}
return null;
});
}
function paheDecrypt(fullString, key, v1, v2) {
const keyIndexMap = {};
for (let i2 = 0; i2 < key.length; i2++)
keyIndexMap[key[i2]] = i2;
let result = "";
let i = 0;
const toFind = key[v2];
while (i < fullString.length) {
const nextIndex = fullString.indexOf(toFind, i);
if (nextIndex === -1)
break;
let decodedCharStr = "";
for (let j = i; j < nextIndex; j++) {
decodedCharStr += keyIndexMap[fullString[j]];
}
i = nextIndex + 1;
const decodedChar = String.fromCharCode(parseInt(decodedCharStr, v2) - v1);
result += decodedChar;
}
return result;
}
function extractPahe(url) {
return __async(this, null, function* () {
try {
const initUrl = url.endsWith("/i") ? url : `${url}/i`;
const initRes = yield fetch(initUrl, {
method: "GET",
redirect: "manual",
headers: {
"User-Agent": USER_AGENT,
"Referer": "https://pahe.win/"
},
cfKiller: true,
skipSizeCheck: true
});
const redirectLoc = initRes.headers.get("location") || initRes.headers.get("Location");
if (!redirectLoc)
return null;
let kwikUrl = redirectLoc;
if (kwikUrl.includes("https://")) {
kwikUrl = "https://" + kwikUrl.split("https://").pop();
} else if (kwikUrl.includes("http://")) {
kwikUrl = "http://" + kwikUrl.split("http://").pop();
} else {
kwikUrl = `https://${kwikUrl.replace(/^\/+/, "")}`;
}
const kwikRes = yield fetch(kwikUrl, {
method: "GET",
headers: {
"User-Agent": USER_AGENT,
"Referer": "https://kwik.cx/",
"Origin": "https://kwik.cx"
},
cfKiller: true,
skipSizeCheck: true
});
const html = yield kwikRes.text();
let cookie = "";
if (typeof kwikRes.headers.getSetCookie === "function") {
cookie = kwikRes.headers.getSetCookie().map((c) => c.split(";")[0]).join("; ");
}
if (!cookie) {
const setCookieHeader = kwikRes.headers.get("set-cookie") || kwikRes.headers.get("Set-Cookie");
if (setCookieHeader) {
cookie = setCookieHeader.split(";")[0];
}
}
const kwikParamsRegex = /\("(\w+)",\d+,"(\w+)",(\d+),(\d+),\d+\)/;
const match = html.match(kwikParamsRegex);
if (!match)
return null;
const [_, fullString, key, v1, v2] = match;
const decrypted = paheDecrypt(fullString, key, parseInt(v1, 10), parseInt(v2, 10));
const actionMatch = decrypted.match(/action="([^"]+)"/);
const tokenMatch = decrypted.match(/value="([^"]+)"/);
if (!actionMatch || !tokenMatch)
return null;
const postUri = actionMatch[1];
const token = tokenMatch[1];
const formData = new URLSearchParams();
formData.append("_token", token);
let tries = 0;
let location = null;
while (tries < 3) {
tries++;
const postRes = yield fetch(postUri, {
method: "POST",
redirect: "manual",
headers: __spreadProps(__spreadValues({
"User-Agent": USER_AGENT,
"Referer": kwikUrl,
"Origin": "https://kwik.cx"
}, cookie ? { "Cookie": cookie } : {}), {
"Content-Type": "application/x-www-form-urlencoded"
}),
body: formData.toString(),
cfKiller: true,
skipSizeCheck: true
});
if (postRes.status === 302 || postRes.status === 301) {
location = postRes.headers.get("location") || postRes.headers.get("Location");
break;
}
}
if (location) {
return {
url: location,
headers: {
"Referer": "https://kwik.cx/",
"Origin": "https://kwik.cx",
"User-Agent": USER_AGENT
}
};
}
} catch (_) {
}
return null;
});
}
// src/animepahe/index.js
function getStreams(tmdbId, mediaType, season, episode) {
return __async(this, null, function* () {
try {
let animeSession = null;
let animeTitle = "";
let mappedEp = episode;
let targetMalId = null;
if (mediaType === "tv") {
const imdbId = yield getImdbId(tmdbId, mediaType);
if (!imdbId)
return [];
const mapping = yield resolveMapping(imdbId, season, episode);
if (!mapping || !mapping.mal_id)
return [];
targetMalId = mapping.mal_id;
mappedEp = mapping.mal_episode || episode;
animeTitle = yield getMalTitle(targetMalId);
if (!animeTitle)
return [];
let searchResults = yield searchAnime(animeTitle);
if (!searchResults.data || searchResults.data.length === 0) {
const clean = animeTitle.replace(/[^a-zA-Z0-9\s]+/g, " ").replace(/\s+/g, " ").trim();
if (clean !== animeTitle) {
searchResults = yield searchAnime(clean);
}
}
if (!searchResults.data || searchResults.data.length === 0) {
const words = animeTitle.split(/\s+/).filter(Boolean);
if (words.length > 3) {
const shortQuery = words.slice(-3).join(" ");
searchResults = yield searchAnime(shortQuery);
}
}
if (searchResults.data && searchResults.data.length > 0) {
for (let i = 0; i < Math.min(searchResults.data.length, 5); i++) {
const item = searchResults.data[i];
try {
const pageHtml = yield fetchText(`/anime/${item.session}`);
if (pageHtml.includes(`myanimelist.net/anime/${targetMalId}`) || item.id && String(item.id) === String(targetMalId)) {
animeSession = item.session;
break;
}
} catch (_) {
}
}
if (!animeSession) {
const normTarget = animeTitle.toLowerCase().replace(/[^a-z0-9]+/g, "");
const titleMatch = searchResults.data.find((r) => {
const normR = (r.title || "").toLowerCase().replace(/[^a-z0-9]+/g, "");
return normR.includes(normTarget) || normTarget.includes(normR);
});
animeSession = titleMatch ? titleMatch.session : searchResults.data[0].session;
}
}
} else {
const tmdbUrl = `https://api.themoviedb.org/3/movie/${tmdbId}?api_key=439c478a771f35c05022f9feabcca01c`;
const tmdbRes = yield fetch(tmdbUrl);
const tmdbData = yield tmdbRes.json();
animeTitle = tmdbData.title || tmdbData.original_title;
mappedEp = 1;
if (!animeTitle)
return [];
let searchResults = yield searchAnime(animeTitle);
if (!searchResults.data || searchResults.data.length === 0) {
const clean = animeTitle.replace(/[^a-zA-Z0-9\s]+/g, " ").replace(/\s+/g, " ").trim();
if (clean !== animeTitle) {
searchResults = yield searchAnime(clean);
}
}
if (searchResults.data && searchResults.data.length > 0) {
const normTarget = animeTitle.toLowerCase().replace(/[^a-z0-9]+/g, "");
const match = searchResults.data.find((r) => {
const normR = (r.title || "").toLowerCase().replace(/[^a-z0-9]+/g, "");
return normR === normTarget || normR.includes(normTarget) || normTarget.includes(normR);
}) || searchResults.data[0];
animeSession = match.session;
}
}
if (!animeSession)
return [];
const firstPageUrl = `/api?m=release&id=${animeSession}&sort=episode_asc&page=1`;
const firstPageData = yield fetchJson(firstPageUrl);
if (!firstPageData.data || firstPageData.data.length === 0)
return [];
const targetEpNum = Number(mappedEp);
let episodeSession = null;
const epInFirstPage = firstPageData.data.find((e) => Math.floor(Number(e.episode)) === targetEpNum || Number(e.episode) === targetEpNum);
if (epInFirstPage) {
episodeSession = epInFirstPage.session;
} else {
const perPage = firstPageData.per_page || 30;
const targetPage = Math.ceil(targetEpNum / perPage) || 1;
const lastPage = firstPageData.last_page || 1;
if (targetPage !== 1 && targetPage <= lastPage) {
const targetPageUrl = `/api?m=release&id=${animeSession}&sort=episode_asc&page=${targetPage}`;
const targetPageData = yield fetchJson(targetPageUrl);
if (targetPageData && targetPageData.data) {
const foundEp = targetPageData.data.find((e) => Math.floor(Number(e.episode)) === targetEpNum || Number(e.episode) === targetEpNum);
if (foundEp)
episodeSession = foundEp.session;
}
}
if (!episodeSession) {
for (let p = 2; p <= Math.min(lastPage, 6); p++) {
if (p === targetPage)
continue;
const pData = yield fetchJson(`/api?m=release&id=${animeSession}&sort=episode_asc&page=${p}`);
if (pData && pData.data) {
const foundEp = pData.data.find((e) => Math.floor(Number(e.episode)) === targetEpNum || Number(e.episode) === targetEpNum);
if (foundEp) {
episodeSession = foundEp.session;
break;
}
}
}
}
}
if (!episodeSession)
return [];
const playUrl = `/play/${animeSession}/${episodeSession}`;
const playHtml = yield fetchText(playUrl);
const $ = import_cheerio_without_node_native.default.load(playHtml);
const streams = [];
const promises = [];
const seen = /* @__PURE__ */ new Set();
const downloadLinks = $("div#pickDownload > a");
const buttons = $("#resolutionMenu > button");
buttons.each((index, el) => {
const $btn = $(el);
const kwikUrl = $btn.attr("data-src");
const fullText = $btn.text().trim();
const qualityText = fullText.includes(" \xB7 ") ? fullText.substring(fullText.indexOf(" \xB7 ") + 3) : fullText;
const isDub = qualityText.toLowerCase().includes("eng");
const isKor = qualityText.toLowerCase().includes("kor");
const isChi = qualityText.toLowerCase().includes("chi");
const langLabel = isDub ? "DUB" : isKor ? "KOR" : isChi ? "CHI" : "SUB";
const cleanQualityText = qualityText.replace(/eng/gi, "").replace(/kor/gi, "").replace(/chi/gi, "").replace(/\s+/g, " ").trim();
const quality = extractQuality(cleanQualityText);
const paheWinLink = downloadLinks.eq(index).attr("href");
if (kwikUrl && kwikUrl.includes("kwik")) {
promises.push(
extractKwik(kwikUrl).then((res) => {
if (res && res.m3u8 && !seen.has(res.m3u8)) {
seen.add(res.m3u8);
streams.push({
name: `AnimePahe [${langLabel}] (${quality} HLS)`,
title: mediaType === "movie" ? `${animeTitle} (${langLabel})` : `${animeTitle} - Episode ${mappedEp} (${langLabel})`,
url: res.m3u8,
quality,
headers: res.headers,
provider: "animepahe",
type: "m3u8"
});
}
if (res && res.mp4 && !seen.has(res.mp4)) {
seen.add(res.mp4);
streams.push({
name: `AnimePahe [${langLabel}] (${quality} MP4)`,
title: mediaType === "movie" ? `${animeTitle} (${langLabel})` : `${animeTitle} - Episode ${mappedEp} (${langLabel})`,
url: res.mp4,
quality,
headers: __spreadProps(__spreadValues({}, res.headers), {
"Referer": kwikUrl
}),
provider: "animepahe",
type: "mp4"
});
}
}).catch(() => {
})
);
}
if (paheWinLink && (paheWinLink.includes("pahe.win") || paheWinLink.includes("pahe.me") || paheWinLink.includes("pahe.li") || paheWinLink.includes("kwik"))) {
promises.push(
extractPahe(paheWinLink).then((res) => {
if (res && res.url && !seen.has(res.url)) {
seen.add(res.url);
streams.push({
name: `AnimePahe [${langLabel}] (${quality} Direct)`,
title: mediaType === "movie" ? `${animeTitle} (${langLabel})` : `${animeTitle} - Episode ${mappedEp} (${langLabel})`,
url: res.url,
quality,
headers: res.headers,
provider: "animepahe",
type: "mp4"
});
}
}).catch(() => {
})
);
}
});
yield Promise.all(promises);
const qualityOrder = { "1080p": 3, "720p": 2, "360p": 1 };
return streams.sort((a, b) => (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0));
} catch (_) {
return [];
}
});
}
module.exports = { getStreams };
+625 -1
View File
@@ -1 +1,625 @@
var _0x557dba=_0x11a3;(function(_0x4c1790,_0x5872e1){var _0x197a18={_0x4f7961:0x20d,_0x21c64b:0x20c,_0x5a8745:0x21a},_0x1cfb1f=_0x11a3,_0x18776a=_0x4c1790();while(!![]){try{var _0x1aacd2=-parseInt(_0x1cfb1f(_0x197a18._0x4f7961))/0x1+parseInt(_0x1cfb1f(_0x197a18._0x21c64b))/0x2+-parseInt(_0x1cfb1f(0x200))/0x3+parseInt(_0x1cfb1f(0x225))/0x4*(parseInt(_0x1cfb1f(_0x197a18._0x5a8745))/0x5)+-parseInt(_0x1cfb1f(0x1f5))/0x6+-parseInt(_0x1cfb1f(0x221))/0x7*(-parseInt(_0x1cfb1f(0x216))/0x8)+parseInt(_0x1cfb1f(0x219))/0x9;if(_0x1aacd2===_0x5872e1)break;else _0x18776a['push'](_0x18776a['shift']());}catch(_0x4b34ca){_0x18776a['push'](_0x18776a['shift']());}}}(_0xa7e9,0x8c273));var TMDB_KEY=_0x557dba(0x21e),BASE='https://animesalt.link',CDN=_0x557dba(0x214),UA=_0x557dba(0x226);function getInvertedSortTag(_0xe5663d,_0x1e3e19){var _0x3c7972={_0x1c36ad:0x202,_0xc87f6a:0x210},_0x51811b=_0x557dba;if(!_0x1e3e19)_0x1e3e19=0xf423f;var _0x39e711=Math['max'](0x0,parseInt(_0xe5663d,0xa)||0x0),_0x217f5a=Math[_0x51811b(_0x3c7972._0x1c36ad)](0x0,_0x1e3e19-_0x39e711),_0x5c2b65=_0x217f5a[_0x51811b(0x1f3)](0x2);while(_0x5c2b65['length']<0x14){_0x5c2b65='0'+_0x5c2b65;}return _0x5c2b65[_0x51811b(_0x3c7972._0xc87f6a)]('')['map'](function(_0x1f86b8){return _0x1f86b8==='1'?'\ufeff':'​';})['join']('');}function getResolutionEmoji(_0x4a47bf){var _0x3387d9={_0x2ca470:0x208,_0x446cad:0x1f7,_0x5e41db:0x21c,_0x3067c5:0x208,_0x28b51a:0x21f,_0x1613bf:0x231},_0x5db03d=_0x557dba,_0x32a132=String(_0x4a47bf||'')['toLowerCase']();if(_0x32a132[_0x5db03d(_0x3387d9._0x2ca470)](_0x5db03d(0x20e))||_0x32a132['includes']('4k')||_0x32a132[_0x5db03d(_0x3387d9._0x2ca470)]('uhd'))return _0x5db03d(0x22a);if(_0x32a132[_0x5db03d(0x208)](_0x5db03d(0x232))||_0x32a132['includes'](_0x5db03d(0x22f)))return _0x5db03d(_0x3387d9._0x446cad);if(_0x32a132['includes'](_0x5db03d(_0x3387d9._0x5e41db))||_0x32a132[_0x5db03d(_0x3387d9._0x3067c5)]('hd'))return'💎\x20720p';if(_0x32a132['includes'](_0x5db03d(_0x3387d9._0x28b51a))||_0x32a132[_0x5db03d(0x208)]('sd'))return _0x5db03d(_0x3387d9._0x1613bf);return'📺\x20'+(_0x4a47bf||'1080p');}function qualityRank(_0x41fc5e){var _0x4aeea4=_0x557dba;if(/2160p|4k/i['test'](_0x41fc5e))return 0x4;if(/1080p/i[_0x4aeea4(0x21d)](_0x41fc5e))return 0x3;if(/720p/i['test'](_0x41fc5e))return 0x2;if(/480p/i['test'](_0x41fc5e))return 0x1;return 0x0;}function httpGet(_0x420b31,_0x57deb1){var _0xb8e8ef={_0xd72923:0x20b},_0x28356a=_0x557dba;return fetch(_0x420b31,{'headers':Object['assign']({'User-Agent':UA},_0x57deb1||{})})[_0x28356a(_0xb8e8ef._0xd72923)](function(_0x534919){var _0x513635=_0x28356a;if(!_0x534919['ok'])throw new Error('HTTP\x20'+_0x534919[_0x513635(0x1f6)]);return _0x534919[_0x513635(0x1fb)]();});}function _0x11a3(_0x479722,_0x33ee57){_0x479722=_0x479722-0x1ef;var _0xa7e9a4=_0xa7e9();var _0x11a3f4=_0xa7e9a4[_0x479722];if(_0x11a3['ZGiWMW']===undefined){var _0x3ca26c=function(_0x1db348){var _0x16b95f='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';var _0xe5663d='',_0x1e3e19='';for(var _0x39e711=0x0,_0x217f5a,_0x5c2b65,_0x1f86b8=0x0;_0x5c2b65=_0x1db348['charAt'](_0x1f86b8++);~_0x5c2b65&&(_0x217f5a=_0x39e711%0x4?_0x217f5a*0x40+_0x5c2b65:_0x5c2b65,_0x39e711++%0x4)?_0xe5663d+=String['fromCharCode'](0xff&_0x217f5a>>(-0x2*_0x39e711&0x6)):0x0){_0x5c2b65=_0x16b95f['indexOf'](_0x5c2b65);}for(var _0x4a47bf=0x0,_0x32a132=_0xe5663d['length'];_0x4a47bf<_0x32a132;_0x4a47bf++){_0x1e3e19+='%'+('00'+_0xe5663d['charCodeAt'](_0x4a47bf)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x1e3e19);};_0x11a3['QUsIIC']=_0x3ca26c,_0x11a3['hkNbvk']={},_0x11a3['ZGiWMW']=!![];}var _0x22daf0=_0xa7e9a4[0x0],_0x3b9c80=_0x479722+_0x22daf0,_0x1e71b2=_0x11a3['hkNbvk'][_0x3b9c80];return!_0x1e71b2?(_0x11a3f4=_0x11a3['QUsIIC'](_0x11a3f4),_0x11a3['hkNbvk'][_0x3b9c80]=_0x11a3f4):_0x11a3f4=_0x1e71b2,_0x11a3f4;}function httpPost(_0x30217a,_0x2a874f,_0x5d2c7b){var _0x4ba3ab={_0x8622c8:0x20b},_0x8b1ada=_0x557dba;return fetch(_0x30217a,{'method':'POST','headers':Object['assign']({'User-Agent':UA,'Content-Type':'application/x-www-form-urlencoded'},_0x5d2c7b||{}),'body':_0x2a874f})[_0x8b1ada(_0x4ba3ab._0x8622c8)](function(_0x248002){var _0x5d3ded=_0x8b1ada;if(!_0x248002['ok'])throw new Error('HTTP\x20'+_0x248002[_0x5d3ded(0x1f6)]);return _0x248002['json']();});}function cleanTitle(_0x5b441f){return _0x5b441f['toLowerCase']()['replace'](/[^a-z0-9\s]/g,'')['replace'](/\s+/g,'\x20')['trim']();}function searchSite(_0x2a21aa,_0x31db93,_0x3faa33){var _0x4a25ab={_0x6d2555:0x203,_0x504a4d:0x227,_0x570a08:0x1f0,_0x2a521d:0x20f,_0x5715b1:0x1fd,_0x4afc3c:0x211,_0x417df0:0x228,_0x106144:0x1f0},_0xb8ef2e={_0x153a14:0x22b},_0x438d59={_0x2459ae:0x1f9},_0x461a90=BASE+'/?s='+encodeURIComponent(_0x2a21aa);return httpGet(_0x461a90,{'Referer':BASE+'/'})['then'](function(_0x41a043){var _0x50788c=_0x11a3,_0x5bcabd=[],_0x32361a=_0x41a043[_0x50788c(_0x4a25ab._0x6d2555)](/id="movies-a"([\s\S]*?)(?=<footer|id="footer|class="footer)/m),_0xb286f3=_0x32361a?_0x32361a[0x1]:_0x41a043Line truncated
/**
* animesalt - Built from src/animesalt/
* Generated: 2026-09-22T20:41:44.444Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/animesalt/index.js
var import_cheerio_without_node_native2 = __toESM(require("cheerio-without-node-native"));
// src/animesalt/constants.js
var MAIN_URL = "https://animesalt.cx";
var TMDB_API_KEY = "1865f43a0549ca50d341dd9ab8b29f49";
var TMDB_BASE_URL = "https://api.themoviedb.org/3";
var USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
var HEADERS = {
"User-Agent": USER_AGENT,
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.5"
};
// src/animesalt/utils.js
function fetchTmdbDetails(tmdbId, mediaType) {
return __async(this, null, function* () {
var _a;
const endpoint = mediaType === "movie" ? "movie" : "tv";
const url = `${TMDB_BASE_URL}/${endpoint}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`;
try {
const res = yield fetch(url, { headers: HEADERS });
if (!res.ok)
return null;
const data = yield res.json();
return {
title: mediaType === "movie" ? data.title || data.original_title : data.name || data.original_name,
year: parseInt((data.release_date || data.first_air_date || "").substring(0, 4)) || null,
imdbId: ((_a = data.external_ids) == null ? void 0 : _a.imdb_id) || null
};
} catch (e) {
return null;
}
});
}
function cleanTitle(str) {
return (str || "").toLowerCase().replace(/[^a-z0-9\s]/g, "").replace(/\s+/g, " ").trim();
}
function titleSimilarity(a, b) {
const cleanA = cleanTitle(a);
const cleanB = cleanTitle(b);
if (!cleanA || !cleanB)
return 0;
if (cleanA === cleanB)
return 1;
if (cleanA.includes(cleanB) || cleanB.includes(cleanA))
return 0.8;
const wordsA = new Set(cleanA.split(" "));
const wordsB = new Set(cleanB.split(" "));
let intersection = 0;
for (const w of wordsA) {
if (wordsB.has(w))
intersection++;
}
return intersection * 2 / (wordsA.size + wordsB.size);
}
function unpack(code) {
try {
const match = code.match(/}\((['"])([\s\S]*?)\1,\s*(\d+),\s*(\d+),\s*(['"])([\s\S]*?)\5\.split\((['"])\|\7\)/);
if (match) {
let [_, quote1, p, a, c, quote2, kStr] = match;
p = p.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
const radix = parseInt(a);
let count = parseInt(c);
const k = kStr.split("|");
const e = (c2) => (c2 < radix ? "" : e(parseInt(c2 / radix))) + ((c2 = c2 % radix) > 35 ? String.fromCharCode(c2 + 29) : c2.toString(36));
const d = {};
while (count--)
d[e(count)] = k[count] || e(count);
return p.replace(/\b\w+\b/g, (w) => d[w]);
}
} catch (e) {
}
return code;
}
function isRealStreamUrl(url) {
if (!url || typeof url !== "string")
return false;
if (!url.startsWith("http://") && !url.startsWith("https://"))
return false;
const lowercase = url.toLowerCase();
if (lowercase.includes("/embed/") || lowercase.includes("/embed-") || lowercase.includes("/e/") || lowercase.includes("/play.php") || lowercase.includes("/player.php") || lowercase.includes("abyssplayer.com") || lowercase.includes("short.icu") || lowercase.includes("cloudy.upns.one") || lowercase.includes("vidcloud.upns.ink") || lowercase.includes("filesforever.link") || lowercase.includes("strmup.to") || lowercase.includes("emturbovid.com") || lowercase.includes("animedekho.app") || lowercase.includes("animesalt.cx") || lowercase.includes("youtube.com") || lowercase.includes("youtu.be") || lowercase.includes("vimeo.com") || lowercase.includes(".html") || lowercase.includes(".htm") || lowercase.includes(".php") || lowercase.includes("#")) {
return false;
}
const isHls = lowercase.includes(".m3u8");
const isMp4 = lowercase.includes(".mp4") || lowercase.includes("/sora/") || lowercase.includes("/stream/");
return isHls || isMp4 || lowercase.includes(".mkv") || lowercase.includes(".mpd");
}
function isPlayableStream(stream) {
return __async(this, null, function* () {
if (!isRealStreamUrl(stream == null ? void 0 : stream.url))
return false;
try {
const headers = __spreadProps(__spreadValues({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
}, stream.headers || {}), {
"Range": "bytes=0-10"
});
const res = yield fetch(stream.url, {
headers,
signal: AbortSignal.timeout(3e3)
});
if (!res.ok && res.status !== 206)
return false;
const contentType = res.headers.get("content-type") || "";
if (contentType.includes("text/html"))
return false;
return true;
} catch (e) {
return false;
}
});
}
// src/animesalt/extractors.js
var import_cheerio_without_node_native = __toESM(require("cheerio-without-node-native"));
var import_crypto_js = __toESM(require("crypto-js"));
function extractAwsStream(url) {
return __async(this, null, function* () {
try {
const hash = url.split("/").filter(Boolean).pop();
if (!hash)
return null;
const origin = new URL(url).origin;
const res = yield fetch(url, { headers: HEADERS });
if (!res.ok)
return null;
const html = yield res.text();
const postUrl = `${origin}/player/index.php?data=${hash}&do=getVideo`;
const postRes = yield fetch(postUrl, {
method: "POST",
headers: __spreadProps(__spreadValues({}, HEADERS), {
"x-requested-with": "XMLHttpRequest",
"Origin": origin,
"Referer": url,
"Content-Type": "application/x-www-form-urlencoded"
}),
body: `hash=${encodeURIComponent(hash)}&r=${encodeURIComponent(origin)}`
});
if (!postRes.ok)
return null;
const json = yield postRes.json();
const m3u8 = json == null ? void 0 : json.videoSource;
if (!m3u8)
return null;
let subtitle = null;
const packedMatch = html.match(/eval\(function\(p,a,c,k,e,d\)[\s\S]*?\.split\(['"]\|['"]\)\)/);
if (packedMatch) {
const unpacked = unpack(packedMatch[0]);
const subMatch = unpacked.match(/"kind":\s*"captions"\s*,\s*"file":\s*"(https?:\/\/[^"]+)"/);
if (subMatch) {
subtitle = subMatch[1].replace(/\\/g, "");
}
}
return {
url: m3u8,
headers: {
"Referer": `${origin}/`,
"Origin": origin,
"User-Agent": HEADERS["User-Agent"]
},
subtitles: subtitle ? [{ lang: "English", url: subtitle }] : []
};
} catch (e) {
return null;
}
});
}
function extractAbyss(url, langName = "Default") {
return __async(this, null, function* () {
var _a;
try {
const cleanUrl = url.replace("https://short.icu", "https://abyssplayer.com");
const reqHeaders = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36",
"Origin": "https://playhydrax.com",
"Referer": "https://playhydrax.com/"
};
const res = yield fetch(cleanUrl, { headers: reqHeaders });
if (!res.ok)
return [];
const html = yield res.text();
const match = html.match(/const\s+datas\s*=\s*"([^"]*)"/);
if (!match || !match[1])
return [];
const decRes = yield fetch("https://enc-dec.app/api/dec-abyss", {
method: "POST",
headers: __spreadProps(__spreadValues({}, reqHeaders), {
"Content-Type": "application/json"
}),
body: JSON.stringify({ text: match[1] })
});
if (!decRes.ok)
return [];
const decData = yield decRes.json();
const sources = ((_a = decData == null ? void 0 : decData.result) == null ? void 0 : _a.sources) || [];
return sources.filter((s) => s && s.url && s.status).map((s) => {
const codec = (s.codec || "MP4").toUpperCase();
const quality = s.type || "720p";
return {
name: `AnimeSalt [${langName}] (${codec} ${quality})`,
url: s.url,
quality,
headers: {
"Referer": "https://playhydrax.com/",
"Origin": "https://playhydrax.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
},
type: s.url.includes(".m3u8") ? "m3u8" : "mp4"
};
});
} catch (e) {
return [];
}
});
}
function extractMultiLang(dataParam) {
return __async(this, null, function* () {
try {
let decodedStr = "";
if (typeof atob === "function") {
decodedStr = atob(dataParam);
} else {
decodedStr = Buffer.from(dataParam, "base64").toString("utf-8");
}
const list = JSON.parse(decodedStr);
if (!Array.isArray(list))
return [];
const streamPromises = list.map((item) => {
const lang = item.language || "Default";
const link = item.link;
if (!link)
return Promise.resolve([]);
return extractAbyss(link, lang);
});
const nested = yield Promise.all(streamPromises);
return nested.flat();
} catch (e) {
return [];
}
});
}
function extractMegaPlay(url) {
return __async(this, null, function* () {
var _a;
try {
let streamPageUrl = url;
if (!url.includes("/stream/s-")) {
const pageRes = yield fetch(url, { headers: HEADERS });
if (!pageRes.ok)
return [];
const html = yield pageRes.text();
const $ = import_cheerio_without_node_native.default.load(html);
const embedSrc = $("iframe.s5-embed").attr("src");
if (!embedSrc)
return [];
streamPageUrl = embedSrc;
}
const idMatch = streamPageUrl.match(/\/stream\/s-\d+\/(\d+)\//);
if (!idMatch || !idMatch[1])
return [];
const id = idMatch[1];
const origin = new URL(streamPageUrl).origin;
const apiHeaders = {
"Accept": "*/*",
"X-Requested-With": "XMLHttpRequest",
"Referer": origin,
"User-Agent": HEADERS["User-Agent"]
};
const apiRes = yield fetch(`${origin}/stream/getSources?id=${id}`, { headers: apiHeaders });
if (!apiRes.ok)
return [];
const resJson = yield apiRes.json();
let file = (_a = resJson == null ? void 0 : resJson.sources) == null ? void 0 : _a.file;
const enc = resJson == null ? void 0 : resJson.enc;
if (!file && enc) {
const keyStr = "i?LMTAx0Q6,:}50U";
const keyHex = import_crypto_js.default.enc.Utf8.parse(keyStr).toString(import_crypto_js.default.enc.Hex).padEnd(64, "0");
const key = import_crypto_js.default.enc.Hex.parse(keyHex);
const iv = import_crypto_js.default.enc.Utf8.parse("W0;27ToaUpl_P%'c");
const normalized = enc.replace(/-/g, "+").replace(/_/g, "/");
const padded = normalized + "=".repeat((4 - normalized.length % 4) % 4);
const decrypted = import_crypto_js.default.AES.decrypt(padded, key, {
iv,
mode: import_crypto_js.default.mode.CBC,
padding: import_crypto_js.default.pad.Pkcs7
});
const decObj = JSON.parse(decrypted.toString(import_crypto_js.default.enc.Utf8));
file = decObj == null ? void 0 : decObj.file;
}
if (!file)
return [];
const tokenMatch = file.match(/\/([a-f0-9]{32})\/([a-f0-9]{32})\//i);
if (tokenMatch && !file.includes("token=")) {
const secret = "MpCdnT0k3n!9f2K#xQ7vL5mR8wN1pY4s";
const expires = Math.floor(Date.now() / 1e3) + 90;
const payload = `${expires}|${tokenMatch[1]}/${tokenMatch[2]}`;
const hash = import_crypto_js.default.HmacSHA256(payload, secret);
const b64Payload = import_crypto_js.default.enc.Base64.stringify(import_crypto_js.default.enc.Utf8.parse(payload)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const b64Sig = import_crypto_js.default.enc.Base64.stringify(hash).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const token = `${b64Payload}.${b64Sig}`;
file = `${file}${file.includes("?") ? "&" : "?"}token=${token}`;
}
const subtitles = ((resJson == null ? void 0 : resJson.tracks) || []).filter((t) => t.file && t.kind !== "thumbnails").map((t) => ({ lang: t.label || "English", url: t.file }));
return [{
name: "AnimeSalt [MegaPlay] (Auto M3U8)",
url: file,
quality: "1080p",
headers: {
"Referer": `${origin}/`,
"Origin": origin,
"User-Agent": HEADERS["User-Agent"]
},
subtitles,
type: "m3u8"
}];
} catch (e) {
return [];
}
});
}
function extractStreamWish(url) {
return __async(this, null, function* () {
try {
const embedUrl = url.includes("/e/") ? url : url.replace("/f/", "/e/");
const res = yield fetch(embedUrl, { headers: HEADERS });
if (!res.ok)
return null;
const html = yield res.text();
const packedMatch = html.match(/eval\(function\(p,a,c,k,e,d\)[\s\S]*?\.split\(['"]\|['"]\)\)/);
if (packedMatch) {
const unpacked = unpack(packedMatch[0]);
const fileMatch = unpacked.match(/file\s*:\s*["'](https?:\/\/[^"'\s]+\.m3u8(?:\?[^"'\s]*)?)["']/);
if (fileMatch) {
const origin = new URL(embedUrl).origin;
return {
name: "AnimeSalt [StreamWish] (Auto M3U8)",
url: fileMatch[1],
quality: "720p",
headers: {
"Referer": `${origin}/`,
"Origin": origin,
"User-Agent": HEADERS["User-Agent"]
},
type: "m3u8"
};
}
}
} catch (e) {
}
return null;
});
}
// src/animesalt/index.js
function searchAnimeSalt(query) {
return __async(this, null, function* () {
var _a;
try {
const body = `action=torofilm_infinite_scroll&page=1&per_page=12&query_type=search&query_args[s]=${encodeURIComponent(query)}`;
const res = yield fetch(`${MAIN_URL}/wp-admin/admin-ajax.php`, {
method: "POST",
headers: __spreadProps(__spreadValues({}, HEADERS), {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest",
"Referer": `${MAIN_URL}/`
}),
body
});
if (!res.ok)
return [];
const json = yield res.json();
if (!(json == null ? void 0 : json.success) || !((_a = json == null ? void 0 : json.data) == null ? void 0 : _a.content))
return [];
const $ = import_cheerio_without_node_native2.default.load(json.data.content);
const results = [];
$("article").each((_, el) => {
const title = $(el).find("header h2").text().trim();
const href = $(el).find("a").first().attr("href");
if (title && href) {
results.push({ title, href });
}
});
return results;
} catch (e) {
return [];
}
});
}
function getStreams(tmdbId, mediaType, seasonNum = 1, episodeNum = 1) {
return __async(this, null, function* () {
try {
const details = yield fetchTmdbDetails(tmdbId, mediaType);
if (!details || !details.title)
return [];
let results = yield searchAnimeSalt(details.title);
if (results.length === 0) {
const cleaned = cleanTitle(details.title);
if (cleaned && cleaned !== details.title.toLowerCase()) {
results = yield searchAnimeSalt(cleaned);
}
}
if (results.length === 0)
return [];
let bestMatch = null;
let highestSim = 0;
for (const item of results) {
const sim = titleSimilarity(details.title, item.title);
if (sim > highestSim) {
highestSim = sim;
bestMatch = item;
}
}
if (!bestMatch || highestSim < 0.2) {
bestMatch = results[0];
}
let targetUrl = bestMatch.href;
if (mediaType === "tv") {
const seriesRes = yield fetch(bestMatch.href, { headers: HEADERS });
if (!seriesRes.ok)
return [];
const seriesHtml = yield seriesRes.text();
const $series = import_cheerio_without_node_native2.default.load(seriesHtml);
let seasonBtn = $series(`div.season-buttons a[data-season="${seasonNum}"]`);
if (seasonBtn.length === 0) {
seasonBtn = $series("div.season-buttons a").first();
}
const postId = seasonBtn.attr("data-post");
const dataSeason = seasonBtn.attr("data-season") || seasonNum;
if (postId) {
const epRes = yield fetch(`${MAIN_URL}/wp-admin/admin-ajax.php`, {
method: "POST",
headers: __spreadProps(__spreadValues({}, HEADERS), {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest",
"Referer": bestMatch.href
}),
body: `action=action_select_season&season=${dataSeason}&post=${postId}`
});
if (epRes.ok) {
const epHtml = yield epRes.text();
const $ep = import_cheerio_without_node_native2.default.load(epHtml);
const epArticles = $ep("li article");
let targetEp = null;
epArticles.each((idx, el) => {
const epText = $ep(el).find("h2.entry-title").text();
if (epText.includes(`x${episodeNum}`) || epText.includes(`Episode ${episodeNum}`)) {
targetEp = $ep(el).find("a").first().attr("href");
}
});
if (!targetEp && epArticles.length >= episodeNum) {
targetEp = $ep(epArticles[episodeNum - 1]).find("a").first().attr("href");
}
if (targetEp) {
targetUrl = targetEp;
}
}
}
}
const pageRes = yield fetch(targetUrl, { headers: HEADERS });
if (!pageRes.ok)
return [];
const pageHtml = yield pageRes.text();
const $page = import_cheerio_without_node_native2.default.load(pageHtml);
const iframeUrls = /* @__PURE__ */ new Set();
$page("iframe").each((_, el) => {
const src = $page(el).attr("data-src") || $page(el).attr("src");
if (src && !src.startsWith("about:") && !src.startsWith("javascript:")) {
const fullUrl = src.startsWith("//") ? `https:${src}` : src.startsWith("http") ? src : `${MAIN_URL}${src}`;
iframeUrls.add(fullUrl);
}
});
const streams = [];
const promises = [];
for (const iframeUrl of iframeUrls) {
if (iframeUrl.includes("multi-lang-plyr/player.php")) {
const urlObj = new URL(iframeUrl);
const dataParam = urlObj.searchParams.get("data");
if (dataParam) {
promises.push(
extractMultiLang(dataParam).then((res) => {
if (Array.isArray(res))
streams.push(...res);
})
);
}
} else if (iframeUrl.includes("as-cdn") || iframeUrl.includes("awstream") || iframeUrl.includes("zephyrflick")) {
promises.push(
extractAwsStream(iframeUrl).then((res) => {
if (res && res.url) {
streams.push({
name: "AnimeSalt [AWSStream] (Auto M3U8)",
url: res.url,
quality: "1080p",
headers: res.headers,
subtitles: res.subtitles,
type: "m3u8"
});
}
})
);
} else if (iframeUrl.includes("abyssplayer.com") || iframeUrl.includes("short.icu")) {
promises.push(
extractAbyss(iframeUrl, "Default").then((res) => {
if (Array.isArray(res))
streams.push(...res);
})
);
} else if (iframeUrl.includes("megaplay.buzz") || iframeUrl.includes("rapid-cloud.co")) {
promises.push(
extractMegaPlay(iframeUrl).then((res) => {
if (Array.isArray(res))
streams.push(...res);
})
);
} else if (iframeUrl.includes("pixdrive") || iframeUrl.includes("ghbrisk") || iframeUrl.includes("streamwish") || iframeUrl.includes("filesim")) {
promises.push(
extractStreamWish(iframeUrl).then((res) => {
if (res)
streams.push(res);
})
);
}
}
yield Promise.allSettled(promises);
const seenUrls = /* @__PURE__ */ new Set();
const candidateStreams = [];
for (const s of streams) {
if (s && s.url && !seenUrls.has(s.url) && isRealStreamUrl(s.url)) {
seenUrls.add(s.url);
candidateStreams.push({
name: s.name || "AnimeSalt",
title: mediaType === "movie" ? details.title : `${details.title} - S${seasonNum}E${episodeNum}`,
url: s.url,
quality: s.quality || "Auto",
headers: s.headers,
subtitles: s.subtitles || [],
provider: "animesalt",
type: s.type || "m3u8"
});
}
}
const probeResults = yield Promise.all(
candidateStreams.map((s) => __async(this, null, function* () {
return { stream: s, playable: yield isPlayableStream(s) };
}))
);
let finalStreams = probeResults.filter((r) => r.playable).map((r) => r.stream);
if (finalStreams.length === 0)
finalStreams = candidateStreams;
const qualityOrder = { "1080p": 4, "720p": 3, "480p": 2, "360p": 1, "Auto": 0 };
return finalStreams.sort((a, b) => {
var _a, _b;
return ((_a = qualityOrder[b.quality]) != null ? _a : 0) - ((_b = qualityOrder[a.quality]) != null ? _b : 0);
});
} catch (e) {
return [];
}
});
}
module.exports = { getStreams };
+1 -1
View File
@@ -1 +1 @@
var _0x12d368=_0x6693;(function(_0x5866cb,_0x2c0651){var _0x2fa589=_0x6693,_0x22f986=_0x5866cb();while(!![]){try{var _0x44a7ff=-parseInt(_0x2fa589(0x19e))/0x1+parseInt(_0x2fa589(0x186))/0x2*(parseInt(_0x2fa589(0x18b))/0x3)+parseInt(_0x2fa589(0x18c))/0x4*(parseInt(_0x2fa589(0x1ae))/0x5)+parseInt(_0x2fa589(0x1a6))/0x6+-parseInt(_0x2fa589(0x1ab))/0x7*(parseInt(_0x2fa589(0x1a5))/0x8)+-parseInt(_0x2fa589(0x194))/0x9+-parseInt(_0x2fa589(0x198))/0xa*(-parseInt(_0x2fa589(0x1a8))/0xb);if(_0x44a7ff===_0x2c0651)break;else _0x22f986['push'](_0x22f986['shift']());}catch(_0xaf737b){_0x22f986['push'](_0x22f986['shift']());}}}(_0x1e0c,0x68dcd));function _0x1e0c(){var _0x2fb3a7=['Bw92Awu','mtbuB1rtDvm','BgvUz3rO','Ahr0Chm6lY93yxrJAgfUAw1LD29YBgqUBMv0','l3bSyxLLCI9PBMrLEc5WAha/zgf0yt0','BMfTzq','we1mshr0CfjLCxvLC3q','ntmYnZiXwLfpBMvy','l2nKBI9KB3DUlW','lZ9Zpq','DxjS','8j+xOE+4JYbbBMLTzvDVCMXK','yxnZAwDU','rw5NBgLZAa','otzAEhnRqKm','nJyYndaWrNPUBuHk','Bw92AwvZ','nZK2mdiWnvbkAgvhAq','y2f0y2G','CgfNzq','nduZndzKEfbwB0W','mta4mha','l1n1yNrPDgXLl3n1yNrPDgXLx2vUzY5ZCNq','ntq3otvqthrAwMe','zxHWB3j0CW','C2vYAwvZ','A2vLCc1HBgL2zq','zxHLyW','sfruuca','DgHLBG','Ahr0Chm6lY9HCgKUDgHLBw92AwvKyI5VCMCVmY8','Bwf0y2G','neTtwfPJAq','jNi9','tw96AwXSys81lJaGkfDPBMrVD3mGtLqGmtaUmdSGv2LUnJq7ihG2ncKGqxbWBgvxzwjlAxqVntm3lJm2icHlsfrntcWGBgLRzsbhzwnRBYKGq2HYB21LlZeYmc4WlJaUmcbtywzHCMKVntm3lJm2','DgL0Bgu','C3rHDhvZ','odm3mteXBevVCfn2','mtm2CKPZyLnl','C2vJDxjLzeXPBMS','ANnVBG','Aw5KzxHpzG','jMrVpwDLDfzPzgvV','C3vIDgL0Bgu','qw5PBwvxB3jSzcdIGkiGtxvSDgKTqxvKAw8Gmta4mha','DhLWzq','nJuYmJG0ou1rtxLStq','DMLKzw9tB3vYy2u','jNbVC3q9'];_0x1e0c=function(){return _0x2fb3a7;};return _0x1e0c();}var TMDB_KEY='d80ba92bc7cefe3359668d30d06f3305',BASE=_0x12d368(0x19a),PLAYER='https://play.zephyrflick.top',UA=_0x12d368(0x188);function httpGet(_0x4dd1ad,_0x12d8c2){var _0x5d0ff1=_0x12d368;return fetch(_0x4dd1ad,{'headers':Object[_0x5d0ff1(0x1a3)]({'User-Agent':UA},_0x12d8c2||{})})[_0x5d0ff1(0x183)](function(_0x4e8bbc){var _0x57654c=_0x5d0ff1;if(!_0x4e8bbc['ok'])throw new Error(_0x57654c(0x1b3)+_0x4e8bbc[_0x57654c(0x18a)]);return _0x4e8bbc['text']();});}function httpPost(_0x2fd8fc,_0x2e768f,_0x3ebb46){var _0x5c935b=_0x12d368;return fetch(_0x2fd8fc,{'method':'POST','headers':Object[_0x5c935b(0x1a3)]({'User-Agent':UA,'Content-Type':'application/x-www-form-urlencoded'},_0x3ebb46||{}),'body':_0x2e768f})[_0x5c935b(0x183)](function(_0x279e4c){var _0x2ca3e4=_0x5c935b;if(!_0x279e4c['ok'])throw new Error(_0x2ca3e4(0x1b3)+_0x279e4c[_0x2ca3e4(0x18a)]);return _0x279e4c['json']();});}function _0x6693(_0x4eac2a,_0x54aa47){_0x4eac2a=_0x4eac2a-0x183;var _0x1e0cef=_0x1e0c();var _0x6693a9=_0x1e0cef[_0x4eac2a];if(_0x6693['lBIKAi']===undefined){var _0x55e4ee=function(_0x4b904c){var _0x3c9b87='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';var _0x4dd1ad='',_0x12d8c2='';for(var _0x4e8bbc=0x0,_0x2fd8fc,_0x2e768f,_0x3ebb46=0x0;_0x2e768f=_0x4b904c['charAt'](_0x3ebb46++);~_0x2e768f&&(_0x2fd8fc=_0x4e8bbc%0x4?_0x2fd8fc*0x40+_0x2e768f:_0x2e768f,_0x4e8bbc++%0x4)?_0x4dd1ad+=String['fromCharCode'](0xff&_0x2fd8fc>>(-0x2*_0x4e8bbc&0x6)):0x0){_0x2e768f=_0x3c9b87['indexOf'](_0x2e768f);}for(var _0x279e4c=0x0,_0x440768=_0x4dd1ad['length'];_0x279e4c<_0x440768;_0x279e4c++){_0x12d8c2+='%'+('00'+_0x4dd1ad['charCodeAt'](_0x279e4c)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x12d8c2);};_0x6693['IhEcis']=_0x55e4ee,_0x6693['totfgc']={},_0x6693['lBIKAi']=!![];}var _0x665320=_0x1e0cef[0x0],_0x479db4=_0x4eac2a+_0x665320,_0x262c2e=_0x6693['totfgc'][_0x479db4];return!_0x262c2e?(_0x6693a9=_0x6693['IhEcis'](_0x6693a9),_0x6693['totfgc'][_0x479db4]=_0x6693a9):_0x6693a9=_0x262c2e,_0x6693a9;}function searchSite(_0x440768,_0x287a36){var _0x175b25=_0x12d368,_0x2f4c24=BASE+_0x175b25(0x1a0)+encodeURIComponent(_0x440768);return httpGet(_0x2f4c24,{'Referer':BASE+'/'})[_0x175b25(0x183)](function(_0x14e8ed){var _0x4b85c5=_0x175b25,_0x3df02a=[],_0x348335=/href="(https:\/\/watchanimeworld\.net\/(series|movies)\/([^\/\"]+)\/)"/g,_0x2eee89;while((_0x2eee89=_0x348335[_0x4b85c5(0x1b2)](_0x14e8ed))!==null){var _0x282822=_0x2eee89[0x1],_0x39bd5d=_0x2eee89[0x2],_0x486c63=_0x2eee89[0x3];_0x486c63&&_0x486c63!==_0x4b85c5(0x1aa)&&_0x3df02a['push']({'url':_0x282822,'type':_0x39bd5d,'slug':_0x486c63});}return _0x3df02a['filter'](function(_0x4e8238){var _0x31801e=_0x4b85c5;return _0x287a36===_0x31801e(0x197)?_0x4e8238[_0x31801e(0x193)]===_0x31801e(0x1a7):_0x4e8238[_0x31801e(0x193)]===_0x31801e(0x1b0);});});}function getEpisodeUrl(_0x251373,_0x5d2023,_0x31ccd1){return httpGet(_0x251373,{'Referer':BASE+'/'})['then'](function(_0x4bddf9){var _0x9bc76c=_0x6693,_0x1445ce=_0x4bddf9[_0x9bc76c(0x185)](/postid-(\d+)/)||_0x4bddf9[_0x9bc76c(0x185)](/data-post="(\d+)"/);if(!_0x1445ce)return null;var _0x29078a=BASE+'/wp-admin/admin-ajax.php?action=action_select_season&season='+_0x5d2023+_0x9bc76c(0x196)+_0x1445ce[0x1];return httpGet(_0x29078a,{'Referer':_0x251373})[_0x9bc76c(0x183)](function(_0x89d2aa){var _0x55a160=_0x9bc76c,_0xLine truncated
var _0x388760=_0x3571;(function(_0x5bf76f,_0x3a97b1){var _0x1a9865={_0x5721b6:0x1e4,_0x533016:0x1e1,_0x41c127:0x1c4,_0x17bb1e:0x1da,_0x40787b:0x1c5,_0xc5f98:0x1f4},_0x226b65=_0x3571,_0x194c2c=_0x5bf76f();while(!![]){try{var _0xc353c8=-parseInt(_0x226b65(_0x1a9865._0x5721b6))/0x1+-parseInt(_0x226b65(_0x1a9865._0x533016))/0x2*(parseInt(_0x226b65(_0x1a9865._0x41c127))/0x3)+parseInt(_0x226b65(0x1d3))/0x4+-parseInt(_0x226b65(0x1c8))/0x5*(parseInt(_0x226b65(0x1d2))/0x6)+-parseInt(_0x226b65(_0x1a9865._0x17bb1e))/0x7+parseInt(_0x226b65(0x1db))/0x8*(parseInt(_0x226b65(_0x1a9865._0x40787b))/0x9)+parseInt(_0x226b65(0x1d0))/0xa*(parseInt(_0x226b65(_0x1a9865._0xc5f98))/0xb);if(_0xc353c8===_0x3a97b1)break;else _0x194c2c['push'](_0x194c2c['shift']());}catch(_0x3b64af){_0x194c2c['push'](_0x194c2c['shift']());}}}(_0xf2c8,0x4bc85));var TMDB_KEY='d80ba92bc7cefe3359668d30d06f3305',BASE='https://watchanimeworld.top',PLAYER='https://play.zephyrix.top',UA=_0x388760(0x1e2);function getInvertedSortTag(_0x4c3f75,_0xfb7bb3){var _0x290f4f={_0x394ae0:0x1e3,_0x178b3e:0x1d1},_0x332005=_0x388760;if(!_0xfb7bb3)_0xfb7bb3=0xf423f;var _0x23a5d2=Math[_0x332005(0x1ce)](0x0,parseInt(_0x4c3f75,0xa)||0x0),_0x5c9928=Math['max'](0x0,_0xfb7bb3-_0x23a5d2),_0x40953a=_0x5c9928['toString'](0x2);while(_0x40953a['length']<0x14){_0x40953a='0'+_0x40953a;}return _0x40953a[_0x332005(0x1de)]('')[_0x332005(_0x290f4f._0x394ae0)](function(_0xefa4ba){return _0xefa4ba==='1'?'\ufeff':'​';})[_0x332005(_0x290f4f._0x178b3e)]('');}function _0x3571(_0x51eec8,_0x90a31b){_0x51eec8=_0x51eec8-0x1be;var _0xf2c8da=_0xf2c8();var _0x3571df=_0xf2c8da[_0x51eec8];if(_0x3571['vcGYyl']===undefined){var _0x22837f=function(_0x7e26eb){var _0x155595='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';var _0x4c3f75='',_0xfb7bb3='';for(var _0x23a5d2=0x0,_0x5c9928,_0x40953a,_0xefa4ba=0x0;_0x40953a=_0x7e26eb['charAt'](_0xefa4ba++);~_0x40953a&&(_0x5c9928=_0x23a5d2%0x4?_0x5c9928*0x40+_0x40953a:_0x40953a,_0x23a5d2++%0x4)?_0x4c3f75+=String['fromCharCode'](0xff&_0x5c9928>>(-0x2*_0x23a5d2&0x6)):0x0){_0x40953a=_0x155595['indexOf'](_0x40953a);}for(var _0x56397c=0x0,_0x631031=_0x4c3f75['length'];_0x56397c<_0x631031;_0x56397c++){_0xfb7bb3+='%'+('00'+_0x4c3f75['charCodeAt'](_0x56397c)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0xfb7bb3);};_0x3571['bUQCiL']=_0x22837f,_0x3571['ZYjsat']={},_0x3571['vcGYyl']=!![];}var _0x1b164b=_0xf2c8da[0x0],_0x50eb6a=_0x51eec8+_0x1b164b,_0x3fd203=_0x3571['ZYjsat'][_0x50eb6a];return!_0x3fd203?(_0x3571df=_0x3571['bUQCiL'](_0x3571df),_0x3571['ZYjsat'][_0x50eb6a]=_0x3571df):_0x3571df=_0x3fd203,_0x3571df;}function qualityRank(_0x56397c){var _0x122cb9={_0x5ab1bc:0x1e8},_0xa97dd7=_0x388760;if(/2160p|4k/i[_0xa97dd7(0x1e8)](_0x56397c))return 0x4;if(/1080p/i[_0xa97dd7(0x1e8)](_0x56397c))return 0x3;if(/720p/i[_0xa97dd7(_0x122cb9._0x5ab1bc)](_0x56397c))return 0x2;if(/480p/i['test'](_0x56397c))return 0x1;return 0x0;}function httpGet(_0x631031,_0x2c3d03){var _0x10d49e={_0x234804:0x1c0},_0x1fdc12=_0x388760;return fetch(_0x631031,{'headers':Object[_0x1fdc12(_0x10d49e._0x234804)]({'User-Agent':UA},_0x2c3d03||{})})['then'](function(_0x35fa86){var _0x4306a6=_0x1fdc12;if(!_0x35fa86['ok'])throw new Error(_0x4306a6(0x1c6)+_0x35fa86[_0x4306a6(0x1ed)]);return _0x35fa86['text']();});}function httpPost(_0x561273,_0x25b05b,_0x23cf0a){var _0x2248c9={_0x23b087:0x1e0},_0x1f5ed3={_0x1cbff5:0x1f1},_0x11f50c=_0x388760;return fetch(_0x561273,{'method':_0x11f50c(_0x2248c9._0x23b087),'headers':Object[_0x11f50c(0x1c0)]({'User-Agent':UA,'Content-Type':'application/x-www-form-urlencoded'},_0x23cf0a||{}),'body':_0x25b05b})['then'](function(_0x19d609){var _0xe21291=_0x11f50c;if(!_0x19d609['ok'])throw new Error('HTTP\x20'+_0x19d609[_0xe21291(0x1ed)]);return _0x19d609[_0xe21291(_0x1f5ed3._0x1cbff5)]();});}function searchSite(_0x351314,_0x4be9e8){var _0x31dfb5={_0x239f28:0x1bf},_0x473b77={_0x3101ee:0x1e6,_0x124cd2:0x1c2},_0x2b3cd0=BASE+'/?s='+encodeURIComponent(_0x351314);return httpGet(_0x2b3cd0,{'Referer':BASE+'/'})['then'](function(_0x9e0c7d){var _0x82d447=_0x3571,_0x2adf89=[],_0x14b4c4=/href="(https:\/\/watchanimeworld\.top\/(series|movies)\/([^\/\"]+)\/)"/g,_0x1e5b68;while((_0x1e5b68=_0x14b4c4['exec'](_0x9e0c7d))!==null){var _0x53679f=_0x1e5b68[0x1],_0x160d23=_0x1e5b68[0x2],_0x1c1991=_0x1e5b68[0x3];_0x1c1991&&_0x1c1991!=='page'&&_0x2adf89[_0x82d447(0x1d7)]({'url':_0x53679f,'type':_0x160d23,'slug':_0x1c1991});}return _0x2adf89[_0x82d447(_0x31dfb5._0x239f28)](function(_0xfcc283){var _0xee17a5=_0x82d447;return _0x4be9e8===_0xee17a5(_0x473b77._0x3101ee)?_0xfcc283['type']===_0xee17a5(0x1d5):_0xfcc283[_0xee17a5(_0x473b77._0x124cd2)]===_0xee17a5(0x1c9);});});}function _0xf2c8(){var _0x2abaea=['BwfW','mZCYmdC5z29KqLbw','8j+tIYbt','Bw92Awu','zxbPC29Kzv9UDw1Izxi','DgvZDa','iokaOIbnDwX0As1bDwrPBW','we1mshr0CfjLCxvLC3q','BgvUz3rO','EwvHCG','C3rHDhvZ','Bwf0y2G','jNi9','DxjS','ANnVBG','BMfTzq','zxHLyW','mJC1u05ouunX','8j+xOE+4JYa','zMLSDgvY','yxnZAwDU','ic0G','DhLWzq','zxbPC29Kzxm','mJCLine truncated
+800
View File
@@ -0,0 +1,800 @@
/**
* anizone - Built from src/anizone/
* Generated: 2026-09-25T19:36:47.745Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/anizone/index.js
var import_cheerio_without_node_native = __toESM(require("cheerio-without-node-native"));
// src/anizone/constants.js
var MAIN_URL = "https://anizone.to";
var HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36",
"Referer": "https://anizone.to/"
};
var TMDB_API_KEY = "68e094699525b18a70bab2f86b1fa706";
// src/anizone/utils.js
var HEX_ESCAPE = /\\x([0-9a-fA-F]{2})/g;
var INVALID_BACKSLASH = /\\(?!["\\/bfnrt]|u[0-9a-fA-F]{4})/g;
function sanitizeJson(raw) {
if (!raw)
return "";
return raw.replace(/\\u0022/g, '"').replace(/\\u0026/g, "&").replace(/\\'/g, "'").replace(/\\\//g, "/").replace(/\\\\/g, "\\").replace(/\\&/g, "&").replace(/\\'/g, "'").replace(/\\0/g, "\\u0000").replace(HEX_ESCAPE, (_, hex) => "\\u00" + hex).replace(INVALID_BACKSLASH, "");
}
function parseXDataJson(rawArg) {
const sanitized = sanitizeJson(rawArg);
return JSON.parse(sanitized);
}
function fetchWithTimeout(_0) {
return __async(this, arguments, function* (url, options = {}, timeoutMs = 8e3) {
const mergedHeaders = __spreadValues({
"User-Agent": HEADERS["User-Agent"],
"Referer": HEADERS["Referer"]
}, options.headers || {});
const fetchOptions = __spreadProps(__spreadValues({
skipSizeCheck: true
}, options), {
headers: mergedHeaders
});
if (typeof setTimeout !== "function") {
return fetch(url, fetchOptions);
}
let timer = null;
const timeoutPromise = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error("Timeout")), timeoutMs);
});
try {
const res = yield Promise.race([
fetch(url, fetchOptions),
timeoutPromise
]);
clearTimeout(timer);
return res;
} catch (e) {
clearTimeout(timer);
throw e;
}
});
}
function fetchText(_0) {
return __async(this, arguments, function* (url, options = {}) {
const finalUrl = url.startsWith("http") ? url : `${MAIN_URL}${url}`;
try {
const response = yield fetchWithTimeout(finalUrl, options, 1e4);
if (!response.ok)
return "";
return yield response.text();
} catch (e) {
return "";
}
});
}
function fetchWithCookies(_0) {
return __async(this, arguments, function* (url, options = {}) {
var _a, _b;
const finalUrl = url.startsWith("http") ? url : `${MAIN_URL}${url}`;
try {
const response = yield fetchWithTimeout(finalUrl, options, 1e4);
if (!response.ok)
return { text: "", cookies: "", ok: false };
const text = yield response.text();
let cookies = "";
try {
if (typeof ((_a = response.headers) == null ? void 0 : _a.getSetCookie) === "function") {
cookies = response.headers.getSetCookie().map((c) => c.split(";")[0]).join("; ");
} else if ((_b = response.headers) == null ? void 0 : _b.get) {
cookies = response.headers.get("set-cookie") || "";
}
} catch (_) {
}
return { text, cookies, ok: true };
} catch (e) {
return { text: "", cookies: "", ok: false };
}
});
}
function getImdbId(tmdbId, mediaType) {
return __async(this, null, function* () {
try {
const url = `https://api.themoviedb.org/3/${mediaType === "tv" ? "tv" : "movie"}/${tmdbId}/external_ids?api_key=${TMDB_API_KEY}`;
const res = yield fetchWithTimeout(url, {}, 5e3);
const data = yield res.json();
return data.imdb_id || null;
} catch (_) {
return null;
}
});
}
function isDateMatch(d1, d2) {
if (!d1 || !d2)
return false;
const s1 = d1.split("T")[0];
const s2 = d2.split("T")[0];
const date1 = /* @__PURE__ */ new Date(s1 + "T00:00:00Z");
const date2 = /* @__PURE__ */ new Date(s2 + "T00:00:00Z");
const diff = Math.abs(date1.getTime() - date2.getTime());
return Math.ceil(diff / (1e3 * 60 * 60 * 24)) <= 2;
}
function resolveMapping(imdbId, season, episode, tmdbId) {
return __async(this, null, function* () {
var _a, _b, _c, _d;
const seasonNum = parseInt(season, 10);
const episodeNum = parseInt(episode, 10);
const mapId = `${imdbId}:s${season}:e${episode}`;
let metaData = null;
const metaUrls = [
`https://v3-cinemeta.strem.io/meta/series/${imdbId}.json`,
`https://cinemeta-live.strem.io/meta/series/${imdbId}.json`
];
for (const url of metaUrls) {
try {
const mRes = yield fetchWithTimeout(url, {}, 5e3);
if (mRes.ok) {
const text = yield mRes.text();
const json = JSON.parse(text);
if ((_a = json == null ? void 0 : json.meta) == null ? void 0 : _a.videos) {
metaData = json.meta;
break;
}
}
} catch (_) {
}
}
if ((!metaData || !metaData.videos) && tmdbId) {
try {
const tmdbEpUrl = `https://api.themoviedb.org/3/tv/${tmdbId}/season/${seasonNum}/episode/${episodeNum}?api_key=${TMDB_API_KEY}`;
const tmdbRes = yield fetchWithTimeout(tmdbEpUrl, {}, 5e3);
if (tmdbRes.ok) {
const epData = JSON.parse(yield tmdbRes.text());
if (epData == null ? void 0 : epData.air_date) {
const tvUrl = `https://api.themoviedb.org/3/tv/${tmdbId}?api_key=${TMDB_API_KEY}`;
const tvRes = yield fetchWithTimeout(tvUrl, {}, 5e3);
const tvData = tvRes.ok ? JSON.parse(yield tvRes.text()) : {};
metaData = {
name: tvData.name || tvData.original_name,
moviedb_id: tmdbId,
videos: [{
season: seasonNum,
episode: episodeNum,
released: epData.air_date
}]
};
}
}
} catch (_) {
}
}
if (!metaData || !metaData.videos)
return null;
const video = metaData.videos.find((v) => v.season === seasonNum && v.episode === episodeNum);
if (!(video == null ? void 0 : video.released))
return null;
const airDate = video.released.split("T")[0];
const showTitle = metaData.name;
const dayIndex = metaData.videos.filter((v) => {
if (!v.released)
return false;
return v.released.split("T")[0] === airDate && (v.season < seasonNum || v.season === seasonNum && v.episode < episodeNum);
}).length;
let malIds = [];
const tId = tmdbId || metaData.moviedb_id || metaData.themoviedb_id;
const tvdbId = metaData.tvdb_id;
const armUrls = [
`https://arm.haglund.dev/api/v2/imdb?id=${imdbId}`,
tId ? `https://arm.haglund.dev/api/v2/themoviedb?id=${tId}` : null,
tvdbId ? `https://arm.haglund.dev/api/v2/thetvdb?id=${tvdbId}` : null
].filter(Boolean);
for (const url of armUrls) {
try {
const res = yield fetchWithTimeout(url, {}, 5e3);
if (res.ok) {
const data = JSON.parse(yield res.text());
if (Array.isArray(data)) {
data.forEach((e) => {
if (e.myanimelist)
malIds.push(e.myanimelist);
});
}
}
} catch (_) {
}
}
try {
const aniIdUrl = tId ? `https://api.ani.zip/mappings?themoviedb_id=${tId}` : `https://api.ani.zip/mappings?imdb_id=${imdbId}`;
const aniRes = yield fetchWithTimeout(aniIdUrl, {}, 5e3);
if (aniRes.ok) {
const aniData = JSON.parse(yield aniRes.text());
if ((_b = aniData == null ? void 0 : aniData.mappings) == null ? void 0 : _b.mal_id)
malIds.push(aniData.mappings.mal_id);
}
} catch (_) {
}
malIds = [...new Set(malIds)].filter(Boolean).sort((a, b) => b - a);
let finalResult = null;
for (const malId of malIds) {
try {
const aniRes = yield fetchWithTimeout(`https://api.ani.zip/mappings?mal_id=${malId}`, {}, 5e3);
if (aniRes.ok) {
const aniData = JSON.parse(yield aniRes.text());
const extraTitles = (aniData == null ? void 0 : aniData.titles) ? Object.values(aniData.titles).filter(Boolean) : [];
if (aniData == null ? void 0 : aniData.episodes) {
const aniEpisodes = Object.values(aniData.episodes).map((ep) => ({
mal_episode_number: parseInt(ep.episode, 10),
air_date: ep.airDateUtc || ep.airDate || ep.airdate
})).filter((ep) => !isNaN(ep.mal_episode_number));
const aniDateMatches = aniEpisodes.filter((ep) => isDateMatch(ep.air_date, airDate)).sort((a, b) => a.mal_episode_number - b.mal_episode_number);
if (aniDateMatches[dayIndex]) {
const match = aniDateMatches[dayIndex];
finalResult = {
id: mapId,
imdb_id: imdbId,
season: seasonNum,
episode: episodeNum,
mal_id: malId,
mal_episode: match.mal_episode_number,
anime_title: showTitle,
titles: extraTitles,
air_date: airDate
};
break;
}
}
}
} catch (_) {
}
try {
const jRes = yield fetchWithTimeout(`https://api.jikan.moe/v4/anime/${malId}`, {}, 5e3);
if (jRes.ok) {
const jData = JSON.parse(yield jRes.text());
if (((_d = (_c = jData == null ? void 0 : jData.data) == null ? void 0 : _c.aired) == null ? void 0 : _d.from) && isDateMatch(jData.data.aired.from, airDate)) {
finalResult = {
id: mapId,
imdb_id: imdbId,
season: seasonNum,
episode: episodeNum,
mal_id: malId,
mal_episode: dayIndex + 1,
anime_title: showTitle,
titles: [jData.data.title, jData.data.title_english, jData.data.title_japanese].filter(Boolean),
air_date: airDate
};
break;
}
}
} catch (_) {
}
}
if (!finalResult && malIds.length === 1 && seasonNum === 1) {
finalResult = {
id: mapId,
imdb_id: imdbId,
season: seasonNum,
episode: episodeNum,
mal_id: malIds[0],
mal_episode: episodeNum,
anime_title: showTitle,
titles: [],
air_date: airDate
};
}
return finalResult;
});
}
function getMalTitle(malId) {
return __async(this, null, function* () {
var _a, _b;
if (!malId)
return null;
try {
const res = yield fetchWithTimeout(`https://api.jikan.moe/v4/anime/${malId}`, {}, 5e3);
if (res.ok) {
const data = yield res.json();
return ((_a = data.data) == null ? void 0 : _a.title) || ((_b = data.data) == null ? void 0 : _b.title_english) || null;
}
} catch (_) {
}
return null;
});
}
function getTmdbInfo(tmdbId, mediaType, season = 1) {
return __async(this, null, function* () {
try {
const url = `https://api.themoviedb.org/3/${mediaType === "tv" ? "tv" : "movie"}/${tmdbId}?api_key=${TMDB_API_KEY}`;
const res = yield fetchWithTimeout(url, {}, 6e3);
if (!res.ok)
return null;
const data = yield res.json();
const info = {
title: data.name || data.title || data.original_name || data.original_title || "",
originalTitle: data.original_name || data.original_title || "",
seasonName: ""
};
if (mediaType === "tv" && season) {
try {
const sUrl = `https://api.themoviedb.org/3/tv/${tmdbId}/season/${season}?api_key=${TMDB_API_KEY}`;
const sRes = yield fetchWithTimeout(sUrl, {}, 6e3);
if (sRes.ok) {
const sData = yield sRes.json();
info.seasonName = sData.name || "";
}
} catch (e) {
}
}
return info;
} catch (e) {
return null;
}
});
}
// src/anizone/index.js
function normalize(str) {
if (!str)
return "";
return str.toLowerCase().replace(/[^a-z0-9]/g, "").trim();
}
function parseCards(html, $) {
const cards = [];
const itemsMatch = html.match(/items:\s*JSON\.parse\('((?:[^'\\]|\\.)*)'\)/);
if (itemsMatch) {
try {
const parsed = parseXDataJson(itemsMatch[1]);
if (Array.isArray(parsed)) {
for (const item of parsed) {
if (!item || !item.slug)
continue;
const titles = /* @__PURE__ */ new Set();
if (item.main_title)
titles.add(item.main_title);
if (item.title_list && typeof item.title_list === "object") {
Object.values(item.title_list).forEach((t) => {
if (t)
titles.add(t);
});
}
cards.push({
slug: item.slug,
url: item.url || `/anime/${item.slug}`,
titles: Array.from(titles)
});
}
}
} catch (e) {
}
}
if (cards.length === 0) {
$('[x-data*="anmTitles"]').each((i, el) => {
const href = $(el).find('a[href*="/anime/"]').first().attr("href");
if (!href)
return;
const parts = href.split("/");
const slug = parts[parts.length - 1] || parts[parts.length - 2];
const titles = /* @__PURE__ */ new Set();
const xData = $(el).attr("x-data") || "";
const jsonMatch = xData.match(/JSON\.parse\('((?:[^'\\]|\\.)*)'\)/);
if (jsonMatch) {
try {
const parsed = parseXDataJson(jsonMatch[1]);
Object.values(parsed).forEach((t) => {
if (t)
titles.add(t);
});
} catch (e) {
}
}
cards.push({ slug, titles: Array.from(titles) });
});
}
return cards;
}
function getSeasonRegexes(season) {
if (season === 1) {
return {
mustNot: [
/season\s*[2-9]/i,
/saison\s*[2-9]/i,
/[\s\-][iI]{2,}/,
/\s+[2-9]nd/i,
/\s+[2-9]rd/i,
/\s+[2-9]th/i,
/\s+ii\b/i,
/\s+iii\b/i,
/\s+iv\b/i,
/\s+v\b/i,
/movie/i,
/gekijouban/i,
/the movie/i
]
};
}
const patterns = [];
if (season === 2) {
patterns.push(/season\s*2/i, /saison\s*2/i, /2nd\s*season/i, /[\s\-]ii\b/i, /\b2\b/);
} else if (season === 3) {
patterns.push(/season\s*3/i, /saison\s*3/i, /3rd\s*season/i, /[\s\-]iii\b/i, /\b3\b/);
} else if (season === 4) {
patterns.push(/season\s*4/i, /saison\s*4/i, /4th\s*season/i, /[\s\-]iv\b/i, /\b4\b/, /final\s*season/i);
} else {
patterns.push(new RegExp(`(?:season|saison)\\s*${season}`, "i"), new RegExp(`\\b${season}\\b`));
}
return { must: patterns };
}
function matchCard(cards, targetTitles, baseTitle, season = 1, seasonName = "") {
const normalizedTargets = targetTitles.map(normalize).filter(Boolean);
const normalizedBase = normalize(baseTitle);
const normalizedSeasonName = normalize(seasonName);
if (normalizedSeasonName && normalizedSeasonName !== "season" + season) {
for (const card of cards) {
for (const title of card.titles) {
if (normalize(title).includes(normalizedSeasonName)) {
return card.slug;
}
}
}
}
for (const target of normalizedTargets) {
for (const card of cards) {
for (const title of card.titles) {
if (normalize(title) === target) {
return card.slug;
}
}
}
}
const seasonRules = getSeasonRegexes(season);
for (const card of cards) {
let matchesBase = false;
for (const title of card.titles) {
const norm = normalize(title);
if (norm.includes(normalizedBase) || normalizedBase.includes(norm)) {
matchesBase = true;
break;
}
}
if (!matchesBase)
continue;
let seasonMatches = false;
if (season === 1) {
let hasOtherSeason = false;
for (const title of card.titles) {
if (seasonRules.mustNot.some((regex) => regex.test(title))) {
hasOtherSeason = true;
break;
}
}
if (!hasOtherSeason)
seasonMatches = true;
} else {
for (const title of card.titles) {
if (seasonRules.must.some((regex) => regex.test(title))) {
seasonMatches = true;
break;
}
}
}
if (seasonMatches)
return card.slug;
}
return cards[0] ? cards[0].slug : null;
}
function matchMovieCard(cards, targetTitles) {
const normalizedTargets = targetTitles.map(normalize).filter(Boolean);
for (const card of cards) {
for (const title of card.titles) {
const norm = normalize(title);
if (normalizedTargets.some((t) => t === norm))
return card.slug;
}
}
for (const card of cards) {
for (const title of card.titles) {
const norm = normalize(title);
if (normalizedTargets.some((t) => norm.includes(t) || t.includes(norm)))
return card.slug;
}
}
return cards[0] ? cards[0].slug : null;
}
function parseVidstackFromHtml(html, $) {
const vidMatch = html.match(/vidstackPlayer\(JSON\.parse\('((?:[^'\\]|\\.)*)'\)\)/);
if (vidMatch) {
try {
const data = parseXDataJson(vidMatch[1]);
const masterUrl2 = data.src ? data.src.replace(/\\/g, "") : null;
const subtitles2 = (data.subtitles || []).map((s) => ({
url: s.file ? s.file.replace(/\\/g, "") : "",
name: s.title || s.language || "English",
language: s.language || "en"
})).filter((s) => s.url);
if (masterUrl2)
return { masterUrl: masterUrl2, subtitles: subtitles2 };
} catch (e) {
}
}
let masterUrl = $("media-player").attr("src");
if (!masterUrl) {
const urlMatch = html.match(/https:\/\/[^"']+\/master\.m3u8/);
if (urlMatch)
masterUrl = urlMatch[0];
}
const subtitles = [];
$("track").each((i, el) => {
const src = $(el).attr("src");
const kind = $(el).attr("kind");
if (src && (kind === "subtitles" || kind === "captions" || src.endsWith(".ass") || src.endsWith(".vtt"))) {
subtitles.push({
url: src,
name: $(el).attr("label") || "English",
language: $(el).attr("srclang") || "en"
});
}
});
return { masterUrl, subtitles };
}
function parseAudioFormat(btnText) {
const lower = btnText.toLowerCase();
const hasJap = lower.includes("japanese") || lower.includes("jpn") || lower.includes("ja");
const hasEng = lower.includes("english") || lower.includes("eng") || lower.includes("en");
if (hasEng && hasJap)
return "Dual Audio";
if (hasEng)
return "Dub";
if (hasJap)
return "Sub";
if (lower.includes("multi"))
return "Multi-Audio";
return "Sub";
}
function searchCards(query) {
return __async(this, null, function* () {
if (!query)
return [];
const searchUrl = `/anime?search=${encodeURIComponent(query)}&sort=title-asc`;
const searchHtml = yield fetchText(searchUrl);
if (!searchHtml)
return [];
const $search = import_cheerio_without_node_native.default.load(searchHtml);
return parseCards(searchHtml, $search);
});
}
function getStreams(tmdbId, mediaType = "tv", season = 1, episode = 1) {
return __async(this, null, function* () {
var _a, _b, _c;
try {
console.log(`[AniZone] Querying streams for TMDB: ${tmdbId}, Type: ${mediaType}, S${season}E${episode}`);
let animeTitle = "";
let altTitles = [];
let mappedEp = episode;
let seasonName = "";
let targetTitles = [];
if (mediaType === "tv") {
const imdbId = yield getImdbId(tmdbId, "tv");
if (imdbId) {
const mapping = yield resolveMapping(imdbId, season, episode, tmdbId);
if (mapping) {
mappedEp = mapping.mal_episode || episode;
animeTitle = mapping.anime_title || "";
if (mapping.titles && Array.isArray(mapping.titles)) {
targetTitles.push(...mapping.titles);
}
const malTitle = yield getMalTitle(mapping.mal_id);
if (malTitle) {
targetTitles.push(malTitle);
if (!animeTitle)
animeTitle = malTitle;
}
console.log(`[AniZone] AnimeSync mapped: "${animeTitle}", mappedEp=${mappedEp}`);
}
}
if (!animeTitle) {
const tmdbInfo = yield getTmdbInfo(tmdbId, mediaType, season);
if (tmdbInfo) {
animeTitle = tmdbInfo.title;
if (tmdbInfo.originalTitle)
altTitles.push(tmdbInfo.originalTitle);
seasonName = tmdbInfo.seasonName || "";
}
}
} else {
const tmdbInfo = yield getTmdbInfo(tmdbId, "movie");
if (tmdbInfo) {
animeTitle = tmdbInfo.title;
if (tmdbInfo.originalTitle)
altTitles.push(tmdbInfo.originalTitle);
}
mappedEp = 1;
}
if (!animeTitle && targetTitles.length === 0)
return [];
if (!animeTitle && targetTitles.length > 0)
animeTitle = targetTitles[0];
const specificTargetTitles = season === 1 || mediaType === "movie" ? [...targetTitles, animeTitle, ...altTitles] : [...targetTitles];
const baseCleanQuery = animeTitle.split(":")[0].replace(/season.*|\d+nd season|\d+rd season|\d+th season|saison.*/gi, "").trim();
let cards = yield searchCards(baseCleanQuery);
if (cards.length === 0 && animeTitle !== baseCleanQuery) {
cards = yield searchCards(animeTitle.split(":")[0].trim());
}
if (cards.length === 0) {
for (const t of altTitles) {
const altClean = t.split(":")[0].trim();
cards = yield searchCards(altClean);
if (cards.length > 0)
break;
}
}
if (cards.length === 0)
return [];
let animeSlug = null;
if (mediaType === "tv") {
animeSlug = matchCard(cards, specificTargetTitles, baseCleanQuery, season, seasonName);
} else {
animeSlug = matchMovieCard(cards, specificTargetTitles);
}
if (!animeSlug) {
console.log(`[AniZone] No matching slug found for "${animeTitle}"`);
return [];
}
console.log(`[AniZone] Selected slug: "${animeSlug}", mappedEp=${mappedEp}`);
const episodeUrl = `/anime/${animeSlug}/${mappedEp}`;
const epResponse = yield fetchWithCookies(episodeUrl);
if (!epResponse.ok || !epResponse.text) {
console.log(`[AniZone] Failed to load episode page: ${episodeUrl}`);
return [];
}
const epHtml = epResponse.text;
const $ep = import_cheerio_without_node_native.default.load(epHtml);
const streams = [];
const defaultStream = parseVidstackFromHtml(epHtml, $ep);
const serverButtons = $ep('button[wire\\:click*="setVideo"]');
let defaultFormat = "Sub";
let defaultServerName = "AniZone";
if (serverButtons.length > 0) {
const firstBtn = serverButtons.first();
const btnText = firstBtn.text().replace(/\s+/g, " ").trim();
defaultFormat = parseAudioFormat(btnText);
const nameMatch = btnText.match(/^([A-Za-z0-9_-]+)/);
if (nameMatch)
defaultServerName = nameMatch[1];
}
if (defaultStream.masterUrl) {
streams.push({
name: "AniZone",
title: `${animeTitle} - Episode ${mappedEp} [${defaultServerName} - ${defaultFormat}]`,
url: defaultStream.masterUrl,
quality: "Multi",
headers: HEADERS,
subtitles: defaultStream.subtitles
});
}
if (serverButtons.length > 1) {
const csrfToken = $ep("script[data-csrf]").attr("data-csrf");
const snapshotEl = $ep("main > div[wire\\:snapshot], main > ul[wire\\:snapshot], [wire\\:snapshot]");
const snapshot = snapshotEl.attr("wire:snapshot");
if (csrfToken && snapshot && epResponse.cookies) {
for (let i = 1; i < serverButtons.length; i++) {
const btn = serverButtons.eq(i);
const clickAttr = btn.attr("wire:click") || "";
const vMatch = clickAttr.match(/setVideo\((\d+)\)/);
if (!vMatch)
continue;
const videoId = parseInt(vMatch[1], 10);
const btnText = btn.text().replace(/\s+/g, " ").trim();
const sFormat = parseAudioFormat(btnText);
const nameMatch = btnText.match(/^([A-Za-z0-9_-]+)/);
const sName = nameMatch ? nameMatch[1] : `Server ${i + 1}`;
try {
const payload = {
_token: csrfToken,
components: [
{
snapshot,
updates: {},
calls: [{ path: "", method: "setVideo", params: [videoId] }]
}
]
};
const postRes = yield fetchWithTimeout(`${MAIN_URL}/livewire/update`, {
method: "POST",
headers: {
"Accept": "*/*",
"Content-Type": "application/json",
"X-Livewire": "",
"X-CSRF-TOKEN": csrfToken,
"Origin": MAIN_URL,
"Referer": `${MAIN_URL}${episodeUrl}`,
"Cookie": epResponse.cookies
},
body: JSON.stringify(payload)
}, 8e3);
if (postRes.ok) {
const postData = yield postRes.json();
const liveHtml = (_c = (_b = (_a = postData.components) == null ? void 0 : _a[0]) == null ? void 0 : _b.effects) == null ? void 0 : _c.html;
if (liveHtml) {
const $live = import_cheerio_without_node_native.default.load(liveHtml);
const extraStream = parseVidstackFromHtml(liveHtml, $live);
if (extraStream.masterUrl && extraStream.masterUrl !== defaultStream.masterUrl) {
streams.push({
name: "AniZone",
title: `${animeTitle} - Episode ${mappedEp} [${sName} - ${sFormat}]`,
url: extraStream.masterUrl,
quality: "Multi",
headers: HEADERS,
subtitles: extraStream.subtitles.length > 0 ? extraStream.subtitles : defaultStream.subtitles
});
}
}
}
} catch (e) {
}
}
}
}
console.log(`[AniZone] Total streams found: ${streams.length}`);
return streams;
} catch (error) {
console.log(`[AniZone] Error: ${error.message}`);
return [];
}
});
}
module.exports = { getStreams };
+159 -1
View File
@@ -1 +1,159 @@
const _0xf741e1=_0x2887;(function(_0x304ad9,_0x44115a){const _0x3e16ff={_0x32d8aa:0x1de,_0x42cdc4:0x214,_0x861482:0x205,_0xb988b1:0x1d3,_0x2b46cb:0x1f7,_0x1f23a8:0x1fb,_0x3e1e14:0x1ee},_0x34545a=_0x2887,_0x3c5ad8=_0x304ad9();while(!![]){try{const _0x1de960=-parseInt(_0x34545a(_0x3e16ff._0x32d8aa))/0x1+parseInt(_0x34545a(_0x3e16ff._0x42cdc4))/0x2*(parseInt(_0x34545a(0x1cc))/0x3)+-parseInt(_0x34545a(_0x3e16ff._0x861482))/0x4*(parseInt(_0x34545a(_0x3e16ff._0xb988b1))/0x5)+-parseInt(_0x34545a(0x201))/0x6+-parseInt(_0x34545a(_0x3e16ff._0x2b46cb))/0x7*(-parseInt(_0x34545a(_0x3e16ff._0x1f23a8))/0x8)+-parseInt(_0x34545a(_0x3e16ff._0x3e1e14))/0x9*(parseInt(_0x34545a(0x20c))/0xa)+-parseInt(_0x34545a(0x1fe))/0xb;if(_0x1de960===_0x44115a)break;else _0x3c5ad8['push'](_0x3c5ad8['shift']());}catch(_0x1a6883){_0x3c5ad8['push'](_0x3c5ad8['shift']());}}}(_0x3133,0xcdd99));var __async=(_0x2d675e,_0x60c5d2,_0x4d995e)=>{return new Promise((_0x4625d3,_0x318b22)=>{const _0x3ca796=_0x2887;var _0x2208ac=_0x3e7f5a=>{try{_0x4a8699(_0x4d995e['next'](_0x3e7f5a));}catch(_0x548bed){_0x318b22(_0x548bed);}},_0x27dcf1=_0x1e6249=>{try{_0x4a8699(_0x4d995e['throw'](_0x1e6249));}catch(_0x39c42){_0x318b22(_0x39c42);}},_0x4a8699=_0x278d21=>_0x278d21['done']?_0x4625d3(_0x278d21[_0x3ca796(0x216)]):Promise['resolve'](_0x278d21[_0x3ca796(0x216)])[_0x3ca796(0x1d6)](_0x2208ac,_0x27dcf1);_0x4a8699((_0x4d995e=_0x4d995e['apply'](_0x2d675e,_0x60c5d2))['next']());});},cheerio=require(_0xf741e1(0x1f5)),BASE_URL=_0xf741e1(0x1f3),TMDB_API_KEY=_0xf741e1(0x1ca),BROWSER_UA=_0xf741e1(0x20d),HEADERS={'User-Agent':BROWSER_UA,'Referer':BASE_URL+'/'},PLAYBACK_HEADERS={'User-Agent':BROWSER_UA,'Referer':'https://urlshortlink.top/','Origin':'https://urlshortlink.top'};function _0x3133(){const _0x43fded=['mtG2nwy0m2eWntq5y2e1mgqZndfKzdLHyJHImJLMndK','ic0G','m1Lot01mDq','zgL2lNzPzgvVlxrODw1IigLTzW','DxjS','CMvWBgfJzq','nZiWCa','lM0ZDtG','vw5RBM93BIbuAxrSzq','nuvjBLvvCa','zxjYB3i','C3rHCNrZv2L0Aa','DgHLBG','zw5NBgLZAa','zxbPC29Kzv9YDw5FDgLTzq','DgvSDwD1','ihWG4O+X77Ipia','DhjPBq','mta4ma','yxr0CG','odK2nduZvwngAfDt','Ahr0Chm6lY9HCgKUDgHLBw92AwvKyI5VCMCVmY8','w0zPyLDHDgnOxq','Cg9WDxa','8j+oNU+4JYa','vgfTAwW','zMLUza','Dw5KzwzPBMvK','rw5NBgLZAcdIGkiGsgLUzgK','Dg9mB3DLCKnHC2u','4PQRiezPyLDHDgnOihWG','Bwf0y2G','BMfTzq','Bg9Hza','Aw5WDxqJDMLKzw8TAwq','zhvHBa','mtm4mZn6BuH5zhu','ywrK','u2LUz2XLluf1zgLV','ChvZAa','DgL0Bgu','Ahr0Chm6lY9MAwj3yxrJAc5HCNq','ANnVBG','y2HLzxjPBY13AxrOB3v0lw5VzguTBMf0AxzL','BxvSDgK','mta3ody5nZL0v1LNzNq','tI9b','ndGW','Ahr0Ca','ofnysvvZqG','rhvHBc1bDwrPBW','BgvUz3rO','ntqWmJiZmMXOA1rXwG','lM1Wna','DxjSpwH0Dha','mtu2mZiZnhr4zgTSta','zxHWB3j0CW','DgfTAwW','8j+oRca','mtC5odG1nKDSC3Dqyq','jNbHz2vFAwq9mq','qMfUz2XH','Dgv4Da','Aw5JBhvKzxm','vw5RBM93BG','sgLUzgK','nJuWqxzzyLvb','tw96AwXSys81lJaGkeXPBNv4oYbbBMrYB2LKideWoYblksbbChbSzvDLyKTPDc81mZCUmZyGkeTive1mlcbSAwTLieDLy2TVksbdAhjVBwuVmtm3lJaUmc4Wie1VyMLSzsbtywzHCMKVntm3lJm2','l2fQyxGVzxbPC29KzxmUCgHWp3zPzgvVx2LKpq','yMfUz2XH','C29YDa','CxvHBgL0Eq','CNvUDgLTzq','zwfJAa','mJK5otC3nfPNtfP1sq','mJe2ma','DMfSDwu','ndGWCa','mZyW','AhjLzG','ic0GuW'];_0x3133=function(){return _0x43fded;};return _0x3133();}function extractQuality(_0x4af06e){const _0x2a1bf5={_0x1845bf:0x209,_0x287843:0x209,_0x846d66:0x1d0,_0x5618bd:0x1f9,_0x1139ad:0x217,_0x368115:0x218},_0x3d3eb7=_0xf741e1,_0x364bfd=(_0x4af06e||'')[_0x3d3eb7(0x1e7)]();if(_0x364bfd['includes'](_0x3d3eb7(0x215))||_0x364bfd[_0x3d3eb7(_0x2a1bf5._0x1845bf)]('4k'))return'4K';if(_0x364bfd['includes'](_0x3d3eb7(0x1dc)))return'1080p';if(_0x364bfd[_0x3d3eb7(_0x2a1bf5._0x287843)]('720'))return _0x3d3eb7(_0x2a1bf5._0x846d66);if(_0x364bfd[_0x3d3eb7(0x209)](_0x3d3eb7(_0x2a1bf5._0x5618bd)))return _0x3d3eb7(_0x2a1bf5._0x1139ad);if(_0x364bfd['includes'](_0x3d3eb7(_0x2a1bf5._0x368115)))return'360p';return'Unknown';}function parseStreamFromShortenerHtml(_0x472691){const _0x1a0a70={_0x5861aa:0x1eb},_0x17f5a5={_0x2ee33e:0x200},_0x1d6725=_0xf741e1;if(!_0x472691)return null;const _0x30fbd7=cheerio[_0x1d6725(_0x1a0a70._0x5861aa)](_0x472691);let _0x37aa7e=_0x30fbd7('a.hidden-button.buttonDownloadnew')['attr'](_0x1d6725(0x219));!_0x37aa7e&&_0x30fbd7('a')['each']((_0x439235,_0x3862d7)=>{const _0xd3d77c=_0x1d6725,_0x58c50c=_0x30fbd7(_0x3862d7)['attr']('href')||'';if(_0x58c50c[_0xd3d77c(0x209)](_0xd3d77c(_0x17f5a5._0x2ee33e)))return _0x37aa7e=_0x58c50c,![];});if(!_0x37aa7e){const _0x34e4f4=/https?:\/\/[^\s"'`<>]+?\.b-cdn\.net\/[^\s"'`<>]+\.(?:mkv|mp4|m3u8)/i,_0x2d5b16=_0x472691['match'](_0x34e4f4);if(_0x2d5b16)return _0x2d5b16[0x0];}if(_0x37aa7e){let _0x88d123=_0x37aa7e[_0x1d6725(0x1cf)](/.*url=/,'')[_0x1d6725(0x1db)]();return decodeURIComponent(_0x88d123);}return null;}function _0x2887(_0x4265b4,_0x56ac93){_0x4265b4=_0x4265b4-0x1ca;const _0x3133cd=_0x3133();let _0x2887f5=_0x3133cd[_0x4265b4];if(_0x2887['OuoIzx']===undefined){var _0x23b500=function(_0xc211e8){const _0x691c83='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x2d675e='',_0x60c5d2='';for(let _0x4d995e=0x0,_0x4Line truncated
const cheerio = require('cheerio-without-node-native');
const DEFAULT_BASE = 'https://fibwatch.art';
const DOMAIN_LIST = 'https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json';
const TMDB_KEY = '439c478a771f35c05022f9feabcca01c';
const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
function absolute(base, value) {
if (!value) return '';
try { return new URL(value, base).href; } catch (_) { return value; }
}
function getBase() {
return fetch(DOMAIN_LIST, { headers: { 'User-Agent': UA } })
.then(r => r.ok ? r.json() : {})
.then(data => data.fibwatch || DEFAULT_BASE)
.catch(() => DEFAULT_BASE);
}
function tmdbDetails(id, type) {
return fetch(`https://api.themoviedb.org/3/${type === 'tv' ? 'tv' : 'movie'}/${id}?api_key=${TMDB_KEY}`, { headers: { 'User-Agent': UA } })
.then(r => r.ok ? r.json() : Promise.reject(new Error(`TMDB ${r.status}`)))
.then(data => ({ title: type === 'tv' ? data.name : data.title, year: Number(((type === 'tv' ? data.first_air_date : data.release_date) || '').slice(0, 4)) || null }));
}
function search(base, title) {
const url = `${base}/search?keyword=${encodeURIComponent(title)}&page_id=1`;
return fetch(url, { headers: { 'User-Agent': UA, 'Referer': `${base}/`, 'Cookie': 'pop_up_18=yes' } })
.then(r => r.ok ? r.text() : '')
.then(html => {
const $ = cheerio.load(html);
const results = [];
$('div.video-thumb').each((_, el) => {
const card = $(el);
const a = card.find('a[href]').first();
const img = card.find('img').first();
const name = (card.find('p.hptag').text() || img.attr('alt') || '').trim();
if (a.attr('href') && name) results.push({ url: absolute(base, a.attr('href')), title: name, image: absolute(base, img.attr('src')) });
});
return results;
});
}
function normalize(s) { return (s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim(); }
function bestMatch(results, title, year) {
const target = normalize(title);
let best = null, bestScore = 0;
for (const item of results) {
const candidate = normalize(item.title);
let score = candidate === target ? 2 : (candidate.includes(target) || target.includes(candidate) ? 1 : 0);
const y = Number((item.title.match(/\b(19|20)\d{2}\b/) || [])[0]);
if (year && y) score += y === year ? 0.3 : -0.2;
if (score > bestScore) { best = item; bestScore = score; }
}
return bestScore >= 1 ? best : null;
}
function findVideoId($) {
return $('#video-id').attr('value') || $('input#video-id').val() || '';
}
function extractPageStreams(base, pageUrl, title) {
return fetch(pageUrl, { headers: { 'User-Agent': UA, 'Referer': `${base}/`, 'Cookie': 'pop_up_18=yes' } })
.then(r => r.ok ? r.text() : '')
.then(html => {
const $ = cheerio.load(html);
const pageTitle = $('meta[property="og:title"]').attr('content') || title;
const videoId = findVideoId($);
if (!videoId) {
const direct = [];
const videoUrl = html.match(/var\s+VIDEO_URL\s*=\s*["']([^"']+)["']/i);
if (videoUrl) direct.push({ name: 'FibWatch', title: pageTitle, url: absolute(base, videoUrl[1]), quality: 'Auto', headers: { Referer: pageUrl } });
return direct;
}
return fetch(`${base}/ajax/resolution_switcher.php?video_id=${encodeURIComponent(videoId)}`, { headers: { 'User-Agent': UA, 'Referer': pageUrl, 'X-Requested-With': 'XMLHttpRequest', 'Cookie': 'pop_up_18=yes' } })
.then(r => r.ok ? r.text() : '')
.then(data => {
const out = [];
const text = typeof data === 'string' ? data : JSON.stringify(data);
const push = (url, label) => {
const absoluteUrl = absolute(base, url);
if (/^https?:/i.test(absoluteUrl) && !out.some(s => s.url === absoluteUrl)) out.push({ name: 'FibWatch', title: label || pageTitle, url: absoluteUrl, quality: (label || absoluteUrl).match(/(2160p|1080p|720p|480p|360p|4k)/i)?.[0] || 'Auto', headers: { Referer: pageUrl } });
};
try {
const json = JSON.parse(text);
const walk = obj => {
if (!obj) return;
if (typeof obj === 'string' && /^(https?:)?\/\//i.test(obj) && /\.(m3u8|mp4|mkv)(\?|$)/i.test(obj)) push(obj);
else if (Array.isArray(obj)) obj.forEach(walk);
else if (typeof obj === 'object') Object.keys(obj).forEach(k => walk(obj[k]));
};
walk(json);
} catch (_) {
const re = /(?:https?:)?\\?\/?\\?["']?([^\s"'<>]+\.(?:m3u8|mp4|mkv)(?:\?[^\s"'<>]*)?)/gi;
let m;
while ((m = re.exec(text))) push(m[1].replace(/\\\//g, '/'));
}
return out;
});
});
}
function episodePage(base, seriesUrl, season, episode) {
return fetch(seriesUrl, { headers: { 'User-Agent': UA, 'Referer': `${base}/`, 'Cookie': 'pop_up_18=yes' } })
.then(r => r.ok ? r.text() : '')
.then(html => {
const $ = cheerio.load(html);
const videoId = findVideoId($);
if (!videoId) return null;
return fetch(`${base}/ajax/episodes.php?video_id=${encodeURIComponent(videoId)}`, {
headers: { 'User-Agent': UA, 'Referer': seriesUrl, 'Cookie': 'pop_up_18=yes', 'X-Requested-With': 'XMLHttpRequest' }
}).then(r => r.ok ? r.text() : '').then(body => {
let data;
try { data = JSON.parse(body); } catch (_) { data = null; }
const items = data && (data.episodes || data.data || data.items);
const episodeText = `s${String(season).padStart(2, '0')}e${String(episode).padStart(2, '0')}`;
if (Array.isArray(items)) {
const found = items.find(item => {
const text = `${item.display || ''} ${item.title || ''}`.toLowerCase();
const match = text.match(/s\s*(\d{1,2})\s*e\s*(\d{1,3})/i);
if (match) return Number(match[1]) === Number(season) && Number(match[2]) === Number(episode);
const seasonMatch = text.match(/\bseason\s*(\d+)\b/i);
const episodeMatch = text.match(/\bepisode\s*(\d+)\b/i);
return Number(seasonMatch && seasonMatch[1]) === Number(season) && Number(episodeMatch && episodeMatch[1]) === Number(episode);
});
if (found && found.url) return absolute(base, found.url);
}
const $episodes = cheerio.load(body);
let href = null;
$episodes('a[href], .video-wrapper a[href]').each((_, el) => {
if (href) return;
const text = `${$episodes(el).text()} ${$episodes(el).attr('title') || ''}`.toLowerCase();
const match = text.match(/s\s*(\d{1,2})\s*e\s*(\d{1,3})/i);
const seasonMatch = text.match(/\bseason\s*(\d+)\b/i);
const episodeMatch = text.match(/\bepisode\s*(\d+)\b/i);
if ((match && Number(match[1]) === Number(season) && Number(match[2]) === Number(episode)) ||
(Number(seasonMatch && seasonMatch[1]) === Number(season) && Number(episodeMatch && episodeMatch[1]) === Number(episode))) href = $episodes(el).attr('href');
});
return href ? absolute(base, href) : null;
});
});
}
function getStreams(tmdbId, mediaType = 'movie', season, episode) {
return Promise.all([getBase(), tmdbDetails(tmdbId, mediaType)])
.then(([base, media]) => search(base, media.title).then(results => ({ base, media, results })))
.then(({ base, media, results }) => {
const match = bestMatch(results, media.title, media.year);
if (!match) return [];
if (mediaType === 'tv' && season != null && episode != null) {
return episodePage(base, match.url, season, episode)
.then(url => url ? extractPageStreams(base, url, `${match.title} S${season}E${episode}`) : []);
}
return extractPageStreams(base, match.url, match.title);
})
.catch(error => { console.error('[FibWatch] Stream lookup failed:', error.message); return []; });
}
module.exports = { getStreams };
+846 -1
View File
@@ -1 +1,846 @@
function _0x1d41(){const _0x4db01a=['zw5J','n1nlz1L4BW','Cg9ZDf90AhvTyM5HAwW','mtK5nZj3s3fituK','Ahr0Chm6lY9UzxCXlMHKAhvInhuUy2W','DgL0Bgu','mtbqEM54yNi','y2HHCKf0','ChvZAa','Ahr0Chm6lY9HCgKUDgHLBw92AwvKyI5VCMCVmW','Ahr0Chm6lY9YyxCUz2L0AhvIDxnLCMnVBNrLBNqUy29Tl3bOAxnOzxi5oc9uvLzwvI9YzwzZl2HLywrZl21HAw4Vzg9TywLUCY5QC29U','yM9KEq','ndm5yZq3oge3nZfMmZvJmduWmJjMowzLywjJy2eWmwm','p2LKpq','CJiUzgv2','zwfJAa','BwvZC2fNzq','zMLUza','zMLYC3rFywLYx2rHDgu','DxjS','CgL4zwXKCMe','w0HeshvInhvDifrnreiGsw5MBZOGiG','C3rHDhvZvgv4Da','qNL0zxm','mZC5oduXB1z0Bwvf','i2rVD25SB2fK','ieHIBgLUA3m','Dgv4Da','lNPPCa','ttnvoa','seriDwi0Dsa','w0HeshvInhvDiezLDgnOAw5Nihn0CMvHBxmGzM9YifrnreiGsuq6ia','jMfWCgvUzf90B19YzxnWB25Zzt1LEhrLCM5HBf9Pzhm','ywXS','vw5RBM93BG','qvzd','ChjVDg9JB2W','AduGysWGAdqGysWGAdmGyq','sgv4','CgvYBwfSAw5R','C3rHCNrZv2L0Aa','C3bSAxq','q0fn','AM9PBG','BM93','mtu2odaWmdDdugDQq3e','AgrZDhjLyw00Dq','v0vcuKLq','z2v0t3DUuhjVCgvYDhLezxnJCMLWDg9Y','C291CMnL','zMLSzu5HBwu','mZu3mJGZmgz6u1nLqG','Aw1KyL9Pza','Ahr0Chm6lY9ZzwfYy2GUCgLUz29Yys5MEwKVy29SBgvJDgLVBNmVCg9ZDc9KB2n1BwvUDhmVC2vHCMnOp3e9','BwfNBMv0oG','DMfSDwu','Ahr0Ca','EMLWzgLZAW','y3j5ChrVAw5ZAwDODhmUC2L0zq','z2v0','AgfZ','AgfZt3DUuhjVCgvYDhK','sdi2nq','BMv4Da','EwvHCG','w0HeshvInhvDiejLC3qGDgL0BguGBwf0y2G6ici','nZiWCa','iIaO','nJyWmdy0ogLmC0r3vG','p2rVD25SB2fK','lNbHz2uTyM9KEsa+igrPDIbH','u3rYzwfTvgfWzq','sfGTuMvKAxjLy3q','DhjPBq','BwfW','v0vclurm','re9mqLLwsvnjt04','wMLWrgLZAYbtzxj2zxi','shvIq2XVDwqGlsbgu0W','zMXHDa','AhvIy2XVDwqUy3G','w0HeshvInhvDiezHAwXLzcb0BYbMzxrJAcbSyxrLC3qGzg9TywLUCZOG','mdeYmZq1nJC4owfIy2rLzG','C3vIC3rYAw5N','y2HLzxjPBY13AxrOB3v0lw5VzguTBMf0AxzL','DgHYB3C','BgLUAZ0','A2LLBxrPzw5TDwe5mtfJyq','qufd','Cg9ZDf90AxrSzq','shvIq2rU','ChjVCgvYDhLjC0vUDw1LCMfIBgu','BNvTyMvY','ywrK','zNjVBunOyxjdB2rL','ihrVia','serivui0Dq','CxvHBgL0Eq','q0jd','shvIq2XVDwqGlsaXmeDIChmG','CMvWBgfJzq','Dg9mB3DLCKnHC2u','EgXHpxm0Da','qujdrevgr0HjsKTmtu5puffsu1rvvLDywvPHyMnKzwzNAgLQA2XTBM9WCxjZDhv2D3H5EJaXmJm0nty3odKRlZ0','mtu4mda0nhn6yMLUra','x19LC01VzhvSzq','Bwf0y2G','AgL0CW','sgjmAw5RCW','Cg9W','l2rVD25SB2fK','CgfYC2u','zxbPC29Kzq','C29Tzq','Bg9N','z2v0t3DUuhjVCgvYDhLtEw1IB2XZ','BgfZDeLUzgv4t2y','mJiZnJq1oeHyBwv5BW','zgvMAw5LuhjVCgvYDhK','CMvZB2X2zq','zNvUy3rPB24','C2v0','zgvMyxvSDa','rgLYzwn0ifiY','z2v0t3DUuhjVCgvYDhLoyw1LCW','ChjVDg90ExbL','uMvMzxjLCG','C3rHDhvZ','AhGTCMvKAxjLy3q','Aw5JBhvKzxm','AdeUCgfNzs10AxrSzsbZCgfU','CMv1CMW','AsnZAxPL','qLjssva','CZmGC2vYDMvY','w0HeshvInhvDifnLBgvJDgvKoIaI','y2fSBa','ifnLyxnVBIa','mta4mha','yMXVz191CMW','iIaOC2nVCMu6ia','AhvIy2XVDwqUAw5R','mtiZndu2nZG5mg9PDxL0CG','AhrTBa','C3rYAw5N','CMvSzwfZzv9KyxrL','C2L6zq','DgvJAhLIB3K0Dq','l2fWAs92ms92AwrLBZ9Pzd0','C2vHC29Uia','C3rYzwfTDgfWzs5JB20','zw51BwvYywjSzq','lcbuExbLoIa','yxr0CG','shvIq2XVDwq','BgvUz3rO','AhjLzG','vxrMoa','zgvMAw5LuhjVCgvYDgLLCW','tw96AwXSys81lJaGkfDPBMrVD3mGtLqGmtaUmdSGv2LUnJq7ihG2ncKGqxbWBgvxzwjlAxqVntm3lJm2','zNnSDJi','z2v0t3DUuhjVCgvYDhLezxnJCMLWDg9YCW','zNnSihnLCNzLCG','zxHWB3j0CW','Bw92Awu','AdmGysWGAdqGyq','zgf0yq','z2fKz2v0C3DLyI54ExO','tw96AwXSys81lJa','Dg9tDhjPBMC','ugL4zwXKCMfPBG','Ag9ZDg5HBwu','AhvIy2rU','AgrODwi0Dq','sdi2na','BwfUDwfS','Dg9vChbLCKnHC2u','rfrt','BMfTzq','zMLSDgvY','zxHLyW','wMLWrgLZAYbtzxj2zxiG','sgrtDhjLyw00Dq','Bg9Hza','B2jQzwn0','p2fWAv9RzxK9','r0vu','AgvHzgvYCW','neTsywD4ua','zxH0zxjUywXFAwrZ','Cg93','CgfKu3rHCNq','shvIC3rYzwfT','Bg9JyxrPB24','zMLUywXmAw5RCW'];_0x1d41=function(){return _0x4db01a;};return _0x1d41();}const _0x4cfe8c=_0x1850;(function(_0x4bd1e8,_0x326e94){const _0x3f3482={_0x2ebcc9:0xb1,_0x1082ec:0xe1,_0x1f3a99:0xaf,_0xdb40a:0xb4},_0x432f61=_0x1850,_0x252534=_0x4bd1e8();while(!![]){try{const _0x7c34e9=-parseInt(_0x432f61(_0x3f3482._0x2ebcc9))/0x1+-parseInt(_0x432f61(0x116))/0x2+parseInt(_0x432f61(0xc6))/0x3+parseInt(_0x432f61(0x16a))/0x4*(parseInt(_0x432f61(_0x3f3482._0x1082ec))/0x5)+-parseInt(_0x432f61(0x123))/0x6*(parseInt(_0x432f61(_0x3f3482._0x1f3a99))/0x7)+-parseInt(_0x432f61(0xf2))/0x8+parseInt(_0x432f61(0xdb))/0x9*(parseInt(_0x432f61(_0x3f3482._0xdb40a))/0xa);if(_0x7c34e9===_0x326e94)break;else _0x252534['push'](_0x252534['shift']());}catch(_0x3cc61a){_0x252534['push'](_0x252534['shift']());}}}(_0x1d41,0x8c864));var __create=Object['create'],__defProp=Object[_0x4cfe8c(0x124)],__defProps=Object[_0x4cfe8c(0x14c)],__getOwnPropDesc=Object[_0x4cfe8c(0xde)],__getOwnPropDescs=Object[_0x4cfe8c(0x14f)],__getOwnPropNames=Object[_0x4cfe8c(0x12a)],__getOwnPropSymbols=Object[_0x4cfe8c(0x121)],__getProtoOf=Object['getPrototypeOf'],__hasOwnProp=Object['prototype'][_0x4cfe8c(0xeb)],__propIsEnum=Object[_0x4cfe8c(0x12b)][_0x4cfe8c(0x109)],__defNormalProp=(_0x88bbc8,_0x59e2f6,_0x38ec05)=>_0x59e2f6 in _0x88bbc8?__defProp(_0x88bbc8,_0x59e2f6,{'enumerable':!![],'configurable':!![],'writable':!![],'value':_0x38ec05}):_0x88bbc8[_0x59e2f6]=_0x38ec05,__spreadValues=(_0x586ac9,_0x243eff)=>{const _0x3d2fc4=_0x4cfe8c;for(var _0x4d4ed6 in _0x243eff||(_0x243eff={}))if(__hasOwnProp['call'](_0x243eff,_0x4d4ed6))__defNormalProp(_0x586ac9,_0x4d4ed6Line truncated
/**
* hdhub4u - Built from src/hdhub4u/
* Generated: 2026-10-02T12:34:10.590Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/hdhub4u/index.js
var import_cheerio_without_node_native2 = __toESM(require("cheerio-without-node-native"));
// src/hdhub4u/constants.js
var TMDB_API_KEY = "439c478a771f35c05022f9feabcca01c";
var TMDB_BASE_URL = "https://api.themoviedb.org/3";
var MAIN_URL = "https://new6.hdhub4u.cl";
var DOMAINS_URL = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json";
var DOMAIN_CACHE_TTL = 4 * 60 * 60 * 1e3;
var HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
"Cookie": "xla=s4t",
"Referer": `${MAIN_URL}/`
};
function updateMainUrl(url) {
MAIN_URL = url;
HEADERS.Referer = `${url}/`;
}
// src/hdhub4u/utils.js
var domainCacheTimestamp = 0;
function formatBytes(bytes) {
if (!bytes || bytes === 0)
return "Unknown";
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
}
function extractServerName(source) {
if (!source)
return "Unknown";
if (source.startsWith("HubCloud")) {
const serverMatch = source.match(/HubCloud(?:\s*-\s*([^[\]]+))?/);
return serverMatch ? serverMatch[1] || "Download" : "HubCloud";
}
if (source.startsWith("Pixeldrain"))
return "Pixeldrain";
if (source.startsWith("StreamTape"))
return "StreamTape";
if (source.startsWith("HubCdn"))
return "HubCdn";
if (source.startsWith("HbLinks"))
return "HbLinks";
if (source.startsWith("Hubstream"))
return "Hubstream";
return source.replace(/^www\./, "").split(".")[0];
}
function rot13(value) {
return value.replace(/[a-zA-Z]/g, function(c) {
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
});
}
var BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function atob(value) {
if (!value)
return "";
let input = String(value).replace(/=+$/, "");
let output = "";
let bc = 0, bs, buffer, idx = 0;
while (buffer = input.charAt(idx++)) {
buffer = BASE64_CHARS.indexOf(buffer);
if (~buffer) {
bs = bc % 4 ? bs * 64 + buffer : buffer;
if (bc++ % 4) {
output += String.fromCharCode(255 & bs >> (-2 * bc & 6));
}
}
}
return output;
}
function cleanTitle(title) {
let name = title.replace(/\.[a-zA-Z0-9]{2,4}$/, "");
const normalized = name.replace(/WEB[-_. ]?DL/gi, "WEB-DL").replace(/WEB[-_. ]?RIP/gi, "WEBRIP").replace(/H[ .]?265/gi, "H265").replace(/H[ .]?264/gi, "H264").replace(/DDP[ .]?([0-9]\.[0-9])/gi, "DDP$1");
const parts = normalized.split(/[\s_.]/);
const sourceTags = /* @__PURE__ */ new Set(["WEB-DL", "WEBRIP", "BLURAY", "HDRIP", "DVDRIP", "HDTV", "CAM", "TS", "BRRIP", "BDRIP"]);
const codecTags = /* @__PURE__ */ new Set(["H264", "H265", "X264", "X265", "HEVC", "AVC"]);
const audioTags = ["AAC", "AC3", "DTS", "MP3", "FLAC", "DD", "DDP", "EAC3"];
const audioExtras = /* @__PURE__ */ new Set(["ATMOS"]);
const hdrTags = /* @__PURE__ */ new Set(["SDR", "HDR", "HDR10", "HDR10+", "DV", "DOLBYVISION"]);
const filtered = parts.map((part) => {
const p = part.toUpperCase();
if (sourceTags.has(p))
return p;
if (codecTags.has(p))
return p;
if (audioTags.some((tag) => p.startsWith(tag)))
return p;
if (audioExtras.has(p))
return p;
if (hdrTags.has(p))
return p === "DOLBYVISION" || p === "DV" ? "DOLBYVISION" : p;
if (p === "NF" || p === "CR")
return p;
return null;
}).filter(Boolean);
return [...new Set(filtered)].join(" ");
}
function fetchAndUpdateDomain() {
return __async(this, null, function* () {
const now = Date.now();
if (now - domainCacheTimestamp < DOMAIN_CACHE_TTL)
return;
console.log("[HDHub4u] Fetching latest domain...");
try {
const response = yield fetch(DOMAINS_URL, {
method: "GET",
headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }
});
if (response.ok) {
const data = yield response.json();
if (data && data.HDHUB4u) {
const newDomain = data.HDHUB4u;
if (newDomain !== MAIN_URL) {
console.log(`[HDHub4u] Updating domain from ${MAIN_URL} to ${newDomain}`);
updateMainUrl(newDomain);
domainCacheTimestamp = now;
}
}
}
} catch (error) {
console.error(`[HDHub4u] Failed to fetch latest domains: ${error.message}`);
}
});
}
function getCurrentDomain() {
return __async(this, null, function* () {
yield fetchAndUpdateDomain();
return MAIN_URL;
});
}
function normalizeTitle(title) {
if (!title)
return "";
return title.toLowerCase().replace(/\b(the|a|an)\b/g, "").replace(/[:\-_]/g, " ").replace(/\s+/g, " ").replace(/[^\w\s]/g, "").trim();
}
function calculateTitleSimilarity(title1, title2) {
const norm1 = normalizeTitle(title1);
const norm2 = normalizeTitle(title2);
if (norm1 === norm2)
return 1;
const words1 = norm1.split(/\s+/).filter((w) => w.length > 0);
const words2 = norm2.split(/\s+/).filter((w) => w.length > 0);
if (words1.length === 0 || words2.length === 0)
return 0;
const set1 = new Set(words1);
const set2 = new Set(words2);
const intersection = words1.filter((w) => set2.has(w));
const union = /* @__PURE__ */ new Set([...words1, ...words2]);
const jaccard = intersection.length / union.size;
const extraWordsCount = words2.filter((w) => !set1.has(w)).length;
let score = jaccard - extraWordsCount * 0.05;
if (words1.length > 0 && words1.every((w) => set2.has(w))) {
score += 0.2;
}
return score;
}
function findBestTitleMatch(mediaInfo, searchResults, mediaType, season) {
if (!searchResults || searchResults.length === 0)
return null;
let bestMatch = null;
let bestScore = 0;
for (const result of searchResults) {
let score = calculateTitleSimilarity(mediaInfo.title, result.title);
if (mediaInfo.year && result.year) {
const yearDiff = Math.abs(mediaInfo.year - result.year);
if (yearDiff === 0)
score += 0.2;
else if (yearDiff <= 1)
score += 0.1;
else if (yearDiff > 5)
score -= 0.3;
}
if (mediaType === "tv" && season) {
const titleLower = result.title.toLowerCase();
const seasonPatterns = [
`season ${season}`,
`s${season}`,
`season ${season.toString().padStart(2, "0")}`,
`s${season.toString().padStart(2, "0")}`
];
const hasSeason = seasonPatterns.some((p) => titleLower.includes(p));
const otherSeasonMatch = titleLower.match(/season\s*(\d+)|s(\d+)/i);
if (otherSeasonMatch) {
const foundSeason = parseInt(otherSeasonMatch[1] || otherSeasonMatch[2]);
if (foundSeason !== season) {
score -= 0.8;
}
}
if (hasSeason)
score += 0.5;
else
score -= 0.3;
}
if (result.title.toLowerCase().includes("2160p") || result.title.toLowerCase().includes("4k")) {
score += 0.05;
}
if (score > bestScore && score > 0.3) {
bestScore = score;
bestMatch = result;
}
}
if (bestMatch)
console.log(`[HDHub4u] Best title match: "${bestMatch.title}" (score: ${bestScore.toFixed(2)})`);
return bestMatch;
}
function getTMDBDetails(tmdbId, mediaType) {
return __async(this, null, function* () {
var _a;
const endpoint = mediaType === "tv" ? "tv" : "movie";
const url = `${TMDB_BASE_URL}/${endpoint}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`;
const response = yield fetch(url, {
method: "GET",
headers: { "Accept": "application/json", "User-Agent": "Mozilla/5.0" }
});
if (!response.ok)
throw new Error(`TMDB API error: ${response.status}`);
const data = yield response.json();
const title = mediaType === "tv" ? data.name : data.title;
const releaseDate = mediaType === "tv" ? data.first_air_date : data.release_date;
const year = releaseDate ? parseInt(releaseDate.split("-")[0]) : null;
return { title, year, imdbId: ((_a = data.external_ids) == null ? void 0 : _a.imdb_id) || null };
});
}
// src/hdhub4u/extractors.js
var import_cheerio_without_node_native = __toESM(require("cheerio-without-node-native"));
var import_crypto_js = __toESM(require("crypto-js"));
function getRedirectLinks(url) {
return __async(this, null, function* () {
try {
const response = yield fetch(url, { headers: HEADERS });
if (!response.ok)
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
const doc = yield response.text();
const regex = /s\s*\(\s*['"]o['"]\s*,\s*['"]([A-Za-z0-9+/=]+)['"]|ck\s*\(\s*['"]_wp_http_\d+['"]\s*,\s*['"]([^'"]+)['"]/g;
let combinedString = "";
let match;
while ((match = regex.exec(doc)) !== null) {
const extractedValue = match[1] || match[2];
if (extractedValue)
combinedString += extractedValue;
}
if (!combinedString) {
const redirectMatch = doc.match(/window\.location\.href\s*=\s*['"]([^'"]+)['"]/);
if (redirectMatch && redirectMatch[1]) {
const newUrl = redirectMatch[1];
if (newUrl !== url && !newUrl.includes(url)) {
return yield getRedirectLinks(newUrl);
}
}
return null;
}
const decodedString = atob(rot13(atob(atob(combinedString))));
const jsonObject = JSON.parse(decodedString);
const encodedUrl = atob(jsonObject.o || "").trim();
if (encodedUrl)
return encodedUrl;
const data = atob(jsonObject.data || "").trim();
const wpHttp = (jsonObject.blog_url || "").trim();
if (wpHttp && data) {
const directLinkResponse = yield fetch(`${wpHttp}?re=${data}`, { headers: HEADERS });
const html = yield directLinkResponse.text();
const $ = import_cheerio_without_node_native.default.load(html);
return ($("body").text() || html).trim();
}
return null;
} catch (e) {
return null;
}
});
}
function vidStackExtractor(url) {
return __async(this, null, function* () {
var _a, _b, _c;
try {
const hash = url.split("#").pop().split("/").pop();
const baseUrl = new URL(url).origin;
const apiUrl = `${baseUrl}/api/v1/video?id=${hash}`;
const response = yield fetch(apiUrl, { headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: url }) });
const encoded = (yield response.text()).trim();
const key = import_crypto_js.default.enc.Utf8.parse("kiemtienmua911ca");
const ivs = ["1234567890oiuytr", "0123456789abcdef"];
for (const ivStr of ivs) {
try {
const iv = import_crypto_js.default.enc.Utf8.parse(ivStr);
const decrypted = import_crypto_js.default.AES.decrypt(
{ ciphertext: import_crypto_js.default.enc.Hex.parse(encoded) },
key,
{ iv, mode: import_crypto_js.default.mode.CBC, padding: import_crypto_js.default.pad.Pkcs7 }
);
const decryptedText = decrypted.toString(import_crypto_js.default.enc.Utf8);
if (decryptedText && decryptedText.includes("source")) {
const m3u8 = (_b = (_a = decryptedText.match(/"source":"(.*?)"/)) == null ? void 0 : _a[1]) == null ? void 0 : _b.replace(/\\/g, "");
const subtitles = [];
const subtitleSection = (_c = decryptedText.match(/"subtitle":\{(.*?)\}/)) == null ? void 0 : _c[1];
if (subtitleSection) {
const subtitlePattern = /"([^"]+)":\s*"([^"]+)"/g;
let subMatch;
while ((subMatch = subtitlePattern.exec(subtitleSection)) !== null) {
const lang = subMatch[1];
const subPath = subMatch[2].split("#")[0].replace(/\\/g, "");
if (subPath) {
subtitles.push({
language: lang,
url: subPath.startsWith("http") ? subPath : `${baseUrl}${subPath}`
});
}
}
}
if (m3u8) {
return [{
source: "Vidstack Hubstream",
quality: "M3U8",
url: m3u8.replace("https:", "http:"),
headers: {
"Referer": url,
"Origin": url.split("/").pop()
},
subtitles
}];
}
}
} catch (e) {
}
}
return [];
} catch (e) {
return [];
}
});
}
function hbLinksExtractor(url) {
return __async(this, null, function* () {
try {
const response = yield fetch(url, { headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: url }) });
const data = yield response.text();
const $ = import_cheerio_without_node_native.default.load(data);
const links = [...new Set($("h3 a, h5 a, div.entry-content p a, div.entry-content a").map((i, el) => $(el).attr("href")).get().filter(Boolean))];
const results = yield Promise.all(links.map((l) => loadExtractor(l, url)));
return results.flat().map((link) => __spreadProps(__spreadValues({}, link), {
source: `${link.source} Hblinks`
}));
} catch (e) {
return [];
}
});
}
function pixelDrainExtractor(link) {
return __async(this, null, function* () {
var _a;
try {
const urlObj = new URL(link);
const baseUrl = `${urlObj.protocol}//${urlObj.hostname}`;
const fileId = ((_a = link.match(/(?:file|u)\/([A-Za-z0-9]+)/)) == null ? void 0 : _a[1]) || link.split("/").pop();
if (!fileId)
return [{ source: "Pixeldrain", quality: 0, url: link }];
const finalUrl = link.includes("?download") ? link : `${baseUrl}/api/file/${fileId}?download`;
return [{ source: "Pixeldrain", quality: 0, url: finalUrl }];
} catch (e) {
return [{ source: "Pixeldrain", quality: 0, url: link }];
}
});
}
function streamTapeExtractor(link) {
return __async(this, null, function* () {
var _a, _b, _c, _d;
try {
const url = new URL(link);
url.hostname = "streamtape.com";
const res = yield fetch(url.toString(), { headers: HEADERS });
const data = yield res.text();
let videoSrc = (_c = (_b = (_a = data.match(/document\.getElementById\('videolink'\)\.innerHTML = (.*?);/)) == null ? void 0 : _a[1]) == null ? void 0 : _b.match(/'(\/\/streamtape\.com\/get_video[^']+)'/)) == null ? void 0 : _c[1];
if (!videoSrc) {
videoSrc = (_d = data.match(/'(\/\/streamtape\.com\/get_video[^']+)'/)) == null ? void 0 : _d[1];
}
return videoSrc ? [{ source: "StreamTape", quality: 720, url: "https:" + videoSrc }] : [];
} catch (e) {
return [];
}
});
}
function hubCloudExtractor(url, referer) {
return __async(this, null, function* () {
var _a;
try {
let currentUrl = url.replace("hubcloud.ink", "hubcloud.dad");
const pageResponse = yield fetch(currentUrl, { headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: referer }) });
let pageData = yield pageResponse.text();
let finalUrl = currentUrl;
if (!currentUrl.includes("hubcloud.php")) {
let nextHref = "";
const $first = import_cheerio_without_node_native.default.load(pageData);
const downloadBtn = $first("#download");
if (downloadBtn.length) {
nextHref = downloadBtn.attr("href");
} else {
const scriptUrlMatch = pageData.match(/var url = '([^']*)'/);
if (scriptUrlMatch)
nextHref = scriptUrlMatch[1];
}
if (nextHref) {
if (!nextHref.startsWith("http")) {
const urlObj = new URL(currentUrl);
nextHref = `${urlObj.protocol}//${urlObj.hostname}/${nextHref.replace(/^\//, "")}`;
}
finalUrl = nextHref;
const secondResponse = yield fetch(finalUrl, { headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: currentUrl }) });
pageData = yield secondResponse.text();
}
}
const $ = import_cheerio_without_node_native.default.load(pageData);
const size = $("i#size").text().trim();
const header = $("div.card-header").text().trim();
const qualityStr = (_a = header.match(/(\d{3,4})[pP]/)) == null ? void 0 : _a[1];
const quality = qualityStr ? parseInt(qualityStr) : 1080;
const headerDetails = cleanTitle(header);
const labelExtras = (headerDetails ? `[${headerDetails}]` : "") + (size ? `[${size}]` : "");
const sizeInBytes = (() => {
const sizeMatch = size.match(/([\d.]+)\s*(GB|MB|KB)/i);
if (!sizeMatch)
return 0;
const multipliers = { GB: 1024 ** 3, MB: 1024 ** 2, KB: 1024 };
return parseFloat(sizeMatch[1]) * (multipliers[sizeMatch[2].toUpperCase()] || 0);
})();
const links = [];
const elements = $("a.btn").get();
for (const element of elements) {
const link = $(element).attr("href");
const text = $(element).text().toLowerCase();
const fileName = header || headerDetails || "Unknown";
if (text.includes("download file") || text.includes("fsl server") || text.includes("s3 server") || text.includes("fslv2") || text.includes("mega server") || link && link.includes("r2.dev")) {
let label = "HubCloud";
if (link && link.includes("r2.dev"))
label = "Direct R2";
else if (link && link.includes("workers.dev"))
label = "ZipDisk Server";
else if (text.includes("fsl server"))
label = "HubCloud - FSL";
else if (text.includes("s3 server"))
label = "HubCloud - S3";
else if (text.includes("fslv2"))
label = "HubCloud - FSLv2";
else if (text.includes("mega server"))
label = "HubCloud - Mega";
links.push({ source: `${label} ${labelExtras}`, quality, url: link, size: sizeInBytes, fileName });
} else if (text.includes("buzzserver")) {
try {
const buzzResp = yield fetch(`${link}/download`, { method: "GET", headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: link }), redirect: "manual" });
let dlink = buzzResp.headers.get("hx-redirect") || buzzResp.headers.get("HX-Redirect");
if (!dlink && buzzResp.url && buzzResp.url !== `${link}/download`) {
dlink = buzzResp.url;
}
if (dlink) {
links.push({ source: `HubCloud - BuzzServer ${labelExtras}`, quality, url: dlink, size: sizeInBytes, fileName });
}
} catch (e) {
}
} else if (text.includes("10gbps") || link && link.includes("hubcloud.cx")) {
let targetUrl = link;
if (link && !link.includes("hubcloud.cx")) {
try {
const resp = yield fetch(link, { method: "GET", redirect: "manual" });
const loc = resp.headers.get("location");
if (loc && loc.includes("link=")) {
targetUrl = loc.substring(loc.indexOf("link=") + 5);
}
} catch (e) {
}
}
links.push({ source: `HubCloud - 10Gbps ${labelExtras}`, quality, url: targetUrl, size: sizeInBytes, fileName });
} else if (text.includes("zipdisk") || link && link.includes("workers.dev")) {
links.push({ source: `ZipDisk Server ${labelExtras}`, quality, url: link, size: sizeInBytes, fileName });
} else if (link && link.includes("pixeldra")) {
const results = yield pixelDrainExtractor(link);
links.push(...results.map((l) => __spreadProps(__spreadValues({}, l), { source: `${l.source} ${labelExtras}`, size: sizeInBytes, fileName })));
} else if (link && !link.includes("magnet:") && link.startsWith("http")) {
const extracted = yield loadExtractor(link, finalUrl);
links.push(...extracted.map((l) => __spreadProps(__spreadValues({}, l), { quality: l.quality || quality })));
}
}
return links;
} catch (e) {
return [];
}
});
}
function hubCdnExtractor(url, referer) {
return __async(this, null, function* () {
try {
const response = yield fetch(url, { headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: referer }) });
const data = yield response.text();
const $ = import_cheerio_without_node_native.default.load(data);
let scriptContent = "";
$("script").each((i, el) => {
const html = $(el).html();
if (html && html.includes("reurl")) {
scriptContent = html;
}
});
if (scriptContent) {
const match = scriptContent.match(/reurl\s*=\s*["']([^"']+)["']/);
if (match && match[1]) {
const reurlVal = match[1];
if (reurlVal.includes("?r=")) {
const queryPart = reurlVal.split("?r=").pop();
try {
const decoded = atob(queryPart);
const m3u8Link = decoded.substring(decoded.lastIndexOf("link=") + 5);
if (m3u8Link && m3u8Link.startsWith("http")) {
return [{ source: "HubCdn", quality: 1080, url: m3u8Link }];
}
} catch (e) {
}
} else if (reurlVal.includes("link=")) {
const m3u8Link = reurlVal.split("link=").pop();
if (m3u8Link && m3u8Link.startsWith("http")) {
return [{ source: "HubCdn", quality: 1080, url: m3u8Link }];
}
} else if (reurlVal.startsWith("http")) {
return [{ source: "HubCdn", quality: 1080, url: reurlVal }];
}
}
}
const encodedMatch = data.match(/r=([A-Za-z0-9+/=]+)/);
if (encodedMatch && encodedMatch[1]) {
try {
const decoded = atob(encodedMatch[1]);
const m3u8Link = decoded.substring(decoded.lastIndexOf("link=") + 5);
if (m3u8Link && m3u8Link.startsWith("http")) {
return [{ source: "HubCdn", quality: 1080, url: m3u8Link }];
}
} catch (e) {
}
}
return [];
} catch (e) {
return [];
}
});
}
function loadExtractor(_0) {
return __async(this, arguments, function* (url, referer = MAIN_URL) {
try {
const hostname = new URL(url).hostname;
const isRedirect = url.includes("?id=") || hostname.includes("techyboy4u") || hostname.includes("gadgetsweb.xyz") || hostname.includes("cryptoinsights.site") || hostname.includes("bloggingvector") || hostname.includes("ampproject.org");
if (isRedirect) {
const finalLink = yield getRedirectLinks(url);
if (finalLink && finalLink !== url)
return yield loadExtractor(finalLink, url);
return [];
}
if (hostname.includes("hubcloud"))
return yield hubCloudExtractor(url, referer);
if (hostname.includes("hubcdn"))
return yield hubCdnExtractor(url, referer);
if (hostname.includes("hblinks") || hostname.includes("hubstream.dad"))
return yield hbLinksExtractor(url);
if (hostname.includes("hubstream") || hostname.includes("vidstack"))
return yield vidStackExtractor(url);
if (hostname.includes("pixeldrain"))
return yield pixelDrainExtractor(url);
if (hostname.includes("streamtape"))
return yield streamTapeExtractor(url);
if (hostname.includes("hdstream4u"))
return [{ source: "HdStream4u", quality: 1080, url }];
if (hostname.includes("hubdrive")) {
const res = yield fetch(url, { headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: referer }) });
const data = yield res.text();
const href = import_cheerio_without_node_native.default.load(data)(".btn.btn-primary.btn-user.btn-success1.m-1").attr("href");
if (href)
return yield loadExtractor(href, url);
}
return [];
} catch (e) {
return [];
}
});
}
// src/hdhub4u/index.js
function search(query) {
return __async(this, null, function* () {
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
const searchUrl = `https://search.hdhub4u.glass/collections/post/documents/search?q=${encodeURIComponent(query)}&query_by=post_title,category&query_by_weights=4,2&sort_by=sort_by_date:desc&limit=15&highlight_fields=none&use_cache=true&page=1&analytics_tag=${today}`;
const response = yield fetch(searchUrl, { headers: HEADERS });
const data = yield response.json();
if (!data || !data.hits)
return [];
return data.hits.map((hit) => {
const doc = hit.document;
const title = doc.post_title;
const yearMatch = title.match(/\((\d{4})\)|\b(\d{4})\b/);
const year = yearMatch ? parseInt(yearMatch[1] || yearMatch[2]) : null;
let url = doc.permalink;
if (url && url.startsWith("/")) {
url = `${MAIN_URL}${url}`;
}
return {
title,
url,
poster: doc.post_thumbnail,
year
};
});
});
}
function getDownloadLinks(mediaUrl) {
return __async(this, null, function* () {
const domain = yield getCurrentDomain();
if (mediaUrl.includes("hdhub4u.")) {
try {
const urlObj = new URL(mediaUrl);
const domainObj = new URL(domain);
urlObj.hostname = domainObj.hostname;
mediaUrl = urlObj.toString();
} catch (e) {
}
}
const response = yield fetch(mediaUrl, { headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: `${domain}/` }) });
const data = yield response.text();
const $ = import_cheerio_without_node_native2.default.load(data);
const typeRaw = $("h1.page-title span").text();
const isMovie = typeRaw.toLowerCase().includes("movie");
if (isMovie) {
const qualityLinks = $("h3 a, h4 a").filter((i, el) => $(el).text().match(/480|720|1080|2160|4K/i));
const bodyLinks = $(".page-body > div a").filter((i, el) => {
const href = $(el).attr("href");
return href && (href.includes("hdstream4u") || href.includes("hubstream"));
});
const initialLinks = [.../* @__PURE__ */ new Set([
...qualityLinks.map((i, el) => $(el).attr("href")).get(),
...bodyLinks.map((i, el) => $(el).attr("href")).get()
])];
const results = yield Promise.all(initialLinks.map((url) => loadExtractor(url, mediaUrl)));
const allFinalLinks = results.flat();
const seenUrls = /* @__PURE__ */ new Set();
const uniqueFinalLinks = allFinalLinks.filter((link) => {
var _a;
if (!link.url || link.url.includes(".zip") || ((_a = link.name) == null ? void 0 : _a.toLowerCase().includes(".zip")))
return false;
if (seenUrls.has(link.url))
return false;
seenUrls.add(link.url);
return true;
});
return { finalLinks: uniqueFinalLinks, isMovie };
} else {
const episodeLinksMap = /* @__PURE__ */ new Map();
const directLinkBlocks = [];
$("h3, h4").each((i, element) => {
const $el = $(element);
const text = $el.text();
const anchors = $el.find("a");
const links = anchors.map((i2, a) => $(a).attr("href")).get();
const isDirectLinkBlock = anchors.get().some((a) => $(a).text().match(/1080|720|4K|2160/i));
if (isDirectLinkBlock) {
directLinkBlocks.push(...links);
return;
}
const episodeMatch = text.match(/(?:EPiSODE\s*(\d+)|E(\d+))/i);
if (episodeMatch) {
const epNum = parseInt(episodeMatch[1] || episodeMatch[2]);
if (!episodeLinksMap.has(epNum))
episodeLinksMap.set(epNum, []);
episodeLinksMap.get(epNum).push(...links);
let nextElement = $el.next();
while (nextElement.length && nextElement.get(0).tagName !== "hr") {
const siblingLinks = nextElement.find("a[href]").map((i2, a) => $(a).attr("href")).get();
episodeLinksMap.get(epNum).push(...siblingLinks);
nextElement = nextElement.next();
}
}
});
if (directLinkBlocks.length > 0) {
yield Promise.all(directLinkBlocks.map((blockUrl) => __async(this, null, function* () {
try {
const resolvedUrl = yield getRedirectLinks(blockUrl);
if (!resolvedUrl)
return;
const blockRes = yield fetch(resolvedUrl, { headers: HEADERS });
const blockData = yield blockRes.text();
const $$ = import_cheerio_without_node_native2.default.load(blockData);
$$("h5 a, h4 a, h3 a").each((i, el) => {
const linkText = $$(el).text();
const linkHref = $$(el).attr("href");
const epMatch = linkText.match(/Episode\s*(\d+)/i);
if (epMatch && linkHref) {
const epNum = parseInt(epMatch[1]);
if (!episodeLinksMap.has(epNum))
episodeLinksMap.set(epNum, []);
episodeLinksMap.get(epNum).push(linkHref);
}
});
} catch (e) {
}
})));
}
const initialLinks = [];
episodeLinksMap.forEach((links, epNum) => {
const uniqueLinks = [...new Set(links)];
initialLinks.push(...uniqueLinks.map((link) => ({ url: link, episode: epNum })));
});
const results = yield Promise.all(initialLinks.map((linkInfo) => __async(this, null, function* () {
try {
const extracted = yield loadExtractor(linkInfo.url, mediaUrl);
return extracted.map((ext) => __spreadProps(__spreadValues({}, ext), { episode: linkInfo.episode }));
} catch (e) {
return [];
}
})));
const allFinalLinks = results.flat();
const seenUrls = /* @__PURE__ */ new Set();
const uniqueFinalLinks = allFinalLinks.filter((link) => {
if (!link.url || link.url.includes(".zip"))
return false;
if (seenUrls.has(link.url))
return false;
seenUrls.add(link.url);
return true;
});
return { finalLinks: uniqueFinalLinks, isMovie };
}
});
}
function getStreams(tmdbId, mediaType = "movie", season = null, episode = null) {
return __async(this, null, function* () {
console.log(`[HDHub4u] Fetching streams for TMDB ID: ${tmdbId}, Type: ${mediaType}`);
try {
const mediaInfo = yield getTMDBDetails(tmdbId, mediaType);
console.log(`[HDHub4u] TMDB Info: "${mediaInfo.title}" (${mediaInfo.year || "N/A"})`);
const searchQuery = mediaType === "tv" && season ? `${mediaInfo.title} Season ${season}` : mediaInfo.title;
const searchResults = yield search(searchQuery);
if (searchResults.length === 0)
return [];
const bestMatch = findBestTitleMatch(mediaInfo, searchResults, mediaType, season);
const selectedMedia = bestMatch || searchResults[0];
console.log(`[HDHub4u] Selected: "${selectedMedia.title}" (${selectedMedia.url})`);
const result = yield getDownloadLinks(selectedMedia.url);
const finalLinks = result.finalLinks;
let filteredLinks = finalLinks;
if (mediaType === "tv" && episode !== null) {
filteredLinks = finalLinks.filter((link) => link.episode === episode);
}
const streams = filteredLinks.map((link) => {
let mediaTitle = link.fileName && link.fileName !== "Unknown" ? link.fileName : mediaInfo.title;
if (mediaType === "tv" && season && episode) {
mediaTitle = `${mediaInfo.title} S${String(season).padStart(2, "0")}E${String(episode).padStart(2, "0")}`;
}
const serverName = extractServerName(link.source);
let qualityStr = "Unknown";
if (typeof link.quality === "number" && link.quality > 0) {
if (link.quality >= 2160)
qualityStr = "4K";
else if (link.quality >= 1080)
qualityStr = "1080p";
else if (link.quality >= 720)
qualityStr = "720p";
else if (link.quality >= 480)
qualityStr = "480p";
} else if (typeof link.quality === "string") {
qualityStr = link.quality;
}
return {
name: `HDHub4u ${serverName}`,
title: mediaTitle,
url: link.url,
quality: qualityStr,
size: formatBytes(link.size),
headers: link.headers || void 0,
provider: "hdhub4u"
};
});
const qualityOrder = { "4K": 4, "1080p": 2, "720p": 1, "480p": 0, "Unknown": -2 };
return streams.sort((a, b) => (qualityOrder[b.quality] || -3) - (qualityOrder[a.quality] || -3));
} catch (error) {
console.error(`[HDHub4u] Scraping error: ${error.message}`);
return [];
}
});
}
module.exports = { getStreams };
+983
View File
@@ -0,0 +1,983 @@
{
"name": "All-in-One-Nuvio",
"version": "1.0.0",
"scrapers": [
{
"id": "allanime",
"name": "AllAnime",
"description": "AllAnime - Anime and Manga content streaming",
"version": "1.0.0",
"author": "",
"supportedTypes": ["movie", "tv"],
"filename": "providers/allanime.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/DwpqLJWV/allanime.png",
"contentLanguage": ["en", "ja"]
},
{
"id": "4khdhub",
"name": "4KHDHub",
"description": "4KHDHub direct links",
"version": "1.0.3",
"author": "Nuvio Team",
"supportedTypes": [
"movie",
"tv"
],
"filename": "providers/4khdhub.js",
"enabled": true,
"formats": [
"mkv"
],
"logo": "https://www.google.com/s2/favicons?domain=4khdhub.click&sz=128",
"contentLanguage": [
"en"
]
},
{
"id": "1shows",
"name": "1Shows",
"description": "1Shows- Movies | Series in 4k, 1080p, 720p & 480p",
"version": "1.0.0",
"author": "A2R14N - Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/1shows.js",
"enabled": true,
"hasSettings": false,
"formats": ["mkv", "mp4", "m3u8"],
"logo": "https://i.postimg.cc/9fDVBvn5/1shows.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "allwish",
"name": "🌟 All-Wish",
"description": "All-Wish TV episodes via All-Wish servers",
"version": "1.0.1",
"author": "Kabir",
"supportedTypes": ["movie", "tv"],
"filename": "providers/allwish.js",
"enabled": true,
"hasSettings": true,
"limited": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/WpFW45WQ/allwish.png",
"contentLanguage": ["en", "ja"]
},
{
"id": "animekai",
"name": "AnimeKai",
"description": "AnimeKai TV episodes via AnimeKai servers",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/animekai.js",
"enabled": true,
"hasSettings": true,
"limited": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/MKJd7fy7/animekai.png",
"contentLanguage": ["en"]
},
{
"id": "anizone",
"name": "AniZone",
"description": "AniZone high-quality anime streaming with multi-audio and soft subtitles",
"version": "1.0.2",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/anizone.js",
"enabled": true,
"formats": ["m3u8"],
"logo": "https://anizone.to/favicon.ico",
"contentLanguage": ["en", "ja"]
},
{
"id": "anikototv",
"name": "AnikotoTV",
"description": "Anime provider for AnikotoTV.to via Mapper API + Native Extractor",
"version": "1.0.5",
"author": "piratezoro9",
"supportedTypes": ["movie", "tv", "anime"],
"filename": "providers/anikototv.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4"],
"logo": "https://i.postimg.cc/JhL3HBR4/anikototv.png",
"contentLanguage": ["en", "ja"]
},
{
"id": "anidb",
"name": "AniDB",
"description": "Subbed and dubbed anime from AniDB.",
"version": "1.0.0",
"author": "Nuvio Team (ChillPill)",
"supportedTypes": ["movie", "tv"],
"filename": "providers/anidb.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/rmMzZ45K/anidb.png",
"contentLanguage": ["en", "ja", "ko"]
},
{
"id": "animepahe",
"name": "AnimePahe",
"description": "Watch anime online free in HD with fast streaming servers. Stream latest anime episodes and movies daily",
"version": "1.0.1",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/animepahe.js",
"enabled": true,
"hasSettings": true,
"formats": ["m3u8", "mp4"],
"logo": "https://i.postimg.cc/c4ZBGNNs/animepahe.png",
"contentLanguage": ["en", "ja"]
},
{
"id": "animesalt",
"name": "AnimeSalt",
"description": "AnimeSalt anime streaming with multi-language audio (Hindi, Tamil, Telugu, English) and high-quality direct HLS streams",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/animesalt.js",
"enabled": true,
"formats": ["m3u8", "mp4"],
"logo": "https://www.google.com/s2/favicons?domain=animesalt.cx&sz=128",
"contentLanguage": ["hi", "ta", "te", "en", "ja"]
},
{
"id": "animedekho",
"name": "AnimeDekho",
"description": "AnimeDekho streaming anime series and movies with Hindi dub, multi-audio and high-speed multi-server support",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/animedekho.js",
"enabled": true,
"formats": ["m3u8", "mp4"],
"logo": "https://www.google.com/s2/favicons?domain=animedekho.app&sz=128",
"contentLanguage": ["hi", "en", "ja"]
},
{
"id": "animetsu",
"name": "Animetsu",
"description": "Lightning fast sub & dub anime streams via Animetsu",
"version": "1.0.0",
"author": "piratezoro9",
"supportedTypes": ["movie", "tv", "anime"],
"filename": "providers/animetsu.js",
"enabled": true,
"hasSettings": true,
"formats": ["m3u8"],
"logo": "https://i.postimg.cc/0Q3DvLx7/animetsu.png",
"contentLanguage": ["en", "ja"]
},
{
"id": "animeworld",
"name": "🗡️ AnimeWorld",
"description": "Watch AnimeWorld India",
"version": "1.0.0",
"author": "piratezoro9",
"supportedTypes": ["movie", "tv"],
"filename": "providers/animeworld.js",
"enabled": true,
"hasSettings": true,
"formats": ["m3u8"],
"logo": "https://i.postimg.cc/wxD6rVKX/animeworld.png",
"contentLanguage": ["hi", "en", "ja"]
},
{
"id": "anime-sama",
"name": "🐍 Anime-Sama",
"description": "Watch AnimeSama France",
"version": "1.1.27",
"author": "Gowaru",
"supportedTypes": ["movie", "tv"],
"filename": "providers/anime-sama.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv"],
"logo": "https://i.postimg.cc/tgYt2pYG/animesama.png",
"contentLanguage": ["fr"]
},
{
"id": "allmovieland",
"name": "AllMovieLand",
"description": "AllMovieLand streaming provider with multi-language support",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/allmovieland.js",
"enabled": true,
"hasSettings": true,
"formats": ["m3u8"],
"logo": "https://i.postimg.cc/hhWqkVQs/allmovieland.png",
"contentLanguage": ["en", "hi", "ta", "te"]
},
{
"id": "animezey",
"name": "AnimeZeY",
"description": "Movies via AnimeZeY, indexed by TMDB",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/animezey.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/RVTy2djk/ainimezey.png",
"contentLanguage": ["en", "pt"]
},
{
"id": "desiflix",
"name": "DesiFlix",
"description": "Bollywood, Hollywood, and South Indian movies, in Dual Language",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/desiflix.js",
"enabled": true,
"hasSettings": false,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/Vvs4fmwM/desiflix.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "castle",
"name": "🏰 Castle",
"description": "Multi Lang provider",
"version": "2.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/castle.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/0NvGzFyK/castle.png",
"contentLanguage": ["en"]
},
{
"id": "Cineby",
"name": "Cineby",
"description": "Multi-server movie and TV streaming — 4K/1080p/720p from Videasy network without subtitles",
"version": "1.9.2",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/cineby.js",
"enabled": true,
"hasSettings": true,
"formats": ["m3u8"],
"logo": "https://i.postimg.cc/dV1HWbqX/cineby.png",
"contentLanguage": ["ar", "en"]
},
{
"id": "cinefreak",
"name": "CineFreak",
"description": "Direct MKV streams from cinefreak.nl",
"version": "1.0.0",
"author": "piratezoro9",
"supportedTypes": ["movie", "tv"],
"filename": "providers/cinefreak.js",
"enabled": true,
"hasSettings": true,
"formats": ["mkv", "mp4"],
"logo": "https://i.postimg.cc/rpDB2284/cinefreak.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "moonflix",
"name": "MoonFlix",
"description": "Bollywood, Hollywood, South Indian Movies & Series",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/moonflix.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv"],
"logo": "https://i.postimg.cc/90dVRJJq/moonflix.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "cinemacity",
"name": "CinemaCity",
"description": "Multi Language Provider",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/cinemacity.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/XYjKhS3b/cinemacity.png",
"contentLanguage": ["en", "hi", "ar"]
},
{
"id": "ctgmovies",
"name": "CTGMovies",
"description": "English | Hindi Movies",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/ctgmovies.js",
"enabled": true,
"hasSettings": true,
"formats": ["m3u8", "mp4", "mkv"],
"logo": "https://i.postimg.cc/jSQmk9B3/ctgmovies.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "dahmermovies",
"name": "Dahmermovies",
"description": "1080p Movies from Dahmermovies",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/dahmermovies.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/hGt3dV6Z/dhamermovies.png",
"contentLanguage": ["en"]
},
{
"id": "dahmermovies-tv",
"name": "Dahmermovies-TV",
"description": "Only works on Android TV",
"version": "1.0.1",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/dahmermovies-4k.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/hGt3dV6Z/dhamermovies.png",
"contentLanguage": ["en"]
},
{
"id": "dooflix",
"name": "DooFlix",
"description": "Fast streaming provider with direct TMDB integration",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/dooflix.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/59H1DmRk/dooflix.png",
"contentLanguage": ["en", "es"]
},
{
"id": "einthusan",
"name": "Einthustan",
"description": "1080p Movies in Multi-Lang",
"version": "1.0.0",
"author": "✮☆[D3ADLY]☆✮",
"supportedTypes": ["movie", "tv"],
"filename": "providers/einthusan.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/QCFYLyRR/einthusan.png",
"contentLanguage": ["hi", "ta", "te", "ba"]
},
{
"id": "fibwatch",
"name": "FibWatch",
"description": "FibWatch movie and TV streams with episode selection",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": [
"movie",
"tv"
],
"filename": "providers/fibwatch.js",
"enabled": true,
"formats": [
"m3u8",
"mp4",
"mkv"
],
"contentLanguage": [
"hi",
"bn",
"en"
]
},
{
"id": "goated",
"name": "🐐 Goated",
"description": "4K • 1080p Movies & Series in Multi Language",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/goated.js",
"enabled": true,
"hasSettings": true,
"formats": ["mkv", "mp4", "m3u8"],
"logo": "https://i.postimg.cc/qqsfgS0F/goated.png",
"contentLanguage": ["en", "hi", "ru", "es"]
},
{
"id": "gramcinema",
"name": "GramCinema",
"description": "Streams in Multi Lang from Bollywood.eu.org. Requires Cookie Token.",
"version": "1.0.0",
"author": "Xyr0nX • =[D3adly]=",
"supportedTypes": ["movie", "tv"],
"filename": "providers/gramcinema.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/WbNPW7Jv/gramcinema.png",
"contentLanguage": ["en", "hi", "ta", "ru"]
},
{
"id": "hdghartv",
"name": "HDGharTV",
"description": "HDGhar TV allows users to watch movies, TV shows and web series in English & Hindi.",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/hdghartv.js",
"enabled": true,
"hasSettings": false,
"formats": ["m3u8"],
"logo": "https://i.postimg.cc/761WVpJS/hdghartv.png",
"contentLanguage": ["en", "hi"],
"limited": false
},
{
"id": "hdhub4u",
"name": "HDHub4u",
"description": "Direct links from HDHub4u with high-speed download support",
"version": "1.1.1",
"author": "Nuvio Team",
"supportedTypes": [
"movie",
"tv"
],
"filename": "providers/hdhub4u.js",
"enabled": true,
"formats": [
"mkv",
"mp4"
],
"logo": "https://www.google.com/s2/favicons?domain=new6.hdhub4u.fo&sz=128",
"contentLanguage": [
"en",
"hin"
]
},
{
"id": "hianime",
"name": "HiAnime",
"description": "HiAnime multi-server anime streaming with real-time mapping and subtitles",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/hianime.js",
"enabled": true,
"hasSettings": true,
"formats": ["m3u8"],
"logo": "https://i.postimg.cc/13SYJPTx/hianime.png",
"contentLanguage": ["ja", "en"]
},
{
"id": "hindmoviez",
"name": "HindMoviez",
"description": "HindMoviez - Hindi & English Movies and Series (480p / 720p / 1080p / 4K)",
"version": "1.0.1",
"author": "Sanchit (@S4NCHITT) — Murph's Streams",
"supportedTypes": ["movie", "tv"],
"filename": "providers/hindmoviez.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/5t55Csm4/hindmoviez.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "kurage",
"name": "Kurage",
"description": "Kurage.live anime streaming with tRPC API and multi-server proxy support",
"version": "1.0.0",
"author": "Paregi12",
"supportedTypes": ["movie", "tv"],
"filename": "providers/kurage.js",
"enabled": true,
"hasSettings": true,
"resources": ["stream"],
"formats": ["mkv", "m3u8"],
"logo": "https://i.postimg.cc/3N2V7pHc/kurage.png",
"contentLanguage": ["en", "ja"]
},
{
"id": "moviebox",
"name": "MovieBox",
"description": "MovieBox streaming with multiple language support (DASH + MP4)",
"version": "1.2.3",
"author": "Nuvio Team",
"supportedTypes": [
"movie",
"tv"
],
"filename": "providers/moviebox.js",
"enabled": true,
"formats": [
"mp4",
"mpd"
],
"logo": "https://moviebox.ph/favicon.ico",
"contentLanguage": [
"en",
"hin",
"tam",
"tel"
]
},
{
"id": "movieblast",
"name": "MovieBlast",
"description": "MovieBlast - Hindi, Tamil, Telugu & English Movies/Series with multi-quality streams",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/movieblast.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/qqkLSyhN/movieblast.png",
"contentLanguage": ["en", "hi", "ta", "te"]
},
{
"id": "moviesdrive",
"name": "MoviesDrive",
"description": "MoviesDrive streaming with HubCloud and Google Drive extraction",
"version": "3.0.1",
"author": "Nuvio Team",
"supportedTypes": [
"movie",
"tv"
],
"filename": "providers/moviesdrive.js",
"enabled": true,
"formats": [
"mkv",
"mp4"
],
"logo": "https://www.google.com/s2/favicons?domain=moviesdrives.my&sz=128",
"contentLanguage": [
"en",
"hin"
]
},
{
"id": "moviesmod",
"name": "MoviesMod",
"description": "Movie and TV show streams from MoviesMod with multiple quality options",
"version": "1.0.1",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/moviesmod.js",
"enabled": true,
"hasSettings": false,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://www.google.com/s2/favicons?domain=moviesmod.farm&sz=128",
"contentLanguage": ["en"]
},
{
"id": "movieshunt",
"name": "🎬 MoviesHunt",
"description": "Hollywood & Bollywood Movies in Multi Language",
"version": "1.0.0",
"author": "piratezoro9",
"supportedTypes": ["movie"],
"filename": "providers/movieshunt.js",
"enabled": true,
"hasSettings": false,
"formats": ["m3u8"],
"logo": "https://i.postimg.cc/3Rc34LJj/movieshunt.png",
"contentLanguage": ["hi", "en"]
},
{
"id": "movies4u",
"name": "Movies4u",
"description": "Hollywood, Bollywood movies including web series, & Hindi dubbed movies in HD quality",
"version": "1.0.2",
"author": "Nuvio Team",
"supportedTypes": ["movie"],
"filename": "providers/movies4u.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/J0QG1QhQ/movies4u.jpg",
"contentLanguage": ["en", "hi", "ta"]
},
{
"id": "movix",
"name": "Movix VF",
"description": "Movies and TV series in English & French (dubbed/subtitled)",
"version": "1.0.0",
"author": "wooodyhood",
"supportedTypes": ["movie", "tv"],
"filename": "providers/movix.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/XYrPQm87/movix.png",
"contentLanguage": ["en", "fr"]
},
{
"id": "nakios",
"name": "Nakios",
"description": "Mainly French, Some English & 4K Quality",
"version": "3.8.2",
"author": "Wooodyhood",
"supportedTypes": ["movie", "tv"],
"filename": "providers/nakios.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/nLwY1pJB/nakios.png",
"contentLanguage": ["fr", "en"]
},
{
"id": "netmirror",
"name": "NetMirror",
"description": "Streaming links from netmirror.",
"version": "1.0.10",
"author": "Nuvio Team",
"supportedTypes": [
"movie",
"tv"
],
"filename": "providers/netmirror.js",
"enabled": true,
"hasSettings": true,
"logo": "https://net22.cc/favicon.ico",
"contentLanguage": [
"en"
],
"supportsExternalPlayer": false
},
{
"id": "persianstremio",
"name": "🌸 PersianStremio",
"description": "Persian Stremio plugin for movies, series,and Persian media content in Iranian & English.",
"version": "1.4.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/persianstremio.js",
"enabled": true,
"hasSettings": false,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/qq6V2fTL/persian.png",
"contentLanguage": ["en", "pe"]
},
{
"id": "peachify",
"name": "🍑 Peachify",
"description": "Streams from peachify.top — 3 server sources (MovieBox/Holly/Air) via Cloudflare Workers with AES-256-GCM decryption",
"version": "1.0.0",
"author": "piratezoro9",
"supportedTypes": ["movie", "tv"],
"filename": "providers/peachify.js",
"enabled": true,
"hasSettings": true,
"formats": ["m3u8", "mp4"],
"logo": "https://i.postimg.cc/tCz8CDH3/peachify.png",
"contentLanguage": ["en", "hi", "te", "ta", "pt"]
},
{
"id": "playimdb",
"name": "PlayIMDb",
"description": "High-Speed Direct Streaming for Movies (IMDb ID Extract)",
"version": "2.0.0",
"author": "PirateZoro9",
"supportedTypes": ["movie", "tv"],
"filename": "providers/playimdb.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/KzjPtYWY/imdb.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "purstream",
"name": "Purstream",
"description": "Films and series in French (VF) / subtitled French (VOSTFR) / multi-language (MULTI) from purstream.art.",
"version": "3.0.0",
"author": "wooodyhood",
"supportedTypes": ["movie", "tv"],
"filename": "providers/purstream.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/7L5shxmC/purstream.png",
"contentLanguage": ["en", "fr"]
},
{
"id": "showbox",
"name": "ShowBox",
"description": "ShowBox streaming with multiple quality options and versions",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/showbox.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/8c5XGzsx/showbox.png",
"contentLanguage": ["en"]
},
{
"id": "topcartoons",
"name": "TopCartoons",
"description": "Popular cartoons streaming",
"version": "1.0.0",
"author": "Phisher",
"supportedTypes": ["movie", "tv"],
"filename": "providers/topcartoons.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/3xVsbwp8/topcartoons.png",
"contentLanguage": ["en"]
},
{
"id": "torrentio",
"name": "🧲 Torrentio",
"description": "Torrentio – Torrent streaming. Supports optional debrid services.",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/torrentio.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/ZRYTCy0T/torrentio.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "vidrock",
"name": "🪨 VidRock",
"description": "VidRock - 1080p 480p and 360p",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/vidrock.js",
"enabled": true,
"hasSettings": false,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/brxL7qg3/multivid.png",
"contentLanguage": ["en"]
},
{
"id": "uhdmovies",
"name": "UHDMovies",
"description": "UHD Movies streaming with multiple resolution",
"version": "1.2.1",
"author": "Nuvio Team",
"supportedTypes": [
"movie",
"tv"
],
"filename": "providers/uhdmovies.js",
"enabled": true,
"formats": [
"mkv"
],
"logo": "https://www.google.com/s2/favicons?domain=uhdmovies.pink&sz=128",
"contentLanguage": [
"en"
]
},
{
"id": "vegamovies",
"name": "VegaMovies",
"description": "VegaMovies streaming with high-quality direct links",
"version": "2.0",
"author": "piratezoro9",
"supportedTypes": ["movie", "tv"],
"filename": "providers/vegamovies.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv"],
"logo": "https://i.postimg.cc/TwYK26jn/vegamovies.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "vidlink",
"name": "VidLink",
"description": "Vidlink streaming with encrypted TMDB ID support for movies and TV shows",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/vidlink.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/RZRHQd75/vidlink.png",
"contentLanguage": ["en"]
},
{
"id": "videasy",
"name": "VidEasy",
"description": "Videasy streaming with encrypted TMDB ID support for movies and TV shows",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/videasy.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/7LHYMtVV/videasy.png",
"contentLanguage": ["en"]
},
{
"id": "vidsrc",
"name": "VidSrc",
"description": "Vidsrc - The best place to watch movies and TV shows online for free. Stream in 1080p HD",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/vidsrc.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/ncMLBsLJ/vidsrc.png",
"contentLanguage": ["en"]
},
{
"id": "vixsrc",
"name": "VixSrc",
"description": "VixSrc - The best place to watch movies and TV shows online for free. Stream in 1080p HD",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/vixsrc.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/1tHrBvzs/vixsrc.png",
"contentLanguage": ["en", "Ita"]
},
{
"id": "vidfast",
"name": "VidFast",
"description": "Stream movies and TV shows from vidfast.pro.",
"version": "1.0.0",
"author": "Dustincos",
"supportedTypes": ["movie", "tv"],
"filename": "providers/vidfast.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/0Qp8PSx5/vidfast.png",
"contentLanguage": ["en"]
},
{
"id": "vidlove",
"name": "❤️ VidLove",
"description": "Movie and TV show streams from MovieBox, LookMovie, VidnNest etc",
"version": "1.0.0",
"author": "Jeff",
"supportedTypes": ["movie", "tv"],
"filename": "providers/vidlove.js",
"enabled": true,
"hasSettings": false,
"formats": ["mp4", "m3u8", "mkv"],
"logo": "https://i.postimg.cc/ZRjQytBY/vidlove.png",
"contentLanguage": ["en"]
},
{
"id": "xpass",
"name": "XPass",
"description": "Play Movie/TV by TMDB ID or IMDb ID",
"version": "1.0.0",
"author": "Dustincos",
"supportedTypes": ["movie", "tv"],
"filename": "providers/xpass.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/tgqNQxdy/xpass.png",
"contentLanguage": ["en", "hi"]
},
{
"id": "zinkmovies",
"name": "ZinkMovies",
"description": "Bollywood Movies, Hollywood Movies, South Indian Movies, Hindi Dubbed Movies, Web Series, OTT Releases, & Trending Cinema",
"version": "1.0.0",
"author": "Kabir",
"supportedTypes": ["movie", "tv"],
"filename": "providers/zinkmovies.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/XqCZyCgp/zinkmovies.png",
"contentLanguage": ["en", "hi", "ta", "te"]
},
{
"id": "onlykdrama",
"name": "🫰 OnlyKDrama",
"description": "Asian Drama",
"version": "1.0.0",
"author": "Moiz Ahmed + Codex",
"supportedTypes": ["movie", "tv"],
"filename": "providers/onlykdrama.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "mkv", "m3u8"],
"logo": "https://i.postimg.cc/dtX84Gqc/onlykdrama.jpg",
"contentLanguage": ["ko"]
},
{
"id": "kisskh",
"name": "💋 Kisskh",
"description": "Streams Korean dramas and movies from onlykdrama.top",
"version": "1.0.0",
"author": "Michat88",
"supportedTypes": ["movie", "tv"],
"filename": "providers/kisskh.js",
"enabled": true,
"hasSettings": true,
"formats": ["mp4", "m3u8"],
"logo": "https://i.postimg.cc/2yLnTzPP/kisskh.jpg",
"contentLanguage": ["ko", "ch", "ja", "th"]
},
{
"id": "reanime",
"name": "Reanime",
"description": "Reanime anime streaming with automated AniList mapping and subtitle support",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/reanime.js",
"enabled": true,
"hasSettings": false,
"formats": ["mkv", "m3u8"],
"logo": "https://www.google.com/s2/favicons?domain=reanime.to&sz=128",
"contentLanguage": ["en"]
},
{
"id": "mapple",
"name": "Mapple",
"description": "Mapple multi-hoster movies and TV streaming with PoW session verification and direct HLS streams",
"version": "1.0.0",
"author": "Nuvio Team",
"supportedTypes": ["movie", "tv"],
"filename": "providers/mapple.js",
"enabled": true,
"hasSettings": false,
"formats": ["m3u8"],
"logo": "https://www.google.com/s2/favicons?domain=mapple.fun&sz=128",
"contentLanguage": ["en"]
}
]
}
+481
View File
@@ -0,0 +1,481 @@
/**
* mapple - Built from src/mapple/
* Generated: 2026-09-21T12:38:36.737Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/mapple/constants.js
var BASE_URL = "https://mapple.fun";
var SUBTITLE_BASE = "https://sub.wyzie.io";
var TMDB_BASE_URL = "https://api.themoviedb.org/3";
var TMDB_API_KEY = "439c478a771f35c05022f9feabcca01c";
var DEFAULT_USER_AGENT = "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Mobile Safari/537.36";
var API_HEADERS = {
"User-Agent": DEFAULT_USER_AGENT,
"Accept": "*/*",
"Origin": BASE_URL,
"Referer": `${BASE_URL}/`
};
var PLAYBACK_HEADERS = {
"Referer": `${BASE_URL}/`,
"Origin": BASE_URL,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
};
var HOSTERS = [
{ name: "Zeus", key: "mapple" },
{ name: "Poseidon", key: "s25" },
{ name: "Athena", key: "s2" },
{ name: "Hera", key: "s4" },
{ name: "Persephone", key: "s12" },
{ name: "Apollo", key: "s19" },
{ name: "Artemis", key: "s13" },
{ name: "Hermes", key: "s26" },
{ name: "Ares", key: "s24" },
{ name: "Aphrodite", key: "s6" },
{ name: "Hephaestus", key: "s15" },
{ name: "Demeter", key: "s7" },
{ name: "Dionysus", key: "s8" },
{ name: "Hestia", key: "s3" },
{ name: "Hades", key: "s16" },
{ name: "Nike", key: "s5" },
{ name: "Atlas", key: "s1" },
{ name: "Prometheus", key: "s10" }
];
// src/mapple/pow.js
var import_crypto_js = __toESM(require("crypto-js"));
var nodeCrypto = null;
try {
const req = require;
nodeCrypto = req("crypto");
} catch (e) {
}
function countLeadingZeroBitsBytes(bytes) {
let count = 0;
for (let i = 0; i < bytes.length; i++) {
const b = bytes[i];
if (b === 0) {
count += 8;
} else {
for (let bit = 7; bit >= 0; bit--) {
if ((b & 1 << bit) !== 0)
return count;
count++;
}
}
}
return count;
}
function countLeadingZeroBitsWords(words) {
let count = 0;
for (let i = 0; i < words.length; i++) {
const w = words[i] >>> 0;
const lz = Math.clz32(w);
count += lz;
if (lz < 32)
break;
}
return count;
}
function solvePow(challenge, difficulty) {
const maxAttempts = 5e7;
let nonce = 0;
if (nodeCrypto && typeof nodeCrypto.createHash === "function") {
while (nonce < maxAttempts) {
const hash = nodeCrypto.createHash("sha256").update(challenge + nonce).digest();
if (countLeadingZeroBitsBytes(hash) >= difficulty) {
return nonce.toString();
}
nonce++;
}
} else {
while (nonce < maxAttempts) {
const hash = import_crypto_js.default.SHA256(challenge + nonce);
if (countLeadingZeroBitsWords(hash.words) >= difficulty) {
return nonce.toString();
}
nonce++;
}
}
throw new Error(`PoW solve exceeded max attempts (difficulty=${difficulty})`);
}
// src/mapple/utils.js
var CookieJar = class {
constructor() {
this.cookies = /* @__PURE__ */ new Map();
}
update(res) {
if (!res || !res.headers)
return;
let rawCookies = [];
if (typeof res.headers.getSetCookie === "function") {
rawCookies = res.headers.getSetCookie();
} else if (res.headers.get) {
const h = res.headers.get("set-cookie");
if (h)
rawCookies = [h];
}
for (const c of rawCookies) {
const parts = c.split(";");
const [k, v] = parts[0].split("=");
if (k && v) {
this.cookies.set(k.trim(), v.trim());
}
}
}
getCookieString() {
const list = [];
for (const [k, v] of this.cookies.entries()) {
list.push(`${k}=${v}`);
}
return list.join("; ");
}
};
function fetchMediaDetails(tmdbId, mediaType) {
return __async(this, null, function* () {
var _a;
try {
const endpoint = mediaType === "tv" ? "tv" : "movie";
const url = `${TMDB_BASE_URL}/${endpoint}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`;
const res = yield fetch(url, {
headers: {
"User-Agent": DEFAULT_USER_AGENT,
"Accept": "application/json"
}
});
if (!res.ok)
throw new Error(`TMDB HTTP ${res.status}`);
const data = yield res.json();
return {
title: mediaType === "tv" ? data.name : data.title,
year: (mediaType === "tv" ? data.first_air_date : data.release_date || "").substring(0, 4),
imdbId: ((_a = data.external_ids) == null ? void 0 : _a.imdb_id) || null,
mediaType
};
} catch (e) {
return {
title: `TMDB ${tmdbId}`,
year: "",
imdbId: null,
mediaType
};
}
});
}
function fetchSubtitles(tmdbId, mediaType, seasonNum = null, episodeNum = null) {
return __async(this, null, function* () {
try {
const isMovie = mediaType !== "tv";
const url = isMovie ? `${SUBTITLE_BASE}/search?id=${tmdbId}` : `${SUBTITLE_BASE}/search?id=${tmdbId}&season=${seasonNum}&episode=${episodeNum}`;
const res = yield fetch(url, { headers: { "Accept": "application/json" } });
if (!res.ok)
return [];
const data = yield res.json();
if (!Array.isArray(data))
return [];
return data.map((sub) => ({
url: sub.url,
language: sub.language || "Unknown",
name: sub.isHearingImpaired ? `${sub.language} (CC)` : sub.language || "Subtitle"
}));
} catch (e) {
return [];
}
});
}
function parseHlsMaster(masterUrl, hosterName, mediaTitle, playbackHeaders) {
return __async(this, null, function* () {
try {
const res = yield fetch(masterUrl, { headers: playbackHeaders });
if (!res.ok)
return null;
const text = yield res.text();
if (!text.includes("#EXT-X-STREAM-INF"))
return null;
const lines = text.split("\n");
const streams = [];
let currentQuality = "Unknown";
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.startsWith("#EXT-X-STREAM-INF")) {
const resMatch = line.match(/RESOLUTION=\d+x(\d+)/);
if (resMatch) {
currentQuality = resMatch[1] + "p";
}
} else if (line && !line.startsWith("#")) {
const streamUrl = line.startsWith("http") ? line : new URL(line, masterUrl).href;
streams.push({
name: `Mapple [${hosterName}] - ${currentQuality}`,
title: mediaTitle,
url: streamUrl,
quality: currentQuality,
size: "Unknown",
headers: playbackHeaders,
provider: "mapple"
});
currentQuality = "Unknown";
}
}
return streams.length > 0 ? streams : null;
} catch (e) {
return null;
}
});
}
// src/mapple/index.js
function getPlaybackSession(tmdbId, mediaType, tvSlug, mediaReferer, cookieJar) {
return __async(this, null, function* () {
const initRes = yield fetch(`${BASE_URL}/`, {
headers: {
"User-Agent": API_HEADERS["User-Agent"],
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
});
cookieJar.update(initRes);
const tokenRes = yield fetch(`${BASE_URL}/api/request-token`, {
method: "POST",
headers: __spreadProps(__spreadValues({}, API_HEADERS), {
"Referer": mediaReferer,
"Content-Type": "application/json",
"Cookie": cookieJar.getCookieString()
}),
body: ""
});
cookieJar.update(tokenRes);
if (!tokenRes.ok)
return null;
const tokenData = yield tokenRes.json();
const requestToken = tokenData == null ? void 0 : tokenData.token;
if (!requestToken)
return null;
const initPayload = {
mediaId: Number(tmdbId),
mediaType,
tv_slug: tvSlug,
requestToken
};
const playbackRes = yield fetch(`${BASE_URL}/api/playback-init`, {
method: "POST",
headers: __spreadProps(__spreadValues({}, API_HEADERS), {
"Referer": mediaReferer,
"Content-Type": "application/json",
"Cookie": cookieJar.getCookieString()
}),
body: JSON.stringify(initPayload)
});
cookieJar.update(playbackRes);
if (!playbackRes.ok)
return null;
const initData = yield playbackRes.json();
let playbackToken = null;
if (initData.success && initData.token) {
playbackToken = initData.token;
} else if (initData.requiresPow && initData.pow) {
const nonce = solvePow(initData.pow.challenge, initData.pow.difficulty);
const powRes = yield fetch(`${BASE_URL}/api/playback-init`, {
method: "POST",
headers: __spreadProps(__spreadValues({}, API_HEADERS), {
"Referer": mediaReferer,
"Content-Type": "application/json",
"Cookie": cookieJar.getCookieString()
}),
body: JSON.stringify(__spreadProps(__spreadValues({}, initPayload), {
pow: {
challengeId: initData.pow.challengeId,
nonce
}
}))
});
cookieJar.update(powRes);
if (powRes.ok) {
const powData = yield powRes.json();
playbackToken = powData == null ? void 0 : powData.token;
}
}
if (!playbackToken)
return null;
return { requestToken, playbackToken };
});
}
function extractHosterStream(hoster, tmdbId, mediaType, tvSlug, mediaReferer, session, cookieJar, mediaTitle, subtitles) {
return __async(this, null, function* () {
var _a;
try {
const encRes = yield fetch(`${BASE_URL}/api/encrypt`, {
method: "POST",
headers: __spreadProps(__spreadValues({}, API_HEADERS), {
"Referer": mediaReferer,
"Content-Type": "application/json",
"Cookie": cookieJar.getCookieString()
}),
body: JSON.stringify({
data: {
mediaId: Number(tmdbId),
mediaType,
tv_slug: tvSlug,
source: hoster.key
},
endpoint: "stream-encrypted",
requestToken: session.requestToken
})
});
if (!encRes.ok)
return [];
const encData = yield encRes.json();
if (!(encData == null ? void 0 : encData.url))
return [];
const streamEndpoint = `${BASE_URL}${encData.url}&requestToken=${encodeURIComponent(session.requestToken)}&token=${encodeURIComponent(session.playbackToken)}`;
const streamRes = yield fetch(streamEndpoint, {
headers: __spreadProps(__spreadValues({}, API_HEADERS), {
"Referer": mediaReferer,
"Cookie": cookieJar.getCookieString()
})
});
if (!streamRes.ok)
return [];
const streamData = yield streamRes.json();
const streamUrl = (_a = streamData == null ? void 0 : streamData.data) == null ? void 0 : _a.stream_url;
if (!(streamData == null ? void 0 : streamData.success) || !streamUrl || streamUrl.includes("playback-unavailable")) {
return [];
}
const streams = [];
const parsedStreams = yield parseHlsMaster(streamUrl, hoster.name, mediaTitle, PLAYBACK_HEADERS);
if (parsedStreams && parsedStreams.length > 0) {
parsedStreams.forEach((s) => {
s.subtitles = subtitles;
streams.push(s);
});
}
streams.push({
name: `Mapple [${hoster.name}] - Auto`,
title: mediaTitle,
url: streamUrl,
quality: "Auto",
size: "Unknown",
headers: PLAYBACK_HEADERS,
provider: "mapple",
subtitles
});
return streams;
} catch (e) {
return [];
}
});
}
function getStreams(tmdbId, mediaType, seasonNum = null, episodeNum = null) {
return __async(this, null, function* () {
const type = mediaType === "tv" || mediaType === "series" ? "tv" : "movie";
const s = seasonNum ? Number(seasonNum) : 1;
const e = episodeNum ? Number(episodeNum) : 1;
const tvSlug = type === "tv" ? `${s}-${e}` : "";
const mediaReferer = type === "tv" ? `${BASE_URL}/tv/${tmdbId}/${s}/${e}` : `${BASE_URL}/movie/${tmdbId}`;
const [mediaDetails, subtitles] = yield Promise.all([
fetchMediaDetails(tmdbId, type),
fetchSubtitles(tmdbId, type, s, e)
]);
let mediaTitle = mediaDetails.title || `TMDB ${tmdbId}`;
if (mediaDetails.year) {
mediaTitle += ` (${mediaDetails.year})`;
}
if (type === "tv") {
mediaTitle += ` S${String(s).padStart(2, "0")}E${String(e).padStart(2, "0")}`;
}
const cookieJar = new CookieJar();
const session = yield getPlaybackSession(tmdbId, type, tvSlug, mediaReferer, cookieJar);
if (!session)
return [];
const hosterPromises = HOSTERS.map(
(hoster) => extractHosterStream(hoster, tmdbId, type, tvSlug, mediaReferer, session, cookieJar, mediaTitle, subtitles)
);
const hosterResults = yield Promise.all(hosterPromises);
const allStreams = hosterResults.flat();
const seen = /* @__PURE__ */ new Set();
const uniqueStreams = [];
allStreams.forEach((stream) => {
if (!seen.has(stream.url)) {
seen.add(stream.url);
uniqueStreams.push(stream);
}
});
const qualityRank = {
"auto": 4e3,
"adaptive": 4e3,
"2160p": 2160,
"4k": 2160,
"1080p": 1080,
"720p": 720,
"480p": 480,
"360p": 360,
"240p": 240,
"unknown": 0
};
uniqueStreams.sort((a, b) => {
var _a, _b;
const qa = qualityRank[(_a = a.quality) == null ? void 0 : _a.toLowerCase()] || 0;
const qb = qualityRank[(_b = b.quality) == null ? void 0 : _b.toLowerCase()] || 0;
return qb - qa;
});
return uniqueStreams;
});
}
module.exports = { getStreams };
+755 -1
View File
@@ -1 +1,755 @@
'use strict';const _0x5df61e=_0x1301;function _0x1301(_0x147c16,_0x38c3f3){_0x147c16=_0x147c16-0xcc;const _0x2a568b=_0x2a56();let _0x130141=_0x2a568b[_0x147c16];if(_0x1301['kiGTOm']===undefined){var _0x21b7b1=function(_0x5b4dfd){const _0x60d9d9='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x40bf53='',_0x6486c7='';for(let _0x5874a7=0x0,_0x4168ea,_0x2a9b98,_0x5882ca=0x0;_0x2a9b98=_0x5b4dfd['charAt'](_0x5882ca++);~_0x2a9b98&&(_0x4168ea=_0x5874a7%0x4?_0x4168ea*0x40+_0x2a9b98:_0x2a9b98,_0x5874a7++%0x4)?_0x40bf53+=String['fromCharCode'](0xff&_0x4168ea>>(-0x2*_0x5874a7&0x6)):0x0){_0x2a9b98=_0x60d9d9['indexOf'](_0x2a9b98);}for(let _0x451df1=0x0,_0x2b5730=_0x40bf53['length'];_0x451df1<_0x2b5730;_0x451df1++){_0x6486c7+='%'+('00'+_0x40bf53['charCodeAt'](_0x451df1)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x6486c7);};_0x1301['QuaViJ']=_0x21b7b1,_0x1301['cnDtGb']={},_0x1301['kiGTOm']=!![];}const _0xda70c7=_0x2a568b[0x0],_0x4c91a7=_0x147c16+_0xda70c7,_0x2f7ed9=_0x1301['cnDtGb'][_0x4c91a7];return!_0x2f7ed9?(_0x130141=_0x1301['QuaViJ'](_0x130141),_0x1301['cnDtGb'][_0x4c91a7]=_0x130141):_0x130141=_0x2f7ed9,_0x130141;}(function(_0x247280,_0xebc547){const _0x4a60e0={_0x319673:0xed,_0x3049a0:0xef,_0x648702:0xe3,_0x14e0d5:0xdf},_0x17a689=_0x1301,_0x2d1757=_0x247280();while(!![]){try{const _0x2bad92=parseInt(_0x17a689(0xcc))/0x1*(parseInt(_0x17a689(0xe6))/0x2)+parseInt(_0x17a689(0xf3))/0x3*(parseInt(_0x17a689(_0x4a60e0._0x319673))/0x4)+-parseInt(_0x17a689(0xe8))/0x5+parseInt(_0x17a689(0xdd))/0x6+parseInt(_0x17a689(_0x4a60e0._0x3049a0))/0x7+-parseInt(_0x17a689(_0x4a60e0._0x648702))/0x8+parseInt(_0x17a689(_0x4a60e0._0x14e0d5))/0x9;if(_0x2bad92===_0xebc547)break;else _0x2d1757['push'](_0x2d1757['shift']());}catch(_0x1fc666){_0x2d1757['push'](_0x2d1757['shift']());}}}(_0x2a56,0xd6d75));var __defProp=Object['defineProperty'],__defProps=Object['defineProperties'],__getOwnPropDescs=Object['getOwnPropertyDescriptors'],__getOwnPropSymbols=Object['getOwnPropertySymbols'],__hasOwnProp=Object['prototype']['hasOwnProperty'],__propIsEnum=Object[_0x5df61e(0xf6)][_0x5df61e(0xeb)],__defNormalProp=(_0x40bf53,_0x6486c7,_0x5874a7)=>_0x6486c7 in _0x40bf53?__defProp(_0x40bf53,_0x6486c7,{'enumerable':!![],'configurable':!![],'writable':!![],'value':_0x5874a7}):_0x40bf53[_0x6486c7]=_0x5874a7,__spreadValues=(_0x4168ea,_0x2a9b98)=>{const _0x51bb8f=_0x5df61e;for(var _0x5882ca in _0x2a9b98||(_0x2a9b98={}))if(__hasOwnProp['call'](_0x2a9b98,_0x5882ca))__defNormalProp(_0x4168ea,_0x5882ca,_0x2a9b98[_0x5882ca]);if(__getOwnPropSymbols)for(var _0x5882ca of __getOwnPropSymbols(_0x2a9b98)){if(__propIsEnum[_0x51bb8f(0xf0)](_0x2a9b98,_0x5882ca))__defNormalProp(_0x4168ea,_0x5882ca,_0x2a9b98[_0x5882ca]);}return _0x4168ea;},__spreadProps=(_0x451df1,_0x2b5730)=>__defProps(_0x451df1,__getOwnPropDescs(_0x2b5730)),__async=(_0x14d30f,_0x6a36a5,_0x4cc304)=>{const _0x2d60b2={_0x1f2408:0xf2};return new Promise((_0x565c41,_0x2dfc0b)=>{const _0x2c160d={_0x5c1f27:0xe7},_0x293180=_0x1301;var _0x2aeac6=_0x300863=>{const _0x49c7d1=_0x1301;try{_0x34f38a(_0x4cc304[_0x49c7d1(0xe9)](_0x300863));}catch(_0x9546d7){_0x2dfc0b(_0x9546d7);}},_0x301a54=_0x5a164e=>{const _0x51b13f=_0x1301;try{_0x34f38a(_0x4cc304[_0x51b13f(_0x2c160d._0x5c1f27)](_0x5a164e));}catch(_0x199ef4){_0x2dfc0b(_0x199ef4);}},_0x34f38a=_0x4ba69b=>_0x4ba69b['done']?_0x565c41(_0x4ba69b[_0x293180(0xdb)]):Promise['resolve'](_0x4ba69b[_0x293180(0xdb)])['then'](_0x2aeac6,_0x301a54);_0x34f38a((_0x4cc304=_0x4cc304[_0x293180(_0x2d60b2._0x1f2408)](_0x14d30f,_0x6a36a5))[_0x293180(0xe9)]());});};function onSettings(){const _0xd81328={_0x50e1b2:0xfe,_0xb098b:0xe5,_0x8a736d:0xe1};return __async(this,null,function*(){const _0x2e9c9c=_0x1301;return[{'type':_0x2e9c9c(_0xd81328._0x50e1b2),'label':_0x2e9c9c(_0xd81328._0xb098b)},{'type':_0x2e9c9c(_0xd81328._0x8a736d),'key':'langEnglish','label':_0x2e9c9c(0xd3),'defaultValue':!![]},{'type':'toggle','key':_0x2e9c9c(0xf4),'label':'Enable\x20Hindi\x20🇮🇳','defaultValue':!![]}];});}var PROVIDER_NAME=_0x5df61e(0xfa),CINESCRAPE_BASE='https://pengu.uk/%7B%22source_moviebox%22%3A%22on%22%2C%22res_1080%22%3A%22on%22%2C%22disable_direct%22%3A%22on%22%2C%22auth_token%22%3A%22XwZg2rLkLlbjXBeDVCyxgfHXjxN1ijLMkUuToW8KaKc%22%7D',TMDB_API_KEY=_0x5df61e(0xd5);function getStreams(_0x5a32a7,_0x2fe227,_0x328cc2,_0x2733e2){const _0x11a400={_0x5d2410:0xe4,_0x277c11:0xfb,_0x19fe37:0xd6,_0x4a3bd8:0xde,_0x4dbb50:0xee,_0x56fb4e:0xff,_0x4eae8d:0xd1,_0x21c047:0xcf,_0x53d823:0xd4};return __async(this,null,function*(){const _0x39b341={_0x3e3e69:0xd8},_0xb642cf=_0x1301;var _0xd04b39;const _0x700f53=_0x2fe227==='tv'||_0x2fe227===_0xb642cf(0xda),_0x59c3c7=_0xb642cf(_0x11a400._0x5d2410)+(_0x700f53?'tv':'movie')+'/'+_0x5a32a7+_0xb642cf(_0x11a400._0x277c11)+TMDB_API_KEY+_0xb642cf(_0x11a400._0x19fe37);try{const _0x3699f4=globalThis['SCRAPER_SETTINGS']||{},_0x51ddfd=_0x3699f4['langEnglish']!==![],_0x2601af=_0x3699f4['langHindi']!==![],_0x11cd2f=yield fetch(_0x59c3c7)['then'](_0xLine truncated
/**
* moviebox - Built from src/moviebox/
* Generated: 2026-09-29T14:51:11.980Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/moviebox/constants.js
var API_BASE = "https://api3.aoneroom.com";
var PLAYER_BASE = "https://moviebox.ph";
var PLAYER_USER_AGENT = "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Mobile Safari/537.36";
var HOST_POOL = [
"https://api6.aoneroom.com",
"https://api5.aoneroom.com",
"https://api4.aoneroom.com",
"https://api4sg.aoneroom.com",
"https://api3.aoneroom.com"
];
var KEY_B64_DEFAULT = "NzZpUmwwN3MweFNOOWpxbUVXQXQ3OUVCSlp1bElRSXNWNjRGWnIyTw==";
var KEY_B64_ALT = "WHFuMm5uTzQxL0w5Mm8xaXVYaFNMSFRiWHZZNFo1Wlo2Mm04bVNMQQ==";
var TMDB_API_KEY = "1865f43a0549ca50d341dd9ab8b29f49";
var TMDB_BASE_URL = "https://api.themoviedb.org/3";
var BRAND_MODELS = {
"Samsung": ["SM-S918B", "SM-A528B", "SM-M336B"],
"Xiaomi": ["2201117TI", "M2012K11AI", "Redmi Note 11"],
"OnePlus": ["LE2111", "CPH2449", "IN2023"],
"Google": ["Pixel 6", "Pixel 7", "Pixel 8"],
"Realme": ["RMX3085", "RMX3360", "RMX3551"]
};
var TOKEN_URL = "https://apig.inmoviebox.com/wefeed-mobile-bff/tab/ranking-list?tabId=0&categoryType=4516404531735022304&page=1&perPage=1";
var PACKAGE_INFO = {
package_name: "com.community.mbox.in",
version_name: "4.0.03.0920.03",
version_code: 50020130
};
// src/moviebox/utils.js
var import_crypto_js = __toESM(require("crypto-js"));
var SECRET_KEY_DEFAULT = import_crypto_js.default.enc.Base64.parse(
import_crypto_js.default.enc.Base64.parse(KEY_B64_DEFAULT).toString(import_crypto_js.default.enc.Utf8)
);
var SECRET_KEY_ALT = import_crypto_js.default.enc.Base64.parse(
import_crypto_js.default.enc.Base64.parse(KEY_B64_ALT).toString(import_crypto_js.default.enc.Utf8)
);
var deviceId = "";
var selectedBrand = "";
var selectedModel = "";
var bearerToken = null;
function decodeJwtExpiry(token) {
try {
const parts = token.split(".");
if (parts.length < 2)
return 0;
let base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
while (base64.length % 4) {
base64 += "=";
}
const parsed = import_crypto_js.default.enc.Base64.parse(base64).toString(import_crypto_js.default.enc.Utf8);
const json = JSON.parse(parsed);
return json.exp || 0;
} catch (e) {
return 0;
}
}
function isTokenValid(token) {
if (!token)
return false;
const exp = decodeJwtExpiry(token);
return exp > Date.now() / 1e3 + 3600;
}
function getCachedToken() {
return __async(this, null, function* () {
if (isTokenValid(bearerToken))
return bearerToken;
console.log("[MovieBox] Fetching fresh anonymous token...");
const url = TOKEN_URL;
const res = yield movieBoxRequest("GET", url, null, {}, true);
if (res && res.headers) {
const xUser = res.headers.get("x-user");
if (xUser) {
try {
const xUserJson = JSON.parse(xUser);
const token = xUserJson.token;
if (token && isTokenValid(token)) {
bearerToken = token;
return token;
}
} catch (e) {
console.error("[MovieBox] Failed to parse x-user header for token", e);
}
}
}
return bearerToken || "";
});
}
function initializeSession() {
if (!deviceId) {
let chars = "0123456789abcdef";
for (let i = 0; i < 32; i++) {
deviceId += chars[Math.floor(Math.random() * 16)];
}
const brands = Object.keys(BRAND_MODELS);
selectedBrand = brands[Math.floor(Math.random() * brands.length)];
const models = BRAND_MODELS[selectedBrand];
selectedModel = models[Math.floor(Math.random() * models.length)];
}
}
function md5(input) {
return import_crypto_js.default.MD5(input).toString(import_crypto_js.default.enc.Hex);
}
function hmacMd5(key, data) {
return import_crypto_js.default.HmacMD5(data, key).toString(import_crypto_js.default.enc.Base64);
}
function generateXClientToken(timestamp) {
const ts = (timestamp || Date.now()).toString();
const reversed = ts.split("").reverse().join("");
const hash = md5(reversed);
return `${ts},${hash}`;
}
function buildCanonicalString(method, accept, contentType, url, body, timestamp) {
let path = "";
let query = "";
try {
const urlObj = new URL(url);
path = urlObj.pathname;
const params = Array.from(urlObj.searchParams.keys()).sort();
if (params.length > 0) {
query = params.map((key) => {
const values = urlObj.searchParams.getAll(key);
return values.map((val) => `${key}=${val}`).join("&");
}).join("&");
}
} catch (e) {
if (url.includes("?")) {
const parts = url.split("?");
path = parts[0].replace(/https?:\/\/[^\/]+/, "");
const qParts = parts[1].split("&").sort();
query = qParts.join("&");
} else {
path = url.replace(/https?:\/\/[^\/]+/, "");
}
}
const canonicalUrl = query ? `${path}?${query}` : path;
let bodyHash = "";
let bodyLength = "";
if (body) {
const bodyWords = import_crypto_js.default.enc.Utf8.parse(body);
const totalBytes = bodyWords.sigBytes;
bodyHash = md5(bodyWords);
bodyLength = totalBytes.toString();
}
return `${method.toUpperCase()}
${accept || ""}
${contentType || ""}
${bodyLength}
${timestamp}
${bodyHash}
` + canonicalUrl;
}
function generateXTrSignature(method, accept, contentType, url, body, useAltKey = false, customTimestamp = null) {
const timestamp = customTimestamp || Date.now();
const canonical = buildCanonicalString(method, accept, contentType, url, body, timestamp);
const secret = useAltKey ? SECRET_KEY_ALT : SECRET_KEY_DEFAULT;
const signatureB64 = hmacMd5(secret, canonical);
return `${timestamp}|2|${signatureB64}`;
}
function movieBoxRequest(_0, _1) {
return __async(this, arguments, function* (method, url, body = null, customHeaders = {}, isTokenFetch = false) {
initializeSession();
const timestamp = Date.now();
const xClientToken = generateXClientToken(timestamp);
const headerContentType = customHeaders["Content-Type"] || (body ? "application/json; charset=utf-8" : "application/json");
const accept = customHeaders["Accept"] || "application/json";
const xTrSignature = generateXTrSignature(method, accept, headerContentType, url, body, false, timestamp);
const xClientInfo = JSON.stringify(__spreadProps(__spreadValues({}, PACKAGE_INFO), {
os: "android",
os_version: "14",
device_id: deviceId,
install_store: "official",
gaid: "1b2212c1-dadf-43c3-a0c8-bd6ce48ae22d",
brand: selectedBrand.toLowerCase(),
model: selectedModel,
system_language: "en",
net: "NETWORK_WIFI",
region: "IN",
timezone: "Asia/Calcutta",
sp_code: ""
}));
const headers = __spreadValues({
"Accept": accept,
"Content-Type": headerContentType,
"x-client-token": xClientToken,
"x-tr-signature": xTrSignature,
"User-Agent": `${PACKAGE_INFO.package_name}/${PACKAGE_INFO.version_code} (Linux; U; Android 14; en_IN; ${selectedModel}; Build/UD1A.230803.041; Cronet/145.0.7582.0)`,
"x-client-info": xClientInfo,
"x-client-status": "0"
}, customHeaders);
if (!isTokenFetch) {
const token = yield getCachedToken();
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
}
const options = {
method,
headers
};
if (body) {
options.body = body;
}
let originalUrl;
try {
originalUrl = new URL(url);
} catch (_) {
return null;
}
const apiHosts = new Set(HOST_POOL.map((host) => new URL(host).host));
const hosts = apiHosts.has(originalUrl.host) ? [originalUrl.host, ...HOST_POOL.map((host) => new URL(host).host).filter((host) => host !== originalUrl.host)] : [originalUrl.host];
const maxAttempts = Math.min(3, hosts.length);
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
const requestUrl = new URL(originalUrl.toString());
requestUrl.host = hosts[attempt];
const res = yield fetch(requestUrl.toString(), options);
if (!res.ok) {
if ((res.status === 403 || res.status === 429 || res.status >= 500) && attempt + 1 < maxAttempts) {
continue;
}
return null;
}
const text = yield res.text();
let parsed = null;
try {
parsed = JSON.parse(text);
} catch (e) {
parsed = text;
}
if (res.headers) {
const xUser = res.headers.get("x-user");
if (xUser) {
try {
const xUserJson = JSON.parse(xUser);
const token = xUserJson.token;
if (token && isTokenValid(token)) {
bearerToken = token;
}
} catch (e) {
}
}
}
return {
data: parsed,
headers: res.headers
};
} catch (err) {
if (attempt + 1 === maxAttempts) {
console.error("[MovieBox Request Error]", err.message);
return null;
}
}
}
return null;
});
}
function fetchTmdbDetails(tmdbId, mediaType) {
return __async(this, null, function* () {
var _a;
try {
const url = `${TMDB_BASE_URL}/${mediaType}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`;
const res = yield fetch(url, {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
"Accept": "application/json",
"Connection": "keep-alive"
}
});
const data = yield res.json();
return {
title: mediaType === "movie" ? data.title || data.original_title : data.name || data.original_name,
year: (data.release_date || data.first_air_date || "").substring(0, 4),
imdbId: (_a = data.external_ids) == null ? void 0 : _a.imdb_id,
originalTitle: data.original_title || data.original_name
};
} catch (e) {
console.error("[MovieBox TMDB Error]", e.message);
return null;
}
});
}
function normalizeTitle(s) {
if (!s)
return "";
return String(s).replace(/\[[^\]]*\]/g, " ").replace(/\([^)]*\)/g, " ").replace(/\b(dub|dubbed|hd|4k|hindi|tamil|telugu|dual audio)\b/gi, " ").trim().toLowerCase().replace(/:/g, " ").replace(/[^\w\s]/g, " ").replace(/\s+/g, " ");
}
function parseQualityNumber(value) {
const match = String(value || "").match(/(\d{3,4})/);
return match ? parseInt(match[1], 10) : 0;
}
function getFormatType(url) {
const u = String(url || "").toLowerCase();
if (u.includes(".mpd"))
return "DASH";
if (u.includes(".m3u8"))
return "HLS";
if (u.includes(".mp4"))
return "MP4";
if (u.includes(".mkv"))
return "MKV";
return "VIDEO";
}
function extractPolicyResource(signCookie) {
var _a, _b;
if (!signCookie || typeof signCookie !== "string")
return null;
const edgeMatch = signCookie.match(/Edge-Cache-Cookie=urlprefix=([^:;\s]+)/);
if (edgeMatch) {
try {
let std = edgeMatch[1].replace(/_/g, "/").replace(/-/g, "+");
const rem = (4 - std.length % 4) % 4;
if (rem > 0)
std += "=".repeat(rem);
const decoded = import_crypto_js.default.enc.Base64.parse(std).toString(import_crypto_js.default.enc.Utf8).replace(/\/+$/, "");
if (decoded)
return `${decoded}/index.mpd`;
} catch (_) {
}
}
const cfMatch = signCookie.match(/CloudFront-Policy=([^;]+)/);
if (cfMatch) {
try {
const policyRaw = cfMatch[1];
let cfB64 = policyRaw.replace(/-/g, "+").replace(/~/g, "/").replace(/_/g, "=");
const rem = cfB64.length % 4;
if (rem > 0)
cfB64 += "=".repeat(rem);
let decodedJson = null;
try {
decodedJson = import_crypto_js.default.enc.Base64.parse(cfB64).toString(import_crypto_js.default.enc.Utf8);
} catch (_) {
let stdB64 = policyRaw.replace(/-/g, "+").replace(/_/g, "/");
const rem2 = stdB64.length % 4;
if (rem2 > 0)
stdB64 += "=".repeat(rem2);
decodedJson = import_crypto_js.default.enc.Base64.parse(stdB64).toString(import_crypto_js.default.enc.Utf8);
}
if (decodedJson) {
const root = JSON.parse(decodedJson);
const resource = (_b = (_a = root == null ? void 0 : root.Statement) == null ? void 0 : _a[0]) == null ? void 0 : _b.Resource;
if (resource && typeof resource === "string") {
const trimmed = resource.replace(/[\*\/]+$/, "");
return trimmed.toLowerCase().endsWith(".mpd") ? trimmed : `${trimmed}/index.mpd`;
}
}
} catch (_) {
}
}
return null;
}
// src/moviebox/index.js
function getStreams(tmdbId, mediaType, seasonNum = 1, episodeNum = 1) {
return __async(this, null, function* () {
console.log(`[MovieBox] Querying streams for TMDB: ${tmdbId}, Type: ${mediaType}`);
const details = yield fetchTmdbDetails(tmdbId, mediaType);
if (!details)
return [];
let subjects = yield searchMovieBox(details.title);
let bestMatch = findBestMatch(subjects, details.title, details.year, mediaType);
if (!bestMatch && details.originalTitle && details.originalTitle !== details.title) {
subjects = yield searchMovieBox(details.originalTitle);
bestMatch = findBestMatch(subjects, details.originalTitle, details.year, mediaType);
}
if (bestMatch) {
const s = mediaType === "tv" ? seasonNum : 0;
const e = mediaType === "tv" ? episodeNum : 0;
return yield getStreamLinks(bestMatch.subjectId, s, e, details.title, mediaType);
}
console.log(`[MovieBox] No matching content found for: ${details.title}`);
return [];
});
}
function searchMovieBox(query) {
return __async(this, null, function* () {
const url = `${API_BASE}/wefeed-mobile-bff/subject-api/search/v2`;
const body = JSON.stringify({ page: 1, perPage: 20, keyword: query, restrictKid: 1 });
const response = yield movieBoxRequest("POST", url, body);
if (response && response.data && response.data.data && response.data.data.results) {
let allSubjects = [];
response.data.data.results.forEach((group) => {
if (group.subjects) {
allSubjects = allSubjects.concat(group.subjects);
}
});
return allSubjects;
}
return [];
});
}
function findBestMatch(subjects, tmdbTitle, tmdbYear, mediaType) {
const normTmdbTitle = normalizeTitle(tmdbTitle);
const targetType = mediaType === "movie" ? 1 : 2;
let bestMatch = null;
let bestScore = 0;
for (const subject of subjects) {
if (subject.subjectType !== targetType)
continue;
const title = subject.title;
const normTitle = normalizeTitle(title);
const year = subject.year || (subject.releaseDate ? subject.releaseDate.substring(0, 4) : null);
let score = 0;
if (normTitle === normTmdbTitle)
score += 50;
else if (normTitle.includes(normTmdbTitle) || normTmdbTitle.includes(normTitle))
score += 15;
if (tmdbYear && year && tmdbYear == year)
score += 35;
if (score > bestScore) {
bestScore = score;
bestMatch = subject;
}
}
if (bestScore >= 40)
return bestMatch;
return null;
}
function getPlaybackPage(subjectData, subjectId) {
const candidates = [subjectData.detailPath, subjectData.detail_path, subjectData.path, subjectData.slug];
let detailPath = candidates.find((value) => typeof value === "string" && value.trim());
let webBase = PLAYER_BASE;
for (const value of [subjectData.detailDomain, subjectData.webDomain, subjectData.webUrl, subjectData.detailUrl, subjectData.shareUrl]) {
if (typeof value !== "string")
continue;
try {
const parsed = new URL(value.startsWith("http") ? value : `https://${value}`);
if (!parsed.hostname.endsWith("aoneroom.com"))
webBase = parsed.origin;
if (!detailPath && parsed.pathname && parsed.pathname !== "/")
detailPath = parsed.pathname;
break;
} catch (e) {
}
}
if (!detailPath)
return { webBase, referer: `${webBase}/` };
detailPath = detailPath.replace(/^\/+/, "").replace(/^movies\//, "");
const pageUrl = new URL(`/movies/${detailPath}`, `${webBase}/`);
pageUrl.searchParams.set("id", subjectId);
pageUrl.searchParams.set("type", "/movie/detail");
pageUrl.searchParams.set("detailSe", "");
pageUrl.searchParams.set("detailEp", "");
pageUrl.searchParams.set("lang", "en");
return { webBase, detailPath, referer: pageUrl.toString() };
}
function collectStreams(playData) {
var _a, _b;
const streams = Array.isArray(playData == null ? void 0 : playData.streams) ? [...playData.streams] : [];
for (const [key, format] of [["netDash", "DASH"], ["netHls", "HLS"]]) {
const value = (_b = playData == null ? void 0 : playData[key]) != null ? _b : (_a = playData == null ? void 0 : playData.data) == null ? void 0 : _a[key];
const values = Array.isArray(value) ? value : value ? [value] : [];
for (const item of values) {
if (typeof item === "string")
streams.push({ url: item, format });
else if (item && typeof item === "object") {
if (item.url || item.playUrl || item.resourceLink || item.streamUrl)
streams.push(__spreadProps(__spreadValues({}, item), { format: item.format || format }));
else
for (const [resolution, url] of Object.entries(item)) {
if (typeof url === "string" && /^https?:\/\//i.test(url))
streams.push({ url, resolution, format });
else if (url && typeof url === "object")
streams.push(__spreadProps(__spreadValues({}, url), { resolution: url.resolution || resolution, format: url.format || format }));
}
}
}
}
const seen = /* @__PURE__ */ new Set();
return streams.filter((stream) => {
const key = (stream == null ? void 0 : stream.url) || (stream == null ? void 0 : stream.playUrl) || (stream == null ? void 0 : stream.resourceLink) || (stream == null ? void 0 : stream.streamUrl);
if (!key || seen.has(key))
return false;
seen.add(key);
return true;
});
}
function getAudioLabel(stream, fallbackLanguage) {
var _a, _b;
const rawLanguage = [stream.languageName, stream.lanName, stream.language, stream.lan, fallbackLanguage].find((value) => typeof value === "string" && value.trim()) || "Unknown";
let language = rawLanguage.replace(/\bdub\b/gi, " ").replace(/\baudio\b/gi, " ").replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
const languageNames = {
ar: "Arabic",
bn: "Bengali",
de: "German",
en: "English",
es: "Spanish",
fr: "French",
hi: "Hindi",
id: "Indonesian",
it: "Italian",
ja: "Japanese",
ko: "Korean",
ml: "Malayalam",
mr: "Marathi",
pt: "Portuguese",
ru: "Russian",
ta: "Tamil",
te: "Telugu",
th: "Thai",
tr: "Turkish",
ur: "Urdu",
vi: "Vietnamese",
zh: "Chinese"
};
const languageCode = (_b = (_a = language.match(/^([a-z]{2,3})(?:\s|$)/i)) == null ? void 0 : _a[1]) == null ? void 0 : _b.toLowerCase();
if (languageCode && languageNames[languageCode]) {
language = languageNames[languageCode];
} else if (language) {
language = language.charAt(0).toUpperCase() + language.slice(1);
} else {
language = "Unknown";
}
return `${language} Audio`;
}
function getStreamLinks(subjectId, season = 0, episode = 0, mediaTitle = "", mediaType = "movie") {
return __async(this, null, function* () {
const subjectUrl = `${API_BASE}/wefeed-mobile-bff/subject-api/get?subjectId=${subjectId}`;
const detailRes = yield movieBoxRequest("GET", subjectUrl);
if (!detailRes || !detailRes.data || !detailRes.data.data)
return [];
const subjectData = detailRes.data.data;
const playbackPage = getPlaybackPage(subjectData, subjectId);
const subjectIds = [];
let originalLang = "Original";
const dubs = subjectData.dubs;
if (Array.isArray(dubs)) {
dubs.forEach((dub) => {
if (dub.subjectId == subjectId) {
originalLang = dub.lanName || "Original";
} else {
subjectIds.push({ id: dub.subjectId, lang: dub.lanName });
}
});
}
subjectIds.unshift({ id: subjectId, lang: originalLang });
const allStreams = [];
const playbackHeaders = {
"Origin": playbackPage.webBase,
"Referer": playbackPage.referer,
"User-Agent": PLAYER_USER_AGENT,
"x-request-lang": "en",
"x-vip-restrict": "0",
"x-no-high-risk-restrict": "0"
};
for (const item of subjectIds) {
try {
const playParams = new URLSearchParams({ subjectId: item.id, se: season, ep: episode, streamSignType: "1" });
if (playbackPage.detailPath)
playParams.set("detailPath", playbackPage.detailPath);
playParams.set("supportCodecs[hevc]", "1");
playParams.set("supportCodecs[h264]", "1");
const playUrl = `${API_BASE}/wefeed-mobile-bff/subject-api/play-info?${playParams.toString()}`;
const playRes = yield movieBoxRequest("GET", playUrl, null, playbackHeaders);
let hasValidStream = false;
if (playRes && playRes.data && playRes.data.data) {
const playData = playRes.data.data;
const streamsList = collectStreams(playData);
if (Array.isArray(streamsList) && streamsList.length > 0) {
for (const stream of streamsList) {
const rawStreamUrl = stream.url || stream.playUrl || stream.resourceLink || stream.streamUrl || "";
const signCookie = stream.signCookie || null;
const policyUrl = extractPolicyResource(signCookie);
const finalStreamUrl = policyUrl || rawStreamUrl;
if (!finalStreamUrl)
continue;
if (finalStreamUrl.includes("b164fbfb4347792950bdfbfb563d39d9"))
continue;
if (finalStreamUrl === rawStreamUrl && rawStreamUrl.includes("/other/2026/09/"))
continue;
let formatType = getFormatType(finalStreamUrl);
if (stream.format) {
const declaredFormat = String(stream.format).toUpperCase();
formatType = ["DASH", "HLS", "MP4", "MKV"].includes(declaredFormat) ? declaredFormat : getFormatType(finalStreamUrl);
}
const qualLabel = stream.resolutions || stream.resolution || stream.quality || "Auto";
const qualNum = parseQualityNumber(qualLabel);
const quality = qualNum ? `${qualNum}p` : "Auto";
const audioLabel = getAudioLabel(stream, item.lang);
const streamId = stream.id || `${item.id}|${season}|${episode}`;
const subtitles = yield fetchSubtitles(item.id, streamId, item.lang);
const signHeaderKey = stream.signHeaderKey || stream.sign_header_key || "Cookie";
allStreams.push({
name: "MovieBox",
title: `${mediaTitle}${season > 0 ? ` S${season}E${episode}` : ""} - ${quality} (${audioLabel}) [${formatType}]`,
url: finalStreamUrl,
quality,
headers: __spreadValues(__spreadValues({}, playbackHeaders), signCookie ? { [signHeaderKey]: signCookie } : {}),
subtitles,
provider: "moviebox"
});
hasValidStream = true;
}
}
if (!hasValidStream) {
let detectors = playData.resourceDetectors;
if (!Array.isArray(detectors)) {
detectors = subjectData.resourceDetectors;
}
if (Array.isArray(detectors)) {
for (const detector of detectors) {
if (Array.isArray(detector.resolutionList)) {
for (const video of detector.resolutionList) {
if (!video.resourceLink)
continue;
const se = video.se != null ? video.se : 0;
const ep = video.ep != null ? video.ep : 0;
if ((season > 0 || episode > 0) && (se !== season || ep !== episode)) {
continue;
}
const quality = video.resolution ? `${video.resolution}p` : "Auto";
const audioLabel = getAudioLabel({}, item.lang);
allStreams.push({
name: "MovieBox",
title: `${mediaTitle}${season > 0 ? ` S${season}E${episode}` : ""} - ${quality} (${audioLabel}) [Fallback]`,
url: video.resourceLink,
quality,
headers: __spreadValues({}, playbackHeaders),
provider: "moviebox"
});
}
}
}
}
}
}
} catch (err) {
console.error(`[MovieBox Stream Fetch Error] ID: ${item.id}`, err.message);
}
}
const qualityRank = {
"2160p": 2160,
"4k": 2160,
"1440p": 1440,
"1080p": 1080,
"720p": 720,
"480p": 480,
"360p": 360,
"240p": 240,
"auto": 1
};
allStreams.sort((a, b) => {
var _a, _b;
const qa = qualityRank[(_a = a.quality) == null ? void 0 : _a.toLowerCase()] || 0;
const qb = qualityRank[(_b = b.quality) == null ? void 0 : _b.toLowerCase()] || 0;
return qb - qa;
});
return allStreams;
});
}
function fetchSubtitles(subjectId, streamId, langLabel) {
return __async(this, null, function* () {
const subtitles = [];
try {
const streamCapUrl = `${API_BASE}/wefeed-mobile-bff/subject-api/get-stream-captions?subjectId=${subjectId}&streamId=${streamId}`;
const capRes = yield movieBoxRequest("GET", streamCapUrl, null);
if (capRes && capRes.data && capRes.data.data && Array.isArray(capRes.data.data.extCaptions)) {
capRes.data.data.extCaptions.forEach((cap) => {
if (cap.url) {
subtitles.push({
url: cap.url,
language: cap.language || cap.lanName || cap.lan || "en",
name: `${cap.lanName || cap.language || "Subtitle"} (${langLabel})`,
headers: { "Referer": API_BASE }
});
}
});
}
} catch (e) {
}
try {
const extCapUrl = `${API_BASE}/wefeed-mobile-bff/subject-api/get-ext-captions?subjectId=${subjectId}&resourceId=${streamId}&episode=0`;
const extRes = yield movieBoxRequest("GET", extCapUrl, null);
if (extRes && extRes.data && extRes.data.data && Array.isArray(extRes.data.data.extCaptions)) {
extRes.data.data.extCaptions.forEach((cap) => {
if (cap.url) {
subtitles.push({
url: cap.url,
language: cap.lan || cap.lanName || cap.language || "en",
name: `${cap.lanName || cap.lan || "Subtitle"} (${langLabel})`,
headers: { "Referer": API_BASE }
});
}
});
}
} catch (e) {
}
return subtitles;
});
}
module.exports = { getStreams };
+435 -1
View File
@@ -1 +1,435 @@
var _0x3ddb21=_0x1b28;(function(_0x5efd39,_0x1b68bc){var _0x32b52e={_0x31e9d8:0x185,_0x1e68a4:0x1b9,_0x436187:0x1ab,_0x4ede22:0x1c1,_0x45ccd4:0x187,_0x156ba0:0x16b},_0x26db9d=_0x1b28,_0x4936d8=_0x5efd39();while(!![]){try{var _0x39fe8e=-parseInt(_0x26db9d(_0x32b52e._0x31e9d8))/0x1*(parseInt(_0x26db9d(_0x32b52e._0x1e68a4))/0x2)+parseInt(_0x26db9d(0x191))/0x3*(parseInt(_0x26db9d(0x1b7))/0x4)+parseInt(_0x26db9d(_0x32b52e._0x436187))/0x5+-parseInt(_0x26db9d(_0x32b52e._0x4ede22))/0x6*(parseInt(_0x26db9d(0x188))/0x7)+-parseInt(_0x26db9d(_0x32b52e._0x45ccd4))/0x8+-parseInt(_0x26db9d(_0x32b52e._0x156ba0))/0x9*(parseInt(_0x26db9d(0x1d1))/0xa)+-parseInt(_0x26db9d(0x1a5))/0xb*(-parseInt(_0x26db9d(0x1a7))/0xc);if(_0x39fe8e===_0x1b68bc)break;else _0x4936d8['push'](_0x4936d8['shift']());}catch(_0x1eb582){_0x4936d8['push'](_0x4936d8['shift']());}}}(_0x1e7a,0x9ef8a));var __defProp=Object[_0x3ddb21(0x1cf)],__defProps=Object[_0x3ddb21(0x1d2)],__getOwnPropDescs=Object[_0x3ddb21(0x175)],__getOwnPropSymbols=Object[_0x3ddb21(0x1c6)],__hasOwnProp=Object[_0x3ddb21(0x1b2)][_0x3ddb21(0x182)],__propIsEnum=Object[_0x3ddb21(0x1b2)][_0x3ddb21(0x176)],__defNormalProp=(_0x2ee21e,_0x9cbb11,_0x1207f5)=>_0x9cbb11 in _0x2ee21e?__defProp(_0x2ee21e,_0x9cbb11,{'enumerable':!![],'configurable':!![],'writable':!![],'value':_0x1207f5}):_0x2ee21e[_0x9cbb11]=_0x1207f5,__spreadValues=(_0x480f16,_0x1472e7)=>{var _0x39ddb0={_0x1c6c1c:0x18b},_0xd84ed7=_0x3ddb21;for(var _0xe3415d in _0x1472e7||(_0x1472e7={}))if(__hasOwnProp[_0xd84ed7(_0x39ddb0._0x1c6c1c)](_0x1472e7,_0xe3415d))__defNormalProp(_0x480f16,_0xe3415d,_0x1472e7[_0xe3415d]);if(__getOwnPropSymbols)for(var _0xe3415d of __getOwnPropSymbols(_0x1472e7)){if(__propIsEnum[_0xd84ed7(0x18b)](_0x1472e7,_0xe3415d))__defNormalProp(_0x480f16,_0xe3415d,_0x1472e7[_0xe3415d]);}return _0x480f16;},__spreadProps=(_0x4e6c84,_0x3807c1)=>__defProps(_0x4e6c84,__getOwnPropDescs(_0x3807c1)),__async=(_0x5b3bff,_0x2e179d,_0x1b79c8)=>{var _0x9b6f33={_0x2adfb8:0x17b};return new Promise((_0xf8680c,_0x315523)=>{var _0x1ad00f=_0x1b28,_0x5d0b89=_0xae726=>{try{_0x502c30(_0x1b79c8['next'](_0xae726));}catch(_0x1611a9){_0x315523(_0x1611a9);}},_0x2bc555=_0x73e0dd=>{try{_0x502c30(_0x1b79c8['throw'](_0x73e0dd));}catch(_0x21f7af){_0x315523(_0x21f7af);}},_0x502c30=_0x2e42b7=>_0x2e42b7[_0x1ad00f(0x193)]?_0xf8680c(_0x2e42b7['value']):Promise['resolve'](_0x2e42b7['value'])['then'](_0x5d0b89,_0x2bc555);_0x502c30((_0x1b79c8=_0x1b79c8[_0x1ad00f(_0x9b6f33._0x2adfb8)](_0x5b3bff,_0x2e179d))['next']());});},PROVIDER_NAME=_0x3ddb21(0x199),MAIN_URL='https://new1.moviesdrive.christmas',ARCHIVE_DOMAIN=_0x3ddb21(0x18e),TMDB_KEY='439c478a771f35c05022f9feabcca01c',MOBILE_UAS=[_0x3ddb21(0x1a4),_0x3ddb21(0x1b4),_0x3ddb21(0x1bc),'Mozilla/5.0\x20(iPhone;\x20CPU\x20iPhone\x20OS\x2017_0\x20like\x20Mac\x20OS\x20X)\x20AppleWebKit/605.1.15\x20(KHTML,\x20like\x20Gecko)\x20Version/17.0\x20Mobile/15E148\x20Safari/604.1','Mozilla/5.0\x20(iPad;\x20CPU\x20OS\x2017_0\x20like\x20Mac\x20OS\x20X)\x20AppleWebKit/605.1.15\x20(KHTML,\x20like\x20Gecko)\x20Version/17.0\x20Mobile/15E148\x20Safari/604.1'];function getHeaders(_0x1fa484){var _0x1ff31e={_0x3dffc3:0x1b0,_0x558810:0x18f,_0x59d52f:0x1a3},_0x5f280d=_0x3ddb21,_0x35ba14=MOBILE_UAS[Math[_0x5f280d(_0x1ff31e._0x3dffc3)](Math[_0x5f280d(_0x1ff31e._0x558810)]()*MOBILE_UAS[_0x5f280d(_0x1ff31e._0x59d52f)])],_0x310ec5={'User-Agent':_0x35ba14,'Accept-Language':_0x5f280d(0x177)};if(_0x1fa484)for(var _0x2f2f4c in _0x1fa484){_0x310ec5[_0x2f2f4c]=_0x1fa484[_0x2f2f4c];}return _0x310ec5;}function _0x1e7a(){var _0xb020df=['Bg9N','C2vYAwvZ','zMLYC3rFywLYx2rHDgu','C3rHCNrZv2L0Aa','Bwf4','Aw1KyG','DgL0Bgu','EwvHCG','z2v0t3DUuhjVCgvYDhLezxnJCMLWDg9YCW','ChjVCgvYDhLjC0vUDw1LCMfIBgu','zw4TvvmSzw47Ct0WlJK','qxv0BW','DgvZDa','iIaO','yxbWBhK','l3nLyxjJAc5WAha/Ct0','z2v0twLUDxrLCW','AgL0CW','zNvUy3rPB24','C2L6zq','zg9JDw1LBNq','AgfZt3DUuhjVCgvYDhK','Dg9mB3DLCKnHC2u','Ahr0Chm6lY9HCgKUDgHLBw92AwvKyI5VCMCVmY8','mJq0ndn0uhbltMm','ChjVy2vZC2LUzYa','otmWotC2oernDMjVtW','mJeXodGZz1DAC3fh','EgXHpxm0Da','C3vIC3rYAw5N','y2fSBa','C29YDa','Ahr0Ca','Ahr0Chm6lY9TzhjPDMuUBg9S','CMfUzg9T','Ahr0Chm6lY9HCgKUDgHLBw92AwvKyI5VCMCVmY9MAw5KlW','m0TjCeTnvW','rLnm','zg9Uzq','mtq0mha','zxHLyW','zMLSDgvY','zM9YrwfJAa','DgL0BguGBwf0y2G6ia','tw92AwvZrhjPDMu','C2LNBMfS','DgLTzw91Da','C2vHC29U','zMv0y2G6ia','CxvHBgL0Eq','ywjZ','DhjPBq','CMvSzwfZzv9KyxrL','C3bSAxq','BgvUz3rO','tw96AwXSys81lJaGkeXPBNv4oYbbBMrYB2LKide0oYbqAxHLBca4ifbYBYKGqxbWBgvxzwjlAxqVntm3lJm2icHlsfrntcWGBgLRzsbhzwnRBYKGq2HYB21LlZeYnc4WlJaUmcbnB2jPBguGu2fMyxjPlZuZnY4ZnG','mtq0nJKXotfYB3njCwy','rLnmDJi','mtjTwKLJB20','ndGWCa','ihm9','BM8GrLnmihn0CMvHBxmGCMvZB2X2zwq','ntu0mZa2nuPtCLfQsa','ihn0CMvHBxm','vgLTzw91Dca','kdXOwZeTnL1BxJ5DkJ58phn0CM9Uz1TEpL0QpIKUkJ8OpZPtzwfZB258u2fPC29UFfn0ywzMzwWPxhmQmcOOxgqRkvXZkLST4OctxvXZkJaQkfXKkYK','C2vHCMnOihPLCM86ia','zMXVB3i','zNjVBunOyxjdB2rL','ChjVDg90ExbL','CMvWBgfJzq','tw96AwXSys81lJaGkeXPBNv4oYbbBMrYB2LKideZoYbtts1tote4qIKGqxbWBgvxzwjlAxqVntm3lJm2icHlsfrntcWGBgLRzsbhzwnRBYKGqLine truncated
/**
* moviesdrive - Built from src/moviesdrive/
* Generated: 2026-09-26T06:11:02.295Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/moviesdrive/index.js
var import_cheerio_without_node_native2 = __toESM(require("cheerio-without-node-native"));
// src/moviesdrive/constants.js
var MAIN_URL = "https://new4.moviesdrive.christmas";
var DOMAINS_URL = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json";
var HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "max-age=0",
"Connection": "keep-alive"
};
// src/moviesdrive/utils.js
var import_cheerio_without_node_native = __toESM(require("cheerio-without-node-native"));
var cachedMainUrl = "";
function getMainUrl() {
return __async(this, null, function* () {
if (cachedMainUrl)
return cachedMainUrl;
try {
const response = yield fetch(DOMAINS_URL, { headers: { "User-Agent": "Mozilla/5.0" } });
const data = yield response.json();
cachedMainUrl = data.moviesdrive || MAIN_URL;
return cachedMainUrl;
} catch (e) {
return MAIN_URL;
}
});
}
function getIndexQuality(str) {
if (!str)
return 1080;
const match = str.match(/(\d{3,4})[pP]/);
if (match)
return parseInt(match[1]);
if (str.toUpperCase().includes("4K") || str.toUpperCase().includes("2160P") || str.toUpperCase().includes("UHD"))
return 2160;
return 1080;
}
function extractMdrive(url) {
return __async(this, null, function* () {
if (!url)
return [];
const regex = /hubcloud|gdflix|gdlink/i;
if (!url.includes("search-recover.php") && regex.test(url) && (url.includes("/drive/") || url.includes("/file/"))) {
return [url];
}
try {
const res = yield fetch(url, { headers: __spreadProps(__spreadValues({}, HEADERS), { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }) });
const html = yield res.text();
if (url.includes("search-recover.php")) {
const qMatch = html.match(/const\s+Q_INITIAL\s*=\s*["']([^"']+)["']/);
const tokenMatch = html.match(/const\s+FROM_AC_TOKEN\s*=\s*["']([^"']+)["']/);
if (qMatch && tokenMatch) {
const apiBase = url.split("/drive/")[0];
const searchParams = new URLSearchParams({
api: "search",
q: qMatch[1],
page: "1",
from_ac: tokenMatch[1]
});
const apiRes = yield fetch(`${apiBase}/drive/search-recover.php?${searchParams.toString()}`, {
headers: __spreadProps(__spreadValues({}, HEADERS), { "Accept": "application/json", Referer: url, "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" })
});
const data = yield apiRes.json();
if (data.hits) {
return data.hits.map((h) => h.url).filter(Boolean);
}
}
}
const $ = import_cheerio_without_node_native.default.load(html);
return $("a[href]").map((i, el) => $(el).attr("href")).get().filter((href) => regex.test(href));
} catch (e) {
return [];
}
});
}
function hubCloudExtractor(url, referer) {
return __async(this, null, function* () {
try {
let currentUrl = url;
const pageResponse = yield fetch(currentUrl, {
headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: referer })
});
let pageData = yield pageResponse.text();
let finalUrl = currentUrl;
if (!currentUrl.includes("hubcloud.php")) {
let nextHref = "";
const $first = import_cheerio_without_node_native.default.load(pageData);
const phpLink = $first('a[href*="hubcloud.php"]').attr("href");
if (phpLink) {
nextHref = phpLink;
} else {
const downloadBtn = $first("#download");
if (downloadBtn.length) {
nextHref = downloadBtn.attr("href");
} else {
const scriptUrlMatch = pageData.match(/var url = ["']([^"']*)["']/);
if (scriptUrlMatch)
nextHref = scriptUrlMatch[1];
}
}
if (nextHref) {
if (!nextHref.startsWith("http")) {
const urlObj = new URL(currentUrl);
nextHref = `${urlObj.protocol}//${urlObj.hostname}/${nextHref.replace(/^\//, "")}`;
}
finalUrl = nextHref;
const secondResponse = yield fetch(finalUrl, {
headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: currentUrl })
});
pageData = yield secondResponse.text();
}
}
const $ = import_cheerio_without_node_native.default.load(pageData);
const size = $("i#size").text().trim();
const header = $("div.card-header").text().trim();
const quality = getIndexQuality(header);
const pxlMatch = pageData.match(/var\s+pxl\s*=\s*["']([^"']+)["']/);
const links = [];
const elements = $("a[href]").get();
const blocked = ["tinyurl", "telegram", "hubcloud.cx/tg", "hubcloud.foo/tg"];
for (const el of elements) {
let link = $(el).attr("href");
const text = $(el).text().toLowerCase().trim();
if (!link || blocked.some((b) => link.includes(b)))
continue;
if (link.includes("negn6f") && pxlMatch) {
link = pxlMatch[1];
}
if (text.includes("fslv2")) {
links.push({ name: "HubCloud - FSLv2", quality, url: link, size });
} else if (text.includes("fsl server") || text.includes("fsl") && !text.includes("v2")) {
links.push({ name: "HubCloud - FSL Server", quality, url: link, size });
} else if (text.includes("download file") || text.includes("instant download") || text.includes("instant") || text.includes("10gbps")) {
let streamUrl = link;
if (streamUrl.includes("link=")) {
streamUrl = streamUrl.split("link=")[1];
} else {
try {
const res = yield fetch(link, {
headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: finalUrl }),
redirect: "follow"
});
if (res.url && res.url.startsWith("http")) {
streamUrl = res.url;
if (streamUrl.includes("link=")) {
streamUrl = streamUrl.split("link=")[1];
}
}
} catch (e) {
}
}
if (streamUrl && streamUrl.startsWith("http")) {
links.push({ name: "HubCloud - Instant", quality, url: streamUrl, size });
}
} else if (text.includes("pixeldra") || text.includes("pixelserver") || text.includes("pixeldrain") || link.includes("pixeldrain")) {
let pUrl = link;
if (pUrl.includes("/u/")) {
const fileId = pUrl.split("/u/")[1].split("?")[0].replace("/", "");
pUrl = `https://pixeldrain.dev/api/file/${fileId}?download`;
}
links.push({ name: "HubCloud - Pixeldrain", quality, url: pUrl, size });
} else if (text.includes("buzzserver") || text.includes("buzz server") || text.includes("buzz") || text.includes("fuckingfast")) {
try {
const dlRes = yield fetch(link, {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
});
const dlHtml = yield dlRes.text();
const copyMatch = dlHtml.match(/copyDownloadLink\(['"]([^'"]+)['"]\)/);
const dlPath = copyMatch ? copyMatch[1].replace(/\\\//g, "/") : null;
const base = new URL(link).origin;
const dlUrl = dlPath ? dlPath.startsWith("http") ? dlPath : `${base}${dlPath}` : link.endsWith("/download") ? link : `${link}/download`;
const resp = yield fetch(dlUrl, {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Referer": link,
"HX-Request": "true"
},
redirect: "manual"
});
const dlink = resp.headers.get("hx-redirect") || resp.headers.get("location");
if (dlink) {
links.push({ name: "HubCloud - BuzzServer", quality, url: dlink, size });
}
} catch (e) {
}
} else if (text.includes("s3 server")) {
links.push({ name: "HubCloud - S3", quality, url: link, size });
} else if (text.includes("mega server")) {
links.push({ name: "HubCloud - Mega", quality, url: link, size });
} else if (link.includes("r2.dev")) {
links.push({ name: "Direct R2", quality, url: link, size });
} else if (link.includes("workers.dev")) {
links.push({ name: "ZipDisk Server", quality, url: link, size });
}
}
return links;
} catch (e) {
return [];
}
});
}
function loadExtractor(url, referer) {
return __async(this, null, function* () {
try {
const hostname = new URL(url).hostname;
if (hostname.includes("hubcloud"))
return yield hubCloudExtractor(url, referer);
if (hostname.includes("gdflix") || hostname.includes("gdlink"))
return [{ name: "GDFlix", quality: 1080, url }];
return [];
} catch (e) {
return [];
}
});
}
// src/moviesdrive/index.js
function getStreams(tmdbId, mediaType, seasonNum = 1, episodeNum = 1) {
return __async(this, null, function* () {
var _a;
console.log(`[MoviesDrive] Querying streams for TMDB: ${tmdbId}, Type: ${mediaType}`);
const tmdbApiKey = "1865f43a0549ca50d341dd9ab8b29f49";
const tmdbUrl = `https://api.themoviedb.org/3/${mediaType}/${tmdbId}?api_key=${tmdbApiKey}&append_to_response=external_ids`;
const tmdbRes = yield fetch(tmdbUrl, {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
"Accept": "application/json"
}
});
const tmdbData = yield tmdbRes.json();
const imdbId = (_a = tmdbData.external_ids) == null ? void 0 : _a.imdb_id;
const cleanTitle = tmdbData.title || tmdbData.name || "";
const mainUrl = yield getMainUrl();
let match = null;
const findMatch = (hits) => {
if (!hits || !hits.length)
return null;
if (mediaType === "tv") {
const sSlug = String(seasonNum).padStart(2, "0");
const seasonPatterns = [
new RegExp(`\\bseason\\s*0?${seasonNum}\\b`, "i"),
new RegExp(`\\bs0?${seasonNum}\\b`, "i"),
new RegExp(`\\bseason\\s*${sSlug}\\b`, "i")
];
return hits.find((doc) => {
const postTitle = (doc.post_title || "").toLowerCase();
const permalink2 = (doc.permalink || "").toLowerCase();
const normDocTitle = postTitle.replace(/[^a-z0-9]/g, "");
const normTitle = cleanTitle.toLowerCase().replace(/[^a-z0-9]/g, "");
const titleMatches = normDocTitle.includes(normTitle) || postTitle.includes(cleanTitle.toLowerCase()) || permalink2.includes(cleanTitle.toLowerCase().replace(/ /g, "-"));
const seasonMatches = seasonPatterns.some((pat) => pat.test(postTitle) || pat.test(permalink2));
return titleMatches && seasonMatches;
});
} else {
return hits.find((d) => imdbId && d.imdb_id === imdbId) || hits.find((doc) => {
const postTitle = (doc.post_title || "").toLowerCase();
const permalink2 = (doc.permalink || "").toLowerCase();
const normDocTitle = postTitle.replace(/[^a-z0-9]/g, "");
const normTitle = cleanTitle.toLowerCase().replace(/[^a-z0-9]/g, "");
return normDocTitle.includes(normTitle) || postTitle.includes(cleanTitle.toLowerCase()) || permalink2.includes(cleanTitle.toLowerCase().replace(/ /g, "-"));
}) || hits[0];
}
};
if (imdbId) {
try {
const searchUrl = `${mainUrl}/search.php?q=${imdbId}&page=1`;
const searchRes = yield fetch(searchUrl, { headers: HEADERS });
if (searchRes.ok) {
const searchData = yield searchRes.json();
match = findMatch((searchData.hits || []).map((h) => h.document));
}
} catch (e) {
}
}
if (!match && cleanTitle) {
try {
const searchUrl = `${mainUrl}/search.php?q=${encodeURIComponent(cleanTitle)}&page=1`;
const searchRes = yield fetch(searchUrl, { headers: HEADERS });
if (searchRes.ok) {
const searchData = yield searchRes.json();
match = findMatch((searchData.hits || []).map((h) => h.document));
}
} catch (e) {
}
}
if (!match) {
console.log("[MoviesDrive] No matching post found");
return [];
}
const permalink = match.permalink;
const href = permalink.startsWith("http") ? permalink : `${mainUrl}${permalink}`;
try {
const pageRes = yield fetch(href, { headers: HEADERS });
const pageHtml = yield pageRes.text();
const $ = import_cheerio_without_node_native2.default.load(pageHtml);
const allStreams = [];
if (mediaType === "movie") {
const links = [];
$("h5 a").each((_, a) => {
const h = $(a).attr("href");
if (h)
links.push(h);
});
for (const link of [...new Set(links)]) {
const extracted = yield extractMdrive(link);
for (const server of extracted) {
const streams = yield loadExtractor(server, href);
allStreams.push(...streams.map((s) => __spreadProps(__spreadValues({}, s), {
title: `${cleanTitle} - ${s.name} [${s.quality}p]`,
provider: "moviesdrive"
})));
}
}
} else {
const sSlug = String(seasonNum).padStart(2, "0");
const stag = `Season ${seasonNum}|S${sSlug}`;
const sepRegex = new RegExp(`\\b(?:ep|episode|e)\\s*0?${episodeNum}\\b|s0?${seasonNum}\\s*e0?${episodeNum}\\b`, "i");
const stopRegex = /^\s*(EP\d+|Episode\s*\d+|S\d+E\d+)/i;
const entries = $("h5").filter((i, el) => new RegExp(stag, "i").test($(el).text()));
for (const entry of entries.get()) {
const nextHref = $(entry).next().find("a").attr("href") || $(entry).find("a").attr("href");
if (!nextHref)
continue;
const epPageRes = yield fetch(nextHref, { headers: HEADERS });
const epPageHtml = yield epPageRes.text();
const $ep = import_cheerio_without_node_native2.default.load(epPageHtml);
const epEntries = $ep("h5").filter((i, el) => sepRegex.test($ep(el).text()));
for (const epEntry of epEntries.get()) {
const epLinks = [];
let sibling = $ep(epEntry).next();
while (sibling.length && !stopRegex.test(sibling.text().trim())) {
sibling.find("a[href]").each((_, a) => {
const h = $ep(a).attr("href");
if (h)
epLinks.push(h);
});
sibling = sibling.next();
}
if (epLinks.length === 0) {
const l1 = $ep(epEntry).next().find("a").attr("href");
const l2 = $ep(epEntry).next().next().find("a").attr("href");
[l1, l2].forEach((l) => l && epLinks.push(l));
}
for (const epLink of [...new Set(epLinks)]) {
const extracted = yield extractMdrive(epLink);
for (const server of extracted) {
const streams = yield loadExtractor(server, nextHref);
allStreams.push(...streams.map((s) => __spreadProps(__spreadValues({}, s), {
title: `${cleanTitle} S${seasonNum}E${episodeNum} - ${s.name} [${s.quality}p]`,
provider: "moviesdrive"
})));
}
}
}
}
}
return allStreams;
} catch (e) {
console.error("[MoviesDrive] Error:", e.message);
return [];
}
});
}
module.exports = { getStreams };
+496
View File
@@ -0,0 +1,496 @@
/**
* moviesmod - Built from src/moviesmod/
* Generated: 2026-09-22T08:14:06.813Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/moviesmod/index.js
var import_cheerio_without_node_native2 = __toESM(require("cheerio-without-node-native"));
// src/moviesmod/constants.js
var DOMAINS_URL = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json";
var FALLBACK_DOMAIN = "https://moviesmod.army";
var TMDB_API_KEY = "1865f43a0549ca50d341dd9ab8b29f49";
var TMDB_BASE_URL = "https://api.themoviedb.org/3";
var HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1"
};
// src/moviesmod/utils.js
var import_cheerio_without_node_native = __toESM(require("cheerio-without-node-native"));
var cachedDomain = "";
function getMainUrl() {
return __async(this, null, function* () {
if (cachedDomain)
return cachedDomain;
try {
const response = yield fetch(DOMAINS_URL);
const data = yield response.json();
cachedDomain = data.moviesmod || FALLBACK_DOMAIN;
return cachedDomain;
} catch (e) {
return FALLBACK_DOMAIN;
}
});
}
function getBaseUrl(url) {
try {
const urlObj = new URL(url);
return `${urlObj.protocol}//${urlObj.host}`;
} catch (e) {
return "";
}
}
function fixUrl(url, domain) {
if (!url)
return "";
if (url.startsWith("http"))
return url;
if (url.startsWith("//"))
return `https:${url}`;
if (url.startsWith("/"))
return domain + url;
return `${domain}/${url}`;
}
function bypassHrefli(url) {
return __async(this, null, function* () {
const host = getBaseUrl(url);
try {
const res1 = yield fetch(url, { headers: HEADERS });
const html1 = yield res1.text();
const $1 = import_cheerio_without_node_native.default.load(html1);
const formUrl1 = $1("form#landing").attr("action");
const formData1 = {};
$1("form#landing input").each((_, el) => {
formData1[$1(el).attr("name")] = $1(el).attr("value") || "";
});
const res2 = yield fetch(formUrl1, {
method: "POST",
headers: __spreadProps(__spreadValues({}, HEADERS), { "Content-Type": "application/x-www-form-urlencoded" }),
body: new URLSearchParams(formData1).toString()
});
const html2 = yield res2.text();
const $2 = import_cheerio_without_node_native.default.load(html2);
const formUrl2 = $2("form#landing").attr("action");
const formData2 = {};
$2("form#landing input").each((_, el) => {
formData2[$2(el).attr("name")] = $2(el).attr("value") || "";
});
const res3 = yield fetch(formUrl2, {
method: "POST",
headers: __spreadProps(__spreadValues({}, HEADERS), { "Content-Type": "application/x-www-form-urlencoded" }),
body: new URLSearchParams(formData2).toString()
});
const html3 = yield res3.text();
const $3 = import_cheerio_without_node_native.default.load(html3);
const script = $3("script:contains(?go=)").html() || "";
const skTokenMatch = script.match(/\?go=([^"]+)/);
if (!skTokenMatch)
return null;
const skToken = skTokenMatch[1];
const wpHttp2 = formData2["_wp_http2"] || "";
const res4 = yield fetch(`${host}?go=${skToken}`, {
headers: __spreadProps(__spreadValues({}, HEADERS), { "Cookie": `${skToken}=${wpHttp2}` })
});
const html4 = yield res4.text();
const $4 = import_cheerio_without_node_native.default.load(html4);
const metaRefresh = $4('meta[http-equiv="refresh"]').attr("content") || "";
const driveUrlMatch = metaRefresh.match(/url=(.+)/);
if (!driveUrlMatch)
return null;
const driveUrl = driveUrlMatch[1];
const res5 = yield fetch(driveUrl, { headers: HEADERS });
const html5 = yield res5.text();
const pathMatch = html5.match(/replace\("([^"]+)"\)/);
if (!pathMatch || pathMatch[1] === "/404")
return null;
return fixUrl(pathMatch[1], getBaseUrl(driveUrl));
} catch (e) {
return null;
}
});
}
function fetchTmdbDetails(tmdbId, mediaType) {
return __async(this, null, function* () {
var _a;
try {
const url = `${TMDB_BASE_URL}/${mediaType}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`;
const res = yield fetch(url, {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "application/json"
}
});
const data = yield res.json();
return {
title: mediaType === "movie" ? data.title || data.original_title : data.name || data.original_name,
year: (data.release_date || data.first_air_date || "").substring(0, 4),
imdbId: (_a = data.external_ids) == null ? void 0 : _a.imdb_id
};
} catch (e) {
return null;
}
});
}
function getIndexQuality(str) {
if (!str)
return "Unknown";
const match = str.match(/(\d{3,4})[pP]/);
if (match)
return match[1] + "p";
if (str.toUpperCase().includes("4K") || str.toUpperCase().includes("UHD"))
return "2160p";
return "Unknown";
}
function extractVideoSeed(finallink) {
return __async(this, null, function* () {
try {
const urlObj = new URL(finallink);
const host = finallink.includes("video-leech") ? "video-leech.xyz" : urlObj.host || "video-seed.xyz";
const token = finallink.includes("?url=") ? finallink.split("?url=")[1] : finallink;
if (!token)
return null;
const res = yield fetch(`https://${host}/api`, {
method: "POST",
headers: __spreadProps(__spreadValues({}, HEADERS), {
"Content-Type": "application/x-www-form-urlencoded",
"x-token": host,
"Referer": finallink,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
}),
body: `keys=${encodeURIComponent(token)}`
});
const data = yield res.json();
if (data && data.url) {
return data.url.replace(/\\\//g, "/");
}
return null;
} catch (e) {
return null;
}
});
}
function instantLink(url) {
return __async(this, null, function* () {
try {
if (url.includes("cdn.video-gen.xyz")) {
const res = yield fetch(url, { headers: HEADERS, redirect: "follow" });
if (res.url && res.url.includes("url=")) {
const redirected = res.url.split("url=")[1];
if (redirected && !redirected.includes("?url="))
return redirected;
return yield extractVideoSeed(redirected);
}
}
if (url.includes("?url=")) {
return yield extractVideoSeed(url);
}
return url;
} catch (e) {
return null;
}
});
}
function resumeBot(url) {
return __async(this, null, function* () {
try {
const res = yield fetch(url, { headers: HEADERS });
const html = yield res.text();
const setCookie = res.headers.get("set-cookie") || "";
const ssidMatch = setCookie.match(/PHPSESSID=([^;]+)/);
const ssid = ssidMatch ? ssidMatch[1] : "";
const tokenMatch = html.match(/formData\.append\('token',\s*'([a-f0-9]+)'\)/);
const pathMatch = html.match(/fetch\('\/download\?id=([a-zA-Z0-9/+]+)'/);
if (!tokenMatch || !pathMatch)
return null;
const baseUrl = url.substring(0, url.indexOf("/download"));
const downloadUrl = `${baseUrl}/download?id=${pathMatch[1]}`;
const postRes = yield fetch(downloadUrl, {
method: "POST",
headers: __spreadValues(__spreadProps(__spreadValues({}, HEADERS), {
"Accept": "*/*",
"Origin": baseUrl,
"Sec-Fetch-Site": "same-origin",
"Content-Type": "application/x-www-form-urlencoded"
}), ssid ? { "Cookie": `PHPSESSID=${ssid}` } : {}),
body: `token=${encodeURIComponent(tokenMatch[1])}`
});
const data = yield postRes.json();
return data && data.url && data.url.startsWith("http") ? data.url : null;
} catch (e) {
return null;
}
});
}
function CFType1(url) {
return __async(this, null, function* () {
try {
const wfileUrl = url.replace("/file", "/wfile") + "?type=1";
const res = yield fetch(wfileUrl, { headers: HEADERS });
const html = yield res.text();
const $ = import_cheerio_without_node_native.default.load(html);
const links = [];
$("a.btn-success").each((_, el) => {
const h = $(el).attr("href");
if (h && h.startsWith("http"))
links.push(h);
});
return links;
} catch (e) {
return [];
}
});
}
function resumeCloudLink(url) {
return __async(this, null, function* () {
try {
const res = yield fetch(url, { headers: HEADERS });
const html = yield res.text();
const keyMatch = html.match(/formData\.append\(\s*['"]key['"]\s*,\s*['"]([^'"]+)['"]\s*\)/);
if (keyMatch) {
const host = new URL(url).host;
const postRes = yield fetch(url, {
method: "POST",
headers: __spreadProps(__spreadValues({}, HEADERS), {
"Content-Type": "application/x-www-form-urlencoded",
"x-token": host,
"X-Requested-With": "XMLHttpRequest"
}),
body: `action=cloud&key=${encodeURIComponent(keyMatch[1])}&action_token=`
});
const data = yield postRes.json();
if (data && data.url) {
return data.url.replace(/\\\//g, "/");
}
}
const $ = import_cheerio_without_node_native.default.load(html);
return $("a.btn-success").first().attr("href") || null;
} catch (e) {
return null;
}
});
}
function extractDriveseedPage(url) {
return __async(this, null, function* () {
const streams = [];
try {
let pageUrl = url;
if (url.includes("r?key=")) {
const res2 = yield fetch(url, { headers: HEADERS });
const html2 = yield res2.text();
const redirectMatch = html2.match(/replace\("([^"]+)"\)/);
if (redirectMatch) {
pageUrl = getBaseUrl(url) + redirectMatch[1];
}
}
const res = yield fetch(pageUrl, { headers: HEADERS });
const html = yield res.text();
const $ = import_cheerio_without_node_native.default.load(html);
const baseDomain = getBaseUrl(pageUrl);
const nameText = $("li.list-group-item:contains(Name)").first().text() || "";
const sizeText = $("li.list-group-item:contains(Size)").first().text() || $("li:nth-child(3)").text() || "";
const size = sizeText.replace(/.*Size\s*:\s*/i, "").trim();
const quality = getIndexQuality(nameText || $("li.list-group-item").first().text() || "");
const instantHref = $("a.btn-danger").attr("href");
if (instantHref) {
const finalInstant = yield instantLink(instantHref);
if (finalInstant) {
streams.push({ name: "Driveseed Instant", url: finalInstant, quality, size });
}
}
const resumeBotHref = $("a.btn.btn-light").attr("href");
if (resumeBotHref) {
const finalBot = yield resumeBot(resumeBotHref);
if (finalBot) {
streams.push({ name: "Driveseed ResumeBot", url: finalBot, quality, size });
}
}
const cfLinks = yield CFType1(pageUrl);
for (const cfLink of cfLinks) {
streams.push({ name: "Driveseed CF Type1", url: cfLink, quality, size });
}
const resumeCloudHref = $("a.btn-warning").attr("href");
if (resumeCloudHref) {
const fullCloudUrl = resumeCloudHref.startsWith("http") ? resumeCloudHref : `${baseDomain}${resumeCloudHref}`;
const finalCloud = yield resumeCloudLink(fullCloudUrl);
if (finalCloud) {
streams.push({ name: "Driveseed ResumeCloud", url: finalCloud, quality, size });
}
}
} catch (e) {
}
return streams;
});
}
// src/moviesmod/index.js
function getStreams(tmdbId, mediaType, seasonNum = 1, episodeNum = 1) {
return __async(this, null, function* () {
console.log(`[MoviesMod] Querying streams for TMDB: ${tmdbId}, Type: ${mediaType}`);
const details = yield fetchTmdbDetails(tmdbId, mediaType);
if (!details)
return [];
const mainUrl = yield getMainUrl();
console.log(`[MoviesMod] Main URL: ${mainUrl}`);
const query = details.imdbId ? details.imdbId : details.title;
const searchUrl = mediaType === "movie" ? `${mainUrl.replace(/\/$/, "")}/search/${encodeURIComponent(query)}` : `${mainUrl.replace(/\/$/, "")}/search/${encodeURIComponent(query)} ${seasonNum}`;
try {
console.log(`[MoviesMod] Searching at: ${searchUrl}`);
const searchRes = yield fetch(searchUrl, { headers: __spreadProps(__spreadValues({}, HEADERS), { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }), cfKiller: true });
const searchHtml = yield searchRes.text();
const $search = import_cheerio_without_node_native2.default.load(searchHtml);
let targetUrl = $search("#content_box article > a").first().attr("href") || $search("#content_box article a").first().attr("href");
if (!targetUrl && details.imdbId && details.title) {
const fallbackQuery = mediaType === "movie" ? `${mainUrl.replace(/\/$/, "")}/search/${encodeURIComponent(details.title)}` : `${mainUrl.replace(/\/$/, "")}/search/${encodeURIComponent(details.title)} ${seasonNum}`;
const fallbackRes = yield fetch(fallbackQuery, { headers: __spreadProps(__spreadValues({}, HEADERS), { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }), cfKiller: true });
const fallbackHtml = yield fallbackRes.text();
const $fallback = import_cheerio_without_node_native2.default.load(fallbackHtml);
targetUrl = $fallback("#content_box article > a").first().attr("href") || $fallback("#content_box article a").first().attr("href");
}
if (!targetUrl) {
console.log("[MoviesMod] No search result found");
return [];
}
const pageRes = yield fetch(targetUrl, { headers: __spreadProps(__spreadValues({}, HEADERS), { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }), cfKiller: true });
const pageHtml = yield pageRes.text();
const $ = import_cheerio_without_node_native2.default.load(pageHtml);
const allStreams = [];
const contentBox = $(".thecontent");
const hTag = mediaType === "movie" ? "h4" : "h3";
const aTag = mediaType === "movie" ? "Download" : "Episode";
const sTag = mediaType === "movie" ? "" : `(S0${seasonNum}|Season ${seasonNum})`;
const qualityRegex = new RegExp(`${sTag}.*(480p|720p|1080p|2160p)`, "i");
const entries = contentBox.find(hTag).filter((i, el) => {
const text = $(el).text();
return qualityRegex.test(text) && !text.includes("MoviesMod");
});
for (const entry of entries.get()) {
const quality = getIndexQuality($(entry).text());
let linkEl = $(entry).next().find(`a:contains('${aTag}')`).first();
if (!linkEl.length) {
linkEl = $(entry).nextAll("p, div").find(`a:contains('${aTag}')`).first();
}
let nextHref = linkEl.attr("href");
if (nextHref && nextHref.includes("=")) {
nextHref = nextHref.substring(nextHref.indexOf("=") + 1);
}
if (nextHref) {
const streams = yield processModLink(nextHref, targetUrl, quality, mediaType, episodeNum);
allStreams.push(...streams);
}
}
return allStreams;
} catch (e) {
console.error("[MoviesMod] Error:", e.message);
return [];
}
});
}
function processModLink(url, referer, quality, mediaType, episodeNum) {
return __async(this, null, function* () {
try {
const res = yield fetch(url, { headers: __spreadProps(__spreadValues({}, HEADERS), { Referer: referer }) });
const html = yield res.text();
const $ = import_cheerio_without_node_native2.default.load(html);
const selector = mediaType === "movie" ? "p a.maxbutton, a:contains('Download')" : `h3 a:contains('Episode ${episodeNum}'), a:contains('Episode ${episodeNum}'), a.maxbutton`;
let source = $(selector).first().attr("href");
if (!source) {
source = $('a[href*="driveseed.org"], a[href*="tech.unblockedgames.world"], a[href*="video-seed"]').first().attr("href");
}
if (!source)
return [];
let finalLink = source;
if (source.includes("unblockedgames") || source.includes("tech.") || source.includes("href.li")) {
finalLink = yield bypassHrefli(source);
}
const results = [];
if (finalLink && finalLink.includes("driveseed")) {
const streams = yield extractDriveseedPage(finalLink);
results.push(...streams.map((s) => __spreadProps(__spreadValues({}, s), {
name: `MoviesMod [${s.name}]`,
title: `MoviesMod - ${s.quality} ${s.size ? `[${s.size}]` : ""}`,
quality: s.quality || quality,
provider: "moviesmod"
})));
} else if (finalLink && (finalLink.includes("video-seed") || finalLink.includes("video-leech"))) {
const streamUrl = yield extractVideoSeed(finalLink);
if (streamUrl) {
results.push({
name: "MoviesMod [VideoSeed]",
title: `MoviesMod - ${quality}`,
url: streamUrl,
quality,
provider: "moviesmod"
});
}
}
return results;
} catch (e) {
return [];
}
});
}
module.exports = { getStreams };
+455 -1
View File
@@ -1 +1,455 @@
const _0x509bf5=_0x3a01;(function(_0x1e402f,_0x34160a){const _0x4e0846={_0x7852e7:0x10b,_0x3c8323:0xcd,_0x2d86c4:0xd5,_0xff8df8:0xe8,_0x5370e5:0xc4},_0x348648=_0x3a01,_0x522e0d=_0x1e402f();while(!![]){try{const _0x154401=-parseInt(_0x348648(0xdc))/0x1*(parseInt(_0x348648(0xe9))/0x2)+-parseInt(_0x348648(0xed))/0x3*(-parseInt(_0x348648(_0x4e0846._0x7852e7))/0x4)+parseInt(_0x348648(_0x4e0846._0x3c8323))/0x5+parseInt(_0x348648(_0x4e0846._0x2d86c4))/0x6*(parseInt(_0x348648(0xe1))/0x7)+parseInt(_0x348648(0xc9))/0x8*(parseInt(_0x348648(_0x4e0846._0xff8df8))/0x9)+parseInt(_0x348648(_0x4e0846._0x5370e5))/0xa*(parseInt(_0x348648(0x101))/0xb)+-parseInt(_0x348648(0x10f))/0xc;if(_0x154401===_0x34160a)break;else _0x522e0d['push'](_0x522e0d['shift']());}catch(_0xf75ed8){_0x522e0d['push'](_0x522e0d['shift']());}}}(_0x5af8,0x2e62b));var __defProp=Object['defineProperty'],__defProps=Object['defineProperties'],__getOwnPropDescs=Object['getOwnPropertyDescriptors'],__getOwnPropSymbols=Object[_0x509bf5(0xd0)],__hasOwnProp=Object['prototype'][_0x509bf5(0xfe)],__propIsEnum=Object['prototype'][_0x509bf5(0xf6)],__defNormalProp=(_0x32c489,_0x19f7da,_0x5a1022)=>_0x19f7da in _0x32c489?__defProp(_0x32c489,_0x19f7da,{'enumerable':!![],'configurable':!![],'writable':!![],'value':_0x5a1022}):_0x32c489[_0x19f7da]=_0x5a1022,__spreadValues=(_0x1b7e14,_0x5f4e4c)=>{for(var _0x3196f1 in _0x5f4e4c||(_0x5f4e4c={}))if(__hasOwnProp['call'](_0x5f4e4c,_0x3196f1))__defNormalProp(_0x1b7e14,_0x3196f1,_0x5f4e4c[_0x3196f1]);if(__getOwnPropSymbols)for(var _0x3196f1 of __getOwnPropSymbols(_0x5f4e4c)){if(__propIsEnum['call'](_0x5f4e4c,_0x3196f1))__defNormalProp(_0x1b7e14,_0x3196f1,_0x5f4e4c[_0x3196f1]);}return _0x1b7e14;},__spreadProps=(_0x1080ab,_0x4c55be)=>__defProps(_0x1080ab,__getOwnPropDescs(_0x4c55be)),__async=(_0x3a30ea,_0xa26949,_0x283487)=>{const _0xb208d6={_0x134346:0xd7,_0x5a8a35:0xc1};return new Promise((_0x4b7c84,_0x273f5d)=>{const _0x10a20a=_0x3a01;var _0x5d3bb3=_0x93a5d4=>{try{_0x2aef9c(_0x283487['next'](_0x93a5d4));}catch(_0x5f4eeb){_0x273f5d(_0x5f4eeb);}},_0x2bd245=_0x82e0c7=>{try{_0x2aef9c(_0x283487['throw'](_0x82e0c7));}catch(_0x3c2029){_0x273f5d(_0x3c2029);}},_0x2aef9c=_0x5c100b=>_0x5c100b[_0x10a20a(0xf7)]?_0x4b7c84(_0x5c100b['value']):Promise['resolve'](_0x5c100b['value'])[_0x10a20a(0xcc)](_0x5d3bb3,_0x2bd245);_0x2aef9c((_0x283487=_0x283487[_0x10a20a(_0xb208d6._0x134346)](_0x3a30ea,_0xa26949))[_0x10a20a(_0xb208d6._0x5a8a35)]());});},TMDB_API_KEY=_0x509bf5(0x108),PLATFORM_MAP={'netflix':{'ott':'nf','search':'/mobile/search.php','post':'/mobile/post.php','episodes':_0x509bf5(0xf5),'playlist':'/mobile/playlist.php','img':_0x509bf5(0xbb),'epImg':_0x509bf5(0xbc)},'primevideo':{'ott':'pv','search':_0x509bf5(0xda),'post':_0x509bf5(0xcb),'episodes':'/mobile/pv/episodes.php','playlist':'/mobile/pv/playlist.php','img':_0x509bf5(0x103),'epImg':'pvepimg'},'hotstar':{'ott':'hs','search':'/mobile/hs/search.php','post':_0x509bf5(0xdf),'episodes':_0x509bf5(0xe6),'playlist':_0x509bf5(0xba),'img':'hs/v','epImg':'hsepimg'},'disney':{'ott':'hs','search':_0x509bf5(0x109),'post':'/mobile/hs/post.php','episodes':_0x509bf5(0xe6),'playlist':'/mobile/hs/playlist.php','img':'hs/v','epImg':'hsepimg'}},NEW_TV_BASE_HEADERS={'Cache-Control':'no-cache,\x20no-store,\x20must-revalidate','Pragma':'no-cache','Expires':'0','X-Requested-With':_0x509bf5(0x107),'User-Agent':'Mozilla/5.0\x20(Windows\x20NT\x2010.0;\x20Win64;\x20x64;\x20rv:136.0)\x20Gecko/20100101\x20Firefox/136.0\x20/OS.GatuNewTV\x20v1.0','Accept':'application/json,\x20text/plain,\x20*/*'},NEW_TV_DOMAINS=['aHR0cHM6Ly9tb2JpbGVkZXRlY3RzLmNvbQ==',_0x509bf5(0xb7),'aHR0cHM6Ly9tb2JpZGV0ZWN0LmFydA==','aHR0cHM6Ly9tb2JpZGV0ZWN0LmNj',_0x509bf5(0xbe),'aHR0cHM6Ly9tb2JpZGV0ZWN0Lmluaw==','aHR0cHM6Ly9tb2JpZGV0ZWN0LmxpdmU=',_0x509bf5(0x104),_0x509bf5(0xc2),'aHR0cHM6Ly9tb2JpZGV0ZWN0LnNpdGU=',_0x509bf5(0xb3),'aHR0cHM6Ly9tb2JpZGV0ZWN0LnN0b3Jl',_0x509bf5(0xff),_0x509bf5(0xd4),_0x509bf5(0x105),'aHR0cHM6Ly9tb2JpZGV0ZWN0cy5hcnQ=','aHR0cHM6Ly9tb2JpZGV0ZWN0cy5jYw==',_0x509bf5(0xee),_0x509bf5(0xf8),_0x509bf5(0xfa),'aHR0cHM6Ly9tb2JpZGV0ZWN0cy5wcm8=',_0x509bf5(0x10a),_0x509bf5(0xb9),'aHR0cHM6Ly9tb2JpZGV0ZWN0cy54eXo='],resolvedApiUrl='';function safeAtob(_0x1e9010){const _0x508b8c={_0x5cc93b:0xc3,_0x2f957d:0xfc},_0x3165d0=_0x509bf5;if(typeof atob===_0x3165d0(_0x508b8c._0x5cc93b))return atob(_0x1e9010);return Buffer['from'](_0x1e9010,_0x3165d0(_0x508b8c._0x2f957d))['toString'](_0x3165d0(0xdb));}function resolveApiUrl(){const _0x14c8f7={_0x5c4956:0x110};return __async(this,null,function*(){const _0x56ebb9=_0x3a01;if(resolvedApiUrl)return resolvedApiUrl;for(const _0x419775 of NEW_TV_DOMAINS){const _0x462e6f=safeAtob(_0x419775)['replace'](/\/$/,'');try{const _0x109402=yield fetch(_0x462e6f+'/checknewtv.php',{'headers':__spreadProps(__spreadValues({},NEW_TV_BASE_HEADERS),{'User-Agent':_0x56ebb9(_0x14c8f7._0x5c4956)})}),_0x475155=yield _0x109402['json'](),_0x507ff3=_0x475155['token_hash'];if(_0x507ff3)return resolvedApiUrl=safeAtob(_0x507ff3)['reLine truncated
/**
* netmirror - Built from src/netmirror/
* Generated: 2026-09-26T18:41:31.637Z
*/
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/netmirror/constants.js
var TMDB_API_KEY = "1865f43a0549ca50d341dd9ab8b29f49";
var PLATFORM_MAP = {
netflix: {
ott: "nf",
search: "/mobile/search.php",
post: "/mobile/post.php",
episodes: "/mobile/episodes.php",
playlist: "/mobile/playlist.php",
img: "poster/v",
epImg: "epimg/150"
},
primevideo: {
ott: "pv",
search: "/mobile/pv/search.php",
post: "/mobile/pv/post.php",
episodes: "/mobile/pv/episodes.php",
playlist: "/mobile/pv/playlist.php",
img: "pv/v",
epImg: "pvepimg"
},
hotstar: {
ott: "hs",
search: "/mobile/hs/search.php",
post: "/mobile/hs/post.php",
episodes: "/mobile/hs/episodes.php",
playlist: "/mobile/hs/playlist.php",
img: "hs/v",
epImg: "hsepimg"
},
disney: {
ott: "hs",
search: "/mobile/hs/search.php",
post: "/mobile/hs/post.php",
episodes: "/mobile/hs/episodes.php",
playlist: "/mobile/hs/playlist.php",
img: "hs/v",
epImg: "hsepimg"
}
};
var BASE_HEADERS = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"Accept-Language": "en-IN,en-US;q=0.9,en;q=0.8",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"sec-ch-ua": '"Not(A:Brand";v="8", "Chromium";v="144", "Android WebView";v="144"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Android"',
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-User": "?1",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Linux; Android 13; Pixel 5 Build/TQ3A.230901.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/144.0.7559.132 Safari/537.36 /OS.Gatu v3.0",
"X-Requested-With": "XMLHttpRequest"
};
// src/netmirror/utils.js
var COOKIE_TTL = 54e6;
var VERIFY_ATTEMPTS = 7;
var VERIFY_DELAY = 1e4;
var APP_USER_AGENT = "Mozilla/5.0 (Linux; Android 12; RMX2117 Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/147.0.7727.55 Mobile Safari/537.36 /OS.Gatu v3.0";
var cookieValue = "";
var cookieTimestamp = 0;
var cookieJar = [];
var delayModeLogged = false;
function setCookieValues(headers) {
var _a, _b;
if (!headers)
return [];
if (typeof headers.getSetCookie === "function") {
try {
return headers.getSetCookie();
} catch (e) {
}
}
const raw = ((_a = headers.get) == null ? void 0 : _a.call(headers, "set-cookie")) || ((_b = headers.get) == null ? void 0 : _b.call(headers, "Set-Cookie")) || "";
return raw.split(/,(?=\s*[^;,\s]+=)/g).map((value) => value.trim()).filter(Boolean);
}
function rememberResponseCookies(headers, responseUrl) {
const host = new URL(responseUrl).hostname.toLowerCase();
for (const raw of setCookieValues(headers)) {
const pair = raw.split(";", 1)[0];
const equals = pair.indexOf("=");
if (equals <= 0)
continue;
const name = pair.slice(0, equals).trim();
const value = pair.slice(equals + 1).trim();
const domainMatch = raw.match(/(?:^|;)\s*domain=([^;]+)/i);
const domain = (domainMatch ? domainMatch[1] : host).trim().replace(/^\./, "").toLowerCase();
const index = cookieJar.findIndex((cookie2) => cookie2.name === name && cookie2.domain === domain);
if (/max-age\s*=\s*0/i.test(raw) || !value) {
if (index >= 0)
cookieJar.splice(index, 1);
continue;
}
const cookie = { name, value, domain };
if (index >= 0)
cookieJar[index] = cookie;
else
cookieJar.push(cookie);
}
}
function cookieHeaderFor(url) {
const host = new URL(url).hostname.toLowerCase();
return cookieJar.filter((cookie) => host === cookie.domain || host.endsWith(`.${cookie.domain}`)).map((cookie) => `${cookie.name}=${cookie.value}`).join("; ");
}
function request(_0) {
return __async(this, arguments, function* (url, options = {}) {
const headers = __spreadValues({}, options.headers || {});
const cookieHeader = cookieHeaderFor(url);
if (cookieHeader)
headers.Cookie = cookieHeader;
const response = yield fetch(url, __spreadProps(__spreadValues({}, options), { headers }));
rememberResponseCookies(response.headers, response.url || url);
return response;
});
}
function getCookie(name) {
var _a;
return ((_a = cookieJar.find((cookie) => cookie.name === name)) == null ? void 0 : _a.value) || "";
}
function logDelayMode(mode) {
if (delayModeLogged)
return;
delayModeLogged = true;
console.log(`[NetMirror] Delay implementation: ${mode}`);
}
function delay(ms) {
if (typeof setTimeout === "function") {
logDelayMode("setTimeout (runtime timer)");
return new Promise((resolve) => setTimeout(resolve, ms));
}
return Promise.resolve().then(() => {
if (typeof SharedArrayBuffer === "function" && typeof Atomics !== "undefined" && typeof Atomics.wait === "function") {
try {
logDelayMode("Atomics.wait fallback");
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
return;
} catch (e) {
}
}
logDelayMode("synchronous busy-wait fallback");
const deadline = Date.now() + ms;
while (Date.now() < deadline) {
}
});
}
function bypass(mainUrl) {
return __async(this, null, function* () {
var _a;
if (cookieValue && Date.now() - cookieTimestamp < COOKIE_TTL)
return cookieValue;
const base = String(mainUrl || "https://net52.cc").replace(/\/$/, "");
const homeUrl = `${base}/mobile/home?app=1`;
const appHeaders = {
"User-Agent": APP_USER_AGENT,
"X-Requested-With": "app.netmirror.netmirrornew"
};
try {
console.log("[NetMirror] Starting mobile cookie verification...");
cookieJar = [];
const homeResponse = yield request(homeUrl, { headers: appHeaders });
const homeHtml = yield homeResponse.text();
if (!homeResponse.ok)
throw new Error(`Mobile home returned HTTP ${homeResponse.status}`);
const addhash = (_a = homeHtml.match(/data-addhash\s*=\s*["']([^"']+)["']/i)) == null ? void 0 : _a[1];
if (!addhash)
throw new Error("NetMirror mobile home did not provide data-addhash");
const userverUrl = `https://userver.net52.cc/?hee5=${encodeURIComponent(addhash)}&a=y&t=${Math.random()}`;
const userverResponse = yield request(userverUrl, { headers: appHeaders });
yield userverResponse.text();
const verifyUrl = `${base}/mobile/verify2.php`;
const verifyHeaders = {
"User-Agent": APP_USER_AGENT,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded"
};
for (let attempt = 1; attempt <= VERIFY_ATTEMPTS; attempt++) {
yield delay(VERIFY_DELAY);
const response = yield request(verifyUrl, {
method: "POST",
headers: verifyHeaders,
body: `verify=${encodeURIComponent(addhash)}`
});
const text = yield response.text();
let allDone = text.includes('"statusup":"All Done"');
if (!allDone) {
try {
allDone = JSON.parse(text).statusup === "All Done";
} catch (e) {
}
}
if (!allDone) {
console.log(`[NetMirror] Cookie verification pending (attempt ${attempt}/${VERIFY_ATTEMPTS}).`);
continue;
}
const verifiedCookie = getCookie("t_hash_t");
if (!verifiedCookie)
throw new Error("Verification completed without a t_hash_t cookie");
cookieValue = verifiedCookie;
cookieTimestamp = Date.now();
console.log("[NetMirror] Mobile cookie verified.");
return cookieValue;
}
throw new Error("Mobile verification did not complete; NetMirror may be waiting for an ad click");
} catch (error) {
cookieValue = "";
cookieTimestamp = 0;
console.error("[NetMirror] Mobile cookie verification failed:", error.message);
return "";
}
});
}
// src/netmirror/index.js
function getStreams(tmdbId, mediaType, season, episode) {
return __async(this, null, function* () {
try {
const settings = globalThis.SCRAPER_SETTINGS || {};
const preferred = settings.preferredPlatform || "all";
const tmdbType = mediaType === "tv" ? "tv" : "movie";
const tmdbResp = yield fetch(`https://api.themoviedb.org/3/${tmdbType}/${tmdbId}?api_key=${TMDB_API_KEY}`, {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
"Accept": "application/json"
}
});
const tmdbData = yield tmdbResp.json();
const title = mediaType === "tv" ? tmdbData.name : tmdbData.title;
if (!title)
throw new Error("Could not fetch title from TMDB");
let platforms = ["netflix", "primevideo", "hotstar", "disney"];
if (preferred !== "all") {
platforms = [preferred, ...platforms.filter((p) => p !== preferred)];
}
for (const platformKey of platforms) {
try {
const streams = yield fetchFromPlatform(platformKey, title, mediaType, season, episode);
if (streams && streams.length > 0)
return streams;
} catch (e) {
}
}
return [];
} catch (error) {
return [];
}
});
}
function fetchFromPlatform(platformKey, title, mediaType, season, episode) {
return __async(this, null, function* () {
const platform = PLATFORM_MAP[platformKey];
return fetchMobileContent(platformKey, platform, title, mediaType, season, episode);
});
}
function fetchMobileContent(platformKey, platform, title, mediaType, season, episode) {
return __async(this, null, function* () {
var _a, _b;
const base = "https://net52.cc";
const cookie = yield bypass(base);
const settings = globalThis.SCRAPER_SETTINGS || {};
const cookies = [];
if (cookie)
cookies.push(`t_hash_t=${cookie}`);
cookies.push(`ott=${platform.ott}`);
if (settings.forceHd !== false)
cookies.push("hd=on");
const headers = __spreadProps(__spreadValues({}, BASE_HEADERS), { Cookie: cookies.join("; ") });
const getJson = (_0, ..._1) => __async(this, [_0, ..._1], function* (url, referer = `${base}/home`, extraHeaders = {}) {
const response = yield fetch(url, {
headers: __spreadValues(__spreadProps(__spreadValues({}, headers), { Referer: referer }), extraHeaders)
});
if (!response.ok)
throw new Error(`NetMirror mobile returned HTTP ${response.status}`);
return response.json();
});
const search = yield getJson(`${base}${platform.search}?s=${encodeURIComponent(title)}&t=${Math.floor(Date.now() / 1e3)}`);
const results = Array.isArray(search.searchResult) ? search.searchResult : [];
if (!results.length)
return null;
const normalize = (value) => String(value || "").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9]+/g, " ").trim();
const wanted = normalize(title);
const rank = (item) => {
const candidate = normalize(item.t || item.title);
return candidate === wanted ? 0 : candidate.includes(wanted) || wanted.includes(candidate) ? 1 : 2;
};
results.sort((a, b) => rank(a) - rank(b));
const wantedSeason = Number(season);
const wantedEpisode = Number(episode);
for (const result of results.slice(0, 8)) {
if (!result.id)
continue;
const post = yield getJson(`${base}${platform.post}?id=${encodeURIComponent(result.id)}&t=${Math.floor(Date.now() / 1e3)}`);
if (!post || post.status === "n" && post.error)
continue;
let targetId = result.id;
if (mediaType === "tv") {
if (post.type !== "t" && !(post.episodes || []).some(Boolean))
continue;
let episodeEntry = findMobileEpisode(
post.episodes,
wantedSeason,
wantedEpisode,
((_b = (_a = post.season) == null ? void 0 : _a.findIndex((s) => s.selected === true)) != null ? _b : -1) + 1
);
const seasonEntry = Array.isArray(post.season) ? post.season.find((s) => Number(String(s.s || "").replace(/\D/g, "")) === wantedSeason) : null;
if (!episodeEntry && (seasonEntry == null ? void 0 : seasonEntry.id)) {
let page = 1;
while (page <= 30) {
const url = `${base}${platform.episodes}?s=${encodeURIComponent(seasonEntry.id)}&series=${encodeURIComponent(result.id)}&t=${Math.floor(Date.now() / 1e3)}&page=${page}`;
const data = yield getJson(url);
episodeEntry = findMobileEpisode(data.episodes, wantedSeason, wantedEpisode, wantedSeason);
if (episodeEntry || !data.nextPageShow || Number(data.nextPageShow) === 0)
break;
page++;
}
}
if (!(episodeEntry == null ? void 0 : episodeEntry.id))
continue;
targetId = episodeEntry.id;
} else if (post.type === "t" || (post.episodes || []).some(Boolean)) {
continue;
}
const playlistUrl = `${base}${platform.playlist}?id=${encodeURIComponent(targetId)}&t=${encodeURIComponent(title)}&tm=${Math.floor(Date.now() / 1e3)}`;
const playlist = yield getJson(playlistUrl, `${base}/mobile/home?app=1`, {
"X-Requested-With": "app.netmirror.netmirrornew",
"Accept": "*/*",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors"
});
const entries = Array.isArray(playlist) ? playlist : playlist.playlist || playlist.data || [];
const streams = [];
for (const entry of entries) {
for (const source of entry.sources || []) {
if (!source.file)
continue;
const streamUrl = /^https?:\/\//i.test(source.file) ? source.file : source.file.startsWith("//") ? `https:${source.file}` : `${base}${source.file.startsWith("/") ? "" : "/"}${source.file}`;
const label = source.label || "Auto";
const quality = (String(label).match(/\d{3,4}p?/i) || [])[0] || (/full\s*hd/i.test(label) ? "1080p" : /mid\s*hd/i.test(label) ? "720p" : /low\s*hd/i.test(label) ? "480p" : "Auto");
const playbackHeaders = {
"Accept": "*/*",
"Accept-Language": "en-IN,en-US;q=0.9,en;q=0.8",
"Connection": "keep-alive",
"Referer": `${base}/mobile/home?app=1`,
"sec-ch-ua": '"Android WebView";v="149", "Chromium";v="149", "Not)A;Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Android"',
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Linux; Android 13; Pixel 5 Build/TQ3A.230901.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/149.0.7827.91 Safari/537.36 /OS.Gatu v3.0",
"X-Requested-With": "app.netmirror.netmirrornew"
};
if (settings.forceHd !== false)
playbackHeaders.Cookie = "hd=on";
streams.push({
name: `NetMirror (${platformKey})`,
title: mediaType === "tv" ? `${title} S${wantedSeason}E${wantedEpisode} - ${label}` : `${title} - ${label}`,
url: streamUrl,
quality,
headers: playbackHeaders
});
}
}
if (streams.length)
return streams;
}
return null;
});
}
function findMobileEpisode(episodes, season, episode, fallbackSeason) {
if (!Array.isArray(episodes))
return null;
return episodes.find((item) => {
if (!item)
return false;
const epNumber = Number(String(item.ep || "").replace(/\D/g, ""));
const seasonNumber = Number(String(item.s || item.sNum || "").replace(/\D/g, "")) || fallbackSeason;
return epNumber === episode && seasonNumber === season;
}) || null;
}
function onSettings() {
return __async(this, null, function* () {
return [
{ type: "header", label: "Source Selection" },
{
type: "select",
key: "preferredPlatform",
label: "Preferred Streaming Source",
description: "Select which platform to try first. If content isn't found, others will be searched as fallback.",
options: [
{ label: "All Sources (Ordered)", value: "all" },
{ label: "Netflix", value: "netflix" },
{ label: "Prime Video", value: "primevideo" },
{ label: "Hotstar / Disney+", value: "hotstar" }
],
defaultValue: "all"
},
{ type: "header", label: "Advanced" },
{
type: "toggle",
key: "forceHd",
label: "Force HD Quality",
description: "Attempts to force the player into HD mode when possible.",
defaultValue: true
}
];
});
}
module.exports = { getStreams, onSettings };
+683
View File
@@ -0,0 +1,683 @@
/**
* reanime - Built from src/reanime/
* Generated: 2026-09-21T13:43:14.525Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/reanime/reanime.js
var import_cheerio_without_node_native = __toESM(require("cheerio-without-node-native"));
// src/reanime/constants.js
var REANIME_DOMAINS = [
"https://reanime.to",
"https://reanime.cz",
"https://reanime.wtf"
];
var REANIME_BASE = "https://reanime.to";
var FLIXCLOUD_BASE = "https://flixcloud.cc";
var TMDB_API_KEY = "439c478a771f35c05022f9feabcca01c";
var ANILIST_URL = "https://graphql.anilist.co";
var ARM_BASE = "https://arm.haglund.dev/api/v2";
var CINEMETA_URL = "https://v3-cinemeta.strem.io/meta";
var USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
var HEADERS = {
"User-Agent": USER_AGENT,
"Accept": "application/json, text/plain, */*",
"Accept-Language": "en-US,en;q=0.9"
};
var FLIX_HEADERS = {
"User-Agent": USER_AGENT,
"Accept": "*/*",
"Origin": FLIXCLOUD_BASE,
"Referer": `${FLIXCLOUD_BASE}/`
};
// src/reanime/reanime.js
var activeBaseUrl = REANIME_BASE;
function absolutize(path, base = activeBaseUrl) {
if (!path)
return "";
if (path.startsWith("http"))
return path;
const cleanPath = path.startsWith("/") ? path : `/${path}`;
return `${base}${cleanPath}`;
}
function fetchText(_0) {
return __async(this, arguments, function* (url, options = {}) {
const isAbsolute = url.startsWith("http");
const urlsToTry = isAbsolute ? [url] : REANIME_DOMAINS.map((domain) => absolutize(url, domain));
let lastError = null;
for (const tryUrl of urlsToTry) {
try {
const response = yield fetch(tryUrl, __spreadProps(__spreadValues({}, options), {
headers: __spreadValues(__spreadValues({}, HEADERS), options.headers || {})
}));
if (response.ok) {
if (!isAbsolute) {
const match = tryUrl.match(/^(https?:\/\/[^\/]+)/);
if (match)
activeBaseUrl = match[1];
}
return yield response.text();
}
lastError = new Error(`Reanime HTTP ${response.status}: ${tryUrl}`);
} catch (e) {
lastError = e;
}
}
throw lastError || new Error(`Failed to fetch: ${url}`);
});
}
function fetchJson(_0) {
return __async(this, arguments, function* (url, options = {}) {
const text = yield fetchText(url, __spreadProps(__spreadValues({}, options), {
headers: __spreadValues({
"Accept": "application/json, text/plain, */*"
}, options.headers || {})
}));
return JSON.parse(text);
});
}
function getTmdbInfo(tmdbId, mediaType) {
return __async(this, null, function* () {
const endpoint = mediaType === "tv" ? "tv" : "movie";
const url = `https://api.themoviedb.org/3/${endpoint}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`;
try {
const data = yield fetchJson(url);
return {
title: data.name || data.title || data.original_name || data.original_title || "",
year: ((data.first_air_date || data.release_date || "").match(/\d{4}/) || [null])[0],
imdbId: data.external_ids && data.external_ids.imdb_id
};
} catch (_) {
return { title: "", year: null, imdbId: null };
}
});
}
function getAnilistInfo(alId) {
return __async(this, null, function* () {
var _a, _b, _c, _d, _e;
const query = "query($id:Int){Media(id:$id){id title{english romaji native} startDate{year}}}";
try {
const json = yield fetchJson(ANILIST_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query, variables: { id: parseInt(alId, 10) } })
});
const media = (_a = json.data) == null ? void 0 : _a.Media;
if (!media)
return { title: "", year: null };
return {
title: ((_b = media.title) == null ? void 0 : _b.english) || ((_c = media.title) == null ? void 0 : _c.romaji) || ((_d = media.title) == null ? void 0 : _d.native) || "",
year: ((_e = media.startDate) == null ? void 0 : _e.year) || null
};
} catch (_) {
return { title: "", year: null };
}
});
}
function getSyncInfo(id, mediaType, season, episode) {
return __async(this, null, function* () {
const isImdb = typeof id === "string" && id.indexOf("tt") === 0;
const getCinemetaInfo = (imdbId2) => __async(this, null, function* () {
const type = mediaType === "movie" ? "movie" : "series";
const url = `${CINEMETA_URL}/${type}/${imdbId2}.json`;
try {
const data = yield fetchJson(url);
const meta = data.meta;
if (!meta)
throw new Error("No Cinemeta metadata");
if (mediaType === "movie")
return { date: meta.released ? meta.released.split("T")[0] : null, title: meta.name, dayIndex: 1 };
const videos = meta.videos || [];
const target = videos.find((v) => v.season == season && v.episode == episode);
if (!target || !target.released)
return { date: null, title: null, dayIndex: 1 };
const targetDate = target.released.split("T")[0];
const dayIndex = videos.filter((v) => v.season == season && v.released && v.released.split("T")[0] === targetDate && parseInt(v.episode) < parseInt(episode)).length + 1;
return { date: targetDate, title: target.name || null, dayIndex };
} catch (_) {
return { date: null, title: null, dayIndex: 1 };
}
});
if (isImdb) {
const info = yield getCinemetaInfo(id);
if (info.date)
return { imdbId: id, releaseDate: info.date, episodeTitle: info.title, dayIndex: info.dayIndex, episode };
throw new Error("Could not find release date on Cinemeta");
}
const tmdbUrl = `https://api.themoviedb.org/3/${mediaType === "movie" ? "movie" : "tv"}/${id}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`;
const details = yield fetchJson(tmdbUrl);
let imdbId = details.external_ids && details.external_ids.imdb_id || details.imdb_id || null;
const title = details.name || details.title || null;
if (!imdbId) {
try {
const armData = yield fetchJson(`${ARM_BASE}/themoviedb?id=${id}`);
imdbId = Array.isArray(armData) && armData.length > 0 ? armData[0].imdb : null;
} catch (_) {
}
}
if (!imdbId)
throw new Error(`No IMDb ID found for TMDB ${id}`);
const cMeta = yield getCinemetaInfo(imdbId);
let finalDate = cMeta.date;
if (mediaType === "movie" && details.release_date)
finalDate = details.release_date;
if (!finalDate)
throw new Error(`Could not find release date for ID ${imdbId}`);
return {
imdbId,
tmdbId: id,
releaseDate: finalDate,
title,
episodeTitle: cMeta.title,
dayIndex: cMeta.dayIndex,
episode
};
});
}
function resolveByDate(releaseDateStr, showTitle, originalEpisode, episodeTitle, dayIndex) {
return __async(this, null, function* () {
var _a, _b;
if (!releaseDateStr || !/^\d{4}-\d{2}-\d{2}/.test(releaseDateStr))
return null;
const query = "query($search:String){Page(perPage:20){media(search:$search,type:ANIME){id type format title{romaji english native}startDate{year month day}endDate{year month day}episodes streamingEpisodes{title}}}}";
try {
const json = yield fetchJson(ANILIST_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query, variables: { search: showTitle } })
});
const candidates = ((_b = (_a = json.data) == null ? void 0 : _a.Page) == null ? void 0 : _b.media) || [];
if (candidates.length === 0)
return null;
const targetDate = new Date(releaseDateStr);
for (const anime of candidates) {
const s = anime.startDate;
const startStr = s.year && s.month && s.day ? `${s.year}-${String(s.month).padStart(2, "0")}-${String(s.day).padStart(2, "0")}` : null;
if (!startStr)
continue;
const startDate = new Date(startStr);
const diffDays = Math.ceil(Math.abs(targetDate.getTime() - startDate.getTime()) / (1e3 * 60 * 60 * 24));
let isMatch = false;
if (anime.format === "MOVIE" || anime.format === "SPECIAL" || anime.episodes === 1) {
if (diffDays <= 2)
isMatch = true;
} else {
const startLimit = new Date(startDate);
startLimit.setDate(startLimit.getDate() - 2);
if (targetDate >= startLimit) {
if (anime.endDate && anime.endDate.year) {
const endDate = new Date(anime.endDate.year, (anime.endDate.month || 12) - 1, anime.endDate.day || 31);
endDate.setDate(endDate.getDate() + 2);
if (targetDate <= endDate)
isMatch = true;
} else {
isMatch = true;
}
}
}
if (isMatch) {
const isTV = anime.format !== "MOVIE" && anime.format !== "SPECIAL" && anime.episodes !== 1;
let episodeNum = isTV && originalEpisode ? originalEpisode : dayIndex || 1;
const episodes = anime.streamingEpisodes || [];
if (episodes.length > 1 && episodeTitle) {
const cleanTarget = episodeTitle.toLowerCase().replace(/[^a-z0-9]/g, "");
for (let j = 0; j < episodes.length; j++) {
const cleanAl = (episodes[j].title || "").toLowerCase().replace(/[^a-z0-9]/g, "");
if (cleanAl && (cleanAl.indexOf(cleanTarget) !== -1 || cleanTarget.indexOf(cleanAl) !== -1)) {
episodeNum = j + 1;
break;
}
}
}
return { alId: anime.id, episode: episodeNum, title: anime.title.english || anime.title.romaji || anime.title.native };
}
}
} catch (_) {
}
return null;
});
}
function normalizeTitle(value) {
return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
}
function scoreCandidate(title, query, year, targetAnilistId, candidateAnilistId) {
if (targetAnilistId && candidateAnilistId && String(targetAnilistId) === String(candidateAnilistId)) {
return 1e3;
}
const a = normalizeTitle(title);
const b = normalizeTitle(query);
if (!a || !b)
return 0;
let score = 0;
if (a === b)
score += 100;
if (a.includes(b) || b.includes(a))
score += 50;
const words = b.split(/\s+/).filter(Boolean);
for (const word of words)
if (a.includes(word))
score += 4;
if (year && String(title).includes(String(year)))
score += 10;
return score;
}
function extractAnilistId(item) {
var _a, _b, _c;
const direct = item && (item.anilist_id || item.anilistId);
if (direct)
return String(direct);
const imageUrls = [
(_a = item == null ? void 0 : item.cover_image) == null ? void 0 : _a.extra_large,
(_b = item == null ? void 0 : item.cover_image) == null ? void 0 : _b.large,
(_c = item == null ? void 0 : item.cover_image) == null ? void 0 : _c.medium,
item == null ? void 0 : item.banner_image
].filter(Boolean);
for (const url of imageUrls) {
const match = String(url).match(/\/b?x?(\d+)-|\/(\d+)[-.]/);
if (match)
return match[1] || match[2];
}
return null;
}
function searchReanimeAnime(query, year, targetAnilistId = null) {
return __async(this, null, function* () {
const endpoints = [
`/api/v1/search?q=${encodeURIComponent(query)}&limit=36`,
`/api/search?q=${encodeURIComponent(query)}`
];
const candidates = [];
for (const endpoint of endpoints) {
try {
const text = yield fetchText(endpoint);
if (text.trim().startsWith("{") || text.trim().startsWith("[")) {
const json = JSON.parse(text);
const list = json.results || json.data || json.anime || (Array.isArray(json) ? json : null);
if (Array.isArray(list)) {
list.forEach((item) => {
const rawSlug = item.anime_id || item.slug || item.id || item.url;
if (rawSlug) {
const cleanSlug = String(rawSlug).replace(/-[a-z0-9]{6}$/, "");
const titles = [];
if (typeof item.title === "object" && item.title) {
if (item.title.english)
titles.push(item.title.english);
if (item.title.romaji)
titles.push(item.title.romaji);
if (item.title.native)
titles.push(item.title.native);
} else if (item.title) {
titles.push(item.title);
}
if (item.name)
titles.push(item.name);
if (titles.length === 0)
titles.push(cleanSlug);
const alId = extractAnilistId(item);
let bestScore = 0;
for (const t of titles) {
const sc = scoreCandidate(t, query, year, targetAnilistId, alId);
if (sc > bestScore)
bestScore = sc;
}
candidates.push({
slug: String(rawSlug),
cleanSlug,
title: titles[0],
anilistId: alId,
score: bestScore
});
}
});
}
}
} catch (_) {
}
if (candidates.some((c) => c.score >= 1e3))
break;
if (candidates.length > 0 && !targetAnilistId)
break;
}
const unique = [];
const seen = /* @__PURE__ */ new Set();
for (const candidate of candidates) {
if (!candidate.slug || seen.has(candidate.slug))
continue;
seen.add(candidate.slug);
unique.push(candidate);
}
unique.sort((a, b) => b.score - a.score);
return unique.length > 0 ? unique[0] : null;
});
}
function getFlixEmbeds(slug, episodeNumber, language, anilistId) {
return __async(this, null, function* () {
const watchPath = `/watch/${slug || "anime"}?ep=${episodeNumber}`;
if (anilistId) {
try {
const flixUrl = `/api/flix/${anilistId}/${episodeNumber}`;
const json = yield fetchJson(flixUrl, {
headers: { "Referer": absolutize(watchPath) }
});
if (json.success && Array.isArray(json.servers) && json.servers.length > 0) {
const filtered = language ? json.servers.filter((s) => s.dataType && s.dataType.toLowerCase() === language.toLowerCase()) : json.servers;
return {
watchUrl: absolutize(watchPath),
servers: filtered,
embeds: filtered.map((s) => s.dataLink).filter(Boolean)
};
}
} catch (_) {
}
}
if (slug) {
try {
const animeApiUrl = `/api/v1/anime/${slug}`;
const animeData = yield fetchJson(animeApiUrl);
const alId = animeData == null ? void 0 : animeData.anilist_id;
if (alId) {
const flixUrl = `/api/flix/${alId}/${episodeNumber}`;
const json = yield fetchJson(flixUrl, {
headers: { "Referer": absolutize(watchPath) }
});
if (json.success && Array.isArray(json.servers) && json.servers.length > 0) {
const filtered = language ? json.servers.filter((s) => s.dataType && s.dataType.toLowerCase() === language.toLowerCase()) : json.servers;
return {
watchUrl: absolutize(watchPath),
servers: filtered,
embeds: filtered.map((s) => s.dataLink).filter(Boolean)
};
}
}
} catch (_) {
}
try {
const html = yield fetchText(`/anime/${slug}?_ep=${episodeNumber}`);
const anilistMatch = html.match(/anilist_id:\s*(\d+)/);
if (anilistMatch) {
const alId = anilistMatch[1];
const flixUrl = `/api/flix/${alId}/${episodeNumber}`;
const json = yield fetchJson(flixUrl, {
headers: { "Referer": absolutize(watchPath) }
});
if (json.success && Array.isArray(json.servers) && json.servers.length > 0) {
const filtered = language ? json.servers.filter((s) => s.dataType && s.dataType.toLowerCase() === language.toLowerCase()) : json.servers;
return {
watchUrl: absolutize(watchPath),
servers: filtered,
embeds: filtered.map((s) => s.dataLink).filter(Boolean)
};
}
}
} catch (_) {
}
}
return { watchUrl: absolutize(watchPath), servers: [], embeds: [] };
});
}
// src/reanime/flixcloud.js
function extractFlixCloudDownload(embedUrl) {
return __async(this, null, function* () {
try {
const match = embedUrl.match(/\/e\/([a-z0-9]+)/i);
const aid = match ? match[1] : null;
if (!aid)
return null;
const dlHeaders = {
"Accept": "*/*",
"Referer": `${FLIXCLOUD_BASE}/`,
"User-Agent": USER_AGENT
};
const res = yield fetch(`${FLIXCLOUD_BASE}/d/${aid}/__data.json`, {
headers: dlHeaders
});
if (!res.ok)
return null;
const dataBody = yield res.text();
const fileIdMatch = dataBody.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);
const tokenMatch = dataBody.match(/eyJ[\w-]+\.[\w-]+\.[\w-]+/);
const baseMatch = dataBody.match(/https:\/\/[a-z0-9-]+\.flixcloud\.cc/i);
const resolutionMatch = dataBody.match(/(\d{3,4}p)/);
const sizeMatch = dataBody.match(/"(\d+(?:\.\d+)?\s*[KMG]B)"/i);
const fileId = fileIdMatch ? fileIdMatch[0] : null;
const token = tokenMatch ? tokenMatch[0] : null;
const base = baseMatch ? baseMatch[0] : FLIXCLOUD_BASE;
const resolution = resolutionMatch ? resolutionMatch[1] : null;
const size = sizeMatch ? sizeMatch[1] : "Unknown";
if (!fileId || !token)
return null;
let ready = false;
try {
const progRes = yield fetch(`${base}/download/${fileId}/progress?token=${token}`, {
headers: dlHeaders
});
if (progRes.ok) {
const text = yield progRes.text();
if (text.includes('"status":"ready"') || text.includes('"ready"')) {
ready = true;
}
}
} catch (_) {
}
const fileUrl = `${base}/download/${fileId}?token=${token}`;
return {
url: fileUrl,
quality: resolution || "1080p",
size,
type: "mkv",
headers: dlHeaders,
ready
};
} catch (_) {
return null;
}
});
}
// src/reanime/index.js
function getStreams(tmdbId, mediaType = "tv", season = null, episode = null) {
return __async(this, null, function* () {
try {
if (mediaType !== "tv" && mediaType !== "movie")
return [];
let alId = null;
let episodeNumber = mediaType === "tv" ? Number(episode || 1) : 1;
let searchTitle = "";
let searchYear = null;
if (typeof tmdbId === "string" && tmdbId.indexOf("anilist:") === 0) {
alId = tmdbId.split(":")[1];
} else {
try {
const syncInfo = yield getSyncInfo(tmdbId, mediaType, season, episodeNumber);
searchTitle = syncInfo.title;
if (syncInfo.releaseDate) {
searchYear = syncInfo.releaseDate.substring(0, 4);
}
const syncResult = yield resolveByDate(syncInfo.releaseDate, syncInfo.title, episodeNumber, syncInfo.episodeTitle, syncInfo.dayIndex);
if (syncResult && syncResult.alId) {
alId = String(syncResult.alId);
episodeNumber = syncResult.episode;
searchTitle = syncResult.title;
}
} catch (_) {
}
if (!searchTitle || !searchYear) {
try {
const tmdb = yield getTmdbInfo(tmdbId, mediaType);
if (!searchTitle)
searchTitle = tmdb.title;
if (!searchYear)
searchYear = tmdb.year;
} catch (_) {
}
}
}
const serversByLang = {};
let watchUrl = "";
if (alId) {
for (const lang of ["sub", "dub"]) {
try {
const res = yield getFlixEmbeds(null, episodeNumber, lang, alId);
if (res.servers && res.servers.length > 0) {
serversByLang[lang] = res.servers;
if (res.watchUrl)
watchUrl = res.watchUrl;
}
} catch (_) {
}
}
}
if (Object.keys(serversByLang).length === 0) {
if (!searchTitle && alId) {
const alInfo = yield getAnilistInfo(alId);
searchTitle = alInfo.title;
searchYear = alInfo.year;
}
if (searchTitle) {
const anime = yield searchReanimeAnime(searchTitle, searchYear, alId);
if (anime) {
const slug = anime.slug;
const finalAlId = alId || anime.anilistId;
for (const lang of ["sub", "dub"]) {
try {
const res = yield getFlixEmbeds(slug, episodeNumber, lang, finalAlId);
if (res.servers && res.servers.length > 0) {
serversByLang[lang] = res.servers;
if (res.watchUrl)
watchUrl = res.watchUrl;
}
} catch (_) {
}
}
}
}
}
if (Object.keys(serversByLang).length === 0)
return [];
const streams = [];
const seen = /* @__PURE__ */ new Set();
const tasks = [];
for (const language of ["sub", "dub"]) {
const serverList = serversByLang[language] || [];
for (let i = 0; i < serverList.length; i++) {
const server = serverList[i];
const dataLink = server.dataLink;
if (!dataLink)
continue;
const serverName = server.serverName || `HD-${i + 1}`;
const langUpper = language.toUpperCase();
const displayTitle = searchTitle || "Anime";
const streamTitle = mediaType === "movie" ? `${displayTitle} (${langUpper})` : `${displayTitle} - Episode ${episodeNumber} (${langUpper})`;
tasks.push((() => __async(this, null, function* () {
try {
const directDl = yield extractFlixCloudDownload(dataLink);
if (directDl && directDl.url) {
return {
name: `Reanime [${langUpper}] ${serverName} (${directDl.quality || "1080p"})`,
title: streamTitle,
url: directDl.url,
quality: directDl.quality || "1080p",
size: directDl.size || "Unknown",
headers: directDl.headers,
provider: "reanime",
type: "mkv"
};
}
} catch (_) {
}
return null;
}))());
}
}
const results = yield Promise.all(tasks);
for (const res of results) {
if (res && res.url && !seen.has(res.name)) {
seen.add(res.name);
streams.push(res);
}
}
const qualityRank = {
"auto": 4e3,
"adaptive": 4e3,
"2160p": 2160,
"4k": 2160,
"1080p": 1080,
"720p": 720,
"480p": 480,
"360p": 360,
"unknown": 0
};
streams.sort((a, b) => {
var _a, _b;
const qa = qualityRank[(_a = a.quality) == null ? void 0 : _a.toLowerCase()] || 0;
const qb = qualityRank[(_b = b.quality) == null ? void 0 : _b.toLowerCase()] || 0;
return qb - qa;
});
return streams;
} catch (error) {
console.error(`[Reanime] Error: ${error.message}`);
return [];
}
});
}
module.exports = { getStreams };
+471 -1
View File
@@ -1 +1,471 @@
const _0x66bb91=_0x43c8;function _0x3b55(){const _0x48983d=['mJe2ma','Dgv4Dc9ODg1SlgfWCgXPy2f0Aw9Ul3HODg1Sk3HTBcXHChbSAwnHDgLVBI94BwW7Ct0WlJKSAw1Hz2uVyxzPzIXPBwfNzs93zwjWlcOVkJTXptaUoa','CMvZB2X2zq','DxjS','otm1mtG0CwvzwhHM','ue9tva','xhmQpvXZkIHBiIDDksHBxhnCu10QpYLCmq','mtmZndbxr3vYrfe','Ag9ZDg5HBwu','BwfW','Dgv4Da','BgfIzwW','EwvHCG','zw5KC1DPDgG','DMLKzw8VEc1TyxrYB3nRyq','ywXS','vuHetw92AwvZ','DMfSDwu','8j+tPIbtAxPLifvUA25VD24','lZ9Zpq','8j+AGcaXmdGWCa','Bw92Awu','CMvSzwfZzv9KyxrL','mZC1mZeXBvzMtw5I','sfruuca','ntK1shDtAfPs','BwvZC2fNzq','Bwf0y2G','Bg9N','DwHKBw92AwvZ','lMDVB2DSzxzPzgvVlMnVBq','ihWG','mtG2nwy0m2eWntq5y2e1mgqZndfKzdLHyJHImJLMndK','AhjLzG','AM9PBG','mty4otiZmJvtC29NweO','zMLSDgvY','w1vire1VDMLLC10GrxjYB3i6ia','Ag9ZDa','lNiYlMrLDG','BgvUz3rO','BgfUz3vHz2u','w1vire1VDMLLC10GvgHLigrVD25SB2fKigDHDgv3yxKGCMvQzwn0zwqGywXSihjLCxvLC3rZigLUihrOAxmGCNvUDgLTzq','C29Tzq','AgKG4OcIigvU','l21VDMLLlW','ywn0Aw9U','C3rHCNrZv2L0Aa','zM9SBg93','C3rHDhvZ','ihjLBgvHC2uOCYK','Aw5JBhvKzxm','zMLUza','Ahr0Chm6lY91AgrTB3zPzxmUCgLUAW','nJiWnJm0y1POy1HH','tw96AwXSys81lJaGkfDPBMrVD3mGtLqGmtaUmdSGv2LUnJq7ihG2ncKGqxbWBgvxzwjlAxqVntm3lJm2icHlsfrntcWGBgLRzsbhzwnRBYKGq2HYB21LlZe0os4WlJaUmcbtywzHCMKVntm3lJm2','Dg9vChbLCKnHC2u','w1vire1VDMLLC10GrM91BMqG','BMfTzq','C2nVCMu','mJe2mha','C3bSAxq','Dg9mB3DLCKnHC2u','nZqXmtq4vLjTAxbo','DgHLBG','yxbWBgLJyxrPB24VEc13D3CTzM9YBs11CMXLBMnVzgvK','B3jPz2LUywXFDgL0Bgu','CMvWBgfJzq','DgL0Bgu','w1vire1VDMLLC10Gtg9VA2LUzYb1CcbTB3zPzsa','mJm3nJH2tgXpDKK','CxvHBgL0Eq','mZCWu2XvDhDm','yxbWBhK','zMLLBgrZ','DgvZDa','w1vire1VDMLLC10GuMvSzwfZzsb1BMf2ywLSywjSztOG','C2L6zq','zM9YrwfJAa','zw4TvvmSzw47Ct0WlJK','8j+mNYaYmtyWCa','DhjPBq','ChvZAa','BMv4Da','vuHetw92AwvZihWG','lNiYlMnSB3vKzMXHCMvZDg9YywDLlMnVBq','8j+xO++4JYbftG','C29YDa','x3DWx2H0DhaY','zxjYB3i','y29Uy2f0'];_0x3b55=function(){return _0x48983d;};return _0x3b55();}(function(_0x178908,_0x50b0b){const _0x26d30e={_0xb00419:0x150,_0x2dd291:0x11d,_0xba6525:0x13d,_0x2996d1:0x140,_0x30c3dd:0x152,_0x515552:0x124,_0x337785:0x15c},_0x46581c=_0x43c8,_0xe5371d=_0x178908();while(!![]){try{const _0x144a3b=-parseInt(_0x46581c(_0x26d30e._0xb00419))/0x1+-parseInt(_0x46581c(_0x26d30e._0x2dd291))/0x2+-parseInt(_0x46581c(_0x26d30e._0xba6525))/0x3+parseInt(_0x46581c(_0x26d30e._0x2996d1))/0x4*(-parseInt(_0x46581c(0x126))/0x5)+-parseInt(_0x46581c(0x114))/0x6+-parseInt(_0x46581c(_0x26d30e._0x30c3dd))/0x7*(parseInt(_0x46581c(_0x26d30e._0x515552))/0x8)+parseInt(_0x46581c(_0x26d30e._0x337785))/0x9;if(_0x144a3b===_0x50b0b)break;else _0xe5371d['push'](_0xe5371d['shift']());}catch(_0x36f3a9){_0xe5371d['push'](_0xe5371d['shift']());}}}(_0x3b55,0x34de4));var __async=(_0x5ede2d,_0x1e1c5d,_0x28b562)=>{const _0x30fbc3={_0x10354e:0x127};return new Promise((_0x4d75eb,_0x10cd35)=>{const _0x4b0345={_0x18a63f:0x131},_0x420663=_0x43c8;var _0x5924b8=_0x55ded8=>{const _0x1b2e21=_0x43c8;try{_0x5493d3(_0x28b562[_0x1b2e21(_0x4b0345._0x18a63f)](_0x55ded8));}catch(_0x420b0f){_0x10cd35(_0x420b0f);}},_0x365cb5=_0x281ba4=>{try{_0x5493d3(_0x28b562['throw'](_0x281ba4));}catch(_0x104167){_0x10cd35(_0x104167);}},_0x5493d3=_0x53dcfe=>_0x53dcfe['done']?_0x4d75eb(_0x53dcfe[_0x420663(0x14a)]):Promise[_0x420663(0x13b)](_0x53dcfe['value'])[_0x420663(0x11e)](_0x5924b8,_0x365cb5);_0x5493d3((_0x28b562=_0x28b562[_0x420663(_0x30fbc3._0x10354e)](_0x5ede2d,_0x1e1c5d))['next']());});};function getInvertedSortTag(_0x355ccf,_0x490fa2=0xf423f){const _0x4c97db={_0x5eb94f:0x142},_0x141413=_0x43c8,_0xfacf2=Math['max'](0x0,parseInt(_0x355ccf,0xa)||0x0),_0x456685=Math['max'](0x0,_0x490fa2-_0xfacf2),_0x39d79c=_0x456685['toString'](0x2)['padStart'](0x14,'0');return _0x39d79c[_0x141413(0x11b)]('')[_0x141413(_0x4c97db._0x5eb94f)](_0xdb05b1=>_0xdb05b1==='1'?'\ufeff':'​')[_0x141413(0x15b)]('');}var BASE_URLS=['https://uhdmovies.autos',_0x66bb91(0x113)],DOMAINS_URL='https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json',TMDB_URL='https://api.themoviedb.org/3',TMDB_API_KEY=_0x66bb91(0x159),USER_AGENT=_0x66bb91(0x115),HEADERS={'User-Agent':USER_AGENT,'Accept':_0x66bb91(0x13a),'Accept-Language':_0x66bb91(0x12d)};function fetchText(_0x5be7be,_0x713b13){return __async(this,null,function*(){const _0x192fa5=_0x43c8,_0x5c72a3=yield fetch(_0x5be7be,_0x713b13);if(!_0x5c72a3['ok'])throw new Error(_0x192fa5(0x151)+_0x5c72a3['status']);return _0x5c72a3['text']();});}function getOrigin(_0x290d55){const _0x15704f={_0x58190d:0x15f},_0x148962=_0x66bb91;try{const _0xc92105=new URL(_0x290d55);return _0xc92105['protocol']+'//'+_0xc92105[_0x148962(_0x15704f._0x58190d)];}catch(_0x34d978){return'';}}function absoluteUrl(_0x264015,_0x4e2c79){if(!_0x264015)return'';try{return new URL(decodeHtml(_0x264015),_0x4e2c79)['toString']();}catch(_0x2946a5){return'';}}function isDirectVideo(_0xe14265){const _0x1da15f={_0x223e4a:0x141,_0x4e2f63:0x133},_0x48c672=_0x66bb91;try{const _0x428522=new URL(_0xe14265)[_0x48c672(_0x1da15f._0x223e4a)][_0x48c672(0x11c)]();return _0x428522[_0x48c672(0x146)]('.workers.dev')||_0x428522['endsWith'Line truncated
/**
* uhdmovies - Built from src/uhdmovies/
* Generated: 2026-09-28T09:06:23.265Z
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/uhdmovies/index.js
var import_cheerio_without_node_native2 = __toESM(require("cheerio-without-node-native"));
// src/uhdmovies/constants.js
var DOMAINS_URL = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json";
var FALLBACK_DOMAIN = "https://uhdmovies.my";
var TMDB_API_KEY = "1865f43a0549ca50d341dd9ab8b29f49";
var TMDB_BASE_URL = "https://api.themoviedb.org/3";
var HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1"
};
// src/uhdmovies/utils.js
var import_cheerio_without_node_native = __toESM(require("cheerio-without-node-native"));
var cachedDomain = "";
function getMainUrl() {
return __async(this, null, function* () {
if (cachedDomain)
return cachedDomain;
try {
const response = yield fetch(DOMAINS_URL, { headers: { "User-Agent": "Mozilla/5.0" } });
const data = yield response.json();
cachedDomain = String(data["UHDMovies"] || FALLBACK_DOMAIN).replace(/\/$/, "");
return cachedDomain;
} catch (e) {
return FALLBACK_DOMAIN;
}
});
}
function getBaseUrl(url) {
try {
const urlObj = new URL(url);
return `${urlObj.protocol}//${urlObj.host}`;
} catch (e) {
return "";
}
}
function fixUrl(url, domain) {
if (!url)
return "";
if (url.startsWith("http"))
return url;
if (url.startsWith("//"))
return `https:${url}`;
if (url.startsWith("/"))
return domain + url;
return `${domain}/${url}`;
}
function bypassHrefli(url) {
return __async(this, null, function* () {
var _a, _b, _c, _d;
const host = getBaseUrl(url);
const cookies = /* @__PURE__ */ new Map();
function absorbCookies(response) {
var _a2, _b2;
let setCookie = "";
try {
const allCookies = (_b2 = (_a2 = response.headers).getSetCookie) == null ? void 0 : _b2.call(_a2);
if (Array.isArray(allCookies))
setCookie = allCookies.join("\n");
} catch (_) {
}
if (!setCookie)
setCookie = response.headers.get("set-cookie") || "";
for (const item of setCookie.split(/\n|,(?=[^;,]+=)/)) {
const pair = item.split(";")[0].trim();
const separator = pair.indexOf("=");
if (separator <= 0)
continue;
const name = pair.slice(0, separator).trim();
const value = pair.slice(separator + 1).trim();
if (!value || value.toLowerCase() === "deleted")
cookies.delete(name);
else
cookies.set(name, value);
}
}
function cookieHeader(extra = {}) {
const values = new Map(cookies);
for (const [name, value] of Object.entries(extra)) {
if (value)
values.set(name, value);
}
return Array.from(values, ([name, value]) => `${name}=${value}`).join("; ");
}
function request(_0) {
return __async(this, arguments, function* (requestUrl, options = {}) {
const headers = __spreadValues(__spreadValues({}, HEADERS), options.headers || {});
const cookie = cookieHeader();
if (cookie)
headers.Cookie = cookie;
const response = yield fetch(requestUrl, __spreadProps(__spreadValues({}, options), { headers }));
absorbCookies(response);
return response;
});
}
try {
let currentUrl = url;
let response = yield request(currentUrl);
let html = yield response.text();
let lastFormData = {};
for (let step = 0; step < 5; step++) {
const $2 = import_cheerio_without_node_native.default.load(html);
const form = $2("form#landing").first();
const action = form.attr("action");
if (!action)
break;
const formData = {};
form.find("input[name]").each((_, el) => {
const name = $2(el).attr("name");
if (name)
formData[name] = $2(el).attr("value") || "";
});
if (Object.keys(formData).length === 0)
break;
lastFormData = formData;
currentUrl = new URL(action, currentUrl).toString();
response = yield request(currentUrl, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Referer": response.url || currentUrl
},
body: new URLSearchParams(formData).toString()
});
html = yield response.text();
if (!import_cheerio_without_node_native.default.load(html)("form#landing").length)
break;
}
const $ = import_cheerio_without_node_native.default.load(html);
let redirectUrl = $("meta[http-equiv='refresh']").attr("content") || "";
redirectUrl = ((_a = redirectUrl.match(/url\s*=\s*['\"]?([^'\";]+)/i)) == null ? void 0 : _a[1]) || "";
if (!redirectUrl) {
const goMatch = html.match(/[?&]go=([^"'&\s]+)/i);
if (goMatch) {
const skToken = decodeURIComponent(goMatch[1]);
const wpHttp2 = lastFormData._wp_http2 || "";
if (wpHttp2)
cookies.set(skToken, wpHttp2);
response = yield request(`${host}?go=${encodeURIComponent(skToken)}`);
html = yield response.text();
const $go = import_cheerio_without_node_native.default.load(html);
redirectUrl = $go("meta[http-equiv='refresh']").attr("content") || "";
redirectUrl = ((_b = redirectUrl.match(/url\s*=\s*['\"]?([^'\";]+)/i)) == null ? void 0 : _b[1]) || "";
}
}
if (!redirectUrl) {
redirectUrl = ((_c = html.match(/(?:location(?:\.href)?\s*=|replace\()\s*['\"]([^'\"]+)['\"]/i)) == null ? void 0 : _c[1]) || "";
}
if (!redirectUrl)
return null;
const driveUrl = new URL(redirectUrl.trim(), response.url || currentUrl).toString();
const driveRes = yield request(driveUrl);
const driveHtml = yield driveRes.text();
const path = (_d = driveHtml.match(/replace\(\s*['\"]([^'\"]+)['\"]\s*\)/i)) == null ? void 0 : _d[1];
if (!path || path === "/404")
return null;
return new URL(path, driveRes.url || driveUrl).toString();
} catch (e) {
console.log("[UHDMovies] Hrefli bypass failed:", e.message);
return null;
}
});
}
function fetchTmdbDetails(tmdbId, mediaType) {
return __async(this, null, function* () {
var _a;
try {
const url = `${TMDB_BASE_URL}/${mediaType}/${tmdbId}?api_key=${TMDB_API_KEY}&append_to_response=external_ids`;
const res = yield fetch(url, {
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "application/json"
}
});
if (!res.ok)
return null;
const data = yield res.json();
return {
title: mediaType === "movie" ? data.title || data.original_title : data.name || data.original_name,
originalTitle: mediaType === "movie" ? data.original_title : data.original_name,
year: (data.release_date || data.first_air_date || "").substring(0, 4),
imdbId: (_a = data.external_ids) == null ? void 0 : _a.imdb_id
};
} catch (e) {
return null;
}
});
}
function getIndexQuality(str) {
if (!str)
return "Unknown";
const match = str.match(/(\d{3,4})[pP]/);
if (match)
return match[1] + "p";
if (str.toUpperCase().includes("4K") || str.toUpperCase().includes("UHD"))
return "2160p";
return "Unknown";
}
function extractVideoSeed(finallink) {
return __async(this, null, function* () {
try {
const urlObj = new URL(finallink);
const host = urlObj.host || "video-seed.xyz";
const token = finallink.split("?url=")[1];
if (!token)
return null;
const res = yield fetch(`https://${host}/api`, {
method: "POST",
headers: __spreadProps(__spreadValues({}, HEADERS), {
"Content-Type": "application/x-www-form-urlencoded",
"x-token": host,
"Referer": finallink
}),
body: `keys=${encodeURIComponent(token)}`
});
const text = yield res.text();
const urlMatch = text.match(/url":"([^"]+)"/);
return urlMatch ? urlMatch[1].replace(/\\\//g, "/") : null;
} catch (e) {
return null;
}
});
}
function extractDriveseedPage(url) {
return __async(this, null, function* () {
const streams = [];
try {
let pageUrl = url;
if (url.includes("r?key=")) {
const res2 = yield fetch(url, { headers: HEADERS });
const html2 = yield res2.text();
const redirectMatch = html2.match(/replace\("([^"]+)"\)/);
if (redirectMatch) {
pageUrl = fixUrl(redirectMatch[1], getBaseUrl(url));
}
}
const res = yield fetch(pageUrl, { headers: HEADERS });
const html = yield res.text();
const $ = import_cheerio_without_node_native.default.load(html);
const baseDomain = getBaseUrl(pageUrl);
const qualityText = $("li.list-group-item").first().text() || "";
const size = $("li:nth-child(3)").text().replace("Size : ", "").trim();
const quality = getIndexQuality(qualityText);
const elements = $("div.text-center > a").get();
for (const el of elements) {
const text = $(el).text().toLowerCase();
const href = $(el).attr("href");
if (!href)
continue;
if (text.includes("instant download")) {
const instantRes = yield fetch(fixUrl(href, baseDomain), { headers: HEADERS, redirect: "follow" });
if (instantRes.url && instantRes.url.includes("url=")) {
streams.push({ name: "Driveseed Instant", url: instantRes.url.split("url=")[1], quality, size });
}
} else if (text.includes("resume cloud")) {
const cloudRes = yield fetch(fixUrl(href, baseDomain), { headers: HEADERS });
const cloudHtml = yield cloudRes.text();
const link = import_cheerio_without_node_native.default.load(cloudHtml)("a.btn-success").first().attr("href");
if (link)
streams.push({ name: "Driveseed Cloud", url: link, quality, size });
} else if (text.includes("cloud download")) {
streams.push({ name: "Driveseed Cloud", url: fixUrl(href, baseDomain), quality, size });
}
}
} catch (e) {
}
return streams;
});
}
// src/uhdmovies/index.js
function normalizeTitle(value) {
return String(value || "").toLowerCase().replace(/\[[^\]]*\]|\([^)]*\)/g, " ").replace(/[^a-z0-9]+/g, " ").trim().replace(/\s+/g, " ");
}
function getStreams(tmdbId, mediaType, seasonNum = 1, episodeNum = 1) {
return __async(this, null, function* () {
console.log(`[UHDMovies] Querying streams for TMDB: ${tmdbId}, Type: ${mediaType}`);
const details = yield fetchTmdbDetails(tmdbId, mediaType);
if (!details)
return [];
const mainUrl = yield getMainUrl();
try {
let targetUrl = "";
const searchTitles = [...new Set([details.title, details.originalTitle].filter(Boolean))];
for (const query of searchTitles) {
const searchUrl = `${mainUrl}/?s=${encodeURIComponent(query)}`;
const searchRes = yield fetch(searchUrl, { headers: __spreadProps(__spreadValues({}, HEADERS), { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }) });
if (!searchRes.ok)
continue;
const $search = import_cheerio_without_node_native2.default.load(yield searchRes.text());
const normalizedSearchTitle = normalizeTitle(query);
$search("article.gridlove-post, article.latestPost").each((i, el) => {
const title = $search(el).find("h1.sanket, h2.title a").text() || $search(el).find("a").attr("title") || "";
const href = $search(el).find("div.entry-image > a, h2.title a, a").first().attr("href");
const normalizedResultTitle = normalizeTitle(title);
const titleMatches = normalizedResultTitle && normalizedSearchTitle && (normalizedResultTitle === normalizedSearchTitle || normalizedResultTitle.includes(normalizedSearchTitle) || normalizedSearchTitle.includes(normalizedResultTitle));
const imdbMatches = details.imdbId && title.includes(details.imdbId);
if (href && (titleMatches || imdbMatches)) {
targetUrl = href;
return false;
}
});
if (targetUrl)
break;
}
if (!targetUrl) {
console.log("[UHDMovies] No search result found");
return [];
}
const pageRes = yield fetch(targetUrl, { headers: __spreadProps(__spreadValues({}, HEADERS), { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }) });
const pageHtml = yield pageRes.text();
const $ = import_cheerio_without_node_native2.default.load(pageHtml);
const allStreams = [];
if (mediaType === "movie") {
const iframeRegex = /\[.*\]/;
$("div.entry-content > p, div.entry-content > div").each((i, el) => {
const text = $(el).text();
if (iframeRegex.test(text)) {
const quality = getIndexQuality(text);
const nextHref = $(el).next().find("a.maxbutton-1, a.maxbutton").attr("href") || $(el).find("a.maxbutton-1, a.maxbutton").attr("href");
if (nextHref) {
allStreams.push({ url: nextHref, quality });
}
}
});
} else {
const episodesMap = {};
let currentSeason = seasonNum;
$("pre, p, a, h3").each((i, el) => {
const text = $(el).text().trim();
const seasonMatch = text.match(/(?:season\s*|S)(\d+)/i);
if (seasonMatch && text.length < 20) {
currentSeason = parseInt(seasonMatch[1]);
}
if (($(el).is("a") || $(el).find("a").length > 0) && text.toLowerCase().includes("episode")) {
if (text.toLowerCase().includes("zip"))
return;
const epMatch = text.match(/Episode\s*(\d+)/i);
if (epMatch) {
const realEp = parseInt(epMatch[1]);
const epUrl = $(el).is("a") ? $(el).attr("href") : $(el).find("a").attr("href");
if (epUrl) {
const key = `${currentSeason}-${realEp}`;
if (!episodesMap[key])
episodesMap[key] = [];
episodesMap[key].push(epUrl);
}
}
}
});
const targetKey = `${seasonNum}-${episodeNum}`;
const urls = episodesMap[targetKey] || [];
urls.forEach((url) => {
allStreams.push({ url, quality: "Unknown" });
});
}
const finalResults = [];
for (const item of allStreams) {
let finalLink = item.url;
if (finalLink.includes("unblockedgames")) {
finalLink = yield bypassHrefli(finalLink);
}
if (finalLink) {
if (finalLink.includes("driveseed") || finalLink.includes("driveleech")) {
const streams = yield extractDriveseedPage(finalLink);
finalResults.push(...streams.map((s) => __spreadProps(__spreadValues({}, s), {
name: "UHDMovies [Driveseed]",
title: `UHDMovies - ${s.quality} ${s.size ? `[${s.size}]` : ""}`,
quality: s.quality || item.quality,
provider: "uhdmovies"
})));
} else if (finalLink.includes("video-seed")) {
const streamUrl = yield extractVideoSeed(finalLink);
if (streamUrl) {
finalResults.push({
name: "UHDMovies [VideoSeed]",
title: `UHDMovies - ${item.quality}`,
url: streamUrl,
quality: item.quality,
provider: "uhdmovies"
});
}
} else {
finalResults.push({
name: "UHDMovies",
title: `UHDMovies - ${item.quality}`,
url: finalLink,
quality: item.quality,
provider: "uhdmovies"
});
}
}
}
return finalResults;
} catch (e) {
console.error("[UHDMovies] Error:", e.message);
return [];
}
});
}
module.exports = { getStreams };
-492
View File
@@ -1,492 +0,0 @@
const spec = {
openapi: '3.0.3',
info: {
title: 'bug.tv api',
version: '1.0.0'
},
tags: [
{ name: 'meta', description: 'service and provider metadata' },
{ name: 'search', description: 'TMDB search and episode browsing' },
{ name: 'details', description: 'TMDB media details' },
{ name: 'streams', description: 'm3u8 stream lookup from providers' },
],
paths: {
'/providers': {
get: {
tags: ['meta'],
summary: 'List all providers and which are enabled',
operationId: 'listProviders',
responses: {
200: {
description: 'provider list',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
all: { type: 'array', items: { type: 'string' } },
enabled: { type: 'array', items: { type: 'string' } },
},
},
},
},
},
},
},
},
'/proxy/media': {
get: {
tags: ['meta'],
summary: 'Proxy upstream media or m3u8 playlists with server-side headers',
operationId: 'proxyMedia',
parameters: [
{
name: 'url',
in: 'query',
required: true,
schema: { type: 'string' },
},
{
name: 'h',
in: 'query',
required: false,
description: 'JSON-encoded headers to send to the upstream URL',
schema: { type: 'string' },
},
],
responses: {
200: {
description: 'Proxied upstream response. m3u8 playlist URIs are rewritten to use the proxy.',
},
400: { $ref: '#/components/responses/BadRequest' },
502: { $ref: '#/components/responses/Upstream' },
},
},
},
'/search': {
get: {
tags: ['search'],
summary: 'Search movies + TV via TMDB',
operationId: 'search',
parameters: [
{
name: 'q',
in: 'query',
required: true,
description: 'search text',
schema: { type: 'string' },
example: 'dune',
},
],
responses: {
200: {
description: 'up to 15 results',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
query: { type: 'string' },
count: { type: 'integer' },
results: { type: 'array', items: { $ref: '#/components/schemas/SearchResult' } },
},
},
},
},
},
400: { $ref: '#/components/responses/BadRequest' },
502: { $ref: '#/components/responses/Upstream' },
},
},
},
'/trending': {
get: {
tags: ['search'],
summary: 'Trending movies and TV via TMDB',
operationId: 'getTrending',
parameters: [
{
name: 'type',
in: 'query',
required: false,
schema: { type: 'string', enum: ['all', 'movie', 'tv'], default: 'all' },
},
{
name: 'window',
in: 'query',
required: false,
schema: { type: 'string', enum: ['day', 'week'], default: 'week' },
},
],
responses: {
200: {
description: 'up to 20 trending items',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
type: { type: 'string' },
window: { type: 'string' },
count: { type: 'integer' },
results: { type: 'array', items: { $ref: '#/components/schemas/SearchResult' } },
},
},
},
},
},
400: { $ref: '#/components/responses/BadRequest' },
502: { $ref: '#/components/responses/Upstream' },
},
},
},
'/movie/{id}': {
get: {
tags: ['details'],
summary: 'Movie details (genres, rating, images, description)',
description: 'Passes through the raw TMDB movie object, plus `poster_url`/`backdrop_url` convenience fields.',
operationId: 'getMovieDetails',
parameters: [{ $ref: '#/components/parameters/MovieId' }],
responses: {
200: {
description: 'TMDB movie object',
content: { 'application/json': { schema: { $ref: '#/components/schemas/MediaDetails' } } },
},
404: { $ref: '#/components/responses/NotFound' },
502: { $ref: '#/components/responses/Upstream' },
},
},
},
'/tv/{id}': {
get: {
tags: ['details'],
summary: 'TV show details (genres, rating, images, description)',
description: 'Passes through the raw TMDB tv object, plus `poster_url`/`backdrop_url` convenience fields.',
operationId: 'getTvDetails',
parameters: [{ $ref: '#/components/parameters/TvId' }],
responses: {
200: {
description: 'TMDB tv object',
content: { 'application/json': { schema: { $ref: '#/components/schemas/MediaDetails' } } },
},
404: { $ref: '#/components/responses/NotFound' },
502: { $ref: '#/components/responses/Upstream' },
},
},
},
'/tv/{id}/seasons': {
get: {
tags: ['search'],
summary: 'List seasons for a TV show',
operationId: 'getSeasons',
parameters: [{ $ref: '#/components/parameters/TvId' }],
responses: {
200: {
description: 'season list',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
tmdb_id: { type: 'string' },
count: { type: 'integer' },
seasons: { type: 'array', items: { $ref: '#/components/schemas/Season' } },
},
},
},
},
},
400: { $ref: '#/components/responses/BadRequest' },
502: { $ref: '#/components/responses/Upstream' },
},
},
},
'/tv/{id}/seasons/{season}': {
get: {
tags: ['search'],
summary: 'List episodes for a season',
operationId: 'getEpisodes',
parameters: [
{ $ref: '#/components/parameters/TvId' },
{
name: 'season',
in: 'path',
required: true,
description: 'season number',
schema: { type: 'integer' },
example: 1,
},
],
responses: {
200: {
description: 'episode list',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
tmdb_id: { type: 'string' },
season: { type: 'integer' },
count: { type: 'integer' },
episodes: { type: 'array', items: { $ref: '#/components/schemas/Episode' } },
},
},
},
},
},
400: { $ref: '#/components/responses/BadRequest' },
502: { $ref: '#/components/responses/Upstream' },
},
},
},
'/streams': {
get: {
tags: ['streams'],
summary: 'Fetch m3u8 streams for a movie or TV episode',
operationId: 'getStreams',
description:
'Scrapes every enabled provider in parallel (override with `providers`) and returns deduped, normalized, quality-ranked streams. ' +
'For `type=tv` you must pass `season` and `episode`. Optional filters are applied before ranking.',
parameters: [
{
name: 'tmdb',
in: 'query',
required: true,
description: 'TMDB numeric id',
schema: { type: 'integer' },
example: 438631,
},
{
name: 'type',
in: 'query',
required: false,
description: 'movie (default) or tv',
schema: { type: 'string', enum: ['movie', 'tv'], default: 'movie' },
},
{
name: 'season',
in: 'query',
required: false,
description: 'season number (required when type=tv)',
schema: { type: 'integer' },
},
{
name: 'episode',
in: 'query',
required: false,
description: 'episode number (required when type=tv)',
schema: { type: 'integer' },
},
{
name: 'providers',
in: 'query',
required: false,
description: 'comma-separated provider names; defaults to the enabled set',
schema: { type: 'string' },
example: 'videasy,vidfast',
},
{
name: 'minQuality',
in: 'query',
required: false,
schema: { type: 'string', enum: ['any', '480', '720', '1080', '2160'], default: 'any' },
},
{
name: 'audioCodec',
in: 'query',
required: false,
schema: { type: 'string', enum: ['any', 'aac', 'ac3', 'dts', 'opus', 'mp3', 'flac'], default: 'any' },
},
{
name: 'subtitles',
in: 'query',
required: false,
schema: { type: 'string', enum: ['any', 'required', 'lang'], default: 'any' },
},
{
name: 'subtitleLang',
in: 'query',
required: false,
description: 'two-letter lang code, used when subtitles=lang',
schema: { type: 'string' },
example: 'en',
},
],
responses: {
200: {
description: 'stream list (best quality first)',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/StreamList' },
},
},
},
400: { $ref: '#/components/responses/BadRequest' },
500: {
description: 'no providers available / internal error',
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
},
},
},
},
},
components: {
parameters: {
MovieId: {
name: 'id',
in: 'path',
required: true,
description: 'TMDB movie id',
schema: { type: 'integer' },
example: 438631,
},
TvId: {
name: 'id',
in: 'path',
required: true,
description: 'TMDB tv id',
schema: { type: 'integer' },
example: 1396,
},
},
responses: {
BadRequest: {
description: 'missing or invalid parameters',
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
},
NotFound: {
description: 'media id not found on TMDB',
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
},
Upstream: {
description: 'TMDB request failed',
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
},
},
schemas: {
Error: {
type: 'object',
properties: { error: { type: 'string' } },
},
SearchResult: {
type: 'object',
properties: {
tmdb_id: { type: 'integer', example: 438631 },
type: { type: 'string', enum: ['movie', 'tv'] },
name: { type: 'string', example: 'Dune' },
year: { type: 'string', example: '2021' },
poster: { type: 'string', format: 'uri' },
overview: { type: 'string' },
},
},
MediaDetails: {
type: 'object',
description: 'raw TMDB media object (movie or tv) with added poster_url/backdrop_url',
properties: {
id: { type: 'integer', example: 438631 },
title: { type: 'string', description: 'movie title' },
name: { type: 'string', description: 'tv show name' },
overview: { type: 'string', description: 'description' },
tagline: { type: 'string' },
genres: {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string' },
},
},
},
vote_average: { type: 'number', description: 'rating, 0-10' },
vote_count: { type: 'integer' },
popularity: { type: 'number' },
status: { type: 'string' },
runtime: { type: 'integer', description: 'movie runtime in minutes' },
number_of_seasons: { type: 'integer', description: 'tv' },
number_of_episodes: { type: 'integer', description: 'tv' },
release_date: { type: 'string', format: 'date', description: 'movie' },
first_air_date: { type: 'string', format: 'date', description: 'tv' },
poster_path: { type: 'string' },
backdrop_path: { type: 'string' },
poster_url: { type: 'string', format: 'uri', description: 'full url (original size)' },
backdrop_url: { type: 'string', format: 'uri', description: 'full url (original size)' },
images: {
type: 'object',
description:
'all available images from TMDB (posters, backdrops, logos, profiles); every item includes `url` with the full image url',
},
},
additionalProperties: true,
},
Season: {
type: 'object',
properties: {
season_number: { type: 'integer' },
name: { type: 'string' },
episode_count: { type: 'integer' },
air_date: { type: 'string', format: 'date' },
},
},
Episode: {
type: 'object',
properties: {
episode_number: { type: 'integer' },
name: { type: 'string' },
air_date: { type: 'string', format: 'date' },
},
},
Subtitle: {
type: 'object',
properties: {
url: { type: 'string', format: 'uri' },
language: { type: 'string' },
name: { type: 'string' },
},
},
Stream: {
type: 'object',
properties: {
provider: { type: 'string', example: 'videasy' },
name: { type: 'string' },
url: { type: 'string', format: 'uri', description: 'the m3u8 (or direct) url' },
quality: { type: 'string', example: '2160p' },
pixels: { type: ['integer', 'null'], example: 2160 },
audio: { type: ['string', 'null'], example: 'aac' },
type: { type: 'string', example: 'm3u8' },
headers: {
type: 'object',
description: 'http headers the url needs (e.g. Referer)',
additionalProperties: { type: 'string' },
},
subtitles: { type: 'array', items: { $ref: '#/components/schemas/Subtitle' } },
},
},
StreamList: {
type: 'object',
properties: {
tmdb_id: { type: 'integer' },
type: { type: 'string', enum: ['movie', 'tv'] },
season: { type: ['integer', 'null'] },
episode: { type: ['integer', 'null'] },
total: { type: 'integer', description: 'streams before filters' },
matched: { type: 'integer', description: 'streams after filters' },
streams: { type: 'array', items: { $ref: '#/components/schemas/Stream' } },
providerErrors: {
type: 'object',
description: 'per-provider scrape errors',
additionalProperties: { type: 'string' },
},
loadErrors: {
type: 'object',
description: 'per-provider load errors',
additionalProperties: { type: 'string' },
},
},
},
},
},
};
module.exports = spec;
-524
View File
@@ -1,524 +0,0 @@
/* https://github.com/oqo0/swagger-themes */
@import url('https://unpkg.com/@catppuccin/palette/css/catppuccin.css');
:root {
--block-border-radius: 8px;
--innner-block-border-radius: 4px;
--icons-opacity: .32;
--secondary-icon-opacity: .6;
--black-icons-filter: invert(1);
}
[data-md-color-scheme="catppuccin-mocha"] {
/* primary colors */
--swagger-color: var(--ctp-latte-green);
--link-color: var(--ctp-latte-blue);
--accept-header-color: var(--ctp-latte-green);
/* methods colors */
--post-method-color: var(--ctp-latte-green);
--post-method-background-color: color-mix(in srgb, var(--ctp-latte-green), transparent 90%);
--get-method-color: var(--ctp-latte-blue);
--get-method-background-color: color-mix(in srgb, var(--ctp-latte-blue), transparent 90%);
--head-method-color: var(--ctp-latte-mauve);
--head-method-background-color: color-mix(in srgb, var(--ctp-latte-mauve), transparent 90%);
--put-method-color: var(--ctp-latte-peach);
--put-method-background-color: color-mix(in srgb, var(--ctp-latte-peach), transparent 90%);
--delete-method-color: var(--ctp-latte-red);
--delete-method-background-color: color-mix(in srgb, var(--ctp-latte-red), transparent 90%);
--options-method-color: var(--ctp-latte-sky);
--options-method-background-color: color-mix(in srgb, var(--ctp-latte-sky), transparent 90%);
--patch-method-color: var(--ctp-latte-teal);
--patch-method-background-color: color-mix(in srgb, var(--ctp-latte-teal), transparent 90%);
/* background */
--all-bg-color: var(--ctp-latte-base);
--secondary-bg-color: var(--ctp-latte-mantle);
--header-bg-color: var(--ctp-latte-mantle);
--block-bg-color: var(--ctp-latte-mantle);
--selecter-bg-color: var(--ctp-latte-mantle);
--teteriary-bg-color: var(--ctp-latte-crust);
/* text */
--primary-text-color: var(--ctp-latte-text);
--secondary-text-color: var(--ctp-latte-subtext0);
/* border */
--block-border-color: var(--ctp-latte-surface0);
/* icons */
--primary-icon-color: var(--ctp-latte-text);
}
[data-md-color-scheme="catppuccin-latte"] {
/* primary colors */
--swagger-color: var(--ctp-mocha-green);
--link-color: var(--ctp-mocha-blue);
--accept-header-color: var(--ctp-mocha-green);
/* methods colors */
--post-method-color: var(--ctp-mocha-green);
--post-method-background-color: color-mix(in srgb, var(--ctp-mocha-green), transparent 90%);
--get-method-color: var(--ctp-mocha-blue);
--get-method-background-color: color-mix(in srgb, var(--ctp-mocha-blue), transparent 90%);
--head-method-color: var(--ctp-mocha-mauve);
--head-method-background-color: color-mix(in srgb, var(--ctp-mocha-mauve), transparent 90%);
--put-method-color: var(--ctp-mocha-peach);
--put-method-background-color: color-mix(in srgb, var(--ctp-mocha-peach), transparent 90%);
--delete-method-color: var(--ctp-mocha-red);
--delete-method-background-color: color-mix(in srgb, var(--ctp-mocha-red), transparent 90%);
--options-method-color: var(--ctp-mocha-sky);
--options-method-background-color: color-mix(in srgb, var(--ctp-mocha-sky), transparent 90%);
--patch-method-color: var(--ctp-mocha-teal);
--patch-method-background-color: color-mix(in srgb, var(--ctp-mocha-teal), transparent 90%);
/* background */
--all-bg-color: var(--ctp-mocha-base);
--secondary-bg-color: var(--ctp-mocha-mantle);
--header-bg-color: var(--ctp-mocha-mantle);
--block-bg-color: var(--ctp-mocha-mantle);
--selecter-bg-color: var(--ctp-mocha-mantle);
--teteriary-bg-color: var(--ctp-mocha-crust);
/* text */
--primary-text-color: var(--ctp-mocha-text);
--secondary-text-color: var(--ctp-mocha-subtext0);
/* border */
--block-border-color: var(--ctp-mocha-surface0);
/* icons */
--primary-icon-color: var(--ctp-mocha-text);
}
/* primary colors */
.swagger-ui .topbar .download-url-wrapper .select-label select {
border: 2px solid var(--swagger-color);
}
.swagger-ui .info .title small.version-stamp {
background-color: var(--swagger-color);
}
.swagger-ui .info a {
color: var(--link-color);
}
.swagger-ui .response-control-media-type--accept-controller select {
border-color: var(--accept-header-color);
}
.swagger-ui .response-control-media-type__accept-message {
color: var(--accept-header-color);
}
.swagger-ui .btn.authorize {
color: var(--post-method-color);
}
.swagger-ui .btn.authorize {
border-color: var(--post-method-color);
}
.swagger-ui .btn.authorize svg {
fill: var(--post-method-color);
}
.swagger-ui .json-schema-2020-12__attribute--primary {
color: var(--head-method-color);
}
/* methods colors */
/* http post */
.swagger-ui .opblock.opblock-post .opblock-summary-method {
background: var(--post-method-color);
}
.swagger-ui .opblock.opblock-post .opblock-summary {
border-color: var(--post-method-color);
}
.swagger-ui .opblock.opblock-post {
background: var(--post-method-background-color);
border-color: var(--post-method-color);
}
.swagger-ui .opblock.opblock-post .tab-header .tab-item.active h4 span::after {
background: var(--post-method-color);
}
/* http get */
.swagger-ui .opblock.opblock-get .opblock-summary-method {
background: var(--get-method-color);
}
.swagger-ui .opblock.opblock-get .opblock-summary {
border-color: var(--get-method-color);
}
.swagger-ui .opblock.opblock-get {
background: var(--get-method-background-color);
border-color: var(--get-method-color);
}
.swagger-ui .opblock.opblock-get .tab-header .tab-item.active h4 span::after {
background: var(--get-method-color);
}
/* http head */
.swagger-ui .opblock.opblock-head .opblock-summary-method {
background: var(--head-method-color);
}
.swagger-ui .opblock.opblock-head .opblock-summary {
border-color: var(--head-method-color);
}
.swagger-ui .opblock.opblock-head {
background: var(--head-method-background-color);
border-color: var(--head-method-color);
}
.swagger-ui .opblock.opblock-head .tab-header .tab-item.active h4 span::after {
background: var(--head-method-color);
}
/* http put */
.swagger-ui .opblock.opblock-put .opblock-summary-method {
background: var(--put-method-color);
}
.swagger-ui .opblock.opblock-put .opblock-summary {
border-color: var(--put-method-color);
}
.swagger-ui .opblock.opblock-put {
background: var(--put-method-background-color);
border-color: var(--put-method-color);
}
.swagger-ui .opblock.opblock-put .tab-header .tab-item.active h4 span::after {
background: var(--put-method-color);
}
/* http delete */
.swagger-ui .opblock.opblock-delete .opblock-summary-method {
background: var(--delete-method-color);
}
.swagger-ui .opblock.opblock-delete .opblock-summary {
border-color: var(--delete-method-color);
}
.swagger-ui .opblock.opblock-delete {
background: var(--delete-method-background-color);
border-color: var(--delete-method-color);
}
.swagger-ui .opblock.opblock-delete .tab-header .tab-item.active h4 span::after {
background: var(--delete-method-color);
}
/* http options */
.swagger-ui .opblock.opblock-options .opblock-summary-method {
background: var(--options-method-color);
}
.swagger-ui .opblock.opblock-options .opblock-summary {
border-color: var(--options-method-color);
}
.swagger-ui .opblock.opblock-options {
background: var(--options-method-background-color);
border-color: var(--options-method-color);
}
.swagger-ui .opblock.opblock-options .tab-header .tab-item.active h4 span::after {
background: var(--options-method-color);
}
/* http patch */
.swagger-ui .opblock.opblock-patch .opblock-summary-method {
background: var(--patch-method-color);
}
.swagger-ui .opblock.opblock-patchs .opblock-summary {
border-color: var(--patch-method-color);
}
.swagger-ui .opblock.opblock-patch {
background: var(--patch-method-background-color);
border-color: var(--patch-method-color);
}
.swagger-ui .opblock.opblock-patch .tab-header .tab-item.active h4 span::after {
background: var(--patch-method-color);
}
/* blocks */
body {
background-color: var(--all-bg-color);
color: white;
}
.swagger-ui .topbar {
background-color: var(--header-bg-color);
}
.swagger-ui .scheme-container {
background: var(--secondary-bg-color);
}
.swagger-ui section.models .model-container {
background: var(--secondary-bg-color);
border-radius: var(--innner-block-border-radius);
}
.swagger-ui select {
background: var(--selecter-bg-color);
border-radius: var(--block-border-radius);
color: var(--primary-text-color);
}
.swagger-ui section.models {
border: 1px solid var(--block-border-color);
background-color: var(--block-bg-color);
}
.swagger-ui .opblock .opblock-section-header {
background: var(--secondary-bg-color);
}
.swagger-ui .body-param__example {
background-color: var(--secondary-bg-color) !important;
border-radius: var(--block-border-radius) !important;
}
.swagger-ui .example {
background-color: var(--secondary-bg-color) !important;
border-radius: var(--block-border-radius) !important;
}
.swagger-ui .copy-to-clipboard {
background: rgba(255, 255, 255, var(--icons-opacity));
border-radius: var(--block-border-radius);
}
.swagger-ui .opblock .opblock-summary-method {
border-radius: var(--innner-block-border-radius);
}
.swagger-ui input[type="email"],
.swagger-ui input[type="file"],
.swagger-ui input[type="password"],
.swagger-ui input[type="search"],
.swagger-ui input[type="text"],
.swagger-ui textarea {
background: var(--secondary-bg-color);
border: 1px solid var(--block-border-color);
border-radius: var(--block-border-radius);
color: var(--primary-text-color);
outline: none;
}
.swagger-ui .dialog-ux .modal-ux-header {
border-bottom: 1px solid var(--block-border-color);
}
.swagger-ui .btn {
border: 2px solid var(--block-border-color);
border-radius: var(--block-border-radius);
color: var(--primary-text-color);
}
.swagger-ui .dialog-ux .modal-ux {
background: var(--block-bg-color);
border: 1px solid var(--block-border-color);
border-radius: var(--block-border-radius);
}
.swagger-ui .auth-btn-wrapper {
justify-content: left;
}
.swagger-ui .opblock-tag {
border-bottom: 1px solid var(--block-border-color);
}
.swagger-ui section.models.is-open h4 {
border-bottom: 1px solid var(--block-border-color);
}
.swagger-ui .opblock {
border-radius: var(--block-border-radius);
}
.swagger-ui section.models {
border-radius: var(--block-border-radius);
}
/* button white outline fix */
.swagger-ui .model-box-control:focus,
.swagger-ui .models-control:focus,
.swagger-ui .opblock-summary-control:focus {
outline: none;
}
/* icons */
.swagger-ui .model-toggle::after {
opacity: var(--icons-opacity);
filter: var(--black-icons-filter);
}
.swagger-ui svg:not(:root) {
fill: var(--primary-icon-color);
}
.swagger-ui .opblock-summary-control svg:not(:root) {
opacity: var(--secondary-icon-opacity);
}
/* text */
.swagger-ui {
color: var(--primary-text-color);
}
.swagger-ui .info .title {
color: var(--primary-text-color);
}
.swagger-ui a.nostyle {
color: var(--primary-text-color);
}
.swagger-ui .model-title {
color: var(--primary-text-color);
}
.swagger-ui .models-control {
color: var(--primary-text-color);
}
.swagger-ui .dialog-ux .modal-ux-header h3 {
color: var(--primary-text-color);
}
.swagger-ui .dialog-ux .modal-ux-content h4 {
color: var(--primary-text-color);
}
.swagger-ui .dialog-ux .modal-ux-content p {
color: var(--secondary-text-color);
}
.swagger-ui ol {
color: var(--primary-text-color);
}
.swagger-ui h3 {
color: var(--primary-text-color) !important;
}
.swagger-ui h4 {
color: var(--primary-text-color) !important;
}
.swagger-ui h5 {
color: var(--secondary-text-color) !important;
}
.swagger-ui label {
color: var(--primary-text-color);
}
.swagger-ui .opblock .opblock-section-header h4 {
color: var(--primary-text-color);
}
.swagger-ui .tab li button.tablinks {
color: var(--primary-text-color);
}
.swagger-ui .opblock-description-wrapper p,
.swagger-ui .opblock-external-docs-wrapper p,
.swagger-ui .opblock-title_normal p {
color: var(--primary-text-color);
}
.opblock-summary-description {
color: var(--secondary-text-color) !important;
}
.swagger-ui table thead tr td, .swagger-ui table thead tr th {
border-bottom: 1px solid var(--block-border-color);
color: var(--primary-text-color);
}
.swagger-ui .response-col_status {
color: var(--primary-text-color);
}
.swagger-ui .response-col_links {
color: var(--secondary-text-color);
}
.swagger-ui .parameter__name {
color: var(--primary-text-color);
}
.swagger-ui .parameter__type {
color: var(--secondary-text-color);
}
.swagger-ui .prop-format {
color: var(--secondary-text-color);
}
.swagger-ui .info li,
.swagger-ui .info p,
.swagger-ui .info table {
color: var(--secondary-text-color);
}
.swagger-ui .model {
color: var(--secondary-text-color);
}
.swagger-ui .opblock-tag small {
color: var(--secondary-text-color);
}
.swagger-ui .json-schema-2020-12__title,
.swagger-ui .json-schema-2020-12-keyword__name--primary,
.swagger-ui .json-schema-2020-12-property .json-schema-2020-12__title {
color: var(--primary-text-color);
}
.swagger-ui .json-schema-2020-12-expand-deep-button {
color: var(--secondary-text-color);
}
/* json */
.swagger-ui .json-schema-2020-12-accordion,
.swagger-ui .json-schema-2020-12-expand-deep-button {
background: none;
}
.swagger-ui .json-schema-2020-12 {
background-color: var(--teteriary-bg-color);
}
.swagger-ui .json-schema-2020-12__constraint--string {
background-color: var(--put-method-color);
}
-386
View File
@@ -1,386 +0,0 @@
const http = require('http');
const fs = require('fs');
const path = require('path');
const { Readable } = require('stream');
const { loadConfig } = require('../mod/config');
const tmdb = require('../mod/tmdb');
const { listAll, loadProviders } = require('../mod/loadProviders');
const { scrapeAll } = require('../mod/scrape');
const { normalize } = require('../mod/normalize');
const { applyFilters, rankStreams } = require('../mod/filter');
const spec = require('./openapi');
const cfg = loadConfig();
const PORT = process.env.STREAM_API_PORT ? parseInt(process.env.STREAM_API_PORT, 10) : cfg.apiPort;
const HOST = process.env.STREAM_API_HOST || cfg.apiHost;
const SWAGGER_HTML = path.join(__dirname, 'public', 'index.html');
function json(res, status, obj) {
const body = JSON.stringify(obj);
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-store',
});
res.end(body);
}
function html(res, status, text, type = 'text/html; charset=utf-8') {
res.writeHead(status, { 'Content-Type': type, 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' });
res.end(text);
}
const PROXY_DISALLOWED = new Set([
'host',
'connection',
'content-length',
'transfer-encoding',
'upgrade',
'keep-alive',
'proxy-authorization',
'proxy-authentication',
'te',
'trailer',
'via',
'warning',
'expect',
'date',
'dnt',
'accept-encoding',
]);
function parseProxyHeaders(raw) {
if (!raw) return {};
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
return {};
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
const out = {};
for (const [name, value] of Object.entries(parsed)) {
if (typeof value !== 'string' || !value) continue;
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) continue;
if (PROXY_DISALLOWED.has(name.toLowerCase())) continue;
out[name] = value;
}
return out;
}
function proxyTarget(target, headers) {
const query = new URLSearchParams({ url: target, h: JSON.stringify(headers || {}) });
return `/proxy/media?${query.toString()}`;
}
function rewriteM3u8(text, baseUrl, headers) {
return text
.split(/\r?\n/)
.map((line) => {
const trimmed = line.trim();
if (!trimmed) return line;
if (trimmed.startsWith('#')) {
return line.replace(/(URI\s*=\s*)(?:"([^"]*)"|'([^']*)')/g, (match, prefix, double, single) => {
const uri = double !== undefined ? double : single;
try {
return `${prefix}"${proxyTarget(new URL(uri, baseUrl).toString(), headers)}"`;
} catch {
return match;
}
});
}
try {
return proxyTarget(new URL(trimmed, baseUrl).toString(), headers);
} catch {
return line;
}
})
.join('\n');
}
async function handleProxyMedia(req, res, url) {
const target = (url.searchParams.get('url') || '').trim();
const headers = parseProxyHeaders(url.searchParams.get('h'));
let parsed;
try {
parsed = new URL(target);
} catch {
return json(res, 400, { error: 'missing or invalid ?url=' });
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
return json(res, 400, { error: 'proxy only supports http/https' });
}
const upstreamHeaders = { ...headers };
if (req.headers.range) upstreamHeaders.range = req.headers.range;
let upstream;
try {
upstream = await fetch(parsed.toString(), { headers: upstreamHeaders, redirect: 'follow' });
} catch (e) {
return json(res, 502, { error: `proxy fetch failed: ${e.message}` });
}
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Cache-Control', 'no-store');
const contentType = upstream.headers.get('content-type') || '';
const looksLikeM3u8 = /mpegurl/i.test(contentType) || /\.m3u8(?:[?#].*)?$/i.test(parsed.pathname + parsed.search);
if (looksLikeM3u8 && upstream.status < 400) {
try {
const text = await upstream.text();
if (/mpegurl/i.test(contentType) || text.trimStart().startsWith('#EXTM3U')) {
const body = rewriteM3u8(text, parsed.toString(), headers);
res.writeHead(upstream.status, {
'Content-Type': 'application/vnd.apple.mpegurl; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
});
return res.end(body);
}
res.writeHead(upstream.status, {
'Content-Type': contentType || 'text/plain; charset=utf-8',
'Content-Length': Buffer.byteLength(text),
});
return res.end(text);
} catch (e) {
if (!res.headersSent) return json(res, 502, { error: `proxy playlist failed: ${e.message}` });
return res.destroy();
}
}
res.statusCode = upstream.status;
const copyHeaders = ['content-type', 'content-range', 'accept-ranges'];
if (upstream.status === 206) copyHeaders.push('content-length');
for (const name of copyHeaders) {
const value = upstream.headers.get(name);
if (value) res.setHeader(name, value);
}
if (!upstream.body) return res.end();
const body = Readable.fromWeb(upstream.body);
body.on('error', () => {
try {
upstream.body.cancel();
} catch {}
});
body.pipe(res).on('error', () => {});
}
function searchResult(m) {
const isTv = m.media_type === 'tv';
const date = isTv ? m.first_air_date : m.release_date;
return {
tmdb_id: m.id,
type: isTv ? 'tv' : 'movie',
name: m.title || m.name,
year: date ? String(date).slice(0, 4) : '',
poster: m.poster_path ? `https://image.tmdb.org/t/p/w342${m.poster_path}` : '',
backdrop: m.backdrop_path ? `https://image.tmdb.org/t/p/w1280${m.backdrop_path}` : '',
rating: m.vote_average ? Number(m.vote_average).toFixed(1) : '',
overview: m.overview || '',
};
}
async function handleSearch(req, res, url) {
const q = (url.searchParams.get('q') || '').trim();
if (!q) return json(res, 400, { error: 'missing ?q=' });
try {
const results = await tmdb.search(q, cfg.tmdbKey);
return json(res, 200, { query: q, count: results.length, results: results.map(searchResult) });
} catch (e) {
return json(res, 502, { error: `tmdb search failed: ${e.message}` });
}
}
async function handleTrending(req, res, url) {
const type = url.searchParams.get('type') || 'all';
const timeWindow = url.searchParams.get('window') || 'week';
if (!['all', 'movie', 'tv'].includes(type)) {
return json(res, 400, { error: '?type= must be all, movie or tv' });
}
if (!['day', 'week'].includes(timeWindow)) {
return json(res, 400, { error: '?window= must be day or week' });
}
try {
const results = await tmdb.trending(type, timeWindow, cfg.tmdbKey);
return json(res, 200, { type, window: timeWindow, count: results.length, results: results.map(searchResult) });
} catch (e) {
return json(res, 502, { error: `tmdb trending failed: ${e.message}` });
}
}
async function handleSeasons(req, res, url, id) {
try {
const seasons = await tmdb.getSeasons(id, cfg.tmdbKey);
return json(res, 200, {
tmdb_id: id,
count: seasons.length,
seasons: seasons.map((s) => ({
season_number: s.season_number,
name: s.name,
episode_count: s.episode_count,
air_date: s.air_date || '',
})),
});
} catch (e) {
return json(res, 502, { error: `tmdb seasons failed: ${e.message}` });
}
}
async function handleEpisodes(req, res, url, id, season) {
try {
const episodes = await tmdb.getEpisodes(id, season, cfg.tmdbKey);
return json(res, 200, {
tmdb_id: id,
season: parseInt(season, 10),
count: episodes.length,
episodes: episodes.map((e) => ({
episode_number: e.episode_number,
name: e.name,
air_date: e.air_date || '',
still: e.still_path ? `https://image.tmdb.org/t/p/w300${e.still_path}` : '',
})),
});
} catch (e) {
return json(res, 502, { error: `tmdb episodes failed: ${e.message}` });
}
}
const TMDB_IMG = 'https://image.tmdb.org/t/p/';
function fullImage(pathname) {
return pathname ? `${TMDB_IMG}original${pathname}` : '';
}
async function handleDetails(req, res, type, id) {
try {
const d = await tmdb.details(type, id, cfg.tmdbKey);
d.poster_url = fullImage(d.poster_path);
d.backdrop_url = fullImage(d.backdrop_path);
if (d.images) {
for (const key of Object.keys(d.images)) {
d.images[key] = (d.images[key] || []).map((im) => ({ ...im, url: fullImage(im.file_path) }));
}
}
return json(res, 200, d);
} catch (e) {
const status = /HTTP 404/.test(e.message) ? 404 : 502;
return json(res, status, { error: `tmdb details failed: ${e.message}` });
}
}
async function handleStreams(req, res, url) {
const id = (url.searchParams.get('tmdb') || '').trim();
if (!/^\d+$/.test(id)) return json(res, 400, { error: 'missing or invalid ?tmdb=<id>' });
const type = url.searchParams.get('type') === 'tv' ? 'tv' : 'movie';
const season = url.searchParams.get('season');
const episode = url.searchParams.get('episode');
if (type === 'tv' && (!season || !episode)) {
return json(res, 400, { error: 'tv streams need ?season=<n>&episode=<n> (see /tv/<id>/seasons)' });
}
const providersParam = url.searchParams.get('providers');
const names = providersParam
? providersParam.split(',').map((s) => s.trim()).filter(Boolean)
: cfg.enabledProviders;
const { providers, loadErrors } = loadProviders(names);
if (!providers.length) return json(res, 500, { error: 'no providers available', loadErrors });
const media = {
id,
type,
seasonId: season ? parseInt(season, 10) : null,
episodeId: episode ? parseInt(episode, 10) : null,
};
const { streams, errors } = await scrapeAll(providers, media, cfg.timeoutMs);
const all = streams.map((s) => normalize(s, s._provider));
const filters = {
minQuality: url.searchParams.get('minQuality') || 'any',
audioCodec: url.searchParams.get('audioCodec') || 'any',
subtitles: url.searchParams.get('subtitles') || 'any',
subtitleLang: url.searchParams.get('subtitleLang') || '',
};
const ranked = rankStreams(applyFilters(all, filters));
return json(res, 200, {
tmdb_id: id,
type,
season: media.seasonId,
episode: media.episodeId,
total: all.length,
matched: ranked.length,
streams: ranked.map((s) => ({
provider: s.provider,
name: s.name,
url: s.url,
quality: s.quality,
pixels: s.pixels,
audio: s.audio,
type: s.type,
headers: s.headers,
subtitles: s.subtitles,
})),
providerErrors: errors,
loadErrors,
});
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
const p = url.pathname.replace(/\/+$/, '') || '/';
try {
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': '*',
});
return res.end();
}
if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed, use GET' });
// web docs
if (p === '/' || p === '/index.html') {
const data = fs.readFileSync(SWAGGER_HTML);
return html(res, 200, data);
}
if (p === '/api.json') {
return json(res, 200, spec);
}
if (p === '/proxy/media') return await handleProxyMedia(req, res, url);
// api
if (p === '/providers') return json(res, 200, { all: listAll(), enabled: cfg.enabledProviders });
if (p === '/search') return await handleSearch(req, res, url);
if (p === '/trending') return await handleTrending(req, res, url);
let m = p.match(/^\/movie\/(\d+)$/);
if (m) return await handleDetails(req, res, 'movie', m[1]);
m = p.match(/^\/tv\/(\d+)$/);
if (m) return await handleDetails(req, res, 'tv', m[1]);
m = p.match(/^\/tv\/(\d+)\/seasons$/);
if (m) return await handleSeasons(req, res, url, m[1]);
m = p.match(/^\/tv\/(\d+)\/seasons\/(\d+)$/);
if (m) return await handleEpisodes(req, res, url, m[1], m[2]);
if (p === '/streams') return await handleStreams(req, res, url);
return json(res, 404, { error: 'not found', hint: 'see GET / (Swagger UI) or GET /api.json' });
} catch (e) {
if (!res.headersSent) return json(res, 500, { error: e.message });
res.destroy();
}
});
server.listen(PORT, HOST, () => {
console.log(`bug.tv api: http://${HOST}:${PORT} (docs at /)`);
console.log(`providers: ${cfg.enabledProviders.join(', ')}`);
});
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env node
// Scrape benchmark: time-to-first-stream and total time over SSE for movie 550 and tv 1399 S1E1.
//
// node scripts/bench.js [--base http://127.0.0.1:8789] [--old http://127.0.0.1:8788]
// [--providers a,b,c] [--runs 1] [--cached]
//
// --old benchmarks a v4 server (GET /streams, JSON only: first stream == total).
// Runs bypass the v5 result cache (fresh=1) unless --cached is given. TMDB counters come from
// the `done` event's debug field: `calls` = TMDB requests the providers made (what v4 sent to
// the network), `network` = requests the v5 main thread actually sent to TMDB.
const args = process.argv.slice(2);
const opt = (name, d) => {
const i = args.indexOf(`--${name}`);
return i >= 0 ? args[i + 1] : d;
};
const flag = (name) => args.includes(`--${name}`);
const BASE = opt('base', 'http://127.0.0.1:8789').replace(/\/+$/, '');
const OLD = opt('old', '')?.replace(/\/+$/, '');
const RUNS = parseInt(opt('runs', '1'), 10);
const CASES = [
{ label: 'movie 550', q: { tmdb: '550', type: 'movie' } },
{ label: 'tv 1399 S1E1', q: { tmdb: '1399', type: 'tv', season: '1', episode: '1' } },
];
async function providers() {
const p = opt('providers', '');
if (p) return p;
const r = await fetch(`${BASE}/v1/providers`).then((r) => r.json());
return r.defaults.join(',');
}
// minimal SSE reader over fetch
async function sseRun(url) {
const t0 = performance.now();
const res = await fetch(url, { headers: { Accept: 'text/event-stream' } });
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const dec = new TextDecoder();
let buf = '';
const out = { first: null, total: null, streams: 0, providers: {}, done: null };
for await (const chunk of res.body) {
buf += dec.decode(chunk, { stream: true });
let i;
while ((i = buf.indexOf('\n\n')) >= 0) {
const block = buf.slice(0, i);
buf = buf.slice(i + 2);
const ev = /^event: (.*)$/m.exec(block)?.[1];
const data = /^data: (.*)$/m.exec(block)?.[1];
if (!ev || !data) continue;
const d = JSON.parse(data);
const t = performance.now() - t0;
if (ev === 'streams' && d.streams.length) {
if (out.first == null) out.first = { ms: t, provider: d.provider };
out.streams += d.streams.length;
} else if (ev === 'provider') out.providers[d.name] = `${d.status}:${d.ms}`;
else if (ev === 'done') {
out.total = t;
out.done = d;
}
}
}
return out;
}
async function oldRun(url) {
const t0 = performance.now();
const r = await fetch(url).then((r) => r.json());
const t = performance.now() - t0;
return { first: r.streams?.length ? { ms: t, provider: '(all)' } : null, total: t, streams: r.streams?.length || 0, errors: r.providerErrors };
}
const fmt = (ms) => (ms == null ? ' - ' : `${(ms / 1000).toFixed(2).padStart(6)}s`);
(async () => {
const list = await providers();
console.log(`providers (${list.split(',').length}): ${list}\n`);
const qs = (q, extra = {}) => new URLSearchParams({ ...q, providers: list, ...extra }).toString();
for (const c of CASES) {
for (let run = 1; run <= RUNS; run++) {
const tag = `${c.label}${RUNS > 1 ? ` #${run}` : ''}`;
const r = await sseRun(`${BASE}/v1/streams?${qs(c.q, flag('cached') ? {} : { fresh: '1' })}`);
const tm = r.done?.debug?.tmdb;
console.log(
`v5 ${tag.padEnd(16)} first ${fmt(r.first?.ms)} (${r.first?.provider || 'none'}) total ${fmt(r.total)} streams ${r.streams}` +
(tm ? ` tmdb: providers asked ${tm.calls} (worker-local ${tm.local}, via main ${tm.remote}), network ${tm.network}` : '')
);
if (flag('verbose')) console.log(' ', r.providers);
if (OLD) {
const o = await oldRun(`${OLD}/streams?${qs(c.q)}`);
console.log(`v4 ${tag.padEnd(16)} first ${fmt(o.first?.ms)} total ${fmt(o.total)} streams ${o.streams}`);
}
}
}
const s = await fetch(`${BASE}/v1/providers`).then((r) => r.json()).catch(() => null);
if (s?.stats?.tmdb) console.log(`\nv5 TMDB totals since boot: ${JSON.stringify(s.stats.tmdb)}`);
})().catch((e) => {
console.error(e.message);
process.exit(1);
});
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env node
// Copy providers + manifest from an All-in-One-Nuvio checkout.
// usage: node scripts/sync-providers.js <path-to-All-in-One-Nuvio>
const fs = require('fs');
const path = require('path');
const src = process.argv[2];
if (!src) {
console.error('usage: sync-providers.js <path-to-All-in-One-Nuvio>');
process.exit(1);
}
const dest = path.join(__dirname, '..', 'providers');
const srcProviders = path.join(src, 'providers');
fs.mkdirSync(dest, { recursive: true });
let added = 0;
let updated = 0;
for (const file of fs.readdirSync(srcProviders).filter((f) => f.endsWith('.js'))) {
const from = path.join(srcProviders, file);
const to = path.join(dest, file);
const next = fs.readFileSync(from);
if (!fs.existsSync(to)) added++;
else if (!fs.readFileSync(to).equals(next)) updated++;
else continue;
fs.writeFileSync(to, next);
}
fs.copyFileSync(path.join(src, 'manifest.json'), path.join(dest, 'manifest.json'));
console.log(`providers: ${added} added, ${updated} updated`);
+88
View File
@@ -0,0 +1,88 @@
// LRU + TTL map with in-flight promise dedupe.
//
// const c = createCache({ max: 500, ttlMs: 60_000 });
// c.set(k, v, ttlMs?) c.get(k) c.has(k) c.delete(k)
// await c.wrap(k, () => fetchThing(), ttlMs?)
//
// `wrap` returns the cached value if fresh, joins an in-flight call for the same key,
// or runs `fn` and caches its resolved value. `ttlMs` may be a function of the value
// (return 0 / falsy to skip caching, e.g. for error results). Rejections are never cached.
function createCache({ max = 1000, ttlMs = 60_000 } = {}) {
const map = new Map(); // key -> { value, expires }; Map order = LRU order (oldest first)
const inflight = new Map(); // key -> Promise
function get(key) {
const hit = map.get(key);
if (!hit) return undefined;
if (hit.expires <= Date.now()) {
map.delete(key);
return undefined;
}
map.delete(key); // bump to most-recent
map.set(key, hit);
return hit.value;
}
function has(key) {
const hit = map.get(key);
if (!hit) return false;
if (hit.expires <= Date.now()) {
map.delete(key);
return false;
}
return true;
}
function set(key, value, ttl = ttlMs) {
if (!(ttl > 0)) return value;
map.delete(key);
map.set(key, { value, expires: Date.now() + ttl });
while (map.size > max) map.delete(map.keys().next().value);
return value;
}
function del(key) {
inflight.delete(key);
return map.delete(key);
}
function wrap(key, fn, ttl = ttlMs) {
if (has(key)) return Promise.resolve(get(key));
const pending = inflight.get(key);
if (pending) return pending;
const p = Promise.resolve()
.then(fn)
.then(
(value) => {
if (inflight.get(key) === p) inflight.delete(key);
set(key, value, typeof ttl === 'function' ? ttl(value) : ttl);
return value;
},
(err) => {
if (inflight.get(key) === p) inflight.delete(key);
throw err;
}
);
inflight.set(key, p);
return p;
}
return {
get,
set,
has,
delete: del,
wrap,
inflight: (key) => inflight.get(key),
clear() {
map.clear();
inflight.clear();
},
get size() {
return map.size;
},
};
}
module.exports = { createCache };
+53
View File
@@ -0,0 +1,53 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const CONFIG_PATH = process.env.BUG_TV_CONFIG || path.join(__dirname, '..', 'config.json');
const DEFAULTS = {
host: '0.0.0.0',
port: 8789,
tmdbKey: '',
tmdbKeyFile: '',
// [] = every provider in providers/ except disabledProviders
enabledProviders: [],
// torrent-only providers are opt-in: their magnets cost server bandwidth/disk to play
disabledProviders: ['torrentio'],
providerSettings: {},
timeoutMs: 20000,
workers: 0,
cacheTtlSec: 1800,
secret: '',
secretFile: '',
torrent: { enable: true, cacheDir: '', maxSizeGB: 20 },
remux: { enable: true, ffmpeg: 'ffmpeg', ffprobe: 'ffprobe' },
filters: { minQuality: 'any', audioCodec: 'any', subtitles: 'any', subtitleLang: '' },
};
function readSecretFile(file) {
return file ? fs.readFileSync(file, 'utf8').trim() : '';
}
function loadConfig() {
const saved = fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {};
const cfg = { ...DEFAULTS, ...saved };
for (const key of ['torrent', 'remux', 'filters']) cfg[key] = { ...DEFAULTS[key], ...(saved[key] || {}) };
const env = process.env;
if (env.BUG_TV_HOST) cfg.host = env.BUG_TV_HOST;
if (env.BUG_TV_PORT) cfg.port = parseInt(env.BUG_TV_PORT, 10);
if (env.BUG_TV_CACHE_DIR) cfg.torrent.cacheDir = env.BUG_TV_CACHE_DIR;
cfg.tmdbKey = cfg.tmdbKey || readSecretFile(cfg.tmdbKeyFile) || env.TMDB_API_KEY || '';
if (!cfg.tmdbKey) {
console.error('No TMDB API key. Set tmdbKey / tmdbKeyFile in the config or TMDB_API_KEY.');
process.exit(1);
}
// signs proxy/remux/subtitle tokens; random per boot unless pinned
cfg.secret = cfg.secret || readSecretFile(cfg.secretFile) || env.BUG_TV_SECRET || crypto.randomBytes(32).toString('hex');
if (!cfg.torrent.cacheDir) cfg.torrent.cacheDir = path.join(require('os').tmpdir(), 'bug-tv-torrents');
return cfg;
}
module.exports = { loadConfig, CONFIG_PATH };
+65
View File
@@ -0,0 +1,65 @@
const zlib = require('zlib');
const CORS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Expose-Headers': 'Content-Length, Content-Range, Accept-Ranges, X-Bug-Tv-Offset',
};
// compress text bodies only; media is already compressed
function send(req, res, status, body, type, extra = {}) {
const buf = Buffer.isBuffer(body) ? body : Buffer.from(String(body));
const headers = { ...CORS, 'Content-Type': type, 'Cache-Control': 'no-store', Vary: 'Accept-Encoding', ...extra };
const accept = String(req.headers['accept-encoding'] || '');
if (buf.length > 1024 && /\bbr\b/.test(accept)) {
const out = zlib.brotliCompressSync(buf, { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4 } });
res.writeHead(status, { ...headers, 'Content-Encoding': 'br', 'Content-Length': out.length });
return res.end(out);
}
if (buf.length > 1024 && /\bgzip\b/.test(accept)) {
const out = zlib.gzipSync(buf, { level: 5 });
res.writeHead(status, { ...headers, 'Content-Encoding': 'gzip', 'Content-Length': out.length });
return res.end(out);
}
res.writeHead(status, { ...headers, 'Content-Length': buf.length });
res.end(buf);
}
function json(req, res, status, obj, extra) {
return send(req, res, status, JSON.stringify(obj), 'application/json; charset=utf-8', extra);
}
function error(req, res, status, message, extra = {}) {
return json(req, res, status, { error: message, ...extra });
}
// Server-sent events; returns { event(name, data), close() }.
function sse(req, res) {
res.writeHead(200, {
...CORS,
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-store',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.flushHeaders?.();
const ping = setInterval(() => res.write(': ping\n\n'), 15000);
let closed = false;
const close = () => {
if (closed) return;
closed = true;
clearInterval(ping);
res.end();
};
req.on('close', close);
return {
event(name, data) {
if (!closed) res.write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
},
close,
get closed() {
return closed;
},
};
}
module.exports = { CORS, send, json, error, sse };
+169
View File
@@ -0,0 +1,169 @@
// Shared upstream networking for the media workstream: one keep-alive undici
// agent, SSRF guard (private/loopback/link-local targets blocked at DNS lookup
// time, so redirects and DNS rebinding are covered too), manual redirects and
// a tiny LRU used by the proxy/subs/probe caches.
const dns = require('dns');
const net = require('net');
const zlib = require('zlib');
const { Agent, buildConnector, request } = require('undici');
let allowPrivate = false;
const blocked = new net.BlockList();
for (const [a, p] of [
['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16],
['172.16.0.0', 12], ['192.0.0.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['224.0.0.0', 3],
]) blocked.addSubnet(a, p, 'ipv4');
for (const [a, p] of [['::', 128], ['::1', 128], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8], ['64:ff9b::', 96]])
blocked.addSubnet(a, p, 'ipv6');
function isPrivateIp(ip) {
const fam = net.isIP(ip);
if (!fam) return false;
if (fam === 6) {
const m = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
if (m) return blocked.check(m[1], 'ipv4');
return blocked.check(ip, 'ipv6');
}
return blocked.check(ip, 'ipv4');
}
class BlockedError extends Error {
constructor(host) {
super(`blocked private/loopback target: ${host}`);
this.code = 'EBLOCKED';
}
}
// dns.lookup replacement that refuses private addresses
function safeLookup(hostname, opts, cb) {
if (typeof opts === 'function') (cb = opts), (opts = {});
dns.lookup(hostname, opts, (err, address, family) => {
if (err || allowPrivate) return cb(err, address, family);
const list = Array.isArray(address) ? address : [{ address, family }];
const ok = list.filter((a) => !isPrivateIp(a.address));
if (!ok.length) return cb(new BlockedError(hostname));
if (opts.all) return cb(null, ok);
cb(null, ok[0].address, ok[0].family);
});
}
// Resolve a hostname once and decide (used before handing a URL to ffmpeg).
async function assertPublicUrl(u) {
const url = typeof u === 'string' ? new URL(u) : u;
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw Object.assign(new Error('only http/https upstreams'), { code: 'EPROTO' });
if (allowPrivate) return url;
const host = url.hostname.replace(/^\[|\]$/g, '');
if (net.isIP(host)) {
if (isPrivateIp(host)) throw new BlockedError(host);
return url;
}
const addrs = await dns.promises.lookup(host, { all: true });
if (!addrs.length || addrs.every((a) => isPrivateIp(a.address))) throw new BlockedError(host);
return url;
}
const connector = buildConnector({ lookup: safeLookup, timeout: 10000 });
const agent = new Agent({
keepAliveTimeout: 30000,
keepAliveMaxTimeout: 120000,
pipelining: 1,
connections: 16,
headersTimeout: 20000,
bodyTimeout: 30000,
connect(opts, cb) {
const host = String(opts.hostname || '').replace(/^\[|\]$/g, '');
if (!allowPrivate && net.isIP(host) && isPrivateIp(host)) return cb(new BlockedError(host), null);
return connector(opts, cb);
},
});
function init(cfg) {
allowPrivate = !!cfg.allowPrivateTargets;
}
const HOP = new Set([
'host', 'connection', 'content-length', 'transfer-encoding', 'upgrade', 'keep-alive', 'proxy-authorization',
'proxy-authenticate', 'te', 'trailer', 'via', 'expect', 'accept-encoding', 'range',
]);
// sanitize header object coming from a token / legacy query
function cleanHeaders(h) {
const out = {};
if (!h || typeof h !== 'object' || Array.isArray(h)) return out;
for (const [k, v] of Object.entries(h)) {
if (typeof v !== 'string' || !v || /[\r\n]/.test(v)) continue;
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(k) || HOP.has(k.toLowerCase())) continue;
out[k] = v;
}
return out;
}
// GET/HEAD with manual redirect following (keeps custom headers, re-checks each hop).
// Returns { statusCode, headers, body, url } (url = final URL).
async function fetchUpstream(url, { headers = {}, method = 'GET', signal, maxRedirects = 5 } = {}) {
let cur = new URL(url);
for (let hop = 0; ; hop++) {
if (cur.protocol !== 'http:' && cur.protocol !== 'https:') throw Object.assign(new Error('only http/https upstreams'), { code: 'EPROTO' });
const r = await request(cur, { method, headers, dispatcher: agent, signal });
if (r.statusCode >= 300 && r.statusCode < 400 && r.headers.location && hop < maxRedirects) {
r.body.resume();
r.body.on('error', () => {});
cur = new URL(String(r.headers.location), cur);
continue;
}
r.body.on('error', () => {}); // consumers use pipeline/for-await; never crash on a stray abort
return { ...r, url: cur.toString() };
}
}
// buffer a body (bounded), undoing content-encoding
async function readBody(r, limit = 16 * 1024 * 1024) {
const chunks = [];
let n = 0;
for await (const c of r.body) {
n += c.length;
if (n > limit) {
r.body.destroy();
throw new Error('upstream body too large');
}
chunks.push(c);
}
let buf = Buffer.concat(chunks);
const enc = String(r.headers['content-encoding'] || '').toLowerCase();
if (enc === 'gzip' || enc === 'x-gzip' || (buf[0] === 0x1f && buf[1] === 0x8b)) buf = zlib.gunzipSync(buf);
else if (enc === 'br') buf = zlib.brotliDecompressSync(buf);
else if (enc === 'deflate') buf = zlib.inflateSync(buf);
return buf;
}
class LRU {
constructor(max = 200) {
this.max = max;
this.map = new Map();
}
get(k) {
const e = this.map.get(k);
if (!e) return undefined;
if (e.exp && e.exp < Date.now()) {
this.map.delete(k);
return undefined;
}
this.map.delete(k);
this.map.set(k, e);
return e.v;
}
set(k, v, ttlMs) {
this.map.delete(k);
this.map.set(k, { v, exp: ttlMs ? Date.now() + ttlMs : 0 });
while (this.map.size > this.max) this.map.delete(this.map.keys().next().value);
}
delete(k) {
this.map.delete(k);
}
get size() {
return this.map.size;
}
}
module.exports = { init, agent, fetchUpstream, readBody, cleanHeaders, assertPublicUrl, isPrivateIp, BlockedError, LRU };
+102
View File
@@ -0,0 +1,102 @@
// Decide how the client should play a normalized stream (see docs/api.md).
// All returned URLs are relative to the API base.
const { sign } = require('../sign');
const TRACKERS = [
'udp://tracker.opentrackr.org:1337/announce',
'udp://open.demonii.com:1337/announce',
'udp://tracker.torrent.eu.org:451/announce',
'udp://exodus.desync.com:6969/announce',
'udp://explodie.org:6969/announce',
'wss://tracker.openwebtorrent.com',
];
function cleanHeaders(h) {
const out = {};
if (!h || typeof h !== 'object') return out;
for (const [k, v] of Object.entries(h)) if (typeof v === 'string' && v) out[k] = v;
return out;
}
// direct play is possible when the only header is (at most) a User-Agent
function needsProxy(headers) {
return Object.keys(headers).some((k) => k.toLowerCase() !== 'user-agent');
}
function proxyUrl(absUrl, headers) {
const u = new URL(absUrl);
const tok = sign({ o: u.origin, h: cleanHeaders(headers) });
return `/v1/p/${tok}${u.pathname}${u.search}`;
}
function remuxUrl(absUrl, headers) {
return `/v1/remux/${sign({ u: absUrl, h: cleanHeaders(headers) })}`;
}
function magnetFor(stream) {
if (/^magnet:/i.test(stream.url || '')) return stream.url;
const hash = stream.infoHash || stream.infohash;
if (!hash) return null;
const tr = TRACKERS.map((t) => `&tr=${encodeURIComponent(t)}`).join('');
return `magnet:?xt=urn:btih:${hash}${stream.title || stream.name ? `&dn=${encodeURIComponent(stream.title || stream.name)}` : ''}${tr}`;
}
function extKind(url) {
const p = (() => {
try {
return new URL(url).pathname.toLowerCase();
} catch {
return String(url).toLowerCase();
}
})();
if (/\.m3u8?$/.test(p)) return 'hls';
if (/\.(mp4|m4v|webm|mov)$/.test(p)) return 'file';
return 'remux';
}
// playbackFor(stream, ctx?) — ctx = { season, episode } for picking the right file in season packs
function playbackFor(stream, ctx = {}) {
const type = String(stream.type || 'other').toLowerCase();
const headers = cleanHeaders(stream.headers);
const magnet = magnetFor(stream);
if (type === 'magnet' || magnet && !/^https?:/i.test(stream.url || '')) {
if (!magnet) return null;
const tok = { m: magnet };
const s = ctx.season ?? stream.season;
const e = ctx.episode ?? stream.episode;
if (s != null && s !== '' && e != null && e !== '') {
tok.s = Number(s);
tok.e = Number(e);
}
const f = stream.fileIdx ?? stream.fileIndex;
if (Number.isInteger(f)) tok.f = f;
const t = sign(tok);
return { kind: 'torrent', url: `/v1/torrent/${t}/stream`, status: `/v1/torrent/${t}/status` };
}
const url = stream.url;
if (!/^https?:\/\//i.test(url || '')) return null;
let kind;
if (type === 'm3u8') kind = 'hls';
else if (type === 'mp4' || type === 'webm') kind = 'file';
else if (type === 'other') kind = extKind(url);
else kind = 'remux';
if (kind === 'remux') return { kind, url: remuxUrl(url, headers) };
const proxied = proxyUrl(url, headers);
if (needsProxy(headers)) return { kind, url: proxied };
return { kind, url, fallback: proxied };
}
// sub: string url or { url, headers? }
function subtitleUrl(sub, headers) {
const url = typeof sub === 'string' ? sub : sub?.url;
if (!url) return '';
if (url.startsWith('/v1/subs/')) return url;
if (!/^https?:\/\//i.test(url)) return '';
const h = cleanHeaders({ ...(headers || {}), ...(typeof sub === 'object' ? sub.headers || {} : {}) });
return `/v1/subs/${sign({ u: url, h })}`;
}
module.exports = { playbackFor, subtitleUrl, proxyUrl, remuxUrl, magnetFor };
+252
View File
@@ -0,0 +1,252 @@
// Path-based signed media proxy: /v1/p/<token>/<upstream path+query>, token = { o: origin, h: headers }.
// Relative URIs inside playlists resolve to the same token by themselves, so only absolute,
// root-relative, parent-relative or post-redirect URIs get rewritten.
const { pipeline } = require('stream');
const { sign, verify } = require('../sign');
const { send, error, CORS } = require('../http');
const { fetchUpstream, readBody, cleanHeaders, LRU } = require('./net');
const playlistCache = new LRU(300); // key -> { status, body, ct, cc }
const smallCache = new LRU(500); // key -> { status, headers, body }
const inflight = new Map();
const SMALL_MAX = 64 * 1024;
const stats = { active: 0, total: 0, playlistHits: 0, smallHits: 0, errors: 0 };
const M3U8_PATH = /\.m3u8?$/i;
const SNIFF_CT = /^(text\/|application\/octet-stream|binary\/octet-stream|application\/x-mpegurl|application\/vnd\.apple\.mpegurl|audio\/x?-?mpegurl|$)/i;
// Rewrite URIs that would not resolve to the right place relative to the proxied playlist URL.
function rewriteM3u8(text, { base, force, toProxy }) {
const fix = (uri) => {
const u = uri.trim();
if (!u || u.startsWith('data:') || u.startsWith('skd:')) return uri;
const needs = force || /^[a-z][a-z0-9+.-]*:/i.test(u) || u.startsWith('/') || u.startsWith('../');
if (!needs) return uri;
try {
const abs = new URL(u, base);
if (abs.protocol !== 'http:' && abs.protocol !== 'https:') return uri;
return toProxy(abs);
} catch {
return uri;
}
};
return text
.split(/\r?\n/)
.map((line) => {
const t = line.trim();
if (!t) return line;
if (t.startsWith('#')) return line.replace(/(URI\s*=\s*)(?:"([^"]*)"|'([^']*)')/gi, (m, p, d, s) => `${p}"${fix(d ?? s)}"`);
return fix(t);
})
.join('\n');
}
function playlistKind(text) {
if (/#EXT-X-STREAM-INF|#EXT-X-MEDIA:/i.test(text)) return 'master';
if (/#EXT-X-ENDLIST|#EXT-X-PLAYLIST-TYPE:\s*VOD/i.test(text)) return 'vod';
return 'live';
}
function copyHeaders(up, decoded) {
const out = { ...CORS };
for (const k of ['content-type', 'content-range', 'accept-ranges', 'last-modified', 'etag']) if (up[k]) out[k] = up[k];
if (!decoded) {
if (up['content-length']) out['content-length'] = up['content-length'];
if (up['content-encoding']) out['content-encoding'] = up['content-encoding'];
}
return out;
}
/**
* Proxy one request.
* opts: { origin, headers, rest (path+query after origin, no leading '/'), prefix (string to reach
* `<base>/v1/p/` from the playlist's directory), force (rewrite every URI) }
*/
async function proxy(req, res, opts) {
const headers = cleanHeaders(opts.headers);
let target;
try {
const o = new URL(opts.origin);
if (o.protocol !== 'http:' && o.protocol !== 'https:') throw new Error('bad origin');
target = new URL(`${o.origin}/${opts.rest}`);
} catch {
return error(req, res, 400, 'invalid upstream');
}
const range = req.headers.range;
const method = req.method === 'HEAD' ? 'HEAD' : 'GET';
const looksPlaylist = M3U8_PATH.test(target.pathname);
const toProxy = (abs) => `${opts.prefix}${sign({ o: abs.origin, h: headers })}${abs.pathname}${abs.search}`;
const plKey = `${req.url}`;
const smallKey = `${target}|${JSON.stringify(headers)}`;
stats.total++;
// cached playlist / small file
if (!range) {
const pl = playlistCache.get(plKey);
if (pl) {
stats.playlistHits++;
return send(req, res, pl.status, pl.body, pl.ct, { 'Cache-Control': pl.cc });
}
const sm = smallCache.get(smallKey);
if (sm) {
stats.smallHits++;
res.writeHead(sm.status, { ...sm.headers, 'Content-Length': sm.body.length });
return res.end(method === 'HEAD' ? undefined : sm.body);
}
}
// coalesce concurrent playlist fetches (many players poll the same live playlist)
if (looksPlaylist && !range && method === 'GET' && inflight.has(plKey)) {
try {
await inflight.get(plKey);
} catch {}
const pl = playlistCache.get(plKey);
if (pl) return send(req, res, pl.status, pl.body, pl.ct, { 'Cache-Control': pl.cc });
}
const ac = new AbortController();
const onClose = () => {
if (!res.writableFinished) ac.abort();
};
res.on('close', onClose);
const upHeaders = { ...headers, 'accept-encoding': looksPlaylist ? 'gzip, br' : 'identity' };
if (range) upHeaders.range = range;
if (req.headers['if-range']) upHeaders['if-range'] = req.headers['if-range'];
stats.active++;
let done;
if (looksPlaylist && !range && method === 'GET') inflight.set(plKey, new Promise((r) => (done = r)));
try {
let up;
try {
up = await fetchUpstream(target, { headers: upHeaders, method, signal: ac.signal });
} catch (e) {
if (ac.signal.aborted) return;
stats.errors++;
if (e.code === 'EBLOCKED' || e.code === 'EPROTO') return error(req, res, 403, e.message);
return error(req, res, 502, `upstream failed: ${e.message}`);
}
const ct = String(up.headers['content-type'] || '');
const redirected = up.url !== target.toString();
const len = Number(up.headers['content-length'] || NaN);
let playlist = /mpegurl/i.test(ct) || (looksPlaylist && up.statusCode < 400);
let first = null;
if (!playlist && method === 'GET' && !range && up.statusCode === 200 && SNIFF_CT.test(ct) && !(len > 4 * 1024 * 1024)) {
// peek at the first chunk to detect disguised playlists
first = await new Promise((resolve, reject) => {
const onData = (c) => {
cleanup();
up.body.pause();
resolve(c);
};
const onEnd = () => (cleanup(), resolve(Buffer.alloc(0)));
const onErr = (e) => (cleanup(), reject(e));
const cleanup = () => {
up.body.off('data', onData);
up.body.off('end', onEnd);
up.body.off('error', onErr);
};
up.body.on('data', onData).on('end', onEnd).on('error', onErr);
}).catch(() => null);
if (first === null) return error(req, res, 502, 'upstream read failed');
const head = first.subarray(0, 16).toString('utf8').replace(/^/, '').trimStart();
if (head.startsWith('#EXTM3U') || (first[0] === 0x1f && first[1] === 0x8b && looksPlaylist)) playlist = true;
}
if (playlist && method === 'GET') {
let buf;
try {
if (first) up.body.unshift(first);
buf = await readBody(up, 8 * 1024 * 1024);
} catch (e) {
if (ac.signal.aborted) return;
return error(req, res, 502, `playlist read failed: ${e.message}`);
}
const text = buf.toString('utf8').replace(/^/, '');
if (!text.trimStart().startsWith('#EXTM3U') || up.statusCode >= 400) {
return send(req, res, up.statusCode, buf, ct || 'text/plain; charset=utf-8');
}
const body = rewriteM3u8(text, { base: up.url, force: opts.force || redirected, toProxy });
const kind = playlistKind(text);
const cc = kind === 'live' ? 'no-store' : 'public, max-age=30';
const ctOut = 'application/vnd.apple.mpegurl; charset=utf-8';
playlistCache.set(plKey, { status: up.statusCode, body, ct: ctOut, cc }, kind === 'live' ? 3000 : 120000);
return send(req, res, up.statusCode, body, ctOut, { 'Cache-Control': cc });
}
const out = copyHeaders(up.headers, false);
out['cache-control'] = up.statusCode === 200 || up.statusCode === 206 ? 'public, max-age=3600' : 'no-store';
if (!out['accept-ranges'] && up.statusCode === 200) out['accept-ranges'] = 'none';
// tiny non-range files (AES keys, init segments): buffer + cache
if (!range && method === 'GET' && up.statusCode === 200 && len <= SMALL_MAX && !up.headers['content-encoding']) {
const chunks = first ? [first] : [];
for await (const c of up.body) chunks.push(c);
const body = Buffer.concat(chunks);
delete out['content-length'];
smallCache.set(smallKey, { status: 200, headers: out, body }, 10 * 60 * 1000);
res.writeHead(200, { ...out, 'Content-Length': body.length });
return res.end(body);
}
res.writeHead(up.statusCode, out);
if (method === 'HEAD') {
up.body.destroy();
return res.end();
}
if (first) {
if (!res.write(first)) await new Promise((r) => res.once('drain', r));
}
await new Promise((resolve) => {
pipeline(up.body, res, () => resolve());
});
} finally {
stats.active--;
res.off('close', onClose);
if (done) {
inflight.delete(plKey);
done();
}
}
}
// /v1/p/<token>/<rest>
async function handlePath(req, res) {
const m = req.url.match(/^\/v1\/p\/([^/?]+)\/([^]*)$/);
if (!m) return error(req, res, 400, 'bad proxy path');
const tok = verify(m[1]);
if (!tok || typeof tok.o !== 'string') return error(req, res, 403, 'invalid token');
const rest = m[2];
const depth = rest.split('?')[0].split('/').length;
return proxy(req, res, { origin: tok.o, headers: tok.h, rest, prefix: '../'.repeat(depth) });
}
// legacy /proxy/media?url=&h=<json>
async function handleLegacy(req, res, ctx) {
const target = (ctx.url.searchParams.get('url') || '').trim();
let u;
try {
u = new URL(target);
} catch {
return error(req, res, 400, 'missing or invalid ?url=');
}
if (u.protocol !== 'http:' && u.protocol !== 'https:') return error(req, res, 400, 'proxy only supports http/https');
let h = {};
try {
h = JSON.parse(ctx.url.searchParams.get('h') || '{}');
} catch {}
return proxy(req, res, {
origin: u.origin,
headers: h,
rest: `${u.pathname.slice(1)}${u.search}`,
prefix: '../v1/p/', // playlist URL dir is <base>/proxy/
force: true,
});
}
function proxyStats() {
return { ...stats, playlistCache: playlistCache.size, smallCache: smallCache.size };
}
module.exports = { proxy, handlePath, handleLegacy, rewriteM3u8, proxyStats };
+235
View File
@@ -0,0 +1,235 @@
// ffmpeg remux: any container ffmpeg can read → fragmented MP4 on stdout, video copied,
// audio copied when the browser can play it (aac/mp3/opus) else AAC stereo.
// Seeking = new request with ?start=<sec> (input seeking, so ffmpeg uses the container index /
// HTTP range requests); the response carries X-Bug-Tv-Offset so the player can offset its clock.
const { spawn } = require('child_process');
const { CORS, error } = require('../http');
const { assertPublicUrl, LRU } = require('./net');
const probeCache = new LRU(200);
const probeInflight = new Map();
const procs = new Set();
let cfgRef = { remux: { ffmpeg: 'ffmpeg', ffprobe: 'ffprobe', maxProcs: 4 } };
const stats = { started: 0, failed: 0 };
const COPY_AUDIO = new Set(['aac', 'mp3', 'opus']);
function init(cfg) {
cfgRef = cfg;
}
function maxProcs() {
return Number(cfgRef.remux?.maxProcs) || 4;
}
// ffmpeg/ffprobe input options for http headers
function inputArgs(url, headers = {}) {
const args = [];
if (!/^https?:/i.test(url)) return args;
let extra = '';
for (const [k, v] of Object.entries(headers || {})) {
if (typeof v !== 'string' || /[\r\n]/.test(v) || /[\r\n:]/.test(k)) continue;
if (k.toLowerCase() === 'user-agent') args.push('-user_agent', v);
else extra += `${k}: ${v}\r\n`;
}
if (extra) args.push('-headers', extra);
return args;
}
function runProbe(url, headers, timeoutMs = 30000) {
return new Promise((resolve, reject) => {
const args = ['-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', ...inputArgs(url, headers), '-i', url];
const p = spawn(cfgRef.remux?.ffprobe || 'ffprobe', args, { stdio: ['ignore', 'pipe', 'pipe'] });
let out = '';
let err = '';
const t = setTimeout(() => p.kill('SIGKILL'), timeoutMs);
p.stdout.on('data', (c) => (out += c));
p.stderr.on('data', (c) => (err = (err + c).slice(-2000)));
p.on('error', (e) => (clearTimeout(t), reject(e)));
p.on('close', (code) => {
clearTimeout(t);
if (code !== 0) return reject(new Error(`ffprobe failed (${code}): ${err.trim() || 'timeout'}`));
try {
resolve(JSON.parse(out));
} catch (e) {
reject(e);
}
});
});
}
function shape(raw) {
const streams = raw.streams || [];
const v = streams.find((s) => s.codec_type === 'video' && !s.disposition?.attached_pic);
const dur = Number(raw.format?.duration) || Number(v?.duration) || null;
return {
duration: dur,
startTime: Number(raw.format?.start_time) || 0,
container: raw.format?.format_name || null,
video: v ? { codec: v.codec_name, width: v.width, height: v.height, profile: v.profile || null, pixFmt: v.pix_fmt || null } : null,
audio: streams
.filter((s) => s.codec_type === 'audio')
.map((s) => ({
index: s.index,
codec: s.codec_name,
lang: s.tags?.language || '',
channels: s.channels || null,
title: s.tags?.title || '',
default: !!s.disposition?.default,
})),
subtitles: streams
.filter((s) => s.codec_type === 'subtitle')
.map((s) => ({ index: s.index, codec: s.codec_name, lang: s.tags?.language || '', title: s.tags?.title || '' })),
};
}
// Time (relative to the container start) of the keyframe ffmpeg will actually start from when
// input-seeking to `start` with stream copy — it is the keyframe at/before `start`, so the
// remux's t=0 is this, not `start`. Resolves null on failure.
function keyframeAt(url, headers, start, startTime = 0, timeoutMs = 8000) {
return new Promise((resolve) => {
const args = ['-v', 'error', ...inputArgs(url, headers), '-read_intervals', `${start + startTime}%+#1`,
'-select_streams', 'v:0', '-show_entries', 'packet=pts_time', '-of', 'csv=p=0', '-i', url];
const p = spawn(cfgRef.remux?.ffprobe || 'ffprobe', args, { stdio: ['ignore', 'pipe', 'ignore'] });
let out = '';
const t = setTimeout(() => p.kill('SIGKILL'), timeoutMs);
p.stdout.on('data', (c) => (out += c));
p.on('error', () => (clearTimeout(t), resolve(null)));
p.on('close', () => {
clearTimeout(t);
const v = parseFloat(out.trim().split(/\s+/)[0]);
resolve(Number.isFinite(v) ? Math.max(0, v - startTime) : null);
});
});
}
// cached probe → contract shape
async function probe(url, headers, { trusted = false, timeoutMs } = {}) {
const key = `${url}|${JSON.stringify(headers || {})}`;
const hit = probeCache.get(key);
if (hit) return hit;
if (probeInflight.has(key)) return probeInflight.get(key);
const p = (async () => {
if (!trusted) await assertPublicUrl(url);
const info = shape(await runProbe(url, headers, timeoutMs));
probeCache.set(key, info, 6 * 60 * 60 * 1000);
return info;
})().finally(() => probeInflight.delete(key));
probeInflight.set(key, p);
return p;
}
function buildArgs({ url, headers, start, audioStream, video }) {
const args = ['-hide_banner', '-loglevel', 'error', '-nostdin', '-fflags', '+genpts+discardcorrupt'];
if (/^https?:/i.test(url)) args.push('-reconnect', '1', '-reconnect_on_network_error', '1', '-reconnect_delay_max', '4');
args.push(...inputArgs(url, headers));
if (start > 0) args.push('-ss', String(start));
args.push('-i', url, '-map', '0:v:0?');
args.push('-map', audioStream ? `0:${audioStream.index}` : '0:a:0?');
args.push('-c:v', 'copy');
if (video?.codec === 'hevc') args.push('-tag:v', 'hvc1');
if (audioStream && COPY_AUDIO.has(audioStream.codec)) args.push('-c:a', 'copy');
else args.push('-c:a', 'aac', '-b:a', '192k', '-ac', '2');
args.push(
'-sn', '-dn', '-map_metadata', '-1', '-max_muxing_queue_size', '2048',
'-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov+default_base_moof', 'pipe:1',
);
return args;
}
/**
* Stream a remux to `res`.
* opts: { url, headers, start, audio (absolute stream index), trusted (skip SSRF check: internal URLs) }
*/
async function remux(req, res, opts) {
const start = Math.max(0, Number(opts.start) || 0);
const baseHeaders = {
...CORS,
'Content-Type': 'video/mp4',
'Cache-Control': 'no-store',
'X-Bug-Tv-Offset': String(start),
'Accept-Ranges': 'none',
};
if (req.method === 'HEAD') {
res.writeHead(200, baseHeaders);
return res.end();
}
if (procs.size >= maxProcs()) return error(req, res, 503, 'too many concurrent remux sessions', { max: maxProcs() });
let info = null;
try {
if (!opts.trusted) await assertPublicUrl(opts.url);
} catch (e) {
return error(req, res, 403, e.message);
}
try {
info = await probe(opts.url, opts.headers, { trusted: true, timeoutMs: opts.probeTimeoutMs || 20000 });
} catch {
info = null; // ffmpeg will still try; audio gets transcoded
}
if (res.destroyed) return;
if (procs.size >= maxProcs()) return error(req, res, 503, 'too many concurrent remux sessions', { max: maxProcs() });
let audioStream = null;
if (info) {
const want = opts.audio != null && opts.audio !== '' ? Number(opts.audio) : null;
audioStream =
(want != null && info.audio.find((a) => a.index === want)) || info.audio.find((a) => a.default) || info.audio[0] || null;
}
const args = buildArgs({ url: opts.url, headers: opts.headers, start, audioStream, video: info?.video });
const ff = spawn(cfgRef.remux?.ffmpeg || 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'] });
// in parallel: find the real start (keyframe) so X-Bug-Tv-Offset matches the output's t=0
const offsetP = start > 0 && info?.video ? keyframeAt(opts.url, opts.headers, start, info.startTime) : Promise.resolve(null);
procs.add(ff);
stats.started++;
let stderr = '';
let killed = false;
const kill = () => {
if (killed || ff.exitCode !== null) return;
killed = true;
ff.kill('SIGTERM');
setTimeout(() => ff.exitCode === null && ff.kill('SIGKILL'), 2000).unref();
};
ff.stderr.on('data', (c) => (stderr = (stderr + c).slice(-4000)));
res.on('close', kill);
await new Promise((resolve) => {
let started = false;
ff.stdout.once('data', async (chunk) => {
started = true;
ff.stdout.pause();
const real = await offsetP;
if (res.destroyed) return;
const off = real != null && real <= start + 0.001 ? real : start;
res.writeHead(200, { ...baseHeaders, 'X-Bug-Tv-Offset': String(Math.round(off * 1000) / 1000) });
res.write(chunk);
ff.stdout.pipe(res);
});
ff.on('error', (e) => {
stats.failed++;
if (!res.headersSent) error(req, res, 500, `ffmpeg spawn failed: ${e.message}`);
resolve();
});
ff.on('close', (code) => {
procs.delete(ff);
res.off('close', kill);
if (!started) {
stats.failed++;
if (!res.headersSent && !res.destroyed) error(req, res, 502, 'remux failed', { code, stderr: stderr.trim().slice(-800) });
} else if (code !== 0 && !killed) {
res.destroy(); // truncated output: let the player notice
}
resolve();
});
});
}
function remuxStats() {
return { ffmpeg: procs.size, maxProcs: maxProcs(), probesCached: probeCache.size, ...stats };
}
function killAll() {
for (const p of procs) p.kill('SIGKILL');
}
module.exports = { init, remux, probe, keyframeAt, remuxStats, killAll, buildArgs };
+51
View File
@@ -0,0 +1,51 @@
// Classify extensionless stream URLs by their first bytes so HLS/MP4 links
// play natively instead of falling through to ffmpeg remux.
const { fetchUpstream, cleanHeaders, LRU } = require('./net');
const cache = new LRU(2000);
const TTL_MS = 30 * 60 * 1000;
function classify(buf, contentType) {
const ct = String(contentType || '').toLowerCase();
const head = buf.subarray(0, 16);
if (/mpegurl/.test(ct) || buf.toString('utf8', 0, 64).trimStart().startsWith('#EXTM3U')) return 'm3u8';
if (head.length >= 8 && head.toString('latin1', 4, 8) === 'ftyp') return 'mp4';
if (head.length >= 4 && head.readUInt32BE(0) === 0x1a45dfa3) return /webm/.test(ct) ? 'webm' : 'mkv';
if (/video\/mp4/.test(ct)) return 'mp4';
if (/video\/webm/.test(ct)) return 'webm';
if (/matroska/.test(ct)) return 'mkv';
return 'other';
}
// never rejects; resolves 'other' when the upstream can't be read in time
async function sniff(url, headers = {}, timeoutMs = 2500) {
const hit = cache.get(url);
if (hit) return hit;
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), timeoutMs);
let type = 'other';
try {
const r = await fetchUpstream(url, { headers: { ...cleanHeaders(headers), range: 'bytes=0-1023' }, signal: ac.signal });
if (r.statusCode < 400) {
const chunks = [];
let n = 0;
for await (const c of r.body) {
chunks.push(c);
n += c.length;
if (n >= 1024) break;
}
r.body.destroy();
type = classify(Buffer.concat(chunks), r.headers['content-type']);
} else {
r.body.destroy();
}
} catch {
// unreachable/blocked: leave as 'other'
} finally {
clearTimeout(timer);
}
cache.set(url, type, TTL_MS);
return type;
}
module.exports = { sniff, classify };
+11
View File
@@ -0,0 +1,11 @@
// Aggregated media stats for the health route.
const { proxyStats } = require('./proxy');
const { remuxStats } = require('./remux');
const { subsStats } = require('./subs');
const { torrentStats } = require('./torrent');
function mediaStats() {
return { proxy: proxyStats(), remux: remuxStats(), subs: subsStats(), torrent: torrentStats() };
}
module.exports = { mediaStats };
+118
View File
@@ -0,0 +1,118 @@
// Subtitle fetch + conversion to WebVTT (VTT passthrough, SRT, ASS/SSA dialogue), cached.
const { fetchUpstream, readBody, cleanHeaders, LRU } = require('./net');
const cache = new LRU(200);
const inflight = new Map();
const TTL = 30 * 60 * 1000;
function decode(buf) {
if (buf[0] === 0xff && buf[1] === 0xfe) return new TextDecoder('utf-16le').decode(buf.subarray(2));
if (buf[0] === 0xfe && buf[1] === 0xff) return new TextDecoder('utf-16be').decode(buf.subarray(2));
try {
return new TextDecoder('utf-8', { fatal: true }).decode(buf).replace(/^/, '');
} catch {
return new TextDecoder('windows-1252').decode(buf);
}
}
const pad = (n, w = 2) => String(n).padStart(w, '0');
function fmt(ms) {
ms = Math.max(0, Math.round(ms));
const h = Math.floor(ms / 3600000);
const m = Math.floor((ms % 3600000) / 60000);
const s = Math.floor((ms % 60000) / 1000);
return `${pad(h)}:${pad(m)}:${pad(s)}.${pad(ms % 1000, 3)}`;
}
// "01:02:03,456" | "1:02:03.45" | "02:03,456" → ms
function parseTime(t) {
const m = String(t).trim().match(/^(?:(\d+):)?(\d{1,2}):(\d{1,2})(?:[.,:](\d{1,3}))?$/);
if (!m) return NaN;
const frac = m[4] ? Number(m[4].padEnd(3, '0')) : 0;
return ((Number(m[1] || 0) * 60 + Number(m[2])) * 60 + Number(m[3])) * 1000 + frac;
}
function srtToVtt(text) {
const out = ['WEBVTT', ''];
for (const block of text.replace(/\r\n?/g, '\n').split(/\n{2,}/)) {
const lines = block.split('\n');
const ti = lines.findIndex((l) => l.includes('-->'));
if (ti < 0) continue;
const [a, b] = lines[ti].split('-->');
const start = parseTime(a);
const end = parseTime(String(b).trim().split(/\s+/)[0]);
if (Number.isNaN(start) || Number.isNaN(end)) continue;
const body = lines
.slice(ti + 1)
.join('\n')
.replace(/\{\\[^}]*\}/g, '')
.replace(/<\/?font[^>]*>/gi, '')
.trim();
if (!body) continue;
out.push(`${fmt(start)} --> ${fmt(end)}`, body.replace(/-->/g, '→'), '');
}
return out.join('\n');
}
function assToVtt(text) {
const cues = [];
let inEvents = false;
let format = ['layer', 'start', 'end', 'style', 'name', 'marginl', 'marginr', 'marginv', 'effect', 'text'];
for (const raw of text.replace(/\r\n?/g, '\n').split('\n')) {
const line = raw.trim();
if (/^\[.*\]$/.test(line)) {
inEvents = /^\[events\]$/i.test(line);
continue;
}
if (!inEvents) continue;
if (/^format\s*:/i.test(line)) {
format = line.replace(/^format\s*:/i, '').split(',').map((s) => s.trim().toLowerCase());
continue;
}
if (!/^dialogue\s*:/i.test(line)) continue;
const parts = line.replace(/^dialogue\s*:/i, '').split(',');
const fields = parts.slice(0, format.length - 1).concat(parts.slice(format.length - 1).join(','));
const get = (k) => (fields[format.indexOf(k)] ?? '').trim();
const start = parseTime(get('start'));
const end = parseTime(get('end'));
const body = get('text')
.replace(/\{[^}]*\}/g, '')
.replace(/\\[Nn]/g, '\n')
.replace(/\\h/g, ' ')
.trim();
if (Number.isNaN(start) || Number.isNaN(end) || !body) continue;
cues.push({ start, end, body });
}
cues.sort((a, b) => a.start - b.start);
return ['WEBVTT', '', ...cues.flatMap((c) => [`${fmt(c.start)} --> ${fmt(c.end)}`, c.body, ''])].join('\n');
}
function toVtt(buf) {
const text = decode(buf);
const head = text.trimStart().slice(0, 200);
if (/^WEBVTT/.test(head)) return text.replace(/\r\n?/g, '\n');
if (/^\[script info\]/i.test(head) || /^\[v4\+? styles\]/i.test(head) || /\n\s*dialogue\s*:/i.test(text.slice(0, 20000)) && /\[events\]/i.test(text))
return assToVtt(text);
return srtToVtt(text);
}
async function getVtt(tok) {
const key = `${tok.u}|${JSON.stringify(tok.h || {})}`;
const hit = cache.get(key);
if (hit) return hit;
if (inflight.has(key)) return inflight.get(key);
const p = (async () => {
const up = await fetchUpstream(tok.u, { headers: { ...cleanHeaders(tok.h), 'accept-encoding': 'gzip, br' } });
if (up.statusCode >= 400) {
up.body.resume();
throw Object.assign(new Error(`upstream ${up.statusCode}`), { status: 502 });
}
const vtt = toVtt(await readBody(up, 10 * 1024 * 1024));
cache.set(key, vtt, TTL);
return vtt;
})().finally(() => inflight.delete(key));
inflight.set(key, p);
return p;
}
module.exports = { getVtt, toVtt, srtToVtt, assToVtt, subsStats: () => ({ cached: cache.size }) };
+355
View File
@@ -0,0 +1,355 @@
// Server-side WebTorrent: one lazily-created client, torrents deduped by infoHash, one chosen
// file per torrent (fileIdx / SxxEyy match / largest video), range-served when browser-native,
// otherwise remuxed by ffmpeg reading our own /raw range endpoint over loopback (so ffmpeg can
// seek with the container index instead of reading a pipe from byte 0).
const fs = require('fs');
const path = require('path');
const { pipeline } = require('stream');
const { CORS, error, json } = require('../http');
const remux = require('./remux');
const VIDEO = /\.(mkv|mp4|m4v|webm|avi|mov|ts|m2ts|wmv|flv|mpg|mpeg|ogv)$/i;
const NATIVE = /\.(mp4|m4v|webm)$/i;
const MIME = { mp4: 'video/mp4', m4v: 'video/mp4', webm: 'video/webm', mkv: 'video/x-matroska', avi: 'video/x-msvideo', mov: 'video/quicktime', ts: 'video/mp2t' };
const IDLE_MS = 10 * 60 * 1000;
const META_TIMEOUT = 45000;
let cfg = null;
let clientP = null;
const entries = new Map(); // infoHash -> { hash, torrent, ready: Promise, lastRead, readers, fileIdx? }
function init(c) {
cfg = c;
}
function getClient() {
if (!clientP) {
// BUG_TV_WEBTORRENT: optional module path/URL override (testing another webtorrent build)
clientP = import(process.env.BUG_TV_WEBTORRENT || 'webtorrent').then(({ default: WebTorrent }) => {
const client = new WebTorrent({ maxConns: 60 });
client.on('error', (e) => console.error('[torrent] client error:', e.message));
setInterval(sweep, 60000).unref();
return client;
});
}
return clientP;
}
const B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
function infoHashOf(magnet) {
const m = String(magnet).match(/xt=urn:bt[im]h:([a-z0-9]+)/i);
if (!m) return null;
const h = m[1];
if (/^[0-9a-f]{40}$/i.test(h)) return h.toLowerCase();
if (/^[a-z2-7]{32}$/i.test(h)) {
let bits = '';
for (const ch of h.toUpperCase()) bits += B32.indexOf(ch).toString(2).padStart(5, '0');
return bits.match(/.{4}/g).map((b) => parseInt(b, 2).toString(16)).join('');
}
return null;
}
const EXTRA_TRACKERS = [
'udp://tracker.opentrackr.org:1337/announce',
'udp://open.demonii.com:1337/announce',
'udp://tracker.torrent.eu.org:451/announce',
'udp://open.stealth.si:80/announce',
'udp://exodus.desync.com:6969/announce',
'udp://explodie.org:6969/announce',
'udp://tracker.dler.org:6969/announce',
'wss://tracker.openwebtorrent.com',
'wss://tracker.webtorrent.dev',
];
function withTrackers(magnet) {
const have = new Set([...String(magnet).matchAll(/[?&]tr=([^&]+)/g)].map((m) => decodeURIComponent(m[1])));
return magnet + EXTRA_TRACKERS.filter((t) => !have.has(t)).map((t) => `&tr=${encodeURIComponent(t)}`).join('');
}
// Get/create the entry for a magnet. e.meta resolves once metadata + store are ready; it has no
// timeout — a request that gives up (waitReady) leaves the torrent running so a retry/status
// poll finds it ready; idle eviction cleans it up otherwise.
function ensure(tok) {
const hash = infoHashOf(tok.m);
if (!hash) throw Object.assign(new Error('invalid magnet'), { status: 400 });
let e = entries.get(hash);
if (e && !e.torrent?.destroyed) return e;
e = { hash, torrent: null, lastRead: Date.now(), readers: 0, error: null, picks: new Map(), selected: new Set() };
e.meta = (async () => {
const client = await getClient();
const dir = path.join(cfg.torrent.cacheDir, hash);
await fs.promises.mkdir(dir, { recursive: true });
const t = (await client.get(hash)) || client.add(withTrackers(tok.m), { path: dir, deselect: true });
e.torrent = t;
t.on('error', (err) => (e.error = err.message));
if (process.env.BUG_TV_DEBUG) {
const t0 = Date.now();
const log = (...a) => console.log(`[torrent ${hash.slice(0, 8)} +${Date.now() - t0}ms]`, ...a);
t.on('infoHash', () => log('infoHash'));
t.on('metadata', () => log('metadata', t.files.length, 'files'));
t.on('ready', () => log('ready'));
t.on('warning', (w) => log('warning', w?.message || w));
t.on('wire', (w, addr) => log('wire', addr));
}
if (!t.ready) {
await new Promise((resolve, reject) => {
t.once('ready', resolve);
t.once('error', reject);
});
}
enforceDiskCap().catch(() => {});
return t;
})();
e.meta.catch((err) => {
e.error = err.message;
if (entries.get(hash) === e) entries.delete(hash);
try {
e.torrent?.destroy();
} catch {}
});
entries.set(hash, e);
return e;
}
function waitReady(e, ms = META_TIMEOUT) {
let timer;
return Promise.race([
e.meta,
new Promise((_, reject) => {
timer = setTimeout(() => reject(Object.assign(new Error('torrent metadata timeout (still trying; retry)'), { status: 504 })), ms);
}),
]).finally(() => clearTimeout(timer));
}
const pad2 = (n) => String(n).padStart(2, '0');
function pickFile(t, tok) {
const files = t.files.map((f, idx) => ({ f, idx }));
if (Number.isInteger(tok.f) && files[tok.f]) return files[tok.f];
const vids = files.filter(({ f }) => VIDEO.test(f.name) && !/\bsample\b/i.test(f.path));
const pool = vids.length ? vids : files;
const bySize = (a, b) => b.f.length - a.f.length;
if (tok.s != null && tok.e != null) {
const s = Number(tok.s);
const ep = Number(tok.e);
const pats = [
new RegExp(`s0*${s}[ ._-]*e0*${ep}(?!\\d)`, 'i'),
new RegExp(`(?<!\\d)${s}x0*${ep}(?!\\d)`, 'i'),
new RegExp(`\\b(?:episode|ep|e)[ ._-]*0*${ep}(?!\\d)`, 'i'),
new RegExp(`(?<![\\dx.])${s}${pad2(ep)}(?![\\dp])`, 'i'),
];
for (const re of pats) {
const hit = pool.filter(({ f }) => re.test(f.name)).sort(bySize);
if (hit.length) return hit[0];
}
for (const re of pats.slice(0, 2)) {
const hit = pool.filter(({ f }) => re.test(f.path)).sort(bySize);
if (hit.length) return hit[0];
}
}
return pool.slice().sort(bySize)[0];
}
async function fileFor(tok) {
const e = ensure(tok);
const t = await waitReady(e);
const key = `${tok.f ?? ''}|${tok.s ?? ''}|${tok.e ?? ''}`;
let idx = e.picks.get(key);
if (idx == null) {
idx = pickFile(t, tok).idx;
e.picks.set(key, idx);
}
// several tokens (episodes of one season pack) may share a torrent: select, never deselect
if (!e.selected.has(idx)) {
e.selected.add(idx);
t.files[idx].select();
}
return { e, t, file: t.files[idx], idx };
}
function parseRange(h, size) {
const m = String(h || '').match(/^bytes=(\d*)-(\d*)$/);
if (!m || (!m[1] && !m[2])) return null;
let start, end;
if (!m[1]) {
start = Math.max(0, size - Number(m[2]));
end = size - 1;
} else {
start = Number(m[1]);
end = m[2] ? Math.min(Number(m[2]), size - 1) : size - 1;
}
if (start > end || start >= size) return 'invalid';
return { start, end };
}
function ext(name) {
return (name.match(/\.([a-z0-9]+)$/i)?.[1] || '').toLowerCase();
}
// range-serve a torrent file
function serveFile(req, res, e, file) {
const size = file.length;
const r = parseRange(req.headers.range, size);
const headers = { ...CORS, 'Accept-Ranges': 'bytes', 'Content-Type': MIME[ext(file.name)] || 'application/octet-stream', 'Cache-Control': 'no-store' };
if (r === 'invalid') {
res.writeHead(416, { ...headers, 'Content-Range': `bytes */${size}` });
return res.end();
}
const { start, end } = r || { start: 0, end: size - 1 };
if (r) headers['Content-Range'] = `bytes ${start}-${end}/${size}`;
headers['Content-Length'] = end - start + 1;
res.writeHead(r ? 206 : 200, headers);
if (req.method === 'HEAD') return res.end();
e.readers++;
e.lastRead = Date.now();
const stream = file.createReadStream({ start, end });
const touch = setInterval(() => (e.lastRead = Date.now()), 30000);
pipeline(stream, res, () => {
clearInterval(touch);
e.readers--;
e.lastRead = Date.now();
});
}
function loopbackBase() {
const h = cfg.host;
const host = !h || h === '0.0.0.0' ? '127.0.0.1' : h === '::' ? '[::1]' : h.includes(':') ? `[${h}]` : h;
return `http://${host}:${cfg.port}`;
}
function contiguous(t, file) {
let bytes = 0;
const pl = t.pieceLength;
const first = Math.floor(file.offset / pl);
const last = Math.floor((file.offset + file.length - 1) / pl);
for (let i = first; i <= last; i++) {
if (!t.bitfield.get(i)) break;
bytes = Math.min(file.length, (i + 1) * pl - file.offset);
}
return bytes;
}
async function handle(req, res, tok, action, rawToken, url) {
if (cfg.torrent?.enable === false) return error(req, res, 501, 'torrents disabled');
try {
if (action === 'status') {
const e = ensure(tok);
e.lastRead = Date.now();
const t = e.torrent;
if (!t || !t.ready) {
return json(req, res, 200, { ready: false, name: t?.name || null, file: null, peers: t?.numPeers || 0, downSpeed: t?.downloadSpeed || 0, progress: 0, buffered: 0, error: e.error });
}
const { file, idx } = await fileFor(tok);
const buf = contiguous(t, file);
return json(req, res, 200, {
ready: true,
infoHash: e.hash,
name: t.name,
file: { idx, name: file.name, size: file.length, container: ext(file.name), remux: !NATIVE.test(file.name) },
peers: t.numPeers,
downSpeed: Math.round(t.downloadSpeed),
progress: Number(file.progress.toFixed(4)),
buffered: file.length ? Number((buf / file.length).toFixed(4)) : 0,
bufferedBytes: buf,
});
}
if (action === 'files') {
const t = await waitReady(ensure(tok));
return json(req, res, 200, { files: t.files.map((f, idx) => ({ idx, name: f.path, size: f.length })) });
}
const { e, file } = await fileFor(tok);
e.lastRead = Date.now();
if (action === 'raw' || (action === 'stream' && NATIVE.test(file.name))) return serveFile(req, res, e, file);
const rawUrl = `${loopbackBase()}/v1/torrent/${rawToken}/raw`;
if (action === 'probe') {
const info = await remux.probe(rawUrl, {}, { trusted: true, timeoutMs: 120000 });
const start = parseFloat(url.searchParams.get('start'));
if (!(start > 0) || !info?.video) return json(req, res, 200, info);
return json(req, res, 200, { ...info, keyframe: await remux.keyframeAt(rawUrl, {}, start, info.startTime) });
}
// stream (non-native) → remux via loopback /raw
if (cfg.remux?.enable === false) return error(req, res, 501, 'remux disabled; use /raw');
return remux.remux(req, res, {
url: rawUrl,
headers: {},
start: url.searchParams.get('start'),
audio: url.searchParams.get('audio'),
trusted: true,
probeTimeoutMs: 120000,
});
} catch (err) {
if (res.headersSent) return res.destroy();
return error(req, res, err.status || 502, err.message);
}
}
function sweep() {
const now = Date.now();
for (const [hash, e] of entries) {
if (e.readers > 0 || now - e.lastRead < IDLE_MS) continue;
entries.delete(hash);
try {
e.torrent?.destroy();
} catch {}
}
enforceDiskCap().catch(() => {});
}
async function dirSize(p) {
let total = 0;
const st = await fs.promises.lstat(p).catch(() => null);
if (!st) return 0;
if (!st.isDirectory()) return st.size;
for (const n of await fs.promises.readdir(p)) total += await dirSize(path.join(p, n));
return total;
}
let capRunning = false;
async function enforceDiskCap() {
const max = Number(cfg.torrent?.maxSizeGB || 0) * 1024 ** 3;
if (!max || capRunning) return;
capRunning = true;
try {
const root = cfg.torrent.cacheDir;
const names = await fs.promises.readdir(root).catch(() => []);
const items = [];
for (const n of names) {
const p = path.join(root, n);
const st = await fs.promises.stat(p).catch(() => null);
if (!st?.isDirectory()) continue;
const e = entries.get(n);
items.push({ n, p, size: await dirSize(p), used: e ? e.lastRead : st.mtimeMs, e });
}
let total = items.reduce((a, b) => a + b.size, 0);
items.sort((a, b) => a.used - b.used);
for (const it of items) {
if (total <= max) break;
if (it.e && it.e.readers > 0) continue;
if (it.e) {
entries.delete(it.n);
await new Promise((r) => it.e.torrent ? it.e.torrent.destroy({ destroyStore: false }, r) : r());
}
await fs.promises.rm(it.p, { recursive: true, force: true });
total -= it.size;
}
} finally {
capRunning = false;
}
}
function torrentStats() {
let peers = 0;
let down = 0;
for (const e of entries.values()) {
peers += e.torrent?.numPeers || 0;
down += e.torrent?.downloadSpeed || 0;
}
return { active: entries.size, readers: [...entries.values()].reduce((a, e) => a + e.readers, 0), peers, downSpeed: Math.round(down) };
}
async function shutdown() {
if (!clientP) return;
const c = await clientP;
await new Promise((r) => c.destroy(r));
}
module.exports = { init, handle, pickFile, infoHashOf, torrentStats, shutdown, enforceDiskCap };
@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>tv.bug.tools api</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/swagger-ui.css" />
<style>
html { box-sizing: border-box; }
*, *:before, *:after { box-sizing: inherit; }
@@ -265,7 +265,7 @@
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/swagger-ui-bundle.js"></script>
<script>
window.addEventListener('load', function () {
var ui = SwaggerUIBundle({
+5
View File
@@ -0,0 +1,5 @@
const { json } = require('../http');
module.exports = {
routes: [{ method: 'GET', path: '/healthz', handler: (req, res) => json(req, res, 200, { ok: true }) }],
};
+49
View File
@@ -0,0 +1,49 @@
const fs = require('fs');
const path = require('path');
const { json, send } = require('../http');
const SWAGGER_HTML = fs.readFileSync(path.join(__dirname, '..', 'public', 'index.html'));
const q = (name, description, schema = { type: 'string' }, required = false) => ({ name, in: 'query', required, description, schema });
const p = (name, description) => ({ name, in: 'path', required: true, description, schema: { type: 'string' } });
const ok = (description, type = 'application/json') => ({ 200: { description, content: { [type]: {} } } });
const mediaParams = [
q('tmdb', 'TMDB id', { type: 'integer' }, true),
q('type', 'movie or tv', { type: 'string', enum: ['movie', 'tv'] }),
q('season', 'season number (tv)', { type: 'integer' }),
q('episode', 'episode number (tv)', { type: 'integer' }),
q('providers', 'comma separated provider ids (default: configured)'),
];
const spec = {
openapi: '3.0.3',
info: { title: 'bug.tv api', version: '5.0.0', description: 'See docs/api.md for the full contract.' },
paths: {
'/healthz': { get: { tags: ['meta'], summary: 'Liveness', responses: ok('ok') } },
'/v1/providers': { get: { tags: ['meta'], summary: 'Providers with manifest metadata and health', responses: ok('providers') } },
'/v1/streams': {
get: {
tags: ['streams'],
summary: 'Scrape providers; SSE (meta, streams, provider, done) by default, JSON with format=json',
parameters: [...mediaParams, q('format', 'json for an aggregated response'), q('minQuality', 'any|480|720|1080|2160')],
responses: ok('event stream', 'text/event-stream'),
},
},
'/v1/prefetch': { get: { tags: ['streams'], summary: 'Warm the stream cache in the background', parameters: mediaParams, responses: { 202: { description: 'queued' } } } },
'/v1/p/{token}/{path}': { get: { tags: ['media'], summary: 'Signed media proxy (path-based, range aware)', parameters: [p('token', 'signed token'), p('path', 'upstream path')], responses: ok('upstream body', 'application/octet-stream') } },
'/v1/remux/{token}': { get: { tags: ['media'], summary: 'ffmpeg remux to fragmented MP4', parameters: [p('token', 'signed token'), q('start', 'start offset seconds', { type: 'number' })], responses: ok('fragmented mp4', 'video/mp4') } },
'/v1/remux/{token}/probe': { get: { tags: ['media'], summary: 'ffprobe summary', parameters: [p('token', 'signed token')], responses: ok('probe') } },
'/v1/torrent/{token}/stream': { get: { tags: ['media'], summary: 'Stream a torrent file (range or remux)', parameters: [p('token', 'signed token'), q('start', 'start offset seconds (remux)', { type: 'number' })], responses: ok('media', 'video/mp4') } },
'/v1/torrent/{token}/status': { get: { tags: ['media'], summary: 'Torrent readiness, peers, speed', parameters: [p('token', 'signed token')], responses: ok('status') } },
'/v1/torrent/{token}/files': { get: { tags: ['media'], summary: 'Files in the torrent', parameters: [p('token', 'signed token')], responses: ok('files') } },
'/v1/subs/{token}': { get: { tags: ['media'], summary: 'Subtitle converted to WebVTT', parameters: [p('token', 'signed token')], responses: ok('vtt', 'text/vtt') } },
},
};
module.exports = {
routes: [
{ method: 'GET', path: '/', handler: (req, res) => send(req, res, 200, SWAGGER_HTML, 'text/html; charset=utf-8') },
{ method: 'GET', path: '/api.json', handler: (req, res) => json(req, res, 200, spec) },
],
};
+35
View File
@@ -0,0 +1,35 @@
// GET /v1/providers (manifest metadata + defaults + health), legacy GET /providers.
const { json } = require('../http');
const scrape = require('../scrape');
function v1(req, res) {
const defaults = scrape.defaults();
const providers = scrape.list().map((id) => {
const m = scrape.meta(id) || {};
const h = scrape.health.get(id);
return {
id,
name: m.name || id,
enabled: defaults.includes(id),
types: m.supportedTypes || ['movie', 'tv'],
formats: m.formats || [],
language: m.contentLanguage || [],
logo: m.logo || '',
description: m.description || '',
health: { ok: h.ok, empty: h.empty, fail: h.fail, timeouts: h.timeouts, avgMs: h.avgMs, p90Ms: h.p90Ms, budgetMs: h.budgetMs },
};
});
return json(req, res, 200, { defaults, providers, stats: scrape.stats() });
}
function legacy(req, res) {
return json(req, res, 200, { all: scrape.list(), enabled: scrape.defaults() });
}
module.exports = {
init: (cfg) => scrape.init(cfg),
routes: [
{ method: 'GET', path: '/v1/providers', handler: v1 },
{ method: 'GET', path: '/providers', handler: legacy },
],
};
+12
View File
@@ -0,0 +1,12 @@
const net = require('../media/net');
const { handlePath, handleLegacy } = require('../media/proxy');
module.exports = {
init(cfg) {
net.init(cfg);
},
routes: [
{ method: 'GET', path: /^\/v1\/p\/([^/]+)\/(.+)$/, handler: (req, res) => handlePath(req, res) },
{ method: 'GET', path: '/proxy/media', handler: (req, res, ctx) => handleLegacy(req, res, ctx) },
],
};
+50
View File
@@ -0,0 +1,50 @@
const { verify } = require('../sign');
const { json, error } = require('../http');
const remux = require('../media/remux');
const net = require('../media/net');
let enabled = true;
function token(req, res, ctx) {
if (!enabled) return error(req, res, 501, 'remux disabled'), null;
const tok = verify(ctx.params[0]);
if (!tok || typeof tok.u !== 'string') return error(req, res, 403, 'invalid token'), null;
return tok;
}
module.exports = {
init(cfg) {
enabled = cfg.remux?.enable !== false;
net.init(cfg);
remux.init(cfg);
},
routes: [
{
method: 'GET',
path: /^\/v1\/remux\/([^/]+)\/probe$/,
async handler(req, res, ctx) {
const tok = token(req, res, ctx);
if (!tok) return;
try {
const info = await remux.probe(tok.u, tok.h);
// ?start=: also report the keyframe the remux will really begin at (the player's clock offset)
const start = parseFloat(ctx.url.searchParams.get('start'));
if (!(start > 0) || !info?.video) return json(req, res, 200, info, { 'Cache-Control': 'public, max-age=3600' });
return json(req, res, 200, { ...info, keyframe: await remux.keyframeAt(tok.u, tok.h, start, info.startTime) });
} catch (e) {
return error(req, res, e.code === 'EBLOCKED' ? 403 : 502, e.message);
}
},
},
{
method: 'GET',
path: /^\/v1\/remux\/([^/]+)$/,
async handler(req, res, ctx) {
const tok = token(req, res, ctx);
if (!tok) return;
const q = ctx.url.searchParams;
return remux.remux(req, res, { url: tok.u, headers: tok.h, start: q.get('start'), audio: q.get('audio') });
},
},
],
};
+203
View File
@@ -0,0 +1,203 @@
// GET /v1/streams (SSE or JSON), GET|POST /v1/prefetch, legacy GET /streams. See docs/api.md.
const { json, error, sse } = require('../http');
const scrape = require('../scrape');
const tmdb = require('../tmdb');
const { toPublic, toLegacy } = require('../scrape/normalize');
const { applyFilters, rankStreams, filtersFrom } = require('../scrape/filter');
const MAX_PROVIDERS = 100;
// -> { p, names } or { err }
function parseParams(url, cfg) {
const q = url.searchParams;
const id = (q.get('tmdb') || q.get('id') || '').trim();
if (!/^\d+$/.test(id)) return { err: 'missing or invalid ?tmdb=<id>' };
const type = q.get('type') === 'tv' ? 'tv' : 'movie';
const season = (q.get('season') || '').trim();
const episode = (q.get('episode') || '').trim();
if (type === 'tv') {
if (!season || !episode) return { err: 'tv streams need ?season=<n>&episode=<n>' };
if (!/^\d+$/.test(season) || !/^\d+$/.test(episode)) return { err: 'season and episode must be numbers' };
}
const param = q.get('providers');
let names = param ? param.split(',').map((s) => s.trim()).filter(Boolean) : scrape.defaults();
names = [...new Set(names)].slice(0, MAX_PROVIDERS);
if (!names.length) return { err: 'no providers requested' };
return {
p: { tmdb: id, type, season: type === 'tv' ? parseInt(season, 10) : null, episode: type === 'tv' ? parseInt(episode, 10) : null },
names,
filters: filtersFrom(q, cfg.filters),
fresh: q.get('fresh') === '1',
};
}
function wantsJson(req, url) {
const f = url.searchParams.get('format');
if (f) return f === 'json';
const accept = String(req.headers.accept || '');
return accept.includes('application/json') && !accept.includes('text/event-stream');
}
const score = (name) => scrape.health.score(name);
function shape(r, filters) {
return rankStreams(applyFilters(r.streams, filters), score);
}
// run every provider; onResult(r, fromCache) fires as each settles
async function runAll(names, p, onResult, fresh = false) {
const cachedNames = [];
const jobs = [];
let warmed = false;
for (const name of names) {
const hit = !fresh && scrape.cached(name, p);
if (hit) {
cachedNames.push(name);
jobs.push(Promise.resolve().then(() => onResult(hit, true)));
continue;
}
if (!warmed) {
scrape.warm(p); // details/external_ids/season fetched once in the main thread, joined by workers
warmed = true;
}
jobs.push(scrape.scrape(name, p, { fresh }).then((r) => onResult(r, false)));
}
return { cachedNames, done: Promise.all(jobs) };
}
function budgetFor(names, p, cachedNames) {
const live = names.filter((n) => !cachedNames.includes(n) && scrape.exists(n) && scrape.supports(n, p.type));
return live.length ? Math.max(...live.map((n) => scrape.health.budget(n))) : 0;
}
async function handleSse(req, res, { p, names, filters, fresh }) {
const t0 = Date.now();
const net0 = tmdb.stats().network;
const ev = sse(req, res);
const dbg = { calls: 0, local: 0, remote: 0 };
let total = 0;
const pending = [];
let metaSent = false;
const onResult = (r, fromCache) => {
if (!fromCache && r.tmdb) for (const k in dbg) dbg[k] += r.tmdb[k] || 0;
if (!metaSent) return pending.push([r, fromCache]);
if (ev.closed) return;
const streams = shape(r, filters).map(toPublic);
total += streams.length;
const ms = fromCache ? 0 : r.ms;
if (streams.length) ev.event('streams', { provider: r.name, ms, streams });
const pe = { name: r.name, status: r.status, ms, count: streams.length };
if (r.error) pe.error = r.error;
if (fromCache) pe.cached = true;
ev.event('provider', pe);
};
const { cachedNames, done } = await runAll(names, p, onResult, fresh);
ev.event('meta', {
tmdb: p.tmdb,
type: p.type,
season: p.season,
episode: p.episode,
providers: names,
timeoutMs: budgetFor(names, p, cachedNames),
cached: cachedNames,
});
metaSent = true;
for (const [r, c] of pending.splice(0)) onResult(r, c);
await done;
ev.event('done', { total, ms: Date.now() - t0, debug: { tmdb: { ...dbg, network: tmdb.stats().network - net0 } } });
ev.close();
}
async function collect(names, p, fresh) {
const out = [];
const { done } = await runAll(names, p, (r, fromCache) => out.push({ r, fromCache }), fresh);
await done;
return out;
}
async function handleJson(req, res, { p, names, filters, fresh }) {
const t0 = Date.now();
const results = await collect(names, p, fresh);
const providerErrors = {};
const providers = {};
let streams = [];
for (const { r, fromCache } of results) {
const kept = applyFilters(r.streams, filters);
streams.push(...kept);
providers[r.name] = { status: r.status, ms: fromCache ? 0 : r.ms, count: kept.length, ...(fromCache ? { cached: true } : {}) };
if ((r.status === 'error' || r.status === 'timeout') && r.error) providerErrors[r.name] = r.error;
}
streams = rankStreams(streams, score).map(toPublic);
return json(req, res, 200, {
tmdb_id: p.tmdb,
type: p.type,
season: p.season,
episode: p.episode,
total: streams.length,
streams,
providerErrors,
providers,
ms: Date.now() - t0,
});
}
async function streams(req, res, ctx) {
const parsed = parseParams(ctx.url, ctx.cfg);
if (parsed.err) return error(req, res, 400, parsed.err);
if (wantsJson(req, ctx.url)) return handleJson(req, res, parsed);
return handleSse(req, res, parsed);
}
async function prefetch(req, res, ctx) {
const parsed = parseParams(ctx.url, ctx.cfg);
if (parsed.err) return error(req, res, 400, parsed.err);
const { p, names } = parsed;
const queued = names.filter((n) => scrape.exists(n) && scrape.supports(n, p.type) && !scrape.cached(n, p));
if (queued.length) {
scrape.warm(p);
for (const n of queued) scrape.scrape(n, p);
}
return json(req, res, 202, { queued });
}
// v4 shape: aggregated JSON, raw urls + headers, filters from query/cfg
async function legacy(req, res, ctx) {
const parsed = parseParams(ctx.url, ctx.cfg);
if (parsed.err) return error(req, res, 400, parsed.err);
const { p, names, filters } = parsed;
const loadErrors = {};
for (const n of names) if (!scrape.exists(n)) loadErrors[n] = 'not found';
const valid = names.filter((n) => scrape.exists(n));
if (!valid.length) return error(req, res, 500, 'no providers available', { loadErrors });
const results = await collect(valid, p);
const providerErrors = {};
const all = [];
for (const { r } of results) {
all.push(...r.streams);
if ((r.status === 'error' || r.status === 'timeout') && r.error) providerErrors[r.name] = r.error;
}
const ranked = rankStreams(applyFilters(all, filters), score);
return json(req, res, 200, {
tmdb_id: p.tmdb,
type: p.type,
season: p.season,
episode: p.episode,
total: all.length,
matched: ranked.length,
streams: ranked.map(toLegacy),
providerErrors,
loadErrors,
});
}
module.exports = {
init: (cfg) => scrape.init(cfg),
routes: [
{ method: 'GET', path: '/v1/streams', handler: streams },
{ method: 'GET', path: '/v1/prefetch', handler: prefetch },
{ method: 'POST', path: '/v1/prefetch', handler: prefetch },
{ method: 'GET', path: '/streams', handler: legacy },
],
};
+27
View File
@@ -0,0 +1,27 @@
const { verify } = require('../sign');
const { send, error } = require('../http');
const { getVtt } = require('../media/subs');
const net = require('../media/net');
module.exports = {
init(cfg) {
net.init(cfg);
},
routes: [
{
method: 'GET',
path: /^\/v1\/subs\/([^/]+?)(?:\.vtt)?$/,
async handler(req, res, ctx) {
const tok = verify(ctx.params[0]);
if (!tok || typeof tok.u !== 'string') return error(req, res, 403, 'invalid token');
try {
const vtt = await getVtt(tok);
return send(req, res, 200, vtt, 'text/vtt; charset=utf-8', { 'Cache-Control': 'public, max-age=3600' });
} catch (e) {
if (e.code === 'EBLOCKED' || e.code === 'EPROTO') return error(req, res, 403, e.message);
return error(req, res, 502, `subtitle fetch failed: ${e.message}`);
}
},
},
],
};
+21
View File
@@ -0,0 +1,21 @@
const { verify } = require('../sign');
const { error } = require('../http');
const torrent = require('../media/torrent');
module.exports = {
init(cfg) {
torrent.init(cfg);
},
routes: [
{
method: 'GET',
path: /^\/v1\/torrent\/([^/]+)\/(stream|status|files|raw|probe)$/,
async handler(req, res, ctx) {
if (ctx.cfg.torrent?.enable === false) return error(req, res, 501, 'torrents disabled');
const tok = verify(ctx.params[0]);
if (!tok || typeof tok.m !== 'string') return error(req, res, 403, 'invalid token');
return torrent.handle(req, res, tok, ctx.params[1], ctx.params[0], ctx.url);
},
},
],
};
+150
View File
@@ -0,0 +1,150 @@
// Installed inside each scrape worker. Wraps globalThis.fetch so that:
// - api.themoviedb.org/3/... requests are answered from a cache keyed by path + sorted query
// (api_key dropped). Seeded per job by the main thread; misses are resolved by the main
// thread (shared cache + in-flight dedupe across workers, real key from cfg).
// - every other request gets a per-fetch timeout and the current job's AbortSignal
// (AsyncLocalStorage, so concurrent jobs in one worker each keep their own signal).
// - connections go through a keep-alive undici Agent (global dispatcher).
const { AsyncLocalStorage } = require('async_hooks');
const dns = require('dns');
const net = require('net');
const { createCache } = require('../cache');
const { canonical } = require('../tmdb');
const als = new AsyncLocalStorage();
const local = createCache({ max: 2000, ttlMs: 6 * 3600e3 });
const totals = { calls: 0, local: 0, remote: 0, errors: 0 };
let realFetch = null;
let fetchTimeoutMs = 15000;
let askMain = null;
function seed(entries) {
for (const [k, v] of entries || []) if (!local.has(k)) local.set(k, v);
}
function urlOf(input) {
if (typeof input === 'string') return input;
if (input instanceof URL) return input.href;
return input?.url || String(input);
}
function jsonResponse(v) {
return new Response(v.body, {
status: v.status,
headers: { 'content-type': 'application/json;charset=utf-8' },
});
}
function abortError(signal) {
const r = signal?.reason;
return r instanceof Error ? r : new DOMException('This operation was aborted', 'AbortError');
}
async function tmdbFetch(c, ctx) {
totals.calls++;
if (ctx) ctx.tmdb.calls++;
let v = local.get(c.key);
if (!v && c.derive) {
const base = local.get(c.derive.base);
if (base && base.status === 200) {
v = { status: 200, body: JSON.stringify(JSON.parse(base.body)[c.derive.field] ?? {}) };
local.set(c.key, v);
}
}
if (v) {
totals.local++;
if (ctx) ctx.tmdb.local++;
return jsonResponse(v);
}
totals.remote++;
if (ctx) ctx.tmdb.remote++;
const signal = ctx?.signal;
if (signal?.aborted) throw abortError(signal);
// local.wrap dedupes concurrent identical misses inside this worker
const p = local.wrap(c.key, () => askMain(c), (val) => (val.status === 200 ? 6 * 3600e3 : val.status === 404 ? 600e3 : 0));
const value = await (signal
? Promise.race([
p,
new Promise((_, rej) => signal.addEventListener('abort', () => rej(abortError(signal)), { once: true })),
])
: p);
return jsonResponse(value);
}
function shimFetch(input, init = {}) {
const ctx = als.getStore();
const method = String(init?.method || input?.method || 'GET').toUpperCase();
const c = method === 'GET' ? canonical(urlOf(input)) : null;
if (c) {
return tmdbFetch(c, ctx).catch((e) => {
totals.errors++;
throw e;
});
}
const signals = [AbortSignal.timeout(fetchTimeoutMs)];
if (ctx?.signal) signals.push(ctx.signal);
const own = init?.signal || (input instanceof Request ? input.signal : null);
if (own) signals.push(own);
if (ctx) ctx.fetches++;
return realFetch(input, { ...init, signal: AbortSignal.any(signals) });
}
// DNS via c-ares (dns.Resolver) instead of getaddrinfo: dead provider domains otherwise hog
// libuv's 4 threadpool threads for seconds and stall every other provider's lookups.
const resolver = new dns.Resolver({ timeout: 2500, tries: 2 });
const dnsCache = new Map(); // host -> { addrs | err, expires }
function lookup(host, opts, cb) {
if (typeof opts === 'function') [cb, opts] = [opts, {}];
if (typeof opts === 'number') opts = { family: opts };
opts = opts || {};
if (net.isIP(host) || !host.includes('.') || opts.family === 6) return dns.lookup(host, opts, cb);
const reply = (e) => {
if (e.err) return cb(e.err);
if (opts.all) return cb(null, e.addrs);
cb(null, e.addrs[0].address, e.addrs[0].family);
};
const hit = dnsCache.get(host);
if (hit && hit.expires > Date.now()) return process.nextTick(reply, hit);
resolver.resolve4(host, { ttl: true }, (err, recs) => {
if (err || !recs?.length) {
if (err && (err.code === 'ENOTFOUND' || err.code === 'ENODATA' || err.code === 'ETIMEOUT')) {
const e = { err, expires: Date.now() + 30e3 };
dnsCache.set(host, e);
return reply(e);
}
return dns.lookup(host, opts, cb); // resolver unavailable: fall back to the OS
}
const ttl = Math.min(300, Math.max(30, Math.min(...recs.map((r) => r.ttl || 60))));
const e = { addrs: recs.map((r) => ({ address: r.address, family: 4 })), expires: Date.now() + ttl * 1000 };
dnsCache.set(host, e);
if (dnsCache.size > 2000) dnsCache.delete(dnsCache.keys().next().value);
reply(e);
});
}
function install(opts = {}) {
if (realFetch) return;
fetchTimeoutMs = opts.fetchTimeoutMs || fetchTimeoutMs;
askMain = opts.askMain;
try {
const { Agent, setGlobalDispatcher } = require('undici');
setGlobalDispatcher(
new Agent({
keepAliveTimeout: 30e3,
keepAliveMaxTimeout: 120e3,
connections: 32,
connect: { timeout: 8000, lookup },
})
);
} catch {}
realFetch = globalThis.fetch.bind(globalThis);
globalThis.fetch = shimFetch;
}
// run fn inside a job context: { signal, provider, tmdb: {calls, local, remote}, fetches }
function runInJob(ctx, fn) {
return als.run(ctx, fn);
}
module.exports = { install, seed, runInJob, current: () => als.getStore(), totals };
+45
View File
@@ -0,0 +1,45 @@
// Stream filters (ported from mod/filter.js). Works on internal or public stream records.
const QUALITY_MIN = { any: 0, 480: 480, 720: 720, 1080: 1080, 2160: 2160 };
const AUDIO_OPTIONS = ['any', 'aac', 'ac3', 'dts', 'opus', 'mp3', 'flac', 'multi'];
const SUBTITLE_OPTIONS = ['any', 'required', 'lang'];
const langCode = (lang) => String(lang || '').toLowerCase().replace(/[^a-z]/g, '').slice(0, 2);
function hasSubtitleLang(subs, wanted) {
const want = langCode(wanted);
if (!want) return true;
return subs.some((s) => (langCode(s.lang ?? s.language) || langCode(s.label ?? s.name)) === want);
}
// query params override cfg.filters
function filtersFrom(searchParams, defaults = {}) {
const pick = (k, d) => searchParams.get(k) || defaults[k] || d;
return {
minQuality: String(pick('minQuality', 'any')).replace(/p$/i, ''),
audioCodec: pick('audioCodec', 'any'),
subtitles: pick('subtitles', 'any'),
subtitleLang: pick('subtitleLang', ''),
};
}
function applyFilters(streams, filters = {}) {
const minPixels = QUALITY_MIN[filters.minQuality] ?? 0;
return streams.filter((s) => {
if (minPixels > 0 && (s.pixels == null || s.pixels < minPixels)) return false;
if (filters.audioCodec && filters.audioCodec !== 'any' && s.audio !== filters.audioCodec) return false;
if (filters.subtitles && filters.subtitles !== 'any') {
if (!s.subtitles.length) return false;
if (filters.subtitles === 'lang' && filters.subtitleLang && !hasSubtitleLang(s.subtitles, filters.subtitleLang)) return false;
}
return true;
});
}
// pixels desc, then provider score desc (scoreOf(name) -> number)
function rankStreams(streams, scoreOf = () => 0) {
return streams
.slice()
.sort((a, b) => (b.pixels || 0) - (a.pixels || 0) || scoreOf(b.provider) - scoreOf(a.provider) || (b.seeds || 0) - (a.seeds || 0));
}
module.exports = { applyFilters, rankStreams, filtersFrom, QUALITY_MIN, AUDIO_OPTIONS, SUBTITLE_OPTIONS };
+75
View File
@@ -0,0 +1,75 @@
// Per-provider latency/success stats (in memory) -> adaptive scrape budget + ordering score.
const RING = 32;
const ALPHA = 0.3;
const MIN_BUDGET = 3000;
const stats = new Map(); // name -> { ok, empty, fail, timeouts, ewma, ring[], i }
let maxBudget = 20000;
function init(cfg) {
maxBudget = cfg.timeoutMs || maxBudget;
}
function entry(name) {
let s = stats.get(name);
if (!s) {
s = { ok: 0, empty: 0, fail: 0, timeouts: 0, ewma: null, ring: [], i: 0 };
stats.set(name, s);
}
return s;
}
// status: ok | empty | error | timeout
function record(name, status, ms) {
const s = entry(name);
if (status === 'ok') s.ok++;
else if (status === 'empty') s.empty++;
else if (status === 'timeout') s.timeouts++;
else s.fail++;
// timeouts count at the budget they hit, so p90 grows towards the cap for slow providers
if (status !== 'error' || ms > 0) {
s.ewma = s.ewma == null ? ms : s.ewma * (1 - ALPHA) + ms * ALPHA;
if (s.ring.length < RING) s.ring.push(ms);
else s.ring[s.i] = ms;
s.i = (s.i + 1) % RING;
}
}
function p90(s) {
if (!s.ring.length) return null;
const sorted = s.ring.slice().sort((a, b) => a - b);
return sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * 0.9) - 1)];
}
// ms the provider gets before its fetches are aborted
function budget(name) {
const s = stats.get(name);
const p = s && s.ok + s.empty >= 2 ? p90(s) : null; // need a couple of samples first
if (p == null) return maxBudget;
return Math.round(Math.min(maxBudget, Math.max(MIN_BUDGET, p * 1.5)));
}
// higher is better: success rate weighted by speed
function score(name) {
const s = stats.get(name);
if (!s) return 0.5;
const total = s.ok + s.empty + s.fail + s.timeouts;
const rate = (s.ok + 1) / (total + 2);
return rate * (2000 / ((s.ewma ?? 4000) + 2000));
}
function get(name) {
const s = stats.get(name);
if (!s) return { ok: 0, empty: 0, fail: 0, timeouts: 0, avgMs: null, p90Ms: null, budgetMs: budget(name) };
return {
ok: s.ok,
empty: s.empty,
fail: s.fail,
timeouts: s.timeouts,
avgMs: s.ewma == null ? null : Math.round(s.ewma),
p90Ms: p90(s),
budgetMs: budget(name),
};
}
module.exports = { init, record, budget, score, get };
+140
View File
@@ -0,0 +1,140 @@
// Scrape orchestration shared by routes/streams.js and routes/providers.js:
// provider registry (manifest), worker pool, per-provider result cache, health.
// Providers that bypass fetch (http/https modules) still resolve via getaddrinfo on libuv's
// shared threadpool; widen it before first use so dead domains can't starve it.
process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || '24';
const fs = require('fs');
const path = require('path');
const { createCache } = require('../cache');
const tmdb = require('../tmdb');
const health = require('./health');
const { createPool } = require('./pool');
const { normalizeAll, streamType } = require('./normalize');
const { sniff } = require('../media/sniff');
// extensionless URLs: look at the first bytes so they get the right playback kind
async function sniffUnknown(list) {
await Promise.all(
(list || []).map(async (raw) => {
if (!raw || !/^https?:/i.test(raw.url || '')) return;
if (streamType(raw.url, `${raw.name || ''} ${raw.title || ''}`, raw) !== 'other') return;
const t = await sniff(raw.url, raw.headers);
if (t !== 'other') raw._sniffed = t;
})
);
}
const PROVIDERS_DIR = path.join(__dirname, '..', '..', 'providers');
const EMPTY_TTL = 5 * 60e3;
let cfg = null;
let pool = null;
let results = null;
let manifest = new Map();
let available = new Set();
function loadManifest() {
available = new Set(
fs
.readdirSync(PROVIDERS_DIR)
.filter((f) => f.endsWith('.js'))
.map((f) => f.slice(0, -3))
);
manifest = new Map();
try {
const m = JSON.parse(fs.readFileSync(path.join(PROVIDERS_DIR, 'manifest.json'), 'utf8'));
for (const s of m.scrapers || []) manifest.set(s.id, s);
} catch {}
}
function init(c) {
if (pool) return;
cfg = c;
loadManifest();
tmdb.init(cfg);
health.init(cfg);
results = createCache({ max: 5000, ttlMs: (cfg.cacheTtlSec || 1800) * 1000 });
const wanted = cfg.enabledProviders;
const disabled = new Set(cfg.disabledProviders || []);
cfg.enabledProviders =
Array.isArray(wanted) && wanted.length && !wanted.includes('all')
? wanted.filter((n) => available.has(n))
: [...available].filter((n) => !disabled.has(n)).sort();
pool = createPool(cfg);
}
const list = () => [...available].sort();
const meta = (name) => manifest.get(name) || null;
const exists = (name) => available.has(name);
function supports(name, type) {
const t = meta(name)?.supportedTypes;
return !Array.isArray(t) || !t.length || t.includes(type);
}
const keyOf = (name, p) => `${name}|${p.tmdb}|${p.type}|${p.season ?? ''}|${p.episode ?? ''}`;
// cached result or undefined
function cached(name, p) {
return results.get(keyOf(name, p));
}
function ttlFor(r) {
if (r.status === 'ok') return (cfg.cacheTtlSec || 1800) * 1000;
if (r.status === 'empty') return Math.min(EMPTY_TTL, (cfg.cacheTtlSec || 1800) * 1000);
return 0; // errors / timeouts retry next time
}
// p = { tmdb, type, season, episode } -> Promise<{ name, status, ms, streams, error?, tmdb? }>
// never rejects. opts.fresh: ignore a cached result (an in-flight scrape is still joined)
function scrape(name, p, opts = {}) {
if (opts.fresh && !results.inflight(keyOf(name, p))) results.delete(keyOf(name, p));
if (!exists(name)) return Promise.resolve({ name, status: 'error', ms: 0, streams: [], error: 'unknown provider' });
if (!supports(name, p.type)) return Promise.resolve({ name, status: 'empty', ms: 0, streams: [], error: `${p.type} not supported` });
return results.wrap(
keyOf(name, p),
async () => {
const budgetMs = health.budget(name);
const r = await pool.run(name, [String(p.tmdb), p.type, p.season ?? null, p.episode ?? null], {
seed: tmdb.seedEntries(p.type, p.tmdb, p.season),
budgetMs,
});
let streams = [];
if (r.status === 'ok') {
try {
await sniffUnknown(r.streams);
streams = normalizeAll(r.streams, name, { season: p.season, episode: p.episode });
} catch (e) {
r.status = 'error';
r.error = `normalize: ${e.message}`;
}
}
const status = r.status === 'ok' ? (streams.length ? 'ok' : 'empty') : r.status;
health.record(name, status, r.status === 'timeout' ? budgetMs : r.ms);
const out = { name, status, ms: r.ms, streams, tmdb: r.tmdb };
if (r.error && status !== 'ok') out.error = String(r.error).slice(0, 300);
return out;
},
ttlFor
);
}
// start fetching TMDB data for a title so workers find it cached
function warm(p) {
return tmdb.warm(p.type, p.tmdb, p.season).catch(() => {});
}
module.exports = {
init,
list,
meta,
exists,
supports,
cached,
scrape,
warm,
health,
defaults: () => (cfg?.enabledProviders || []).filter((n) => available.has(n)),
stats: () => ({ tmdb: tmdb.stats(), pool: pool?.stats(), results: results?.size || 0 }),
timeoutMs: () => cfg?.timeoutMs || 20000,
};
+226
View File
@@ -0,0 +1,226 @@
// Raw provider stream -> internal stream record. `toPublic` projects it to the v1 Stream shape
// (docs/api.md); `toLegacy` to the v4 /streams shape.
const crypto = require('crypto');
let playback = null;
function media() {
// src/media/playback.js is owned by the media workstream; degrade gracefully if it fails
if (playback) return playback;
try {
playback = require('../media/playback');
} catch (e) {
return {
playbackFor: (s) => (s.url && /^https?:/i.test(s.url) ? { kind: s.type === 'm3u8' ? 'hls' : 'file', url: s.url } : null),
subtitleUrl: (sub) => (typeof sub === 'string' ? sub : sub?.url || ''),
};
}
return playback;
}
const ZW = /[​-‏⁠-⁤­]/g;
const clean = (v) => (typeof v === 'string' ? v.replace(ZW, '').trim() : '');
// display text: providers decorate names with emoji (💾 👤 ⚙️ …); strip them line by line
const EMOJI = /[\p{Extended_Pictographic}\p{Regional_Indicator}\u{1F3FB}-\u{1F3FF}\u20E3\uFE0E\uFE0F\u200D]/gu;
const plain = (v) =>
String(v || '')
.replace(EMOJI, '')
.split('\n')
.map((l) => l.replace(/\s{2,}/g, ' ').replace(/^[\s|·•:,/-]+|[\s|·•:,/-]+$/g, ''))
.filter(Boolean)
.join('\n');
function qualityToPixels(q) {
if (!q) return null;
const s = String(q).toLowerCase();
if (/2160|\b4k\b|\buhd\b/.test(s)) return 2160;
const m = s.match(/\b(\d{3,4})\s*p\b/);
if (m) {
const n = parseInt(m[1], 10);
if (n >= 1440) return 2160;
if (n >= 240) return n;
}
if (/1080|full\s?hd|\bfhd\b/.test(s)) return 1080;
if (/\b720\b|\bhd\b/.test(s)) return 720;
if (/\b480\b|\bsd\b/.test(s)) return 480;
if (/\b360\b/.test(s)) return 360;
return null;
}
function detectAudio(text) {
const t = ` ${String(text || '').toLowerCase()} `;
if (/\bdts\b|dts-?hd|truehd|atmos/.test(t)) return 'dts';
if (/e-?ac-?3|\bddp?\+?\s?[57]\.1|dd\+|\bac-?3\b|dolby digital/.test(t)) return 'ac3';
if (/\baac\b/.test(t)) return 'aac';
if (/\bopus\b/.test(t)) return 'opus';
if (/\bflac\b|lossless/.test(t)) return 'flac';
if (/\bmp3\b/.test(t)) return 'mp3';
if (/dual-?audio|multi-?audio|original[- ]audio|\bmulti\b/.test(t)) return 'multi';
return null;
}
function extOf(text) {
const m = String(text || '').toLowerCase().split(/[?#]/)[0].match(/\.([a-z0-9]{2,5})$/);
return m ? m[1] : '';
}
function streamType(url, name, raw = {}) {
const u = String(url || '');
const n = String(name || '').toLowerCase();
if (/^magnet:/i.test(u) || (!u && raw.infoHash)) return 'magnet';
if (raw._sniffed) return raw._sniffed;
if (/m3u8/i.test(u) || raw.type === 'hls') return 'm3u8';
const ext = extOf(u) || extOf(raw.filename || raw.behaviorHints?.filename || '') || extOf(n);
if (ext === 'mkv' || /\.mkv\b|\bmkv\b/.test(n)) return 'mkv';
if (ext === 'mp4' || ext === 'm4v' || ext === 'mov' || /\.mp4\b/.test(n)) return 'mp4';
if (ext === 'avi' || /\.avi\b/.test(n)) return 'avi';
if (ext === 'webm') return 'webm';
return 'other';
}
const UNITS = { b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4 };
// "💾 1.2 GB" / "1,4 GiB" -> { bytes, text }
function parseSize(text) {
const m = String(text || '').match(/(\d+(?:[.,]\d+)?)\s*(TiB|GiB|MiB|KiB|TB|GB|MB|KB)\b/i);
if (!m) return null;
const n = parseFloat(m[1].replace(',', '.'));
return { bytes: Math.round(n * UNITS[m[2].toLowerCase()]), text: `${m[1]} ${m[2]}` };
}
function parseSeeds(raw, text) {
for (const k of ['seeds', 'seeders', 'peers']) if (Number.isFinite(raw[k])) return raw[k];
const m = String(text).match(/(?:👤|👥|🌱|seed(?:s|ers)?[:\s])\s*(\d+)/iu);
return m ? parseInt(m[1], 10) : null;
}
function formatBytes(n) {
if (!n || n <= 0) return '';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
let v = n;
while (v >= 1000 && i < units.length - 1) {
v /= 1000;
i++;
}
return `${v.toFixed(v >= 100 || i === 0 ? 0 : 1)} ${units[i]}`;
}
function rawSubtitles(subs) {
if (!Array.isArray(subs)) return [];
return subs
.filter((s) => s && typeof s.url === 'string' && s.url.length > 0)
.map((s) => ({ url: s.url, language: clean(s.language || s.lang || s.id || ''), name: clean(s.name || s.label || ''), headers: s.headers }));
}
const hashId = (provider, url) => crypto.createHash('sha1').update(`${provider}\n${url}`).digest('base64url').slice(0, 12);
// raw: provider object; ctx: { season, episode }
function normalize(raw, provider, ctx = {}) {
if (!raw || typeof raw !== 'object') return null;
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
if (!url && !raw.infoHash) return null;
const name = clean(raw.name) || clean(raw.title) || 'stream';
const title = clean(raw.title);
const description = clean(raw.description);
const sizeField = typeof raw.size === 'string' ? clean(raw.size) : '';
const text = [name, title, description].filter(Boolean).join(' ');
const rawQuality = clean(typeof raw.quality === 'number' ? `${raw.quality}p` : raw.quality);
const pixels = qualityToPixels(rawQuality) ?? qualityToPixels(`${name} ${title}`) ?? qualityToPixels(description);
let size = typeof raw.size === 'number' && raw.size > 0 ? raw.size : 0;
let sizeText = size ? formatBytes(size) : '';
if (!size) {
const p = parseSize(sizeField) || parseSize(text);
if (p) {
size = p.bytes;
sizeText = p.text;
} else if (sizeField && sizeField.length < 24) sizeText = sizeField;
}
const headers = raw.headers && typeof raw.headers === 'object' ? raw.headers : {};
const type = streamType(url, `${name} ${title}`, raw);
const subs = rawSubtitles(raw.subtitles);
const s = {
id: hashId(provider, url || raw.infoHash),
provider,
name,
title,
description,
url,
headers,
infoHash: raw.infoHash || null,
fileIdx: Number.isInteger(raw.fileIdx) ? raw.fileIdx : undefined,
quality: rawQuality && !/^(auto|unknown|default|n\/?a|-)$/i.test(rawQuality) ? rawQuality : pixels ? `${pixels}p` : '',
pixels,
audio: detectAudio(text),
type,
size,
sizeText,
language: clean(raw.language || raw.lang || ''),
seeds: parseSeeds(raw, `${name}\n${title}\n${description}\n${sizeField}`),
rawSubtitles: subs,
};
const m = media();
try {
s.playback = m.playbackFor(s, ctx);
} catch {
s.playback = null;
}
if (!s.playback) return null; // nothing a client can play
s.subtitles = subs
.map((sub) => {
let u = '';
try {
u = m.subtitleUrl(sub, headers);
} catch {}
return u ? { url: u, lang: sub.language, label: sub.name || sub.language } : null;
})
.filter(Boolean);
return s;
}
function toPublic(s) {
return {
id: s.id,
provider: s.provider,
name: plain(s.name) || s.provider,
title: plain(s.title),
quality: s.quality,
pixels: s.pixels,
audio: s.audio,
type: s.type,
size: s.size,
sizeText: s.sizeText,
language: s.language,
seeds: s.seeds,
subtitles: s.subtitles,
playback: s.playback,
};
}
function toLegacy(s) {
return {
provider: s.provider,
name: plain(s.name) || s.provider,
url: s.url,
quality: s.quality,
pixels: s.pixels,
audio: s.audio,
type: s.type,
headers: s.headers,
subtitles: s.rawSubtitles.map(({ url, language, name }) => ({ url, language, name })),
};
}
// dedupe within one provider's result
function normalizeAll(rawList, provider, ctx) {
const seen = new Set();
const out = [];
for (const raw of rawList || []) {
const s = normalize(raw, provider, ctx);
if (!s || seen.has(s.id)) continue;
seen.add(s.id);
out.push(s);
}
return out;
}
module.exports = { normalize, normalizeAll, toPublic, toLegacy, qualityToPixels, detectAudio, parseSize, formatBytes, streamType };
+177
View File
@@ -0,0 +1,177 @@
// worker_threads pool running provider getStreams() jobs.
//
// const pool = createPool(cfg);
// const r = await pool.run('vidfast', [tmdbId, type, season, episode], { seed, budgetMs });
// // r = { status: 'ok'|'error'|'timeout', streams, error?, ms, tmdb: {calls, local, remote} }
//
// Jobs past their budget are cancelled (worker aborts all of the job's fetches). If a worker
// doesn't ack a cancel within GRACE_MS its event loop is wedged: it is terminated and respawned.
const os = require('os');
const path = require('path');
const { Worker } = require('worker_threads');
const tmdb = require('../tmdb');
const GRACE_MS = 3000;
const WORKER_FILE = path.join(__dirname, 'worker.js');
function createPool(cfg) {
const size = cfg.workers > 0 ? cfg.workers : Math.max(1, Math.min(os.cpus().length, 4));
const slots = [];
let jobSeq = 0;
let closing = false;
const totals = { jobs: 0, timeouts: 0, restarts: 0 };
function spawn(slot) {
const worker = new Worker(WORKER_FILE, {
workerData: {
providerSettings: cfg.providerSettings || {},
preload: cfg.enabledProviders || [],
providersDir: cfg.providersDir,
fetchTimeoutMs: Math.min(cfg.timeoutMs || 20000, 15000),
debug: !!process.env.BUG_TV_DEBUG_PROVIDERS,
},
resourceLimits: { maxOldGenerationSizeMb: 768 },
stdout: false,
stderr: false,
});
slot.worker = worker;
slot.jobs = new Map();
slot.loaded = new Set();
slot.ready = false;
slot.wedgeTimers = new Map();
worker.on('message', (msg) => onMessage(slot, worker, msg));
worker.on('error', (e) => {
if (slot.worker === worker) console.error(`[pool] worker ${slot.idx} error: ${e.message}`);
});
worker.on('exit', (code) => {
if (slot.worker !== worker || closing) return;
console.error(`[pool] worker ${slot.idx} exited (${code}); respawning`);
fail(slot, 'worker exited');
setTimeout(() => !closing && spawn(slot), 500);
});
}
function fail(slot, error) {
for (const job of slot.jobs.values()) finish(slot, job, { status: 'error', error, streams: [] });
slot.jobs.clear();
for (const t of slot.wedgeTimers.values()) clearTimeout(t);
slot.wedgeTimers.clear();
}
function respawn(slot, why) {
totals.restarts++;
slot.restarts = (slot.restarts || 0) + 1;
console.error(`[pool] worker ${slot.idx} ${why}; terminating + respawning`);
const old = slot.worker;
slot.worker = null; // its exit event is now ignored
fail(slot, `worker restarted (${why})`);
old.terminate().catch(() => {});
spawn(slot);
}
function onMessage(slot, worker, msg) {
if (slot.worker !== worker) return;
switch (msg.type) {
case 'ready':
slot.ready = true;
for (const n of msg.loaded) slot.loaded.add(n);
if (Object.keys(msg.errors).length && slot.idx === 0) {
console.error('[pool] provider load errors:', msg.errors);
}
if (slot.idx === 0) console.log(`[pool] ${size} workers, ${msg.loaded.length} providers preloaded in ${msg.ms}ms`);
break;
case 'result': {
const job = slot.jobs.get(msg.jobId);
if (!job) break;
slot.jobs.delete(msg.jobId);
slot.loaded.add(job.provider);
finish(slot, job, {
status: msg.ok ? 'ok' : 'error',
streams: msg.streams || [],
error: msg.error,
tmdb: msg.tmdb,
});
break;
}
case 'cancelled': {
const t = slot.wedgeTimers.get(msg.jobId);
if (t) clearTimeout(t);
slot.wedgeTimers.delete(msg.jobId);
break;
}
case 'tmdb':
tmdb.resolve(msg.c).then(
(value) => slot.worker === worker && worker.postMessage({ type: 'tmdb', reqId: msg.reqId, value }),
(e) => slot.worker === worker && worker.postMessage({ type: 'tmdb', reqId: msg.reqId, error: e.message })
);
break;
}
}
function finish(slot, job, r) {
if (job.done) return;
job.done = true;
clearTimeout(job.timer);
job.resolve({ ...r, ms: Date.now() - job.start, tmdb: r.tmdb || null });
}
function pick(provider) {
let best = null;
for (const s of slots) {
if (!s.worker) continue;
const score = s.jobs.size - (s.loaded.has(provider) ? 0.5 : 0);
if (!best || score < best.score) best = { s, score };
}
return best?.s;
}
function run(provider, args, { seed = [], budgetMs = cfg.timeoutMs || 20000 } = {}) {
totals.jobs++;
return new Promise((resolve) => {
const slot = pick(provider);
if (!slot) return resolve({ status: 'error', error: 'no workers', streams: [], ms: 0, tmdb: null });
const jobId = ++jobSeq;
const job = { jobId, provider, resolve, start: Date.now(), done: false };
slot.jobs.set(jobId, job);
job.timer = setTimeout(() => {
if (job.done) return;
totals.timeouts++;
slot.jobs.delete(jobId);
finish(slot, job, { status: 'timeout', error: `timed out after ${budgetMs}ms`, streams: [] });
const worker = slot.worker;
if (!worker) return;
worker.postMessage({ type: 'cancel', jobId });
slot.wedgeTimers.set(
jobId,
setTimeout(() => {
slot.wedgeTimers.delete(jobId);
if (slot.worker === worker) respawn(slot, `unresponsive after cancelling ${provider}`);
}, GRACE_MS)
);
}, budgetMs);
slot.worker.postMessage({ type: 'job', jobId, provider, args, seed, budgetMs });
});
}
for (let i = 0; i < size; i++) {
const slot = { idx: i };
slots.push(slot);
spawn(slot);
}
return {
run,
size,
stats: () => ({
workers: slots.map((s) => ({ idx: s.idx, ready: !!s.ready, jobs: s.jobs?.size || 0, loaded: s.loaded?.size || 0, restarts: s.restarts || 0 })),
...totals,
}),
async close() {
closing = true;
await Promise.all(slots.map((s) => s.worker?.terminate()));
},
};
}
module.exports = { createPool };
+150
View File
@@ -0,0 +1,150 @@
// Scrape worker: keeps providers require()d for its lifetime and runs getStreams jobs.
//
// main -> worker: { type:'job', jobId, provider, args, seed, budgetMs }
// { type:'cancel', jobId } (worker acks with { type:'cancelled', jobId })
// { type:'tmdb', reqId, value | error } (reply to a tmdb miss)
// { type:'seed', entries } { type:'load', names }
// worker -> main: { type:'ready', loaded, errors, ms }
// { type:'result', jobId, ok, streams?, error?, ms, tmdb, fetches }
// { type:'tmdb', reqId, c } (cache miss, main resolves)
const path = require('path');
const { parentPort, workerData, threadId } = require('worker_threads');
const shim = require('./fetch-shim');
const PROVIDERS_DIR = workerData.providersDir || path.join(__dirname, '..', '..', 'providers');
global.SCRAPER_SETTINGS = workerData.providerSettings || {};
// Providers are chatty. Drop their console output unless BUG_TV_DEBUG_PROVIDERS is set,
// in which case prefix each line with the provider that produced it.
const debug = !!workerData.debug;
const origConsole = { ...console };
for (const level of ['log', 'info', 'debug', 'warn', 'error', 'trace']) {
console[level] = (...a) => {
if (!debug) return;
const p = shim.current()?.provider || 'worker';
origConsole[level === 'trace' ? 'error' : level](`[w${threadId} ${p}]`, ...a);
};
}
// tmdb misses go to the main thread (shared cache across workers)
let reqSeq = 0;
const pendingTmdb = new Map();
function askMain(c) {
return new Promise((resolve, reject) => {
const reqId = ++reqSeq;
const t = setTimeout(() => {
pendingTmdb.delete(reqId);
reject(new Error('tmdb lookup timed out'));
}, 12000);
pendingTmdb.set(reqId, { resolve, reject, t });
parentPort.postMessage({ type: 'tmdb', reqId, c });
});
}
shim.install({ fetchTimeoutMs: workerData.fetchTimeoutMs, askMain });
const loaded = new Map(); // name -> { getStreams } | { error }
function load(name) {
if (loaded.has(name)) return loaded.get(name);
let entry;
if (!/^[a-z0-9][a-z0-9._-]*$/i.test(name)) entry = { error: 'invalid provider name' };
else {
try {
const mod = shim.runInJob({ provider: name, tmdb: { calls: 0, local: 0, remote: 0 }, fetches: 0 }, () =>
require(path.join(PROVIDERS_DIR, `${name}.js`))
);
entry = typeof mod?.getStreams === 'function' ? { getStreams: mod.getStreams } : { error: 'does not export getStreams()' };
} catch (e) {
entry = { error: e.code === 'MODULE_NOT_FOUND' && String(e.message).includes(name) ? 'not found' : String(e.message).split('\n')[0] };
}
}
loaded.set(name, entry);
return entry;
}
// structured-clone-safe copy of whatever the provider returned
function plain(raw) {
const arr = Array.isArray(raw) ? raw : raw && typeof raw === 'object' && raw.url ? [raw] : [];
try {
return JSON.parse(JSON.stringify(arr));
} catch {
return [];
}
}
const jobs = new Map(); // jobId -> { ac }
async function runJob(msg) {
const { jobId, provider, args, seed } = msg;
const start = Date.now();
shim.seed(seed);
const ac = new AbortController();
const ctx = { signal: ac.signal, provider, tmdb: { calls: 0, local: 0, remote: 0 }, fetches: 0 };
jobs.set(jobId, { ac });
let out;
try {
const p = load(provider);
if (p.error) throw new Error(p.error);
const raw = await shim.runInJob(ctx, () =>
Promise.race([
Promise.resolve().then(() => p.getStreams(...args)),
new Promise((_, rej) => ac.signal.addEventListener('abort', () => rej(new Error('cancelled')), { once: true })),
])
);
out = { ok: true, streams: plain(raw) };
} catch (e) {
out = { ok: false, error: (e && (e.message || String(e))) || 'error' };
}
if (!jobs.has(jobId)) return; // cancelled: main already reported it
jobs.delete(jobId);
ac.abort(); // stop any stragglers the provider left running
parentPort.postMessage({ type: 'result', jobId, ...out, ms: Date.now() - start, tmdb: ctx.tmdb, fetches: ctx.fetches });
}
parentPort.on('message', (msg) => {
switch (msg.type) {
case 'job':
runJob(msg);
break;
case 'cancel': {
const j = jobs.get(msg.jobId);
if (j) {
jobs.delete(msg.jobId);
j.ac.abort(new Error('budget exceeded'));
}
parentPort.postMessage({ type: 'cancelled', jobId: msg.jobId });
break;
}
case 'tmdb': {
const p = pendingTmdb.get(msg.reqId);
if (!p) break;
pendingTmdb.delete(msg.reqId);
clearTimeout(p.t);
if (msg.error) p.reject(new Error(msg.error));
else p.resolve(msg.value);
break;
}
case 'seed':
shim.seed(msg.entries);
break;
case 'load':
for (const n of msg.names || []) load(n);
break;
case 'ping':
parentPort.postMessage({ type: 'pong', id: msg.id });
break;
}
});
process.on('unhandledRejection', () => {}); // providers leave plenty of these behind
process.on('uncaughtException', (e) => {
if (debug) origConsole.error(`[w${threadId}] uncaught`, e);
});
const t0 = Date.now();
const errors = {};
for (const n of workerData.preload || []) {
const e = load(n);
if (e.error) errors[n] = e.error;
}
parentPort.postMessage({ type: 'ready', loaded: [...loaded.keys()].filter((k) => !loaded.get(k).error), errors, ms: Date.now() - t0 });
+69
View File
@@ -0,0 +1,69 @@
// providers resolve many dead domains; widen libuv's pool before anything uses it
process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || '24';
const http = require('http');
const { loadConfig } = require('./config');
const sign = require('./sign');
const { CORS, error } = require('./http');
const cfg = loadConfig();
sign.init(cfg.secret);
// Each routes module exports { routes: [{ method, path, handler(req, res, ctx) }], init?(cfg) }.
// `path` is a string (exact) or a RegExp whose groups become ctx.params.
const MODULES = ['health', 'providers', 'streams', 'proxy', 'torrent', 'remux', 'subs', 'openapi'];
const routes = [];
for (const name of MODULES) {
let mod;
try {
mod = require(`./routes/${name}`);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND' && e.message.includes(`routes/${name}`)) continue;
throw e;
}
mod.init?.(cfg);
routes.push(...mod.routes);
}
function match(method, pathname) {
for (const r of routes) {
if (r.method !== method && !(r.method === 'GET' && method === 'HEAD')) continue;
if (typeof r.path === 'string') {
if (r.path === pathname) return { route: r, params: [] };
} else {
const m = pathname.match(r.path);
if (m) return { route: r, params: m.slice(1).map(decodeURIComponent) };
}
}
return null;
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
const pathname = url.pathname.length > 1 ? url.pathname.replace(/\/+$/, '') : url.pathname;
try {
if (req.method === 'OPTIONS') {
res.writeHead(204, {
...CORS,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': '*',
'Access-Control-Max-Age': '86400',
});
return res.end();
}
const found = match(req.method, pathname);
if (!found) return error(req, res, 404, 'not found', { hint: 'see GET / (Swagger UI)' });
await found.route.handler(req, res, { cfg, url, params: found.params });
} catch (e) {
console.error(e);
if (!res.headersSent) return error(req, res, 500, e.message);
res.destroy();
}
});
server.listen(cfg.port, cfg.host, () => {
console.log(`bug.tv api v5: http://${cfg.host}:${cfg.port}`);
});
module.exports = { server, cfg };
+34
View File
@@ -0,0 +1,34 @@
// Compact signed tokens: base64url(json) + '.' + hmac. Used to hand the client
// opaque URLs for proxy/remux/subs without exposing an open proxy.
const crypto = require('crypto');
let secret = '';
function init(s) {
secret = s;
}
function mac(body) {
return crypto.createHmac('sha256', secret).update(body).digest('base64url').slice(0, 22);
}
function sign(obj) {
const body = Buffer.from(JSON.stringify(obj)).toString('base64url');
return `${body}.${mac(body)}`;
}
function verify(token) {
const i = String(token || '').lastIndexOf('.');
if (i <= 0) return null;
const body = token.slice(0, i);
const sig = Buffer.from(token.slice(i + 1));
const want = Buffer.from(mac(body));
if (sig.length !== want.length || !crypto.timingSafeEqual(sig, want)) return null;
try {
return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
} catch {
return null;
}
}
module.exports = { init, sign, verify };
+188
View File
@@ -0,0 +1,188 @@
// Cached TMDB client for the main thread, plus the request canonicalisation shared with the
// worker fetch shim (src/scrape/fetch-shim.js).
//
// Cache values are `{ status, body }` where body is the raw JSON text, so they cross
// worker_threads cheaply and can be turned back into a Response verbatim.
const { createCache } = require('./cache');
const API = 'https://api.themoviedb.org/3';
const HOST = 'api.themoviedb.org';
// what the main thread appends to /{type}/{id}; any provider asking for a subset gets the same entry
const DETAIL_APPENDS = ['external_ids', 'alternative_titles'];
const OK_TTL = 6 * 3600e3;
const MISS_TTL = 10 * 60e3;
// -> { key, path, query, derive? } or null when `input` isn't a TMDB v3 API url
function canonical(input) {
let u;
try {
u = input instanceof URL ? input : new URL(String(input));
} catch {
return null;
}
if (u.hostname !== HOST || !u.pathname.startsWith('/3/')) return null;
const path = u.pathname.slice(2).replace(/\/+$/, '');
const params = [...u.searchParams.entries()].filter(([k, v]) => {
if (k === 'api_key') return false;
if (k === 'language' && /^en(-US)?$/i.test(v)) return false;
return v !== '';
});
const det = path.match(/^\/(movie|tv)\/(\d+)$/);
if (det) {
const appends = params.filter(([k]) => k === 'append_to_response');
const rest = params.filter(([k]) => k !== 'append_to_response');
const wanted = appends.flatMap(([, v]) => v.split(',')).map((s) => s.trim()).filter(Boolean);
if (!rest.length && wanted.every((w) => DETAIL_APPENDS.includes(w))) {
return { key: path, path, query: `append_to_response=${DETAIL_APPENDS.join(',')}` };
}
}
const sub = path.match(/^\/(movie|tv)\/(\d+)\/(external_ids|alternative_titles)$/);
if (sub && !params.length) {
return { key: path, path, query: '', derive: { base: `/${sub[1]}/${sub[2]}`, field: sub[3] } };
}
params.sort(([a, x], [b, y]) => (a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0));
const query = new URLSearchParams(params).toString();
return { key: query ? `${path}?${query}` : path, path, query };
}
let apiKey = '';
const cache = createCache({ max: 3000, ttlMs: OK_TTL });
const imdbIndex = new Map(); // imdb id -> details key
const stats = { requests: 0, hits: 0, network: 0, errors: 0 };
function init(cfg) {
apiKey = cfg.tmdbKey;
}
function ttlFor(v) {
if (!v) return 0;
if (v.status === 200) return OK_TTL;
if (v.status === 404) return MISS_TTL;
return 0;
}
function indexDetails(key, v) {
if (v.status !== 200 || !/^\/(movie|tv)\/\d+$/.test(key)) return;
try {
const imdb = JSON.parse(v.body).external_ids?.imdb_id;
if (imdb) imdbIndex.set(imdb, key);
} catch {}
}
async function networkGet(c) {
stats.network++;
const url = `${API}${c.path}?${c.query ? `${c.query}&` : ''}api_key=${encodeURIComponent(apiKey)}`;
try {
const res = await fetch(url, { signal: AbortSignal.timeout(10000) });
const body = await res.text();
const v = { status: res.status, body };
indexDetails(c.key, v);
return v;
} catch (e) {
stats.errors++;
throw e;
}
}
function synthFind(key) {
const m = key.match(/^\/find\/(tt\d+)\?external_source=imdb_id$/);
const base = m && imdbIndex.get(m[1]);
const v = base && cache.get(base);
if (!v) return null;
const d = JSON.parse(v.body);
const isMovie = base.startsWith('/movie/');
const item = { ...d, media_type: isMovie ? 'movie' : 'tv' };
return {
status: 200,
body: JSON.stringify({
movie_results: isMovie ? [item] : [],
person_results: [],
tv_results: isMovie ? [] : [item],
tv_episode_results: [],
tv_season_results: [],
}),
};
}
// canonical descriptor (or url) -> Promise<{status, body}>
function resolve(c) {
if (typeof c === 'string') c = canonical(c.startsWith('http') ? c : `${API}${c}`);
if (!c) return Promise.reject(new Error('not a TMDB url'));
stats.requests++;
if (cache.has(c.key) || cache.inflight(c.key)) {
stats.hits++;
return cache.wrap(c.key, () => networkGet(c), ttlFor);
}
return cache.wrap(
c.key,
async () => {
if (c.derive) {
const base = await resolve(c.derive.base);
if (base.status !== 200) return base;
return { status: 200, body: JSON.stringify(JSON.parse(base.body)[c.derive.field] ?? {}) };
}
const found = synthFind(c.key);
if (found) {
stats.hits++;
return found;
}
return networkGet(c);
},
ttlFor
);
}
async function getJson(path) {
const v = await resolve(path);
if (v.status !== 200) throw new Error(`TMDB HTTP ${v.status} for ${path}`);
return JSON.parse(v.body);
}
const details = (type, id) => getJson(`/${type === 'tv' ? 'tv' : 'movie'}/${id}`);
const season = (tvId, n) => getJson(`/tv/${tvId}/season/${n}`);
const find = (imdbId) => getJson(`/find/${imdbId}?external_source=imdb_id`);
// Keys a scrape for this title is likely to need. warm() fetches them (errors swallowed);
// seedEntries() returns those already cached, as [key, {status, body}] pairs for workers.
function seedKeys(type, id, s) {
const t = type === 'tv' ? 'tv' : 'movie';
const keys = [`/${t}/${id}`, `/${t}/${id}/external_ids`, `/${t}/${id}/alternative_titles`];
if (t === 'tv' && s != null) keys.push(`/tv/${id}/season/${s}`);
const imdbKey = [...imdbIndex.entries()].find(([, k]) => k === `/${t}/${id}`)?.[0];
if (imdbKey) keys.push(`/find/${imdbKey}?external_source=imdb_id`);
return keys;
}
async function warm(type, id, s) {
const t = type === 'tv' ? 'tv' : 'movie';
const base = resolve(`/${t}/${id}`).catch(() => null);
const jobs = [base];
if (t === 'tv' && s != null) jobs.push(resolve(`/tv/${id}/season/${s}`).catch(() => null));
await Promise.all(jobs);
// derived + find entries are cheap once the details are in
await Promise.all(seedKeys(type, id, s).map((k) => resolve(k).catch(() => null)));
}
function seedEntries(type, id, s) {
const out = [];
for (const k of seedKeys(type, id, s)) {
const v = cache.get(k);
if (v) out.push([k, v]);
}
return out;
}
module.exports = {
init,
canonical,
resolve,
details,
season,
find,
warm,
seedEntries,
stats: () => ({ ...stats, cached: cache.size }),
API,
HOST,
};
+91
View File
@@ -0,0 +1,91 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<meta name="theme-color" content="#09090b">
<meta name="description" content="bug tv — stream movies and series.">
<!-- API base default; replaced at build time (empty → https://api-tv.bug.tools). -->
<meta name="bug-tv-api" content="">
<!-- Path the site is served under (history routing); "/" for a domain root. -->
<meta name="bug-tv-root" content="/">
<title>bug tv</title>
<script>
/* Router mode + <base> so assets resolve from deep links (/title/tv/1399) and file://. */
(function () {
var l = location;
var m = document.querySelector('meta[name="bug-tv-root"]');
var root = m && m.content && !/^@.*@$/.test(m.content) ? m.content : '/';
if (root.slice(-1) !== '/') root += '/';
var fileish = l.protocol === 'file:' || /\.html?$/i.test(l.pathname);
var hash = fileish || /^#\//.test(l.hash);
var base = document.createElement('base');
base.href = fileish ? l.href.split('#')[0] : l.origin + root;
document.head.appendChild(base);
window.__BUGTV_ROUTER = { mode: hash ? 'hash' : 'history', root: root };
})();
</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preconnect" href="https://image.tmdb.org">
<link rel="preconnect" href="https://api.themoviedb.org">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap">
<link rel="icon" type="image/svg+xml" href="img/bug.svg">
<link rel="stylesheet" href="css/tokens.css">
<link rel="stylesheet" href="css/base.css">
<link rel="stylesheet" href="css/components.css">
<link rel="stylesheet" href="css/pages.css">
<link rel="stylesheet" href="css/player.css">
<link rel="modulepreload" href="js/router.js">
</head>
<body>
<a class="skip-link" href="#app">Skip to content</a>
<header class="site-header is-over-hero">
<div class="site-header__inner container">
<a class="brand" data-href="/" aria-label="bug tv home">
<img class="brand__mark" src="img/bug.svg" alt="" width="32" height="32"><span class="brand__word">bug<span>.tv</span></span>
</a>
<nav class="site-nav" aria-label="Primary">
<a class="site-nav__link" data-nav data-href="/">Home</a>
<a class="site-nav__link" data-nav data-href="/movies">Movies</a>
<a class="site-nav__link" data-nav data-href="/tv">Series</a>
<a class="site-nav__link" data-nav data-href="/list">My List</a>
</nav>
<div class="site-header__actions">
<form class="header-search" role="search">
<button class="header-search__icon" type="button" tabindex="-1" aria-hidden="true"><span data-icon="search"></span></button>
<input type="search" name="q" placeholder="Search titles" autocomplete="off" spellcheck="false" aria-label="Search movies and series">
<kbd class="header-search__kbd" aria-hidden="true">/</kbd>
</form>
<a class="icon-btn header-search-link" data-nav data-href="/search" aria-label="Search" title="Search"><span data-icon="search"></span></a>
<a class="icon-btn" data-nav data-href="/settings" aria-label="Settings" title="Settings"><span data-icon="settings"></span></a>
</div>
</div>
</header>
<main id="app" class="app" aria-live="polite"></main>
<footer class="site-footer">
<div class="container site-footer__inner">
<span class="brand brand--sm"><img class="brand__mark" src="img/bug.svg" alt="" width="32" height="32"><span class="brand__word">bug<span>.tv</span></span></span>
<span class="site-footer__note">bug tv doesn't host files — it links to third-party sources. Metadata by TMDB.</span>
<span class="site-footer__api">api · <a id="apiBaseLabel" href="#" target="_blank" rel="noopener"></a></span>
</div>
</footer>
<nav class="tabbar" aria-label="Primary">
<a class="tabbar__link" data-nav data-href="/"><span data-icon="home" data-size="22"></span><span>Home</span></a>
<a class="tabbar__link" data-nav data-href="/movies"><span data-icon="film" data-size="22"></span><span>Movies</span></a>
<a class="tabbar__link" data-nav data-href="/tv"><span data-icon="tv" data-size="22"></span><span>Series</span></a>
<a class="tabbar__link" data-nav data-href="/search"><span data-icon="search" data-size="22"></span><span>Search</span></a>
<a class="tabbar__link" data-nav data-href="/list"><span data-icon="bookmark" data-size="22"></span><span>My List</span></a>
</nav>
<div id="toasts" class="toasts" role="status" aria-live="polite"></div>
<noscript><p style="padding:2rem;color:#fff">bug tv needs JavaScript.</p></noscript>
<script type="module" src="js/app.js"></script>
</body>
</html>
+160 -149
View File
@@ -1,196 +1,207 @@
/*
BASE — reset, typography, page frame (header/footer/container).
Layout-level stuff only; reusable widgets live in components.css.
base.css — reset, typography, layout shell (header, footer, tab bar), utilities.
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
[hidden] {
display: none !important;
}
*, *::before, *::after { box-sizing: border-box; }
html {
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
scrollbar-color: var(--surface-3) var(--bg);
background: var(--bg);
}
html.has-modal { overflow: hidden; }
body {
margin: 0;
font-family: var(--font-sans);
font-size: var(--text-md);
line-height: var(--leading-normal);
background: var(--color-bg);
color: var(--color-text);
min-height: 100vh;
background: var(--bg);
color: var(--text);
font-family: var(--font);
font-size: var(--fs-base);
line-height: var(--lh);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
overflow-x: hidden;
padding-bottom: var(--tabbar-h);
}
img {
max-width: 100%;
display: block;
}
img, svg, video, iframe { display: block; max-width: 100%; }
img { color: transparent; }
h1, h2, h3, h4, p { margin: 0; }
h1, h2, h3 { line-height: var(--lh-tight); letter-spacing: -0.01em; }
a { color: inherit; text-decoration: none; }
button, input, select, textarea { font: inherit; color: inherit; }
button { cursor: pointer; background: none; border: 0; padding: 0; }
[hidden] { display: none !important; }
::selection { background: var(--accent); color: var(--accent-ink); }
a {
color: inherit;
text-decoration: none;
}
:focus { outline: none; }
:focus-visible { outline: 2px solid var(--focus); outline-offset: 3px; border-radius: var(--r-sm); }
button {
font: inherit;
.sr-only {
position: absolute !important;
width: 1px; height: 1px;
padding: 0; margin: -1px;
overflow: hidden; clip: rect(0 0 0 0);
white-space: nowrap; border: 0;
}
h1,
h2,
h3 {
margin: 0;
line-height: var(--leading-tight);
}
p {
margin: 0;
}
code {
padding: 1px var(--space-1);
border-radius: var(--radius-sm);
background: var(--color-surface-2);
border: 1px solid var(--color-border);
font-size: 0.9em;
}
/* ---- page frame ---------------------------------------------------------- */
.container {
max-width: var(--container-max);
margin: 0 auto;
padding-left: var(--container-pad);
padding-right: var(--container-pad);
width: 100%;
padding-inline: var(--gutter);
}
.page {
padding-top: var(--space-5);
padding-bottom: var(--space-8);
.muted { color: var(--text-3); }
.center { text-align: center; }
.skip-link {
position: fixed; top: 8px; left: 8px; z-index: 200;
padding: 10px 16px; border-radius: var(--r-md);
background: var(--accent); color: var(--accent-ink); font-weight: var(--fw-bold);
transform: translateY(-150%);
transition: transform var(--dur) var(--ease);
}
.skip-link:focus { transform: none; }
/* ---- header ---------------------------------------------------------------- */
.app { min-height: calc(100vh - 120px); }
.app:focus { outline: none; }
/* ---- header ------------------------------------------------------------------- */
.site-header {
position: sticky;
top: 0;
z-index: 50;
border-bottom: 1px solid var(--color-border);
background: var(--color-bg);
background: color-mix(in srgb, var(--color-bg) 85%, transparent);
backdrop-filter: blur(12px);
position: fixed; inset: 0 0 auto 0; z-index: var(--z-header);
height: var(--header-h);
background: var(--overlay);
background-origin: border-box;
-webkit-backdrop-filter: saturate(160%) blur(18px);
backdrop-filter: saturate(160%) blur(18px);
border-bottom: 1px solid var(--border);
transition: background var(--dur) var(--ease), border-color var(--dur) var(--ease), backdrop-filter var(--dur) var(--ease);
}
.site-header.is-over-hero:not(.is-solid) {
background: linear-gradient(180deg, rgba(0, 0, 0, 0.72) 0%, rgba(0, 0, 0, 0.35) 60%, transparent 100%);
-webkit-backdrop-filter: none;
backdrop-filter: none;
border-bottom-color: transparent;
box-shadow: none;
}
.site-header__inner {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: var(--space-4);
height: var(--header-height);
height: 100%;
display: flex; align-items: center; gap: var(--sp-7);
}
.brand {
font-size: var(--text-xl);
font-weight: var(--font-weight-bold);
letter-spacing: -0.02em;
display: inline-flex; align-items: center; gap: 10px;
font-weight: var(--fw-heavy); font-size: 1.3rem; letter-spacing: -0.03em;
flex-shrink: 0;
}
.brand__mark {
display: block; width: 32px; height: 32px;
filter: drop-shadow(0 2px 10px var(--accent-glow));
}
.brand__word span { color: var(--accent); }
.brand--sm { font-size: 1rem; }
.brand--sm .brand__mark { width: 24px; height: 24px; filter: none; }
.site-nav { display: flex; gap: var(--sp-2); }
.site-nav__link {
position: relative;
padding: 8px 12px; border-radius: var(--r-md);
color: var(--text-2); font-weight: var(--fw-semi); font-size: 0.95rem;
transition: color var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease);
}
.site-nav__link:hover { color: var(--text); }
.site-nav__link.is-active { color: var(--text); }
.site-nav__link.is-active::after {
content: ""; position: absolute; left: 50%; bottom: 0;
width: 18px; height: 3px; border-radius: 3px; background: var(--accent);
transform: translateX(-50%);
}
.brand span {
color: var(--color-accent);
}
.site-header__actions { margin-left: auto; display: flex; align-items: center; gap: var(--sp-2); }
.site-header__nav {
display: flex;
gap: var(--space-1);
.header-search {
display: flex; align-items: center; gap: 8px;
width: 260px; height: 42px; padding: 0 10px 0 12px;
border-radius: var(--r-pill);
background: rgba(255, 255, 255, 0.08);
border: 1px solid var(--glass-border);
transition: width var(--dur) var(--ease), background var(--dur) var(--ease), border-color var(--dur) var(--ease);
}
.site-header__nav a {
padding: var(--space-2) var(--space-4);
border-radius: var(--radius-full);
font-size: var(--text-sm);
font-weight: var(--font-weight-medium);
color: var(--color-text-dim);
transition: background 120ms ease, color 120ms ease;
.header-search:focus-within { width: 320px; background: rgba(0, 0, 0, 0.55); border-color: rgba(255, 255, 255, 0.4); }
.header-search__icon { color: var(--text-2); display: grid; place-items: center; }
.header-search input {
flex: 1; min-width: 0; height: 100%;
background: none; border: 0; outline: none;
font-size: var(--fs-sm); font-weight: var(--fw-medium);
}
.site-header__nav a:hover {
color: var(--color-text);
background: var(--color-surface);
.header-search input::placeholder { color: var(--text-3); }
.header-search input::-webkit-search-cancel-button { filter: invert(1) opacity(0.5); }
.header-search__kbd {
font-family: var(--font-mono); font-size: var(--fs-2xs); color: var(--text-3);
border: 1px solid var(--border-strong); border-radius: 5px; padding: 1px 6px;
}
.site-header__nav a.is-active {
color: var(--color-accent-text);
background: var(--color-accent);
}
.site-header__actions {
display: flex;
justify-content: flex-end;
gap: var(--space-1);
}
/* ---- icon buttons ----------------------------------------------------------- */
.header-search:focus-within .header-search__kbd { display: none; }
.header-search-link { display: none !important; }
.icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 38px;
height: 38px;
border: none;
border-radius: var(--radius-full);
background: transparent;
color: var(--color-text-dim);
cursor: pointer;
transition: background 120ms ease, color 120ms ease;
display: inline-grid; place-items: center;
width: 42px; height: 42px; border-radius: var(--r-pill);
color: var(--text-2);
transition: color var(--dur-fast) var(--ease), background var(--dur-fast) var(--ease);
}
.icon-btn:hover, .icon-btn.is-active { color: var(--text); background: var(--glass); }
.icon-btn:hover {
background: var(--color-surface);
color: var(--color-text);
}
.icon-btn.is-active {
color: var(--color-accent);
}
.icon-btn svg {
width: 20px;
height: 20px;
}
/* ---- footer ------------------------------------------------------------------ */
/* ---- footer ------------------------------------------------------------------- */
.site-footer {
border-top: 1px solid var(--color-border);
padding: var(--space-4) 0 var(--space-5);
color: var(--color-text-faint);
font-size: var(--text-xs);
margin-top: var(--sp-10);
border-top: 1px solid var(--border);
color: var(--text-3); font-size: var(--fs-xs);
}
.site-footer .container {
display: flex;
gap: var(--space-3);
flex-wrap: wrap;
.site-footer__inner {
display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-3) var(--sp-7);
padding-block: var(--sp-7);
}
.site-footer__note { flex: 1; min-width: 220px; }
.site-footer a { color: var(--text-2); }
.site-footer a:hover { color: var(--accent); }
.site-footer a {
color: var(--color-text-dim);
/* ---- mobile tab bar ------------------------------------------------------------- */
.tabbar { display: none; }
@media (max-width: 1080px) {
.site-header__inner { gap: var(--sp-5); }
.site-nav__link { padding-inline: 8px; }
.header-search, .header-search:focus-within { width: 200px; }
}
.site-footer a:hover {
color: var(--color-text);
}
/* ---- responsive ---------------------------------------------------------------- */
@media (max-width: 720px) {
.site-header__nav a {
padding: var(--space-2) var(--space-3);
.site-nav, .header-search { display: none; }
.header-search-link { display: inline-grid !important; }
.site-header__actions { gap: 0; }
.brand { font-size: 1.15rem; }
.brand__mark { width: 28px; height: 28px; }
.tabbar {
position: fixed; inset: auto 0 0 0; z-index: var(--z-tabbar);
display: grid; grid-template-columns: repeat(5, 1fr);
height: var(--tabbar-h);
padding-bottom: env(safe-area-inset-bottom, 0px);
background: rgba(12, 12, 15, 0.92);
-webkit-backdrop-filter: blur(18px);
backdrop-filter: blur(18px);
border-top: 1px solid var(--border);
}
.tabbar__link {
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px;
color: var(--text-3); font-size: var(--fs-2xs); font-weight: var(--fw-semi);
}
.tabbar__link.is-active { color: var(--text); }
.tabbar__link.is-active .icon { color: var(--accent); }
.site-footer { margin-top: var(--sp-8); }
}
/* the player takes over the screen; it renders its own chrome */
body[data-route="watch"] .site-header,
body[data-route="watch"] .site-footer,
body[data-route="watch"] .tabbar { display: none; }
body[data-route="watch"] { padding-bottom: 0; }
+420 -716
View File
File diff suppressed because it is too large. Load diff
+179 -763
View File
@@ -1,782 +1,198 @@
/*
PAGES — page-specific layout: home, search, watch.
Widget styling lives in components.css; this file only positions
page-level blocks and handles responsive behavior.
*/
pages.css — page-level layout: home, title, search, list/browse, settings.
*/
.page--padded { padding-top: calc(var(--header-h) + clamp(20px, 3vw, 40px)); }
.page--center { min-height: 70vh; display: grid; place-items: center; padding-top: var(--header-h); }
.page__head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px; margin-bottom: clamp(20px, 2.5vw, 32px); }
.page__title { font-size: var(--fs-2xl); font-weight: var(--fw-heavy); letter-spacing: -0.03em; }
.page__eyebrow { color: var(--accent); font-size: var(--fs-xs); font-weight: var(--fw-heavy); letter-spacing: 0.1em; text-transform: uppercase; margin-bottom: 6px; }
.section { margin-top: clamp(28px, 3.5vw, 48px); }
.section__head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 24px; margin-bottom: 18px; }
.section__title { font-size: clamp(1.1rem, 0.95rem + 0.6vw, 1.45rem); font-weight: var(--fw-heavy); letter-spacing: -0.02em; }
/* ---- home: hero carousel ------------------------------------------------------ */
.hero {
position: relative;
height: clamp(440px, 72vh, 640px);
margin: calc(-1 * var(--space-5)) 0 var(--space-6);
overflow: hidden;
background: var(--color-surface);
/* ---- home ---------------------------------------------------------------------------- */
.hero-slot { min-height: clamp(560px, 88vh, 920px); }
.hero-slot > .hero--empty { height: var(--header-h); }
.rows { position: relative; z-index: 2; margin-top: clamp(-120px, -9vh, -60px); }
.rows > .row:first-child { margin-top: 0; }
@media (max-width: 720px) {
.hero-slot { min-height: max(560px, 82svh); }
.rows { margin-top: -24px; }
}
.hero__slides,
.hero__slide {
position: absolute;
inset: 0;
/* ---- title page -------------------------------------------------------------------------- */
.title-hero {
position: relative; overflow: hidden;
min-height: clamp(540px, 82vh, 860px);
display: flex; align-items: flex-end;
}
.hero__slide {
opacity: 0;
visibility: hidden;
transition: opacity 600ms ease, visibility 0s linear 600ms;
}
.hero__slide.is-active {
z-index: 1;
opacity: 1;
visibility: visible;
transition: opacity 600ms ease;
}
.hero__backdrop {
width: 100%;
height: 100%;
object-fit: cover;
transform: scale(1.04);
transition: transform 8s ease;
}
.hero__slide.is-active .hero__backdrop {
transform: scale(1);
}
.hero__scrim {
position: absolute;
inset: 0;
.title-hero .hero__media { position: absolute; inset: 0; }
.title-hero .hero__img { opacity: 1; object-position: center 25%; }
.title-hero .hero__scrim {
background:
linear-gradient(90deg, rgba(0, 0, 0, 0.84) 0%, rgba(0, 0, 0, 0.58) 45%, rgba(0, 0, 0, 0.22) 75%, rgba(0, 0, 0, 0.05) 100%),
linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.18) 45%, rgba(0, 0, 0, 0.05) 100%);
linear-gradient(90deg, rgba(9, 9, 11, 0.92) 0%, rgba(9, 9, 11, 0.6) 32%, transparent 68%),
linear-gradient(0deg, var(--bg) 0%, rgba(9, 9, 11, 0.55) 26%, transparent 55%),
linear-gradient(180deg, rgba(9, 9, 11, 0.6) 0%, transparent 24%);
}
.title-hero__content {
position: relative; z-index: 2;
display: flex; flex-direction: column; align-items: flex-start; gap: 16px;
padding-top: calc(var(--header-h) + 40px); padding-bottom: clamp(28px, 4vw, 56px);
max-width: calc(min(760px, 64vw) + var(--gutter) * 2);
animation: rise var(--dur-slow) var(--ease) both;
}
.title-hero--loading { background: linear-gradient(180deg, var(--surface) 0%, var(--bg) 100%); }
.title-hero__title { font-size: var(--fs-hero); font-weight: var(--fw-heavy); letter-spacing: -0.035em; line-height: 1.02; text-wrap: balance; text-shadow: 0 2px 30px rgba(0, 0, 0, 0.5); }
.title-hero__tagline { color: var(--text-2); font-style: italic; font-size: var(--fs-md); }
@keyframes rise { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: none; } }
.story { display: grid; grid-template-columns: minmax(0, 1.7fr) minmax(260px, 1fr); gap: clamp(24px, 4vw, 72px); }
.story__text { margin-top: 12px; color: var(--text-2); font-size: 1rem; line-height: 1.7; max-width: 80ch; }
.facts { margin: 0; display: grid; gap: 12px; align-content: start; padding: 20px 22px; border-radius: var(--r-lg); background: var(--surface); border: 1px solid var(--border); }
.facts__row { display: grid; grid-template-columns: 110px 1fr; gap: 12px; font-size: var(--fs-sm); }
.facts dt { color: var(--text-3); font-weight: var(--fw-semi); }
.facts dd { margin: 0; color: var(--text); font-weight: var(--fw-semi); }
.container-row { margin-top: clamp(20px, 3vw, 40px); }
/* cast */
.cast {
display: flex; align-items: center; gap: 12px;
padding: 8px 12px 8px 8px; border-radius: var(--r-pill);
transition: background var(--dur-fast);
}
.cast:hover, .cast:focus-visible { background: var(--surface-2); }
.cast:focus-visible { outline: none; box-shadow: var(--ring); }
.cast__avatar {
flex-shrink: 0; width: 56px; height: 56px; border-radius: 50%; overflow: hidden;
background: var(--surface-3); display: grid; place-items: center;
box-shadow: 0 0 0 2px var(--border);
}
.cast__img { width: 100%; height: 100%; object-fit: cover; }
.cast__initials { font-weight: var(--fw-heavy); color: var(--text-2); }
.cast__text { min-width: 0; }
.cast__name { font-size: var(--fs-sm); font-weight: var(--fw-bold); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.cast__role { font-size: var(--fs-xs); color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* episodes */
.episodes .section__head { border-bottom: 1px solid var(--border); padding-bottom: 0; align-items: flex-end; }
.episodes .section__head .tabs { border-bottom: 0; order: -1; flex-basis: 100%; }
.episodes .section__head .section__title { padding-bottom: 12px; font-size: var(--fs-md); color: var(--text-2); }
.episodes .section__head .select-wrap { margin-bottom: 12px; }
.episodes__grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(290px, 100%), 1fr)); gap: 28px 18px; }
.card--episode .card__media { aspect-ratio: 16 / 9; }
.ep__num {
position: absolute; left: 10px; bottom: 10px; z-index: 1;
padding: 2px 8px; border-radius: var(--r-xs);
background: rgba(0, 0, 0, 0.65); font-size: var(--fs-xs); font-weight: var(--fw-heavy);
}
.card--episode .card__progress { left: 0; right: 0; bottom: 0; border-radius: 0; height: 4px; }
.card--episode .card__shade { opacity: 0.6; }
.ep__body { padding: 12px 2px 0; }
.ep__title { font-weight: var(--fw-bold); font-size: 0.98rem; line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.ep__meta { margin-top: 3px; font-size: var(--fs-xs); color: var(--text-3); font-weight: var(--fw-semi); }
.ep__overview {
margin-top: 6px; font-size: var(--fs-sm); color: var(--text-2); line-height: 1.5;
display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
}
.card--episode.is-future { opacity: 0.55; }
.card--episode.is-watched .ep__meta { color: var(--accent); }
@media (max-width: 900px) {
.story { grid-template-columns: 1fr; }
}
@media (max-width: 720px) {
.title-hero { min-height: auto; padding-top: 52vw; }
.title-hero .hero__media { bottom: auto; height: 78vw; }
.title-hero .hero__img { object-position: center; }
.title-hero .hero__scrim {
background: linear-gradient(0deg, var(--bg) 0%, var(--bg) calc(100% - 78vw), rgba(9, 9, 11, 0.4) calc(100% - 30vw), rgba(9, 9, 11, 0.35) 100%);
}
.title-hero__content { max-width: none; padding-top: 0; gap: 12px; }
.title-hero__title { font-size: 2.2rem; }
.title-hero .hero__logo { max-height: 90px; max-width: 75%; }
.title-hero .hero__actions { width: 100%; }
.title-hero .hero__actions .btn--primary { flex-basis: 100%; }
.title-hero .hero__actions .btn--glass:not(.btn--icon) { flex: 1; }
.title-hero .hero__actions .btn--lg { height: 46px; padding: 0 16px; font-size: 0.95rem; }
.title-hero .hero__actions .btn--lg.btn--icon { width: 46px; padding: 0; }
.facts__row { grid-template-columns: 96px 1fr; }
.card--episode .card__link { display: grid; grid-template-columns: 42% minmax(0, 1fr); gap: 12px; align-items: start; }
.card--episode .ep__body { padding: 0; }
.card--episode .ep__overview { -webkit-line-clamp: 3; line-clamp: 3; font-size: var(--fs-xs); }
.card--episode.card--skeleton { display: grid; grid-template-columns: 42% minmax(0, 1fr); gap: 12px; }
.episodes__grid { gap: 16px; }
}
.hero__fade {
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 34%;
background: linear-gradient(to top, var(--color-bg) 2%, color-mix(in srgb, var(--color-bg) 72%, transparent) 58%, transparent 100%);
pointer-events: none;
/* ---- search ----------------------------------------------------------------------------- */
.search-field {
display: flex; align-items: center; gap: 12px;
height: 60px; padding: 0 20px; margin-bottom: clamp(24px, 3vw, 40px);
border-radius: var(--r-lg); background: var(--surface); border: 1px solid var(--border-strong);
color: var(--text-3);
transition: border-color var(--dur-fast), box-shadow var(--dur-fast);
}
.search-field:focus-within { border-color: var(--accent); box-shadow: 0 0 0 4px var(--accent-soft); color: var(--text); }
.search-field__input { flex: 1; min-width: 0; height: 100%; border: 0; background: none; outline: none; font-size: 1.15rem; font-weight: var(--fw-semi); color: var(--text); }
.search-field__input::placeholder { color: var(--text-3); }
.search-field__input::-webkit-search-cancel-button { filter: invert(1) opacity(0.5); }
.page--padded > .page__title { font-size: var(--fs-lg); margin-bottom: 20px; }
@media (max-width: 720px) { .search-field { height: 52px; } .search-field__input { font-size: 1rem; } }
.hero__inner {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
transform: translateX(-50%);
z-index: 2;
width: 100%;
max-width: var(--container-max);
padding: 0 var(--container-pad);
display: flex;
align-items: flex-end;
}
.load-more { height: 1px; }
.hero__content {
max-width: 620px;
padding-bottom: clamp(72px, 12vh, 112px);
}
.hero__kicker {
display: inline-block;
margin-bottom: var(--space-3);
padding: 4px 10px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: var(--radius-full);
background: rgba(255, 255, 255, 0.08);
backdrop-filter: blur(8px);
color: rgba(255, 255, 255, 0.78);
font-size: var(--text-xs);
font-weight: var(--font-weight-semibold);
letter-spacing: 0.08em;
text-transform: uppercase;
}
.hero__logo {
max-width: min(420px, 60vw);
max-height: 140px;
object-fit: contain;
margin-bottom: var(--space-4);
}
.hero__title {
font-size: clamp(2.2rem, 5vw, 3.6rem);
line-height: 1.05;
letter-spacing: -0.03em;
text-shadow: 0 2px 24px rgba(0, 0, 0, 0.4);
}
.hero__meta {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
margin-top: var(--space-4);
color: rgba(255, 255, 255, 0.78);
font-size: var(--text-sm);
font-weight: var(--font-weight-medium);
}
.hero__rating {
color: var(--color-star);
font-weight: var(--font-weight-semibold);
}
.hero__dot {
color: rgba(255, 255, 255, 0.35);
}
.hero__meta .badge {
border-color: rgba(255, 255, 255, 0.18);
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.88);
}
.hero__overview {
max-width: 58ch;
margin-top: var(--space-4);
color: rgba(255, 255, 255, 0.8);
font-size: var(--text-sm);
line-height: 1.6;
text-shadow: 0 1px 12px rgba(0, 0, 0, 0.35);
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.hero__actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
margin-top: var(--space-5);
}
.hero__play {
padding: 10px 24px;
font-size: var(--text-md);
}
.hero__play svg {
width: 18px;
height: 18px;
}
.hero__arrow {
position: absolute;
z-index: 3;
top: 50%;
transform: translateY(-50%);
display: grid;
place-items: center;
width: 44px;
height: 44px;
border: none;
border-radius: var(--radius-full);
background: rgba(10, 10, 10, 0.42);
color: #fff;
backdrop-filter: blur(8px);
cursor: pointer;
opacity: 0;
transition: opacity 160ms ease, background 120ms ease;
}
.hero:hover .hero__arrow,
.hero__arrow:focus-visible {
opacity: 1;
}
.hero__arrow:hover {
background: rgba(10, 10, 10, 0.65);
}
.hero__arrow svg {
width: 22px;
height: 22px;
}
.hero__arrow--prev {
left: 20px;
}
.hero__arrow--next {
right: 20px;
}
.hero__dots {
position: absolute;
z-index: 3;
left: 50%;
transform: translateX(-50%);
bottom: var(--space-5);
display: flex;
gap: var(--space-2);
}
.hero__dot {
width: 8px;
height: 8px;
padding: 0;
border: none;
border-radius: var(--radius-full);
background: rgba(255, 255, 255, 0.32);
cursor: pointer;
transition: width 160ms ease, background 160ms ease;
}
.hero__dot.is-active {
width: 24px;
background: var(--color-accent);
}
/* ---- search ------------------------------------------------------------------ */
.search-bar {
margin-bottom: var(--space-5);
}
.search-bar__form {
display: flex;
gap: var(--space-2);
}
.search-bar__input {
flex: 1;
font-size: var(--text-md);
padding: var(--space-3) var(--space-4);
}
.search-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
flex-wrap: wrap;
margin-bottom: var(--space-4);
}
.search-count {
font-size: var(--text-sm);
color: var(--color-text-faint);
}
/* ---- watch: player (.player-wrap + controls live in components.css) ------------- */
.player-status {
position: absolute;
inset: 0;
z-index: 2;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-3);
background: rgba(0, 0, 0, 0.75);
color: var(--color-text-dim);
font-size: var(--text-sm);
text-align: center;
padding: var(--space-5);
}
.player-status h3 {
font-size: var(--text-md);
color: var(--color-text);
}
.player-status .spinner {
margin-bottom: var(--space-1);
}
/* ---- watch: toolbar (source popup lives in components.css with the player) ---------- */
.watch-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-3);
margin: var(--space-4) 0 var(--space-5);
font-size: var(--text-sm);
color: var(--color-text-dim);
}
.watch-toolbar__source {
font-weight: var(--font-weight-semibold);
color: var(--color-text);
}
.watch-toolbar__spacer {
flex: 1;
}
/* ---- settings ------------------------------------------------------------------ */
.settings {
display: grid;
grid-template-columns: 200px minmax(0, 1fr);
gap: var(--space-6);
align-items: start;
}
.settings__nav {
position: sticky;
top: calc(var(--header-height) + var(--space-5));
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.settings__navlink {
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-full);
font-size: var(--text-sm);
font-weight: var(--font-weight-medium);
color: var(--color-text-dim);
text-align: left;
}
.settings__navlink:hover {
color: var(--color-text);
background: var(--color-surface);
}
.settings__navlink.is-active {
color: var(--color-accent-text);
background: var(--color-accent);
}
.settings__content {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.settings__card {
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
background: var(--color-surface);
padding: var(--space-5);
scroll-margin-top: calc(var(--header-height) + var(--space-4));
}
.settings__card h2 {
font-size: var(--text-xl);
margin-bottom: var(--space-2);
}
.settings__hint {
color: var(--color-text-dim);
font-size: var(--text-sm);
margin-bottom: var(--space-4);
max-width: 60ch;
}
.settings__actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin: var(--space-4) 0;
}
.settings__status {
font-size: var(--text-sm);
min-height: 1.2em;
}
.settings__status--ok {
color: var(--color-success);
}
.settings__status--err {
color: var(--color-danger);
}
.provider-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: var(--space-2);
margin-top: var(--space-4);
}
/* ---- settings ---------------------------------------------------------------------------- */
.settings__layout { display: grid; grid-template-columns: 200px minmax(0, 1fr); gap: clamp(24px, 4vw, 56px); align-items: start; }
.settings-nav { position: sticky; top: calc(var(--header-h) + 24px); display: flex; flex-direction: column; gap: 2px; }
.settings-nav__link { text-align: left; padding: 10px 14px; border-radius: var(--r-md); color: var(--text-2); font-weight: var(--fw-bold); font-size: var(--fs-sm); }
.settings-nav__link:hover { background: var(--surface); color: var(--text); }
.settings__cards { display: flex; flex-direction: column; gap: 20px; max-width: 980px; }
.settings-card { padding: clamp(18px, 2.4vw, 28px); border-radius: var(--r-lg); background: var(--surface); border: 1px solid var(--border); scroll-margin-top: calc(var(--header-h) + 20px); }
.settings-card__head { margin-bottom: 18px; }
.settings-card__title { font-size: var(--fs-lg); font-weight: var(--fw-heavy); }
.settings-card__desc { margin-top: 4px; color: var(--text-3); font-size: var(--fs-sm); }
.field-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--border); }
.field-row__label { font-weight: var(--fw-bold); }
.switch-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 0 4px; cursor: pointer; }
.switch-row__text { display: flex; flex-direction: column; gap: 2px; font-weight: var(--fw-bold); }
.switch-row__text small { color: var(--text-3); font-weight: var(--fw-medium); font-size: var(--fs-xs); }
.input-row { display: flex; gap: 8px; }
.input-row .input { flex: 1; min-width: 0; }
.toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; }
.toolbar__actions { display: flex; flex-wrap: wrap; gap: 8px; }
.provider-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 8px; margin-top: 14px; }
.provider {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
background: var(--color-surface-2);
cursor: pointer;
transition: border-color 120ms ease;
position: relative; display: flex; align-items: center; gap: 12px;
padding: 10px 12px; border-radius: var(--r-md);
background: var(--bg-elev); border: 1px solid var(--border);
cursor: pointer; transition: border-color var(--dur-fast), background var(--dur-fast);
}
.provider:hover {
border-color: var(--color-border-strong);
.provider:hover { border-color: var(--border-strong); }
.provider input { position: absolute; opacity: 0; pointer-events: none; }
.provider__check {
flex-shrink: 0; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 6px;
border: 1.5px solid var(--border-strong); color: transparent;
transition: background var(--dur-fast), border-color var(--dur-fast), color var(--dur-fast);
}
.provider input:checked ~ .provider__check { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.provider:has(input:checked) { border-color: rgba(192, 132, 252, 0.35); background: rgba(192, 132, 252, 0.06); }
.provider input:focus-visible ~ .provider__check { box-shadow: var(--ring); }
.provider__text { min-width: 0; display: flex; flex-direction: column; }
.provider__name { font-weight: var(--fw-bold); font-size: var(--fs-sm); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.provider__meta { display: flex; align-items: center; gap: 6px; font-size: var(--fs-2xs); color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.health { flex-shrink: 0; width: 7px; height: 7px; border-radius: 50%; background: var(--surface-3); }
.health--good { background: var(--accent); }
.health--fair { background: var(--warn); }
.health--bad { background: var(--danger); }
.provider input[type="checkbox"] {
flex: 0 0 auto;
width: 16px;
height: 16px;
margin: 0;
accent-color: var(--color-accent);
cursor: pointer;
@media (max-width: 900px) {
.settings__layout { grid-template-columns: 1fr; }
.settings-nav { position: static; flex-direction: row; overflow-x: auto; scrollbar-width: none; margin: 0 calc(var(--gutter) * -1); padding: 0 var(--gutter); }
.settings-nav__link { flex-shrink: 0; background: var(--surface); }
}
.provider__name {
font-size: var(--text-sm);
font-weight: var(--font-weight-medium);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* ---- responsive ---------------------------------------------------------------- */
@media (max-width: 720px) {
:root {
--card-width: 132px;
}
.hero {
height: clamp(360px, 58vh, 520px);
margin-bottom: var(--space-5);
}
.hero__content {
padding-bottom: 64px;
}
.hero__overview {
-webkit-line-clamp: 2;
}
.hero__arrow {
display: none;
}
.search-bar__form {
flex-direction: column;
}
.settings {
grid-template-columns: 1fr;
gap: var(--space-4);
}
.settings__nav {
position: static;
flex-direction: row;
flex-wrap: wrap;
}
.settings__card {
padding: var(--space-4);
}
}
.watch-page .page--watch {
padding-top: 0;
}
.watch-page .site-header {
background: transparent;
border-bottom-color: transparent;
backdrop-filter: none;
}
.watch-page.is-scrolled .site-header {
background: color-mix(in srgb, var(--color-bg) 85%, transparent);
border-bottom-color: var(--color-border);
backdrop-filter: blur(12px);
}
.watch-hero {
position: relative;
isolation: isolate;
margin-top: calc(var(--header-height) * -1);
min-height: min(85svh, 900px);
display: flex;
align-items: flex-end;
overflow: hidden;
background: var(--color-surface);
}
.watch-hero__backdrop {
position: absolute;
inset: 0;
z-index: -2;
background-size: cover;
background-position: center;
background-color: var(--color-surface);
}
.watch-hero__scrim {
position: absolute;
inset: 0;
z-index: -1;
background:
linear-gradient(
180deg,
color-mix(in srgb, var(--color-bg) 20%, transparent) 0%,
color-mix(in srgb, var(--color-bg) 55%, transparent) 55%,
var(--color-bg) 100%
),
linear-gradient(
90deg,
color-mix(in srgb, var(--color-bg) 85%, transparent) 0%,
transparent 65%
);
}
.watch-hero__inner {
width: 100%;
max-width: var(--container-max);
margin: 0 auto;
padding: calc(var(--header-height) + var(--space-8)) var(--container-pad) var(--space-8);
}
.watch-hero__logo {
max-width: min(420px, 60vw);
max-height: 140px;
object-fit: contain;
margin-bottom: var(--space-4);
}
.watch-hero__title {
margin: 0;
font-size: clamp(2.2rem, 6vw, 4.5rem);
line-height: 1.02;
letter-spacing: -0.035em;
}
.watch-hero__meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2) var(--space-3);
margin-top: var(--space-4);
color: var(--color-text-dim);
font-size: var(--text-sm);
}
.watch-hero__rating {
color: var(--color-star);
letter-spacing: 2px;
}
.watch-hero__dot {
color: var(--color-text-faint);
}
.watch-hero__genres {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin-top: var(--space-4);
}
.watch-hero__overview {
max-width: 72ch;
margin: var(--space-4) 0 0;
color: var(--color-text-dim);
line-height: 1.55;
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
}
.watch-hero__actions {
margin-top: var(--space-6);
display: flex;
}
.watch-hero__actions .btn--primary {
padding: var(--space-3) var(--space-6);
font-size: var(--text-md);
}
.watch-episodes {
padding: var(--space-8) 0;
}
.watch-episodes__title {
margin: 0 0 var(--space-4);
font-size: var(--text-xl);
}
.season-tabs {
display: flex;
gap: var(--space-2);
overflow-x: auto;
padding-bottom: var(--space-2);
margin-bottom: var(--space-5);
}
.episode-shelf {
display: grid;
grid-auto-flow: column;
grid-auto-columns: minmax(220px, 1fr);
gap: var(--space-4);
overflow-x: auto;
scroll-snap-type: x mandatory;
padding: var(--space-2) var(--space-2) var(--space-3);
scroll-padding: var(--space-2);
}
.episode-shelf__loading,
.episode-shelf__empty {
grid-column: 1 / -1;
display: grid;
place-items: center;
min-height: 180px;
}
.episode-card {
scroll-snap-align: start;
text-align: left;
border: 1px solid var(--color-border);
background: var(--color-surface);
border-radius: var(--radius-lg);
overflow: hidden;
padding: 0;
cursor: pointer;
}
.episode-card--current {
outline: 2px solid var(--color-accent);
outline-offset: 2px;
}
.episode-card__thumb {
position: relative;
display: block;
aspect-ratio: 16 / 9;
width: 100%;
background: var(--color-surface-2);
}
.episode-card__thumb img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.episode-card__thumb--empty {
display: grid;
place-items: center;
font-size: var(--text-2xl);
color: var(--color-text-faint);
}
.episode-card__progress {
position: absolute;
left: 0;
bottom: 0;
height: 3px;
background: var(--color-accent);
}
.episode-card__body {
display: grid;
gap: var(--space-1);
padding: var(--space-3);
}
.episode-card__num {
color: var(--color-text-faint);
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.08em;
}
.episode-card__title {
font-weight: 600;
color: var(--color-text-dim);
}
.episode-card__meta {
color: var(--color-text-dim);
font-size: var(--text-xs);
}
.player-overlay {
position: fixed;
inset: 0;
z-index: 100;
background: #000;
display: grid;
place-items: center;
}
.player-overlay[hidden] {
display: none;
}
body.player-open {
overflow: hidden;
}
body.player-open .player-overlay {
display: grid;
}
.player-overlay__close {
position: absolute;
top: var(--space-4);
right: var(--space-4);
z-index: 20;
background: color-mix(in srgb, #000 60%, transparent);
color: #fff;
border: 1px solid rgb(255 255 255 / 20%);
}
#playerOverlay .player-wrap {
width: 100vw;
height: 100vh;
height: 100dvh;
aspect-ratio: auto;
border: none;
border-radius: 0;
}
#playerOverlay .watch-toolbar {
position: absolute;
left: 50%;
transform: translateX(-50%);
bottom: var(--space-5);
z-index: 2;
background: color-mix(in srgb, #000 65%, transparent);
border: 1px solid rgb(255 255 255 / 10%);
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-md);
}
@media (max-width: 720px) {
.watch-hero {
min-height: 70svh;
}
.watch-hero__inner {
padding-bottom: var(--space-6);
}
.watch-hero__actions .btn--primary {
width: 100%;
}
.episode-shelf {
grid-auto-columns: minmax(160px, 80vw);
}
.player-overlay__close {
top: var(--space-2);
right: var(--space-2);
}
.input-row { flex-wrap: wrap; }
.input-row .input { flex-basis: 100%; }
.provider-grid { grid-template-columns: 1fr; }
.input--sm { max-width: none; flex: 1; }
}
+1292
View File
File diff suppressed because it is too large. Load diff
+114 -60
View File
@@ -1,68 +1,122 @@
/*
============================================================================
DESIGN TOKENS — the only file you need to touch to restyle the whole UI.
Every color, font size, spacing step, radius and shadow used elsewhere
references a variable defined here. Change a value and it applies everywhere.
============================================================================
tokens.css — design tokens. Every color, size, radius, shadow and duration used by the
UI comes from here; retheme by editing this file only.
*/
:root {
/* ---- palette (retheme here) ----------------------------------------- */
--color-bg: #0a0a0a; /* page background */
--color-surface: #141414; /* cards, panels */
--color-surface-hover: #1d1d1d; /* hover state for surfaces */
--color-surface-2: #1a1a1a; /* inputs, alt surfaces */
--color-border: #262626; /* default borders */
--color-border-strong: #3a3a3a; /* visible borders / hover borders */
--color-text: #f2f2f2; /* primary text */
--color-text-dim: #9a9a9a; /* secondary text */
--color-text-faint: #5c5c5c; /* tertiary text */
--color-accent: #c084fc; /* brand / primary action color */
--color-accent-hover: #d8b4fe;
--color-accent-text: #12071f; /* text on accent buttons */
--color-danger: #ff6b6b;
--color-success: #c084fc;
--color-star: #ffc94d; /* rating stars */
color-scheme: dark;
/* ---- typography ------------------------------------------------------ */
--font-sans: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--text-xs: 0.75rem;
--text-sm: 0.875rem;
--text-md: 1rem;
--text-lg: 1.125rem;
--text-xl: 1.375rem;
--text-2xl: 1.75rem;
--text-3xl: 2.25rem;
--leading-tight: 1.2;
--leading-normal: 1.55;
--font-weight-normal: 400;
--font-weight-medium: 500;
--font-weight-semibold: 600;
--font-weight-bold: 700;
/* palette */
--bg: #09090b;
--bg-elev: #0f0f12;
--surface: #15151a;
--surface-2: #1c1c22;
--surface-3: #26262d;
--overlay: rgba(9, 9, 11, 0.82);
--glass: rgba(255, 255, 255, 0.1);
--glass-hover: rgba(255, 255, 255, 0.18);
--glass-border: rgba(255, 255, 255, 0.16);
--border: rgba(255, 255, 255, 0.08);
--border-strong: rgba(255, 255, 255, 0.16);
--text: #f4f4f6;
--text-2: #b6b6c0;
--text-3: #7c7c88;
--accent: #c084fc;
--accent-hover: #d8b4fe;
--accent-ink: #12071f;
--accent-soft: rgba(192, 132, 252, 0.16);
--accent-glow: rgba(192, 132, 252, 0.4);
--star: #f5c518;
--danger: #ff5f5f;
--warn: #f5a524;
--ok: var(--accent);
--focus: #ffffff;
/* ---- spacing (4px scale) ---------------------------------------------- */
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-5: 24px;
--space-6: 32px;
--space-7: 48px;
--space-8: 64px;
/* type */
--font: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--font-mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;
--fs-2xs: 0.6875rem;
--fs-xs: 0.75rem;
--fs-sm: 0.875rem;
--fs-base: 1rem;
--fs-md: 1.125rem;
--fs-lg: 1.375rem;
--fs-xl: 1.75rem;
--fs-2xl: clamp(1.75rem, 1.2rem + 1.6vw, 2.5rem);
--fs-hero: clamp(2.4rem, 1.4rem + 4vw, 4.75rem);
--lh-tight: 1.1;
--lh: 1.55;
--fw-medium: 500;
--fw-semi: 600;
--fw-bold: 700;
--fw-heavy: 800;
/* ---- shape ------------------------------------------------------------- */
--radius-sm: 8px;
--radius-md: 12px;
--radius-lg: 16px;
--radius-full: 999px;
--shadow-1: 0 2px 8px rgba(0, 0, 0, 0.45);
--shadow-2: 0 12px 40px rgba(0, 0, 0, 0.6);
/* spacing (4px base) */
--sp-1: 4px;
--sp-2: 8px;
--sp-3: 12px;
--sp-4: 16px;
--sp-5: 20px;
--sp-6: 24px;
--sp-7: 32px;
--sp-8: 40px;
--sp-9: 48px;
--sp-10: 64px;
--sp-11: 80px;
--max-w: 1680px;
--gutter: max(clamp(16px, 4vw, 56px), calc((100vw - var(--max-w)) / 2));
/* ---- layout ------------------------------------------------------------ */
--container-max: 1280px;
--container-pad: var(--space-5);
--header-height: 64px;
--poster-aspect: 2 / 3; /* 2:3 poster cards */
--card-width: 160px; /* poster card width in carousels */
--player-aspect: 16 / 9;
/* layout */
--header-h: 72px;
--tabbar-h: 0px;
--row-gap: clamp(10px, 1vw, 16px);
--card-poster-w: clamp(128px, 12.5vw, 210px);
--card-wide-w: clamp(250px, 23vw, 380px);
--card-logo-w: clamp(150px, 15vw, 220px);
/* radii */
--r-xs: 4px;
--r-sm: 6px;
--r-md: 10px;
--r-lg: 14px;
--r-xl: 20px;
--r-pill: 999px;
/* shadows */
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4);
--shadow-md: 0 8px 24px rgba(0, 0, 0, 0.45);
--shadow-lg: 0 18px 50px rgba(0, 0, 0, 0.6);
--ring: 0 0 0 2px var(--bg), 0 0 0 4px var(--focus);
/* motion */
--ease: cubic-bezier(0.2, 0.8, 0.2, 1);
--ease-in-out: cubic-bezier(0.65, 0, 0.35, 1);
--dur-fast: 140ms;
--dur: 240ms;
--dur-slow: 600ms;
--dur-fade: 900ms;
/* z layers */
--z-header: 50;
--z-tabbar: 55;
--z-modal: 100;
--z-toast: 110;
}
@media (max-width: 720px) {
:root {
--header-h: 60px;
--tabbar-h: calc(62px + env(safe-area-inset-bottom, 0px));
--card-poster-w: 31vw;
--card-wide-w: 74vw;
--card-logo-w: 40vw;
}
}
@media (prefers-reduced-motion: reduce) {
:root {
--dur-fast: 0ms;
--dur: 0ms;
--dur-slow: 0ms;
--dur-fade: 0ms;
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36"><path fill="#AA8DD8" d="M7.415 4c1-1 .25-4-1.438-4s-1.562 2-.562 2 1 2 1 3 1-1 1-1zM3.232 5.72c1-1 .25-4-1.438-4s-1.562 2-.562 2 1 2 1 3 1-1 1-1z"/><path fill="#744EAA" d="M29.607 32.856c.189.808 1.227 2.28 2.032 2.091.806-.19 1.077-1.971.888-2.777-.189-.808-.998-1.307-1.804-1.117-.805.19-1.306.997-1.116 1.803zm-5.434.649c.003.83.681 2.498 1.509 2.495.828-.004 1.494-1.677 1.491-2.506-.003-.829-.677-1.497-1.505-1.495-.828.004-1.498.677-1.495 1.506zm-5.271-2.446c-.326.764-.365 2.563.396 2.89.763.324 2.037-.947 2.363-1.71.325-.762-.028-1.643-.789-1.97-.762-.325-1.643.027-1.97.79zm-5.031-11.04c-.812.172-2.308 1.173-2.139 1.983.173.81 1.945 1.124 2.757.953.811-.171 1.329-.967 1.16-1.777-.172-.81-.965-1.33-1.778-1.159zm-2.037-5c-.812.172-2.308 1.173-2.139 1.983.173.81 1.945 1.124 2.757.953.811-.171 1.329-.967 1.16-1.777-.172-.81-.966-1.33-1.778-1.159z"/><path fill="#9266CC" d="M27.244 34c2.831 0 4.926-.877 5.266-1.027 2.271-1.01 3.293-3.669 2.284-5.939-.999-2.25-3.616-3.275-5.872-2.314-.133.05-1.793.649-3.343-.072-1.851-.861-2.995-3.309-3.628-5.209-.144-.43-.385-1.274-.686-2.316-1.866-6.471-2.832-8.285-3.983-9.82C13.571 2.352 7.69 2.007 4.799 2.587c-2.437.487-4.018 2.858-3.53 5.295.488 2.438 2.86 4.02 5.296 3.53.162-.026 2.204-.306 3.424 1.169.643 1.287 2.08 5.128 2.63 7.034.346 1.199.629 2.171.794 2.667 1.773 5.317 4.666 8.893 8.603 10.629C23.868 33.729 25.67 34 27.244 34z"/><circle fill="#FFF" cx="6.682" cy="5" r="1"/><path d="M30.923 32.964c-.089 0-.18-.012-.269-.036-.532-.148-.844-.699-.696-1.231.757-2.722-.77-4.542-.785-4.56-.359-.419-.312-1.051.107-1.41.418-.359 1.051-.312 1.41.107.092.107 2.234 2.66 1.195 6.397-.122.443-.525.733-.962.733zm-7.199-.563c-.245 0-.49-.089-.684-.27-.403-.378-.424-1.011-.047-1.414 1.485-1.587 1.453-4.193 1.452-4.22-.016-.552.419-1.012.972-1.028.542-.005 1.013.419 1.028.972.004.139.073 3.437-1.991 5.644-.197.21-.464.316-.73.316zm-8.542-8.696c-.48 0-.904-.347-.985-.837-.09-.544.278-1.06.823-1.149 3.074-.51 4.774-2.377 4.791-2.396.365-.41.998-.449 1.409-.084.412.365.453.993.091 1.406-.087.099-2.156 2.415-5.964 3.046-.056.01-.111.014-.165.014zm2.921 4.857c-.425 0-.819-.272-.954-.698-.166-.526.126-1.089.652-1.255 2.693-.853 3.88-2.83 3.892-2.85.28-.477.892-.637 1.368-.357.477.279.636.893.357 1.368-.063.108-1.595 2.663-5.013 3.744-.101.033-.203.048-.302.048zm-4.619-10.67c-.496 0-.927-.369-.991-.875-.069-.548.319-1.048.867-1.118 2.689-.34 4.657-1.971 4.676-1.988.422-.354 1.053-.303 1.408.119.356.421.305 1.05-.115 1.407-.097.083-2.42 2.029-5.718 2.446-.043.006-.085.009-.127.009zm-1.821-4.767c-.425 0-.819-.273-.954-.701-.165-.527.127-1.088.654-1.254 3.13-.983 4.253-2.692 4.299-2.764.295-.462.911-.605 1.375-.312.465.292.611.899.324 1.366-.06.097-1.506 2.396-5.399 3.619-.099.031-.2.046-.299.046z" fill="#744EAA"/></svg>

After

Width:  |  Height:  |  Size: 2.8 KiB

+68 -30
View File
@@ -2,52 +2,90 @@
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>bug.tv — home</title>
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<meta name="theme-color" content="#09090b">
<meta name="description" content="bug tv — stream movies and series.">
<!-- API base default; replaced at build time (empty → https://api-tv.bug.tools). -->
<meta name="bug-tv-api" content="">
<!-- Path the site is served under (history routing); "/" for a domain root. -->
<meta name="bug-tv-root" content="/">
<title>bug tv</title>
<script>
/* Router mode + <base> so assets resolve from deep links (/title/tv/1399) and file://. */
(function () {
var l = location;
var m = document.querySelector('meta[name="bug-tv-root"]');
var root = m && m.content && !/^@.*@$/.test(m.content) ? m.content : '/';
if (root.slice(-1) !== '/') root += '/';
var fileish = l.protocol === 'file:' || /\.html?$/i.test(l.pathname);
var hash = fileish || /^#\//.test(l.hash);
var base = document.createElement('base');
base.href = fileish ? l.href.split('#')[0] : l.origin + root;
document.head.appendChild(base);
window.__BUGTV_ROUTER = { mode: hash ? 'hash' : 'history', root: root };
})();
</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preconnect" href="https://image.tmdb.org">
<link rel="preconnect" href="https://api.themoviedb.org">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap">
<link rel="icon" type="image/svg+xml" href="img/bug.svg">
<link rel="stylesheet" href="css/tokens.css">
<link rel="stylesheet" href="css/base.css">
<link rel="stylesheet" href="css/components.css">
<link rel="stylesheet" href="css/pages.css">
<link rel="stylesheet" href="css/player.css">
<link rel="modulepreload" href="js/router.js">
</head>
<body class="home-page">
<header class="site-header">
<div class="container site-header__inner">
<a class="brand" href="index.html">bug<span>.tv</span></a>
<nav class="site-header__nav" aria-label="Primary">
<body>
<a class="skip-link" href="#app">Skip to content</a>
<header class="site-header is-over-hero">
<div class="site-header__inner container">
<a class="brand" data-href="/" aria-label="bug tv home">
<img class="brand__mark" src="img/bug.svg" alt="" width="32" height="32"><span class="brand__word">bug<span>.tv</span></span>
</a>
<nav class="site-nav" aria-label="Primary">
<a class="site-nav__link" data-nav data-href="/">Home</a>
<a class="site-nav__link" data-nav data-href="/movies">Movies</a>
<a class="site-nav__link" data-nav data-href="/tv">Series</a>
<a class="site-nav__link" data-nav data-href="/list">My List</a>
</nav>
<div class="site-header__actions">
<a class="icon-btn" href="search.html" aria-label="Search" title="Search">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
</a>
<a class="icon-btn" href="settings.html" aria-label="Settings" title="Settings">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
</a>
<form class="header-search" role="search">
<button class="header-search__icon" type="button" tabindex="-1" aria-hidden="true"><span data-icon="search"></span></button>
<input type="search" name="q" placeholder="Search titles" autocomplete="off" spellcheck="false" aria-label="Search movies and series">
<kbd class="header-search__kbd" aria-hidden="true">/</kbd>
</form>
<a class="icon-btn header-search-link" data-nav data-href="/search" aria-label="Search" title="Search"><span data-icon="search"></span></a>
<a class="icon-btn" data-nav data-href="/settings" aria-label="Settings" title="Settings"><span data-icon="settings"></span></a>
</div>
</div>
</header>
<main class="page" id="content">
<div id="heroSlot"></div>
<div class="container">
<div id="sections"></div>
</div>
</main>
<main id="app" class="app" aria-live="polite"></main>
<footer class="site-footer">
<div class="container">
<span>tv.bug.tools</span>
<span>api: <a id="apiBaseLabel" href="#" target="_blank" rel="noopener"></a></span>
<span>tv.bug.tools doesn't store files, but provides links to external services.</span>
<div class="container site-footer__inner">
<span class="brand brand--sm"><img class="brand__mark" src="img/bug.svg" alt="" width="32" height="32"><span class="brand__word">bug<span>.tv</span></span></span>
<span class="site-footer__note">bug tv doesn't host files — it links to third-party sources. Metadata by TMDB.</span>
<span class="site-footer__api">api · <a id="apiBaseLabel" href="#" target="_blank" rel="noopener"></a></span>
</div>
</footer>
<script src="js/util.js"></script>
<script src="js/config.js"></script>
<script src="js/api.js"></script>
<script src="js/storage.js"></script>
<script src="js/cards.js"></script>
<script src="js/app.js"></script>
<script src="js/home.js"></script>
<nav class="tabbar" aria-label="Primary">
<a class="tabbar__link" data-nav data-href="/"><span data-icon="home" data-size="22"></span><span>Home</span></a>
<a class="tabbar__link" data-nav data-href="/movies"><span data-icon="film" data-size="22"></span><span>Movies</span></a>
<a class="tabbar__link" data-nav data-href="/tv"><span data-icon="tv" data-size="22"></span><span>Series</span></a>
<a class="tabbar__link" data-nav data-href="/search"><span data-icon="search" data-size="22"></span><span>Search</span></a>
<a class="tabbar__link" data-nav data-href="/list"><span data-icon="bookmark" data-size="22"></span><span>My List</span></a>
</nav>
<div id="toasts" class="toasts" role="status" aria-live="polite"></div>
<noscript><p style="padding:2rem;color:#fff">bug tv needs JavaScript.</p></noscript>
<script type="module" src="js/app.js"></script>
</body>
</html>
+169 -166
View File
@@ -1,176 +1,179 @@
/*
API — two upstreams:
1. the bug-tv REST server (SR.config.getBase()): provider catalog,
/streams lookup, and the /proxy/media tunnel the player needs (CORS,
headers, m3u8 rewrite).
2. TMDB, called straight from the browser (it is CORS-enabled): search,
trending, details, seasons, episodes. Each returns the same shape the
server's endpoints used to, so the pages are unchanged.
API — client for the bug-tv server (docs/api.md, "Endpoints").
Keeping catalog traffic off the server means it only does provider scraping
and stream proxying.
streams(params, handlers) opens the SSE stream at /v1/streams and calls
handlers as events arrive:
onMeta({tmdb,type,season,episode,providers,timeoutMs,cached})
onStreams({provider, ms, streams:[Stream]})
onProvider({name, status, ms, count, error?})
onDone({total, ms})
onError(Error)
Returns { close() }.
If EventSource fails before any event arrives (old proxy, CORS, a browser
without SSE), it falls back to ?format=json and replays the aggregated
response through the same handlers.
*/
(function () {
'use strict';
import { resolveUrl, getProviders } from './config.js';
const TMDB_BASE = 'https://api.themoviedb.org/3';
const TMDB_IMG = 'https://image.tmdb.org/t/p/';
async function request(path, params) {
const url = new URL(SR.config.getBase() + path);
if (params) {
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null || value === '') continue;
url.searchParams.set(key, String(value));
}
}
let res;
try {
res = await fetch(url.toString());
} catch (e) {
throw new Error(`cannot reach the API at ${SR.config.getBase()} — check the base URL in Settings`);
}
let data = null;
try {
data = await res.json();
} catch (e) {
/* non-JSON body */
}
if (!res.ok) {
throw new Error((data && data.error) || `API error: HTTP ${res.status}`);
}
return data;
function providerList() {
let list;
try {
list = getProviders();
} catch (e) {
list = null;
}
return Array.isArray(list) ? list.filter(Boolean) : [];
}
// Direct TMDB call. `key` overrides the configured key (Settings "Test").
async function tmdb(pathname, params, key) {
const url = new URL(TMDB_BASE + pathname);
url.searchParams.set('api_key', key || SR.config.getTmdbKey());
url.searchParams.set('language', 'en-US');
if (params) {
for (const [k, v] of Object.entries(params)) {
if (v === undefined || v === null || v === '') continue;
url.searchParams.set(k, String(v));
}
}
let res;
try {
res = await fetch(url.toString());
} catch (e) {
throw new Error('cannot reach the TMDB API — check your connection or the TMDB API key in Settings');
}
let data = null;
try {
data = await res.json();
} catch (e) {
/* non-JSON body */
}
if (!res.ok) {
if (res.status === 401) {
throw new Error('TMDB rejected the API key — check "TMDB API key" in Settings');
}
throw new Error((data && (data.status_message || data.error)) || `TMDB error: HTTP ${res.status}`);
}
return data;
function query(params, extra) {
const q = new URLSearchParams();
q.set('tmdb', String(params.tmdb ?? params.id));
q.set('type', params.type === 'tv' ? 'tv' : 'movie');
if (params.type === 'tv') {
if (params.season != null) q.set('season', String(params.season));
if (params.episode != null) q.set('episode', String(params.episode));
}
const providers = Array.isArray(params.providers) ? params.providers : providerList();
if (providers.length) q.set('providers', providers.join(','));
for (const [k, v] of Object.entries(extra || {})) q.set(k, v);
return q.toString();
}
// route a media/subtitle URL through the API proxy (CORS, headers, m3u8 rewrite)
function proxyUrl(target, headers) {
const q = new URLSearchParams();
q.set('url', target);
q.set('h', JSON.stringify(headers || {}));
return SR.config.getBase() + '/proxy/media?' + q.toString();
}
async function getJson(path) {
const res = await fetch(resolveUrl(path), { headers: { Accept: 'application/json' } });
if (!res.ok) throw new Error(`HTTP ${res.status} for ${path}`);
return res.json();
}
// Same shapes the server endpoints used to return.
function searchResult(m) {
const isTv = m.media_type === 'tv';
const date = isTv ? m.first_air_date : m.release_date;
return {
tmdb_id: m.id,
type: isTv ? 'tv' : 'movie',
name: m.title || m.name,
year: date ? String(date).slice(0, 4) : '',
poster: m.poster_path ? `${TMDB_IMG}w342${m.poster_path}` : '',
backdrop: m.backdrop_path ? `${TMDB_IMG}w1280${m.backdrop_path}` : '',
rating: m.vote_average ? Number(m.vote_average).toFixed(1) : '',
overview: m.overview || '',
};
}
function fullImage(pathname) {
return pathname ? `${TMDB_IMG}original${pathname}` : '';
}
window.SR = window.SR || {};
SR.api = {
request,
tmdb,
proxyUrl,
// — TMDB, straight from the browser —
search: (q) =>
tmdb('/search/multi', { query: q, include_adult: 'false', page: 1 }).then((r) => {
const results = (r.results || [])
.filter((m) => m.media_type === 'movie' || m.media_type === 'tv')
.slice(0, 15)
.map(searchResult);
return { query: q, count: results.length, results };
}),
trending: (type, timeWindow) => {
const t = ['movie', 'tv', 'all'].includes(type) ? type : 'all';
const w = timeWindow === 'day' ? 'day' : 'week';
return tmdb(`/trending/${t}/${w}`).then((r) => {
const results = (r.results || []).slice(0, 20).map(searchResult);
return { type: t, window: w, count: results.length, results };
});
},
details: (type, id) =>
tmdb(`/${type}/${id}`, { append_to_response: 'images' }).then((d) => {
d.poster_url = fullImage(d.poster_path);
d.backdrop_url = fullImage(d.backdrop_path);
if (d.images) {
for (const key of Object.keys(d.images)) {
d.images[key] = (d.images[key] || []).map((im) => ({ ...im, url: fullImage(im.file_path) }));
}
}
return d;
}),
seasons: (id) =>
tmdb(`/tv/${id}`).then((r) => {
const seasons = (r.seasons || [])
.filter((s) => s.season_number > 0 && (s.episode_count || 0) > 0)
.map((s) => ({
season_number: s.season_number,
name: s.name,
episode_count: s.episode_count,
air_date: s.air_date || '',
}));
return { tmdb_id: id, count: seasons.length, seasons };
}),
episodes: (id, season) =>
tmdb(`/tv/${id}/season/${season}`).then((r) => {
const episodes = (r.episodes || [])
.slice()
.sort((a, b) => a.episode_number - b.episode_number)
.map((e) => ({
episode_number: e.episode_number,
name: e.name,
air_date: e.air_date || '',
still: e.still_path ? `${TMDB_IMG}w300${e.still_path}` : '',
}));
return { tmdb_id: id, season: parseInt(season, 10), count: episodes.length, episodes };
}),
// — bug-tv server (providers, streams, proxy) —
streams: ({ tmdb, type, season, episode, providers }) =>
request('/streams', {
tmdb,
type,
season,
episode,
providers: Array.isArray(providers) && providers.length ? providers.join(',') : '',
}),
providers: () => request('/providers'),
export function streams(params, handlers = {}) {
const h = {
onMeta() {},
onStreams() {},
onProvider() {},
onDone() {},
onError() {},
...handlers,
};
})();
let closed = false;
let gotEvent = false;
let finished = false;
let es = null;
let abort = null;
const call = (fn, data) => {
try {
fn(data);
} catch (e) {
console.error('[api.streams] handler failed', e);
}
};
const listen = (fn) => (ev) => {
if (closed || finished) return;
gotEvent = true;
let data;
try {
data = JSON.parse(ev.data);
} catch (e) {
return;
}
call(fn, data);
};
function finish(data) {
if (finished || closed) return;
finished = true;
if (es) es.close();
call(h.onDone, data || { total: 0, ms: 0 });
}
async function jsonFallback() {
if (es) es.close();
es = null;
abort = typeof AbortController === 'function' ? new AbortController() : null;
const started = performance.now();
try {
const res = await fetch(resolveUrl(`/v1/streams?${query(params, { format: 'json' })}`), {
headers: { Accept: 'application/json' },
signal: abort ? abort.signal : undefined,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (closed) return;
const list = Array.isArray(data.streams) ? data.streams : [];
const errors = data.providerErrors || {};
const byProvider = new Map();
for (const s of list) {
const p = s.provider || 'unknown';
if (!byProvider.has(p)) byProvider.set(p, []);
byProvider.get(p).push(s);
}
const names = [...new Set([...byProvider.keys(), ...Object.keys(errors)])];
const ms = Math.round(performance.now() - started);
call(h.onMeta, {
tmdb: params.tmdb,
type: params.type,
season: params.season,
episode: params.episode,
providers: names,
timeoutMs: 0,
cached: [],
});
for (const [provider, s] of byProvider) call(h.onStreams, { provider, ms, streams: s });
for (const name of names) {
const count = (byProvider.get(name) || []).length;
call(
h.onProvider,
errors[name]
? { name, status: 'error', ms, count, error: String(errors[name]) }
: { name, status: count ? 'ok' : 'empty', ms, count },
);
}
finish({ total: list.length, ms });
} catch (e) {
if (closed) return;
call(h.onError, e);
finish({ total: 0, ms: Math.round(performance.now() - started), error: String(e.message || e) });
}
}
if (typeof EventSource !== 'function') {
jsonFallback();
} else {
es = new EventSource(resolveUrl(`/v1/streams?${query(params)}`));
es.addEventListener('meta', listen(h.onMeta));
es.addEventListener('streams', listen(h.onStreams));
es.addEventListener('provider', listen(h.onProvider));
es.addEventListener('done', listen(finish));
es.addEventListener('error', () => {
if (closed || finished) return;
if (!gotEvent) {
jsonFallback();
return;
}
// Connection dropped mid-stream. EventSource would reconnect and replay
// the whole scrape; stop and treat what arrived as final.
finish({ total: -1, ms: 0, error: 'stream interrupted' });
});
}
return {
close() {
if (closed) return;
closed = true;
if (es) es.close();
if (abort) abort.abort();
},
};
}
export function providers() {
return getJson('/v1/providers');
}
export function prefetch(params) {
return fetch(resolveUrl(`/v1/prefetch?${query(params)}`), { headers: { Accept: 'application/json' } })
.then((r) => (r.ok ? r.json() : null))
.catch(() => null);
}
+96 -32
View File
@@ -1,41 +1,105 @@
/*
APP — shared chrome for every page: footer API label, toast notifications.
(Settings moved to its own page: settings.html)
app.js — boots the shell: header (glass → solid on scroll, nav state, search box),
mobile tab bar, footer label, then starts the router.
Exposes window.bugtv = { navigate, href, toast } for non-module callers / debugging.
*/
(function () {
'use strict';
import { h, debounce } from './util.js';
import { getBase } from './config.js';
import { start, navigate, href, onChange, current } from './router.js';
import { toast } from './ui/toast.js';
import { icon } from './ui/icons.js';
function initChrome() {
const label = document.getElementById('apiBaseLabel');
if (label) {
const base = SR.config.getBase();
label.textContent = base;
label.href = base;
}
const header = document.querySelector('.site-header');
const outlet = document.getElementById('app');
// links declared as data-href="/path" in index.html get mode-aware hrefs
function wireLinks(scope = document) {
scope.querySelectorAll('[data-href]').forEach((a) => a.setAttribute('href', href(a.dataset.href)));
}
// icons for static markup: <span data-icon="search"></span>
document.querySelectorAll('[data-icon]').forEach((el) => el.replaceWith(icon(el.dataset.icon, { size: Number(el.dataset.size) || 20 })));
wireLinks();
// header: transparent over the hero, solid once scrolled
const onScroll = () => header.classList.toggle('is-solid', window.scrollY > 24);
window.addEventListener('scroll', onScroll, { passive: true });
onScroll();
// search box in the header
const searchForm = document.querySelector('.header-search');
const searchInput = searchForm.querySelector('input');
const searchGo = debounce(() => {
const q = searchInput.value.trim();
const onSearch = current().name === 'search';
if (!q && !onSearch) return;
navigate(`/search${q ? `?q=${encodeURIComponent(q)}` : ''}`, { replace: onSearch });
}, 300);
searchInput.addEventListener('input', searchGo);
searchForm.addEventListener('submit', (e) => {
e.preventDefault();
searchGo.cancel();
const q = searchInput.value.trim();
navigate(`/search${q ? `?q=${encodeURIComponent(q)}` : ''}`, { replace: current().name === 'search' });
});
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
searchInput.value = '';
searchInput.blur();
}
});
searchForm.querySelector('.header-search__icon').addEventListener('click', () => searchInput.focus());
let toastTimer = null;
function toast(message, isError) {
let el = document.getElementById('toast');
if (!el) {
el = document.createElement('div');
el.id = 'toast';
el.className = 'toast';
el.setAttribute('role', 'status');
document.body.appendChild(el);
}
el.textContent = message;
el.classList.toggle('toast--error', !!isError);
el.classList.add('toast--show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.classList.remove('toast--show'), 4500);
// "/" focuses search (like most streaming sites)
document.addEventListener('keydown', (e) => {
if (e.key === '/' && !/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName) && !e.metaKey && !e.ctrlKey) {
e.preventDefault();
if (getComputedStyle(searchForm).display === 'none') navigate('/search');
else searchInput.focus();
}
});
function showError(err, fallback) {
toast(err && err.message ? err.message : fallback || 'Something went wrong', true);
// active nav state + keep the header search in sync with the URL
const navMap = { home: '/', movies: '/movies', tv: '/tv', list: '/list', search: '/search', settings: '/settings' };
onChange((r) => {
const active = navMap[r.name] || (r.name === 'browse' ? (r.params.type === 'tv' ? '/tv' : '/movies') : null);
document.querySelectorAll('[data-nav]').forEach((a) => {
const on = a.dataset.href === active;
a.classList.toggle('is-active', on);
if (on) a.setAttribute('aria-current', 'page');
else a.removeAttribute('aria-current');
});
if (r.name === 'search') {
if (document.activeElement !== searchInput) searchInput.value = r.query.get('q') || '';
} else {
searchInput.value = '';
}
header.classList.toggle('is-over-hero', r.name === 'home' || r.name === 'movies' || r.name === 'tv' || r.name === 'title');
onScroll();
});
window.SR = window.SR || {};
SR.app = { initChrome, toast, showError };
})();
// footer API label
const apiLabel = document.getElementById('apiBaseLabel');
if (apiLabel) {
const paint = () => {
apiLabel.textContent = getBase().replace(/^https?:\/\//, '');
apiLabel.href = getBase();
};
paint();
window.addEventListener('storage', paint);
onChange(paint);
}
// skip link (fragment links would navigate because of <base>)
const skip = document.querySelector('.skip-link');
if (skip) {
skip.addEventListener('click', (e) => {
e.preventDefault();
outlet.setAttribute('tabindex', '-1');
outlet.focus();
});
}
window.bugtv = Object.assign(window.bugtv || {}, { navigate, href, toast, h });
start(outlet);
-249
View File
@@ -1,249 +0,0 @@
/*
CARDS — renders poster cards, rows (carousels) and grids.
Items can come straight from the API ({tmdb_id, type, name, year, poster})
or from storage records; normalizeItem() handles both.
*/
(function () {
'use strict';
const { escapeHtml: esc, tmdbResize, formatSeconds } = SR.util;
function normalizeItem(r) {
return {
tmdbId: r.tmdb_id != null ? r.tmdb_id : r.tmdbId,
type: r.type,
season: r.season,
episode: r.episode,
name: r.name || r.title || '',
year: r.year || '',
poster: r.poster || r.poster_url || '',
backdrop: r.backdrop || r.backdrop_url || '',
rating: r.rating || (r.vote_average ? Number(r.vote_average).toFixed(1) : ''),
overview: r.overview || '',
};
}
function watchHref(item) {
const p = new URLSearchParams();
p.set('id', item.tmdbId);
p.set('type', item.type);
if (item.type === 'tv') {
if (item.season != null) p.set('s', item.season);
if (item.episode != null) p.set('e', item.episode);
}
return `watch.html?${p.toString()}`;
}
function card(item, opts = {}) {
const el = document.createElement('a');
el.className = 'card';
el.href = opts.href || watchHref(item);
const poster = tmdbResize(item.poster, 'w342');
const progress =
opts.progress != null
? `<span class="card__progress"><i style="width:${Math.round(Math.min(1, opts.progress) * 100)}%"></i></span>`
: '';
const meta =
item.meta ||
(item.year
? `${item.year} · ${item.type === 'tv' ? 'TV' : 'Movie'}`
: item.type === 'tv'
? 'TV'
: 'Movie');
const metaHtml = item.metaHtml || `<span class="card__meta__text">${esc(meta)}</span>`;
const title = item.hideTitle
? ''
: `<span class="card__title">${esc(item.name)}</span>`;
el.innerHTML = `
<span class="card__poster${poster ? '' : ' card__poster--empty'}">
${poster ? `<img src="${poster}" alt="" loading="lazy">` : '?'}
${progress}
</span>
${title}
<span class="card__meta">${metaHtml}</span>`;
if (item.hideTitle) el.setAttribute('aria-label', `${item.name} — ${meta}`);
return el;
}
function row(title, items) {
const section = document.createElement('section');
section.className = 'row';
section.innerHTML = `<div class="row__header"><h2 class="row__title">${esc(title)}</h2></div>`;
const scroll = document.createElement('div');
scroll.className = 'row__scroll';
for (const item of items) scroll.appendChild(card(item));
section.appendChild(scroll);
return section;
}
function grid(items) {
const el = document.createElement('div');
el.className = 'grid';
for (const item of items) el.appendChild(card(item));
return el;
}
function emptyState(title, hint) {
const el = document.createElement('div');
el.className = 'empty';
el.innerHTML = `<h3>${esc(title)}</h3>${hint ? `<p>${esc(hint)}</p>` : ''}`;
return el;
}
// "Continue watching" row: latest record per show, with progress bar
function continueRow() {
const recs = SR.storage.latestPerShow();
if (!recs.length) return null;
const items = recs.map((r) => ({
tmdbId: r.tmdbId,
type: r.type,
season: r.season,
episode: r.episode,
name: r.show || r.title || '',
poster: r.poster || '',
hideTitle: true,
meta:
r.type === 'tv'
? `S${r.season} · E${r.episode} · ${formatSeconds(Math.max(0, r.d - r.t))} left`
: `Movie · ${formatSeconds(Math.max(0, r.d - r.t))} left`,
metaHtml:
r.type === 'tv'
? `<span class="card__ep">S${r.season} <span class="card__ep-dot">·</span> E${r.episode}</span><span class="card__dot">·</span><span class="card__meta__text">${formatSeconds(Math.max(0, r.d - r.t))} left</span>`
: `<span class="card__meta__text">Movie · ${formatSeconds(Math.max(0, r.d - r.t))} left</span>`,
progress: r.d ? r.t / r.d : 0,
}));
return row('Continue watching', items);
}
function heroCarousel(items) {
const data = (items || []).filter((item) => item && item.backdrop && item.name);
if (!data.length) return null;
const section = document.createElement('section');
section.className = 'hero';
section.setAttribute('aria-roledescription', 'carousel');
section.setAttribute('aria-label', 'Featured titles');
const wrap = document.createElement('div');
wrap.className = 'hero__slides';
const slideEls = [];
for (let i = 0; i < data.length; i += 1) {
const item = data[i];
const slide = document.createElement('article');
slide.className = i === 0 ? 'hero__slide is-active' : 'hero__slide';
slide.setAttribute('role', 'group');
slide.setAttribute('aria-roledescription', 'slide');
slide.setAttribute('aria-label', `${i + 1} of ${data.length}: ${item.name}`);
const typeLabel = item.type === 'tv' ? 'TV' : 'Movie';
const metaBits = [
item.rating ? `<span class="hero__rating">★ ${esc(item.rating)}</span>` : '',
item.year ? `<span>${esc(item.year)}</span>` : '',
`<span class="badge">${esc(typeLabel)}</span>`,
]
.filter(Boolean)
.join('<span class="hero__dot" style="height: 1px;">·</span>');
slide.innerHTML = `
<img class="hero__backdrop" src="${item.backdrop}" alt="" loading="${i === 0 ? 'eager' : 'lazy'}">
<div class="hero__scrim"></div>
<div class="hero__fade"></div>
<div class="container hero__inner">
<div class="hero__content">
<h1 class="hero__title">${esc(item.name)}</h1>
<div class="hero__meta">${metaBits}</div>
${item.overview ? `<p class="hero__overview">${esc(item.overview)}</p>` : ''}
<div class="hero__actions">
<a class="btn btn--primary hero__play" href="${watchHref(item)}">
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"></path></svg>
<span>Play</span>
</a>
</div>
</div>
</div>`;
wrap.appendChild(slide);
slideEls.push(slide);
}
section.appendChild(wrap);
if (slideEls.length > 1) {
const prev = document.createElement('button');
prev.type = 'button';
prev.className = 'hero__arrow hero__arrow--prev';
prev.setAttribute('aria-label', 'Previous slide');
prev.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 18l-6-6 6-6"></path></svg>';
const next = document.createElement('button');
next.type = 'button';
next.className = 'hero__arrow hero__arrow--next';
next.setAttribute('aria-label', 'Next slide');
next.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"></path></svg>';
const dots = document.createElement('div');
dots.className = 'hero__dots';
const dotEls = [];
for (let i = 0; i < slideEls.length; i += 1) {
const dot = document.createElement('button');
dot.type = 'button';
dot.className = i === 0 ? 'hero__dot is-active' : 'hero__dot';
dot.setAttribute('aria-label', `Go to slide ${i + 1}`);
dots.appendChild(dot);
dotEls.push(dot);
}
section.append(prev, next, dots);
let current = 0;
let timer = null;
function goTo(index) {
current = (index + slideEls.length) % slideEls.length;
slideEls.forEach((slide, i) => slide.classList.toggle('is-active', i === current));
dotEls.forEach((dot, i) => dot.classList.toggle('is-active', i === current));
}
function start() {
stop();
if (!document.hidden) timer = setInterval(() => goTo(current + 1), 7000);
}
function stop() {
if (timer) {
clearInterval(timer);
timer = null;
}
}
prev.addEventListener('click', () => {
goTo(current - 1);
start();
});
next.addEventListener('click', () => {
goTo(current + 1);
start();
});
dotEls.forEach((dot, i) => dot.addEventListener('click', () => {
goTo(i);
start();
}));
section.addEventListener('mouseenter', stop);
section.addEventListener('mouseleave', start);
section.addEventListener('focusin', stop);
section.addEventListener('focusout', (e) => {
if (!section.contains(e.relatedTarget)) start();
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) stop();
else start();
});
start();
}
return section;
}
window.SR = window.SR || {};
SR.cards = { normalizeItem, card, row, grid, emptyState, continueRow, watchHref, heroCarousel };
})();
+96 -171
View File
@@ -1,182 +1,107 @@
/*
CONFIG — where the API lives + which providers to query.
config.js — where the API lives, the TMDB key, and which providers to query.
API base resolution order:
1. ?api=<url> query param on any page (session override)
2. localStorage (saved from Settings)
3. built-in default
1. ?api=<url> query param (session override, also read from a hash route)
2. localStorage (saved from Settings) key: bug-tv.apiBase.v1
3. <meta name="bug-tv-api" content="…"> in index.html (substituted at build time by nix)
4. built-in default https://api-tv.bug.tools
Providers: until the user toggles anything in Settings, the server's own
enabled list is used. Once customized, a {name: bool} map is stored in
localStorage; names missing from the map default to enabled.
Providers: until the user toggles anything in Settings, getProviders() returns null and
the server's defaults apply. Once customized a {id: bool} map is stored (same format as v4,
key bug-tv.providers.v1); getProviders() returns the enabled ids.
TMDB key: search/trending/details/images go straight to TMDB from the
browser (the server only serves providers, streams and the media proxy).
The key resolves from localStorage (Settings) or the built-in default.
TMDB key: catalog calls go straight from the browser to TMDB.
*/
(function () {
'use strict';
import { getParam, safe } from './util.js';
const DEFAULT_BASE = 'https://api-tv.bug.tools';
const STORAGE_KEY = 'bug-tv.apiBase.v1';
const PROVIDER_KEY = 'bug-tv.providers.v1';
export const FALLBACK_BASE = 'https://api-tv.bug.tools';
export const STORAGE_KEY = 'bug-tv.apiBase.v1';
export const PROVIDER_KEY = 'bug-tv.providers.v1';
export const DEFAULT_TMDB_KEY = 'ac014b130a8e6344c91dff4e68b18d47';
export const TMDB_KEY_STORAGE_KEY = 'bug-tv.tmdbKey.v1';
// Search/details/images go straight to TMDB from the browser; this key
// only ever reaches api.themoviedb.org.
const DEFAULT_TMDB_KEY = 'ac014b130a8e6344c91dff4e68b18d47';
const TMDB_KEY_STORAGE_KEY = 'bug-tv.tmdbKey.v1';
function normalize(value) {
let v = String(value || '').trim();
if (!v) return '';
if (!/^https?:\/\//i.test(v)) v = `${/^(localhost|127\.|\[::1\])/.test(v) ? 'http' : 'https'}://${v}`;
return v.replace(/\/+$/, '');
}
function normalize(value) {
let v = String(value || '').trim();
if (!v) return '';
if (!/^https?:\/\//i.test(v)) v = `https://${v}`;
return v.replace(/\/+$/, '');
function metaBase() {
const el = typeof document !== 'undefined' && document.querySelector('meta[name="bug-tv-api"]');
const v = el && el.getAttribute('content');
// ignore unsubstituted placeholders like "@API_BASE@"
return v && !/^@.*@$/.test(v.trim()) ? normalize(v) : '';
}
export const DEFAULT_BASE = metaBase() || FALLBACK_BASE;
export function getBase() {
const fromQuery = getParam('api');
if (fromQuery) return normalize(fromQuery);
const stored = safe(() => localStorage.getItem(STORAGE_KEY), null);
if (stored) return normalize(stored);
return DEFAULT_BASE;
}
export function setBase(value) {
const v = normalize(value);
safe(() => (v ? localStorage.setItem(STORAGE_KEY, v) : localStorage.removeItem(STORAGE_KEY)));
return getBase();
}
export function clearBase() {
safe(() => localStorage.removeItem(STORAGE_KEY));
}
// Resolves API-relative URLs ("/v1/p/…") against the configured base; absolute URLs pass through.
export function resolveUrl(relOrAbs) {
const s = String(relOrAbs || '');
if (/^[a-z][a-z0-9+.-]*:/i.test(s)) return s;
return getBase() + (s.startsWith('/') ? s : `/${s}`);
}
export function getTmdbKey() {
const stored = safe(() => localStorage.getItem(TMDB_KEY_STORAGE_KEY), null);
return stored && stored.trim() ? stored.trim() : DEFAULT_TMDB_KEY;
}
export function setTmdbKey(value) {
const v = String(value || '').trim();
safe(() => (v ? localStorage.setItem(TMDB_KEY_STORAGE_KEY, v) : localStorage.removeItem(TMDB_KEY_STORAGE_KEY)));
return getTmdbKey();
}
export function clearTmdbKey() {
safe(() => localStorage.removeItem(TMDB_KEY_STORAGE_KEY));
}
// Raw {id: bool} map or null when the user never customized.
export function getProviderMap() {
const raw = safe(() => localStorage.getItem(PROVIDER_KEY), null);
if (!raw) return null;
const parsed = safe(() => JSON.parse(raw), null);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
}
// Enabled provider ids, or null → use the server's defaults.
export function getProviders() {
const map = getProviderMap();
return map ? Object.keys(map).filter((n) => map[n] !== false) : null;
}
// Accepts a list of enabled ids or an {id: bool} map; null/undefined clears the override.
export function setProviders(listOrMap) {
if (listOrMap == null) return clearProviders();
let map = listOrMap;
if (Array.isArray(listOrMap)) {
map = {};
for (const id of listOrMap) map[id] = true;
}
safe(() => localStorage.setItem(PROVIDER_KEY, JSON.stringify(map)));
}
function getBase() {
const fromQuery = SR.util.getParam('api');
if (fromQuery) return normalize(fromQuery);
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) return normalize(stored);
} catch (e) {
/* private mode etc. */
}
return DEFAULT_BASE;
}
function setBase(value) {
const v = normalize(value);
try {
localStorage.setItem(STORAGE_KEY, v);
} catch (e) {
/* ignore */
}
return v;
}
function clearBase() {
try {
localStorage.removeItem(STORAGE_KEY);
} catch (e) {
/* ignore */
}
}
function getTmdbKey() {
try {
const stored = localStorage.getItem(TMDB_KEY_STORAGE_KEY);
if (stored) return stored.trim();
} catch (e) {
/* private mode etc. */
}
return DEFAULT_TMDB_KEY;
}
function setTmdbKey(value) {
const v = String(value || '').trim();
try {
localStorage.setItem(TMDB_KEY_STORAGE_KEY, v);
} catch (e) {
/* ignore */
}
return v;
}
function clearTmdbKey() {
try {
localStorage.removeItem(TMDB_KEY_STORAGE_KEY);
} catch (e) {
/* ignore */
}
}
// null → user has not customized; caller should fall back to server defaults
function getProviders() {
try {
const raw = localStorage.getItem(PROVIDER_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
} catch (e) {
return null;
}
}
function setProviders(map) {
try {
localStorage.setItem(PROVIDER_KEY, JSON.stringify(map));
} catch (e) {
/* ignore */
}
}
function clearProviders() {
try {
localStorage.removeItem(PROVIDER_KEY);
} catch (e) {
/* ignore */
}
}
const PREFERRED_PROVIDERS = ['cineby', 'playimdb', 'vidrock'];
// Merge the server's provider lists with the user's toggles.
// Returns the enabled provider names, in the server's `all` order.
function enabledProviders(allNames, serverEnabled) {
const all = Array.isArray(allNames) ? allNames : [];
const overrides = getProviders();
if (overrides) {
return Object.keys(overrides).filter((n) => overrides[n] !== false);
}
const server = Array.isArray(serverEnabled) ? serverEnabled : [];
const wanted = new Set([...PREFERRED_PROVIDERS, ...server]);
return (all.length ? all : PREFERRED_PROVIDERS.slice()).filter((n) =>
wanted.has(n)
);
}
// Watch-page resolver. Re-reads localStorage on every call so provider
// changes made in Settings apply to the next lookup without a reload.
function resolveProviders(catalog) {
const all = Array.isArray(catalog && catalog.all) ? catalog.all : [];
const serverEnabled = Array.isArray(catalog && catalog.enabled) ? catalog.enabled : [];
const overrides = getProviders();
if (overrides) {
return {
names: Object.keys(overrides).filter((n) => overrides[n] !== false),
customized: true,
useServerDefaults: false,
};
}
const wanted = new Set([...PREFERRED_PROVIDERS, ...serverEnabled]);
const names = all.length
? all.filter((n) => wanted.has(n))
: PREFERRED_PROVIDERS.slice();
return {
names,
customized: false,
useServerDefaults: !names.length,
};
}
window.SR = window.SR || {};
SR.config = {
DEFAULT_BASE,
STORAGE_KEY,
PROVIDER_KEY,
DEFAULT_TMDB_KEY,
TMDB_KEY_STORAGE_KEY,
getBase,
setBase,
clearBase,
getTmdbKey,
setTmdbKey,
clearTmdbKey,
getProviders,
setProviders,
clearProviders,
enabledProviders,
resolveProviders,
};
})();
export function clearProviders() {
safe(() => localStorage.removeItem(PROVIDER_KEY));
}
-79
View File
@@ -1,79 +0,0 @@
/*
HOME — continue-watching row + trending rows.
*/
(function () {
'use strict';
SR.app.initChrome();
const heroSlot = document.getElementById('heroSlot');
const sections = document.getElementById('sections');
const cont = SR.cards.continueRow();
if (cont) sections.appendChild(cont);
function appendRow(data, title) {
if (!data || !data.count) return;
sections.appendChild(SR.cards.row(title, data.results.map(SR.cards.normalizeItem)));
}
function itemsFrom(data) {
return data && Array.isArray(data.results) ? data.results.map(SR.cards.normalizeItem) : [];
}
function loadHeroLogos(section, items) {
const slides = section.querySelectorAll('.hero__slide');
items.forEach((item, i) => {
const slide = slides[i];
if (!slide || !item || item.tmdbId == null) return;
const titleEl = slide.querySelector('.hero__title');
if (!titleEl) return;
const logo = document.createElement('img');
logo.className = 'hero__logo';
logo.alt = item.name;
logo.hidden = true;
titleEl.insertAdjacentElement('beforebegin', logo);
SR.api.details(item.type, item.tmdbId)
.then((details) => {
const images = (details && details.images) || {};
const logos = images.logos || [];
const url = (logos.find((l) => l && l.url && String(l.iso_639_1 || '').toLowerCase() === 'en') || {}).url;
if (!url) return;
logo.onerror = () => {
logo.hidden = true;
titleEl.hidden = false;
};
logo.src = SR.util.tmdbResize(url, 'w500');
logo.hidden = false;
titleEl.hidden = true;
})
.catch(() => {});
});
}
(async () => {
const [movieRes, tvRes] = await Promise.allSettled([
SR.api.trending('movie', 'day'),
SR.api.trending('tv', 'week'),
]);
if (movieRes.status === 'fulfilled') appendRow(movieRes.value, 'Trending movies today');
else SR.app.showError(movieRes.reason, 'could not load trending movies');
if (tvRes.status === 'fulfilled') appendRow(tvRes.value, 'Trending shows this week');
else SR.app.showError(tvRes.reason, 'could not load trending shows');
try {
const heroData = [...itemsFrom(tvRes.value), ...itemsFrom(movieRes.value)]
.filter((item) => item.backdrop && item.overview && item.name)
.slice(0, 6);
const hero = SR.cards.heroCarousel(heroData);
if (hero) {
heroSlot.appendChild(hero);
loadHeroLogos(hero, heroData);
}
} catch (e) {
SR.app.showError(e, 'could not load featured titles');
}
})();
})();
-182
View File
@@ -1,182 +0,0 @@
/*
PLAYER — plays a stream in a <video> element and supports switching
sources mid-watch without losing your place.
Pipeline per stream:
- hls.js for .m3u8 when available
- native HLS for Safari (canPlayType check)
- direct <video src> for mp4/webm
- everything else (DASH, mkv, magnet, …) → friendly error
Every media + subtitle URL is routed through the API proxy.
On source switch we carry over currentTime, playbackRate, volume, muted
and the playing state, clamped to the new duration.
*/
(function () {
'use strict';
function create(video, handlers = {}) {
const onStatus = handlers.onStatus || (() => {});
const onError = handlers.onError || (() => {});
const onReady = handlers.onReady || (() => {});
let hls = null;
let token = 0; // guards against overlapping loads
let networkRetry = false;
function teardown() {
token++;
if (hls) {
try {
hls.destroy();
} catch (e) {
/* already destroyed */
}
hls = null;
}
for (const track of video.querySelectorAll('track')) track.remove();
video.removeAttribute('src');
try {
video.load();
} catch (e) {
/* ignore */
}
}
function capture() {
const v = video;
return {
time: isFinite(v.currentTime) && v.currentTime > 0 ? v.currentTime : 0,
rate: v.playbackRate || 1,
volume: v.volume,
muted: v.muted,
playing: !v.paused && !v.ended,
};
}
function restore(st) {
const v = video;
v.playbackRate = st.rate;
v.volume = st.volume;
v.muted = st.muted;
const seek = () => {
const d = v.duration;
let t = st.time;
if (isFinite(d) && d > 0) t = Math.min(t, Math.max(0, d - 5));
if (t > 10) v.currentTime = t;
if (st.playing) v.play().catch(() => {});
};
if (isFinite(v.duration) && v.duration > 0) seek();
else v.addEventListener('loadedmetadata', seek, { once: true });
}
function attachSubtitles(stream) {
for (const sub of stream.subtitles || []) {
let resolved;
try {
resolved = new URL(sub.url, stream.url).toString();
} catch (e) {
continue;
}
const track = document.createElement('track');
track.kind = 'subtitles';
track.srclang = sub.language || 'en';
track.label = sub.name || sub.language || 'Subtitles';
track.src = SR.api.proxyUrl(resolved, stream.headers);
video.appendChild(track);
}
}
function load(stream, opts = {}) {
const st = capture();
const explicitResume = typeof opts.resumeAt === 'number' && opts.resumeAt > 10;
if (typeof opts.resumeAt === 'number') st.time = Math.max(0, opts.resumeAt);
const readyAt = () => (explicitResume ? st.time : 0);
teardown();
networkRetry = false;
const myToken = token;
const guarded = (fn) => () => {
if (myToken === token) fn();
};
const url = stream.url || '';
const isHls = stream.type === 'm3u8' || /\.m3u8($|\?)/i.test(url);
const isDash = stream.type === 'dash' || /\.mpd($|\?)/i.test(url);
const isDirect =
stream.type === 'mp4' ||
stream.type === 'webm' ||
/\.(mp4|m4v|webm)(\?|#|$)/i.test(url);
if (isDash) {
onError('DASH streams are not supported yet — pick another source.');
return;
}
if (!isHls && !isDirect) {
onError(`The browser can't play ${stream.type} files directly — pick an MP4 or HLS source.`);
return;
}
attachSubtitles(stream);
const proxied = SR.api.proxyUrl(url, stream.headers);
if (isHls && window.Hls && Hls.isSupported()) {
onStatus('Loading stream…');
const h = new Hls({ enableWorker: true });
hls = h;
h.loadSource(proxied);
h.attachMedia(video);
h.on(Hls.Events.MANIFEST_PARSED, guarded(() => {
restore(st);
onReady(readyAt());
}));
h.on(Hls.Events.ERROR, (evt, data) => {
if (myToken !== token || !data.fatal) return;
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
if (!networkRetry) {
networkRetry = true;
setTimeout(() => {
networkRetry = false;
if (myToken === token && hls === h) h.startLoad();
}, 2000);
}
} else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
h.recoverMediaError();
} else {
onError('Playback failed: ' + (data.details || 'unknown stream error'));
teardown();
}
});
return;
}
// native HLS (Safari) or direct file
onStatus('Loading stream…');
video.src = proxied;
video.addEventListener(
'loadedmetadata',
guarded(() => {
restore(st);
onReady(readyAt());
}),
{ once: true }
);
video.addEventListener(
'error',
guarded(() => {
onError('Could not load this stream — try another source.');
}),
{ once: true }
);
}
function destroy() {
teardown();
}
return { load, destroy };
}
window.SR = window.SR || {};
SR.player = { create };
})();
+305
View File
@@ -0,0 +1,305 @@
/*
router.js — single-page router with clean paths + hash fallback.
Modes (decided once at boot by the inline script in index.html, recomputed here if absent):
history /title/tv/1399 (host rewrites unknown paths to index.html or 404.html)
hash /#/title/tv/1399 (file://, /index.html, or a hash route present on load)
Views: every route lazily imports a module exporting
render(root: HTMLElement, params) → cleanup function | void | Promise<cleanup|void>
update?(params) → boolean (optional: handle a same-route change in place, e.g. ?q=)
params = { ...pathParams (strings), query: URLSearchParams, path, route: name, signal: AbortSignal }
The signal aborts when the user navigates away; cleanup is also called then.
Public API:
navigate(path, { replace }), href(path) → string for <a href>, back(fallbackPath),
current() → { path, name, params, query }, register(name, pattern, loader),
onChange(fn) → unsubscribe, start(outlet), mode, root
*/
import { h } from './util.js';
const boot = window.__BUGTV_ROUTER || (() => {
const meta = document.querySelector('meta[name="bug-tv-root"]');
let root = meta && meta.content && !/^@.*@$/.test(meta.content) ? meta.content : '/';
if (!root.endsWith('/')) root += '/';
const hash = location.protocol === 'file:' || /\.html?$/i.test(location.pathname) || /^#\//.test(location.hash);
return { mode: hash ? 'hash' : 'history', root };
})();
export const mode = boot.mode;
export const root = boot.root;
const routes = [];
const listeners = new Set();
let outlet = null;
let active = null; // { route, mod, cleanup, controller, token }
let token = 0;
function compile(pattern) {
const keys = [];
const src = pattern
.replace(/\/+$/, '')
.split('/')
.map((seg) => {
if (!seg) return '';
const m = seg.match(/^:(\w+)(\?)?$/);
if (!m) return `/${seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`;
keys.push(m[1]);
return m[2] ? '(?:/([^/]+))?' : '/([^/]+)';
})
.join('');
return { re: new RegExp(`^${src || ''}/?$`), keys };
}
export function register(name, pattern, loader, defaults = {}) {
const { re, keys } = compile(pattern);
routes.push({ name, pattern, re, keys, loader, defaults });
}
// Built-in routes. The watch view is owned by the player workstream.
register('home', '/', () => import('./views/home.js'));
register('movies', '/movies', () => import('./views/home.js'), { kind: 'movie' });
register('tv', '/tv', () => import('./views/home.js'), { kind: 'tv' });
register('title', '/title/:type/:id', () => import('./views/title.js'));
register('watch', '/watch/:type/:id/:season?/:episode?', () => import('./views/watch.js'));
register('search', '/search', () => import('./views/search.js'));
register('list', '/list', () => import('./views/list.js'));
register('browse', '/browse/:type', () => import('./views/browse.js'));
register('settings', '/settings', () => import('./views/settings.js'));
function match(path) {
for (const r of routes) {
const m = r.re.exec(path);
if (!m) continue;
const params = { ...r.defaults };
r.keys.forEach((k, i) => {
if (m[i + 1] !== undefined) params[k] = decodeURIComponent(m[i + 1]);
});
return { route: r, params };
}
return null;
}
// Current app location → { path, search }
function location_() {
if (mode === 'hash') {
const raw = location.hash.replace(/^#/, '') || '/';
const i = raw.indexOf('?');
return { path: i >= 0 ? raw.slice(0, i) || '/' : raw, search: i >= 0 ? raw.slice(i) : '' };
}
let p = location.pathname;
if (p.startsWith(root)) p = `/${p.slice(root.length)}`;
else if (`${p}/` === root) p = '/';
return { path: p || '/', search: location.search };
}
export function href(path) {
const p = String(path || '/');
if (mode === 'hash') return `#${p.startsWith('/') ? p : `/${p}`}`;
return root + p.replace(/^\/+/, '');
}
export function current() {
const { path, search } = location_();
const m = match(path);
return { path, name: m ? m.route.name : null, params: m ? m.params : {}, query: new URLSearchParams(search) };
}
export function onChange(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
}
function saveScroll() {
try {
history.replaceState({ ...(history.state || {}), scrollY: window.scrollY }, '');
} catch (e) {
/* ignore */
}
}
export function navigate(path, opts = {}) {
const target = String(path || '/');
const cur = location_();
if (!opts.replace && target === cur.path + cur.search) return;
if (!opts.replace) {
saveScroll();
depth++;
}
if (mode === 'hash') {
const url = `${location.href.split('#')[0]}#${target}`;
if (opts.replace) history.replaceState({}, '', url);
else history.pushState({}, '', url);
} else {
const url = href(target);
if (opts.replace) history.replaceState({}, '', url);
else history.pushState({}, '', url);
}
resolve({ scroll: opts.replace ? 'keep' : 'top' });
}
let depth = 0; // in-app history entries we pushed (best effort)
export function back(fallback = '/') {
if (depth > 0) history.back();
else navigate(fallback, { replace: true });
}
function errorView(title, detail) {
return h('section.page.page--center',
h('div.empty',
h('div.empty__icon', '!'),
h('h1.empty__title', title),
detail ? h('p.empty__text', detail) : null,
h('a.btn.btn--primary', { href: href('/') }, 'Back to home')));
}
async function resolve({ scroll = 'top' } = {}) {
if (!outlet) return;
const loc = location_();
// legacy v4 URLs (watch.html?id=&type=&s=&e=, search.html?q=)
const legacy = legacyRedirect(loc);
if (legacy) {
navigate(legacy, { replace: true });
return;
}
const m = match(loc.path);
const query = new URLSearchParams(loc.search);
const my = ++token;
// same route + view supports in-place update (e.g. search ?q= typing)
if (m && active && active.route === m.route && active.mod && typeof active.mod.update === 'function') {
const handled = active.mod.update({ ...m.params, query, path: loc.path, route: m.route.name, signal: active.controller.signal });
if (handled) {
emit(m, loc);
return;
}
}
if (active) {
try {
active.controller.abort();
if (typeof active.cleanup === 'function') active.cleanup();
} catch (e) {
console.error(e);
}
active = null;
}
document.body.dataset.route = m ? m.route.name : 'notfound';
emit(m, loc);
outlet.replaceChildren();
outlet.setAttribute('aria-busy', 'true');
if (scroll !== 'keep') window.scrollTo(0, 0);
if (!m) {
outlet.replaceChildren(errorView('Page not found', 'That page does not exist.'));
outlet.removeAttribute('aria-busy');
return;
}
const controller = new AbortController();
const entry = { route: m.route, mod: null, cleanup: null, controller };
active = entry;
let mod;
try {
mod = await m.route.loader();
} catch (e) {
if (my !== token) return;
console.error(e);
outlet.replaceChildren(
errorView(
m.route.name === 'watch' ? 'Player unavailable' : 'Could not load this page',
m.route.name === 'watch' ? 'The player module is not installed yet.' : String(e && e.message ? e.message : e),
),
);
outlet.removeAttribute('aria-busy');
return;
}
if (my !== token) return;
entry.mod = mod;
const params = { ...m.params, query, path: loc.path, route: m.route.name, signal: controller.signal };
try {
if (typeof mod.render !== 'function') throw new Error('view has no render()');
const result = await mod.render(outlet, params);
if (my !== token || controller.signal.aborted) {
if (typeof result === 'function') result();
return;
}
entry.cleanup = result;
} catch (e) {
if (my !== token) return;
console.error(e);
outlet.replaceChildren(errorView('Something went wrong', String(e && e.message ? e.message : e)));
}
outlet.removeAttribute('aria-busy');
if (scroll === 'restore' && history.state && history.state.scrollY) {
const y = history.state.scrollY;
requestAnimationFrame(() => window.scrollTo(0, y));
setTimeout(() => window.scrollTo(0, y), 400);
}
}
function emit(m, loc) {
const info = { path: loc.path, name: m ? m.route.name : null, params: m ? m.params : {}, query: new URLSearchParams(loc.search) };
for (const fn of listeners) {
try {
fn(info);
} catch (e) {
console.error(e);
}
}
}
function legacyRedirect(loc) {
const p = loc.path.replace(/\/+$/, '');
if (/\/watch\.html$/.test(p)) {
const q = new URLSearchParams(loc.search);
const id = q.get('id');
const type = q.get('type') === 'tv' ? 'tv' : 'movie';
if (!id) return '/';
return type === 'tv' ? `/watch/tv/${id}/${q.get('s') || 1}/${q.get('e') || 1}` : `/watch/movie/${id}`;
}
if (/\/search\.html$/.test(p)) return `/search${loc.search}`;
if (/\/settings\.html$/.test(p)) return '/settings';
if (/\/(index|404)\.html$/.test(p) && mode === 'history') return `/${loc.search}`;
return null;
}
function onClick(e) {
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const a = e.target.closest && e.target.closest('a[href]');
if (!a || a.target === '_blank' || a.hasAttribute('download') || a.dataset.native != null) return;
const raw = a.getAttribute('href');
if (mode === 'hash') return; // "#/…" links navigate natively via hashchange
let url;
try {
url = new URL(a.href, location.href);
} catch (err) {
return;
}
if (url.origin !== location.origin || !url.pathname.startsWith(root) || raw.startsWith('#')) return;
if (/\.[a-z0-9]{2,5}$/i.test(url.pathname) && !/\/(index|404)\.html$/.test(url.pathname)) return;
e.preventDefault();
navigate(`/${url.pathname.slice(root.length)}${url.search}`);
}
export function start(el) {
outlet = el;
if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
document.addEventListener('click', onClick);
if (mode === 'hash') {
// covers <a href="#/…"> clicks and back/forward (pushState itself fires nothing)
window.addEventListener('hashchange', () => {
if (history.state && history.state.scrollY != null) depth = Math.max(0, depth - 1);
else depth++;
resolve({ scroll: 'restore' });
});
} else {
window.addEventListener('popstate', () => {
depth = Math.max(0, depth - 1);
resolve({ scroll: 'restore' });
});
}
resolve({ scroll: 'keep' });
}
-88
View File
@@ -1,88 +0,0 @@
/*
SEARCH — debounced live search with client-side type filter.
URL ?q= is kept in sync so results are shareable/bookmarkable.
*/
(function () {
'use strict';
SR.app.initChrome();
const input = document.getElementById('searchInput');
const chipsEl = document.getElementById('typeChips');
const resultsEl = document.getElementById('results');
const countEl = document.getElementById('searchCount');
const state = { type: 'all', results: [] };
function render() {
resultsEl.replaceChildren();
const filtered = state.type === 'all' ? state.results : state.results.filter((i) => i.type === state.type);
if (!state.results.length) {
countEl.textContent = '';
resultsEl.appendChild(
SR.cards.emptyState('Nothing found', 'Check the spelling or try a different name.')
);
return;
}
countEl.textContent = `${filtered.length} of ${state.results.length} result${state.results.length === 1 ? '' : 's'}`;
if (!filtered.length) {
resultsEl.appendChild(SR.cards.emptyState('No matches for this filter', 'Try the All filter, or a different search.'));
return;
}
resultsEl.appendChild(SR.cards.grid(filtered));
}
async function runSearch(q) {
q = (q || '').trim();
if (!q) {
state.results = [];
countEl.textContent = '';
resultsEl.replaceChildren(SR.cards.emptyState('Search the catalog', 'Type a movie or show name above.'));
return;
}
countEl.textContent = 'Searching…';
try {
const data = await SR.api.search(q);
state.results = data.results.map(SR.cards.normalizeItem);
render();
} catch (e) {
SR.app.showError(e, 'search failed');
countEl.textContent = '';
}
}
const LABELS = { all: 'All', movie: 'Movies', tv: 'TV' };
for (const t of ['all', 'movie', 'tv']) {
const b = document.createElement('button');
b.type = 'button';
b.className = t === 'all' ? 'chip chip--active' : 'chip';
b.textContent = LABELS[t];
b.addEventListener('click', () => {
state.type = t;
for (const c of chipsEl.querySelectorAll('.chip')) c.classList.remove('chip--active');
b.classList.add('chip--active');
render();
});
chipsEl.appendChild(b);
}
input.addEventListener(
'input',
SR.util.debounce(() => {
const q = input.value.trim();
history.replaceState(null, '', q ? `?q=${encodeURIComponent(q)}` : 'search.html');
runSearch(q);
}, 450)
);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
runSearch(input.value.trim());
}
});
const initialQ = SR.util.getParam('q') || '';
input.value = initialQ;
if (initialQ) runSearch(initialQ);
else input.focus();
})();
-187
View File
@@ -1,187 +0,0 @@
/*
SETTINGS — source provider toggles, API server base URL, TMDB key, local data.
*/
(function () {
'use strict';
SR.app.initChrome();
const providerList = document.getElementById('providerList');
const providersStatus = document.getElementById('providersStatus');
const apiBaseInput = document.getElementById('apiBaseInput');
const connStatus = document.getElementById('connStatus');
const tmdbKeyInput = document.getElementById('tmdbKeyInput');
const tmdbStatus = document.getElementById('tmdbStatus');
const dataStatus = document.getElementById('dataStatus');
/* ---- nav --------------------------------------------------------------------- */
const navlinks = Array.from(document.querySelectorAll('.settings__navlink'));
navlinks.forEach((link) => {
link.addEventListener('click', (e) => {
e.preventDefault();
const target = document.querySelector(link.getAttribute('href'));
if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
navlinks.forEach((l) => l.classList.toggle('is-active', l === link));
history.replaceState(null, '', link.getAttribute('href'));
});
});
/* ---- sources ------------------------------------------------------------------- */
let allProviders = [];
let serverEnabled = [];
const boxes = new Map(); // provider name -> checkbox
function setStatus(el, message, kind) {
el.textContent = message || '';
el.className =
kind === 'ok' ? 'settings__status settings__status--ok'
: kind === 'err' ? 'settings__status settings__status--err'
: 'settings__status';
}
function currentMap() {
const map = {};
for (const [name, box] of boxes) map[name] = box.checked;
return map;
}
function persist(map, message) {
SR.config.setProviders(map);
if (message) setStatus(providersStatus, message);
}
function renderProviders() {
providerList.replaceChildren();
boxes.clear();
const overrides = SR.config.getProviders();
const enabled = SR.config.enabledProviders(allProviders, serverEnabled);
for (const name of allProviders) {
const checked = enabled.includes(name);
const label = document.createElement('label');
label.className = 'provider';
const input = document.createElement('input');
input.type = 'checkbox';
input.checked = !!checked;
const nameEl = document.createElement('span');
nameEl.className = 'provider__name';
nameEl.textContent = name;
label.append(input, nameEl);
input.addEventListener('change', () =>
persist(currentMap(), input.checked ? `${name} enabled` : `${name} disabled`));
boxes.set(name, input);
providerList.appendChild(label);
}
const on = boxes.size ? Array.from(boxes.values()).filter((b) => b.checked).length : 0;
const source = overrides ? 'your selection' : 'default sources';
let host;
try { host = new URL(SR.config.getBase()).host; } catch (e) { host = SR.config.getBase(); }
setStatus(providersStatus, `${on} of ${allProviders.length} enabled — ${source} · ${host}`);
}
function resetProviders(message) {
SR.config.clearProviders();
renderProviders();
if (message) setStatus(providersStatus, message);
}
document.getElementById('allOn').addEventListener('click', () => {
if (!boxes.size) return;
for (const box of boxes.values()) box.checked = true;
persist(currentMap(), 'All sources enabled');
});
document.getElementById('allOff').addEventListener('click', () => {
if (!boxes.size) return;
for (const box of boxes.values()) box.checked = false;
persist(currentMap(), 'All sources disabled');
});
document.getElementById('providersReset').addEventListener('click', () =>
resetProviders('Using default sources'));
async function initSources() {
try {
const data = await SR.api.providers();
allProviders = data.all || [];
serverEnabled = data.enabled || [];
renderProviders();
} catch (e) {
setStatus(providersStatus, `Could not load the provider list: ${e.message}`, 'err');
}
}
/* ---- server ----------------------------------------------------------------------- */
apiBaseInput.value = SR.config.getBase();
async function testConnection() {
try {
const data = await SR.api.providers();
setStatus(connStatus, `Connected — ${data.all ? data.all.length : 0} provider(s) known.`, 'ok');
return true;
} catch (e) {
setStatus(connStatus, `Not reachable: ${e.message}`, 'err');
return false;
}
}
document.getElementById('apiBaseSave').addEventListener('click', async () => {
SR.config.setBase(apiBaseInput.value);
apiBaseInput.value = SR.config.getBase();
SR.app.initChrome(); // refresh the footer label
if (await testConnection()) SR.app.toast('API base URL saved');
});
document.getElementById('apiBaseReset').addEventListener('click', async () => {
SR.config.clearBase();
apiBaseInput.value = SR.config.getBase();
SR.app.initChrome();
await testConnection();
});
/* ---- TMDB key ------------------------------------------------------------------- */
tmdbKeyInput.value = SR.config.getTmdbKey();
async function testTmdbKey(key) {
setStatus(tmdbStatus, 'Testing TMDB key…');
try {
await SR.api.tmdb('/search/movie', { query: 'The Matrix', page: 1 }, key);
setStatus(tmdbStatus, 'TMDB key works — search, details and images load directly from TMDB.', 'ok');
} catch (e) {
setStatus(tmdbStatus, e.message, 'err');
}
}
document.getElementById('tmdbKeySave').addEventListener('click', async () => {
SR.config.setTmdbKey(tmdbKeyInput.value);
tmdbKeyInput.value = SR.config.getTmdbKey();
await testTmdbKey(SR.config.getTmdbKey());
});
document.getElementById('tmdbKeyTest').addEventListener('click', async () => {
await testTmdbKey(tmdbKeyInput.value.trim());
});
document.getElementById('tmdbKeyReset').addEventListener('click', async () => {
SR.config.clearTmdbKey();
tmdbKeyInput.value = SR.config.getTmdbKey();
await testTmdbKey(SR.config.getTmdbKey());
});
/* ---- data ---------------------------------------------------------------------------- */
document.getElementById('clearHistory').addEventListener('click', () => {
SR.storage.clear();
setStatus(dataStatus, 'Continue-watching history cleared.');
});
document.getElementById('resetProviders').addEventListener('click', () => {
resetProviders('');
setStatus(dataStatus, 'Source toggles reset to default sources.');
});
initSources();
})();
+150 -71
View File
@@ -1,91 +1,170 @@
/*
STORAGE — resume points, kept in localStorage (survives restarts, no size
worries like cookies, no per-request overhead).
storage.js — resume points, My List and preferences in localStorage.
A "record" looks like:
{
key: "m:603" | "t:1396:s1:e2",
type: "movie" | "tv",
tmdbId: 1396,
season: 1, // tv only
episode: 2, // tv only
show: "Show name",
title: "Episode name", // tv only
poster: "https://…/w342/…",
t: 934.2, // seconds played
d: 2710.5, // duration seconds
at: 1712345678901,
provider: "cineby"
}
Resume record (key bug-tv.resume.v1, unchanged from v4):
{ key: "m:603" | "t:1396:s1:e2", type: "movie"|"tv", tmdbId, season?, episode?,
show: "Show name", title?: "Episode name", poster: "https://…/w342/…",
backdrop?: "https://…/w780/…", still?: "https://…/w300/…",
t: seconds played, d: duration seconds, at: epoch ms, provider? }
One record per (movie) or (show, season, episode). The home page collapses
to the most recent record per show.
My List item (key bug-tv.mylist.v1):
{ type, id, title, poster_path, backdrop_path, year, rating, addedAt }
Prefs (key bug-tv.prefs.v1): free-form { name: value }. Names used by the UI:
subtitleLang ("" = off, "en", …), autoplayNext (bool, default true), volume (0..1), muted.
Every mutation dispatches a window event so views can refresh:
"bugtv:resume", "bugtv:mylist", "bugtv:prefs" (detail = { key? / item? / name? })
*/
(function () {
'use strict';
import { safe } from './util.js';
const KEY = 'bug-tv.resume.v1';
const MAX_RECORDS = 200;
const RESUME_KEY = 'bug-tv.resume.v1';
const LIST_KEY = 'bug-tv.mylist.v1';
const PREFS_KEY = 'bug-tv.prefs.v1';
const MAX_RECORDS = 200;
function readAll() {
try {
const parsed = JSON.parse(localStorage.getItem(KEY) || '{}');
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
} catch (e) {
return {};
}
}
function readObj(key) {
const parsed = safe(() => JSON.parse(localStorage.getItem(key) || '{}'), {});
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
}
function writeAll(all) {
try {
localStorage.setItem(KEY, JSON.stringify(all));
} catch (e) {
/* storage full/blocked — resume just won't persist */
}
}
function writeObj(key, obj) {
safe(() => localStorage.setItem(key, JSON.stringify(obj)));
}
function keyFor({ type, tmdbId, season, episode }) {
return type === 'tv' ? `t:${tmdbId}:s${season}:e${episode}` : `m:${tmdbId}`;
}
function emit(name, detail) {
safe(() => window.dispatchEvent(new CustomEvent(name, { detail })));
}
function get(key) {
return readAll()[key] || null;
}
export function keyFor({ type, tmdbId, season, episode }) {
return type === 'tv' ? `t:${tmdbId}:s${season}:e${episode}` : `m:${tmdbId}`;
}
function save(record) {
const all = readAll();
all[record.key] = record;
export const resume = {
KEY: RESUME_KEY,
keyFor,
get(key) {
return readObj(RESUME_KEY)[key] || null;
},
save(record) {
if (!record || !record.key) return;
const all = readObj(RESUME_KEY);
all[record.key] = { ...record, at: record.at || Date.now() };
const keys = Object.keys(all).sort((a, b) => (all[a].at || 0) - (all[b].at || 0));
while (keys.length > MAX_RECORDS) delete all[keys.shift()];
writeAll(all);
}
function remove(key) {
const all = readAll();
writeObj(RESUME_KEY, all);
emit('bugtv:resume', { key: record.key });
},
remove(key) {
const all = readObj(RESUME_KEY);
if (all[key]) {
delete all[key];
writeAll(all);
writeObj(RESUME_KEY, all);
emit('bugtv:resume', { key });
}
}
function clear() {
writeAll({});
}
function list() {
return Object.values(readAll());
}
},
// remove every record of a movie/show
removeShow(type, tmdbId) {
const all = readObj(RESUME_KEY);
let changed = false;
for (const [k, r] of Object.entries(all)) {
if (r && r.type === type && String(r.tmdbId) === String(tmdbId)) {
delete all[k];
changed = true;
}
}
if (changed) {
writeObj(RESUME_KEY, all);
emit('bugtv:resume', {});
}
},
clear() {
writeObj(RESUME_KEY, {});
emit('bugtv:resume', {});
},
list() {
return Object.values(readObj(RESUME_KEY)).filter((r) => r && r.key);
},
// records of one movie/show, newest first
forShow(type, tmdbId) {
return resume
.list()
.filter((r) => r.type === type && String(r.tmdbId) === String(tmdbId))
.sort((a, b) => (b.at || 0) - (a.at || 0));
},
// one entry per movie/show: the most recently watched record wins
function latestPerShow() {
latestPerShow() {
const byShow = new Map();
for (const rec of list().sort((a, b) => (a.at || 0) - (b.at || 0))) {
const showKey = rec.type === 'tv' ? `t:${rec.tmdbId}` : `m:${rec.tmdbId}`;
byShow.set(showKey, rec);
for (const rec of resume.list().sort((a, b) => (a.at || 0) - (b.at || 0))) {
byShow.set(`${rec.type === 'tv' ? 't' : 'm'}:${rec.tmdbId}`, rec);
}
return [...byShow.values()].sort((a, b) => (b.at || 0) - (a.at || 0));
}
},
};
window.SR = window.SR || {};
SR.storage = { KEY, keyFor, get, save, remove, clear, list, latestPerShow };
})();
// fraction watched 0..1 for a record (0 when unknown)
export function progressOf(rec) {
return rec && rec.d > 0 ? Math.min(1, Math.max(0, rec.t / rec.d)) : 0;
}
export const myList = {
KEY: LIST_KEY,
_all() {
return readObj(LIST_KEY);
},
has(type, id) {
return !!myList._all()[`${type}:${id}`];
},
// item: { type, id, title, poster_path?, backdrop_path?, year?, rating? } → returns new state
toggle(item) {
const all = myList._all();
const k = `${item.type}:${item.id}`;
let state;
if (all[k]) {
delete all[k];
state = false;
} else {
all[k] = {
type: item.type,
id: item.id,
title: item.title || item.name || '',
poster_path: item.poster_path || null,
backdrop_path: item.backdrop_path || null,
year: item.year || '',
rating: item.rating || item.vote_average || 0,
addedAt: Date.now(),
};
state = true;
}
writeObj(LIST_KEY, all);
emit('bugtv:mylist', { type: item.type, id: item.id, state });
return state;
},
remove(type, id) {
const all = myList._all();
if (all[`${type}:${id}`]) {
delete all[`${type}:${id}`];
writeObj(LIST_KEY, all);
emit('bugtv:mylist', { type, id, state: false });
}
},
// newest first
all() {
return Object.values(myList._all()).sort((a, b) => (b.addedAt || 0) - (a.addedAt || 0));
},
};
export const prefs = {
KEY: PREFS_KEY,
get(name, fallback) {
const all = readObj(PREFS_KEY);
return Object.prototype.hasOwnProperty.call(all, name) ? all[name] : fallback;
},
set(name, value) {
const all = readObj(PREFS_KEY);
if (value === undefined) delete all[name];
else all[name] = value;
writeObj(PREFS_KEY, all);
emit('bugtv:prefs', { name, value });
},
};
+234
View File
@@ -0,0 +1,234 @@
/*
tmdb.js — direct browser → TMDB client (CORS-enabled API), cached.
- In-memory promise cache for every request (dedupes concurrent callers).
- sessionStorage cache (30 min) for list endpoints (trending/popular/discover/search/seasons…),
so navigating back and forth is instant. Details stay memory-only (large payloads).
All functions resolve to raw TMDB JSON. List results get `media_type` filled in when the
endpoint is type-specific, so cards always know whether an item is a movie or tv show.
*/
import { getTmdbKey } from './config.js';
import { safe } from './util.js';
const API = 'https://api.themoviedb.org/3';
export const IMG_BASE = 'https://image.tmdb.org/t/p/';
const SESSION_PREFIX = 'bug-tv.tmdb.';
const SESSION_TTL = 30 * 60 * 1000;
const mem = new Map();
function buildUrl(path, params) {
const url = new URL(API + path);
url.searchParams.set('api_key', getTmdbKey());
if (!params || params.language === undefined) url.searchParams.set('language', 'en-US');
for (const [k, v] of Object.entries(params || {})) {
if (v === undefined || v === null || v === '') continue;
url.searchParams.set(k, String(v));
}
return url;
}
function cacheKey(path, params) {
const p = new URLSearchParams();
for (const k of Object.keys(params || {}).sort()) {
const v = params[k];
if (v !== undefined && v !== null && v !== '') p.set(k, String(v));
}
return `${path}?${p}`;
}
async function fetchJson(path, params, key) {
const url = buildUrl(path, params);
if (key) url.searchParams.set('api_key', key);
let res;
try {
res = await fetch(url.toString());
} catch (e) {
throw new Error('Cannot reach TMDB — check your connection');
}
let data = null;
try {
data = await res.json();
} catch (e) {
/* non-JSON */
}
if (!res.ok) {
const msg = (data && data.status_message) || `TMDB error: HTTP ${res.status}`;
const err = new Error(res.status === 401 ? `TMDB key rejected: ${msg}` : msg);
err.status = res.status;
throw err;
}
return data;
}
// get(path, params, { session: bool })
export function get(path, params = {}, opts = {}) {
const ck = cacheKey(path, params);
if (mem.has(ck)) return mem.get(ck);
if (opts.session) {
const hit = safe(() => JSON.parse(sessionStorage.getItem(SESSION_PREFIX + ck)), null);
if (hit && hit.at && Date.now() - hit.at < SESSION_TTL && hit.data) {
const p = Promise.resolve(hit.data);
mem.set(ck, p);
return p;
}
}
const p = fetchJson(path, params).then((data) => {
if (opts.session) {
safe(() => sessionStorage.setItem(SESSION_PREFIX + ck, JSON.stringify({ at: Date.now(), data })));
}
return data;
});
mem.set(ck, p);
p.catch(() => mem.delete(ck));
return p;
}
// Validate a key without touching the cache (Settings "Test").
export function testKey(key) {
return fetchJson('/configuration', {}, key);
}
function tag(type) {
return (data) => {
if (data && Array.isArray(data.results) && type && type !== 'all') {
data.results.forEach((r) => {
if (r && !r.media_type) r.media_type = type;
});
}
return data;
};
}
const t = (type) => (type === 'tv' ? 'tv' : 'movie');
export function trending(type = 'all', window = 'day', page = 1) {
const ty = type === 'all' ? 'all' : t(type);
return get(`/trending/${ty}/${window === 'week' ? 'week' : 'day'}`, { page }, { session: true }).then(tag(ty));
}
export function popular(type, page = 1) {
return get(`/${t(type)}/popular`, { page }, { session: true }).then(tag(t(type)));
}
export function topRated(type, page = 1) {
return get(`/${t(type)}/top_rated`, { page }, { session: true }).then(tag(t(type)));
}
export function discover(type, params = {}) {
return get(`/discover/${t(type)}`, { sort_by: 'popularity.desc', ...params }, { session: true }).then(tag(t(type)));
}
export function details(type, id) {
const ty = t(type);
const extra = ty === 'tv' ? 'content_ratings' : 'release_dates';
return get(`/${ty}/${id}`, {
append_to_response: `images,credits,similar,recommendations,external_ids,videos,${extra}`,
include_image_language: 'en,null',
}).then((d) => {
if (d) {
d.media_type = ty;
if (d.similar) tag(ty)(d.similar);
if (d.recommendations) tag(ty)(d.recommendations);
}
return d;
});
}
export function season(tvId, n) {
return get(`/tv/${tvId}/season/${n}`, {}, { session: true });
}
export function search(q, page = 1) {
const query = String(q || '').trim();
if (!query) return Promise.resolve({ results: [], total_results: 0, page: 1, total_pages: 0 });
return get('/search/multi', { query, page, include_adult: 'false' }, { session: true }).then((d) => {
d.results = (d.results || []).filter((r) => r.media_type === 'movie' || r.media_type === 'tv');
return d;
});
}
export function genres(type) {
return get(`/genre/${t(type)}/list`, {}, { session: true }).then((d) => {
const map = {};
for (const g of (d && d.genres) || []) map[g.id] = g.name;
return map;
});
}
export function network(id) {
return get(`/network/${id}`, {}, { session: true });
}
export function company(id) {
return get(`/company/${id}`, {}, { session: true });
}
// Image URL helper: img('/abc.jpg', 'w342'); returns '' for missing paths.
export function img(path, size = 'original') {
if (!path) return '';
if (/^https?:/i.test(path)) return path;
return `${IMG_BASE}${size}${path}`;
}
// srcset for responsive images: srcset('/abc.jpg', ['w300','w780','w1280'])
export function srcset(path, sizes) {
if (!path) return '';
return sizes
.map((s) => `${img(path, s)} ${s.replace(/^w/, '')}w`)
.filter((s) => !/original/.test(s))
.join(', ');
}
/* ---- details helpers ---------------------------------------------------------------- */
// Best logo: English png first, then English, then language-neutral; null if none.
export function logoFor(d) {
const logos = (d && d.images && d.images.logos) || [];
if (!logos.length) return null;
const score = (l) =>
(l.iso_639_1 === 'en' ? 4 : l.iso_639_1 == null ? 1 : 0) +
(/\.png$/i.test(l.file_path) ? 2 : 0) +
(l.vote_average || 0) / 20;
const best = [...logos].sort((a, b) => score(b) - score(a))[0];
return best && (best.iso_639_1 === 'en' || best.iso_639_1 == null) ? best : null;
}
export function trailerFor(d) {
const vids = ((d && d.videos && d.videos.results) || []).filter((v) => v.site === 'YouTube');
const score = (v) =>
(v.type === 'Trailer' ? 4 : v.type === 'Teaser' ? 2 : 0) + (v.official ? 1 : 0) + (v.iso_639_1 === 'en' ? 1 : 0);
return vids.sort((a, b) => score(b) - score(a))[0] || null;
}
export function certificationFor(d) {
if (!d) return '';
if (d.content_ratings) {
const us = (d.content_ratings.results || []).find((r) => r.iso_3166_1 === 'US');
return (us && us.rating) || '';
}
if (d.release_dates) {
const us = (d.release_dates.results || []).find((r) => r.iso_3166_1 === 'US');
const c = us && (us.release_dates || []).map((r) => r.certification).find(Boolean);
return c || '';
}
return '';
}
// normalize any TMDB list result / details / my-list item into a card model
export function toItem(r, typeHint) {
if (!r) return null;
const type = r.media_type === 'tv' || r.media_type === 'movie' ? r.media_type : r.type || typeHint || (r.first_air_date !== undefined ? 'tv' : 'movie');
return {
type: type === 'tv' ? 'tv' : 'movie',
id: r.id,
title: r.title || r.name || r.original_title || r.original_name || '',
year: r.year || String(r.release_date || r.first_air_date || '').slice(0, 4),
rating: Number(r.vote_average || r.rating || 0),
poster_path: r.poster_path || null,
backdrop_path: r.backdrop_path || null,
overview: r.overview || '',
genre_ids: r.genre_ids || (r.genres ? r.genres.map((g) => g.id) : []),
};
}
+104
View File
@@ -0,0 +1,104 @@
/*
actions.js — shared title actions: links, play/resume targets, My List toggle, share.
*/
import { h } from '../util.js';
import { href } from '../router.js';
import { resume, myList, progressOf } from '../storage.js';
import { icon } from './icons.js';
import { toast } from './toast.js';
export function titlePath(type, id) {
return `/title/${type === 'tv' ? 'tv' : 'movie'}/${id}`;
}
export function watchPath(type, id, season, episode) {
if (type === 'tv') return `/watch/tv/${id}/${season || 1}/${episode || 1}`;
return `/watch/movie/${id}`;
}
export const titleHref = (type, id) => href(titlePath(type, id));
export const watchHref = (type, id, s, e) => href(watchPath(type, id, s, e));
/*
Where "Play" should go for a title, using resume data.
details (optional, tv) lets us advance past a finished episode and pick the first real season.
→ { path, label, record, progress }
*/
export function playTarget(type, id, details) {
const recs = resume.forShow(type === 'tv' ? 'tv' : 'movie', id);
const rec = recs[0] || null;
if (type !== 'tv') {
const p = progressOf(rec);
if (rec && p > 0.01 && p < 0.95) return { path: watchPath('movie', id), label: 'Resume', record: rec, progress: p };
return { path: watchPath('movie', id), label: 'Play', record: null, progress: 0 };
}
if (rec) {
let s = Number(rec.season) || 1;
let e = Number(rec.episode) || 1;
const p = progressOf(rec);
if (p >= 0.95 && details) {
const seasons = (details.seasons || []).filter((x) => x.season_number > 0);
const cur = seasons.find((x) => x.season_number === s);
if (cur && e < cur.episode_count) e += 1;
else if (seasons.some((x) => x.season_number === s + 1)) {
s += 1;
e = 1;
}
return { path: watchPath('tv', id, s, e), label: `Play S${s} E${e}`, record: rec, progress: 0 };
}
return { path: watchPath('tv', id, s, e), label: `Continue S${s} E${e}`, record: rec, progress: p };
}
let first = 1;
if (details && Array.isArray(details.seasons)) {
const real = details.seasons.filter((x) => x.season_number > 0 && x.episode_count > 0);
if (real.length) first = real[0].season_number;
}
return { path: watchPath('tv', id, first, 1), label: 'Play', record: null, progress: 0 };
}
// "+ My List" toggle button; item = { type, id, title, poster_path, backdrop_path, year, rating }
export function myListButton(item, opts = {}) {
const btn = h('button', { type: 'button', class: opts.className || 'btn btn--glass' });
function paint() {
const on = myList.has(item.type, item.id);
btn.classList.toggle('is-on', on);
btn.setAttribute('aria-pressed', on ? 'true' : 'false');
btn.setAttribute('aria-label', on ? 'Remove from My List' : 'Add to My List');
btn.title = on ? 'Remove from My List' : 'Add to My List';
btn.replaceChildren(...[icon(on ? 'check' : 'plus'), opts.iconOnly ? null : h('span', on ? 'In My List' : 'My List')].filter(Boolean));
}
btn.dataset.mylist = `${item.type}:${item.id}`;
btn._paint = paint;
btn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
const on = myList.toggle(item);
toast(on ? `Added “${item.title}” to My List` : `Removed “${item.title}” from My List`);
});
paint();
return btn;
}
// one global listener repaints every toggle for the changed title
window.addEventListener('bugtv:mylist', (e) => {
const d = e.detail || {};
document.querySelectorAll(`[data-mylist="${d.type}:${d.id}"]`).forEach((b) => b._paint && b._paint());
});
export async function shareTitle(title, path) {
const url = new URL(href(path), location.href).toString();
try {
if (navigator.share) {
await navigator.share({ title, url });
return;
}
} catch (e) {
if (e && e.name === 'AbortError') return;
}
try {
await navigator.clipboard.writeText(url);
toast('Link copied to clipboard');
} catch (e) {
toast(url);
}
}
+132
View File
@@ -0,0 +1,132 @@
/*
card.js — media cards.
posterCard(item) 2:3 poster, hover lift + quick info
wideCard(item, { progress, kicker, meta, href, onRemove, image }) 16:9 backdrop, title overlay
logoCard({ name, logo, href }) network/studio tile
skeletonCard(variant)
grid(items, render?) responsive poster grid
`item` is the shape from tmdb.toItem(): { type, id, title, year, rating, poster_path, backdrop_path, overview }.
Every card root carries class "card" and its focus target is the <a class="card__link">.
*/
import { h } from '../util.js';
import { img, srcset } from '../tmdb.js';
import { titleHref, playTarget } from './actions.js';
import { navigate } from '../router.js';
import { icon } from './icons.js';
function typeLabel(type) {
return type === 'tv' ? 'Series' : 'Movie';
}
function ratingNode(r) {
if (!r || r <= 0) return null;
return h('span.rating', icon('star', { size: 12 }), Number(r).toFixed(1));
}
function image(path, sizes, alt, sizesAttr, cls = 'card__img') {
if (!path) return null;
const el = h('img', {
class: cls,
src: img(path, sizes[1] || sizes[0]),
srcset: srcset(path, sizes),
sizes: sizesAttr,
alt: alt || '',
loading: 'lazy',
decoding: 'async',
});
el.addEventListener('load', () => el.classList.add('is-loaded'), { once: true });
el.addEventListener('error', () => el.remove(), { once: true });
return el;
}
// the hover play button skips the title page and starts playback (resuming if there's progress)
function playButton(item, size, extraClass = '') {
return h(`span.card__play${extraClass}`, {
role: 'button',
'aria-label': `Play ${item.title}`,
title: 'Play',
onclick: (e) => {
e.preventDefault();
e.stopPropagation();
navigate(playTarget(item.type, item.id).path);
},
}, icon('play', { size }));
}
export function posterCard(item, opts = {}) {
const meta = [item.year, typeLabel(item.type)].filter(Boolean).join(' · ');
return h('div.card.card--poster', { role: 'listitem' },
h('a.card__link', { href: opts.href || titleHref(item.type, item.id), 'aria-label': `${item.title}${item.year ? ` (${item.year})` : ''}` },
h('div.card__media',
h('div.card__fallback', h('span', item.title)),
image(item.poster_path, ['w185', 'w342', 'w500'], '', '(max-width: 720px) 34vw, 200px'),
opts.rank ? h('span.card__rank', String(opts.rank)) : null,
h('div.card__hover',
playButton(item, 18),
h('div.card__hover-meta', ratingNode(item.rating), item.year ? h('span', item.year) : null),
),
opts.progress > 0 ? h('div.progress.card__progress', h('i', { style: { width: `${Math.round(opts.progress * 100)}%` } })) : null,
),
h('div.card__body',
h('div.card__title', item.title),
h('div.card__meta', opts.meta || meta),
),
),
);
}
export function wideCard(item, opts = {}) {
const path = opts.image !== undefined ? opts.image : item.backdrop_path;
const imgEl = typeof path === 'string' && /^https?:/.test(path)
? h('img.card__img', { src: path, alt: '', loading: 'lazy', decoding: 'async', onload: (e) => e.target.classList.add('is-loaded'), onerror: (e) => e.target.remove() })
: image(path, ['w300', 'w780'], '', '(max-width: 720px) 75vw, 340px');
const card = h('div.card.card--wide', { role: 'listitem' },
h('a.card__link', { href: opts.href || titleHref(item.type, item.id), 'aria-label': [item.title, opts.kicker, opts.meta].filter(Boolean).join(' — ') },
h('div.card__media',
h('div.card__fallback', h('span', item.title)),
imgEl,
h('div.card__shade'),
h('div.card__overlay',
opts.kicker ? h('div.card__kicker', opts.kicker) : null,
h('div.card__title', item.title),
opts.meta ? h('div.card__meta', opts.meta) : h('div.card__meta', ratingNode(item.rating), [item.year, typeLabel(item.type)].filter(Boolean).join(' · ')),
opts.progress != null ? h('div.progress', h('i', { style: { width: `${Math.round(Math.min(1, opts.progress) * 100)}%` } })) : null,
),
playButton(item, 22, '.card__play--center'),
),
),
);
if (opts.onRemove) {
card.appendChild(h('button.card__remove', {
type: 'button',
'aria-label': `Remove ${item.title} from Continue Watching`,
title: 'Remove',
onclick: (e) => {
e.preventDefault();
opts.onRemove(card);
},
}, icon('close', { size: 16 })));
}
return card;
}
export function logoCard({ name, logo, href }) {
return h('div.card.card--logo', { role: 'listitem' },
h('a.card__link', { href, 'aria-label': name },
h('div.card__media',
logo ? h('img.card__logo', { src: img(logo, 'w300'), alt: name, loading: 'lazy', decoding: 'async', onerror: (e) => { e.target.replaceWith(h('span.card__logo-text', name)); } }) : h('span.card__logo-text', name),
),
),
);
}
export function skeletonCard(variant = 'poster') {
return h('div.card.card--skeleton', { class: `card--${variant}`, 'aria-hidden': 'true' },
h('div.card__media.skeleton'),
variant === 'poster' ? h('div.card__body', h('div.skeleton.skeleton--line'), h('div.skeleton.skeleton--line.skeleton--short')) : null,
);
}
export function grid(items, render = (it) => posterCard(it)) {
return h('div.grid', { role: 'list' }, items.map(render));
}
+30
View File
@@ -0,0 +1,30 @@
/*
cast.js — "Top Cast" carousel: round avatars, name + character.
castRow(credits, { limit = 15 }) → row section (or null when there is no cast).
*/
import { h } from '../util.js';
import { img } from '../tmdb.js';
import { row } from './row.js';
import { icon } from './icons.js';
function initials(name) {
return String(name || '?').split(/\s+/).slice(0, 2).map((p) => p[0] || '').join('').toUpperCase();
}
export function castCard(p) {
const avatar = p.profile_path
? h('img.cast__img', { src: img(p.profile_path, 'w185'), alt: '', loading: 'lazy', decoding: 'async', onerror: (e) => e.target.replaceWith(h('span.cast__initials', initials(p.name))) })
: h('span.cast__initials', initials(p.name) || icon('user'));
return h('div.card.card--cast', { role: 'listitem' },
h('div.cast', { tabindex: '0', 'data-focus': '', 'aria-label': `${p.name}${p.character ? ` as ${p.character}` : ''}` },
h('div.cast__avatar', avatar),
h('div.cast__text',
h('div.cast__name', p.name),
p.character ? h('div.cast__role', p.character) : null)));
}
export function castRow(credits, opts = {}) {
const cast = ((credits && credits.cast) || []).slice(0, opts.limit || 15);
if (!cast.length) return null;
return row({ title: opts.title || 'Top Cast', variant: 'cast', items: cast, render: castCard, lazy: false });
}
+122
View File
@@ -0,0 +1,122 @@
/*
episodes.js — season picker + episode cards for a tv title page.
episodesSection(details, { season }) → <section class="episodes">
Season tabs (≤ 7 seasons) or a dropdown; cards show still, "E3 · title", synopsis,
runtime, air date and resume progress; click → /watch/tv/:id/:s/:e.
*/
import { h, runtimeLabel, plural } from '../util.js';
import { img, season as fetchSeason } from '../tmdb.js';
import { resume, keyFor, progressOf } from '../storage.js';
import { watchHref } from './actions.js';
import { icon } from './icons.js';
function episodeCard(show, ep) {
const rec = resume.get(keyFor({ type: 'tv', tmdbId: show.id, season: ep.season_number, episode: ep.episode_number }));
const p = progressOf(rec);
const future = ep.air_date && new Date(ep.air_date) > new Date();
const still = ep.still_path || show.backdrop_path;
const imgEl = still
? h('img.card__img', {
src: img(still, 'w300'),
srcset: `${img(still, 'w300')} 300w, ${img(still, 'w780')} 780w`,
sizes: '(max-width: 720px) 92vw, 320px',
alt: '', loading: 'lazy', decoding: 'async',
class: ep.still_path ? null : 'is-fallback',
onload: (e) => e.target.classList.add('is-loaded'),
onerror: (e) => e.target.remove(),
})
: null;
const left = rec && rec.d ? Math.max(0, rec.d - rec.t) : 0;
const metaBits = [
future ? `Airs ${new Date(ep.air_date).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}` : null,
!future && p > 0.01 && p < 0.95 ? `${runtimeLabel(Math.round(left / 60)) || '1m'} left` : null,
!future && p >= 0.95 ? 'Watched' : null,
ep.runtime ? runtimeLabel(ep.runtime) : null,
].filter(Boolean);
return h('div.card.card--episode', { role: 'listitem', class: [future ? 'is-future' : null, p >= 0.95 ? 'is-watched' : null] },
h('a.card__link', { href: watchHref('tv', show.id, ep.season_number, ep.episode_number), 'aria-label': `Episode ${ep.episode_number}: ${ep.name}` },
h('div.card__media',
h('div.card__fallback', h('span', `E${ep.episode_number}`)),
imgEl,
h('div.card__shade'),
h('span.ep__num', `E${ep.episode_number}`),
h('span.card__play.card__play--center', icon('play', { size: 22 })),
p > 0.01 ? h('div.progress.card__progress', h('i', { style: { width: `${Math.round(p * 100)}%` } })) : null),
h('div.ep__body',
h('div.ep__title', ep.name || `Episode ${ep.episode_number}`),
metaBits.length ? h('div.ep__meta', metaBits.join(' · ')) : null,
ep.overview ? h('p.ep__overview', ep.overview) : null)));
}
export function episodesSection(show, opts = {}) {
const seasons = (show.seasons || []).filter((s) => s.season_number > 0 && (s.episode_count > 0 || s.air_date));
if (!seasons.length && show.seasons && show.seasons.length) seasons.push(...show.seasons);
const specials = (show.seasons || []).find((s) => s.season_number === 0 && s.episode_count > 0);
if (specials && seasons.length && !seasons.includes(specials)) seasons.push(specials);
if (!seasons.length) return null;
let current = seasons.find((s) => s.season_number === Number(opts.season)) || seasons[0];
const heading = h('h2.section__title');
const list = h('div.episodes__grid', { role: 'list', 'aria-live': 'polite' });
const label = (s) => (s.season_number === 0 ? 'Specials' : `Season ${s.season_number}`);
let picker;
const tabs = [];
if (seasons.length <= 10) {
picker = h('div.tabs', { role: 'tablist', 'aria-label': 'Seasons' },
seasons.map((s) => {
const t = h('button.tab', { type: 'button', role: 'tab', 'aria-selected': 'false', onclick: () => select(s) }, label(s));
t._season = s;
tabs.push(t);
return t;
}));
picker.addEventListener('keydown', (e) => {
const i = tabs.indexOf(document.activeElement);
if (i < 0 || (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft')) return;
e.preventDefault();
const j = (i + (e.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
tabs[j].focus();
select(tabs[j]._season);
});
} else {
const sel = h('select.select', { 'aria-label': 'Season', onchange: (e) => select(seasons.find((s) => String(s.season_number) === e.target.value)) },
seasons.map((s) => h('option', { value: String(s.season_number) }, `${label(s)}${s.episode_count ? ` · ${s.episode_count} ep` : ''}`)));
picker = h('div.select-wrap', sel, icon('down', { size: 18 }));
picker._sel = sel;
}
let reqId = 0;
async function select(s) {
if (!s) return;
current = s;
tabs.forEach((t) => {
const on = t._season === s;
t.classList.toggle('is-active', on);
t.setAttribute('aria-selected', on ? 'true' : 'false');
t.tabIndex = on ? 0 : -1;
});
if (picker._sel) picker._sel.value = String(s.season_number);
heading.textContent = s.episode_count ? plural(s.episode_count, 'episode') : label(s);
const my = ++reqId;
list.replaceChildren(...Array.from({ length: Math.min(s.episode_count || 6, 8) }, () =>
h('div.card.card--episode.card--skeleton', h('div.card__media.skeleton'), h('div.ep__body', h('div.skeleton.skeleton--line'), h('div.skeleton.skeleton--line.skeleton--short')))));
try {
const data = await fetchSeason(show.id, s.season_number);
if (my !== reqId) return;
const eps = data.episodes || [];
heading.textContent = `${label(s)} · ${plural(eps.length, 'episode')}`;
list.replaceChildren(...eps.map((ep) => episodeCard(show, ep)));
if (!eps.length) list.replaceChildren(h('p.muted', 'No episodes listed yet.'));
} catch (e) {
if (my !== reqId) return;
list.replaceChildren(h('p.muted', `Could not load episodes: ${e.message}`));
}
}
const section = h('section.section.episodes', { id: 'episodes' },
h('div.section__head', heading, picker),
list);
section.refresh = () => select(current);
select(current);
return section;
}
+178
View File
@@ -0,0 +1,178 @@
/*
hero.js — rotating billboard for the home page.
billboard(items, { eyebrow: (i) => string, interval = 8000 }) → { el, destroy() }
items: tmdb.toItem() shapes (need backdrop_path). Details (logo art, genres, certification,
runtime/seasons) are fetched per slide and patched in when they arrive.
*/
import { h, runtimeLabel, plural, reducedMotion } from '../util.js';
import { details as fetchDetails, img, logoFor, certificationFor } from '../tmdb.js';
import { href } from '../router.js';
import { icon } from './icons.js';
import { playTarget, titlePath, myListButton } from './actions.js';
function backdrop(path, eager) {
const el = h('img.hero__img', {
src: img(path, 'w1280'),
srcset: `${img(path, 'w780')} 780w, ${img(path, 'w1280')} 1280w, ${img(path, 'original')} 1920w`,
sizes: '100vw',
alt: '',
decoding: 'async',
loading: eager ? 'eager' : 'lazy',
fetchpriority: eager ? 'high' : 'low',
});
el.addEventListener('load', () => el.classList.add('is-loaded'), { once: true });
return el;
}
function slide(item, i, opts) {
const titleText = h('h2.hero__title', item.title);
const titleBox = h('div.hero__titlebox', titleText);
const meta = h('div.hero__meta',
item.rating > 0 ? h('span.rating.rating--lg', icon('star', { size: 16 }), item.rating.toFixed(1)) : null,
item.year ? h('span', item.year) : null,
h('span.chip', item.type === 'tv' ? 'Series' : 'Movie'),
);
const play = h('a.btn.btn--primary.btn--lg', { href: href(playTarget(item.type, item.id).path) }, icon('play'), h('span', playTarget(item.type, item.id).label));
const more = h('a.btn.btn--glass.btn--lg', { href: href(titlePath(item.type, item.id)) }, icon('info'), h('span', 'More Info'));
const el = h('article.hero__slide', { 'aria-roledescription': 'slide', 'aria-label': `${i + 1} of ${opts.count}: ${item.title}`, 'aria-hidden': i === 0 ? 'false' : 'true' },
h('div.hero__media', backdrop(item.backdrop_path, i === 0)),
h('div.hero__scrim'),
h('div.hero__content.container',
opts.eyebrow ? h('div.hero__eyebrow', icon('fire', { size: 18 }), opts.eyebrow(i, item)) : null,
titleBox,
meta,
item.overview ? h('p.hero__overview', item.overview) : null,
h('div.hero__actions', play, more, myListButton(item, { className: 'btn btn--icon btn--glass btn--lg', iconOnly: true })),
),
);
if (i !== 0) el.inert = true;
el._hydrate = async () => {
let d;
try {
d = await fetchDetails(item.type, item.id);
} catch (e) {
return;
}
const logo = logoFor(d);
if (logo) {
const im = h('img.hero__logo', { src: img(logo.file_path, 'w500'), alt: item.title, decoding: 'async' });
im.addEventListener('load', () => {
titleBox.classList.add('has-logo');
titleText.classList.add('sr-only');
}, { once: true });
im.addEventListener('error', () => im.remove(), { once: true });
titleBox.prepend(im);
}
const genres = (d.genres || []).slice(0, 3).map((g) => g.name);
const cert = certificationFor(d);
const extra = item.type === 'tv'
? d.number_of_seasons ? plural(d.number_of_seasons, 'Season') : ''
: runtimeLabel(d.runtime);
meta.replaceChildren(...[
item.rating > 0 ? h('span.rating.rating--lg', icon('star', { size: 16 }), item.rating.toFixed(1)) : null,
item.year ? h('span', item.year) : null,
extra ? h('span', extra) : null,
genres.length ? h('span.hero__genres', genres.join(' · ')) : null,
cert ? h('span.chip.chip--outline', cert) : null,
].filter(Boolean));
const target = playTarget(item.type, item.id, d);
play.href = href(target.path);
play.lastChild.textContent = target.label;
};
return el;
}
export function billboard(items, opts = {}) {
const data = (items || []).filter((x) => x && x.backdrop_path).slice(0, opts.max || 5);
const interval = opts.interval || 8000;
if (!data.length) return { el: h('div.hero.hero--empty'), destroy() {} };
const slides = data.map((it, i) => slide(it, i, { count: data.length, eyebrow: opts.eyebrow }));
const dots = data.map((it, i) => h('button.hero__dot', { type: 'button', 'aria-label': `Show ${it.title}`, style: { '--dur': `${interval}ms` } }, h('i')));
const el = h('section.hero', { 'aria-roledescription': 'carousel', 'aria-label': 'Featured' },
h('div.hero__slides', slides),
data.length > 1 ? h('div.hero__dots.container', h('div.hero__dots-inner', dots)) : null,
);
let cur = 0;
let timer = null;
let paused = false;
let destroyed = false;
function show(i) {
const nextI = (i + data.length) % data.length;
slides.forEach((s, k) => {
const on = k === nextI;
s.classList.toggle('is-active', on);
s.setAttribute('aria-hidden', on ? 'false' : 'true');
s.inert = !on;
});
dots.forEach((d, k) => {
d.classList.toggle('is-active', k === nextI);
d.setAttribute('aria-current', k === nextI ? 'true' : 'false');
});
cur = nextI;
// restart the dot fill animation
const fill = dots[cur] && dots[cur].firstChild;
if (fill) {
fill.style.animation = 'none';
void fill.offsetWidth;
fill.style.animation = '';
}
schedule();
}
function schedule() {
clearTimeout(timer);
if (destroyed || paused || document.hidden || data.length < 2 || reducedMotion()) return;
timer = setTimeout(() => show(cur + 1), interval);
}
function setPaused(p) {
paused = p;
el.classList.toggle('is-paused', p);
if (p) clearTimeout(timer);
else schedule();
}
dots.forEach((d, i) => d.addEventListener('click', () => show(i)));
el.addEventListener('mouseenter', () => setPaused(true));
el.addEventListener('mouseleave', () => setPaused(false));
el.addEventListener('focusin', () => setPaused(true));
el.addEventListener('focusout', (e) => {
if (!el.contains(e.relatedTarget)) setPaused(false);
});
el.addEventListener('keydown', (e) => {
if (e.target.closest('.hero__dots') && (e.key === 'ArrowRight' || e.key === 'ArrowLeft')) {
e.preventDefault();
show(cur + (e.key === 'ArrowRight' ? 1 : -1));
dots[cur].focus();
}
});
// swipe on touch
let sx = null;
el.addEventListener('touchstart', (e) => { sx = e.touches[0].clientX; }, { passive: true });
el.addEventListener('touchend', (e) => {
if (sx == null) return;
const dx = e.changedTouches[0].clientX - sx;
sx = null;
if (Math.abs(dx) > 50) show(cur + (dx < 0 ? 1 : -1));
});
const onVis = () => (document.hidden ? clearTimeout(timer) : schedule());
document.addEventListener('visibilitychange', onVis);
show(0);
slides[0]._hydrate();
setTimeout(() => slides.slice(1).forEach((s) => s._hydrate()), 600);
return {
el,
destroy() {
destroyed = true;
clearTimeout(timer);
document.removeEventListener('visibilitychange', onVis);
},
};
}
+48
View File
@@ -0,0 +1,48 @@
/*
icons.js — inline SVG icons (stroke style, 24×24). icon(name, { size, fill }) → <svg>.
*/
import { h } from '../util.js';
const P = {
play: [['path', { d: 'M7 4.5v15a1 1 0 0 0 1.5.86l12.5-7.5a1 1 0 0 0 0-1.72L8.5 3.64A1 1 0 0 0 7 4.5z', fill: 'currentColor', stroke: 'none' }]],
info: [['circle', { cx: 12, cy: 12, r: 9.5 }], ['path', { d: 'M12 11v6M12 7.5v.01' }]],
plus: [['path', { d: 'M12 5v14M5 12h14' }]],
check: [['path', { d: 'M5 12.5l4.5 4.5L19 7.5' }]],
search: [['circle', { cx: 11, cy: 11, r: 7 }], ['path', { d: 'M20.5 20.5L16 16' }]],
settings: [['circle', { cx: 12, cy: 12, r: 3 }], ['path', { d: 'M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z' }]],
home: [['path', { d: 'M3 10.5L12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1z' }]],
film: [['rect', { x: 3, y: 3, width: 18, height: 18, rx: 2.5 }], ['path', { d: 'M7 3v18M17 3v18M3 8h4M3 16h4M17 8h4M17 16h4M3 12h18' }]],
tv: [['rect', { x: 2.5, y: 6.5, width: 19, height: 13, rx: 2.5 }], ['path', { d: 'M8 2.5l4 4 4-4' }]],
bookmark: [['path', { d: 'M6 3.5h12a.5.5 0 0 1 .5.5v17l-6.5-4.5L5.5 21V4a.5.5 0 0 1 .5-.5z' }]],
share: [['circle', { cx: 18, cy: 5, r: 2.5 }], ['circle', { cx: 6, cy: 12, r: 2.5 }], ['circle', { cx: 18, cy: 19, r: 2.5 }], ['path', { d: 'M8.2 13.3l7.6 4.4M15.8 6.3l-7.6 4.4' }]],
trailer: [['rect', { x: 3, y: 4, width: 18, height: 16, rx: 2.5 }], ['path', { d: 'M10 9v6l5-3z', fill: 'currentColor' }]],
star: [['path', { d: 'M12 2.8l2.8 5.8 6.3.9-4.6 4.4 1.1 6.3L12 17.2l-5.6 3 1.1-6.3L2.9 9.5l6.3-.9z', fill: 'currentColor', stroke: 'none' }]],
close: [['path', { d: 'M6 6l12 12M18 6L6 18' }]],
left: [['path', { d: 'M15 18l-6-6 6-6' }]],
right: [['path', { d: 'M9 6l6 6-6 6' }]],
down: [['path', { d: 'M6 9l6 6 6-6' }]],
back: [['path', { d: 'M19 12H5M11 18l-6-6 6-6' }]],
trash: [['path', { d: 'M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3' }]],
user: [['circle', { cx: 12, cy: 8, r: 4 }], ['path', { d: 'M4 21c1.5-4 4.5-6 8-6s6.5 2 8 6' }]],
spark: [['path', { d: 'M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5L18 18M6 18l2.5-2.5M15.5 8.5L18 6' }]],
fire: [['path', { d: 'M12 22c4 0 7-2.7 7-6.6 0-3.6-2.4-5.7-4-8.4-.5 2-1.6 3.2-3 3.4.4-3-1-6-4-8.4.2 3.3-1.4 5.5-2.8 7.4C4.2 11 3 12.6 3 15.4 3 19.3 6 22 10 22z' }]],
list: [['path', { d: 'M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01' }]],
};
export function icon(name, opts = {}) {
const size = opts.size || 20;
const parts = P[name] || P.info;
return h('svg', {
class: ['icon', opts.class],
viewBox: '0 0 24 24',
width: size,
height: size,
fill: 'none',
stroke: 'currentColor',
'stroke-width': opts.stroke || 2,
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
'aria-hidden': 'true',
focusable: 'false',
}, parts.map(([tag, attrs]) => h(tag, attrs)));
}
+68
View File
@@ -0,0 +1,68 @@
/*
modal.js — accessible dialog. openModal(content, { label, wide, onClose }) → close()
trailerModal(youtubeKey, title) plays a YouTube trailer in an iframe.
*/
import { h } from '../util.js';
import { icon } from './icons.js';
export function openModal(content, opts = {}) {
const prevFocus = document.activeElement;
const closeBtn = h('button.modal__close.icon-btn', { type: 'button', 'aria-label': 'Close' }, icon('close'));
const dialog = h('div.modal__dialog', { class: opts.wide ? 'modal__dialog--wide' : null, role: 'dialog', 'aria-modal': 'true', 'aria-label': opts.label || 'Dialog', tabindex: '-1' }, closeBtn, content);
const backdrop = h('div.modal', dialog);
let closed = false;
function close() {
if (closed) return;
closed = true;
document.removeEventListener('keydown', onKey, true);
backdrop.classList.remove('is-open');
document.documentElement.classList.remove('has-modal');
setTimeout(() => backdrop.remove(), 250);
if (opts.onClose) opts.onClose();
if (prevFocus && prevFocus.focus) prevFocus.focus();
}
function onKey(e) {
if (e.key === 'Escape') {
e.preventDefault();
close();
} else if (e.key === 'Tab') {
const f = dialog.querySelectorAll('button, [href], input, select, textarea, iframe, [tabindex]:not([tabindex="-1"])');
if (!f.length) return;
const first = f[0];
const last = f[f.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
}
closeBtn.addEventListener('click', close);
backdrop.addEventListener('click', (e) => {
if (e.target === backdrop) close();
});
document.addEventListener('keydown', onKey, true);
document.body.appendChild(backdrop);
document.documentElement.classList.add('has-modal');
requestAnimationFrame(() => {
backdrop.classList.add('is-open');
closeBtn.focus();
});
return close;
}
export function trailerModal(key, title) {
const frame = h('iframe.modal__video', {
src: `https://www.youtube-nocookie.com/embed/${encodeURIComponent(key)}?autoplay=1&rel=0&modestbranding=1`,
title: title ? `${title} — trailer` : 'Trailer',
allow: 'autoplay; encrypted-media; picture-in-picture; fullscreen',
allowfullscreen: true,
referrerpolicy: 'strict-origin-when-cross-origin',
});
return openModal(h('div.modal__media', frame), { label: title ? `${title} trailer` : 'Trailer', wide: true });
}
+764
View File
@@ -0,0 +1,764 @@
/*
PLAYER ENGINE — plays one Stream (docs/api.md "Stream") in a <video>.
createPlayer(video, { onState, onError, onLevels, onAudioTracks, onTorrent, onTime })
load(stream, { startAt, autoplay }) start a source (tears down the previous one)
play() / pause() / toggle()
seek(t) absolute seconds (offset-aware for remux)
currentTime() / duration() / buffered() → [[start,end]…] in absolute seconds
levels() / setLevel(i) hls.js quality, -1 = auto
audioTracks() / setAudioTrack(i)
subtitles() / setSubtitle(i) stream.subtitles, -1 = off (fetched → blob VTT)
destroy()
playback.kind:
hls hls.js (or native HLS on Safari)
file <video src>, native range seeking
remux <video src=url?start=t>, clock = offset + video.currentTime,
seeking outside the buffer reloads with a new start, duration
from `${path}/probe`
torrent poll playback.status every 1s until ready, then remux-style
(status.file.remux) or file-style playback of playback.url
Direct → fallback: when playback.fallback exists and the direct url fails
(fatal hls network error, <video> error, or no metadata within 8s) the
engine silently reloads the fallback at the same position. Anything that
fails after that is reported to onError({ fatal: true }) so the caller can
move on to the next source.
*/
import { resolveUrl } from '../config.js';
const DIRECT_TIMEOUT_MS = 8000;
const STARTUP_TIMEOUT_MS = 12000;
const TORRENT_TIMEOUT_MS = 90000;
let hlsPromise = null;
export function loadHls() {
if (window.Hls) return Promise.resolve(window.Hls);
if (hlsPromise) return hlsPromise;
hlsPromise = new Promise((resolve) => {
const s = document.createElement('script');
s.src = new URL('../../vendor/hls.min.js', import.meta.url).href;
s.async = true;
s.onload = () => resolve(window.Hls || null);
s.onerror = () => {
hlsPromise = null;
resolve(null);
};
document.head.appendChild(s);
});
return hlsPromise;
}
function abs(url) {
if (!url) return '';
if (/^(https?:|blob:|data:)/i.test(url)) return url;
try {
return resolveUrl(url);
} catch (e) {
return url;
}
}
function splitUrl(url) {
const i = url.indexOf('?');
return i < 0 ? [url, ''] : [url.slice(0, i), url.slice(i + 1)];
}
/** url with ?start=<t> set (keeps other params). */
export function withStart(url, t) {
const [path, qs] = splitUrl(url);
const q = new URLSearchParams(qs);
if (t > 0) q.set('start', String(Math.floor(t)));
else q.delete('start');
const s = q.toString();
return s ? `${path}?${s}` : path;
}
/** `/v1/remux/<token>?x` → `/v1/remux/<token>/probe?x` */
export function probeUrl(url) {
const [path, qs] = splitUrl(url);
const q = new URLSearchParams(qs);
q.delete('start');
const s = q.toString();
return `${path.replace(/\/+$/, '')}/probe${s ? `?${s}` : ''}`;
}
export function createPlayer(video, handlers = {}) {
const h = {
onState() {},
onError() {},
onLevels() {},
onAudioTracks() {},
onTorrent() {},
...handlers,
};
let token = 0;
let stream = null;
let hls = null;
let mode = ''; // hls | native-hls | file | remux
let offset = 0;
let knownDuration = 0;
let mediaUrl = '';
let usingFallback = false;
let started = false;
let wantPlay = true;
let pendingTime = null;
let timers = [];
let subIndex = -1;
let subTrackEl = null;
const subCache = new Map();
let lastTorrent = null;
let probeInfo = null; // remux/torrent ffprobe summary
let remuxAudio = null; // absolute ffprobe audio index (?audio=)
let mediaRetries = 0;
let netRetries = 0;
const emit = (phase, extra) => h.onState({ phase, ...extra });
const later = (fn, ms, my) => {
const id = setTimeout(() => {
if (my === token) fn();
}, ms);
timers.push(id);
return id;
};
const clearTimers = () => {
for (const id of timers) {
clearTimeout(id);
clearInterval(id);
}
timers = [];
};
/* ---- teardown -------------------------------------------------------- */
function teardownMedia() {
if (hls) {
try {
hls.destroy();
} catch (e) {
/* already gone */
}
hls = null;
}
video.removeAttribute('src');
try {
video.load();
} catch (e) {
/* ignore */
}
}
function removeSubTrack() {
if (subTrackEl) subTrackEl.remove();
subTrackEl = null;
}
function reset() {
token++;
clearTimers();
teardownMedia();
removeSubTrack();
mode = '';
offset = 0;
knownDuration = 0;
started = false;
pendingTime = null;
usingFallback = false;
mediaRetries = 0;
netRetries = 0;
lastTorrent = null;
probeInfo = null;
remuxAudio = null;
}
/* ---- errors ---------------------------------------------------------- */
function fail(my, message, code) {
if (my !== token) return;
// direct url failed before playing → try the server fallback once
if (!usingFallback && stream && stream.playback && stream.playback.fallback && (mode === 'hls' || mode === 'file' || mode === 'native-hls')) {
const at = pendingTime != null ? pendingTime : currentTime();
usingFallback = true;
emit('fallback', { message: 'Switching to relay…' });
startMedia(stream.playback.fallback, at, /* keepFallbackFlag */ true);
return;
}
clearTimers();
h.onError({ fatal: true, message: message || 'Playback failed', code: code || 'error', stream });
}
/* ---- media start ----------------------------------------------------- */
function armWatchdogs(my) {
// a direct url that hasn't produced metadata quickly is treated as failed
if (!usingFallback && stream.playback && stream.playback.fallback) {
later(() => {
if (video.readyState < 1) fail(my, 'Direct source timed out', 'direct-timeout');
}, DIRECT_TIMEOUT_MS, my);
}
later(() => {
if (!started && video.readyState < 3 && !(video.paused && video.readyState >= 2)) {
fail(my, 'Source stalled while starting', 'stall');
}
}, STARTUP_TIMEOUT_MS, my);
}
async function startHls(url, startAt, my) {
const Hls = await loadHls();
if (my !== token) return;
const nativeOk = video.canPlayType('application/vnd.apple.mpegurl');
if (!Hls || !Hls.isSupported()) {
if (nativeOk) {
mode = 'native-hls';
startFile(url, startAt, my);
return;
}
fail(my, 'HLS is not supported in this browser', 'unsupported');
return;
}
mode = 'hls';
const inst = new Hls({
enableWorker: true,
lowLatencyMode: false,
startLevel: -1,
capLevelToPlayerSize: true,
maxBufferLength: 30,
maxMaxBufferLength: 120,
backBufferLength: 60,
progressive: true,
startPosition: startAt > 0 ? startAt : -1,
testBandwidth: true,
fragLoadPolicy: {
default: {
maxTimeToFirstByteMs: 10000,
maxLoadTimeMs: 120000,
timeoutRetry: { maxNumRetry: 2, retryDelayMs: 0, maxRetryDelayMs: 0 },
errorRetry: { maxNumRetry: 3, retryDelayMs: 1000, maxRetryDelayMs: 8000 },
},
},
});
hls = inst;
const E = Hls.Events;
inst.on(E.MANIFEST_PARSED, () => {
if (my !== token) return;
h.onLevels(levels(), inst.currentLevel);
if (wantPlay) tryPlay(my);
});
inst.on(E.LEVEL_SWITCHED, () => my === token && h.onLevels(levels(), inst.currentLevel));
inst.on(E.AUDIO_TRACKS_UPDATED, () => my === token && h.onAudioTracks(audioTracks(), inst.audioTrack));
inst.on(E.AUDIO_TRACK_SWITCHED, () => my === token && h.onAudioTracks(audioTracks(), inst.audioTrack));
inst.on(E.ERROR, (evt, data) => {
if (my !== token || !data.fatal) return;
if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
mediaRetries++;
if (mediaRetries === 1) inst.recoverMediaError();
else if (mediaRetries === 2) {
inst.swapAudioCodec();
inst.recoverMediaError();
} else fail(my, `Media error: ${data.details}`, 'media');
return;
}
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
// before playback started, a network error on the direct url means CORS/blocked
if (!started && !usingFallback && stream.playback.fallback) return fail(my, data.details, 'network');
const manifestish = /manifest|level/i.test(data.details || '');
if (started && !manifestish && netRetries < 3) {
netRetries++;
later(() => inst.startLoad(), 1500 * netRetries, my);
return;
}
fail(my, `Network error: ${data.details}`, 'network');
return;
}
fail(my, `Stream error: ${data.details}`, 'other');
});
inst.loadSource(url);
inst.attachMedia(video);
}
function startFile(url, startAt, my) {
if (!mode) mode = 'file';
video.src = url;
if (startAt > 0) {
pendingTime = startAt;
const seekTo = () => {
if (my !== token) return;
const d = video.duration;
let t = startAt;
if (isFinite(d) && d > 0) t = Math.min(t, Math.max(0, d - 5));
try {
video.currentTime = t;
} catch (e) {
/* ignore */
}
pendingTime = null;
};
video.addEventListener('loadedmetadata', seekTo, { once: true });
}
if (wantPlay) tryPlay(my);
}
function startRemux(url, startAt, my) {
mode = 'remux';
offset = Math.max(0, Math.floor(startAt || 0));
if (!knownDuration) {
// torrent: /v1/torrent/<token>/probe (sibling of /status); remux: <token>/probe
const pb = stream && stream.playback;
const probe = pb && pb.kind === 'torrent' && pb.status ? abs(pb.status).replace(/\/status(\?|$)/, '/probe$1') : probeUrl(url);
fetch(probe)
.then((r) => (r.ok ? r.json() : null))
.then((p) => {
if (my !== token || !p) return;
if (p.duration > 0) knownDuration = p.duration;
probeInfo = p;
emit('probe', { probe: p });
h.onAudioTracks(audioTracks(), currentAudioTrack());
})
.catch(() => {});
}
video.src = remuxSrc(offset);
syncOffset(offset, my);
if (wantPlay) tryPlay(my);
}
function startMedia(url, startAt, keepFallback) {
const prevSub = subIndex;
const keepFlag = keepFallback ? usingFallback : false;
const keptDuration = knownDuration;
const prevTorrentMode = mode === 'remux' ? 'remux' : null;
clearTimers();
teardownMedia();
token++;
const my = token;
usingFallback = keepFlag;
started = false;
pendingTime = startAt > 0 ? startAt : null;
mediaUrl = abs(url);
emit('loading', { message: usingFallback ? 'Connecting through relay…' : 'Loading…', fallback: usingFallback });
armWatchdogs(my);
const kind = stream.playback ? stream.playback.kind : 'file';
if (kind === 'hls') startHls(mediaUrl, startAt, my);
else if (kind === 'remux' || prevTorrentMode === 'remux' || (kind === 'torrent' && lastTorrent && lastTorrent.file && lastTorrent.file.remux)) {
knownDuration = keptDuration;
startRemux(mediaUrl, startAt, my);
} else {
mode = 'file';
startFile(mediaUrl, startAt, my);
}
if (prevSub >= 0) setSubtitle(prevSub);
}
function startTorrent(startAt, my) {
const statusUrl = abs(stream.playback.status);
const began = Date.now();
emit('torrent', { message: 'Connecting to peers…', torrent: null });
let polling = false;
const poll = async () => {
if (my !== token || polling) return;
polling = true;
let st = null;
try {
const r = await fetch(statusUrl);
if (r.ok) st = await r.json();
} catch (e) {
/* retry next tick */
}
polling = false;
if (my !== token) return;
if (st) {
lastTorrent = st;
h.onTorrent(st);
}
if (!mode) {
if (st && st.ready) {
if (st.file && st.file.duration > 0) knownDuration = st.file.duration;
else if (st.duration > 0) knownDuration = st.duration;
const url = abs(stream.playback.url);
mediaUrl = url;
emit('loading', { message: 'Buffering…' });
armWatchdogs(my);
if (st.file && st.file.remux) startRemux(url, startAt, my);
else {
mode = 'file';
startFile(withStart(url, 0), startAt, my);
}
if (subIndex >= 0) setSubtitle(subIndex);
} else {
emit('torrent', { message: st && st.peers ? 'Downloading…' : 'Connecting to peers…', torrent: st });
if (Date.now() - began > TORRENT_TIMEOUT_MS && !(st && st.peers > 0)) {
fail(my, 'No peers for this torrent', 'torrent-timeout');
}
}
}
};
poll();
let tick = 0;
const id = setInterval(() => {
// 1s while waiting for the torrent, every 3s once playing (stats only)
tick++;
if (!mode || tick % 3 === 0) poll();
}, 1000);
timers.push(id);
}
function tryPlay(my) {
const p = video.play();
if (p && p.catch) {
p.catch((e) => {
if (my !== token) return;
if (e && e.name === 'NotAllowedError') emit('blocked', { message: 'Press play to start' });
});
}
}
/* ---- video events ---------------------------------------------------- */
const on = (name, fn) => video.addEventListener(name, fn);
const listeners = [];
const bind = (name, fn) => {
on(name, fn);
listeners.push([name, fn]);
};
bind('loadedmetadata', () => {
if (!stream) return;
emit('metadata', { duration: duration() });
});
bind('playing', () => {
if (!stream) return;
started = true;
emit('playing');
});
bind('canplay', () => {
if (!stream) return;
if (video.paused) emit('ready');
});
bind('waiting', () => stream && emit('buffering', { message: 'Buffering…' }));
bind('pause', () => stream && emit('paused'));
bind('ended', () => stream && emit('ended'));
bind('error', () => {
if (!stream || !mode || mode === 'hls') return;
const err = video.error;
// remux: retry once from the current position before giving up
fail(token, err ? `Video error ${err.code}${err.message ? `: ${err.message}` : ''}` : 'Video error', 'video');
});
/* ---- public: load ---------------------------------------------------- */
function load(s, opts = {}) {
reset();
stream = s;
wantPlay = opts.autoplay !== false;
const startAt = Math.max(0, Number(opts.startAt) || 0);
const pb = s.playback || { kind: 'file', url: s.url };
if (pb.kind === 'torrent') {
const my = token;
pendingTime = startAt || null;
startTorrent(startAt, my);
return;
}
startMedia(pb.url, startAt, false);
}
/* ---- public: transport ----------------------------------------------- */
function currentTime() {
if (pendingTime != null && video.readyState < 1) return pendingTime;
const t = video.currentTime || 0;
return mode === 'remux' ? offset + t : t;
}
function duration() {
if (mode === 'remux') {
if (knownDuration > 0) return knownDuration;
const d = video.duration;
return isFinite(d) && d > 0 ? offset + d : 0;
}
const d = video.duration;
if (isFinite(d) && d > 0) return d;
return knownDuration || 0;
}
function buffered() {
const out = [];
const b = video.buffered;
const add = mode === 'remux' ? offset : 0;
for (let i = 0; i < b.length; i++) out.push([b.start(i) + add, b.end(i) + add]);
return out;
}
function seek(t) {
if (!stream || !mode) return;
const d = duration();
if (d > 0) t = Math.min(t, Math.max(0, d - 1));
t = Math.max(0, t);
if (mode !== 'remux') {
try {
video.currentTime = t;
} catch (e) {
/* not seekable yet */
}
return;
}
const rel = t - offset;
const b = video.buffered;
for (let i = 0; i < b.length; i++) {
if (rel >= b.start(i) && rel <= b.end(i) - 0.5) {
video.currentTime = rel;
return;
}
}
reloadRemux(t);
}
// the remux begins at the keyframe at/before t, not t itself: ask the server which one
function syncOffset(t, my) {
if (!(t > 0)) return;
const pb = stream && stream.playback;
const base = pb && pb.kind === 'torrent' && pb.status ? abs(pb.status).replace(/\/status(\?|$)/, '/probe$1') : probeUrl(mediaUrl);
fetch(`${base}${base.includes('?') ? '&' : '?'}start=${t}`)
.then((r) => (r.ok ? r.json() : null))
.then((p) => {
if (my === token && p && Number.isFinite(p.keyframe) && p.keyframe <= t) offset = p.keyframe;
})
.catch(() => {});
}
function remuxSrc(t) {
let u = withStart(mediaUrl, t);
if (remuxAudio != null) u += `${u.includes('?') ? '&' : '?'}audio=${remuxAudio}`;
return u;
}
// restart the remux at t (seek outside the buffer, or audio track change)
function reloadRemux(t) {
const my = ++token;
clearTimers();
const wasPlaying = !video.paused || wantPlay;
wantPlay = wasPlaying;
offset = Math.floor(t);
pendingTime = offset;
started = false;
emit('seeking', { message: 'Seeking…' });
video.src = remuxSrc(offset);
syncOffset(offset, my);
armWatchdogs(my);
if (lastTorrent || (stream.playback && stream.playback.kind === 'torrent')) {
// keep torrent stats ticking after a remux seek
const statusUrl = abs(stream.playback.status);
const id = setInterval(() => {
fetch(statusUrl)
.then((r) => (r.ok ? r.json() : null))
.then((st) => {
if (st && my === token) {
lastTorrent = st;
h.onTorrent(st);
}
})
.catch(() => {});
}, 3000);
timers.push(id);
}
video.addEventListener('loadedmetadata', () => my === token && (pendingTime = null), { once: true });
if (wasPlaying) tryPlay(my);
}
function play() {
wantPlay = true;
tryPlay(token);
}
function pause() {
wantPlay = false;
video.pause();
}
function toggle() {
if (video.paused || video.ended) play();
else pause();
}
/* ---- public: tracks -------------------------------------------------- */
function levels() {
if (!hls || !hls.levels) return [];
return hls.levels.map((l, i) => ({
index: i,
height: l.height || 0,
width: l.width || 0,
bitrate: l.bitrate || 0,
label: l.height ? `${l.height}p` : l.bitrate ? `${Math.round(l.bitrate / 1000)} kbps` : `Level ${i + 1}`,
}));
}
function setLevel(i) {
if (!hls) return;
hls.currentLevel = i;
hls.loadLevel = i;
h.onLevels(levels(), i);
}
function currentLevel() {
if (!hls) return -1;
return hls.autoLevelEnabled ? -1 : hls.currentLevel;
}
function playingLevel() {
if (!hls || hls.currentLevel < 0 || !hls.levels) return null;
return levels()[hls.currentLevel] || null;
}
function probeAudio() {
return mode === 'remux' && probeInfo && Array.isArray(probeInfo.audio) ? probeInfo.audio : [];
}
function audioTracks() {
if (hls && hls.audioTracks) {
return hls.audioTracks.map((t, i) => ({ index: i, lang: t.lang || '', label: t.name || t.lang || `Track ${i + 1}` }));
}
return probeAudio().map((a, i) => ({
index: i,
lang: a.lang || '',
label: a.title || [a.lang ? a.lang.toUpperCase() : `Track ${i + 1}`, a.codec, a.channels ? `${a.channels}ch` : ''].filter(Boolean).join(' · '),
}));
}
function setAudioTrack(i) {
if (hls) {
hls.audioTrack = i;
return;
}
const list = probeAudio();
if (!list[i] || list[i].index === remuxAudio) return;
remuxAudio = list[i].index;
reloadRemux(currentTime());
h.onAudioTracks(audioTracks(), i);
}
function currentAudioTrack() {
if (hls) return hls.audioTrack;
const list = probeAudio();
if (!list.length) return -1;
if (remuxAudio != null) return list.findIndex((a) => a.index === remuxAudio);
const def = list.findIndex((a) => a.default);
return def >= 0 ? def : 0;
}
function subtitles() {
return ((stream && stream.subtitles) || []).map((s, i) => ({
index: i,
lang: s.lang || s.language || '',
label: s.label || s.name || s.lang || `Subtitles ${i + 1}`,
url: s.url,
}));
}
async function vttBlob(url) {
if (subCache.has(url)) return subCache.get(url);
const p = fetch(abs(url))
.then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.text();
})
.then((text) => {
if (!/^\uFEFF?WEBVTT/.test(text)) text = `WEBVTT\n\n${text.replace(/(\d\d:\d\d:\d\d),(\d\d\d)/g, '$1.$2')}`;
return URL.createObjectURL(new Blob([text], { type: 'text/vtt' }));
});
subCache.set(url, p);
p.catch(() => subCache.delete(url));
return p;
}
/** Remux restarts the clock at `offset`; shift cues so they still line up. */
function shiftTrack(track) {
if (mode !== 'remux' || !offset || !track || !track.cues) return;
const my = offset;
for (const cue of Array.from(track.cues)) {
if (cue._orig == null) {
cue._orig = [cue.startTime, cue.endTime];
}
cue.startTime = cue._orig[0] - my;
cue.endTime = cue._orig[1] - my;
}
}
async function setSubtitle(i) {
subIndex = i;
removeSubTrack();
for (const t of Array.from(video.textTracks)) t.mode = 'disabled';
const list = subtitles();
if (i < 0 || !list[i]) return true;
const my = token;
let url;
try {
url = await vttBlob(list[i].url);
} catch (e) {
return false;
}
if (my !== token || subIndex !== i) return true;
const el = document.createElement('track');
el.kind = 'subtitles';
el.label = list[i].label;
if (list[i].lang) el.srclang = list[i].lang;
el.src = url;
el.default = true;
el.addEventListener('load', () => {
el.track.mode = 'showing';
shiftTrack(el.track);
});
video.appendChild(el);
subTrackEl = el;
el.track.mode = 'showing';
return true;
}
// re-align subtitle cues after a remux reload
bind('loadeddata', () => {
if (subTrackEl && subTrackEl.track) shiftTrack(subTrackEl.track);
});
function stop() {
reset();
stream = null;
}
function destroy() {
reset();
stream = null;
for (const [n, fn] of listeners) video.removeEventListener(n, fn);
for (const p of subCache.values()) p.then((u) => URL.revokeObjectURL(u)).catch(() => {});
subCache.clear();
}
return {
load,
stop,
play,
pause,
toggle,
seek,
currentTime,
duration,
buffered,
levels,
setLevel,
currentLevel,
playingLevel,
audioTracks,
setAudioTrack,
currentAudioTrack,
subtitles,
setSubtitle,
destroy,
get stream() {
return stream;
},
get mode() {
return mode;
},
get usingFallback() {
return usingFallback;
},
get torrent() {
return lastTorrent;
},
get started() {
return started;
},
};
}
+106
View File
@@ -0,0 +1,106 @@
/*
row.js — horizontal carousel row.
row({
title, moreHref?, variant: 'poster'|'wide'|'logo'|'cast',
items?: array, load?: () => Promise<array>, render: (item, i) => Node,
lazy = true, skeletons = 8, className?
}) → <section class="row"> with .setItems(items) for live refreshes.
- Loads when it nears the viewport (IntersectionObserver) and shows skeletons meanwhile.
- Removes itself (hidden) when it ends up empty or the load fails.
- Arrow buttons on pointer devices; scroll-snap + swipe on touch.
- Keyboard: ←/→ move focus between cards, Home/End jump to the ends.
*/
import { h } from '../util.js';
import { skeletonCard } from './card.js';
import { icon } from './icons.js';
const io = 'IntersectionObserver' in window
? new IntersectionObserver((entries) => {
for (const e of entries) {
if (e.isIntersecting && e.target._load) {
io.unobserve(e.target);
e.target._load();
}
}
}, { rootMargin: '600px 0px' })
: null;
export function row(opts) {
const variant = opts.variant || 'poster';
const track = h('div.row__track', { role: 'list', 'aria-label': opts.title || '' });
const prev = h('button.row__arrow.row__arrow--prev', { type: 'button', 'aria-label': 'Scroll left', tabindex: '-1' }, icon('left', { size: 22 }));
const next = h('button.row__arrow.row__arrow--next', { type: 'button', 'aria-label': 'Scroll right', tabindex: '-1' }, icon('right', { size: 22 }));
const titleEl = opts.title ? h('h2.row__title', opts.title) : null;
const header = opts.title || opts.moreHref
? h('div.row__head', titleEl, opts.moreHref ? h('a.row__more', { href: opts.moreHref }, 'See all', icon('right', { size: 16 })) : null)
: null;
const section = h('section.row', { class: [`row--${variant}`, opts.className] }, header, h('div.row__viewport', prev, track, next));
for (let i = 0; i < (opts.skeletons || (variant === 'wide' ? 5 : 8)); i++) track.appendChild(skeletonCard(variant === 'cast' ? 'cast' : variant));
function updateArrows() {
const max = track.scrollWidth - track.clientWidth - 2;
prev.classList.toggle('is-hidden', track.scrollLeft <= 2);
next.classList.toggle('is-hidden', track.scrollLeft >= max);
}
function scrollByPage(dir) {
const amount = Math.max(track.clientWidth * 0.85, 200);
track.scrollBy({ left: dir * amount, behavior: 'smooth' });
}
prev.addEventListener('click', () => scrollByPage(-1));
next.addEventListener('click', () => scrollByPage(1));
track.addEventListener('scroll', updateArrows, { passive: true });
if ('ResizeObserver' in window) new ResizeObserver(updateArrows).observe(track);
track.addEventListener('keydown', (e) => {
const links = [...track.querySelectorAll(':scope > .card > .card__link, :scope > .card > [data-focus]')];
const i = links.indexOf(document.activeElement);
if (i < 0) return;
let j = -1;
if (e.key === 'ArrowRight') j = Math.min(links.length - 1, i + 1);
else if (e.key === 'ArrowLeft') j = Math.max(0, i - 1);
else if (e.key === 'Home') j = 0;
else if (e.key === 'End') j = links.length - 1;
if (j < 0) return;
e.preventDefault();
links[j].focus({ preventScroll: true });
links[j].scrollIntoView({ inline: 'nearest', block: 'nearest', behavior: 'smooth' });
});
section.setItems = (items) => {
const list = (items || []).filter(Boolean);
if (!list.length) {
section.hidden = true;
track.replaceChildren();
return;
}
section.hidden = false;
track.replaceChildren(...list.map((it, i) => opts.render(it, i)).filter(Boolean));
section.classList.add('is-loaded');
requestAnimationFrame(updateArrows);
};
const load = async () => {
try {
const items = opts.items || (opts.load ? await opts.load() : []);
section.setItems(items);
} catch (e) {
console.warn(`row "${opts.title}" failed:`, e);
section.hidden = true;
}
};
if (opts.items && opts.lazy !== true) {
section.setItems(opts.items);
} else if (io && opts.lazy !== false) {
section._load = load;
io.observe(section);
} else {
load();
}
return section;
}
+35
View File
@@ -0,0 +1,35 @@
/*
toast.js — transient notifications. toast(message, { error, timeout, action: { label, onClick } })
Also exposed as window.bugtv.toast for non-module callers.
*/
import { h } from '../util.js';
let stack = null;
function ensureStack() {
if (stack && document.body.contains(stack)) return stack;
stack = document.getElementById('toasts') || h('div#toasts.toasts', { role: 'status', 'aria-live': 'polite' });
if (!stack.isConnected) document.body.appendChild(stack);
return stack;
}
export function toast(message, opts = {}) {
const el = h('div.toast', { class: opts.error ? 'toast--error' : null },
h('span.toast__msg', String(message)),
opts.action ? h('button.toast__action', { type: 'button', onclick: () => { opts.action.onClick(); dismiss(); } }, opts.action.label) : null);
ensureStack().appendChild(el);
requestAnimationFrame(() => el.classList.add('is-shown'));
let done = false;
function dismiss() {
if (done) return;
done = true;
el.classList.remove('is-shown');
setTimeout(() => el.remove(), 300);
}
setTimeout(dismiss, opts.timeout || (opts.error ? 6000 : 3500));
return dismiss;
}
export function errorToast(err, fallback) {
return toast(err && err.message ? err.message : fallback || 'Something went wrong', { error: true });
}
+171 -58
View File
@@ -1,70 +1,183 @@
/*
UTIL — small shared helpers. No dependencies.
util.js — small shared helpers (no dependencies).
h(tag, attrs, ...children) builds DOM without innerHTML:
h('a.card.card--wide', { href: '/x', onclick: fn, dataset: { id: 1 } }, 'text', node)
- tag may carry .class and #id suffixes
- attrs: class (string|array), style (string|object, supports --custom-props),
dataset, on<event> functions, booleans (true → present, false/null → omitted),
anything else → setAttribute. `attrs` may be omitted.
- children: strings (text nodes — never parsed as HTML), nodes, arrays, null/false (skipped)
*/
(function () {
'use strict';
function escapeHtml(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
export function escapeHtml(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
const SVG_NS = 'http://www.w3.org/2000/svg';
const SVG_TAGS = new Set(['svg', 'path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'g']);
export function h(tag, attrs, ...children) {
let name = 'div';
const classes = [];
let id = '';
const m = String(tag).match(/^([a-z0-9-]*)((?:[.#][\w-]+)*)$/i);
if (m) {
name = m[1] || 'div';
(m[2].match(/[.#][\w-]+/g) || []).forEach((p) => {
if (p[0] === '.') classes.push(p.slice(1));
else id = p.slice(1);
});
} else {
name = tag;
}
function getParam(name) {
return new URLSearchParams(location.search).get(name);
const isSvg = SVG_TAGS.has(name);
const el = isSvg ? document.createElementNS(SVG_NS, name) : document.createElement(name);
if (classes.length) el.setAttribute('class', classes.join(' '));
if (id) el.id = id;
if (attrs != null && (typeof attrs !== 'object' || attrs instanceof Node || Array.isArray(attrs))) {
children.unshift(attrs);
attrs = null;
}
// 95 -> "1:35", 3675 -> "1:01:15"
function formatSeconds(sec) {
sec = Math.max(0, Math.floor(sec || 0));
const h = Math.floor(sec / 3600);
const m = Math.floor((sec % 3600) / 60);
const s = sec % 60;
const mm = h ? String(m).padStart(2, '0') : String(m);
const ss = String(s).padStart(2, '0');
return h ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
if (attrs) {
for (const [k, v] of Object.entries(attrs)) {
if (v == null || v === false) continue;
if (k === 'class' || k === 'className') {
const extra = Array.isArray(v) ? v.filter(Boolean).join(' ') : String(v);
if (extra) el.setAttribute('class', [el.getAttribute('class'), extra].filter(Boolean).join(' '));
} else if (k === 'style') {
if (typeof v === 'string') el.setAttribute('style', v);
else {
for (const [sk, sv] of Object.entries(v)) {
if (sv == null) continue;
if (sk.startsWith('--')) el.style.setProperty(sk, sv);
else el.style[sk] = sv;
}
}
} else if (k === 'dataset') {
for (const [dk, dv] of Object.entries(v)) if (dv != null) el.dataset[dk] = dv;
} else if (k.startsWith('on') && typeof v === 'function') {
el.addEventListener(k.slice(2).toLowerCase(), v);
} else if (k === 'text') {
el.textContent = v;
} else if (!isSvg && (k === 'value' || k === 'checked' || k === 'selected')) {
el[k] = v;
} else if (v === true) {
el.setAttribute(k, '');
} else {
el.setAttribute(k, String(v));
}
}
}
appendChildren(el, children);
return el;
}
// 141 -> "2h 21m"
function runtimeLabel(mins) {
if (!mins || mins <= 0) return '';
const h = Math.floor(mins / 60);
const m = mins % 60;
return h ? (m ? `${h}h ${m}m` : `${h}h`) : `${m}m`;
function appendChildren(el, children) {
for (const c of children) {
if (c == null || c === false || c === true) continue;
if (Array.isArray(c)) appendChildren(el, c);
else if (c instanceof Node) el.appendChild(c);
else el.appendChild(document.createTextNode(String(c)));
}
}
function debounce(fn, wait) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
export function clear(el) {
if (el) el.replaceChildren();
return el;
}
// Reads a query param from the real query string or from a hash route (#/search?q=x).
export function getParam(name) {
const q = new URLSearchParams(location.search).get(name);
if (q != null) return q;
const hash = location.hash || '';
const i = hash.indexOf('?');
return i >= 0 ? new URLSearchParams(hash.slice(i + 1)).get(name) : null;
}
// 95 -> "1:35", 3675 -> "1:01:15"
export function formatSeconds(sec) {
sec = Math.max(0, Math.floor(sec || 0));
const hh = Math.floor(sec / 3600);
const m = Math.floor((sec % 3600) / 60);
const s = sec % 60;
const mm = hh ? String(m).padStart(2, '0') : String(m);
const ss = String(s).padStart(2, '0');
return hh ? `${hh}:${mm}:${ss}` : `${mm}:${ss}`;
}
// 141 -> "2h 21m"
export function runtimeLabel(mins) {
if (!mins || mins <= 0) return '';
const hh = Math.floor(mins / 60);
const m = Math.round(mins % 60);
return hh ? (m ? `${hh}h ${m}m` : `${hh}h`) : `${m}m`;
}
// seconds → "23m" / "1h 4m"
export function durationLabel(sec) {
return runtimeLabel(Math.max(1, Math.round((sec || 0) / 60)));
}
export function yearOf(date) {
return date ? String(date).slice(0, 4) : '';
}
export function debounce(fn, wait) {
let timer = null;
const d = function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
d.cancel = () => clearTimeout(timer);
return d;
}
// resize a full TMDB image URL (…/t/p/<size>/path) to another size
export function tmdbResize(url, size) {
if (!url) return '';
return String(url).replace(/\/t\/p\/[A-Za-z0-9._-]+/, `/t/p/${size}`);
}
export function clamp(n, lo, hi) {
return Math.min(hi, Math.max(lo, n));
}
export function plural(n, word, pluralWord) {
return `${n} ${n === 1 ? word : pluralWord || `${word}s`}`;
}
// Kept from v4 for the player workstream.
export function webPlayable(stream) {
const s = stream || {};
const url = String(s.url || '');
if (!/^https?:\/\//i.test(url)) return false;
const type = String(s.type || '').toLowerCase();
if (['magnet', 'torrent', 'dash', 'mkv', 'avi'].includes(type)) return false;
const isHls = type === 'm3u8' || /\.m3u8($|\?)/i.test(url);
const isDirect = type === 'mp4' || type === 'webm' || /\.(mp4|m4v|webm)(\?|#|$)/i.test(url);
return isHls || isDirect;
}
export function reducedMotion() {
try {
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
} catch (e) {
return false;
}
}
// resize a full TMDB image URL (…/t/p/<size>/path) to another size
function tmdbResize(url, size) {
if (!url) return '';
return url.replace(/\/t\/p\/[A-Za-z0-9._-]+/, `/t/p/${size}`);
// Swallow errors from storage access in private mode etc.
export function safe(fn, fallback) {
try {
return fn();
} catch (e) {
return fallback;
}
// True when the in-browser player can load the stream through the proxy.
function webPlayable(stream) {
const s = stream || {};
const url = String(s.url || '');
if (!/^https?:\/\//i.test(url)) return false;
const type = String(s.type || '').toLowerCase();
if (['magnet', 'torrent', 'dash', 'mkv', 'avi'].includes(type)) return false;
const isHls = type === 'm3u8' || /\.m3u8($|\?)/i.test(url);
const isDirect =
type === 'mp4' ||
type === 'webm' ||
/\.(mp4|m4v|webm)(\?|#|$)/i.test(url);
return isHls || isDirect;
}
window.SR = window.SR || {};
SR.util = { escapeHtml, getParam, formatSeconds, runtimeLabel, debounce, tmdbResize, webPlayable };
})();
}
+63
View File
@@ -0,0 +1,63 @@
/*
views/browse.js — /browse/:type?with_genres=&with_networks=&title= discover grid with infinite scroll.
Without filters it lists popular titles of that type.
*/
import { h } from '../util.js';
import * as tmdb from '../tmdb.js';
import { posterCard, skeletonCard } from '../ui/card.js';
const PASS = ['with_genres', 'with_networks', 'with_companies', 'with_original_language', 'sort_by', 'with_keywords', 'first_air_date_year', 'primary_release_year'];
export function render(root, params) {
const type = params.type === 'tv' ? 'tv' : 'movie';
const q = params.query;
const filters = {};
PASS.forEach((k) => q.get(k) && (filters[k] = q.get(k)));
const title = q.get('title') || (type === 'tv' ? 'Series' : 'Movies');
document.title = `${title} · bug tv`;
const gridEl = h('div.grid', { role: 'list' });
const sentinel = h('div.load-more');
const status = h('p.muted.center');
root.append(h('div.page.page--padded.container',
h('div.page__head', h('div', h('p.page__eyebrow', type === 'tv' ? 'Series' : 'Movies'), h('h1.page__title', title))),
gridEl, status, sentinel));
let page = 0;
let total = 1;
let loading = false;
const seen = new Set();
async function more() {
if (loading || page >= total || page >= 20) return;
loading = true;
const skels = Array.from({ length: 12 }, () => skeletonCard('poster'));
gridEl.append(...skels);
try {
const next = page + 1;
const d = Object.keys(filters).length
? await tmdb.discover(type, { ...filters, page: next, 'vote_count.gte': filters.with_networks ? 20 : 50 })
: await tmdb.popular(type, next);
if (params.signal.aborted) return;
page = next;
total = d.total_pages || 1;
skels.forEach((s) => s.remove());
const items = (d.results || []).map((r) => tmdb.toItem(r, type)).filter((x) => x.poster_path && !seen.has(x.id) && seen.add(x.id));
gridEl.append(...items.map((it) => posterCard(it)));
if (!gridEl.children.length) status.textContent = 'Nothing found.';
} catch (e) {
skels.forEach((s) => s.remove());
status.textContent = e.message;
total = 0;
} finally {
loading = false;
}
// keep filling while the sentinel is still visible
if (sentinel.getBoundingClientRect().top < window.innerHeight + 600) more();
}
const io = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && more(), { rootMargin: '800px 0px' });
io.observe(sentinel);
more();
return () => io.disconnect();
}
+186
View File
@@ -0,0 +1,186 @@
/*
views/home.js — home (/), Movies (/movies) and TV (/tv) browse pages.
params.kind: undefined | 'movie' | 'tv'
*/
import { h, durationLabel } from '../util.js';
import * as tmdb from '../tmdb.js';
import { href } from '../router.js';
import { resume, myList, progressOf } from '../storage.js';
import { billboard } from '../ui/hero.js';
import { row } from '../ui/row.js';
import { posterCard, wideCard, logoCard } from '../ui/card.js';
import { watchHref } from '../ui/actions.js';
import { toast } from '../ui/toast.js';
const NETWORKS = [
{ id: 213, name: 'Netflix' },
{ id: 49, name: 'HBO' },
{ id: 2739, name: 'Disney+' },
{ id: 2552, name: 'Apple TV+' },
{ id: 1024, name: 'Prime Video' },
{ id: 453, name: 'Hulu' },
{ id: 4330, name: 'Paramount+' },
{ id: 3186, name: 'HBO Max' },
];
const GENRES = {
all: [
{ type: 'movie', id: 28, name: 'Action Movies' },
{ type: 'tv', id: 10765, name: 'Sci-Fi & Fantasy Series' },
{ type: 'movie', id: 35, name: 'Comedy Movies' },
{ type: 'tv', id: 80, name: 'Crime Series' },
{ type: 'movie', id: 16, name: 'Animation' },
{ type: 'movie', id: 27, name: 'Horror' },
],
movie: [
{ type: 'movie', id: 28, name: 'Action' },
{ type: 'movie', id: 878, name: 'Science Fiction' },
{ type: 'movie', id: 35, name: 'Comedy' },
{ type: 'movie', id: 53, name: 'Thrillers' },
{ type: 'movie', id: 16, name: 'Animation' },
{ type: 'movie', id: 27, name: 'Horror' },
{ type: 'movie', id: 10749, name: 'Romance' },
{ type: 'movie', id: 99, name: 'Documentaries' },
],
tv: [
{ type: 'tv', id: 18, name: 'Drama' },
{ type: 'tv', id: 10765, name: 'Sci-Fi & Fantasy' },
{ type: 'tv', id: 80, name: 'Crime' },
{ type: 'tv', id: 35, name: 'Comedy' },
{ type: 'tv', id: 16, name: 'Animation' },
{ type: 'tv', id: 10759, name: 'Action & Adventure' },
{ type: 'tv', id: 9648, name: 'Mystery' },
{ type: 'tv', id: 99, name: 'Documentary' },
],
};
const items = (type) => (d) => ((d && d.results) || []).map((r) => tmdb.toItem(r, type)).filter((x) => x.poster_path || x.backdrop_path);
const poster = (it) => posterCard(it);
// Continue Watching record → wide card, backdrop looked up lazily when the record has none
function continueCard(rec, onRemoved) {
const item = { type: rec.type, id: rec.tmdbId, title: rec.show || rec.title || '', backdrop_path: null, rating: 0 };
const left = rec.d ? Math.max(0, rec.d - rec.t) : 0;
const leftText = left ? `${durationLabel(left)} left` : '';
const meta = rec.type === 'tv' ? [`S${rec.season} E${rec.episode}`, leftText].filter(Boolean).join(' · ') : leftText || 'Movie';
const image = rec.backdrop || rec.still || null;
const card = wideCard(item, {
href: watchHref(rec.type, rec.tmdbId, rec.season, rec.episode),
image: image || null,
meta,
kicker: rec.type === 'tv' && rec.title && rec.title !== rec.show ? rec.title : null,
progress: progressOf(rec),
onRemove: (el) => {
resume.removeShow(rec.type, rec.tmdbId);
el.remove();
onRemoved();
toast(`Removed “${item.title}” from Continue Watching`);
},
});
if (!image) {
tmdb.details(rec.type, rec.tmdbId).then((d) => {
const path = d.backdrop_path || d.poster_path;
if (!path) return;
const media = card.querySelector('.card__media');
const im = h('img.card__img', { src: tmdb.img(path, 'w780'), alt: '', loading: 'lazy', decoding: 'async', onload: (e) => e.target.classList.add('is-loaded') });
media.insertBefore(im, media.querySelector('.card__shade'));
}).catch(() => {});
}
return card;
}
export async function render(root, params) {
const kind = params.kind === 'movie' || params.kind === 'tv' ? params.kind : null;
document.title = kind === 'movie' ? 'Movies · bug tv' : kind === 'tv' ? 'Series · bug tv' : 'bug tv';
const heroSlot = h('div.hero-slot', h('div.hero.hero--loading', h('div.hero__skeleton.skeleton')));
const rows = h('div.rows');
root.append(h('div.page.page--home', heroSlot, rows));
let hero = null;
const listeners = [];
// hero: top trending
tmdb.trending(kind || 'all', 'day').then((d) => {
if (params.signal.aborted) return;
const list = items(kind)(d).filter((x) => x.backdrop_path && x.overview).slice(0, 5);
const label = kind === 'movie' ? 'Movies' : kind === 'tv' ? 'TV Shows' : null;
hero = billboard(list, {
eyebrow: (i, it) => `#${i + 1} in ${label || (it.type === 'tv' ? 'TV Shows' : 'Movies')} Today`,
});
heroSlot.replaceChildren(hero.el);
}).catch((e) => {
heroSlot.replaceChildren();
toast(e.message, { error: true });
});
// Continue Watching
const contRecords = () => resume.latestPerShow().filter((r) => !kind || r.type === kind).filter((r) => progressOf(r) < 0.97 || r.type === 'tv');
const cont = row({
title: 'Continue Watching',
variant: 'wide',
items: contRecords(),
render: (rec) => continueCard(rec, () => { if (!cont.querySelector('.card')) cont.hidden = true; }),
});
rows.appendChild(cont);
const onResume = () => cont.setItems(contRecords());
window.addEventListener('bugtv:resume', onResume);
listeners.push(['bugtv:resume', onResume]);
// My List
const listItems = () => myList.all().filter((x) => !kind || x.type === kind).map((x) => tmdb.toItem(x, x.type));
const mine = row({ title: 'My List', moreHref: href('/list'), items: listItems(), render: poster });
rows.appendChild(mine);
const onList = () => mine.setItems(listItems());
window.addEventListener('bugtv:mylist', onList);
listeners.push(['bugtv:mylist', onList]);
const add = (opts) => rows.appendChild(row(opts));
if (!kind) {
add({ title: 'Trending Today', load: () => tmdb.trending('all', 'day').then(items()), render: (it, i) => posterCard(it, { rank: i < 10 ? i + 1 : null }) });
add({ title: 'Popular on Streaming', variant: 'logo', items: NETWORKS.slice(0, 6), render: networkCard, lazy: true });
add({ title: 'Popular Movies', moreHref: href('/browse/movie?title=Popular%20Movies'), load: () => tmdb.popular('movie').then(items('movie')), render: poster });
add({ title: 'Popular Series', variant: 'wide', moreHref: href('/browse/tv?title=Popular%20Series'), load: () => tmdb.popular('tv').then(items('tv')), render: (it) => wideCard(it) });
add({ title: 'Top Rated Movies', load: () => tmdb.topRated('movie').then(items('movie')), render: poster });
add({ title: 'Top Rated Series', load: () => tmdb.topRated('tv').then(items('tv')), render: poster });
} else {
const label = kind === 'movie' ? 'Movies' : 'Series';
add({ title: `Trending ${label}`, load: () => tmdb.trending(kind, 'day').then(items(kind)), render: (it, i) => posterCard(it, { rank: i < 10 ? i + 1 : null }) });
if (kind === 'tv') add({ title: 'Networks', variant: 'logo', items: NETWORKS, render: networkCard, lazy: true });
add({ title: `Popular ${label}`, variant: 'wide', moreHref: href(`/browse/${kind}?title=${encodeURIComponent(`Popular ${label}`)}`), load: () => tmdb.popular(kind).then(items(kind)), render: (it) => wideCard(it) });
add({ title: `Top Rated ${label}`, load: () => tmdb.topRated(kind).then(items(kind)), render: poster });
if (kind === 'movie') {
add({ title: 'Now in Theaters', load: () => tmdb.get('/movie/now_playing', { page: 1 }, { session: true }).then(items('movie')), render: poster });
} else {
add({ title: 'Airing This Week', load: () => tmdb.get('/tv/on_the_air', { page: 1 }, { session: true }).then(items('tv')), render: poster });
}
}
(GENRES[kind || 'all']).forEach((g, i) => {
const more = href(`/browse/${g.type}?with_genres=${g.id}&title=${encodeURIComponent(g.name)}`);
add({
title: g.name,
moreHref: more,
variant: i % 3 === 1 ? 'wide' : 'poster',
load: () => tmdb.discover(g.type, { with_genres: g.id, 'vote_count.gte': 200 }).then(items(g.type)),
render: i % 3 === 1 ? (it) => wideCard(it) : poster,
});
});
return () => {
if (hero) hero.destroy();
listeners.forEach(([n, fn]) => window.removeEventListener(n, fn));
};
}
function networkCard(n) {
const card = logoCard({ name: n.name, logo: null, href: href(`/browse/tv?with_networks=${n.id}&title=${encodeURIComponent(n.name)}`) });
tmdb.network(n.id).then((d) => {
if (!d || !d.logo_path) return;
const media = card.querySelector('.card__media');
const im = h('img.card__logo', { src: tmdb.img(d.logo_path, 'w300'), alt: n.name, decoding: 'async' });
im.addEventListener('load', () => media.replaceChildren(im), { once: true });
}).catch(() => {});
return card;
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more