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,816 @@
1
+ """Pure-Python KatMovies provider."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html as html_mod
6
+ import json
7
+ import re
8
+ from typing import Any
9
+ from urllib.parse import quote, urljoin, urlparse
10
+
11
+ from ..html import parse_html
12
+ from ..utils import format_season_title, to_relative_path
13
+ from .common import (
14
+ BaseProvider,
15
+ add_cinemeta_context,
16
+ apply_cinemeta_meta,
17
+ enrich_cinemeta_episodes,
18
+ enrich_episodes_with_skip_timings,
19
+ get_base_url,
20
+ get_cinemeta_meta,
21
+ get_cinemeta_season,
22
+ read_cinemeta_context,
23
+ throw_provider_error,
24
+ )
25
+ from .common.extractors import gdflix_extractor, hubcloud_extractor
26
+
27
+ _DEFAULT_KMHD_TOKEN = (
28
+ "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
29
+ "eyJzdWIiOiJhZG1pbiIsImV4cCI6MTgwNzQ4NDIzMywiaWF0IjoxNzA3NDg0MjMzfQ."
30
+ "7u5bF9PcMhvClSDZgsd6EU-CQnp1Ec--wsezkDEgiZo"
31
+ )
32
+
33
+
34
+ def _js_object_to_json(src: str) -> str:
35
+ """Convert a JS object literal (SvelteKit SSR payload) into valid JSON."""
36
+ out: list[str] = []
37
+ i = 0
38
+ n = len(src)
39
+ while i < n:
40
+ ch = src[i]
41
+ if ch in ('"', "'"):
42
+ quote_char = ch
43
+ i += 1
44
+ buf: list[str] = ['"']
45
+ while i < n:
46
+ c = src[i]
47
+ if c == "\\":
48
+ if i + 1 < n:
49
+ nxt = src[i + 1]
50
+ if quote_char == "'" and nxt == "'":
51
+ buf.append("'")
52
+ elif nxt == '"':
53
+ buf.append('\\"')
54
+ else:
55
+ buf.append("\\" + nxt)
56
+ i += 2
57
+ continue
58
+ if c == quote_char:
59
+ i += 1
60
+ break
61
+ if c == '"' and quote_char == "'":
62
+ buf.append('\\"')
63
+ elif c == "\n":
64
+ buf.append("\\n")
65
+ elif c == "\r":
66
+ buf.append("\\r")
67
+ elif c == "\t":
68
+ buf.append("\\t")
69
+ else:
70
+ buf.append(c)
71
+ i += 1
72
+ buf.append('"')
73
+ out.append("".join(buf))
74
+ continue
75
+ out.append(ch)
76
+ i += 1
77
+
78
+ text = "".join(out)
79
+ # Replace void 0 / undefined outside strings
80
+ parts = re.split(r'("(?:\\.|[^"\\])*")', text)
81
+ for idx in range(0, len(parts), 2):
82
+ seg = parts[idx]
83
+ seg = re.sub(r"\bvoid\s+0\b", "null", seg)
84
+ seg = re.sub(r"\bundefined\b", "null", seg)
85
+ seg = re.sub(r"([,{]\s*)([A-Za-z_$][A-Za-z0-9_$]*)\s*:", r'\1"\2":', seg)
86
+ seg = re.sub(r",\s*([}\]])", r"\1", seg)
87
+ parts[idx] = seg
88
+ return "".join(parts)
89
+
90
+
91
+ def _parse_svelte_data(html_text: str) -> dict[str, Any] | None:
92
+ m = re.search(r"resolve\(\{\s*id:\s*\d+,\s*data:", html_text)
93
+ if not m:
94
+ return None
95
+ start = m.end()
96
+ err_idx = html_text.find(",error:", start)
97
+ if err_idx == -1:
98
+ return None
99
+ data_str = html_text[start:err_idx].strip()
100
+ try:
101
+ parsed = json.loads(data_str)
102
+ return parsed if isinstance(parsed, dict) else None
103
+ except Exception:
104
+ pass
105
+ try:
106
+ parsed = json.loads(_js_object_to_json(data_str))
107
+ return parsed if isinstance(parsed, dict) else None
108
+ except Exception:
109
+ return None
110
+
111
+
112
+ class KatmoviesClient(BaseProvider):
113
+ """Pure-Python client for the KatMovies provider."""
114
+
115
+ name: str = "katmovies"
116
+ catalog: list[dict[str, str]] = [
117
+ {"title": "Latest", "filter": ""},
118
+ {"title": "Netflix", "filter": "/category/netflix"},
119
+ {"title": "Amazon Prime", "filter": "/category/amazon-prime"},
120
+ ]
121
+ genres: list[dict[str, str]] = [
122
+ {"title": "Action", "filter": "/category/action"},
123
+ {"title": "Crime", "filter": "/category/crime"},
124
+ {"title": "Comedy", "filter": "/category/comedy"},
125
+ {"title": "Drama", "filter": "/category/drama"},
126
+ {"title": "Horror", "filter": "/category/horror"},
127
+ {"title": "Family", "filter": "/category/family"},
128
+ {"title": "Sci-Fi", "filter": "/category/sifi"},
129
+ {"title": "Thriller", "filter": "/category/triller"},
130
+ {"title": "Romance", "filter": "/category/romance"},
131
+ {"title": "Fight", "filter": "/category/fight"},
132
+ ]
133
+ settings_schema: list[dict[str, Any]] = [
134
+ {
135
+ "key": "katmovies_quickDownload",
136
+ "type": "toggle",
137
+ "label": "Quick Download",
138
+ "description": (
139
+ "Automatically download the preferred server in 1-click without "
140
+ "showing server selection"
141
+ ),
142
+ "defaultValue": True,
143
+ },
144
+ {
145
+ "key": "katmovies_preferredDownloadServer",
146
+ "type": "select",
147
+ "label": "Preferred Download Server",
148
+ "description": "Server to prioritize for 1-click quick download",
149
+ "options": [
150
+ {"label": "Auto (Best Available)", "value": "auto"},
151
+ {"label": "CF Worker (Fastest)", "value": "cf worker"},
152
+ {"label": "CF Storage (R2 Direct)", "value": "cf storage"},
153
+ {"label": "GDrive (Google Direct)", "value": "gdrive"},
154
+ {"label": "Pixeldrain", "value": "pixeldrain"},
155
+ {"label": "FastDl", "value": "fastdl"},
156
+ {"label": "HubCdn", "value": "hubcdn"},
157
+ ],
158
+ "defaultValue": "auto",
159
+ },
160
+ {
161
+ "key": "katmovies_skipTimings",
162
+ "type": "toggle",
163
+ "label": "Skip Timings",
164
+ "description": (
165
+ "Automatically fetch intro and recap skip timestamps from "
166
+ "TheIntroDB for verified episodes"
167
+ ),
168
+ "defaultValue": True,
169
+ },
170
+ ]
171
+
172
+ def _base_url(self) -> str:
173
+ return get_base_url("kat").rstrip("/")
174
+
175
+ def _get_with_waf(self, url: str, extra_headers: dict[str, str] | None = None) -> str:
176
+ base = "/".join(url.split("/")[:3])
177
+ headers = {"Referer": base}
178
+ if extra_headers:
179
+ headers.update(extra_headers)
180
+ return self.fetch_text(url, headers=headers)
181
+
182
+ def _fetch_posts(self, base_url: str, url: str, operation: str) -> list[dict[str, str]]:
183
+ try:
184
+ data = self._get_with_waf(url)
185
+ catalog: list[dict[str, str]] = []
186
+
187
+ parsed = _parse_svelte_data(data)
188
+ items = ((parsed or {}).get("data") or {}).get("items") or (parsed or {}).get("items")
189
+ if isinstance(items, list) and items:
190
+ for item in items:
191
+ if not isinstance(item, dict):
192
+ continue
193
+ raw_title = html_mod.unescape(str(item.get("post_title") or ""))
194
+ raw_title = re.sub(r"^Download\s+", "", raw_title, flags=re.I).strip()
195
+ slug = str(item.get("slug") or "")
196
+ link = slug if slug.startswith("/") else f"/{slug}"
197
+ image = str(item.get("thumbnail_image") or "")
198
+ if raw_title and link:
199
+ catalog.append({"title": raw_title, "link": link, "image": image})
200
+ if catalog:
201
+ return catalog
202
+
203
+ doc = parse_html(data)
204
+ for container in doc.select(".recent-posts, .posts-list, article"):
205
+ for el in container.children_elements():
206
+ img = el.select_one("img")
207
+ h_el = el.select_one("h2, h3")
208
+ a_el = el.select_one("a")
209
+ title = (img.attr("alt") if img else "") or (
210
+ h_el.text().strip() if h_el else ""
211
+ )
212
+ href = a_el.attr("href") if a_el else ""
213
+ image = img.attr("src") if img else ""
214
+ if title and href and image:
215
+ catalog.append(
216
+ {
217
+ "title": re.sub(r"^Download\s+", "", title, flags=re.I).strip(),
218
+ "link": to_relative_path(base_url, href),
219
+ "image": image,
220
+ }
221
+ )
222
+ return catalog
223
+ except Exception as err:
224
+ throw_provider_error("KatMovies", operation, err)
225
+ return []
226
+
227
+ def get_posts(self, filter_path: str = "", page: int = 1) -> list[dict[str, str]]:
228
+ base_url = self._base_url()
229
+ if not filter_path or filter_path == "/":
230
+ url = f"{base_url}/?page={page}" if page > 1 else f"{base_url}/"
231
+ else:
232
+ clean = filter_path if filter_path.startswith("/") else f"/{filter_path}"
233
+ url = f"{base_url}{clean}?page={page}" if page > 1 else f"{base_url}{clean}"
234
+ return self._fetch_posts(base_url, url, "posts")
235
+
236
+ def get_search_posts(self, query: str, page: int = 1) -> list[dict[str, str]]:
237
+ base_url = self._base_url()
238
+ q = quote(query)
239
+ url = f"{base_url}/?s={q}&page={page}" if page > 1 else f"{base_url}/?s={q}"
240
+ return self._fetch_posts(base_url, url, "search posts")
241
+
242
+ def get_meta(self, link: str) -> dict[str, Any]:
243
+ try:
244
+ base_url = self._base_url()
245
+ url = urljoin(f"{base_url}/", link)
246
+ data = self._get_with_waf(url)
247
+
248
+ parsed = _parse_svelte_data(data)
249
+ post_content = str(((parsed or {}).get("data") or {}).get("post_content") or "")
250
+ page_doc = parse_html(data)
251
+ doc = (
252
+ parse_html(f'<div class="entry-content">{post_content}</div>')
253
+ if post_content
254
+ else page_doc
255
+ )
256
+
257
+ info_box = doc.select_one(".yQ8hqd.ksSzJd.LoQAYe")
258
+ container = info_box if (info_box and info_box.html()) else doc.select_one(".FxvUNb")
259
+
260
+ imdb_id = ""
261
+ if container is not None:
262
+ imdb_a = container.select_one(
263
+ 'a[href*="imdb.com/title/tt"]:not([href*="imdb.com/title/tt/"])'
264
+ )
265
+ if imdb_a:
266
+ parts = imdb_a.attr("href").split("/")
267
+ if len(parts) > 4:
268
+ imdb_id = parts[4]
269
+ if not imdb_id:
270
+ a_imdb = doc.select_one('a[href*="imdb.com/title/tt"]')
271
+ if a_imdb:
272
+ m = re.search(r"tt\d+", a_imdb.attr("href"))
273
+ if m:
274
+ imdb_id = m.group(0)
275
+ if not imdb_id:
276
+ m = re.search(r"imdb\.com/title/(tt\d+)", data, re.I) or (
277
+ re.search(r"imdb\.com/title/(tt\d+)", post_content, re.I)
278
+ if post_content
279
+ else None
280
+ )
281
+ if m:
282
+ imdb_id = m.group(1)
283
+
284
+ page_title_el = page_doc.select_one("title")
285
+ og_title_el = page_doc.select_one('meta[property="og:title"]')
286
+ h1_el = doc.select_one("h1, .entry-title")
287
+ page_title = (
288
+ re.sub(r"^Download\s+", "", page_title_el.text(), flags=re.I).strip()
289
+ if page_title_el and page_title_el.text().strip()
290
+ else (
291
+ re.sub(
292
+ r"^Download\s+",
293
+ "",
294
+ og_title_el.attr("content"),
295
+ flags=re.I,
296
+ ).strip()
297
+ if og_title_el and og_title_el.attr("content").strip()
298
+ else (
299
+ re.sub(r"^Download\s+", "", h1_el.text(), flags=re.I).strip()
300
+ if h1_el
301
+ else ""
302
+ )
303
+ )
304
+ )
305
+
306
+ title = ""
307
+ if container is not None:
308
+ name_li = container.select_one('li:contains("Name")')
309
+ if name_li is not None:
310
+ title = "".join(
311
+ c for c in name_li.children if isinstance(c, str)
312
+ ).strip()
313
+ if not title:
314
+ h_el = doc.select_one("h3, h2")
315
+ if h_el:
316
+ title = re.sub(r"^Download\s+", "", h_el.text(), flags=re.I).strip()
317
+ if not title:
318
+ title = re.sub(r"\[.*?\]|\(.*?\)|\|.*", "", page_title).strip()
319
+
320
+ is_series = (
321
+ bool(re.search(r"season\s*\d+", page_title, re.I))
322
+ or bool(re.search(r"\[\s*s\d{1,2}\s*\]", page_title, re.I))
323
+ or (
324
+ bool(re.search(r"(?:^|\b)(?:season|episode)\b", post_content or data, re.I))
325
+ and "full movie" not in page_title.lower()
326
+ )
327
+ or len(doc.select(".yQ8hqd.ksSzJd.LoQAYe")) > 0
328
+ )
329
+ media_type = "series" if is_series else "movie"
330
+
331
+ synopsis = ""
332
+ if container is not None:
333
+ syn_els = container.select('li:contains("Stars"), li:contains("Storyline")')
334
+ synopsis = " ".join(el.text().strip() for el in syn_els).strip()
335
+ if not synopsis:
336
+ st_el = doc.select_one('p:contains("Storyline"), h2:contains("Storyline")')
337
+ st_p = st_el.next_element_sibling("p") if st_el else None
338
+ meta_desc = page_doc.select_one('meta[name="description"]')
339
+ synopsis = (st_p.text().strip() if st_p else "") or (
340
+ meta_desc.attr("content") if meta_desc else ""
341
+ )
342
+
343
+ ss_h4 = doc.select_one('h4:contains("SCREENSHOTS")')
344
+ ss_img = (
345
+ ss_h4.next_element_sibling().select_one("img")
346
+ if ss_h4 and ss_h4.next_element_sibling()
347
+ else None
348
+ )
349
+ amz_img = doc.select_one('img[src*="amazon.com"], img[src*="tmdb.org"]')
350
+ entry_img = doc.select_one(".entry-content img")
351
+ og_img = page_doc.select_one('meta[property="og:image"]')
352
+ image = (
353
+ (ss_img.attr("src") if ss_img else "")
354
+ or (amz_img.attr("src") if amz_img else "")
355
+ or (entry_img.attr("src") if entry_img else "")
356
+ or (og_img.attr("content") if og_img else "")
357
+ or ""
358
+ )
359
+
360
+ links: list[dict[str, Any]] = []
361
+ direct_links: list[dict[str, Any]] = []
362
+
363
+ for p_el in doc.select('.entry-content p:contains("Episode")'):
364
+ dl_title = p_el.text().strip()
365
+ if "Episode" not in dl_title:
366
+ continue
367
+ sib = p_el.next_element_sibling()
368
+ dl_link = ""
369
+ while sib is not None:
370
+ if sib.tag in ("h3", "h2"):
371
+ a_el = sib.select_one(
372
+ 'a:contains("1080"), a:contains("720"), '
373
+ 'a:contains("480"), a:contains("HEVC")'
374
+ )
375
+ if a_el:
376
+ dl_link = a_el.attr("href")
377
+ break
378
+ sib = sib.next_element_sibling()
379
+ if dl_link.strip():
380
+ direct_links.append(
381
+ {"title": dl_title, "link": dl_link, "type": "series"}
382
+ )
383
+
384
+ if direct_links:
385
+ links.append({"quality": "", "title": title, "directLinks": direct_links})
386
+
387
+ for a_el in doc.select(".entry-content a"):
388
+ a_href = a_el.attr("href")
389
+ a_text = re.sub(r"\s+", " ", a_el.text()).strip()
390
+ a_lower = a_text.lower()
391
+ if (
392
+ not a_href
393
+ or a_href == "#"
394
+ or not a_href.startswith("http")
395
+ or "imdb.com" in a_href
396
+ or "catimages" in a_href
397
+ or "sample" in a_lower
398
+ or "online" in a_lower
399
+ or "trailer" in a_lower
400
+ or "/directlink" in a_href
401
+ ):
402
+ continue
403
+
404
+ if (
405
+ re.search(r"links\.(?:kmhd|kmphotos)\.[a-z]+/(?:file|pack)/[\w-]+", a_href, re.I)
406
+ or re.search(r"(?:480|720|1080|2160|4k)", a_text, re.I)
407
+ or "gdflix" in a_href
408
+ or "hubcloud" in a_href
409
+ ):
410
+ parent = a_el.parent
411
+ link_title = ""
412
+ if parent is not None and parent.tag in ("h2", "h3", "h4", "h5", "p"):
413
+ link_title = re.sub(r"[\r\n\t]+", " ", parent.text()).strip()
414
+ if not link_title or link_title == a_text or len(link_title) < 4:
415
+ link_title = a_text
416
+
417
+ q_m = re.search(
418
+ r"\b(480p|720p|1080p|2160p|4k)\b",
419
+ f"{link_title} {a_text}",
420
+ re.I,
421
+ )
422
+ quality = q_m.group(0) if q_m else ""
423
+ is_pack = "/pack/" in a_href
424
+
425
+ if media_type == "movie":
426
+ if not any(
427
+ (l.get("directLinks") or [{}])[0].get("link") == a_href
428
+ for l in links
429
+ ):
430
+ links.append(
431
+ {
432
+ "quality": quality,
433
+ "title": link_title,
434
+ "directLinks": [
435
+ {
436
+ "link": a_href,
437
+ "title": link_title,
438
+ "type": "movie",
439
+ }
440
+ ],
441
+ }
442
+ )
443
+ else:
444
+ if is_pack:
445
+ if not any(l.get("episodesLink") == a_href for l in links):
446
+ links.append(
447
+ {
448
+ "quality": quality,
449
+ "title": link_title,
450
+ "episodesLink": a_href,
451
+ }
452
+ )
453
+ else:
454
+ already = any(
455
+ any(dl.get("link") == a_href for dl in (l.get("directLinks") or []))
456
+ for l in links
457
+ )
458
+ if not already:
459
+ first_group = next(
460
+ (l for l in links if l.get("directLinks")), None
461
+ )
462
+ if first_group is not None:
463
+ first_group["directLinks"].append(
464
+ {
465
+ "title": link_title,
466
+ "link": a_href,
467
+ "type": "series",
468
+ }
469
+ )
470
+ else:
471
+ links.append(
472
+ {
473
+ "quality": quality,
474
+ "title": link_title,
475
+ "directLinks": [
476
+ {
477
+ "link": a_href,
478
+ "title": link_title,
479
+ "type": "series",
480
+ }
481
+ ],
482
+ }
483
+ )
484
+
485
+ quick_download = self.kv.get("katmovies_quickDownload", True)
486
+ website_info: dict[str, Any] = {
487
+ "title": title,
488
+ "synopsis": synopsis,
489
+ "image": image,
490
+ "imdbId": imdb_id or "",
491
+ "type": media_type,
492
+ "quickDownload": True if quick_download is None else bool(quick_download),
493
+ "linkList": [
494
+ {**item, "title": format_season_title(item["title"])}
495
+ for item in links
496
+ ],
497
+ "webUrl": url,
498
+ }
499
+ if not imdb_id:
500
+ return website_info
501
+
502
+ try:
503
+ cinemeta = get_cinemeta_meta(imdb_id, media_type, self.session)
504
+ if cinemeta:
505
+ if media_type == "series" and cinemeta.get("type") == "series":
506
+ skip_timings = self.kv.get("katmovies_skipTimings", True)
507
+ st_val = True if skip_timings is None else bool(skip_timings)
508
+ updated_list: list[dict[str, Any]] = []
509
+ for item in website_info["linkList"]:
510
+ season_num = get_cinemeta_season(item["title"]) or get_cinemeta_season(title)
511
+ if not season_num:
512
+ updated_list.append(item)
513
+ continue
514
+ if item.get("directLinks"):
515
+ enriched = enrich_cinemeta_episodes(
516
+ item["directLinks"],
517
+ cinemeta.get("videos") or [],
518
+ season_num,
519
+ )
520
+ if st_val:
521
+ try:
522
+ enriched = enrich_episodes_with_skip_timings(
523
+ enriched, imdb_id, season_num, self.session
524
+ )
525
+ except Exception:
526
+ pass
527
+ updated_list.append({**item, "directLinks": enriched})
528
+ elif item.get("episodesLink"):
529
+ updated_list.append(
530
+ {
531
+ **item,
532
+ "episodesLink": add_cinemeta_context(
533
+ urljoin(url, item["episodesLink"]),
534
+ imdb_id,
535
+ season_num,
536
+ ),
537
+ }
538
+ )
539
+ else:
540
+ updated_list.append(item)
541
+ website_info["linkList"] = updated_list
542
+ return apply_cinemeta_meta(website_info, cinemeta)
543
+ except Exception:
544
+ return website_info
545
+ return website_info
546
+ except Exception as err:
547
+ throw_provider_error("KatMovies", "metadata", err)
548
+ return {}
549
+
550
+ def _extract_kmhd_episodes(self, katlink: str, cached_data: str = "") -> list[str]:
551
+ origin = "https://links.kmhd.me"
552
+ try:
553
+ parsed = urlparse(katlink)
554
+ if parsed.scheme and parsed.netloc:
555
+ origin = f"{parsed.scheme}://{parsed.netloc}"
556
+ except Exception:
557
+ pass
558
+
559
+ page_data = cached_data
560
+ if not page_data:
561
+ try:
562
+ page_data = self._get_with_waf(
563
+ katlink, {"Cookie": "unlocked=true", "Referer": f"{origin}/"}
564
+ )
565
+ except Exception:
566
+ page_data = ""
567
+
568
+ pack_m = re.search(r"[\w]+_[a-f0-9]{8}", katlink)
569
+ if pack_m and page_data:
570
+ pack_id = pack_m.group(0)
571
+ tok_m = re.search(r'"PUBLIC_TOKEN"\s*:\s*"([^"]+)"', page_data)
572
+ token = tok_m.group(1) if tok_m else _DEFAULT_KMHD_TOKEN
573
+ chibi_m = re.search(
574
+ r'"PUBLIC_CHIBI_PATH"\s*:\s*"https?://([^"/]+)"', page_data
575
+ )
576
+ api_host = (
577
+ re.sub(r"^upload-[^.]+\.", "api.", chibi_m.group(1))
578
+ if chibi_m
579
+ else "api.dandndn.one"
580
+ )
581
+ try:
582
+ res = self.fetch_json(
583
+ f"https://{api_host}/api/v1/file/{pack_id}",
584
+ headers={
585
+ "Authorization": f"Bearer {token}",
586
+ "Origin": origin,
587
+ "Referer": f"{origin}/",
588
+ },
589
+ )
590
+ zip_files = res.get("zip_files") if isinstance(res, dict) else None
591
+ if isinstance(zip_files, list) and zip_files:
592
+ return [str(x) for x in zip_files]
593
+ except Exception:
594
+ pass
595
+
596
+ ids = re.findall(r"[\w]+_[a-f0-9]{8}", page_data or "")
597
+ return list(dict.fromkeys(ids))
598
+
599
+ def get_episodes(
600
+ self,
601
+ url: str,
602
+ imdb_id: str = "",
603
+ season: int | None = None,
604
+ ) -> list[dict[str, Any]]:
605
+ episodes_link: list[dict[str, Any]] = []
606
+ try:
607
+ req_url, ctx_imdb, ctx_season = read_cinemeta_context(url)
608
+ eff_imdb = ctx_imdb or imdb_id
609
+ eff_season = ctx_season if ctx_season is not None else season
610
+
611
+ def _finish() -> list[dict[str, Any]]:
612
+ qd = self.kv.get("katmovies_quickDownload", True)
613
+ qd_val = True if qd is None else bool(qd)
614
+ if not eff_imdb or not eff_season:
615
+ return [{**ep, "quickDownload": qd_val} for ep in episodes_link]
616
+ try:
617
+ enriched = episodes_link
618
+ cinemeta = get_cinemeta_meta(eff_imdb, "series", self.session)
619
+ if cinemeta:
620
+ enriched = enrich_cinemeta_episodes(
621
+ episodes_link, cinemeta.get("videos") or [], eff_season
622
+ )
623
+ skip_timings = self.kv.get("katmovies_skipTimings", True)
624
+ if True if skip_timings is None else bool(skip_timings):
625
+ try:
626
+ enriched = enrich_episodes_with_skip_timings(
627
+ enriched, eff_imdb, eff_season, self.session
628
+ )
629
+ except Exception:
630
+ pass
631
+ return [{**ep, "quickDownload": qd_val} for ep in enriched]
632
+ except Exception:
633
+ return [{**ep, "quickDownload": qd_val} for ep in episodes_link]
634
+
635
+ if "gdflix" in req_url:
636
+ base_url = req_url.split("/pack")[0]
637
+ doc = parse_html(self._get_with_waf(req_url))
638
+ for idx, item in enumerate(doc.select(".list-group-item")):
639
+ a_el = item.select_one("a")
640
+ href = a_el.attr("href") if a_el else ""
641
+ if href:
642
+ episodes_link.append(
643
+ {
644
+ "title": item.text().strip() or f"Episode {idx + 1}",
645
+ "link": href if href.startswith("http") else f"{base_url}{href}",
646
+ }
647
+ )
648
+ if episodes_link:
649
+ return _finish()
650
+
651
+ if "/pack" in req_url or "kmhd" in req_url or "kmphotos" in req_url:
652
+ data = self._get_with_waf(req_url)
653
+ parsed = _parse_svelte_data(data)
654
+ info = (parsed or {}).get("info") or ((parsed or {}).get("data") or {}).get("info")
655
+ host_base = req_url.split("/pack")[0].split("/file")[0]
656
+ if isinstance(info, dict):
657
+ for ep_id, ep_val in info.items():
658
+ ep_name = ep_val.get("name") if isinstance(ep_val, dict) else None
659
+ ep_title = (
660
+ re.sub(r"\.mkv$", "", str(ep_name), flags=re.I)
661
+ .replace(".", " ")
662
+ .strip()
663
+ if ep_name
664
+ else str(ep_id)
665
+ )
666
+ episodes_link.append(
667
+ {"title": ep_title, "link": f"{host_base}/file/{ep_id}"}
668
+ )
669
+ if episodes_link:
670
+ return _finish()
671
+
672
+ ep_ids = self._extract_kmhd_episodes(req_url, data)
673
+ if ep_ids:
674
+ for idx, ep_id in enumerate(ep_ids):
675
+ episodes_link.append(
676
+ {
677
+ "title": f"Episode {idx + 1}",
678
+ "link": f"{host_base}/file/{ep_id}",
679
+ }
680
+ )
681
+ return _finish()
682
+
683
+ ep_doc = parse_html(self._get_with_waf(req_url, {"Cookie": "unlocked=true"}))
684
+ for idx, a_el in enumerate(
685
+ ep_doc.select(
686
+ ".autohyperlink, a[href*='/file/'], a[href*='hubcloud'], a[href*='gdflix']"
687
+ )
688
+ ):
689
+ href = a_el.attr("href")
690
+ if href:
691
+ episodes_link.append(
692
+ {"title": a_el.text().strip() or f"Episode {idx + 1}", "link": href}
693
+ )
694
+ return _finish()
695
+ except Exception as err:
696
+ throw_provider_error("KatMovies", "episodes", err)
697
+ return []
698
+
699
+ def _extract_kmhd_link(self, katlink: str) -> str:
700
+ origin = "https://links.kmhd.me"
701
+ try:
702
+ parsed = urlparse(katlink)
703
+ if parsed.scheme and parsed.netloc:
704
+ origin = f"{parsed.scheme}://{parsed.netloc}"
705
+ except Exception:
706
+ pass
707
+
708
+ page_data = ""
709
+ try:
710
+ page_data = self._get_with_waf(
711
+ katlink, {"Cookie": "unlocked=true", "Referer": f"{origin}/"}
712
+ )
713
+ except Exception:
714
+ pass
715
+
716
+ if page_data:
717
+ parsed = _parse_svelte_data(page_data)
718
+ val = (parsed or {}).get("val") or ((parsed or {}).get("data") or {}).get("val") or {}
719
+ upload_links = val.get("upload_links") if isinstance(val, dict) else {}
720
+ links_meta = (parsed or {}).get("links") or ((parsed or {}).get("data") or {}).get("links") or {}
721
+
722
+ hub_id = upload_links.get("hubdrive_res") if isinstance(upload_links, dict) else None
723
+ if hub_id and hub_id != "None":
724
+ hub_base = (
725
+ ((links_meta.get("hubdrive_res") or {}).get("link"))
726
+ if isinstance(links_meta, dict)
727
+ else None
728
+ ) or "https://hubcloud.cx/drive/"
729
+ return f"{hub_base}{hub_id}"
730
+
731
+ gd_id = upload_links.get("gdflix_res") if isinstance(upload_links, dict) else None
732
+ if gd_id and gd_id != "None":
733
+ gd_base = (
734
+ ((links_meta.get("gdflix_res") or {}).get("link"))
735
+ if isinstance(links_meta, dict)
736
+ else None
737
+ ) or "https://gd.kmhd.eu/file/"
738
+ return f"{gd_base}{gd_id}"
739
+
740
+ hub_m = re.search(r'hubdrive_res:\s*"([^"]+)"', page_data)
741
+ if hub_m and hub_m.group(1) != "None":
742
+ link_m = re.search(
743
+ r'hubdrive_res\s*:\s*\{[^}]*?link\s*:\s*"([^"]+)"', page_data
744
+ )
745
+ base = (
746
+ link_m.group(1).replace("hubcloud.foo", "hubcloud.cx")
747
+ if link_m
748
+ else "https://hubcloud.cx/drive/"
749
+ )
750
+ return f"{base}{hub_m.group(1)}"
751
+
752
+ file_m = re.search(r"[\w]+_[a-f0-9]{8}", katlink)
753
+ if file_m:
754
+ file_id = file_m.group(0)
755
+ tok_m = re.search(r'"PUBLIC_TOKEN"\s*:\s*"([^"]+)"', page_data)
756
+ token = tok_m.group(1) if tok_m else _DEFAULT_KMHD_TOKEN
757
+ chibi_m = re.search(
758
+ r'"PUBLIC_CHIBI_PATH"\s*:\s*"https?://([^"/]+)"', page_data
759
+ )
760
+ api_host = (
761
+ re.sub(r"^upload-[^.]+\.", "api.", chibi_m.group(1))
762
+ if chibi_m
763
+ else "api.dandndn.one"
764
+ )
765
+ try:
766
+ res = self.fetch_json(
767
+ f"https://{api_host}/api/v1/file/{file_id}",
768
+ headers={
769
+ "Authorization": f"Bearer {token}",
770
+ "Origin": origin,
771
+ "Referer": f"{origin}/",
772
+ },
773
+ )
774
+ up = res.get("upload_links") if isinstance(res, dict) else {}
775
+ if isinstance(up, dict):
776
+ if up.get("hubdrive_res") and up["hubdrive_res"] != "None":
777
+ return f"https://hubcloud.cx/drive/{up['hubdrive_res']}"
778
+ if up.get("gdflix_res") and up["gdflix_res"] != "None":
779
+ return f"https://new.gdflix.cfd/file/{up['gdflix_res']}"
780
+ except Exception:
781
+ pass
782
+
783
+ return katlink
784
+
785
+ def get_stream(
786
+ self,
787
+ url: str,
788
+ is_download: bool = False,
789
+ media_type: str = "movie",
790
+ ) -> list[dict[str, Any]]:
791
+ try:
792
+ if "gdflix" in url or "gd.kmhd" in url:
793
+ return gdflix_extractor(url, self.session)
794
+
795
+ if "kmhd" in url or "kmphotos" in url:
796
+ hubcloud_link = self._extract_kmhd_link(url)
797
+ if "gdflix" in hubcloud_link or "gd.kmhd" in hubcloud_link:
798
+ return gdflix_extractor(hubcloud_link, self.session)
799
+ return hubcloud_extractor(
800
+ hubcloud_link,
801
+ self.session,
802
+ is_download=is_download,
803
+ provider_value="katmovies",
804
+ kv_store=self.kv,
805
+ )
806
+
807
+ return hubcloud_extractor(
808
+ url,
809
+ self.session,
810
+ is_download=is_download,
811
+ provider_value="katmovies",
812
+ kv_store=self.kv,
813
+ )
814
+ except Exception as err:
815
+ throw_provider_error("KatMovies", "stream", err)
816
+ return []