Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,11 @@ This file records user-visible changes maintained on the `stable` branch from
- `twitter notifications` for account activity including mentions, replies,
quotes, likes, follows, and reposts.
- `twitter users <query>` for user typeahead search.
- Bookmark timelines, including individual folders, accept `--cursor` and
expose the continuation in structured output.
- Structured tweets and media include X's sensitive-content labels.

### Fixed

- Resume a timeline from the last returned tweet when X sends an oversized page.
- Require curl_cffi 0.15.0 or later for GHSA-qw2m-4pqf-rmpp.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ twitter feed --json # Structured stdout for scripts/agents
# Bookmarks
twitter bookmarks
twitter bookmarks --full-text
twitter bookmarks --cursor "<nextCursor>" --json
twitter bookmarks --max 30 --yaml

# Notifications
Expand Down Expand Up @@ -501,6 +502,7 @@ twitter feed --cursor "<上一页返回的 nextCursor>"
# 收藏
twitter bookmarks
twitter bookmarks --full-text
twitter bookmarks --cursor "<nextCursor>" --json

# 通知
twitter notifications --max 20 --json
Expand Down
10 changes: 9 additions & 1 deletion SCHEMA.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,22 @@ error:
- non-TTY stdout defaults to YAML
- tweet and user lists are returned under `data`
- `lists` returns owned and followed list metadata under `data`
- timeline-style list commands may also return `pagination.nextCursor`
- Timeline commands, including `bookmarks`, `favorites`, and `bookmarks folders <id>`,
may return `pagination.nextCursor`. Pass its value unchanged to the same timeline
with `--cursor` to continue.
- `article` returns a single tweet object under `data`
- `status` returns `data.authenticated` plus `data.user`
- `whoami` returns `data.user`
- `user-posts --cursor ...` returns tweets under `data` and may include `pagination.nextCursor`
- `notifications` returns account activity under `data` and may include `pagination.nextCursor`
- write commands also support explicit `--json` / `--yaml`

## Sensitive media

Structured tweet data includes `possiblySensitive` on tweets and quoted tweets.
Each media item includes `adultContent`, `graphicViolence`, and `otherWarning`.
A false value means X supplied no positive flag for that field.

## Notification Fields

```yaml
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ dependencies = [
"click>=8.0",
"rich>=13.0",
"PyYAML>=6.0",
"curl_cffi>=0.7",
"curl_cffi>=0.15.0",
"xclienttransaction>=1.0.1",
"beautifulsoup4>=4.12",
]
Expand Down
1 change: 1 addition & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ 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),
)

return _make_tweet
Expand Down
25 changes: 23 additions & 2 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,25 @@ def bookmark_tweet(self, tweet_id: str) -> bool:
assert calls == ["123"]


@pytest.mark.parametrize("command", [["bookmarks"], ["favorites"], ["bookmarks", "folders", "42"]])
def test_bookmark_commands_resume_pages(command, monkeypatch, tweet_factory):
from unittest.mock import Mock
client = Mock()
fetch = client.fetch_bookmark_folder_timeline if "folders" in command else client.fetch_bookmarks
fetch.return_value = ([tweet_factory("9")], "next")
monkeypatch.setattr("twitter_cli.cli._get_client", lambda config, quiet: client)
monkeypatch.setattr("twitter_cli.cli.save_tweet_cache", lambda tweets: None)

result = CliRunner().invoke(cli, [*command, "--cursor", "prev", "--max", "1", "--json"])

assert result.exit_code == 0, result.output
payload = json.loads(result.output)
assert [row["id"] for row in payload["data"]] == ["9"]
assert payload["pagination"] == {"nextCursor": "next"}
args = ("42", 1) if "folders" in command else (1,)
fetch.assert_called_once_with(*args, cursor="prev", return_cursor=True)


def test_cli_bookmarks_folders_inherits_parent_options(monkeypatch) -> None:
calls = []

Expand All @@ -630,6 +649,7 @@ def fake_folder_timeline(
do_filter: bool,
compact: bool,
full_text: bool,
cursor: str | None,
) -> None:
calls.append(
(
Expand All @@ -642,6 +662,7 @@ def fake_folder_timeline(
do_filter,
compact,
full_text,
cursor,
)
)

Expand All @@ -650,11 +671,11 @@ def fake_folder_timeline(

result = runner.invoke(
cli,
["bookmarks", "--json", "--full-text", "-n", "7", "-o", "root.json", "--filter", "folders", "123"],
["bookmarks", "--cursor", "folder-page", "--json", "--full-text", "-n", "7", "-o", "root.json", "--filter", "folders", "123"],
)

assert result.exit_code == 0
assert calls == [("123", 7, None, True, False, "root.json", True, False, True)]
assert calls == [("123", 7, None, True, False, "root.json", True, False, True, "folder-page")]


def test_cli_bookmarks_folders_list_inherits_parent_output_options(monkeypatch) -> None:
Expand Down
33 changes: 33 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,39 @@ def test_cookie_string_used_when_available(


class TestPaginationBehavior:
@pytest.mark.parametrize("minimum_page_size", [1, 4])
def test_bookmark_pages_resume_without_skipping(self, minimum_page_size, monkeypatch, tweet_factory):
client = TwitterClient.__new__(TwitterClient)
client._request_delay = 0
client._max_count = 200
items = [tweet_factory(str(i)) for i in range(9)]

def get_page(operation, variables, features, field_toggles=None):
assert operation == "Bookmarks"
offset = int(variables.get("cursor", 0))
end = offset + max(minimum_page_size, variables["count"])
return items[offset:end], str(end) if end < len(items) else None

monkeypatch.setattr(client, "_graphql_get", get_page)
monkeypatch.setattr("twitter_cli.client.parse_timeline_response", lambda page, extract: page)
assert client.fetch_bookmarks(0, return_cursor=True) == ([], None)
assert client.fetch_bookmarks(2) == items[:2]
cursor = None
received = []
for limit in (2, 1, 3, 3):
page, cursor = client.fetch_bookmarks(limit, cursor=cursor, return_cursor=True)
assert len(page) == limit
received.extend(page)
assert received == items
assert cursor is None

def test_changed_bookmark_page_reports_expired_position(self, monkeypatch):
client = TwitterClient.__new__(TwitterClient)
client._max_count = 200
monkeypatch.setattr(client, "_graphql_get", MagicMock(return_value={}))
with pytest.raises(InvalidInputError, match="Restart without --cursor"):
client.fetch_bookmarks(1, cursor="twitter-cli:page:1:removed:", return_cursor=True)

def test_fetch_timeline_can_include_promoted_content(self):
client = TwitterClient.__new__(TwitterClient)
client._request_delay = 0.0
Expand Down
49 changes: 48 additions & 1 deletion tests/test_parser_fixtures.py
Original file line number Diff line number Diff line change
@@ -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


def _make_client() -> TwitterClient:
Expand All @@ -26,6 +26,8 @@ def test_parse_home_timeline_fixture(fixture_loader) -> None:
assert [tweet.id for tweet in tweets] == ["1", "20"]
assert cursor == "cursor-bottom-1"
assert tweets[0].media[0].type == "photo"
assert tweets[0].possibly_sensitive is False
assert tweets[0].media[0].adult_content is False
# note_tweet full text should be preferred over legacy.full_text for long tweets
assert "Show More" in tweets[0].text
assert tweets[0].text.startswith("Hello\nworld\n")
Expand All @@ -36,6 +38,51 @@ def test_parse_home_timeline_fixture(fixture_loader) -> None:
assert tweets[1].quoted_tweet.id == "30"


def test_parse_home_timeline_fixture_sensitive_media(fixture_loader) -> None:
payload = fixture_loader("home_timeline.json")
result = payload["data"]["home"]["home_timeline_urt"]["instructions"][0]["entries"][0]
legacy = result["content"]["itemContent"]["tweet_results"]["result"]["legacy"]
legacy["possibly_sensitive"] = True
legacy["extended_entities"]["media"][0]["ext_sensitive_media_warning"] = {
"adult_content": True,
"graphic_violence": False,
"other": False,
}

tweets, _ = parse_timeline_response(
payload,
lambda data: _deep_get(data, "data", "home", "home_timeline_urt", "instructions"),
)

assert tweets[0].possibly_sensitive is True
assert tweets[0].media[0].adult_content is True
assert tweets[0].media[0].graphic_violence is False
assert tweets[1].possibly_sensitive is False


def test_extract_media_reads_nested_sensitive_warning() -> None:
legacy = {
"extended_entities": {
"media": [
{
"type": "photo",
"media_url_https": "https://pbs.twimg.com/media/fake.jpg",
"original_info": {"width": 10, "height": 10},
"media_results": {
"result": {
"sensitive_media_warning": {"graphic_violence": True}
}
},
}
]
}
}
media = _extract_media(legacy)
assert len(media) == 1
assert media[0].graphic_violence is True
assert media[0].adult_content is False


def test_parse_home_timeline_fixture_marks_promoted_entries(fixture_loader) -> None:
payload = fixture_loader("home_timeline.json")
entry = payload["data"]["home"]["home_timeline_urt"]["instructions"][0]["entries"][0]
Expand Down
36 changes: 36 additions & 0 deletions tests/test_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ def test_tweet_roundtrip_dict(tweet_factory) -> None:
assert restored.id == tweet.id
assert restored.author.screen_name == tweet.author.screen_name
assert restored.metrics.likes == tweet.metrics.likes
assert payload["possiblySensitive"] is False
assert restored.possibly_sensitive is False


def test_tweets_json_roundtrip(tweet_factory) -> None:
Expand Down Expand Up @@ -146,3 +148,37 @@ def test_tweet_roundtrip_preserves_reply_metadata(tweet_factory) -> None:
assert restored.conversation_id == "100"
assert restored.in_reply_to_status_id == "100"
assert restored.in_reply_to_screen_name == "dashhuang"


def test_tweet_roundtrip_preserves_sensitive_media(tweet_factory) -> None:
quoted = tweet_factory("101", possibly_sensitive=True)
tweet = tweet_factory(
"100",
possibly_sensitive=True,
quoted_tweet=quoted,
media=[
TweetMedia(
type="photo",
url="https://pbs.twimg.com/media/example.jpg",
width=10,
height=10,
adult_content=True,
graphic_violence=True,
other_warning=False,
)
],
)
payload = tweet_to_dict(tweet)
assert payload["possiblySensitive"] is True
assert payload["quotedTweet"]["possiblySensitive"] is True
assert payload["media"][0]["adultContent"] is True
assert payload["media"][0]["graphicViolence"] is True
assert payload["media"][0]["otherWarning"] is False

restored = tweet_from_dict(payload)
assert restored.possibly_sensitive is True
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].graphic_violence is True
assert restored.media[0].other_warning is False
Loading