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,566 @@
1
+ """Pure-Python YouTube provider."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import json
7
+ import re
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from typing import Any
10
+ from urllib.parse import quote
11
+
12
+ from ..html import parse_html
13
+ from .common import BaseProvider
14
+
15
+ _DEFAULT_HEADERS = {
16
+ "User-Agent": (
17
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
18
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
19
+ ),
20
+ "Accept-Language": "en-US,en;q=0.9",
21
+ }
22
+
23
+ _FALLBACK_VISITOR_DATA = (
24
+ "CgtSdHczNXdoNzhqQSiYoJ7WBjIKCgJJThIEGgAgZGLfAgrcAjIyLllUPUpQRHNlLWd6ZzYwc3FRN2JRSGNlMzdJWHFlelQxLUZMd00yR3M5"
25
+ "X1gxZUd4RWtRdUxyakphLS1iaU1LMk9fcU83MHl4cExXcFRKd3p2ckcxcGMyU0RBS3FmYXVPOGpnd1dpWUtUdU5rQ1pZZzFZeHh3UkFnRXYt"
26
+ "NE9YR1gtaWhvd2RvblQ3dENIV0NmdDgtZU9Ibi04M2QtUlBoZlhoZGpyNjE4YlFGY0VWVU5UanJBZ2g0cVFCRXJWbktnQm4tV1Eydm1CNE5q"
27
+ "Tl9FajBQVV9TaFlsYkxEOGY3WFJaUGVNRnIzTzhoejEyMDJQQlJpRUwyX1gtV2N0WG1YRmFvLVYyZXRpTWJDSUZLaU9jNEZUTU1lSktrWVBK"
28
+ "V1A0WlV5eFZYeTNPZUlFMS1XeXpaa1Y3T1dVVDE5SllHcTNSN0NFcE5HNTNFZElmcW9UVDdMYjV2N09mdw=="
29
+ )
30
+
31
+ _QUALITY_ORDER: dict[str, int] = {
32
+ "2160": 1,
33
+ "1440": 2,
34
+ "1080": 3,
35
+ "720": 4,
36
+ "480": 5,
37
+ "360": 6,
38
+ "240": 7,
39
+ "144": 8,
40
+ }
41
+
42
+
43
+ def _extract_video_id(link: str) -> str:
44
+ m = re.search(
45
+ r"(?:v=|/watch\?v=|/embed/|/v/|youtu\.be/|/shorts/)([a-zA-Z0-9_-]{11})",
46
+ link,
47
+ re.I,
48
+ ) or re.search(r"([a-zA-Z0-9_-]{11})", link)
49
+ return m.group(1) if m else link
50
+
51
+
52
+ def _format_views(raw_count: Any) -> str:
53
+ try:
54
+ num = int(raw_count)
55
+ except (TypeError, ValueError):
56
+ return ""
57
+ if num <= 0:
58
+ return ""
59
+ if num >= 1_000_000_000:
60
+ return f"{num / 1_000_000_000:.1f}".removesuffix(".0") + "B views"
61
+ if num >= 1_000_000:
62
+ return f"{num / 1_000_000:.1f}".removesuffix(".0") + "M views"
63
+ if num >= 1_000:
64
+ return f"{num / 1_000:.1f}".removesuffix(".0") + "K views"
65
+ return f"{num:,} views"
66
+
67
+
68
+ def _format_duration(total_seconds: Any) -> str:
69
+ try:
70
+ sec = int(total_seconds)
71
+ except (TypeError, ValueError):
72
+ return ""
73
+ if sec <= 0:
74
+ return ""
75
+ m, s = divmod(sec, 60)
76
+ h, rem_m = divmod(m, 60)
77
+ if h > 0:
78
+ return f"{h}:{rem_m:02d}:{s:02d}"
79
+ return f"{m}:{s:02d}"
80
+
81
+
82
+ def _extract_videos_from_data(data: Any) -> list[dict[str, Any]]:
83
+ posts: list[dict[str, Any]] = []
84
+ seen_ids: set[str] = set()
85
+
86
+ def walk(obj: Any) -> None:
87
+ if isinstance(obj, dict):
88
+ vr = obj.get("videoRenderer")
89
+ if isinstance(vr, dict):
90
+ vid = vr.get("videoId")
91
+ if vid and vid not in seen_ids:
92
+ seen_ids.add(vid)
93
+ t_obj = vr.get("title") or {}
94
+ title = (
95
+ "".join(r.get("text", "") for r in t_obj.get("runs", []) if isinstance(r, dict))
96
+ or t_obj.get("simpleText")
97
+ or ""
98
+ )
99
+ o_obj = vr.get("ownerText") or vr.get("shortBylineText") or {}
100
+ channel = "".join(
101
+ r.get("text", "") for r in o_obj.get("runs", []) if isinstance(r, dict)
102
+ )
103
+ views = (
104
+ (vr.get("shortViewCountText") or {}).get("simpleText")
105
+ or (vr.get("viewCountText") or {}).get("simpleText")
106
+ or ""
107
+ )
108
+ duration = (vr.get("lengthText") or {}).get("simpleText") or ""
109
+ tag = f"{channel}{f' • {views}' if views else ''}" if channel else (views or "")
110
+ item: dict[str, Any] = {
111
+ "title": title.strip(),
112
+ "link": f"https://www.youtube.com/watch?v={vid}",
113
+ "image": f"https://i.ytimg.com/vi/{vid}/hq720.jpg",
114
+ "aspectRatio": 16 / 9,
115
+ "borderRadius": 8,
116
+ }
117
+ if tag:
118
+ item["tag"] = tag
119
+ if duration:
120
+ item["cornerTag"] = duration
121
+ posts.append(item)
122
+ for v in obj.values():
123
+ walk(v)
124
+ elif isinstance(obj, list):
125
+ for v in obj:
126
+ walk(v)
127
+
128
+ walk(data)
129
+ return posts
130
+
131
+
132
+ def _extract_captions(data: Any) -> list[dict[str, str]]:
133
+ subtitles: list[dict[str, str]] = []
134
+ if not isinstance(data, dict):
135
+ return subtitles
136
+ tracks = ((data.get("captions") or {}).get("playerCaptionsTracklistRenderer") or {}).get("captionTracks")
137
+ if isinstance(tracks, list):
138
+ for c in tracks:
139
+ if isinstance(c, dict) and c.get("baseUrl"):
140
+ n_obj = c.get("name") or {}
141
+ runs = n_obj.get("runs") or []
142
+ name = (
143
+ (runs[0].get("text") if runs and isinstance(runs[0], dict) else None)
144
+ or n_obj.get("simpleText")
145
+ or c.get("languageCode")
146
+ or ""
147
+ )
148
+ base_url = c["baseUrl"]
149
+ subtitles.append(
150
+ {
151
+ "title": name,
152
+ "language": c.get("languageCode") or name,
153
+ "type": "text/vtt",
154
+ "uri": base_url if "fmt=" in base_url else f"{base_url}&fmt=vtt",
155
+ }
156
+ )
157
+ return subtitles
158
+
159
+
160
+ class YoutubeClient(BaseProvider):
161
+ """Provider client for YouTube."""
162
+
163
+ name = "youtube"
164
+ catalog = [
165
+ {"title": "Trending", "filter": "trending"},
166
+ {"title": "Music", "filter": "trending music"},
167
+ {"title": "Gaming", "filter": "trending gaming"},
168
+ {"title": "Movies & Trailers", "filter": "official movie trailers"},
169
+ {"title": "News", "filter": "world news"},
170
+ {"title": "Documentaries", "filter": "documentary full"},
171
+ {"title": "Tech & Science", "filter": "technology science"},
172
+ ]
173
+ genres = [
174
+ {"title": "Podcasts", "filter": "popular podcasts"},
175
+ {"title": "Animation", "filter": "animation short film"},
176
+ {"title": "Comedy", "filter": "comedy standup"},
177
+ {"title": "Education", "filter": "educational documentary"},
178
+ {"title": "Sports", "filter": "sports highlights"},
179
+ {"title": "Nature", "filter": "4k nature wildlife"},
180
+ ]
181
+ settings_schema = [
182
+ {
183
+ "key": "preferredQuality",
184
+ "type": "select",
185
+ "label": "Preferred Streaming Quality",
186
+ "description": "Default resolution to prioritize when loading video playback",
187
+ "options": [
188
+ {"label": "Auto (Highest Available)", "value": "auto"},
189
+ {"label": "1080p (Full HD)", "value": "1080"},
190
+ {"label": "720p (HD)", "value": "720"},
191
+ {"label": "480p (Standard)", "value": "480"},
192
+ {"label": "360p (Data Saver)", "value": "360"},
193
+ ],
194
+ "defaultValue": "auto",
195
+ }
196
+ ]
197
+
198
+ def _search_page(self, query: str, page: int) -> list[dict[str, Any]]:
199
+ try:
200
+ url = f"https://www.youtube.com/results?search_query={quote(query)}"
201
+ html = self.fetch_text(url, headers=_DEFAULT_HEADERS)
202
+ m = (
203
+ re.search(r"var ytInitialData\s*=\s*(\{.+?\});</script>", html)
204
+ or re.search(r"ytInitialData\s*=\s*(\{.+?\});", html)
205
+ )
206
+ if not m:
207
+ return []
208
+ data = json.loads(m.group(1))
209
+ posts = _extract_videos_from_data(data)
210
+ page_size = 20
211
+ start = (page - 1) * page_size
212
+ if start >= len(posts):
213
+ return posts[:page_size]
214
+ return posts[start : start + page_size]
215
+ except Exception:
216
+ return []
217
+
218
+ def get_posts(self, filter_path: str = "", page: int = 1) -> list[dict[str, Any]]:
219
+ return self._search_page(filter_path or "trending", page)
220
+
221
+ def get_search_posts(self, query: str, page: int = 1) -> list[dict[str, Any]]:
222
+ return self._search_page(query, page)
223
+
224
+ def get_meta(self, link: str) -> dict[str, Any]:
225
+ video_id = _extract_video_id(link)
226
+ watch_url = f"https://www.youtube.com/watch?v={video_id}"
227
+ landscape_img = f"https://i.ytimg.com/vi/{video_id}/hq720.jpg"
228
+ try:
229
+ html = self.fetch_text(watch_url, headers=_DEFAULT_HEADERS)
230
+ doc = parse_html(html)
231
+
232
+ m_title = doc.select_one('meta[name="title"]')
233
+ og_title = doc.select_one('meta[property="og:title"]')
234
+ t_tag = doc.select_one("title")
235
+ title = (
236
+ (m_title.attr("content") if m_title else "")
237
+ or (og_title.attr("content") if og_title else "")
238
+ or (re.sub(r" - YouTube$", "", t_tag.text()).strip() if t_tag else "")
239
+ )
240
+
241
+ m_desc = doc.select_one('meta[name="description"]')
242
+ og_desc = doc.select_one('meta[property="og:description"]')
243
+ synopsis = (
244
+ (m_desc.attr("content") if m_desc else "")
245
+ or (og_desc.attr("content") if og_desc else "")
246
+ )
247
+
248
+ l_name = doc.select_one('link[itemprop="name"]') or doc.select_one(
249
+ 'span[itemprop="author"] link[itemprop="name"]'
250
+ )
251
+ channel = l_name.attr("content") if l_name else ""
252
+
253
+ view_str = ""
254
+ duration_str = ""
255
+ pub_date_str = ""
256
+ category = ""
257
+ likes = ""
258
+
259
+ pr_m = (
260
+ re.search(r"var ytInitialPlayerResponse\s*=\s*(\{.+?\});(?:var|</script>)", html)
261
+ or re.search(r"ytInitialPlayerResponse\s*=\s*(\{.+?\});", html)
262
+ )
263
+ if pr_m:
264
+ try:
265
+ pr = json.loads(pr_m.group(1))
266
+ details = pr.get("videoDetails") or {}
267
+ title = details.get("title") or title
268
+ synopsis = details.get("shortDescription") or synopsis
269
+ channel = details.get("author") or channel
270
+ if details.get("viewCount"):
271
+ view_str = _format_views(details["viewCount"])
272
+ if details.get("lengthSeconds"):
273
+ duration_str = _format_duration(details["lengthSeconds"])
274
+ micro = (pr.get("microformat") or {}).get("playerMicroformatRenderer") or {}
275
+ if micro.get("category"):
276
+ category = micro["category"]
277
+ pub_date = micro.get("publishDate") or micro.get("uploadDate")
278
+ if pub_date:
279
+ try:
280
+ dt = datetime.datetime.fromisoformat(pub_date.replace("Z", "+00:00"))
281
+ pub_date_str = dt.strftime("%b %d, %Y").replace(" 0", " ")
282
+ except Exception:
283
+ pass
284
+ except Exception:
285
+ pass
286
+
287
+ d_m = (
288
+ re.search(r"var ytInitialData\s*=\s*(\{.+?\});</script>", html)
289
+ or re.search(r"ytInitialData\s*=\s*(\{.+?\});", html)
290
+ )
291
+ if d_m:
292
+ try:
293
+ data = json.loads(d_m.group(1))
294
+
295
+ def find_likes(obj: Any) -> None:
296
+ nonlocal likes
297
+ if likes or not isinstance(obj, (dict, list)):
298
+ return
299
+ if isinstance(obj, dict):
300
+ if obj.get("iconName") == "LIKE" and isinstance(obj.get("title"), str):
301
+ likes = obj["title"].strip()
302
+ return
303
+ dt = obj.get("defaultText")
304
+ if (
305
+ isinstance(dt, dict)
306
+ and isinstance(dt.get("simpleText"), str)
307
+ and re.match(r"^[0-9.]+[KMB]?$", dt["simpleText"], re.I)
308
+ ):
309
+ likes = dt["simpleText"].strip()
310
+ return
311
+ for v in obj.values():
312
+ if not likes:
313
+ find_likes(v)
314
+ else:
315
+ for v in obj:
316
+ if not likes:
317
+ find_likes(v)
318
+
319
+ find_likes(data)
320
+ except Exception:
321
+ pass
322
+
323
+ if not likes:
324
+ rm = re.search(r'"iconName":"LIKE"[^}]*?"title":"([^"]+)"', html)
325
+ if rm:
326
+ likes = rm.group(1).strip()
327
+
328
+ tags: list[str] = []
329
+ if view_str:
330
+ tags.append(view_str)
331
+ if likes:
332
+ tags.append(likes if "like" in likes.lower() else f"{likes} likes")
333
+ if duration_str:
334
+ tags.append(f"⏱ {duration_str}")
335
+ if pub_date_str:
336
+ tags.append(pub_date_str)
337
+ if category:
338
+ tags.append(category)
339
+
340
+ out: dict[str, Any] = {
341
+ "title": title or "YouTube Video",
342
+ "synopsis": synopsis,
343
+ "image": landscape_img,
344
+ "poster": landscape_img,
345
+ "imdbId": "",
346
+ "type": "movie",
347
+ "linkList": [
348
+ {
349
+ "title": "Watch Video",
350
+ "quality": "HD",
351
+ "directLinks": [
352
+ {
353
+ "title": "Play Video",
354
+ "link": f"https://www.youtube.com/watch?v={video_id}",
355
+ "type": "movie",
356
+ "image": landscape_img,
357
+ }
358
+ ],
359
+ }
360
+ ],
361
+ "webUrl": watch_url,
362
+ }
363
+ if channel:
364
+ out["cast"] = [channel]
365
+ if tags:
366
+ out["tags"] = tags
367
+ return out
368
+ except Exception:
369
+ return {
370
+ "title": "YouTube Video",
371
+ "synopsis": "",
372
+ "image": landscape_img,
373
+ "poster": landscape_img,
374
+ "imdbId": "",
375
+ "type": "movie",
376
+ "linkList": [
377
+ {
378
+ "title": "Watch Video",
379
+ "quality": "HD",
380
+ "directLinks": [
381
+ {
382
+ "title": "Play Video",
383
+ "link": f"https://www.youtube.com/watch?v={video_id}",
384
+ "type": "movie",
385
+ }
386
+ ],
387
+ }
388
+ ],
389
+ "webUrl": watch_url,
390
+ }
391
+
392
+ def _get_visitor_data(self) -> str:
393
+ try:
394
+ cached = self.kv.get("youtube_visitor_data")
395
+ if cached:
396
+ return str(cached)
397
+ html = self.fetch_text(
398
+ "https://www.youtube.com",
399
+ headers={
400
+ "User-Agent": (
401
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
402
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
403
+ )
404
+ },
405
+ timeout=3,
406
+ )
407
+ m = re.search(r'"visitorData"\s*:\s*"([^"]+)"', html)
408
+ if m and m.group(1):
409
+ self.kv.set("youtube_visitor_data", m.group(1))
410
+ return m.group(1)
411
+ except Exception:
412
+ pass
413
+ return _FALLBACK_VISITOR_DATA
414
+
415
+ def _fetch_innertube(self, video_id: str) -> tuple[list[dict[str, Any]], list[dict[str, str]]]:
416
+ visitor_data = self._get_visitor_data()
417
+ innertube_url = "https://www.youtube.com/youtubei/v1/player?prettyPrint=false&alt=json"
418
+
419
+ def fetch_vision() -> Any:
420
+ return self.fetch_json(
421
+ innertube_url,
422
+ method="POST",
423
+ headers={
424
+ "Content-Type": "application/json",
425
+ "X-YouTube-Client-Name": "101",
426
+ "X-YouTube-Client-Version": "1.02",
427
+ "X-Goog-Visitor-Id": visitor_data,
428
+ "User-Agent": (
429
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) "
430
+ "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15"
431
+ ),
432
+ "Origin": "https://www.youtube.com",
433
+ "Referer": f"https://www.youtube.com/watch?v={video_id}",
434
+ },
435
+ json_body={
436
+ "videoId": video_id,
437
+ "racyCheckOk": True,
438
+ "contentCheckOk": True,
439
+ "playbackContext": {"contentPlaybackContext": {"signatureTimestamp": 20731}},
440
+ "context": {
441
+ "client": {
442
+ "hl": "en",
443
+ "gl": "US",
444
+ "visitorData": visitor_data,
445
+ "clientName": "VISIONOS",
446
+ "clientVersion": "1.02",
447
+ "osName": "visionOS",
448
+ "osVersion": "26.5.23O471",
449
+ "platform": "MOBILE",
450
+ "deviceMake": "Apple",
451
+ "deviceModel": "RealityDevice17,1",
452
+ }
453
+ },
454
+ },
455
+ timeout=5,
456
+ )
457
+
458
+ def fetch_vr() -> Any:
459
+ return self.fetch_json(
460
+ innertube_url,
461
+ method="POST",
462
+ headers={
463
+ "Content-Type": "application/json",
464
+ "User-Agent": "Mozilla/5.0 (Linux; Android 12; Quest 3) AppleWebKit/537.36",
465
+ },
466
+ json_body={
467
+ "videoId": video_id,
468
+ "racyCheckOk": True,
469
+ "contentCheckOk": True,
470
+ "playbackContext": {"contentPlaybackContext": {"signatureTimestamp": 20731}},
471
+ "context": {
472
+ "client": {
473
+ "clientName": "ANDROID_VR",
474
+ "clientVersion": "1.60.19",
475
+ "deviceMake": "Oculus",
476
+ "deviceModel": "Quest 3",
477
+ "platform": "MOBILE",
478
+ "hl": "en",
479
+ "gl": "US",
480
+ }
481
+ },
482
+ },
483
+ timeout=5,
484
+ )
485
+
486
+ v_data: Any = None
487
+ vr_data: Any = None
488
+ with ThreadPoolExecutor(max_workers=2) as pool:
489
+ f1 = pool.submit(fetch_vision)
490
+ f2 = pool.submit(fetch_vr)
491
+ try:
492
+ v_data = f1.result()
493
+ except Exception:
494
+ pass
495
+ try:
496
+ vr_data = f2.result()
497
+ except Exception:
498
+ pass
499
+
500
+ streams: list[dict[str, Any]] = []
501
+ master_url = ((v_data or {}).get("streamingData") or {}).get("hlsManifestUrl")
502
+ if master_url:
503
+ streams.append(
504
+ {
505
+ "server": "YouTube HLS (Multi-Quality)",
506
+ "link": master_url,
507
+ "type": "m3u8",
508
+ "quality": "1080",
509
+ "tag": "Audio + Video",
510
+ }
511
+ )
512
+
513
+ for f in ((vr_data or {}).get("streamingData") or {}).get("formats") or []:
514
+ if isinstance(f, dict) and f.get("url"):
515
+ q_label = f.get("qualityLabel") or "360p"
516
+ streams.append(
517
+ {
518
+ "server": f"YouTube ({q_label} MP4)",
519
+ "link": f["url"],
520
+ "type": "mp4",
521
+ "quality": q_label.replace("p", ""),
522
+ "tag": "Audio + Video",
523
+ }
524
+ )
525
+
526
+ subtitles = _extract_captions(v_data) or _extract_captions(vr_data) or []
527
+ return streams, subtitles
528
+
529
+ def get_stream(
530
+ self,
531
+ url: str,
532
+ is_download: bool = False,
533
+ media_type: str = "movie",
534
+ ) -> list[dict[str, Any]]:
535
+ video_id = _extract_video_id(url)
536
+ if not video_id:
537
+ return []
538
+
539
+ preferred_quality = self.kv.get("preferredQuality")
540
+ streams, subtitles = self._fetch_innertube(video_id)
541
+ if not streams:
542
+ return []
543
+
544
+ seen: set[str] = set()
545
+ unique: list[dict[str, Any]] = []
546
+ for s in streams:
547
+ if s["link"] not in seen:
548
+ seen.add(s["link"])
549
+ if subtitles and "subtitles" not in s:
550
+ s["subtitles"] = subtitles
551
+ unique.append(s)
552
+
553
+ clean_pref = str(preferred_quality).replace("p", "") if preferred_quality and preferred_quality != "auto" else ""
554
+
555
+ def sort_key(s: dict[str, Any]) -> tuple[int, int, int]:
556
+ if is_download:
557
+ type_rank = 0 if s.get("type") == "mp4" else 1
558
+ else:
559
+ is_hls = "Multi-Quality" in s.get("server", "") or s.get("type") == "m3u8"
560
+ type_rank = 0 if is_hls else 1
561
+ pref_rank = 0 if (clean_pref and s.get("quality") == clean_pref) else 1
562
+ q_rank = _QUALITY_ORDER.get(str(s.get("quality") or ""), 99)
563
+ return (type_rank, pref_rank, q_rank)
564
+
565
+ unique.sort(key=sort_key)
566
+ return unique