Repository navigation
Expand file tree
/
Copy pathpython.py
More file actions
executable file
·87 lines (69 loc) · 2.51 KB
/
Copy pathpython.py
File metadata and controls
executable file
·87 lines (69 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
"""Resolve a public X post with the xvideodownloader.pro HTTP API and save the
highest-bitrate MP4 variant.
Usage:
API_KEY=sk_xxxxx python3 python.py https://x.com/USERNAME/status/POST_ID
Requires Python 3.9+ and the `requests` library (pip install requests).
"""
from __future__ import annotations
import os
import pathlib
import sys
import requests
API_BASE = "https://xvideodownloader.pro"
def resolve(api_key: str, post_url: str) -> dict:
"""Resolve a post URL and return the `data` payload."""
resp = requests.post(
f"{API_BASE}/api/v1/resolve",
json={"url": post_url},
headers={"Authorization": f"Bearer {api_key}"},
timeout=30,
)
# Errors carry code / message / request_id / error / retryable.
resp.raise_for_status()
body = resp.json()
if body.get("code") != 0:
raise RuntimeError(f"resolve failed: {body.get('message')} ({body.get('error')})")
return body["data"]
def best_variant(data: dict) -> dict:
"""Pick the highest-bitrate variant that has a download URL."""
variants = [
v
for video in data.get("videos", [])
for v in video.get("variants", [])
if v.get("download_url")
]
if not variants:
raise RuntimeError("no downloadable variant in response")
return max(variants, key=lambda v: v.get("bitrate") or 0)
def download(variant: dict, dest: pathlib.Path) -> None:
"""Stream the temporary download URL to disk (expires after 15 minutes)."""
with requests.get(
variant["download_url"],
stream=True,
timeout=120,
headers={}, # the opaque URL needs no auth header
) as resp:
resp.raise_for_status()
with dest.open("wb") as fh:
for chunk in resp.iter_content(chunk_size=1 << 16):
fh.write(chunk)
def main() -> int:
api_key = os.environ.get("API_KEY")
if not api_key or len(sys.argv) != 2:
print(__doc__, file=sys.stderr)
return 2
post_url = sys.argv[1]
data = resolve(api_key, post_url)
variant = best_variant(data)
print(
f"Post {data.get('post_id')}: {variant.get('width')}x{variant.get('height')}, "
f"~{variant.get('size_bytes') or '?'} bytes, "
f"ticket expires {variant.get('ticket_expires_at')}"
)
dest = pathlib.Path(f"{data.get('post_id') or 'video'}_{variant.get('bitrate') or 0}.mp4")
download(variant, dest)
print(f"Saved {dest}")
return 0
if __name__ == "__main__":
raise SystemExit(main())