Add delete-downloaded-video and real YouTube unsubscribe

Delete local copy:
- MeTubeClient.delete_download() -> POST /delete {ids, where: "done"}
- Only ever acts on a job our own app tracked (metube_job_id we stored from
  its own 'completed' event), never a pre-existing MeTube file
- New "deleted" terminal status; DELETE /api/videos/{id}/download
- Frontend: delete button next to "На сервере" badge, confirm dialog

Unsubscribe (deliberate deviation from the original TZ's MVP exclusion of
subscription management, per explicit user request after being shown the
tradeoff):
- OAuth scope widened from youtube.readonly to full youtube (read/write) --
  existing stored tokens only cover the old scope, so unsubscribing needs a
  fresh reconnect; reads keep working unchanged on the old token meanwhile
- channels.youtube_subscription_id (distinct from the channel id; that's
  what subscriptions.delete actually keys on) captured during subscriptions
  sync
- YouTubeInsufficientScope raised on 401/403 "insufficient authentication
  scopes" and surfaced as a clear 403 asking the user to reconnect, rather
  than a generic API error
- POST /api/channels/{id}/unsubscribe calls subscriptions.delete and marks
  the channel unsubscribed locally on success
- Frontend: "Отписаться" button on ChannelCard with confirm dialog

10 new backend tests (73 total).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-09-16 19:47:35 +00:00
parent 10c16ba2cb
commit 3089202316
18 changed files with 453 additions and 15 deletions

View file

@ -19,12 +19,20 @@ class YouTubeAPIError(Exception):
pass
class YouTubeInsufficientScope(Exception):
"""Raised when Google rejects a call because the stored token was granted
under an older, narrower scope (e.g. readonly tokens issued before the
unsubscribe feature needed write access) -- the fix is reconnecting."""
pass
def _headers(credentials: Credentials) -> dict:
return {"Authorization": f"Bearer {credentials.token}"}
def _raise_for_status(response: httpx.Response) -> None:
if response.status_code == 200:
if response.status_code in (200, 204):
return
try:
payload = response.json()
@ -37,6 +45,11 @@ def _raise_for_status(response: httpx.Response) -> None:
if response.status_code == 403 and reason in ("quotaExceeded", "dailyLimitExceeded", "rateLimitExceeded"):
raise YouTubeQuotaExceeded(message)
if response.status_code in (401, 403) and (
reason == "insufficientPermissions" or "insufficient authentication scopes" in message.lower()
):
raise YouTubeInsufficientScope(message)
logger.error("YouTube API error %s: %s", response.status_code, message)
raise YouTubeAPIError(f"{response.status_code}: {message}")
@ -72,6 +85,10 @@ def fetch_subscriptions(credentials: Credentials) -> list[dict]:
subscriptions.append(
{
"youtube_channel_id": channel_id,
# The subscription resource's own id -- distinct from
# the channel id, required to later call
# subscriptions.delete (unsubscribe).
"youtube_subscription_id": item.get("id"),
"title": snippet.get("title", ""),
"description": snippet.get("description", ""),
"thumbnail_url": thumbnail,
@ -142,6 +159,19 @@ def fetch_videos_details(credentials: Credentials, video_ids: list[str]) -> list
return results
def unsubscribe(credentials: Credentials, youtube_subscription_id: str) -> None:
with httpx.Client(timeout=settings.metube_request_timeout_seconds) as client:
response = client.delete(
f"{API_BASE}/subscriptions",
params={"id": youtube_subscription_id},
headers=_headers(credentials),
)
if response.status_code == 404:
# Already gone (unsubscribed elsewhere, or stale id) -- treat as success.
return
_raise_for_status(response)
def fetch_uploads_playlists(credentials: Credentials, channel_ids: list[str]) -> dict[str, str]:
result: dict[str, str] = {}