-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtx
More file actions
executable file
·1067 lines (951 loc) · 38.8 KB
/
Copy pathtx
File metadata and controls
executable file
·1067 lines (951 loc) · 38.8 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""tx — unified router across 3 X/Twitter backends + 132 site adapters.
Backends:
bird npm @steipete/bird plain-HTTPS GraphQL (fallback for unique cmds)
twitter-cli uv tool twitter-cli curl_cffi + TLS impersonation + write jitter ⭐
opencli npm @jackwener/opencli Chromium browser bridge (132 site adapters)
Routing rules (after stripping global flags):
1. internal cmd (auth/archive/cookies-save/doctor/help) → handled here
2. tx bird|twitter-cli <args...> → exec respective tool
3. tx <site> <args...> → exec opencli <site>
4. tx --via <bird|twitter-cli|opencli> <cmd> → forced backend
5. cmd in twitter-cli → twitter-cli (TLS, best for X)
6. cmd in bird → bird (mentions/news/about)
7. cmd in opencli → opencli (block/notif/etc)
8. unknown → suggest similar, exit 2
Global flags (must come BEFORE the subcommand):
--refresh rebuild discovery cache
--version print version
--via <bird|twitter-cli|opencli> force backend
--help / -h show this help
-- end of tx flags (rest is passthrough)
Cache: ~/.tx/cache.json (rebuilt every 7d or via --refresh).
Cookies: ~/.tx/cookies.env exports both bird-style (AUTH_TOKEN) and
twitter-cli-style (TWITTER_AUTH_TOKEN) — extract once via tx cookies-save.
"""
import difflib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
VERSION = "0.3.0"
CACHE_DIR = Path.home() / ".tx"
CACHE_FILE = CACHE_DIR / "cache.json"
CONFIG_FILE = CACHE_DIR / "config.json"
CACHE_TTL = 7 * 24 * 3600 # 7 days
# Default download preferences — override via ~/.tx/config.json:
# {"download": {"video_quality": "max", "image_quality": "orig"}}
# video_quality: max | medium | low | <kbps int>
# image_quality: orig | large | medium | small
DEFAULT_CONFIG = {
"download": {
"video_quality": "max",
"image_quality": "orig",
}
}
def _load_config():
if not CONFIG_FILE.exists():
return DEFAULT_CONFIG
try:
user = json.loads(CONFIG_FILE.read_text())
except (json.JSONDecodeError, OSError):
return DEFAULT_CONFIG
# shallow-merge with defaults
merged = {k: dict(v) if isinstance(v, dict) else v for k, v in DEFAULT_CONFIG.items()}
for k, v in user.items():
if isinstance(v, dict) and isinstance(merged.get(k), dict):
merged[k].update(v)
else:
merged[k] = v
return merged
INTERNAL_CMDS = {"auth", "archive", "cookies-save", "doctor", "download", "help"}
COOKIES_FILE = CACHE_DIR / "cookies.env"
NPM_GLOBAL_LIB = Path.home() / ".npm-global" / "lib" / "node_modules"
# ---------- Discovery ----------
def _run(args):
try:
return subprocess.run(args, capture_output=True, text=True, timeout=15)
except (FileNotFoundError, subprocess.TimeoutExpired):
return None
def parse_bird_cmds():
if not shutil.which("bird"):
return set()
res = _run(["bird", "--help"])
if not res or res.returncode != 0:
return set()
cmds = set()
in_section = False
for line in res.stdout.splitlines():
stripped = line.strip()
if stripped.startswith("Commands:"):
in_section = True
continue
if in_section and (stripped.startswith("Examples") or stripped == ""):
if stripped.startswith("Examples"):
break
continue
if in_section:
m = re.match(r"\s+([a-z][\w|-]*)", line)
if m:
for n in m.group(1).split("|"):
cmds.add(n)
return cmds
def parse_twitter_cli_cmds():
"""Parse `twitter --help` for top-level subcommands.
twitter-cli (jackwener/twitter-cli) is a Python X CLI with TLS-fingerprint
impersonation via curl_cffi — preferred over bird for both reads and writes
when available. Install: `uv tool install twitter-cli` or `pipx install twitter-cli`.
"""
if not shutil.which("twitter"):
return set()
res = _run(["twitter", "--help"])
if not res or res.returncode != 0:
return set()
cmds = set()
in_section = False
for line in res.stdout.splitlines():
if line.startswith("Commands:"):
in_section = True
continue
if in_section:
m = re.match(r"^\s+([a-z][\w-]*)\s+\S", line)
if m:
cmds.add(m.group(1))
elif line.strip() == "":
continue
return cmds
def parse_opencli_twitter():
if not shutil.which("opencli"):
return {}
res = _run(["opencli", "twitter", "--help"])
if not res or res.returncode != 0:
return {}
cmds = {}
for line in res.stdout.splitlines():
m = re.match(r"\s+([a-z][\w-]*)\s.*\[(read|write)\]", line)
if m:
cmds[m.group(1)] = m.group(2)
return cmds
def parse_opencli_adapters():
"""Return set of adapter names from `opencli list`.
Format: each adapter is a 2-space-indented bare identifier on its own line,
followed by 4-space-indented sub-command lines. Example:
2-space indent ▸ 1688
4-space indent ▸ assets [cookie] — ...
"""
if not shutil.which("opencli"):
return set()
res = _run(["opencli", "list"])
if not res or res.returncode != 0:
return set()
names = set()
for line in res.stdout.splitlines():
# exactly 2 leading spaces, then a bare identifier, nothing else
m = re.match(r"^ ([a-z][\w-]*)\s*$", line)
if m:
names.add(m.group(1))
return names
def build_cache():
CACHE_DIR.mkdir(parents=True, exist_ok=True)
data = {
"version": 2,
"built_at": time.time(),
"bird": sorted(parse_bird_cmds()),
"twitter_cli": sorted(parse_twitter_cli_cmds()),
"opencli_twitter": parse_opencli_twitter(),
"opencli_sites": sorted(parse_opencli_adapters()),
}
# atomic write
fd, tmp = tempfile.mkstemp(dir=str(CACHE_DIR), prefix=".cache.", suffix=".json")
try:
with os.fdopen(fd, "w") as f:
json.dump(data, f, indent=2)
os.replace(tmp, CACHE_FILE)
except Exception:
try: os.unlink(tmp)
except OSError: pass
raise
return data
def load_cache(force_refresh=False):
if force_refresh:
return build_cache()
if not CACHE_FILE.exists():
return build_cache()
if time.time() - CACHE_FILE.stat().st_mtime > CACHE_TTL:
return build_cache()
try:
data = json.loads(CACHE_FILE.read_text())
# backfill v1 caches missing twitter_cli key (v0.2 → v0.3 migration)
if "twitter_cli" not in data:
return build_cache()
return data
except (json.JSONDecodeError, OSError):
return build_cache()
# ---------- Internal commands ----------
def cmd_help(rest, cache):
if rest:
# tx help <subcommand> → forward to backing tool's --help
sub = rest[0]
sites = set(cache["opencli_sites"])
bird = set(cache["bird"])
tw = set(cache.get("twitter_cli", []))
oc = cache["opencli_twitter"]
if sub in ("bird",):
os.execvp("bird", ["bird", "--help"])
if sub in ("twitter-cli", "twitter_cli", "twitter"):
os.execvp("twitter", ["twitter", "--help"])
if sub in sites:
os.execvp("opencli", ["opencli", sub, "--help"])
# priority for sub-help: twitter-cli > bird > opencli (matches routing)
if sub in tw:
os.execvp("twitter", ["twitter", sub, "--help"])
if sub in bird:
os.execvp("bird", ["bird", sub, "--help"])
if sub in oc:
os.execvp("opencli", ["opencli", "twitter", sub, "--help"])
print(f"unknown command: {sub}", file=sys.stderr)
return 2
# categorized listing
bird = set(cache["bird"])
tw = set(cache.get("twitter_cli", []))
oc = set(cache["opencli_twitter"])
sites = sorted(cache["opencli_sites"])
# Categorize per backend uniqueness for help display.
# `download` is intercepted by an internal handler (uses twitter-cli + curl),
# so don't display it as opencli-only even though opencli has the name.
INTERNAL_OVERRIDES = {"download"}
twitter_cli_only = sorted(tw - bird - oc)
bird_only = sorted(bird - tw - oc - {"tweet"}) # tweet is alias-resolved
opencli_only = sorted(oc - bird - tw - INTERNAL_OVERRIDES)
twitter_cli_wins = sorted((bird & tw) | (tw & oc) | (bird & tw & oc))
print(f"tx {VERSION} — unified twitter-cli + bird + opencli router")
print()
print("USAGE")
print(" tx [global-flags] <command> [args...]")
print()
print("GLOBAL FLAGS (must precede the subcommand)")
print(" --refresh rebuild discovery cache")
print(" --version print version")
print(" --via <bird|twitter-cli|opencli> force backend")
print(" --help, -h this help")
print()
print("INTERNAL")
print(" tx auth check bird + twitter-cli + opencli auth status")
print(" tx archive sync X bookmarks → ~/.tx/bookmarks.db")
print(" tx download <user> [--limit N] [--output DIR]")
print(" tx download --tweet-url <url> [--output DIR]")
print(" download videos/images from tweets (twitter-cli + curl)")
print(" tx cookies-save [--from edge|chrome|safari|firefox|edge-stable]")
print(" extract X cookies → ~/.tx/cookies.env (default: edge)")
print(" tx cookies-save --check-age")
print(" show cookie age + status (no extraction)")
print(" tx doctor diagnose installation")
print(" tx help <cmd> forward to backing tool's --help")
print()
print(f"X COMMANDS — auto-routed (priority: twitter-cli > bird > opencli)")
print(f" twitter-cli ({len(tw)} cmds, TLS impersonation + jitter):")
if twitter_cli_wins:
print(f" overlap (wins by default): {' '.join(twitter_cli_wins)}")
if twitter_cli_only:
print(f" twitter-cli-only: {' '.join(twitter_cli_only)}")
print(f" bird-only ({len(bird_only)}, fallback for unique cmds):")
if bird_only:
print(f" {' '.join(bird_only)}")
print(f" opencli-only ({len(opencli_only)}, browser-required):")
if opencli_only:
print(f" {' '.join(opencli_only)}")
print(f" Note: `tx tweet <id>` views a tweet (twitter-cli).")
print(f" Use `tx post \"text\"` to create a new tweet.")
print()
print(f"SITE / APP ADAPTERS ({len(sites)}) — usage: tx <name> <verb> [args...]")
cols = 6
for i in range(0, len(sites), cols):
print(" ", " ".join(f"{s:14s}" for s in sites[i:i + cols]))
print()
print("ESCAPES")
print(" tx bird <args> force bird")
print(" tx twitter-cli <args> force twitter-cli")
print(" tx <site> <args> force opencli <site> (incl. tx twitter)")
return 0
def cmd_auth(rest, cache):
print("=== tx auth check ===")
print()
print("[bird]")
if shutil.which("bird"):
r = _run(["bird", "check"])
if r and r.returncode == 0:
for line in r.stdout.splitlines():
print(" ", line)
else:
print(" ❌ bird check failed")
if r: print(" ", (r.stderr or r.stdout).strip())
else:
print(" ❌ bird not installed → npm i -g @steipete/bird")
print()
print("[twitter-cli]")
if shutil.which("twitter"):
_load_cookies_env()
r = _run(["twitter", "status"])
if r and r.returncode == 0:
for line in r.stdout.splitlines()[:6]:
print(" ", line)
else:
print(" ❌ twitter status failed")
if r: print(" ", (r.stderr or r.stdout).strip())
else:
print(" ❌ twitter-cli not installed → uv tool install twitter-cli")
print()
print("[opencli]")
if shutil.which("opencli"):
r = _run(["opencli", "doctor"])
if r:
for line in r.stdout.splitlines():
print(" ", line)
else:
print(" ❌ opencli doctor failed")
else:
print(" ❌ opencli not installed → npm i -g @jackwener/opencli")
print()
print("[saved cookies]")
age, source, label = _cookies_status()
if age is None:
print(f" ⚠️ no ~/.tx/cookies.env — launchd/cron will fail. run: tx cookies-save")
else:
days = age / 86400
icon = {"fresh": "✅", "aging": "🟡", "stale (renew soon)": "🟠",
"expired (renew NOW)": "🔴"}.get(label, "❓")
print(f" {icon} source: {source}, age: {days:.1f}d, status: {label}")
if "stale" in label or "expired" in label:
print(f" → re-run: tx cookies-save")
return 0
def cmd_doctor(rest, cache):
print(f"tx {VERSION}")
print(f" bird: {shutil.which('bird') or 'NOT FOUND'}")
print(f" twitter-cli: {shutil.which('twitter') or 'NOT FOUND'}")
print(f" opencli: {shutil.which('opencli') or 'NOT FOUND'}")
print(f" cache: {CACHE_FILE} ({'exists' if CACHE_FILE.exists() else 'missing'})")
if CACHE_FILE.exists():
age = time.time() - CACHE_FILE.stat().st_mtime
print(f" age: {age / 3600:.1f} h (TTL {CACHE_TTL / 3600:.0f} h)")
print(f" bird cmds: {len(cache['bird'])}")
print(f" twitter-cli cmds: {len(cache.get('twitter_cli', []))}")
print(f" opencli twitter cmds: {len(cache['opencli_twitter'])}")
print(f" opencli adapters: {len(cache['opencli_sites'])}")
return 0
def _load_cookies_env():
"""Read cookies from ~/.tx/cookies.env into env. Exports both bird-style
(AUTH_TOKEN/CT0) and twitter-cli-style (TWITTER_AUTH_TOKEN/TWITTER_CT0)
aliases so all 3 backends find the cookies."""
if not COOKIES_FILE.exists():
return
try:
for line in COOKIES_FILE.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, _, v = line.partition("=")
k, v = k.strip(), v.strip()
os.environ.setdefault(k, v)
# mirror to twitter-cli's expected env var names
if k == "AUTH_TOKEN":
os.environ.setdefault("TWITTER_AUTH_TOKEN", v)
elif k == "CT0":
os.environ.setdefault("TWITTER_CT0", v)
except OSError:
pass
def _cookies_status():
"""Return (age_seconds, source, status_label) for ~/.tx/cookies.env, or (None,)*3."""
if not COOKIES_FILE.exists():
return None, None, "missing"
try:
age = time.time() - COOKIES_FILE.stat().st_mtime
first_line = COOKIES_FILE.read_text().splitlines()[0]
# parse "# tx cookies — extracted from <SOURCE> at ..."
m = re.search(r"extracted from (\S+(?:\s+\S+)?)\s+at", first_line)
source = m.group(1) if m else "unknown"
except (OSError, IndexError):
return None, None, "unreadable"
days = age / 86400
if days < 30: label = "fresh"
elif days < 60: label = "aging"
elif days < 90: label = "stale (renew soon)"
else: label = "expired (renew NOW)"
return age, source, label
def _is_auth_error(stderr_text):
"""Heuristic: bird auth failure → suggests cookies need renewal."""
if not stderr_text:
return False
s = stderr_text.lower()
return any(k in s for k in (
"401", "could not authenticate", "missing required credentials",
"no twitter cookies", "missing auth_token", "missing ct0",
))
SWEET_COOKIE_DIR = (
NPM_GLOBAL_LIB / "@steipete" / "bird" / "node_modules" / "@steipete" / "sweet-cookie"
)
EDGE_PROFILE_DIR = (
Path.home() / "Library" / "Application Support" / "Microsoft Edge Beta" / "Default"
)
EDGE_STABLE_PROFILE_DIR = (
Path.home() / "Library" / "Application Support" / "Microsoft Edge" / "Default"
)
def _extract_cookies_via_provider(provider_path, opts_json):
"""Run a sweet-cookie provider (edge / chrome / safari / firefox) directly.
Returns (auth_token, ct0, source) tuple or raises RuntimeError.
"""
js = (
f"const p = require('./dist/providers/{provider_path}');"
f"const fn = Object.values(p)[0];" # each provider exports one fn
f"fn({opts_json}, ['https://x.com','https://twitter.com'], null).then(r => {{"
" const cs = r.cookies || [];"
" const auth = cs.find(c => c.name === 'auth_token');"
" const ct0 = cs.find(c => c.name === 'ct0');"
" if (!auth || !ct0) {"
" console.error('no auth_token/ct0 — make sure x.com is logged in');"
" if (r.warnings && r.warnings.length) console.error(r.warnings.join('\\n'));"
" process.exit(1);"
" }"
" console.log(auth.value);"
" console.log(ct0.value);"
"}).catch(e => { console.error(e.message); process.exit(1); });"
)
res = subprocess.run(
["node", "-e", js],
cwd=str(SWEET_COOKIE_DIR),
capture_output=True, text=True, timeout=45,
)
if res.returncode != 0:
raise RuntimeError(res.stderr.strip() or "extraction failed")
lines = res.stdout.strip().splitlines()
if len(lines) < 2:
raise RuntimeError(f"unexpected output: {res.stdout!r}")
return lines[0], lines[1]
def cmd_cookies_save(rest, cache):
"""Extract X cookies and persist to ~/.tx/cookies.env (mode 0600).
Default: Edge Beta (most persistent on macOS — no Safari ITP, no annual rotation).
Override: tx cookies-save --from <edge|edge-stable|chrome|safari|firefox>
"""
# --check-age: print status and exit, no extraction
if "--check-age" in rest:
age, source, label = _cookies_status()
if age is None:
print("no cookies file — run `tx cookies-save` to create one")
return 1
days = age / 86400
print(f"source: {source}")
print(f"age: {days:.1f} days")
print(f"status: {label}")
return 0 if "stale" not in label and "expired" not in label else 2
browser = "edge"
if "--from" in rest:
i = rest.index("--from")
if i + 1 >= len(rest):
print("tx cookies-save: --from requires a value", file=sys.stderr)
return 2
browser = rest[i + 1]
if not SWEET_COOKIE_DIR.exists():
print(f"sweet-cookie not found at {SWEET_COOKIE_DIR}", file=sys.stderr)
return 1
common_opts = {"timeoutMs": 30000}
if browser == "edge":
if not EDGE_PROFILE_DIR.exists():
print(f"Edge Beta profile not found: {EDGE_PROFILE_DIR}", file=sys.stderr)
return 1
opts = {**common_opts, "profile": str(EDGE_PROFILE_DIR)}
provider = "edge.js"
source = "Edge Beta"
elif browser == "edge-stable":
opts = {**common_opts, "profile": str(EDGE_STABLE_PROFILE_DIR)}
provider = "edge.js"
source = "Edge"
elif browser == "chrome":
opts = common_opts
provider = "chrome.js"
source = "Chrome"
elif browser == "safari":
opts = common_opts
provider = "safariBinaryCookies.js"
source = "Safari"
elif browser == "firefox":
opts = common_opts
provider = "firefoxSqlite.js"
source = "Firefox"
else:
print(f"tx cookies-save: unknown browser '{browser}'. "
f"options: edge, edge-stable, chrome, safari, firefox", file=sys.stderr)
return 2
try:
auth_token, ct0 = _extract_cookies_via_provider(provider, json.dumps(opts))
except RuntimeError as e:
print(f"cookie extraction failed:\n{e}", file=sys.stderr)
return 1
except subprocess.TimeoutExpired:
print(f"cookie extraction timed out after 45s "
f"(may need Keychain approval on first run — try `security unlock-keychain`)", file=sys.stderr)
return 1
CACHE_DIR.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=str(CACHE_DIR), prefix=".cookies.", suffix=".env")
try:
with os.fdopen(fd, "w") as f:
f.write(f"# tx cookies — extracted from {source} at {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"AUTH_TOKEN={auth_token}\n")
f.write(f"CT0={ct0}\n")
os.chmod(tmp, 0o600)
os.replace(tmp, COOKIES_FILE)
except Exception:
try: os.unlink(tmp)
except OSError: pass
raise
print(f"saved → {COOKIES_FILE} (source: {source}, mode 0600)")
print(f"valid until X session expires — re-run `tx cookies-save` after relogin")
return 0
def _extract_media_urls(node, tweet_id=None, found=None):
"""Recursively find all media dicts in a twitter-cli JSON response, tagging
each with the containing tweet's id so we can later fetch variants per tweet.
"""
if found is None:
found = []
if isinstance(node, dict):
# tweet boundary: object with both `id` (str) and `text` (str) is a tweet
if isinstance(node.get("id"), str) and isinstance(node.get("text"), str):
tweet_id = node["id"]
if (
node.get("type") in ("video", "photo", "animated_gif")
and isinstance(node.get("url"), str)
and node["url"].startswith("http")
):
entry = dict(node)
entry["_tweet_id"] = tweet_id
found.append(entry)
for v in node.values():
_extract_media_urls(v, tweet_id, found)
elif isinstance(node, list):
for x in node:
_extract_media_urls(x, tweet_id, found)
return found
def _ext_for(media):
"""Pick file extension by media type, falling back to URL."""
t = media.get("type")
if t == "video":
return ".mp4"
if t == "animated_gif":
return ".mp4" # X serves GIFs as MP4
if t == "photo":
url = media.get("url", "")
for ext in (".jpg", ".jpeg", ".png", ".webp", ".gif"):
if ext in url.lower():
return ext
return ".jpg"
return ".bin"
def _curl_download(url, dest_path):
"""Download URL to file via curl. Returns True on success."""
res = subprocess.run(
["curl", "-fsSL", "-o", str(dest_path), url],
capture_output=True, text=True, timeout=300,
)
return res.returncode == 0
_IMAGE_QUALITY_MAP = {"orig": "orig", "large": "large", "medium": "medium", "small": "small"}
def _upgrade_image_url(url, image_quality="orig"):
"""Force pbs.twimg.com URL to a specific quality level.
Quality levels (small → orig): 680px → 1200px → 2048px → original upload.
"""
if "pbs.twimg.com" not in url:
return url
name = _IMAGE_QUALITY_MAP.get(image_quality, "orig")
from urllib.parse import urlparse, urlunparse, parse_qsl, urlencode
parsed = urlparse(url)
query = dict(parse_qsl(parsed.query))
query["name"] = name
return urlunparse(parsed._replace(query=urlencode(query)))
def _get_video_variants(tweet_id):
"""Fetch all mp4 video variants for a tweet via bird read --json-full.
Returns list sorted by bitrate descending. Each item: {url, bitrate, width, height}.
Empty list if bird unavailable or tweet has no video.
"""
if not shutil.which("bird"):
return []
res = _run(["bird", "read", str(tweet_id), "--json-full"])
if not res or res.returncode != 0:
return []
try:
data = json.loads(res.stdout)
except json.JSONDecodeError:
return []
found = []
def walk(node):
if isinstance(node, dict):
if (
node.get("content_type") == "video/mp4"
and isinstance(node.get("url"), str)
):
m = re.search(r"/(\d+)x(\d+)/", node["url"])
found.append({
"url": node["url"],
"bitrate": int(node.get("bitrate") or 0),
"width": int(m.group(1)) if m else 0,
"height": int(m.group(2)) if m else 0,
})
for v in node.values():
walk(v)
elif isinstance(node, list):
for x in node:
walk(x)
walk(data)
# dedupe by URL
seen = set()
unique = []
for v in found:
if v["url"] not in seen:
seen.add(v["url"])
unique.append(v)
return sorted(unique, key=lambda v: (v["bitrate"], v["width"]), reverse=True)
def _select_variant(variants, preference):
"""Pick a variant per preference. preference: 'max' | 'medium' | 'low' | int (target kbps)."""
if not variants:
return None
if preference == "max":
return variants[0]
if preference == "low":
return variants[-1]
if preference == "medium":
return variants[len(variants) // 2]
if isinstance(preference, int):
target = preference * 1000
return min(variants, key=lambda v: abs(v["bitrate"] - target))
return variants[0]
_TWEET_ID_RE = re.compile(r"/status/(\d+)")
def cmd_download(rest, cache):
"""Download media (videos/images) from tweets via twitter-cli + curl.
Usage:
tx download <username> # download user's recent N tweets' media
tx download --tweet-url <url> # download a single tweet's media
tx download --tweet-id <id> # same, by id
[--limit N] # default 10 for user mode
[--output DIR] # default ./twitter-downloads
"""
# Parse args
tweet_id = None
username = None
limit = 10
output_dir = Path("./twitter-downloads")
i = 0
while i < len(rest):
a = rest[i]
if a == "--tweet-url" and i + 1 < len(rest):
m = _TWEET_ID_RE.search(rest[i + 1])
if not m:
print(f"tx download: cannot parse tweet ID from URL: {rest[i + 1]}", file=sys.stderr)
return 2
tweet_id = m.group(1)
i += 2
elif a == "--tweet-id" and i + 1 < len(rest):
tweet_id = rest[i + 1]
i += 2
elif a in ("--limit", "-n") and i + 1 < len(rest):
limit = int(rest[i + 1])
i += 2
elif a in ("--output", "-o") and i + 1 < len(rest):
output_dir = Path(rest[i + 1]).expanduser()
i += 2
elif a.startswith("-"):
print(f"tx download: unknown flag: {a}", file=sys.stderr)
return 2
elif username is None and tweet_id is None:
username = a.lstrip("@")
i += 1
else:
print(f"tx download: unexpected arg: {a}", file=sys.stderr)
return 2
if not tweet_id and not username:
print(cmd_download.__doc__, file=sys.stderr)
return 2
if not shutil.which("twitter"):
print("tx download: twitter-cli not installed → uv tool install twitter-cli", file=sys.stderr)
return 1
if not shutil.which("curl"):
print("tx download: curl not found", file=sys.stderr)
return 1
_load_cookies_env()
output_dir.mkdir(parents=True, exist_ok=True)
# Fetch metadata via twitter-cli
if tweet_id:
cmd = ["twitter", "tweet", tweet_id, "--json"]
label = f"tweet {tweet_id}"
else:
cmd = ["twitter", "user-posts", username, "--max", str(limit), "--json"]
label = f"@{username} (recent {limit})"
print(f"fetching media list from {label}...")
res = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if res.returncode != 0:
print(f"twitter-cli failed: {res.stderr.strip()}", file=sys.stderr)
return 1
try:
data = json.loads(res.stdout)
except json.JSONDecodeError as e:
print(f"twitter-cli returned invalid JSON: {e}", file=sys.stderr)
return 1
media_list = _extract_media_urls(data)
# Dedupe by URL (some tweets reference same media in multiple places)
seen = set()
unique = []
for m in media_list:
if m["url"] not in seen:
seen.add(m["url"])
unique.append(m)
if not unique:
print(f"no media found in {label}")
return 1
# Load quality preferences from config
cfg = _load_config().get("download", {})
video_q = cfg.get("video_quality", "max")
image_q = cfg.get("image_quality", "orig")
print(f"found {len(unique)} media item(s), downloading to {output_dir}/")
print(f" quality: video={video_q}, image={image_q}")
ok, fail = 0, 0
# Cache variants by tweet_id to avoid duplicate bird calls within a batch
variant_cache = {}
for idx, m in enumerate(unique, 1):
prefix = tweet_id or username
ext = _ext_for(m)
dest = output_dir / f"{prefix}_{idx}{ext}"
if dest.exists():
print(f" [{idx}/{len(unique)}] {dest.name} already exists, skip")
continue
# Determine the best download URL based on media type
download_url = m["url"]
quality_tag = ""
m_type = m.get("type")
if m_type == "photo":
new_url = _upgrade_image_url(m["url"], image_q)
if new_url != m["url"]:
download_url = new_url
quality_tag = f" ({image_q})"
elif m_type in ("video", "animated_gif"):
tid = m.get("_tweet_id")
if tid:
if tid not in variant_cache:
variant_cache[tid] = _get_video_variants(tid)
variants = variant_cache[tid]
chosen = _select_variant(variants, video_q)
if chosen and chosen["url"] != m["url"]:
download_url = chosen["url"]
quality_tag = f" → {chosen['width']}x{chosen['height']} @ {chosen['bitrate']//1000}k ({video_q})"
elif chosen:
quality_tag = f" ({video_q}, already best)"
size_hint = (
f"{m.get('width','?')}x{m.get('height','?')}"
if m_type == "video" else m_type or "?"
)
print(f" [{idx}/{len(unique)}] {size_hint}{quality_tag} → {dest.name}")
if _curl_download(download_url, dest):
ok += 1
else:
print(f" ⚠️ download failed", file=sys.stderr)
fail += 1
print(f"\ndone: {ok} downloaded, {fail} failed")
return 0 if fail == 0 else 1
def cmd_archive(rest, cache):
"""Port of ve-twini archive: bird bookmarks → SQLite."""
import sqlite3
from datetime import datetime
db_path = Path(os.environ.get("TX_DB", "~/.tx/bookmarks.db")).expanduser()
db_path.parent.mkdir(parents=True, exist_ok=True)
# Load saved cookies for non-interactive (e.g. launchd) runs
_load_cookies_env()
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS bookmarks (
tweet_id TEXT PRIMARY KEY, text TEXT,
author_username TEXT, author_name TEXT,
created_at TEXT, raw_json TEXT,
synced_at TEXT DEFAULT CURRENT_TIMESTAMP)""")
conn.commit()
# Prefer twitter-cli for fetch (TLS impersonation = lower rate-limit risk),
# fall back to bird if twitter-cli not installed.
use_twitter_cli = shutil.which("twitter") is not None
if use_twitter_cli:
r = _run(["twitter", "bookmarks", "--json"])
backend_label = "twitter-cli"
else:
r = _run(["bird", "bookmarks", "--json"])
backend_label = "bird"
if not r or r.returncode != 0:
err = (r.stderr if r else "no result").strip()
print(f"{backend_label} bookmarks failed: {err}", file=sys.stderr)
if r and _is_auth_error(err):
age, source, _ = _cookies_status()
if age is None:
print("\n → cookies missing. run: tx cookies-save", file=sys.stderr)
else:
print(f"\n → cookies likely expired ({age/86400:.0f}d old, from {source}).", file=sys.stderr)
print(" 1) Open Edge Beta → x.com → make sure logged in", file=sys.stderr)
print(" 2) Run: tx cookies-save", file=sys.stderr)
return 1
try:
parsed = json.loads(r.stdout)
# twitter-cli wraps payload in {ok, schema_version, data: [...]}
# bird returns a bare list
if isinstance(parsed, dict) and "data" in parsed:
data = parsed["data"]
tweets = data if isinstance(data, list) else data.get("tweets", [])
else:
tweets = parsed
except json.JSONDecodeError as e:
print(f"{backend_label} returned invalid JSON: {e}", file=sys.stderr)
return 1
cur.execute("SELECT tweet_id FROM bookmarks")
seen = {row[0] for row in cur.fetchall()}
new = [t for t in tweets if t.get("id") not in seen]
for t in new:
author = t.get("author") or {}
# bird uses author.username, twitter-cli uses author.screenName
username = author.get("screenName") or author.get("username")
cur.execute("""INSERT OR REPLACE INTO bookmarks
(tweet_id, text, author_username, author_name, created_at, raw_json, synced_at)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(t.get("id"), t.get("text"),
username, author.get("name"),
t.get("createdAt"), json.dumps(t),
datetime.utcnow().isoformat()))
conn.commit()
conn.close()
print(f"archived {len(new)} new bookmarks → {db_path}")
return 0
# ---------- Routing ----------
def suggest_similar(cmd, candidates):
matches = difflib.get_close_matches(cmd, candidates, n=3, cutoff=0.6)
if matches:
print(f" did you mean: {', '.join(matches)}?", file=sys.stderr)
def exec_or_fail(prog, args):
if not shutil.which(prog):
hint = {"bird": "npm i -g @steipete/bird",
"opencli": "npm i -g @jackwener/opencli"}.get(prog, "")
print(f"tx: {prog} not installed{' → ' + hint if hint else ''}", file=sys.stderr)
sys.exit(127)
os.execvp(prog, [prog] + args)
def route(argv):
# Peel global flags
via = None
refresh = False
i = 0
while i < len(argv):
a = argv[i]
if a == "--":
argv = argv[i + 1:]
break
if a in ("--help", "-h"):
cache = load_cache()
return cmd_help(argv[i + 1:], cache)
if a == "--version":
print(VERSION)
return 0
if a == "--refresh":
refresh = True
i += 1
continue
if a == "--via":
if i + 1 >= len(argv):
print("tx: --via requires bird|twitter-cli|opencli", file=sys.stderr)
return 2
via = argv[i + 1]
if via not in ("bird", "twitter-cli", "twitter_cli", "opencli"):
print(f"tx: --via must be bird or opencli, got: {via}", file=sys.stderr)
return 2
i += 2
continue
# not a known global flag → assume subcommand starts here
argv = argv[i:]
break
else:
argv = argv[i:]
cache = load_cache(force_refresh=refresh)
if refresh and not argv:
print(f"cache rebuilt: {len(cache['bird'])} bird cmds, "
f"{len(cache['opencli_twitter'])} opencli twitter cmds, "
f"{len(cache['opencli_sites'])} adapters")
return 0
if not argv:
return cmd_help([], cache)
cmd = argv[0]
rest = argv[1:]
# Internal
if cmd == "help":
return cmd_help(rest, cache)
if cmd == "auth":
return cmd_auth(rest, cache)
if cmd == "doctor":
return cmd_doctor(rest, cache)
if cmd == "archive":
return cmd_archive(rest, cache)
if cmd == "cookies-save":
return cmd_cookies_save(rest, cache)
if cmd == "download":
return cmd_download(rest, cache)
bird_cmds = set(cache["bird"])
tw_cmds = set(cache.get("twitter_cli", []))
oc_cmds = set(cache["opencli_twitter"])
sites = set(cache["opencli_sites"])
# --via override