ytstudio-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ import json
2
+ from dataclasses import asdict, dataclass
3
+ from enum import StrEnum
4
+
5
+ import typer
6
+ from googleapiclient.errors import HttpError
7
+
8
+ from ytstudio.api import api, handle_api_error
9
+ from ytstudio.services import get_data_service
10
+ from ytstudio.ui import console, create_table, time_ago, truncate
11
+
12
+ app = typer.Typer(help="Comment commands")
13
+
14
+
15
+ class SortOrder(StrEnum):
16
+ relevance = "relevance"
17
+ time = "time"
18
+
19
+
20
+ class ModerationStatus(StrEnum):
21
+ published = "published"
22
+ held = "held"
23
+ spam = "spam"
24
+
25
+ def to_api_value(self) -> str:
26
+ """Convert to YouTube API moderationStatus value"""
27
+ return {"published": "published", "held": "heldForReview", "spam": "likelySpam"}[self.value]
28
+
29
+
30
+ @dataclass
31
+ class Comment:
32
+ id: str
33
+ author: str
34
+ text: str
35
+ likes: int
36
+ published_at: str
37
+ video_id: str = ""
38
+
39
+
40
+ def get_channel_id(service) -> str:
41
+ response = api(service.channels().list(part="id", mine=True))
42
+ if not response.get("items"):
43
+ console.print("[red]No channel found[/red]")
44
+ raise typer.Exit(1)
45
+ return response["items"][0]["id"]
46
+
47
+
48
+ def fetch_comments(
49
+ data_service,
50
+ video_id: str | None = None,
51
+ limit: int = 100,
52
+ order: SortOrder = SortOrder.relevance,
53
+ moderation_status: ModerationStatus = ModerationStatus.published,
54
+ ) -> list[Comment]:
55
+ try:
56
+ # Build query parameters based on filters
57
+ params = {
58
+ "part": "snippet",
59
+ "maxResults": min(limit, 100),
60
+ "order": order.value,
61
+ }
62
+
63
+ if video_id:
64
+ params["videoId"] = video_id
65
+ else:
66
+ channel_id = get_channel_id(data_service)
67
+ params["allThreadsRelatedToChannelId"] = channel_id
68
+ if moderation_status != ModerationStatus.published:
69
+ params["moderationStatus"] = moderation_status.to_api_value()
70
+
71
+ response = api(data_service.commentThreads().list(**params))
72
+ except HttpError as e:
73
+ handle_api_error(e)
74
+ except Exception as e:
75
+ console.print(f"[yellow]Could not fetch comments (may be disabled): {e}[/yellow]")
76
+ raise typer.Exit(1) from None
77
+
78
+ comments = []
79
+ for item in response.get("items", []):
80
+ snippet = item["snippet"]["topLevelComment"]["snippet"]
81
+ comments.append(
82
+ Comment(
83
+ id=item["id"],
84
+ author=snippet["authorDisplayName"],
85
+ text=snippet["textOriginal"],
86
+ likes=snippet["likeCount"],
87
+ published_at=snippet["publishedAt"],
88
+ video_id=snippet.get("videoId", ""),
89
+ )
90
+ )
91
+ return comments
92
+
93
+
94
+ @app.command("list")
95
+ def list_comments(
96
+ video_id: str = typer.Option(None, "--video", "-v", help="Filter by video ID"),
97
+ status: ModerationStatus = typer.Option(
98
+ ModerationStatus.published, "--status", help="Moderation status: published, held, spam"
99
+ ),
100
+ limit: int = typer.Option(20, "--limit", "-n", help="Number of comments"),
101
+ sort: SortOrder = typer.Option(SortOrder.time, "--sort", "-s", help="Sort order"),
102
+ output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
103
+ ):
104
+ """List comments across channel or for a specific video"""
105
+ if sort == SortOrder.relevance and not video_id:
106
+ console.print("[red]--sort relevance requires --video (YouTube API limitation)[/red]")
107
+ raise typer.Exit(1)
108
+
109
+ service = get_data_service()
110
+ comments = fetch_comments(service, video_id, limit, sort, status)
111
+
112
+ if output == "json":
113
+ print(json.dumps([asdict(c) for c in comments], indent=2))
114
+ return
115
+
116
+ status_label = {"published": "Published", "held": "Held for Review", "spam": "Likely Spam"}
117
+ label = status_label.get(status.value, status.value)
118
+ scope = f"video {video_id}" if video_id else "channel"
119
+ console.print(f"\n[bold]{label} Comments ({len(comments)})[/bold] — {scope}\n")
120
+
121
+ table = create_table()
122
+ table.add_column("ID", style="yellow")
123
+ if not video_id:
124
+ table.add_column("Video", style="cyan")
125
+ table.add_column("Author")
126
+ table.add_column("Posted")
127
+ table.add_column("Comment")
128
+
129
+ for c in comments:
130
+ date = f"{c.published_at[:16].replace('T', ' ')} ({time_ago(c.published_at)})"
131
+ row = [c.id]
132
+ if not video_id:
133
+ row.append(c.video_id)
134
+ row += [c.author, date, truncate(c.text, 80)]
135
+ table.add_row(*row)
136
+
137
+ console.print(table)
138
+
139
+
140
+ def _set_moderation_status(comment_ids: list[str], status: str, ban_author: bool = False) -> int:
141
+ service = get_data_service()
142
+ success = 0
143
+ batch_size = 50
144
+ for i in range(0, len(comment_ids), batch_size):
145
+ batch = comment_ids[i : i + batch_size]
146
+ try:
147
+ params = {
148
+ "id": ",".join(batch),
149
+ "moderationStatus": status,
150
+ }
151
+ if ban_author and status == "rejected":
152
+ params["banAuthor"] = True
153
+ api(service.comments().setModerationStatus(**params))
154
+ success += len(batch)
155
+ except HttpError as e:
156
+ handle_api_error(e)
157
+ return success
158
+
159
+
160
+ @app.command()
161
+ def publish(
162
+ comment_ids: list[str] = typer.Argument(help="Comment IDs to publish"),
163
+ ):
164
+ """Publish held comments (approve for public display)"""
165
+ count = _set_moderation_status(comment_ids, "published")
166
+ console.print(f"{count} comment(s) published")
167
+
168
+
169
+ @app.command()
170
+ def reject(
171
+ comment_ids: list[str] = typer.Argument(help="Comment IDs to reject"),
172
+ ban: bool = typer.Option(False, "--ban", help="Also ban the comment author"),
173
+ ):
174
+ """Reject comments (hide from public display)"""
175
+ count = _set_moderation_status(comment_ids, "rejected", ban_author=ban)
176
+ console.print(f"{count} comment(s) rejected")
@@ -0,0 +1,475 @@
1
+ import json
2
+ import re
3
+ from dataclasses import asdict, dataclass, field
4
+
5
+ import typer
6
+ from googleapiclient.errors import HttpError
7
+
8
+ from ytstudio.api import api, handle_api_error
9
+ from ytstudio.services import get_data_service
10
+ from ytstudio.ui import (
11
+ console,
12
+ create_kv_table,
13
+ create_table,
14
+ dim,
15
+ format_number,
16
+ success_message,
17
+ truncate,
18
+ )
19
+
20
+ app = typer.Typer(help="Video management commands")
21
+
22
+
23
+ @dataclass
24
+ class Video:
25
+ id: str
26
+ title: str
27
+ description: str
28
+ published_at: str
29
+ views: int
30
+ likes: int
31
+ comments: int
32
+ duration: str
33
+ privacy: str
34
+ tags: list[str] = field(default_factory=list)
35
+ category_id: str = ""
36
+ licensed: bool = False
37
+ default_language: str | None = None
38
+ default_audio_language: str | None = None
39
+ localizations: dict = field(default_factory=dict)
40
+
41
+
42
+ def format_duration(iso_duration: str) -> str:
43
+ """Format ISO 8601 duration (PT1M19S -> 1:19)"""
44
+ if not iso_duration:
45
+ return ""
46
+
47
+ match = re.match(r"PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?", iso_duration)
48
+ if not match:
49
+ return ""
50
+
51
+ hours = int(match.group(1) or 0)
52
+ minutes = int(match.group(2) or 0)
53
+ seconds = int(match.group(3) or 0)
54
+
55
+ if hours > 0:
56
+ return f"{hours}:{minutes:02d}:{seconds:02d}"
57
+ return f"{minutes}:{seconds:02d}"
58
+
59
+
60
+ def get_channel_uploads_playlist(service) -> str:
61
+ response = api(service.channels().list(part="contentDetails", mine=True))
62
+ if not response.get("items"):
63
+ console.print("[red]No channel found[/red]")
64
+ raise typer.Exit(1)
65
+ return response["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]
66
+
67
+
68
+ def fetch_video(data_service, video_id: str) -> Video | None:
69
+ response = api(
70
+ data_service.videos().list(
71
+ part="snippet,statistics,contentDetails,status,localizations",
72
+ id=video_id,
73
+ )
74
+ )
75
+
76
+ if not response.get("items"):
77
+ return None
78
+
79
+ item = response["items"][0]
80
+ snippet = item["snippet"]
81
+ stats = item.get("statistics", {})
82
+ content = item.get("contentDetails", {})
83
+
84
+ return Video(
85
+ id=item["id"],
86
+ title=snippet["title"],
87
+ description=snippet.get("description", ""),
88
+ published_at=snippet["publishedAt"],
89
+ views=int(stats.get("viewCount", 0)),
90
+ likes=int(stats.get("likeCount", 0)),
91
+ comments=int(stats.get("commentCount", 0)),
92
+ duration=content.get("duration", ""),
93
+ privacy=item.get("status", {}).get("privacyStatus", "unknown"),
94
+ tags=snippet.get("tags", []),
95
+ default_language=snippet.get("defaultLanguage"),
96
+ default_audio_language=snippet.get("defaultAudioLanguage"),
97
+ localizations=item.get("localizations", {}),
98
+ )
99
+
100
+
101
+ def fetch_videos(
102
+ data_service, limit: int = 50, page_token: str | None = None
103
+ ) -> dict[str, list[Video] | str | int | None]:
104
+ uploads_playlist_id = get_channel_uploads_playlist(data_service)
105
+
106
+ all_videos = []
107
+ current_page_token = page_token
108
+ total_results = None
109
+ next_page_token = None
110
+
111
+ parts = "statistics,status,snippet,contentDetails,localizations"
112
+
113
+ while len(all_videos) < limit:
114
+ batch_size = min(limit - len(all_videos), 50)
115
+
116
+ playlist_response = api(
117
+ data_service.playlistItems().list(
118
+ part="snippet,contentDetails",
119
+ playlistId=uploads_playlist_id,
120
+ maxResults=batch_size,
121
+ pageToken=current_page_token,
122
+ )
123
+ )
124
+
125
+ if total_results is None:
126
+ total_results = playlist_response.get("pageInfo", {}).get("totalResults", 0)
127
+
128
+ items = playlist_response.get("items", [])
129
+ if not items:
130
+ break
131
+
132
+ video_ids = [item["contentDetails"]["videoId"] for item in items]
133
+
134
+ videos_response = api(
135
+ data_service.videos().list(
136
+ part=parts,
137
+ id=",".join(video_ids),
138
+ )
139
+ )
140
+
141
+ stats_map = {v["id"]: v for v in videos_response.get("items", [])}
142
+
143
+ for item in items:
144
+ video_id = item["contentDetails"]["videoId"]
145
+ data = stats_map.get(video_id, {})
146
+ stats = data.get("statistics", {})
147
+ snippet = data.get("snippet", {})
148
+ content_details = data.get("contentDetails", {})
149
+
150
+ video = Video(
151
+ id=video_id,
152
+ title=item["snippet"]["title"],
153
+ description=item["snippet"].get("description", ""),
154
+ published_at=item["snippet"]["publishedAt"],
155
+ views=int(stats.get("viewCount", 0)),
156
+ likes=int(stats.get("likeCount", 0)),
157
+ comments=int(stats.get("commentCount", 0)),
158
+ privacy=data.get("status", {}).get("privacyStatus", "unknown"),
159
+ tags=snippet.get("tags", []),
160
+ category_id=snippet.get("categoryId", ""),
161
+ duration=content_details.get("duration", ""),
162
+ licensed=content_details.get("licensedContent", False),
163
+ localizations=data.get("localizations", {}),
164
+ default_language=snippet.get("defaultLanguage"),
165
+ default_audio_language=snippet.get("defaultAudioLanguage"),
166
+ )
167
+
168
+ all_videos.append(video)
169
+
170
+ next_page_token = playlist_response.get("nextPageToken")
171
+ if not next_page_token:
172
+ break
173
+ current_page_token = next_page_token
174
+
175
+ return {
176
+ "videos": all_videos,
177
+ "next_page_token": next_page_token,
178
+ "total_results": total_results,
179
+ }
180
+
181
+
182
+ @app.command("list")
183
+ def list_videos(
184
+ limit: int = typer.Option(20, "--limit", "-n", help="Number of videos to list"),
185
+ page_token: str = typer.Option(None, "--page-token", "-p", help="Page token for pagination"),
186
+ sort: str = typer.Option("date", "--sort", "-s", help="Sort by: date, views, likes"),
187
+ output: str = typer.Option("table", "--output", "-o", help="Output format: table, json, csv"),
188
+ audio_lang: str = typer.Option(
189
+ None, "--audio-lang", help="Filter by audio language (e.g., en, nl)"
190
+ ),
191
+ meta_lang: str = typer.Option(
192
+ None, "--meta-lang", help="Filter by metadata language (e.g., en, nl)"
193
+ ),
194
+ has_localization: str = typer.Option(
195
+ None, "--has-localization", help="Filter by available translation (e.g., en, nl)"
196
+ ),
197
+ ):
198
+ """List your YouTube videos"""
199
+ service = get_data_service()
200
+ result = fetch_videos(service, limit, page_token)
201
+ videos: list[Video] = result["videos"]
202
+
203
+ if audio_lang:
204
+ videos = [v for v in videos if v.default_audio_language == audio_lang]
205
+ if meta_lang:
206
+ videos = [v for v in videos if v.default_language == meta_lang]
207
+ if has_localization:
208
+ videos = [v for v in videos if has_localization in v.localizations]
209
+
210
+ if sort == "views":
211
+ videos.sort(key=lambda x: x.views, reverse=True)
212
+ elif sort == "likes":
213
+ videos.sort(key=lambda x: x.likes, reverse=True)
214
+
215
+ if output == "json":
216
+ print(
217
+ json.dumps(
218
+ {
219
+ "videos": [asdict(v) for v in videos],
220
+ "next_page_token": result["next_page_token"],
221
+ "total_results": result["total_results"],
222
+ },
223
+ indent=2,
224
+ )
225
+ )
226
+ elif output == "csv":
227
+ print("id,title,views,likes,comments,privacy,published_at")
228
+ for v in videos:
229
+ title_escaped = v.title.replace('"', '""')
230
+ print(
231
+ f'{v.id},"{title_escaped}",{v.views},{v.likes},{v.comments},{v.privacy},{v.published_at}'
232
+ )
233
+ else:
234
+ table = create_table()
235
+ table.add_column("ID", style="yellow")
236
+ table.add_column("Title", style="cyan")
237
+ table.add_column("URL")
238
+ table.add_column("Views", justify="right")
239
+ table.add_column("Likes", justify="right")
240
+ table.add_column("Comments", justify="right")
241
+ table.add_column("Published")
242
+
243
+ for v in videos:
244
+ video_url = f"https://youtu.be/{v.id}"
245
+ title = truncate(v.title)
246
+ table.add_row(
247
+ v.id,
248
+ title,
249
+ video_url,
250
+ format_number(v.views),
251
+ format_number(v.likes),
252
+ format_number(v.comments),
253
+ v.published_at[:10],
254
+ )
255
+
256
+ console.print(table)
257
+
258
+ if result["next_page_token"]:
259
+ console.print(f"\nNext page: --page-token {result['next_page_token']}")
260
+
261
+
262
+ @app.command()
263
+ def show(
264
+ video_id: str = typer.Argument(..., help="Video ID"),
265
+ output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
266
+ ):
267
+ """Show details for a specific video"""
268
+ service = get_data_service()
269
+ video = fetch_video(service, video_id)
270
+
271
+ if not video:
272
+ console.print(f"[red]Video not found: {video_id}[/red]")
273
+ raise typer.Exit(1)
274
+
275
+ if output == "json":
276
+ print(json.dumps(asdict(video), indent=2))
277
+ return
278
+
279
+ console.print(f"\n[bold]{video.title}[/bold]")
280
+ console.print(f"[cyan]https://youtu.be/{video_id}[/cyan]\n")
281
+
282
+ table = create_kv_table()
283
+ table.add_column("field", style="dim")
284
+ table.add_column("value")
285
+
286
+ table.add_row("views", format_number(video.views))
287
+ table.add_row("likes", format_number(video.likes))
288
+ table.add_row("comments", format_number(video.comments))
289
+ table.add_row("duration", video.duration or "N/A")
290
+ table.add_row("published", video.published_at[:10])
291
+ table.add_row("privacy", video.privacy)
292
+ table.add_row("language", video.default_language or "-")
293
+ table.add_row("audio language", video.default_audio_language or "-")
294
+
295
+ if video.localizations:
296
+ table.add_row("localizations", ", ".join(sorted(video.localizations.keys())))
297
+
298
+ console.print(table)
299
+
300
+ if video.tags:
301
+ console.print(f"\n[dim]tags:[/dim] {', '.join(video.tags[:15])}")
302
+
303
+ console.print(f"\n[bold]description:[/bold]\n{video.description}")
304
+
305
+
306
+ @app.command()
307
+ def update(
308
+ video_id: str = typer.Argument(..., help="Video ID"),
309
+ title: str = typer.Option(None, "--title", "-t", help="New title"),
310
+ description: str = typer.Option(None, "--description", "-d", help="New description"),
311
+ tags: str = typer.Option(None, "--tags", help="Comma-separated tags"),
312
+ execute: bool = typer.Option(False, "--execute", help="Apply changes (default is dry-run)"),
313
+ ):
314
+ """Update a video's metadata"""
315
+ if not any([title, description, tags]):
316
+ console.print(
317
+ "[yellow]Nothing to update. Provide --title, --description, or --tags[/yellow]"
318
+ )
319
+ raise typer.Exit(1)
320
+
321
+ service = get_data_service()
322
+
323
+ response = api(service.videos().list(part="snippet", id=video_id))
324
+ if not response.get("items"):
325
+ console.print(f"[red]Video not found: {video_id}[/red]")
326
+ raise typer.Exit(1)
327
+
328
+ current = response["items"][0]["snippet"]
329
+
330
+ new_title = title if title else current["title"]
331
+ new_desc = description if description else current.get("description", "")
332
+ new_tags = [t.strip() for t in tags.split(",")] if tags else current.get("tags", [])
333
+
334
+ if not execute:
335
+ console.print("[bold]Preview changes:[/bold]\n")
336
+ if title:
337
+ console.print(f"title: {current['title']} → [green]{new_title}[/green]")
338
+ if description:
339
+ console.print("description: [green](updated)[/green]")
340
+ if tags:
341
+ console.print(f"tags: [green]{', '.join(new_tags[:5])}[/green]")
342
+ console.print("\nRun with --execute to apply")
343
+ return
344
+
345
+ body = {
346
+ "id": video_id,
347
+ "snippet": {
348
+ "title": new_title,
349
+ "description": new_desc,
350
+ "tags": new_tags,
351
+ "categoryId": current["categoryId"],
352
+ },
353
+ }
354
+
355
+ api(service.videos().update(part="snippet", body=body))
356
+ success_message(f"Updated: {new_title}")
357
+
358
+
359
+ @app.command("search-replace")
360
+ def search_replace(
361
+ search: str = typer.Option(..., "--search", "-s", help="Text to search for"),
362
+ replace: str = typer.Option(..., "--replace", "-r", help="Text to replace with"),
363
+ field: str = typer.Option(..., "--field", "-f", help="Field to update: title, description"),
364
+ regex: bool = typer.Option(False, "--regex", help="Treat search as regex"),
365
+ limit: int = typer.Option(10, "--limit", "-n", help="Max matches to find"),
366
+ execute: bool = typer.Option(False, "--execute", help="Apply changes (default is dry-run)"),
367
+ ):
368
+ """Bulk update videos using search and replace"""
369
+ service = get_data_service()
370
+ uploads_playlist_id = get_channel_uploads_playlist(service)
371
+
372
+ changes = []
373
+ page_token = None
374
+
375
+ while len(changes) < limit:
376
+ # Fetch batch of videos
377
+ playlist_response = api(
378
+ service.playlistItems().list(
379
+ part="snippet,contentDetails",
380
+ playlistId=uploads_playlist_id,
381
+ maxResults=50,
382
+ pageToken=page_token,
383
+ )
384
+ )
385
+
386
+ items = playlist_response.get("items", [])
387
+ if not items:
388
+ break
389
+
390
+ video_ids = [item["contentDetails"]["videoId"] for item in items]
391
+
392
+ videos_response = api(
393
+ service.videos().list(
394
+ part="snippet",
395
+ id=",".join(video_ids),
396
+ )
397
+ )
398
+
399
+ for video in videos_response.get("items", []):
400
+ if len(changes) >= limit:
401
+ break
402
+
403
+ old_value = video["snippet"].get(field, "")
404
+ if regex:
405
+ new_value = re.sub(search, replace, old_value)
406
+ else:
407
+ new_value = old_value.replace(search, replace)
408
+
409
+ if new_value != old_value:
410
+ changes.append(
411
+ {
412
+ "id": video["id"],
413
+ "field": field,
414
+ "old": old_value,
415
+ "new": new_value,
416
+ }
417
+ )
418
+
419
+ page_token = playlist_response.get("nextPageToken")
420
+ if not page_token:
421
+ break
422
+
423
+ if not changes:
424
+ console.print("[yellow]No matches found[/yellow]")
425
+ return
426
+
427
+ table = create_table()
428
+ table.add_column("Video ID", style="yellow")
429
+ table.add_column("Current")
430
+ table.add_column("→", justify="center", style="dim")
431
+ table.add_column("New")
432
+
433
+ for c in changes:
434
+ table.add_row(c["id"], c["old"], "→", f"[green]{c['new']}[/green]")
435
+
436
+ console.print(dim(f"{'Pending' if not execute else 'Applying'} {len(changes)} changes\n"))
437
+
438
+ console.print(table)
439
+
440
+ if not execute:
441
+ console.print("\n[dim]Run with --execute to apply changes[/dim]")
442
+ return
443
+
444
+ console.print("\n[bold]Applying changes...[/bold]\n")
445
+ success = 0
446
+ failed = 0
447
+
448
+ for c in changes:
449
+ try:
450
+ response = api(service.videos().list(part="snippet", id=c["id"]))
451
+ if not response.get("items"):
452
+ continue
453
+
454
+ snippet = response["items"][0]["snippet"]
455
+ snippet[field] = c["new"]
456
+
457
+ api(service.videos().update(part="snippet", body={"id": c["id"], "snippet": snippet}))
458
+
459
+ console.print(f"[green]✓[/green] {c['id']}: {c['new']}")
460
+ success += 1
461
+ except HttpError as e:
462
+ # Quota exceeded - stop immediately
463
+ error_details = e.error_details[0] if e.error_details else {}
464
+ if error_details.get("reason") == "quotaExceeded":
465
+ console.print(
466
+ f"\n[bold]Partial progress:[/bold] {success} updated, {failed} failed"
467
+ )
468
+ handle_api_error(e)
469
+ console.print(f"[red]✗[/red] {c['id']}: {e}")
470
+ failed += 1
471
+ except Exception as e:
472
+ console.print(f"[red]✗[/red] {c['id']}: {e}")
473
+ failed += 1
474
+
475
+ console.print(f"\n[bold]Done:[/bold] {success} updated, {failed} failed")