vega-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. vega_cli/__init__.py +1 -0
  2. vega_cli/__main__.py +6 -0
  3. vega_cli/cli.py +247 -0
  4. vega_cli/config.py +99 -0
  5. vega_cli/display.py +138 -0
  6. vega_cli/html.py +540 -0
  7. vega_cli/interactive.py +220 -0
  8. vega_cli/player.py +82 -0
  9. vega_cli/providers/__init__.py +13 -0
  10. vega_cli/providers/ani_dream.py +1089 -0
  11. vega_cli/providers/anikoto.py +820 -0
  12. vega_cli/providers/animesalt.py +649 -0
  13. vega_cli/providers/animesub.py +1374 -0
  14. vega_cli/providers/animeworld.py +504 -0
  15. vega_cli/providers/auto_embed.py +479 -0
  16. vega_cli/providers/castle.py +497 -0
  17. vega_cli/providers/cncverse.py +873 -0
  18. vega_cli/providers/common/__init__.py +51 -0
  19. vega_cli/providers/common/aes.py +152 -0
  20. vega_cli/providers/common/aniskip.py +186 -0
  21. vega_cli/providers/common/base_url.py +102 -0
  22. vega_cli/providers/common/cinemeta.py +231 -0
  23. vega_cli/providers/common/errors.py +25 -0
  24. vega_cli/providers/common/extractors/__init__.py +23 -0
  25. vega_cli/providers/common/extractors/abbasy.py +247 -0
  26. vega_cli/providers/common/extractors/buzzheavier.py +72 -0
  27. vega_cli/providers/common/extractors/cinejoy.py +33 -0
  28. vega_cli/providers/common/extractors/gdflix.py +170 -0
  29. vega_cli/providers/common/extractors/gofile.py +167 -0
  30. vega_cli/providers/common/extractors/hubcloud.py +277 -0
  31. vega_cli/providers/common/extractors/movy.py +349 -0
  32. vega_cli/providers/common/extractors/st111477.py +139 -0
  33. vega_cli/providers/common/extractors/transferit.py +53 -0
  34. vega_cli/providers/common/extractors/vegadrive.py +161 -0
  35. vega_cli/providers/common/extractors/vidstuck.py +379 -0
  36. vega_cli/providers/common/extractors/zcloud.py +158 -0
  37. vega_cli/providers/common/extractors/zypter.py +72 -0
  38. vega_cli/providers/common/headers.py +25 -0
  39. vega_cli/providers/common/http.py +121 -0
  40. vega_cli/providers/common/net_mirror.py +1494 -0
  41. vega_cli/providers/common/theintrodb.py +112 -0
  42. vega_cli/providers/common/unpack.py +54 -0
  43. vega_cli/providers/disney_mirror.py +31 -0
  44. vega_cli/providers/dramacool.py +297 -0
  45. vega_cli/providers/drive.py +695 -0
  46. vega_cli/providers/durbin_live.py +354 -0
  47. vega_cli/providers/eon_movies.py +752 -0
  48. vega_cli/providers/extraflix.py +701 -0
  49. vega_cli/providers/four_khdhub.py +307 -0
  50. vega_cli/providers/goku_hd.py +336 -0
  51. vega_cli/providers/hdhub4u.py +665 -0
  52. vega_cli/providers/internet_archive.py +552 -0
  53. vega_cli/providers/kartoons.py +642 -0
  54. vega_cli/providers/kartoons2.py +395 -0
  55. vega_cli/providers/katmovies.py +816 -0
  56. vega_cli/providers/kick_ass_anime.py +445 -0
  57. vega_cli/providers/kiss_kh.py +490 -0
  58. vega_cli/providers/live_tg_tv.py +540 -0
  59. vega_cli/providers/lux_movies.py +650 -0
  60. vega_cli/providers/mod.py +676 -0
  61. vega_cli/providers/movie_box_web.py +921 -0
  62. vega_cli/providers/movielinkdb.py +734 -0
  63. vega_cli/providers/movies4u.py +580 -0
  64. vega_cli/providers/moviezwap.py +199 -0
  65. vega_cli/providers/mxplayer.py +470 -0
  66. vega_cli/providers/netflix_mirror.py +32 -0
  67. vega_cli/providers/one_cinevood.py +596 -0
  68. vega_cli/providers/prime_mirror.py +31 -0
  69. vega_cli/providers/rareanimes.py +676 -0
  70. vega_cli/providers/registry.py +124 -0
  71. vega_cli/providers/showbox.py +245 -0
  72. vega_cli/providers/topmovies.py +707 -0
  73. vega_cli/providers/torrentio.py +398 -0
  74. vega_cli/providers/uhd.py +483 -0
  75. vega_cli/providers/vega.py +891 -0
  76. vega_cli/providers/youtube.py +566 -0
  77. vega_cli/providers/zeefliz.py +563 -0
  78. vega_cli/store.py +45 -0
  79. vega_cli/utils.py +90 -0
  80. vega_cli-0.1.0.dist-info/METADATA +8 -0
  81. vega_cli-0.1.0.dist-info/RECORD +84 -0
  82. vega_cli-0.1.0.dist-info/WHEEL +5 -0
  83. vega_cli-0.1.0.dist-info/entry_points.txt +2 -0
  84. vega_cli-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1374 @@
1
+ """Pure-Python implementation of the Vega 'animesub' provider."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from datetime import datetime, timezone
8
+ from typing import Any
9
+ from urllib.parse import quote, urlencode
10
+
11
+ from ..html import parse_html
12
+ from .common import (
13
+ COMMON_HEADERS,
14
+ BaseProvider,
15
+ apply_cinemeta_meta,
16
+ enrich_anime_episodes_with_skip_timings,
17
+ enrich_cinemeta_episodes,
18
+ enrich_episodes_with_skip_timings,
19
+ fetch_aniskip_timings,
20
+ fetch_theintrodb_skip_timings,
21
+ format_episode_title,
22
+ get_cinemeta_meta,
23
+ resolve_mal_id_from_title,
24
+ throw_provider_error,
25
+ )
26
+
27
+ _DEFAULT_TOKEN = "u_mFxNX2Pva_iYMF-kz9CsNA"
28
+ _DEFAULT_INSTANCE_URL = "https://animesub.duckdns.org"
29
+
30
+ _MAL_HEADERS = {
31
+ "User-Agent": (
32
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
33
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
34
+ ),
35
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
36
+ }
37
+
38
+ _ALL_TORRENT_SOURCES = (
39
+ "nyaa",
40
+ "animetosho",
41
+ "tokyoTosho",
42
+ "eraiRaws",
43
+ "seadex",
44
+ "nekobt",
45
+ "animegarden",
46
+ "tsukihimeDirect",
47
+ "mikan",
48
+ "dmhy",
49
+ "subsplease",
50
+ "anibt",
51
+ "acgrip",
52
+ "knaben",
53
+ "piratebay",
54
+ "torrentgalaxy",
55
+ "torlock",
56
+ "zilean",
57
+ "comet",
58
+ "stremthruTorz",
59
+ )
60
+
61
+ _LANGUAGE_CODES: tuple[tuple[str, str], ...] = (
62
+ ("MULTI", "MULTI"),
63
+ ("DUAL", "DUAL"),
64
+ ("JAPANESE", "JP"),
65
+ ("ENGLISH", "EN"),
66
+ ("HINDI", "HI"),
67
+ ("TAMIL", "TA"),
68
+ ("TELUGU", "TE"),
69
+ ("SPANISH", "ES"),
70
+ ("FRENCH", "FR"),
71
+ ("GERMAN", "DE"),
72
+ ("ITALIAN", "IT"),
73
+ ("KOREAN", "KO"),
74
+ ("CHINESE", "ZH"),
75
+ ("PORTUGUESE", "PT"),
76
+ ("RUSSIAN", "RU"),
77
+ )
78
+
79
+ _SUBTITLE_FIELD_RE = re.compile(
80
+ r"(?:[\U0001f4ac\U0001f5e8\U0001f5ef]\ufe0f?|\b(?:subs?|subtitles?)\s*:)\s*((?:[^\n\U0001f3a7\U0001f4ac\U0001f5e8\U0001f5ef]|\ufe0f)*)",
81
+ re.I | re.U,
82
+ )
83
+ _FLAG_RE = re.compile(r"[\U0001f1e6-\U0001f1ff]{2}")
84
+
85
+ _NON_UPLOADER_RE = re.compile(
86
+ r"^(\d+|[a-zA-Z]{1,2}|\d{3,4}p?|4k|uhd|bluray|bd|dvd|web(-?dl|-?rip)?|h\.?26[45]|x26[45]|hevc|av1|opus|flac|aac|ac3|dts|mp3|multi(-?audio|-?sub)?|dual(-?audio)?|sub(s|bed)?|dub(bed)?|audio|remux|hdr(10\+?)?|dv|dolby|hi10p?|10bit|8bit|v\d+|repack\d*|proper|raws?|es|lat|ger|ita|fra|eng?|jap?|batch|[0-9a-f]{8}|unofficial\s*batch)$",
87
+ re.I,
88
+ )
89
+ _SPEC_WORDS_RE = re.compile(
90
+ r"\b(1080p?|720p?|480p?|360p?|2160p?|4k|bd|bluray|hevc|x26[45]|h\.?26[45]|av1|aac|ac3|dts|mp3|flac|opus|dual-audio|multi-audio|sub|dub|web(-?dl|-?rip)?|remux|10-?bit|hi10p?)\b",
91
+ re.I,
92
+ )
93
+
94
+ _QUALITY_RANKS = {"2160": 5, "1080": 4, "720": 3, "480": 2, "360": 1}
95
+
96
+
97
+ def _clean_mal_image(src: str) -> str:
98
+ return re.sub(r"/r/\d+x\d+", "", src) if src else ""
99
+
100
+
101
+ def _flags_to_codes(text: str) -> list[str]:
102
+ codes: list[str] = []
103
+ for flag in _FLAG_RE.findall(text):
104
+ codes.append("".join(chr(65 + ord(ch) - 0x1F1E6) for ch in flag))
105
+ return codes
106
+
107
+
108
+ def _get_language_codes(title: str) -> str:
109
+ flag_codes = _flags_to_codes(title)
110
+ if flag_codes:
111
+ unique = list(dict.fromkeys(flag_codes))
112
+ return "MULTI" if len(unique) > 2 else ", ".join(unique)
113
+ upper = title.upper()
114
+ matches = [code for lang, code in _LANGUAGE_CODES if lang in upper]
115
+ return ", ".join(dict.fromkeys(matches)) if matches else "JA/EN"
116
+
117
+
118
+ def _subtitle_codes(field: str) -> list[str]:
119
+ out: list[str] = []
120
+ known_map = dict(_LANGUAGE_CODES)
121
+ for part in re.split(r"[,/|•·]+", field):
122
+ flags = _flags_to_codes(part)
123
+ if flags:
124
+ out.extend("ZH" if c == "CN" else c for c in flags)
125
+ continue
126
+ label = part.strip().upper()
127
+ if label in known_map:
128
+ out.append(known_map[label])
129
+ elif re.match(r"^[A-Z]{2,3}(?:-[A-Z]{2,8})*$", label):
130
+ out.append(label)
131
+ return out
132
+
133
+
134
+ def _format_bytes(num_bytes: float | int | None) -> str:
135
+ if not num_bytes or num_bytes <= 0:
136
+ return ""
137
+ gb = num_bytes / (1024 * 1024 * 1024)
138
+ if gb >= 1:
139
+ return f"{gb:.2f} GB"
140
+ mb = num_bytes / (1024 * 1024)
141
+ return f"{mb:.1f} MB"
142
+
143
+
144
+ def _extract_quality(text: str) -> str | None:
145
+ low = text.lower()
146
+ for q, tokens in (
147
+ ("2160", ("2160", "4k")),
148
+ ("1080", ("1080",)),
149
+ ("720", ("720",)),
150
+ ("480", ("480",)),
151
+ ("360", ("360",)),
152
+ ):
153
+ if any(t in low for t in tokens):
154
+ return q
155
+ return None
156
+
157
+
158
+ def _extract_format_tags(text: str) -> list[str]:
159
+ tags: list[str] = []
160
+ if re.search(r"AV1", text, re.I):
161
+ tags.append("AV1")
162
+ elif re.search(r"x265|HEVC", text, re.I):
163
+ tags.append("HEVC")
164
+ elif re.search(r"x264|AVC", text, re.I):
165
+ tags.append("AVC")
166
+
167
+ if re.search(r"10-?bit|hi10p?", text, re.I):
168
+ tags.append("10-bit")
169
+ if re.search(r"[\b\s.]DV[\b\s.]|Dolby\s*Vision", text, re.I):
170
+ tags.append("DV")
171
+ if re.search(r"[\b\s.]HDR(?:10(?:\+)?)?[\b\s.]", text, re.I):
172
+ tags.append("HDR")
173
+ if re.search(r"REMUX", text, re.I):
174
+ tags.append("Remux")
175
+ if re.search(r"BluRay|BD\b|BDRip", text, re.I):
176
+ tags.append("BluRay")
177
+ elif re.search(r"WEB-?DL|WEBRip", text, re.I):
178
+ tags.append("WEB-DL")
179
+ if re.search(r"Dual[\s-]Audio", text, re.I):
180
+ tags.append("Dual-Audio")
181
+ elif re.search(r"Multi[\s-]Audio", text, re.I):
182
+ tags.append("Multi-Audio")
183
+ return tags
184
+
185
+
186
+ def _extract_seeders(text: str, s: dict[str, Any] | None = None) -> tuple[str, int]:
187
+ if isinstance(s, dict):
188
+ if isinstance(s.get("seeders"), (int, float)) and s["seeders"] >= 0:
189
+ cnt = int(s["seeders"])
190
+ return f"👤{cnt}", cnt
191
+ bh = s.get("behaviorHints") or {}
192
+ if isinstance(bh.get("seeders"), (int, float)) and bh["seeders"] >= 0:
193
+ cnt = int(bh["seeders"])
194
+ return f"👤{cnt}", cnt
195
+ m = (
196
+ re.search(r"👤\s*(\d+)", text)
197
+ or re.search(r"\bS:\s*(\d+)", text, re.I)
198
+ or re.search(r"(\d+)\s*(?:seeds?|seeders?)", text, re.I)
199
+ )
200
+ if m:
201
+ cnt = int(m.group(1))
202
+ return f"👤{cnt}", cnt
203
+ return "", 0
204
+
205
+
206
+ def _extract_size_bytes(text: str, s: dict[str, Any] | None = None) -> tuple[str, float]:
207
+ if isinstance(s, dict):
208
+ bh = s.get("behaviorHints") or {}
209
+ raw = bh.get("videoSize") or bh.get("fileSize") or s.get("size")
210
+ if isinstance(raw, (int, float)) and raw > 0:
211
+ return _format_bytes(raw), float(raw)
212
+ m = re.search(r"(?:💾\s*)?([\d.]+)\s*(KB|MB|GB|TB)\b", text, re.I)
213
+ if m:
214
+ val = float(m.group(1))
215
+ unit = m.group(2).upper()
216
+ mult = {
217
+ "TB": 1024**4,
218
+ "GB": 1024**3,
219
+ "MB": 1024**2,
220
+ "KB": 1024,
221
+ }[unit]
222
+ return f"{m.group(1)} {unit}", val * mult
223
+ return "", 0.0
224
+
225
+
226
+ def _file_size_bytes(s: dict[str, Any]) -> int:
227
+ bh = s.get("behaviorHints") or {}
228
+ for val in (bh.get("fileSize"), s.get("fileSize")):
229
+ if isinstance(val, str) and val.strip().isdigit():
230
+ val = int(val.strip())
231
+ if isinstance(val, int) and val > 0:
232
+ return val
233
+ return 0
234
+
235
+
236
+ def _file_index(val: Any) -> int | None:
237
+ if isinstance(val, str) and val.strip().isdigit():
238
+ val = int(val.strip())
239
+ return val if isinstance(val, int) and val >= 0 else None
240
+
241
+
242
+ def _torrent_hash(s: dict[str, Any]) -> str:
243
+ h = s.get("infoHash")
244
+ if not h and isinstance(s.get("url"), str):
245
+ m = re.search(r"urn:btih:([a-f0-9]{40})", s["url"], re.I)
246
+ if m:
247
+ h = m.group(1)
248
+ return str(h or "").lower()
249
+
250
+
251
+ def _filename(s: dict[str, Any]) -> str:
252
+ fn = str((s.get("behaviorHints") or {}).get("filename") or "")
253
+ return re.split(r"[\\/]", fn)[-1].strip().lower()
254
+
255
+
256
+ def _is_uploader_candidate(val: str) -> bool:
257
+ if not val or len(val) <= 2:
258
+ return False
259
+ if _NON_UPLOADER_RE.match(val) or _SPEC_WORDS_RE.search(val):
260
+ return False
261
+ return True
262
+
263
+
264
+ def _extract_uploader(s: dict[str, Any]) -> str:
265
+ bh = s.get("behaviorHints") or {}
266
+ lines: list[str] = []
267
+ for raw in (bh.get("filename"), s.get("description"), s.get("title"), s.get("name")):
268
+ if raw:
269
+ for ln in str(raw).splitlines():
270
+ t = ln.strip()
271
+ if t:
272
+ lines.append(t)
273
+
274
+ for ln in lines:
275
+ m = re.match(r"^\[([a-zA-Z0-9_.\s@-]+)\]", ln)
276
+ if m:
277
+ val = m.group(1).lstrip("@").strip()
278
+ if _is_uploader_candidate(val):
279
+ return val
280
+
281
+ for ln in lines:
282
+ m = re.search(r"⚙️\s*([^\n\r]+)", ln)
283
+ if m:
284
+ val = m.group(1).lstrip("@").strip()
285
+ if _is_uploader_candidate(val):
286
+ return val
287
+
288
+ for ln in lines:
289
+ cleaned = re.sub(r"(\s*\[[^\]]*\]|\s*\([^)]*\))+$", "", ln)
290
+ cleaned = re.sub(r"\.(mkv|mp4|avi|webm|ts)$", "", cleaned, flags=re.I).strip()
291
+ m = re.search(r"[-_–]\s*@?([a-zA-Z0-9_]+(?:-[a-zA-Z0-9_]+)?)$", cleaned)
292
+ if m and _is_uploader_candidate(m.group(1).strip()):
293
+ return m.group(1).strip()
294
+
295
+ for ln in lines:
296
+ for m in re.finditer(r"\[([a-zA-Z0-9_.\s@-]+)\]", ln):
297
+ val = m.group(1).lstrip("@").strip()
298
+ if _is_uploader_candidate(val):
299
+ return val
300
+
301
+ return "AnimeSub+"
302
+
303
+
304
+ def _is_quality_allowed(q: str | None, quality_filter: str) -> bool:
305
+ if not q or not quality_filter or quality_filter == "all":
306
+ return True
307
+ if quality_filter == "720":
308
+ return q in ("720", "480", "360")
309
+ if quality_filter == "1080":
310
+ return q in ("1080", "720", "480", "360")
311
+ if quality_filter == "480":
312
+ return q in ("480", "360")
313
+ return True
314
+
315
+
316
+ def _is_future_release(release_str: str | None) -> bool:
317
+ if not release_str:
318
+ return False
319
+ try:
320
+ dt = datetime.fromisoformat(release_str.replace("Z", "+00:00"))
321
+ return dt.timestamp() > datetime.now(timezone.utc).timestamp()
322
+ except Exception:
323
+ return False
324
+
325
+
326
+ class AnimesubClient(BaseProvider):
327
+ """Pure-Python implementation of the Vega 'animesub' provider."""
328
+
329
+ name = "animesub"
330
+ catalog = [
331
+ {"title": "Top Airing", "filter": "mal:topanime:airing"},
332
+ {"title": "Current Season", "filter": "mal:season:current"},
333
+ {"title": "Most Popular", "filter": "mal:topanime:bypopularity"},
334
+ {"title": "Most Favorited", "filter": "mal:topanime:favorite"},
335
+ ]
336
+ genres = [
337
+ {"title": "Action", "filter": "mal:genre:1:Action"},
338
+ {"title": "Adventure", "filter": "mal:genre:2:Adventure"},
339
+ {"title": "Comedy", "filter": "mal:genre:4:Comedy"},
340
+ {"title": "Drama", "filter": "mal:genre:8:Drama"},
341
+ {"title": "Fantasy", "filter": "mal:genre:10:Fantasy"},
342
+ {"title": "Horror", "filter": "mal:genre:14:Horror"},
343
+ {"title": "Mystery", "filter": "mal:genre:7:Mystery"},
344
+ {"title": "Psychological", "filter": "mal:genre:40:Psychological"},
345
+ {"title": "Romance", "filter": "mal:genre:22:Romance"},
346
+ {"title": "Sci-Fi", "filter": "mal:genre:24:Sci-Fi"},
347
+ {"title": "Slice of Life", "filter": "mal:genre:36:Slice_of_Life"},
348
+ {"title": "Supernatural", "filter": "mal:genre:37:Supernatural"},
349
+ {"title": "Sports", "filter": "mal:genre:30:Sports"},
350
+ {"title": "Suspense", "filter": "mal:genre:41:Suspense"},
351
+ ]
352
+ settings_schema = [
353
+ {
354
+ "key": "animesub_manifestUrl",
355
+ "type": "text",
356
+ "label": "Custom Manifest URL",
357
+ "description": (
358
+ "Optional: Paste your configured AnimeSub+ manifest URL "
359
+ "(from https://animesub.duckdns.org/configure)"
360
+ ),
361
+ "placeholder": "https://animesub.duckdns.org/u_.../manifest.json",
362
+ "defaultValue": "",
363
+ },
364
+ {
365
+ "key": "animesub_debridService",
366
+ "type": "select",
367
+ "label": "Debrid Provider",
368
+ "description": (
369
+ "Select your premium debrid service for high-speed streaming without P2P seeding"
370
+ ),
371
+ "options": [
372
+ {"label": "None (Direct Torrent / P2P)", "value": "none"},
373
+ {"label": "Real-Debrid", "value": "realdebrid"},
374
+ {"label": "AllDebrid", "value": "alldebrid"},
375
+ {"label": "Premiumize", "value": "premiumize"},
376
+ {"label": "TorBox", "value": "torbox"},
377
+ {"label": "Debrid-Link", "value": "debridlink"},
378
+ ],
379
+ "defaultValue": "none",
380
+ },
381
+ {
382
+ "key": "animesub_debridApiKey",
383
+ "type": "text",
384
+ "label": "Debrid API Key / Token",
385
+ "description": (
386
+ "Your API token from your Debrid provider account (leave empty for regular torrents)"
387
+ ),
388
+ "placeholder": "e.g. your_debrid_api_token",
389
+ "defaultValue": "",
390
+ },
391
+ {
392
+ "key": "animesub_qualityFilter",
393
+ "type": "select",
394
+ "label": "Resolution Filter",
395
+ "description": "Limit results to maximum or specific qualities",
396
+ "options": [
397
+ {"label": "All Qualities (4K, 1080p, 720p, 480p)", "value": "all"},
398
+ {"label": "Up to 4K / 2160p", "value": "2160"},
399
+ {"label": "Up to 1080p (Exclude 4K)", "value": "1080"},
400
+ {"label": "Up to 720p (Exclude 4K & 1080p)", "value": "720"},
401
+ {"label": "480p SD only", "value": "480"},
402
+ ],
403
+ "defaultValue": "all",
404
+ },
405
+ {
406
+ "key": "animesub_sortBy",
407
+ "type": "select",
408
+ "label": "Sort Stream Results By",
409
+ "description": "Prioritize results order in player stream list",
410
+ "options": [
411
+ {"label": "Quality then Seeders (Default)", "value": "qualitythenseeders"},
412
+ {"label": "Seeders (Most seeds first)", "value": "seeders"},
413
+ {"label": "File Size (Largest first)", "value": "size"},
414
+ ],
415
+ "defaultValue": "qualitythenseeders",
416
+ },
417
+ {
418
+ "key": "animesub_instanceUrl",
419
+ "type": "text",
420
+ "label": "AnimeSub+ Server URL",
421
+ "description": "AnimeSub+ instance host (default: https://animesub.duckdns.org)",
422
+ "placeholder": "https://animesub.duckdns.org",
423
+ "defaultValue": "https://animesub.duckdns.org",
424
+ },
425
+ {
426
+ "key": "animesub_enableP2P",
427
+ "type": "toggle",
428
+ "label": "Enable P2P Fallback",
429
+ "description": (
430
+ "Include raw P2P torrent links when Debrid has not cached the file or when no Debrid is used"
431
+ ),
432
+ "defaultValue": True,
433
+ },
434
+ {
435
+ "key": "animesub_skipTimings",
436
+ "type": "toggle",
437
+ "label": "Skip Timings",
438
+ "description": (
439
+ "Automatically fetch intro and recap skip timestamps from TheIntroDB for verified anime episodes"
440
+ ),
441
+ "defaultValue": True,
442
+ },
443
+ ]
444
+
445
+ def _parse_mal_top_anime(self, html: str) -> list[dict[str, str]]:
446
+ doc = parse_html(html)
447
+ posts: list[dict[str, str]] = []
448
+ for el in doc.select("tr.ranking-list"):
449
+ title_el = el.select_one(".anime_ranking_h3 a, h3 a")
450
+ title = title_el.text().strip() if title_el else ""
451
+ mal_url = title_el.attr("href") if title_el else ""
452
+ m_id = re.search(r"anime/(\d+)", mal_url)
453
+ if not title or not m_id:
454
+ continue
455
+ mal_id = m_id.group(1)
456
+ img_el = el.select_one("td.title img, .hoverinfo_trigger img")
457
+ raw_img = (img_el.attr("data-src") or img_el.attr("src")) if img_el else ""
458
+ image = _clean_mal_image(raw_img)
459
+ sc_el = el.select_one(".score span")
460
+ score = sc_el.text().strip() if sc_el else ""
461
+ post: dict[str, str] = {
462
+ "title": title,
463
+ "link": json.dumps({"malId": mal_id, "title": title, "image": image, "type": "series"}),
464
+ "image": image,
465
+ }
466
+ if score and score != "N/A":
467
+ post["tag"] = f"{score}★"
468
+ posts.append(post)
469
+ return posts
470
+
471
+ def _parse_mal_seasonal_cards(self, html: str) -> list[dict[str, str]]:
472
+ doc = parse_html(html)
473
+ posts: list[dict[str, str]] = []
474
+ for el in doc.select(".seasonal-anime"):
475
+ title_el = el.select_one(".title a.link-title, .title-text .link-title")
476
+ title = title_el.text().strip() if title_el else ""
477
+ mal_url = title_el.attr("href") if title_el else ""
478
+ m_id = re.search(r"anime/(\d+)", mal_url)
479
+ if not title or not m_id:
480
+ continue
481
+ mal_id = m_id.group(1)
482
+ img_el = el.select_one(".image img")
483
+ raw_img = (img_el.attr("data-src") or img_el.attr("src")) if img_el else ""
484
+ image = _clean_mal_image(raw_img)
485
+ sc_el = el.select_one(".score")
486
+ score = sc_el.text().strip() if sc_el else ""
487
+ post: dict[str, str] = {
488
+ "title": title,
489
+ "link": json.dumps({"malId": mal_id, "title": title, "image": image, "type": "series"}),
490
+ "image": image,
491
+ }
492
+ if score and score != "N/A":
493
+ post["tag"] = f"{score}★"
494
+ posts.append(post)
495
+ return posts
496
+
497
+ def _fetch_kitsu_fallback_posts(self, filter_path: str, page: int) -> list[dict[str, str]]:
498
+ try:
499
+ skip_param = f"&skip={(page - 1) * 20}" if page > 1 else ""
500
+ filter_with_skip = filter_path.replace(".json", f"{skip_param}.json")
501
+ base = "" if filter_path.startswith("http") else "https://anime-kitsu.strem.fun"
502
+ data = self.fetch_json(f"{base}{filter_with_skip}", headers=COMMON_HEADERS, timeout=10) or {}
503
+ posts: list[dict[str, str]] = []
504
+ for res in data.get("metas") or []:
505
+ kid = res.get("id")
506
+ if not kid:
507
+ continue
508
+ rating = res.get("kitsuRating") or res.get("rating")
509
+ post: dict[str, str] = {
510
+ "title": res.get("name") or "",
511
+ "link": f"https://anime-kitsu.strem.fun/meta/anime/{kid}.json",
512
+ "image": res.get("poster") or "",
513
+ }
514
+ if rating:
515
+ post["tag"] = f"{rating}★"
516
+ posts.append(post)
517
+ return posts
518
+ except Exception:
519
+ return []
520
+
521
+ def get_posts(self, filter_path: str = "", page: int = 1) -> list[dict[str, str]]:
522
+ try:
523
+ if filter_path.startswith("mal:topanime:"):
524
+ cat_type = filter_path.replace("mal:topanime:", "").strip()
525
+ offset = (page - 1) * 50
526
+ html = self.fetch_text(
527
+ f"https://myanimelist.net/topanime.php?type={cat_type}&limit={offset}",
528
+ headers=_MAL_HEADERS,
529
+ timeout=10,
530
+ )
531
+ return self._parse_mal_top_anime(html)
532
+
533
+ if filter_path == "mal:season:current":
534
+ html = self.fetch_text(
535
+ "https://myanimelist.net/anime/season", headers=_MAL_HEADERS, timeout=10
536
+ )
537
+ all_seasonal = self._parse_mal_seasonal_cards(html)
538
+ start = (page - 1) * 25
539
+ return all_seasonal[start : start + 25]
540
+
541
+ if filter_path.startswith("mal:genre:"):
542
+ parts = filter_path.split(":")
543
+ genre_id = parts[2]
544
+ genre_name = parts[3] if len(parts) > 3 and parts[3] else "Action"
545
+ html = self.fetch_text(
546
+ f"https://myanimelist.net/anime/genre/{genre_id}/{genre_name}?page={page}",
547
+ headers=_MAL_HEADERS,
548
+ timeout=10,
549
+ )
550
+ return self._parse_mal_seasonal_cards(html)
551
+
552
+ return self._fetch_kitsu_fallback_posts(filter_path, page)
553
+ except Exception:
554
+ return self._fetch_kitsu_fallback_posts(filter_path, page)
555
+
556
+ def get_search_posts(self, query: str, page: int = 1) -> list[dict[str, str]]:
557
+ try:
558
+ if page > 1:
559
+ return []
560
+ html = self.fetch_text(
561
+ f"https://myanimelist.net/anime.php?q={quote(query)}",
562
+ headers=_MAL_HEADERS,
563
+ timeout=10,
564
+ )
565
+ doc = parse_html(html)
566
+ tables = doc.select("table")
567
+ posts: list[dict[str, str]] = []
568
+ seen_titles: set[str] = set()
569
+ if len(tables) > 1:
570
+ for idx, row in enumerate(tables[1].select("tr")):
571
+ if idx == 0:
572
+ continue
573
+ t_el = row.select_one("a.hoverinfo_trigger strong, strong")
574
+ a_el = row.select_one("a.hoverinfo_trigger")
575
+ title = (t_el.text().strip() if t_el else "") or (
576
+ a_el.text().strip() if a_el else ""
577
+ )
578
+ href = a_el.attr("href") if a_el else ""
579
+ m_id = re.search(r"anime/(\d+)", href)
580
+ if not title or not m_id:
581
+ continue
582
+ mal_id = m_id.group(1)
583
+ img_el = row.select_one("img")
584
+ raw_img = (img_el.attr("data-src") or img_el.attr("src")) if img_el else ""
585
+ image = _clean_mal_image(raw_img)
586
+ sc_el = row.select_one("td:nth-child(5)")
587
+ score = sc_el.text().strip() if sc_el else ""
588
+ if title.lower() not in seen_titles:
589
+ seen_titles.add(title.lower())
590
+ post: dict[str, str] = {
591
+ "title": title,
592
+ "link": json.dumps(
593
+ {"malId": mal_id, "title": title, "image": image, "type": "series"}
594
+ ),
595
+ "image": image,
596
+ }
597
+ if score and score != "N/A":
598
+ post["tag"] = f"{score}★"
599
+ posts.append(post)
600
+ if posts:
601
+ return posts
602
+ except Exception:
603
+ pass
604
+
605
+ try:
606
+ data = (
607
+ self.fetch_json(
608
+ f"https://anime-kitsu.strem.fun/catalog/anime/kitsu-anime-list/search={quote(query)}.json",
609
+ headers=COMMON_HEADERS,
610
+ timeout=10,
611
+ )
612
+ or {}
613
+ )
614
+ posts = []
615
+ seen_ids: set[str] = set()
616
+ for res in data.get("metas") or []:
617
+ kid = res.get("id")
618
+ if not kid or kid in seen_ids:
619
+ continue
620
+ seen_ids.add(kid)
621
+ rating = res.get("kitsuRating") or res.get("rating")
622
+ post = {
623
+ "title": res.get("name") or "",
624
+ "link": f"https://anime-kitsu.strem.fun/meta/anime/{kid}.json",
625
+ "image": res.get("poster") or "",
626
+ }
627
+ if rating:
628
+ post["tag"] = f"{rating}★"
629
+ posts.append(post)
630
+ return posts
631
+ except Exception:
632
+ return []
633
+
634
+ def _resolve_kitsu_id_from_mal(self, mal_id: str) -> str | None:
635
+ clean = str(mal_id).strip()
636
+ if not clean.isdigit():
637
+ return None
638
+ try:
639
+ data = self.fetch_json(
640
+ f"https://kitsu.io/api/edge/mappings?filter[externalSite]=myanimelist/anime&filter[externalId]={clean}&include=item",
641
+ headers={"Accept": "application/vnd.api+json"},
642
+ timeout=5,
643
+ )
644
+ included = (data or {}).get("included") or []
645
+ for item in included:
646
+ if item.get("type") == "anime" and item.get("id"):
647
+ return f"kitsu:{item['id']}"
648
+ except Exception:
649
+ pass
650
+ return None
651
+
652
+ def _skip_timings_enabled(self) -> bool:
653
+ val = self.kv.get("animesub_skipTimings")
654
+ if val is None:
655
+ val = self.kv.get("torrentio_skipTimings")
656
+ return True if val is None else bool(val)
657
+
658
+ def _get_cinemeta_info(self, link: str) -> dict[str, Any]:
659
+ m_imdb = re.search(r"tt\d+", link)
660
+ imdb_id = m_imdb.group(0) if m_imdb else ""
661
+ media_type = "series" if re.search(r"\bseries\b", link, re.I) else "movie"
662
+ if not imdb_id:
663
+ raise ValueError(f"Missing IMDb ID in link: {link}")
664
+
665
+ meta = get_cinemeta_meta(imdb_id, media_type, session=self.session)
666
+ if not meta:
667
+ return {
668
+ "title": imdb_id,
669
+ "synopsis": "",
670
+ "image": "",
671
+ "imdbId": imdb_id,
672
+ "type": media_type,
673
+ "linkList": [],
674
+ }
675
+
676
+ link_list: list[dict[str, Any]] = []
677
+ if media_type == "series":
678
+ seasons: dict[int, list[dict[str, Any]]] = {}
679
+ for video in meta.get("videos") or []:
680
+ ep = video.get("episode") or video.get("number")
681
+ s_num = video.get("season")
682
+ if not s_num or s_num <= 0 or not ep:
683
+ continue
684
+ if _is_future_release(video.get("released") or video.get("firstAired")):
685
+ continue
686
+ vid_parts = str(video.get("id") or "").split(":")
687
+ payload = json.dumps(
688
+ {
689
+ "title": meta.get("name") or "",
690
+ "imdbId": imdb_id,
691
+ "season": str(s_num or (vid_parts[1] if len(vid_parts) > 1 else "")),
692
+ "episode": str(ep or (vid_parts[2] if len(vid_parts) > 2 else "")),
693
+ "type": "series",
694
+ "tmdbId": str(meta.get("moviedb_id") or ""),
695
+ "year": meta.get("year"),
696
+ }
697
+ )
698
+ seasons.setdefault(int(s_num), []).append(
699
+ {"title": format_episode_title(ep, video.get("name")), "link": payload}
700
+ )
701
+
702
+ skip_enabled = self._skip_timings_enabled()
703
+ for season_num in sorted(seasons):
704
+ eps = enrich_cinemeta_episodes(
705
+ seasons[season_num], meta.get("videos") or [], season_num
706
+ )
707
+ if skip_enabled:
708
+ eps = enrich_episodes_with_skip_timings(
709
+ eps, imdb_id, season_num, session=self.session
710
+ )
711
+ link_list.append({"title": f"Season {season_num}", "directLinks": eps})
712
+ else:
713
+ link_list.append(
714
+ {
715
+ "title": meta.get("name") or "Movie",
716
+ "directLinks": [
717
+ {
718
+ "title": "Movie",
719
+ "type": "movie",
720
+ "link": json.dumps(
721
+ {
722
+ "title": meta.get("name") or "",
723
+ "imdbId": imdb_id,
724
+ "season": "",
725
+ "episode": "",
726
+ "type": "movie",
727
+ "tmdbId": str(meta.get("moviedb_id") or ""),
728
+ "year": meta.get("year"),
729
+ }
730
+ ),
731
+ }
732
+ ],
733
+ }
734
+ )
735
+
736
+ return apply_cinemeta_meta(
737
+ {
738
+ "title": meta.get("name") or "",
739
+ "synopsis": meta.get("description") or "",
740
+ "image": meta.get("background") or meta.get("poster") or "",
741
+ "poster": meta.get("poster") or "",
742
+ "imdbId": imdb_id or meta.get("imdb_id") or "",
743
+ "type": media_type,
744
+ "linkList": link_list,
745
+ },
746
+ meta,
747
+ )
748
+
749
+ def _get_kitsu_info(self, kitsu_id: str, mal_id: str | None = None) -> dict[str, Any]:
750
+ data = self.fetch_json(
751
+ f"https://anime-kitsu.strem.fun/meta/anime/{kitsu_id}.json",
752
+ headers=COMMON_HEADERS,
753
+ timeout=10,
754
+ )
755
+ meta = (data or {}).get("meta")
756
+ if not meta:
757
+ raise ValueError(f"Failed to load Kitsu meta for {kitsu_id}")
758
+
759
+ videos = meta.get("videos") or []
760
+ is_movie = (
761
+ meta.get("type") == "movie"
762
+ or meta.get("animeType") == "movie"
763
+ or (
764
+ len(videos) <= 1
765
+ and bool(meta.get("runtime"))
766
+ and not (videos and videos[0].get("episode"))
767
+ )
768
+ )
769
+
770
+ link_list: list[dict[str, Any]] = []
771
+ skip_enabled = self._skip_timings_enabled()
772
+
773
+ if is_movie:
774
+ v0 = videos[0] if videos else {}
775
+ imdb_id = v0.get("imdb_id") or meta.get("imdb_id") or ""
776
+ link_list.append(
777
+ {
778
+ "title": meta.get("name") or "Movie",
779
+ "directLinks": [
780
+ {
781
+ "title": "Movie",
782
+ "type": "movie",
783
+ "link": json.dumps(
784
+ {
785
+ "title": meta.get("name"),
786
+ "kitsuId": v0.get("id") or meta.get("id"),
787
+ "imdbId": imdb_id,
788
+ "type": "movie",
789
+ }
790
+ ),
791
+ }
792
+ ],
793
+ }
794
+ )
795
+ else:
796
+ seasons: dict[int, list[dict[str, Any]]] = {}
797
+ for video in videos:
798
+ anime_ep = video.get("episode") or video.get("number") or 1
799
+ imdb_season = video.get("imdbSeason")
800
+ season_num = (
801
+ int(imdb_season)
802
+ if imdb_season and str(imdb_season).isdigit() and int(imdb_season) > 0
803
+ else int(video.get("season") or 1)
804
+ )
805
+ imdb_ep = video.get("imdbEpisode")
806
+ ep_num = (
807
+ int(imdb_ep)
808
+ if imdb_ep and str(imdb_ep).isdigit() and int(imdb_ep) > 0
809
+ else int(anime_ep)
810
+ )
811
+ if _is_future_release(video.get("released")):
812
+ continue
813
+
814
+ ep_title = (
815
+ format_episode_title(ep_num, video["title"])
816
+ if video.get("title")
817
+ else f"Episode {ep_num}"
818
+ )
819
+ imdb_id = video.get("imdb_id") or meta.get("imdb_id") or ""
820
+ ep_entry: dict[str, Any] = {
821
+ "title": ep_title,
822
+ "link": json.dumps(
823
+ {
824
+ "title": meta.get("name"),
825
+ "kitsuId": video.get("id") or f"{meta.get('id')}:{anime_ep}",
826
+ "malId": mal_id,
827
+ "animeEpisode": str(anime_ep),
828
+ "imdbId": imdb_id,
829
+ "season": str(season_num),
830
+ "episode": str(ep_num),
831
+ "type": "series",
832
+ }
833
+ ),
834
+ }
835
+ if video.get("overview"):
836
+ ep_entry["description"] = video["overview"]
837
+ if video.get("thumbnail"):
838
+ ep_entry["image"] = video["thumbnail"]
839
+ seasons.setdefault(season_num, []).append(ep_entry)
840
+
841
+ for season_num in sorted(seasons):
842
+ direct_links = seasons[season_num]
843
+ season_imdb = meta.get("imdb_id")
844
+ for d in direct_links:
845
+ try:
846
+ cand = json.loads(d["link"]).get("imdbId")
847
+ if cand:
848
+ season_imdb = cand
849
+ break
850
+ except Exception:
851
+ pass
852
+ if skip_enabled:
853
+ direct_links = enrich_anime_episodes_with_skip_timings(
854
+ direct_links,
855
+ kitsu_id=kitsu_id,
856
+ mal_id=mal_id,
857
+ title=meta.get("name"),
858
+ imdb_id=season_imdb,
859
+ season=season_num,
860
+ session=self.session,
861
+ )
862
+ link_list.append({"title": f"Season {season_num}", "directLinks": direct_links})
863
+
864
+ res: dict[str, Any] = {
865
+ "title": meta.get("name") or "",
866
+ "synopsis": meta.get("description") or "",
867
+ "image": meta.get("background") or meta.get("poster") or "",
868
+ "poster": meta.get("poster") or "",
869
+ "imdbId": meta.get("imdb_id") or "",
870
+ "type": "movie" if is_movie else "series",
871
+ "linkList": link_list,
872
+ }
873
+ if meta.get("logo"):
874
+ res["logo"] = meta["logo"]
875
+ if meta.get("genres"):
876
+ res["tags"] = meta["genres"]
877
+ if meta.get("imdbRating") or meta.get("kitsuRating"):
878
+ res["rating"] = meta.get("imdbRating") or meta.get("kitsuRating")
879
+ return res
880
+
881
+ def _get_mal_info(self, mal_id: str, title: str | None = None) -> dict[str, Any]:
882
+ kitsu_id = self._resolve_kitsu_id_from_mal(mal_id)
883
+ if not kitsu_id and title:
884
+ try:
885
+ res = self.fetch_json(
886
+ f"https://kitsu.io/api/edge/anime?filter[text]={quote(title)}&page[limit]=1",
887
+ headers={"Accept": "application/vnd.api+json"},
888
+ timeout=6,
889
+ )
890
+ raw_id = ((res or {}).get("data") or [{}])[0].get("id")
891
+ if raw_id:
892
+ kitsu_id = f"kitsu:{raw_id}"
893
+ except Exception:
894
+ pass
895
+
896
+ if kitsu_id:
897
+ if not kitsu_id.startswith("kitsu:"):
898
+ kitsu_id = f"kitsu:{kitsu_id}"
899
+ return self._get_kitsu_info(kitsu_id, mal_id=mal_id)
900
+
901
+ if title:
902
+ try:
903
+ c_res = self.fetch_json(
904
+ f"https://v3-cinemeta.strem.io/catalog/series/top/search={quote(title)}.json",
905
+ timeout=6,
906
+ )
907
+ imdb_id = ((c_res or {}).get("metas") or [{}])[0].get("imdb_id")
908
+ if imdb_id:
909
+ return self._get_cinemeta_info(imdb_id)
910
+ except Exception:
911
+ pass
912
+
913
+ raise ValueError(f"Failed to resolve metadata for MAL ID {mal_id}")
914
+
915
+ def get_meta(self, link: str) -> dict[str, Any]:
916
+ try:
917
+ mal_id: str | None = None
918
+ title: str | None = None
919
+ try:
920
+ parsed = json.loads(link)
921
+ if isinstance(parsed, dict):
922
+ if parsed.get("malId"):
923
+ mal_id = str(parsed["malId"])
924
+ if parsed.get("title"):
925
+ title = str(parsed["title"])
926
+ except Exception:
927
+ m_mal = re.search(r"mal:(\d+)", link) or re.search(
928
+ r"myanimelist\.net/anime/(\d+)", link
929
+ )
930
+ if m_mal:
931
+ mal_id = m_mal.group(1)
932
+
933
+ if mal_id:
934
+ return self._get_mal_info(mal_id, title)
935
+
936
+ m_kitsu = re.search(r"kitsu:(\d+)", link)
937
+ if m_kitsu:
938
+ return self._get_kitsu_info(m_kitsu.group(0))
939
+
940
+ return self._get_cinemeta_info(link)
941
+ except Exception as err:
942
+ throw_provider_error("AnimeSub", "metadata", err)
943
+ return {}
944
+
945
+ def _register_debrid_config(
946
+ self, instance_url: str, service: str, api_key: str, enable_p2p: bool
947
+ ) -> str | None:
948
+ try:
949
+ config_url = f"{instance_url}/configure"
950
+ html = self.fetch_text(config_url, timeout=8)
951
+ doc = parse_html(html)
952
+ form = doc.select_one("#configForm")
953
+ fields: list[tuple[str, str]] = []
954
+ if form:
955
+ for el in form.select("input, select, textarea"):
956
+ fname = el.attr("name")
957
+ if not fname:
958
+ continue
959
+ ftype = el.attr("type").lower()
960
+ val = el.attr("value")
961
+ if el.tag == "select":
962
+ opt = el.select_one("option[selected]") or el.select_one("option")
963
+ val = opt.attr("value") if opt else ""
964
+ elif el.tag == "textarea":
965
+ val = el.text()
966
+ if ftype == "checkbox":
967
+ if "checked" in el.attrs:
968
+ fields.append((fname, val or "on"))
969
+ elif ftype == "radio":
970
+ if "checked" in el.attrs:
971
+ fields.append((fname, val))
972
+ else:
973
+ fields.append((fname, val))
974
+
975
+ def _set_field(k: str, v: str) -> None:
976
+ nonlocal fields
977
+ fields = [(fk, fv) for fk, fv in fields if fk != k]
978
+ fields.append((k, v))
979
+
980
+ def _del_field(k: str) -> None:
981
+ nonlocal fields
982
+ fields = [(fk, fv) for fk, fv in fields if fk != k]
983
+
984
+ if enable_p2p:
985
+ _set_field("enableP2P", "on")
986
+ _del_field("hideUncached")
987
+ else:
988
+ _del_field("enableP2P")
989
+ _set_field("hideUncached", "on")
990
+
991
+ if service and service != "none":
992
+ _set_field("service[]", service)
993
+ _set_field("apiKey[]", api_key)
994
+
995
+ existing_srcs = {fv for fk, fv in fields if fk == "torrentSources[]"}
996
+ for src in _ALL_TORRENT_SOURCES:
997
+ if src not in existing_srcs:
998
+ fields.append(("torrentSources[]", src))
999
+
1000
+ post_html = self.fetch_text(
1001
+ config_url,
1002
+ method="POST",
1003
+ data=urlencode(fields),
1004
+ headers={
1005
+ "Content-Type": "application/x-www-form-urlencoded",
1006
+ "Referer": config_url,
1007
+ },
1008
+ timeout=8,
1009
+ )
1010
+ m_tok = re.search(r"/(u_[a-zA-Z0-9_-]+)(?:/manifest\.json|/stream)", post_html)
1011
+ if m_tok:
1012
+ return m_tok.group(1)
1013
+ except Exception:
1014
+ pass
1015
+ return None
1016
+
1017
+ def _resolve_token_and_base_url(self) -> tuple[str, str]:
1018
+ custom_manifest = (
1019
+ self.kv.get("animesub_manifestUrl") or self.kv.get("customManifestUrl") or ""
1020
+ )
1021
+ inst = self.kv.get("animesub_instanceUrl") or self.kv.get("customInstanceUrl")
1022
+ instance_url = (
1023
+ str(inst).strip().rstrip("/")
1024
+ if isinstance(inst, str) and inst.strip()
1025
+ else _DEFAULT_INSTANCE_URL
1026
+ )
1027
+ debrid_service = (
1028
+ self.kv.get("animesub_debridService") or self.kv.get("debridService") or "none"
1029
+ )
1030
+ debrid_api_key = str(
1031
+ self.kv.get("animesub_debridApiKey") or self.kv.get("debridApiKey") or ""
1032
+ ).strip()
1033
+ p2p_val = self.kv.get("animesub_enableP2P")
1034
+ if p2p_val is None:
1035
+ p2p_val = self.kv.get("enableP2P")
1036
+ enable_p2p = True if p2p_val is None else bool(p2p_val)
1037
+
1038
+ if custom_manifest:
1039
+ clean = re.sub(r"^stremio://", "https://", str(custom_manifest).strip(), flags=re.I)
1040
+ m = re.match(r"^(https?://[^/]+)/(u_[a-zA-Z0-9_-]+)", clean)
1041
+ if m:
1042
+ return m.group(1), m.group(2)
1043
+
1044
+ if debrid_service != "none" and debrid_api_key:
1045
+ cache_key = f"animesub_token_{debrid_service}_{debrid_api_key[:10]}_{enable_p2p}"
1046
+ cached = self.kv.get(cache_key)
1047
+ if not cached:
1048
+ cached = self._register_debrid_config(
1049
+ instance_url, str(debrid_service), debrid_api_key, enable_p2p
1050
+ )
1051
+ if cached:
1052
+ self.kv.set(cache_key, cached)
1053
+ if cached:
1054
+ return instance_url, str(cached)
1055
+
1056
+ return instance_url, _DEFAULT_TOKEN
1057
+
1058
+ def _get_episode_file_sizes(
1059
+ self, streams: list[dict[str, Any]], imdb_id: str, season: str, episode: str
1060
+ ) -> dict[int, tuple[str, float]]:
1061
+ sizes: dict[int, tuple[str, float]] = {}
1062
+ for idx, s in enumerate(streams):
1063
+ b = _file_size_bytes(s)
1064
+ if b:
1065
+ sizes[idx] = (_format_bytes(b), float(b))
1066
+ if not (re.match(r"^tt\d+$", imdb_id) and season.isdigit() and episode.isdigit()):
1067
+ return sizes
1068
+ if not any(_torrent_hash(s) and idx not in sizes for idx, s in enumerate(streams)):
1069
+ return sizes
1070
+
1071
+ try:
1072
+ data = self.fetch_json(
1073
+ f"https://torrentio.strem.fun/stream/series/{imdb_id}:{season}:{episode}.json",
1074
+ headers=COMMON_HEADERS,
1075
+ timeout=5,
1076
+ )
1077
+ candidates = (data or {}).get("streams") or []
1078
+ for idx, s in enumerate(streams):
1079
+ if idx in sizes:
1080
+ continue
1081
+ h = _torrent_hash(s)
1082
+ if not h:
1083
+ continue
1084
+ s_fidx = _file_index(s.get("fileIdx"))
1085
+ s_name = _filename(s)
1086
+ matches = []
1087
+ for cand in candidates:
1088
+ if _torrent_hash(cand) != h:
1089
+ continue
1090
+ c_fidx = _file_index(cand.get("fileIdx"))
1091
+ if s_fidx is not None and c_fidx is not None:
1092
+ if s_fidx == c_fidx:
1093
+ matches.append(cand)
1094
+ elif re.search(r"\.(mkv|mp4|avi|webm|m4v|ts)$", s_name, re.I) and s_name == _filename(cand):
1095
+ matches.append(cand)
1096
+ for sel in matches:
1097
+ b = _file_size_bytes(sel)
1098
+ if b:
1099
+ sizes[idx] = (_format_bytes(b), float(b))
1100
+ break
1101
+ lbl, sz = _extract_size_bytes(
1102
+ f"{sel.get('description', '')} {sel.get('title', '')}", sel
1103
+ )
1104
+ if sz > 0:
1105
+ sizes[idx] = (lbl, sz)
1106
+ break
1107
+ except Exception:
1108
+ pass
1109
+ return sizes
1110
+
1111
+ def _parse_stream_item(
1112
+ self,
1113
+ s: dict[str, Any],
1114
+ stream_skip: list[dict[str, Any]] | None,
1115
+ episode_size: tuple[str, float] | None,
1116
+ ) -> tuple[dict[str, Any], int, float] | None:
1117
+ combined = f"{s.get('name', '')} {s.get('description', '')} {s.get('title', '')}"
1118
+ quality = _extract_quality(combined)
1119
+
1120
+ link = s.get("url")
1121
+ if not link and s.get("infoHash"):
1122
+ trackers = [
1123
+ f"tr={quote(src.replace('tracker:', '', 1))}"
1124
+ for src in (s.get("sources") or [])
1125
+ if isinstance(src, str) and src.startswith("tracker:")
1126
+ ]
1127
+ tr_q = f"&{'&'.join(trackers)}" if trackers else ""
1128
+ link = f"magnet:?xt=urn:btih:{s['infoHash']}{tr_q}"
1129
+ if not link:
1130
+ return None
1131
+
1132
+ seed_lbl, seed_cnt = _extract_seeders(combined, s)
1133
+ size_lbl, size_bytes = (
1134
+ episode_size if episode_size is not None else _extract_size_bytes(combined, s)
1135
+ )
1136
+ fmt_tags = _extract_format_tags(combined)
1137
+ sub_text = "\n".join(str(x) for x in (s.get("name"), s.get("description"), s.get("title")) if x)
1138
+ language = _get_language_codes(_SUBTITLE_FIELD_RE.sub("", sub_text))
1139
+
1140
+ m_badge = re.search(
1141
+ r"\[(RD\+?|AD\+?|PM\+?|TB\+?|DL\+?|EN\+?|RD download|AD download)\]",
1142
+ s.get("name", ""),
1143
+ re.I,
1144
+ )
1145
+ debrid_badge = m_badge.group(0) if m_badge else None
1146
+ is_cached = (
1147
+ bool(debrid_badge and "download" not in debrid_badge.lower())
1148
+ or not str(link).startswith("magnet:")
1149
+ )
1150
+
1151
+ uploader = _extract_uploader(s)
1152
+ server = f"{debrid_badge} {uploader}" if debrid_badge else uploader
1153
+
1154
+ tags: list[str] = []
1155
+ if quality:
1156
+ tags.append(f"{quality}p")
1157
+ if seed_lbl and not is_cached:
1158
+ tags.append(seed_lbl)
1159
+ if debrid_badge:
1160
+ tags.append(debrid_badge.strip("[]"))
1161
+ tags.extend(fmt_tags)
1162
+ if language and language not in ("ENG", "JA/EN"):
1163
+ tags.append(language)
1164
+ if size_lbl:
1165
+ tags.append(size_lbl)
1166
+
1167
+ subtitles: list[dict[str, Any]] | None = None
1168
+ sub_langs: list[str] = []
1169
+ if isinstance(s.get("subtitles"), list) and s["subtitles"]:
1170
+ subtitles = []
1171
+ for sub in s["subtitles"]:
1172
+ if not isinstance(sub, dict):
1173
+ continue
1174
+ sub_url = sub.get("url") or ""
1175
+ sub_lang = sub.get("lang") or "en"
1176
+ subtitles.append(
1177
+ {
1178
+ "title": sub.get("lang") or sub.get("id") or "Subtitle",
1179
+ "language": sub_lang,
1180
+ "type": "text/vtt" if sub_url.endswith(".vtt") else "application/x-subrip",
1181
+ "uri": sub_url,
1182
+ }
1183
+ )
1184
+ if sub_url and isinstance(sub.get("lang"), str) and sub["lang"].strip():
1185
+ code = sub["lang"].strip().upper()
1186
+ if code not in sub_langs:
1187
+ sub_langs.append(code)
1188
+
1189
+ reported_subs = list(dict.fromkeys(
1190
+ sub_langs
1191
+ + [c for m in _SUBTITLE_FIELD_RE.finditer(sub_text) for c in _subtitle_codes(m.group(1))]
1192
+ ))
1193
+ if reported_subs:
1194
+ tags.append(f"Subs: {', '.join(reported_subs)}")
1195
+
1196
+ stream_obj: dict[str, Any] = {
1197
+ "server": server,
1198
+ "link": link,
1199
+ "type": "torrent" if str(link).startswith("magnet:") else "mp4",
1200
+ "quality": quality,
1201
+ }
1202
+ if tags:
1203
+ stream_obj["tags"] = tags
1204
+ stream_obj["tag"] = " • ".join(tags)
1205
+ if subtitles:
1206
+ stream_obj["subtitles"] = subtitles
1207
+ if stream_skip:
1208
+ stream_obj["skip"] = stream_skip
1209
+
1210
+ return stream_obj, seed_cnt, size_bytes
1211
+
1212
+ def get_stream(
1213
+ self,
1214
+ url: str,
1215
+ is_download: bool = False,
1216
+ media_type: str = "movie",
1217
+ ) -> list[dict[str, Any]]:
1218
+ try:
1219
+ try:
1220
+ payload = json.loads(url)
1221
+ if not isinstance(payload, dict):
1222
+ payload = {}
1223
+ except Exception:
1224
+ payload = {
1225
+ "imdbId": url if url.startswith("tt") else None,
1226
+ "kitsuId": url if url.startswith("kitsu:") else None,
1227
+ "malId": url.replace("mal:", "", 1) if url.startswith("mal:") else None,
1228
+ }
1229
+
1230
+ kitsu_id = str(
1231
+ payload.get("kitsuId") or (url if url.startswith("kitsu:") else "")
1232
+ )
1233
+ imdb_id = str(payload.get("imdbId") or (url if url.startswith("tt") else ""))
1234
+ mal_id = str(
1235
+ payload.get("malId")
1236
+ or (url.replace("mal:", "", 1) if url.startswith("mal:") else "")
1237
+ )
1238
+ title = str(payload.get("title") or "")
1239
+ season = str(payload.get("season") or "")
1240
+ episode = str(payload.get("episode") or "")
1241
+ m_k_ep = re.match(r"^kitsu:\d+:(\d+)$", kitsu_id)
1242
+ anime_ep = str(
1243
+ payload.get("animeEpisode") or (m_k_ep.group(1) if m_k_ep else "") or episode
1244
+ )
1245
+ effective_type = str(payload.get("type") or media_type or "series")
1246
+
1247
+ if not kitsu_id and mal_id:
1248
+ kitsu_id = self._resolve_kitsu_id_from_mal(mal_id) or ""
1249
+
1250
+ if not imdb_id and not kitsu_id and not title:
1251
+ return []
1252
+
1253
+ stream_skip: list[dict[str, Any]] | None = None
1254
+ if self._skip_timings_enabled() and effective_type == "series" and episode:
1255
+ try:
1256
+ ep_num = int(episode)
1257
+ except ValueError:
1258
+ ep_num = 0
1259
+ if ep_num > 0:
1260
+ resolved_mal = mal_id or None
1261
+ if not resolved_mal and not kitsu_id and title:
1262
+ if not season or (season.isdigit() and int(season) <= 1):
1263
+ resolved_mal = resolve_mal_id_from_title(title, session=self.session)
1264
+ if resolved_mal:
1265
+ ep_for_skip = int(anime_ep) if anime_ep.isdigit() else ep_num
1266
+ stream_skip = fetch_aniskip_timings(
1267
+ resolved_mal, ep_for_skip, session=self.session
1268
+ )
1269
+ if not stream_skip and imdb_id and season.isdigit():
1270
+ stream_skip = fetch_theintrodb_skip_timings(
1271
+ imdb_id=imdb_id,
1272
+ season=int(season),
1273
+ episode=ep_num,
1274
+ session=self.session,
1275
+ )
1276
+ if not stream_skip:
1277
+ stream_skip = None
1278
+
1279
+ base_url, token = self._resolve_token_and_base_url()
1280
+ quality_filter = str(
1281
+ self.kv.get("animesub_qualityFilter") or self.kv.get("qualityFilter") or "all"
1282
+ )
1283
+ sort_by = str(
1284
+ self.kv.get("animesub_sortBy")
1285
+ or self.kv.get("sortBy")
1286
+ or "qualitythenseeders"
1287
+ )
1288
+
1289
+ raw_streams: list[dict[str, Any]] = []
1290
+
1291
+ if kitsu_id:
1292
+ target_kitsu = kitsu_id
1293
+ if (
1294
+ effective_type == "series"
1295
+ and re.match(r"^(?:kitsu:)?\d+$", kitsu_id)
1296
+ and anime_ep
1297
+ ):
1298
+ target_kitsu = f"{kitsu_id}:{anime_ep}"
1299
+ st_type = "movie" if effective_type == "movie" else "anime"
1300
+ try:
1301
+ res = self.fetch_json(
1302
+ f"{base_url}/{token}/stream/{st_type}/{target_kitsu}.json", timeout=12
1303
+ )
1304
+ if isinstance((res or {}).get("streams"), list):
1305
+ raw_streams = res["streams"]
1306
+ except Exception:
1307
+ raw_streams = []
1308
+
1309
+ if not raw_streams and imdb_id.startswith("tt"):
1310
+ target_imdb = (
1311
+ f"{imdb_id}:{season}:{episode}"
1312
+ if effective_type == "series" and season and episode
1313
+ else imdb_id
1314
+ )
1315
+ st_type = "series" if effective_type == "series" else "movie"
1316
+ try:
1317
+ res = self.fetch_json(
1318
+ f"{base_url}/{token}/stream/{st_type}/{target_imdb}.json", timeout=12
1319
+ )
1320
+ if isinstance((res or {}).get("streams"), list):
1321
+ raw_streams = res["streams"]
1322
+ except Exception:
1323
+ raw_streams = []
1324
+
1325
+ if not raw_streams and title:
1326
+ try:
1327
+ search_term = (
1328
+ f"{title} Season {season}"
1329
+ if season.isdigit() and int(season) > 1
1330
+ else title
1331
+ )
1332
+ k_res = self.fetch_json(
1333
+ f"https://kitsu.io/api/edge/anime?filter[text]={quote(search_term)}&page[limit]=1",
1334
+ timeout=5,
1335
+ )
1336
+ kid = ((k_res or {}).get("data") or [{}])[0].get("id")
1337
+ if kid:
1338
+ ep_sfx = f":{episode}" if episode else ""
1339
+ s_res = self.fetch_json(
1340
+ f"{base_url}/{token}/stream/anime/kitsu:{kid}{ep_sfx}.json",
1341
+ timeout=10,
1342
+ )
1343
+ if isinstance((s_res or {}).get("streams"), list):
1344
+ raw_streams = s_res["streams"]
1345
+ except Exception:
1346
+ pass
1347
+
1348
+ ep_sizes = (
1349
+ self._get_episode_file_sizes(raw_streams, imdb_id, season, episode)
1350
+ if effective_type == "series"
1351
+ else None
1352
+ )
1353
+
1354
+ parsed_items: list[tuple[dict[str, Any], int, float]] = []
1355
+ for idx, s in enumerate(raw_streams):
1356
+ sz = ep_sizes.get(idx, ("", 0.0)) if ep_sizes is not None else None
1357
+ parsed = self._parse_stream_item(s, stream_skip, sz)
1358
+ if parsed and _is_quality_allowed(parsed[0].get("quality"), quality_filter):
1359
+ parsed_items.append(parsed)
1360
+
1361
+ if sort_by == "seeders":
1362
+ parsed_items.sort(key=lambda x: x[1], reverse=True)
1363
+ elif sort_by == "size":
1364
+ parsed_items.sort(key=lambda x: x[2], reverse=True)
1365
+ else:
1366
+ parsed_items.sort(
1367
+ key=lambda x: (_QUALITY_RANKS.get(x[0].get("quality") or "", 0), x[1]),
1368
+ reverse=True,
1369
+ )
1370
+
1371
+ return [item[0] for item in parsed_items]
1372
+ except Exception as err:
1373
+ throw_provider_error("AnimeSub", "stream", err)
1374
+ return []