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:
parent
10c16ba2cb
commit
3089202316
18 changed files with 453 additions and 15 deletions
|
|
@ -15,6 +15,10 @@ class MeTubeRejected(Exception):
|
|||
pass
|
||||
|
||||
|
||||
class DeleteNotAllowed(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def get_latest_job(db: Session, video_id: int) -> DownloadJob | None:
|
||||
return (
|
||||
db.query(DownloadJob)
|
||||
|
|
@ -55,6 +59,24 @@ def request_download(db: Session, video: Video) -> DownloadJob:
|
|||
return job
|
||||
|
||||
|
||||
def delete_local_copy(db: Session, video: Video) -> DownloadJob:
|
||||
"""Deletes our own previously-downloaded copy from MeTube. Only ever acts
|
||||
on a job this app itself created and tracked (never a file MeTube already
|
||||
had before we existed) -- see AGENTS.md constraint 10."""
|
||||
job = get_latest_job(db, video.id)
|
||||
if job is None or job.status != "completed":
|
||||
raise DeleteNotAllowed("No completed local copy to delete")
|
||||
if not job.metube_job_id:
|
||||
raise DeleteNotAllowed("Missing MeTube job id, cannot request deletion")
|
||||
|
||||
MeTubeClient().delete_download(job.metube_job_id)
|
||||
|
||||
job.status = "deleted"
|
||||
job.media_url = None
|
||||
db.commit()
|
||||
return job
|
||||
|
||||
|
||||
def _find_job_by_payload(db: Session, payload: dict) -> DownloadJob | None:
|
||||
metube_id = payload.get("id")
|
||||
if metube_id:
|
||||
|
|
|
|||
|
|
@ -14,7 +14,13 @@ from app.models.oauth_credentials import SINGLETON_ID, OAuthCredentials
|
|||
logger = logging.getLogger(__name__)
|
||||
|
||||
SCOPES = [
|
||||
"https://www.googleapis.com/auth/youtube.readonly",
|
||||
# Full read/write scope, not just youtube.readonly: unsubscribing from a
|
||||
# channel (subscriptions.delete) requires write access. Deliberate
|
||||
# deviation from the original "minimal scope" TZ recommendation, per
|
||||
# explicit user request. Existing stored refresh tokens were granted
|
||||
# under the old readonly-only scope and won't cover this -- users must
|
||||
# reconnect once for this to take effect.
|
||||
"https://www.googleapis.com/auth/youtube",
|
||||
"openid",
|
||||
"https://www.googleapis.com/auth/userinfo.email",
|
||||
"https://www.googleapis.com/auth/userinfo.profile",
|
||||
|
|
|
|||
|
|
@ -77,6 +77,21 @@ class MeTubeClient:
|
|||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def delete_download(self, metube_job_id: str) -> dict:
|
||||
"""Asks MeTube to remove a finished download from its 'done' list and
|
||||
delete the underlying file (actual file deletion additionally depends
|
||||
on MeTube's own DELETE_FILE_ON_TRASHCAN config, which we don't
|
||||
control). Only ever called with a metube_job_id our own app tracked
|
||||
from a download it started -- never touches files MeTube already had
|
||||
before we existed."""
|
||||
response = httpx.post(
|
||||
f"{self.api_base_url}/delete",
|
||||
json={"ids": [metube_job_id], "where": "done"},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def build_media_url(self, filename: str) -> str | None:
|
||||
"""Safely turn a MeTube-reported filename into a public /download/... URL.
|
||||
|
||||
|
|
|
|||
|
|
@ -78,6 +78,7 @@ def sync_subscriptions(db: Session) -> dict:
|
|||
if channel is None:
|
||||
channel = Channel(
|
||||
youtube_channel_id=sub["youtube_channel_id"],
|
||||
youtube_subscription_id=sub["youtube_subscription_id"],
|
||||
title=sub["title"],
|
||||
description=sub["description"],
|
||||
thumbnail_url=sub["thumbnail_url"],
|
||||
|
|
@ -88,6 +89,7 @@ def sync_subscriptions(db: Session) -> dict:
|
|||
existing[sub["youtube_channel_id"]] = channel
|
||||
added += 1
|
||||
else:
|
||||
channel.youtube_subscription_id = sub["youtube_subscription_id"]
|
||||
channel.title = sub["title"]
|
||||
channel.description = sub["description"]
|
||||
channel.thumbnail_url = sub["thumbnail_url"]
|
||||
|
|
@ -249,3 +251,21 @@ def sync_videos(db: Session) -> dict:
|
|||
raise
|
||||
finally:
|
||||
_videos_lock.release()
|
||||
|
||||
|
||||
class ChannelHasNoSubscriptionId(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def unsubscribe_channel(db: Session, channel: Channel) -> None:
|
||||
"""Actually unsubscribes on YouTube (subscriptions.delete) -- deliberately
|
||||
out of the original MVP scope, added on explicit user request. Requires
|
||||
the write-capable OAuth scope; see google_oauth.SCOPES."""
|
||||
if not channel.youtube_subscription_id:
|
||||
raise ChannelHasNoSubscriptionId(
|
||||
"This channel was synced before subscription ids were tracked; run a subscriptions sync first"
|
||||
)
|
||||
credentials = google_oauth.get_credentials(db)
|
||||
youtube_client.unsubscribe(credentials, channel.youtube_subscription_id)
|
||||
channel.subscribed = False
|
||||
db.commit()
|
||||
|
|
|
|||
|
|
@ -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] = {}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue