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,820 @@
1
+ """Pure-Python implementation of the Vega 'anikoto' provider."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import re
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from typing import Any
10
+ from urllib.parse import parse_qs, quote, urlparse
11
+
12
+ from ..html import parse_html
13
+ from .common import BaseProvider, COMMON_HEADERS, aes_cbc_decrypt, throw_provider_error
14
+
15
+ _BASE_URL = "https://anikototv.bz"
16
+ _ALT_BASE_URL = "https://anikototv.to"
17
+
18
+ _STREAM_HEADERS = {
19
+ "User-Agent": (
20
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
21
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
22
+ ),
23
+ "Accept": "*/*",
24
+ }
25
+
26
+
27
+ def _canonical_link(href: str) -> str:
28
+ absolute = href if href.startswith("http") else f"{_BASE_URL}{'' if href.startswith('/') else '/'}{href}"
29
+ return re.sub(r"^https?://(?:www\.)?anikototv\.[a-z]+", _BASE_URL, absolute, flags=re.I)
30
+
31
+
32
+ def _resolve_response_origin(
33
+ resp: Any, html_data_url: str = "", fallback: str = _BASE_URL
34
+ ) -> str:
35
+ try:
36
+ raw_url = getattr(resp, "url", None) or html_data_url or fallback
37
+ parsed = urlparse(raw_url)
38
+ if parsed.scheme and parsed.netloc:
39
+ return f"{parsed.scheme}://{parsed.netloc}"
40
+ except Exception:
41
+ pass
42
+ return fallback
43
+
44
+
45
+ def _rc4(key: str, data: str) -> bytes:
46
+ s = list(range(256))
47
+ a = 0
48
+ for n in range(256):
49
+ a = (s[n] + a + ord(key[n % len(key)])) % 256
50
+ s[n], s[a] = s[a], s[n]
51
+ out = bytearray()
52
+ n2 = 0
53
+ a2 = 0
54
+ for ch in data:
55
+ n2 = (n2 + 1) % 256
56
+ a2 = (s[n2] + a2) % 256
57
+ s[n2], s[a2] = s[a2], s[n2]
58
+ k = s[(s[n2] + s[a2]) % 256]
59
+ out.append((ord(ch) & 0xFF) ^ k)
60
+ return bytes(out)
61
+
62
+
63
+ def _encode_vrf(anime_id: str) -> str:
64
+ return base64.b64encode(_rc4("simple-hash", anime_id)).decode("ascii")
65
+
66
+
67
+ def _decrypt_megaplay(enc_str: str) -> str:
68
+ if not enc_str or not isinstance(enc_str, str):
69
+ return ""
70
+ key_bytes = b"i?LMTAx0Q6,:}50U".ljust(32, b"\x00")[:32]
71
+ iv_bytes = b"W0;27ToaUpl_P%'c"[:16]
72
+ b64 = enc_str.replace("-", "+").replace("_", "/")
73
+ pad = len(b64) % 4
74
+ if pad:
75
+ b64 += "=" * (4 - pad)
76
+ try:
77
+ cipher_bytes = base64.b64decode(b64)
78
+ dec = aes_cbc_decrypt(cipher_bytes, key_bytes, iv_bytes)
79
+ return dec.decode("utf-8", errors="replace")
80
+ except Exception:
81
+ return ""
82
+
83
+
84
+ def _infer_lang(label: str) -> str:
85
+ low = (label or "").lower()
86
+ for tokens, code in (
87
+ (("english", "eng"), "en"),
88
+ (("spanish", "spa", "es-"), "es"),
89
+ (("french", "fra", "fre"), "fr"),
90
+ (("german", "deu", "ger"), "de"),
91
+ (("portuguese", "por"), "pt"),
92
+ (("italian", "ita"), "it"),
93
+ (("japanese", "jpn"), "ja"),
94
+ (("chinese", "chi", "zho"), "zh"),
95
+ (("indonesian", "ind"), "id"),
96
+ (("thai", "tha"), "th"),
97
+ (("vietnamese", "vie"), "vi"),
98
+ (("arabic", "ara"), "ar"),
99
+ (("hindi", "hin"), "hi"),
100
+ (("korean", "kor"), "ko"),
101
+ (("russian", "rus"), "ru"),
102
+ ):
103
+ if any(tok in low for tok in tokens):
104
+ return code
105
+ return "und"
106
+
107
+
108
+ def _extract_candidate_url(data: Any) -> str:
109
+ if not data:
110
+ return ""
111
+ if isinstance(data, str):
112
+ return data if data.startswith("http") else ""
113
+ if isinstance(data, dict):
114
+ for key in ("file", "sources"):
115
+ val = data.get(key)
116
+ if isinstance(val, str) and val.startswith("http"):
117
+ return val
118
+ if isinstance(val, dict):
119
+ f = val.get("file")
120
+ if isinstance(f, str) and f.startswith("http"):
121
+ return f
122
+ if isinstance(val, list) and val:
123
+ first = val[0]
124
+ if isinstance(first, str) and first.startswith("http"):
125
+ return first
126
+ if isinstance(first, dict):
127
+ f = first.get("file", "")
128
+ if isinstance(f, str) and f.startswith("http"):
129
+ return f
130
+ return ""
131
+
132
+
133
+ class AnikotoClient(BaseProvider):
134
+ """Pure-Python implementation of the Vega 'anikoto' provider."""
135
+
136
+ name = "anikoto"
137
+ catalog = [
138
+ {"title": "Popular", "filter": "/most-viewed"},
139
+ {"title": "Recently Updated", "filter": "/latest-updated"},
140
+ {"title": "New Releases", "filter": "/new-release"},
141
+ {"title": "Top Rated", "filter": "/filter?sort=score"},
142
+ {"title": "Anime Movies", "filter": "/type/movie"},
143
+ {"title": "Ongoing Anime", "filter": "/status/currently-airing"},
144
+ {"title": "Completed Anime", "filter": "/status/finished-airing"},
145
+ ]
146
+ genres = [
147
+ {"title": "Action", "filter": "/genre/action"},
148
+ {"title": "Adventure", "filter": "/genre/adventure"},
149
+ {"title": "Comedy", "filter": "/genre/comedy"},
150
+ {"title": "Drama", "filter": "/genre/drama"},
151
+ {"title": "Ecchi", "filter": "/genre/ecchi"},
152
+ {"title": "Fantasy", "filter": "/genre/fantasy"},
153
+ {"title": "Horror", "filter": "/genre/horror"},
154
+ {"title": "Isekai", "filter": "/genre/isekai"},
155
+ {"title": "Mecha", "filter": "/genre/mecha"},
156
+ {"title": "Mystery", "filter": "/genre/mystery"},
157
+ {"title": "Psychological", "filter": "/genre/psychological"},
158
+ {"title": "Romance", "filter": "/genre/romance"},
159
+ {"title": "Sci-Fi", "filter": "/genre/sci-fi"},
160
+ {"title": "Seinen", "filter": "/genre/seinen"},
161
+ {"title": "Shoujo", "filter": "/genre/shoujo"},
162
+ {"title": "Shounen", "filter": "/genre/shounen"},
163
+ {"title": "Slice of Life", "filter": "/genre/slice-of-life"},
164
+ {"title": "Sports", "filter": "/genre/sports"},
165
+ {"title": "Supernatural", "filter": "/genre/supernatural"},
166
+ {"title": "Thriller", "filter": "/genre/thriller"},
167
+ ]
168
+ settings_schema = [
169
+ {
170
+ "key": "anikoto_skipTimings",
171
+ "type": "toggle",
172
+ "label": "Skip Timings",
173
+ "description": "Automatically enable intro and outro skip timestamps from Anikoto",
174
+ "defaultValue": True,
175
+ }
176
+ ]
177
+
178
+ def _parse_post_items(self, html: str) -> list[dict[str, str]]:
179
+ doc = parse_html(html)
180
+ posts: list[dict[str, str]] = []
181
+ for el in doc.select(".ani.items .item, .items .item, div.item"):
182
+ title_el = el.select_one(".info a.name, .info a.d-title, a.name.d-title")
183
+ img_el = el.select_one("img")
184
+ title = (
185
+ (title_el.text().strip() if title_el else "")
186
+ or (title_el.attr("data-jp") if title_el else "")
187
+ or (img_el.attr("alt") if img_el else "")
188
+ )
189
+ link_el = el.select_one(".info a.name, .info a.d-title, .poster a, a[href*='/watch/']")
190
+ raw_href = link_el.attr("href") if link_el else ""
191
+ if not raw_href:
192
+ continue
193
+ href = _canonical_link(raw_href)
194
+ image = img_el.attr("src") if img_el else ""
195
+ if title and href:
196
+ posts.append({"title": title, "link": href, "image": image})
197
+ return posts
198
+
199
+ def get_posts(self, filter_path: str = "", page: int = 1) -> list[dict[str, str]]:
200
+ try:
201
+ delimiter = "&" if "?" in filter_path else "?"
202
+ url = f"{_BASE_URL}{filter_path}{delimiter}page={page}"
203
+ html = self.fetch_text(
204
+ url, headers={**COMMON_HEADERS, "Referer": f"{_BASE_URL}/"}
205
+ )
206
+ return self._parse_post_items(html)
207
+ except Exception:
208
+ return []
209
+
210
+ def get_search_posts(self, query: str, page: int = 1) -> list[dict[str, str]]:
211
+ try:
212
+ url = f"{_BASE_URL}/filter?keyword={quote(query)}&page={page}"
213
+ html = self.fetch_text(
214
+ url, headers={**COMMON_HEADERS, "Referer": f"{_BASE_URL}/"}
215
+ )
216
+ return self._parse_post_items(html)
217
+ except Exception:
218
+ return []
219
+
220
+ def _fetch_episode_list_json(
221
+ self, host_origin: str, anime_id: str, slug: str
222
+ ) -> tuple[Any, str]:
223
+ vrf = quote(_encode_vrf(anime_id))
224
+ url = f"{host_origin}/ajax/episode/list/{anime_id}?vrf={vrf}&style=default"
225
+ resp = self.session.get(
226
+ url,
227
+ headers={
228
+ **COMMON_HEADERS,
229
+ "X-Requested-With": "XMLHttpRequest",
230
+ "Referer": f"{host_origin}/watch/{slug}/ep-1",
231
+ },
232
+ timeout=self.timeout,
233
+ )
234
+ resp.raise_for_status()
235
+ return resp.json(), _resolve_response_origin(resp, fallback=host_origin)
236
+
237
+ def get_meta(self, link: str) -> dict[str, Any]:
238
+ try:
239
+ watch_url = link
240
+ if not watch_url.startswith("http"):
241
+ watch_url = f"{_BASE_URL}{'' if watch_url.startswith('/') else '/'}{watch_url}"
242
+ else:
243
+ watch_url = re.sub(
244
+ r"^https?://(?:www\.)?anikototv\.[a-z]+",
245
+ _BASE_URL,
246
+ watch_url,
247
+ flags=re.I,
248
+ )
249
+ if "/ep-" not in watch_url:
250
+ watch_url = f"{watch_url.rstrip('/')}/ep-1"
251
+
252
+ m_slug = re.search(r"/watch/([^/?#]+)", watch_url)
253
+ slug = (
254
+ m_slug.group(1)
255
+ if m_slug
256
+ else re.sub(r"[?#].*$", "", watch_url).rstrip("/").split("/")[-1]
257
+ )
258
+
259
+ resp = self.session.get(
260
+ watch_url,
261
+ headers={**COMMON_HEADERS, "Referer": f"{_BASE_URL}/"},
262
+ timeout=self.timeout,
263
+ )
264
+ resp.raise_for_status()
265
+ doc = parse_html(resp.text)
266
+
267
+ data_url_el = doc.select_one("#watch-page, #watch-main, .watch-wrap, [data-url]")
268
+ html_data_url = data_url_el.attr("data-url") if data_url_el else ""
269
+ origin = _resolve_response_origin(resp, html_data_url, _BASE_URL)
270
+
271
+ h1_el = doc.select_one("h1.title") or doc.select_one(".binfo h1")
272
+ title = h1_el.text().strip() if h1_el else slug
273
+ if not title:
274
+ title = slug
275
+
276
+ syn_el = doc.select_one("div.synopsis div.content") or doc.select_one("div.synopsis")
277
+ synopsis = syn_el.text().strip() if syn_el else ""
278
+
279
+ img_el = doc.select_one("#w-info .poster img, .poster img") or doc.select_one("img")
280
+ image = img_el.attr("src") if img_el else ""
281
+
282
+ rating: str | None = None
283
+ rv_el = doc.select_one("[itemprop='ratingValue']")
284
+ if rv_el and rv_el.text().strip():
285
+ rating = rv_el.text().strip()
286
+ if not rating:
287
+ mal_el = doc.select_one(".meta div:contains('MAL'), #w-info div:contains('MAL')")
288
+ if mal_el:
289
+ m_mal = re.search(r"MAL:\s*(\d+(?:\.\d+)?)", mal_el.text())
290
+ if m_mal:
291
+ rating = m_mal.group(1)
292
+ if not rating:
293
+ sc_el = doc.select_one(".score .value")
294
+ if sc_el:
295
+ m_sc = re.search(r"\d+(?:\.\d+)?", sc_el.text())
296
+ if m_sc:
297
+ rating = m_sc.group(0)
298
+
299
+ tags: list[str] = []
300
+ for g_el in doc.select("div:contains(Genres) span a, .genre a"):
301
+ g = g_el.text().strip()
302
+ if g and g not in tags:
303
+ tags.append(g)
304
+
305
+ type_el = doc.select_one(".meta div:contains(Type) span, .m-item span")
306
+ type_text = type_el.text().strip().lower() if type_el else ""
307
+ media_type = "movie" if "movie" in type_text else "series"
308
+
309
+ id_el = doc.select_one("#watch-page, #watch-main, .watch-wrap, [data-id]")
310
+ anime_id = id_el.attr("data-id") if id_el else ""
311
+
312
+ link_list: list[dict[str, Any]] = []
313
+ if anime_id:
314
+ active_origin = origin
315
+ ep_data: Any = None
316
+ try:
317
+ ep_data, active_origin = self._fetch_episode_list_json(
318
+ active_origin, anime_id, slug
319
+ )
320
+ except Exception:
321
+ ep_data = None
322
+ if not isinstance(ep_data, dict) or ep_data.get("status") != 200:
323
+ retry_origin = _ALT_BASE_URL if active_origin == _BASE_URL else _BASE_URL
324
+ try:
325
+ ep_data, active_origin = self._fetch_episode_list_json(
326
+ retry_origin, anime_id, slug
327
+ )
328
+ except Exception:
329
+ ep_data = None
330
+
331
+ if isinstance(ep_data, dict) and ep_data.get("status") == 200 and ep_data.get("result"):
332
+ ep_doc = parse_html(ep_data["result"])
333
+ direct_links: list[dict[str, Any]] = []
334
+ for el in ep_doc.select("ul.ep-range a, .ep-range a, .range a, a[data-ids]"):
335
+ num = el.attr("data-num")
336
+ if not num:
337
+ continue
338
+ data_ids = el.attr("data-ids")
339
+ mal_id = el.attr("data-mal")
340
+ timestamp = el.attr("data-timestamp")
341
+ has_sub = el.attr("data-sub") == "1"
342
+ has_dub = el.attr("data-dub") == "1"
343
+ ep_title = el.attr("title") or f"Episode {num}"
344
+ direct_links.append(
345
+ {
346
+ "title": ep_title,
347
+ "link": json.dumps(
348
+ {
349
+ "slug": slug,
350
+ "epNum": num,
351
+ "dataIds": data_ids,
352
+ "malId": mal_id,
353
+ "timestamp": timestamp,
354
+ "hasSub": has_sub,
355
+ "hasDub": has_dub,
356
+ "title": ep_title,
357
+ "origin": active_origin,
358
+ }
359
+ ),
360
+ }
361
+ )
362
+ if direct_links:
363
+ link_list.append({"title": title, "directLinks": direct_links})
364
+
365
+ if not link_list:
366
+ if anime_id and media_type != "movie":
367
+ throw_provider_error(
368
+ "Anikoto", "episode list", RuntimeError("episode list unavailable")
369
+ )
370
+ link_list.append(
371
+ {
372
+ "title": title,
373
+ "directLinks": [
374
+ {
375
+ "title": "Movie" if media_type == "movie" else "Episode 1",
376
+ "link": json.dumps(
377
+ {
378
+ "slug": slug,
379
+ "epNum": "1",
380
+ "dataIds": "",
381
+ "malId": "",
382
+ "timestamp": "",
383
+ "hasSub": True,
384
+ "hasDub": False,
385
+ "title": title,
386
+ }
387
+ ),
388
+ "type": media_type,
389
+ }
390
+ ],
391
+ }
392
+ )
393
+
394
+ result: dict[str, Any] = {
395
+ "title": title,
396
+ "synopsis": synopsis,
397
+ "image": image,
398
+ "imdbId": "",
399
+ "type": media_type,
400
+ "linkList": link_list,
401
+ "webUrl": watch_url,
402
+ }
403
+ if tags:
404
+ result["tags"] = tags
405
+ if rating is not None:
406
+ result["rating"] = rating
407
+ return result
408
+ except Exception as err:
409
+ throw_provider_error("Anikoto", "metadata", err)
410
+ return {}
411
+
412
+ def _add_m3u8_variants(
413
+ self,
414
+ master_url: str,
415
+ server_label: str,
416
+ headers: dict[str, str],
417
+ subtitles: list[dict[str, Any]] | None,
418
+ skip_intervals: list[dict[str, Any]] | None,
419
+ add_stream: Any,
420
+ ) -> None:
421
+ try:
422
+ m3u8_text = self.fetch_text(master_url, headers=headers, timeout=6)
423
+ lines = m3u8_text.splitlines()
424
+ base_url = master_url[: master_url.rfind("/") + 1]
425
+ for i, raw in enumerate(lines):
426
+ line = raw.strip()
427
+ if line.startswith("#EXT-X-STREAM-INF") and i + 1 < len(lines):
428
+ m_res = re.search(r"RESOLUTION=\d+x(\d+)", line)
429
+ quality = f"{m_res.group(1)}p" if m_res else "unknown"
430
+ nxt = lines[i + 1].strip()
431
+ if nxt and not nxt.startswith("#"):
432
+ stream_url = nxt if nxt.startswith("http") else f"{base_url}{nxt}"
433
+ entry: dict[str, Any] = {
434
+ "server": f"{server_label} {quality}",
435
+ "link": stream_url,
436
+ "type": "m3u8",
437
+ "quality": quality,
438
+ "headers": headers,
439
+ }
440
+ if subtitles:
441
+ entry["subtitles"] = subtitles
442
+ if skip_intervals:
443
+ entry["skip"] = skip_intervals
444
+ add_stream(entry)
445
+ except Exception:
446
+ pass
447
+
448
+ def get_stream(
449
+ self,
450
+ url: str,
451
+ is_download: bool = False,
452
+ media_type: str = "movie",
453
+ ) -> list[dict[str, Any]]:
454
+ try:
455
+ try:
456
+ payload = json.loads(url)
457
+ if not isinstance(payload, dict):
458
+ payload = {"slug": url, "epNum": "1"}
459
+ except Exception:
460
+ payload = {"slug": url, "epNum": "1"}
461
+
462
+ slug = str(payload.get("slug") or "")
463
+ ep_num = str(payload.get("epNum") or "1")
464
+ data_ids = str(payload.get("dataIds") or "")
465
+
466
+ if not slug and isinstance(url, str):
467
+ slug = url
468
+
469
+ if "/watch/" in slug:
470
+ m_w = re.search(r"/watch/([^/]+)(?:/ep-(\d+))?", slug)
471
+ if m_w:
472
+ slug = m_w.group(1)
473
+ if m_w.group(2):
474
+ ep_num = m_w.group(2)
475
+ elif slug.startswith("http"):
476
+ slug = slug.rstrip("/").split("/")[-1]
477
+
478
+ if not slug:
479
+ return []
480
+
481
+ raw_origin = payload.get("origin", "")
482
+ origin = (
483
+ raw_origin
484
+ if isinstance(raw_origin, str)
485
+ and re.match(r"^https?://(?:www\.)?anikototv\.[a-z]+$", raw_origin, re.I)
486
+ else _BASE_URL
487
+ )
488
+
489
+ def watch_url_for(host_origin: str) -> str:
490
+ return f"{host_origin}/watch/{slug}/ep-{ep_num or '1'}"
491
+
492
+ def headers_for(host_origin: str) -> dict[str, str]:
493
+ return {**_STREAM_HEADERS, "Referer": f"{host_origin}/"}
494
+
495
+ if not data_ids:
496
+ detail_resp = self.session.get(
497
+ watch_url_for(origin), headers=headers_for(origin), timeout=self.timeout
498
+ )
499
+ detail_resp.raise_for_status()
500
+ d_doc = parse_html(detail_resp.text)
501
+ du_el = d_doc.select_one("#watch-page, #watch-main, .watch-wrap, [data-url]")
502
+ origin = _resolve_response_origin(
503
+ detail_resp, du_el.attr("data-url") if du_el else "", origin
504
+ )
505
+ id_el = d_doc.select_one("#watch-page, #watch-main, .watch-wrap, [data-id]")
506
+ anime_id = id_el.attr("data-id") if id_el else ""
507
+ if anime_id:
508
+ ep_data: Any = None
509
+ try:
510
+ ep_data, origin = self._fetch_episode_list_json(origin, anime_id, slug)
511
+ except Exception:
512
+ ep_data = None
513
+ if not isinstance(ep_data, dict) or ep_data.get("status") != 200:
514
+ retry_origin = _ALT_BASE_URL if origin == _BASE_URL else _BASE_URL
515
+ try:
516
+ ep_data, origin = self._fetch_episode_list_json(
517
+ retry_origin, anime_id, slug
518
+ )
519
+ except Exception:
520
+ ep_data = None
521
+ if isinstance(ep_data, dict) and ep_data.get("status") == 200 and ep_data.get("result"):
522
+ ep_doc = parse_html(ep_data["result"])
523
+ ep_el = ep_doc.select_one(
524
+ f'ul.ep-range a[data-num="{ep_num}"], .ep-range a[data-num="{ep_num}"], a[data-ids]'
525
+ )
526
+ if ep_el:
527
+ data_ids = ep_el.attr("data-ids")
528
+
529
+ if not data_ids:
530
+ return []
531
+
532
+ def fetch_server_list(host_origin: str) -> Any:
533
+ r = self.session.get(
534
+ f"{host_origin}/ajax/server/list?servers={quote(data_ids)}",
535
+ headers={
536
+ **headers_for(host_origin),
537
+ "X-Requested-With": "XMLHttpRequest",
538
+ "Referer": watch_url_for(host_origin),
539
+ },
540
+ timeout=self.timeout,
541
+ )
542
+ r.raise_for_status()
543
+ return r.json()
544
+
545
+ srv_data: Any = None
546
+ try:
547
+ srv_data = fetch_server_list(origin)
548
+ except Exception:
549
+ srv_data = None
550
+
551
+ if not isinstance(srv_data, dict) or srv_data.get("status") != 200:
552
+ retry_origin = _ALT_BASE_URL if origin == _BASE_URL else _BASE_URL
553
+ try:
554
+ d_resp = self.session.get(
555
+ watch_url_for(retry_origin),
556
+ headers=headers_for(retry_origin),
557
+ timeout=self.timeout,
558
+ )
559
+ d_resp.raise_for_status()
560
+ r_doc = parse_html(d_resp.text)
561
+ ru_el = r_doc.select_one("#watch-page, #watch-main, .watch-wrap, [data-url]")
562
+ next_origin = _resolve_response_origin(
563
+ d_resp, ru_el.attr("data-url") if ru_el else "", retry_origin
564
+ )
565
+ srv_data = fetch_server_list(next_origin)
566
+ if isinstance(srv_data, dict) and srv_data.get("status") == 200:
567
+ origin = next_origin
568
+ except Exception:
569
+ pass
570
+
571
+ if not isinstance(srv_data, dict) or srv_data.get("status") != 200 or not srv_data.get("result"):
572
+ return []
573
+
574
+ s_doc = parse_html(srv_data["result"])
575
+ tasks: list[dict[str, str]] = []
576
+ seen_link_ids: set[str] = set()
577
+ for type_el in s_doc.select("div.type, .server-type, div.types > div.type, div.servers > div.type"):
578
+ data_type = type_el.attr("data-type") or "sub"
579
+ for s_el in type_el.select("[data-link-id], [data-id], .item"):
580
+ link_id = s_el.attr("data-link-id") or s_el.attr("data-id")
581
+ server_name = s_el.text().strip() or "Server"
582
+ if link_id and link_id not in seen_link_ids:
583
+ seen_link_ids.add(link_id)
584
+ tasks.append(
585
+ {"dataType": data_type, "serverName": server_name, "linkId": link_id}
586
+ )
587
+
588
+ skip_val = self.kv.get("anikoto_skipTimings")
589
+ skip_timings_enabled = True if skip_val is None else bool(skip_val)
590
+
591
+ streams: list[dict[str, Any]] = []
592
+ seen_links: set[str] = set()
593
+
594
+ def add_stream(stream: dict[str, Any]) -> None:
595
+ lnk = stream.get("link")
596
+ if not lnk or lnk in seen_links:
597
+ return
598
+ seen_links.add(lnk)
599
+ streams.append(stream)
600
+
601
+ def process_task(task: dict[str, str]) -> list[dict[str, Any]]:
602
+ local_streams: list[dict[str, Any]] = []
603
+
604
+ def add_local(st: dict[str, Any]) -> None:
605
+ local_streams.append(st)
606
+
607
+ try:
608
+ get_url = f"{origin}/ajax/server?get={quote(task['linkId'])}"
609
+ get_data = self.fetch_json(
610
+ get_url,
611
+ headers={
612
+ **headers_for(origin),
613
+ "X-Requested-With": "XMLHttpRequest",
614
+ "Referer": watch_url_for(origin),
615
+ },
616
+ timeout=8,
617
+ )
618
+ res_obj = get_data.get("result") or {}
619
+ iframe_url = res_obj.get("url")
620
+ if not iframe_url:
621
+ return local_streams
622
+
623
+ skip_intervals: list[dict[str, Any]] | None = None
624
+ if skip_timings_enabled:
625
+ skip_data = res_obj.get("skip_data")
626
+ if isinstance(skip_data, dict):
627
+ intervals: list[dict[str, Any]] = []
628
+ for key, label in (("intro", "Intro"), ("outro", "Outro")):
629
+ arr = skip_data.get(key)
630
+ if isinstance(arr, list) and len(arr) >= 2:
631
+ try:
632
+ start, end = float(arr[0]), float(arr[1])
633
+ if end > start:
634
+ intervals.append({"title": label, "from": start, "to": end})
635
+ except (TypeError, ValueError):
636
+ pass
637
+ if intervals:
638
+ skip_intervals = intervals
639
+
640
+ host = urlparse(iframe_url).netloc
641
+ if not host and "://" in iframe_url:
642
+ host = iframe_url.split("://", 1)[1].split("/", 1)[0]
643
+ audio_label = task["dataType"].upper()
644
+ server_label = f"{task['serverName']} ({audio_label})"
645
+
646
+ # Flow 1: Kiwi / VibePlayer
647
+ if "#" in iframe_url:
648
+ fragment = iframe_url.split("#", 1)[1]
649
+ if fragment:
650
+ try:
651
+ decoded = base64.b64decode(fragment + "=" * (-len(fragment) % 4)).decode(
652
+ "utf-8", errors="replace"
653
+ )
654
+ if decoded.startswith("http"):
655
+ kiwi_headers = {
656
+ "Referer": "https://vibeplayer.site/",
657
+ "Origin": "https://vibeplayer.site",
658
+ "User-Agent": _STREAM_HEADERS["User-Agent"],
659
+ }
660
+ st_entry: dict[str, Any] = {
661
+ "server": server_label,
662
+ "link": decoded,
663
+ "type": "m3u8",
664
+ "quality": "auto",
665
+ "headers": kiwi_headers,
666
+ }
667
+ if skip_intervals:
668
+ st_entry["skip"] = skip_intervals
669
+ add_local(st_entry)
670
+ self._add_m3u8_variants(
671
+ decoded, server_label, kiwi_headers, None, skip_intervals, add_local
672
+ )
673
+ except Exception:
674
+ pass
675
+
676
+ # Flow 2: VidTube / MegaPlay / VidWish / Mewstream
677
+ try:
678
+ page_html = self.fetch_text(
679
+ iframe_url,
680
+ headers={
681
+ **_STREAM_HEADERS,
682
+ "Referer": f"https://{host}/",
683
+ "Origin": f"https://{host}",
684
+ },
685
+ timeout=8,
686
+ )
687
+ m_id = re.search(r'data-id=["\']?([^"\'\s>]+)["\']?', page_html, re.I)
688
+ m_real = re.search(r'data-realid=["\']?([^"\'\s>]+)["\']?', page_html, re.I)
689
+ m_url_id = re.search(r"/stream/[^/]+/([^/?#]+)", iframe_url)
690
+
691
+ data_id = m_id.group(1) if m_id else (m_url_id.group(1) if m_url_id else "")
692
+ real_id = m_real.group(1) if m_real else ""
693
+ id_candidates = [x for x in (data_id, real_id) if x]
694
+
695
+ if id_candidates:
696
+ qs = parse_qs(urlparse(iframe_url).query)
697
+ s_param = qs.get("s", [""])[0]
698
+ type_param = task["dataType"]
699
+ if "/hsub" in iframe_url:
700
+ type_param = "hsub"
701
+ elif "/hdub" in iframe_url:
702
+ type_param = "hdub"
703
+
704
+ type_candidates = list(dict.fromkeys(
705
+ v for v in (type_param, task["dataType"], "sub", "dub") if v
706
+ ))
707
+ s_candidates = list(dict.fromkeys([s_param, "tcdn", "bcdn", ""]))
708
+
709
+ api_headers = {
710
+ **_STREAM_HEADERS,
711
+ "X-Requested-With": "XMLHttpRequest",
712
+ "Referer": iframe_url,
713
+ "Origin": f"https://{host}",
714
+ }
715
+
716
+ src_data: dict[str, Any] | None = None
717
+ master_url = ""
718
+
719
+ for curr_id in id_candidates:
720
+ if master_url:
721
+ break
722
+ for curr_type in type_candidates:
723
+ if master_url:
724
+ break
725
+ for curr_s in s_candidates:
726
+ if master_url:
727
+ break
728
+ s_query = f"&s={quote(curr_s)}" if curr_s else ""
729
+ endpoints = (
730
+ f"https://{host}/stream/getSources?id={curr_id}&type={curr_type}{s_query}",
731
+ f"https://{host}/stream/getSourcesNew?id={curr_id}&type={curr_type}{s_query}",
732
+ f"https://{host}/stream/getSources?id={curr_id}&id={curr_id}&type={curr_type}&type={curr_type}{s_query}",
733
+ )
734
+ for ep in endpoints:
735
+ try:
736
+ data = self.fetch_json(ep, headers=api_headers, timeout=8)
737
+ if not isinstance(data, dict):
738
+ continue
739
+ candidate = ""
740
+ if isinstance(data.get("enc"), str) and data["enc"]:
741
+ dec = _decrypt_megaplay(data["enc"])
742
+ if dec:
743
+ try:
744
+ candidate = _extract_candidate_url(json.loads(dec))
745
+ except Exception:
746
+ if dec.startswith("http"):
747
+ candidate = dec
748
+ if not candidate:
749
+ candidate = _extract_candidate_url(data)
750
+ if candidate and candidate.startswith("http"):
751
+ master_url = candidate
752
+ src_data = data
753
+ break
754
+ except Exception:
755
+ continue
756
+
757
+ if master_url:
758
+ stream_headers = {
759
+ "Referer": f"https://{host}/",
760
+ "Origin": f"https://{host}",
761
+ "User-Agent": _STREAM_HEADERS["User-Agent"],
762
+ }
763
+ tracks = (src_data or {}).get("tracks") or []
764
+ subtitles: list[dict[str, Any]] = []
765
+ for t in tracks:
766
+ if (
767
+ isinstance(t, dict)
768
+ and isinstance(t.get("file"), str)
769
+ and t["file"].startswith("http")
770
+ and t.get("label")
771
+ ):
772
+ subtitles.append(
773
+ {
774
+ "title": t["label"],
775
+ "language": _infer_lang(t["label"]),
776
+ "type": "text/vtt",
777
+ "uri": (
778
+ "https://fetch.1proxy.workers.dev/fetch?url="
779
+ f"{quote(t['file'], safe='')}&headers="
780
+ f"{quote(json.dumps(stream_headers), safe='')}"
781
+ ),
782
+ }
783
+ )
784
+
785
+ master_entry: dict[str, Any] = {
786
+ "server": server_label,
787
+ "link": master_url,
788
+ "type": "m3u8",
789
+ "quality": "auto",
790
+ "headers": stream_headers,
791
+ }
792
+ if subtitles:
793
+ master_entry["subtitles"] = subtitles
794
+ if skip_intervals:
795
+ master_entry["skip"] = skip_intervals
796
+ add_local(master_entry)
797
+ self._add_m3u8_variants(
798
+ master_url,
799
+ server_label,
800
+ stream_headers,
801
+ subtitles or None,
802
+ skip_intervals,
803
+ add_local,
804
+ )
805
+ except Exception:
806
+ pass
807
+ except Exception:
808
+ pass
809
+ return local_streams
810
+
811
+ if tasks:
812
+ with ThreadPoolExecutor(max_workers=min(len(tasks), 6)) as pool:
813
+ for batch in pool.map(process_task, tasks):
814
+ for st in batch:
815
+ add_stream(st)
816
+
817
+ return streams
818
+ except Exception as err:
819
+ throw_provider_error("Anikoto", "stream", err)
820
+ return []