From a47589f3cecb51c1dbcae991b44e19f5f8ebfb45 Mon Sep 17 00:00:00 2001 From: jackwener Date: Fri, 27 Nov 2026 18:12:03 +0000 Subject: [PATCH 1/8] fix(deps,security): upgrade curl_cffi & xclienttransaction, owner-only cache, harden CI - Raise curl_cffi floor to >=0.15.0 (resolves GHSA-qw2m-4pqf-rmpp / CVE-2026-33752, closes #100) - Raise xclienttransaction floor to >=1.0.3 for X's numeric webpack module map - Enforce owner-only permissions (0600 files / 0700 dir) on tweet and transaction caches - Make auth path tests portable across POSIX/Windows - Harden CI workflow (minimal permissions, concurrency, timeouts, ubuntu-24.04, Python 3.13) Absorbs #102, #103, and dependency updates from #91/#93. Co-authored-by: axsddlr Co-authored-by: Canc Co-authored-by: Stoner --- .github/workflows/ci.yml | 21 ++- pyproject.toml | 7 +- tests/test_auth.py | 32 ++--- tests/test_cache_permissions.py | 90 ++++++++++++ tests/test_curl_cffi_floor.py | 59 ++++++++ twitter_cli/cache.py | 38 ++++- twitter_cli/client.py | 8 +- uv.lock | 245 +++++++++++++++++++------------- 8 files changed, 376 insertions(+), 124 deletions(-) create mode 100644 tests/test_cache_permissions.py create mode 100644 tests/test_curl_cffi_floor.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 201c1f2..48fedb1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,18 +6,31 @@ on: pull_request: workflow_call: +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: test: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 + timeout-minutes: 20 strategy: + fail-fast: false matrix: - python-version: ["3.10", "3.11", "3.12"] + python-version: ["3.10", "3.11", "3.12", "3.13"] steps: - name: Checkout uses: actions/checkout@v4 + with: + persist-credentials: false - name: Setup uv uses: astral-sh/setup-uv@v6 + with: + enable-cache: true - name: Setup Python uses: actions/setup-python@v5 @@ -26,12 +39,16 @@ jobs: - name: Install dependencies run: uv sync --extra dev + timeout-minutes: 10 - name: Lint run: uv run ruff check . + timeout-minutes: 5 - name: Type check run: uv run mypy twitter_cli + timeout-minutes: 5 - name: Test run: uv run pytest -q + timeout-minutes: 10 diff --git a/pyproject.toml b/pyproject.toml index de8f3dc..14378c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,8 +24,11 @@ dependencies = [ "click>=8.0", "rich>=13.0", "PyYAML>=6.0", - "curl_cffi>=0.7", - "xclienttransaction>=1.0.1", + # >=0.15.0 is required: earlier releases are affected by + # GHSA-qw2m-4pqf-rmpp (CVE-2026-33752), a redirect-based SSRF. + "curl_cffi>=0.15.0", + # >=1.0.3 is required for X's numeric webpack module map for ondemand.s. + "xclienttransaction>=1.0.3", "beautifulsoup4>=4.12", ] diff --git a/tests/test_auth.py b/tests/test_auth.py index 8010c08..341a7f4 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -10,6 +10,13 @@ from twitter_cli import auth +def _patch_home(monkeypatch, tmp_path) -> None: + """Point ``os.path.expanduser("~")`` at ``tmp_path`` on POSIX and Windows.""" + monkeypatch.setenv("HOME", str(tmp_path)) + if os.name == "nt": + monkeypatch.setenv("USERPROFILE", str(tmp_path)) + + def test_get_cookies_prefers_env(monkeypatch) -> None: monkeypatch.setattr(auth, "load_from_env", lambda: {"auth_token": "env-token", "ct0": "env-csrf"}) monkeypatch.setattr(auth, "extract_from_browser", lambda: pytest.fail("should not extract from browser")) @@ -192,13 +199,8 @@ def get(self, url, headers=None, timeout=5): def test_iter_chrome_cookie_files_default_first(monkeypatch, tmp_path) -> None: """Default profile should be yielded first, then Profile N sorted.""" - # Create the correct platform-specific directory structure - if sys.platform == "darwin": - chrome_dir = tmp_path / "Library" / "Application Support" / "Google" / "Chrome" - elif sys.platform == "win32": - chrome_dir = tmp_path / "Google" / "Chrome" / "User Data" - else: - chrome_dir = tmp_path / ".config" / "Google" / "Chrome" + monkeypatch.setattr(auth.sys, "platform", "linux") + chrome_dir = tmp_path / ".config" / "Google" / "Chrome" (chrome_dir / "Default").mkdir(parents=True) (chrome_dir / "Default" / "Cookies").touch() @@ -208,9 +210,7 @@ def test_iter_chrome_cookie_files_default_first(monkeypatch, tmp_path) -> None: (chrome_dir / "Profile 1" / "Cookies").touch() monkeypatch.delenv("TWITTER_CHROME_PROFILE", raising=False) - monkeypatch.setenv("HOME", str(tmp_path)) - if sys.platform == "win32": - monkeypatch.setenv("LOCALAPPDATA", str(tmp_path)) + _patch_home(monkeypatch, tmp_path) paths = auth._iter_chrome_cookie_files("chrome") @@ -224,17 +224,15 @@ def test_iter_chrome_cookie_files_default_first(monkeypatch, tmp_path) -> None: def test_iter_chrome_cookie_files_env_override(monkeypatch, tmp_path) -> None: """TWITTER_CHROME_PROFILE should restrict to that single profile.""" - if sys.platform == "darwin": - chrome_dir = tmp_path / "Library" / "Application Support" / "Google" / "Chrome" - else: - chrome_dir = tmp_path / ".config" / "Google" / "Chrome" + monkeypatch.setattr(auth.sys, "platform", "linux") + chrome_dir = tmp_path / ".config" / "Google" / "Chrome" (chrome_dir / "Default").mkdir(parents=True) (chrome_dir / "Default" / "Cookies").touch() (chrome_dir / "Profile 5").mkdir() (chrome_dir / "Profile 5" / "Cookies").touch() - monkeypatch.setenv("HOME", str(tmp_path)) + _patch_home(monkeypatch, tmp_path) monkeypatch.setenv("TWITTER_CHROME_PROFILE", "Profile 5") paths = auth._iter_chrome_cookie_files("chrome") @@ -249,13 +247,13 @@ def test_iter_chrome_cookie_files_edge_linux_uses_microsoft_edge_path(monkeypatc (edge_dir / "Default").mkdir(parents=True) (edge_dir / "Default" / "Cookies").touch() - monkeypatch.setenv("HOME", str(tmp_path)) + _patch_home(monkeypatch, tmp_path) monkeypatch.delenv("TWITTER_CHROME_PROFILE", raising=False) paths = auth._iter_chrome_cookie_files("edge") assert len(paths) == 1 - assert paths[0].endswith(".config/microsoft-edge/Default/Cookies") + assert paths[0] == os.path.join(str(tmp_path), ".config", "microsoft-edge", "Default", "Cookies") def test_iter_chrome_cookie_files_edge_windows_uses_user_data(monkeypatch, tmp_path) -> None: diff --git a/tests/test_cache_permissions.py b/tests/test_cache_permissions.py new file mode 100644 index 0000000..d7893bf --- /dev/null +++ b/tests/test_cache_permissions.py @@ -0,0 +1,90 @@ +"""Owner-only permissions for cache artefacts.""" + +from __future__ import annotations + +import json +import os +import stat + +import pytest + +from twitter_cli import cache + +posix_only = pytest.mark.skipif( + os.name != "posix", reason="POSIX permission bits are not enforced on this OS" +) + + +def _make_tweet(tweet_factory, tweet_id: str = "100"): + return tweet_factory(tweet_id=tweet_id, text="cache me") + + +@posix_only +def test_save_writes_owner_only(tmp_path, monkeypatch, tweet_factory) -> None: + cache_file = tmp_path / ".twitter-cli" / "last_results.json" + monkeypatch.setattr(cache, "_CACHE_DIR", cache_file.parent) + monkeypatch.setattr(cache, "_CACHE_FILE", cache_file) + + cache.save_tweet_cache([_make_tweet(tweet_factory)]) + + assert cache_file.exists() + assert stat.S_IMODE(cache_file.stat().st_mode) == 0o600 + assert stat.S_IMODE(cache_file.parent.stat().st_mode) == 0o700 + assert json.loads(cache_file.read_text(encoding="utf-8"))["tweets"][0]["id"] == "100" + + +@posix_only +def test_save_tightens_preexisting_world_readable_file(tmp_path, monkeypatch, tweet_factory) -> None: + cache_file = tmp_path / ".twitter-cli" / "last_results.json" + cache_file.parent.mkdir(parents=True) + cache_file.write_text("{}", encoding="utf-8") + cache_file.chmod(0o644) + assert stat.S_IMODE(cache_file.stat().st_mode) == 0o644 + + monkeypatch.setattr(cache, "_CACHE_DIR", cache_file.parent) + monkeypatch.setattr(cache, "_CACHE_FILE", cache_file) + + cache.save_tweet_cache([_make_tweet(tweet_factory)]) + + assert stat.S_IMODE(cache_file.stat().st_mode) == 0o600 + + +def test_save_never_raises_on_unwritable_dir(tmp_path, monkeypatch, tweet_factory) -> None: + cache_file = tmp_path / "missing" / "last_results.json" + monkeypatch.setattr(cache, "_CACHE_DIR", cache_file.parent) + monkeypatch.setattr(cache, "_CACHE_FILE", cache_file) + blocker = tmp_path / "missing" + blocker.write_text("not a directory", encoding="utf-8") + + cache.save_tweet_cache([_make_tweet(tweet_factory)]) + + assert not cache_file.exists() + + +def test_client_transaction_cache_is_owner_only(tmp_path, monkeypatch) -> None: + from twitter_cli.client import TwitterClient + + ct_cache = tmp_path / ".twitter-cli" / "transaction_cache.json" + monkeypatch.setattr( + TwitterClient, "_ct_cache_path", staticmethod(lambda: str(ct_cache)) + ) + + client = TwitterClient.__new__(TwitterClient) + client._save_ct_cache("home", "ondemand") + + assert ct_cache.exists() + payload = json.loads(ct_cache.read_text(encoding="utf-8")) + assert payload["home_html"] == "home" + if os.name == "posix": + assert stat.S_IMODE(ct_cache.stat().st_mode) == 0o600 + assert stat.S_IMODE(ct_cache.parent.stat().st_mode) == 0o700 + + +def test_open_owner_only_uses_restrictive_mode(tmp_path) -> None: + target = tmp_path / "secret.json" + with cache._open_owner_only(target) as handle: + handle.write('{"ok": true}') + + assert target.read_text(encoding="utf-8") == '{"ok": true}' + if os.name == "posix": + assert stat.S_IMODE(target.stat().st_mode) == 0o600 diff --git a/tests/test_curl_cffi_floor.py b/tests/test_curl_cffi_floor.py new file mode 100644 index 0000000..dc95035 --- /dev/null +++ b/tests/test_curl_cffi_floor.py @@ -0,0 +1,59 @@ +"""Dependency-floor guards for curl_cffi and xclienttransaction.""" + +from __future__ import annotations + +import re +from pathlib import Path + +PYPROJECT = Path(__file__).resolve().parent.parent / "pyproject.toml" + + +def _declared_specifiers() -> dict[str, str]: + """Return {package: minimal-version-specifier} from [project].dependencies.""" + text = PYPROJECT.read_text(encoding="utf-8") + block = re.search(r"^dependencies\s*=\s*\[\s*$(.*?)^\]\s*$", text, re.S | re.M) + assert block, "could not locate dependencies = [...] in pyproject.toml" + specifiers = {} + for raw in re.findall(r'"([^"]+)"', block.group(1)): + name, sep, version = raw.partition(">=") + if sep: + specifiers[name.strip().lower()] = ">=" + version.strip() + return specifiers + + +def _parse_version_tuple(raw: str) -> tuple[int, ...]: + parts = [] + for chunk in raw.split("."): + digits = "".join(c for c in chunk if c.isdigit()) + if not digits: + break + parts.append(int(digits)) + while len(parts) < 3: + parts.append(0) + return tuple(parts[:3]) + + +def test_curl_cffi_floor_excludes_ghsa_qw2m_4pqf_rmpp() -> None: + """GHSA-qw2m-4pqf-rmpp (CVE-2026-33752): redirect SSRF, fixed in 0.15.0.""" + specifier = _declared_specifiers()["curl_cffi"] + min_version = _parse_version_tuple(specifier.removeprefix(">=")) + assert min_version >= (0, 15, 0), ( + "curl_cffi floor must be >=0.15.0 to exclude GHSA-qw2m-4pqf-rmpp; got %s" % specifier + ) + + +def test_installed_curl_cffi_is_not_vulnerable() -> None: + import curl_cffi + + raw = getattr(curl_cffi, "__version__", "0") + assert _parse_version_tuple(raw) >= (0, 15, 0), ( + "installed curl_cffi %s is affected by GHSA-qw2m-4pqf-rmpp" % raw + ) + + +def test_xclienttransaction_floor_supports_numeric_module_map() -> None: + specifier = _declared_specifiers()["xclienttransaction"] + min_version = _parse_version_tuple(specifier.removeprefix(">=")) + assert min_version >= (1, 0, 3), ( + "xclienttransaction floor must be >=1.0.3; got %s" % specifier + ) diff --git a/twitter_cli/cache.py b/twitter_cli/cache.py index fb1cad5..b2e3b1e 100644 --- a/twitter_cli/cache.py +++ b/twitter_cli/cache.py @@ -4,9 +4,10 @@ import json import logging +import os import time from pathlib import Path -from typing import List, Optional, Tuple +from typing import IO, List, Optional, Tuple from .models import Tweet @@ -16,18 +17,51 @@ _CACHE_FILE = _CACHE_DIR / "last_results.json" _TTL = 3600 # seconds +# Owner-only permissions for cache artefacts (0600 files / 0700 directory). +_OWNER_ONLY_FILE = 0o600 +_OWNER_ONLY_DIR = 0o700 + + +def _open_owner_only(path: Path) -> IO[str]: + """Open ``path`` for writing with owner-only permissions. + + Uses ``O_CREAT`` with mode ``0o600`` so a newly created file is never + briefly world-readable, and tightens preexisting files on every write. + """ + flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0) + fd = os.open(str(path), flags, _OWNER_ONLY_FILE) + try: + fchmod = getattr(os, "fchmod", None) + if fchmod is not None: + fchmod(fd, _OWNER_ONLY_FILE) + else: # pragma: no cover - non-POSIX + os.chmod(str(path), _OWNER_ONLY_FILE) + except OSError: # pragma: no cover - permission change is best-effort + pass + return os.fdopen(fd, "w", encoding="utf-8") + + +def _tighten_dir(directory: Path) -> None: + """Best-effort owner-only permission on a cache directory.""" + try: + os.chmod(str(directory), _OWNER_ONLY_DIR) + except OSError: + pass + def save_tweet_cache(tweets: List[Tweet]) -> None: """Persist tweet list so indices can be resolved by `show`.""" try: _CACHE_DIR.mkdir(parents=True, exist_ok=True) + _tighten_dir(_CACHE_DIR) entries = [ {"index": i + 1, "id": t.id, "author": t.author.screen_name, "text": t.text[:80]} for i, t in enumerate(tweets) if t.id ] payload = {"created_at": time.time(), "tweets": entries} - _CACHE_FILE.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") + with _open_owner_only(_CACHE_FILE) as f: + f.write(json.dumps(payload, ensure_ascii=False, indent=2)) except OSError as exc: logger.debug("Failed to write tweet cache: %s", exc) diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 0436c8e..97afda9 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -11,6 +11,7 @@ import random import time import urllib.parse +from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, cast import bs4 @@ -18,6 +19,8 @@ from x_client_transaction import ClientTransaction from x_client_transaction.utils import generate_headers as _gen_ct_headers, get_ondemand_file_url +from .cache import _open_owner_only, _tighten_dir + from .constants import ( BEARER_TOKEN, SEC_CH_UA_BITNESS, @@ -1066,17 +1069,18 @@ def _load_ct_cache(self): def _save_ct_cache(self, home_html, ondemand_text): # type: (str, str) -> None - """Save transaction data to cache file.""" + """Save transaction data to cache file with owner-only permissions.""" try: cache_path = self._ct_cache_path() cache_dir = os.path.dirname(cache_path) os.makedirs(cache_dir, exist_ok=True) + _tighten_dir(Path(cache_dir)) cache = { "home_html": home_html, "ondemand_text": ondemand_text, "created_at": time.time(), } - with open(cache_path, "w", encoding="utf-8") as f: + with _open_owner_only(Path(cache_path)) as f: json.dump(cache, f) logger.debug("Saved CT cache to %s", cache_path) except Exception as exc: diff --git a/uv.lock b/uv.lock index 5c2ba17..d0f5d81 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" [[package]] @@ -20,7 +20,7 @@ name = "browser-cookie3" version = "0.20.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "jeepney", marker = "'bsd' in sys_platform or sys_platform == 'linux'" }, + { name = "jeepney", marker = "sys_platform == 'linux' or 'bsd' in sys_platform" }, { name = "lz4" }, { name = "pycryptodomex" }, { name = "shadowcopy", marker = "sys_platform == 'win32'" }, @@ -32,93 +32,121 @@ wheels = [ [[package]] name = "certifi" -version = "2026.2.25" +version = "2026.11.20" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/af/2d/7bf41579a8986e348fa033a31cdd0e4121114f6bce2457e8876010b092dd/certifi-2026.2.25.tar.gz", hash = "sha256:e887ab5cee78ea814d3472169153c2d12cd43b14bd03329a39a9c6e2e80bfba7", size = 155029, upload-time = "2026-02-25T02:54:17.342Z" } +sdist = { url = "https://files.pythonhosted.org/packages/51/33/4cd27639502f010084bcef7a2036391dd637439901341ce1a530f36f6e51/certifi-2026.11.20.tar.gz", hash = "sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e", size = 128901, upload-time = "2026-11-20T23:37:49.522Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9a/3c/c17fb3ca2d9c3acff52e30b309f538586f9f5b9c9cf454f3845fc9af4881/certifi-2026.2.25-py3-none-any.whl", hash = "sha256:027692e4402ad994f1c42e52a4997a9763c646b73e4096e4d5d6db8af1d6f0fa", size = 153684, upload-time = "2026-02-25T02:54:15.766Z" }, + { url = "https://files.pythonhosted.org/packages/6d/39/5eec3296860b94ac20bb8ed807725b88f6adfab3f343df592afd975f5f86/certifi-2026.11.20-py3-none-any.whl", hash = "sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f", size = 127913, upload-time = "2026-11-20T23:37:48.117Z" }, ] [[package]] name = "cffi" -version = "2.0.0" +version = "2.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pycparser", marker = "implementation_name != 'PyPy'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/93/d7/516d984057745a6cd96575eea814fe1edd6646ee6efd552fb7b0921dec83/cffi-2.0.0-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:0cf2d91ecc3fcc0625c2c530fe004f82c110405f101548512cce44322fa8ac44", size = 184283, upload-time = "2025-09-08T23:22:08.01Z" }, - { url = "https://files.pythonhosted.org/packages/9e/84/ad6a0b408daa859246f57c03efd28e5dd1b33c21737c2db84cae8c237aa5/cffi-2.0.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:f73b96c41e3b2adedc34a7356e64c8eb96e03a3782b535e043a986276ce12a49", size = 180504, upload-time = "2025-09-08T23:22:10.637Z" }, - { url = "https://files.pythonhosted.org/packages/50/bd/b1a6362b80628111e6653c961f987faa55262b4002fcec42308cad1db680/cffi-2.0.0-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:53f77cbe57044e88bbd5ed26ac1d0514d2acf0591dd6bb02a3ae37f76811b80c", size = 208811, upload-time = "2025-09-08T23:22:12.267Z" }, - { url = "https://files.pythonhosted.org/packages/4f/27/6933a8b2562d7bd1fb595074cf99cc81fc3789f6a6c05cdabb46284a3188/cffi-2.0.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3e837e369566884707ddaf85fc1744b47575005c0a229de3327f8f9a20f4efeb", size = 216402, upload-time = "2025-09-08T23:22:13.455Z" }, - { url = "https://files.pythonhosted.org/packages/05/eb/b86f2a2645b62adcfff53b0dd97e8dfafb5c8aa864bd0d9a2c2049a0d551/cffi-2.0.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:5eda85d6d1879e692d546a078b44251cdd08dd1cfb98dfb77b670c97cee49ea0", size = 203217, upload-time = "2025-09-08T23:22:14.596Z" }, - { url = "https://files.pythonhosted.org/packages/9f/e0/6cbe77a53acf5acc7c08cc186c9928864bd7c005f9efd0d126884858a5fe/cffi-2.0.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:9332088d75dc3241c702d852d4671613136d90fa6881da7d770a483fd05248b4", size = 203079, upload-time = "2025-09-08T23:22:15.769Z" }, - { url = "https://files.pythonhosted.org/packages/98/29/9b366e70e243eb3d14a5cb488dfd3a0b6b2f1fb001a203f653b93ccfac88/cffi-2.0.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fc7de24befaeae77ba923797c7c87834c73648a05a4bde34b3b7e5588973a453", size = 216475, upload-time = "2025-09-08T23:22:17.427Z" }, - { url = "https://files.pythonhosted.org/packages/21/7a/13b24e70d2f90a322f2900c5d8e1f14fa7e2a6b3332b7309ba7b2ba51a5a/cffi-2.0.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:cf364028c016c03078a23b503f02058f1814320a56ad535686f90565636a9495", size = 218829, upload-time = "2025-09-08T23:22:19.069Z" }, - { url = "https://files.pythonhosted.org/packages/60/99/c9dc110974c59cc981b1f5b66e1d8af8af764e00f0293266824d9c4254bc/cffi-2.0.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e11e82b744887154b182fd3e7e8512418446501191994dbf9c9fc1f32cc8efd5", size = 211211, upload-time = "2025-09-08T23:22:20.588Z" }, - { url = "https://files.pythonhosted.org/packages/49/72/ff2d12dbf21aca1b32a40ed792ee6b40f6dc3a9cf1644bd7ef6e95e0ac5e/cffi-2.0.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8ea985900c5c95ce9db1745f7933eeef5d314f0565b27625d9a10ec9881e1bfb", size = 218036, upload-time = "2025-09-08T23:22:22.143Z" }, - { url = "https://files.pythonhosted.org/packages/e2/cc/027d7fb82e58c48ea717149b03bcadcbdc293553edb283af792bd4bcbb3f/cffi-2.0.0-cp310-cp310-win32.whl", hash = "sha256:1f72fb8906754ac8a2cc3f9f5aaa298070652a0ffae577e0ea9bd480dc3c931a", size = 172184, upload-time = "2025-09-08T23:22:23.328Z" }, - { url = "https://files.pythonhosted.org/packages/33/fa/072dd15ae27fbb4e06b437eb6e944e75b068deb09e2a2826039e49ee2045/cffi-2.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:b18a3ed7d5b3bd8d9ef7a8cb226502c6bf8308df1525e1cc676c3680e7176739", size = 182790, upload-time = "2025-09-08T23:22:24.752Z" }, - { url = "https://files.pythonhosted.org/packages/12/4a/3dfd5f7850cbf0d06dc84ba9aa00db766b52ca38d8b86e3a38314d52498c/cffi-2.0.0-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:b4c854ef3adc177950a8dfc81a86f5115d2abd545751a304c5bcf2c2c7283cfe", size = 184344, upload-time = "2025-09-08T23:22:26.456Z" }, - { url = "https://files.pythonhosted.org/packages/4f/8b/f0e4c441227ba756aafbe78f117485b25bb26b1c059d01f137fa6d14896b/cffi-2.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2de9a304e27f7596cd03d16f1b7c72219bd944e99cc52b84d0145aefb07cbd3c", size = 180560, upload-time = "2025-09-08T23:22:28.197Z" }, - { url = "https://files.pythonhosted.org/packages/b1/b7/1200d354378ef52ec227395d95c2576330fd22a869f7a70e88e1447eb234/cffi-2.0.0-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:baf5215e0ab74c16e2dd324e8ec067ef59e41125d3eade2b863d294fd5035c92", size = 209613, upload-time = "2025-09-08T23:22:29.475Z" }, - { url = "https://files.pythonhosted.org/packages/b8/56/6033f5e86e8cc9bb629f0077ba71679508bdf54a9a5e112a3c0b91870332/cffi-2.0.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:730cacb21e1bdff3ce90babf007d0a0917cc3e6492f336c2f0134101e0944f93", size = 216476, upload-time = "2025-09-08T23:22:31.063Z" }, - { url = "https://files.pythonhosted.org/packages/dc/7f/55fecd70f7ece178db2f26128ec41430d8720f2d12ca97bf8f0a628207d5/cffi-2.0.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6824f87845e3396029f3820c206e459ccc91760e8fa24422f8b0c3d1731cbec5", size = 203374, upload-time = "2025-09-08T23:22:32.507Z" }, - { url = "https://files.pythonhosted.org/packages/84/ef/a7b77c8bdc0f77adc3b46888f1ad54be8f3b7821697a7b89126e829e676a/cffi-2.0.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:9de40a7b0323d889cf8d23d1ef214f565ab154443c42737dfe52ff82cf857664", size = 202597, upload-time = "2025-09-08T23:22:34.132Z" }, - { url = "https://files.pythonhosted.org/packages/d7/91/500d892b2bf36529a75b77958edfcd5ad8e2ce4064ce2ecfeab2125d72d1/cffi-2.0.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8941aaadaf67246224cee8c3803777eed332a19d909b47e29c9842ef1e79ac26", size = 215574, upload-time = "2025-09-08T23:22:35.443Z" }, - { url = "https://files.pythonhosted.org/packages/44/64/58f6255b62b101093d5df22dcb752596066c7e89dd725e0afaed242a61be/cffi-2.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:a05d0c237b3349096d3981b727493e22147f934b20f6f125a3eba8f994bec4a9", size = 218971, upload-time = "2025-09-08T23:22:36.805Z" }, - { url = "https://files.pythonhosted.org/packages/ab/49/fa72cebe2fd8a55fbe14956f9970fe8eb1ac59e5df042f603ef7c8ba0adc/cffi-2.0.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:94698a9c5f91f9d138526b48fe26a199609544591f859c870d477351dc7b2414", size = 211972, upload-time = "2025-09-08T23:22:38.436Z" }, - { url = "https://files.pythonhosted.org/packages/0b/28/dd0967a76aab36731b6ebfe64dec4e981aff7e0608f60c2d46b46982607d/cffi-2.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:5fed36fccc0612a53f1d4d9a816b50a36702c28a2aa880cb8a122b3466638743", size = 217078, upload-time = "2025-09-08T23:22:39.776Z" }, - { url = "https://files.pythonhosted.org/packages/2b/c0/015b25184413d7ab0a410775fdb4a50fca20f5589b5dab1dbbfa3baad8ce/cffi-2.0.0-cp311-cp311-win32.whl", hash = "sha256:c649e3a33450ec82378822b3dad03cc228b8f5963c0c12fc3b1e0ab940f768a5", size = 172076, upload-time = "2025-09-08T23:22:40.95Z" }, - { url = "https://files.pythonhosted.org/packages/ae/8f/dc5531155e7070361eb1b7e4c1a9d896d0cb21c49f807a6c03fd63fc877e/cffi-2.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:66f011380d0e49ed280c789fbd08ff0d40968ee7b665575489afa95c98196ab5", size = 182820, upload-time = "2025-09-08T23:22:42.463Z" }, - { url = "https://files.pythonhosted.org/packages/95/5c/1b493356429f9aecfd56bc171285a4c4ac8697f76e9bbbbb105e537853a1/cffi-2.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:c6638687455baf640e37344fe26d37c404db8b80d037c3d29f58fe8d1c3b194d", size = 177635, upload-time = "2025-09-08T23:22:43.623Z" }, - { url = "https://files.pythonhosted.org/packages/ea/47/4f61023ea636104d4f16ab488e268b93008c3d0bb76893b1b31db1f96802/cffi-2.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", size = 185271, upload-time = "2025-09-08T23:22:44.795Z" }, - { url = "https://files.pythonhosted.org/packages/df/a2/781b623f57358e360d62cdd7a8c681f074a71d445418a776eef0aadb4ab4/cffi-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", size = 181048, upload-time = "2025-09-08T23:22:45.938Z" }, - { url = "https://files.pythonhosted.org/packages/ff/df/a4f0fbd47331ceeba3d37c2e51e9dfc9722498becbeec2bd8bc856c9538a/cffi-2.0.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", size = 212529, upload-time = "2025-09-08T23:22:47.349Z" }, - { url = "https://files.pythonhosted.org/packages/d5/72/12b5f8d3865bf0f87cf1404d8c374e7487dcf097a1c91c436e72e6badd83/cffi-2.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", size = 220097, upload-time = "2025-09-08T23:22:48.677Z" }, - { url = "https://files.pythonhosted.org/packages/c2/95/7a135d52a50dfa7c882ab0ac17e8dc11cec9d55d2c18dda414c051c5e69e/cffi-2.0.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", size = 207983, upload-time = "2025-09-08T23:22:50.06Z" }, - { url = "https://files.pythonhosted.org/packages/3a/c8/15cb9ada8895957ea171c62dc78ff3e99159ee7adb13c0123c001a2546c1/cffi-2.0.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", size = 206519, upload-time = "2025-09-08T23:22:51.364Z" }, - { url = "https://files.pythonhosted.org/packages/78/2d/7fa73dfa841b5ac06c7b8855cfc18622132e365f5b81d02230333ff26e9e/cffi-2.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", size = 219572, upload-time = "2025-09-08T23:22:52.902Z" }, - { url = "https://files.pythonhosted.org/packages/07/e0/267e57e387b4ca276b90f0434ff88b2c2241ad72b16d31836adddfd6031b/cffi-2.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", size = 222963, upload-time = "2025-09-08T23:22:54.518Z" }, - { url = "https://files.pythonhosted.org/packages/b6/75/1f2747525e06f53efbd878f4d03bac5b859cbc11c633d0fb81432d98a795/cffi-2.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", size = 221361, upload-time = "2025-09-08T23:22:55.867Z" }, - { url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932, upload-time = "2025-09-08T23:22:57.188Z" }, - { url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557, upload-time = "2025-09-08T23:22:58.351Z" }, - { url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762, upload-time = "2025-09-08T23:22:59.668Z" }, - { url = "https://files.pythonhosted.org/packages/4b/8d/a0a47a0c9e413a658623d014e91e74a50cdd2c423f7ccfd44086ef767f90/cffi-2.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb", size = 185230, upload-time = "2025-09-08T23:23:00.879Z" }, - { url = "https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:45d5e886156860dc35862657e1494b9bae8dfa63bf56796f2fb56e1679fc0bca", size = 181043, upload-time = "2025-09-08T23:23:02.231Z" }, - { url = "https://files.pythonhosted.org/packages/b0/1e/d22cc63332bd59b06481ceaac49d6c507598642e2230f201649058a7e704/cffi-2.0.0-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b", size = 212446, upload-time = "2025-09-08T23:23:03.472Z" }, - { url = "https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d48a880098c96020b02d5a1f7d9251308510ce8858940e6fa99ece33f610838b", size = 220101, upload-time = "2025-09-08T23:23:04.792Z" }, - { url = "https://files.pythonhosted.org/packages/f2/7f/e6647792fc5850d634695bc0e6ab4111ae88e89981d35ac269956605feba/cffi-2.0.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f93fd8e5c8c0a4aa1f424d6173f14a892044054871c771f8566e4008eaa359d2", size = 207948, upload-time = "2025-09-08T23:23:06.127Z" }, - { url = "https://files.pythonhosted.org/packages/cb/1e/a5a1bd6f1fb30f22573f76533de12a00bf274abcdc55c8edab639078abb6/cffi-2.0.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:dd4f05f54a52fb558f1ba9f528228066954fee3ebe629fc1660d874d040ae5a3", size = 206422, upload-time = "2025-09-08T23:23:07.753Z" }, - { url = "https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c8d3b5532fc71b7a77c09192b4a5a200ea992702734a2e9279a37f2478236f26", size = 219499, upload-time = "2025-09-08T23:23:09.648Z" }, - { url = "https://files.pythonhosted.org/packages/50/e1/a969e687fcf9ea58e6e2a928ad5e2dd88cc12f6f0ab477e9971f2309b57c/cffi-2.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d9b29c1f0ae438d5ee9acb31cadee00a58c46cc9c0b2f9038c6b0b3470877a8c", size = 222928, upload-time = "2025-09-08T23:23:10.928Z" }, - { url = "https://files.pythonhosted.org/packages/36/54/0362578dd2c9e557a28ac77698ed67323ed5b9775ca9d3fe73fe191bb5d8/cffi-2.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d50360be4546678fc1b79ffe7a66265e28667840010348dd69a314145807a1b", size = 221302, upload-time = "2025-09-08T23:23:12.42Z" }, - { url = "https://files.pythonhosted.org/packages/eb/6d/bf9bda840d5f1dfdbf0feca87fbdb64a918a69bca42cfa0ba7b137c48cb8/cffi-2.0.0-cp313-cp313-win32.whl", hash = "sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27", size = 172909, upload-time = "2025-09-08T23:23:14.32Z" }, - { url = "https://files.pythonhosted.org/packages/37/18/6519e1ee6f5a1e579e04b9ddb6f1676c17368a7aba48299c3759bbc3c8b3/cffi-2.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75", size = 183402, upload-time = "2025-09-08T23:23:15.535Z" }, - { url = "https://files.pythonhosted.org/packages/cb/0e/02ceeec9a7d6ee63bb596121c2c8e9b3a9e150936f4fbef6ca1943e6137c/cffi-2.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91", size = 177780, upload-time = "2025-09-08T23:23:16.761Z" }, - { url = "https://files.pythonhosted.org/packages/92/c4/3ce07396253a83250ee98564f8d7e9789fab8e58858f35d07a9a2c78de9f/cffi-2.0.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fc33c5141b55ed366cfaad382df24fe7dcbc686de5be719b207bb248e3053dc5", size = 185320, upload-time = "2025-09-08T23:23:18.087Z" }, - { url = "https://files.pythonhosted.org/packages/59/dd/27e9fa567a23931c838c6b02d0764611c62290062a6d4e8ff7863daf9730/cffi-2.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c654de545946e0db659b3400168c9ad31b5d29593291482c43e3564effbcee13", size = 181487, upload-time = "2025-09-08T23:23:19.622Z" }, - { url = "https://files.pythonhosted.org/packages/d6/43/0e822876f87ea8a4ef95442c3d766a06a51fc5298823f884ef87aaad168c/cffi-2.0.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:24b6f81f1983e6df8db3adc38562c83f7d4a0c36162885ec7f7b77c7dcbec97b", size = 220049, upload-time = "2025-09-08T23:23:20.853Z" }, - { url = "https://files.pythonhosted.org/packages/b4/89/76799151d9c2d2d1ead63c2429da9ea9d7aac304603de0c6e8764e6e8e70/cffi-2.0.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:12873ca6cb9b0f0d3a0da705d6086fe911591737a59f28b7936bdfed27c0d47c", size = 207793, upload-time = "2025-09-08T23:23:22.08Z" }, - { url = "https://files.pythonhosted.org/packages/bb/dd/3465b14bb9e24ee24cb88c9e3730f6de63111fffe513492bf8c808a3547e/cffi-2.0.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:d9b97165e8aed9272a6bb17c01e3cc5871a594a446ebedc996e2397a1c1ea8ef", size = 206300, upload-time = "2025-09-08T23:23:23.314Z" }, - { url = "https://files.pythonhosted.org/packages/47/d9/d83e293854571c877a92da46fdec39158f8d7e68da75bf73581225d28e90/cffi-2.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:afb8db5439b81cf9c9d0c80404b60c3cc9c3add93e114dcae767f1477cb53775", size = 219244, upload-time = "2025-09-08T23:23:24.541Z" }, - { url = "https://files.pythonhosted.org/packages/2b/0f/1f177e3683aead2bb00f7679a16451d302c436b5cbf2505f0ea8146ef59e/cffi-2.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:737fe7d37e1a1bffe70bd5754ea763a62a066dc5913ca57e957824b72a85e205", size = 222828, upload-time = "2025-09-08T23:23:26.143Z" }, - { url = "https://files.pythonhosted.org/packages/c6/0f/cafacebd4b040e3119dcb32fed8bdef8dfe94da653155f9d0b9dc660166e/cffi-2.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:38100abb9d1b1435bc4cc340bb4489635dc2f0da7456590877030c9b3d40b0c1", size = 220926, upload-time = "2025-09-08T23:23:27.873Z" }, - { url = "https://files.pythonhosted.org/packages/3e/aa/df335faa45b395396fcbc03de2dfcab242cd61a9900e914fe682a59170b1/cffi-2.0.0-cp314-cp314-win32.whl", hash = "sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f", size = 175328, upload-time = "2025-09-08T23:23:44.61Z" }, - { url = "https://files.pythonhosted.org/packages/bb/92/882c2d30831744296ce713f0feb4c1cd30f346ef747b530b5318715cc367/cffi-2.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25", size = 185650, upload-time = "2025-09-08T23:23:45.848Z" }, - { url = "https://files.pythonhosted.org/packages/9f/2c/98ece204b9d35a7366b5b2c6539c350313ca13932143e79dc133ba757104/cffi-2.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad", size = 180687, upload-time = "2025-09-08T23:23:47.105Z" }, - { url = "https://files.pythonhosted.org/packages/3e/61/c768e4d548bfa607abcda77423448df8c471f25dbe64fb2ef6d555eae006/cffi-2.0.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:9a67fc9e8eb39039280526379fb3a70023d77caec1852002b4da7e8b270c4dd9", size = 188773, upload-time = "2025-09-08T23:23:29.347Z" }, - { url = "https://files.pythonhosted.org/packages/2c/ea/5f76bce7cf6fcd0ab1a1058b5af899bfbef198bea4d5686da88471ea0336/cffi-2.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7a66c7204d8869299919db4d5069a82f1561581af12b11b3c9f48c584eb8743d", size = 185013, upload-time = "2025-09-08T23:23:30.63Z" }, - { url = "https://files.pythonhosted.org/packages/be/b4/c56878d0d1755cf9caa54ba71e5d049479c52f9e4afc230f06822162ab2f/cffi-2.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7cc09976e8b56f8cebd752f7113ad07752461f48a58cbba644139015ac24954c", size = 221593, upload-time = "2025-09-08T23:23:31.91Z" }, - { url = "https://files.pythonhosted.org/packages/e0/0d/eb704606dfe8033e7128df5e90fee946bbcb64a04fcdaa97321309004000/cffi-2.0.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:92b68146a71df78564e4ef48af17551a5ddd142e5190cdf2c5624d0c3ff5b2e8", size = 209354, upload-time = "2025-09-08T23:23:33.214Z" }, - { url = "https://files.pythonhosted.org/packages/d8/19/3c435d727b368ca475fb8742ab97c9cb13a0de600ce86f62eab7fa3eea60/cffi-2.0.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b1e74d11748e7e98e2f426ab176d4ed720a64412b6a15054378afdb71e0f37dc", size = 208480, upload-time = "2025-09-08T23:23:34.495Z" }, - { url = "https://files.pythonhosted.org/packages/d0/44/681604464ed9541673e486521497406fadcc15b5217c3e326b061696899a/cffi-2.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:28a3a209b96630bca57cce802da70c266eb08c6e97e5afd61a75611ee6c64592", size = 221584, upload-time = "2025-09-08T23:23:36.096Z" }, - { url = "https://files.pythonhosted.org/packages/25/8e/342a504ff018a2825d395d44d63a767dd8ebc927ebda557fecdaca3ac33a/cffi-2.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7553fb2090d71822f02c629afe6042c299edf91ba1bf94951165613553984512", size = 224443, upload-time = "2025-09-08T23:23:37.328Z" }, - { url = "https://files.pythonhosted.org/packages/e1/5e/b666bacbbc60fbf415ba9988324a132c9a7a0448a9a8f125074671c0f2c3/cffi-2.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6c6c373cfc5c83a975506110d17457138c8c63016b563cc9ed6e056a82f13ce4", size = 223437, upload-time = "2025-09-08T23:23:38.945Z" }, - { url = "https://files.pythonhosted.org/packages/a0/1d/ec1a60bd1a10daa292d3cd6bb0b359a81607154fb8165f3ec95fe003b85c/cffi-2.0.0-cp314-cp314t-win32.whl", hash = "sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e", size = 180487, upload-time = "2025-09-08T23:23:40.423Z" }, - { url = "https://files.pythonhosted.org/packages/bf/41/4c1168c74fac325c0c8156f04b6749c8b6a8f405bbf91413ba088359f60d/cffi-2.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6", size = 191726, upload-time = "2025-09-08T23:23:41.742Z" }, - { url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195, upload-time = "2025-09-08T23:23:43.004Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/d2/2cde336b375f55c76ca670f0be3978cc048e31e24f3b4d7ce8473150a388/cffi-2.1.1-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be", size = 183779, upload-time = "2026-08-03T21:19:15.602Z" }, + { url = "https://files.pythonhosted.org/packages/94/1a/4b2f7c92293ba05cbd4a9a1b28faaf0326272d9488e6354657571c48a7aa/cffi-2.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b", size = 184178, upload-time = "2026-08-03T21:19:16.67Z" }, + { url = "https://files.pythonhosted.org/packages/17/0b/ba385d8ccedf926c3cd06e8e2f327027da5afe5f0eb30f1f7bc43ac55125/cffi-2.1.1-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004", size = 211037, upload-time = "2026-08-03T21:19:17.705Z" }, + { url = "https://files.pythonhosted.org/packages/a3/b9/0f2e58b2cefa33255bff36935d42b13180fe559bba82596540eb404bde7d/cffi-2.1.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9", size = 218652, upload-time = "2026-08-03T21:19:18.735Z" }, + { url = "https://files.pythonhosted.org/packages/37/15/180e0dab27b9312c7479003d14c9e547634b7dcb934e2cc4650e1b131a7a/cffi-2.1.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98", size = 205422, upload-time = "2026-08-03T21:19:19.96Z" }, + { url = "https://files.pythonhosted.org/packages/18/d4/03026f0c850cbbaa9030750490225b4a7f4d524ea4df72c3cc740a90f4ef/cffi-2.1.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9", size = 205444, upload-time = "2026-08-03T21:19:21.246Z" }, + { url = "https://files.pythonhosted.org/packages/75/77/60bebf6f818bec84210ac5b6979ce4eeadce6fbbaabc9c7ab23e506d1ce5/cffi-2.1.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6", size = 218742, upload-time = "2026-08-03T21:19:22.523Z" }, + { url = "https://files.pythonhosted.org/packages/b0/ae/679bf47e73fd77b352171727f07de559a003f14de5d02b904a6ec1fa73ca/cffi-2.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf", size = 221054, upload-time = "2026-08-03T21:19:23.694Z" }, + { url = "https://files.pythonhosted.org/packages/09/b8/eefc0e06913b70aa153bf74c946094a18f58fd4aff11b7f372bfdfdca050/cffi-2.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659", size = 213489, upload-time = "2026-08-03T21:19:24.922Z" }, + { url = "https://files.pythonhosted.org/packages/6f/13/4e56852824a03cdf68523a35686f1c28eacd4bd30a7b0a78e682e6e6e1d3/cffi-2.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9", size = 220241, upload-time = "2026-08-03T21:19:26.214Z" }, + { url = "https://files.pythonhosted.org/packages/99/7f/040f9e163e4acac3ee3d85b02d00b2576e7ca980d8785f0a3a5f1a9bf7f5/cffi-2.1.1-cp310-cp310-win32.whl", hash = "sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41", size = 174578, upload-time = "2026-08-03T21:19:27.338Z" }, + { url = "https://files.pythonhosted.org/packages/ba/0b/644a2ec1a4eaba49c2939410bb1eb1d25b09d6d0582f5d2f95c537043725/cffi-2.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1", size = 185082, upload-time = "2026-08-03T21:19:28.409Z" }, + { url = "https://files.pythonhosted.org/packages/70/d2/16d99a0c4948febc0ebd133a13b2f688ff7f8cb04da971e1128872ce0c03/cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12", size = 183838, upload-time = "2026-08-03T21:19:29.637Z" }, + { url = "https://files.pythonhosted.org/packages/cd/95/31b535a9f0220ae9f357de4a08d57ce89cb417653c2fd9f075f50822a388/cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1", size = 184168, upload-time = "2026-08-03T21:19:30.764Z" }, + { url = "https://files.pythonhosted.org/packages/ad/5a/4707a0dc1f203f5dde5a907b0d4e3c25d71120241048bd5bc6f1bb9d4e71/cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0", size = 211805, upload-time = "2026-08-03T21:19:31.867Z" }, + { url = "https://files.pythonhosted.org/packages/ad/66/c19feabb28485b6e0bbaaafa90837a1ef5d302e90f2178bd33f17a49879b/cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813", size = 218716, upload-time = "2026-08-03T21:19:32.896Z" }, + { url = "https://files.pythonhosted.org/packages/a7/92/500760486c8baab49a7a8a58ba7fc3355ec3974b454b8a09e528efde9e1d/cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990", size = 205569, upload-time = "2026-08-03T21:19:34.142Z" }, + { url = "https://files.pythonhosted.org/packages/a5/a7/a67c733254d6e7373f7822f8082d8d6beade791e0cf12a7611f376fa61c7/cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af", size = 204907, upload-time = "2026-08-03T21:19:35.174Z" }, + { url = "https://files.pythonhosted.org/packages/f7/a4/4399daaf8f7dfee9d7c3327fdb0426ee041cc63edc358b93911ceb2bfc7a/cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632", size = 217807, upload-time = "2026-08-03T21:19:36.286Z" }, + { url = "https://files.pythonhosted.org/packages/28/f7/dabe6da2466ecbd82dc62e7342dc6b1065dad990c06f00f0ede9ebf2a0ed/cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd", size = 221252, upload-time = "2026-08-03T21:19:37.416Z" }, + { url = "https://files.pythonhosted.org/packages/ce/87/616202d8e51342c07d2534c510111c4cc37201775ce8f60802c9335d1edd/cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a", size = 214214, upload-time = "2026-08-03T21:19:38.507Z" }, + { url = "https://files.pythonhosted.org/packages/b4/c6/ab025d75d2c26c19b087c0124e75ee31cb65032f4fe345d356d8c507ab97/cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa", size = 219408, upload-time = "2026-08-03T21:19:39.809Z" }, + { url = "https://files.pythonhosted.org/packages/db/e2/7e8109f65445bdc673a7b54f02c677de462db75674220fd1335efc8eb598/cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3", size = 174470, upload-time = "2026-08-03T21:19:41.246Z" }, + { url = "https://files.pythonhosted.org/packages/73/c0/77ba02423c2f7d7091143c45cd49e0e6575c4c1967394bb542bd923a9b74/cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0", size = 185096, upload-time = "2026-08-03T21:19:42.615Z" }, + { url = "https://files.pythonhosted.org/packages/7c/47/9f1f85f9672ceda4984dc6c4f8824e8558992a2972c3d3c81fb8eb28d4ba/cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455", size = 179941, upload-time = "2026-08-03T21:19:43.747Z" }, + { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, + { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, + { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, + { url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" }, + { url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" }, + { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, + { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, + { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, + { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, + { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" }, + { url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" }, + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" }, + { url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" }, + { url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" }, + { url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" }, + { url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" }, + { url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" }, + { url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" }, + { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, + { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, + { url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" }, + { url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" }, + { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, + { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, + { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, + { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, + { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, + { url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" }, + { url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" }, + { url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" }, + { url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" }, + { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, + { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, + { url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" }, + { url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" }, ] [[package]] @@ -144,25 +172,44 @@ wheels = [ [[package]] name = "curl-cffi" -version = "0.14.0" +version = "0.17.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi" }, { name = "cffi" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/9b/c9/0067d9a25ed4592b022d4558157fcdb6e123516083700786d38091688767/curl_cffi-0.14.0.tar.gz", hash = "sha256:5ffbc82e59f05008ec08ea432f0e535418823cda44178ee518906a54f27a5f0f", size = 162633, upload-time = "2025-12-16T03:25:07.931Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/aa/f0/0f21e9688eaac85e705537b3a87a5588d0cefb2f09d83e83e0e8be93aa99/curl_cffi-0.14.0-cp39-abi3-macosx_14_0_arm64.whl", hash = "sha256:e35e89c6a69872f9749d6d5fda642ed4fc159619329e99d577d0104c9aad5893", size = 3087277, upload-time = "2025-12-16T03:24:49.607Z" }, - { url = "https://files.pythonhosted.org/packages/ba/a3/0419bd48fce5b145cb6a2344c6ac17efa588f5b0061f212c88e0723da026/curl_cffi-0.14.0-cp39-abi3-macosx_15_0_x86_64.whl", hash = "sha256:5945478cd28ad7dfb5c54473bcfb6743ee1d66554d57951fdf8fc0e7d8cf4e45", size = 5804650, upload-time = "2025-12-16T03:24:51.518Z" }, - { url = "https://files.pythonhosted.org/packages/e2/07/a238dd062b7841b8caa2fa8a359eb997147ff3161288f0dd46654d898b4d/curl_cffi-0.14.0-cp39-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c42e8fa3c667db9ccd2e696ee47adcd3cd5b0838d7282f3fc45f6c0ef3cfdfa7", size = 8231918, upload-time = "2025-12-16T03:24:52.862Z" }, - { url = "https://files.pythonhosted.org/packages/7c/d2/ce907c9b37b5caf76ac08db40cc4ce3d9f94c5500db68a195af3513eacbc/curl_cffi-0.14.0-cp39-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:060fe2c99c41d3cb7f894de318ddf4b0301b08dca70453d769bd4e74b36b8483", size = 8654624, upload-time = "2025-12-16T03:24:54.579Z" }, - { url = "https://files.pythonhosted.org/packages/f2/ae/6256995b18c75e6ef76b30753a5109e786813aa79088b27c8eabb1ef85c9/curl_cffi-0.14.0-cp39-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b158c41a25388690dd0d40b5bc38d1e0f512135f17fdb8029868cbc1993d2e5b", size = 8010654, upload-time = "2025-12-16T03:24:56.507Z" }, - { url = "https://files.pythonhosted.org/packages/fb/10/ff64249e516b103cb762e0a9dca3ee0f04cf25e2a1d5d9838e0f1273d071/curl_cffi-0.14.0-cp39-abi3-manylinux_2_28_i686.whl", hash = "sha256:1439fbef3500fb723333c826adf0efb0e2e5065a703fb5eccce637a2250db34a", size = 7781969, upload-time = "2025-12-16T03:24:57.885Z" }, - { url = "https://files.pythonhosted.org/packages/51/76/d6f7bb76c2d12811aa7ff16f5e17b678abdd1b357b9a8ac56310ceccabd5/curl_cffi-0.14.0-cp39-abi3-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e7176f2c2d22b542e3cf261072a81deb018cfa7688930f95dddef215caddb469", size = 7969133, upload-time = "2025-12-16T03:24:59.261Z" }, - { url = "https://files.pythonhosted.org/packages/23/7c/cca39c0ed4e1772613d3cba13091c0e9d3b89365e84b9bf9838259a3cd8f/curl_cffi-0.14.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:03f21ade2d72978c2bb8670e9b6de5260e2755092b02d94b70b906813662998d", size = 9080167, upload-time = "2025-12-16T03:25:00.946Z" }, - { url = "https://files.pythonhosted.org/packages/75/03/a942d7119d3e8911094d157598ae0169b1c6ca1bd3f27d7991b279bcc45b/curl_cffi-0.14.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:58ebf02de64ee5c95613209ddacb014c2d2f86298d7080c0a1c12ed876ee0690", size = 9520464, upload-time = "2025-12-16T03:25:02.922Z" }, - { url = "https://files.pythonhosted.org/packages/a2/77/78900e9b0833066d2274bda75cba426fdb4cef7fbf6a4f6a6ca447607bec/curl_cffi-0.14.0-cp39-abi3-win_amd64.whl", hash = "sha256:6e503f9a103f6ae7acfb3890c843b53ec030785a22ae7682a22cc43afb94123e", size = 1677416, upload-time = "2025-12-16T03:25:04.902Z" }, - { url = "https://files.pythonhosted.org/packages/5c/7c/d2ba86b0b3e1e2830bd94163d047de122c69a8df03c5c7c36326c456ad82/curl_cffi-0.14.0-cp39-abi3-win_arm64.whl", hash = "sha256:2eed50a969201605c863c4c31269dfc3e0da52916086ac54553cfa353022425c", size = 1425067, upload-time = "2025-12-16T03:25:06.454Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/96/4c/69074f9797d83a5401b3c6bc58c5de5aad6d1a085d0497b87a093a152e87/curl_cffi-0.17.0.tar.gz", hash = "sha256:31ee8500d06d6502ce1ec0b7ded1c5aa8e8f3401bbe37ccd78d6153d859d8f3c", size = 282294, upload-time = "2026-10-26T04:13:39.396Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c6/f8/6e289cc68d943c4625732eb253bdeec92c5022c7d5ea9215c0581c526789/curl_cffi-0.17.0-cp310-abi3-macosx_10_9_x86_64.whl", hash = "sha256:56d622930eac5cee4cc6ebe63eaba3ecca65a2c73aa6bdf099c2ffae55ee988c", size = 3171349, upload-time = "2026-10-26T04:12:42.896Z" }, + { url = "https://files.pythonhosted.org/packages/dc/ab/cd7e71bc96c36521193d3dcd38e1a08a9939538fc34b50ba81f30201f9b3/curl_cffi-0.17.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:88cb5e34eb23eb2106711b06df68027209c72be709df239c6029345551e0acfd", size = 2921615, upload-time = "2026-10-26T04:12:44.941Z" }, + { url = "https://files.pythonhosted.org/packages/e6/6f/063eb68f3353bde506f4ca01005b24a07f59103bc8640889ea1954af9302/curl_cffi-0.17.0-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:aa91d26234516ddb9eb97310d5fe1705aa6f677f101d57ffdb76d5f75439506e", size = 13438302, upload-time = "2026-10-26T04:12:46.663Z" }, + { url = "https://files.pythonhosted.org/packages/5a/94/3a45c5c9742bbfca3dbbcb3734d4451f769a14fb87a81e2704569fb4fb01/curl_cffi-0.17.0-cp310-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:93f706c46370cf83c53ffe08cf33892e657c21a6597802f67f1559e4c642ee65", size = 13226053, upload-time = "2026-10-26T04:12:48.904Z" }, + { url = "https://files.pythonhosted.org/packages/e5/ef/7bb612007cf254ad6406e9563201baf87f57686308353b0fefde4b356212/curl_cffi-0.17.0-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:af0782d5e340b65fd76701630f0284a8f8243d77df5f2637efd09a4b009f4e24", size = 14053278, upload-time = "2026-10-26T04:12:51.053Z" }, + { url = "https://files.pythonhosted.org/packages/82/54/ba4debb95ac4ea365e189c8ed10bf6d28c4d9406b967d0b2bb4636e6b0a6/curl_cffi-0.17.0-cp310-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7e126f4675d100f1ad6247a0d8e0b3ebe3fa2f4a123e2b9b78e4880b40f5bedd", size = 13410090, upload-time = "2026-10-26T04:12:53.222Z" }, + { url = "https://files.pythonhosted.org/packages/c7/c5/5d95229b9e237671365f0a320ea65f96dee515e798103f0ec006b1cf3402/curl_cffi-0.17.0-cp310-abi3-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c11b405fa10530cec589349c1cc8d60a3a4fac20fb7be0b2713e7271a2737f57", size = 13510704, upload-time = "2026-10-26T04:12:55.554Z" }, + { url = "https://files.pythonhosted.org/packages/46/b0/0339a88f8b9236721f80e598b26173a2f1cbf415c1270b55a270a2f3ab4e/curl_cffi-0.17.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:3f737d386e77d4e5ac64998fac8b494b35d37e8cbda22f675b0126913e0e4d6d", size = 13160153, upload-time = "2026-10-26T04:12:57.623Z" }, + { url = "https://files.pythonhosted.org/packages/29/95/6d760e34a9935def9fdf4180a20080d6fb44153f79a5db76c7777724a3a2/curl_cffi-0.17.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:539eb6708c46433cd61745fda756f2754807f4774b31255d8ee56db0e97068fe", size = 13791120, upload-time = "2026-10-26T04:12:59.747Z" }, + { url = "https://files.pythonhosted.org/packages/a1/9f/e860ed1a3fc55c06ea2a148613d07342dc6c6ec2844a2f0ee864eb1b19ce/curl_cffi-0.17.0-cp310-abi3-win_amd64.whl", hash = "sha256:4c3993c7df155d622869b82a56adb018440587fd3faffeaf8d01cc016d2e1357", size = 2108164, upload-time = "2026-10-26T04:13:01.756Z" }, + { url = "https://files.pythonhosted.org/packages/69/30/f9609e68941179904c9a96498d4b83d9085887aa01192f81dffbec37d98d/curl_cffi-0.17.0-cp310-abi3-win_arm64.whl", hash = "sha256:e8cfb7eee2019fe879ab3304b33e84ba60dbcec148c34c343c49b8c67f9ddad5", size = 1828546, upload-time = "2026-10-26T04:13:03.152Z" }, + { url = "https://files.pythonhosted.org/packages/f5/74/e085f86545e823f0da48e2f922e28e56596a477333ad76913bcf5be856a2/curl_cffi-0.17.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:ae0442e45d6e0c987f84cb88bd6a99d7b91c8e2b017c18048a6c4fed63847c80", size = 8659725, upload-time = "2026-10-26T04:13:04.517Z" }, + { url = "https://files.pythonhosted.org/packages/ea/ef/40e7c64a01d9928c16f79cf0bf7f1afc9be02f331a8a32e4617b60b815f1/curl_cffi-0.17.0-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:0d85bec9648bf7c14c3b43056ba82521740f72cd96ed7700a0e1973e7fc93f74", size = 8659709, upload-time = "2026-10-26T04:13:06.308Z" }, + { url = "https://files.pythonhosted.org/packages/e4/67/4c0d6a0bd44da23f36c53752825583785242ce714f63737e4d2dc813047f/curl_cffi-0.17.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:8a08236aac049468d83fc19699102a3d953769ccbfe2b31b63e1d26c5bb07af3", size = 3171701, upload-time = "2026-10-26T04:13:08.14Z" }, + { url = "https://files.pythonhosted.org/packages/43/23/44a51c58960590a8a588a0ed4593bb124f86c54f7e052b5e2894607b25ec/curl_cffi-0.17.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:9426fa386a0f299ab043f64e59689d52e6ee2370f19238aa0bb42e6bf3620aaf", size = 2921843, upload-time = "2026-10-26T04:13:09.566Z" }, + { url = "https://files.pythonhosted.org/packages/71/5d/52559ff48b2ff03f307e059421038a491f888d674e68b655a2b28a169b7d/curl_cffi-0.17.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a93d3cd83aed4307001ca560b931317e0690ddf3c17e86c2d5b6e0722780b40c", size = 13446820, upload-time = "2026-10-26T04:13:11.419Z" }, + { url = "https://files.pythonhosted.org/packages/19/f9/b2df601e21aeece023f61e75bfb7cbf8c93c400267263ca4a9a238fc2bfd/curl_cffi-0.17.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f7e0817633948a8b00e65ef3662bf139cef3fb4d3847e29a720f8072c3d76a18", size = 14056775, upload-time = "2026-10-26T04:13:13.33Z" }, + { url = "https://files.pythonhosted.org/packages/e1/e9/f01dc638b6b97b51fcad2852a4ae981a176503d883af4f7a43102d065f0e/curl_cffi-0.17.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:2cc7d939014953223c96e78098bb24c336e7268eb6529c0d5fa9a53805a4acee", size = 13167425, upload-time = "2026-10-26T04:13:15.621Z" }, + { url = "https://files.pythonhosted.org/packages/a1/50/2b72426b0860a0b551bf69f3c085519b69d1f7d6ec098f5fac9fd5cdcfa9/curl_cffi-0.17.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fc33ca76371bc96df3c4e8593449a1e0e28086bf8016addb851905090069178c", size = 13796024, upload-time = "2026-10-26T04:13:17.846Z" }, + { url = "https://files.pythonhosted.org/packages/3f/07/8eeeb3516ebfa4677ef6b74109bee3a72790123a850d4ff0936a8d2d6ed3/curl_cffi-0.17.0-cp314-cp314t-win_amd64.whl", hash = "sha256:51199328450e07c8ef8430a7ccce1acfb199b5cd7595e8f958e84f2faedccdac", size = 2161866, upload-time = "2026-10-26T04:13:19.908Z" }, + { url = "https://files.pythonhosted.org/packages/36/fc/35c6216d7140bed71b3b54b3cb3e7d16a380fb0bb5e47d9b19056198d729/curl_cffi-0.17.0-cp314-cp314t-win_arm64.whl", hash = "sha256:b09f03f1aafcbbf6175610005e4e0192413148fe44c65b789a2aadfff9384a7d", size = 1898770, upload-time = "2026-10-26T04:13:21.228Z" }, + { url = "https://files.pythonhosted.org/packages/62/72/9b1e633ebfc860e08ddb9346b54f7bcb59701dbbd5b0c9c3af5d65443389/curl_cffi-0.17.0-cp315-abi3.abi3t-macosx_10_15_x86_64.whl", hash = "sha256:a055f709029d2deaafed6a3a2a58c219d7ee2776a1d2357272d3ef230fb30c5c", size = 3171558, upload-time = "2026-10-26T04:13:23.09Z" }, + { url = "https://files.pythonhosted.org/packages/a7/ab/770a84343fbf72d07d6829bc0f633b77391ab710b28078e9c93a4b9f7f93/curl_cffi-0.17.0-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:f8cf840646d3e57637b8caae7d0d93334dfed0bfbf6f160b36479a7d6069d547", size = 2921865, upload-time = "2026-10-26T04:13:24.474Z" }, + { url = "https://files.pythonhosted.org/packages/b9/81/4562d29ee38fc71864ce1157a620024dd6d91bed50542ee944abd8d51e64/curl_cffi-0.17.0-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ad88837e627896f794ab77c5d61245f5fbc0da1e86a39043404b94bef45e98ef", size = 13437898, upload-time = "2026-10-26T04:13:25.908Z" }, + { url = "https://files.pythonhosted.org/packages/e0/c1/3790bbfd5051ead4d00bb8c3beefa985c071b0630e2ed0c03afcb3247e5a/curl_cffi-0.17.0-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2dac9c915a0ee7d7cc4285203d210816bb187c8deb5c20ee21e0613639c2a8bf", size = 14052826, upload-time = "2026-10-26T04:13:27.954Z" }, + { url = "https://files.pythonhosted.org/packages/e1/04/6f439a1e6ff837996f604892455d0513d380f5db59b7957968896b6811e9/curl_cffi-0.17.0-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:0e70d25d88adc66818d831805e460704088f445269eaabbf884ab05d437c2f99", size = 13160741, upload-time = "2026-10-26T04:13:29.952Z" }, + { url = "https://files.pythonhosted.org/packages/a6/2f/cb78f0af5a48853638553023bc360718a8a371424591c5c1f7f9cd5d80ce/curl_cffi-0.17.0-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:4f3413b62c780f2a5c7f8a0f6a1d8114f055043a273981b9732abedb5367202b", size = 13791446, upload-time = "2026-10-26T04:13:32.161Z" }, + { url = "https://files.pythonhosted.org/packages/1d/4c/b577dbd652069ad4860d3ab06ed9e72b4e71959d5fce2dcc920e1fc4e00a/curl_cffi-0.17.0-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:5ca006230676c7c2f2e5708d02e5852a09caee49d82f1f2a469d5d6537a11baa", size = 2161586, upload-time = "2026-10-26T04:13:34.042Z" }, + { url = "https://files.pythonhosted.org/packages/4a/c5/3bba2797e70d8e392caa4fe1543dc9398b859bec7f8e2f8b4dd6988cefd9/curl_cffi-0.17.0-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:32f9508a92adaa8c9c35fd4cda786c9e697643afc2eda8dc4c3d426a910b453a", size = 1898563, upload-time = "2026-10-26T04:13:35.354Z" }, + { url = "https://files.pythonhosted.org/packages/61/c2/4ab387b783b61b6fb43bcb0bbd9c126b33e0398241c7179dec343d428465/curl_cffi-0.17.0-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:918a493717da703bc10507b811e347f4ad94132e30c6709fc1e85daf79979565", size = 8659769, upload-time = "2026-10-26T04:13:37.043Z" }, ] [[package]] @@ -170,7 +217,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -634,14 +681,14 @@ requires-dist = [ { name = "beautifulsoup4", specifier = ">=4.12" }, { name = "browser-cookie3", specifier = ">=0.19" }, { name = "click", specifier = ">=8.0" }, - { name = "curl-cffi", specifier = ">=0.7" }, + { name = "curl-cffi", specifier = ">=0.15.0" }, { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.14,<1.15" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" }, { name = "pyyaml", specifier = ">=6.0" }, { name = "rich", specifier = ">=13.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.8" }, { name = "types-pyyaml", marker = "extra == 'dev'", specifier = ">=6.0.12" }, - { name = "xclienttransaction", specifier = ">=1.0.1" }, + { name = "xclienttransaction", specifier = ">=1.0.3" }, ] provides-extras = ["dev"] @@ -677,12 +724,12 @@ wheels = [ [[package]] name = "xclienttransaction" -version = "1.0.1" +version = "1.0.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "beautifulsoup4" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/eb/c7/c841afe6759567cf29e36196dff65c935682b69ae38e986bd14e7decf74e/xclienttransaction-1.0.1.tar.gz", hash = "sha256:e4e032ff27e76ab927c0a7f57ad3630e06b7100c113bdf22b03cdde9584756f3", size = 9062, upload-time = "2025-10-09T10:38:31.485Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/11/6f5a55df6d464fe6f839fe96c3863fa2338005ed8e83e89b0a9db5716b5a/xclienttransaction-1.0.3.tar.gz", hash = "sha256:1eeb5d48cec6a224189bbd8a6021c40486fa3aff650478672bccf82b3436cedc", size = 10609, upload-time = "2026-06-26T10:47:39.664Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/b8/b953828e2f0f658f7f2d6354525728c9569c83937ebe4903f2391f02a702/xclienttransaction-1.0.1-py3-none-any.whl", hash = "sha256:0280e021129a38f8ee2ebede6406d4c065a599430bd4c8aa0c122f2e42f9f0f0", size = 10724, upload-time = "2025-10-09T10:38:30.098Z" }, + { url = "https://files.pythonhosted.org/packages/fa/a1/be735112ebe49916065e6f80017b93e92fc8880789c3f4f17380db7f531a/xclienttransaction-1.0.3-py3-none-any.whl", hash = "sha256:f73dd2a4b6856f98fa45f0cd26c9a0fdc0b2ceba0e79b5523cdf8aac7efc59fe", size = 10778, upload-time = "2026-06-26T10:47:38.401Z" }, ] From a50aa90e42226302e973c2b098a7e50bb66a20fe Mon Sep 17 00:00:00 2001 From: jackwener Date: Fri, 27 Nov 2026 18:14:54 +0000 Subject: [PATCH 2/8] fix(graphql,tx): restore ClientTransaction bootstrap, refresh queryIds, fail-closed unsigned POSTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Bootstrap ClientTransaction from authenticated https://x.com/home with unauthenticated fallback to https://x.com/i/jf/ (handles X's Vite x-web migration on anonymous / and /home) and never leak cookies to CDN assets - Refresh FALLBACK_QUERY_IDS against current twitter-openapi IDs and add UserByRestId; support TWITTER_QID_ env overrides and 24h owner-only disk cache for live-resolved queryIds - Scan both responsive-web/client-web and x-web/x-web bundles (following ./assets/*.js chunks) via /i/jf/ and / - Treat GraphQL "Query: Unspecified" / persisted-query-not-found errors as stale queryIds and retry once with live lookup on GET and POST (fixes #59) - Fail closed on unsigned POST requests when x-client-transaction-id is unavailable (overrideable with TWITTER_ALLOW_UNSIGNED=1, mitigates #72) - Prefer chrome136 TLS impersonation target when available in curl_cffi Absorbs #74, #77, #79, #82, #83, #84, #86, #89, #90, #91, #93, #98, #99, #101, and query-ID/transaction practices from quangdang46/twitter_cli. Closes #59, #69, #73, #78, #88. Co-authored-by: Lucius Co-authored-by: Canc Co-authored-by: Jawad Margieh Co-authored-by: Kage Co-authored-by: Ahmed Elshaabany Co-authored-by: Perry Huang Co-authored-by: LiuWei Co-authored-by: Abdurrahman Özkan Co-authored-by: Blacksuite Co-authored-by: GodfreyPrince Co-authored-by: Mckgare0717 Co-authored-by: Stoner Co-authored-by: Trần Quang Đãng <91641923+quangdang46@users.noreply.github.com> --- tests/test_client.py | 295 ++++++++++++++++++++++++++++++++++++++++- tests/test_smoke.py | 17 +++ twitter_cli/client.py | 144 +++++++++++++++----- twitter_cli/graphql.py | 237 +++++++++++++++++++++++++++------ 4 files changed, 622 insertions(+), 71 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index c1393d3..b167f70 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -207,8 +207,8 @@ def test_url_length_with_full_features(self): assert len(url) < 8000, f"URL too long: {len(url)} chars" def test_searchtimeline_fallback_query_id_regression(self): - """Keep SearchTimeline fallback aligned with the live operation after issue #39.""" - assert FALLBACK_QUERY_IDS["SearchTimeline"] == "VhUd6vHVmLBcw0uX-6jMLA" + """Keep SearchTimeline fallback aligned with the live operation.""" + assert FALLBACK_QUERY_IDS["SearchTimeline"] == "vLHjqbDv7TPFMBkIIO1nOA" # ── _best_chrome_target ────────────────────────────────────────────────── @@ -1356,7 +1356,9 @@ def _make_client(self): client._max_retries = 3 client._retry_base_delay = 5.0 client._max_count = 200 - client._client_transaction = None + # media upload is a POST: it needs a transaction id like any other write + client._client_transaction = MagicMock() + client._client_transaction.generate_transaction_id.return_value = "tid-media" client._ct_init_attempted = True return client @@ -1496,7 +1498,9 @@ def _make_client(self): client._max_retries = 0 client._retry_base_delay = 0 client._max_count = 200 - client._client_transaction = None + # media upload is a POST: it needs a transaction id like any other write + client._client_transaction = MagicMock() + client._client_transaction.generate_transaction_id.return_value = "tid-media" client._ct_init_attempted = True return client @@ -1545,3 +1549,286 @@ def mock_post(operation_name, variables, features=None): assert captured.get("product") == "Latest" assert captured.get("querySource") == "typed_query" + + +# ── Stale queryId retry & resolution ───────────────────────────────────── + + +class TestStaleQueryRetry: + def test_graphql_get_retries_query_unspecified_with_live_id(self): + client = TwitterClient.__new__(TwitterClient) + fallback = FALLBACK_QUERY_IDS["HomeTimeline"] + urls = [] + + def api_get(url): + urls.append(url) + if len(urls) == 1: + raise TwitterAPIError(0, "Twitter API returned errors: Query: Unspecified") + return {"data": {"home": {}}} + + client._api_get = api_get + + with ( + patch( + "twitter_cli.client._resolve_query_id", + side_effect=[fallback, "live-query-id"], + ) as resolve, + patch("twitter_cli.client._invalidate_query_id") as invalidate, + ): + result = client._graphql_get("HomeTimeline", {"count": 3}, FEATURES) + + assert result == {"data": {"home": {}}} + assert fallback in urls[0] + assert "live-query-id" in urls[1] + assert resolve.call_count == 2 + assert resolve.call_args_list[1].kwargs["prefer_fallback"] is False + invalidate.assert_called_once_with("HomeTimeline") + + def test_graphql_post_retries_query_unspecified_with_live_id(self): + client = TwitterClient.__new__(TwitterClient) + fallback = FALLBACK_QUERY_IDS["CreateTweet"] + requests = [] + + def api_request(url, method="GET", body=None): + requests.append((url, method, body)) + if len(requests) == 1: + raise TwitterAPIError(0, "Twitter API returned errors: Query: Unspecified") + return {"data": {"create_tweet": {}}} + + client._api_request = api_request + + with ( + patch( + "twitter_cli.client._resolve_query_id", + side_effect=[fallback, "live-query-id"], + ), + patch("twitter_cli.client._invalidate_query_id") as invalidate, + ): + result = client._graphql_post("CreateTweet", {"tweet_text": "hello"}, FEATURES) + + assert result == {"data": {"create_tweet": {}}} + assert requests[0][2]["queryId"] == fallback + assert requests[1][2]["queryId"] == "live-query-id" + invalidate.assert_called_once_with("CreateTweet") + + def test_graphql_get_does_not_retry_unrelated_status_zero_error(self): + client = TwitterClient.__new__(TwitterClient) + fallback = FALLBACK_QUERY_IDS["HomeTimeline"] + client._api_get = MagicMock( + side_effect=TwitterAPIError(0, "Twitter API network error: timeout") + ) + + with ( + patch("twitter_cli.client._resolve_query_id", return_value=fallback) as resolve, + patch("twitter_cli.client._invalidate_query_id") as invalidate, + pytest.raises(TwitterAPIError), + ): + client._graphql_get("HomeTimeline", {"count": 3}, FEATURES) + + resolve.assert_called_once() + invalidate.assert_not_called() + + +class TestQueryIdResolution: + def test_env_override_takes_precedence(self, monkeypatch): + from twitter_cli import graphql + + monkeypatch.setenv("TWITTER_QID_SearchTimeline", "pinned-search-qid") + assert graphql._resolve_query_id("SearchTimeline") == "pinned-search-qid" + + def test_disk_cache_roundtrip_and_invalidation(self, monkeypatch, tmp_path): + import json + from twitter_cli import graphql + + cache_file = tmp_path / "query_ids_cache.json" + monkeypatch.setattr(graphql, "_qid_cache_path", lambda: cache_file) + monkeypatch.setattr(graphql, "_cached_query_ids", {}) + monkeypatch.setattr(graphql, "_disk_cache_loaded", False) + + graphql._save_disk_query_ids({"HomeTimeline": "disk-cached-id"}) + assert cache_file.exists() + + resolved = graphql._resolve_query_id("HomeTimeline", prefer_fallback=True) + assert resolved == "disk-cached-id" + + graphql._invalidate_query_id("HomeTimeline") + assert "HomeTimeline" not in graphql._cached_query_ids + assert "HomeTimeline" not in json.loads(cache_file.read_text(encoding="utf-8"))["query_ids"] + + def test_scan_bundles_follows_xweb_assets(self, monkeypatch, tmp_path): + from twitter_cli import graphql + + cache_file = tmp_path / "query_ids_cache.json" + monkeypatch.setattr(graphql, "_qid_cache_path", lambda: cache_file) + monkeypatch.setattr(graphql, "_cached_query_ids", {}) + monkeypatch.setattr(graphql, "_bundles_scanned", False) + + def fake_fetch(url, headers=None): + if url == "https://x.com/i/jf/": + return '' + if url == "https://abs.twimg.com/x-web/x-web/entry-client.js": + return 'const deps=["./assets/chunk-abc.js"];' + if url == "https://abs.twimg.com/x-web/x-web/assets/chunk-abc.js": + return 'queryId:"freshQid123",operationName:"SearchTimeline"' + raise RuntimeError("unexpected url: " + url) + + graphql._scan_bundles(fake_fetch) + assert graphql._cached_query_ids["SearchTimeline"] == "freshQid123" + + +# ── ClientTransaction bootstrap (x-client-transaction-id) ─────────────── + +_CT_HOME_HTML = ( + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' +) + +_CT_STRIPPED_HTML = "" + +_CT_ONDEMAND_JS = ( + "var a=[0,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];" + "var b=function(c){return(a[(c[0], 16)],(a[(c[1], 17)]),(a[(c[2], 18)])," + "(a[(c[3], 19)]),(a[(c[4], 20)]));};var d=b(a);" +) + + +class TestClientTransactionBootstrap: + def _make_client(self, cookie_string=None): + client = TwitterClient.__new__(TwitterClient) + client._auth_token = "auth_tok" + client._ct0 = "ct0_val" + client._cookie_string = cookie_string + client._client_transaction = None + client._ct_init_attempted = False + client._load_ct_cache = MagicMock(return_value=False) + client._save_ct_cache = MagicMock() + return client + + @patch("twitter_cli.client._update_features_from_html") + @patch("twitter_cli.client.ClientTransaction") + @patch("twitter_cli.client._gen_ct_headers", return_value={"Referer": "https://x.com"}) + @patch("twitter_cli.client._get_cffi_session") + def test_bootstraps_from_home_with_cookie( + self, mock_session, _mock_ct_headers, mock_tx, _mock_features + ): + import bs4 + + home_page = MagicMock(content=_CT_HOME_HTML.encode("utf-8"), text=_CT_HOME_HTML) + ondemand_page = MagicMock(text=_CT_ONDEMAND_JS) + mock_session.return_value.get.side_effect = [home_page, ondemand_page] + + client = self._make_client(cookie_string="auth_token=auth_tok; ct0=ct0_val") + client._ensure_client_transaction() + + first = mock_session.return_value.get.call_args_list[0] + second = mock_session.return_value.get.call_args_list[1] + assert first.args[0] == "https://x.com/home" + assert first.kwargs["headers"]["Cookie"] == "auth_token=auth_tok; ct0=ct0_val" + assert second.args[0] == ( + "https://abs.twimg.com/responsive-web/client-web/" + "ondemand.s.38289b77fa31a72ca.js" + ) + # Session cookies must not leak onto the CDN ondemand JS fetch. + assert "Cookie" not in second.kwargs["headers"] + mock_tx.assert_called_once() + assert isinstance(mock_tx.call_args.kwargs["home_page_response"], bs4.BeautifulSoup) + + @patch("twitter_cli.client._update_features_from_html") + @patch("twitter_cli.client.ClientTransaction") + @patch("twitter_cli.client._gen_ct_headers", return_value={"Referer": "https://x.com"}) + @patch("twitter_cli.client._get_cffi_session") + def test_falls_back_to_i_jf_when_home_lacks_ondemand( + self, mock_session, _mock_ct_headers, mock_tx, _mock_features + ): + stripped = MagicMock(content=_CT_STRIPPED_HTML.encode("utf-8"), text=_CT_STRIPPED_HTML) + jf_page = MagicMock(content=_CT_HOME_HTML.encode("utf-8"), text=_CT_HOME_HTML) + ondemand_page = MagicMock(text=_CT_ONDEMAND_JS) + mock_session.return_value.get.side_effect = [stripped, jf_page, ondemand_page] + + client = self._make_client(cookie_string=None) + client._ensure_client_transaction() + + calls = mock_session.return_value.get.call_args_list + assert calls[0].args[0] == "https://x.com/home" + assert calls[1].args[0] == "https://x.com/i/jf/" + assert "Cookie" not in calls[1].kwargs["headers"] + assert calls[2].args[0] == ( + "https://abs.twimg.com/responsive-web/client-web/" + "ondemand.s.38289b77fa31a72ca.js" + ) + mock_tx.assert_called_once() + + def test_real_parser_resolves_ondemand_from_current_layout(self): + import bs4 + from x_client_transaction.utils import get_ondemand_file_url + + soup = bs4.BeautifulSoup(_CT_HOME_HTML, "html.parser") + url = get_ondemand_file_url(response=soup) + assert url == ( + "https://abs.twimg.com/responsive-web/client-web/" + "ondemand.s.38289b77fa31a72ca.js" + ) + + +# ── Fail-closed guard for unsigned POSTs ───────────────────────────────── + + +class TestUnsignedWriteGuard: + @staticmethod + def _client(): + client = TwitterClient.__new__(TwitterClient) + client._auth_token = "test_token" + client._ct0 = "test_ct0" + client._cookie_string = None + client._client_transaction = None + client._ct_init_attempted = True + return client + + def test_post_without_transaction_id_is_refused(self): + client = self._client() + with pytest.raises(TwitterAPIError) as exc: + client._build_headers("https://x.com/i/api/graphql/qid/CreateTweet", "POST") + assert "REFUSING unsigned write" in str(exc.value) + + def test_override_env_allows_unsigned_post(self, monkeypatch): + monkeypatch.setenv("TWITTER_ALLOW_UNSIGNED", "1") + client = self._client() + headers = client._build_headers( + "https://x.com/i/api/graphql/qid/CreateTweet", "POST" + ) + assert "X-Client-Transaction-Id" not in headers + + def test_get_without_transaction_id_is_allowed(self): + client = self._client() + headers = client._build_headers( + "https://x.com/i/api/graphql/qid/HomeTimeline", "GET" + ) + assert "X-Client-Transaction-Id" not in headers + assert "Authorization" in headers + + def test_post_with_transaction_id_sets_header(self): + client = self._client() + transaction = MagicMock() + transaction.generate_transaction_id.return_value = "tid-123" + client._client_transaction = transaction + headers = client._build_headers( + "https://x.com/i/api/graphql/qid/CreateTweet", "POST" + ) + assert headers["X-Client-Transaction-Id"] == "tid-123" + + def test_failing_generator_also_refuses(self): + client = self._client() + transaction = MagicMock() + transaction.generate_transaction_id.side_effect = RuntimeError("boom") + client._client_transaction = transaction + with pytest.raises(TwitterAPIError): + client._build_headers("https://x.com/i/api/graphql/qid/CreateTweet", "POST") diff --git a/tests/test_smoke.py b/tests/test_smoke.py index d7cec04..db2f1ae 100644 --- a/tests/test_smoke.py +++ b/tests/test_smoke.py @@ -83,3 +83,20 @@ def test_feed(self): result, payload = _invoke("feed", "--max", "3") assert result.exit_code == 0, f"feed failed: {result.output}" assert payload["ok"] is True + + +@smoke +class TestCTGatedReads: + """Endpoints that 404 without x-client-transaction-id.""" + + def test_followers(self): + result, payload = _invoke("followers", "elonmusk", "--max", "3") + assert result.exit_code == 0, f"followers failed: {result.output}" + assert payload["ok"] is True + assert len(payload["data"]) >= 1 + + def test_following(self): + result, payload = _invoke("following", "elonmusk", "--max", "3") + assert result.exit_code == 0, f"following failed: {result.output}" + assert payload["ok"] is True + assert len(payload["data"]) >= 1 diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 97afda9..38e98c6 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -43,7 +43,6 @@ TwitterAPIError, ) from .graphql import ( - FALLBACK_QUERY_IDS, FEATURES, _build_graphql_url, _invalidate_query_id, @@ -93,8 +92,8 @@ def _best_chrome_target(): logger.debug("curl_cffi.BrowserType not available, using fallback targets") available = set() - # Preference order: exact chrome versions, then suffixed variants - for target in ("chrome133", "chrome133a", "chrome136", "chrome131", "chrome130"): + # Preference order: modern Chrome versions first, then older fallbacks + for target in ("chrome136", "chrome133a", "chrome133", "chrome131", "chrome130"): if target in available: return target # Fallback: pick highest chrome* with a pure numeric suffix @@ -133,6 +132,25 @@ def _url_fetch(url, headers=None): return resp.text +def _is_stale_query_error(exc): + # type: (TwitterAPIError) -> bool + """Return whether an API error indicates a stale persisted query ID.""" + if exc.status_code in (404, 422): + return True + if exc.status_code != 0: + return False + message = exc.message.lower() + return any( + marker in message + for marker in ( + "query: unspecified", + "persistedquerynotfound", + "persisted query not found", + "query not found", + ) + ) + + # ── TwitterClient ──────────────────────────────────────────────────────── @@ -901,28 +919,27 @@ def _fetch_user_list(self, operation_name, user_id, count, get_instructions, use def _graphql_get(self, operation_name, variables, features, field_toggles=None): # type: (str, Dict[str, Any], Dict[str, Any], Optional[Dict[str, Any]]) -> Dict[str, Any] - """Issue GraphQL GET request with automatic stale-fallback retry.""" + """Issue GraphQL GET request with automatic stale-queryId retry.""" query_id = _resolve_query_id(operation_name, prefer_fallback=True, url_fetch_fn=_url_fetch) - using_fallback = query_id == FALLBACK_QUERY_IDS.get(operation_name) url = _build_graphql_url(query_id, operation_name, variables, features, field_toggles) try: return self._api_get(url) except TwitterAPIError as exc: - # Fallback query IDs can go stale. Retry with live lookup if 404/422. - if exc.status_code in (404, 422) and using_fallback: - logger.info("Retrying %s with live queryId after %d", operation_name, exc.status_code) + # Stale queryIds surface as HTTP 404/422 or GraphQL "Query: Unspecified". + if _is_stale_query_error(exc): + logger.info("Retrying %s with live queryId after stale-query response", operation_name) _invalidate_query_id(operation_name) refreshed_query_id = _resolve_query_id(operation_name, prefer_fallback=False, url_fetch_fn=_url_fetch) - retry_url = _build_graphql_url(refreshed_query_id, operation_name, variables, features, field_toggles) - return self._api_get(retry_url) + if refreshed_query_id != query_id: + retry_url = _build_graphql_url(refreshed_query_id, operation_name, variables, features, field_toggles) + return self._api_get(retry_url) raise def _graphql_post(self, operation_name, variables, features=None): # type: (str, Dict[str, Any], Optional[Dict[str, Any]]) -> Dict[str, Any] - """Issue GraphQL POST request with automatic stale-fallback retry.""" + """Issue GraphQL POST request with automatic stale-queryId retry.""" query_id = _resolve_query_id(operation_name, prefer_fallback=True, url_fetch_fn=_url_fetch) - using_fallback = query_id == FALLBACK_QUERY_IDS.get(operation_name) def _do_post(qid): # type: (str) -> Dict[str, Any] @@ -935,11 +952,12 @@ def _do_post(qid): try: return _do_post(query_id) except TwitterAPIError as exc: - if exc.status_code in (404, 422) and using_fallback: - logger.info("Retrying POST %s with live queryId after %d", operation_name, exc.status_code) + if _is_stale_query_error(exc): + logger.info("Retrying POST %s with live queryId after stale-query response", operation_name) _invalidate_query_id(operation_name) refreshed = _resolve_query_id(operation_name, prefer_fallback=False, url_fetch_fn=_url_fetch) - return _do_post(refreshed) + if refreshed != query_id: + return _do_post(refreshed) raise # ── Internal: HTTP request engine ──────────────────────────────── @@ -1086,12 +1104,28 @@ def _save_ct_cache(self, home_html, ondemand_text): except Exception as exc: logger.debug("Failed to save CT cache: %s", exc) + def _ct_bootstrap_cookie(self): + # type: () -> Optional[str] + """Return session cookie header for authenticated bootstrap, if available.""" + cookie_string = getattr(self, "_cookie_string", None) + if cookie_string: + return cookie_string + auth_token = getattr(self, "_auth_token", "") + ct0 = getattr(self, "_ct0", "") + if auth_token and ct0: + return "auth_token=%s; ct0=%s" % (auth_token, ct0) + return None + def _ensure_client_transaction(self): # type: () -> None """Initialize ClientTransaction for x-client-transaction-id header. - Tries cache first (1h TTL), then fetches fresh data from x.com. - Also attempts to extract live feature flags from JS bundles. + Tries cache first (1h TTL), then fetches fresh responsive-web bootstrap + HTML from x.com. Since X migrated anonymous `/` and `/home` to the + stripped Vite `x-web` shell without `ondemand.s`, we try authenticated + `https://x.com/home` first and fall back to unauthenticated + `https://x.com/i/jf/` (which serves the responsive-web shell). + Also updates live feature flags from the fetched HTML. """ if self._ct_init_attempted: return @@ -1101,21 +1135,49 @@ def _ensure_client_transaction(self): if self._load_ct_cache(): return + last_exc: Optional[Exception] = None try: # Use curl_cffi for ClientTransaction init to maintain consistent # Chrome TLS fingerprint. Using Python requests here would leak # a different TLS fingerprint on the same IP — a detection vector. cffi_session = _get_cffi_session() - ct_headers = _gen_ct_headers() - home_page = cffi_session.get( - "https://x.com", headers=ct_headers, timeout=10, - ) - home_page_response = bs4.BeautifulSoup(home_page.content, "html.parser") - ondemand_url = get_ondemand_file_url(response=home_page_response) - if not ondemand_url: - raise ValueError("Failed to extract ondemand file URL from homepage") + base_headers = dict(_gen_ct_headers()) + cookie_header = self._ct_bootstrap_cookie() + + candidates = [] + if cookie_header: + auth_headers = dict(base_headers) + auth_headers["Cookie"] = cookie_header + candidates.append(("https://x.com/home", auth_headers)) + candidates.append(("https://x.com/i/jf/", dict(base_headers))) + + home_page = None + home_page_response = None + ondemand_url = None + + for bootstrap_url, req_headers in candidates: + try: + resp = cffi_session.get(bootstrap_url, headers=req_headers, timeout=10) + soup = bs4.BeautifulSoup(resp.content, "html.parser") + url = get_ondemand_file_url(response=soup) + if url: + home_page = resp + home_page_response = soup + ondemand_url = url + logger.debug("Bootstrapped ClientTransaction from %s", bootstrap_url) + break + last_exc = ValueError("No ondemand.s URL found at %s" % bootstrap_url) + except Exception as exc: + last_exc = exc + logger.debug("ClientTransaction bootstrap candidate %s failed: %s", bootstrap_url, exc) + continue + + if not ondemand_url or home_page is None or home_page_response is None: + raise last_exc or ValueError("Failed to extract ondemand file URL from x.com") + + # Fetch ondemand JS bundle without session cookies (CDN asset). ondemand_file = cffi_session.get( - ondemand_url, headers=ct_headers, timeout=10, + ondemand_url, headers=base_headers, timeout=10, ) self._client_transaction = ClientTransaction( home_page_response=home_page_response, @@ -1123,13 +1185,19 @@ def _ensure_client_transaction(self): ) logger.info("ClientTransaction initialized for x-client-transaction-id") - # Try to extract live FEATURES from the homepage JS bundles + # Try to extract live FEATURES from the bootstrap HTML _update_features_from_html(home_page.text) # Save to cache for future use self._save_ct_cache(home_page.text, ondemand_file.text) except Exception as exc: - logger.warning("Failed to init ClientTransaction: %s", exc) + logger.warning( + "Failed to init ClientTransaction: %s — x-client-transaction-id is " + "UNAVAILABLE. Write requests will be REFUSED (unsigned POSTs risk " + "account flags/suspension). Run `twitter doctor` to diagnose, or set " + "TWITTER_ALLOW_UNSIGNED=1 to override at your own risk.", + exc, + ) def _build_headers(self, url="", method="GET"): # type: (str, str) -> Dict[str, str] @@ -1163,14 +1231,30 @@ def _build_headers(self, url="", method="GET"): headers["Content-Type"] = "application/json" headers["Referer"] = "https://x.com/compose/post" headers["Priority"] = "u=1, i" - # Generate x-client-transaction-id if available + # Generate x-client-transaction-id. X gates writes and POST queries on + # this header; an unsigned POST is treated as automation and can trigger + # 344 errors or account suspension. Fail CLOSED by default. + tid = None if self._client_transaction and url: try: path = urllib.parse.urlparse(url).path tid = self._client_transaction.generate_transaction_id( method=method, path=path, ) - headers["X-Client-Transaction-Id"] = tid except Exception as exc: logger.debug("Failed to generate transaction id: %s", exc) + if tid: + headers["X-Client-Transaction-Id"] = tid + elif method == "POST": + msg = ( + "REFUSING unsigned write: x-client-transaction-id is not available " + "(ClientTransaction failed to init). X treats unsigned POST requests as " + "automation and can flag or suspend the account. Fix the ClientTransaction " + "bootstrap, or set TWITTER_ALLOW_UNSIGNED=1 to override at your own risk." + ) + if os.environ.get("TWITTER_ALLOW_UNSIGNED") == "1": + logger.warning("%s [overridden by TWITTER_ALLOW_UNSIGNED=1]", msg) + else: + logger.error("%s", msg) + raise TwitterAPIError(0, msg) return headers diff --git a/twitter_cli/graphql.py b/twitter_cli/graphql.py index d34ea35..68f7c15 100644 --- a/twitter_cli/graphql.py +++ b/twitter_cli/graphql.py @@ -1,20 +1,25 @@ """GraphQL infrastructure for Twitter API. -Handles queryId resolution, URL building, JS bundle scanning, -and feature flag management. +Handles queryId resolution (env overrides, disk cache, community OpenAPI, +JS bundle scanning, and fallback constants), URL building, and feature flag +management. """ from __future__ import annotations import json import logging +import os import re +import time import urllib.parse +from pathlib import Path from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Any, Dict, Optional # noqa: F401 +from .cache import _open_owner_only, _tighten_dir from .exceptions import QueryIdError logger = logging.getLogger(__name__) @@ -26,27 +31,30 @@ ) # ── Fallback (hardcoded) queryIds ──────────────────────────────────────── +# Refreshed against twitter-openapi placeholder.json on 2026-11-27. +# Override any single operation at runtime via TWITTER_QID_. FALLBACK_QUERY_IDS = { - "HomeTimeline": "c-CzHF1LboFilMpsx4ZCrQ", - "HomeLatestTimeline": "BKB7oi212Fi7kQtCBGE4zA", - "UserByScreenName": "1VOOyvKkiI3FMmkeDNxM9A", - "UserTweets": "q6xj5bs0hapm9309hexA_g", - "TweetDetail": "xd_EMdYvB9hfZsZ6Idri0w", - "Likes": "lIDpu_NWL7_VhimGGt0o6A", - "SearchTimeline": "VhUd6vHVmLBcw0uX-6jMLA", - "Bookmarks": "2neUNDqrrFzbLui8yallcQ", - "ListLatestTweetsTimeline": "RlZzktZY_9wJynoepm8ZsA", - "Followers": "IOh4aS6UdGWGJUYTqliQ7Q", - "Following": "zx6e-TLzRkeDO_a7p4b3JQ", - "CreateTweet": "IID9x6WsdMnTlXnzXGq8ng", - "DeleteTweet": "VaenaVgh5q5ih7kvyVjgtg", + "HomeTimeline": "KmJCeZ__ef1fNos7tKN_fg", + "HomeLatestTimeline": "IVA5BUbeYPTrpYekQH7jiA", + "UserByScreenName": "AMIBMjtxEEATh4z8V9GtRg", + "UserByRestId": "mxaYWwt52eAb6OAzYHMVzg", + "UserTweets": "7_KBXBpG0zBPRN6UCIV0-w", + "TweetDetail": "dQDdKtt882nl-Km98FJGSQ", + "Likes": "ZjyvI1V9gajq5eclHCObzA", + "SearchTimeline": "vLHjqbDv7TPFMBkIIO1nOA", + "Bookmarks": "fjf5b5Lu82lYMSBRhppK2g", + "ListLatestTweetsTimeline": "UMc_lPEeKz_WiKSY8ZT7yw", + "Followers": "Xe3y9_ndZ9-RtWz8zd_wpg", + "Following": "eDqlbOS46zda8jDT8dEQ_Q", + "CreateTweet": "wR5Z_lEibLvkew3tF9w-Sg", + "DeleteTweet": "nxpZCY2K-I6QoFHAHeojFQ", "FavoriteTweet": "lI07N6Otwv1PhnEgXILM7A", "UnfavoriteTweet": "ZYKSe-w7KEslx3JhSIk5LA", - "CreateRetweet": "ojPdsZsimiJrUGLR1sjUtA", - "DeleteRetweet": "iQtK4dl5hBmXewYZuEOKVw", + "CreateRetweet": "mbRO74GrOvSfRcJnlMapnQ", + "DeleteRetweet": "ZyZigVsNiFO6v1dEks1eWg", "CreateBookmark": "aoDbu3RHznuiSkQ9aNM67Q", "DeleteBookmark": "Wlmlj2-xzyS1GN3a6cj-mQ", - "TweetResultByRestId": "7xflPyRiUxGVbJd4uWmbfg", + "TweetResultByRestId": "U8lc5aomF5krJzZ9vJ9wxg", "BookmarkFoldersSlice": "i78YDd0Tza-dV4SYs58kRg", "BookmarkFolderTimeline": "hNY7X2xE2N7HVF6Qb_mu6w", } @@ -80,8 +88,85 @@ # Module-level caches (not thread-safe — CLI is single-threaded) _cached_query_ids: Dict[str, str] = {} +_disk_cache_loaded = False _bundles_scanned = False +_QID_CACHE_TTL = 86400 # 24 hours +_MAX_SCAN_CHUNKS = 100 + + +def _qid_cache_path() -> Path: + """Return path for the persistent queryId cache file.""" + return Path.home() / ".twitter-cli" / "query_ids_cache.json" + + +def _load_disk_query_ids() -> Dict[str, str]: + """Load non-expired queryIds from disk cache.""" + global _disk_cache_loaded + if _disk_cache_loaded: + return {} + _disk_cache_loaded = True + try: + path = _qid_cache_path() + if not path.exists(): + return {} + payload = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(payload, dict): + return {} + if time.time() - float(payload.get("created_at", 0)) > _QID_CACHE_TTL: + return {} + qids = payload.get("query_ids", {}) + if isinstance(qids, dict): + return {str(k): str(v) for k, v in qids.items() if k and v} + except Exception as exc: + logger.debug("Failed to load queryId disk cache: %s", exc) + return {} + + +def _save_disk_query_ids(query_ids: Dict[str, str]) -> None: + """Persist live-resolved queryIds to disk with owner-only permissions.""" + if not query_ids: + return + try: + path = _qid_cache_path() + path.parent.mkdir(parents=True, exist_ok=True) + _tighten_dir(path.parent) + existing: Dict[str, str] = {} + if path.exists(): + try: + old = json.loads(path.read_text(encoding="utf-8")) + if ( + isinstance(old, dict) + and time.time() - float(old.get("created_at", 0)) <= _QID_CACHE_TTL + and isinstance(old.get("query_ids"), dict) + ): + existing = {str(k): str(v) for k, v in old["query_ids"].items() if k and v} + except Exception: + pass + existing.update(query_ids) + payload = {"created_at": time.time(), "query_ids": existing} + with _open_owner_only(path) as f: + json.dump(payload, f, indent=2) + except Exception as exc: + logger.debug("Failed to save queryId disk cache: %s", exc) + + +def _remove_disk_query_id(operation_name: str) -> None: + """Remove a stale queryId from the disk cache if present.""" + try: + path = _qid_cache_path() + if not path.exists(): + return + payload = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(payload, dict) or not isinstance(payload.get("query_ids"), dict): + return + if operation_name in payload["query_ids"]: + payload["query_ids"].pop(operation_name, None) + with _open_owner_only(path) as f: + json.dump(payload, f, indent=2) + except Exception as exc: + logger.debug("Failed to update queryId disk cache: %s", exc) + def _build_graphql_url(query_id, operation_name, variables, features, field_toggles=None): # type: (str, str, Dict[str, Any], Dict[str, Any], Optional[Dict[str, Any]]) -> str @@ -90,7 +175,6 @@ def _build_graphql_url(query_id, operation_name, variables, features, field_togg Only includes True-valued feature flags in the URL to avoid 414 URI Too Long. Twitter's API defaults missing features to False. """ - # Compact features: omit False values to keep URL under server limits compact_features = {k: v for k, v in features.items() if v is not False} url = "https://x.com/i/api/graphql/%s/%s?variables=%s&features=%s" % ( query_id, @@ -109,6 +193,9 @@ def _scan_bundles(url_fetch_fn): # type: (Any) -> None """Scan Twitter JS bundles and cache queryId mappings. + Supports both legacy ``responsive-web/client-web`` bundles (via ``/i/jf/``) + and newer ``x-web/x-web`` Vite bundles (following relative asset chunks). + Args: url_fetch_fn: Function to fetch URLs (injected to avoid circular import). """ @@ -117,34 +204,69 @@ def _scan_bundles(url_fetch_fn): return _bundles_scanned = True + script_pattern = re.compile( + r'(?:src|href)=["\']' + r'(https://abs\.twimg\.com/(?:responsive-web/client-web|x-web/x-web)[^"\']+' + r'\.js)' + r'["\']' + ) + script_urls = [] try: from .constants import get_user_agent - html = url_fetch_fn("https://x.com", {"user-agent": get_user_agent()}) - script_pattern = re.compile( - r'(?:src|href)=["\']' - r'(https://abs\.twimg\.com/responsive-web/client-web[^"\']+' - r'\.js)' - r'["\']' - ) - script_urls = script_pattern.findall(html) + + headers = {"user-agent": get_user_agent()} + for page_url in ("https://x.com/i/jf/", "https://x.com"): + try: + html = url_fetch_fn(page_url, headers) + found_urls = script_pattern.findall(html) + if found_urls: + script_urls = found_urls + break + except Exception as exc: # pragma: no cover - network-dependent branch + logger.debug("Bundle page fetch failed for %s: %s", page_url, exc) + continue except Exception as exc: # pragma: no cover - network-dependent branch logger.warning("Failed to scan JS bundles: %s", exc) return - for script_url in script_urls: + if not script_urls: + return + + discovered: Dict[str, str] = {} + op_pattern = re.compile( + r'queryId:\s*"([A-Za-z0-9_-]+)"[^}]{0,200}' + r'operationName:\s*"([^"]+)"' + ) + chunk_ref_pattern = re.compile(r'["\'](?:\./)?assets/([A-Za-z0-9._\-]+\.js)["\']') + + seen_urls = set() + queue = list(script_urls) + scanned = 0 + while queue and scanned < _MAX_SCAN_CHUNKS: + script_url = queue.pop(0) + if script_url in seen_urls: + continue + seen_urls.add(script_url) + scanned += 1 try: bundle = url_fetch_fn(script_url) - op_pattern = re.compile( - r'queryId:\s*"([A-Za-z0-9_-]+)"[^}]{0,200}' - r'operationName:\s*"([^"]+)"' - ) for match in op_pattern.finditer(bundle): query_id, operation_name = match.group(1), match.group(2) _cached_query_ids.setdefault(operation_name, query_id) + discovered.setdefault(operation_name, query_id) + + if "/x-web/x-web/" in script_url: + base = script_url.rsplit("/", 1)[0] + "/" + for rel in chunk_ref_pattern.findall(bundle): + chunk_url = base + "assets/" + rel + if chunk_url not in seen_urls: + queue.append(chunk_url) except Exception: continue - logger.info("Scanned %d JS bundles, cached %d query IDs", len(script_urls), len(_cached_query_ids)) + if discovered: + _save_disk_query_ids(discovered) + logger.info("Scanned %d JS bundles, cached %d query IDs", scanned, len(_cached_query_ids)) def _update_features_from_html(html): @@ -164,8 +286,6 @@ def _update_features_from_html(html): for match in feature_pattern.finditer(html): key = match.group(1) value = match.group(2).lower() == "true" - # Only update keys already in FEATURES — never add new ones - # Adding new keys inflates URL length, causing 414/431 errors if key in FEATURES and FEATURES[key] != value: logger.debug("Feature flag updated: %s = %s -> %s", key, FEATURES[key], value) FEATURES[key] = value @@ -193,26 +313,68 @@ def _fetch_from_github(url_fetch_fn, operation_name): def _invalidate_query_id(operation_name): # type: (str) -> None - """Remove a cached queryId for an operation.""" + """Remove a cached queryId for an operation (memory and disk).""" _cached_query_ids.pop(operation_name, None) + _remove_disk_query_id(operation_name) + + +def refresh_query_ids(url_fetch_fn): + # type: (Any) -> Dict[str, str] + """Force a live refresh of queryIds from twitter-openapi and x.com bundles.""" + global _bundles_scanned + _cached_query_ids.clear() + _bundles_scanned = False + refreshed: Dict[str, str] = {} + + try: + payload = url_fetch_fn(TWITTER_OPENAPI_URL) + parsed = json.loads(payload) + if isinstance(parsed, dict): + for op_name, op_data in parsed.items(): + if isinstance(op_data, dict): + qid = op_data.get("queryId") + if isinstance(qid, str) and qid: + refreshed[op_name] = qid + except Exception as exc: + logger.debug("GitHub bulk queryId refresh failed: %s", exc) + + _scan_bundles(url_fetch_fn) + refreshed.update(_cached_query_ids) + _cached_query_ids.update(refreshed) + if refreshed: + _save_disk_query_ids(refreshed) + return dict(refreshed) def _resolve_query_id(operation_name, prefer_fallback=True, url_fetch_fn=None): # type: (str, bool, Any) -> str - """Resolve queryId using cache, remote sources, and fallback constants.""" + """Resolve queryId using env override, caches, remote sources, and fallbacks.""" + # 1. Explicit per-operation environment override: TWITTER_QID_ + env_override = os.environ.get("TWITTER_QID_%s" % operation_name, "").strip() + if env_override: + return env_override + + # 2. In-memory cache (populated from disk cache or prior lookups) + if not _disk_cache_loaded: + for op_name, qid in _load_disk_query_ids().items(): + _cached_query_ids.setdefault(op_name, qid) + cached = _cached_query_ids.get(operation_name) if cached: return cached + # 3. Fallback constants (when prefer_fallback=True) fallback = FALLBACK_QUERY_IDS.get(operation_name) if prefer_fallback and fallback: _cached_query_ids[operation_name] = fallback return fallback + # 4. Live resolution: community twitter-openapi -> x.com JS bundle scan if url_fetch_fn: github_query_id = _fetch_from_github(url_fetch_fn, operation_name) if github_query_id: _cached_query_ids[operation_name] = github_query_id + _save_disk_query_ids({operation_name: github_query_id}) return github_query_id _scan_bundles(url_fetch_fn) @@ -220,6 +382,7 @@ def _resolve_query_id(operation_name, prefer_fallback=True, url_fetch_fn=None): if cached: return cached + # 5. Last-resort fallback if fallback: _cached_query_ids[operation_name] = fallback return fallback From d1125c6efbfff1aa40cb1db4432c8d10bb94955a Mon Sep 17 00:00:00 2001 From: jackwener Date: Fri, 27 Nov 2026 18:16:54 +0000 Subject: [PATCH 3/8] feat(auth): support custom Chromium dirs, Vivaldi, Zen, TWITTER_COOKIE_STRING, and better diagnostics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Support TWITTER_CHROMIUM_USER_DATA_DIR for ungoogled-chromium and custom Chromium profiles (discovers both Cookies and Network/Cookies, passes matching Local State key file, closes #61) - Add Vivaldi and Zen browser cookie extraction (in-process + subprocess, with profiles.ini priority and Linux Flatpak/XDG discovery for Zen) - Support TWITTER_COOKIE_STRING env var so headless/SigCLI/Windows users can supply a full cookie header without losing write/226 protection (#58) - Improve Windows Chrome/Edge >=127 App-Bound Encryption diagnostics with actionable workarounds (addresses #28, #46, #66) Absorbs #76, #92, #95, auth diagnostics from #104, and full-cookie env support inspired by #58 and quangdang46/twitter_cli. Co-authored-by: Lucius Co-authored-by: RiriAgent Co-authored-by: Aditya Gupta Co-authored-by: axsddlr Co-authored-by: Trần Quang Đãng <91641923+quangdang46@users.noreply.github.com> --- tests/test_auth.py | 180 ++++++++++++++++- twitter_cli/auth.py | 480 +++++++++++++++++++++++++++++++++----------- 2 files changed, 544 insertions(+), 116 deletions(-) diff --git a/tests/test_auth.py b/tests/test_auth.py index 341a7f4..9349e87 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -142,7 +142,9 @@ def _run(cmd, capture_output=True, text=True, timeout=15): cookies, diagnostics = auth._extract_via_subprocess() assert cookies is None - assert '"arc": browser_cookie3.arc' in seen["script"] + assert 'DEFAULT_ORDER = ["arc", "chrome", "edge", "firefox", "brave", "vivaldi", "zen"]' in seen["script"] + assert 'CUSTOM_CHROMIUM_BROWSER = "custom-chromium"' in seen["script"] + assert "browser_cookie3.chromium(" in seen["script"] def test_extract_via_subprocess_retries_uv_when_current_env_has_no_output(monkeypatch) -> None: @@ -410,3 +412,179 @@ class BrowserError(Exception): assert cookies is None assert any("cookie decryption" in d for d in diagnostics) + + +def test_load_from_env_supports_full_cookie_string(monkeypatch) -> None: + monkeypatch.delenv("TWITTER_AUTH_TOKEN", raising=False) + monkeypatch.delenv("TWITTER_CT0", raising=False) + monkeypatch.setenv("TWITTER_COOKIE_STRING", "guest_id=v1; auth_token=tok123; ct0=csrf456; kdt=abc") + + cookies = auth.load_from_env() + + assert cookies == { + "auth_token": "tok123", + "ct0": "csrf456", + "cookie_string": "guest_id=v1; auth_token=tok123; ct0=csrf456; kdt=abc", + } + + +def test_get_browser_order_prepends_custom_chromium_dir(monkeypatch, tmp_path) -> None: + monkeypatch.delenv("TWITTER_BROWSER", raising=False) + monkeypatch.setenv("TWITTER_CHROMIUM_USER_DATA_DIR", str(tmp_path)) + + order = auth._get_browser_order() + + assert order[0] == "custom-chromium" + assert "chrome" in order + + +def test_iter_chrome_cookie_files_supports_custom_user_data_dir(monkeypatch, tmp_path) -> None: + root = tmp_path / "Ungoogled Chromium" + network_dir = root / "Profile 1" / "Network" + network_dir.mkdir(parents=True) + cookie_file = network_dir / "Cookies" + cookie_file.touch() + local_state = root / "Local State" + local_state.touch() + + monkeypatch.setenv("TWITTER_CHROMIUM_USER_DATA_DIR", str(root)) + monkeypatch.delenv("TWITTER_CHROME_PROFILE", raising=False) + + paths = auth._iter_chrome_cookie_files("custom-chromium") + + assert paths == [str(cookie_file)] + assert auth._profile_name_from_cookie_file(str(cookie_file)) == "Profile 1" + assert auth._chromium_key_file_for_cookie(str(cookie_file)) == str(local_state) + + +def test_extract_in_process_uses_chromium_loader_for_custom_dir(monkeypatch, tmp_path) -> None: + class Cookie: + def __init__(self, domain: str, name: str, value: str) -> None: + self.domain = domain + self.name = name + self.value = value + + root = tmp_path / "User Data" + profile_dir = root / "Default" / "Network" + profile_dir.mkdir(parents=True) + cookie_file = profile_dir / "Cookies" + cookie_file.touch() + local_state = root / "Local State" + local_state.touch() + seen = {} + + def chromium(cookie_file=None, key_file=None): + seen["cookie_file"] = cookie_file + seen["key_file"] = key_file + return [ + Cookie(".x.com", "auth_token", "custom-token"), + Cookie(".x.com", "ct0", "custom-csrf"), + ] + + monkeypatch.setenv("TWITTER_CHROMIUM_USER_DATA_DIR", str(root)) + monkeypatch.setattr(auth, "_get_browser_order", lambda: ["custom-chromium"]) + monkeypatch.setitem(sys.modules, "browser_cookie3", SimpleNamespace(chromium=chromium)) + + cookies, diagnostics = auth._extract_in_process() + + assert diagnostics == [] + assert cookies is not None + assert cookies["auth_token"] == "custom-token" + assert seen == {"cookie_file": str(cookie_file), "key_file": str(local_state)} + + +def test_vivaldi_browser_order_and_paths(monkeypatch, tmp_path) -> None: + monkeypatch.setenv("TWITTER_BROWSER", "vivaldi") + order = auth._get_browser_order() + assert order[0] == "vivaldi" + assert "vivaldi" in order + + monkeypatch.setattr(auth.sys, "platform", "linux") + vivaldi_dir = tmp_path / ".config" / "vivaldi" + (vivaldi_dir / "Default").mkdir(parents=True) + (vivaldi_dir / "Default" / "Cookies").touch() + _patch_home(monkeypatch, tmp_path) + monkeypatch.delenv("TWITTER_CHROME_PROFILE", raising=False) + + paths = auth._iter_chrome_cookie_files("vivaldi") + assert paths == [os.path.join(str(tmp_path), ".config", "vivaldi", "Default", "Cookies")] + + +@pytest.mark.parametrize( + "platform,relative", + [ + ("linux", ".zen/test/cookies.sqlite"), + ("linux", ".var/app/app.zen_browser.zen/zen/test/cookies.sqlite"), + ("linux", ".var/app/app.zen_browser.zen/.zen/test/cookies.sqlite"), + ("darwin", "Library/Application Support/zen/Profiles/test/cookies.sqlite"), + ("win32", "zen/Profiles/test/cookies.sqlite"), + ], +) +def test_zen_profile_discovery(monkeypatch, tmp_path, platform, relative) -> None: + monkeypatch.setattr(auth.sys, "platform", platform) + monkeypatch.setattr(auth.os.path, "expanduser", lambda _: str(tmp_path)) + monkeypatch.setenv("APPDATA", str(tmp_path)) + cookie_file = tmp_path / relative + cookie_file.parent.mkdir(parents=True) + cookie_file.touch() + assert auth._iter_zen_cookie_files() == [str(cookie_file)] + + +@pytest.mark.parametrize("subprocess_mode", [False, True]) +def test_zen_extracts_from_later_profile(monkeypatch, subprocess_mode) -> None: + monkeypatch.setenv("TWITTER_BROWSER", " ZEN ") + monkeypatch.setattr(auth, "_iter_zen_cookie_files", lambda: ["empty", "broken", "valid"]) + calls = [] + + def firefox(cookie_file=None): + calls.append(cookie_file) + if cookie_file == "broken": + raise RuntimeError("profile unreadable") + if cookie_file != "valid": + return [] + return [ + SimpleNamespace(domain=".x.com", name=name, value=value) + for name, value in [("auth_token", "token"), ("ct0", "csrf"), ("extra", "value")] + ] + + fake_module = SimpleNamespace(firefox=firefox) + for name in ("arc", "chrome", "edge", "brave", "vivaldi"): + setattr(fake_module, name, lambda: pytest.fail("Zen should succeed first")) + monkeypatch.setitem(sys.modules, "browser_cookie3", fake_module) + if subprocess_mode: + import contextlib + import io + + def run(cmd, **kwargs): + output = io.StringIO() + with contextlib.redirect_stdout(output), pytest.raises(SystemExit) as exited: + exec(cmd[-1], {}) + assert exited.value.code == 0 + return SimpleNamespace(stdout=output.getvalue(), stderr="") + + monkeypatch.setattr(auth.subprocess, "run", run) + cookies, _ = auth._extract_via_subprocess() + else: + cookies, _ = auth._extract_in_process() + assert calls == ["empty", "broken", "valid"] + assert cookies == { + "auth_token": "token", + "ct0": "csrf", + "cookie_string": "auth_token=token; ct0=csrf; extra=value", + } + + +def test_windows_app_bound_encryption_diagnostics(monkeypatch) -> None: + monkeypatch.setattr(auth.sys, "platform", "win32") + for var in ("SSH_CLIENT", "SSH_TTY", "SSH_CONNECTION"): + monkeypatch.delenv(var, raising=False) + + hint = auth._diagnose_keychain_issues( + ["chrome in-process extraction failed: Unable to get key for cookie decryption"] + ) + assert hint is not None + assert "App-Bound Encryption" in hint + assert "not a permissions issue" in hint + assert "TWITTER_BROWSER=firefox" in hint + assert "TWITTER_COOKIE_STRING" in hint + assert "VSS shadowcopy" in hint diff --git a/twitter_cli/auth.py b/twitter_cli/auth.py index 81dd44c..b6e4f9e 100644 --- a/twitter_cli/auth.py +++ b/twitter_cli/auth.py @@ -1,8 +1,11 @@ """Cookie authentication for Twitter/X. Supports: -1. Environment variables: TWITTER_AUTH_TOKEN + TWITTER_CT0 +1. Environment variables: TWITTER_COOKIE_STRING (full cookie header) or + TWITTER_AUTH_TOKEN + TWITTER_CT0 2. Auto-extract from browser via browser-cookie3 + (Arc, Chrome, Edge, Firefox, Brave, Vivaldi, Zen, plus custom Chromium dirs + via TWITTER_CHROMIUM_USER_DATA_DIR) Extracts ALL Twitter cookies for full browser-like fingerprint. Prefers in-process extraction (required on macOS for Keychain access), falls back to subprocess if in-process fails (e.g. SQLite lock). @@ -10,6 +13,7 @@ from __future__ import annotations +import configparser import glob import json import logging @@ -44,7 +48,7 @@ def _is_twitter_domain(domain: str) -> bool: def _diagnose_keychain_issues(diagnostics: List[str]) -> Optional[str]: - """Analyse extraction diagnostics for Keychain permission issues. + """Analyse extraction diagnostics for Keychain / DPAPI permission issues. Returns a user-friendly hint string, or None. """ @@ -67,13 +71,31 @@ def _diagnose_keychain_issues(diagnostics: List[str]) -> Optional[str]: " Or click \"Always Allow\" when the Keychain authorization popup appears." ) if sys.platform == "win32": + if "decrypt" in lowered and "key" in lowered: + return ( + "Windows: Chrome/Edge cookie decryption failed (DPAPI/App-Bound Encryption).\n" + " This is usually App-Bound Encryption (Chrome/Edge 127+), which\n" + " browser_cookie3 cannot decrypt. It is not a permissions issue, so\n" + " running as admin will not help.\n" + " If this is not App-Bound Encryption: close Chrome (it locks the\n" + " cookie database), or run as admin to allow a VSS shadowcopy.\n" + " Options:\n" + " 1. Use Firefox or Zen for x.com — Gecko cookies are still readable:\n" + " set TWITTER_BROWSER=firefox\n" + " 2. Export cookies manually and pass them as env vars:\n" + " set TWITTER_COOKIE_STRING=\n" + " Or minimal tokens (reads work; writes prefer full cookie string):\n" + " set TWITTER_AUTH_TOKEN=\n" + " set TWITTER_CT0=\n" + " In DevTools: Application -> Cookies -> https://x.com" + ) return ( "Windows DPAPI cookie decryption failed.\n" " Possible causes:\n" " 1. Chrome is running (locks the cookie database). Try closing Chrome first.\n" " 2. browser_cookie3 may not support the latest Chrome cookie encryption format.\n" " 3. If Chrome was running, admin privileges may be required for VSS shadowcopy.\n" - " Workaround: Set TWITTER_AUTH_TOKEN and TWITTER_CT0 environment variables manually." + " Workaround: Set TWITTER_COOKIE_STRING (or TWITTER_AUTH_TOKEN and TWITTER_CT0) manually." ) # Linux: gnome-keyring / SecretStorage issues return ( @@ -82,10 +104,50 @@ def _diagnose_keychain_issues(diagnostics: List[str]) -> Optional[str]: ) +def _parse_cookie_string(raw: str) -> Dict[str, str]: + """Parse a raw HTTP Cookie header into a dict of cookie name -> value.""" + parsed: Dict[str, str] = {} + for part in raw.split(";"): + item = part.strip() + if not item or "=" not in item: + continue + name, value = item.split("=", 1) + name = name.strip() + value = value.strip() + if name and value: + parsed[name] = value + return parsed + + def load_from_env() -> Optional[Dict[str, str]]: - """Load cookies from environment variables.""" - auth_token = os.environ.get("TWITTER_AUTH_TOKEN", "") - ct0 = os.environ.get("TWITTER_CT0", "") + """Load cookies from environment variables. + + Supports either: + - ``TWITTER_COOKIE_STRING`` (full Cookie header — preserves all cookies for + write/anti-detection compatibility; works with SigCLI and headless setups) + - ``TWITTER_AUTH_TOKEN`` + ``TWITTER_CT0`` + """ + raw_cookie_string = os.environ.get("TWITTER_COOKIE_STRING", "").strip() + auth_token = os.environ.get("TWITTER_AUTH_TOKEN", "").strip() + ct0 = os.environ.get("TWITTER_CT0", "").strip() + + if raw_cookie_string: + parsed = _parse_cookie_string(raw_cookie_string) + resolved_auth = auth_token or parsed.get("auth_token", "") + resolved_ct0 = ct0 or parsed.get("ct0", "") + if resolved_auth and resolved_ct0: + return { + "auth_token": resolved_auth, + "ct0": resolved_ct0, + "cookie_string": raw_cookie_string, + } + logger.debug( + "TWITTER_COOKIE_STRING incomplete: auth_token=%s ct0=%s", + bool(resolved_auth), + bool(resolved_ct0), + ) + return None + if auth_token and ct0: return {"auth_token": auth_token, "ct0": ct0} if auth_token or ct0: @@ -111,7 +173,6 @@ def verify_cookies(auth_token: str, ct0: str, cookie_string: Optional[str] = Non "https://x.com/i/api/1.1/account/settings.json", ] - # Use full cookie string if available, otherwise minimal cookie_header = cookie_string or "auth_token=%s; ct0=%s" % (auth_token, ct0) headers = { @@ -123,7 +184,6 @@ def verify_cookies(auth_token: str, ct0: str, cookie_string: Optional[str] = Non "User-Agent": get_user_agent(), } - # Reuse the shared curl_cffi session for consistent TLS fingerprint session = _get_cffi_session() attempts = [] @@ -155,7 +215,6 @@ def verify_cookies(auth_token: str, ct0: str, cookie_string: Optional[str] = Non logger.debug("Verification endpoint %s failed: %s", url, e) continue - # All endpoints failed with non-auth errors — proceed without verification logger.info( "Cookie verification skipped (attempts: %s), will verify on first API call", ", ".join(attempts) if attempts else "none", @@ -195,88 +254,208 @@ def _extract_cookies_from_jar(jar: Any, source: str = "unknown") -> Optional[Dic # Base directories for Chromium-based browsers, keyed by browser name. -# Each entry maps to the directory under the platform-specific app data root. _CHROMIUM_BASE_DIRS: Dict[str, str] = { "chrome": os.path.join("Google", "Chrome"), "arc": os.path.join("Arc", "User Data"), "edge": "Microsoft Edge", "brave": os.path.join("BraveSoftware", "Brave-Browser"), + "vivaldi": "Vivaldi", } +_CUSTOM_CHROMIUM_BROWSER = "custom-chromium" + # Default browser order for cookie extraction -_DEFAULT_BROWSER_ORDER = ["arc", "chrome", "edge", "firefox", "brave"] +_DEFAULT_BROWSER_ORDER = ["arc", "chrome", "edge", "firefox", "brave", "vivaldi", "zen"] +_SUPPORTED_BROWSERS = set(_DEFAULT_BROWSER_ORDER) | {_CUSTOM_CHROMIUM_BROWSER} + + +def _custom_chromium_user_data_dir() -> Optional[str]: + """Return a custom Chromium user-data/profile directory, if configured.""" + root = os.environ.get("TWITTER_CHROMIUM_USER_DATA_DIR", "").strip() + if not root: + return None + return os.path.abspath(os.path.expanduser(root)) def _get_browser_order() -> List[str]: - """Return browser extraction order, respecting TWITTER_BROWSER env var.""" + """Return browser extraction order, respecting TWITTER_BROWSER and custom Chromium dir.""" + default_order = list(_DEFAULT_BROWSER_ORDER) + if _custom_chromium_user_data_dir(): + default_order.insert(0, _CUSTOM_CHROMIUM_BROWSER) + env = os.environ.get("TWITTER_BROWSER", "").strip().lower() if not env: - return _DEFAULT_BROWSER_ORDER - if env not in {"arc", "chrome", "edge", "firefox", "brave"}: + return default_order + if env not in _SUPPORTED_BROWSERS: logger.warning("TWITTER_BROWSER='%s' is invalid, using default order", env) - return _DEFAULT_BROWSER_ORDER - return [env] + [b for b in _DEFAULT_BROWSER_ORDER if b != env] + return default_order + return [env] + [b for b in default_order if b != env] + + +def _profile_cookie_paths(profile_dir: str) -> List[str]: + """Return existing Chromium cookie database paths for one profile.""" + paths = [] + for relative_path in ("Cookies", os.path.join("Network", "Cookies")): + cookie_path = os.path.join(profile_dir, relative_path) + if os.path.exists(cookie_path): + paths.append(cookie_path) + return paths + + +def _profile_name_from_cookie_file(cookie_file: str) -> str: + """Return the profile name for a Chromium or Zen cookie database path.""" + parent = os.path.basename(os.path.dirname(cookie_file)) + if parent == "Network": + return os.path.basename(os.path.dirname(os.path.dirname(cookie_file))) + return parent + + +def _chromium_key_file_for_cookie(cookie_file: str) -> Optional[str]: + """Return the Local State file associated with a Chromium cookie database.""" + candidates = [] + custom_root = _custom_chromium_user_data_dir() + if custom_root: + candidates.append(os.path.join(custom_root, "Local State")) + + profile_dir = os.path.dirname(cookie_file) + if os.path.basename(profile_dir) == "Network": + profile_dir = os.path.dirname(profile_dir) + candidates.append(os.path.join(os.path.dirname(profile_dir), "Local State")) + + for candidate in dict.fromkeys(candidates): + if os.path.exists(candidate): + return candidate + return None def _iter_chrome_cookie_files(browser_name: str) -> List[str]: - """Return cookie file paths for all Chrome profiles. + """Return cookie file paths for all Chromium profiles. If TWITTER_CHROME_PROFILE is set, only that profile is returned. Otherwise yields Default first, then Profile 1, Profile 2, ... sorted. """ - base_dir = _CHROMIUM_BASE_DIRS.get(browser_name) - if base_dir is None: - return [] - - if sys.platform == "darwin": - root = os.path.join(os.path.expanduser("~"), "Library", "Application Support", base_dir) - elif sys.platform == "win32": - if browser_name == "edge": - root = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Microsoft", "Edge", "User Data") - else: - root = os.path.join(os.environ.get("LOCALAPPDATA", ""), base_dir) + if browser_name == _CUSTOM_CHROMIUM_BROWSER: + root = _custom_chromium_user_data_dir() + if not root: + return [] else: - if browser_name == "edge": - root = os.path.join(os.path.expanduser("~"), ".config", "microsoft-edge") + base_dir = _CHROMIUM_BASE_DIRS.get(browser_name) + if base_dir is None: + return [] + + if sys.platform == "darwin": + root = os.path.join(os.path.expanduser("~"), "Library", "Application Support", base_dir) + elif sys.platform == "win32": + if browser_name == "edge": + root = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Microsoft", "Edge", "User Data") + elif browser_name == "vivaldi": + root = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Vivaldi", "User Data") + else: + root = os.path.join(os.environ.get("LOCALAPPDATA", ""), base_dir) else: - root = os.path.join(os.path.expanduser("~"), ".config", base_dir) + if browser_name == "edge": + root = os.path.join(os.path.expanduser("~"), ".config", "microsoft-edge") + elif browser_name == "vivaldi": + root = os.path.join(os.path.expanduser("~"), ".config", "vivaldi") + else: + root = os.path.join(os.path.expanduser("~"), ".config", base_dir) if not os.path.isdir(root): return [] - # If user explicitly specifies a profile, only use that one env_profile = os.environ.get("TWITTER_CHROME_PROFILE", "").strip() if env_profile: - cookie_path = os.path.join(root, env_profile, "Cookies") - if os.path.exists(cookie_path): - logger.debug("Using specified Chrome profile: %s", env_profile) - return [cookie_path] - logger.warning("TWITTER_CHROME_PROFILE='%s' not found at %s", env_profile, cookie_path) + profile_dir = env_profile if os.path.isabs(env_profile) else os.path.join(root, env_profile) + profile_paths = _profile_cookie_paths(profile_dir) + if profile_paths: + logger.debug("Using specified Chromium profile: %s", env_profile) + return profile_paths + logger.warning("TWITTER_CHROME_PROFILE='%s' not found under %s", env_profile, root) return [] - # Auto-discover: Default first, then Profile N sorted paths: List[str] = [] - default_cookies = os.path.join(root, "Default", "Cookies") - if os.path.exists(default_cookies): - paths.append(default_cookies) + seen = set() + + def append_profile(profile_dir: str) -> None: + for cookie_path in _profile_cookie_paths(profile_dir): + if cookie_path not in seen: + seen.add(cookie_path) + paths.append(cookie_path) - profile_dirs = sorted(glob.glob(os.path.join(root, "Profile *"))) - for profile_dir in profile_dirs: - cookie_file = os.path.join(profile_dir, "Cookies") - if os.path.exists(cookie_file): - paths.append(cookie_file) + # Configured path may be either a User Data root or a direct profile dir. + append_profile(root) + append_profile(os.path.join(root, "Default")) + for profile_dir in sorted(glob.glob(os.path.join(root, "Profile *"))): + append_profile(profile_dir) return paths -def _extract_in_process() -> Tuple[Optional[Dict[str, str]], List[str]]: - """Extract cookies in the main process (required on macOS for Keychain access). +def _iter_zen_cookie_files() -> List[str]: + """Discover Zen browser profiles across Linux (incl. Flatpak), macOS, and Windows.""" + home = os.path.expanduser("~") + if sys.platform == "darwin": + roots = [os.path.join(home, "Library", "Application Support", "zen")] + elif sys.platform == "win32": + appdata = os.environ.get("APPDATA") + roots = [os.path.join(appdata, "zen")] if appdata else [] + else: + roots = [ + os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config"), "zen"), + os.path.join(home, ".zen"), + os.path.join(home, ".var", "app", "app.zen_browser.zen", "zen"), + os.path.join(home, ".var", "app", "app.zen_browser.zen", ".zen"), + ] + paths: List[str] = [] + for root in roots: + config = configparser.ConfigParser(interpolation=None) + try: + config.read(os.path.join(root, "profiles.ini"), encoding="utf-8") + except (configparser.Error, OSError, UnicodeError) as exc: + logger.debug("Could not read Zen profiles.ini at %s: %s", root, exc) + config = configparser.ConfigParser(interpolation=None) + # Prefer the install default over the legacy Default=1 profile (like Firefox). + defaults = [ + config[section].get("Default", "") + for section in config.sections() + if section.startswith("Install") + ] + profiles = [ + config[section] + for section in config.sections() + if section.startswith("Profile") and config[section].get("Path") + ] + profiles.sort( + key=lambda profile: (profile["Path"] not in defaults, profile.get("Default") != "1") + ) + candidates = [] + for profile in profiles: + directory = profile["Path"] + if profile.get("IsRelative", "1") != "0": + directory = os.path.join(root, directory) + candidates.append(os.path.join(directory, "cookies.sqlite")) + for pattern in ("*/cookies.sqlite", "Profiles/*/cookies.sqlite"): + candidates.extend(sorted(glob.glob(os.path.join(root, pattern)))) + for path in candidates: + if os.path.isfile(path) and path not in paths: + paths.append(path) + return paths - On macOS, Chrome encrypts cookies using a key stored in the system Keychain. - Child processes do NOT inherit the parent's Keychain authorization, so - browser_cookie3 must run in the main process to decrypt cookies. - For Chromium-based browsers, iterates all profiles to find Twitter cookies. +def _get_browser_cookie_fn(browser_cookie3: Any, browser_name: str) -> Any: + """Return a browser-cookie3 loader for a configured browser.""" + if browser_name == _CUSTOM_CHROMIUM_BROWSER: + return lambda cookie_file=None: browser_cookie3.chromium( + cookie_file=cookie_file, + key_file=_chromium_key_file_for_cookie(cookie_file) if cookie_file else None, + ) + if browser_name == "zen": + return browser_cookie3.firefox + return getattr(browser_cookie3, browser_name) + + +def _extract_in_process() -> Tuple[Optional[Dict[str, str]], List[str]]: + """Extract cookies in the main process (required on macOS for Keychain access). Returns (cookies_dict | None, diagnostics_list). """ @@ -286,23 +465,29 @@ def _extract_in_process() -> Tuple[Optional[Dict[str, str]], List[str]]: logger.debug("browser_cookie3 not installed, skipping in-process extraction") return None, ["browser-cookie3 not installed"] - browser_fns = { - "arc": browser_cookie3.arc, - "chrome": browser_cookie3.chrome, - "edge": browser_cookie3.edge, - "firefox": browser_cookie3.firefox, - "brave": browser_cookie3.brave, - } attempts: List[str] = [] diagnostics: List[str] = [] for name in _get_browser_order(): - fn = browser_fns[name] - if name in _CHROMIUM_BASE_DIRS: - # Chromium-based: iterate all profiles - cookie_files = _iter_chrome_cookie_files(name) + try: + fn = _get_browser_cookie_fn(browser_cookie3, name) + except AttributeError as e: + logger.debug("%s browser-cookie3 loader missing: %s", name, e) + attempts.append("%s=missing-loader" % name) + diagnostics.append("%s: %s" % (name, e)) + continue + + if name in _CHROMIUM_BASE_DIRS or name in (_CUSTOM_CHROMIUM_BROWSER, "zen"): + cookie_files = ( + _iter_zen_cookie_files() if name == "zen" else _iter_chrome_cookie_files(name) + ) if not cookie_files: - # No profile dirs found — try the default (no cookie_file arg) + if name == _CUSTOM_CHROMIUM_BROWSER: + attempts.append("%s=not-found" % name) + continue + if name == "zen": + attempts.append("zen=no-profiles") + continue try: jar = fn() except Exception as e: @@ -318,7 +503,7 @@ def _extract_in_process() -> Tuple[Optional[Dict[str, str]], List[str]]: continue for cookie_file in cookie_files: - profile_name = os.path.basename(os.path.dirname(cookie_file)) + profile_name = _profile_name_from_cookie_file(cookie_file) try: jar = fn(cookie_file=cookie_file) except Exception as e: @@ -367,42 +552,101 @@ def _extract_via_subprocess() -> Tuple[Optional[Dict[str, str]], List[str]]: CHROMIUM_BASE_DIRS = { "chrome": os.path.join("Google", "Chrome"), "arc": os.path.join("Arc", "User Data"), - "edge": os.path.join("Microsoft Edge"), + "edge": "Microsoft Edge", "brave": os.path.join("BraveSoftware", "Brave-Browser"), + "vivaldi": "Vivaldi", } +CUSTOM_CHROMIUM_BROWSER = "custom-chromium" +ZEN_COOKIE_FILES = __ZEN_COOKIE_FILES__ + +def custom_chromium_user_data_dir(): + root = os.environ.get("TWITTER_CHROMIUM_USER_DATA_DIR", "").strip() + if not root: + return None + return os.path.abspath(os.path.expanduser(root)) + +def profile_cookie_paths(profile_dir): + paths = [] + for relative_path in ("Cookies", os.path.join("Network", "Cookies")): + cookie_path = os.path.join(profile_dir, relative_path) + if os.path.exists(cookie_path): + paths.append(cookie_path) + return paths + +def profile_name_from_cookie_file(cookie_file): + parent = os.path.basename(os.path.dirname(cookie_file)) + if parent == "Network": + return os.path.basename(os.path.dirname(os.path.dirname(cookie_file))) + return parent + +def chromium_key_file_for_cookie(cookie_file): + candidates = [] + custom_root = custom_chromium_user_data_dir() + if custom_root: + candidates.append(os.path.join(custom_root, "Local State")) + profile_dir = os.path.dirname(cookie_file) + if os.path.basename(profile_dir) == "Network": + profile_dir = os.path.dirname(profile_dir) + candidates.append(os.path.join(os.path.dirname(profile_dir), "Local State")) + for candidate in dict.fromkeys(candidates): + if os.path.exists(candidate): + return candidate + return None def iter_cookie_files(browser_name): - base_dir = CHROMIUM_BASE_DIRS.get(browser_name) - if base_dir is None: - return [] - if sys.platform == "darwin": - root = os.path.join(os.path.expanduser("~"), "Library", "Application Support", base_dir) - elif sys.platform == "win32": - if browser_name == "edge": - root = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Microsoft", "Edge", "User Data") - else: - root = os.path.join(os.environ.get("LOCALAPPDATA", ""), base_dir) + if browser_name == CUSTOM_CHROMIUM_BROWSER: + root = custom_chromium_user_data_dir() + if not root: + return [] else: - if browser_name == "edge": - root = os.path.join(os.path.expanduser("~"), ".config", "microsoft-edge") + base_dir = CHROMIUM_BASE_DIRS.get(browser_name) + if base_dir is None: + return [] + if sys.platform == "darwin": + root = os.path.join(os.path.expanduser("~"), "Library", "Application Support", base_dir) + elif sys.platform == "win32": + if browser_name == "edge": + root = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Microsoft", "Edge", "User Data") + elif browser_name == "vivaldi": + root = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Vivaldi", "User Data") + else: + root = os.path.join(os.environ.get("LOCALAPPDATA", ""), base_dir) else: - root = os.path.join(os.path.expanduser("~"), ".config", base_dir) + if browser_name == "edge": + root = os.path.join(os.path.expanduser("~"), ".config", "microsoft-edge") + elif browser_name == "vivaldi": + root = os.path.join(os.path.expanduser("~"), ".config", "vivaldi") + else: + root = os.path.join(os.path.expanduser("~"), ".config", base_dir) if not os.path.isdir(root): return [] env_profile = os.environ.get("TWITTER_CHROME_PROFILE", "").strip() if env_profile: - p = os.path.join(root, env_profile, "Cookies") - return [p] if os.path.exists(p) else [] + profile_dir = env_profile if os.path.isabs(env_profile) else os.path.join(root, env_profile) + return profile_cookie_paths(profile_dir) paths = [] - d = os.path.join(root, "Default", "Cookies") - if os.path.exists(d): - paths.append(d) + seen = set() + def append_profile(profile_dir): + for cookie_path in profile_cookie_paths(profile_dir): + if cookie_path not in seen: + seen.add(cookie_path) + paths.append(cookie_path) + append_profile(root) + append_profile(os.path.join(root, "Default")) for pd in sorted(glob.glob(os.path.join(root, "Profile *"))): - cf = os.path.join(pd, "Cookies") - if os.path.exists(cf): - paths.append(cf) + append_profile(pd) return paths +def get_browser_cookie_fn(browser_name): + if browser_name == CUSTOM_CHROMIUM_BROWSER: + return lambda cookie_file=None: browser_cookie3.chromium( + cookie_file=cookie_file, + key_file=chromium_key_file_for_cookie(cookie_file) if cookie_file else None, + ) + if browser_name == "zen": + return browser_cookie3.firefox + return getattr(browser_cookie3, browser_name) + def extract_from_jar(jar, name, profile=""): result = {} all_cookies = {} @@ -423,26 +667,31 @@ def extract_from_jar(jar, name, profile=""): return result return None -DEFAULT_ORDER = ["arc", "chrome", "edge", "firefox", "brave"] +DEFAULT_ORDER = ["arc", "chrome", "edge", "firefox", "brave", "vivaldi", "zen"] +SUPPORTED_BROWSERS = set(DEFAULT_ORDER) | {CUSTOM_CHROMIUM_BROWSER} +browser_order = list(DEFAULT_ORDER) +if custom_chromium_user_data_dir(): + browser_order.insert(0, CUSTOM_CHROMIUM_BROWSER) env_browser = os.environ.get("TWITTER_BROWSER", "").strip().lower() -if env_browser in {"arc", "chrome", "edge", "firefox", "brave"}: - browser_order = [env_browser] + [b for b in DEFAULT_ORDER if b != env_browser] -else: - browser_order = DEFAULT_ORDER -browser_fns = { - "arc": browser_cookie3.arc, - "chrome": browser_cookie3.chrome, - "edge": browser_cookie3.edge, - "firefox": browser_cookie3.firefox, - "brave": browser_cookie3.brave, -} +if env_browser in SUPPORTED_BROWSERS: + browser_order = [env_browser] + [b for b in browser_order if b != env_browser] attempts = [] for name in browser_order: - fn = browser_fns[name] - if name in CHROMIUM_BASE_DIRS: - cookie_files = iter_cookie_files(name) + try: + fn = get_browser_cookie_fn(name) + except AttributeError as exc: + attempts.append(f"{name}=missing-loader: {exc}") + continue + if name in CHROMIUM_BASE_DIRS or name in (CUSTOM_CHROMIUM_BROWSER, "zen"): + cookie_files = ZEN_COOKIE_FILES if name == "zen" else iter_cookie_files(name) if not cookie_files: + if name == CUSTOM_CHROMIUM_BROWSER: + attempts.append(f"{name}=not-found") + continue + if name == "zen": + attempts.append("zen=no-profiles") + continue try: jar = fn() except Exception as exc: @@ -455,7 +704,7 @@ def extract_from_jar(jar, name, profile=""): attempts.append(f"{name}=no-cookies") continue for cf in cookie_files: - pname = os.path.basename(os.path.dirname(cf)) + pname = profile_name_from_cookie_file(cf) try: jar = fn(cookie_file=cf) except Exception as exc: @@ -484,6 +733,7 @@ def extract_from_jar(jar, name, profile=""): })) sys.exit(1) ''' + extract_script = extract_script.replace("__ZEN_COOKIE_FILES__", repr(_iter_zen_cookie_files())) diagnostics: List[str] = [] @@ -547,7 +797,6 @@ def _run_extract_command( return None, diagnostics logger.info("Found cookies in %s (subprocess)", data.get("browser", "unknown")) - # Build full cookie string from all extracted cookies cookies: Dict[str, str] = {"auth_token": data["auth_token"], "ct0": data["ct0"]} all_cookies = data.get("all_cookies", {}) if all_cookies: @@ -571,13 +820,11 @@ def extract_from_browser() -> Tuple[Optional[Dict[str, str]], List[str]]: """ all_diagnostics: List[str] = [] - # 1. In-process (works on macOS, may fail with SQLite lock) cookies, diag = _extract_in_process() all_diagnostics.extend(diag) if cookies: return cookies, all_diagnostics - # 2. Subprocess fallback (handles SQLite lock, but fails on macOS Keychain) logger.debug("In-process extraction failed, trying subprocess fallback") cookies, diag = _extract_via_subprocess() all_diagnostics.extend(diag) @@ -589,45 +836,48 @@ def extract_from_browser() -> Tuple[Optional[Dict[str, str]], List[str]]: def get_cookies() -> Dict[str, str]: """Get Twitter cookies. Priority: env vars -> browser extraction. - Raises RuntimeError if no cookies found. + Raises AuthenticationError if no cookies found. """ cookies: Optional[Dict[str, str]] = None diagnostics: List[str] = [] - # 1. Try environment variables cookies = load_from_env() if cookies: logger.info("Loaded cookies from environment variables") - # 2. Try browser extraction (auto-detect) if not cookies: logger.debug("Attempting browser cookie extraction") cookies, diagnostics = extract_from_browser() if not cookies: lines = ["No Twitter cookies found."] - # Add actionable Keychain hint when relevant hint = _diagnose_keychain_issues(diagnostics) if hint: lines.append("") lines.append("Likely cause:") lines.extend(" " + line for line in hint.splitlines()) lines.append("") - lines.append("Option 1: Set TWITTER_AUTH_TOKEN and TWITTER_CT0 environment variables") - lines.append("Option 2: Make sure you are logged into x.com in your browser (Arc/Chrome/Edge/Firefox/Brave)") + lines.append( + "Option 1: Set TWITTER_COOKIE_STRING (or TWITTER_AUTH_TOKEN and TWITTER_CT0) environment variables" + ) + lines.append( + "Option 2: Make sure you are logged into x.com in your browser " + "(Arc/Chrome/Edge/Firefox/Brave/Vivaldi/Zen)" + ) + lines.append( + "Option 3: For a custom Chromium profile, set TWITTER_CHROMIUM_USER_DATA_DIR " + "to its --user-data-dir" + ) lines.append("") lines.append("Run 'twitter -v ' for debug diagnostics.") raise AuthenticationError("\n".join(lines)) - # Verify only for explicit auth failures; transient endpoint issues are tolerated. try: verify_cookies(cookies["auth_token"], cookies["ct0"], cookies.get("cookie_string")) except RuntimeError: - # Auth failure — re-extract from browser and retry verification logger.info("Cookie verification failed, re-extracting from browser") fresh_cookies, _ = extract_from_browser() if fresh_cookies: - # Verify fresh cookies — if this also fails, let it raise verify_cookies(fresh_cookies["auth_token"], fresh_cookies["ct0"], fresh_cookies.get("cookie_string")) return fresh_cookies raise From ed674bef14e4b150af2ddb225ae560afcc0ab1fa Mon Sep 17 00:00:00 2001 From: jackwener Date: Fri, 27 Nov 2026 18:21:15 +0000 Subject: [PATCH 4/8] feat(parser,model): rich tweet/user/media metadata, TweetDetail validation, article rich content, numeric user IDs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add author followers/following counts (#57) and optional viewer follow state (viewerFollowing / viewerFollowedBy) - Expose possiblySensitive and per-media warning labels (adultContent, graphicViolence, otherWarning) plus optional posterUrl, altText, and durationMs (#87 + quangdang46/twitter_cli) - Expose thread relationship fields (conversationId, inReplyToStatusId, inReplyToUserId, inReplyToScreenName) and --cursor / pagination.nextCursor on `twitter tweet` (closes #105) - Validate TweetDetail responses contain the requested focal tweet and order it first, returning structured not_found instead of empty success (closes #53) - Support post-legacy UserByRestId shapes (profile_bio, website, relationship_counts, tweet_counts, action_counts) and accept numeric user IDs in fetch_user() - Add Draft.js article rich content parsing (DIVIDER, TWEET, inline Bold/Italic/Code/Strikethrough with overlap-safe link rendering) and `twitter bookmarks --cursor` pagination Absorbs #57, #70, #75, #87, and live-payload audit fixes from quangdang46/twitter_cli. Closes #53, #105. Co-authored-by: edwinbernadus Co-authored-by: Lucius Co-authored-by: Li Chenxi Co-authored-by: kangxl <230263957+zh-xl-kang@users.noreply.github.com> Co-authored-by: Trần Quang Đãng <91641923+quangdang46@users.noreply.github.com> --- tests/conftest.py | 5 + tests/test_article_parsing.py | 124 ++++++++++++++ tests/test_cli.py | 79 +++++++++ tests/test_client.py | 63 +++++++ tests/test_parser_fixtures.py | 105 +++++++++++- tests/test_serialization.py | 69 ++++++++ twitter_cli/cli.py | 93 ++++++++--- twitter_cli/client.py | 145 +++++++++++----- twitter_cli/models.py | 20 ++- twitter_cli/parser.py | 304 +++++++++++++++++++++++++++------- twitter_cli/serialization.py | 94 +++++++++-- 11 files changed, 956 insertions(+), 145 deletions(-) create mode 100644 tests/test_article_parsing.py diff --git a/tests/conftest.py b/tests/conftest.py index d435289..65f3bdc 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -40,6 +40,11 @@ def _make_tweet(tweet_id: str = "1", **overrides: Any) -> Tweet: article_text=overrides.pop("article_text", None), is_subscriber_only=overrides.pop("is_subscriber_only", False), is_promoted=overrides.pop("is_promoted", False), + possibly_sensitive=overrides.pop("possibly_sensitive", False), + conversation_id=overrides.pop("conversation_id", None), + in_reply_to_status_id=overrides.pop("in_reply_to_status_id", None), + in_reply_to_user_id=overrides.pop("in_reply_to_user_id", None), + in_reply_to_screen_name=overrides.pop("in_reply_to_screen_name", None), ) return _make_tweet diff --git a/tests/test_article_parsing.py b/tests/test_article_parsing.py new file mode 100644 index 0000000..ff599f0 --- /dev/null +++ b/tests/test_article_parsing.py @@ -0,0 +1,124 @@ +"""Tests for Twitter Article (long-form) Draft.js rich content parsing.""" + +from __future__ import annotations + +from twitter_cli.parser import ( + _extract_atomic_content, + _normalize_article_entity_map, + _parse_article, + _render_article_text_block, +) + + +class TestRenderArticleTextBlock: + def test_plain_text_unchanged(self): + block = {"text": "hello world", "entityRanges": [], "inlineStyleRanges": []} + assert _render_article_text_block(block, {}) == "hello world" + + def test_empty_text(self): + assert _render_article_text_block({"text": "", "entityRanges": [], "inlineStyleRanges": []}, {}) == "" + + def test_bold_italic_code_strikethrough(self): + block = { + "text": "bold italic code strike", + "entityRanges": [], + "inlineStyleRanges": [ + {"offset": 0, "length": 4, "style": "Bold"}, + {"offset": 5, "length": 6, "style": "Italic"}, + {"offset": 12, "length": 4, "style": "Code"}, + {"offset": 17, "length": 6, "style": "Strikethrough"}, + ], + } + assert _render_article_text_block(block, {}) == "**bold** *italic* `code` ~~strike~~" + + def test_bold_and_link_mixed_non_overlapping(self): + block = { + "text": "Click here for more", + "entityRanges": [{"key": 0, "offset": 6, "length": 4}], + "inlineStyleRanges": [{"offset": 0, "length": 5, "style": "Bold"}], + } + entity_map = {"0": {"type": "LINK", "data": {"url": "https://example.com"}}} + result = _render_article_text_block(block, entity_map) + assert result == "**Click** [here](https://example.com) for more" + + def test_overlapping_style_and_link_preserves_link_without_corruption(self): + block = { + "text": "Read docs now", + "entityRanges": [{"key": 0, "offset": 5, "length": 4}], + "inlineStyleRanges": [{"offset": 5, "length": 4, "style": "Bold"}], + } + entity_map = {"0": {"type": "LINK", "data": {"url": "https://example.com"}}} + result = _render_article_text_block(block, entity_map) + assert result == "Read [docs](https://example.com) now" + + def test_out_of_bounds_style_ignored(self): + block = { + "text": "short", + "entityRanges": [], + "inlineStyleRanges": [{"offset": 0, "length": 100, "style": "Bold"}], + } + assert _render_article_text_block(block, {}) == "short" + + +class TestExtractAtomicContent: + def test_divider(self): + block = {"entityRanges": [{"key": 0, "length": 1, "offset": 0}]} + entity_map = {"0": {"type": "DIVIDER", "data": {}}} + assert _extract_atomic_content(block, entity_map) == ["---"] + + def test_embedded_tweet(self): + block = {"entityRanges": [{"key": 0, "length": 1, "offset": 0}]} + entity_map = {"0": {"type": "TWEET", "data": {"tweetId": "123456"}}} + result = _extract_atomic_content(block, entity_map) + assert result == ["> [Embedded Tweet](https://x.com/i/status/123456)"] + + def test_markdown_block(self): + block = {"entityRanges": [{"key": 0, "length": 1, "offset": 0}]} + entity_map = {"0": {"type": "MARKDOWN", "data": {"markdown": "# Heading"}}} + assert _extract_atomic_content(block, entity_map) == ["# Heading"] + + +class TestNormalizeAndParseArticle: + def test_list_and_dict_entity_map(self): + assert _normalize_article_entity_map([{"key": "0", "value": {"type": "DIVIDER"}}]) == { + "0": {"type": "DIVIDER"} + } + assert _normalize_article_entity_map({"0": {"type": "DIVIDER"}}) == {"0": {"type": "DIVIDER"}} + + def test_parse_article_divider_and_image(self): + tweet_data = { + "article": { + "article_results": { + "result": { + "title": "Test Article", + "content_state": { + "blocks": [ + {"type": "unstyled", "text": "Intro", "entityRanges": [], "inlineStyleRanges": []}, + {"type": "atomic", "text": " ", "entityRanges": [{"key": 0, "length": 1, "offset": 0}]}, + {"type": "atomic", "text": " ", "entityRanges": [{"key": 1, "length": 1, "offset": 0}]}, + ], + "entityMap": [ + {"key": "0", "value": {"type": "DIVIDER", "data": {}}}, + { + "key": "1", + "value": { + "type": "MEDIA", + "data": {"caption": "Diagram", "mediaItems": [{"mediaId": "111"}]}, + }, + }, + ], + }, + "media_entities": [ + { + "media_id": "111", + "media_info": {"original_img_url": "https://pbs.twimg.com/media/test.jpg"}, + } + ], + } + } + } + } + result = _parse_article(tweet_data) + assert result["article_title"] == "Test Article" + assert "---" in result["article_text"] + assert "![Diagram](https://pbs.twimg.com/media/test.jpg)" in result["article_text"] diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c6c58a..4530329 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -868,3 +868,82 @@ def test_show_malformed_cache_treated_as_empty(monkeypatch, tmp_path): result = runner.invoke(cli, ["show", "1"]) assert result.exit_code != 0 assert "No cached results" in result.output + + +def test_cli_tweet_reports_missing_focal_tweet_as_structured_error(monkeypatch) -> None: + from twitter_cli.exceptions import NotFoundError + + class FakeClient: + def fetch_tweet_detail(self, tweet_id: str, max_count: int, cursor=None, return_cursor=False): + raise NotFoundError("Tweet %s was not returned by the TweetDetail response" % tweet_id) + + monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient()) + monkeypatch.setattr( + "twitter_cli.cli.load_config", + lambda: {"fetch": {"count": 50}, "filter": {}, "rateLimit": {}}, + ) + runner = CliRunner() + + result = runner.invoke(cli, ["tweet", "12345", "--json"]) + + assert result.exit_code == 1 + payload = json.loads(result.output) + assert payload["ok"] is False + assert payload["error"]["code"] == "not_found" + assert "TweetDetail response" in payload["error"]["message"] + + +def test_cli_tweet_emits_pagination_cursor_and_thread_fields(monkeypatch, tweet_factory) -> None: + captured = {} + + class FakeClient: + def fetch_tweet_detail(self, tweet_id: str, max_count: int, cursor=None, return_cursor=False): + captured["cursor"] = cursor + captured["return_cursor"] = return_cursor + return [ + tweet_factory("100", conversation_id="100"), + tweet_factory("101", conversation_id="100", in_reply_to_status_id="100", in_reply_to_screen_name="alice"), + ], "cursor-replies-2" + + monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient()) + monkeypatch.setattr( + "twitter_cli.cli.load_config", + lambda: {"fetch": {"count": 50}, "filter": {}, "rateLimit": {}}, + ) + runner = CliRunner() + + result = runner.invoke(cli, ["tweet", "100", "--cursor", "cursor-1", "--json"]) + + assert result.exit_code == 0, result.output + payload = json.loads(result.output) + assert payload["ok"] is True + assert payload["pagination"]["nextCursor"] == "cursor-replies-2" + assert payload["data"][1]["conversationId"] == "100" + assert payload["data"][1]["inReplyToStatusId"] == "100" + assert captured == {"cursor": "cursor-1", "return_cursor": True} + + +def test_cli_bookmarks_cursor_pagination(monkeypatch, tweet_factory) -> None: + captured = {} + + class FakeClient: + def fetch_bookmarks(self, count: int, cursor=None, return_cursor=False): + captured["cursor"] = cursor + captured["return_cursor"] = return_cursor + return [tweet_factory("77")], "bm-cursor-2" + + monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient()) + monkeypatch.setattr( + "twitter_cli.cli.load_config", + lambda: {"fetch": {"count": 20}, "filter": {}, "rateLimit": {}}, + ) + runner = CliRunner() + + result = runner.invoke(cli, ["bookmarks", "--cursor", "bm-cursor-1", "--json"]) + + assert result.exit_code == 0, result.output + payload = json.loads(result.output) + assert payload["ok"] is True + assert payload["data"][0]["id"] == "77" + assert payload["pagination"]["nextCursor"] == "bm-cursor-2" + assert captured == {"cursor": "bm-cursor-1", "return_cursor": True} diff --git a/tests/test_client.py b/tests/test_client.py index b167f70..a1c6269 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1832,3 +1832,66 @@ def test_failing_generator_also_refuses(self): client._client_transaction = transaction with pytest.raises(TwitterAPIError): client._build_headers("https://x.com/i/api/graphql/qid/CreateTweet", "POST") + + +class TestTweetDetailFetch: + def test_raises_when_focal_tweet_is_missing(self): + from twitter_cli.exceptions import NotFoundError + + client = TwitterClient.__new__(TwitterClient) + client._fetch_timeline = MagicMock(return_value=[MagicMock(id="reply-1")]) + + with pytest.raises( + NotFoundError, + match="Tweet 123 was not returned by the TweetDetail response", + ): + client.fetch_tweet_detail("123", 20) + + def test_places_focal_tweet_before_replies(self): + client = TwitterClient.__new__(TwitterClient) + reply = MagicMock(id="reply-1") + focal_tweet = MagicMock(id="123") + client._fetch_timeline = MagicMock(return_value=[reply, focal_tweet]) + + tweets = client.fetch_tweet_detail("123", 20) + + assert tweets == [focal_tweet, reply] + + def test_supports_cursor_and_return_cursor(self): + client = TwitterClient.__new__(TwitterClient) + reply = MagicMock(id="reply-2") + client._fetch_timeline = MagicMock(return_value=([reply], "next-cur")) + + tweets, next_cursor = client.fetch_tweet_detail( + "123", 20, cursor="prev-cur", return_cursor=True + ) + + assert tweets == [reply] + assert next_cursor == "next-cur" + + +class TestFetchUserByNumericId: + def test_fetch_user_routes_numeric_id_to_user_by_rest_id(self): + client = TwitterClient.__new__(TwitterClient) + calls = [] + + def mock_get(operation_name, variables, features, field_toggles=None): + calls.append((operation_name, variables)) + return { + "data": { + "user": { + "result": { + "rest_id": "44196397", + "core": {"name": "Elon Musk", "screen_name": "elonmusk"}, + "relationship_counts": {"followers": 1000, "following": 50}, + } + } + } + } + + client._graphql_get = mock_get + profile = client.fetch_user("44196397") + assert calls[0][0] == "UserByRestId" + assert calls[0][1]["userId"] == "44196397" + assert profile.screen_name == "elonmusk" + assert profile.followers_count == 1000 diff --git a/tests/test_parser_fixtures.py b/tests/test_parser_fixtures.py index 0e37183..6d7e9eb 100644 --- a/tests/test_parser_fixtures.py +++ b/tests/test_parser_fixtures.py @@ -1,7 +1,7 @@ from __future__ import annotations from twitter_cli.client import TwitterClient -from twitter_cli.parser import _deep_get, parse_timeline_response +from twitter_cli.parser import _deep_get, _extract_media, parse_timeline_response, parse_user_result def _make_client() -> TwitterClient: @@ -107,3 +107,106 @@ def test_fetch_user_list_with_fixture(monkeypatch, fixture_loader) -> None: assert len(users) == 1 assert users[0].screen_name == "follower1" assert users[0].verified is True + + +def test_parse_sensitive_media_and_thread_metadata(fixture_loader) -> None: + payload = fixture_loader("home_timeline.json") + entry = payload["data"]["home"]["home_timeline_urt"]["instructions"][0]["entries"][0] + tweet_res = entry["content"]["itemContent"]["tweet_results"]["result"] + legacy = tweet_res["legacy"] + legacy["possibly_sensitive"] = True + legacy["conversation_id_str"] = "1" + legacy["in_reply_to_status_id_str"] = "999" + legacy["in_reply_to_user_id_str"] = "42" + legacy["in_reply_to_screen_name"] = "parent_user" + legacy["extended_entities"]["media"][0]["ext_sensitive_media_warning"] = { + "adult_content": True, + "graphic_violence": False, + "other": False, + } + legacy["extended_entities"]["media"][0]["ext_alt_text"] = "A cat" + user_legacy = tweet_res["core"]["user_results"]["result"]["legacy"] + user_legacy["followers_count"] = 1234 + user_legacy["friends_count"] = 56 + user_legacy["following"] = True + user_legacy["followed_by"] = False + + tweets, _ = parse_timeline_response( + payload, + lambda data: _deep_get(data, "data", "home", "home_timeline_urt", "instructions"), + ) + + t = tweets[0] + assert t.possibly_sensitive is True + assert t.conversation_id == "1" + assert t.in_reply_to_status_id == "999" + assert t.in_reply_to_user_id == "42" + assert t.in_reply_to_screen_name == "parent_user" + assert t.media[0].adult_content is True + assert t.media[0].graphic_violence is False + assert t.media[0].alt_text == "A cat" + assert t.author.followers_count == 1234 + assert t.author.following_count == 56 + assert t.author.viewer_following is True + assert t.author.viewer_followed_by is False + + +def test_extract_media_reads_nested_warning_and_video_poster() -> None: + legacy = { + "extended_entities": { + "media": [ + { + "type": "video", + "media_url_https": "https://pbs.twimg.com/thumb.jpg", + "original_info": {"width": 1280, "height": 720}, + "video_info": { + "duration_millis": 15000, + "variants": [ + {"content_type": "video/mp4", "bitrate": 832000, "url": "https://v.mp4"} + ], + }, + "media_results": { + "result": { + "sensitive_media_warning": {"graphic_violence": True} + } + }, + } + ] + } + } + media = _extract_media(legacy) + assert len(media) == 1 + assert media[0].url == "https://v.mp4" + assert media[0].poster_url == "https://pbs.twimg.com/thumb.jpg" + assert media[0].duration_ms == 15000 + assert media[0].graphic_violence is True + assert media[0].adult_content is False + + +def test_parse_user_result_handles_post_legacy_user_by_rest_id_shape() -> None: + user_data = { + "rest_id": "44196397", + "core": {"name": "Elon Musk", "screen_name": "elonmusk", "created_at": "Tue Jun 02 20:12:29 +0000 2009"}, + "avatar": {"image_url": "https://pbs.twimg.com/avatar.jpg"}, + "location": {"location": "Mars"}, + "profile_bio": {"description": "Builder"}, + "website": {"url": "https://x.com"}, + "relationship_counts": {"followers": 200000000, "following": 800}, + "tweet_counts": {"tweets": 50000}, + "action_counts": {"favorites_count": 90000}, + "relationship_perspectives": {"following": True, "followed_by": False}, + "verification": {"verified": True}, + } + profile = parse_user_result(user_data) + assert profile is not None + assert profile.id == "44196397" + assert profile.screen_name == "elonmusk" + assert profile.bio == "Builder" + assert profile.url == "https://x.com" + assert profile.followers_count == 200000000 + assert profile.following_count == 800 + assert profile.tweets_count == 50000 + assert profile.likes_count == 90000 + assert profile.verified is True + assert profile.viewer_following is True + assert profile.viewer_followed_by is False diff --git a/tests/test_serialization.py b/tests/test_serialization.py index cd11545..fe692f4 100644 --- a/tests/test_serialization.py +++ b/tests/test_serialization.py @@ -1,5 +1,6 @@ from __future__ import annotations +from twitter_cli.models import Author, TweetMedia from twitter_cli.serialization import tweet_from_dict, tweet_to_dict, tweets_from_json, tweets_to_json @@ -93,3 +94,71 @@ def test_tweet_roundtrip_preserves_promoted_flag(tweet_factory) -> None: assert payload["isPromoted"] is True restored = tweet_from_dict(payload) assert restored.is_promoted is True + + +def test_tweet_roundtrip_preserves_rich_metadata(tweet_factory) -> None: + quoted = tweet_factory("101", possibly_sensitive=True) + tweet = tweet_factory( + "100", + author=Author( + id="u1", + name="Alice", + screen_name="alice", + followers_count=500, + following_count=120, + viewer_following=True, + viewer_followed_by=False, + ), + possibly_sensitive=True, + conversation_id="100", + in_reply_to_status_id="99", + in_reply_to_user_id="u0", + in_reply_to_screen_name="bob", + quoted_tweet=quoted, + media=[ + TweetMedia( + type="video", + url="https://video.mp4", + width=1280, + height=720, + adult_content=True, + graphic_violence=True, + other_warning=False, + poster_url="https://thumb.jpg", + alt_text="clip", + duration_ms=4500, + ) + ], + ) + payload = tweet_to_dict(tweet) + assert payload["author"]["followers"] == 500 + assert payload["author"]["following"] == 120 + assert payload["author"]["viewerFollowing"] is True + assert payload["author"]["viewerFollowedBy"] is False + assert payload["possiblySensitive"] is True + assert payload["conversationId"] == "100" + assert payload["inReplyToStatusId"] == "99" + assert payload["inReplyToUserId"] == "u0" + assert payload["inReplyToScreenName"] == "bob" + assert payload["quotedTweet"]["possiblySensitive"] is True + assert payload["media"][0]["adultContent"] is True + assert payload["media"][0]["posterUrl"] == "https://thumb.jpg" + assert payload["media"][0]["altText"] == "clip" + assert payload["media"][0]["durationMs"] == 4500 + + restored = tweet_from_dict(payload) + assert restored.author.followers_count == 500 + assert restored.author.following_count == 120 + assert restored.author.viewer_following is True + assert restored.author.viewer_followed_by is False + assert restored.possibly_sensitive is True + assert restored.conversation_id == "100" + assert restored.in_reply_to_status_id == "99" + assert restored.in_reply_to_user_id == "u0" + assert restored.in_reply_to_screen_name == "bob" + assert restored.quoted_tweet is not None + assert restored.quoted_tweet.possibly_sensitive is True + assert restored.media[0].adult_content is True + assert restored.media[0].poster_url == "https://thumb.jpg" + assert restored.media[0].alt_text == "clip" + assert restored.media[0].duration_ms == 4500 diff --git a/twitter_cli/cli.py b/twitter_cli/cli.py index d2dc523..c53c783 100644 --- a/twitter_cli/cli.py +++ b/twitter_cli/cli.py @@ -358,25 +358,56 @@ def _emit_timeline_structured(tweets, next_cursor, *, as_json, as_yaml): return emit_structured(payload, as_json=as_json, as_yaml=as_yaml) -def _run_bookmarks_command(max_count, as_json, as_yaml, output_file, do_filter, compact=False, full_text=False): - # type: (Optional[int], bool, bool, Optional[str], bool, bool, bool) -> None +def _run_bookmarks_command( + max_count, as_json, as_yaml, output_file, do_filter, compact=False, full_text=False, cursor=None +): + # type: (Optional[int], bool, bool, Optional[str], bool, bool, bool, Optional[str]) -> None + """Fetch bookmarks with optional cursor-based pagination.""" config = load_config() + rich_output = use_rich_output(as_json=as_json, as_yaml=as_yaml, compact=compact) def _run(): - client = _get_client(config) - _fetch_and_display( - lambda count: client.fetch_bookmarks(count), - "bookmarks", - "🔖", - max_count, - as_json, - as_yaml, - output_file, - do_filter, - config, - compact=compact, + client = _get_client(config, quiet=not rich_output) + fetch_count = _resolve_configured_count(config, max_count) + if rich_output: + console.print("🔖 Fetching bookmarks (%d tweets)...\n" % fetch_count) + start = time.time() + try: + result = client.fetch_bookmarks(fetch_count, cursor=cursor, return_cursor=True) + except TypeError: + result = (client.fetch_bookmarks(fetch_count), None) + if isinstance(result, tuple) and len(result) == 2: + tweets, next_cursor = result + else: + tweets, next_cursor = result, None + elapsed = time.time() - start + if rich_output: + console.print("✅ Fetched %d bookmarks in %.1fs\n" % (len(tweets), elapsed)) + + filtered = _apply_filter(tweets, do_filter, config, rich_output=rich_output) + + if output_file: + Path(output_file).write_text(tweets_to_json(filtered), encoding="utf-8") + if rich_output: + console.print("💾 Saved to %s\n" % output_file) + + if compact: + click.echo(tweets_to_compact_json(filtered)) + return + + save_tweet_cache(filtered) + + if _emit_timeline_structured(filtered, next_cursor, as_json=as_json, as_yaml=as_yaml): + return + + print_tweet_table( + filtered, + console, + title="🔖 Bookmarks — %d tweets" % len(filtered), full_text=full_text, ) + _print_show_hint() + console.print() _run_guarded(_run) @@ -509,13 +540,14 @@ def favorites(ctx, max_count, as_json, as_yaml, output_file, do_filter, full_tex @cli.group(name="bookmarks", invoke_without_command=True) @click.option("--max", "-n", "max_count", type=int, default=None, help="Max number of tweets to fetch.") +@click.option("--cursor", type=str, default=None, help="Pagination cursor to continue a previous bookmarks fetch.") @structured_output_options @click.option("--output", "-o", "output_file", type=str, default=None, help="Save tweets to JSON file.") @click.option("--filter", "do_filter", is_flag=True, help="Enable score-based filtering.") @click.option("--full-text", is_flag=True, help="Show full tweet text in table output.") @click.pass_context -def bookmarks(ctx, max_count, as_json, as_yaml, output_file, do_filter, full_text): - # type: (Any, Optional[int], bool, bool, Optional[str], bool, bool) -> None +def bookmarks(ctx, max_count, cursor, as_json, as_yaml, output_file, do_filter, full_text): + # type: (Any, Optional[int], Optional[str], bool, bool, Optional[str], bool, bool) -> None """Fetch bookmarked tweets, or manage bookmark folders.""" if ctx.invoked_subcommand is None: _run_bookmarks_command( @@ -526,6 +558,7 @@ def bookmarks(ctx, max_count, as_json, as_yaml, output_file, do_filter, full_tex do_filter, compact=ctx.obj.get("compact", False), full_text=full_text, + cursor=cursor, ) @@ -852,39 +885,53 @@ def _run(): @cli.command() @click.argument("tweet_id") @click.option("--max", "-n", "max_count", type=int, default=None, help="Max replies to fetch.") +@click.option("--cursor", type=str, default=None, help="Pagination cursor for continuing a thread fetch.") @click.option("--full-text", is_flag=True, help="Show full reply text in table output.") @structured_output_options @click.pass_context -def tweet(ctx, tweet_id, max_count, full_text, as_json, as_yaml): - # type: (Any, str, int, bool, bool, bool) -> None +def tweet(ctx, tweet_id, max_count, cursor, full_text, as_json, as_yaml): + # type: (Any, str, Optional[int], Optional[str], bool, bool, bool) -> None """View a tweet and its replies. TWEET_ID is the numeric tweet ID or full URL.""" compact = ctx.obj.get("compact", False) tweet_id = _normalize_tweet_id(tweet_id) config = load_config() rich_output = use_rich_output(as_json=as_json, as_yaml=as_yaml, compact=compact) + next_cursor = None # type: Optional[str] try: client = _get_client(config, quiet=not rich_output) if rich_output: console.print("🐦 Fetching tweet %s...\n" % tweet_id) start = time.time() - tweets = client.fetch_tweet_detail(tweet_id, _resolve_configured_count(config, max_count)) + fetch_count = _resolve_configured_count(config, max_count) + try: + result = client.fetch_tweet_detail( + tweet_id, fetch_count, cursor=cursor, return_cursor=True + ) + except TypeError: + result = (client.fetch_tweet_detail(tweet_id, fetch_count), None) + if isinstance(result, tuple) and len(result) == 2: + tweets, next_cursor = result + else: + tweets, next_cursor = result, None elapsed = time.time() - start if rich_output: console.print("✅ Fetched %d tweets in %.1fs\n" % (len(tweets), elapsed)) except (TwitterError, RuntimeError) as exc: _exit_with_error(exc) - _emit_tweet_detail(tweets, compact=compact, as_json=as_json, as_yaml=as_yaml, full_text=full_text) + _emit_tweet_detail( + tweets, compact=compact, as_json=as_json, as_yaml=as_yaml, full_text=full_text, next_cursor=next_cursor + ) -def _emit_tweet_detail(tweets, compact, as_json, as_yaml, full_text): - # type: (list, bool, bool, bool, bool) -> None +def _emit_tweet_detail(tweets, compact, as_json, as_yaml, full_text, next_cursor=None): + # type: (list, bool, bool, bool, bool, Optional[str]) -> None """Render tweet detail + replies in the requested output format.""" if compact: click.echo(tweets_to_compact_json(tweets)) return - if emit_structured(tweets_to_data(tweets), as_json=as_json, as_yaml=as_yaml): + if _emit_timeline_structured(tweets, next_cursor, as_json=as_json, as_yaml=as_yaml): return if tweets: diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 38e98c6..6860e29 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -198,9 +198,13 @@ def fetch_following_feed(self, count=20, include_promoted=False, cursor=None, re return_cursor=return_cursor, ) - def fetch_bookmarks(self, count=50): - # type: (int) -> List[Tweet] - """Fetch bookmarked tweets.""" + def fetch_bookmarks(self, count=50, cursor=None, return_cursor=False): + # type: (int, Optional[str], bool) -> Any + """Fetch bookmarked tweets. + + When ``return_cursor`` is True, returns ``(tweets, next_cursor)`` for + resumable batched pagination. + """ def get_instructions(data): # type: (Any) -> Any instructions = _deep_get(data, "data", "bookmark_timeline", "timeline", "instructions") @@ -208,7 +212,13 @@ def get_instructions(data): instructions = _deep_get(data, "data", "bookmark_timeline_v2", "timeline", "instructions") return instructions - return self._fetch_timeline("Bookmarks", count, get_instructions) + return self._fetch_timeline( + "Bookmarks", + count, + get_instructions, + start_cursor=cursor, + return_cursor=return_cursor, + ) def fetch_bookmark_folders(self): # type: () -> List[BookmarkFolder] @@ -274,51 +284,75 @@ def resolve_user_id(self, identifier): profile = self.fetch_user(identifier) return profile.id + _USER_FEATURES = { + "hidden_profile_subscriptions_enabled": True, + "rweb_tipjar_consumption_enabled": True, + "responsive_web_graphql_exclude_directive_enabled": True, + "verified_phone_label_enabled": False, + "subscriptions_verification_info_is_identity_verified_enabled": True, + "subscriptions_verification_info_verified_since_enabled": True, + "highlights_tweets_tab_ui_enabled": True, + "responsive_web_twitter_article_notes_tab_enabled": True, + "subscriptions_feature_can_gift_premium": True, + "creator_subscriptions_tweet_preview_api_enabled": True, + "responsive_web_graphql_skip_user_profile_image_extensions_enabled": False, + "responsive_web_graphql_timeline_navigation_enabled": True, + } + + def fetch_user_by_id(self, user_id): + # type: (str) -> UserProfile + """Fetch user profile by numeric user ID (UserByRestId).""" + variables = { + "userId": user_id, + "withSafetyModeUserFields": True, + } + data = self._graphql_get("UserByRestId", variables, self._USER_FEATURES) + result = _deep_get(data, "data", "user", "result") + profile = parse_user_result(result) if isinstance(result, dict) else None + if not profile: + raise NotFoundError("User %s not found" % user_id) + return profile + def fetch_user(self, screen_name): # type: (str) -> UserProfile - """Fetch user profile by screen name.""" + """Fetch user profile by screen name or numeric user ID.""" + if screen_name.isdigit(): + return self.fetch_user_by_id(screen_name) variables = { "screen_name": screen_name, "withSafetyModeUserFields": True, } - features = { - "hidden_profile_subscriptions_enabled": True, - "rweb_tipjar_consumption_enabled": True, - "responsive_web_graphql_exclude_directive_enabled": True, - "verified_phone_label_enabled": False, - "subscriptions_verification_info_is_identity_verified_enabled": True, - "subscriptions_verification_info_verified_since_enabled": True, - "highlights_tweets_tab_ui_enabled": True, - "responsive_web_twitter_article_notes_tab_enabled": True, - "subscriptions_feature_can_gift_premium": True, - "creator_subscriptions_tweet_preview_api_enabled": True, - "responsive_web_graphql_skip_user_profile_image_extensions_enabled": False, - "responsive_web_graphql_timeline_navigation_enabled": True, - } - data = self._graphql_get("UserByScreenName", variables, features) + data = self._graphql_get("UserByScreenName", variables, self._USER_FEATURES) result = _deep_get(data, "data", "user", "result") - if not result: + if not isinstance(result, dict): raise NotFoundError("User @%s not found" % screen_name) - legacy = result.get("legacy", {}) - core = result.get("core", {}) - avatar = result.get("avatar", {}) - location_obj = result.get("location", {}) - return UserProfile( - id=result.get("rest_id", ""), - name=core.get("name") or legacy.get("name", ""), - screen_name=core.get("screen_name") or legacy.get("screen_name", screen_name), - bio=legacy.get("description", ""), - location=location_obj.get("location") or legacy.get("location", ""), - url=_deep_get(legacy, "entities", "url", "urls", 0, "expanded_url") or "", - followers_count=_parse_int(legacy.get("followers_count"), 0), - following_count=_parse_int(legacy.get("friends_count"), 0), - tweets_count=_parse_int(legacy.get("statuses_count"), 0), - likes_count=_parse_int(legacy.get("favourites_count"), 0), - verified=bool(result.get("is_blue_verified") or legacy.get("verified", False)), - profile_image_url=avatar.get("image_url") or legacy.get("profile_image_url_https", ""), - created_at=core.get("created_at") or legacy.get("created_at", ""), - ) + profile = parse_user_result(result) + if profile is None: + if result.get("__typename") == "UserUnavailable" or not result: + raise NotFoundError("User @%s not found" % screen_name) + legacy = result.get("legacy") or {} + core = result.get("core") or {} + avatar = result.get("avatar") or {} + location_obj = result.get("location") or {} + return UserProfile( + id=result.get("rest_id", ""), + name=core.get("name") or legacy.get("name", ""), + screen_name=core.get("screen_name") or legacy.get("screen_name", screen_name), + bio=legacy.get("description", ""), + location=location_obj.get("location") or legacy.get("location", ""), + url=_deep_get(legacy, "entities", "url", "urls", 0, "expanded_url") or "", + followers_count=_parse_int(legacy.get("followers_count"), 0), + following_count=_parse_int(legacy.get("friends_count"), 0), + tweets_count=_parse_int(legacy.get("statuses_count"), 0), + likes_count=_parse_int(legacy.get("favourites_count"), 0), + verified=bool(result.get("is_blue_verified") or legacy.get("verified", False)), + profile_image_url=avatar.get("image_url") or legacy.get("profile_image_url_https", ""), + created_at=core.get("created_at") or legacy.get("created_at", ""), + ) + if not profile.screen_name: + profile.screen_name = screen_name + return profile def fetch_user_tweets(self, user_id, count=20): # type: (str, int) -> List[Tweet] @@ -391,10 +425,15 @@ def fetch_search(self, query, count=20, product="Top"): use_post=True, ) - def fetch_tweet_detail(self, tweet_id, count=20): - # type: (str, int) -> List[Tweet] - """Fetch a tweet and its conversation thread (replies).""" - return self._fetch_timeline( + def fetch_tweet_detail(self, tweet_id, count=20, cursor=None, return_cursor=False): + # type: (str, int, Optional[str], bool) -> Any + """Fetch a tweet and its conversation thread (replies). + + When ``cursor`` is None, verifies that the focal tweet is present in + the response (raising NotFoundError instead of silently returning empty + or reply-only results) and places it first. + """ + result = self._fetch_timeline( "TweetDetail", count, lambda data: _deep_get(data, "data", "tweetResult", "result", "timeline", "instructions") @@ -417,7 +456,25 @@ def fetch_tweet_detail(self, tweet_id, count=20): "withGrokAnalyze": False, "withDisallowedReplyControls": False, }, + start_cursor=cursor, + return_cursor=return_cursor, ) + if return_cursor: + tweets, next_cursor = result + else: + tweets, next_cursor = result, None + + if cursor is None: + focal_tweet = next((tweet for tweet in tweets if tweet.id == tweet_id), None) + if focal_tweet is None: + raise NotFoundError( + "Tweet %s was not returned by the TweetDetail response" % tweet_id + ) + tweets = [focal_tweet] + [tweet for tweet in tweets if tweet.id != tweet_id] + + if return_cursor: + return tweets, next_cursor + return tweets def fetch_article(self, tweet_id): # type: (str) -> Tweet diff --git a/twitter_cli/models.py b/twitter_cli/models.py index ee1d314..d3ad56c 100644 --- a/twitter_cli/models.py +++ b/twitter_cli/models.py @@ -1,6 +1,7 @@ """Data models for twitter-cli. -Defines Tweet, Author, Metrics, and TweetMedia as simple dataclasses. +Defines Tweet, Author, Metrics, TweetMedia, BookmarkFolder, and UserProfile +as simple dataclasses. """ from __future__ import annotations @@ -16,6 +17,10 @@ class Author: screen_name: str profile_image_url: str = "" verified: bool = False + followers_count: int = 0 + following_count: int = 0 + viewer_following: Optional[bool] = None + viewer_followed_by: Optional[bool] = None @dataclass @@ -34,6 +39,12 @@ class TweetMedia: url: str width: Optional[int] = None height: Optional[int] = None + adult_content: bool = False + graphic_violence: bool = False + other_warning: bool = False + poster_url: Optional[str] = None + alt_text: Optional[str] = None + duration_ms: Optional[int] = None @dataclass @@ -54,6 +65,11 @@ class Tweet: article_text: Optional[str] = None is_subscriber_only: bool = False is_promoted: bool = False + possibly_sensitive: bool = False + conversation_id: Optional[str] = None + in_reply_to_status_id: Optional[str] = None + in_reply_to_user_id: Optional[str] = None + in_reply_to_screen_name: Optional[str] = None @dataclass @@ -77,3 +93,5 @@ class UserProfile: verified: bool = False profile_image_url: str = "" created_at: str = "" + viewer_following: Optional[bool] = None + viewer_followed_by: Optional[bool] = None diff --git a/twitter_cli/parser.py b/twitter_cli/parser.py index 58378be..598e9d5 100644 --- a/twitter_cli/parser.py +++ b/twitter_cli/parser.py @@ -60,6 +60,94 @@ def _extract_cursor(content): # ── Media / Author extraction ──────────────────────────────────────────── +def _opt_str(value): + # type: (Any) -> Optional[str] + if isinstance(value, str) and value: + return value + return None + + +def _opt_bool(value): + # type: (Any) -> Optional[bool] + if isinstance(value, bool): + return value + return None + + +def _opt_int(value): + # type: (Any) -> Optional[int] + if value is None or isinstance(value, bool): + return None + try: + text = str(value).replace(",", "").strip() + if not text: + return None + return int(float(text)) + except (TypeError, ValueError): + return None + + +def _truthy(value): + # type: (Any) -> bool + return value is True or value == 1 or value in ("true", "True") + + +def _media_warning(item): + # type: (Any) -> Dict[str, bool] + """Read adult/graphic/other sensitive-media labels from a GraphQL media entity.""" + out = {"adult_content": False, "graphic_violence": False, "other": False} + if not isinstance(item, dict): + return out + + sources = [ + item.get("ext_sensitive_media_warning"), + item.get("sensitive_media_warning"), + item.get("extSensitiveMediaWarning"), + item.get("sensitiveMediaWarning"), + ] + media_results = item.get("media_results") or item.get("mediaResults") + if isinstance(media_results, dict): + result = media_results.get("result") or media_results + if isinstance(result, dict): + sources.extend( + [ + result.get("ext_sensitive_media_warning"), + result.get("sensitive_media_warning"), + result.get("extSensitiveMediaWarning"), + result.get("sensitiveMediaWarning"), + ] + ) + for src in sources: + if not isinstance(src, dict): + continue + for key, value in src.items(): + lk = str(key).replace("-", "_").lower() + if lk in ("adult_content", "adultcontent") and _truthy(value): + out["adult_content"] = True + elif lk in ("graphic_violence", "graphicviolence") and _truthy(value): + out["graphic_violence"] = True + elif lk in ("other", "other_warning", "otherwarning") and _truthy(value): + out["other"] = True + return out + + +def _tweet_media(media_type, url, media_item, poster_url=None): + # type: (str, str, Dict[str, Any], Optional[str]) -> TweetMedia + warning = _media_warning(media_item) + return TweetMedia( + type=media_type, + url=url, + width=_deep_get(media_item, "original_info", "width"), + height=_deep_get(media_item, "original_info", "height"), + adult_content=warning["adult_content"], + graphic_violence=warning["graphic_violence"], + other_warning=warning["other"], + poster_url=poster_url, + alt_text=_opt_str(media_item.get("ext_alt_text")), + duration_ms=_opt_int(_deep_get(media_item, "video_info", "duration_millis")), + ) + + def _extract_media(legacy): # type: (Dict[str, Any]) -> List[TweetMedia] """Extract media items from tweet legacy data.""" @@ -68,23 +156,23 @@ def _extract_media(legacy): media_type = media_item.get("type", "") if media_type == "photo": media.append( - TweetMedia( - type="photo", - url=media_item.get("media_url_https", ""), - width=_deep_get(media_item, "original_info", "width"), - height=_deep_get(media_item, "original_info", "height"), - ) + _tweet_media("photo", media_item.get("media_url_https", ""), media_item) ) elif media_type in {"video", "animated_gif"}: variants = media_item.get("video_info", {}).get("variants", []) mp4_variants = [v for v in variants if v.get("content_type") == "video/mp4"] mp4_variants.sort(key=lambda v: v.get("bitrate", 0), reverse=True) + url = ( + mp4_variants[0]["url"] + if mp4_variants + else media_item.get("media_url_https", "") + ) media.append( - TweetMedia( - type=media_type, - url=mp4_variants[0]["url"] if mp4_variants else media_item.get("media_url_https", ""), - width=_deep_get(media_item, "original_info", "width"), - height=_deep_get(media_item, "original_info", "height"), + _tweet_media( + media_type, + url, + media_item, + poster_url=_opt_str(media_item.get("media_url_https")), ) ) return media @@ -94,6 +182,20 @@ def _extract_author(user_data, user_legacy): # type: (Dict[str, Any], Dict[str, Any]) -> Author """Extract Author from user result data.""" user_core = user_data.get("core", {}) + rel_counts = user_data.get("relationship_counts", {}) + perspectives = user_data.get("relationship_perspectives", {}) + followers = _parse_int(user_legacy.get("followers_count"), 0) or _parse_int( + rel_counts.get("followers"), 0 + ) + following = _parse_int(user_legacy.get("friends_count"), 0) or _parse_int( + rel_counts.get("following"), 0 + ) + viewer_following = _opt_bool(user_legacy.get("following")) + if viewer_following is None: + viewer_following = _opt_bool(perspectives.get("following")) + viewer_followed_by = _opt_bool(user_legacy.get("followed_by")) + if viewer_followed_by is None: + viewer_followed_by = _opt_bool(perspectives.get("followed_by")) return Author( id=user_data.get("rest_id", ""), name=user_core.get("name") or user_legacy.get("name") or user_data.get("name", "Unknown"), @@ -107,6 +209,10 @@ def _extract_author(user_data, user_legacy): or user_legacy.get("profile_image_url_https", "") ), verified=bool(user_data.get("is_blue_verified") or user_legacy.get("verified", False)), + followers_count=followers, + following_count=following, + viewer_following=viewer_following, + viewer_followed_by=viewer_followed_by, ) @@ -196,9 +302,9 @@ def _extract_article_media_url_map(article_results): return media_url_map -def _extract_atomic_markdown(block, entity_map): +def _extract_atomic_content(block, entity_map): # type: (Dict[str, Any], Dict[str, Any]) -> List[str] - """Extract embedded markdown/code payloads from atomic Draft.js entities.""" + """Extract content from atomic Draft.js entities (MARKDOWN, DIVIDER, TWEET).""" parts = [] # type: List[str] for entity_range in block.get("entityRanges", []) or []: if not isinstance(entity_range, dict): @@ -207,28 +313,42 @@ def _extract_atomic_markdown(block, entity_map): entity = entity_map.get(str(entity_key)) if entity_key is not None else None if not isinstance(entity, dict): continue - if str(entity.get("type") or "").upper() != "MARKDOWN": - continue - markdown = _deep_get(entity, "data", "markdown") - if isinstance(markdown, str) and markdown.strip(): - parts.append(markdown.strip()) + entity_type = str(entity.get("type") or "").upper() + if entity_type == "MARKDOWN": + markdown = _deep_get(entity, "data", "markdown") + if isinstance(markdown, str) and markdown.strip(): + parts.append(markdown.strip()) + elif entity_type == "DIVIDER": + parts.append("---") + elif entity_type == "TWEET": + tweet_id = _deep_get(entity, "data", "tweetId") + if isinstance(tweet_id, str) and tweet_id: + parts.append("> [Embedded Tweet](https://x.com/i/status/%s)" % tweet_id) return parts +# Backwards-compatibility alias +_extract_atomic_markdown = _extract_atomic_content + + def _render_article_text_block(block, entity_map): # type: (Dict[str, Any], Dict[str, Any]) -> str - """Render a Draft.js text block, converting inline hyperlinks to Markdown.""" + """Render a Draft.js text block, converting inline styles and hyperlinks to Markdown. + + Both inlineStyleRanges and entityRanges (links) reference original text + offsets. Links take priority over overlapping style spans so offsets are + never corrupted, and accepted non-overlapping spans are applied + right-to-left. + """ text = block.get("text", "") if not isinstance(text, str) or not text: return "" - entity_ranges = block.get("entityRanges", []) or [] - if not entity_ranges: - return text + # Collect operations as (priority, start, end, replacement): lower priority wins overlaps. + candidates = [] # type: List[Tuple[int, int, int, str]] - rendered = text - ranges = [] - for entity_range in entity_ranges: + # Entity links (priority 0) + for entity_range in block.get("entityRanges", []) or []: if not isinstance(entity_range, dict): continue entity_key = entity_range.get("key") @@ -241,26 +361,53 @@ def _render_article_text_block(block, entity_map): length = entity_range.get("length") if not isinstance(offset, int) or not isinstance(length, int) or length <= 0: continue + if offset < 0 or offset + length > len(text): + continue url = _deep_get(entity, "data", "url") if not isinstance(url, str) or not url.strip(): continue - ranges.append((offset, length, url.strip())) - - for offset, length, url in sorted(ranges, reverse=True): - if offset < 0 or offset + length > len(rendered): - continue - label = rendered[offset:offset + length] + label = text[offset:offset + length] if not label: continue - # Escape markdown special chars: ] in labels and ) in URLs safe_label = label.replace("[", "\\[").replace("]", "\\]") - safe_url = url.replace(")", "%29") - rendered = "%s[%s](%s)%s" % ( - rendered[:offset], - safe_label, - safe_url, - rendered[offset + length:], - ) + safe_url = url.strip().replace(")", "%29") + candidates.append((0, offset, offset + length, "[%s](%s)" % (safe_label, safe_url))) + + # Inline styles (priority 1) + style_markers = { + "BOLD": ("**", "**"), + "ITALIC": ("*", "*"), + "CODE": ("`", "`"), + "STRIKETHROUGH": ("~~", "~~"), + } # type: Dict[str, Tuple[str, str]] + for sr in block.get("inlineStyleRanges", []) or []: + if not isinstance(sr, dict): + continue + style = str(sr.get("style", "")).upper() + offset = sr.get("offset") + length = sr.get("length") + if not isinstance(offset, int) or not isinstance(length, int) or length <= 0: + continue + if offset < 0 or offset + length > len(text): + continue + if style in style_markers: + open_m, close_m = style_markers[style] + segment = text[offset:offset + length] + candidates.append((1, offset, offset + length, "%s%s%s" % (open_m, segment, close_m))) + + if not candidates: + return text + + # Accept non-overlapping spans (links first, then styles). + accepted = [] # type: List[Tuple[int, int, str]] + for _prio, start, end, replacement in sorted(candidates, key=lambda x: (x[0], x[1], -(x[2] - x[1]))): + if any(not (end <= a_start or start >= a_end) for a_start, a_end, _ in accepted): + continue + accepted.append((start, end, replacement)) + + rendered = text + for start, end, replacement in sorted(accepted, key=lambda x: x[0], reverse=True): + rendered = "%s%s%s" % (rendered[:start], replacement, rendered[end:]) return rendered @@ -334,7 +481,7 @@ def _parse_article(tweet_data): for block in blocks: block_type = block.get("type", "unstyled") # type: str if block_type == "atomic": - parts.extend(_extract_atomic_markdown(block, entity_map)) + parts.extend(_extract_atomic_content(block, entity_map)) parts.extend(_extract_article_images(block, entity_map, media_url_map)) ordered_counter = 0 continue @@ -372,35 +519,69 @@ def _parse_article(tweet_data): def parse_user_result(user_data): # type: (Dict[str, Any]) -> Optional[UserProfile] - """Parse a user result object into UserProfile.""" + """Parse a user result object into UserProfile. + + Handles both legacy shapes (``legacy{}``) and newer post-legacy shapes + returned by ``UserByRestId`` (``core``, ``profile_bio``, ``website``, + ``relationship_counts``, ``tweet_counts``, ``action_counts``, + ``relationship_perspectives``, ``verification``). + """ if user_data.get("__typename") == "UserUnavailable": return None - # Twitter API migrated name/screen_name/created_at to core{}, avatar to - # avatar.image_url, and location to location.location. Newer responses - # may omit legacy{} entirely; fall back to legacy for older shapes. - legacy = user_data.get("legacy", {}) - core = user_data.get("core", {}) - avatar = user_data.get("avatar", {}) - location_obj = user_data.get("location", {}) - # Use rest_id presence as the existence signal, not legacy{}, so - # this stays consistent with fetch_user() once Twitter fully drops - # legacy. + legacy = user_data.get("legacy") or {} + core = user_data.get("core") or {} + avatar = user_data.get("avatar") or {} + location_obj = user_data.get("location") or {} + profile_bio = user_data.get("profile_bio") or {} + website = user_data.get("website") or {} + rel_counts = user_data.get("relationship_counts") or {} + tweet_counts = user_data.get("tweet_counts") or {} + action_counts = user_data.get("action_counts") or {} + perspectives = user_data.get("relationship_perspectives") or {} + verification = user_data.get("verification") or {} + if not user_data.get("rest_id"): return None + + viewer_following = _opt_bool(legacy.get("following")) + if viewer_following is None: + viewer_following = _opt_bool(perspectives.get("following")) + viewer_followed_by = _opt_bool(legacy.get("followed_by")) + if viewer_followed_by is None: + viewer_followed_by = _opt_bool(perspectives.get("followed_by")) + return UserProfile( id=user_data.get("rest_id", ""), name=core.get("name") or legacy.get("name", ""), screen_name=core.get("screen_name") or legacy.get("screen_name", ""), - bio=legacy.get("description", ""), + bio=legacy.get("description") or profile_bio.get("description", ""), location=location_obj.get("location") or legacy.get("location", ""), - url=_deep_get(legacy, "entities", "url", "urls", 0, "expanded_url") or "", - followers_count=_parse_int(legacy.get("followers_count"), 0), - following_count=_parse_int(legacy.get("friends_count"), 0), - tweets_count=_parse_int(legacy.get("statuses_count"), 0), - likes_count=_parse_int(legacy.get("favourites_count"), 0), - verified=user_data.get("is_blue_verified", False) or legacy.get("verified", False), + url=_deep_get(legacy, "entities", "url", "urls", 0, "expanded_url") or website.get("url", ""), + followers_count=max( + _parse_int(legacy.get("followers_count"), 0), + _parse_int(rel_counts.get("followers"), 0), + ), + following_count=max( + _parse_int(legacy.get("friends_count"), 0), + _parse_int(rel_counts.get("following"), 0), + ), + tweets_count=max( + _parse_int(legacy.get("statuses_count"), 0), + _parse_int(tweet_counts.get("tweets"), 0), + ), + likes_count=max( + _parse_int(legacy.get("favourites_count"), 0), + _parse_int(action_counts.get("favorites_count"), 0), + ), + verified=bool( + user_data.get("is_blue_verified", False) + or legacy.get("verified", False) + or verification.get("verified", False) + ), profile_image_url=avatar.get("image_url") or legacy.get("profile_image_url_https", ""), created_at=core.get("created_at") or legacy.get("created_at", ""), + viewer_following=viewer_following, + viewer_followed_by=viewer_followed_by, ) @@ -484,6 +665,13 @@ def parse_tweet_result(result, depth=0): quoted_tweet=quoted_tweet, lang=actual_legacy.get("lang", ""), is_subscriber_only=(is_subscriber_only or retweet_subscriber_only) if is_retweet else is_subscriber_only, + possibly_sensitive=bool( + actual_legacy.get("possibly_sensitive") or actual_legacy.get("possiblySensitive") + ), + conversation_id=_opt_str(actual_legacy.get("conversation_id_str")), + in_reply_to_status_id=_opt_str(actual_legacy.get("in_reply_to_status_id_str")), + in_reply_to_user_id=_opt_str(actual_legacy.get("in_reply_to_user_id_str")), + in_reply_to_screen_name=_opt_str(actual_legacy.get("in_reply_to_screen_name")), **_parse_article(actual_data), ) diff --git a/twitter_cli/serialization.py b/twitter_cli/serialization.py index 25ceede..eae4d89 100644 --- a/twitter_cli/serialization.py +++ b/twitter_cli/serialization.py @@ -9,18 +9,46 @@ from .timeutil import format_iso8601, format_local_time +def _media_to_dict(media: TweetMedia) -> Dict[str, Any]: + """Convert a TweetMedia dataclass into a JSON-safe dict.""" + item: Dict[str, Any] = { + "type": media.type, + "url": media.url, + "width": media.width, + "height": media.height, + "adultContent": media.adult_content, + "graphicViolence": media.graphic_violence, + "otherWarning": media.other_warning, + } + if media.poster_url is not None: + item["posterUrl"] = media.poster_url + if media.alt_text is not None: + item["altText"] = media.alt_text + if media.duration_ms is not None: + item["durationMs"] = media.duration_ms + return item + + def tweet_to_dict(tweet: Tweet) -> Dict[str, Any]: """Convert a Tweet dataclass into a JSON-safe dict.""" - data = { + author_dict: Dict[str, Any] = { + "id": tweet.author.id, + "name": tweet.author.name, + "screenName": tweet.author.screen_name, + "profileImageUrl": tweet.author.profile_image_url, + "verified": tweet.author.verified, + "followers": tweet.author.followers_count, + "following": tweet.author.following_count, + } + if tweet.author.viewer_following is not None: + author_dict["viewerFollowing"] = tweet.author.viewer_following + if tweet.author.viewer_followed_by is not None: + author_dict["viewerFollowedBy"] = tweet.author.viewer_followed_by + + data: Dict[str, Any] = { "id": tweet.id, "text": tweet.text, - "author": { - "id": tweet.author.id, - "name": tweet.author.name, - "screenName": tweet.author.screen_name, - "profileImageUrl": tweet.author.profile_image_url, - "verified": tweet.author.verified, - }, + "author": author_dict, "metrics": { "likes": tweet.metrics.likes, "retweets": tweet.metrics.retweets, @@ -32,15 +60,7 @@ def tweet_to_dict(tweet: Tweet) -> Dict[str, Any]: "createdAt": tweet.created_at, "createdAtLocal": format_local_time(tweet.created_at), "createdAtISO": format_iso8601(tweet.created_at), - "media": [ - { - "type": media.type, - "url": media.url, - "width": media.width, - "height": media.height, - } - for media in tweet.media - ], + "media": [_media_to_dict(media) for media in tweet.media], "urls": list(tweet.urls), "isRetweet": tweet.is_retweet, "retweetedBy": tweet.retweeted_by, @@ -48,7 +68,16 @@ def tweet_to_dict(tweet: Tweet) -> Dict[str, Any]: "score": tweet.score, "isSubscriberOnly": tweet.is_subscriber_only, "isPromoted": tweet.is_promoted, + "possiblySensitive": tweet.possibly_sensitive, } + if tweet.conversation_id is not None: + data["conversationId"] = tweet.conversation_id + if tweet.in_reply_to_status_id is not None: + data["inReplyToStatusId"] = tweet.in_reply_to_status_id + if tweet.in_reply_to_user_id is not None: + data["inReplyToUserId"] = tweet.in_reply_to_user_id + if tweet.in_reply_to_screen_name is not None: + data["inReplyToScreenName"] = tweet.in_reply_to_screen_name if tweet.article_title is not None: data["articleTitle"] = tweet.article_title if tweet.article_text is not None: @@ -61,6 +90,7 @@ def tweet_to_dict(tweet: Tweet) -> Dict[str, Any]: "screenName": tweet.quoted_tweet.author.screen_name, "name": tweet.quoted_tweet.author.name, }, + "possiblySensitive": tweet.quoted_tweet.possibly_sensitive, } return data @@ -85,6 +115,7 @@ def tweet_from_dict(data: Dict[str, Any]) -> Tweet: ), metrics=Metrics(), created_at="", + possibly_sensitive=bool(quoted_data.get("possiblySensitive", False)), ) return Tweet( @@ -96,6 +127,10 @@ def tweet_from_dict(data: Dict[str, Any]) -> Tweet: screen_name=str(author_data.get("screenName") or ""), profile_image_url=str(author_data.get("profileImageUrl") or ""), verified=bool(author_data.get("verified", False)), + followers_count=int(author_data.get("followers") or 0), + following_count=int(author_data.get("following") or 0), + viewer_following=_optional_bool(author_data.get("viewerFollowing")), + viewer_followed_by=_optional_bool(author_data.get("viewerFollowedBy")), ), metrics=Metrics( likes=int(metrics_data.get("likes") or 0), @@ -112,6 +147,12 @@ def tweet_from_dict(data: Dict[str, Any]) -> Tweet: url=str(item.get("url") or ""), width=_optional_int(item.get("width")), height=_optional_int(item.get("height")), + adult_content=bool(item.get("adultContent", False)), + graphic_violence=bool(item.get("graphicViolence", False)), + other_warning=bool(item.get("otherWarning", False)), + poster_url=_optional_str(item.get("posterUrl")), + alt_text=_optional_str(item.get("altText")), + duration_ms=_optional_int(item.get("durationMs")), ) for item in media_data if isinstance(item, dict) @@ -126,6 +167,11 @@ def tweet_from_dict(data: Dict[str, Any]) -> Tweet: article_text=_optional_str(data.get("articleText")), is_subscriber_only=bool(data.get("isSubscriberOnly", False)), is_promoted=bool(data.get("isPromoted", False)), + possibly_sensitive=bool(data.get("possiblySensitive", False)), + conversation_id=_optional_str(data.get("conversationId")), + in_reply_to_status_id=_optional_str(data.get("inReplyToStatusId")), + in_reply_to_user_id=_optional_str(data.get("inReplyToUserId")), + in_reply_to_screen_name=_optional_str(data.get("inReplyToScreenName")), ) @@ -194,7 +240,7 @@ def bookmark_folders_to_data(folders: Iterable[BookmarkFolder]) -> List[Dict[str def user_profile_to_dict(user: UserProfile) -> Dict[str, Any]: """Convert a UserProfile dataclass into a JSON-safe dict.""" - return { + data: Dict[str, Any] = { "id": user.id, "name": user.name, "screenName": user.screen_name, @@ -210,6 +256,11 @@ def user_profile_to_dict(user: UserProfile) -> Dict[str, Any]: "createdAt": user.created_at, "createdAtISO": format_iso8601(user.created_at), } + if user.viewer_following is not None: + data["viewerFollowing"] = user.viewer_following + if user.viewer_followed_by is not None: + data["viewerFollowedBy"] = user.viewer_followed_by + return data def users_to_json(users: Iterable[UserProfile]) -> str: @@ -242,3 +293,10 @@ def _optional_str(value: Any) -> Optional[str]: return None text = str(value) return text if text else None + + +def _optional_bool(value: Any) -> Optional[bool]: + """Parse an optional boolean value.""" + if isinstance(value, bool): + return value + return None From a9c098fcd0d3f263d0d94afe4a8733cefe046d63 Mon Sep 17 00:00:00 2001 From: jackwener Date: Fri, 27 Nov 2026 18:24:02 +0000 Subject: [PATCH 5/8] feat(cli,config): pagination cap, --time, shell completion, user config, news, and doctor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Raise user-list pagination safety ceiling to 10000 and honour explicit --max on followers/following instead of clamping to rateLimit.maxCount (closes #50) - Resolve ~/.twitter-cli/config.yaml between cwd and package defaults - Add root --time relative|absolute|iso option and display.time config (closes #35) - Add `twitter completion bash|zsh|fish` using Click shell completion (closes #36) - Add `twitter news` command for Explore > News stories (closes #47) - Add `twitter doctor [--refresh]` diagnostic command (never leaks secrets) - Normalize tweet URLs consistently across like/retweet/bookmark/delete Absorbs #63, #104, and config/doctor/normalization practices from quangdang46/twitter_cli. Closes #35, #36, #47, #50. Co-authored-by: axsddlr Co-authored-by: Ankit Ranjan Co-authored-by: Trần Quang Đãng <91641923+quangdang46@users.noreply.github.com> --- config.yaml | 5 +- tests/test_cli.py | 70 +++++++++++ tests/test_client.py | 87 +++++++++++++ tests/test_completion.py | 47 +++++++ tests/test_config.py | 17 +++ tests/test_pagination_cap.py | 92 ++++++++++++++ tests/test_time_style.py | 95 ++++++++++++++ twitter_cli/cli.py | 205 +++++++++++++++++++++++++++++- twitter_cli/client.py | 206 ++++++++++++++++++++++++++++++- twitter_cli/commands/__init__.py | 3 +- twitter_cli/config.py | 13 ++ twitter_cli/formatter.py | 43 ++++++- twitter_cli/graphql.py | 2 + 13 files changed, 869 insertions(+), 16 deletions(-) create mode 100644 tests/test_completion.py create mode 100644 tests/test_pagination_cap.py create mode 100644 tests/test_time_style.py diff --git a/config.yaml b/config.yaml index 0a62952..686ec95 100644 --- a/config.yaml +++ b/config.yaml @@ -1,6 +1,9 @@ fetch: count: 50 +display: + time: relative # relative | absolute | iso (overridable with --time) + filter: mode: "topN" topN: 20 @@ -18,4 +21,4 @@ rateLimit: requestDelay: 1.5 # seconds between paginated requests maxRetries: 3 # retry count on 429 / rate-limit errors retryBaseDelay: 5.0 # base delay for exponential backoff (seconds) - maxCount: 200 # hard cap for single fetch + maxCount: 200 # default cap for a single fetch; explicit --max on user lists may exceed it diff --git a/tests/test_cli.py b/tests/test_cli.py index 4530329..7b25f9c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -947,3 +947,73 @@ def fetch_bookmarks(self, count: int, cursor=None, return_cursor=False): assert payload["data"][0]["id"] == "77" assert payload["pagination"]["nextCursor"] == "bm-cursor-2" assert captured == {"cursor": "bm-cursor-1", "return_cursor": True} + + +def test_cli_news_json(monkeypatch) -> None: + captured = {} + + class FakeClient: + def fetch_explore_news(self, count: int): + captured["count"] = count + return [ + { + "rank": 1, + "title": "Major AI story", + "context": "Trending now · News · 105 posts", + "post_count": 105, + "url": "https://x.com/i/trending/123", + } + ] + + monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient()) + monkeypatch.setattr( + "twitter_cli.cli.load_config", + lambda: {"fetch": {"count": 50}, "filter": {}, "rateLimit": {}}, + ) + runner = CliRunner() + + result = runner.invoke(cli, ["news", "--max", "5", "--json"]) + + assert result.exit_code == 0, result.output + payload = json.loads(result.output) + assert payload["ok"] is True + assert payload["data"][0]["title"] == "Major AI story" + assert captured == {"count": 5} + + +def test_cli_doctor_json_never_leaks_secrets(monkeypatch, tmp_path) -> None: + monkeypatch.setenv("TWITTER_AUTH_TOKEN", "super-secret-auth-token") + monkeypatch.setenv("TWITTER_CT0", "super-secret-ct0") + monkeypatch.setattr("twitter_cli.cli._qid_cache_path", lambda: tmp_path / "missing.json") + monkeypatch.setattr( + "twitter_cli.cli.TwitterClient._ct_cache_path", + staticmethod(lambda: str(tmp_path / "missing_ct.json")), + ) + runner = CliRunner() + + result = runner.invoke(cli, ["doctor", "--json"]) + + assert result.exit_code == 0, result.output + assert "super-secret-auth-token" not in result.output + assert "super-secret-ct0" not in result.output + payload = json.loads(result.output) + assert payload["ok"] is True + categories = {c["category"] for c in payload["data"]["checks"]} + assert {"deps", "config", "auth", "tx_cache", "query_ids"}.issubset(categories) + + +def test_cli_like_accepts_full_tweet_url(monkeypatch) -> None: + called = [] + + class FakeClient: + def like_tweet(self, tweet_id: str): + called.append(tweet_id) + return True + + monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient()) + runner = CliRunner() + + result = runner.invoke(cli, ["like", "https://x.com/alice/status/987654321", "--json"]) + + assert result.exit_code == 0, result.output + assert called == ["987654321"] diff --git a/tests/test_client.py b/tests/test_client.py index a1c6269..39a389f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1895,3 +1895,90 @@ def mock_get(operation_name, variables, features, field_toggles=None): assert calls[0][1]["userId"] == "44196397" assert profile.screen_name == "elonmusk" assert profile.followers_count == 1000 + + +class TestFetchExploreNews: + def test_fetch_explore_news_uses_news_timeline_id(self): + client = TwitterClient.__new__(TwitterClient) + client._max_count = 200 + calls = [] + + def mock_graphql_get(operation_name, variables, features, field_toggles=None): + calls.append((operation_name, variables)) + if operation_name == "ExplorePage": + return { + "data": { + "explore_page": { + "body": { + "timelines": [ + {"id": "for_you", "timeline": {"id": "for-you-id"}}, + {"id": "news", "timeline": {"id": "news-id"}}, + ] + } + } + } + } + if operation_name == "GenericTimelineById": + assert variables["timelineId"] == "news-id" + return { + "data": { + "timeline": { + "timeline": { + "instructions": [ + { + "type": "TimelineAddEntries", + "entries": [ + { + "entryId": "stories", + "content": { + "entryType": "TimelineTimelineModule", + "items": [ + { + "item": { + "itemContent": { + "__typename": "TimelineTrend", + "is_ai_trend": True, + "name": "Major AI story", + "social_context": { + "text": "Trending now · News · 26K posts" + }, + "trend_metadata": { + "url": { + "url": "twitter://trending/123", + "urlType": "DeepLink", + } + }, + } + } + } + ], + }, + } + ], + } + ] + } + } + } + } + raise AssertionError(operation_name) + + client._graphql_get = mock_graphql_get + stories = client.fetch_explore_news(count=5) + + assert [c[0] for c in calls] == ["ExplorePage", "GenericTimelineById"] + assert stories == [ + { + "rank": 1, + "title": "Major AI story", + "name": "Major AI story", + "category": "", + "context": "Trending now · News · 26K posts", + "query": "Major AI story", + "url": "https://x.com/i/trending/123", + "post_count": 26000, + "trend_id": "123", + "is_ai_trend": True, + "type": "TimelineTrend", + } + ] diff --git a/tests/test_completion.py b/tests/test_completion.py new file mode 100644 index 0000000..c8b358b --- /dev/null +++ b/tests/test_completion.py @@ -0,0 +1,47 @@ +"""Shell completion script generation (issue #36).""" + +from __future__ import annotations + +import pytest +from click.testing import CliRunner + +from twitter_cli.cli import cli + + +def _run(*args: str): + return CliRunner().invoke(cli, list(args)) + + +@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"]) +def test_completion_script_is_emitted(shell: str) -> None: + result = _run("completion", shell) + + assert result.exit_code == 0, result.output + script = result.output + assert len(script) > 100 + assert "twitter" in script + + +def test_bash_script_defines_completion_function() -> None: + result = _run("completion", "bash") + assert result.exit_code == 0 + assert "_twitter_completion" in result.output + assert "complete" in result.output + + +def test_zsh_script_is_a_compdef() -> None: + result = _run("completion", "zsh") + assert result.exit_code == 0 + assert result.output.lstrip().startswith("#compdef") + assert "_TWITTER_COMPLETE" in result.output + + +def test_fish_script_defines_function() -> None: + result = _run("completion", "fish") + assert result.exit_code == 0 + assert "function" in result.output + + +def test_unknown_shell_is_rejected() -> None: + result = _run("completion", "powershell") + assert result.exit_code != 0 diff --git a/tests/test_config.py b/tests/test_config.py index 7ab1f3f..1370e89 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -41,3 +41,20 @@ def test_load_config_does_not_mutate_defaults(tmp_path: Path) -> None: config = load_config(str(tmp_path / "missing-config.yaml")) config["filter"]["weights"]["likes"] = 999 assert DEFAULT_CONFIG["filter"]["weights"]["likes"] == 1.0 + + +def test_resolve_config_path_checks_user_home_dir(monkeypatch, tmp_path: Path) -> None: + from twitter_cli import config as config_mod + + user_cfg = tmp_path / ".twitter-cli" / "config.yaml" + user_cfg.parent.mkdir(parents=True) + user_cfg.write_text("display:\n time: absolute\n", encoding="utf-8") + + empty_cwd = tmp_path / "cwd" + empty_cwd.mkdir() + monkeypatch.chdir(empty_cwd) + monkeypatch.setattr(Path, "home", staticmethod(lambda: tmp_path)) + + assert config_mod._resolve_config_path(None) == user_cfg + loaded = load_config() + assert loaded["display"]["time"] == "absolute" diff --git a/tests/test_pagination_cap.py b/tests/test_pagination_cap.py new file mode 100644 index 0000000..185a25b --- /dev/null +++ b/tests/test_pagination_cap.py @@ -0,0 +1,92 @@ +"""Followers/following pagination honours explicit --max (issue #50).""" + +from __future__ import annotations + +from types import SimpleNamespace + +from twitter_cli import client as client_mod +from twitter_cli.client import _ABSOLUTE_MAX_COUNT, TwitterClient + + +class _StubClient(TwitterClient): + def __init__(self): + self._auth_token = "t" + self._ct0 = "c" + self._cookie_string = None + self._client_transaction = None + self._ct_init_attempted = True + self._max_count = 200 + self._request_delay = 0.0 + self._max_retries = 0 + self.pages_requested = 0 + + +def _instructions(user_ids, cursor=None): + entries = [ + { + "content": { + "entryType": "TimelineTimelineItem", + "itemContent": {"user_results": {"result": {"rest_id": uid}}}, + } + } + for uid in user_ids + ] + if cursor: + entries.append( + { + "content": { + "entryType": "TimelineTimelineCursor", + "cursorType": "Bottom", + "value": cursor, + } + } + ) + return [{"entries": entries}] + + +def _make_paged_client(monkeypatch, page_size=20, total_pages=40): + stub = _StubClient() + state = {"page": 0} + + def fake_graphql(operation_name, variables, features, field_toggles=None): + index = state["page"] + state["page"] += 1 + stub.pages_requested += 1 + ids = ["u%d" % (index * page_size + i) for i in range(page_size)] + has_more = index + 1 < total_pages + return { + "instructions": _instructions( + ids, cursor="cursor-%d" % (index + 1) if has_more else None + ) + } + + monkeypatch.setattr(stub, "_graphql_get", fake_graphql) + monkeypatch.setattr(stub, "_graphql_post", fake_graphql) + monkeypatch.setattr( + client_mod, + "parse_user_result", + lambda result: SimpleNamespace(id=result.get("rest_id")) if result.get("rest_id") else None, + ) + return stub + + +def test_explicit_max_beyond_old_500_cap_is_fetched(monkeypatch) -> None: + stub = _make_paged_client(monkeypatch, page_size=20, total_pages=40) + users = stub._fetch_user_list("Followers", "123", 600, lambda data: data.get("instructions")) + assert len(users) == 600 + assert stub.pages_requested >= 30 + + +def test_safety_ceiling_still_applies(monkeypatch, caplog) -> None: + stub = _StubClient() + monkeypatch.setattr(stub, "_graphql_get", lambda *a, **kw: {"instructions": _instructions(["u1"])}) + monkeypatch.setattr(client_mod, "parse_user_result", lambda r: SimpleNamespace(id="u1")) + + with caplog.at_level("WARNING"): + stub._fetch_user_list("Followers", "1", _ABSOLUTE_MAX_COUNT + 5000, lambda d: d["instructions"]) + + assert "exceeds the safety ceiling" in caplog.text + + +def test_ceiling_is_large_enough_for_real_accounts() -> None: + assert _ABSOLUTE_MAX_COUNT >= 5000 diff --git a/tests/test_time_style.py b/tests/test_time_style.py new file mode 100644 index 0000000..8646fd3 --- /dev/null +++ b/tests/test_time_style.py @@ -0,0 +1,95 @@ +"""Timestamp display style (issue #35).""" + +from __future__ import annotations + +import pytest +from rich.console import Console + +from twitter_cli import formatter +from twitter_cli.formatter import ( + get_time_style, + print_tweet_detail, + print_tweet_table, + set_time_style, +) +from twitter_cli.models import Author, Metrics, Tweet + +CREATED_AT = "Sat Mar 14 21:08:00 +0000 2026" + + +def _tweet() -> Tweet: + return Tweet( + id="1", + text="hello world", + author=Author(id="u1", name="Alice", screen_name="alice"), + metrics=Metrics(likes=1, retweets=0, replies=0, quotes=0, views=10, bookmarks=0), + created_at=CREATED_AT, + ) + + +def _render(printer) -> str: + console = Console(record=True, width=120, file=None) + printer(console) + return console.export_text() + + +@pytest.fixture(autouse=True) +def _restore_style(): + original = get_time_style() + yield + formatter.set_time_style(original) + + +def test_relative_style_renders_ago() -> None: + set_time_style("relative") + text = _render(lambda c: print_tweet_table([_tweet()], console=c)) + assert "ago" in text + + +def test_absolute_style_renders_datetime() -> None: + set_time_style("absolute") + text = _render(lambda c: print_tweet_table([_tweet()], console=c)) + assert "ago" not in text + assert ":" in text + + +def test_iso_style_renders_iso8601() -> None: + set_time_style("iso") + text = _render(lambda c: print_tweet_table([_tweet()], console=c)) + assert "2026-03-14T" in text + assert "ago" not in text + + +def test_detail_view_does_not_repeat_stamp_under_absolute() -> None: + set_time_style("absolute") + text = _render(lambda c: print_tweet_detail(_tweet(), console=c)) + assert "ago" not in text + assert "2026-03-" in text + + +def test_invalid_style_is_ignored() -> None: + set_time_style("iso") + assert set_time_style("bogus") == "iso" + assert get_time_style() == "iso" + + +def test_cli_option_and_config_set_time_style(monkeypatch) -> None: + from click.testing import CliRunner + from twitter_cli import cli as cli_module + from twitter_cli.cli import cli + + set_time_style("relative") + result = CliRunner().invoke(cli, ["--time", "absolute", "post"]) + assert result.exit_code != 0 + assert get_time_style() == "absolute" + + fake = { + "fetch": {"count": 50}, + "display": {"time": "iso"}, + "filter": {"mode": "topN", "topN": 20, "minScore": 50, "lang": [], "excludeRetweets": False}, + "rateLimit": {"requestDelay": 0, "maxRetries": 0, "retryBaseDelay": 0, "maxCount": 200}, + } + monkeypatch.setattr(cli_module, "load_config", lambda: fake) + set_time_style("relative") + CliRunner().invoke(cli, ["post"]) + assert get_time_style() == "iso" diff --git a/twitter_cli/cli.py b/twitter_cli/cli.py index c53c783..7d3490d 100644 --- a/twitter_cli/cli.py +++ b/twitter_cli/cli.py @@ -42,15 +42,17 @@ from typing import Any, Callable, Dict, List, Optional import click +from click.shell_completion import get_completion_class from rich.console import Console +from rich.table import Table import yaml from . import __version__ -from .auth import get_cookies +from .auth import get_cookies, load_from_env from .cache import resolve_cached_tweet, save_tweet_cache from .exceptions import TwitterError -from .client import TwitterClient -from .config import load_config +from .client import TwitterClient, _url_fetch +from .config import _resolve_config_path, load_config from .filter import filter_tweets from .formatter import ( article_to_markdown, @@ -60,7 +62,9 @@ print_tweet_table, print_user_profile, print_user_table, + set_time_style, ) +from .graphql import FALLBACK_QUERY_IDS, _qid_cache_path, refresh_query_ids from .models import Tweet, UserProfile from .output import ( default_structured_format, @@ -96,6 +100,7 @@ SEARCH_PRODUCTS = ["Top", "Latest", "Photos", "Videos"] SEARCH_HAS_CHOICES = ["links", "images", "videos", "media"] SEARCH_EXCLUDE_CHOICES = ["retweets", "replies", "links"] +_COMPLETION_SHELLS = ("bash", "zsh", "fish") def _agent_user_profile(profile: UserProfile) -> dict: @@ -294,15 +299,28 @@ def _run_write_command( @click.group() @click.option("--verbose", "-v", is_flag=True, help="Enable debug logging.") @click.option("--compact", "-c", is_flag=True, help="Compact output (minimal fields, LLM-friendly).") +@click.option( + "--time", + "time_style", + type=click.Choice(["relative", "absolute", "iso"]), + default=None, + help=( + "Timestamp style in human-readable output: relative (14d ago), " + "absolute (local datetime), or iso. Defaults to config display.time." + ), +) @click.version_option(version=__version__) @click.pass_context -def cli(ctx, verbose, compact): - # type: (Any, bool, bool) -> None +def cli(ctx, verbose, compact, time_style): + # type: (Any, bool, bool, Optional[str]) -> None """twitter — Twitter/X CLI tool 🐦""" ensure_utf8_streams() _setup_logging(verbose) ctx.ensure_object(dict) ctx.obj["compact"] = compact + if time_style is None: + time_style = (load_config().get("display") or {}).get("time") + set_time_style(time_style) def _fetch_and_display(fetch_fn, label, emoji, max_count, as_json, as_yaml, output_file, do_filter, config=None, compact=False, full_text=False): @@ -349,6 +367,27 @@ def _fetch_and_display(fetch_fn, label, emoji, max_count, as_json, as_yaml, outp console.print() +def _print_news_table(stories, title="News stories"): + # type: (List[dict], str) -> None + """Print Explore News stories in a compact table.""" + table = Table(title=title, show_lines=False) + table.add_column("#", justify="right", style="dim", width=4) + table.add_column("Story", style="bold", overflow="fold") + table.add_column("Context", overflow="fold") + table.add_column("Posts", justify="right") + + for story in stories: + count = story.get("post_count") + table.add_row( + str(story.get("rank", "")), + str(story.get("title", "")), + str(story.get("context", "") or story.get("category", "") or ""), + f"{count:,}" if isinstance(count, int) and count > 0 else "", + ) + console.print(table) + console.print() + + def _emit_timeline_structured(tweets, next_cursor, *, as_json, as_yaml): # type: (TweetList, Optional[str], bool, bool) -> bool """Emit timeline data with pagination metadata while keeping `data` a tweet list.""" @@ -1190,6 +1229,7 @@ def _write_action(emoji, action_desc, client_method, tweet_id, as_json=False, as Emits structured JSON/YAML when piped or when OUTPUT env is set. """ + tweet_id = _normalize_tweet_id(tweet_id) action_name = action_desc.lower().replace(" ", "_") def operation(client: TwitterClient) -> WritePayload: @@ -1485,5 +1525,160 @@ def unbookmark(tweet_id, as_json, as_yaml): +@cli.command(name="news") +@click.option("--max", "-n", "max_count", type=int, default=20, show_default=True, help="Max stories to return.") +@structured_output_options +def news(max_count, as_json, as_yaml): + # type: (int, bool, bool) -> None + """Fetch personalized stories from Explore > News.""" + config = load_config() + + def _run(): + rich_output = use_rich_output(as_json=as_json, as_yaml=as_yaml) + client = _get_client(config, quiet=not rich_output) + if rich_output: + console.print("🗞️ Fetching Explore > News stories...\n") + stories = client.fetch_explore_news(count=max_count) + + if emit_structured(stories, as_json=as_json, as_yaml=as_yaml): + return + + _print_news_table(stories, title="🗞️ Explore News — %d stories" % len(stories)) + + _run_guarded(_run) + + +@cli.command(name="completion") +@click.argument("shell", type=click.Choice(sorted(_COMPLETION_SHELLS))) +def completion(shell): + # type: (str) -> None + """Print a shell completion script for SHELL. + + \b + bash: twitter completion bash >> ~/.bashrc + zsh: twitter completion zsh > "${fpath[1]}/_twitter" + fish: twitter completion fish > ~/.config/fish/completions/twitter.fish + """ + completion_cls = get_completion_class(shell) + if completion_cls is None: # pragma: no cover - guarded by Choice + raise click.ClickException("Shell completion is not supported for %r" % shell) + click.echo(completion_cls(cli, {}, "twitter", "_TWITTER_COMPLETE").source()) + + +@cli.command(name="doctor") +@click.option("--refresh", is_flag=True, help="Refresh cached GraphQL query IDs from live sources.") +@structured_output_options +def doctor(refresh, as_json, as_yaml): + # type: (bool, bool, bool) -> None + """Run local diagnostics for dependencies, config, auth presence, and caches. + + Never prints raw cookies or secrets. + """ + checks = [] # type: List[Dict[str, Any]] + + # 1. Dependency versions + try: + import curl_cffi + curl_ver = getattr(curl_cffi, "__version__", "unknown") + except Exception: + curl_ver = "missing" + try: + from importlib.metadata import version as _pkg_version + xct_ver = _pkg_version("xclienttransaction") + except Exception: + xct_ver = "unknown" + checks.append({ + "category": "deps", + "status": "pass" if curl_ver != "missing" else "error", + "message": "curl_cffi=%s, xclienttransaction=%s" % (curl_ver, xct_ver), + }) + + # 2. Config resolution + resolved_cfg = _resolve_config_path(None) + checks.append({ + "category": "config", + "status": "pass", + "message": str(resolved_cfg) if resolved_cfg else "built-in defaults", + }) + + # 3. Auth presence (metadata only — never reveal cookie values) + env_cookies = load_from_env() + if env_cookies: + source = "env:cookie_string" if env_cookies.get("cookie_string") else "env:tokens" + checks.append({ + "category": "auth", + "status": "pass", + "message": "Credentials present (%s)" % source, + }) + else: + checks.append({ + "category": "auth", + "status": "warning", + "message": "No env credentials set; commands will attempt browser cookie extraction", + }) + + # 4. Transaction cache status + ct_path = Path(TwitterClient._ct_cache_path()) + if ct_path.exists(): + try: + ct_payload = json.loads(ct_path.read_text(encoding="utf-8")) + age_s = int(time.time() - float(ct_payload.get("created_at", 0))) + fresh = age_s <= 3600 + checks.append({ + "category": "tx_cache", + "status": "pass" if fresh else "warning", + "message": "Transaction cache %s (age=%ds)" % ("fresh" if fresh else "expired", age_s), + }) + except Exception as exc: + checks.append({ + "category": "tx_cache", + "status": "warning", + "message": "Transaction cache unreadable: %s" % exc, + }) + else: + checks.append({ + "category": "tx_cache", + "status": "warning", + "message": "Transaction cache not initialized yet", + }) + + # 5. Query IDs cache / live refresh + qid_path = _qid_cache_path() + if refresh: + refreshed = refresh_query_ids(_url_fetch) + checks.append({ + "category": "query_ids", + "status": "pass" if refreshed else "warning", + "message": "Refreshed %d live queryIds (fallback baseline: %d)" % ( + len(refreshed), len(FALLBACK_QUERY_IDS) + ), + }) + else: + cached_count = 0 + if qid_path.exists(): + try: + cached_count = len(json.loads(qid_path.read_text(encoding="utf-8")).get("query_ids", {})) + except Exception: + cached_count = 0 + checks.append({ + "category": "query_ids", + "status": "pass", + "message": "Fallback baseline=%d, disk cache=%d" % (len(FALLBACK_QUERY_IDS), cached_count), + }) + + if emit_structured({"checks": checks}, as_json=as_json, as_yaml=as_yaml): + return + + table = Table(title="🩺 twitter-cli doctor") + table.add_column("Check", style="cyan") + table.add_column("Status", style="bold") + table.add_column("Details") + for item in checks: + icon = "✅" if item["status"] == "pass" else ("⚠️" if item["status"] == "warning" else "❌") + table.add_row(item["category"], "%s %s" % (icon, item["status"]), item["message"]) + console.print(table) + console.print() + + if __name__ == "__main__": cli() diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 6860e29..ce4fad2 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -9,6 +9,7 @@ import mimetypes import os import random +import re import time import urllib.parse from pathlib import Path @@ -70,8 +71,9 @@ TimelineInstructionGetter = Callable[[Any], Any] -# Hard ceiling to prevent accidental massive fetches -_ABSOLUTE_MAX_COUNT = 500 +# Hard safety ceiling to prevent runaway fetches; explicit --max on user lists +# is honoured up to here (issue #50). +_ABSOLUTE_MAX_COUNT = 10000 # ── Session management ─────────────────────────────────────────────────── @@ -151,6 +153,159 @@ def _is_stale_query_error(exc): ) +def _coerce_string(value): + # type: (Any) -> str + if isinstance(value, str): + return value.strip() + return "" + + +def _first_text(*values): + # type: (*Any) -> str + for value in values: + text = _coerce_string(value) + if text: + return text + return "" + + +def _extract_post_count(text): + # type: (str) -> Optional[int] + match = re.search(r"([\d,.]+)\s*([KMB])?\s+(?:posts?|tweets?)", text or "", re.IGNORECASE) + if not match: + return None + raw = match.group(1).replace(",", "").strip() + try: + numeric = float(raw) + except ValueError: + return None + suffix = (match.group(2) or "").upper() + if suffix == "K": + numeric *= 1_000 + elif suffix == "M": + numeric *= 1_000_000 + elif suffix == "B": + numeric *= 1_000_000_000 + return int(round(numeric)) + + +def _twitter_deeplink_to_url(url): + # type: (Optional[str]) -> Optional[str] + if not url: + return None + if url.startswith(("https://", "http://")): + return url + if url.startswith("twitter://trending/"): + trend_id = url.rsplit("/", 1)[-1] + return "https://x.com/i/trending/%s" % urllib.parse.quote(trend_id) + if url.startswith("twitter://search/"): + parsed = urllib.parse.urlparse(url) + query = urllib.parse.parse_qs(parsed.query) + raw_query = query.get("query", [""])[0] + if raw_query: + return "https://x.com/search?q=%s" % urllib.parse.quote(raw_query) + return "https://x.com/explore" + return url + + +def _extract_query_from_url(url): + # type: (Optional[str]) -> str + if not url: + return "" + parsed = urllib.parse.urlparse(url) + params = urllib.parse.parse_qs(parsed.query) + return _first_text(params.get("query", [""])[0], params.get("q", [""])[0]) + + +def _extract_trend_id(url): + # type: (Optional[str]) -> Optional[str] + if not url: + return None + match = re.search(r"(?:twitter://trending/|/i/trending/)(\d+)", url) + if match: + return match.group(1) + return None + + +def _normalize_explore_story(raw, rank): + # type: (Any, int) -> Optional[Dict[str, Any]] + if not isinstance(raw, dict): + return None + + typename = raw.get("__typename") or raw.get("itemType") or "" + metadata = raw.get("trend_metadata") or {} + social_context = raw.get("social_context") or {} + url_obj = metadata.get("url") or raw.get("trend_url") or raw.get("url") or {} + raw_url = url_obj.get("url") if isinstance(url_obj, dict) else _coerce_string(url_obj) + + title = _first_text( + raw.get("name"), + raw.get("title"), + raw.get("headline"), + raw.get("display_text"), + raw.get("text"), + _deep_get(raw, "content", "title"), + ) + if not title: + return None + + context = _first_text( + social_context.get("text"), + metadata.get("domain_context"), + raw.get("context"), + raw.get("description"), + ) + category = _first_text(metadata.get("domain_context")) + + return { + "rank": rank, + "title": title, + "name": title, + "category": category, + "context": context, + "query": _extract_query_from_url(raw_url) or title, + "url": _twitter_deeplink_to_url(raw_url), + "post_count": _extract_post_count(context), + "trend_id": _extract_trend_id(raw_url), + "is_ai_trend": bool(raw.get("is_ai_trend")), + "type": typename, + } + + +def _extract_explore_item_contents(instructions): + # type: (Any) -> List[Dict[str, Any]] + items = [] # type: List[Dict[str, Any]] + for instruction in instructions or []: + for entry in instruction.get("entries", []) or []: + content = entry.get("content", {}) or {} + item_content = content.get("itemContent") + if isinstance(item_content, dict): + items.append(item_content) + for module_item in content.get("items", []) or []: + module_content = _deep_get(module_item, "item", "itemContent") + if isinstance(module_content, dict): + items.append(module_content) + return items + + +def _normalize_explore_items(instructions, count=20): + # type: (Any, int) -> List[Dict[str, Any]] + stories = [] # type: List[Dict[str, Any]] + seen = set() + for raw in _extract_explore_item_contents(instructions): + story = _normalize_explore_story(raw, rank=len(stories) + 1) + if not story: + continue + key = (story.get("title"), story.get("url")) + if key in seen: + continue + seen.add(key) + stories.append(story) + if len(stories) >= count: + break + return stories + + # ── TwitterClient ──────────────────────────────────────────────────────── @@ -425,6 +580,39 @@ def fetch_search(self, query, count=20, product="Top"): use_post=True, ) + def fetch_explore_news(self, count=20): + # type: (int) -> List[Dict[str, Any]] + """Fetch personalized Explore > News story cards.""" + if count <= 0: + return [] + count = min(count, self._max_count) + + page = self._graphql_get( + "ExplorePage", + {"cursor": "", "context": "news"}, + FEATURES, + ) + timelines = _deep_get(page, "data", "explore_page", "body", "timelines") or [] + news_timeline_id = None + for timeline in timelines: + if timeline.get("id") == "news": + news_timeline_id = _deep_get(timeline, "timeline", "id") + break + if not news_timeline_id: + raise TwitterAPIError(0, "Explore News timeline was not found") + + data = self._graphql_get( + "GenericTimelineById", + { + "timelineId": news_timeline_id, + "count": min(count + 5, 40), + "withQuickPromoteEligibilityTweetFields": True, + }, + FEATURES, + ) + instructions = _deep_get(data, "data", "timeline", "timeline", "instructions") + return _normalize_explore_items(instructions, count=count) + def fetch_tweet_detail(self, tweet_id, count=20, cursor=None, return_cursor=False): # type: (str, int, Optional[str], bool) -> Any """Fetch a tweet and its conversation thread (replies). @@ -904,10 +1092,20 @@ def _fetch_timeline(self, operation_name, count, get_instructions, extra_variabl def _fetch_user_list(self, operation_name, user_id, count, get_instructions, use_post=False): # type: (str, str, int, Callable[[Any], Any], bool) -> List[UserProfile] - """Generic user list fetcher (for followers/following) with pagination.""" + """Generic user list fetcher (for followers/following) with pagination. + + Honours explicit ``count`` requests up to ``_ABSOLUTE_MAX_COUNT`` instead + of clamping to ``rateLimit.maxCount`` (issue #50). + """ if count <= 0: return [] - count = min(count, self._max_count) + if count > _ABSOLUTE_MAX_COUNT: + logger.warning( + "Requested %d users exceeds the safety ceiling; fetching %d", + count, + _ABSOLUTE_MAX_COUNT, + ) + count = _ABSOLUTE_MAX_COUNT users = [] # type: List[UserProfile] seen_ids = set() # type: Set[str] cursor = None # type: Optional[str] diff --git a/twitter_cli/commands/__init__.py b/twitter_cli/commands/__init__.py index c6e8be2..2d447f6 100644 --- a/twitter_cli/commands/__init__.py +++ b/twitter_cli/commands/__init__.py @@ -1,7 +1,8 @@ """CLI command sub-modules for twitter-cli. Commands are split into three groups: - - read: feed, bookmarks, search, tweet, article, show, list, favorites + - read: feed, bookmarks, search, news, tweet, article, show, list, favorites - write: post, reply, quote, delete, like/unlike, retweet/unretweet, bookmark/unbookmark - user: user, user-posts, likes, followers, following, whoami, status, follow/unfollow + - util: completion, doctor """ diff --git a/twitter_cli/config.py b/twitter_cli/config.py index e57acb0..b8e70aa 100644 --- a/twitter_cli/config.py +++ b/twitter_cli/config.py @@ -16,6 +16,9 @@ "fetch": { "count": 50, }, + "display": { + "time": "relative", + }, "filter": { "mode": "topN", "topN": 20, @@ -74,6 +77,7 @@ def _resolve_config_path(config_path: Optional[str]) -> Optional[Path]: candidates = [ Path.cwd() / "config.yaml", + Path.home() / ".twitter-cli" / "config.yaml", Path(__file__).parent.parent / "config.yaml", ] for candidate in candidates: @@ -105,6 +109,15 @@ def _normalize_config(config: Dict[str, Any]) -> Dict[str, Any]: fetch["count"] = max(fetch_count, 1) merged["fetch"] = fetch + display = merged.get("display") + if not isinstance(display, dict): + display = {} + time_style = str(display.get("time", "relative")).strip().lower() + if time_style not in {"relative", "absolute", "iso"}: + time_style = "relative" + display["time"] = time_style + merged["display"] = display + filter_config = merged.get("filter") if not isinstance(filter_config, dict): filter_config = {} diff --git a/twitter_cli/formatter.py b/twitter_cli/formatter.py index 44564f0..1671d31 100644 --- a/twitter_cli/formatter.py +++ b/twitter_cli/formatter.py @@ -11,7 +11,36 @@ from rich.table import Table from .models import Tweet, UserProfile -from .timeutil import format_local_time, format_relative_time +from .timeutil import format_iso8601, format_local_time, format_relative_time + +# How timestamps are rendered in human-readable output (issue #35): +# relative -> "28s ago", "14d ago" +# absolute -> "2026-03-14 21:08" +# iso -> "2026-03-14T21:08:00+00:00" +_TIME_STYLES = ("relative", "absolute", "iso") +_TIME_STYLE = "relative" + + +def set_time_style(style: Optional[str]) -> str: + """Select the timestamp rendering style; returns the style in effect.""" + global _TIME_STYLE + if style and style in _TIME_STYLES: + _TIME_STYLE = style + return _TIME_STYLE + + +def get_time_style() -> str: + """Return the timestamp rendering style currently in effect.""" + return _TIME_STYLE + + +def _render_time(created_at: str) -> str: + """Render one timestamp according to the selected style.""" + if _TIME_STYLE == "absolute": + return format_local_time(created_at) + if _TIME_STYLE == "iso": + return format_iso8601(created_at) + return format_relative_time(created_at) def _make_console() -> Console: @@ -91,7 +120,7 @@ def print_tweet_table( text += "\n🔗 x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id) # Stats - rel_time = format_relative_time(tweet.created_at) + rel_time = _render_time(tweet.created_at) stats = ( "❤️ %s 🔄 %s\n💬 %s 👁️ %s\n🕐 %s" % ( @@ -155,10 +184,14 @@ def print_tweet_detail(tweet: Tweet, console: Optional[Console] = None) -> None: ) ) local_time = format_local_time(tweet.created_at) - rel_time = format_relative_time(tweet.created_at) + rel_time = _render_time(tweet.created_at) + if _TIME_STYLE == "relative": + time_text = "%s (%s)" % (local_time, rel_time) + else: + time_text = local_time if _TIME_STYLE == "absolute" else rel_time body_parts.append( - "🕐 %s (%s) · https://x.com/%s/status/%s" - % (local_time, rel_time, tweet.author.screen_name, tweet.id) + "🕐 %s · https://x.com/%s/status/%s" + % (time_text, tweet.author.screen_name, tweet.id) ) console.print(Panel( diff --git a/twitter_cli/graphql.py b/twitter_cli/graphql.py index 68f7c15..d153db1 100644 --- a/twitter_cli/graphql.py +++ b/twitter_cli/graphql.py @@ -42,6 +42,8 @@ "TweetDetail": "dQDdKtt882nl-Km98FJGSQ", "Likes": "ZjyvI1V9gajq5eclHCObzA", "SearchTimeline": "vLHjqbDv7TPFMBkIIO1nOA", + "ExplorePage": "CVExg1KY6Ec9BioRBbI8Jg", + "GenericTimelineById": "UToImY30uYcerTaw8gu21w", "Bookmarks": "fjf5b5Lu82lYMSBRhppK2g", "ListLatestTweetsTimeline": "UMc_lPEeKz_WiKSY8ZT7yw", "Followers": "Xe3y9_ndZ9-RtWz8zd_wpg", From 3ddca2dfc54a9d059c19bdacb2bf7eb467ee9570 Mon Sep 17 00:00:00 2001 From: jackwener Date: Fri, 27 Nov 2026 18:27:00 +0000 Subject: [PATCH 6/8] feat(write): video upload, Premium long-form CreateNoteTweet, and article-publish - Support chunked video upload (tweet_video, up to 512 MB, 4 MB APPEND chunks, async STATUS polling) and add --video / -V to post, reply, and quote (closes #13) - Add twitter-text v3 weighted character counting and automatic CreateNoteTweet routing for posts/quotes exceeding 280 weighted chars (closes #54) - Add `twitter article-publish --title ... [--draft]` with Markdown-to-Draft.js conversion Absorbs #60, #62, #64, #65, #96. Closes #13, #54. Co-authored-by: jollyroger1480 Co-authored-by: rakei076 Co-authored-by: hhh2210 --- tests/test_article.py | 53 +++++++++ tests/test_cli.py | 71 ++++++++++++ tests/test_client.py | 214 ++++++++++++++++++++++++++++++++++ tests/test_text.py | 40 +++++++ twitter_cli/article.py | 154 +++++++++++++++++++++++++ twitter_cli/cli.py | 84 +++++++++++--- twitter_cli/client.py | 253 ++++++++++++++++++++++++++++++++++------- twitter_cli/graphql.py | 34 +++++- twitter_cli/text.py | 153 +++++++++++++++++++++++++ 9 files changed, 1000 insertions(+), 56 deletions(-) create mode 100644 tests/test_article.py create mode 100644 tests/test_text.py create mode 100644 twitter_cli/article.py create mode 100644 twitter_cli/text.py diff --git a/tests/test_article.py b/tests/test_article.py new file mode 100644 index 0000000..735a670 --- /dev/null +++ b/tests/test_article.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import re + +from twitter_cli.article import article_markdown_to_content_state + + +def test_article_markdown_to_content_state_blocks_and_link_entity() -> None: + content_state = article_markdown_to_content_state( + "# Title\n\n" + "Paragraph with [docs](https://example.com) link.\n" + "- item\n" + "> quote\n" + "---\n" + "```python\n" + "print('hi')\n" + "```\n" + ) + + blocks = content_state["blocks"] + assert [block["type"] for block in blocks] == [ + "header-one", + "unstyled", + "unordered-list-item", + "blockquote", + "atomic", + "atomic", + ] + assert blocks[0]["text"] == "Title" + assert blocks[1]["text"] == "Paragraph with docs link." + + entities = content_state["entity_map"] + assert entities[0]["value"]["type"] == "LINK" + assert entities[0]["value"]["data"] == {"url": "https://example.com"} + assert blocks[1]["entity_ranges"] == [{"key": 0, "offset": 15, "length": 4}] + + assert entities[1]["value"]["type"] == "DIVIDER" + assert entities[2]["value"]["type"] == "MARKDOWN" + assert "print('hi')" in entities[2]["value"]["data"]["markdown"] + + +def test_article_markdown_to_content_state_empty_body_has_empty_block() -> None: + content_state = article_markdown_to_content_state("\n\n") + + assert content_state["entity_map"] == [] + assert len(content_state["blocks"]) == 1 + block = content_state["blocks"][0] + assert block["data"] == {} + assert block["text"] == "" + assert block["type"] == "unstyled" + assert block["entity_ranges"] == [] + assert block["inline_style_ranges"] == [] + assert re.fullmatch(r"[0-9a-f]{5}", block["key"]) diff --git a/tests/test_cli.py b/tests/test_cli.py index 7b25f9c..b830595 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1017,3 +1017,74 @@ def like_tweet(self, tweet_id: str): assert result.exit_code == 0, result.output assert called == ["987654321"] + + +def test_cli_post_with_video_and_mutually_exclusive_image(monkeypatch, tmp_path) -> None: + vid = tmp_path / "clip.mp4" + vid.write_bytes(b"\x00" * 64) + img = tmp_path / "pic.png" + img.write_bytes(b"\x89PNG") + uploaded = [] + + class FakeClient: + def upload_media(self, path: str) -> str: + uploaded.append(path) + return "media-vid-1" + + def create_tweet(self, text: str, reply_to_id=None, media_ids=None) -> str: + assert media_ids == ["media-vid-1"] + return "tweet-555" + + monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient()) + runner = CliRunner() + + ok_res = runner.invoke(cli, ["post", "Watch this", "--video", str(vid), "--json"]) + assert ok_res.exit_code == 0, ok_res.output + assert json.loads(ok_res.output)["data"]["id"] == "tweet-555" + assert uploaded == [str(vid)] + + bad_res = runner.invoke(cli, ["post", "Both", "-i", str(img), "-V", str(vid)]) + assert bad_res.exit_code != 0 + assert "not both" in bad_res.output + + +def test_cli_article_publish_json_and_draft_yaml(monkeypatch, tmp_path) -> None: + markdown_path = tmp_path / "article.md" + markdown_path.write_text("# Heading\n\nBody with [link](https://example.com).", encoding="utf-8") + captured = {} + + class FakeClient: + def create_article(self, title, content_state, publish=True): + captured["title"] = title + captured["content_state"] = content_state + captured["publish"] = publish + return { + "id": "article-1" if publish else "draft-1", + "title": title, + "url": ( + "https://x.com/i/article/article-1" + if publish + else "https://x.com/compose/article/edit/draft-1" + ), + "published": publish, + } + + monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient()) + runner = CliRunner() + + pub_res = runner.invoke( + cli, ["article-publish", str(markdown_path), "--title", "Article title", "--json"] + ) + assert pub_res.exit_code == 0, pub_res.output + payload = json.loads(pub_res.output[pub_res.output.index("{"):]) + assert payload["data"]["id"] == "article-1" + assert payload["data"]["published"] is True + assert captured["content_state"]["blocks"][0]["type"] == "header-one" + + draft_res = runner.invoke( + cli, ["article-publish", str(markdown_path), "--title", "Draft title", "--draft", "--yaml"] + ) + assert draft_res.exit_code == 0, draft_res.output + yaml_payload = yaml.safe_load(draft_res.output) + assert yaml_payload["data"]["id"] == "draft-1" + assert yaml_payload["data"]["published"] is False diff --git a/tests/test_client.py b/tests/test_client.py index 39a389f..4936315 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1982,3 +1982,217 @@ def mock_graphql_get(operation_name, variables, features, field_toggles=None): "type": "TimelineTrend", } ] + + +class TestCreateLongFormTweet: + @staticmethod + def _make_client(): + client = TwitterClient.__new__(TwitterClient) + client._write_delay = lambda: None + return client + + def test_standard_tweet_uses_create_tweet(self): + from twitter_cli.graphql import NOTE_TWEET_FEATURES + + client = self._make_client() + calls = [] + + def mock_graphql_post(operation_name, variables, features=None): + calls.append((operation_name, variables, features)) + return {"data": {"create_tweet": {"tweet_results": {"result": {"rest_id": "88"}}}}} + + client._graphql_post = mock_graphql_post + + assert client.create_tweet("x" * 280) == "88" + op, variables, features = calls[0] + assert op == "CreateTweet" + assert "disallowed_reply_options" not in variables + assert features is FEATURES + assert NOTE_TWEET_FEATURES.keys().isdisjoint(features) + + def test_long_tweet_uses_create_note_tweet(self): + from twitter_cli.graphql import NOTE_TWEET_FEATURES + + client = self._make_client() + calls = [] + + def mock_graphql_post(operation_name, variables, features=None): + calls.append((operation_name, variables, features)) + return { + "data": {"notetweet_create": {"tweet_results": {"result": {"rest_id": "99"}}}} + } + + client._graphql_post = mock_graphql_post + + assert client.create_tweet("x" * 281, reply_to_id="123") == "99" + op, variables, features = calls[0] + assert op == "CreateNoteTweet" + assert variables["disallowed_reply_options"] is None + assert variables["reply"]["in_reply_to_tweet_id"] == "123" + assert features == dict(FEATURES, **NOTE_TWEET_FEATURES) + + def test_long_quote_uses_create_note_tweet(self): + from twitter_cli.graphql import NOTE_TWEET_FEATURES + + client = self._make_client() + calls = [] + + def mock_graphql_post(operation_name, variables, features=None): + calls.append((operation_name, variables, features)) + return { + "data": {"notetweet_create": {"tweet_results": {"result": {"rest_id": "100"}}}} + } + + client._graphql_post = mock_graphql_post + + assert client.quote_tweet("456", "x" * 281) == "100" + op, variables, features = calls[0] + assert op == "CreateNoteTweet" + assert variables["attachment_url"] == "https://x.com/i/status/456" + assert features == dict(FEATURES, **NOTE_TWEET_FEATURES) + + +class TestUploadVideo: + def _make_client(self): + client = TwitterClient.__new__(TwitterClient) + client._auth_token = "tok" + client._ct0 = "ct0" + client._cookie_string = None + client._client_transaction = MagicMock() + client._client_transaction.generate_transaction_id.return_value = "tid-video" + client._ct_init_attempted = True + return client + + @patch("twitter_cli.client.time.sleep") + @patch("twitter_cli.client._get_cffi_session") + def test_upload_video_chunks_and_polls_status(self, mock_session, _mock_sleep, tmp_path): + vid = tmp_path / "clip.mp4" + # 5 MB -> 2 chunks (4 MB + 1 MB) + vid.write_bytes(b"\x00" * (5 * 1024 * 1024)) + + resp_init = MagicMock(status_code=200, text='{"media_id_string": "vid-999"}') + resp_append0 = MagicMock(status_code=204, text="") + resp_append1 = MagicMock(status_code=204, text="") + resp_finalize = MagicMock( + status_code=200, + text='{"media_id_string": "vid-999", "processing_info": {"state": "pending", "check_after_secs": 1}}', + ) + resp_status = MagicMock( + status_code=200, + text='{"media_id_string": "vid-999", "processing_info": {"state": "succeeded"}}', + ) + + sess = MagicMock() + sess.post = MagicMock(side_effect=[resp_init, resp_append0, resp_append1, resp_finalize]) + sess.get = MagicMock(return_value=resp_status) + mock_session.return_value = sess + + client = self._make_client() + media_id = client.upload_media(str(vid)) + + assert media_id == "vid-999" + assert sess.post.call_count == 4 + assert sess.post.call_args_list[0].kwargs["data"]["media_category"] == "tweet_video" + assert sess.get.call_count == 1 + + @patch("twitter_cli.client.time.sleep") + @patch("twitter_cli.client._get_cffi_session") + def test_upload_video_raises_on_failed_processing(self, mock_session, _mock_sleep, tmp_path): + from twitter_cli.exceptions import MediaUploadError + + vid = tmp_path / "bad.mp4" + vid.write_bytes(b"\x00" * 100) + + sess = MagicMock() + sess.post = MagicMock( + side_effect=[ + MagicMock(status_code=200, text='{"media_id_string": "vid-1"}'), + MagicMock(status_code=204, text=""), + MagicMock( + status_code=200, + text='{"processing_info": {"state": "failed", "error": {"message": "bad codec"}}}', + ), + ] + ) + mock_session.return_value = sess + + client = self._make_client() + with pytest.raises(MediaUploadError, match="Video processing failed"): + client.upload_media(str(vid)) + + +class TestCreateArticle: + def _make_client(self): + client = TwitterClient.__new__(TwitterClient) + client._write_delay = lambda: None + return client + + def test_create_article_publishes_draft_with_content(self): + client = self._make_client() + calls = [] + + def mock_graphql_post(operation_name, variables, features=None): + calls.append((operation_name, variables)) + if operation_name == "ArticleEntityDraftCreate": + return { + "data": { + "articleentity_create_draft": { + "article_entity_results": {"result": {"rest_id": "draft-1"}} + } + } + } + if operation_name == "ArticleEntityPublish": + return { + "data": { + "articleentity_publish": { + "article_entity_results": {"result": {"rest_id": "article-1"}} + } + } + } + return {"data": {}} + + client._graphql_post = mock_graphql_post + result = client.create_article( + "Title", {"blocks": [{"text": "Body"}], "entity_map": []}, publish=True + ) + + assert result == { + "id": "article-1", + "title": "Title", + "url": "https://x.com/i/article/article-1", + "published": True, + } + assert [c[0] for c in calls] == [ + "ArticleEntityDraftCreate", + "ArticleEntityUpdateTitle", + "ArticleEntityUpdateContent", + "ArticleEntityPublish", + ] + + def test_create_article_draft_skips_publish(self): + client = self._make_client() + calls = [] + + def mock_graphql_post(operation_name, variables, features=None): + calls.append(operation_name) + if operation_name == "ArticleEntityDraftCreate": + return { + "data": { + "articleentity_create_draft": { + "article_entity_results": {"result": {"rest_id": "draft-2"}} + } + } + } + return {"data": {}} + + client._graphql_post = mock_graphql_post + result = client.create_article("Draft title", {"blocks": [], "entity_map": []}, publish=False) + + assert result["id"] == "draft-2" + assert result["published"] is False + assert result["url"] == "https://x.com/compose/article/edit/draft-2" + assert calls == [ + "ArticleEntityDraftCreate", + "ArticleEntityUpdateTitle", + "ArticleEntityUpdateContent", + ] diff --git a/tests/test_text.py b/tests/test_text.py new file mode 100644 index 0000000..8b37c83 --- /dev/null +++ b/tests/test_text.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from twitter_cli.text import ( + CREATE_NOTE_TWEET_OPERATION, + CREATE_TWEET_OPERATION, + tweet_create_route, + tweet_weighted_length, +) + + +def test_weighted_length_uses_twitter_text_v3_unicode_ranges() -> None: + assert tweet_weighted_length("\u00e9" * 280) == 280 + assert tweet_weighted_length("\u00df" * 280) == 280 + assert tweet_weighted_length("\u4f60" * 140) == 280 + + +def test_weighted_length_normalizes_nfc() -> None: + assert tweet_weighted_length("A\u0301B") == 2 + + +def test_weighted_length_normalizes_http_url_to_23_characters() -> None: + assert tweet_weighted_length("Hi http://test.co") == 26 + long_url = "https://example.com/" + ("path/" * 80) + assert tweet_weighted_length(long_url) == 23 + + +def test_weighted_length_normalizes_common_bare_domain() -> None: + assert tweet_weighted_length("See example.com/a/very/long/path") == 27 + + +def test_weighted_length_collapses_emoji_sequences() -> None: + family = "\U0001f468\u200d\U0001f469\u200d\U0001f467\u200d\U0001f466" + flag = "\U0001f1fa\U0001f1f8" + assert tweet_weighted_length(family * 140) == 280 + assert tweet_weighted_length(flag) == 2 + + +def test_route_uses_weighted_limit() -> None: + assert tweet_create_route("\u00e9" * 280) == (CREATE_TWEET_OPERATION, 280) + assert tweet_create_route("\u4f60" * 141) == (CREATE_NOTE_TWEET_OPERATION, 282) diff --git a/twitter_cli/article.py b/twitter_cli/article.py new file mode 100644 index 0000000..8936ffe --- /dev/null +++ b/twitter_cli/article.py @@ -0,0 +1,154 @@ +"""Helpers for composing X Article content_state payloads.""" + +from __future__ import annotations + +import hashlib +import re +from typing import Any + + +DraftBlock = dict[str, Any] +DraftEntity = dict[str, Any] +DraftContentState = dict[str, Any] + + +def _block_key(seed: str, index: int) -> str: + return hashlib.sha1(("%s:%d" % (seed, index)).encode("utf-8")).hexdigest()[:5] + + +def _utf16_len(text: str) -> int: + return len(text.encode("utf-16-le")) // 2 + + +def _plain_block(block_type: str, text: str, key: str) -> DraftBlock: + return { + "data": {}, + "text": text, + "key": key, + "type": block_type, + "entity_ranges": [], + "inline_style_ranges": [], + } + + +def _atomic_block(entity_key: int, key: str) -> DraftBlock: + return { + "data": {}, + "text": " ", + "key": key, + "type": "atomic", + "entity_ranges": [{"key": entity_key, "offset": 0, "length": 1}], + "inline_style_ranges": [], + } + + +def _append_entity(content_state: DraftContentState, entity_type: str, mutability: str, data: dict[str, Any]) -> int: + entity_map = content_state["entity_map"] + key = len(entity_map) + entity_map.append( + { + "key": str(key), + "value": { + "data": data, + "type": entity_type, + "mutability": mutability, + }, + } + ) + return key + + +def _extract_links(text: str, content_state: DraftContentState) -> tuple[str, list[dict[str, int]]]: + ranges: list[dict[str, int]] = [] + output: list[str] = [] + cursor = 0 + for match in re.finditer(r"\[([^\]]+)\]\(([^)]+)\)", text): + output.append(text[cursor:match.start()]) + label = match.group(1) + url = match.group(2) + offset = _utf16_len("".join(output)) + output.append(label) + entity_key = _append_entity(content_state, "LINK", "Mutable", {"url": url}) + ranges.append({"key": entity_key, "offset": offset, "length": _utf16_len(label)}) + cursor = match.end() + output.append(text[cursor:]) + return "".join(output), ranges + + +def _strip_inline_markup(text: str) -> str: + text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) + text = re.sub(r"\*([^*]+)\*", r"\1", text) + text = re.sub(r"`([^`]+)`", r"\1", text) + return text + + +def article_markdown_to_content_state(markdown: str) -> DraftContentState: + """Convert a conservative Markdown subset into X Article content_state. + + Supported block forms: paragraphs, #/## headings, unordered and ordered + list items, blockquotes, horizontal rules, fenced code blocks, and inline + Markdown links. + """ + content_state: DraftContentState = {"blocks": [], "entity_map": []} + lines = markdown.splitlines() + i = 0 + block_index = 0 + + while i < len(lines): + raw = lines[i].rstrip() + stripped = raw.strip() + i += 1 + if not stripped: + continue + + if stripped.startswith("```"): + code_lines: list[str] = [] + opening = stripped + while i < len(lines): + code_line = lines[i].rstrip() + i += 1 + if code_line.strip().startswith("```"): + break + code_lines.append(code_line) + markdown_block = opening + "\n" + "\n".join(code_lines) + "\n```" + entity_key = _append_entity(content_state, "MARKDOWN", "Mutable", {"markdown": markdown_block}) + content_state["blocks"].append(_atomic_block(entity_key, _block_key(markdown_block, block_index))) + block_index += 1 + continue + + if stripped == "---": + entity_key = _append_entity(content_state, "DIVIDER", "Immutable", {}) + content_state["blocks"].append(_atomic_block(entity_key, _block_key(stripped, block_index))) + block_index += 1 + continue + + block_type = "unstyled" + text = stripped + if stripped.startswith("# "): + block_type = "header-one" + text = stripped[2:].strip() + elif stripped.startswith("## "): + block_type = "header-two" + text = stripped[3:].strip() + elif stripped.startswith("> "): + block_type = "blockquote" + text = stripped[2:].strip() + elif stripped.startswith(("- ", "* ")): + block_type = "unordered-list-item" + text = stripped[2:].strip() + else: + ordered = re.match(r"^\d+\.\s+(.+)$", stripped) + if ordered: + block_type = "ordered-list-item" + text = ordered.group(1).strip() + + text, entity_ranges = _extract_links(_strip_inline_markup(text), content_state) + block = _plain_block(block_type, text, _block_key(text, block_index)) + block["entity_ranges"] = entity_ranges + content_state["blocks"].append(block) + block_index += 1 + + if not content_state["blocks"]: + content_state["blocks"].append(_plain_block("unstyled", "", _block_key("", 0))) + + return content_state diff --git a/twitter_cli/cli.py b/twitter_cli/cli.py index 7d3490d..aa8c0d2 100644 --- a/twitter_cli/cli.py +++ b/twitter_cli/cli.py @@ -48,6 +48,7 @@ import yaml from . import __version__ +from .article import article_markdown_to_content_state from .auth import get_cookies, load_from_env from .cache import resolve_cached_tweet, save_tweet_cache from .exceptions import TwitterError @@ -1091,6 +1092,41 @@ def article(ctx, tweet_id, as_json, as_yaml, as_markdown, output_file): console.print() +@cli.command(name="article-publish") +@click.argument("markdown_file", type=click.Path(exists=True, dir_okay=False)) +@click.option("--title", "-t", required=True, help="Article title.") +@click.option("--draft", is_flag=True, help="Create a draft without publishing.") +@structured_output_options +def article_publish(markdown_file, title, draft, as_json, as_yaml): + # type: (str, str, bool, bool, bool) -> None + """Publish an X Article from a Markdown file.""" + markdown = Path(markdown_file).read_text(encoding="utf-8") + content_state = article_markdown_to_content_state(markdown) + + def operation(client: TwitterClient) -> WritePayload: + result = client.create_article(title, content_state, publish=not draft) + return { + "success": True, + "action": "article_publish", + "id": result["id"], + "title": result["title"], + "url": result["url"], + "published": result["published"], + } + + action = "Creating article draft" if draft else "Publishing article" + payload = _run_write_command( + as_json=as_json, + as_yaml=as_yaml, + operation=operation, + progress_lines=["📝 %s..." % action], + success_lines=["[green]✅ Article %s![/green]" % ("draft created" if draft else "published")], + error_details={"action": "article_publish", "title": title, "draft": draft}, + ) + if payload and not _structured_mode(as_json=as_json, as_yaml=as_yaml): + console.print("🔗 %s" % payload["url"]) + + @cli.command(name="list") @click.argument("list_id") @click.option("--max", "-n", "max_count", type=int, default=None, help="Max tweets to fetch.") @@ -1206,19 +1242,33 @@ def following(screen_name, max_count, as_json, as_yaml): # ── Write commands ────────────────────────────────────────────────────── _MAX_IMAGES = 4 # Twitter allows up to 4 images per tweet +_MAX_VIDEOS = 1 # X allows 1 video per tweet (or up to 4 images, not both) -def _upload_images(client, image_paths, rich_output=True): - # type: (TwitterClient, tuple, bool) -> list - """Upload images and return list of media_id strings.""" - if not image_paths: +def _upload_images(client, image_paths, video_paths=None, rich_output=True): + # type: (TwitterClient, tuple, Optional[tuple], bool) -> list + """Upload images or a video and return list of media_id strings.""" + image_paths = tuple(image_paths or ()) + video_paths = tuple(video_paths or ()) + if not image_paths and not video_paths: return [] if len(image_paths) > _MAX_IMAGES: raise click.UsageError("Too many images: max %d, got %d" % (_MAX_IMAGES, len(image_paths))) + if len(video_paths) > _MAX_VIDEOS: + raise click.UsageError( + "Too many videos: max %d, got %d (X allows 1 video per tweet)" % (_MAX_VIDEOS, len(video_paths)) + ) + if image_paths and video_paths: + raise click.UsageError("Attach images OR a video, not both (X allows one media type per tweet)") media_ids = [] + total = len(image_paths) + len(video_paths) for i, path in enumerate(image_paths, 1): if rich_output: - console.print("📤 Uploading image %d/%d: %s" % (i, len(image_paths), path)) + console.print("📤 Uploading image %d/%d: %s" % (i, total, path)) + media_ids.append(client.upload_media(path)) + for i, path in enumerate(video_paths, 1): + if rich_output: + console.print("🎥 Uploading video %d/%d: %s" % (i, total, path)) media_ids.append(client.upload_media(path)) return media_ids @@ -1250,23 +1300,25 @@ def operation(client: TwitterClient) -> WritePayload: @click.argument("text") @click.option("--reply-to", "-r", default=None, help="Reply to this tweet ID.") @click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.") +@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True), help="Attach video (max 1; mp4/mov/webm up to 512 MB).") @structured_output_options -def post(text, reply_to, images, as_json, as_yaml): - # type: (str, Optional[str], tuple, bool, bool) -> None +def post(text, reply_to, images, videos, as_json, as_yaml): + # type: (str, Optional[str], tuple, tuple, bool, bool) -> None """Post a new tweet. TEXT is the tweet content. - Attach images with --image / -i (up to 4): + Attach images with --image / -i (up to 4), or one video with --video / -V: \b twitter post "Hello!" --image photo.jpg twitter post "Gallery" -i a.png -i b.png -i c.jpg + twitter post "Clip:" --video clip.mp4 """ normalized_reply_to = _normalize_tweet_id(reply_to) if reply_to else None action = "Replying to %s" % normalized_reply_to if normalized_reply_to else "Posting tweet" rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml) def operation(client: TwitterClient) -> WritePayload: - media_ids = _upload_images(client, images, rich_output=rich_output) + media_ids = _upload_images(client, images, video_paths=videos, rich_output=rich_output) tweet_id = client.create_tweet(text, reply_to_id=normalized_reply_to, media_ids=media_ids or None) return {"success": True, "action": "post", "id": tweet_id, "url": "https://x.com/i/status/%s" % tweet_id} @@ -1286,14 +1338,15 @@ def operation(client: TwitterClient) -> WritePayload: @click.argument("tweet_id") @click.argument("text") @click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.") +@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True), help="Attach video (max 1; mp4/mov/webm up to 512 MB).") @structured_output_options -def reply_tweet(tweet_id, text, images, as_json, as_yaml): - # type: (str, str, tuple, bool, bool) -> None +def reply_tweet(tweet_id, text, images, videos, as_json, as_yaml): + # type: (str, str, tuple, tuple, bool, bool) -> None """Reply to a tweet. TWEET_ID is the tweet to reply to, TEXT is the reply content.""" tweet_id = _normalize_tweet_id(tweet_id) rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml) def operation(client: TwitterClient) -> WritePayload: - media_ids = _upload_images(client, images, rich_output=rich_output) + media_ids = _upload_images(client, images, video_paths=videos, rich_output=rich_output) new_id = client.create_tweet(text, reply_to_id=tweet_id, media_ids=media_ids or None) return { "success": True, @@ -1319,14 +1372,15 @@ def operation(client: TwitterClient) -> WritePayload: @click.argument("tweet_id") @click.argument("text") @click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.") +@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True), help="Attach video (max 1; mp4/mov/webm up to 512 MB).") @structured_output_options -def quote_tweet(tweet_id, text, images, as_json, as_yaml): - # type: (str, str, tuple, bool, bool) -> None +def quote_tweet(tweet_id, text, images, videos, as_json, as_yaml): + # type: (str, str, tuple, tuple, bool, bool) -> None """Quote-tweet a tweet. TWEET_ID is the tweet to quote, TEXT is the commentary.""" tweet_id = _normalize_tweet_id(tweet_id) rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml) def operation(client: TwitterClient) -> WritePayload: - media_ids = _upload_images(client, images, rich_output=rich_output) + media_ids = _upload_images(client, images, video_paths=videos, rich_output=rich_output) new_id = client.quote_tweet(tweet_id, text, media_ids=media_ids or None) return { "success": True, diff --git a/twitter_cli/client.py b/twitter_cli/client.py index ce4fad2..7368669 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -44,11 +44,13 @@ TwitterAPIError, ) from .graphql import ( + ARTICLE_FEATURES, FEATURES, _build_graphql_url, _invalidate_query_id, _resolve_query_id, _update_features_from_html, + operation_features, ) from .models import BookmarkFolder, UserProfile from .parser import ( @@ -58,6 +60,7 @@ parse_tweet_result, parse_user_result, ) +from .text import CREATE_NOTE_TWEET_OPERATION, tweet_create_route if TYPE_CHECKING: from typing import Dict, List, Optional, Set, Tuple # noqa: F401 @@ -306,6 +309,29 @@ def _normalize_explore_items(instructions, count=20): return stories +def _prepare_tweet_create(text, variables): + # type: (str, Dict[str, Any]) -> Tuple[str, Dict[str, Any]] + """Apply operation-specific variables and return its feature set.""" + operation_name, weighted_length = tweet_create_route(text) + if operation_name == CREATE_NOTE_TWEET_OPERATION: + variables["disallowed_reply_options"] = None + logger.info( + "Tweet weighted=%d, using CreateNoteTweet (long-form)", + weighted_length, + ) + return operation_name, operation_features(operation_name) + + +def _created_tweet_result(data): + # type: (Dict[str, Any]) -> Optional[Dict[str, Any]] + """Extract tweet result from CreateTweet or CreateNoteTweet responses.""" + return ( + _deep_get(data, "data", "create_tweet", "tweet_results", "result") + or _deep_get(data, "data", "notetweet_create", "tweet_results", "result") + or _deep_get(data, "data", "create_note_tweet", "tweet_results", "result") + ) + + # ── TwitterClient ──────────────────────────────────────────────────────── @@ -703,6 +729,84 @@ def fetch_article(self, tweet_id): logger.info("fetch_article: tweet_id=%s", tweet_id) return tweet + def create_article(self, title, content_state, publish=True): + # type: (str, Dict[str, Any], bool) -> Dict[str, Any] + """Create an X Article draft, optionally publish it, and return metadata.""" + if not title.strip(): + raise TwitterAPIError(0, "Article title is required") + + article_id = self._create_article_draft() + self._update_article_title(article_id, title) + self._update_article_content(article_id, content_state) + if publish: + article_id = self._publish_article(article_id) + url = "https://x.com/i/article/%s" % article_id + else: + url = "https://x.com/compose/article/edit/%s" % article_id + + self._write_delay() + return { + "id": article_id, + "title": title, + "url": url, + "published": bool(publish), + } + + def _create_article_draft(self): + # type: () -> str + variables = { + "content_state": {"blocks": [], "entity_map": []}, + "title": "", + } + data = self._graphql_post("ArticleEntityDraftCreate", variables, ARTICLE_FEATURES) + result = _deep_get( + data, + "data", + "articleentity_create_draft", + "article_entity_results", + "result", + ) + if result and result.get("rest_id"): + return result["rest_id"] + raise TwitterAPIError(0, "Failed to create article draft") + + def _update_article_title(self, article_id, title): + # type: (str, str) -> None + variables = { + "articleEntityId": article_id, + "title": title, + } + self._graphql_post("ArticleEntityUpdateTitle", variables, ARTICLE_FEATURES) + + def _update_article_content(self, article_id, content_state): + # type: (str, Dict[str, Any]) -> None + variables = { + "content_state": { + "blocks": content_state.get("blocks") or [], + "entity_map": content_state.get("entity_map") or [], + }, + "article_entity": article_id, + } + self._graphql_post("ArticleEntityUpdateContent", variables, ARTICLE_FEATURES) + + def _publish_article(self, article_id): + # type: (str) -> str + variables = { + "articleEntityId": article_id, + "visibilitySetting": "Public", + } + data = self._graphql_post("ArticleEntityPublish", variables, ARTICLE_FEATURES) + result = _deep_get( + data, + "data", + "articleentity_publish", + "article_entity_results", + "result", + ) + if result and result.get("rest_id"): + return result["rest_id"] + raise TwitterAPIError(0, "Failed to publish article") + def fetch_list_timeline(self, list_id, count=20, cursor=None, return_cursor=False): # type: (str, int, Optional[str], bool) -> Any """Fetch tweets from a Twitter List.""" @@ -736,9 +840,12 @@ def fetch_following(self, user_id, count=20): # ── Write operations ───────────────────────────────────────────── - # Supported image MIME types and max file size (5 MB) + # Supported image MIME types and max file sizes _SUPPORTED_IMAGE_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"} _MAX_IMAGE_SIZE = 5 * 1024 * 1024 # 5 MB + _MAX_VIDEO_SIZE = 512 * 1024 * 1024 # 512 MB (X hard cap for tweet_video) + _VIDEO_CHUNK_SIZE = 4 * 1024 * 1024 # 4 MB per APPEND segment + _VIDEO_PROCESS_TIMEOUT = 300 # seconds to wait for async video processing def _write_delay(self): # type: () -> None @@ -749,26 +856,37 @@ def _write_delay(self): def upload_media(self, file_path): # type: (str) -> str - """Upload an image file to Twitter. Returns the media_id string. + """Upload an image or video file to Twitter. Returns the media_id string. - Uses Twitter's chunked upload API (INIT → APPEND → FINALIZE). - Supports JPEG, PNG, GIF, and WebP images up to 5 MB. + Uses Twitter's chunked upload API (INIT → APPEND → FINALIZE [+ STATUS for video]). + Images: JPEG, PNG, GIF, WebP up to 5 MB. + Videos (mp4/mov/webm): up to 512 MB, uploaded in 4 MB chunks with async STATUS polling. """ if not os.path.isfile(file_path): raise MediaUploadError("File not found: %s" % file_path) file_size = os.path.getsize(file_path) - if file_size > self._MAX_IMAGE_SIZE: - raise MediaUploadError( - "File too large: %.1f MB (max %.0f MB)" - % (file_size / (1024 * 1024), self._MAX_IMAGE_SIZE / (1024 * 1024)) - ) - media_type = mimetypes.guess_type(file_path)[0] or "" - if media_type not in self._SUPPORTED_IMAGE_TYPES: - raise MediaUploadError( - "Unsupported image format: %s (supported: jpeg, png, gif, webp)" % media_type - ) + is_video = media_type.startswith("video/") + + if is_video: + if file_size > self._MAX_VIDEO_SIZE: + raise MediaUploadError( + "File too large: %.1f MB (max %.0f MB)" + % (file_size / (1024 * 1024), self._MAX_VIDEO_SIZE / (1024 * 1024)) + ) + media_category = "tweet_video" + else: + if file_size > self._MAX_IMAGE_SIZE: + raise MediaUploadError( + "File too large: %.1f MB (max %.0f MB)" + % (file_size / (1024 * 1024), self._MAX_IMAGE_SIZE / (1024 * 1024)) + ) + if media_type not in self._SUPPORTED_IMAGE_TYPES: + raise MediaUploadError( + "Unsupported image format: %s (supported: jpeg, png, gif, webp)" % media_type + ) + media_category = "tweet_image" upload_url = "https://upload.twitter.com/i/media/upload.json" session = _get_cffi_session() @@ -780,6 +898,7 @@ def upload_media(self, file_path): "command": "INIT", "total_bytes": str(file_size), "media_type": media_type, + "media_category": media_category, } resp = session.post(upload_url, headers=headers, data=init_data, timeout=30) if resp.status_code >= 400: @@ -791,25 +910,39 @@ def upload_media(self, file_path): media_id = init_result.get("media_id_string", "") if not media_id: raise MediaUploadError("INIT did not return media_id") - logger.info("Media INIT: media_id=%s", media_id) + logger.info("Media INIT: media_id=%s category=%s", media_id, media_category) # ── APPEND ─────────────────────────────────────────────────── + segment_index = 0 with open(file_path, "rb") as f: - media_data = base64.b64encode(f.read()).decode("ascii") - - headers = self._build_headers(url=upload_url, method="POST") - # Remove JSON content-type — curl_cffi handles multipart encoding - headers.pop("Content-Type", None) - append_data = { - "command": "APPEND", - "media_id": media_id, - "segment_index": "0", - "media_data": media_data, - } - resp = session.post(upload_url, headers=headers, data=append_data, timeout=60) - if resp.status_code >= 400: - raise MediaUploadError("APPEND failed (HTTP %d): %s" % (resp.status_code, resp.text[:300])) - logger.info("Media APPEND: segment 0 uploaded") + while True: + media_bytes = f.read(self._VIDEO_CHUNK_SIZE if is_video else None) + if not media_bytes: + if segment_index == 0 and not is_video: + media_bytes = b"" + else: + break + media_data = base64.b64encode(media_bytes).decode("ascii") + headers = self._build_headers(url=upload_url, method="POST") + headers.pop("Content-Type", None) + append_data = { + "command": "APPEND", + "media_id": media_id, + "segment_index": str(segment_index), + "media_data": media_data, + } + resp = session.post( + upload_url, headers=headers, data=append_data, timeout=300 if is_video else 60 + ) + if resp.status_code >= 400: + raise MediaUploadError( + "APPEND segment %d failed (HTTP %d): %s" + % (segment_index, resp.status_code, resp.text[:300]) + ) + logger.info("Media APPEND: segment %d uploaded", segment_index) + segment_index += 1 + if not is_video: + break # ── FINALIZE ───────────────────────────────────────────────── headers = self._build_headers(url=upload_url, method="POST") @@ -823,16 +956,52 @@ def upload_media(self, file_path): raise MediaUploadError("FINALIZE failed (HTTP %d): %s" % (resp.status_code, resp.text[:300])) logger.info("Media FINALIZE: media_id=%s ready", media_id) + # ── STATUS (videos only) ───────────────────────────────────── + if is_video: + try: + finalize_result = json.loads(resp.text) + except (json.JSONDecodeError, ValueError): + finalize_result = {} + info = finalize_result.get("processing_info") if isinstance(finalize_result, dict) else None + deadline = time.time() + self._VIDEO_PROCESS_TIMEOUT + while isinstance(info, dict) and info.get("state") not in (None, "succeeded"): + state = info.get("state") + if state == "failed": + raise MediaUploadError( + "Video processing failed: %s" % json.dumps(info.get("error", info)) + ) + wait = max(1, int(info.get("check_after_secs", 3))) + time.sleep(wait) + if time.time() > deadline: + raise MediaUploadError( + "Video processing timed out after %ds" % self._VIDEO_PROCESS_TIMEOUT + ) + headers = self._build_headers(url=upload_url, method="GET") + resp = session.get( + upload_url, + headers=headers, + params={"command": "STATUS", "media_id": media_id}, + timeout=30, + ) + if resp.status_code >= 400: + raise MediaUploadError( + "STATUS failed (HTTP %d): %s" % (resp.status_code, resp.text[:300]) + ) + try: + status_result = json.loads(resp.text) + except (json.JSONDecodeError, ValueError): + raise MediaUploadError("STATUS returned invalid JSON") + info = status_result.get("processing_info") if isinstance(status_result, dict) else None + logger.info("Media STATUS: video processing complete") + return media_id def create_tweet(self, text, reply_to_id=None, media_ids=None): # type: (str, Optional[str], Optional[List[str]]) -> str """Post a new tweet. Returns the new tweet ID. - Args: - text: Tweet text content. - reply_to_id: Optional tweet ID to reply to. - media_ids: Optional list of media IDs (from upload_media) to attach. + Posts exceeding 280 weighted characters automatically route through + CreateNoteTweet for X Premium long-form posts. """ media_entities = [] if media_ids: @@ -842,18 +1011,20 @@ def create_tweet(self, text, reply_to_id=None, media_ids=None): "media": {"media_entities": media_entities, "possibly_sensitive": False}, "semantic_annotation_ids": [], "dark_request": False, + "includePromotedContent": False, } # type: Dict[str, Any] if reply_to_id: variables["reply"] = { "in_reply_to_tweet_id": reply_to_id, "exclude_reply_user_ids": [], } - data = self._graphql_post("CreateTweet", variables, FEATURES) + operation_name, features = _prepare_tweet_create(text, variables) + data = self._graphql_post(operation_name, variables, features) self._write_delay() - result = _deep_get(data, "data", "create_tweet", "tweet_results", "result") + result = _created_tweet_result(data) if result: return result.get("rest_id", "") - raise TwitterAPIError(0, "Failed to create tweet") + raise TwitterAPIError(0, "Failed to create tweet (op=%s)" % operation_name) def delete_tweet(self, tweet_id): # type: (str) -> bool @@ -977,13 +1148,15 @@ def quote_tweet(self, tweet_id, text, media_ids=None): "media": {"media_entities": media_entities, "possibly_sensitive": False}, "semantic_annotation_ids": [], "dark_request": False, + "includePromotedContent": False, } - data = self._graphql_post("CreateTweet", variables, FEATURES) + operation_name, features = _prepare_tweet_create(text, variables) + data = self._graphql_post(operation_name, variables, features) self._write_delay() - result = _deep_get(data, "data", "create_tweet", "tweet_results", "result") + result = _created_tweet_result(data) if result: return result.get("rest_id", "") - raise TwitterAPIError(0, "Failed to create quote tweet") + raise TwitterAPIError(0, "Failed to create quote tweet (op=%s)" % operation_name) def follow_user(self, user_id): # type: (str) -> bool diff --git a/twitter_cli/graphql.py b/twitter_cli/graphql.py index d153db1..cb5f017 100644 --- a/twitter_cli/graphql.py +++ b/twitter_cli/graphql.py @@ -21,6 +21,7 @@ from .cache import _open_owner_only, _tighten_dir from .exceptions import QueryIdError +from .text import CREATE_NOTE_TWEET_OPERATION, CREATE_TWEET_OPERATION logger = logging.getLogger(__name__) @@ -48,7 +49,8 @@ "ListLatestTweetsTimeline": "UMc_lPEeKz_WiKSY8ZT7yw", "Followers": "Xe3y9_ndZ9-RtWz8zd_wpg", "Following": "eDqlbOS46zda8jDT8dEQ_Q", - "CreateTweet": "wR5Z_lEibLvkew3tF9w-Sg", + CREATE_TWEET_OPERATION: "wR5Z_lEibLvkew3tF9w-Sg", + CREATE_NOTE_TWEET_OPERATION: "_eeuQKX1-VyRP_ROM-GN7g", "DeleteTweet": "nxpZCY2K-I6QoFHAHeojFQ", "FavoriteTweet": "lI07N6Otwv1PhnEgXILM7A", "UnfavoriteTweet": "ZYKSe-w7KEslx3JhSIk5LA", @@ -59,6 +61,10 @@ "TweetResultByRestId": "U8lc5aomF5krJzZ9vJ9wxg", "BookmarkFoldersSlice": "i78YDd0Tza-dV4SYs58kRg", "BookmarkFolderTimeline": "hNY7X2xE2N7HVF6Qb_mu6w", + "ArticleEntityDraftCreate": "g1l5N8BxGewYuCy5USe_bQ", + "ArticleEntityUpdateTitle": "x75E2ABzm8_mGTg1bz8hcA", + "ArticleEntityUpdateContent": "M7N2FrPrlOmu-YrVIBxFnQ", + "ArticleEntityPublish": "m4SHicYMoWO_qkLvjhDk7Q", } # ── Default feature flags ──────────────────────────────────────────────── @@ -88,6 +94,32 @@ # Features dict that gets updated dynamically from x.com JS bundles FEATURES = dict(_DEFAULT_FEATURES) +# Extra composer flags scoped to CreateNoteTweet +NOTE_TWEET_FEATURES = { + "longform_notetweets_creation_enabled": True, + "longform_notetweets_richtext_consumption_enabled": True, + "articles_preview_enabled": True, + "tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled": True, +} + +# Feature flags scoped to X Article authoring mutations +ARTICLE_FEATURES = { + "profile_label_improvements_pcf_label_in_post_enabled": True, + "responsive_web_profile_redirect_enabled": False, + "rweb_tipjar_consumption_enabled": False, + "verified_phone_label_enabled": False, + "responsive_web_graphql_skip_user_profile_image_extensions_enabled": False, + "responsive_web_graphql_timeline_navigation_enabled": True, +} + + +def operation_features(operation_name): + # type: (str) -> Dict[str, Any] + """Return base features plus overrides scoped to one operation.""" + if operation_name == CREATE_NOTE_TWEET_OPERATION: + return dict(FEATURES, **NOTE_TWEET_FEATURES) + return FEATURES + # Module-level caches (not thread-safe — CLI is single-threaded) _cached_query_ids: Dict[str, str] = {} _disk_cache_loaded = False diff --git a/twitter_cli/text.py b/twitter_cli/text.py new file mode 100644 index 0000000..c65bb35 --- /dev/null +++ b/twitter_cli/text.py @@ -0,0 +1,153 @@ +"""X weighted text length and long-form routing helpers.""" + +from __future__ import annotations + +import re +import unicodedata +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Iterator, Optional, Tuple # noqa: F401 + + +CREATE_TWEET_OPERATION = "CreateTweet" +CREATE_NOTE_TWEET_OPERATION = "CreateNoteTweet" +STANDARD_TWEET_WEIGHT_LIMIT = 280 + +_TRANSFORMED_URL_LENGTH = 23 +_WEIGHT_ONE_RANGES = ( + (0x0000, 0x10FF), + (0x2000, 0x200D), + (0x2010, 0x201F), + (0x2032, 0x2037), +) + +_PROTOCOL_URL = r"https?://[^\s<>{}\[\]\"']+" +_BARE_URL = ( + r"(?:[^\W_](?:[\w-]{0,61}[^\W_])?\.)+" + r"(?:[^\W\d_]{2,63}|xn--[\w-]{2,59})" + r"(?::\d{1,5})?(?:[/?#][^\s<>{}\[\]\"']*)?" +) +_URL_RE = re.compile(r"(? int + """Return the URL end before prose punctuation or unmatched closers.""" + end = len(url) + while end and url[end - 1] in _TRAILING_URL_PUNCTUATION: + end -= 1 + for opening, closing in (("(", ")"), ("[", "]"), ("{", "}")): + while end and url[end - 1] == closing and url[:end].count(closing) > url[:end].count(opening): + end -= 1 + return end + + +def _url_spans(text): + # type: (str) -> Iterator[Tuple[int, int]] + for match in _URL_RE.finditer(text): + end = match.start() + _trim_url_end(match.group(0)) + if end > match.start(): + yield match.start(), end + + +def _is_emoji_base(codepoint): + # type: (int) -> bool + return codepoint in _EMOJI_BASES or any(start <= codepoint <= end for start, end in _EMOJI_BASE_RANGES) + + +def _consume_emoji_suffix(text, index, limit): + # type: (str, int, int) -> int + while index < limit and ( + ord(text[index]) in (0xFE0E, 0xFE0F) + or 0x1F3FB <= ord(text[index]) <= 0x1F3FF + or 0xE0020 <= ord(text[index]) <= 0xE007F + ): + index += 1 + return index + + +def _emoji_sequence_end(text, index, limit): + # type: (str, int, int) -> Optional[int] + codepoint = ord(text[index]) + + if text[index] in "#*0123456789": + cursor = index + 1 + if cursor < limit and ord(text[cursor]) == 0xFE0F: + cursor += 1 + if cursor < limit and ord(text[cursor]) == 0x20E3: + return cursor + 1 + return None + + if 0x1F1E6 <= codepoint <= 0x1F1FF: + if index + 1 < limit and 0x1F1E6 <= ord(text[index + 1]) <= 0x1F1FF: + return index + 2 + return index + 1 + + if not _is_emoji_base(codepoint): + return None + + cursor = _consume_emoji_suffix(text, index + 1, limit) + while cursor + 1 < limit and ord(text[cursor]) == 0x200D: + next_codepoint = ord(text[cursor + 1]) + if not _is_emoji_base(next_codepoint): + break + cursor = _consume_emoji_suffix(text, cursor + 2, limit) + return cursor + + +def _character_weight(codepoint): + # type: (int) -> int + if any(start <= codepoint <= end for start, end in _WEIGHT_ONE_RANGES): + return 1 + return 2 + + +def _weighted_segment(text, start, end): + # type: (str, int, int) -> int + weight = 0 + index = start + while index < end: + emoji_end = _emoji_sequence_end(text, index, end) + if emoji_end is not None: + weight += 2 + index = emoji_end + continue + weight += _character_weight(ord(text[index])) + index += 1 + return weight + + +def tweet_weighted_length(text): + # type: (str) -> int + """Return the twitter-text v3 weighted length used for routing.""" + normalized = unicodedata.normalize("NFC", text) + weight = 0 + cursor = 0 + for start, end in _url_spans(normalized): + weight += _weighted_segment(normalized, cursor, start) + weight += _TRANSFORMED_URL_LENGTH + cursor = end + return weight + _weighted_segment(normalized, cursor, len(normalized)) + + +def tweet_create_route(text): + # type: (str) -> Tuple[str, int] + """Return the create operation and weighted length for tweet text.""" + weighted_length = tweet_weighted_length(text) + operation = ( + CREATE_NOTE_TWEET_OPERATION + if weighted_length > STANDARD_TWEET_WEIGHT_LIMIT + else CREATE_TWEET_OPERATION + ) + return operation, weighted_length From 2e07af9c5f337b9fca107e92a2e641086f9135ed Mon Sep 17 00:00:00 2001 From: jackwener Date: Fri, 27 Nov 2026 18:30:26 +0000 Subject: [PATCH 7/8] feat(api,docs): export Python library API and update README, SKILL.md, SCHEMA.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Export clean public Python library API from twitter_cli.__init__ (TwitterClient, get_cookies, load_config, filter_tweets, models, exceptions, serializers) and add import-surface tests (addresses #9). - Document updated structured output fields in SCHEMA.md (possiblySensitive, media sensitivity/poster/altText/durationMs, author followers/following & viewer follow flags, thread metadata, bookmarks/tweet nextCursor, news, doctor, article-publish). - Update README.md (English & Chinese) and SKILL.md for all newly absorbed features, browsers, auth methods, environment variables, and Python 3.10–3.13 CI matrix. Co-authored-by: axsddlr Co-authored-by: hhh2210 Co-authored-by: Lucius Co-authored-by: RiriAgent Co-authored-by: Aditya Gupta Co-authored-by: Li Chenxi Co-authored-by: Trần Quang Đãng <91641923+quangdang46@users.noreply.github.com> --- README.md | 174 ++++++++++++++++++++++++++++----------- SCHEMA.md | 18 +++- SKILL.md | 60 ++++++++------ tests/test_public_api.py | 36 ++++++++ twitter_cli/__init__.py | 70 +++++++++++++++- 5 files changed, 283 insertions(+), 75 deletions(-) create mode 100644 tests/test_public_api.py diff --git a/README.md b/README.md index e033cd2..5e646b2 100644 --- a/README.md +++ b/README.md @@ -21,22 +21,26 @@ A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles **Read:** - Timeline: fetch `for-you` and `following` feeds -- Bookmarks: list saved tweets from your account -- Search: find tweets by keyword with Top/Latest/Photos/Videos tabs -- Tweet detail: view a tweet and its replies; use `show ` to open tweet #N from the last list output -- Article: fetch a Twitter Article and export it as Markdown +- Bookmarks: list saved tweets (with `--cursor` pagination and bookmark folders) +- Explore News: fetch personalized stories from Explore > News (`twitter news`) +- Search: find tweets by keyword with Top/Latest/Photos/Videos tabs and advanced filters +- Tweet detail: view a tweet and its replies (with `--cursor` pagination); use `show ` to open tweet #N from the last list output +- Article: fetch a Twitter Article with rich Draft.js formatting (Markdown blocks, links, inline styles, embedded tweets) and export as Markdown - List timeline: fetch tweets from a Twitter List -- User lookup: fetch user profile, tweets, likes, followers, and following -- `--full-text`: disable tweet text truncation in rich table output +- User lookup: fetch user profile (by `@handle` or numeric user ID), tweets, likes, followers, and following +- Display controls: `--full-text` for untruncated tables, `--time relative|absolute|iso` for timestamps, `completion bash|zsh|fish`, and `doctor [--refresh]` - Structured output: export any data as YAML or JSON for scripting and AI agent integration - Optional scoring filter: rank tweets by engagement weights +- Python library API: import `TwitterClient`, `get_cookies`, models, and serializers directly from `twitter_cli` - Structured output contract: [SCHEMA.md](./SCHEMA.md) > **AI Agent Tip:** Prefer `--yaml` for structured output unless a strict JSON parser is required. Non-TTY stdout defaults to YAML automatically. Use `--max` to limit results. **Write:** -- Post: create new tweets and replies, with optional image attachments (up to 4) -- Quote: quote-tweet with optional images +- Post: create new tweets and replies, with optional images (up to 4) or video (`--video` / `-V`, MP4/MOV/WebM up to 512 MB) +- Long-form posts: tweets over 280 weighted characters automatically route to `CreateNoteTweet` (X Premium) +- Article publish: publish X Articles (or drafts) directly from Markdown (`twitter article-publish`) +- Quote: quote-tweet with optional images or video - Delete: remove your own tweets - Like / Unlike: manage tweet likes - Retweet / Unretweet: manage retweets @@ -44,12 +48,12 @@ A terminal-first CLI for Twitter/X: read timelines, bookmarks, and user profiles - Write commands also support explicit `--json` / `--yaml` output now **Auth & Anti-Detection:** -- Cookie auth: use browser cookies or environment variables +- Cookie auth: browser cookies (Arc, Chrome, Edge, Firefox, Brave, Vivaldi, Zen, custom Chromium dir) or env vars (`TWITTER_COOKIE_STRING` or `TWITTER_AUTH_TOKEN` + `TWITTER_CT0`) - Full cookie forwarding: extracts ALL browser cookies for richer browser context - TLS fingerprint impersonation: `curl_cffi` with dynamic Chrome version matching -- `x-client-transaction-id` header generation -- Request timing jitter to avoid pattern detection -- Write operation delays (1.5–4s random) to mitigate rate limits +- `x-client-transaction-id` header generation with fail-closed protection on unsigned `POST` mutations +- Self-healing GraphQL `queryId` resolution with 24h local cache and `TWITTER_QID_` overrides +- Request timing jitter and write delays (1.5–4s random) to mitigate rate limits - Proxy support via `TWITTER_PROXY` environment variable ### Installation @@ -105,9 +109,14 @@ twitter feed --json # Structured stdout for scripts/agents # Bookmarks twitter bookmarks +twitter bookmarks --cursor "" twitter bookmarks --full-text twitter bookmarks --max 30 --yaml +# Explore News +twitter news --max 20 +twitter news --json + # Search twitter search "Claude Code" twitter search "AI agent" -t Latest --max 50 @@ -120,6 +129,7 @@ twitter search "trending" --filter # Apply ranking filter # Tweet detail (view tweet + replies) twitter tweet 1234567890 +twitter tweet 1234567890 --cursor "" twitter tweet 1234567890 --full-text twitter tweet https://x.com/user/status/1234567890 @@ -128,19 +138,22 @@ twitter show 2 # Open tweet #2 from last feed/search twitter show 2 --full-text # Full text in reply table twitter show 2 --json # Structured output -# Twitter Article +# Twitter Article (read & publish) twitter article 1234567890 twitter article https://x.com/user/article/1234567890 --json twitter article 1234567890 --markdown twitter article 1234567890 --output article.md +twitter article-publish post.md --title "My Article" # Publish X Article +twitter article-publish post.md --title "My Draft" --draft # Save as draft # List timeline twitter list 1539453138322673664 twitter list 1539453138322673664 --cursor "" twitter list 1539453138322673664 --full-text -# User +# User (accepts @handle or numeric user ID) twitter user elonmusk +twitter user 44196397 twitter user-posts elonmusk --max 20 twitter user-posts elonmusk --full-text twitter user-posts elonmusk -o tweets.json @@ -154,6 +167,7 @@ twitter following elonmusk --max 50 twitter post "Hello from twitter-cli!" twitter post "Hello!" --image photo.jpg # Post with image twitter post "Gallery" -i a.png -i b.jpg -i c.webp # Up to 4 images +twitter post "Demo clip" --video clip.mp4 # Post with video (up to 512 MB) twitter post "reply text" --reply-to 1234567890 twitter reply 1234567890 "Nice!" -i screenshot.png # Reply with image twitter quote 1234567890 "Look" -i chart.png # Quote with image @@ -167,16 +181,39 @@ twitter unretweet 1234567890 twitter bookmark 1234567890 twitter unbookmark 1234567890 twitter follow elonmusk --json + +# Display, completion & diagnostics +twitter --time relative feed # relative | absolute | iso +twitter completion zsh # bash | zsh | fish +twitter doctor # Check deps, config, auth presence, caches +twitter doctor --refresh # Refresh cached GraphQL query IDs +``` + +### Python Library Usage + +```python +from twitter_cli import TwitterClient, get_cookies + +cookies = get_cookies() +client = TwitterClient( + cookies["auth_token"], + cookies["ct0"], + cookie_string=cookies.get("cookie_string"), +) +tweets = client.fetch_home_timeline(count=20) +for tweet in tweets: + print(f"@{tweet.author.screen_name}: {tweet.text[:80]}") ``` ### Authentication twitter-cli uses this auth priority: -1. **Environment variables**: `TWITTER_AUTH_TOKEN` + `TWITTER_CT0` -2. **Browser cookies** (recommended): auto-extract from Arc/Chrome/Edge/Firefox/Brave +1. **Full cookie string**: `TWITTER_COOKIE_STRING` (full `Cookie:` header; auto-extracts `auth_token` + `ct0` while keeping all session cookies — great for remote servers, SigCLI, or Windows Chrome >=127) +2. **Environment variables**: `TWITTER_AUTH_TOKEN` + `TWITTER_CT0` +3. **Browser cookies** (recommended locally): auto-extract from Arc, Chrome, Edge, Firefox, Brave, Vivaldi, or Zen -Browser extraction is recommended — it forwards ALL Twitter cookies (not just `auth_token` + `ct0`) and aligns request headers with your local runtime, which is closer to normal browser traffic than minimal cookie auth. +Browser extraction is recommended locally — it forwards ALL Twitter cookies (not just `auth_token` + `ct0`) and aligns request headers with your local runtime, which is closer to normal browser traffic than minimal cookie auth. **Chrome multi-profile**: All Chrome profiles are scanned automatically. To specify a profile: @@ -184,14 +221,24 @@ Browser extraction is recommended — it forwards ALL Twitter cookies (not just TWITTER_CHROME_PROFILE="Profile 2" twitter feed ``` +**Custom Chromium directory:** For Chromium, Opera, Brave/Chrome custom data dirs, or portable builds: + +```bash +TWITTER_CHROMIUM_USER_DATA_DIR="/path/to/User Data" twitter feed +``` + **Browser priority:** If you have multiple browsers, set `TWITTER_BROWSER` to try a specific browser first: ```bash -TWITTER_BROWSER=chrome twitter feed # Supported: arc, chrome, edge, firefox, brave +TWITTER_BROWSER=chrome twitter feed # Supported: arc, chrome, edge, firefox, brave, vivaldi, zen ``` After loading cookies, the CLI performs lightweight verification. Commands that require account access fail fast on clear auth errors (`401/403`). +**Advanced GraphQL & Transaction env vars:** +- `TWITTER_QID_=` — override a specific GraphQL queryId (e.g. `TWITTER_QID_HomeTimeline=...`) +- `TWITTER_ALLOW_UNSIGNED=1` — opt-in bypass if `x-client-transaction-id` cannot be generated on write (`POST`) requests (fails closed by default to prevent 226 anti-bot flags) + ### Proxy Support Set `TWITTER_PROXY` to route all requests through a proxy: @@ -208,12 +255,15 @@ Using a proxy can help reduce IP-based rate limiting risks. ### Configuration -Create `config.yaml` in your working directory: +Create `config.yaml` in your working directory or `~/.twitter-cli/config.yaml` (search order: explicit path → `./config.yaml` → `~/.twitter-cli/config.yaml` → built-in defaults): ```yaml fetch: count: 50 +display: + time: "absolute" # "absolute" | "relative" | "iso" + filter: mode: "topN" # "topN" | "score" | "all" topN: 20 @@ -231,7 +281,7 @@ rateLimit: requestDelay: 2.5 # base delay between requests (randomized ×0.7–1.5) maxRetries: 3 # retry count on rate limit (429) retryBaseDelay: 5.0 # base delay for exponential backoff - maxCount: 200 # hard cap on fetched items + maxCount: 200 # default pagination cap (explicit --max can exceed up to 10,000) ``` Fetch behavior: @@ -321,26 +371,31 @@ uv run ruff check . uv run pytest -q ``` -Current CI validates the project on Python 3.8, 3.10, and 3.12. +Current CI validates the project on Python 3.10, 3.11, 3.12, and 3.13. ### Project Structure ```text twitter_cli/ -├── __init__.py -├── cli.py -├── client.py -├── graphql.py # GraphQL query IDs, URL building, JS bundle scanning -├── parser.py # Tweet, User, Media parsing logic -├── auth.py -├── config.py +├── __init__.py # Public Python library exports +├── article.py # Markdown -> Draft.js content_state builder for X Articles +├── auth.py # Browser cookie extraction & env auth +├── cache.py # Owner-only local cache helpers +├── cli.py # Click CLI commands +├── client.py # HTTP/GraphQL/media client & ClientTransaction bootstrap +├── config.py # YAML configuration loader ├── constants.py ├── exceptions.py ├── filter.py ├── formatter.py +├── graphql.py # GraphQL query IDs, disk cache, live JS bundle scanning +├── models.py ├── output.py +├── parser.py # Tweet, User, Media, Article Draft.js parsing +├── search.py # Advanced search query builder ├── serialization.py -└── models.py +├── text.py # twitter-text v3 weighted character length +└── timeutil.py ``` ### Use as AI Agent Skill @@ -376,20 +431,24 @@ git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli **读取:** - 时间线读取:支持 `for-you` 和 `following` -- 收藏读取:查看账号书签推文 -- 搜索:按关键词搜索推文,支持 Top/Latest/Photos/Videos -- 推文详情:查看推文及其回复;用 `show ` 可直接打开上次列表里的第 N 条推文 -- 文章读取:获取 Twitter 长文,并导出为 Markdown +- 收藏读取:查看账号书签推文(支持 `--cursor` 翻页及书签文件夹) +- Explore 新闻:`twitter news` 获取个性化新闻摘要 +- 搜索:按关键词搜索推文,支持 Top/Latest/Photos/Videos 与高级过滤 +- 推文详情:查看推文及其回复(支持 `--cursor` 翻页);用 `show ` 可直接打开上次列表里的第 N 条推文 +- 文章读取:获取 Twitter 长文(完整保留 Draft.js Markdown/链接/行内样式/嵌入推文),并导出为 Markdown - 列表时间线:获取 Twitter List 的推文 -- 用户查询:查看用户资料、推文、点赞、粉丝和关注 -- `--full-text`:在 rich table 输出里关闭推文正文截断 +- 用户查询:支持 `@handle` 或纯数字 user ID 查询资料、推文、点赞、粉丝和关注 +- 展示与工具:`--full-text` 关闭正文截断、`--time relative|absolute|iso` 控制时间格式、`completion bash|zsh|fish`、`doctor [--refresh]` - 结构化输出:支持 YAML 和 JSON,便于脚本处理和 AI agent 集成 +- Python 库 API:可直接 `from twitter_cli import TwitterClient, get_cookies` 调用 > **AI Agent 提示:** 需要结构化输出时优先使用 `--yaml`,除非下游必须是 JSON。stdout 不是 TTY 时默认输出 YAML。用 `--max` 控制返回数量。 **写入:** -- 发推:发布新推文和回复,支持附带图片(最多 4 张,支持 JPEG/PNG/GIF/WebP) -- 引用推文:带评论的转发,也支持附带图片 +- 发推:发布新推文和回复,支持附带图片(最多 4 张)或视频(`--video` / `-V`,MP4/MOV/WebM,最大 512 MB) +- 长推文自动适配:超过 280 加权字符时自动切换 `CreateNoteTweet`(需 X Premium) +- 长文发布:`twitter article-publish` 直接从 Markdown 发布 X Article 或保存草稿 +- 引用推文:带评论的转发,支持附带图片或视频 - 删除:删除自己的推文 - 点赞 / 取消点赞 - 转推 / 取消转推 @@ -397,12 +456,12 @@ git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli - 写操作现在也显式支持 `--json` / `--yaml` **认证与反风控:** -- Cookie 认证:支持环境变量和浏览器自动提取 +- Cookie 认证:支持环境变量(`TWITTER_COOKIE_STRING` 或 `TWITTER_AUTH_TOKEN` + `TWITTER_CT0`)和浏览器自动提取(Arc/Chrome/Edge/Firefox/Brave/Vivaldi/Zen 及自定义 Chromium 目录) - 完整 Cookie 转发:提取浏览器中所有 Twitter Cookie,保留更多浏览器上下文 - TLS 指纹伪装:`curl_cffi` 动态匹配 Chrome 版本 -- `x-client-transaction-id` 请求头生成 -- 请求时序随机化(jitter) -- 写操作随机延迟(1.5–4 秒),降低频率风控 +- `x-client-transaction-id` 请求头生成,写操作缺失签名时默认 fail-closed 拦截以防 226 风控 +- GraphQL `queryId` 24 小时本地缓存、实时 bundle 刷新与 `TWITTER_QID_` 覆盖 +- 请求时序随机化(jitter)与写操作随机延迟(1.5–4 秒),降低频率风控 - 代理支持:`TWITTER_PROXY` 环境变量 ### 安装 @@ -433,8 +492,12 @@ twitter feed --cursor "<上一页返回的 nextCursor>" # 收藏 twitter bookmarks +twitter bookmarks --cursor "<上一页返回的 nextCursor>" twitter bookmarks --full-text +# Explore 新闻 +twitter news --max 20 + # 搜索 twitter search "Claude Code" twitter search "AI agent" -t Latest --max 50 @@ -444,6 +507,7 @@ twitter search "trending" --filter # 启用排序筛选 # 推文详情 twitter tweet 1234567890 +twitter tweet 1234567890 --cursor "" twitter tweet 1234567890 --full-text # 通过序号打开上次列表里的推文 @@ -451,19 +515,22 @@ twitter show 2 # 打开上次 feed/search 的第 2 条 twitter show 2 --full-text # 在回复表格里显示完整正文 twitter show 2 --json # 结构化输出 -# Twitter 长文 +# Twitter 长文(读取与发布) twitter article 1234567890 twitter article https://x.com/user/article/1234567890 --json twitter article 1234567890 --markdown twitter article 1234567890 --output article.md +twitter article-publish post.md --title "我的长文" +twitter article-publish post.md --title "草稿标题" --draft # 列表时间线 twitter list 1539453138322673664 twitter list 1539453138322673664 --cursor "<上一页返回的 nextCursor>" twitter list 1539453138322673664 --full-text -# 用户 +# 用户(支持 @handle 或纯数字 ID) twitter user elonmusk +twitter user 44196397 twitter user-posts elonmusk --max 20 twitter user-posts elonmusk --full-text twitter user-posts elonmusk -o tweets.json @@ -477,6 +544,7 @@ twitter following elonmusk twitter post "你好,世界!" twitter post "发图" --image photo.jpg # 带图发推 twitter post "多图" -i a.png -i b.jpg -i c.webp # 最多 4 张图片 +twitter post "发视频" --video clip.mp4 # 带视频发推(最大 512 MB) twitter post "回复内容" --reply-to 1234567890 twitter reply 1234567890 "回复" -i screenshot.png # 带图回复 twitter quote 1234567890 "评论" -i chart.png # 带图引用 @@ -490,14 +558,20 @@ twitter unretweet 1234567890 twitter bookmark 1234567890 twitter unbookmark 1234567890 twitter follow elonmusk --json + +# 展示、补全与诊断 +twitter --time relative feed # relative | absolute | iso +twitter completion zsh # bash | zsh | fish +twitter doctor --refresh # 检查环境并刷新 GraphQL queryId 缓存 ``` ### 认证说明 认证优先级: -1. **环境变量**:`TWITTER_AUTH_TOKEN` + `TWITTER_CT0` -2. **浏览器提取**(推荐):Arc/Chrome/Edge/Firefox/Brave 全量 Cookie 提取 +1. **完整 Cookie 字符串**:`TWITTER_COOKIE_STRING`(完整 `Cookie:` 请求头,自动解析 `auth_token` + `ct0` 并保留全部会话 Cookie,适合云端/Windows Chrome >=127) +2. **环境变量**:`TWITTER_AUTH_TOKEN` + `TWITTER_CT0` +3. **浏览器提取**(本地推荐):Arc/Chrome/Edge/Firefox/Brave/Vivaldi/Zen 全量 Cookie 提取 推荐使用浏览器提取方式,会转发所有 Twitter Cookie,并按本机运行环境生成语言和平台请求头;它比仅发送 `auth_token` + `ct0` 更接近普通浏览器流量,但不等于完整浏览器自动化。 @@ -507,12 +581,20 @@ twitter follow elonmusk --json TWITTER_CHROME_PROFILE="Profile 2" twitter feed ``` +**自定义 Chromium 目录**:适用于 Chromium、Opera 或自定义数据目录: + +```bash +TWITTER_CHROMIUM_USER_DATA_DIR="/path/to/User Data" twitter feed +``` + **浏览器优先级**:如果有多个浏览器,可通过 `TWITTER_BROWSER` 指定优先尝试的浏览器: ```bash -TWITTER_BROWSER=chrome twitter feed # 支持: arc, chrome, edge, firefox, brave +TWITTER_BROWSER=chrome twitter feed # 支持: arc, chrome, edge, firefox, brave, vivaldi, zen ``` +配置文件查找顺序:显式路径 → 当前目录 `./config.yaml` → `~/.twitter-cli/config.yaml` → 内置默认配置。 + ### 代理支持 设置 `TWITTER_PROXY` 环境变量即可: diff --git a/SCHEMA.md b/SCHEMA.md index 2b8a64c..f68c0c9 100644 --- a/SCHEMA.md +++ b/SCHEMA.md @@ -27,11 +27,22 @@ error: - `--yaml` and `--json` both use this envelope - non-TTY stdout defaults to YAML - tweet and user lists are returned under `data` -- timeline-style list commands may also return `pagination.nextCursor` +- timeline-style list commands (`feed`, `bookmarks`, `list`, `tweet`) may also return `pagination.nextCursor` - `article` returns a single tweet object under `data` +- `news` returns a list of Explore News story objects (`id`, `headline`, `category`, `timeAgo`, `postCount`, `summary`, `hook`, `keywords`, `tweetIds`, `url`) under `data` +- `doctor` returns `data.checks` (metadata only — never emits cookies or tokens) - `status` returns `data.authenticated` plus `data.user` - `whoami` returns `data.user` -- write commands also support explicit `--json` / `--yaml` +- write commands (`post`, `reply`, `quote`, `article-publish`, etc.) also support explicit `--json` / `--yaml` + +## Tweet & Media Fields + +Each tweet object in `data` includes: + +- `author`: `id`, `name`, `screenName`, `profileImageUrl`, `verified`, `followers`, `following`, plus optional `viewerFollowing` / `viewerFollowedBy` (when present in upstream payload) +- `possiblySensitive`: boolean flag from the tweet payload +- Thread metadata (included when present): `conversationId`, `inReplyToStatusId`, `inReplyToUserId`, `inReplyToScreenName` +- `media[]`: `type`, `url`, `width`, `height`, `adultContent`, `graphicViolence`, `otherWarning`, plus optional `posterUrl`, `altText`, `durationMs` ## Article Fields @@ -54,4 +65,7 @@ Common structured error codes: - `not_found` - `invalid_input` - `rate_limited` +- `network_error` +- `query_id_error` +- `media_upload_error` - `api_error` diff --git a/SKILL.md b/SKILL.md index 82a3afe..179ddad 100644 --- a/SKILL.md +++ b/SKILL.md @@ -19,7 +19,7 @@ tags: ## Setup ```bash -# Install (requires Python 3.8+) +# Install (requires Python 3.10+) uv tool install twitter-cli # Or: pipx install twitter-cli @@ -47,9 +47,10 @@ If `AUTH_NEEDED`, proceed to guide the user: **Method A: Browser cookie extraction (recommended)** -Ensure user is logged into x.com in one of: Arc, Chrome, Edge, Firefox, Brave. twitter-cli auto-extracts cookies. +Ensure user is logged into x.com in one of: Arc, Chrome, Edge, Firefox, Brave, Vivaldi, Zen. twitter-cli auto-extracts cookies. All Chrome profiles are scanned automatically. To specify a profile: `TWITTER_CHROME_PROFILE="Profile 2" twitter feed`. -To prioritize a specific browser: `TWITTER_BROWSER=chrome twitter feed` (supported: arc, chrome, edge, firefox, brave). +To point to a custom Chromium user data directory (e.g., Chromium, Opera, portable Chrome): `TWITTER_CHROMIUM_USER_DATA_DIR="/path/to/User Data" twitter feed`. +To prioritize a specific browser: `TWITTER_BROWSER=chrome twitter feed` (supported: arc, chrome, edge, firefox, brave, vivaldi, zen). ```bash twitter whoami @@ -63,9 +64,16 @@ export TWITTER_CT0="" twitter whoami ``` -**Method C: Full cookie string (for cloud/remote agents)** +**Method C: Full cookie string (recommended for cloud/remote agents & Windows Chrome >=127)** -Tell the user: +Pass the full browser `Cookie:` header via `TWITTER_COOKIE_STRING` (preserves all session/anti-bot cookies and auto-extracts `auth_token` + `ct0`): + +```bash +export TWITTER_COOKIE_STRING="auth_token=...; ct0=...; twid=..." +twitter whoami +``` + +If asking the user to copy it: > 我需要你的 Twitter 登录凭证。请按以下步骤获取: > @@ -73,18 +81,7 @@ Tell the user: > 2. 按 `F12` 打开开发者工具 → **Network** 标签 > 3. 在页面上刷新,点击任意 `x.com` 请求 > 4. 找到 **Request Headers** → **Cookie:** 这一行,右键 → 复制值 -> 5. 把完整 Cookie 字符串发给我 -> -> ⚠️ Cookie 包含登录信息,请不要分享给其他人。 - -Then extract and set env vars: - -```bash -FULL_COOKIE="" -export TWITTER_AUTH_TOKEN=$(echo "$FULL_COOKIE" | grep -oE 'auth_token=[a-f0-9]+' | cut -d= -f2) -export TWITTER_CT0=$(echo "$FULL_COOKIE" | grep -oE 'ct0=[a-f0-9]+' | cut -d= -f2) -twitter whoami -``` +> 5. 把完整 Cookie 字符串设置为 `TWITTER_COOKIE_STRING` 环境变量(⚠️ Cookie 包含登录信息,请不要分享给其他人)。 ### Step 2: Handle common auth issues @@ -144,31 +141,38 @@ twitter -c search "AI" --max 20 # ~80% fewer tokens than --json ```bash twitter status # Quick auth check twitter status --yaml # Structured auth status +twitter doctor # Diagnostics (deps, config, auth presence, caches) +twitter doctor --refresh # Refresh cached GraphQL query IDs twitter whoami # Current authenticated user twitter whoami --yaml # YAML output twitter whoami --json # JSON output -twitter user elonmusk # User profile -twitter user elonmusk --json # JSON output +twitter user elonmusk # User profile (screen name or numeric rest_id) +twitter user 44196397 --json # Lookup by numeric user ID twitter feed # Home timeline (For You) twitter feed -t following # Following timeline twitter feed --max 50 # Limit count twitter feed --full-text # Show full post body in table +twitter --time iso feed # Timestamp display: relative | absolute | iso twitter feed --filter # Enable ranking filter twitter feed --yaml > tweets.yaml # Export as YAML twitter feed --input tweets.json # Read from local JSON file twitter bookmarks # Bookmarked tweets +twitter bookmarks --cursor "" # Paginate bookmarks twitter bookmarks --full-text # Full text in bookmarks table twitter bookmarks --max 30 --yaml +twitter news --max 20 # Explore > News personalized stories twitter search "keyword" # Search tweets twitter search "AI agent" -t Latest --max 50 twitter search "AI agent" --full-text # Full text in search results twitter search "topic" -o results.json # Save to file twitter tweet 1234567890 # Tweet detail + replies +twitter tweet 1234567890 --cursor "" # Paginate replies twitter tweet 1234567890 --full-text # Full text in reply table twitter tweet https://x.com/user/status/12345 # Accepts URL twitter show 2 # Open tweet #2 from last feed/search list twitter show 2 --full-text # Full text in reply table twitter show 2 --json # Structured output +twitter article 1234567890 --markdown # Fetch Twitter Article as Markdown twitter list 1539453138322673664 # List timeline twitter list 1539453138322673664 --cursor "" twitter list 1539453138322673664 --full-text @@ -178,19 +182,24 @@ twitter likes elonmusk --max 30 # User's likes (own only, see note) twitter likes elonmusk --full-text twitter followers elonmusk --max 50 # Followers twitter following elonmusk --max 50 # Following +twitter completion zsh # Print shell completion (bash/zsh/fish) ``` ### Write Operations ```bash -twitter post "Hello from twitter-cli!" # Post tweet +twitter post "Hello from twitter-cli!" # Post tweet (auto-uses CreateNoteTweet for >280 chars on Premium) twitter post "Hello!" --image photo.jpg # Post with image twitter post "Gallery" -i a.png -i b.jpg # Up to 4 images +twitter post "Demo clip" --video clip.mp4 # Post with video (mp4/mov/webm up to 512 MB) twitter reply 1234567890 "Great tweet!" # Reply (standalone) twitter reply 1234567890 "Nice!" -i pic.png # Reply with image +twitter reply 1234567890 "Clip" -V clip.mp4 # Reply with video twitter post "reply text" --reply-to 1234567890 # Reply (via post) twitter quote 1234567890 "Interesting take" # Quote-tweet twitter quote 1234567890 "Look" -i chart.png # Quote with image +twitter quote 1234567890 "Clip" -V clip.mp4 # Quote with video +twitter article-publish post.md --title "My Post" # Publish X Article from Markdown (--draft for draft) twitter delete 1234567890 # Delete tweet twitter like 1234567890 # Like twitter unlike 1234567890 # Unlike @@ -202,11 +211,9 @@ twitter follow elonmusk # Follow user twitter unfollow elonmusk # Unfollow user ``` -**Image upload notes:** -- Supported formats: JPEG, PNG, GIF, WebP -- Max file size: 5 MB per image -- Max 4 images per tweet -- Use `--image` / `-i` (repeatable) +**Media upload notes:** +- Images: JPEG, PNG, GIF, WebP — max 5 MB per image, up to 4 images per tweet (`--image` / `-i`) +- Video: MP4, MOV, WebM — max 512 MB, 1 video per tweet (`--video` / `-V`, chunked upload + async processing poll); cannot mix images and video in the same tweet ## Agent Workflows @@ -331,16 +338,17 @@ twitter bookmarks --filter ## Limitations -- **Images only** — video/GIF animation upload not yet supported (image upload supports JPEG/PNG/GIF/WebP) - **No DMs** — no direct messaging - **No notifications** — can't read notifications - **No polls** — can't create polls - **Single account** — one set of credentials at a time - **Likes are private** — Twitter/X made all likes private since June 2024. `twitter likes` only works for your own account +- **Long-form posts & Articles** — posts > 280 weighted chars automatically use `CreateNoteTweet` and `article-publish` publishes X Articles (both require an X Premium account) ## Safety Notes - Write operations have built-in random delays (1.5–4s) to avoid rate limits. +- GraphQL write (`POST`) requests fail closed if `x-client-transaction-id` cannot be generated, preventing unsigned-write 226 flags (override only for debugging with `TWITTER_ALLOW_UNSIGNED=1`). - TLS fingerprint and User-Agent are automatically matched to the Chrome version used. - Do not ask users to share raw cookie values in chat logs. - Prefer local browser cookie extraction over manual secret copy/paste. diff --git a/tests/test_public_api.py b/tests/test_public_api.py new file mode 100644 index 0000000..eace3b6 --- /dev/null +++ b/tests/test_public_api.py @@ -0,0 +1,36 @@ +"""Tests for the public Python library API exported from twitter_cli.""" + +import twitter_cli + + +def test_public_api_exports(): + expected = { + "__version__", + "TwitterClient", + "get_cookies", + "load_config", + "filter_tweets", + "Author", + "BookmarkFolder", + "Metrics", + "Tweet", + "TweetMedia", + "UserProfile", + "TwitterError", + "AuthenticationError", + "InvalidInputError", + "MediaUploadError", + "NetworkError", + "NotFoundError", + "QueryIdError", + "RateLimitError", + "TwitterAPIError", + "tweet_to_dict", + "tweet_from_dict", + "tweets_to_json", + "tweets_from_json", + "user_profile_to_dict", + } + assert expected.issubset(set(twitter_cli.__all__)) + for name in twitter_cli.__all__: + assert hasattr(twitter_cli, name), f"Missing exported symbol: {name}" diff --git a/twitter_cli/__init__.py b/twitter_cli/__init__.py index d14197d..cf7299c 100644 --- a/twitter_cli/__init__.py +++ b/twitter_cli/__init__.py @@ -1,4 +1,6 @@ -"""twitter-cli: A CLI for Twitter/X.""" +"""twitter-cli: A terminal-first CLI and Python library for Twitter/X.""" + +from __future__ import annotations try: from importlib.metadata import version @@ -6,3 +8,69 @@ __version__ = version("twitter-cli") except Exception: __version__ = "0.0.0" + +from .auth import get_cookies +from .client import TwitterClient +from .config import load_config +from .exceptions import ( + AuthenticationError, + InvalidInputError, + MediaUploadError, + NetworkError, + NotFoundError, + QueryIdError, + RateLimitError, + TwitterAPIError, + TwitterError, +) +from .filter import filter_tweets +from .models import Author, BookmarkFolder, Metrics, Tweet, TweetMedia, UserProfile +from .serialization import ( + bookmark_folder_to_dict, + bookmark_folders_to_data, + tweet_from_dict, + tweet_to_compact_dict, + tweet_to_dict, + tweets_from_json, + tweets_to_compact_json, + tweets_to_data, + tweets_to_json, + user_profile_to_dict, + users_to_data, + users_to_json, +) + +__all__ = [ + "__version__", + "TwitterClient", + "get_cookies", + "load_config", + "filter_tweets", + "Author", + "BookmarkFolder", + "Metrics", + "Tweet", + "TweetMedia", + "UserProfile", + "TwitterError", + "AuthenticationError", + "InvalidInputError", + "MediaUploadError", + "NetworkError", + "NotFoundError", + "QueryIdError", + "RateLimitError", + "TwitterAPIError", + "tweet_to_dict", + "tweet_from_dict", + "tweets_to_json", + "tweets_from_json", + "tweets_to_data", + "tweet_to_compact_dict", + "tweets_to_compact_json", + "bookmark_folder_to_dict", + "bookmark_folders_to_data", + "user_profile_to_dict", + "users_to_data", + "users_to_json", +] From b3df49ab432392823f0206b942750da62354a12c Mon Sep 17 00:00:00 2001 From: jackwener Date: Sat, 28 Nov 2026 03:34:48 +0000 Subject: [PATCH 8/8] fix(review): harden cache atomicity, GraphQL fallback, media upload, parser/text edge cases, and docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses findings from full adversarial code review of PR #106: - Cache security (`cache.py`, `client.py`, `graphql.py`): replace in-place truncating writes with atomic `O_CREAT | O_EXCL | O_NOFOLLOW` sibling temp file + `os.replace`, create cache dirs with `0o700`, and preserve `created_at` on incremental queryId disk merges while replacing cleanly on `refresh_query_ids()`. - GraphQL & ClientTransaction (`graphql.py`, `client.py`): pass `exclude_ids` on stale queryId retries so lagged `twitter-openapi` IDs fall through to live `_scan_bundles`; anchor Vite `x-web` asset URLs to `/x-web/x-web/` (fixes `/assets/assets/` 404); recognize HTTP 400 stale-query errors; prefer unauthenticated `/i/jf/` first, validate `ClientTransaction(...)` inside the candidate loop, and avoid caching authenticated `/home` HTML on disk. - TweetDetail, media upload & deeplinks (`client.py`): return `([], None)` when `count <= 0` with `return_cursor=True`; place focal tweet first before slicing to `count` so replies with ancestors don't raise false `NotFoundError`; restore `tweet_gif` category + `STATUS` polling for GIFs; allowlist mp4/mov/webm video MIME types; reject 0-byte uploads; lower video chunk size to 2 MB (under 5 MB base64 cap); use `time.monotonic()` and guard `check_after_secs: null` in `STATUS` polling; fix `twitter://trending/?...` and `twitter://search?...` deeplink parsing. - Auth (`auth.py`): sanitize `TWITTER_COOKIE_STRING` (`Cookie:` prefix, CR/LF, quotes) and rebuild cookie header when `TWITTER_AUTH_TOKEN`/`TWITTER_CT0` override or supplement it; add Flatpak `config/zen` path & normalize Windows Zen paths; check profile parent `Local State` first and try Chromium-family keychain loaders on non-Windows for `TWITTER_CHROMIUM_USER_DATA_DIR`; detect Windows DPAPI errors. - Parser, text, article & formatter (`parser.py`, `text.py`, `article.py`, `formatter.py`): map Draft.js UTF-16 code unit offsets to Python indices so emoji + links/styles round-trip cleanly; guard `null` nested user dicts & strings; restrict bare-URL matching to ASCII hostnames with common IANA TLDs (prevents `config.yaml`/`cli.py` misrouting to `CreateNoteTweet`); refine `©`/`®`, Geometric Shapes emoji, and repeated trailing URL trimming; support `###` headings, balanced-paren link URLs, inline-code/image/math preservation, and strict fenced-code opening in `article.py`; widen `--time iso` Stats column, render `print_article` time via `_render_time`, and reset `set_time_style(None)` to `"relative"`. - CLI, library API, docs & tests (`cli.py`, `__init__.py`, `SCHEMA.md`, `SKILL.md`, `README.md`, `pyproject.toml`, `tests/`): lazy PEP 562 exports in `__init__.py` and resilient `.client` import so `doctor` works when deps are missing; guard invalid tweet IDs with `InvalidInputError` across write commands; validate `article-publish` title/UTF-8/non-empty input, upfront media MIME/count checks, `news --max >= 1`, `doctor` error exit code + `query_ids` TTL, and `likes` own numeric ID check; fix `SCHEMA.md` `news` fields, `SKILL.md` `jq` queries, `README.md` `display.time` default & EN/ZH parity, `public-clis/twitter-cli` URLs; isolate `~/.twitter-cli` caches and `TWITTER_*` env vars in `tests/conftest.py` and add 25 regression tests. --- README.md | 51 +++- SCHEMA.md | 2 +- SKILL.md | 20 +- pyproject.toml | 6 +- tests/conftest.py | 22 ++ tests/test_cli.py | 2 +- tests/test_client.py | 54 ++-- tests/test_curl_cffi_floor.py | 15 +- tests/test_review_regressions.py | 460 +++++++++++++++++++++++++++++++ tests/test_time_style.py | 30 +- twitter_cli/__init__.py | 113 ++++++-- twitter_cli/article.py | 115 ++++++-- twitter_cli/auth.py | 95 +++++-- twitter_cli/cache.py | 70 +++-- twitter_cli/cli.py | 272 +++++++++++++----- twitter_cli/client.py | 192 +++++++------ twitter_cli/formatter.py | 9 +- twitter_cli/graphql.py | 51 ++-- twitter_cli/parser.py | 100 ++++--- twitter_cli/text.py | 47 +++- 20 files changed, 1358 insertions(+), 368 deletions(-) create mode 100644 tests/test_review_regressions.py diff --git a/README.md b/README.md index 5e646b2..93b6265 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # twitter-cli -[![CI](https://github.com/jackwener/twitter-cli/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/jackwener/twitter-cli/actions/workflows/ci.yml) +[![CI](https://github.com/public-clis/twitter-cli/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/public-clis/twitter-cli/actions/workflows/ci.yml) [![PyPI version](https://badge.fury.io/py/twitter-cli.svg)](https://pypi.org/project/twitter-cli/) [![Python](https://img.shields.io/badge/python-%3E%3D3.10-blue.svg)](https://pypi.org/project/twitter-cli/) @@ -78,7 +78,7 @@ uv tool upgrade twitter-cli Install from source: ```bash -git clone git@github.com:jackwener/twitter-cli.git +git clone git@github.com:public-clis/twitter-cli.git cd twitter-cli uv sync ``` @@ -262,7 +262,7 @@ fetch: count: 50 display: - time: "absolute" # "absolute" | "relative" | "iso" + time: "relative" # "relative" | "absolute" | "iso" filter: mode: "topN" # "topN" | "score" | "all" @@ -328,9 +328,9 @@ Mode behavior: ### Troubleshooting - `No Twitter cookies found` - - Ensure you are logged in to `x.com` in a supported browser (Arc/Chrome/Edge/Firefox/Brave). - - Or set `TWITTER_AUTH_TOKEN` and `TWITTER_CT0` manually. - - Run with `-v` to see browser extraction diagnostics. + - Ensure you are logged in to `x.com` in a supported browser (Arc/Chrome/Edge/Firefox/Brave/Vivaldi/Zen) or point to a custom directory with `TWITTER_CHROMIUM_USER_DATA_DIR`. + - Or set `TWITTER_COOKIE_STRING` (recommended for headless/Windows Chrome >=127) or `TWITTER_AUTH_TOKEN` + `TWITTER_CT0` manually. + - Run with `-v` or `twitter doctor` to see diagnostics. - `Cookie expired or invalid (HTTP 401/403)` - Re-login to `x.com` and retry. @@ -358,7 +358,7 @@ Mode behavior: -Structured error codes commonly include `not_authenticated`, `not_found`, `invalid_input`, `rate_limited`, and `api_error`. +Structured error codes commonly include `not_authenticated`, `not_found`, `invalid_input`, `rate_limited`, `network_error`, `query_id_error`, `media_upload_error`, and `api_error`. ### Development @@ -405,7 +405,7 @@ twitter-cli ships with a [`SKILL.md`](./SKILL.md) so AI agents can execute commo #### [Skills CLI](https://github.com/vercel-labs/skills) (Recommended) ```bash -npx skills add jackwener/twitter-cli +npx skills add public-clis/twitter-cli ``` | Flag | Description | @@ -418,7 +418,7 @@ npx skills add jackwener/twitter-cli ```bash mkdir -p .agents/skills -git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli +git clone git@github.com:public-clis/twitter-cli.git .agents/skills/twitter-cli ``` #### ~~OpenClaw / ClawHub~~ (Deprecated) @@ -562,9 +562,26 @@ twitter follow elonmusk --json # 展示、补全与诊断 twitter --time relative feed # relative | absolute | iso twitter completion zsh # bash | zsh | fish +twitter doctor # 检查依赖、配置、认证状态与缓存 twitter doctor --refresh # 检查环境并刷新 GraphQL queryId 缓存 ``` +### Python 库调用 + +```python +from twitter_cli import TwitterClient, get_cookies + +cookies = get_cookies() +client = TwitterClient( + cookies["auth_token"], + cookies["ct0"], + cookie_string=cookies.get("cookie_string"), +) +tweets = client.fetch_home_timeline(count=20) +for tweet in tweets: + print(f"@{tweet.author.screen_name}: {tweet.text[:80]}") +``` + ### 认证说明 认证优先级: @@ -593,7 +610,11 @@ TWITTER_CHROMIUM_USER_DATA_DIR="/path/to/User Data" twitter feed TWITTER_BROWSER=chrome twitter feed # 支持: arc, chrome, edge, firefox, brave, vivaldi, zen ``` -配置文件查找顺序:显式路径 → 当前目录 `./config.yaml` → `~/.twitter-cli/config.yaml` → 内置默认配置。 +**高级 GraphQL 与签名环境变量**: +- `TWITTER_QID_=` — 运行时覆盖指定 GraphQL operation 的 queryId(例如 `TWITTER_QID_HomeTimeline=...`) +- `TWITTER_ALLOW_UNSIGNED=1` — 当写操作(`POST`)无法生成 `x-client-transaction-id` 时默认 fail-closed 拦截以防 226 风控,仅调试时可显式设此变量绕过 + +**配置文件**:查找顺序为显式路径 → `./config.yaml` → `~/.twitter-cli/config.yaml` → 内置默认配置。可在 `display.time` 设置默认时间格式(`relative` / `absolute` / `iso`),显式 `--max` 可突破默认 `rateLimit.maxCount`(200)直到 10,000 安全上限。结构化输出规范见 [SCHEMA.md](./SCHEMA.md)。 ### 代理支持 @@ -633,8 +654,8 @@ score = likes_w * likes ### 常见问题 -- 报错 `No Twitter cookies found`:请先登录 `x.com`,并确认浏览器为 Arc/Chrome/Edge/Firefox/Brave 之一,或手动设置环境变量。 -- 如需查看浏览器提取细节,可加 `-v` 打开诊断日志。 +- 报错 `No Twitter cookies found`:请先登录 `x.com`,并确认浏览器为 Arc/Chrome/Edge/Firefox/Brave/Vivaldi/Zen 之一(或通过 `TWITTER_CHROMIUM_USER_DATA_DIR` 指定目录),或手动设置 `TWITTER_COOKIE_STRING` / `TWITTER_AUTH_TOKEN` + `TWITTER_CT0`。 +- 如需查看浏览器提取细节或环境状态,可加 `-v` 或运行 `twitter doctor`。 - 报错 `Cookie expired or invalid`:Cookie 过期,重新登录后重试。 - 报错 `Unable to get key for cookie decryption`(macOS Keychain 问题): - **SSH 远程登录**:Keychain 默认锁定,需手动解锁: @@ -653,7 +674,7 @@ score = likes_w * likes -- 结构化错误码通常会区分 `not_authenticated`、`not_found`、`invalid_input`、`rate_limited`、`api_error`。 +- 结构化错误码通常会区分 `not_authenticated`、`not_found`、`invalid_input`、`rate_limited`、`network_error`、`query_id_error`、`media_upload_error`、`api_error`。 ### 使用建议(防封号) @@ -678,7 +699,7 @@ twitter-cli 提供了 [`SKILL.md`](./SKILL.md),可让 AI Agent 更稳定地调 #### [Skills CLI](https://github.com/vercel-labs/skills)(推荐) ```bash -npx skills add jackwener/twitter-cli +npx skills add public-clis/twitter-cli ``` | 参数 | 说明 | @@ -691,7 +712,7 @@ npx skills add jackwener/twitter-cli ```bash mkdir -p .agents/skills -git clone git@github.com:jackwener/twitter-cli.git .agents/skills/twitter-cli +git clone git@github.com:public-clis/twitter-cli.git .agents/skills/twitter-cli ``` #### ~~OpenClaw / ClawHub~~(已过时) diff --git a/SCHEMA.md b/SCHEMA.md index f68c0c9..505adef 100644 --- a/SCHEMA.md +++ b/SCHEMA.md @@ -29,7 +29,7 @@ error: - tweet and user lists are returned under `data` - timeline-style list commands (`feed`, `bookmarks`, `list`, `tweet`) may also return `pagination.nextCursor` - `article` returns a single tweet object under `data` -- `news` returns a list of Explore News story objects (`id`, `headline`, `category`, `timeAgo`, `postCount`, `summary`, `hook`, `keywords`, `tweetIds`, `url`) under `data` +- `news` returns a list of Explore News story objects (`rank`, `title`, `name`, `category`, `context`, `query`, `url`, `post_count`, `trend_id`, `is_ai_trend`, `type`) under `data` - `doctor` returns `data.checks` (metadata only — never emits cookies or tokens) - `status` returns `data.authenticated` plus `data.user` - `whoami` returns `data.user` diff --git a/SKILL.md b/SKILL.md index 179ddad..99b0388 100644 --- a/SKILL.md +++ b/SKILL.md @@ -2,7 +2,7 @@ name: twitter-cli description: Use twitter-cli for ALL Twitter/X operations — reading tweets, posting, replying, quoting, liking, retweeting, following, searching, user lookups. Invoke whenever user requests any Twitter interaction. author: jackwener -version: "0.8.0" +version: "0.8.6" tags: - twitter - x @@ -32,7 +32,7 @@ uv tool upgrade twitter-cli **IMPORTANT FOR AGENTS**: Before executing ANY twitter-cli command, you MUST first check if credentials exist. If not, you MUST proactively guide the user through the authentication process. Do NOT assume credentials are configured. -**CRITICAL**: Write operations (posting tweets, replying, quoting) REQUIRE full browser cookies. Only providing `auth_token` + `ct0` via env vars may result in **226 error** ("looks like automated behavior"). For best results, use browser cookie extraction. +**CRITICAL**: Write operations (posting tweets, replying, quoting) REQUIRE full browser cookies. Only providing `auth_token` + `ct0` via env vars may result in **226 error** ("looks like automated behavior"). For best results, use browser cookie extraction or `TWITTER_COOKIE_STRING` (full `Cookie:` header). ### Step 0: Check if already authenticated @@ -88,7 +88,7 @@ If asking the user to copy it: | Symptom | Agent action | |---------|-------------| | `No Twitter cookies found` | Guide user to login to x.com in browser, or set env vars | -| Read works, write returns 226 | Full cookies missing — use browser cookie extraction instead of env vars | +| Read works, write returns 226 | Full cookies missing — use browser cookie extraction or `TWITTER_COOKIE_STRING` instead of minimal `auth_token`/`ct0` env vars | | `Cookie expired (401/403)` | Ask user to re-login to x.com and retry | | User changed password | All old cookies invalidated — re-extract | @@ -106,7 +106,7 @@ Non-TTY stdout defaults to YAML automatically. Use `OUTPUT=yaml|json|rich|auto` ```bash twitter feed --yaml -twitter feed --json | jq '.[0].text' +twitter feed --json | jq '.data[0].text' ``` All machine-readable output uses the envelope documented in [SCHEMA.md](./SCHEMA.md). @@ -269,7 +269,7 @@ done ### Get user info then follow ```bash -twitter user targethandle --json | jq '.data | {username, followers, bio}' +twitter user targethandle --json | jq '.data | {screenName, followers, bio}' twitter follow targethandle ``` @@ -282,8 +282,8 @@ twitter user-posts elonmusk --max 20 --json | jq '.data | sort_by(.metrics.likes ### Check follower relationship ```bash -MY_NAME=$(twitter whoami --json | jq -r '.data.user.username') -twitter followers "$MY_NAME" --max 200 --json | jq -r '.data[].username' | grep -q "targetuser" && echo "Yes" || echo "No" +MY_NAME=$(twitter whoami --json | jq -r '.data.user.screenName') +twitter followers "$MY_NAME" --max 200 --json | jq -r '.data[].screenName' | grep -q "targetuser" && echo "Yes" || echo "No" ``` ### Daily reading workflow @@ -329,12 +329,12 @@ twitter bookmarks --filter | Error | Cause | Fix | |-------|-------|-----| | `No Twitter cookies found` | Not authenticated | Login to x.com in browser, or set env vars | -| HTTP 226 | Automated detection | Use browser cookie extraction (not env vars) | +| HTTP 226 | Automated detection | Use browser cookie extraction or full `TWITTER_COOKIE_STRING` | | HTTP 401/403 | Cookie expired | Re-login to x.com and retry | -| HTTP 404 | QueryId rotation | Retry (auto-fallback built in) | +| HTTP 404 | QueryId rotation | Retry (auto-fallback built in) or run `twitter doctor --refresh` | | HTTP 429 | Rate limited | Wait 15+ minutes, then retry | | Error 187 | Duplicate tweet | Change text content | -| Error 186 | Tweet too long | Keep under 280 chars | +| Error 186 | Tweet too long | Keep under 280 weighted chars (or use X Premium, which auto-routes via `CreateNoteTweet`) | ## Limitations diff --git a/pyproject.toml b/pyproject.toml index 14378c3..e53ea60 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,9 +41,9 @@ dev = [ ] [project.urls] -Homepage = "https://github.com/jackwener/twitter-cli" -Repository = "https://github.com/jackwener/twitter-cli" -Issues = "https://github.com/jackwener/twitter-cli/issues" +Homepage = "https://github.com/public-clis/twitter-cli" +Repository = "https://github.com/public-clis/twitter-cli" +Issues = "https://github.com/public-clis/twitter-cli/issues" [project.scripts] twitter = "twitter_cli.cli:cli" diff --git a/tests/conftest.py b/tests/conftest.py index 65f3bdc..9e5f0b0 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,6 +12,28 @@ os.environ.setdefault("OUTPUT", "rich") +@pytest.fixture(autouse=True) +def _isolate_env_and_caches(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """Prevent tests from reading/writing host ~/.twitter-cli caches or host TWITTER_* env vars.""" + from twitter_cli import cache as cache_mod + from twitter_cli import client as client_mod + from twitter_cli import graphql as graphql_mod + + for key in list(os.environ): + if key.startswith("TWITTER_") or key == "XDG_CONFIG_HOME": + monkeypatch.delenv(key, raising=False) + + cache_dir = tmp_path / ".twitter-cli-test-cache" + monkeypatch.setattr(cache_mod, "_CACHE_DIR", cache_dir) + monkeypatch.setattr(cache_mod, "_CACHE_FILE", cache_dir / "last_results.json") + monkeypatch.setattr(graphql_mod, "_qid_cache_path", lambda: cache_dir / "query_ids_cache.json") + monkeypatch.setattr( + client_mod.TwitterClient, + "_ct_cache_path", + staticmethod(lambda: str(cache_dir / "transaction_cache.json")), + ) + + @pytest.fixture() def tweet_factory(): def _make_tweet(tweet_id: str = "1", **overrides: Any) -> Tweet: diff --git a/tests/test_cli.py b/tests/test_cli.py index b830595..0fabfd9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1076,7 +1076,7 @@ def create_article(self, title, content_state, publish=True): cli, ["article-publish", str(markdown_path), "--title", "Article title", "--json"] ) assert pub_res.exit_code == 0, pub_res.output - payload = json.loads(pub_res.output[pub_res.output.index("{"):]) + payload = json.loads(pub_res.output) assert payload["data"]["id"] == "article-1" assert payload["data"]["published"] is True assert captured["content_state"]["blocks"][0]["type"] == "header-one" diff --git a/tests/test_client.py b/tests/test_client.py index 4936315..ed52003 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1717,22 +1717,22 @@ def _make_client(self, cookie_string=None): @patch("twitter_cli.client.ClientTransaction") @patch("twitter_cli.client._gen_ct_headers", return_value={"Referer": "https://x.com"}) @patch("twitter_cli.client._get_cffi_session") - def test_bootstraps_from_home_with_cookie( + def test_bootstraps_from_i_jf_without_cookie_first( self, mock_session, _mock_ct_headers, mock_tx, _mock_features ): import bs4 - home_page = MagicMock(content=_CT_HOME_HTML.encode("utf-8"), text=_CT_HOME_HTML) - ondemand_page = MagicMock(text=_CT_ONDEMAND_JS) - mock_session.return_value.get.side_effect = [home_page, ondemand_page] + jf_page = MagicMock(status_code=200, content=_CT_HOME_HTML.encode("utf-8"), text=_CT_HOME_HTML) + ondemand_page = MagicMock(status_code=200, text=_CT_ONDEMAND_JS) + mock_session.return_value.get.side_effect = [jf_page, ondemand_page] client = self._make_client(cookie_string="auth_token=auth_tok; ct0=ct0_val") client._ensure_client_transaction() first = mock_session.return_value.get.call_args_list[0] second = mock_session.return_value.get.call_args_list[1] - assert first.args[0] == "https://x.com/home" - assert first.kwargs["headers"]["Cookie"] == "auth_token=auth_tok; ct0=ct0_val" + assert first.args[0] == "https://x.com/i/jf/" + assert "Cookie" not in first.kwargs["headers"] assert second.args[0] == ( "https://abs.twimg.com/responsive-web/client-web/" "ondemand.s.38289b77fa31a72ca.js" @@ -1741,31 +1741,36 @@ def test_bootstraps_from_home_with_cookie( assert "Cookie" not in second.kwargs["headers"] mock_tx.assert_called_once() assert isinstance(mock_tx.call_args.kwargs["home_page_response"], bs4.BeautifulSoup) + client._save_ct_cache.assert_called_once() @patch("twitter_cli.client._update_features_from_html") @patch("twitter_cli.client.ClientTransaction") @patch("twitter_cli.client._gen_ct_headers", return_value={"Referer": "https://x.com"}) @patch("twitter_cli.client._get_cffi_session") - def test_falls_back_to_i_jf_when_home_lacks_ondemand( + def test_falls_back_to_authenticated_home_when_i_jf_fails_without_caching_auth_html( self, mock_session, _mock_ct_headers, mock_tx, _mock_features ): - stripped = MagicMock(content=_CT_STRIPPED_HTML.encode("utf-8"), text=_CT_STRIPPED_HTML) - jf_page = MagicMock(content=_CT_HOME_HTML.encode("utf-8"), text=_CT_HOME_HTML) - ondemand_page = MagicMock(text=_CT_ONDEMAND_JS) - mock_session.return_value.get.side_effect = [stripped, jf_page, ondemand_page] + stripped = MagicMock(status_code=200, content=_CT_STRIPPED_HTML.encode("utf-8"), text=_CT_STRIPPED_HTML) + home_page = MagicMock(status_code=200, content=_CT_HOME_HTML.encode("utf-8"), text=_CT_HOME_HTML) + ondemand_page = MagicMock(status_code=200, text=_CT_ONDEMAND_JS) + mock_session.return_value.get.side_effect = [stripped, home_page, ondemand_page] - client = self._make_client(cookie_string=None) + client = self._make_client(cookie_string="auth_token=auth_tok; ct0=ct0_val") client._ensure_client_transaction() calls = mock_session.return_value.get.call_args_list - assert calls[0].args[0] == "https://x.com/home" - assert calls[1].args[0] == "https://x.com/i/jf/" - assert "Cookie" not in calls[1].kwargs["headers"] + assert calls[0].args[0] == "https://x.com/i/jf/" + assert "Cookie" not in calls[0].kwargs["headers"] + assert calls[1].args[0] == "https://x.com/home" + assert calls[1].kwargs["headers"]["Cookie"] == "auth_token=auth_tok; ct0=ct0_val" assert calls[2].args[0] == ( "https://abs.twimg.com/responsive-web/client-web/" "ondemand.s.38289b77fa31a72ca.js" ) + assert "Cookie" not in calls[2].kwargs["headers"] mock_tx.assert_called_once() + # Authenticated /home HTML must not be persisted to disk. + client._save_ct_cache.assert_not_called() def test_real_parser_resolves_ondemand_from_current_layout(self): import bs4 @@ -2067,12 +2072,11 @@ def _make_client(self): @patch("twitter_cli.client._get_cffi_session") def test_upload_video_chunks_and_polls_status(self, mock_session, _mock_sleep, tmp_path): vid = tmp_path / "clip.mp4" - # 5 MB -> 2 chunks (4 MB + 1 MB) + # 5 MB -> 3 chunks (2 MB + 2 MB + 1 MB) staying under X's 5 MB base64 segment cap vid.write_bytes(b"\x00" * (5 * 1024 * 1024)) resp_init = MagicMock(status_code=200, text='{"media_id_string": "vid-999"}') - resp_append0 = MagicMock(status_code=204, text="") - resp_append1 = MagicMock(status_code=204, text="") + resp_append = MagicMock(status_code=204, text="") resp_finalize = MagicMock( status_code=200, text='{"media_id_string": "vid-999", "processing_info": {"state": "pending", "check_after_secs": 1}}', @@ -2083,7 +2087,9 @@ def test_upload_video_chunks_and_polls_status(self, mock_session, _mock_sleep, t ) sess = MagicMock() - sess.post = MagicMock(side_effect=[resp_init, resp_append0, resp_append1, resp_finalize]) + sess.post = MagicMock( + side_effect=[resp_init, resp_append, resp_append, resp_append, resp_finalize] + ) sess.get = MagicMock(return_value=resp_status) mock_session.return_value = sess @@ -2091,9 +2097,13 @@ def test_upload_video_chunks_and_polls_status(self, mock_session, _mock_sleep, t media_id = client.upload_media(str(vid)) assert media_id == "vid-999" - assert sess.post.call_count == 4 - assert sess.post.call_args_list[0].kwargs["data"]["media_category"] == "tweet_video" + assert sess.post.call_count == 5 + post_datas = [c.kwargs["data"] for c in sess.post.call_args_list] + assert [d["command"] for d in post_datas] == ["INIT", "APPEND", "APPEND", "APPEND", "FINALIZE"] + assert post_datas[0]["media_category"] == "tweet_video" + assert [d["segment_index"] for d in post_datas[1:4]] == ["0", "1", "2"] assert sess.get.call_count == 1 + assert sess.get.call_args.kwargs["params"] == {"command": "STATUS", "media_id": "vid-999"} @patch("twitter_cli.client.time.sleep") @patch("twitter_cli.client._get_cffi_session") @@ -2117,7 +2127,7 @@ def test_upload_video_raises_on_failed_processing(self, mock_session, _mock_slee mock_session.return_value = sess client = self._make_client() - with pytest.raises(MediaUploadError, match="Video processing failed"): + with pytest.raises(MediaUploadError, match="Media processing failed"): client.upload_media(str(vid)) diff --git a/tests/test_curl_cffi_floor.py b/tests/test_curl_cffi_floor.py index dc95035..81caf30 100644 --- a/tests/test_curl_cffi_floor.py +++ b/tests/test_curl_cffi_floor.py @@ -22,15 +22,12 @@ def _declared_specifiers() -> dict[str, str]: def _parse_version_tuple(raw: str) -> tuple[int, ...]: - parts = [] - for chunk in raw.split("."): - digits = "".join(c for c in chunk if c.isdigit()) - if not digits: - break - parts.append(int(digits)) - while len(parts) < 3: - parts.append(0) - return tuple(parts[:3]) + # Strip any upper-bound specifier (e.g. "0.14.0,<1.0") before matching digits. + lower = raw.split(",", 1)[0].strip() + match = re.match(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?", lower) + if not match: + return (0, 0, 0) + return tuple(int(group or 0) for group in match.groups()) def test_curl_cffi_floor_excludes_ghsa_qw2m_4pqf_rmpp() -> None: diff --git a/tests/test_review_regressions.py b/tests/test_review_regressions.py new file mode 100644 index 0000000..d27d546 --- /dev/null +++ b/tests/test_review_regressions.py @@ -0,0 +1,460 @@ +"""Regression tests for all code-review findings on PR #106.""" + +from __future__ import annotations + +import json +import os +import time +from unittest.mock import MagicMock, patch + +import pytest +from click.testing import CliRunner + +from twitter_cli import auth, cache, graphql +from twitter_cli.article import article_markdown_to_content_state +from twitter_cli.cli import cli +from twitter_cli.client import ( + TwitterClient, + _is_stale_query_error, + _twitter_deeplink_to_url, +) +from twitter_cli.exceptions import MediaUploadError, TwitterAPIError +from twitter_cli.models import UserProfile +from twitter_cli.parser import ( + _extract_author, + _render_article_text_block, + parse_tweet_result, + parse_user_result, +) +from twitter_cli.text import tweet_create_route, tweet_weighted_length + + +# ── 1. GraphQL stale-retry fallthrough, Vite asset URLs, cache TTL ─────── + + +def test_stale_query_retry_skips_stale_github_id_and_scans_bundles(monkeypatch) -> None: + monkeypatch.setattr(graphql, "_cached_query_ids", {}) + monkeypatch.setattr(graphql, "_disk_cache_loaded", True) + monkeypatch.setattr(graphql, "_bundles_scanned", False) + + stale_id = graphql.FALLBACK_QUERY_IDS["HomeTimeline"] + fresh_id = "FRESH_FROM_BUNDLE_999" + + def fake_fetch(url: str, headers=None) -> str: + if url == graphql.TWITTER_OPENAPI_URL: + # Simulates twitter-openapi lagging behind X with the same stale ID. + return json.dumps({"HomeTimeline": {"queryId": stale_id}}) + if url == "https://x.com/i/jf/": + return '' + if url == "https://abs.twimg.com/x-web/x-web/assets/index-abc.js": + # Also exercises Vite /x-web/x-web/assets/ chunk anchoring (no /assets/assets/). + return 'import("./assets/chunk-1.js");' + if url == "https://abs.twimg.com/x-web/x-web/assets/chunk-1.js": + return 'queryId:"%s",operationName:"HomeTimeline"' % fresh_id + raise AssertionError("Unexpected URL fetched: %s" % url) + + resolved = graphql._resolve_query_id( + "HomeTimeline", + prefer_fallback=False, + url_fetch_fn=fake_fetch, + exclude_ids={stale_id}, + ) + assert resolved == fresh_id + + +def test_disk_query_id_cache_preserves_created_at_and_refresh_replaces(monkeypatch, tmp_path) -> None: + cache_file = tmp_path / "query_ids_cache.json" + monkeypatch.setattr(graphql, "_qid_cache_path", lambda: cache_file) + monkeypatch.setattr(graphql, "_cached_query_ids", {}) + monkeypatch.setattr(graphql, "_disk_cache_loaded", False) + monkeypatch.setattr(graphql, "_bundles_scanned", False) + + old_ts = time.time() - 3600 + cache_file.write_text( + json.dumps({"created_at": old_ts, "query_ids": {"OldOp": "OLD1"}}), + encoding="utf-8", + ) + + # Incremental save must NOT reset created_at (prevents immortal stale entries). + graphql._save_disk_query_ids({"NewOp": "NEW1"}) + saved = json.loads(cache_file.read_text(encoding="utf-8")) + assert saved["created_at"] == pytest.approx(old_ts, abs=1.0) + assert saved["query_ids"] == {"OldOp": "OLD1", "NewOp": "NEW1"} + + # refresh_query_ids must replace old entries and reset created_at. + def fake_fetch(url: str, headers=None) -> str: + if url == graphql.TWITTER_OPENAPI_URL: + return json.dumps({"FreshOp": {"queryId": "FRESH1"}}) + return "" + + refreshed = graphql.refresh_query_ids(fake_fetch) + assert refreshed == {"FreshOp": "FRESH1"} + reloaded = json.loads(cache_file.read_text(encoding="utf-8")) + assert "OldOp" not in reloaded["query_ids"] + assert reloaded["query_ids"] == {"FreshOp": "FRESH1"} + assert reloaded["created_at"] > old_ts + + +# ── 2. Atomic owner-only cache write (symlink safety) ──────────────────── + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX symlink semantics") +def test_open_owner_only_replaces_symlink_without_touching_target(tmp_path) -> None: + victim = tmp_path / "victim.txt" + victim.write_text("precious", encoding="utf-8") + link = tmp_path / "cache.json" + link.symlink_to(victim) + + with cache._open_owner_only(link) as f: + f.write('{"ok": true}') + + assert victim.read_text(encoding="utf-8") == "precious" + assert not link.is_symlink() + assert json.loads(link.read_text(encoding="utf-8")) == {"ok": True} + + +# ── 3. Client: HTTP 400 stale error, TweetDetail ancestors/count<=0, media, deeplinks ─ + + +def test_is_stale_query_error_detects_http_400_persisted_query_not_found() -> None: + assert _is_stale_query_error(TwitterAPIError(400, "Twitter API error 400: Query: Unspecified")) + assert _is_stale_query_error(TwitterAPIError(400, "PersistedQueryNotFound")) + assert not _is_stale_query_error(TwitterAPIError(400, "Bad request: missing text")) + + +def test_fetch_tweet_detail_preserves_focal_tweet_when_ancestors_exceed_count(tweet_factory) -> None: + client = TwitterClient.__new__(TwitterClient) + client._max_count = 200 + client._request_delay = 0.0 + + ancestor1 = tweet_factory("100") + ancestor2 = tweet_factory("101") + focal = tweet_factory("102") + reply = tweet_factory("103") + + with patch.object(client, "_graphql_get", return_value={}): + with patch( + "twitter_cli.client.parse_timeline_response", + return_value=([ancestor1, ancestor2, focal, reply], "next-c"), + ): + tweets, cursor = client.fetch_tweet_detail("102", count=1, return_cursor=True) + + assert [t.id for t in tweets] == ["102"] + assert cursor == "next-c" + assert client.fetch_tweet_detail("102", count=0, return_cursor=True) == ([], None) + assert client.fetch_tweet_detail("102", count=0, return_cursor=False) == [] + + +@patch("twitter_cli.client.time.sleep") +@patch("twitter_cli.client._get_cffi_session") +def test_upload_gif_uses_tweet_gif_and_polls_status(mock_session, _mock_sleep, tmp_path) -> None: + gif = tmp_path / "anim.gif" + gif.write_bytes(b"GIF89a\x01\x00") + + sess = MagicMock() + sess.post = MagicMock( + side_effect=[ + MagicMock(status_code=200, text='{"media_id_string": "gif-1"}'), + MagicMock(status_code=204, text=""), + MagicMock( + status_code=200, + text='{"processing_info": {"state": "in_progress", "check_after_secs": null}}', + ), + ] + ) + sess.get = MagicMock( + return_value=MagicMock(status_code=200, text='{"processing_info": {"state": "succeeded"}}') + ) + mock_session.return_value = sess + + client = TwitterClient.__new__(TwitterClient) + client._auth_token = "tok" + client._ct0 = "ct0" + client._cookie_string = None + client._client_transaction = MagicMock() + client._client_transaction.generate_transaction_id.return_value = "tid" + client._ct_init_attempted = True + + assert client.upload_media(str(gif)) == "gif-1" + assert sess.post.call_args_list[0].kwargs["data"]["media_category"] == "tweet_gif" + assert sess.get.call_count == 1 + + +def test_upload_media_rejects_empty_and_unsupported_video(tmp_path) -> None: + client = TwitterClient.__new__(TwitterClient) + empty = tmp_path / "empty.mp4" + empty.write_bytes(b"") + with pytest.raises(MediaUploadError, match="File is empty"): + client.upload_media(str(empty)) + + avi = tmp_path / "clip.avi" + avi.write_bytes(b"\x00" * 16) + with pytest.raises(MediaUploadError, match="Unsupported video format"): + client.upload_media(str(avi)) + + +def test_twitter_deeplink_to_url_handles_trending_query_and_search_without_slash() -> None: + assert _twitter_deeplink_to_url("twitter://trending/12345?source=explore") == ( + "https://x.com/i/trending/12345" + ) + assert _twitter_deeplink_to_url("twitter://search?query=ai%20agents") == ( + "https://x.com/search?q=ai%20agents" + ) + + +# ── 4. Auth: TWITTER_COOKIE_STRING sync/sanitization, Zen Flatpak, DPAPI ─ + + +def test_cookie_string_env_override_syncs_cookie_header_and_strips_prefix(monkeypatch) -> None: + monkeypatch.setenv( + "TWITTER_COOKIE_STRING", + 'Cookie: auth_token="old_tok"; ct0="old_ct0"; guest_id=v1%3Dabc==\r\n', + ) + monkeypatch.setenv("TWITTER_CT0", "new_ct0") + + cookies = auth.load_from_env() + assert cookies is not None + assert cookies["auth_token"] == "old_tok" + assert cookies["ct0"] == "new_ct0" + assert "ct0=new_ct0" in cookies["cookie_string"] + assert "old_ct0" not in cookies["cookie_string"] + assert "guest_id=v1%3Dabc==" in cookies["cookie_string"] + assert not cookies["cookie_string"].lower().startswith("cookie:") + + +def test_cookie_string_incomplete_without_ct0_returns_none(monkeypatch) -> None: + monkeypatch.setenv("TWITTER_COOKIE_STRING", "auth_token=only_auth; twid=1") + assert auth.load_from_env() is None + + +def test_windows_dpapi_diagnostic_matches_dpapi_error(monkeypatch) -> None: + monkeypatch.setattr(auth.sys, "platform", "win32") + hint = auth._diagnose_keychain_issues(["chrome: Failed to decrypt the cipher text with DPAPI"]) + assert hint is not None + assert "DPAPI" in hint + + +def test_zen_linux_discovers_flatpak_config_zen_path(monkeypatch, tmp_path) -> None: + monkeypatch.setattr(auth.sys, "platform", "linux") + monkeypatch.setenv("HOME", str(tmp_path)) + cookie_db = tmp_path / ".var" / "app" / "app.zen_browser.zen" / "config" / "zen" / "p1.default" / "cookies.sqlite" + cookie_db.parent.mkdir(parents=True) + cookie_db.write_text("x", encoding="utf-8") + + found = auth._iter_zen_cookie_files() + assert str(cookie_db) in found + + +# ── 5. Parser: Draft.js UTF-16 emoji offsets & null-safe user dicts ────── + + +def test_draft_js_emoji_utf16_roundtrip() -> None: + state = article_markdown_to_content_state("🚀 [Click here](https://x.com)") + block = state["blocks"][0] + entity_map = {item["key"]: item["value"] for item in state["entity_map"]} + rendered = _render_article_text_block( + { + "text": block["text"], + "entityRanges": block["entity_ranges"], + "inlineStyleRanges": [], + }, + entity_map, + ) + assert rendered == "🚀 [Click here](https://x.com)" + + +def test_draft_js_emoji_utf16_bold_offset() -> None: + rendered = _render_article_text_block( + { + "text": "🚀 Hello world!", + "entityRanges": [], + "inlineStyleRanges": [{"offset": 3, "length": 5, "style": "Bold"}], + }, + {}, + ) + assert rendered == "🚀 **Hello** world!" + + +def test_parser_handles_null_nested_user_dicts_and_null_strings() -> None: + author = _extract_author( + { + "rest_id": "42", + "core": None, + "avatar": None, + "relationship_counts": None, + "relationship_perspectives": None, + }, + None, + ) + assert author.id == "42" + assert author.name == "Unknown" + + profile = parse_user_result( + { + "rest_id": "42", + "core": {"name": None, "screen_name": "alice", "created_at": None}, + "profile_bio": {"description": None}, + "website": {"url": None}, + "legacy": {"description": None, "location": None}, + } + ) + assert profile is not None + assert profile.bio == "" + assert profile.url == "" + assert profile.name == "" + assert profile.created_at == "" + + tweet = parse_tweet_result( + { + "rest_id": "10", + "legacy": {"full_text": "hi"}, + "core": {"user_results": {"result": {"rest_id": "42", "legacy": None, "core": None}}}, + } + ) + assert tweet is not None + assert tweet.author.id == "42" + + +# ── 6. Text weighting & Article Markdown edge cases ────────────────────── + + +def test_text_bare_url_ignores_filenames_emails_and_prose() -> None: + assert tweet_weighted_length("config.yaml") == len("config.yaml") + assert tweet_weighted_length("README.md") == len("README.md") + assert tweet_weighted_length("cli.py") == len("cli.py") + assert tweet_weighted_length("Hello.World") == len("Hello.World") + assert tweet_weighted_length("user.com@example.com") == len("user.com@example.com") + assert tweet_weighted_length("https://example.com") == 23 + assert tweet_weighted_length("Visit x.com/home today") == len("Visit ") + 23 + len(" today") + assert tweet_weighted_length("(https://example.com/foo.)") == 1 + 23 + 2 + assert tweet_weighted_length("©®") == 2 + assert tweet_weighted_length("©️") == 2 + assert tweet_weighted_length("▶️") == 2 + assert tweet_weighted_length("🐦‍⬛") == 2 + op, _ = tweet_create_route("Edited config.yaml and cli.py " + "a" * 240) + assert op == "CreateTweet" + + +def test_article_markdown_handles_inline_code_images_math_parens_h3_and_single_line_ticks() -> None: + md = "\n".join( + [ + "### Sub Heading", + "Use `[label](https://x.com)` and compute 2 * 3 * 4 now", + "See [Py](https://en.wikipedia.org/wiki/Python_(lang)) and ![pic](https://pbs.twimg.com/a.png)", + "```inline``` stays paragraph", + "Following paragraph survives", + ] + ) + state = article_markdown_to_content_state(md) + blocks = state["blocks"] + assert blocks[0]["type"] == "header-three" + assert blocks[0]["text"] == "Sub Heading" + + # Inline code link must NOT become an entity, and `2 * 3 * 4` keeps asterisks. + assert blocks[1]["text"] == "Use [label](https://x.com) and compute 2 * 3 * 4 now" + assert blocks[1]["entity_ranges"] == [] + + # Balanced-paren URL captured intact; image NOT turned into a link entity. + assert len(blocks[2]["entity_ranges"]) == 1 + link_entity = state["entity_map"][blocks[2]["entity_ranges"][0]["key"]]["value"] + assert link_entity["data"]["url"] == "https://en.wikipedia.org/wiki/Python_(lang)" + assert "![pic](https://pbs.twimg.com/a.png)" in blocks[2]["text"] + + # Single-line triple backticks do not swallow following paragraphs. + assert len(blocks) == 5 + assert blocks[4]["text"] == "Following paragraph survives" + + +# ── 7. CLI: structured error guards, upfront media checks, news, doctor, likes ─ + + +def test_write_action_invalid_id_emits_structured_json_error() -> None: + runner = CliRunner() + res = runner.invoke(cli, ["like", "not-a-valid-id", "--json"]) + assert res.exit_code == 1 + payload = json.loads(res.output) + assert payload["ok"] is False + assert payload["error"]["code"] == "invalid_input" + + +def test_article_publish_rejects_empty_and_non_utf8_files(tmp_path) -> None: + runner = CliRunner() + empty = tmp_path / "empty.md" + empty.write_text(" \n", encoding="utf-8") + res_empty = runner.invoke(cli, ["article-publish", str(empty), "--title", "Hi", "--json"]) + assert res_empty.exit_code == 1 + assert json.loads(res_empty.output)["error"]["code"] == "invalid_input" + + bad = tmp_path / "bad.md" + bad.write_bytes(b"\xff\xfe\x00") + res_bad = runner.invoke(cli, ["article-publish", str(bad), "--title", "Hi", "--json"]) + assert res_bad.exit_code == 1 + assert json.loads(res_bad.output)["error"]["code"] == "invalid_input" + + +def test_post_rejects_mismatched_media_mime_before_auth(tmp_path) -> None: + runner = CliRunner() + vid = tmp_path / "clip.mp4" + vid.write_bytes(b"\x00" * 16) + img = tmp_path / "photo.jpg" + img.write_bytes(b"\xff\xd8\xff") + + res_vid_as_img = runner.invoke(cli, ["post", "hi", "--image", str(vid)]) + assert res_vid_as_img.exit_code == 2 + assert "Unsupported image format" in res_vid_as_img.output + + res_img_as_vid = runner.invoke(cli, ["post", "hi", "--video", str(img)]) + assert res_img_as_vid.exit_code == 2 + assert "Unsupported video format" in res_img_as_vid.output + + +def test_news_rejects_non_positive_max() -> None: + runner = CliRunner() + res = runner.invoke(cli, ["news", "--max", "0"]) + assert res.exit_code == 2 + + +def test_doctor_refresh_and_error_exit_code(monkeypatch, tmp_path) -> None: + runner = CliRunner() + monkeypatch.setenv("TWITTER_COOKIE_STRING", "auth_token=super_secret_auth; ct0=super_secret_ct0") + monkeypatch.setattr( + "twitter_cli.cli.refresh_query_ids", + lambda _fetch: {"HomeTimeline": "LIVE_ID"}, + ) + res = runner.invoke(cli, ["doctor", "--refresh", "--json"]) + assert res.exit_code == 0 + assert "super_secret_auth" not in res.output + assert "super_secret_ct0" not in res.output + data = json.loads(res.output)["data"] + qid_check = next(c for c in data["checks"] if c["category"] == "query_ids") + assert qid_check["status"] == "pass" + assert "Refreshed 1 live queryIds" in qid_check["message"] + + # Expired query_ids cache -> warning + qid_cache = tmp_path / "expired_qids.json" + qid_cache.write_text( + json.dumps({"created_at": time.time() - 90000, "query_ids": {"HomeTimeline": "OLD"}}), + encoding="utf-8", + ) + monkeypatch.setattr("twitter_cli.cli._qid_cache_path", lambda: qid_cache) + res_exp = runner.invoke(cli, ["doctor", "--json"]) + assert res_exp.exit_code == 0 + qid_exp = next(c for c in json.loads(res_exp.output)["data"]["checks"] if c["category"] == "query_ids") + assert qid_exp["status"] == "warning" + assert "expired" in qid_exp["message"] + + +def test_likes_own_numeric_id_does_not_warn_private_likes(monkeypatch, tweet_factory) -> None: + from twitter_cli import cli as cli_module + + me = UserProfile(id="42", name="Alice", screen_name="alice") + fake_client = MagicMock() + fake_client.fetch_user.return_value = me + fake_client.fetch_me.return_value = me + fake_client.fetch_user_likes.return_value = [tweet_factory("1")] + + monkeypatch.setattr(cli_module, "_get_client", lambda *_a, **_kw: fake_client) + runner = CliRunner() + res = runner.invoke(cli, ["likes", "42"]) + assert res.exit_code == 0 + assert "private since June 2024" not in res.output diff --git a/tests/test_time_style.py b/tests/test_time_style.py index 8646fd3..2822bd7 100644 --- a/tests/test_time_style.py +++ b/tests/test_time_style.py @@ -2,12 +2,15 @@ from __future__ import annotations +import io + import pytest from rich.console import Console from twitter_cli import formatter from twitter_cli.formatter import ( get_time_style, + print_article, print_tweet_detail, print_tweet_table, set_time_style, @@ -24,11 +27,13 @@ def _tweet() -> Tweet: author=Author(id="u1", name="Alice", screen_name="alice"), metrics=Metrics(likes=1, retweets=0, replies=0, quotes=0, views=10, bookmarks=0), created_at=CREATED_AT, + article_title="My Article", + article_text="Body", ) def _render(printer) -> str: - console = Console(record=True, width=120, file=None) + console = Console(record=True, width=120, file=io.StringIO()) printer(console) return console.export_text() @@ -40,10 +45,11 @@ def _restore_style(): formatter.set_time_style(original) -def test_relative_style_renders_ago() -> None: +def test_relative_style_renders_ago(monkeypatch) -> None: + monkeypatch.setattr(formatter, "format_relative_time", lambda _s: "3d ago") set_time_style("relative") text = _render(lambda c: print_tweet_table([_tweet()], console=c)) - assert "ago" in text + assert "3d ago" in text def test_absolute_style_renders_datetime() -> None: @@ -53,10 +59,10 @@ def test_absolute_style_renders_datetime() -> None: assert ":" in text -def test_iso_style_renders_iso8601() -> None: +def test_iso_style_renders_full_iso8601_without_truncation() -> None: set_time_style("iso") text = _render(lambda c: print_tweet_table([_tweet()], console=c)) - assert "2026-03-14T" in text + assert "2026-03-14T21:08:00+00:00" in text assert "ago" not in text @@ -64,7 +70,19 @@ def test_detail_view_does_not_repeat_stamp_under_absolute() -> None: set_time_style("absolute") text = _render(lambda c: print_tweet_detail(_tweet(), console=c)) assert "ago" not in text - assert "2026-03-" in text + assert text.count("2026-03-") == 1 + + +def test_article_view_respects_time_style() -> None: + set_time_style("iso") + text = _render(lambda c: print_article(_tweet(), console=c)) + assert "2026-03-14T21:08:00+00:00" in text + + +def test_set_time_style_none_resets_to_relative() -> None: + set_time_style("iso") + assert set_time_style(None) == "relative" + assert get_time_style() == "relative" def test_invalid_style_is_ignored() -> None: diff --git a/twitter_cli/__init__.py b/twitter_cli/__init__.py index cf7299c..0bae787 100644 --- a/twitter_cli/__init__.py +++ b/twitter_cli/__init__.py @@ -2,6 +2,9 @@ from __future__ import annotations +import importlib +from typing import TYPE_CHECKING, Any + try: from importlib.metadata import version @@ -9,36 +12,71 @@ except Exception: __version__ = "0.0.0" -from .auth import get_cookies -from .client import TwitterClient -from .config import load_config -from .exceptions import ( - AuthenticationError, - InvalidInputError, - MediaUploadError, - NetworkError, - NotFoundError, - QueryIdError, - RateLimitError, - TwitterAPIError, - TwitterError, -) -from .filter import filter_tweets -from .models import Author, BookmarkFolder, Metrics, Tweet, TweetMedia, UserProfile -from .serialization import ( - bookmark_folder_to_dict, - bookmark_folders_to_data, - tweet_from_dict, - tweet_to_compact_dict, - tweet_to_dict, - tweets_from_json, - tweets_to_compact_json, - tweets_to_data, - tweets_to_json, - user_profile_to_dict, - users_to_data, - users_to_json, -) +if TYPE_CHECKING: + from .auth import get_cookies + from .client import TwitterClient + from .config import load_config + from .exceptions import ( + AuthenticationError, + InvalidInputError, + MediaUploadError, + NetworkError, + NotFoundError, + QueryIdError, + RateLimitError, + TwitterAPIError, + TwitterError, + ) + from .filter import filter_tweets + from .models import Author, BookmarkFolder, Metrics, Tweet, TweetMedia, UserProfile + from .serialization import ( + bookmark_folder_to_dict, + bookmark_folders_to_data, + tweet_from_dict, + tweet_to_compact_dict, + tweet_to_dict, + tweets_from_json, + tweets_to_compact_json, + tweets_to_data, + tweets_to_json, + user_profile_to_dict, + users_to_data, + users_to_json, + ) + +_LAZY_EXPORTS: dict[str, tuple[str, str]] = { + "TwitterClient": (".client", "TwitterClient"), + "get_cookies": (".auth", "get_cookies"), + "load_config": (".config", "load_config"), + "filter_tweets": (".filter", "filter_tweets"), + "Author": (".models", "Author"), + "BookmarkFolder": (".models", "BookmarkFolder"), + "Metrics": (".models", "Metrics"), + "Tweet": (".models", "Tweet"), + "TweetMedia": (".models", "TweetMedia"), + "UserProfile": (".models", "UserProfile"), + "TwitterError": (".exceptions", "TwitterError"), + "AuthenticationError": (".exceptions", "AuthenticationError"), + "InvalidInputError": (".exceptions", "InvalidInputError"), + "MediaUploadError": (".exceptions", "MediaUploadError"), + "NetworkError": (".exceptions", "NetworkError"), + "NotFoundError": (".exceptions", "NotFoundError"), + "QueryIdError": (".exceptions", "QueryIdError"), + "RateLimitError": (".exceptions", "RateLimitError"), + "TwitterAPIError": (".exceptions", "TwitterAPIError"), + "tweet_to_dict": (".serialization", "tweet_to_dict"), + "tweet_from_dict": (".serialization", "tweet_from_dict"), + "tweets_to_json": (".serialization", "tweets_to_json"), + "tweets_from_json": (".serialization", "tweets_from_json"), + "tweets_to_data": (".serialization", "tweets_to_data"), + "tweet_to_compact_dict": (".serialization", "tweet_to_compact_dict"), + "tweets_to_compact_json": (".serialization", "tweets_to_compact_json"), + "bookmark_folder_to_dict": (".serialization", "bookmark_folder_to_dict"), + "bookmark_folders_to_data": (".serialization", "bookmark_folders_to_data"), + "user_profile_to_dict": (".serialization", "user_profile_to_dict"), + "users_to_data": (".serialization", "users_to_data"), + "users_to_json": (".serialization", "users_to_json"), +} __all__ = [ "__version__", @@ -74,3 +112,18 @@ "users_to_data", "users_to_json", ] + + +def __getattr__(name: str) -> Any: + spec = _LAZY_EXPORTS.get(name) + if spec is None: + raise AttributeError("module %r has no attribute %r" % (__name__, name)) + module_name, attr_name = spec + module = importlib.import_module(module_name, __name__) + value = getattr(module, attr_name) + globals()[name] = value + return value + + +def __dir__() -> list[str]: + return sorted(set(globals()) | set(__all__)) diff --git a/twitter_cli/article.py b/twitter_cli/article.py index 8936ffe..bbbb6b7 100644 --- a/twitter_cli/article.py +++ b/twitter_cli/article.py @@ -11,6 +11,11 @@ DraftEntity = dict[str, Any] DraftContentState = dict[str, Any] +_FENCE_OPEN_RE = re.compile(r"^```[A-Za-z0-9_+-]*$") +_INLINE_CODE_RE = re.compile(r"`([^`]+)`") +_BOLD_RE = re.compile(r"\*\*([^\s*](?:[^*]*[^\s*])?)\*\*") +_ITALIC_RE = re.compile(r"(? str: return hashlib.sha1(("%s:%d" % (seed, index)).encode("utf-8")).hexdigest()[:5] @@ -58,34 +63,99 @@ def _append_entity(content_state: DraftContentState, entity_type: str, mutabilit return key -def _extract_links(text: str, content_state: DraftContentState) -> tuple[str, list[dict[str, int]]]: +def _find_balanced_link_end(text: str, start: int) -> int: + """Return index of closing ')' matching '(' at ``start - 1``, or -1.""" + depth = 1 + pos = start + while pos < len(text): + ch = text[pos] + if ch == "(": + depth += 1 + elif ch == ")": + depth -= 1 + if depth == 0: + return pos + elif ch in ("\n", "\r"): + return -1 + pos += 1 + return -1 + + +def _strip_emphasis(text: str) -> str: + """Strip bold/italic Markdown delimiters without harming math/spaced asterisks.""" + text = _BOLD_RE.sub(r"\1", text) + text = _ITALIC_RE.sub(r"\1", text) + return text + + +def _process_inline_text(text: str, content_state: DraftContentState) -> tuple[str, list[dict[str, int]]]: + """Strip inline markup and extract Markdown links while protecting inline code and images.""" + code_spans: list[str] = [] + + def _stash_code(match: re.Match[str]) -> str: + token = "\x00CODE%d\x00" % len(code_spans) + code_spans.append(match.group(1)) + return token + + protected = _INLINE_CODE_RE.sub(_stash_code, text) + protected = _strip_emphasis(protected) + ranges: list[dict[str, int]] = [] output: list[str] = [] cursor = 0 - for match in re.finditer(r"\[([^\]]+)\]\(([^)]+)\)", text): - output.append(text[cursor:match.start()]) - label = match.group(1) - url = match.group(2) + pos = 0 + + def _restore_code(segment: str) -> str: + if not code_spans: + return segment + return re.sub( + r"\x00CODE(\d+)\x00", + lambda m: code_spans[int(m.group(1))], + segment, + ) + + while pos < len(protected): + bracket_start = protected.find("[", pos) + if bracket_start == -1: + break + # Skip Markdown images `![alt](url)` + if bracket_start > 0 and protected[bracket_start - 1] == "!": + pos = bracket_start + 1 + continue + bracket_end = protected.find("]", bracket_start + 1) + if bracket_end == -1 or bracket_end + 1 >= len(protected) or protected[bracket_end + 1] != "(": + pos = bracket_start + 1 + continue + url_start = bracket_end + 2 + url_end = _find_balanced_link_end(protected, url_start) + if url_end == -1: + pos = bracket_start + 1 + continue + + raw_label = protected[bracket_start + 1:bracket_end] + raw_url = protected[url_start:url_end].strip() + if not raw_label or not raw_url: + pos = url_end + 1 + continue + + output.append(_restore_code(protected[cursor:bracket_start])) + label = _restore_code(raw_label) + url = _restore_code(raw_url) offset = _utf16_len("".join(output)) output.append(label) entity_key = _append_entity(content_state, "LINK", "Mutable", {"url": url}) ranges.append({"key": entity_key, "offset": offset, "length": _utf16_len(label)}) - cursor = match.end() - output.append(text[cursor:]) - return "".join(output), ranges + cursor = url_end + 1 + pos = cursor - -def _strip_inline_markup(text: str) -> str: - text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) - text = re.sub(r"\*([^*]+)\*", r"\1", text) - text = re.sub(r"`([^`]+)`", r"\1", text) - return text + output.append(_restore_code(protected[cursor:])) + return "".join(output), ranges def article_markdown_to_content_state(markdown: str) -> DraftContentState: """Convert a conservative Markdown subset into X Article content_state. - Supported block forms: paragraphs, #/## headings, unordered and ordered + Supported block forms: paragraphs, #/##/### headings, unordered and ordered list items, blockquotes, horizontal rules, fenced code blocks, and inline Markdown links. """ @@ -101,13 +171,13 @@ def article_markdown_to_content_state(markdown: str) -> DraftContentState: if not stripped: continue - if stripped.startswith("```"): + if _FENCE_OPEN_RE.match(stripped): code_lines: list[str] = [] opening = stripped while i < len(lines): code_line = lines[i].rstrip() i += 1 - if code_line.strip().startswith("```"): + if code_line.strip() == "```": break code_lines.append(code_line) markdown_block = opening + "\n" + "\n".join(code_lines) + "\n```" @@ -124,12 +194,15 @@ def article_markdown_to_content_state(markdown: str) -> DraftContentState: block_type = "unstyled" text = stripped - if stripped.startswith("# "): - block_type = "header-one" - text = stripped[2:].strip() + if stripped.startswith("### "): + block_type = "header-three" + text = stripped[4:].strip() elif stripped.startswith("## "): block_type = "header-two" text = stripped[3:].strip() + elif stripped.startswith("# "): + block_type = "header-one" + text = stripped[2:].strip() elif stripped.startswith("> "): block_type = "blockquote" text = stripped[2:].strip() @@ -142,7 +215,7 @@ def article_markdown_to_content_state(markdown: str) -> DraftContentState: block_type = "ordered-list-item" text = ordered.group(1).strip() - text, entity_ranges = _extract_links(_strip_inline_markup(text), content_state) + text, entity_ranges = _process_inline_text(text, content_state) block = _plain_block(block_type, text, _block_key(text, block_index)) block["entity_ranges"] = entity_ranges content_state["blocks"].append(block) diff --git a/twitter_cli/auth.py b/twitter_cli/auth.py index b6e4f9e..f7f9e62 100644 --- a/twitter_cli/auth.py +++ b/twitter_cli/auth.py @@ -44,6 +44,7 @@ def _is_twitter_domain(domain: str) -> bool: "safe storage", "keychain", "secretstorage", + "dpapi", ) @@ -104,16 +105,34 @@ def _diagnose_keychain_issues(diagnostics: List[str]) -> Optional[str]: ) +def _sanitize_cookie_header(raw: str) -> str: + """Strip CR/LF and an accidental leading 'Cookie:' header prefix.""" + cleaned = raw.replace("\r", "").replace("\n", "").strip() + if cleaned.lower().startswith("cookie:"): + cleaned = cleaned.split(":", 1)[1].strip() + return cleaned + + +def _unquote_cookie_value(value: str) -> str: + """Strip one pair of surrounding double quotes from a cookie value.""" + if len(value) >= 2 and value[0] == '"' and value[-1] == '"': + return value[1:-1] + return value + + def _parse_cookie_string(raw: str) -> Dict[str, str]: """Parse a raw HTTP Cookie header into a dict of cookie name -> value.""" parsed: Dict[str, str] = {} - for part in raw.split(";"): + cleaned = _sanitize_cookie_header(raw) + for part in cleaned.split(";"): item = part.strip() if not item or "=" not in item: continue name, value = item.split("=", 1) name = name.strip() value = value.strip() + if name in ("auth_token", "ct0"): + value = _unquote_cookie_value(value) if name and value: parsed[name] = value return parsed @@ -127,19 +146,32 @@ def load_from_env() -> Optional[Dict[str, str]]: write/anti-detection compatibility; works with SigCLI and headless setups) - ``TWITTER_AUTH_TOKEN`` + ``TWITTER_CT0`` """ - raw_cookie_string = os.environ.get("TWITTER_COOKIE_STRING", "").strip() - auth_token = os.environ.get("TWITTER_AUTH_TOKEN", "").strip() - ct0 = os.environ.get("TWITTER_CT0", "").strip() + raw_cookie_string = _sanitize_cookie_header(os.environ.get("TWITTER_COOKIE_STRING", "")) + auth_token = _unquote_cookie_value(os.environ.get("TWITTER_AUTH_TOKEN", "").strip()) + ct0 = _unquote_cookie_value(os.environ.get("TWITTER_CT0", "").strip()) if raw_cookie_string: parsed = _parse_cookie_string(raw_cookie_string) resolved_auth = auth_token or parsed.get("auth_token", "") resolved_ct0 = ct0 or parsed.get("ct0", "") if resolved_auth and resolved_ct0: + # Ensure Cookie header carries the exact auth_token/ct0 values + # used for X-Csrf-Token (even when overridden or supplemented by env vars). + needs_rebuild = ( + parsed.get("auth_token") != resolved_auth + or parsed.get("ct0") != resolved_ct0 + ) + if needs_rebuild: + rebuilt = dict(parsed) + rebuilt["auth_token"] = resolved_auth + rebuilt["ct0"] = resolved_ct0 + effective_cookie_string = "; ".join("%s=%s" % (k, v) for k, v in rebuilt.items()) + else: + effective_cookie_string = raw_cookie_string return { "auth_token": resolved_auth, "ct0": resolved_ct0, - "cookie_string": raw_cookie_string, + "cookie_string": effective_cookie_string, } logger.debug( "TWITTER_COOKIE_STRING incomplete: auth_token=%s ct0=%s", @@ -313,15 +345,16 @@ def _profile_name_from_cookie_file(cookie_file: str) -> str: def _chromium_key_file_for_cookie(cookie_file: str) -> Optional[str]: """Return the Local State file associated with a Chromium cookie database.""" candidates = [] - custom_root = _custom_chromium_user_data_dir() - if custom_root: - candidates.append(os.path.join(custom_root, "Local State")) - profile_dir = os.path.dirname(cookie_file) if os.path.basename(profile_dir) == "Network": profile_dir = os.path.dirname(profile_dir) + # Check the profile's own parent user-data dir first (handles absolute TWITTER_CHROME_PROFILE). candidates.append(os.path.join(os.path.dirname(profile_dir), "Local State")) + custom_root = _custom_chromium_user_data_dir() + if custom_root: + candidates.append(os.path.join(custom_root, "Local State")) + for candidate in dict.fromkeys(candidates): if os.path.exists(candidate): return candidate @@ -403,10 +436,12 @@ def _iter_zen_cookie_files() -> List[str]: roots = [ os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config"), "zen"), os.path.join(home, ".zen"), + os.path.join(home, ".var", "app", "app.zen_browser.zen", "config", "zen"), os.path.join(home, ".var", "app", "app.zen_browser.zen", "zen"), os.path.join(home, ".var", "app", "app.zen_browser.zen", ".zen"), ] paths: List[str] = [] + seen = set() for root in roots: config = configparser.ConfigParser(interpolation=None) try: @@ -437,18 +472,42 @@ def _iter_zen_cookie_files() -> List[str]: for pattern in ("*/cookies.sqlite", "Profiles/*/cookies.sqlite"): candidates.extend(sorted(glob.glob(os.path.join(root, pattern)))) for path in candidates: - if os.path.isfile(path) and path not in paths: - paths.append(path) + norm = os.path.normpath(path) + if os.path.isfile(norm) and norm not in seen: + seen.add(norm) + paths.append(norm) return paths def _get_browser_cookie_fn(browser_cookie3: Any, browser_name: str) -> Any: """Return a browser-cookie3 loader for a configured browser.""" if browser_name == _CUSTOM_CHROMIUM_BROWSER: - return lambda cookie_file=None: browser_cookie3.chromium( - cookie_file=cookie_file, - key_file=_chromium_key_file_for_cookie(cookie_file) if cookie_file else None, - ) + env_browser = os.environ.get("TWITTER_BROWSER", "").strip().lower() + loader_names = ["chromium"] + if env_browser in _CHROMIUM_BASE_DIRS: + loader_names = [env_browser] + [n for n in loader_names if n != env_browser] + if sys.platform != "win32": + for fallback_name in ("chrome", "brave", "edge", "vivaldi", "arc"): + if fallback_name not in loader_names: + loader_names.append(fallback_name) + + def _load_custom(cookie_file: Optional[str] = None) -> Any: + key_file = _chromium_key_file_for_cookie(cookie_file) if cookie_file else None + last_exc: Optional[Exception] = None + for loader_name in loader_names: + loader = getattr(browser_cookie3, loader_name, None) + if loader is None: + continue + try: + return loader(cookie_file=cookie_file, key_file=key_file) + except Exception as exc: + last_exc = exc + continue + if last_exc is not None: + raise last_exc + return browser_cookie3.chromium(cookie_file=cookie_file, key_file=key_file) + + return _load_custom if browser_name == "zen": return browser_cookie3.firefox return getattr(browser_cookie3, browser_name) @@ -581,13 +640,13 @@ def profile_name_from_cookie_file(cookie_file): def chromium_key_file_for_cookie(cookie_file): candidates = [] - custom_root = custom_chromium_user_data_dir() - if custom_root: - candidates.append(os.path.join(custom_root, "Local State")) profile_dir = os.path.dirname(cookie_file) if os.path.basename(profile_dir) == "Network": profile_dir = os.path.dirname(profile_dir) candidates.append(os.path.join(os.path.dirname(profile_dir), "Local State")) + custom_root = custom_chromium_user_data_dir() + if custom_root: + candidates.append(os.path.join(custom_root, "Local State")) for candidate in dict.fromkeys(candidates): if os.path.exists(candidate): return candidate diff --git a/twitter_cli/cache.py b/twitter_cli/cache.py index b2e3b1e..16c7ba3 100644 --- a/twitter_cli/cache.py +++ b/twitter_cli/cache.py @@ -6,8 +6,10 @@ import logging import os import time +import uuid +from contextlib import contextmanager from pathlib import Path -from typing import IO, List, Optional, Tuple +from typing import IO, Iterator, List, Optional, Tuple from .models import Tweet @@ -22,23 +24,57 @@ _OWNER_ONLY_DIR = 0o700 -def _open_owner_only(path: Path) -> IO[str]: - """Open ``path`` for writing with owner-only permissions. +@contextmanager +def _open_owner_only(path: Path) -> Iterator[IO[str]]: + """Atomically write ``path`` with owner-only permissions. - Uses ``O_CREAT`` with mode ``0o600`` so a newly created file is never - briefly world-readable, and tightens preexisting files on every write. + Creates a unique sibling temporary file using ``O_CREAT | O_EXCL`` (and + ``O_NOFOLLOW`` where supported) with mode ``0o600``, then atomically + replaces ``path`` via ``os.replace``. This prevents symlink-following + attacks and partial/interleaved reads under concurrent invocations. """ - flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0) - fd = os.open(str(path), flags, _OWNER_ONLY_FILE) + flags = ( + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_BINARY", 0) + ) + tmp_path = path.parent / (".%s.%d.%s.tmp" % (path.name, os.getpid(), uuid.uuid4().hex[:8])) + fd = os.open(str(tmp_path), flags, _OWNER_ONLY_FILE) + handle: Optional[IO[str]] = None try: - fchmod = getattr(os, "fchmod", None) - if fchmod is not None: - fchmod(fd, _OWNER_ONLY_FILE) - else: # pragma: no cover - non-POSIX - os.chmod(str(path), _OWNER_ONLY_FILE) - except OSError: # pragma: no cover - permission change is best-effort - pass - return os.fdopen(fd, "w", encoding="utf-8") + try: + fchmod = getattr(os, "fchmod", None) + if fchmod is not None: + fchmod(fd, _OWNER_ONLY_FILE) + else: # pragma: no cover - non-POSIX + os.chmod(str(tmp_path), _OWNER_ONLY_FILE) + except OSError: # pragma: no cover - permission change is best-effort + pass + handle = os.fdopen(fd, "w", encoding="utf-8") + fd = -1 + yield handle + handle.flush() + handle.close() + handle = None + os.replace(str(tmp_path), str(path)) + except BaseException: + if handle is not None: + try: + handle.close() + except OSError: + pass + elif fd >= 0: + try: + os.close(fd) + except OSError: + pass + try: + tmp_path.unlink() + except OSError: + pass + raise def _tighten_dir(directory: Path) -> None: @@ -52,7 +88,7 @@ def _tighten_dir(directory: Path) -> None: def save_tweet_cache(tweets: List[Tweet]) -> None: """Persist tweet list so indices can be resolved by `show`.""" try: - _CACHE_DIR.mkdir(parents=True, exist_ok=True) + _CACHE_DIR.mkdir(mode=_OWNER_ONLY_DIR, parents=True, exist_ok=True) _tighten_dir(_CACHE_DIR) entries = [ {"index": i + 1, "id": t.id, "author": t.author.screen_name, "text": t.text[:80]} @@ -97,4 +133,4 @@ def resolve_cached_tweet(index: int) -> Tuple[Optional[str], int]: if entry.get("index") == index: tweet_id = entry.get("id") return (str(tweet_id) if tweet_id is not None else None), len(entries) - return None, len(entries) \ No newline at end of file + return None, len(entries) diff --git a/twitter_cli/cli.py b/twitter_cli/cli.py index aa8c0d2..b449bf4 100644 --- a/twitter_cli/cli.py +++ b/twitter_cli/cli.py @@ -34,6 +34,7 @@ import json import logging +import mimetypes import re import sys import time @@ -51,8 +52,12 @@ from .article import article_markdown_to_content_state from .auth import get_cookies, load_from_env from .cache import resolve_cached_tweet, save_tweet_cache -from .exceptions import TwitterError -from .client import TwitterClient, _url_fetch +from .exceptions import InvalidInputError, TwitterError +try: + from .client import TwitterClient, _url_fetch +except ImportError: # pragma: no cover - allows `twitter doctor` to run when runtime deps are missing + TwitterClient = None # type: ignore[assignment,misc] + _url_fetch = None # type: ignore[assignment] from .config import _resolve_config_path, load_config from .filter import filter_tweets from .formatter import ( @@ -65,7 +70,7 @@ print_user_table, set_time_style, ) -from .graphql import FALLBACK_QUERY_IDS, _qid_cache_path, refresh_query_ids +from .graphql import FALLBACK_QUERY_IDS, _QID_CACHE_TTL, _qid_cache_path, refresh_query_ids from .models import Tweet, UserProfile from .output import ( default_structured_format, @@ -207,7 +212,7 @@ def _normalize_tweet_id(value): """Extract a numeric tweet ID from raw input or a full X/Twitter URL.""" raw = value.strip() if not raw: - raise RuntimeError("Tweet ID or URL is required") + raise InvalidInputError("Tweet ID or URL is required") parsed = urllib.parse.urlparse(raw) candidate = raw @@ -215,14 +220,14 @@ def _normalize_tweet_id(value): path = parsed.path.rstrip("/") match = re.search(r"/(?:status|article)/(\d+)$", path) if not match: - raise RuntimeError("Invalid tweet URL: %s" % value) + raise InvalidInputError("Invalid tweet URL: %s" % value) candidate = match.group(1) else: candidate = raw.rstrip("/").split("/")[-1] candidate = candidate.split("?", 1)[0].split("#", 1)[0] if not candidate.isdigit(): - raise RuntimeError("Invalid tweet ID: %s" % value) + raise InvalidInputError("Invalid tweet ID: %s" % value) return candidate @@ -898,18 +903,23 @@ def _run(): # Warn if querying another user's likes (Twitter made likes private since June 2024) try: me = client.fetch_me() - if me.screen_name.lower() != screen_name.lower(): + is_other_user = ( + (me.id != profile.id) + if (me.id and profile.id) + else (me.screen_name.lower() != profile.screen_name.lower()) + ) + if is_other_user: if rich_output: console.print( "\n[yellow]⚠️ Twitter/X made all likes private since June 2024. " "You can only view your own likes. " - "Querying @%s's likes will likely return empty results.[/yellow]\n" % screen_name + "Querying @%s's likes will likely return empty results.[/yellow]\n" % profile.screen_name ) else: logger.warning( "Twitter/X made likes private (June 2024). " "Only your own likes are visible. @%s's likes will likely be empty.", - screen_name, + profile.screen_name, ) except Exception: pass # Don't block the command if whoami fails @@ -1100,11 +1110,38 @@ def article(ctx, tweet_id, as_json, as_yaml, as_markdown, output_file): def article_publish(markdown_file, title, draft, as_json, as_yaml): # type: (str, str, bool, bool, bool) -> None """Publish an X Article from a Markdown file.""" - markdown = Path(markdown_file).read_text(encoding="utf-8") + mode = _structured_mode(as_json=as_json, as_yaml=as_yaml) + clean_title = title.strip() + if not clean_title: + _handle_structured_runtime_error( + InvalidInputError("Article --title must not be empty."), + mode=mode, + details={"action": "article_publish", "draft": draft}, + ) + return + + try: + markdown = Path(markdown_file).read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError) as exc: + _handle_structured_runtime_error( + InvalidInputError("Failed to read UTF-8 Markdown file %s: %s" % (markdown_file, exc)), + mode=mode, + details={"action": "article_publish", "title": clean_title, "draft": draft}, + ) + return + + if not markdown.strip(): + _handle_structured_runtime_error( + InvalidInputError("Markdown file %s is empty." % markdown_file), + mode=mode, + details={"action": "article_publish", "title": clean_title, "draft": draft}, + ) + return + content_state = article_markdown_to_content_state(markdown) def operation(client: TwitterClient) -> WritePayload: - result = client.create_article(title, content_state, publish=not draft) + result = client.create_article(clean_title, content_state, publish=not draft) return { "success": True, "action": "article_publish", @@ -1121,9 +1158,9 @@ def operation(client: TwitterClient) -> WritePayload: operation=operation, progress_lines=["📝 %s..." % action], success_lines=["[green]✅ Article %s![/green]" % ("draft created" if draft else "published")], - error_details={"action": "article_publish", "title": title, "draft": draft}, + error_details={"action": "article_publish", "title": clean_title, "draft": draft}, ) - if payload and not _structured_mode(as_json=as_json, as_yaml=as_yaml): + if payload and not mode: console.print("🔗 %s" % payload["url"]) @@ -1243,15 +1280,13 @@ def following(screen_name, max_count, as_json, as_yaml): _MAX_IMAGES = 4 # Twitter allows up to 4 images per tweet _MAX_VIDEOS = 1 # X allows 1 video per tweet (or up to 4 images, not both) +_ALLOWED_IMAGE_MIMES = {"image/jpeg", "image/png", "image/gif", "image/webp"} +_ALLOWED_VIDEO_MIMES = {"video/mp4", "video/quicktime", "video/webm"} -def _upload_images(client, image_paths, video_paths=None, rich_output=True): - # type: (TwitterClient, tuple, Optional[tuple], bool) -> list - """Upload images or a video and return list of media_id strings.""" - image_paths = tuple(image_paths or ()) - video_paths = tuple(video_paths or ()) - if not image_paths and not video_paths: - return [] +def _validate_media_paths(image_paths, video_paths): + # type: (tuple, tuple) -> None + """Validate media counts, non-mixing, and MIME class before authenticating.""" if len(image_paths) > _MAX_IMAGES: raise click.UsageError("Too many images: max %d, got %d" % (_MAX_IMAGES, len(image_paths))) if len(video_paths) > _MAX_VIDEOS: @@ -1260,6 +1295,30 @@ def _upload_images(client, image_paths, video_paths=None, rich_output=True): ) if image_paths and video_paths: raise click.UsageError("Attach images OR a video, not both (X allows one media type per tweet)") + for path in image_paths: + mime = mimetypes.guess_type(path)[0] or "" + if mime not in _ALLOWED_IMAGE_MIMES: + raise click.UsageError( + "Unsupported image format for --image %s: %s (supported: jpeg, png, gif, webp)" + % (path, mime or "unknown") + ) + for path in video_paths: + mime = mimetypes.guess_type(path)[0] or "" + if mime not in _ALLOWED_VIDEO_MIMES: + raise click.UsageError( + "Unsupported video format for --video %s: %s (supported: mp4, mov, webm)" + % (path, mime or "unknown") + ) + + +def _upload_images(client, image_paths, video_paths=None, rich_output=True): + # type: (TwitterClient, tuple, Optional[tuple], bool) -> list + """Upload images or a video and return list of media_id strings.""" + image_paths = tuple(image_paths or ()) + video_paths = tuple(video_paths or ()) + if not image_paths and not video_paths: + return [] + _validate_media_paths(image_paths, video_paths) media_ids = [] total = len(image_paths) + len(video_paths) for i, path in enumerate(image_paths, 1): @@ -1273,34 +1332,51 @@ def _upload_images(client, image_paths, video_paths=None, rich_output=True): return media_ids +def _normalize_tweet_id_guarded(tweet_id, *, mode, details): + # type: (str, StructuredMode, Dict[str, Any]) -> Optional[str] + """Normalize a tweet ID/URL, emitting structured errors on invalid input.""" + try: + return _normalize_tweet_id(tweet_id) + except (TwitterError, RuntimeError) as exc: + _handle_structured_runtime_error(exc, mode=mode, details=details) + return None + + def _write_action(emoji, action_desc, client_method, tweet_id, as_json=False, as_yaml=False): # type: (str, str, str, str, bool, bool) -> None """Generic write action helper to reduce CLI command boilerplate. Emits structured JSON/YAML when piped or when OUTPUT env is set. """ - tweet_id = _normalize_tweet_id(tweet_id) action_name = action_desc.lower().replace(" ", "_") + mode = _structured_mode(as_json=as_json, as_yaml=as_yaml) + normalized_id = _normalize_tweet_id_guarded( + tweet_id, + mode=mode, + details={"action": action_name, "id": tweet_id}, + ) + if normalized_id is None: + return def operation(client: TwitterClient) -> WritePayload: - getattr(client, client_method)(tweet_id) - return {"success": True, "action": action_name, "id": tweet_id} + getattr(client, client_method)(normalized_id) + return {"success": True, "action": action_name, "id": normalized_id} _run_write_command( as_json=as_json, as_yaml=as_yaml, operation=operation, - progress_lines=["%s %s %s..." % (emoji, action_desc, tweet_id)], + progress_lines=["%s %s %s..." % (emoji, action_desc, normalized_id)], success_lines=["[green]✅ Done.[/green]"], - error_details={"action": action_name, "id": tweet_id}, + error_details={"action": action_name, "id": normalized_id}, ) @cli.command() @click.argument("text") @click.option("--reply-to", "-r", default=None, help="Reply to this tweet ID.") -@click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.") -@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True), help="Attach video (max 1; mp4/mov/webm up to 512 MB).") +@click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True, dir_okay=False), help="Attach image (up to 4). Repeatable.") +@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True, dir_okay=False), help="Attach video (max 1; mp4/mov/webm up to 512 MB).") @structured_output_options def post(text, reply_to, images, videos, as_json, as_yaml): # type: (str, Optional[str], tuple, tuple, bool, bool) -> None @@ -1313,9 +1389,17 @@ def post(text, reply_to, images, videos, as_json, as_yaml): twitter post "Gallery" -i a.png -i b.png -i c.jpg twitter post "Clip:" --video clip.mp4 """ - normalized_reply_to = _normalize_tweet_id(reply_to) if reply_to else None + _validate_media_paths(images, videos) + mode = _structured_mode(as_json=as_json, as_yaml=as_yaml) + normalized_reply_to = None + if reply_to: + normalized_reply_to = _normalize_tweet_id_guarded( + reply_to, mode=mode, details={"action": "post", "replyTo": reply_to} + ) + if normalized_reply_to is None: + return action = "Replying to %s" % normalized_reply_to if normalized_reply_to else "Posting tweet" - rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml) + rich_output = not mode def operation(client: TwitterClient) -> WritePayload: media_ids = _upload_images(client, images, video_paths=videos, rich_output=rich_output) @@ -1330,29 +1414,36 @@ def operation(client: TwitterClient) -> WritePayload: success_lines=["[green]✅ Tweet posted![/green]"], error_details={"action": "post", "replyTo": normalized_reply_to}, ) - if payload and not _structured_mode(as_json=as_json, as_yaml=as_yaml): + if payload and not mode: console.print("🔗 %s" % payload["url"]) @cli.command(name="reply") @click.argument("tweet_id") @click.argument("text") -@click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.") -@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True), help="Attach video (max 1; mp4/mov/webm up to 512 MB).") +@click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True, dir_okay=False), help="Attach image (up to 4). Repeatable.") +@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True, dir_okay=False), help="Attach video (max 1; mp4/mov/webm up to 512 MB).") @structured_output_options def reply_tweet(tweet_id, text, images, videos, as_json, as_yaml): # type: (str, str, tuple, tuple, bool, bool) -> None """Reply to a tweet. TWEET_ID is the tweet to reply to, TEXT is the reply content.""" - tweet_id = _normalize_tweet_id(tweet_id) - rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml) + _validate_media_paths(images, videos) + mode = _structured_mode(as_json=as_json, as_yaml=as_yaml) + normalized_id = _normalize_tweet_id_guarded( + tweet_id, mode=mode, details={"action": "reply", "replyTo": tweet_id} + ) + if normalized_id is None: + return + rich_output = not mode + def operation(client: TwitterClient) -> WritePayload: media_ids = _upload_images(client, images, video_paths=videos, rich_output=rich_output) - new_id = client.create_tweet(text, reply_to_id=tweet_id, media_ids=media_ids or None) + new_id = client.create_tweet(text, reply_to_id=normalized_id, media_ids=media_ids or None) return { "success": True, "action": "reply", "id": new_id, - "replyTo": tweet_id, + "replyTo": normalized_id, "url": "https://x.com/i/status/%s" % new_id, } @@ -1360,33 +1451,40 @@ def operation(client: TwitterClient) -> WritePayload: as_json=as_json, as_yaml=as_yaml, operation=operation, - progress_lines=["💬 Replying to %s..." % tweet_id], + progress_lines=["💬 Replying to %s..." % normalized_id], success_lines=["[green]✅ Reply posted![/green]"], - error_details={"action": "reply", "replyTo": tweet_id}, + error_details={"action": "reply", "replyTo": normalized_id}, ) - if payload and not _structured_mode(as_json=as_json, as_yaml=as_yaml): + if payload and not mode: console.print("🔗 %s" % payload["url"]) @cli.command(name="quote") @click.argument("tweet_id") @click.argument("text") -@click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.") -@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True), help="Attach video (max 1; mp4/mov/webm up to 512 MB).") +@click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True, dir_okay=False), help="Attach image (up to 4). Repeatable.") +@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True, dir_okay=False), help="Attach video (max 1; mp4/mov/webm up to 512 MB).") @structured_output_options def quote_tweet(tweet_id, text, images, videos, as_json, as_yaml): # type: (str, str, tuple, tuple, bool, bool) -> None """Quote-tweet a tweet. TWEET_ID is the tweet to quote, TEXT is the commentary.""" - tweet_id = _normalize_tweet_id(tweet_id) - rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml) + _validate_media_paths(images, videos) + mode = _structured_mode(as_json=as_json, as_yaml=as_yaml) + normalized_id = _normalize_tweet_id_guarded( + tweet_id, mode=mode, details={"action": "quote", "quotedId": tweet_id} + ) + if normalized_id is None: + return + rich_output = not mode + def operation(client: TwitterClient) -> WritePayload: media_ids = _upload_images(client, images, video_paths=videos, rich_output=rich_output) - new_id = client.quote_tweet(tweet_id, text, media_ids=media_ids or None) + new_id = client.quote_tweet(normalized_id, text, media_ids=media_ids or None) return { "success": True, "action": "quote", "id": new_id, - "quotedId": tweet_id, + "quotedId": normalized_id, "url": "https://x.com/i/status/%s" % new_id, } @@ -1394,12 +1492,12 @@ def operation(client: TwitterClient) -> WritePayload: as_json=as_json, as_yaml=as_yaml, operation=operation, - progress_lines=["🔄 Quoting tweet %s..." % tweet_id], + progress_lines=["🔄 Quoting tweet %s..." % normalized_id], success_lines=["[green]✅ Quote tweet posted![/green]"], - error_details={"action": "quote", "quotedId": tweet_id}, + error_details={"action": "quote", "quotedId": normalized_id}, ) - if payload and not _structured_mode(as_json=as_json, as_yaml=as_yaml): - console.print("🔗 %s" % payload["url"]) + if payload and not mode: + console.print("🔗 %s" % payload["url"]) @cli.command(name="status") @@ -1580,7 +1678,7 @@ def unbookmark(tweet_id, as_json, as_yaml): @cli.command(name="news") -@click.option("--max", "-n", "max_count", type=int, default=20, show_default=True, help="Max stories to return.") +@click.option("--max", "-n", "max_count", type=click.IntRange(min=1), default=20, show_default=True, help="Max stories to return.") @structured_output_options def news(max_count, as_json, as_yaml): # type: (int, bool, bool) -> None @@ -1640,10 +1738,11 @@ def doctor(refresh, as_json, as_yaml): from importlib.metadata import version as _pkg_version xct_ver = _pkg_version("xclienttransaction") except Exception: - xct_ver = "unknown" + xct_ver = "missing" + deps_ok = curl_ver != "missing" and xct_ver != "missing" checks.append({ "category": "deps", - "status": "pass" if curl_ver != "missing" else "error", + "status": "pass" if deps_ok else "error", "message": "curl_cffi=%s, xclienttransaction=%s" % (curl_ver, xct_ver), }) @@ -1672,7 +1771,11 @@ def doctor(refresh, as_json, as_yaml): }) # 4. Transaction cache status - ct_path = Path(TwitterClient._ct_cache_path()) + ct_path = Path( + TwitterClient._ct_cache_path() + if TwitterClient is not None + else str(Path.home() / ".twitter-cli" / "transaction_cache.json") + ) if ct_path.exists(): try: ct_payload = json.loads(ct_path.read_text(encoding="utf-8")) @@ -1699,28 +1802,55 @@ def doctor(refresh, as_json, as_yaml): # 5. Query IDs cache / live refresh qid_path = _qid_cache_path() if refresh: - refreshed = refresh_query_ids(_url_fetch) - checks.append({ - "category": "query_ids", - "status": "pass" if refreshed else "warning", - "message": "Refreshed %d live queryIds (fallback baseline: %d)" % ( - len(refreshed), len(FALLBACK_QUERY_IDS) - ), - }) + if _url_fetch is None: + checks.append({ + "category": "query_ids", + "status": "error", + "message": "Cannot refresh live queryIds: HTTP client dependencies are missing", + }) + else: + refreshed = refresh_query_ids(_url_fetch) + checks.append({ + "category": "query_ids", + "status": "pass" if refreshed else "warning", + "message": "Refreshed %d live queryIds (fallback baseline: %d)" % ( + len(refreshed), len(FALLBACK_QUERY_IDS) + ), + }) else: - cached_count = 0 if qid_path.exists(): try: - cached_count = len(json.loads(qid_path.read_text(encoding="utf-8")).get("query_ids", {})) - except Exception: - cached_count = 0 - checks.append({ - "category": "query_ids", - "status": "pass", - "message": "Fallback baseline=%d, disk cache=%d" % (len(FALLBACK_QUERY_IDS), cached_count), - }) + qid_payload = json.loads(qid_path.read_text(encoding="utf-8")) + cached_count = len(qid_payload.get("query_ids", {})) + age_s = int(time.time() - float(qid_payload.get("created_at", 0))) + fresh = age_s <= _QID_CACHE_TTL + checks.append({ + "category": "query_ids", + "status": "pass" if fresh else "warning", + "message": "Fallback baseline=%d, disk cache=%d (%s, age=%ds)" % ( + len(FALLBACK_QUERY_IDS), + cached_count, + "fresh" if fresh else "expired", + age_s, + ), + }) + except Exception as exc: + checks.append({ + "category": "query_ids", + "status": "warning", + "message": "Query ID cache unreadable: %s" % exc, + }) + else: + checks.append({ + "category": "query_ids", + "status": "pass", + "message": "Fallback baseline=%d, disk cache=0" % len(FALLBACK_QUERY_IDS), + }) + has_error = any(item["status"] == "error" for item in checks) if emit_structured({"checks": checks}, as_json=as_json, as_yaml=as_yaml): + if has_error: + sys.exit(1) return table = Table(title="🩺 twitter-cli doctor") @@ -1732,6 +1862,8 @@ def doctor(refresh, as_json, as_yaml): table.add_row(item["category"], "%s %s" % (icon, item["status"]), item["message"]) console.print(table) console.print() + if has_error: + sys.exit(1) if __name__ == "__main__": diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 7368669..503aec6 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -142,7 +142,7 @@ def _is_stale_query_error(exc): """Return whether an API error indicates a stale persisted query ID.""" if exc.status_code in (404, 422): return True - if exc.status_code != 0: + if exc.status_code not in (0, 400): return False message = exc.message.lower() return any( @@ -199,9 +199,10 @@ def _twitter_deeplink_to_url(url): if url.startswith(("https://", "http://")): return url if url.startswith("twitter://trending/"): - trend_id = url.rsplit("/", 1)[-1] + parsed = urllib.parse.urlparse(url) + trend_id = _extract_trend_id(url) or parsed.path.rsplit("/", 1)[-1] return "https://x.com/i/trending/%s" % urllib.parse.quote(trend_id) - if url.startswith("twitter://search/"): + if url.startswith(("twitter://search/", "twitter://search?")): parsed = urllib.parse.urlparse(url) query = urllib.parse.parse_qs(parsed.query) raw_query = query.get("query", [""])[0] @@ -645,8 +646,11 @@ def fetch_tweet_detail(self, tweet_id, count=20, cursor=None, return_cursor=Fals When ``cursor`` is None, verifies that the focal tweet is present in the response (raising NotFoundError instead of silently returning empty - or reply-only results) and places it first. + or reply-only results) and places it first before truncating to ``count``. """ + if count <= 0: + return ([], None) if return_cursor else [] + result = self._fetch_timeline( "TweetDetail", count, @@ -672,6 +676,7 @@ def fetch_tweet_detail(self, tweet_id, count=20, cursor=None, return_cursor=Fals }, start_cursor=cursor, return_cursor=return_cursor, + truncate=cursor is not None, ) if return_cursor: tweets, next_cursor = result @@ -684,7 +689,8 @@ def fetch_tweet_detail(self, tweet_id, count=20, cursor=None, return_cursor=Fals raise NotFoundError( "Tweet %s was not returned by the TweetDetail response" % tweet_id ) - tweets = [focal_tweet] + [tweet for tweet in tweets if tweet.id != tweet_id] + limit = min(count, getattr(self, "_max_count", count)) + tweets = ([focal_tweet] + [tweet for tweet in tweets if tweet.id != tweet_id])[:limit] if return_cursor: return tweets, next_cursor @@ -840,11 +846,13 @@ def fetch_following(self, user_id, count=20): # ── Write operations ───────────────────────────────────────────── - # Supported image MIME types and max file sizes + # Supported image/video MIME types and max file sizes _SUPPORTED_IMAGE_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"} + _SUPPORTED_VIDEO_TYPES = {"video/mp4", "video/quicktime", "video/webm"} _MAX_IMAGE_SIZE = 5 * 1024 * 1024 # 5 MB _MAX_VIDEO_SIZE = 512 * 1024 * 1024 # 512 MB (X hard cap for tweet_video) - _VIDEO_CHUNK_SIZE = 4 * 1024 * 1024 # 4 MB per APPEND segment + # Keep raw chunk <= 2 MB so base64 + form encoding stays safely below X's 5 MB segment limit + _VIDEO_CHUNK_SIZE = 2 * 1024 * 1024 _VIDEO_PROCESS_TIMEOUT = 300 # seconds to wait for async video processing def _write_delay(self): @@ -858,18 +866,25 @@ def upload_media(self, file_path): # type: (str) -> str """Upload an image or video file to Twitter. Returns the media_id string. - Uses Twitter's chunked upload API (INIT → APPEND → FINALIZE [+ STATUS for video]). + Uses Twitter's chunked upload API (INIT → APPEND → FINALIZE [+ STATUS]). Images: JPEG, PNG, GIF, WebP up to 5 MB. - Videos (mp4/mov/webm): up to 512 MB, uploaded in 4 MB chunks with async STATUS polling. + Videos (mp4/mov/webm): up to 512 MB, uploaded in 2 MB chunks with async STATUS polling. """ if not os.path.isfile(file_path): raise MediaUploadError("File not found: %s" % file_path) file_size = os.path.getsize(file_path) + if file_size <= 0: + raise MediaUploadError("File is empty: %s" % file_path) + media_type = mimetypes.guess_type(file_path)[0] or "" - is_video = media_type.startswith("video/") + is_video = media_type in self._SUPPORTED_VIDEO_TYPES - if is_video: + if media_type.startswith("video/"): + if not is_video: + raise MediaUploadError( + "Unsupported video format: %s (supported: mp4, mov, webm)" % media_type + ) if file_size > self._MAX_VIDEO_SIZE: raise MediaUploadError( "File too large: %.1f MB (max %.0f MB)" @@ -886,7 +901,7 @@ def upload_media(self, file_path): raise MediaUploadError( "Unsupported image format: %s (supported: jpeg, png, gif, webp)" % media_type ) - media_category = "tweet_image" + media_category = "tweet_gif" if media_type == "image/gif" else "tweet_image" upload_url = "https://upload.twitter.com/i/media/upload.json" session = _get_cffi_session() @@ -918,10 +933,7 @@ def upload_media(self, file_path): while True: media_bytes = f.read(self._VIDEO_CHUNK_SIZE if is_video else None) if not media_bytes: - if segment_index == 0 and not is_video: - media_bytes = b"" - else: - break + break media_data = base64.b64encode(media_bytes).decode("ascii") headers = self._build_headers(url=upload_url, method="POST") headers.pop("Content-Type", None) @@ -956,25 +968,34 @@ def upload_media(self, file_path): raise MediaUploadError("FINALIZE failed (HTTP %d): %s" % (resp.status_code, resp.text[:300])) logger.info("Media FINALIZE: media_id=%s ready", media_id) - # ── STATUS (videos only) ───────────────────────────────────── - if is_video: - try: - finalize_result = json.loads(resp.text) - except (json.JSONDecodeError, ValueError): - finalize_result = {} - info = finalize_result.get("processing_info") if isinstance(finalize_result, dict) else None - deadline = time.time() + self._VIDEO_PROCESS_TIMEOUT + # ── STATUS (whenever FINALIZE returns processing_info, e.g. video/GIF) ── + try: + finalize_result = json.loads(resp.text) + except (json.JSONDecodeError, ValueError): + finalize_result = {} + info = finalize_result.get("processing_info") if isinstance(finalize_result, dict) else None + if isinstance(info, dict): + deadline = time.monotonic() + self._VIDEO_PROCESS_TIMEOUT while isinstance(info, dict) and info.get("state") not in (None, "succeeded"): state = info.get("state") if state == "failed": raise MediaUploadError( - "Video processing failed: %s" % json.dumps(info.get("error", info)) + "Media processing failed: %s" % json.dumps(info.get("error", info)) ) - wait = max(1, int(info.get("check_after_secs", 3))) - time.sleep(wait) - if time.time() > deadline: + raw_wait = info.get("check_after_secs") + try: + wait = max(1.0, float(raw_wait)) if raw_wait is not None else 3.0 + except (TypeError, ValueError): + wait = 3.0 + remaining = deadline - time.monotonic() + if remaining <= 0: raise MediaUploadError( - "Video processing timed out after %ds" % self._VIDEO_PROCESS_TIMEOUT + "Media processing timed out after %ds" % self._VIDEO_PROCESS_TIMEOUT + ) + time.sleep(min(wait, remaining)) + if time.monotonic() >= deadline: + raise MediaUploadError( + "Media processing timed out after %ds" % self._VIDEO_PROCESS_TIMEOUT ) headers = self._build_headers(url=upload_url, method="GET") resp = session.get( @@ -992,7 +1013,7 @@ def upload_media(self, file_path): except (json.JSONDecodeError, ValueError): raise MediaUploadError("STATUS returned invalid JSON") info = status_result.get("processing_info") if isinstance(status_result, dict) else None - logger.info("Media STATUS: video processing complete") + logger.info("Media STATUS: processing complete") return media_id @@ -1188,8 +1209,8 @@ def unfollow_user(self, user_id): # ── Internal: timeline / user list fetchers ────────────────────── - def _fetch_timeline(self, operation_name, count, get_instructions, extra_variables=None, override_base_variables=False, field_toggles=None, use_post=False, include_promoted=False, start_cursor=None, return_cursor=False): - # type: (str, int, Callable[[Any], Any], Optional[Dict[str, Any]], bool, Optional[Dict[str, Any]], bool, bool, Optional[str], bool) -> Any + def _fetch_timeline(self, operation_name, count, get_instructions, extra_variables=None, override_base_variables=False, field_toggles=None, use_post=False, include_promoted=False, start_cursor=None, return_cursor=False, truncate=True): + # type: (str, int, Callable[[Any], Any], Optional[Dict[str, Any]], bool, Optional[Dict[str, Any]], bool, bool, Optional[str], bool, bool) -> Any """Generic timeline fetcher with pagination and deduplication. Args: @@ -1198,9 +1219,10 @@ def _fetch_timeline(self, operation_name, count, get_instructions, extra_variabl endpoints like SearchTimeline that reject unknown variables. use_post: If True, send request via POST instead of GET. Required for endpoints like SearchTimeline that Twitter migrated to POST. + truncate: If True (default), slice returned tweets to ``count``. """ if count <= 0: - return [] + return ([], None) if return_cursor else [] # Enforce max count cap count = min(count, self._max_count) @@ -1259,9 +1281,10 @@ def _fetch_timeline(self, operation_name, count, get_instructions, extra_variabl logger.debug("Sleeping %.1fs between requests", jitter) time.sleep(jitter) + result_tweets = tweets[:count] if truncate else tweets if return_cursor: - return tweets[:count], continuation_cursor - return tweets[:count] + return result_tweets, continuation_cursor + return result_tweets def _fetch_user_list(self, operation_name, user_id, count, get_instructions, use_post=False): # type: (str, str, int, Callable[[Any], Any], bool) -> List[UserProfile] @@ -1358,7 +1381,12 @@ def _graphql_get(self, operation_name, variables, features, field_toggles=None): if _is_stale_query_error(exc): logger.info("Retrying %s with live queryId after stale-query response", operation_name) _invalidate_query_id(operation_name) - refreshed_query_id = _resolve_query_id(operation_name, prefer_fallback=False, url_fetch_fn=_url_fetch) + refreshed_query_id = _resolve_query_id( + operation_name, + prefer_fallback=False, + url_fetch_fn=_url_fetch, + exclude_ids={query_id}, + ) if refreshed_query_id != query_id: retry_url = _build_graphql_url(refreshed_query_id, operation_name, variables, features, field_toggles) return self._api_get(retry_url) @@ -1383,7 +1411,12 @@ def _do_post(qid): if _is_stale_query_error(exc): logger.info("Retrying POST %s with live queryId after stale-query response", operation_name) _invalidate_query_id(operation_name) - refreshed = _resolve_query_id(operation_name, prefer_fallback=False, url_fetch_fn=_url_fetch) + refreshed = _resolve_query_id( + operation_name, + prefer_fallback=False, + url_fetch_fn=_url_fetch, + exclude_ids={query_id}, + ) if refreshed != query_id: return _do_post(refreshed) raise @@ -1519,7 +1552,7 @@ def _save_ct_cache(self, home_html, ondemand_text): try: cache_path = self._ct_cache_path() cache_dir = os.path.dirname(cache_path) - os.makedirs(cache_dir, exist_ok=True) + os.makedirs(cache_dir, mode=0o700, exist_ok=True) _tighten_dir(Path(cache_dir)) cache = { "home_html": home_html, @@ -1549,11 +1582,11 @@ def _ensure_client_transaction(self): """Initialize ClientTransaction for x-client-transaction-id header. Tries cache first (1h TTL), then fetches fresh responsive-web bootstrap - HTML from x.com. Since X migrated anonymous `/` and `/home` to the - stripped Vite `x-web` shell without `ondemand.s`, we try authenticated - `https://x.com/home` first and fall back to unauthenticated - `https://x.com/i/jf/` (which serves the responsive-web shell). - Also updates live feature flags from the fetched HTML. + HTML from x.com. Prefers unauthenticated ``https://x.com/i/jf/`` first + (avoids sending session cookies or caching authenticated HTML on disk) + and falls back to authenticated ``https://x.com/home`` if needed. + Validates the full ``ClientTransaction(...)`` initialization inside the + candidate loop so an incomplete/interstitial page cleanly falls back. """ if self._ct_init_attempted: return @@ -1572,52 +1605,55 @@ def _ensure_client_transaction(self): base_headers = dict(_gen_ct_headers()) cookie_header = self._ct_bootstrap_cookie() - candidates = [] + candidates = [("https://x.com/i/jf/", dict(base_headers), False)] if cookie_header: auth_headers = dict(base_headers) auth_headers["Cookie"] = cookie_header - candidates.append(("https://x.com/home", auth_headers)) - candidates.append(("https://x.com/i/jf/", dict(base_headers))) + candidates.append(("https://x.com/home", auth_headers, True)) - home_page = None - home_page_response = None - ondemand_url = None - - for bootstrap_url, req_headers in candidates: + for bootstrap_url, req_headers, is_authenticated in candidates: try: resp = cffi_session.get(bootstrap_url, headers=req_headers, timeout=10) + resp_status = getattr(resp, "status_code", 200) + if isinstance(resp_status, int) and resp_status >= 400: + raise ValueError("HTTP %s from %s" % (resp_status, bootstrap_url)) soup = bs4.BeautifulSoup(resp.content, "html.parser") - url = get_ondemand_file_url(response=soup) - if url: - home_page = resp - home_page_response = soup - ondemand_url = url - logger.debug("Bootstrapped ClientTransaction from %s", bootstrap_url) - break - last_exc = ValueError("No ondemand.s URL found at %s" % bootstrap_url) + ondemand_url = get_ondemand_file_url(response=soup) + if not ondemand_url: + raise ValueError("No ondemand.s URL found at %s" % bootstrap_url) + + # Fetch ondemand JS bundle without session cookies (CDN asset). + ondemand_file = cffi_session.get( + ondemand_url, headers=base_headers, timeout=10, + ) + ondemand_status = getattr(ondemand_file, "status_code", 200) + if isinstance(ondemand_status, int) and ondemand_status >= 400: + raise ValueError( + "HTTP %s from %s" % (ondemand_status, ondemand_url) + ) + ct = ClientTransaction( + home_page_response=soup, + ondemand_file_response=ondemand_file.text, + ) + self._client_transaction = ct + logger.info( + "ClientTransaction initialized for x-client-transaction-id (via %s)", + bootstrap_url, + ) + _update_features_from_html(resp.text) + # Only cache unauthenticated HTML to disk to avoid persisting + # account state from authenticated /home payloads. + if not is_authenticated: + self._save_ct_cache(resp.text, ondemand_file.text) + return except Exception as exc: last_exc = exc - logger.debug("ClientTransaction bootstrap candidate %s failed: %s", bootstrap_url, exc) + logger.debug( + "ClientTransaction bootstrap candidate %s failed: %s", bootstrap_url, exc + ) continue - if not ondemand_url or home_page is None or home_page_response is None: - raise last_exc or ValueError("Failed to extract ondemand file URL from x.com") - - # Fetch ondemand JS bundle without session cookies (CDN asset). - ondemand_file = cffi_session.get( - ondemand_url, headers=base_headers, timeout=10, - ) - self._client_transaction = ClientTransaction( - home_page_response=home_page_response, - ondemand_file_response=ondemand_file.text, - ) - logger.info("ClientTransaction initialized for x-client-transaction-id") - - # Try to extract live FEATURES from the bootstrap HTML - _update_features_from_html(home_page.text) - - # Save to cache for future use - self._save_ct_cache(home_page.text, ondemand_file.text) + raise last_exc or ValueError("Failed to initialize ClientTransaction from x.com") except Exception as exc: logger.warning( "Failed to init ClientTransaction: %s — x-client-transaction-id is " diff --git a/twitter_cli/formatter.py b/twitter_cli/formatter.py index 1671d31..ecdadce 100644 --- a/twitter_cli/formatter.py +++ b/twitter_cli/formatter.py @@ -24,7 +24,9 @@ def set_time_style(style: Optional[str]) -> str: """Select the timestamp rendering style; returns the style in effect.""" global _TIME_STYLE - if style and style in _TIME_STYLES: + if style is None: + _TIME_STYLE = "relative" + elif style in _TIME_STYLES: _TIME_STYLE = style return _TIME_STYLE @@ -77,11 +79,12 @@ def print_tweet_table( if not title: title = "📱 Twitter — %d tweets" % len(tweets) + stats_width = 29 if _TIME_STYLE == "iso" else 22 table = Table(title=title, show_lines=True, expand=True) table.add_column("#", style="dim", width=3, justify="right") table.add_column("Author", style="cyan", width=18, no_wrap=True) table.add_column("Tweet", ratio=3) - table.add_column("Stats", style="green", width=22, no_wrap=True) + table.add_column("Stats", style="green", width=stats_width, no_wrap=True) table.add_column("Score", style="yellow", width=6, justify="right") for i, tweet in enumerate(tweets): @@ -233,7 +236,7 @@ def print_article(tweet: Tweet, console: Optional[Console] = None) -> None: title = tweet.article_title or "Twitter Article" meta_parts = [ "By @%s%s (%s)" % (tweet.author.screen_name, verified, tweet.author.name), - "🕐 %s" % tweet.created_at, + "🕐 %s" % _render_time(tweet.created_at), "🔗 x.com/%s/status/%s" % (tweet.author.screen_name, tweet.id), "", "❤️ %s 🔄 %s 💬 %s 🔖 %s 👁️ %s" diff --git a/twitter_cli/graphql.py b/twitter_cli/graphql.py index cb5f017..011dbb3 100644 --- a/twitter_cli/graphql.py +++ b/twitter_cli/graphql.py @@ -17,9 +17,9 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from typing import Any, Dict, Optional # noqa: F401 + from typing import Any, Collection, Dict, Optional # noqa: F401 -from .cache import _open_owner_only, _tighten_dir +from .cache import _OWNER_ONLY_DIR, _open_owner_only, _tighten_dir from .exceptions import QueryIdError from .text import CREATE_NOTE_TWEET_OPERATION, CREATE_TWEET_OPERATION @@ -157,28 +157,37 @@ def _load_disk_query_ids() -> Dict[str, str]: return {} -def _save_disk_query_ids(query_ids: Dict[str, str]) -> None: - """Persist live-resolved queryIds to disk with owner-only permissions.""" +def _save_disk_query_ids(query_ids: Dict[str, str], replace: bool = False) -> None: + """Persist live-resolved queryIds to disk with owner-only permissions. + + When ``replace`` is False, merges into any non-expired existing cache while + preserving its original ``created_at`` timestamp so stale entries cannot + live forever via a sliding TTL. When ``replace`` is True (full refresh), + replaces the cache contents and resets ``created_at``. + """ if not query_ids: return try: path = _qid_cache_path() - path.parent.mkdir(parents=True, exist_ok=True) + path.parent.mkdir(mode=_OWNER_ONLY_DIR, parents=True, exist_ok=True) _tighten_dir(path.parent) existing: Dict[str, str] = {} - if path.exists(): + created_at = time.time() + if not replace and path.exists(): try: old = json.loads(path.read_text(encoding="utf-8")) + old_created_at = float(old.get("created_at", 0)) if isinstance(old, dict) else 0.0 if ( isinstance(old, dict) - and time.time() - float(old.get("created_at", 0)) <= _QID_CACHE_TTL + and time.time() - old_created_at <= _QID_CACHE_TTL and isinstance(old.get("query_ids"), dict) ): existing = {str(k): str(v) for k, v in old["query_ids"].items() if k and v} + created_at = old_created_at except Exception: pass existing.update(query_ids) - payload = {"created_at": time.time(), "query_ids": existing} + payload = {"created_at": created_at, "query_ids": existing} with _open_owner_only(path) as f: json.dump(payload, f, indent=2) except Exception as exc: @@ -290,8 +299,10 @@ def _scan_bundles(url_fetch_fn): discovered.setdefault(operation_name, query_id) if "/x-web/x-web/" in script_url: - base = script_url.rsplit("/", 1)[0] + "/" + base = script_url.split("/x-web/x-web/", 1)[0] + "/x-web/x-web/" for rel in chunk_ref_pattern.findall(bundle): + if ".." in rel: + continue chunk_url = base + "assets/" + rel if chunk_url not in seen_urls: queue.append(chunk_url) @@ -355,9 +366,10 @@ def _invalidate_query_id(operation_name): def refresh_query_ids(url_fetch_fn): # type: (Any) -> Dict[str, str] """Force a live refresh of queryIds from twitter-openapi and x.com bundles.""" - global _bundles_scanned + global _bundles_scanned, _disk_cache_loaded _cached_query_ids.clear() _bundles_scanned = False + _disk_cache_loaded = True refreshed: Dict[str, str] = {} try: @@ -376,13 +388,15 @@ def refresh_query_ids(url_fetch_fn): refreshed.update(_cached_query_ids) _cached_query_ids.update(refreshed) if refreshed: - _save_disk_query_ids(refreshed) + _save_disk_query_ids(refreshed, replace=True) return dict(refreshed) -def _resolve_query_id(operation_name, prefer_fallback=True, url_fetch_fn=None): - # type: (str, bool, Any) -> str +def _resolve_query_id(operation_name, prefer_fallback=True, url_fetch_fn=None, exclude_ids=None): + # type: (str, bool, Any, Optional[Collection[str]]) -> str """Resolve queryId using env override, caches, remote sources, and fallbacks.""" + excluded = set(exclude_ids) if exclude_ids else set() + # 1. Explicit per-operation environment override: TWITTER_QID_ env_override = os.environ.get("TWITTER_QID_%s" % operation_name, "").strip() if env_override: @@ -394,31 +408,32 @@ def _resolve_query_id(operation_name, prefer_fallback=True, url_fetch_fn=None): _cached_query_ids.setdefault(op_name, qid) cached = _cached_query_ids.get(operation_name) - if cached: + if cached and cached not in excluded: return cached # 3. Fallback constants (when prefer_fallback=True) fallback = FALLBACK_QUERY_IDS.get(operation_name) - if prefer_fallback and fallback: + if prefer_fallback and fallback and fallback not in excluded: _cached_query_ids[operation_name] = fallback return fallback # 4. Live resolution: community twitter-openapi -> x.com JS bundle scan if url_fetch_fn: github_query_id = _fetch_from_github(url_fetch_fn, operation_name) - if github_query_id: + if github_query_id and github_query_id not in excluded: _cached_query_ids[operation_name] = github_query_id _save_disk_query_ids({operation_name: github_query_id}) return github_query_id _scan_bundles(url_fetch_fn) cached = _cached_query_ids.get(operation_name) - if cached: + if cached and cached not in excluded: return cached # 5. Last-resort fallback if fallback: - _cached_query_ids[operation_name] = fallback + if fallback not in excluded: + _cached_query_ids[operation_name] = fallback return fallback raise QueryIdError('Cannot resolve queryId for "%s"' % operation_name) diff --git a/twitter_cli/parser.py b/twitter_cli/parser.py index 598e9d5..8b4882c 100644 --- a/twitter_cli/parser.py +++ b/twitter_cli/parser.py @@ -181,9 +181,12 @@ def _extract_media(legacy): def _extract_author(user_data, user_legacy): # type: (Dict[str, Any], Dict[str, Any]) -> Author """Extract Author from user result data.""" - user_core = user_data.get("core", {}) - rel_counts = user_data.get("relationship_counts", {}) - perspectives = user_data.get("relationship_perspectives", {}) + user_data = user_data or {} + user_legacy = user_legacy or {} + user_core = user_data.get("core") or {} + rel_counts = user_data.get("relationship_counts") or {} + perspectives = user_data.get("relationship_perspectives") or {} + avatar = user_data.get("avatar") or {} followers = _parse_int(user_legacy.get("followers_count"), 0) or _parse_int( rel_counts.get("followers"), 0 ) @@ -197,16 +200,18 @@ def _extract_author(user_data, user_legacy): if viewer_followed_by is None: viewer_followed_by = _opt_bool(perspectives.get("followed_by")) return Author( - id=user_data.get("rest_id", ""), - name=user_core.get("name") or user_legacy.get("name") or user_data.get("name", "Unknown"), + id=user_data.get("rest_id") or "", + name=user_core.get("name") or user_legacy.get("name") or user_data.get("name") or "Unknown", screen_name=( user_core.get("screen_name") or user_legacy.get("screen_name") - or user_data.get("screen_name", "unknown") + or user_data.get("screen_name") + or "unknown" ), profile_image_url=( - user_data.get("avatar", {}).get("image_url") - or user_legacy.get("profile_image_url_https", "") + avatar.get("image_url") + or user_legacy.get("profile_image_url_https") + or "" ), verified=bool(user_data.get("is_blue_verified") or user_legacy.get("verified", False)), followers_count=followers, @@ -331,19 +336,46 @@ def _extract_atomic_content(block, entity_map): _extract_atomic_markdown = _extract_atomic_content +def _utf16_offset_map(text): + # type: (str) -> Dict[int, int] + """Map UTF-16 code unit boundaries to Python codepoint indices.""" + mapping = {0: 0} + utf16_pos = 0 + for py_idx, ch in enumerate(text): + utf16_pos += 2 if ord(ch) > 0xFFFF else 1 + mapping[utf16_pos] = py_idx + 1 + return mapping + + +def _valid_draft_range(offset, length, u16_map): + # type: (Any, Any, Dict[int, int]) -> Optional[Tuple[int, int]] + """Convert a Draft.js UTF-16 (offset, length) range into Python slice indices.""" + if isinstance(offset, bool) or isinstance(length, bool): + return None + if not isinstance(offset, int) or not isinstance(length, int) or length <= 0 or offset < 0: + return None + py_start = u16_map.get(offset) + py_end = u16_map.get(offset + length) + if py_start is None or py_end is None or py_end <= py_start: + return None + return py_start, py_end + + def _render_article_text_block(block, entity_map): # type: (Dict[str, Any], Dict[str, Any]) -> str """Render a Draft.js text block, converting inline styles and hyperlinks to Markdown. - Both inlineStyleRanges and entityRanges (links) reference original text - offsets. Links take priority over overlapping style spans so offsets are - never corrupted, and accepted non-overlapping spans are applied + Both inlineStyleRanges and entityRanges (links) use Draft.js UTF-16 code + unit offsets. Links take priority over overlapping style spans so offsets + are never corrupted, and accepted non-overlapping spans are applied right-to-left. """ text = block.get("text", "") if not isinstance(text, str) or not text: return "" + u16_map = _utf16_offset_map(text) + # Collect operations as (priority, start, end, replacement): lower priority wins overlaps. candidates = [] # type: List[Tuple[int, int, int, str]] @@ -357,21 +389,19 @@ def _render_article_text_block(block, entity_map): continue if str(entity.get("type") or "").upper() != "LINK": continue - offset = entity_range.get("offset") - length = entity_range.get("length") - if not isinstance(offset, int) or not isinstance(length, int) or length <= 0: - continue - if offset < 0 or offset + length > len(text): + bounds = _valid_draft_range(entity_range.get("offset"), entity_range.get("length"), u16_map) + if bounds is None: continue + py_start, py_end = bounds url = _deep_get(entity, "data", "url") if not isinstance(url, str) or not url.strip(): continue - label = text[offset:offset + length] + label = text[py_start:py_end] if not label: continue safe_label = label.replace("[", "\\[").replace("]", "\\]") safe_url = url.strip().replace(")", "%29") - candidates.append((0, offset, offset + length, "[%s](%s)" % (safe_label, safe_url))) + candidates.append((0, py_start, py_end, "[%s](%s)" % (safe_label, safe_url))) # Inline styles (priority 1) style_markers = { @@ -384,16 +414,14 @@ def _render_article_text_block(block, entity_map): if not isinstance(sr, dict): continue style = str(sr.get("style", "")).upper() - offset = sr.get("offset") - length = sr.get("length") - if not isinstance(offset, int) or not isinstance(length, int) or length <= 0: - continue - if offset < 0 or offset + length > len(text): + bounds = _valid_draft_range(sr.get("offset"), sr.get("length"), u16_map) + if bounds is None: continue + py_start, py_end = bounds if style in style_markers: open_m, close_m = style_markers[style] - segment = text[offset:offset + length] - candidates.append((1, offset, offset + length, "%s%s%s" % (open_m, segment, close_m))) + segment = text[py_start:py_end] + candidates.append((1, py_start, py_end, "%s%s%s" % (open_m, segment, close_m))) if not candidates: return text @@ -551,12 +579,12 @@ def parse_user_result(user_data): viewer_followed_by = _opt_bool(perspectives.get("followed_by")) return UserProfile( - id=user_data.get("rest_id", ""), - name=core.get("name") or legacy.get("name", ""), - screen_name=core.get("screen_name") or legacy.get("screen_name", ""), - bio=legacy.get("description") or profile_bio.get("description", ""), - location=location_obj.get("location") or legacy.get("location", ""), - url=_deep_get(legacy, "entities", "url", "urls", 0, "expanded_url") or website.get("url", ""), + id=user_data.get("rest_id") or "", + name=core.get("name") or legacy.get("name") or "", + screen_name=core.get("screen_name") or legacy.get("screen_name") or "", + bio=legacy.get("description") or profile_bio.get("description") or "", + location=location_obj.get("location") or legacy.get("location") or "", + url=_deep_get(legacy, "entities", "url", "urls", 0, "expanded_url") or website.get("url") or "", followers_count=max( _parse_int(legacy.get("followers_count"), 0), _parse_int(rel_counts.get("followers"), 0), @@ -578,8 +606,8 @@ def parse_user_result(user_data): or legacy.get("verified", False) or verification.get("verified", False) ), - profile_image_url=avatar.get("image_url") or legacy.get("profile_image_url_https", ""), - created_at=core.get("created_at") or legacy.get("created_at", ""), + profile_image_url=avatar.get("image_url") or legacy.get("profile_image_url_https") or "", + created_at=core.get("created_at") or legacy.get("created_at") or "", viewer_following=viewer_following, viewer_followed_by=viewer_followed_by, ) @@ -612,8 +640,8 @@ def parse_tweet_result(result, depth=0): return None user = _deep_get(core, "user_results", "result") or {} - user_legacy = user.get("legacy", {}) - user_core = user.get("core", {}) + user_legacy = user.get("legacy") or {} + user_core = user.get("core") or {} is_retweet = bool(_deep_get(legacy, "retweeted_status_result", "result")) actual_data = tweet_data @@ -630,7 +658,7 @@ def parse_tweet_result(result, depth=0): actual_data = retweet_result actual_legacy = rt_legacy actual_user = _deep_get(rt_core, "user_results", "result") or {} - actual_user_legacy = actual_user.get("legacy", {}) + actual_user_legacy = actual_user.get("legacy") or {} media = _extract_media(actual_legacy) urls = [item.get("expanded_url", "") for item in _deep_get(actual_legacy, "entities", "urls") or []] diff --git a/twitter_cli/text.py b/twitter_cli/text.py index c65bb35..c569bcc 100644 --- a/twitter_cli/text.py +++ b/twitter_cli/text.py @@ -22,34 +22,56 @@ (0x2032, 0x2037), ) -_PROTOCOL_URL = r"https?://[^\s<>{}\[\]\"']+" +# Common IANA TLDs recognized by twitter-text for bare domains without http(s):// +# (prevents filenames like config.yaml / README.md / cli.py or prose like Hello.World +# from being inflated to 23 chars and misrouted to CreateNoteTweet). +_COMMON_TLDS = ( + "com|org|net|edu|gov|mil|int|io|co|ai|app|dev|me|tv|gg|xyz|info|biz|tech|cloud|" + "news|live|shop|store|site|online|blog|page|link|so|sh|to|ly|gl|be|de|uk|fr|jp|" + "cn|kr|ca|au|in|br|es|it|nl|se|ch|ru|pl|tw|hk|sg|eu|us|nz|id|vn|th|mx|ar|cl|za|" + "pro|club|top|icu|vip|cc|fm|im|is|la|vc|ws|ag|am|at|cz|dk|fi|gr|hu|ie|il|no|pt|" + "ro|sk|tr|ua|ac|pub|run|bot|fun|wtf|lol|new|now|one|art|inc|nyc|ooo|tel|xxx" +) + +_PROTOCOL_URL = r"(?{}\[\]\"']+" _BARE_URL = ( - r"(?:[^\W_](?:[\w-]{0,61}[^\W_])?\.)+" - r"(?:[^\W\d_]{2,63}|xn--[\w-]{2,59})" + r"(?{}\[\]\"']*)?" -) -_URL_RE = re.compile(r"(? int """Return the URL end before prose punctuation or unmatched closers.""" end = len(url) - while end and url[end - 1] in _TRAILING_URL_PUNCTUATION: - end -= 1 - for opening, closing in (("(", ")"), ("[", "]"), ("{", "}")): - while end and url[end - 1] == closing and url[:end].count(closing) > url[:end].count(opening): + while end: + prev = end + while end and url[end - 1] in _TRAILING_URL_PUNCTUATION: end -= 1 + for opening, closing in (("(", ")"), ("[", "]"), ("{", "}")): + while end and url[end - 1] == closing and url[:end].count(closing) > url[:end].count(opening): + end -= 1 + if end == prev: + break return end @@ -94,6 +116,11 @@ def _emoji_sequence_end(text, index, limit): return index + 2 return index + 1 + if codepoint in _TEXT_DEFAULT_EMOJI_BASES: + if index + 1 < limit and ord(text[index + 1]) == 0xFE0F: + return _consume_emoji_suffix(text, index + 2, limit) + return None + if not _is_emoji_base(codepoint): return None