From 86ac8c901f6330cf1cab849715d4c140d86365de Mon Sep 17 00:00:00 2001 From: Jelmer de Wit <1598297+jdwit@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:20:51 +0100 Subject: [PATCH] fix: drop duplicate videos when paging the uploads playlist (#58) playlistItems.list on the uploads playlist can return the same video on more than one page. videos list printed every copy. Keep the first copy per video id, keep the API order, and count only unique videos toward --limit. The same guard goes on the other paged reads: search-replace and playlists add --from-search (dedupe on video id, so no video is updated or added twice) and playlist item listing (dedupe on playlist item id, because a playlist can hold the same video twice on purpose). --- src/ytstudio/commands/playlists.py | 13 +++- src/ytstudio/commands/videos.py | 44 ++++++++---- tests/test_playlists.py | 46 +++++++++++++ tests/test_videos.py | 107 +++++++++++++++++++++++++++++ 4 files changed, 196 insertions(+), 14 deletions(-) diff --git a/src/ytstudio/commands/playlists.py b/src/ytstudio/commands/playlists.py index fbda088..47e5a0d 100644 --- a/src/ytstudio/commands/playlists.py +++ b/src/ytstudio/commands/playlists.py @@ -137,6 +137,7 @@ def _fetch_playlist(service, playlist_id: str) -> Playlist | None: def _fetch_all_items(service, playlist_id: str, limit: int | None = None) -> list[PlaylistItem]: """Paginate through playlistItems, capping at `limit` if provided.""" items: list[PlaylistItem] = [] + seen_ids: set[str] = set() page_token: str | None = None while True: @@ -157,8 +158,14 @@ def _fetch_all_items(service, playlist_id: str, limit: int | None = None) -> lis or {} ) + # Pages can overlap. Dedupe on the playlist item id, not the video id: + # a playlist can hold the same video twice on purpose. for raw in response.get("items", []): - items.append(_parse_playlist_item(raw)) + item = _parse_playlist_item(raw) + if item.id and item.id in seen_ids: + continue + seen_ids.add(item.id) + items.append(item) page_token = response.get("nextPageToken") if not page_token: @@ -545,6 +552,7 @@ def items( def _resolve_search_video_ids(service, query: str, limit: int) -> list[tuple[str, str]]: """Return [(video_id, title)] from search().list, capped at `limit`.""" results: list[tuple[str, str]] = [] + seen_ids: set[str] = set() page_token: str | None = None while len(results) < limit: @@ -566,8 +574,9 @@ def _resolve_search_video_ids(service, query: str, limit: int) -> list[tuple[str for item in response.get("items", []): vid_field = item.get("id") or {} video_id = vid_field.get("videoId") if isinstance(vid_field, dict) else None - if not video_id: + if not video_id or video_id in seen_ids: continue + seen_ids.add(video_id) title = (item.get("snippet") or {}).get("title", "") results.append((video_id, title)) if len(results) >= limit: diff --git a/src/ytstudio/commands/videos.py b/src/ytstudio/commands/videos.py index 1da578c..6b3f67a 100644 --- a/src/ytstudio/commands/videos.py +++ b/src/ytstudio/commands/videos.py @@ -118,6 +118,8 @@ def fetch_videos( uploads_playlist_id = get_channel_uploads_playlist(data_service) all_videos = [] + # The uploads playlist can repeat a video across pages (#58). Keep the first copy. + seen_ids: set[str] = set() current_page_token = page_token total_results = None next_page_token = None @@ -139,20 +141,26 @@ def fetch_videos( if total_results is None: total_results = playlist_response.get("pageInfo", {}).get("totalResults", 0) - items = playlist_response.get("items", []) - if not items: + page_items = playlist_response.get("items", []) + if not page_items: break - video_ids = [item["contentDetails"]["videoId"] for item in items] - - videos_response = api( - data_service.videos().list( - part=parts, - id=",".join(video_ids), + items = [] + for item in page_items: + video_id = item["contentDetails"]["videoId"] + if video_id not in seen_ids: + seen_ids.add(video_id) + items.append(item) + + stats_map = {} + if items: + videos_response = api( + data_service.videos().list( + part=parts, + id=",".join(item["contentDetails"]["videoId"] for item in items), + ) ) - ) - - stats_map = {v["id"]: v for v in videos_response.get("items", [])} + stats_map = {v["id"]: v for v in videos_response.get("items", [])} for item in items: video_id = item["contentDetails"]["videoId"] @@ -532,6 +540,7 @@ def search_replace( service = get_data_service() changes = [] + seen_ids: set[str] = set() page_token = None while True: @@ -549,7 +558,18 @@ def search_replace( if not items: break - video_ids = [item["id"]["videoId"] for item in items] + video_ids = [] + for item in items: + video_id = item["id"]["videoId"] + if video_id not in seen_ids: + seen_ids.add(video_id) + video_ids.append(video_id) + + if not video_ids: + page_token = search_response.get("nextPageToken") + if not page_token: + break + continue videos_response = api( service.videos().list( diff --git a/tests/test_playlists.py b/tests/test_playlists.py index 2c9d23e..269bceb 100644 --- a/tests/test_playlists.py +++ b/tests/test_playlists.py @@ -8,6 +8,7 @@ from typer.testing import CliRunner from tests.conftest import MOCK_PLAYLIST, MOCK_PLAYLIST_ITEM_FULL +from ytstudio.commands.playlists import _fetch_all_items from ytstudio.main import app runner = CliRunner() @@ -703,3 +704,48 @@ def test_add_session_expired_exits_friendly(self, mock_auth): assert result.exit_code == 1 assert "Session expired" in result.stdout assert "ytstudio login" in result.stdout + + +class TestPagingDuplicates: + """Overlapping API pages must not repeat rows or writes (#58).""" + + def _item(self, item_id, video_id): + return { + "id": item_id, + "snippet": {"title": video_id, "position": 0, "resourceId": {"videoId": video_id}}, + "contentDetails": {"videoId": video_id}, + } + + def test_items_dedupes_on_item_id_not_video_id(self, mock_auth): + _set_playlist_items_list_side_effect( + mock_auth, + [ + {"items": [self._item("i1", "v1"), self._item("i2", "v2")], "nextPageToken": "t"}, + # i2 repeats; i3 is the same video as i1 but a separate entry, so it stays. + {"items": [self._item("i2", "v2"), self._item("i3", "v1")]}, + ], + ) + items = _fetch_all_items(mock_auth, "PL_test_123") + + assert [i.id for i in items] == ["i1", "i2", "i3"] + + def test_add_from_search_adds_each_video_once(self, mock_auth): + search_mock = MagicMock() + search_mock.execute.side_effect = [ + { + "items": [{"id": {"videoId": "a"}}, {"id": {"videoId": "b"}}], + "nextPageToken": "t", + }, + {"items": [{"id": {"videoId": "a"}}, {"id": {"videoId": "c"}}]}, + ] + mock_auth.search.return_value.list.return_value = search_mock + + result = runner.invoke( + app, + ["playlists", "add", "PL_test_123", "--from-search", "q", "-n", "10", "--execute"], + ) + + assert result.exit_code == 0 + calls = mock_auth.playlistItems.return_value.insert.call_args_list + ids = [c.kwargs["body"]["snippet"]["resourceId"]["videoId"] for c in calls] + assert ids == ["a", "b", "c"] diff --git a/tests/test_videos.py b/tests/test_videos.py index e1e32c1..f6c6822 100644 --- a/tests/test_videos.py +++ b/tests/test_videos.py @@ -375,3 +375,110 @@ def videos_side_effect(): ) assert result.exit_code == 0 assert "NewName Old Video" in result.stdout + + +def _uploads_item(video_id): + return { + "snippet": {"title": f"Title {video_id}", "publishedAt": "2025-01-01T00:00:00Z"}, + "contentDetails": {"videoId": video_id}, + } + + +def _install_paged_uploads(mock_service, entries): + """Fake uploads playlist whose entries repeat videos, like the live API in #58. + + The page token is the offset into `entries`, so pages behave like real + offset-based tokens for any maxResults. + """ + + def playlist_items_list(**kwargs): + start = int(kwargs.get("pageToken") or 0) + end = start + kwargs["maxResults"] + request = MagicMock() + request.execute.return_value = { + "items": [_uploads_item(v) for v in entries[start:end]], + "nextPageToken": str(end) if end < len(entries) else None, + "pageInfo": {"totalResults": len(entries)}, + } + return request + + def videos_list(**kwargs): + ids = kwargs["id"].split(",") + assert len(ids) == len(set(ids)) <= 50 + request = MagicMock() + request.execute.return_value = {"items": [make_search_video(v, f"Title {v}") for v in ids]} + return request + + mock_service.playlistItems.return_value.list.side_effect = playlist_items_list + mock_service.videos.return_value.list.side_effect = videos_list + + +# 115 uploads entries for 110 videos over three 50-item pages. v1..v5 come back +# again on later pages, as the live API did in #58. +UNIQUE = [f"v{i}" for i in range(1, 111)] +ENTRIES = [*UNIQUE[:48], "v1", "v2", *UNIQUE[48:96], "v3", "v4", "v5", *UNIQUE[96:]] + + +class TestListDuplicates: + """Regression for #58: the uploads playlist can repeat videos across pages.""" + + def test_json_has_no_duplicates_and_keeps_order(self, mock_auth): + _install_paged_uploads(mock_auth, ENTRIES) + + result = runner.invoke(app, ["videos", "list", "-n", "500", "-o", "json"]) + + assert result.exit_code == 0 + ids = [v["id"] for v in json.loads(result.stdout)["videos"]] + assert ids == UNIQUE + + def test_limit_counts_unique_videos(self, mock_auth): + _install_paged_uploads(mock_auth, ENTRIES) + + result = runner.invoke(app, ["videos", "list", "-n", "100", "-o", "json"]) + + assert result.exit_code == 0 + ids = [v["id"] for v in json.loads(result.stdout)["videos"]] + assert ids == UNIQUE[:100] + + def test_csv_has_one_row_per_video(self, mock_auth): + _install_paged_uploads(mock_auth, ENTRIES) + + result = runner.invoke(app, ["videos", "list", "-n", "500", "-o", "csv"]) + + assert result.exit_code == 0 + rows = result.stdout.strip().splitlines()[1:] + assert [r.split(",")[0] for r in rows] == UNIQUE + + def test_search_replace_updates_each_video_once(self, mock_auth): + pages = iter( + [ + { + "items": [{"id": {"videoId": "a"}}, {"id": {"videoId": "b"}}], + "nextPageToken": "t", + }, + {"items": [{"id": {"videoId": "b"}}, {"id": {"videoId": "a"}}]}, + ] + ) + search_list = MagicMock() + search_list.execute.side_effect = lambda: next(pages) + mock_auth.search.return_value.list.return_value = search_list + + def videos_list(**kwargs): + request = MagicMock() + request.execute.return_value = { + "items": [make_search_video(v, f"old {v}") for v in kwargs["id"].split(",")] + } + return request + + mock_auth.videos.return_value.list.side_effect = videos_list + + result = runner.invoke( + app, + ["videos", "search-replace", "-s", "old", "-r", "new", "-f", "title", "--execute"], + ) + + assert result.exit_code == 0 + updated = [ + c.kwargs["body"]["id"] for c in mock_auth.videos.return_value.update.call_args_list + ] + assert updated == ["a", "b"]