fix(i18n): hold every refusal reason by type, and refuse what the scan cannot read
Review round 1 of the refusal contract: it claimed more than it held. - The other reason carriers get their Literal too (BlockedUrl, ClipError, FolderError, the playlist and sign-in refusal helpers), so the type checker refuses a reason passed by variable or an unknown literal, and the contract reads one shape. - A literal reason in a detail dict built anywhere counts as a reason of its code; a code the scan cannot read, a refused() whose reason it cannot read, and a new reason passed by variable each fail the contract until listed with what holds them. - A sign-in refusal key the backend no longer sends is caught too. - localizeDetail's numbers (download cap in GB, upload cap in bytes) and the shared-sentence fallbacks are tested in both languages. - One Literal parser in the contract; a stale comment fixed.
This commit is contained in:
@@ -22,6 +22,7 @@ import json
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from app.downloads.edit import AAC_ARGS, EVEN_FRAME, INPUT_GUARD, X264_ARGS
|
||||
from app.plex.sync import HDR_TRANSFERS
|
||||
@@ -57,11 +58,26 @@ _CROP_ASPECTS = (0.25, 4.0)
|
||||
_EDGE_SLACK = 1e-3
|
||||
|
||||
|
||||
# Every reason a clip is refused; the UI names each one (`clip.errors.<reason>`, held by the frontend's
|
||||
# backendIds contract, which reads this Literal).
|
||||
ClipReason = Literal[
|
||||
"bad_source",
|
||||
"bad_range",
|
||||
"too_short",
|
||||
"too_long",
|
||||
"bad_audio",
|
||||
"bad_crop",
|
||||
"not_found",
|
||||
"media_missing",
|
||||
"past_end",
|
||||
]
|
||||
|
||||
|
||||
class ClipError(Exception):
|
||||
"""A clip request that cannot be cut; `reason` is an i18n-mappable key, `params` the numbers its
|
||||
message names (the cap itself, so the client never says a stale one)."""
|
||||
|
||||
def __init__(self, reason: str, **params: float):
|
||||
def __init__(self, reason: ClipReason, **params: float):
|
||||
self.reason = reason
|
||||
self.params = params
|
||||
super().__init__(reason)
|
||||
|
||||
@@ -24,6 +24,7 @@ kept it — and its `ready_at`, the moment it finished (`stamp_done`).
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Literal
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from sqlalchemy import select
|
||||
@@ -181,10 +182,20 @@ def stamp_done(db: Session, job: DownloadJob) -> None:
|
||||
job.expiry_warned = False
|
||||
|
||||
|
||||
# Every folder change the rules refuse, answered as a generic refusal; the UI names each one
|
||||
# (`errors.refused.<reason>`, held by the frontend's backendIds contract, which reads this Literal).
|
||||
FolderReason = Literal[
|
||||
"file_folder_gone",
|
||||
"file_folder_name_taken",
|
||||
"file_folder_not_its_source",
|
||||
"file_folder_not_own",
|
||||
]
|
||||
|
||||
|
||||
class FolderError(Exception):
|
||||
"""A folder change the rules refuse; `reason` is the refusal the route answers with."""
|
||||
|
||||
def __init__(self, reason: str) -> None:
|
||||
def __init__(self, reason: FolderReason) -> None:
|
||||
super().__init__(reason)
|
||||
self.reason = reason
|
||||
|
||||
|
||||
@@ -33,22 +33,31 @@ user-controlled destination to guard.
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
from typing import Literal
|
||||
from urllib.parse import urlparse
|
||||
|
||||
# Reason codes travel to the client inside the structured 422 detail, so they are part of the API
|
||||
# vocabulary (frontend `localizeDetail`) — keep them stable.
|
||||
REASON_SCHEME = "scheme" # not http(s)
|
||||
REASON_NO_HOST = "no_host" # URL carries no hostname
|
||||
REASON_MALFORMED = "malformed" # unparseable authority or port; urlparse raises late, so guard it
|
||||
REASON_UNRESOLVABLE = "unresolvable" # DNS said nothing (honest: not the same as "blocked")
|
||||
REASON_PRIVATE = "private" # resolves into a network the server must not fetch from
|
||||
# vocabulary — keep them stable. The UI names each one (`downloads.errors.urlBlocked.<reason>`, held by
|
||||
# the frontend's backendIds contract, which reads this Literal).
|
||||
UrlBlockedReason = Literal["scheme", "no_host", "malformed", "unresolvable", "private"]
|
||||
REASON_SCHEME: UrlBlockedReason = "scheme" # not http(s)
|
||||
REASON_NO_HOST: UrlBlockedReason = "no_host" # URL carries no hostname
|
||||
REASON_MALFORMED: UrlBlockedReason = (
|
||||
"malformed" # unparseable authority or port; urlparse raises late
|
||||
)
|
||||
REASON_UNRESOLVABLE: UrlBlockedReason = (
|
||||
"unresolvable" # DNS said nothing (not the same as "blocked")
|
||||
)
|
||||
REASON_PRIVATE: UrlBlockedReason = (
|
||||
"private" # resolves into a network the server must not fetch from
|
||||
)
|
||||
|
||||
|
||||
class BlockedUrl(Exception):
|
||||
"""A user-supplied URL that must not be fetched server-side. ``reason`` is one of the
|
||||
REASON_* codes above."""
|
||||
|
||||
def __init__(self, reason: str):
|
||||
def __init__(self, reason: UrlBlockedReason):
|
||||
super().__init__(reason)
|
||||
self.reason = reason
|
||||
|
||||
|
||||
@@ -11,7 +11,8 @@ A test (`test_http_details.py`) reads every `HTTPException` in the app and fails
|
||||
and the frontend's contract test (`i18n/backendIds.contract.test.ts`) requires every `code` a detail
|
||||
carries to be in one record of `lib/api/refusalCodes.ts`, and every reason it can be sent with — a
|
||||
literal, or a `Literal` type when it travels in a variable — to have its sentence in both languages.
|
||||
So the rule is enforced, not described.
|
||||
A code or reason that scan cannot read fails it until it is listed with what holds it. So the rule is
|
||||
enforced, not described.
|
||||
"""
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
@@ -976,7 +976,16 @@ def _resend_verify_if_eligible(email: str) -> None:
|
||||
send_verification_link(db, user)
|
||||
|
||||
|
||||
def _login_refused(status: int, reason: str, user: User | None = None, **extra) -> HTTPException:
|
||||
# Every refusal a password sign-in answers with; the UI names each one (`welcome.auth.blocked.<reason>`,
|
||||
# held by the frontend's backendIds contract, which reads this Literal).
|
||||
LoginRefusal = Literal[
|
||||
"rate_limited", "invalid", "suspended", "email_unverified", "pending_approval"
|
||||
]
|
||||
|
||||
|
||||
def _login_refused(
|
||||
status: int, reason: LoginRefusal, user: User | None = None, **extra
|
||||
) -> HTTPException:
|
||||
"""Every refusal password_login can answer with, in the codebase's structured `{code, reason}`
|
||||
shape so the SPA can say it in the user's own language (the old bare English strings were
|
||||
unreadable under a bilingual UI, and unusable as anything but a one-line error).
|
||||
|
||||
@@ -3,7 +3,7 @@ CRUD (create / rename / delete, add / remove / reorder items) plus YouTube two-w
|
||||
mirror the user's own YouTube playlists in (`/sync-youtube`) and push/revert local edits back
|
||||
out (`/{id}/push-plan`, `/{id}/revert-youtube`), behind the optional write scope."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -53,7 +53,22 @@ def _check_pull_cooldown(user: User) -> None:
|
||||
raise HTTPException(status_code=429, detail={"code": "sync_cooldown"})
|
||||
|
||||
|
||||
def _refused(status: int, reason: str) -> HTTPException:
|
||||
# Every playlist action the server refuses; the UI names each one (`playlists.errors.<reason>`, held by
|
||||
# the frontend's backendIds contract, which reads this Literal).
|
||||
PlaylistRefusal = Literal[
|
||||
"name_required",
|
||||
"not_on_youtube",
|
||||
"quota_exceeded",
|
||||
"sync_all_busy",
|
||||
"sync_busy",
|
||||
"watch_later_not_pushable",
|
||||
"watch_later_undeletable",
|
||||
"youtube_editing_off",
|
||||
"youtube_read_scope",
|
||||
]
|
||||
|
||||
|
||||
def _refused(status: int, reason: PlaylistRefusal) -> HTTPException:
|
||||
"""A playlist action the server refuses, as a reason the UI translates
|
||||
(`playlists.errors.<reason>`) — a bare English detail reached the Hungarian UI verbatim."""
|
||||
return HTTPException(status_code=status, detail={"code": "playlist", "reason": reason})
|
||||
|
||||
Reference in New Issue
Block a user