diff --git a/docs/api-quota.md b/docs/api-quota.md index b6b0de3..77f8168 100644 --- a/docs/api-quota.md +++ b/docs/api-quota.md @@ -49,6 +49,17 @@ Captions are the other pricey read: `videos transcript` first lists the tracks Author metadata per video rather than pulling transcripts across a whole channel. +Comment moderation is the other cost to plan for. `comments.setModerationStatus` +costs 50 units per call, and `commentThreads.list` costs 1 unit per page of up to +100 comments. One call can change up to 50 comment ids, and `comments reject` and +`comments publish` send them in batches of 50. A run of 200 ids is 4 calls (200 +units). One call per id is 200 calls (10 000 units), which is the full daily +budget. Always pass all ids to one command. + +`comments list --unanswered` reads the `replies` part with the thread. That part +holds only a few replies. For a thread with more replies, the CLI makes one +more `comments.list` call (1 unit per page) to check for a reply from the owner. + ## Increasing the quota In the Google Cloud Console, go to **IAM & Admin** :material-arrow-right: diff --git a/docs/comments.md b/docs/comments.md index c4444ca..a9019b8 100644 --- a/docs/comments.md +++ b/docs/comments.md @@ -11,49 +11,129 @@ downstream tooling. ytstudio comments list --video ytstudio comments list --video -o json | jq -# Held queue, ordered chronologically +# Held queue for one video, newest first ytstudio comments list --video --status held --sort time + +# Whole held queue of the channel +ytstudio comments list --status held -n 500 -o json ``` `--status` accepts `published`, `held`, or `spam` (mapped internally to -YouTube's `published`, `heldForReview`, and `likelySpam` values). `--sort` -accepts `time` or `relevance`; the YouTube API only honours `relevance` for -a single video, so `--sort relevance` requires `--video `. Omit -`--video` to list across the channel (time-sorted only). +YouTube's `published`, `heldForReview`, and `likelySpam` values). It works +with and without `--video`. `--sort` accepts `time` or `relevance`. The +YouTube API uses `relevance` only for a single video, so +`--sort relevance` requires `--video `. Omit `--video` to list across +the channel (time-sorted only). + +`--limit/-n` is the number of comments to return. The CLI reads as many +pages of 100 as it needs (1 quota unit per page). -## Approve held comments +### Unanswered comments ```bash -ytstudio comments publish [ ...] +ytstudio comments list --unanswered -n 50 -o json ``` -`publish` takes one or more comment IDs and transitions each to -`published`. +`--unanswered` returns only threads that have no reply from the channel +owner. It skips threads that the owner started. It works only with published +comments. + +### Signals in JSON output + +`-o json` adds fields that the CLI calculates without a model. They are +evidence for the reader, not a decision: + +| Field | Meaning | +|---|---| +| `author_channel_id` | Channel id of the author. Use it to find repeat authors. | +| `reply_count` | Number of replies in the thread. | +| `has_link` | The text contains a link (`https://`, `www.`, or `host/path` such as `t.me/x`). | +| `link_hosts` | The hosts of those links. | +| `off_youtube_link` | At least one link goes to a host that is not YouTube. | +| `duplicate_of` | Id of an earlier comment with the same text on another video or from the same author. The CLI ignores case, punctuation and spacing. It does not compare texts shorter than 15 characters. | +| `impersonation_suspect` | The display name is close to the channel title or handle, and the author is not the channel owner. | -## Reject +The CLI looks for duplicates only in the comments of one command run. Raise +`-n` to compare more of the backlog. + +## Approve and reject ```bash -ytstudio comments reject [ ...] -ytstudio comments reject --ban # also ban the author +ytstudio comments publish [ ...] # preview +ytstudio comments publish [ ...] --execute # apply + +ytstudio comments reject [ ...] # preview +ytstudio comments reject [ ...] --execute # apply +ytstudio comments reject --ban --execute # also ban the author ``` -`reject` hides the comment from public view. Pass `--ban` to also ban the -author from the channel. +Both commands do a **dry run by default**. The preview shows the author, the +text, the video and the signals of each comment. It changes nothing. Add +`--execute` to apply. `--ban` also needs `--execute`. + +The preview reads the comments from the API, not from your input. It searches +for each id in this order: + +1. By thread id. +2. By comment id. +3. In the held and spam queues. +4. In the local moderation log. + +If the CLI cannot find an id, the command lists it, changes nothing and exits +with code 1. + +### Moderation log + +`--execute` appends to `profiles//moderation-log.jsonl` **before** each +API call. Each line has the comment id, author, author channel id, text, video +id, a timestamp and the action. After the call the CLI appends an `applied` or +`failed` line for each id. + +This log is the only record of a rejected comment. The API cannot list +rejected comments, and a reject also hides all replies of the comment. To undo +a reject, run `comments publish ` with the ids from the log. The preview +then shows the text from the log. The YouTube documentation does not say if +YouTube accepts a publish on a rejected comment. + +### Batches and partial failure + +The CLI sends up to 50 ids per API call. If a call fails, the CLI stops and +exits with code 1. It prints the ids in three groups: + +- Applied: the API accepted the call. +- Status unknown: the call failed with a 5xx error, a timeout or a network + error. The change can be applied or not. Check these comments in YouTube + Studio before you run the command again. +- Not applied: the CLI did not send these ids, or the API refused the call + with a 4xx error. Run the command again with these ids. + +The log marks each id as `applied`, `unknown` or `failed`. ## Reply ```bash -ytstudio comments reply --text "Thanks for watching!" +ytstudio comments reply --text "Thanks for watching!" # preview +ytstudio comments reply --text "Thanks for watching!" --execute # post ``` -`reply` posts a public reply to a comment and prints the new reply id. -Replies are flat on YouTube: `` must be a **top-level** comment -id (the `id` shown by `comments list`), not the id of another reply. Passing -a reply id (or an otherwise invalid id) returns a clear error. Like -`publish` and `reject`, `reply` executes immediately. +`reply` does a dry run by default. The preview shows the comment and the +reply text. With `--execute`, it posts the reply and prints the new reply id. Replies are flat +on YouTube: `` must be a **top-level** comment id (the `id` shown +by `comments list`), not the id of another reply. Passing a reply id (or an +otherwise invalid id) returns a clear error. + +## Triage with an agent + +The agent makes the decisions. The CLI supplies the context, a preview and a +log for each write. Store the channel's rules once with `ytstudio profile policy edit` (see +[Profiles](profiles.md#moderation-policy)). The loop and the label set are in +the bundled agent skill (`skills/ytstudio/SKILL.md`). !!! note "Quota" `comments.setModerationStatus` and `comments.insert` (reply) each cost - about 50 quota units per call. For larger moderation runs, see - [API quota](api-quota.md). + about 50 quota units per call. A preview costs about 1 unit per 50 ids. + If an id lookup does not find a comment, the preview also reads the + held and spam queues. That fallback costs 1 unit per page of 100 + comments. + For larger moderation runs, see [API quota](api-quota.md). diff --git a/docs/profiles.md b/docs/profiles.md index 8e983c9..4aab2a3 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -48,6 +48,23 @@ The file lives at `profiles//brand.md` and is written owner-only (`0600`), the same as credentials, because a brand voice can encode private channel strategy. +## Moderation policy + +Each profile can also carry a **moderation policy**: a markdown file that says +how an agent must triage comments on the channel. Write down what to reject, +what to leave held, what never to touch, and which topics always go to you. +The agent reads it before [comment triage](comments.md#triage-with-an-agent). + +```bash +ytstudio profile policy show # print the active profile's policy +ytstudio profile policy edit # create/open moderation.md in $EDITOR +ytstudio profile policy set --file policy.md # import a policy file +``` + +The commands work the same as the `brand` commands. The file lives at +`profiles//moderation.md` (`0600`). `moderation.md` controls what happens +to a comment. `brand.md` controls how a reply sounds. Keep them separate. + ## Storage ``` @@ -61,7 +78,9 @@ channel strategy. └── work/ ├── credentials.json ├── meta.json - └── brand.md # optional; per-channel brand voice (0600) + ├── brand.md # optional, per-channel brand voice (0600) + ├── moderation.md # optional, comment moderation policy (0600) + └── moderation-log.jsonl # written by comments reject/publish --execute (0600) ``` Profile directories are `0700`; credential files are `0600`. State writes go diff --git a/skills/ytstudio/SKILL.md b/skills/ytstudio/SKILL.md index 1a028b1..562b54a 100644 --- a/skills/ytstudio/SKILL.md +++ b/skills/ytstudio/SKILL.md @@ -32,15 +32,18 @@ mistakes: also support `-o csv`. The auth/setup commands (`init`, `login`, `status`) have no JSON mode. 2. **Most mutations are dry-run by default.** Commands with `--execute` - (`videos update/search-replace/upload`, `livestreams schedule/update`, and - playlist writes) preview what they *would* do and change nothing until you - re-run the exact command with `--execute`. Always preview first, show the + (`videos update/search-replace/upload`, `livestreams schedule/update`, + `comments publish/reject/reply`, and playlist writes) preview what they + *would* do. They change nothing until you re-run the exact command with + `--execute`. Always preview first, show the user the preview when consequential, then re-run with `--execute`. -Some writes execute immediately because they have no `--execute`: comment -moderation/replies (`comments publish`, `comments reject`, `comments reply`) and -livestream transitions (`livestreams start`, `livestreams stop`). Treat these as -high-risk: confirm intent before running them. +Livestream transitions (`livestreams start`, `livestreams stop`) have no +`--execute`, so they execute immediately. Treat them as high-risk. Confirm the +intent of the user before you run them. + +Up to 0.4.x, `comments publish`, `comments reject` and `comments reply` +executed immediately. Now they show a preview by default and need `--execute`. Treat write operations as costly and irreversible-ish: they consume API quota (see [Quota](#quota-awareness)) and act on a real, public channel. @@ -302,19 +305,106 @@ ytstudio comments list -o json # recent comments across t ytstudio comments list --status held -o json # the moderation queue ytstudio comments list --status spam -o json # likely spam comments ytstudio comments list --sort time -o json # channel-wide newest first +ytstudio comments list -v --status held -o json # held queue of one video ytstudio comments list -v --sort relevance -n 50 -o json -ytstudio comments publish [ ...] # approve held; executes immediately -ytstudio comments reject --ban # reject (+ optional ban); executes immediately -ytstudio comments reply -t "Thanks!" # executes immediately +ytstudio comments list --unanswered -n 50 -o json # no reply from the owner yet +ytstudio comments publish [ ...] # preview +ytstudio comments publish [ ...] --execute # approve held +ytstudio comments reject [ ...] --execute # reject +ytstudio comments reply -t "Thanks!" # preview +ytstudio comments reply -t "Thanks!" --execute # post ``` -`comments list` without `-v/--video` is channel-wide. Use `--status spam` for -spam review. Channel-wide listing supports `--sort time`; `--sort relevance` -requires `-v/--video` because of a YouTube API limitation. `publish`/`reject` -take one or more comment ids and execute immediately (no `--execute` dry-run). -`reply` also posts immediately. Confirm the exact comment ids/text first. -`--ban` on `reject` also bans the author - only use it when the user explicitly -asks to ban. +`comments list` without `-v/--video` is channel-wide. `--status` works with and +without `-v`. Channel-wide listing supports `--sort time`. `--sort relevance` +requires `-v/--video` because of a YouTube API limitation. `-n` follows pages, so +`-n 500` returns up to 500 comments. + +`-o json` adds these signals for each comment. They are evidence, not decisions. + +- `author_channel_id` +- `reply_count` +- `has_link` +- `link_hosts` +- `off_youtube_link`: a link to a host that is not YouTube. +- `duplicate_of`: the id of an earlier copy of the same text, on another video + or from the same author. +- `impersonation_suspect`: the name is close to the channel title or handle, + and the comment comes from another channel. + +`publish`/`reject` take one or more ids. The preview shows the author, text, +video and signals from the API. If the CLI cannot find an id, the command stops +and changes nothing. `--execute` writes each comment to +`profiles//moderation-log.jsonl` before the API call. If a batch fails, the +command stops and exits with code 1. It prints three groups: applied, status +unknown (5xx, timeout or network error), and not applied. Tell the user to check +the "status unknown" ids in YouTube Studio. Do not send them again without a check. +`--ban` on `reject` also bans the author. Never pass `--ban` unless the user +explicitly asks to ban. + +#### Comment triage - policy-grounded, preview first + +You make the decisions. The CLI gives you the policy, the comments, the +signals, and a preview and a log for each write. Do these steps: + +1. Run `ytstudio profile policy show` to get the moderation rules of the + channel. If there is no policy, tell the user. Ask the user to write one + with `ytstudio profile policy edit`. Do not moderate without a policy. +2. Run `ytstudio comments list --status held -n 500 -o json`. For one video, + add `-v `. For the likely-spam queue, use `--status spam`. +3. Give each comment one label from the table below. Use the policy to select + the label. +4. Run `ytstudio comments reject ` without `--execute`. **Show the preview + to the user.** Group the comments by label and give the reason for each + comment. +5. After the user confirms, run the same command with `--execute`. Use the same + steps for `comments publish `. +6. Tell the user which comments you left held, and why. Include questions, + leads, and all comments that you were not sure about. + +| Label | Meaning | Default action | +|---|---|---| +| `junk` | link farms, fake giveaways, phishing, crypto/WhatsApp/Telegram bait | propose reject | +| `impersonation` | author name copies the channel, "message me on Telegram" | propose reject, tell the user | +| `toxic` | harassment, slurs, threats | propose reject | +| `question` | a question to the creator | leave held, show to the user, candidate for a reply | +| `lead` | buying intent, price or availability questions, collaboration requests | leave held, show to the user, never act on it | +| `criticism` | negative but genuine | publish, never reject | +| `praise` / `neutral` | positive or plain | publish | + +Use the label `junk`, not `spam`. `--status spam` is the classification of +YouTube. The label is your decision. If you are not sure about the label of a +comment, leave the comment held. Put it in the "needs you" list. + +Hard rules: + +- Never ban. +- When in doubt, leave the comment held. +- Never reject genuine criticism or negative feedback. +- Never reject a comment only because it is negative about the channel. +- For each reject that you propose, give the line in the policy or the signal + that is the reason. + +**Pass all ids to one command.** `comments.setModerationStatus` costs 50 units +per call. The CLI sends 50 ids per call. A loop with one command per id costs +50 units per comment. After 200 comments, that loop uses the full 10,000-unit +daily budget. + +Undo: the API cannot list rejected comments. To restore a rejected comment: + +1. Read its id from `moderation-log.jsonl`. +2. Run `comments publish ` (preview, then `--execute`). + +The YouTube documentation does not say if YouTube accepts this. Report the +result to the user. + +Reply triage is a separate pass on published comments: + +1. Run `ytstudio comments list --unanswered -o json`. +2. Write draft replies in the brand voice (`profile brand show`). +3. Preview each reply with `comments reply -t "..."`. +4. Show the previews to the user. +5. Post each reply with `--execute`. ### livestreams - broadcast lifecycle @@ -360,7 +450,8 @@ resetting at midnight Pacific. Rough costs: | Read (list/show videos, comments, playlists; analytics) | ~1 unit | | Caption list (`videos captions`) | ~50 units | | Caption download (`videos transcript`) | ~200 units | -| Write (update video, moderate comment, playlist insert/reorder, schedule broadcast) | ~50 units | +| Write (update video, playlist insert/reorder, schedule broadcast, reply) | ~50 units | +| Comment moderation (`comments publish/reject`) | ~50 units per call of up to 50 ids | | Search (`playlists add --from-search`) | ~100 units/call | | Upload (`videos upload`) | ~1600 units | diff --git a/skills/ytstudio/references/reference.md b/skills/ytstudio/references/reference.md index 591ece1..fe80f67 100644 --- a/skills/ytstudio/references/reference.md +++ b/skills/ytstudio/references/reference.md @@ -428,7 +428,7 @@ $ ytstudio comments [OPTIONS] COMMAND [ARGS]... * `list`: List comments across channel or for a... * `publish`: Publish held comments (approve for public... -* `reject`: Reject comments (hide from public display) +* `reject`: Reject comments (hide from public view). * `reply`: Reply to a top-level comment. ### `ytstudio comments list` @@ -447,12 +447,13 @@ $ ytstudio comments list [OPTIONS] * `--status `: Moderation status: published, held, spam [default: published] * `-n, --limit `: Number of comments [default: 20] * `-s, --sort `: Sort order [default: time] +* `--unanswered`: Show only threads that have no reply from the channel owner * `-o, --output `: Output format: table, json [default: table] * `--help`: Show this message and exit. ### `ytstudio comments publish` -Publish held comments (approve for public display) +Publish held comments (approve for public view). The default is a dry run. **Usage**: @@ -466,11 +467,12 @@ $ ytstudio comments publish [OPTIONS] {comment_ids}... **Options**: +* `--execute`: Apply changes (default is dry-run) * `--help`: Show this message and exit. ### `ytstudio comments reject` -Reject comments (hide from public display) +Reject comments (hide from public view). The default is a dry run. **Usage**: @@ -485,11 +487,12 @@ $ ytstudio comments reject [OPTIONS] {comment_ids}... **Options**: * `--ban`: Also ban the comment author +* `--execute`: Apply changes (default is dry-run) * `--help`: Show this message and exit. ### `ytstudio comments reply` -Reply to a top-level comment. +Reply to a top-level comment. The default is a dry run. Replies are flat on YouTube: COMMENT_ID must be a top-level comment id (the id shown by 'comments list'), not the id of another reply. @@ -507,6 +510,7 @@ $ ytstudio comments reply [OPTIONS] {comment_id} **Options**: * `-t, --text `: Reply text [required] +* `--execute`: Post the reply (default is dry-run) * `--help`: Show this message and exit. ## `ytstudio livestreams` @@ -904,6 +908,7 @@ $ ytstudio profile [OPTIONS] COMMAND [ARGS]... * `status`: Show authentication status for a profile * `remove`: Remove a profile and its stored credentials * `brand`: Manage per-channel brand voice (brand.md) +* `policy`: Manage per-channel moderation policy... ### `ytstudio profile add` @@ -1058,3 +1063,69 @@ $ ytstudio profile brand edit [OPTIONS] * `-p, --profile `: Profile (default: active) * `--help`: Show this message and exit. + +### `ytstudio profile policy` + +Manage per-channel moderation policy (moderation.md) + +**Usage**: + +```console +$ ytstudio profile policy [OPTIONS] COMMAND [ARGS]... +``` + +**Options**: + +* `--help`: Show this message and exit. + +**Commands**: + +* `show`: Print the moderation policy for a profile +* `set`: Set moderation policy non-interactively... +* `edit`: Open the moderation policy in $EDITOR + +#### `ytstudio profile policy show` + +Print the moderation policy for a profile + +**Usage**: + +```console +$ ytstudio profile policy show [OPTIONS] +``` + +**Options**: + +* `-p, --profile `: Profile (default: active) +* `--help`: Show this message and exit. + +#### `ytstudio profile policy set` + +Set moderation policy non-interactively from a file + +**Usage**: + +```console +$ ytstudio profile policy set [OPTIONS] +``` + +**Options**: + +* `-f, --file `: Path to a markdown file to import [required] +* `-p, --profile `: Profile (default: active) +* `--help`: Show this message and exit. + +#### `ytstudio profile policy edit` + +Open the moderation policy in $EDITOR + +**Usage**: + +```console +$ ytstudio profile policy edit [OPTIONS] +``` + +**Options**: + +* `-p, --profile `: Profile (default: active) +* `--help`: Show this message and exit. diff --git a/src/ytstudio/commands/comments.py b/src/ytstudio/commands/comments.py index 8db0d63..b9dc4de 100644 --- a/src/ytstudio/commands/comments.py +++ b/src/ytstudio/commands/comments.py @@ -1,16 +1,26 @@ import json -from dataclasses import asdict, dataclass +from collections.abc import Iterator +from dataclasses import asdict, dataclass, field +from datetime import UTC, datetime from enum import StrEnum +import httplib2 import typer +from google.auth.exceptions import RefreshError from googleapiclient.errors import HttpError +from ytstudio import comment_signals, config from ytstudio.api import api, handle_api_error from ytstudio.services import get_data_service from ytstudio.ui import console, create_table, time_ago, truncate app = typer.Typer(help="Comment commands") +# comments.setModerationStatus accepts up to 50 ids per call (50 quota units each call). +MODERATION_BATCH_SIZE = 50 +# commentThreads.list / comments.list with id= accept a comma-separated list. Keep it bounded. +LOOKUP_BATCH_SIZE = 50 + class SortOrder(StrEnum): relevance = "relevance" @@ -35,14 +45,90 @@ class Comment: likes: int published_at: str video_id: str = "" + author_channel_id: str = "" + reply_count: int = 0 + has_link: bool = False + off_youtube_link: bool = False + link_hosts: list[str] = field(default_factory=list) + duplicate_of: str | None = None + impersonation_suspect: bool = False + + +@dataclass +class Owner: + id: str + names: list[str] -def get_channel_id(service) -> str: - response = api(service.channels().list(part="id", mine=True)) +def get_owner(service) -> Owner: + response = api(service.channels().list(part="id,snippet", mine=True)) if not response.get("items"): console.print("[red]No channel found[/red]") raise typer.Exit(1) - return response["items"][0]["id"] + item = response["items"][0] + snippet = item.get("snippet", {}) + names = [n for n in (snippet.get("title"), snippet.get("customUrl")) if n] + return Owner(id=item["id"], names=names) + + +def _parse_comment(comment_id: str, snippet: dict, reply_count: int = 0) -> Comment: + return Comment( + id=comment_id, + author=snippet.get("authorDisplayName", ""), + # The API does not always return textOriginal. textDisplay is the fallback. + text=snippet.get("textOriginal", snippet.get("textDisplay", "")), + likes=snippet.get("likeCount", 0), + published_at=snippet.get("publishedAt", ""), + video_id=snippet.get("videoId", ""), + author_channel_id=snippet.get("authorChannelId", {}).get("value", ""), + reply_count=reply_count, + ) + + +def _parse_thread(item: dict) -> Comment: + snippet = item["snippet"] + return _parse_comment( + item["id"], snippet["topLevelComment"]["snippet"], snippet.get("totalReplyCount", 0) + ) + + +def add_signals(comments: list[Comment], owner: Owner | None) -> None: + duplicates = comment_signals.duplicate_map(comments) + for c in comments: + c.link_hosts = comment_signals.link_hosts(c.text) + c.has_link = bool(c.link_hosts) + c.off_youtube_link = any(not comment_signals.is_youtube_host(h) for h in c.link_hosts) + c.duplicate_of = duplicates.get(c.id) + if owner: + c.impersonation_suspect = comment_signals.impersonation_suspect( + c.author, c.author_channel_id, owner.id, owner.names + ) + + +def _iter_pages(request_fn, params: dict) -> Iterator[dict]: + """Yield items across all pages of a list call.""" + token = None + while True: + page_params = {**params, "pageToken": token} if token else params + response = api(request_fn(**page_params)) + yield from response.get("items", []) + token = response.get("nextPageToken") + if not token: + return + + +def _owner_replied(service, item: dict, owner_id: str) -> bool: + replies = item.get("replies", {}).get("comments", []) + if any(r["snippet"].get("authorChannelId", {}).get("value") == owner_id for r in replies): + return True + if item["snippet"].get("totalReplyCount", 0) <= len(replies): + return False + # The replies part holds only a few replies. Page through the rest. + params = {"part": "snippet", "parentId": item["id"], "maxResults": 100} + for reply in _iter_pages(service.comments().list, params): + if reply["snippet"].get("authorChannelId", {}).get("value") == owner_id: + return True + return False def fetch_comments( @@ -51,43 +137,39 @@ def fetch_comments( limit: int = 100, order: SortOrder = SortOrder.relevance, moderation_status: ModerationStatus = ModerationStatus.published, + owner: Owner | None = None, + unanswered: bool = False, ) -> list[Comment]: - try: - # Build query parameters based on filters - params = { - "part": "snippet", - "maxResults": min(limit, 100), - "order": order.value, - } - - if video_id: - params["videoId"] = video_id - else: - channel_id = get_channel_id(data_service) - params["allThreadsRelatedToChannelId"] = channel_id - if moderation_status != ModerationStatus.published: - params["moderationStatus"] = moderation_status.to_api_value() + """List comment threads, following nextPageToken until `limit` comments are collected.""" + params = { + "part": "snippet,replies" if unanswered else "snippet", + "textFormat": "plainText", + "maxResults": 100 if unanswered else min(limit, 100), + "order": order.value, + } + if video_id: + params["videoId"] = video_id + else: + params["allThreadsRelatedToChannelId"] = (owner or get_owner(data_service)).id + if moderation_status != ModerationStatus.published: + params["moderationStatus"] = moderation_status.to_api_value() - response = api(data_service.commentThreads().list(**params)) + comments = [] + try: + for item in _iter_pages(data_service.commentThreads().list, params): + c = _parse_thread(item) + if unanswered and ( + c.author_channel_id == owner.id or _owner_replied(data_service, item, owner.id) + ): + continue + comments.append(c) + if len(comments) >= limit: + break except HttpError as e: handle_api_error(e) except Exception as e: console.print(f"[yellow]Could not fetch comments (may be disabled): {e}[/yellow]") raise typer.Exit(1) from None - - comments = [] - for item in response.get("items", []): - snippet = item["snippet"]["topLevelComment"]["snippet"] - comments.append( - Comment( - id=item["id"], - author=snippet["authorDisplayName"], - text=snippet["textOriginal"], - likes=snippet["likeCount"], - published_at=snippet["publishedAt"], - video_id=snippet.get("videoId", ""), - ) - ) return comments @@ -99,15 +181,23 @@ def list_comments( ), limit: int = typer.Option(20, "--limit", "-n", help="Number of comments"), sort: SortOrder = typer.Option(SortOrder.time, "--sort", "-s", help="Sort order"), + unanswered: bool = typer.Option( + False, "--unanswered", help="Show only threads that have no reply from the channel owner" + ), output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"), ): """List comments across channel or for a specific video""" if sort == SortOrder.relevance and not video_id: console.print("[red]--sort relevance requires --video (YouTube API limitation)[/red]") raise typer.Exit(1) + if unanswered and status != ModerationStatus.published: + console.print("[red]--unanswered works only with published comments[/red]") + raise typer.Exit(1) service = get_data_service() - comments = fetch_comments(service, video_id, limit, sort, status) + owner = get_owner(service) + comments = fetch_comments(service, video_id, limit, sort, status, owner, unanswered) + add_signals(comments, owner) if output == "json": print(json.dumps([asdict(c) for c in comments], indent=2)) @@ -115,6 +205,8 @@ def list_comments( status_label = {"published": "Published", "held": "Held for Review", "spam": "Likely Spam"} label = status_label.get(status.value, status.value) + if unanswered: + label = f"Unanswered {label}" scope = f"video {video_id}" if video_id else "channel" console.print(f"\n[bold]{label} Comments ({len(comments)})[/bold] — {scope}\n") @@ -137,43 +229,260 @@ def list_comments( console.print(table) -def _set_moderation_status(comment_ids: list[str], status: str, ban_author: bool = False) -> int: - service = get_data_service() - success = 0 - batch_size = 50 - for i in range(0, len(comment_ids), batch_size): - batch = comment_ids[i : i + batch_size] - try: +# --- moderation: preview, write-ahead log, batched apply --- + + +def _chunks(items: list, size: int) -> Iterator[list]: + for i in range(0, len(items), size): + yield items[i : i + size] + + +def _log_lookup(ids: set[str]) -> dict[str, Comment]: + """Latest logged copy of each id, so a rejected comment can still be previewed for undo.""" + found = {} + for r in config.read_moderation_log(): + if r.get("phase") == "intent" and r.get("id") in ids: + found[r["id"]] = Comment( + id=r["id"], + author=r.get("author", ""), + text=r.get("text", ""), + likes=0, + published_at=r.get("published_at", ""), + video_id=r.get("video_id", ""), + author_channel_id=r.get("author_channel_id", ""), + ) + return found + + +def resolve_comments(service, ids: list[str], owner: Owner) -> tuple[dict[str, Comment], set[str]]: + """Look up comment ids so the preview and the log show API truth, not caller input. + + Order: threads by id, comments by id (replies), the held and spam queues, then the + local moderation log. Returns (found, from_log) where from_log marks log-only hits. + """ + found: dict[str, Comment] = {} + + def missing() -> list[str]: + return [i for i in ids if i not in found] + + for chunk in _chunks(missing(), LOOKUP_BATCH_SIZE): + resp = api( + service.commentThreads().list( + part="snippet", id=",".join(chunk), textFormat="plainText" + ) + ) + for item in resp.get("items", []): + found[item["id"]] = _parse_thread(item) + + for chunk in _chunks(missing(), LOOKUP_BATCH_SIZE): + resp = api( + service.comments().list(part="snippet", id=",".join(chunk), textFormat="plainText") + ) + for item in resp.get("items", []): + found[item["id"]] = _parse_comment(item["id"], item["snippet"]) + + if missing(): + # The docs do not say if id lookups return held comments. The queues do. + owner_id = owner.id + for status in (ModerationStatus.held, ModerationStatus.spam): params = { - "id": ",".join(batch), - "moderationStatus": status, + "part": "snippet", + "textFormat": "plainText", + "allThreadsRelatedToChannelId": owner_id, + "moderationStatus": status.to_api_value(), + "maxResults": 100, } - if ban_author and status == "rejected": - params["banAuthor"] = True - api(service.comments().setModerationStatus(**params)) - success += len(batch) - except HttpError as e: - handle_api_error(e) - return success + wanted = set(missing()) + for item in _iter_pages(service.commentThreads().list, params): + if item["id"] in wanted: + found[item["id"]] = _parse_thread(item) + wanted.discard(item["id"]) + if not wanted: + break + if not missing(): + break + + from_log = set() + if missing(): + logged = _log_lookup(set(missing())) + found.update(logged) + from_log = set(logged) + return found, from_log + + +def _flags(c: Comment, from_log: bool) -> str: + flags = [] + if c.off_youtube_link: + flags.append("link:" + ",".join(c.link_hosts)) + elif c.has_link: + flags.append("link:youtube") + if c.duplicate_of: + flags.append(f"dup:{c.duplicate_of}") + if c.impersonation_suspect: + flags.append("impersonation?") + if from_log: + flags.append("from log") + return " ".join(flags) + + +def _print_preview(comments: list[Comment], from_log: set[str], action: str) -> None: + console.print(f"\n[bold]{action} {len(comments)} comment(s)[/bold]\n") + table = create_table() + table.add_column("ID", style="yellow") + table.add_column("Video", style="cyan") + table.add_column("Author") + table.add_column("Flags") + table.add_column("Comment") + for c in comments: + table.add_row( + c.id, c.video_id, c.author, _flags(c, c.id in from_log), truncate(c.text, 100) + ) + console.print(table) + + +def _now() -> str: + return datetime.now(UTC).isoformat(timespec="seconds") + + +def _api_error_text(error: Exception) -> str: + if isinstance(error, RefreshError): + return "session expired or revoked" + if not isinstance(error, HttpError): + return f"{type(error).__name__}: {error}" if str(error) else type(error).__name__ + details = error.error_details[0] if getattr(error, "error_details", None) else {} + reason = details.get("reason") if isinstance(details, dict) else None + return f"HTTP {error.resp.status}" + (f" {reason}" if reason else "") + + +@dataclass +class ModerationResult: + applied: list[str] = field(default_factory=list) + # Sent, but the call failed with a 5xx or a network error: the change may have landed. + unknown: list[str] = field(default_factory=list) + # Never sent, or refused by the API (4xx, auth). + unapplied: list[str] = field(default_factory=list) + error: str | None = None + + +def _outcome_unknown(error: Exception) -> bool: + if isinstance(error, HttpError): + return error.resp.status >= 500 + return not isinstance(error, RefreshError) + + +def _set_moderation_status( + service, comments: list[Comment], action: str, status: str, ban_author: bool +) -> ModerationResult: + """Apply in batches. Log each batch before its call. Stop at the first failed batch.""" + result = ModerationResult() + batches = list(_chunks(comments, MODERATION_BATCH_SIZE)) + for n, batch in enumerate(batches): + ids = [c.id for c in batch] + config.append_moderation_log( + [ + { + "ts": _now(), + "phase": "intent", + "action": action, + "ban": ban_author, + "id": c.id, + "author": c.author, + "author_channel_id": c.author_channel_id, + "video_id": c.video_id, + "published_at": c.published_at, + "text": c.text, + } + for c in batch + ] + ) + params = {"id": ",".join(ids), "moderationStatus": status} + if ban_author and status == "rejected": + params["banAuthor"] = True + try: + service.comments().setModerationStatus(**params).execute() + except (HttpError, RefreshError, OSError, httplib2.HttpLib2Error) as e: + result.error = _api_error_text(e) + phase = "unknown" if _outcome_unknown(e) else "failed" + config.append_moderation_log( + [ + {"ts": _now(), "phase": phase, "action": action, "id": i, "error": result.error} + for i in ids + ] + ) + (result.unknown if phase == "unknown" else result.unapplied).extend(ids) + result.unapplied.extend(c.id for b in batches[n + 1 :] for c in b) + return result + config.append_moderation_log( + [{"ts": _now(), "phase": "applied", "action": action, "id": i} for i in ids] + ) + result.applied.extend(ids) + return result + + +def _moderate(comment_ids: list[str], action: str, status: str, ban: bool, execute: bool) -> None: + ids = list(dict.fromkeys(comment_ids)) + service = get_data_service() + owner = get_owner(service) + found, from_log = resolve_comments(service, ids, owner) + comments = [found[i] for i in ids if i in found] + unresolved = [i for i in ids if i not in found] + add_signals(comments, owner) + + label = f"{'Would ' if not execute else ''}{action}" + (" and ban the author of" if ban else "") + _print_preview(comments, from_log, label[0].upper() + label[1:]) + + if unresolved: + console.print( + f"\n[red]The CLI did not find {len(unresolved)} id(s) in the API or in the " + "moderation log. The CLI changed nothing.[/red]\n" + " ".join(unresolved) + ) + raise typer.Exit(1) + + if not execute: + console.print( + f"\n[dim]Dry run. Run with --execute to apply " + f"({len(list(_chunks(comments, MODERATION_BATCH_SIZE)))} call(s), " + f"50 quota units each).[/dim]" + ) + return + + result = _set_moderation_status(service, comments, action, status, ban) + past = {"reject": "rejected", "publish": "published"}[action] + console.print(f"\n{len(result.applied)} comment(s) {past}") + if result.error: + console.print(f"[red]Stopped: {result.error}.[/red]") + if result.unknown: + console.print( + f"[yellow]{len(result.unknown)} comment(s) have status unknown, check:[/yellow]\n" + + " ".join(result.unknown) + ) + if result.unapplied: + console.print( + f"[red]{len(result.unapplied)} comment(s) are not {past}:[/red]\n" + + " ".join(result.unapplied) + ) + console.print(f"[dim]Log: {config.moderation_log_path()}[/dim]") + if result.error: + raise typer.Exit(1) @app.command() def publish( comment_ids: list[str] = typer.Argument(help="Comment IDs to publish"), + execute: bool = typer.Option(False, "--execute", help="Apply changes (default is dry-run)"), ): - """Publish held comments (approve for public display)""" - count = _set_moderation_status(comment_ids, "published") - console.print(f"{count} comment(s) published") + """Publish held comments (approve for public view). The default is a dry run.""" + _moderate(comment_ids, "publish", "published", ban=False, execute=execute) @app.command() def reject( comment_ids: list[str] = typer.Argument(help="Comment IDs to reject"), ban: bool = typer.Option(False, "--ban", help="Also ban the comment author"), + execute: bool = typer.Option(False, "--execute", help="Apply changes (default is dry-run)"), ): - """Reject comments (hide from public display)""" - count = _set_moderation_status(comment_ids, "rejected", ban_author=ban) - console.print(f"{count} comment(s) rejected") + """Reject comments (hide from public view). The default is a dry run.""" + _moderate(comment_ids, "reject", "rejected", ban=ban, execute=execute) @app.command() @@ -182,13 +491,29 @@ def reply( help="Top-level comment ID to reply to (from 'comments list')" ), text: str = typer.Option(..., "--text", "-t", help="Reply text"), + execute: bool = typer.Option(False, "--execute", help="Post the reply (default is dry-run)"), ): - """Reply to a top-level comment. + """Reply to a top-level comment. The default is a dry run. Replies are flat on YouTube: COMMENT_ID must be a top-level comment id (the id shown by 'comments list'), not the id of another reply. """ service = get_data_service() + if not execute: + resp = api( + service.commentThreads().list(part="snippet", id=comment_id, textFormat="plainText") + ) + items = resp.get("items", []) + if items: + parent = _parse_thread(items[0]) + console.print(f"\n[bold]Comment[/bold] {parent.id} by {parent.author}:\n{parent.text}") + else: + console.print( + f"\n[yellow]The API did not return comment {comment_id} for this id.[/yellow]" + ) + console.print(f"\n[bold]Would reply:[/bold]\n{text}") + console.print("\n[dim]Dry run. Run with --execute to post (50 quota units).[/dim]") + return try: response = api( service.comments().insert( diff --git a/src/ytstudio/commands/profile.py b/src/ytstudio/commands/profile.py index d1eba8a..558b03a 100644 --- a/src/ytstudio/commands/profile.py +++ b/src/ytstudio/commands/profile.py @@ -100,9 +100,6 @@ def remove( success_message(f"Profile '{name}' removed.") -brand_app = typer.Typer(help="Manage per-channel brand voice (brand.md)") -app.add_typer(brand_app, name="brand") - _BRAND_TEMPLATE = """# Brand voice +## Reject -@brand_app.command("show") -def brand_show( - profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), -): - """Print the brand voice for a profile""" - target = _resolve_brand_target(profile) - text = config.load_brand(target) - if not text: - console.print( - f"[yellow]No brand voice for '{target}'. Set one with " - f"'ytstudio profile brand edit' or '... brand set --file '.[/yellow]" - ) - raise typer.Exit(1) - # Raw stdout so an agent can capture the markdown verbatim for a system prompt. - print(text) +## Leave held +## Never touch -@brand_app.command("set") -def brand_set( - file: str = typer.Option(..., "--file", "-f", help="Path to a markdown file to import"), - profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), -): - """Set brand voice non-interactively from a file""" - target = _resolve_brand_target(profile) - src = Path(file) - if not src.is_file(): - console.print(f"[red]File not found: {file}[/red]") +## Always send to me +""" + + +def _resolve_profile(profile: str | None) -> str: + target = profile or config.get_active_profile() + if not config.profile_exists(target): + console.print(f"[red]No profile named '{target}'. See 'ytstudio profile list'.[/red]") raise typer.Exit(1) - config.save_brand(target, src.read_text()) - success_message(f"Brand voice set for '{target}'.") + return target -@brand_app.command("edit") -def brand_edit( - profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), -): - """Open the brand voice in $EDITOR""" - target = _resolve_brand_target(profile) - if config.load_brand(target) is None: - config.save_brand(target, _BRAND_TEMPLATE) - path = config.brand_path(target) - editor = os.environ.get("EDITOR", "vi") - subprocess.run([editor, str(path)], check=False) - # An editor may rewrite the file with looser permissions; re-assert owner-only. - if os.name == "posix": - path.chmod(0o600) - success_message(f"Brand voice saved for '{target}'.") +def _markdown_file_app(*, cmd: str, label: str, template: str, load, save, path) -> typer.Typer: + """show/set/edit commands for one per-profile markdown file (brand.md, moderation.md).""" + sub = typer.Typer(help=f"Manage per-channel {label.lower()} ({path('x').name})") + + @sub.command("show") + def show( + profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), + ): + target = _resolve_profile(profile) + text = load(target) + if not text: + console.print( + f"[yellow]No {label.lower()} for '{target}'. Set one with " + f"'ytstudio profile {cmd} edit' or '... {cmd} set --file '.[/yellow]" + ) + raise typer.Exit(1) + # Raw stdout so an agent can capture the markdown verbatim for a system prompt. + print(text) + + show.__doc__ = f"Print the {label.lower()} for a profile" + + @sub.command("set") + def set_( + file: str = typer.Option(..., "--file", "-f", help="Path to a markdown file to import"), + profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), + ): + target = _resolve_profile(profile) + src = Path(file) + if not src.is_file(): + console.print(f"[red]File not found: {file}[/red]") + raise typer.Exit(1) + save(target, src.read_text()) + success_message(f"{label} set for '{target}'.") + + set_.__doc__ = f"Set {label.lower()} non-interactively from a file" + + @sub.command("edit") + def edit( + profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), + ): + target = _resolve_profile(profile) + if load(target) is None: + save(target, template) + file_path = path(target) + editor = os.environ.get("EDITOR", "vi") + subprocess.run([editor, str(file_path)], check=False) + # An editor may rewrite the file with looser permissions; re-assert owner-only. + if os.name == "posix": + file_path.chmod(0o600) + success_message(f"{label} saved for '{target}'.") + + edit.__doc__ = f"Open the {label.lower()} in $EDITOR" + return sub + + +app.add_typer( + _markdown_file_app( + cmd="brand", + label="Brand voice", + template=_BRAND_TEMPLATE, + load=config.load_brand, + save=config.save_brand, + path=config.brand_path, + ), + name="brand", +) +app.add_typer( + _markdown_file_app( + cmd="policy", + label="Moderation policy", + template=_POLICY_TEMPLATE, + load=config.load_policy, + save=config.save_policy, + path=config.policy_path, + ), + name="policy", +) diff --git a/src/ytstudio/comment_signals.py b/src/ytstudio/comment_signals.py new file mode 100644 index 0000000..e428feb --- /dev/null +++ b/src/ytstudio/comment_signals.py @@ -0,0 +1,82 @@ +"""Deterministic triage signals for comments. No model; evidence for the agent and the human.""" + +import re +import unicodedata +from difflib import SequenceMatcher + +# Scheme, "www." or a bare host followed by a path ("t.me/x", "wa.me/123"). +_LINK = re.compile( + r"(?:https?://|www\.)([a-z0-9.-]+\.[a-z]{2,})|\b([a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,})/", + re.IGNORECASE, +) +_YOUTUBE_HOSTS = ("youtube.com", "youtu.be") +_NON_WORD = re.compile(r"[\W_]+") + +# Shorter normalized texts ("nice video") repeat by chance, so they never count as duplicates. +DUPLICATE_MIN_LENGTH = 15 +IMPERSONATION_RATIO = 0.85 + + +def link_hosts(text: str) -> list[str]: + hosts = [] + for m in _LINK.finditer(text): + host = (m.group(1) or m.group(2)).lower().rstrip(".") + host = host.removeprefix("www.") + if host not in hosts: + hosts.append(host) + return hosts + + +def is_youtube_host(host: str) -> bool: + return any(host == h or host.endswith("." + h) for h in _YOUTUBE_HOSTS) + + +def normalize(text: str) -> str: + """Casefold and drop punctuation, emoji and spacing, so near-identical copies compare equal.""" + text = unicodedata.normalize("NFKC", text).casefold() + return _NON_WORD.sub(" ", text).strip() + + +def _name_key(name: str) -> str: + # authorDisplayName now carries the @handle. Strip it so "@chan" matches "Chan". + return _NON_WORD.sub("", normalize(name.removeprefix("@"))) + + +def impersonation_suspect( + author: str, author_channel_id: str, owner_id: str, owner_names: list[str] +) -> bool: + """Display name close to the channel's title or handle, posted from another channel.""" + if not owner_id or not author_channel_id or author_channel_id == owner_id: + return False + key = _name_key(author) + if not key: + return False + for name in owner_names: + target = _name_key(name) + if target and SequenceMatcher(None, key, target).ratio() >= IMPERSONATION_RATIO: + return True + return False + + +def duplicate_map(comments: list) -> dict[str, str]: + """Map comment id -> id of the earliest earlier copy of the same text. + + An earlier copy counts when it is on another video or from the same author. + Different authors with the same text on one video do not count. + """ + groups: dict[str, list] = {} + for c in comments: + key = normalize(c.text) + if len(key) >= DUPLICATE_MIN_LENGTH: + groups.setdefault(key, []).append(c) + + result = {} + for group in groups.values(): + group.sort(key=lambda c: c.published_at) + for j, c in enumerate(group): + for prev in group[:j]: + same_author = c.author_channel_id and c.author_channel_id == prev.author_channel_id + if c.video_id != prev.video_id or same_author: + result[c.id] = prev.id + break + return result diff --git a/src/ytstudio/config.py b/src/ytstudio/config.py index 7daec39..5a7ed88 100644 --- a/src/ytstudio/config.py +++ b/src/ytstudio/config.py @@ -211,6 +211,14 @@ def brand_path(name: str | None = None) -> Path: return profile_dir(name or get_active_profile()) / "brand.md" +def policy_path(name: str | None = None) -> Path: + return profile_dir(name or get_active_profile()) / "moderation.md" + + +def moderation_log_path(name: str | None = None) -> Path: + return profile_dir(name or get_active_profile()) / "moderation-log.jsonl" + + def list_profiles() -> list[str]: if not PROFILES_DIR.exists(): return [] @@ -284,6 +292,42 @@ def save_brand(name: str, text: str) -> None: _write_private(brand_path(name), text) +def load_policy(name: str | None = None) -> str | None: + path = policy_path(name) + if not path.exists(): + return None + return path.read_text() + + +def save_policy(name: str, text: str) -> None: + _ensure_profile_dir(name) + _write_private(policy_path(name), text) + + +def append_moderation_log(records: list[dict], name: str | None = None) -> None: + """Append JSONL records and fsync, so they survive a crash during the API call.""" + _ensure_profile_dir(name or get_active_profile()) + data = "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in records) + fd = os.open(moderation_log_path(name), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(data) + fh.flush() + os.fsync(fh.fileno()) + + +def read_moderation_log(name: str | None = None) -> list[dict]: + path = moderation_log_path(name) + if not path.exists(): + return [] + records = [] + for line in path.read_text().splitlines(): + try: + records.append(json.loads(line)) + except json.JSONDecodeError: + continue # a torn last line must not block recovery + return records + + def migrate_legacy_credentials() -> bool: """Move a pre-profiles credentials.json into the default profile. One-shot. diff --git a/tests/conftest.py b/tests/conftest.py index 6991a5b..45b1416 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,7 @@ import pytest +from ytstudio import config from ytstudio.commands import playlists as _playlists_module MOCK_CHANNEL = { @@ -101,6 +102,7 @@ "topLevelComment": { "snippet": { "authorDisplayName": "Test User", + "authorChannelId": {"value": "UC_test_user"}, "textOriginal": "Great video! Love it!", "textDisplay": "Great video! Love it!", "likeCount": 5, @@ -117,6 +119,7 @@ "topLevelComment": { "snippet": { "authorDisplayName": "Angry User", + "authorChannelId": {"value": "UC_angry_user"}, "textOriginal": "This is terrible and boring", "textDisplay": "This is terrible and boring", "likeCount": 0, @@ -271,3 +274,20 @@ def mock_credentials(): } with patch("ytstudio.config.load_credentials", return_value=mock_creds): yield mock_creds + + +@pytest.fixture +def temp_config(tmp_path, monkeypatch): + config_dir = tmp_path / ".config" / "ytstudio-cli" + config_dir.mkdir(parents=True) + + monkeypatch.delenv(config.PROFILE_ENV_VAR, raising=False) + + with ( + patch.object(config, "CONFIG_DIR", config_dir), + patch.object(config, "CLIENT_SECRETS_FILE", config_dir / "client_secrets.json"), + patch.object(config, "PROFILES_DIR", config_dir / "profiles"), + patch.object(config, "STATE_FILE", config_dir / "state.json"), + patch.object(config, "LEGACY_CREDENTIALS_FILE", config_dir / "credentials.json"), + ): + yield config_dir diff --git a/tests/test_comment_signals.py b/tests/test_comment_signals.py new file mode 100644 index 0000000..01b4e17 --- /dev/null +++ b/tests/test_comment_signals.py @@ -0,0 +1,94 @@ +from ytstudio.commands.comments import Comment +from ytstudio.comment_signals import ( + duplicate_map, + impersonation_suspect, + is_youtube_host, + link_hosts, + normalize, +) + + +def _c(cid, text, video="v1", channel="UC_a", ts="2026-01-01T00:00:00Z"): + return Comment(cid, "x", text, 0, ts, video_id=video, author_channel_id=channel) + + +class TestLinks: + def test_hosts(self): + assert link_hosts("go to https://Scam.example.com/a and www.foo.io") == [ + "scam.example.com", + "foo.io", + ] + + def test_bare_host_with_path(self): + assert link_hosts("chat on wa.me/31612345678 or t.me/bob") == ["wa.me", "t.me"] + + def test_plain_text_has_no_links(self): + assert link_hosts("v2.0 is great, see file.py") == [] + + def test_youtube_hosts(self): + assert is_youtube_host("youtube.com") + assert is_youtube_host("m.youtube.com") + assert is_youtube_host("youtu.be") + assert not is_youtube_host("notyoutube.com") + + +class TestDuplicates: + def test_normalize_ignores_case_punctuation_and_spacing(self): + assert normalize("Free GIFT!!! Click now") == normalize("free gift click now") + + def test_same_text_across_videos(self): + dups = duplicate_map( + [ + _c("b", "free gift card click my profile", "v2", "UC_b", "2026-01-02T00:00:00Z"), + _c("a", "Free gift card, click my profile!", "v1", "UC_a"), + ] + ) + assert dups == {"b": "a"} + + def test_same_author_same_video(self): + dups = duplicate_map( + [_c("a", "subscribe to my channel please"), _c("b", "subscribe to my channel please")] + ) + assert dups == {"b": "a"} + + def test_earlier_copy_from_same_author_after_other_author(self): + # Order [B v1, A v1, A v1]: the second A copy points to the first A copy, not to B. + dups = duplicate_map( + [ + _c("b1", "join my telegram for signals", "v1", "UC_b", "2026-01-01T00:00:00Z"), + _c("a1", "join my telegram for signals", "v1", "UC_a", "2026-01-02T00:00:00Z"), + _c("a2", "join my telegram for signals", "v1", "UC_a", "2026-01-03T00:00:00Z"), + ] + ) + assert dups == {"a2": "a1"} + + def test_different_authors_same_video_not_flagged(self): + dups = duplicate_map( + [ + _c("a", "this helped me a lot, thanks", channel="UC_a"), + _c("b", "this helped me a lot, thanks", channel="UC_b"), + ] + ) + assert dups == {} + + def test_short_text_not_flagged(self): + assert duplicate_map([_c("a", "nice video", "v1"), _c("b", "nice video", "v2")]) == {} + + +class TestImpersonation: + names = ("Test Channel", "@testchannel") + + def test_exact_copy_from_other_channel(self): + assert impersonation_suspect("Test Channel", "UC_fake", "UC_owner", self.names) + + def test_handle_form(self): + assert impersonation_suspect("@TestChannel", "UC_fake", "UC_owner", self.names) + + def test_near_miss(self): + assert impersonation_suspect("Test Channe1", "UC_fake", "UC_owner", self.names) + + def test_owner_is_never_suspect(self): + assert not impersonation_suspect("Test Channel", "UC_owner", "UC_owner", self.names) + + def test_unrelated_name(self): + assert not impersonation_suspect("@janedoe", "UC_fake", "UC_owner", self.names) diff --git a/tests/test_comments.py b/tests/test_comments.py index 0adb3e3..590e78f 100644 --- a/tests/test_comments.py +++ b/tests/test_comments.py @@ -1,14 +1,73 @@ +import json from datetime import UTC, datetime, timedelta from unittest.mock import MagicMock +import httplib2 +import pytest from googleapiclient.errors import HttpError from typer.testing import CliRunner +from tests.conftest import MOCK_CHANNEL, MOCK_COMMENT +from ytstudio import config from ytstudio.main import app from ytstudio.ui import time_ago runner = CliRunner() +OWNER_ID = MOCK_CHANNEL["id"] + + +def _thread(cid, text="hello there", author="Someone", channel="UC_x", video="vid1", **extra): + snippet = { + "authorDisplayName": author, + "authorChannelId": {"value": channel}, + "textOriginal": text, + "likeCount": 0, + "publishedAt": extra.pop("published_at", "2026-01-20T15:00:00Z"), + "videoId": video, + } + item = { + "id": cid, + "snippet": { + "topLevelComment": {"id": cid, "snippet": snippet}, + "totalReplyCount": extra.pop("total_replies", 0), + }, + } + if "replies" in extra: + item["replies"] = {"comments": extra.pop("replies")} + return item + + +def _reply(channel): + return {"snippet": {"authorChannelId": {"value": channel}}} + + +def _request(response): + req = MagicMock() + if isinstance(response, Exception): + req.execute.side_effect = response + else: + req.execute.return_value = response + return req + + +def _route(mock_method, fn): + """Answer each list(**kwargs) call with fn(kwargs).""" + mock_method.side_effect = lambda **kw: _request(fn(kw)) + + +def _http_error(status=500, reason="backendError"): + resp = MagicMock() + resp.status = status + body = json.dumps({"error": {"errors": [{"reason": reason}], "message": reason}}) + return HttpError(resp, body.encode()) + + +@pytest.fixture +def profile(temp_config): + config.save_credentials({"token": "x"}, name="default") + return temp_config + class TestTimeAgo: def test_formats_correctly(self): @@ -19,7 +78,7 @@ def test_formats_correctly(self): assert "5h ago" in time_ago(hours_ago) -class TestCommentsCommands: +class TestCommentsList: def test_list_channel_wide(self, mock_auth): result = runner.invoke(app, ["comments", "list"]) assert result.exit_code == 0 @@ -49,8 +108,235 @@ def test_list_json_output(self, mock_auth): assert '"id": "UgwComment123"' in result.stdout assert '"author": "Test User"' in result.stdout - def test_publish_comments(self, mock_auth): - result = runner.invoke(app, ["comments", "publish", "UgwComment123", "UgwComment456"]) + def test_status_applies_with_video_filter(self, mock_auth): + result = runner.invoke(app, ["comments", "list", "-v", "vid1", "--status", "held"]) + assert result.exit_code == 0 + kwargs = mock_auth.commentThreads.return_value.list.call_args.kwargs + assert kwargs["videoId"] == "vid1" + assert kwargs["moderationStatus"] == "heldForReview" + + def test_paginates_past_100(self, mock_auth): + pages = { + None: {"items": [_thread(f"a{i}") for i in range(100)], "nextPageToken": "p2"}, + "p2": {"items": [_thread(f"b{i}") for i in range(100)], "nextPageToken": "p3"}, + "p3": {"items": [_thread(f"c{i}") for i in range(100)]}, + } + method = mock_auth.commentThreads.return_value.list + _route(method, lambda kw: pages[kw.get("pageToken")]) + + result = runner.invoke(app, ["comments", "list", "-n", "150", "-o", "json"]) + + assert result.exit_code == 0 + assert len(json.loads(result.stdout)) == 150 + assert method.call_count == 2 # stops once the limit is reached + + def test_paginates_until_last_page(self, mock_auth): + pages = { + None: {"items": [_thread(f"a{i}") for i in range(100)], "nextPageToken": "p2"}, + "p2": {"items": [_thread(f"b{i}") for i in range(30)]}, + } + _route(mock_auth.commentThreads.return_value.list, lambda kw: pages[kw.get("pageToken")]) + result = runner.invoke(app, ["comments", "list", "-n", "500", "-o", "json"]) + assert len(json.loads(result.stdout)) == 130 + + def test_json_signals(self, mock_auth): + items = [ + _thread("s1", "Win a prize at https://scam.example.com/x now", channel="UC_a"), + _thread("s2", "WIN a prize at https://scam.example.com/x now!!", "B", "UC_b", "vid2"), + _thread("imp", "message me on telegram", "@TestChannel", "UC_fake"), + _thread("own", "pinned note", "@testchannel", OWNER_ID), + _thread("yt", "see https://youtu.be/abc", channel="UC_c"), + ] + items[1]["snippet"]["topLevelComment"]["snippet"]["publishedAt"] = "2026-01-21T00:00:00Z" + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": items}) + + result = runner.invoke(app, ["comments", "list", "-o", "json"]) + + rows = {r["id"]: r for r in json.loads(result.stdout)} + assert rows["s1"]["has_link"] and rows["s1"]["off_youtube_link"] + assert rows["s1"]["link_hosts"] == ["scam.example.com"] + assert rows["s1"]["duplicate_of"] is None + assert rows["s2"]["duplicate_of"] == "s1" + assert rows["s1"]["author_channel_id"] == "UC_a" + assert rows["imp"]["impersonation_suspect"] is True + assert rows["own"]["impersonation_suspect"] is False + assert rows["yt"]["has_link"] and not rows["yt"]["off_youtube_link"] + + def test_comments_disabled(self, mock_auth): + mock_auth.commentThreads.return_value.list.return_value.execute.side_effect = Exception( + "Comments disabled" + ) + result = runner.invoke(app, ["comments", "list", "--video", "test_video_123"]) + assert result.exit_code == 1 + + +class TestUnanswered: + def test_filters_threads_the_owner_answered(self, mock_auth): + items = [ + _thread("open", "how do I do this?"), + _thread("answered", "q", total_replies=1, replies=[_reply(OWNER_ID)]), + _thread("others", "q", total_replies=1, replies=[_reply("UC_other")]), + _thread("mine", "my own comment", channel=OWNER_ID), + _thread("deep", "q", total_replies=7, replies=[_reply("UC_other")] * 5), + ] + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": items}) + # Full reply list for "deep" holds the owner's reply beyond the inline five. + _route( + mock_auth.comments.return_value.list, + lambda kw: {"items": [_reply("UC_other"), _reply(OWNER_ID)]}, + ) + + result = runner.invoke(app, ["comments", "list", "--unanswered", "-o", "json"]) + + assert result.exit_code == 0 + assert [r["id"] for r in json.loads(result.stdout)] == ["open", "others"] + thread_kwargs = mock_auth.commentThreads.return_value.list.call_args.kwargs + assert thread_kwargs["part"] == "snippet,replies" + reply_kwargs = mock_auth.comments.return_value.list.call_args.kwargs + assert reply_kwargs["parentId"] == "deep" + + def test_requires_published(self, mock_auth): + result = runner.invoke(app, ["comments", "list", "--unanswered", "--status", "held"]) + assert result.exit_code == 1 + assert "published" in result.stdout + + +class TestModerationPreview: + def test_reject_is_dry_run_by_default(self, mock_auth, profile): + result = runner.invoke(app, ["comments", "reject", "UgwComment123"]) + assert result.exit_code == 0 + assert "Would reject 1 comment(s)" in result.stdout + assert "Test User" in result.stdout + assert "Great video" in result.stdout + assert "--execute" in result.stdout + mock_auth.comments.return_value.setModerationStatus.assert_not_called() + assert not config.moderation_log_path().exists() + + def test_publish_is_dry_run_by_default(self, mock_auth, profile): + result = runner.invoke(app, ["comments", "publish", "UgwComment123"]) + assert result.exit_code == 0 + assert "Would publish" in result.stdout + mock_auth.comments.return_value.setModerationStatus.assert_not_called() + + def test_ban_still_needs_execute(self, mock_auth, profile): + result = runner.invoke(app, ["comments", "reject", "UgwComment123", "--ban"]) + assert result.exit_code == 0 + assert "ban" in result.stdout + mock_auth.comments.return_value.setModerationStatus.assert_not_called() + + def test_unresolved_id_blocks_execute(self, mock_auth, profile): + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": []}) + _route(mock_auth.comments.return_value.list, lambda kw: {"items": []}) + result = runner.invoke(app, ["comments", "reject", "ghost", "--execute"]) + assert result.exit_code == 1 + assert "ghost" in result.stdout + assert "changed nothing" in result.stdout + mock_auth.comments.return_value.setModerationStatus.assert_not_called() + + def test_resolves_from_held_queue(self, mock_auth, profile): + held = _thread("held1", "buy followers cheap", "Spammer") + + def threads(kw): + if kw.get("moderationStatus") == "heldForReview": + return {"items": [held]} + return {"items": []} + + _route(mock_auth.commentThreads.return_value.list, threads) + _route(mock_auth.comments.return_value.list, lambda kw: {"items": []}) + + result = runner.invoke(app, ["comments", "reject", "held1"]) + + assert result.exit_code == 0 + assert "Spammer" in result.stdout + assert "buy followers" in result.stdout + + def test_resolves_reply_ids_by_comment_id(self, mock_auth, profile): + reply = { + "id": "reply1", + "snippet": { + "authorDisplayName": "Replier", + "authorChannelId": {"value": "UC_r"}, + "textOriginal": "a reply text", + "videoId": "vid1", + }, + } + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": []}) + _route( + mock_auth.comments.return_value.list, + lambda kw: {"items": [reply] if "reply1" in kw["id"].split(",") else []}, + ) + + result = runner.invoke(app, ["comments", "reject", "reply1"]) + + assert result.exit_code == 0 + assert "Replier" in result.stdout + kwargs = mock_auth.comments.return_value.list.call_args.kwargs + assert kwargs["id"] == "reply1" + # The held and spam queues are not read when id lookups find everything. + statuses = [ + c.kwargs.get("moderationStatus") + for c in mock_auth.commentThreads.return_value.list.call_args_list + ] + assert statuses == [None] + + def test_held_queue_fallback_paginates(self, mock_auth, profile): + pages = { + None: {"items": [_thread(f"h{i}") for i in range(100)], "nextPageToken": "p2"}, + "p2": {"items": [_thread("target", "found on page two", "Late")]}, + } + + def threads(kw): + if kw.get("moderationStatus") == "heldForReview": + return pages[kw.get("pageToken")] + return {"items": []} + + _route(mock_auth.commentThreads.return_value.list, threads) + _route(mock_auth.comments.return_value.list, lambda kw: {"items": []}) + + result = runner.invoke(app, ["comments", "reject", "target"]) + + assert result.exit_code == 0 + assert "found on page two" in result.stdout + tokens = [ + c.kwargs.get("pageToken") + for c in mock_auth.commentThreads.return_value.list.call_args_list + if c.kwargs.get("moderationStatus") == "heldForReview" + ] + assert tokens == [None, "p2"] + + def test_preview_flags_impersonation(self, mock_auth, profile): + fake = _thread("fake1", "dm me on telegram", "@TestChannel", "UC_fake") + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": [fake]}) + + result = runner.invoke(app, ["comments", "reject", "fake1"]) + + assert result.exit_code == 0 + assert "impersonation?" in result.stdout + + def test_lookups_ask_for_plain_text(self, mock_auth, profile): + runner.invoke(app, ["comments", "reject", "UgwComment123"]) + kwargs = mock_auth.commentThreads.return_value.list.call_args.kwargs + assert kwargs["textFormat"] == "plainText" + + def test_resolves_from_log_for_undo(self, mock_auth, profile): + config.append_moderation_log( + [{"phase": "intent", "id": "gone1", "author": "Was Rejected", "text": "oops"}] + ) + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": []}) + _route(mock_auth.comments.return_value.list, lambda kw: {"items": []}) + + result = runner.invoke(app, ["comments", "publish", "gone1", "--execute"]) + + assert result.exit_code == 0 + assert "from log" in result.stdout + assert "1 comment(s) published" in result.stdout + + +class TestModerationExecute: + def test_publish(self, mock_auth, profile): + result = runner.invoke( + app, ["comments", "publish", "UgwComment123", "UgwComment456", "--execute"] + ) assert result.exit_code == 0 assert "2 comment(s) published" in result.stdout mock_auth.comments.return_value.setModerationStatus.assert_called_once_with( @@ -58,8 +344,8 @@ def test_publish_comments(self, mock_auth): moderationStatus="published", ) - def test_reject_comments_with_ban(self, mock_auth): - result = runner.invoke(app, ["comments", "reject", "UgwComment123", "--ban"]) + def test_reject_with_ban(self, mock_auth, profile): + result = runner.invoke(app, ["comments", "reject", "UgwComment123", "--ban", "--execute"]) assert result.exit_code == 0 assert "1 comment(s) rejected" in result.stdout mock_auth.comments.return_value.setModerationStatus.assert_called_once_with( @@ -68,34 +354,131 @@ def test_reject_comments_with_ban(self, mock_auth): banAuthor=True, ) - def test_list_comments_disabled(self, mock_auth): - mock_auth.commentThreads.return_value.list.return_value.execute.side_effect = Exception( - "Comments disabled" + def test_log_is_written_before_the_call(self, mock_auth, profile): + seen = [] + + def capture(**kwargs): + seen.extend(config.read_moderation_log()) + return _request({}) + + mock_auth.comments.return_value.setModerationStatus.side_effect = capture + result = runner.invoke(app, ["comments", "reject", "UgwComment123", "--execute"]) + + assert result.exit_code == 0 + assert len(seen) == 1 + entry = seen[0] + assert entry["phase"] == "intent" + assert entry["action"] == "reject" + assert entry["id"] == MOCK_COMMENT["id"] + assert entry["author"] == "Test User" + assert entry["text"] == "Great video! Love it!" + assert entry["video_id"] == "test_video_123" + assert entry["ts"] + phases = [r["phase"] for r in config.read_moderation_log()] + assert phases == ["intent", "applied"] + + def _run_with_failure(self, mock_auth, error, n_ids=120): + ids = [f"c{i}" for i in range(n_ids)] + _route( + mock_auth.commentThreads.return_value.list, + lambda kw: {"items": [_thread(i) for i in kw["id"].split(",")]}, ) - result = runner.invoke(app, ["comments", "list", "--video", "test_video_123"]) + calls = [] + + def set_status(**kwargs): + calls.append(kwargs["id"].split(",")) + return _request(error if len(calls) == 2 else {}) + + mock_auth.comments.return_value.setModerationStatus.side_effect = set_status + result = runner.invoke(app, ["comments", "reject", *ids, "--execute"]) + return result, calls + + @staticmethod + def _section(stdout, header): + # The ids after a report header. Rich can wrap them over several lines. + lines = stdout.splitlines() + i = next(n for n, line in enumerate(lines) if header in line) + ids = [] + for line in lines[i + 1 :]: + if "comment(s)" in line or line.startswith("Log:"): + break + ids += line.split() + return ids + + def test_5xx_batch_is_status_unknown(self, mock_auth, profile): + result, calls = self._run_with_failure(mock_auth, _http_error(500)) + assert result.exit_code == 1 + assert [len(c) for c in calls] == [50, 50] # third batch never sent + assert "50 comment(s) rejected" in result.stdout + assert "HTTP 500 backendError" in result.stdout + unknown = self._section(result.stdout, "50 comment(s) have status unknown, check") + assert unknown == [f"c{i}" for i in range(50, 100)] + unapplied = self._section(result.stdout, "20 comment(s) are not rejected") + assert unapplied == [f"c{i}" for i in range(100, 120)] + log = config.read_moderation_log() + assert sum(r["phase"] == "applied" for r in log) == 50 + assert sum(r["phase"] == "unknown" for r in log) == 50 - def test_reply(self, mock_auth): + def test_4xx_batch_is_not_applied(self, mock_auth, profile): + result, _ = self._run_with_failure(mock_auth, _http_error(400, "invalidParameter")) + + assert result.exit_code == 1 + assert "status unknown" not in result.stdout + unapplied = self._section(result.stdout, "70 comment(s) are not rejected") + assert unapplied == [f"c{i}" for i in range(50, 120)] + assert sum(r["phase"] == "failed" for r in config.read_moderation_log()) == 50 + + @pytest.mark.parametrize( + "error", [TimeoutError("timed out"), ConnectionResetError("reset"), OSError("down")] + ) + def test_network_error_mid_batch_still_reports(self, mock_auth, profile, error): + result, calls = self._run_with_failure(mock_auth, error) + + assert result.exit_code == 1 + assert len(calls) == 2 + assert "50 comment(s) rejected" in result.stdout + assert "50 comment(s) have status unknown, check" in result.stdout + assert "20 comment(s) are not rejected" in result.stdout + + def test_httplib2_error_mid_batch_still_reports(self, mock_auth, profile): + result, _ = self._run_with_failure(mock_auth, httplib2.ServerNotFoundError("no host")) + assert result.exit_code == 1 + assert "50 comment(s) have status unknown, check" in result.stdout + + def test_duplicate_ids_sent_once(self, mock_auth, profile): + runner.invoke(app, ["comments", "publish", "UgwComment123", "UgwComment123", "--execute"]) + kwargs = mock_auth.comments.return_value.setModerationStatus.call_args.kwargs + assert kwargs["id"] == "UgwComment123" + + +class TestReply: + def test_dry_run_by_default(self, mock_auth): + result = runner.invoke(app, ["comments", "reply", "UgwComment123", "-t", "Thanks!"]) + assert result.exit_code == 0 + assert "Would reply" in result.stdout + assert "Great video" in result.stdout + mock_auth.comments.return_value.insert.assert_not_called() + + def test_execute(self, mock_auth): result = runner.invoke( - app, ["comments", "reply", "UgwComment123", "--text", "Thanks for watching!"] + app, + ["comments", "reply", "UgwComment123", "--text", "Thanks for watching!", "--execute"], ) assert result.exit_code == 0 assert "UgwReply789" in result.stdout - insert = mock_auth.comments.return_value.insert - body = insert.call_args.kwargs["body"] + body = mock_auth.comments.return_value.insert.call_args.kwargs["body"] assert body["snippet"]["parentId"] == "UgwComment123" assert body["snippet"]["textOriginal"] == "Thanks for watching!" - def test_reply_requires_text(self, mock_auth): + def test_requires_text(self, mock_auth): result = runner.invoke(app, ["comments", "reply", "UgwComment123"]) assert result.exit_code != 0 - def test_reply_invalid_parent(self, mock_auth): - resp = MagicMock() - resp.status = 400 - mock_auth.comments.return_value.insert.return_value.execute.side_effect = HttpError( - resp, b'{"error": {"message": "invalid"}}' + def test_invalid_parent(self, mock_auth): + mock_auth.comments.return_value.insert.return_value.execute.side_effect = _http_error(400) + result = runner.invoke( + app, ["comments", "reply", "not_a_top_level_id", "--text", "hi", "--execute"] ) - result = runner.invoke(app, ["comments", "reply", "not_a_top_level_id", "--text", "hi"]) assert result.exit_code == 1 assert "top-level comment id" in result.stdout diff --git a/tests/test_profile.py b/tests/test_profile.py index 1b181f5..48811fe 100644 --- a/tests/test_profile.py +++ b/tests/test_profile.py @@ -11,23 +11,6 @@ runner = CliRunner() -@pytest.fixture -def temp_config(tmp_path, monkeypatch): - config_dir = tmp_path / ".config" / "ytstudio-cli" - config_dir.mkdir(parents=True) - - monkeypatch.delenv(config.PROFILE_ENV_VAR, raising=False) - - with ( - patch.object(config, "CONFIG_DIR", config_dir), - patch.object(config, "CLIENT_SECRETS_FILE", config_dir / "client_secrets.json"), - patch.object(config, "PROFILES_DIR", config_dir / "profiles"), - patch.object(config, "STATE_FILE", config_dir / "state.json"), - patch.object(config, "LEGACY_CREDENTIALS_FILE", config_dir / "credentials.json"), - ): - yield config_dir - - def _make_profile(name, title=None): config.save_credentials({"token": "x"}, name=name) config.save_profile_meta(name, {"title": title or f"{name} channel"}) @@ -219,3 +202,68 @@ def loosen(*args, **kwargs): assert result.exit_code == 0 assert stat.S_IMODE(path.stat().st_mode) == 0o600 assert path.read_text() == "edited by editor" + + +class TestProfilePolicy: + def test_policy_path_helper(self, temp_config): + path = config.policy_path("work") + assert path.name == "moderation.md" + assert path.parent == config.profile_dir("work") + + def test_set_and_show_verbatim(self, temp_config, tmp_path): + _make_profile("work") + config.set_active_profile("work") + src = tmp_path / "policy.md" + src.write_text("# Policy\n- Reject crypto bait.\n") + + assert runner.invoke(app, ["profile", "policy", "set", "--file", str(src)]).exit_code == 0 + result = runner.invoke(app, ["profile", "policy", "show"]) + assert result.exit_code == 0 + assert result.stdout == "# Policy\n- Reject crypto bait.\n\n" + + def test_separate_from_brand(self, temp_config, tmp_path): + _make_profile("work") + config.set_active_profile("work") + src = tmp_path / "policy.md" + src.write_text("policy text") + runner.invoke(app, ["profile", "policy", "set", "--file", str(src)]) + assert config.load_policy("work") == "policy text" + assert config.load_brand("work") is None + + def test_show_missing(self, temp_config): + _make_profile("work") + config.set_active_profile("work") + result = runner.invoke(app, ["profile", "policy", "show"]) + assert result.exit_code == 1 + assert "No moderation policy" in result.stdout + assert "profile policy edit" in result.stdout + + def test_edit_seeds_template_owner_only(self, temp_config): + _make_profile("work") + config.set_active_profile("work") + with patch("ytstudio.commands.profile.subprocess.run") as run: + result = runner.invoke(app, ["profile", "policy", "edit"]) + assert result.exit_code == 0 + run.assert_called_once() + path = config.policy_path("work") + assert "Moderation policy" in path.read_text() + if os.name == "posix": + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + +class TestModerationLog: + def test_append_and_read(self, temp_config): + _make_profile("work") + config.append_moderation_log([{"id": "a"}, {"id": "b"}], name="work") + config.append_moderation_log([{"id": "c"}], name="work") + assert [r["id"] for r in config.read_moderation_log("work")] == ["a", "b", "c"] + if os.name == "posix": + mode = stat.S_IMODE(config.moderation_log_path("work").stat().st_mode) + assert mode == 0o600 + + def test_torn_line_is_skipped(self, temp_config): + _make_profile("work") + config.append_moderation_log([{"id": "a"}], name="work") + with config.moderation_log_path("work").open("a") as fh: + fh.write('{"id": "b"') + assert [r["id"] for r in config.read_moderation_log("work")] == ["a"]