Compare commits
49
Commits
84af92aa29
...
v0.113.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4084dd2f92 | ||
|
|
6aa6a6efdf | ||
|
|
5686759bca | ||
|
|
99a33e7fd1 | ||
|
|
8804bdde63 | ||
|
|
35266fd7e8 | ||
|
|
6211e15611 | ||
|
|
02906d0acb | ||
|
|
66e427dfa4 | ||
|
|
011dea8eb7 | ||
|
|
e2b725dba7 | ||
|
|
6d57d62ac8 | ||
|
|
0d5c6273f1 | ||
|
|
7b4e007680 | ||
|
|
3d26ca0efa | ||
|
|
fa893c73a3 | ||
|
|
d4f24de4ba | ||
|
|
91d36b3357 | ||
|
|
9bd7304bb9 | ||
|
|
b30c60d1a5 | ||
|
|
4aff19a9a4 | ||
|
|
dc50b856fd | ||
|
|
ee6e37f032 | ||
|
|
4c2fbf9b8d | ||
|
|
9d6d7525e5 | ||
|
|
ee4a5b46f8 | ||
|
|
0bc1024287 | ||
|
|
13f65b4844 | ||
|
|
2e1934689f | ||
|
|
84db570951 | ||
|
|
b25179c06a | ||
|
|
620dd8178f | ||
|
|
5d009964d8 | ||
|
|
4b5b66343d | ||
|
|
ed51f5be7e | ||
|
|
005784e291 | ||
|
|
b5045165c0 | ||
|
|
d53729a63d | ||
|
|
b04b51c909 | ||
|
|
7d45c4f59f | ||
|
|
5205091116 | ||
|
|
686c673fb2 | ||
|
|
8b37c470ba | ||
|
|
4695e1a62f | ||
|
|
1adf59ea1b | ||
|
|
bc8fe2cc6c | ||
|
|
33dd9ff054 | ||
|
|
b5f9cf14db | ||
|
|
bd2340c204 |
@@ -0,0 +1,8 @@
|
||||
# gitleaks false positives, one fingerprint per finding (commit:file:rule:line). Each says why it is no secret.
|
||||
#
|
||||
# YouTube's public WEB InnerTube key: embedded in every youtube.com results page, read live and cached;
|
||||
# this constant is only the fallback (backend/app/youtube/innertube.py).
|
||||
8b37c470ba5d11c45757f0b2e62d660b782e816d:backend/app/youtube/innertube.py:gcp-api-key:23
|
||||
# A recorded watch-next page's continuation cursors (continuationCommand.token): page pointers, not credentials.
|
||||
8b37c470ba5d11c45757f0b2e62d660b782e816d:backend/tests/fixtures/innertube_next_first.json:generic-api-key:768
|
||||
8b37c470ba5d11c45757f0b2e62d660b782e816d:backend/tests/fixtures/innertube_next_first.json:generic-api-key:792
|
||||
@@ -7,6 +7,51 @@ edit the release notes and re-run the generator.
|
||||
|
||||
Upgrading, pinning a version and rolling back: [docs/self-hosting.md](docs/self-hosting.md#upgrading).
|
||||
|
||||
## 0.113.0 — 2026-10-28
|
||||
|
||||
### New
|
||||
|
||||
- The address names what you see: tabs, list views, sorts and searches (the live YouTube search too), the YouTube player and the file viewer. A reload, a bookmark or a shared link opens the same view.
|
||||
- A link to a video reopens the player over its page once; Back closes it. A video the page no longer lists plays on its own and says so.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Back and Forward step through the views as you saw them, across dialogs, players and reloads: a reload under an open player no longer leaves a Back step that does nothing.
|
||||
- Signed out on a Plex page, the sign-in card could show a button with no text.
|
||||
- The channel page's address names the channel and its own view, not the page under it.
|
||||
- A reload during a Plex binge reopens the episode playing now, not the one it started from.
|
||||
|
||||
## 0.112.1 — 2026-10-27
|
||||
|
||||
### Fixed
|
||||
|
||||
- Security: the sign-in library is updated, closing two published vulnerabilities.
|
||||
|
||||
## 0.112.0 — 2026-10-25
|
||||
|
||||
### New
|
||||
|
||||
- Player: a Related tab lists videos related to the one playing, leaving out what you have already watched (your uploaded YouTube history included). Channels you follow are marked, and you can switch between On topic and Trending.
|
||||
- Play a related video in place; Back returns to the one you opened. Admins set a daily per-user limit in Config › Quota (default 200, 0 turns it off).
|
||||
- Side panel: the list controls and the watched toggle are glyphs on one line, and Auto and Loop show when they are on, also under the pointer.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Live search: a search that never reached YouTube no longer uses up a daily slot, a busy moment says so after a few seconds instead of waiting on, and a first page that failed offers Retry.
|
||||
- Menus: Play from the beginning wears the same ↺ glyph everywhere, and Reset its own eraser glyph.
|
||||
- On the day of this update, API searches made earlier that day stop counting toward the daily search limit, until Pacific midnight.
|
||||
|
||||
## 0.111.0 — 2026-10-24
|
||||
|
||||
### New
|
||||
|
||||
- Channels › Discover from your history: the channels your uploaded YouTube history shows you watching often (five videos of five minutes or more) but not following.
|
||||
- Follow one, put it out of the list (with Undo), or open the videos you watched there and play them one by one or all in a row.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A channel someone explored and then followed on YouTube is now part of the shared Library like any followed channel, and so are its videos; before, they could stay hidden and their watched marks never applied.
|
||||
|
||||
## 0.110.0 — 2026-10-23
|
||||
|
||||
### New
|
||||
|
||||
@@ -115,6 +115,7 @@ CQRS, a repository/DI framework, a router library, a generic CRUD-router factory
|
||||
| FE keyboard shortcut | a row in `lib/keymap.ts` + `dispatch()` | a private `keydown` listener with its own key literals |
|
||||
| FE list/grid keys | `NavGrid`/`keyboardNav` + `navItemAttrs` + `data-nav-open` | a private arrow-key / roving-tabindex handler |
|
||||
| FE view push (history) | `rememberNavPosition()` right before `history.pushState` | a push that forgets: Back strands focus on `<body>` |
|
||||
| FE view state | the module's URL codec: its keys in `urlKeys` (`module.ts`), read and written by `lib/<id>UrlState.ts` through `useUrlMirror` (contract-held, `e2e/bookmark.spec.ts`) | `useState` / sessionStorage alone: a reload, a bookmark or a shared link loses the view |
|
||||
| FE a page's header content | the page renders it into the floating header itself (`PageHeader`, `ui/PageShell`) | a `page === …` branch in the shell's header, or a bridge carrying a page's state up to it |
|
||||
| FE module store | its definition's `Store` (`module.ts`), mounted at the root by `ModuleStores`; it reads no other module's store (contract-held) | a provider hand-nested in `main.tsx` |
|
||||
| FE saved views | the module's own store from `features/filters` (`createSavedViewsStore` + `useSavedViewsStore`) | one store switched by the active page — every visit elsewhere reset it |
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""A watched Takeout video's length, and the channels a user put out of their list
|
||||
|
||||
Revision ID: 0115_takeout_channels
|
||||
Revises: 0114_video_unmarks
|
||||
Create Date: 2026-10-24
|
||||
|
||||
The "channels you watch but do not follow" list counts a user's watched videos over five minutes
|
||||
by channel. The length is asked of YouTube for that list and kept on the Takeout row; a channel the
|
||||
user does not want on the list is kept apart.
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0115_takeout_channels"
|
||||
down_revision: str | None = "0114_video_unmarks"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
"takeout_items", sa.Column("looked_up_at", sa.DateTime(timezone=True), nullable=True)
|
||||
)
|
||||
op.add_column("takeout_items", sa.Column("duration_seconds", sa.Integer(), nullable=True))
|
||||
op.create_table(
|
||||
"takeout_channel_dismissals",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column(
|
||||
"user_id",
|
||||
sa.Integer(),
|
||||
sa.ForeignKey("users.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("channel_id", sa.String(32), nullable=False),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.func.now(),
|
||||
nullable=False,
|
||||
),
|
||||
sa.UniqueConstraint("user_id", "channel_id", name="uq_takeout_channel_dismissal"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("takeout_channel_dismissals")
|
||||
op.drop_column("takeout_items", "duration_seconds")
|
||||
op.drop_column("takeout_items", "looked_up_at")
|
||||
@@ -0,0 +1,34 @@
|
||||
"""An explored channel someone follows is the catalog's own, and so are its videos
|
||||
|
||||
Revision ID: 0116_followed_explored_channels
|
||||
Revises: 0115_takeout_channels
|
||||
Create Date: 2026-10-24
|
||||
|
||||
A follow pulled in from YouTube (the subscription import) left an explored channel flagged as an
|
||||
exploration's, and a subscribe landing while an exploration's videos came in left those videos
|
||||
flagged on a channel that no longer was one. Both are held in the code now; this clears what they
|
||||
left: the channel of a subscription is not an exploration's, and no video is an exploration's on a
|
||||
channel that is not one. Data only, so the downgrade has nothing to undo.
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0116_followed_explored_channels"
|
||||
down_revision: str | None = "0115_takeout_channels"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(
|
||||
"UPDATE channels SET from_explore = false WHERE from_explore"
|
||||
" AND EXISTS (SELECT 1 FROM subscriptions s WHERE s.channel_id = channels.id)"
|
||||
)
|
||||
op.execute(
|
||||
"UPDATE videos SET via_explore = false WHERE via_explore"
|
||||
" AND channel_id IN (SELECT id FROM channels WHERE NOT from_explore)"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -71,10 +71,12 @@ class Channel(Base, TimestampMixin):
|
||||
Boolean, default=False, server_default="false", index=True
|
||||
)
|
||||
# True when this channel exists only because a user EXPLORED it (opened its page without
|
||||
# subscribing) — an ephemeral, per-explorer addition. The cleanup job hard-deletes such a
|
||||
# channel (and its via_explore videos) once nobody keeps it (no subscription, no live
|
||||
# ExploredChannel row, no per-user state) after a grace period. Cleared when someone
|
||||
# subscribes (the "keep" signal promotes it to organic).
|
||||
# subscribing) — an ephemeral, per-explorer addition. After a grace period the cleanup job
|
||||
# hard-deletes its via_explore videos nobody keeps (no subscription, no live ExploredChannel
|
||||
# row, no per-user state), and then the channel row itself once it holds no videos — unless a
|
||||
# Takeout watch history shows it watched: the "watched but not followed" list names it from
|
||||
# that row. Cleared when someone subscribes, here or on YouTube (the "keep" signal promotes it
|
||||
# to organic).
|
||||
from_explore: Mapped[bool] = mapped_column(
|
||||
Boolean, default=False, server_default="false", index=True
|
||||
)
|
||||
@@ -235,8 +237,9 @@ class ExploredChannel(Base, TimestampMixin):
|
||||
Exploring an un-subscribed channel ingests its recent uploads (flagged via_explore) so the
|
||||
user can browse them, but keeps them out of everyone else's catalog. This row (a) gates the
|
||||
explorer's access to those ephemeral videos in the feed query and (b) drives the grace-period
|
||||
purge: a from_explore channel with no live ExploredChannel row (and no subscription / no
|
||||
per-user state on its videos) is hard-deleted by the cleanup job. Subscribing is the "keep"
|
||||
purge: of a from_explore channel with no live ExploredChannel row (and no subscription) the
|
||||
cleanup job hard-deletes the videos without per-user state, then the channel once it holds none
|
||||
and no Takeout watch history shows it watched. Subscribing is the "keep"
|
||||
signal — it promotes the channel to organic and these rows become irrelevant. `created_at`
|
||||
(from TimestampMixin) is the grace clock; a re-visit refreshes it."""
|
||||
|
||||
|
||||
@@ -158,6 +158,19 @@ def blocked_ids(db: Session, user: User) -> set[str]:
|
||||
)
|
||||
|
||||
|
||||
def followed_among(db: Session, user: User, channel_ids: set[str]) -> set[str]:
|
||||
"""Which of these channels the user subscribes to."""
|
||||
if not channel_ids:
|
||||
return set()
|
||||
return set(
|
||||
db.scalars(
|
||||
select(Subscription.channel_id).where(
|
||||
owned_by(Subscription.user_id, user), Subscription.channel_id.in_(channel_ids)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def blocked_channels(db: Session, user: User, lang: str) -> list[Channel]:
|
||||
return list(
|
||||
db.execute(
|
||||
|
||||
@@ -75,7 +75,8 @@ def ingest_candidates(
|
||||
) -> list[str]:
|
||||
"""Materialise one page of search candidates into the catalog (channel stubs + enrich,
|
||||
video stubs flagged via_search, enrich, Shorts classification) and return the KEEPABLE
|
||||
video ids — non-Short, non-live — in the input relevance order."""
|
||||
video ids — non-Short, non-live — in the input relevance order. A videos.list that fails
|
||||
raises its YouTubeError: with nothing enriched, nothing could be kept."""
|
||||
ids = [it["id"] for it in candidates]
|
||||
if not ids:
|
||||
return []
|
||||
@@ -132,13 +133,16 @@ def ingest_candidates(
|
||||
with quota.attribute(user.id, quota.QuotaAction.VIDEOS_ENRICH):
|
||||
detail_by_id = {it["id"]: it for it in yt.get_videos(ids)}
|
||||
except YouTubeError:
|
||||
# Every candidate then stays unenriched, and an unenriched video cannot be judged live or
|
||||
# Short — so it is dropped. A working search returns nothing and reads as "no results".
|
||||
# An unenriched video cannot be judged live or Short, so none of this page could be kept:
|
||||
# swallowed, the failure answered as a page with nothing on it — "no results" for a search
|
||||
# that never ran (the shared budget spent, no API key). The stubs stay (`insert_stubs`
|
||||
# committed them), as the channels' do above; the caller answers the failure (its refusal
|
||||
# says which).
|
||||
log.warning(
|
||||
"the videos found by a search could not be enriched",
|
||||
extra=logs.event("search.video_enrich_failed", candidates=len(ids)),
|
||||
)
|
||||
detail_by_id = {}
|
||||
raise
|
||||
enriched_at = datetime.now(
|
||||
timezone.utc
|
||||
) # when THIS enrich ran (distinct from the stub placeholder)
|
||||
@@ -212,17 +216,25 @@ def clear(db: Session, user: User, video_ids: list[str]) -> int:
|
||||
"""Discard these results "as if never added": drop this user's finds of them, then delete the
|
||||
ones nobody kept — a `via_search` video no reader holds (`reader.queries.kept_by_a_reader`),
|
||||
whose channel nobody subscribes to, and that no other user still has as a find. Returns how
|
||||
many videos went."""
|
||||
db.execute(
|
||||
delete(SearchFind).where(
|
||||
owned_by(SearchFind.user_id, user), SearchFind.video_id.in_(video_ids)
|
||||
many videos went.
|
||||
|
||||
Only the ones this user found: a video in the catalog with no find at all (a related list's,
|
||||
which records none) is in someone's list right now, and an id any user could name would let
|
||||
them delete it from under that list."""
|
||||
mine = list(
|
||||
db.scalars(
|
||||
delete(SearchFind)
|
||||
.where(owned_by(SearchFind.user_id, user), SearchFind.video_id.in_(video_ids))
|
||||
.returning(SearchFind.video_id)
|
||||
)
|
||||
)
|
||||
if not mine:
|
||||
return 0
|
||||
subscribed = select(Subscription.id).where(Subscription.channel_id == Video.channel_id).exists()
|
||||
other_find = select(SearchFind.id).where(SearchFind.video_id == Video.id).exists()
|
||||
result = db.execute(
|
||||
delete(Video).where(
|
||||
Video.id.in_(video_ids),
|
||||
Video.id.in_(mine),
|
||||
Video.via_search.is_(True),
|
||||
~reader_queries.kept_by_a_reader(Video.id),
|
||||
~subscribed,
|
||||
|
||||
@@ -96,13 +96,24 @@ def record_subscription(db: Session, user: User, channel: Channel, yt_subscripti
|
||||
subscribed_at=datetime.now(timezone.utc),
|
||||
)
|
||||
)
|
||||
if channel.from_explore:
|
||||
channel.from_explore = False
|
||||
db.execute(
|
||||
update(Video)
|
||||
.where(Video.channel_id == channel.id, Video.via_explore.is_(True))
|
||||
.values(via_explore=False)
|
||||
)
|
||||
db.flush()
|
||||
settle_explored(db, channel)
|
||||
|
||||
|
||||
def settle_explored(db: Session, channel: Channel) -> None:
|
||||
"""Hold the rule that a channel's videos are an exploration's only while nobody follows it,
|
||||
decided by who follows it now, not by the flag held in memory: a subscribe in another request
|
||||
may have cleared that while YouTube answered this one, and the videos that came in meanwhile
|
||||
would stay flagged. A channel someone follows, however the follow came (here or pulled in from
|
||||
YouTube), is the catalog's own, and so are its videos."""
|
||||
if channel.from_explore and not queries.followed(db, channel.id):
|
||||
return
|
||||
channel.from_explore = False
|
||||
db.execute(
|
||||
update(Video)
|
||||
.where(Video.channel_id == channel.id, Video.via_explore.is_(True))
|
||||
.values(via_explore=False)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
|
||||
|
||||
@@ -113,6 +113,11 @@ class Settings(BaseSettings):
|
||||
# each search.list costs 100 units, so the shared budget only affords ~80-90/day total; with
|
||||
# the zero-quota scrape source it's a pure anti-abuse rate limit. Admin-tunable.
|
||||
search_daily_limit_per_user: int = 70
|
||||
# Per-user cap on related-video requests per day — a list opened and each "Show more" (the
|
||||
# InnerTube watch page, no quota; its enrich is up to ~8 units: up to 4 pages, each a videos.list
|
||||
# and a channels.list). A failed one gives its slot back. 0 turns related videos off.
|
||||
# Admin-tunable.
|
||||
related_daily_limit_per_user: int = 200
|
||||
# Source for live YouTube search: "scrape" (InnerTube, no API quota) or "api" (search.list,
|
||||
# 100 units/page). Scrape is the default; flip to "api" if scraping is blocked/breaks.
|
||||
search_source: SearchSource = "scrape"
|
||||
|
||||
+31
-13
@@ -44,6 +44,7 @@ class QuotaAction:
|
||||
VIDEOS_ENRICH = "videos_enrich"
|
||||
VIDEOS_LOOKUP = "videos_lookup"
|
||||
VIDEOS_SEARCH = "videos_search"
|
||||
VIDEOS_RELATED = "videos_related"
|
||||
CHANNELS_DISCOVER = "channels_discover"
|
||||
CHANNELS_EXPLORE = "channels_explore"
|
||||
CHANNELS_SUBSCRIBE = "channels_subscribe"
|
||||
@@ -142,7 +143,7 @@ def backfill_reserve_reached() -> bool:
|
||||
condition for every backfill/explore path (recent, deep, immediate full-history, explore, and
|
||||
rolling revalidation).
|
||||
|
||||
Reads in its OWN short-lived session (like record_usage / log_action), for two reasons: it
|
||||
Reads in its OWN short-lived session (like record_usage / claim_action), for two reasons: it
|
||||
replaces the remaining/reserve comparison that was open-coded at every call site, and — critically
|
||||
for the per-page guards in paging loops — a guard must not hold the caller's transaction open
|
||||
across the network fetch that follows it. Quota is committed independently of any caller, so a
|
||||
@@ -151,24 +152,40 @@ def backfill_reserve_reached() -> bool:
|
||||
return remaining_today(qs) <= sysconfig.get_int(qs, "backfill_quota_reserve")
|
||||
|
||||
|
||||
def log_action(user_id: int, action: str) -> None:
|
||||
"""Record a zero-cost action event so per-user daily caps still count it.
|
||||
def claim_action(user_id: int, action: str, limit: int) -> int | None:
|
||||
"""Take one of this user's `limit` daily `action` slots, or None when they are all taken — the
|
||||
check and the take in one transaction, under a lock per user and action. Checked first and
|
||||
logged after the work, N requests sent together at the last free slot all passed the check
|
||||
(the work in between is seconds of scraping). Returns the event's id, for `refund_action` when
|
||||
the work then produced nothing.
|
||||
|
||||
`record_usage` only logs when units are actually charged; a scrape-based search spends no
|
||||
quota yet must still be rate-limited per user, so it logs its event here directly.
|
||||
|
||||
Writes in its OWN session (like record_usage) — quota accounting is durable independent of the
|
||||
caller's transaction and must never commit the caller's session (that would flush a job's
|
||||
partial state mid-run, defeating its own rollback)."""
|
||||
The ONE way to count a capped action: a claim is a zero-unit event, and `actions_today` counts
|
||||
those alone, so a call the action then pays for (search.list's own `record_usage` event, under
|
||||
the same action) is accounting, never a second slot. Own session, committed at once — quota
|
||||
accounting is durable whatever the caller's transaction does next, and must never commit it."""
|
||||
with SessionLocal() as qs:
|
||||
qs.add(QuotaEvent(user_id=user_id, action=action, units=0))
|
||||
qs.execute(select(func.pg_advisory_xact_lock(func.hashtext(action), user_id)))
|
||||
if actions_today(qs, user_id, action) >= limit:
|
||||
return None
|
||||
event = QuotaEvent(user_id=user_id, action=action, units=0)
|
||||
qs.add(event)
|
||||
qs.commit()
|
||||
return event.id
|
||||
|
||||
|
||||
def refund_action(event_id: int) -> None:
|
||||
"""Give a slot `claim_action` took back: the work it was taken for failed outright, and a
|
||||
request that showed the user nothing must not count against them."""
|
||||
with SessionLocal() as qs:
|
||||
qs.execute(delete(QuotaEvent).where(QuotaEvent.id == event_id))
|
||||
qs.commit()
|
||||
|
||||
|
||||
def actions_today(db: Session, user_id: int, action: str) -> int:
|
||||
"""How many quota events of `action` this user has logged so far in the current Pacific
|
||||
day — for per-user, per-action daily caps (e.g. the live-search limit). Counts events,
|
||||
not units, so it only works for actions charged exactly once per user action."""
|
||||
"""How many slots of `action` this user has claimed so far in the current Pacific day — for
|
||||
per-user, per-action daily caps (the live search, the related lists). Counts the zero-unit
|
||||
claim events (`claim_action`) only: `record_usage`'s events for units the action spent are not
|
||||
slots (it logs only when units were charged)."""
|
||||
return (
|
||||
db.scalar(
|
||||
select(func.count())
|
||||
@@ -176,6 +193,7 @@ def actions_today(db: Session, user_id: int, action: str) -> int:
|
||||
.where(
|
||||
owned_by(QuotaEvent.user_id, user_id),
|
||||
QuotaEvent.action == action,
|
||||
QuotaEvent.units == 0,
|
||||
QuotaEvent.created_at >= pacific_day_start_utc(),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -254,8 +254,9 @@ class TakeoutItem(Base, TimestampMixin):
|
||||
"""One video from a user's Google Takeout export: watched (with when) or in their YouTube Watch
|
||||
later list (with when it was added). The rows are both the import job's input and its memory: a
|
||||
video the catalog does not know yet waits here, with no outcome, until it enters the catalog.
|
||||
The id is not a foreign key for that reason. The channel is kept for a later "channels you
|
||||
watch but do not follow" list."""
|
||||
The id is not a foreign key for that reason. A watched row's channel and length feed the
|
||||
"channels you watch but do not follow" list: the length is asked of YouTube for that list alone
|
||||
and kept here, so its videos need not enter the shared catalog to be counted."""
|
||||
|
||||
__tablename__ = "takeout_items"
|
||||
__table_args__ = (
|
||||
@@ -277,3 +278,21 @@ class TakeoutItem(Base, TimestampMixin):
|
||||
# Watched: the last time in the export; Watch later: when it was added.
|
||||
at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
outcome: Mapped[str | None] = mapped_column(String(12))
|
||||
# When YouTube was asked for the video's length (NULL = not yet), and the length it gave; a
|
||||
# video it no longer has keeps a NULL length.
|
||||
looked_up_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
duration_seconds: Mapped[int | None] = mapped_column(Integer)
|
||||
|
||||
|
||||
class TakeoutChannelDismissal(Base, TimestampMixin):
|
||||
"""A channel the user put out of their "watched but not followed" list. The id is not a foreign
|
||||
key: the channel may never have entered the catalog, or may leave it, and the choice stays."""
|
||||
|
||||
__tablename__ = "takeout_channel_dismissals"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("user_id", "channel_id", name="uq_takeout_channel_dismissal"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
channel_id: Mapped[str] = mapped_column(String(32))
|
||||
|
||||
@@ -16,13 +16,14 @@ from sqlalchemy.orm import InstrumentedAttribute, Session, aliased
|
||||
from app.collation import collated
|
||||
from app.feedquery import feed_columns, serialize
|
||||
from app.models import User
|
||||
from app.catalog.models import Channel, Subscription, Video
|
||||
from app.catalog.models import BlockedChannel, Channel, Subscription, Video
|
||||
from app.reader.models import (
|
||||
ChannelTag,
|
||||
Playlist,
|
||||
PlaylistItem,
|
||||
SavedView,
|
||||
Tag,
|
||||
TakeoutChannelDismissal,
|
||||
TakeoutItem,
|
||||
TakeoutKind,
|
||||
VideoState,
|
||||
@@ -243,6 +244,18 @@ def kept_by_a_reader(video_id: InstrumentedAttribute[str]) -> ColumnElement[bool
|
||||
)
|
||||
|
||||
|
||||
def in_a_watch_history(channel_id: InstrumentedAttribute[str]) -> ColumnElement[bool]:
|
||||
"""A channel someone's uploaded Takeout history shows watched. The "watched but not followed"
|
||||
list names a channel from its catalog row, so the explore cleanup keeps the row of one (its
|
||||
videos it may still reclaim: opening the list's videos brings them back). As a clause, so the
|
||||
cleanup's DELETE stays one statement."""
|
||||
return (
|
||||
select(TakeoutItem.id)
|
||||
.where(TakeoutItem.channel_id == channel_id, TakeoutItem.kind == TakeoutKind.WATCHED)
|
||||
.exists()
|
||||
)
|
||||
|
||||
|
||||
def playlisted_by(db: Session, video_ids: list[str]) -> list[tuple[int, str]]:
|
||||
"""(user id, video id) for every user who has one of these videos in a playlist."""
|
||||
return list(
|
||||
@@ -306,6 +319,36 @@ def held_by(db: Session, user: User, video_ids: list[str]) -> set[str]:
|
||||
)
|
||||
|
||||
|
||||
def seen_by(db: Session, user: User, video_ids: list[str]) -> set[str]:
|
||||
"""Which of these videos the user has already seen or set aside: watched or hidden here, or in
|
||||
their uploaded Takeout history unless they took it back to "new" here since. The ids need not
|
||||
be in the catalog — a Takeout row names a video the catalog may never have had — so a list
|
||||
of what YouTube suggests can drop them before anything is ingested."""
|
||||
if not video_ids:
|
||||
return set()
|
||||
marked = select(VideoState.video_id).where(
|
||||
owned_by(VideoState.user_id, user),
|
||||
VideoState.video_id.in_(video_ids),
|
||||
VideoState.status.in_(("watched", "hidden")),
|
||||
)
|
||||
unmarked_since = (
|
||||
select(VideoUnmark.id)
|
||||
.where(
|
||||
owned_by(VideoUnmark.user_id, user),
|
||||
VideoUnmark.video_id == TakeoutItem.video_id,
|
||||
VideoUnmark.at > TakeoutItem.at,
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
in_history = select(TakeoutItem.video_id).where(
|
||||
owned_by(TakeoutItem.user_id, user),
|
||||
TakeoutItem.kind == TakeoutKind.WATCHED,
|
||||
TakeoutItem.video_id.in_(video_ids),
|
||||
~unmarked_since,
|
||||
)
|
||||
return set(db.scalars(marked)) | set(db.scalars(in_history))
|
||||
|
||||
|
||||
def feed_rows_by_ids(db: Session, user: User, video_ids: list[str]) -> list[dict]:
|
||||
"""These videos serialized with the feed's projection (their channel, this user's watch state,
|
||||
saved), in the order given."""
|
||||
@@ -533,3 +576,194 @@ def takeout_users_watch_later_waiting(db: Session) -> list[int]:
|
||||
.distinct()
|
||||
).scalars()
|
||||
)
|
||||
|
||||
|
||||
# --- channels watched but not followed ---------------------------------------------------------
|
||||
|
||||
# A channel joins the list with this many watched videos of at least this length. A Short is three
|
||||
# minutes at most, so the length alone keeps them out, and a video under five minutes says too
|
||||
# little of what a channel is about to count towards it.
|
||||
WATCHED_CHANNEL_MIN_VIDEOS = 5
|
||||
WATCHED_CHANNEL_MIN_SECONDS = 300
|
||||
|
||||
|
||||
def _unfollowed(user: User) -> ColumnElement[bool]:
|
||||
"""A watched row whose channel the user neither follows, blocked, put out of the list, nor is."""
|
||||
subscribed = select(Subscription.channel_id).where(owned_by(Subscription.user_id, user))
|
||||
blocked = select(BlockedChannel.channel_id).where(owned_by(BlockedChannel.user_id, user))
|
||||
dismissed = select(TakeoutChannelDismissal.channel_id).where(
|
||||
owned_by(TakeoutChannelDismissal.user_id, user)
|
||||
)
|
||||
clauses = [
|
||||
owned_by(TakeoutItem.user_id, user),
|
||||
TakeoutItem.kind == TakeoutKind.WATCHED,
|
||||
TakeoutItem.channel_id.is_not(None),
|
||||
TakeoutItem.channel_id.not_in(subscribed),
|
||||
TakeoutItem.channel_id.not_in(blocked),
|
||||
TakeoutItem.channel_id.not_in(dismissed),
|
||||
]
|
||||
if user.yt_channel_id:
|
||||
clauses.append(TakeoutItem.channel_id != user.yt_channel_id)
|
||||
return and_(*clauses)
|
||||
|
||||
|
||||
def _candidate_channels(user: User):
|
||||
"""The unfollowed channels with enough watched videos to make the list once their lengths are
|
||||
known: (channel id, how many watched)."""
|
||||
return (
|
||||
select(TakeoutItem.channel_id, func.count().label("watched"))
|
||||
.where(_unfollowed(user))
|
||||
.group_by(TakeoutItem.channel_id)
|
||||
.having(func.count() >= WATCHED_CHANNEL_MIN_VIDEOS)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
|
||||
def takeout_lengths_to_ask(db: Session, user: User) -> list[str]:
|
||||
"""The watched videos whose length the list still needs: those of the candidate channels not
|
||||
asked about yet, the most watched channels first, so a lookup cut short fills the top."""
|
||||
cand = _candidate_channels(user)
|
||||
return list(
|
||||
db.execute(
|
||||
select(TakeoutItem.video_id)
|
||||
.join(cand, cand.c.channel_id == TakeoutItem.channel_id)
|
||||
.where(_unfollowed(user), TakeoutItem.looked_up_at.is_(None))
|
||||
.order_by(cand.c.watched.desc(), TakeoutItem.channel_id, TakeoutItem.at.desc())
|
||||
).scalars()
|
||||
)
|
||||
|
||||
|
||||
def watched_channels_pending(db: Session, user: User) -> int:
|
||||
"""How many channels a later run may still add to the list: the candidates with a watched video
|
||||
whose length is not known, and the ones that made it but have no catalog row to be listed from
|
||||
yet. One the catalog holds without details is listed already (by the name it came in with), so
|
||||
it is not one to come."""
|
||||
cand = _candidate_channels(user)
|
||||
unasked = db.execute(
|
||||
select(TakeoutItem.channel_id)
|
||||
.join(cand, cand.c.channel_id == TakeoutItem.channel_id)
|
||||
.where(_unfollowed(user), TakeoutItem.looked_up_at.is_(None))
|
||||
.distinct()
|
||||
).scalars()
|
||||
counted = _counted_channels(user)
|
||||
unlisted = db.execute(
|
||||
select(counted.c.channel_id)
|
||||
.outerjoin(Channel, Channel.id == counted.c.channel_id)
|
||||
.where(Channel.id.is_(None))
|
||||
).scalars()
|
||||
return len(set(unasked) | set(unlisted))
|
||||
|
||||
|
||||
def _counted_channels(user: User):
|
||||
"""The channels that make the list by their counted videos, whatever the catalog holds of them."""
|
||||
return (
|
||||
select(TakeoutItem.channel_id)
|
||||
.where(_unfollowed(user), TakeoutItem.duration_seconds >= WATCHED_CHANNEL_MIN_SECONDS)
|
||||
.group_by(TakeoutItem.channel_id)
|
||||
.having(func.count() >= WATCHED_CHANNEL_MIN_VIDEOS)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
|
||||
def watched_channels_to_describe(db: Session, user: User) -> list[str]:
|
||||
"""The channels on the list (by their counted videos) that the catalog lacks or has no details
|
||||
of yet: what the list cannot name, or names with no more than a video brought."""
|
||||
counted = _counted_channels(user)
|
||||
return list(
|
||||
db.execute(
|
||||
select(counted.c.channel_id)
|
||||
.outerjoin(Channel, Channel.id == counted.c.channel_id)
|
||||
.where(Channel.details_synced_at.is_(None))
|
||||
).scalars()
|
||||
)
|
||||
|
||||
|
||||
def watched_channels(db: Session, user: User) -> list[tuple[Channel, int, datetime]]:
|
||||
"""The channels the user watched often but does not follow: (channel, how many of its videos
|
||||
over five minutes they watched, when last). Most watched first; on a tie the one watched more
|
||||
lately, which is the likelier interest."""
|
||||
n = func.count(TakeoutItem.id)
|
||||
last = func.max(TakeoutItem.at)
|
||||
return list(
|
||||
db.execute(
|
||||
select(Channel, n, last)
|
||||
.join(Channel, Channel.id == TakeoutItem.channel_id)
|
||||
.where(_unfollowed(user), TakeoutItem.duration_seconds >= WATCHED_CHANNEL_MIN_SECONDS)
|
||||
.group_by(Channel.id)
|
||||
.having(n >= WATCHED_CHANNEL_MIN_VIDEOS)
|
||||
.order_by(n.desc(), last.desc(), Channel.id)
|
||||
).tuples()
|
||||
)
|
||||
|
||||
|
||||
def has_watch_history(db: Session, user: User) -> bool:
|
||||
"""Whether the user has uploaded a Takeout watch history at all."""
|
||||
return bool(
|
||||
db.scalar(
|
||||
select(
|
||||
select(TakeoutItem.id)
|
||||
.where(owned_by(TakeoutItem.user_id, user), TakeoutItem.kind == TakeoutKind.WATCHED)
|
||||
.exists()
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def watched_in_history(db: Session, user: User, channel_id: str) -> bool:
|
||||
"""Whether the user's Takeout history shows them watching this channel at all."""
|
||||
return bool(
|
||||
db.scalar(
|
||||
select(
|
||||
select(TakeoutItem.id)
|
||||
.where(
|
||||
owned_by(TakeoutItem.user_id, user),
|
||||
TakeoutItem.kind == TakeoutKind.WATCHED,
|
||||
TakeoutItem.channel_id == channel_id,
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def watched_channel_videos(
|
||||
db: Session, user: User, channel_id: str
|
||||
) -> tuple[list[tuple[str, datetime]], int]:
|
||||
"""The user's watched videos of one channel that the list counts, last watched first: (video
|
||||
id, when). And how many YouTube no longer has."""
|
||||
rows = db.execute(
|
||||
select(TakeoutItem.video_id, TakeoutItem.at, TakeoutItem.duration_seconds)
|
||||
.where(
|
||||
owned_by(TakeoutItem.user_id, user),
|
||||
TakeoutItem.kind == TakeoutKind.WATCHED,
|
||||
TakeoutItem.channel_id == channel_id,
|
||||
TakeoutItem.looked_up_at.is_not(None),
|
||||
)
|
||||
.order_by(TakeoutItem.at.desc(), TakeoutItem.video_id)
|
||||
).tuples()
|
||||
counted: list[tuple[str, datetime]] = []
|
||||
gone = 0
|
||||
for vid, at, seconds in rows:
|
||||
if seconds is None:
|
||||
gone += 1
|
||||
elif seconds >= WATCHED_CHANNEL_MIN_SECONDS:
|
||||
counted.append((vid, at))
|
||||
return counted, gone
|
||||
|
||||
|
||||
def takeout_users_with_list_work(db: Session) -> list[int]:
|
||||
"""Every user whose "watched but not followed" list a run can still add to: lengths to ask, or
|
||||
channels to name. Asked of each user whose history holds a channel of enough watched videos,
|
||||
since what is off a list (followed, blocked, put out, their own) is that user's own — a row of
|
||||
one is never asked about, and would otherwise bring the user back on every run."""
|
||||
per_channel = (
|
||||
select(TakeoutItem.user_id)
|
||||
.where(TakeoutItem.kind == TakeoutKind.WATCHED, TakeoutItem.channel_id.is_not(None))
|
||||
.group_by(TakeoutItem.user_id, TakeoutItem.channel_id)
|
||||
.having(func.count() >= WATCHED_CHANNEL_MIN_VIDEOS)
|
||||
.subquery()
|
||||
)
|
||||
users = db.execute(
|
||||
select(User).where(User.id.in_(select(per_channel.c.user_id))).order_by(User.id)
|
||||
).scalars()
|
||||
return [user.id for user in users if watched_channels_pending(db, user)]
|
||||
|
||||
@@ -9,7 +9,9 @@ unique key, a row lock taken before a presence check. The comfort shelf's writes
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import exists, func, select, text, update
|
||||
from typing import cast
|
||||
|
||||
from sqlalchemy import Table, bindparam, delete, exists, func, select, text, update
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -21,6 +23,7 @@ from app.reader.models import (
|
||||
PlaylistItem,
|
||||
SavedView,
|
||||
Tag,
|
||||
TakeoutChannelDismissal,
|
||||
TakeoutItem,
|
||||
TakeoutKind,
|
||||
TakeoutOutcome,
|
||||
@@ -662,3 +665,51 @@ def apply_takeout_watch_later(
|
||||
"watch_later_present": len(done[TakeoutOutcome.PRESENT]),
|
||||
"watch_later_missing": len(done[TakeoutOutcome.MISSING]),
|
||||
}
|
||||
|
||||
|
||||
# --- channels watched but not followed ---------------------------------------------------------
|
||||
|
||||
|
||||
def record_takeout_lengths(
|
||||
db: Session, user: User, asked: list[str], lengths: dict[str, int | None]
|
||||
) -> None:
|
||||
"""Keep what YouTube said of the user's watched videos `asked` about: each one's length, or none
|
||||
for a video it no longer has (`lengths` leaves it out). Every asked row is marked asked, so a
|
||||
video YouTube lost is not asked about again."""
|
||||
if not asked:
|
||||
return
|
||||
lock_takeout(db, user) # these rows are an upload's to update too
|
||||
now = datetime.now(timezone.utc)
|
||||
table = cast(Table, TakeoutItem.__table__)
|
||||
db.execute(
|
||||
table.update()
|
||||
.where(
|
||||
owned_by(TakeoutItem.user_id, user),
|
||||
table.c.kind == TakeoutKind.WATCHED,
|
||||
table.c.video_id == bindparam("vid"),
|
||||
)
|
||||
.values(looked_up_at=now, duration_seconds=bindparam("seconds")),
|
||||
[{"vid": vid, "seconds": lengths.get(vid)} for vid in asked],
|
||||
)
|
||||
db.flush()
|
||||
|
||||
|
||||
def dismiss_watched_channel(db: Session, user: User, channel_id: str) -> None:
|
||||
"""Put a channel out of the user's "watched but not followed" list (again is a no-op)."""
|
||||
db.execute(
|
||||
pg_insert(TakeoutChannelDismissal)
|
||||
.values(user_id=user.id, channel_id=channel_id)
|
||||
.on_conflict_do_nothing(constraint="uq_takeout_channel_dismissal")
|
||||
)
|
||||
db.flush()
|
||||
|
||||
|
||||
def restore_watched_channel(db: Session, user: User, channel_id: str) -> None:
|
||||
"""Let a channel the user put out of the list back on it."""
|
||||
db.execute(
|
||||
delete(TakeoutChannelDismissal).where(
|
||||
owned_by(TakeoutChannelDismissal.user_id, user),
|
||||
TakeoutChannelDismissal.channel_id == channel_id,
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
@@ -4,7 +4,9 @@ only way in.
|
||||
|
||||
Two files of the export are read, each uploaded on its own: `history/watch-history.json` and
|
||||
`playlists/Watch later-videos.csv`. Their videos are kept (`TakeoutItem`) and the import job applies
|
||||
what it can; a video the catalog does not know yet waits for it.
|
||||
what it can; a video the catalog does not know yet waits for it. The watched videos' channels also
|
||||
make the list of channels the user watches but does not follow (`queries.watched_channels`): the
|
||||
job asks YouTube how long those videos are, and what the channels are, for it.
|
||||
|
||||
The format, measured on a real export (2026-10): the history is a JSON list, one entry per view,
|
||||
newest first. A view of a video has a `titleUrl` with `watch?v=<id>` (on www.youtube.com or
|
||||
@@ -37,8 +39,9 @@ from app.ratelimit import RateLimiter
|
||||
from app.reader import queries, service
|
||||
from app.reader.models import TakeoutKind
|
||||
from app.sync.runner import get_service_user
|
||||
from app.sync.videos import ensure_videos
|
||||
from app.youtube.client import YouTubeClient
|
||||
from app.sync.subscriptions import describe_channels
|
||||
from app.sync.videos import ensure_videos, parse_iso8601_duration
|
||||
from app.youtube.client import YouTubeClient, YouTubeError
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
@@ -317,8 +320,15 @@ def stage(db: Session, user: User, parsed: Parsed) -> None:
|
||||
|
||||
|
||||
# How many unknown Watch later videos one user may have looked up on the shared API budget in a day:
|
||||
# two full Watch later lists (two units a hundred ids). The rest wait for the next day's runs.
|
||||
# two full Watch later lists (two units a hundred ids). The rest wait for the next day's runs. Both
|
||||
# shares pace the work, they do not bound its cost: they are held in memory, so a restart starts
|
||||
# them afresh, which only brings the rest forward — every video is asked about once (a looked-up
|
||||
# row is marked), and `quota.backfill_reserve_reached` still guards the shared budget.
|
||||
_lookups = RateLimiter(max_events=2 * WATCH_LATER_MAX, window_seconds=24 * 3600)
|
||||
# How many watched videos' lengths one user may ask about in a day for the "watched but not followed"
|
||||
# list (a unit a fifty). A share of its own: a large history asks for thousands, and on the Watch
|
||||
# later share it would leave the export's Watch later file waiting a day behind it.
|
||||
_lengths = RateLimiter(max_events=2 * WATCH_LATER_MAX, window_seconds=24 * 3600)
|
||||
|
||||
|
||||
def _put_in_watch_later(db: Session, user: User) -> dict:
|
||||
@@ -351,10 +361,79 @@ def _put_in_watch_later(db: Session, user: User) -> dict:
|
||||
return service.apply_takeout_watch_later(db, user, waiting, asked)
|
||||
|
||||
|
||||
def _ask_lengths(db: Session, user: User) -> dict:
|
||||
"""Ask YouTube how long the user's watched videos are that the "watched but not followed" list
|
||||
still needs, and keep the answer — on the same terms as the Watch later lookups, on a daily
|
||||
share of its own. What is not asked yet (no YouTube-connected account, the reserve reached, the
|
||||
share spent) waits for a later run, and the list says it is not complete. A YouTube failure is
|
||||
logged and left for a later run too: it is no reason to fail the import it follows. The caller
|
||||
commits."""
|
||||
ask = queries.takeout_lengths_to_ask(db, user)
|
||||
fetcher = get_service_user(db) if ask else None
|
||||
if fetcher is None or quota.backfill_reserve_reached():
|
||||
return {}
|
||||
ask = ask[: int(_lengths.room(str(user.id)))]
|
||||
if not ask:
|
||||
return {}
|
||||
try:
|
||||
with quota.attribute(user.id, quota.QuotaAction.VIDEOS_LOOKUP):
|
||||
with YouTubeClient(db, fetcher) as yt:
|
||||
items = yt.get_videos(ask)
|
||||
except YouTubeError as exc:
|
||||
log.warning(
|
||||
"Takeout: asking the watched videos' lengths failed: %s",
|
||||
exc,
|
||||
extra=logs.event("takeout.lengths.failed", user_id=user.id, reason=exc.reason),
|
||||
)
|
||||
return {}
|
||||
_lengths.allow(str(user.id), cost=len(ask))
|
||||
lengths = {
|
||||
it["id"]: parse_iso8601_duration(it.get("contentDetails", {}).get("duration"))
|
||||
for it in items
|
||||
if it.get("id")
|
||||
}
|
||||
service.record_takeout_lengths(db, user, ask, lengths)
|
||||
return {"lengths_asked": len(ask)}
|
||||
|
||||
|
||||
def _describe_channels(db: Session, user: User) -> dict:
|
||||
"""Bring the channels the user's list holds into the catalog with their details (name, picture,
|
||||
description), the ones it lacks: without them the list cannot show a channel. A YouTube failure
|
||||
is logged and left for a later run. The caller commits."""
|
||||
need = queries.watched_channels_to_describe(db, user)
|
||||
fetcher = get_service_user(db) if need else None
|
||||
if fetcher is None or quota.backfill_reserve_reached():
|
||||
return {}
|
||||
try:
|
||||
with quota.attribute(user.id, quota.QuotaAction.CHANNELS_DISCOVER):
|
||||
with YouTubeClient(db, fetcher) as yt:
|
||||
describe_channels(db, yt, need)
|
||||
except YouTubeError as exc:
|
||||
db.rollback()
|
||||
log.warning(
|
||||
"Takeout: describing the watched channels failed: %s",
|
||||
exc,
|
||||
extra=logs.event("takeout.channels.failed", user_id=user.id, reason=exc.reason),
|
||||
)
|
||||
return {}
|
||||
return {"channels_described": len(need)}
|
||||
|
||||
|
||||
def _channel_list(db: Session, user: User) -> dict:
|
||||
"""The "watched but not followed" list's part of a run: the lengths, landed, then the channels.
|
||||
Commits each."""
|
||||
result = _ask_lengths(db, user)
|
||||
db.commit()
|
||||
result |= _describe_channels(db, user)
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
def run_import(user_id: int) -> dict:
|
||||
"""The import job: apply what the user's kept Takeout rows can say now, as one recorded run.
|
||||
The watched part commits before the Watch later part asks YouTube for the videos the catalog
|
||||
lacks, so a YouTube failure there loses nothing already marked. Returns the counts."""
|
||||
lacks, so a YouTube failure there loses nothing already marked; the "watched but not followed"
|
||||
list's lookups come last. Returns the counts."""
|
||||
with _one_import(user_id), SessionLocal() as db:
|
||||
user = db.get(User, user_id)
|
||||
if user is None:
|
||||
@@ -363,6 +442,7 @@ def run_import(user_id: int) -> dict:
|
||||
db.commit()
|
||||
result |= _put_in_watch_later(db, user)
|
||||
db.commit()
|
||||
result |= _channel_list(db, user)
|
||||
outcomes = queries.takeout_outcomes(db, user)
|
||||
result["waiting"] = outcomes.get((TakeoutKind.WATCHED, None), 0)
|
||||
if outcomes.get((TakeoutKind.WATCH_LATER, None)):
|
||||
@@ -373,13 +453,15 @@ def run_import(user_id: int) -> dict:
|
||||
def apply_waiting(db: Session) -> dict:
|
||||
"""Settle what every user's import left waiting and can be settled now, one commit each: a
|
||||
watched video the catalog has come to know and the Shorts probe has cleared (by its job or a
|
||||
search's), and the Watch later videos a run could not put in yet. Run after each run of the
|
||||
search's), the Watch later videos a run could not put in yet, and what the "watched but not
|
||||
followed" list still needs asked of YouTube. Run after each run of the
|
||||
`shorts` job, which is what clears the most of them. Returns its counts, or an empty dict when
|
||||
nothing was waiting that could move."""
|
||||
marked = added = failed = 0
|
||||
marked = added = asked = failed = 0
|
||||
ready = set(queries.takeout_users_ready(db))
|
||||
later = set(queries.takeout_users_watch_later_waiting(db))
|
||||
for user_id in sorted(ready | later):
|
||||
lengths = set(queries.takeout_users_with_list_work(db))
|
||||
for user_id in sorted(ready | later | lengths):
|
||||
user = db.get(User, user_id)
|
||||
if user is None:
|
||||
continue
|
||||
@@ -393,6 +475,8 @@ def apply_waiting(db: Session) -> dict:
|
||||
if user_id in later:
|
||||
added += _put_in_watch_later(db, user).get("watch_later_added", 0)
|
||||
db.commit()
|
||||
if user_id in lengths:
|
||||
asked += _channel_list(db, user).get("lengths_asked", 0)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
failed += 1
|
||||
@@ -406,6 +490,8 @@ def apply_waiting(db: Session) -> dict:
|
||||
out["takeout_watched"] = marked
|
||||
if added:
|
||||
out["takeout_watch_later_added"] = added
|
||||
if asked:
|
||||
out["takeout_lengths_asked"] = asked
|
||||
if failed:
|
||||
out["takeout_failed"] = failed
|
||||
return out
|
||||
|
||||
@@ -307,9 +307,9 @@ def explore_channel(
|
||||
"""Open an un-subscribed channel for browsing. Records the exploration (a per-user,
|
||||
grace-clocked row that gates this user's access to the channel's ephemeral videos and
|
||||
drives the later cleanup), flags the channel ephemeral unless someone organically follows
|
||||
it, then ingests one page of its uploads (newest-first) marked via_explore + enriched.
|
||||
Returns the next page token so the page can "load more". Guarded against the shared
|
||||
backfill quota reserve."""
|
||||
it, then ingests one page of its uploads (newest-first), enriched — marked via_explore while
|
||||
nobody follows it. Returns the next page token so the page can "load more". Guarded against
|
||||
the shared backfill quota reserve."""
|
||||
channel = _channel_or_404(db, channel_id)
|
||||
if queries.is_blocked(db, user, channel_id):
|
||||
raise refused(403, "channel_blocked")
|
||||
|
||||
+116
-2
@@ -3,12 +3,13 @@ from collections.abc import AsyncIterator
|
||||
from datetime import date
|
||||
from functools import partial
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from fastapi import APIRouter, Depends, Path, Query, Request
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm.exc import StaleDataError
|
||||
|
||||
from app import jobruns, quota, scheduler
|
||||
from app.catalog import queries as catalog_queries, service as catalog_service
|
||||
from app.auth import current_user
|
||||
from app.db import get_db, release_read_connection
|
||||
from app.mailtext import lang_for_user
|
||||
@@ -24,7 +25,7 @@ from app.routes._common import (
|
||||
not_found,
|
||||
youtube_refusal,
|
||||
)
|
||||
from app.sync.videos import parse_iso8601_duration
|
||||
from app.sync.videos import ensure_videos, parse_iso8601_duration
|
||||
from app.utils import iso
|
||||
from app.youtube.client import YouTubeClient, YouTubeError
|
||||
from app.refusal import refused
|
||||
@@ -248,6 +249,21 @@ def set_video_progress(
|
||||
return {"ok": True, "video_id": video_id, "position_seconds": position}
|
||||
|
||||
|
||||
@router.get("/videos/{video_id}/row")
|
||||
def get_video_row(
|
||||
video_id: str = Path(max_length=32),
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""One catalog video as the feed lists it (its channel, this user's watch state and resume point,
|
||||
saved): what a player opened from an address starts from. The catalog only, so it costs nothing;
|
||||
every video a player can open (a list's row, a related one) is in it."""
|
||||
rows = queries.feed_rows_by_ids(db, user, [video_id])
|
||||
if not rows:
|
||||
raise not_found("video")
|
||||
return rows[0]
|
||||
|
||||
|
||||
@router.get("/videos/{video_id}")
|
||||
def get_video_detail(
|
||||
video_id: str,
|
||||
@@ -417,3 +433,101 @@ def takeout_status(user: User = Depends(current_user), db: Session = Depends(get
|
||||
},
|
||||
**queries.takeout_summary(db, user),
|
||||
}
|
||||
|
||||
|
||||
# --- channels watched but not followed -----------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/takeout/channels")
|
||||
def watched_channels(user: User = Depends(current_user), db: Session = Depends(get_db)) -> dict:
|
||||
"""The channels the user's Takeout history shows them watching often but not following: each
|
||||
with how many of its videos over five minutes they watched, and when last. `pending` is how many
|
||||
more channels may join once the import has asked YouTube for their videos' lengths or their
|
||||
names, so a list still being made does not read as the whole of it; `imported` tells "no history
|
||||
uploaded" from "nothing to suggest"."""
|
||||
return {
|
||||
"imported": queries.has_watch_history(db, user),
|
||||
"pending": queries.watched_channels_pending(db, user),
|
||||
"channels": [
|
||||
{
|
||||
"id": ch.id,
|
||||
"title": ch.title,
|
||||
"handle": ch.handle,
|
||||
"thumbnail_url": ch.thumbnail_url,
|
||||
"subscriber_count": ch.subscriber_count,
|
||||
"video_count": ch.video_count,
|
||||
"description": ch.description,
|
||||
"watched": int(n),
|
||||
"last_watched_at": iso(last),
|
||||
}
|
||||
for ch, n, last in queries.watched_channels(db, user)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/takeout/channels/{channel_id}/videos")
|
||||
def watched_channel_videos(
|
||||
channel_id: str, user: User = Depends(current_user), db: Session = Depends(get_db)
|
||||
) -> dict:
|
||||
"""The videos of a channel that the user's list counts, ready to play, last watched first. The
|
||||
channel is explored for the user (as its page does), and the videos the catalog lacks come in as
|
||||
the exploration's: the player needs them in the catalog, the shared Library does not get them,
|
||||
and the cleanup reclaims them once nobody keeps them. Of a channel someone follows they come in
|
||||
as the catalog's own, as its uploads do. `gone`: how many YouTube no longer has."""
|
||||
channel = catalog_queries.channel(db, channel_id)
|
||||
if channel is None:
|
||||
raise not_found("channel")
|
||||
if catalog_queries.is_blocked(db, user, channel_id):
|
||||
raise refused(403, "channel_blocked")
|
||||
counted, gone = queries.watched_channel_videos(db, user, channel_id)
|
||||
ids = [vid for vid, _ in counted]
|
||||
known = queries.known_video_ids(db, ids)
|
||||
missing = [vid for vid in ids if vid not in known]
|
||||
if missing and quota.backfill_reserve_reached():
|
||||
raise refused(429, "quota_reserve")
|
||||
catalog_service.explore(db, user, channel)
|
||||
db.commit()
|
||||
if missing:
|
||||
try:
|
||||
with (
|
||||
quota.attribute(user.id, quota.QuotaAction.CHANNELS_EXPLORE),
|
||||
YouTubeClient(db, user) as yt,
|
||||
):
|
||||
ensure_videos(db, yt, missing, explore=channel.from_explore)
|
||||
except YouTubeError as exc:
|
||||
raise youtube_refusal(exc) from exc
|
||||
catalog_service.settle_explored(db, channel)
|
||||
db.commit()
|
||||
items = queries.feed_rows_by_ids(db, user, ids)
|
||||
watched_at = dict(counted)
|
||||
for item in items:
|
||||
item["takeout_watched_at"] = iso(watched_at[item["id"]])
|
||||
# A video YouTube still had when its length was asked may have gone since.
|
||||
return {"ok": True, "items": items, "gone": gone + len(ids) - len(items)}
|
||||
|
||||
|
||||
@router.put("/takeout/channels/{channel_id}/dismissal")
|
||||
def dismiss_watched_channel(
|
||||
channel_id: str = Path(max_length=32),
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""Put a channel out of the user's list (it stays out until restored). Only one their own history
|
||||
shows them watching: a made-up id would only pile up rows every list read then has to skip."""
|
||||
if not queries.watched_in_history(db, user, channel_id):
|
||||
raise not_found("channel")
|
||||
service.dismiss_watched_channel(db, user, channel_id)
|
||||
db.commit()
|
||||
return {"ok": True, "channel_id": channel_id}
|
||||
|
||||
|
||||
@router.delete("/takeout/channels/{channel_id}/dismissal")
|
||||
def restore_watched_channel(
|
||||
channel_id: str = Path(max_length=32),
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""Let a channel the user put out of the list back on it."""
|
||||
service.restore_watched_channel(db, user, channel_id)
|
||||
db.commit()
|
||||
return {"ok": True, "channel_id": channel_id}
|
||||
|
||||
@@ -79,6 +79,10 @@ def get_me(
|
||||
# Which live-search source runs, so the search button can say what a search costs: "scrape"
|
||||
# spends no API quota, "api" spends 100 units a page.
|
||||
"search_source": sysconfig.get_str(db, "search_source"),
|
||||
# Whether live search and related videos are on: an admin turns either off with a daily
|
||||
# limit of 0, and the UI then leaves out what would only be refused.
|
||||
"search_enabled": sysconfig.get_int(db, "search_daily_limit_per_user") > 0,
|
||||
"related_enabled": sysconfig.get_int(db, "related_daily_limit_per_user") > 0,
|
||||
"can_read": has_read_scope(user),
|
||||
"can_write": has_write_scope(user),
|
||||
"pending_invites": pending_invites,
|
||||
|
||||
+303
-96
@@ -13,10 +13,18 @@ this search-discovered "noise" by default. Shorts and currently-live/upcoming vi
|
||||
ingested this way (Shorts are confirmed by the youtube.com/shorts probe; live/upcoming are
|
||||
dropped from the search response up front).
|
||||
|
||||
A video's related videos (`/related/{video_id}`, the list YouTube shows beside it) come in the same
|
||||
way: read from the website (`related_scrape`), ingested as search finds are, under their own daily
|
||||
cap — with what this user has already seen left out.
|
||||
|
||||
This is the HTTP side — the paging, the caps and the refusals; what a page of results leaves in the
|
||||
catalog is `catalog/search`."""
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, Path
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -26,8 +34,10 @@ from app.catalog import queries
|
||||
from app.catalog import search as catalog_search
|
||||
from app.db import get_db
|
||||
from app.models import User
|
||||
from app.ratelimit import RateLimiter
|
||||
from app.reader import queries as reader_queries
|
||||
from app.youtube import search_scrape
|
||||
from app.youtube import related_scrape, search_scrape
|
||||
from app.youtube.innertube import ScrapeError
|
||||
from app.youtube.client import YouTubeClient, YouTubeError
|
||||
from app.refusal import refused
|
||||
from app.routes._common import youtube_refusal
|
||||
@@ -37,6 +47,115 @@ router = APIRouter(prefix="/api/search", tags=["search"])
|
||||
|
||||
# search.list costs this many quota units per page.
|
||||
SEARCH_COST = 100
|
||||
# The scrape source reads at most this many pages for one search.
|
||||
SEARCH_MAX_PAGES = 12
|
||||
|
||||
# A related list is filled to this many unseen videos, reading at most this many pages (about 20
|
||||
# videos each, measured) — the ones the user has seen are left out, so a page alone can fall short.
|
||||
RELATED_TARGET = 20
|
||||
RELATED_MAX_PAGES = 4
|
||||
# The locale YouTube fills a related list in: on the video's topic, or with what trends in Hungary.
|
||||
RELATED_REGIONS = {"topical": ("en", "US"), "hu": ("hu", "HU")}
|
||||
|
||||
# A request that fails outright gives its slot back, but its shape is the user's (a cursor is a
|
||||
# free string): one built to fail would read YouTube for nothing, without end. So only this many
|
||||
# refunds an hour per user and list; past them a failure keeps its slot, as a success does.
|
||||
REFUNDS_PER_HOUR = 5
|
||||
_refunds = RateLimiter(max_events=REFUNDS_PER_HOUR, window_seconds=3600)
|
||||
# The API source's budget check and the search.list call it pays for run one at a time: checked
|
||||
# apart, searches sent together at the last 100 units all passed, and all spent. One process
|
||||
# serves the API (a single uvicorn worker, as `ratelimit` says), so a process lock holds them all.
|
||||
# A search waits this long for it, then is refused as busy: each waiter holds a request worker, and
|
||||
# a slow YouTube (30 s a call at worst) would otherwise park them all behind one another.
|
||||
_api_search = threading.Lock()
|
||||
API_SEARCH_WAIT_SECONDS = 10.0
|
||||
|
||||
|
||||
def _gather(
|
||||
db: Session,
|
||||
yt: YouTubeClient,
|
||||
user: User,
|
||||
*,
|
||||
cursor: str | None,
|
||||
max_pages: int,
|
||||
fetch: Callable[[str | None], dict],
|
||||
candidates_of: Callable[[list[dict], list[str]], list[dict]],
|
||||
enough: Callable[[list[str]], bool],
|
||||
scrape_failed: Callable[[Exception], None],
|
||||
ingest_failed: Callable[[int, int], None],
|
||||
) -> tuple[list[str], str | None]:
|
||||
"""Page through a YouTube list into the catalog: fetch a page, keep its `candidates_of`, ingest
|
||||
them, and go on from its continuation until `enough` or `max_pages`. Returns the kept ids and
|
||||
the cursor to read further from. A page that fails after earlier ones gathered something ends
|
||||
the list with what it has; a first page that fails raises the 422 refusal.
|
||||
|
||||
422, not 502: this is a JSON endpoint, and the FE treats 502/503/504 as a gateway dropout
|
||||
(auto-retry + "connection lost" banner — lib/api/core RETRIABLE_GATEWAY), which hides the real
|
||||
message and repeats the work. A Data API failure is logged where it happened; the scraper's is
|
||||
not, and its text does not ride the answer — so `scrape_failed` says it. An ingest (DB writes +
|
||||
enrich) fails the same way, guarded for any exception so a write or shape failure is a 422 with
|
||||
a message too, not a bare 500; `ingest_failed` logs it inside the `except`, with the trace."""
|
||||
collected: list[str] = []
|
||||
next_cursor = cursor
|
||||
for _ in range(max_pages):
|
||||
try:
|
||||
page = fetch(next_cursor)
|
||||
except (YouTubeError, ScrapeError) as exc:
|
||||
if collected:
|
||||
break # keep what earlier pages already gathered
|
||||
if isinstance(exc, ScrapeError):
|
||||
scrape_failed(exc)
|
||||
raise youtube_refusal(exc) from exc
|
||||
candidates = candidates_of(page["items"], collected)
|
||||
try:
|
||||
collected.extend(catalog_search.ingest_candidates(db, yt, user, candidates))
|
||||
except Exception as exc: # any ingest failure, not just YouTubeError
|
||||
db.rollback()
|
||||
ingest_failed(len(candidates), len(collected))
|
||||
if collected:
|
||||
break
|
||||
raise youtube_refusal(exc) from exc
|
||||
next_cursor = page["next_page_token"]
|
||||
if enough(collected) or not next_cursor:
|
||||
break
|
||||
return collected, next_cursor
|
||||
|
||||
|
||||
def _give_back(claimed: int, feature: str, user_id: int) -> None:
|
||||
"""Refund the slot of a request that failed outright, while this user has refunds left."""
|
||||
if _refunds.allow(f"{feature}:{user_id}"):
|
||||
quota.refund_action(claimed)
|
||||
return
|
||||
log.info(
|
||||
"a failed request kept its slot: this hour's refunds are spent",
|
||||
extra=logs.event(f"{feature}.refund_refused", per_hour=REFUNDS_PER_HOUR),
|
||||
)
|
||||
|
||||
|
||||
def _budget_spent() -> None:
|
||||
"""Say that a live search was refused because the shared YouTube budget cannot pay for it."""
|
||||
log.info(
|
||||
"a live search was refused: the shared YouTube budget is spent",
|
||||
extra=logs.event("search.refused", reason="shared_quota", cost=SEARCH_COST),
|
||||
)
|
||||
|
||||
|
||||
def _busy() -> None:
|
||||
"""Say that a live search was refused because other API searches held the line too long."""
|
||||
log.info(
|
||||
"a live search was refused: other searches held the line",
|
||||
extra=logs.event("search.refused", reason="busy", waited=API_SEARCH_WAIT_SECONDS),
|
||||
)
|
||||
|
||||
|
||||
def _cap_spent(feature: str, limit: int) -> None:
|
||||
"""Say that a request was refused for the per-user daily cap. The 429 is in the request line
|
||||
either way; which of the caps produced it is not, and they are answered by different things —
|
||||
this one by tomorrow, the shared budget by the admin."""
|
||||
log.info(
|
||||
"a request was refused: the per-user daily cap is spent",
|
||||
extra=logs.event(f"{feature}.refused", reason="daily_cap", limit=limit),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/youtube")
|
||||
@@ -59,109 +178,122 @@ def search_youtube(
|
||||
# Source: "scrape" (InnerTube, no API quota) or "api" (search.list, 100 units/page).
|
||||
source = sysconfig.get_str(db, "search_source")
|
||||
|
||||
# Per-user daily cap applies to both sources (anti-abuse); with scrape it's the only guard
|
||||
# since the search itself spends no quota.
|
||||
# Every request takes a slot of the per-user daily cap, a cursor's too (anti-abuse); with
|
||||
# scrape it's the only guard since the search itself spends no quota. A limit of 0 turns live
|
||||
# search off on this instance — a refusal tomorrow will not change.
|
||||
daily_limit = sysconfig.get_int(db, "search_daily_limit_per_user")
|
||||
used = quota.actions_today(db, user.id, quota.QuotaAction.VIDEOS_SEARCH)
|
||||
if used >= daily_limit:
|
||||
# The 429 is in the request line either way; which of the two caps produced it is not, and
|
||||
# they are answered by different things — this one by tomorrow, the other by the admin.
|
||||
log.info(
|
||||
"a live search was refused: the per-user daily cap is spent",
|
||||
extra=logs.event("search.refused", reason="daily_cap", limit=daily_limit),
|
||||
)
|
||||
raise refused(429, "search_daily_limit", limit=daily_limit)
|
||||
# The 100-unit budget pre-check only applies to the API source.
|
||||
if daily_limit <= 0:
|
||||
raise refused(409, "search_disabled")
|
||||
# The 100-unit budget pre-check only applies to the API source. It is asked again under the
|
||||
# lock, right before the call (`fetch`); this one refuses before a slot is taken.
|
||||
if source == "api" and not quota.can_spend(db, SEARCH_COST):
|
||||
log.info(
|
||||
"a live search was refused: the shared YouTube budget is spent",
|
||||
extra=logs.event("search.refused", reason="shared_quota", cost=SEARCH_COST),
|
||||
)
|
||||
_budget_spent()
|
||||
raise refused(429, "quota_spent")
|
||||
# The check and the take are one step (`quota.claim_action`), whichever the source: checked
|
||||
# first and logged after, requests sent together at the last free slot all passed — and with
|
||||
# the API source each of them spent 100 units. A search that fails outright gives it back below.
|
||||
claimed = quota.claim_action(user.id, quota.QuotaAction.VIDEOS_SEARCH, daily_limit)
|
||||
if claimed is None:
|
||||
_cap_spent("search", daily_limit)
|
||||
raise refused(429, "search_daily_limit", limit=daily_limit)
|
||||
|
||||
# Channels this user has blocked are dropped before ingestion — never shown, never stored.
|
||||
blocked = queries.blocked_ids(db, user)
|
||||
|
||||
collected: list[str] = []
|
||||
next_cursor = cursor
|
||||
MAX_PAGES = 12 # scrape safety bound
|
||||
with YouTubeClient(db, user) as yt:
|
||||
for _ in range(MAX_PAGES):
|
||||
try:
|
||||
if source == "api":
|
||||
with quota.attribute(user.id, quota.QuotaAction.VIDEOS_SEARCH):
|
||||
page = yt.search_videos(term, page_token=next_cursor)
|
||||
else:
|
||||
page = search_scrape.search(term, continuation=next_cursor)
|
||||
except (YouTubeError, search_scrape.ScrapeError) as exc:
|
||||
if collected:
|
||||
break # keep what we already gathered
|
||||
# 422, not 502: this is a JSON endpoint, and the FE treats 502/503/504 as a gateway
|
||||
# dropout (auto-retry + "connection lost" banner — lib/api/core RETRIABLE_GATEWAY),
|
||||
# which hides the real message and burns a second quota-costed search. Upstream failure
|
||||
# on a JSON endpoint = 422 + message; reserve 5xx for the raw byte-proxies. (B-core-1)
|
||||
# A Data API failure is logged where it happened; the scraper's is not, and its text
|
||||
# no longer rides the answer — so it is said here.
|
||||
if isinstance(exc, search_scrape.ScrapeError):
|
||||
log.warning(
|
||||
"the YouTube search scrape failed",
|
||||
extra=logs.event("search.scrape_failed", error=str(exc)),
|
||||
)
|
||||
raise youtube_refusal(exc) from exc
|
||||
# Whether search.list was paid for: YouTube charges a call it refuses too, so once the client
|
||||
# recorded its units — or the request went out and no answer came back — the search has spent
|
||||
# the shared budget. One that never reached YouTube (no connection, no token) has not.
|
||||
charged = False
|
||||
|
||||
# Drop currently-live/upcoming, channel-less, and blocked-channel results.
|
||||
candidates = [
|
||||
it
|
||||
for it in page["items"]
|
||||
if it["live_broadcast"] == "none"
|
||||
and it["channel_id"]
|
||||
and it["channel_id"] not in blocked
|
||||
]
|
||||
# Ingest (DB writes + enrich) runs outside the page-fetch try above; guard it too so a
|
||||
# write/shape failure degrades to a 422 with a message on this JSON endpoint instead of a
|
||||
# bare 500 hidden behind the FE's generic "search failed" (same rationale as B-core-1).
|
||||
try:
|
||||
collected.extend(catalog_search.ingest_candidates(db, yt, user, candidates))
|
||||
except Exception as exc: # any ingest failure, not just YouTubeError
|
||||
db.rollback()
|
||||
# The term is NOT in this line. A search string is exactly what the privacy
|
||||
# policy keeps out of the log unless the user turned Teljes/TRACE on for
|
||||
# themselves, and `redact_text` does not cover it — it scrubs addresses and
|
||||
# credential params, not what someone typed into the search box. What the
|
||||
# ERROR line carries instead is the shape of the failure, which is what tells
|
||||
# an ingest bug from an upstream one; the term follows at TRACE, and only
|
||||
# under this user's own consent — not whenever the process runs at TRACE.
|
||||
log.exception(
|
||||
"live search ingest failed",
|
||||
extra=logs.event(
|
||||
"search.live.ingest_failed",
|
||||
source=source,
|
||||
candidates=len(candidates),
|
||||
collected=len(collected),
|
||||
),
|
||||
)
|
||||
if logs.consented_trace():
|
||||
log.log(
|
||||
logs.TRACE,
|
||||
"the term the ingest failed on",
|
||||
# log-pii-ok: only under this user's own Teljes consent
|
||||
extra=logs.event("search.live.term", term=term),
|
||||
)
|
||||
if collected:
|
||||
break # keep what earlier pages already gathered
|
||||
raise youtube_refusal(exc) from exc
|
||||
next_cursor = page["next_page_token"]
|
||||
# The API source pages cost 100 units each — never auto-page; one page per request.
|
||||
if source == "api" or len(collected) >= limit or not next_cursor:
|
||||
break
|
||||
def fetch(token: str | None) -> dict:
|
||||
if source != "api":
|
||||
return search_scrape.search(term, continuation=token)
|
||||
if not _api_search.acquire(timeout=API_SEARCH_WAIT_SECONDS):
|
||||
_busy()
|
||||
raise refused(429, "search_busy")
|
||||
try:
|
||||
return paid_search(token)
|
||||
finally:
|
||||
_api_search.release()
|
||||
|
||||
# Count this as ONE per-user search against the daily cap. The scrape source spends no
|
||||
# quota, so it never logs an event on its own; the API source already logged exactly one
|
||||
# (via record_usage — it never auto-pages). Logging once here, after a search that produced
|
||||
# at least one page (a total failure raises 502 above and never reaches this), keeps the cap
|
||||
# counting user searches instead of internal continuation pages.
|
||||
if source != "api":
|
||||
quota.log_action(user.id, quota.QuotaAction.VIDEOS_SEARCH)
|
||||
def paid_search(token: str | None) -> dict:
|
||||
nonlocal charged
|
||||
with quota.attribute(user.id, quota.QuotaAction.VIDEOS_SEARCH):
|
||||
if not quota.can_spend(db, SEARCH_COST):
|
||||
_budget_spent()
|
||||
raise refused(429, "quota_spent")
|
||||
spent = yt.spent
|
||||
try:
|
||||
page = yt.search_videos(term, page_token=token)
|
||||
except YouTubeError as exc:
|
||||
charged = yt.spent > spent or exc.sent
|
||||
raise
|
||||
charged = True
|
||||
return page
|
||||
|
||||
def candidates_of(items: list[dict], _collected: list[str]) -> list[dict]:
|
||||
# Drop currently-live/upcoming, channel-less, and blocked-channel results.
|
||||
return [
|
||||
it
|
||||
for it in items
|
||||
if it["live_broadcast"] == "none"
|
||||
and it["channel_id"]
|
||||
and it["channel_id"] not in blocked
|
||||
]
|
||||
|
||||
def scrape_failed(exc: Exception) -> None:
|
||||
log.warning(
|
||||
"the YouTube search scrape failed",
|
||||
extra=logs.event("search.scrape_failed", error=str(exc)),
|
||||
)
|
||||
|
||||
def ingest_failed(candidates: int, collected: int) -> None:
|
||||
# The term is NOT in this line. A search string is exactly what the privacy policy keeps
|
||||
# out of the log unless the user turned Teljes/TRACE on for themselves, and `redact_text`
|
||||
# does not cover it — it scrubs addresses and credential params, not what someone typed
|
||||
# into the search box. What the ERROR line carries instead is the shape of the failure,
|
||||
# which is what tells an ingest bug from an upstream one; the term follows at TRACE, and
|
||||
# only under this user's own consent — not whenever the process runs at TRACE.
|
||||
log.exception(
|
||||
"live search ingest failed",
|
||||
extra=logs.event(
|
||||
"search.live.ingest_failed",
|
||||
source=source,
|
||||
candidates=candidates,
|
||||
collected=collected,
|
||||
),
|
||||
)
|
||||
if logs.consented_trace():
|
||||
log.log(
|
||||
logs.TRACE,
|
||||
"the term the ingest failed on",
|
||||
# log-pii-ok: only under this user's own Teljes consent
|
||||
extra=logs.event("search.live.term", term=term),
|
||||
)
|
||||
|
||||
try:
|
||||
with YouTubeClient(db, user) as yt:
|
||||
collected, next_cursor = _gather(
|
||||
db,
|
||||
yt,
|
||||
user,
|
||||
cursor=cursor,
|
||||
# The API source pages cost 100 units each — never auto-page; one page per request.
|
||||
max_pages=1 if source == "api" else SEARCH_MAX_PAGES,
|
||||
fetch=fetch,
|
||||
candidates_of=candidates_of,
|
||||
enough=lambda got: len(got) >= limit,
|
||||
scrape_failed=scrape_failed,
|
||||
ingest_failed=ingest_failed,
|
||||
)
|
||||
except Exception:
|
||||
# A search that showed the user nothing does not count against them, unless search.list
|
||||
# was already paid for: then the slot is what stops a failing search (a bogus cursor gets
|
||||
# a 400 every time) from spending the shared budget without end. A busy refusal paid
|
||||
# nothing and gives it back.
|
||||
if not charged:
|
||||
_give_back(claimed, "search", user.id)
|
||||
raise
|
||||
|
||||
ordered = collected[:limit]
|
||||
|
||||
@@ -201,3 +333,78 @@ def clear_search(
|
||||
removed = catalog_search.clear(db, user, ids)
|
||||
db.commit()
|
||||
return {"ok": True, "removed": removed}
|
||||
|
||||
|
||||
@router.get("/related/{video_id}")
|
||||
def related_videos(
|
||||
video_id: str = Path(max_length=16),
|
||||
cursor: str | None = None,
|
||||
region: Literal["topical", "hu"] = "topical",
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""The videos YouTube shows beside this one, materialised into the catalog like search results,
|
||||
without the ones this user has watched or hidden here or in their Takeout history, and without
|
||||
blocked channels. Pages on (`cursor`) until `RELATED_TARGET` are gathered; `next_cursor` reads
|
||||
further. `region` picks the locale YouTube fills the list in (`RELATED_REGIONS`)."""
|
||||
# Every request takes a slot, a cursor's too: each one scrapes pages and enriches what they
|
||||
# hold, and a cursor is a free string — counting only first pages let a replayed cursor read
|
||||
# without end. The check and the take are one step (`quota.claim_action`); a request that fails
|
||||
# outright gives its slot back, a few an hour (`_give_back`). A limit of 0 turns related videos
|
||||
# off on this instance.
|
||||
daily_limit = sysconfig.get_int(db, "related_daily_limit_per_user")
|
||||
if daily_limit <= 0:
|
||||
raise refused(409, "related_disabled")
|
||||
claimed = quota.claim_action(user.id, quota.QuotaAction.VIDEOS_RELATED, daily_limit)
|
||||
if claimed is None:
|
||||
_cap_spent("related", daily_limit)
|
||||
raise refused(429, "related_daily_limit", limit=daily_limit)
|
||||
|
||||
hl, gl = RELATED_REGIONS[region]
|
||||
blocked = queries.blocked_ids(db, user)
|
||||
|
||||
def candidates_of(items: list[dict], collected: list[str]) -> list[dict]:
|
||||
ids = [it["id"] for it in items]
|
||||
drop = reader_queries.seen_by(db, user, ids) | set(collected) | {video_id}
|
||||
return [it for it in items if it["id"] not in drop and it["channel_id"] not in blocked]
|
||||
|
||||
def scrape_failed(exc: Exception) -> None:
|
||||
log.warning(
|
||||
"the related-videos scrape failed",
|
||||
extra=logs.event("related.scrape_failed", error=str(exc)),
|
||||
)
|
||||
|
||||
def ingest_failed(candidates: int, collected: int) -> None:
|
||||
log.exception(
|
||||
"a related list's ingest failed",
|
||||
extra=logs.event("related.ingest_failed", candidates=candidates, collected=collected),
|
||||
)
|
||||
|
||||
try:
|
||||
with YouTubeClient(db, user) as yt:
|
||||
collected, next_cursor = _gather(
|
||||
db,
|
||||
yt,
|
||||
user,
|
||||
cursor=cursor,
|
||||
max_pages=RELATED_MAX_PAGES,
|
||||
fetch=lambda token: related_scrape.related(
|
||||
video_id, continuation=token, hl=hl, gl=gl
|
||||
),
|
||||
candidates_of=candidates_of,
|
||||
enough=lambda got: len(got) >= RELATED_TARGET,
|
||||
scrape_failed=scrape_failed,
|
||||
ingest_failed=ingest_failed,
|
||||
)
|
||||
except Exception:
|
||||
_give_back(claimed, "related", user.id)
|
||||
raise
|
||||
|
||||
rows = reader_queries.feed_rows_by_ids(db, user, collected)
|
||||
# A related list mixes channels the user follows with ones they never met: each row says which.
|
||||
followed = queries.followed_among(db, user, {r["channel_id"] for r in rows})
|
||||
return {
|
||||
"items": [{**r, "followed": r["channel_id"] in followed} for r in rows],
|
||||
"next_cursor": next_cursor,
|
||||
"has_more": bool(next_cursor),
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ from sqlalchemy import delete, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import logs, sysconfig
|
||||
from app.catalog import service as catalog_service
|
||||
from app.catalog.models import Channel, ExploredChannel, SearchFind, Subscription, Video
|
||||
from app.reader import queries as reader_queries
|
||||
from app.sync.videos import insert_stubs, stub_from_playlist_item, apply_video_details
|
||||
@@ -66,11 +67,13 @@ def _enrich_new(db: Session, yt: YouTubeClient, video_ids: list[str]) -> int:
|
||||
def explore_ingest_page(
|
||||
db: Session, yt: YouTubeClient, channel: Channel, page_token: str | None = None
|
||||
) -> dict:
|
||||
"""Ingest one page (up to 50, newest-first) of the channel's uploads, marking the new
|
||||
videos via_explore, then enrich them. Returns the count ingested and the next page token
|
||||
(None when the back-catalogue is exhausted) so the caller can offer "load more". Stateless
|
||||
pagination: the caller round-trips the token, so the channel's own backfill cursor (used by
|
||||
the organic deep backfill) is never touched."""
|
||||
"""Ingest one page (up to 50, newest-first) of the channel's uploads, marking the new videos
|
||||
via_explore while the channel is an exploration's (`from_explore`): of a channel someone follows
|
||||
they are its uploads like any other, and a flag there would never be cleared, since subscribing
|
||||
clears only an explored channel's. Then enrich them. Returns the count ingested and the next
|
||||
page token (None when the back-catalogue is exhausted) so the caller can offer "load more".
|
||||
Stateless pagination: the caller round-trips the token, so the channel's own backfill cursor
|
||||
(used by the organic deep backfill) is never touched."""
|
||||
if not channel.uploads_playlist_id:
|
||||
return {"ingested": 0, "next_page_token": None}
|
||||
try:
|
||||
@@ -86,9 +89,10 @@ def explore_ingest_page(
|
||||
for item in data.get("items", []):
|
||||
stub = stub_from_playlist_item(item, channel.id)
|
||||
if stub is not None:
|
||||
stub["via_explore"] = True
|
||||
stub["via_explore"] = channel.from_explore
|
||||
stubs.append(stub)
|
||||
inserted = insert_stubs(db, stubs)
|
||||
catalog_service.settle_explored(db, channel)
|
||||
self_enriched = _enrich_new(db, yt, [s["id"] for s in stubs])
|
||||
log.info(
|
||||
"explore ingest channel=%s ingested=%s enriched=%s", channel.id, inserted, self_enriched
|
||||
@@ -105,7 +109,9 @@ def purge_unkept_explored(db: Session) -> dict:
|
||||
- a live ExploredChannel row (someone explored it within the grace window — channel-level), or
|
||||
- a video has per-user state: watched/in-progress (VideoState), in a playlist (PlaylistItem),
|
||||
or surfaced by the user's own search (SearchFind) — these survive even if the channel goes.
|
||||
A channel row is dropped only once it holds no videos at all. 0 quota."""
|
||||
A channel row is dropped only once it holds no videos at all, and not while someone's Takeout
|
||||
history shows it watched (their "watched but not followed" list names it from that row).
|
||||
0 quota."""
|
||||
grace_days = sysconfig.get_int(db, "explore_grace_days")
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=grace_days)
|
||||
|
||||
@@ -135,7 +141,9 @@ def purge_unkept_explored(db: Session) -> dict:
|
||||
|
||||
has_videos = select(Video.id).where(Video.channel_id == Channel.id).exists()
|
||||
channels_deleted = db.execute(
|
||||
delete(Channel).where(Channel.id.in_(orphan_ids), ~has_videos)
|
||||
delete(Channel).where(
|
||||
Channel.id.in_(orphan_ids), ~has_videos, ~reader_queries.in_a_watch_history(Channel.id)
|
||||
)
|
||||
).rowcount
|
||||
db.commit()
|
||||
return {
|
||||
|
||||
@@ -8,6 +8,7 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app import logs
|
||||
from app.models import User
|
||||
from app.catalog import service as catalog_service
|
||||
from app.catalog.models import Channel, Subscription
|
||||
from app.utils import normalize_description
|
||||
from app.youtube.client import YouTubeClient, YouTubeError, best_thumbnail
|
||||
@@ -109,6 +110,21 @@ def apply_channel_details(db: Session, items: list[dict], asked: Iterable[str])
|
||||
channel.details_synced_at = now
|
||||
|
||||
|
||||
def describe_channels(db: Session, yt: YouTubeClient, channel_ids: list[str]) -> None:
|
||||
"""Make sure each given channel is in the catalog with its details: a channel it lacks is added
|
||||
as a stub, then all of them are asked for (`channels.list`, 1 unit a 50). Flushes; the caller
|
||||
commits."""
|
||||
if not channel_ids:
|
||||
return
|
||||
have = set(db.execute(select(Channel.id).where(Channel.id.in_(channel_ids))).scalars())
|
||||
for cid in dict.fromkeys(channel_ids):
|
||||
if cid not in have:
|
||||
db.add(Channel(id=cid))
|
||||
db.flush()
|
||||
apply_channel_details(db, yt.get_channels(channel_ids), channel_ids)
|
||||
db.flush()
|
||||
|
||||
|
||||
def should_prune(fetched_count: int, existing_count: int) -> bool:
|
||||
"""Whether an import may delete the local subscriptions missing from this fetch.
|
||||
|
||||
@@ -182,6 +198,10 @@ def import_subscriptions(db: Session, user: User) -> dict:
|
||||
db.add(sub_row)
|
||||
sub_row.yt_subscription_id = sub.get("yt_subscription_id")
|
||||
db.flush()
|
||||
# A follow made on youtube.com keeps an explored channel as a follow made here does.
|
||||
explored = select(Channel).where(Channel.id.in_(fetched), Channel.from_explore.is_(True))
|
||||
for channel in db.execute(explored).scalars():
|
||||
catalog_service.settle_explored(db, channel)
|
||||
|
||||
# Prune subscriptions removed on YouTube — but only when this fetch is trustworthy
|
||||
# (see `should_prune`).
|
||||
|
||||
@@ -420,11 +420,15 @@ def run_shorts_classification(db: Session, limit: int | None = None) -> dict:
|
||||
return {"probed": probed, "shorts": shorts}
|
||||
|
||||
|
||||
def ensure_videos(db: Session, yt: YouTubeClient, video_ids: list[str]) -> None:
|
||||
def ensure_videos(
|
||||
db: Session, yt: YouTubeClient, video_ids: list[str], *, explore: bool = False
|
||||
) -> None:
|
||||
"""Make sure every given video id exists in the catalog, fetching + ingesting the
|
||||
missing ones (and a stub channel for any unknown channel). Deleted/private videos that
|
||||
the API won't return are simply left out. The catalog's write for a playlist sync that names
|
||||
videos it has never seen; commits."""
|
||||
videos it has never seen; commits. `explore` adds the new ones as an exploration's
|
||||
(`via_explore`): visible to who explores or follows their channel, and reclaimed by the cleanup
|
||||
once nobody keeps them."""
|
||||
if not video_ids:
|
||||
return
|
||||
have = set(db.execute(select(Video.id).where(Video.id.in_(video_ids))).scalars().all())
|
||||
@@ -458,7 +462,12 @@ def ensure_videos(db: Session, yt: YouTubeClient, video_ids: list[str]) -> None:
|
||||
seen.add(vid)
|
||||
# published_at is NOT NULL (0068); apply_video_details re-fills a missing date, but seed a now()
|
||||
# fallback here too so the constructor never carries an explicit NULL.
|
||||
v = Video(id=vid, channel_id=cid, published_at=parse_dt(sn.get("publishedAt")) or now)
|
||||
v = Video(
|
||||
id=vid,
|
||||
channel_id=cid,
|
||||
published_at=parse_dt(sn.get("publishedAt")) or now,
|
||||
via_explore=explore,
|
||||
)
|
||||
apply_video_details(v, it)
|
||||
v.enriched_at = now
|
||||
db.add(v)
|
||||
|
||||
@@ -140,6 +140,15 @@ SPECS: tuple[ConfigSpec, ...] = (
|
||||
max=100_000,
|
||||
applies=LIVE,
|
||||
),
|
||||
ConfigSpec(
|
||||
"related_daily_limit_per_user",
|
||||
"int",
|
||||
"quota",
|
||||
"related_daily_limit_per_user",
|
||||
min=0,
|
||||
max=100_000,
|
||||
applies=LIVE,
|
||||
),
|
||||
# Live-search source: "scrape" (InnerTube, zero API quota) or "api" (search.list, 100u/page).
|
||||
ConfigSpec("search_source", "choice", "quota", "search_source", applies=LIVE),
|
||||
ConfigSpec(
|
||||
|
||||
@@ -30,12 +30,26 @@ class YouTubeError(Exception):
|
||||
message is prose, it changes under us, and it is deliberately the poorer of the two here.
|
||||
|
||||
`path` is the API endpoint that ANSWERED with the failure (`playlistItems`); empty when no
|
||||
endpoint did — the request never got through (`transport`) or the token step refused first."""
|
||||
endpoint did — the request never got through (`transport`) or the token step refused first.
|
||||
|
||||
def __init__(self, message: str, *, reason: str = "", path: str = ""):
|
||||
`sent` is a `transport` failure that came after the request may have gone out (a read timeout,
|
||||
a dropped answer): nothing answered, but YouTube may have counted the call."""
|
||||
|
||||
def __init__(self, message: str, *, reason: str = "", path: str = "", sent: bool = False):
|
||||
super().__init__(message)
|
||||
self.reason = reason
|
||||
self.path = path
|
||||
self.sent = sent
|
||||
|
||||
|
||||
# The transport failures that stop a request before it reaches YouTube: nothing went out.
|
||||
_UNSENT = (
|
||||
httpx.ConnectError,
|
||||
httpx.ConnectTimeout,
|
||||
httpx.PoolTimeout,
|
||||
httpx.ProxyError,
|
||||
httpx.UnsupportedProtocol,
|
||||
)
|
||||
|
||||
|
||||
def _error_reason(resp: httpx.Response) -> str:
|
||||
@@ -162,6 +176,9 @@ def best_thumbnail(thumbnails: dict | None) -> str | None:
|
||||
|
||||
|
||||
class YouTubeClient:
|
||||
# The quota units this client has recorded: what its calls have spent of the shared budget.
|
||||
spent: int = 0
|
||||
|
||||
def __init__(self, db, user: User):
|
||||
self.db = db
|
||||
self.user = user
|
||||
@@ -189,9 +206,16 @@ class YouTubeClient:
|
||||
return self._http.request(method, url, **kwargs)
|
||||
except httpx.HTTPError as exc:
|
||||
raise YouTubeError(
|
||||
f"YouTube API unreachable ({exc.__class__.__name__}: {exc})", reason="transport"
|
||||
f"YouTube API unreachable ({exc.__class__.__name__}: {exc})",
|
||||
reason="transport",
|
||||
sent=not isinstance(exc, _UNSENT),
|
||||
) from exc
|
||||
|
||||
def _spend(self, units: int) -> None:
|
||||
"""Record what a call YouTube answered cost — a refused one too: it is charged all the same."""
|
||||
quota.record_usage(units)
|
||||
self.spent += units
|
||||
|
||||
# --- auth ---
|
||||
def _access_token(self) -> str:
|
||||
tok = self.user.token
|
||||
@@ -269,7 +293,7 @@ class YouTubeClient:
|
||||
else:
|
||||
headers["Authorization"] = f"Bearer {self._access_token()}"
|
||||
resp = self._send("GET", f"{API_BASE}/{path}", params=p, headers=headers)
|
||||
quota.record_usage(cost)
|
||||
self._spend(cost)
|
||||
if resp.status_code != 200:
|
||||
raise _upstream_failure("GET", path, resp, expected)
|
||||
return resp.json()
|
||||
@@ -401,7 +425,7 @@ class YouTubeClient:
|
||||
params={"id": subscription_id},
|
||||
headers={"Authorization": f"Bearer {self._access_token()}"},
|
||||
)
|
||||
quota.record_usage(50)
|
||||
self._spend(50)
|
||||
if resp.status_code not in (200, 204):
|
||||
raise _upstream_failure("DELETE", "subscriptions", resp)
|
||||
|
||||
@@ -431,7 +455,7 @@ class YouTubeClient:
|
||||
def _write(self, method: str, path: str, *, params: dict, json: dict | None = None) -> dict:
|
||||
headers = {"Authorization": f"Bearer {self._access_token()}"}
|
||||
resp = self._send(method, f"{API_BASE}/{path}", params=params, json=json, headers=headers)
|
||||
quota.record_usage(50)
|
||||
self._spend(50)
|
||||
if resp.status_code not in (200, 204):
|
||||
raise _upstream_failure(method, path, resp)
|
||||
return resp.json() if resp.content else {}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""The website's own InnerTube API (`youtubei/v1/*`), read the way the website reads it — no quota.
|
||||
|
||||
The zero-quota search (`search_scrape`) and the related videos (`related_scrape`) both POST here with
|
||||
the public WEB key and a client version, read out of a live results page. This deliberately calls an
|
||||
undocumented endpoint: if YouTube changes the JSON shape or blocks the host, each caller says so as a
|
||||
`ScrapeError`, never as an empty answer.
|
||||
|
||||
The SOCS=CAI consent-skip cookie is sent like the Shorts probe's, so a server-side request isn't
|
||||
bounced to consent.youtube.com."""
|
||||
|
||||
import re
|
||||
|
||||
import httpx
|
||||
|
||||
from app import logs
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
_API_URL = "https://www.youtube.com/youtubei/v1/"
|
||||
_RESULTS_URL = "https://www.youtube.com/results"
|
||||
# Public WEB InnerTube key + a recent client version. These are also embedded in every results
|
||||
# page; we fetch the live pair once and cache it, falling back to these constants.
|
||||
_FALLBACK_KEY = "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8" # gitleaks:allow -- the public WEB key, in every results page
|
||||
_FALLBACK_CLIENT_VERSION = "2.20240101.00.00"
|
||||
|
||||
_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
|
||||
# SOCS skips YouTube's cookie-consent interstitial (otherwise every server-side request is
|
||||
# redirected to consent.youtube.com).
|
||||
"Cookie": "SOCS=CAI",
|
||||
"Accept-Language": "en-US,en;q=0.9",
|
||||
}
|
||||
|
||||
_KEY_RE = re.compile(r'"INNERTUBE_API_KEY":"([^"]+)"')
|
||||
_VER_RE = re.compile(r'"INNERTUBE_CLIENT_VERSION":"([^"]+)"')
|
||||
|
||||
# Cached (api_key, client_version) extracted from a results page; refreshed on demand.
|
||||
_config: tuple[str, str] | None = None
|
||||
|
||||
|
||||
class ScrapeError(Exception):
|
||||
"""An InnerTube read could not be completed (network, blocked, or unexpected shape)."""
|
||||
|
||||
|
||||
def runs_text(node: dict | None) -> str | None:
|
||||
"""The text of an InnerTube text node: a `simpleText`, or its `runs` joined."""
|
||||
if not node:
|
||||
return None
|
||||
if node.get("simpleText"):
|
||||
return node["simpleText"]
|
||||
runs = node.get("runs") or []
|
||||
if runs:
|
||||
return "".join(r.get("text", "") for r in runs)
|
||||
return None
|
||||
|
||||
|
||||
def scraped_video(
|
||||
vid: str, channel_id: object, channel_title: object, title: object, thumbnails: object
|
||||
) -> dict:
|
||||
"""One scraped video in the shape `YouTubeClient.search_videos` answers, so a page of either
|
||||
source is ingested the same way. `published_at` is None (the website shows only a relative
|
||||
"3 years ago"; the enrich fills the real date) and `live_broadcast` "none" (live/upcoming are
|
||||
judged after the enrich, by `live_status`). The largest thumbnail is the last."""
|
||||
thumbs = thumbnails if isinstance(thumbnails, list) else []
|
||||
last = thumbs[-1] if thumbs else None
|
||||
return {
|
||||
"id": vid,
|
||||
"channel_id": channel_id if isinstance(channel_id, str) and channel_id else None,
|
||||
"channel_title": channel_title if isinstance(channel_title, str) else None,
|
||||
"title": title if isinstance(title, str) else None,
|
||||
"published_at": None,
|
||||
"thumbnail_url": last.get("url") if isinstance(last, dict) else None,
|
||||
"live_broadcast": "none",
|
||||
}
|
||||
|
||||
|
||||
def video_renderer(node: dict) -> dict | None:
|
||||
"""A `videoRenderer` (search) or `compactVideoRenderer` (the older related column) flattened —
|
||||
the two draw a video the same way. None without a video id; the channel is None when the byline
|
||||
names none."""
|
||||
vid = node.get("videoId")
|
||||
if not isinstance(vid, str) or not vid:
|
||||
return None
|
||||
owner = node.get("ownerText") or node.get("longBylineText") or {}
|
||||
runs = owner.get("runs") if isinstance(owner, dict) else None
|
||||
first = runs[0] if isinstance(runs, list) and runs and isinstance(runs[0], dict) else {}
|
||||
endpoint = (first.get("navigationEndpoint") or {}).get("browseEndpoint") or {}
|
||||
return scraped_video(
|
||||
vid,
|
||||
endpoint.get("browseId"),
|
||||
first.get("text"),
|
||||
runs_text(node.get("title")),
|
||||
(node.get("thumbnail") or {}).get("thumbnails"),
|
||||
)
|
||||
|
||||
|
||||
def continuation_token(node: object) -> str | None:
|
||||
"""The "load more" cursor of a `continuationItemRenderer`, or None when `node` is not one."""
|
||||
if not isinstance(node, dict):
|
||||
return None
|
||||
command = (node.get("continuationEndpoint") or {}).get("continuationCommand") or {}
|
||||
token = command.get("token")
|
||||
return token if isinstance(token, str) and token else None
|
||||
|
||||
|
||||
def _get_config(client: httpx.Client) -> tuple[str, str]:
|
||||
"""The current InnerTube (api_key, client_version), cached after the first fetch that FOUND them.
|
||||
|
||||
The fallback pair is never cached: it used to be, so one failed fetch (or a consent page with no
|
||||
keys on it) at the wrong moment pinned every later search to a hard-coded key and version for
|
||||
the life of the process — and when those went stale, search returned nothing, with no error
|
||||
anywhere. Now the next call simply tries the live pair again."""
|
||||
global _config
|
||||
if _config is not None:
|
||||
return _config
|
||||
try:
|
||||
html = client.get(_RESULTS_URL, params={"search_query": "music"}).text
|
||||
except httpx.HTTPError as exc:
|
||||
log.warning(
|
||||
"the InnerTube config could not be fetched; falling back to the pinned key",
|
||||
extra=logs.event("youtube.scrape.config_fallback", reason=type(exc).__name__),
|
||||
)
|
||||
return (_FALLBACK_KEY, _FALLBACK_CLIENT_VERSION)
|
||||
key = _KEY_RE.search(html)
|
||||
ver = _VER_RE.search(html)
|
||||
if key and ver:
|
||||
_config = (key.group(1), ver.group(1))
|
||||
return _config
|
||||
log.warning(
|
||||
"the results page carried no InnerTube config; falling back to the pinned key",
|
||||
extra=logs.event("youtube.scrape.config_fallback", reason="not_on_page"),
|
||||
)
|
||||
return (
|
||||
key.group(1) if key else _FALLBACK_KEY,
|
||||
ver.group(1) if ver else _FALLBACK_CLIENT_VERSION,
|
||||
)
|
||||
|
||||
|
||||
def post(endpoint: str, body: dict, *, hl: str = "en", gl: str = "US") -> dict:
|
||||
"""POST `body` to `youtubei/v1/<endpoint>` as the WEB client in the `hl`/`gl` locale and return
|
||||
the decoded JSON object. A network failure, an HTTP error or a body that is not a JSON object (a
|
||||
block, consent or captcha page) raises `ScrapeError`; the caller judges the shape."""
|
||||
with httpx.Client(timeout=20.0, headers=_HEADERS) as client:
|
||||
api_key, client_version = _get_config(client)
|
||||
context = {
|
||||
"client": {"clientName": "WEB", "clientVersion": client_version, "hl": hl, "gl": gl}
|
||||
}
|
||||
try:
|
||||
resp = client.post(
|
||||
_API_URL + endpoint, params={"key": api_key}, json={"context": context, **body}
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
except httpx.HTTPError as exc:
|
||||
raise ScrapeError(f"InnerTube request failed: {exc}") from exc
|
||||
except ValueError as exc: # non-JSON body (blocked / consent / captcha)
|
||||
raise ScrapeError("InnerTube returned a non-JSON response") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise ScrapeError("InnerTube returned an unexpected shape")
|
||||
return data
|
||||
@@ -0,0 +1,141 @@
|
||||
"""A video's related videos, read from the watch page's InnerTube `next` endpoint — no quota.
|
||||
|
||||
The Data API has no related-videos call any more, so this is the only source: the same list the
|
||||
website shows beside a playing video. A page holds about 20 videos and a continuation token for the
|
||||
next 20. The returned page has the search scrape's shape (``{"items": [...], "next_page_token"}``)
|
||||
so the catalog ingests it the same way (`catalog.search.ingest_candidates`).
|
||||
|
||||
YouTube draws each item as a `lockupViewModel` now; the older `compactVideoRenderer` is read too, so
|
||||
a rollback on its side does not empty the list. An item that names no single channel — a video by
|
||||
several channels draws an avatar stack, not one avatar — is left out: the catalog row needs its
|
||||
channel up front, and the stack does not say which one uploaded it.
|
||||
|
||||
`hl`/`gl` pick the locale YouTube fills the list in: ``en``/``US`` keeps it on the video's topic,
|
||||
``hu``/``HU`` mixes in what is trending in Hungary (measured)."""
|
||||
|
||||
from app.youtube.innertube import (
|
||||
ScrapeError,
|
||||
continuation_token,
|
||||
post,
|
||||
scraped_video,
|
||||
video_renderer,
|
||||
)
|
||||
|
||||
__all__ = ["ScrapeError", "related"]
|
||||
|
||||
# Where a first page and a continuation page put their item list.
|
||||
_FIRST = (
|
||||
"contents",
|
||||
"twoColumnWatchNextResults",
|
||||
"secondaryResults",
|
||||
"secondaryResults",
|
||||
"results",
|
||||
)
|
||||
_APPENDS = ("appendContinuationItemsAction", "reloadContinuationItemsCommand")
|
||||
|
||||
|
||||
def _at(node: object, *path: str | int) -> object:
|
||||
"""The value under `path` in nested dicts/lists, or None where the path stops."""
|
||||
for key in path:
|
||||
if isinstance(node, dict) and isinstance(key, str):
|
||||
node = node.get(key)
|
||||
elif isinstance(node, list) and isinstance(key, int) and -len(node) <= key < len(node):
|
||||
node = node[key]
|
||||
else:
|
||||
return None
|
||||
return node
|
||||
|
||||
|
||||
def _lockup(node: dict) -> dict | None:
|
||||
if node.get("contentType") != "LOCKUP_CONTENT_TYPE_VIDEO" or not node.get("contentId"):
|
||||
return None
|
||||
meta = _at(node, "metadata", "lockupMetadataViewModel")
|
||||
channel_id = _at(
|
||||
meta,
|
||||
"image",
|
||||
"decoratedAvatarViewModel",
|
||||
"rendererContext",
|
||||
"commandContext",
|
||||
"onTap",
|
||||
"innertubeCommand",
|
||||
"browseEndpoint",
|
||||
"browseId",
|
||||
)
|
||||
channel_title = _at(
|
||||
meta, "metadata", "contentMetadataViewModel", "metadataRows", 0, "metadataParts", 0
|
||||
)
|
||||
return scraped_video(
|
||||
node["contentId"],
|
||||
channel_id,
|
||||
_at(channel_title, "text", "content"),
|
||||
_at(meta, "title", "content"),
|
||||
_at(node, "contentImage", "thumbnailViewModel", "image", "sources"),
|
||||
)
|
||||
|
||||
|
||||
def _unavailable(data: dict) -> bool:
|
||||
"""Whether the watch page says the video is not available: its main column draws a
|
||||
`backgroundPromoRenderer` ("This video isn't available anymore") and there is no related column.
|
||||
YouTube's own word for "nothing related" — the one empty page that is not a shape we lost."""
|
||||
sections = _at(data, "contents", "twoColumnWatchNextResults", "results", "results", "contents")
|
||||
for section in sections if isinstance(sections, list) else []:
|
||||
inner = _at(section, "itemSectionRenderer", "contents")
|
||||
for node in inner if isinstance(inner, list) else []:
|
||||
if isinstance(node, dict) and "backgroundPromoRenderer" in node:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _items(data: dict) -> list | None:
|
||||
"""The page's item list (first page or continuation), or None when it has neither frame."""
|
||||
first = _at(data, *_FIRST)
|
||||
if isinstance(first, list):
|
||||
return first
|
||||
if _unavailable(data):
|
||||
return []
|
||||
for endpoint in data.get("onResponseReceivedEndpoints") or []:
|
||||
for key in _APPENDS:
|
||||
items = _at(endpoint, key, "continuationItems")
|
||||
if isinstance(items, list):
|
||||
return items
|
||||
return None
|
||||
|
||||
|
||||
def related(
|
||||
video_id: str, continuation: str | None = None, *, hl: str = "en", gl: str = "US"
|
||||
) -> dict:
|
||||
"""One page of `video_id`'s related videos (`continuation` = the token a previous page gave).
|
||||
|
||||
A video YouTube says it no longer has is an empty page. An answer of a shape this does not know
|
||||
— no related column, or one whose entries are all renderers it cannot read — is a `ScrapeError`:
|
||||
not an empty page, which would read as "nothing related"."""
|
||||
body = {"continuation": continuation} if continuation else {"videoId": video_id}
|
||||
data = post("next", body, hl=hl, gl=gl)
|
||||
items = _items(data)
|
||||
if items is None:
|
||||
raise ScrapeError("InnerTube returned no related list")
|
||||
out: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
token = None
|
||||
known = 0 # entries drawn by a renderer read here (a video's, or the cursor)
|
||||
for entry in items:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
if "lockupViewModel" in entry:
|
||||
item = _lockup(entry["lockupViewModel"])
|
||||
elif "compactVideoRenderer" in entry:
|
||||
item = video_renderer(entry["compactVideoRenderer"])
|
||||
else:
|
||||
found = continuation_token(entry.get("continuationItemRenderer"))
|
||||
known += found is not None
|
||||
token = token or found
|
||||
continue
|
||||
known += 1
|
||||
# A video by several channels draws an avatar stack, not one: no channel, left out.
|
||||
if item and item["channel_id"] and item["id"] not in seen:
|
||||
seen.add(item["id"])
|
||||
out.append(item)
|
||||
# A list with entries but none of them one we read: YouTube draws its items some new way.
|
||||
if items and not known:
|
||||
raise ScrapeError("InnerTube's related list holds no renderer this reads")
|
||||
return {"items": out, "next_page_token": token}
|
||||
@@ -6,9 +6,9 @@ calls — and read the result list straight out of the JSON. The returned video
|
||||
through the normal enrich path (videos.list, 1 unit / 50), exactly as the official search does,
|
||||
so the search itself is effectively free and only the (cheap, shared) enrichment is charged.
|
||||
|
||||
The SOCS=CAI consent-skip cookie is used like the Shorts probe so a server-side request isn't
|
||||
bounced to consent.youtube.com. This deliberately scrapes an undocumented endpoint: if YouTube
|
||||
changes the JSON shape or blocks the host, an admin can flip ``search_source`` back to ``api``.
|
||||
The request itself (the live key, the consent cookie) is `innertube`'s. This deliberately scrapes an
|
||||
undocumented endpoint: if YouTube changes the JSON shape or blocks the host, an admin can flip
|
||||
``search_source`` back to ``api``.
|
||||
|
||||
The returned page mirrors :meth:`YouTubeClient.search_videos` exactly
|
||||
(``{"items": [...], "next_page_token": str | None}``) so the route is source-agnostic — the
|
||||
@@ -17,110 +17,16 @@ only difference is the cursor is an InnerTube *continuation token*, not a Data A
|
||||
the real date is filled by the videos.list enrich. ``live_broadcast`` is reported as ``"none"``
|
||||
and live/upcoming filtering happens post-enrich via ``live_status`` (same as the API path)."""
|
||||
|
||||
import re
|
||||
from app.youtube.innertube import ScrapeError, continuation_token, post, video_renderer
|
||||
|
||||
import httpx
|
||||
__all__ = ["ScrapeError", "search"]
|
||||
|
||||
from app import logs
|
||||
|
||||
log = logs.get_logger(__name__)
|
||||
|
||||
_SEARCH_URL = "https://www.youtube.com/youtubei/v1/search"
|
||||
_RESULTS_URL = "https://www.youtube.com/results"
|
||||
# Public WEB InnerTube key + a recent client version. These are also embedded in every results
|
||||
# page; we fetch the live pair once and cache it, falling back to these constants.
|
||||
_FALLBACK_KEY = "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8"
|
||||
_FALLBACK_CLIENT_VERSION = "2.20240101.00.00"
|
||||
# sp / params value selecting the "type: video" search filter (base64 protobuf EgIQAQ==).
|
||||
_TYPE_VIDEO = "EgIQAQ=="
|
||||
|
||||
_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
|
||||
# SOCS skips YouTube's cookie-consent interstitial (otherwise every server-side request is
|
||||
# redirected to consent.youtube.com).
|
||||
"Cookie": "SOCS=CAI",
|
||||
"Accept-Language": "en-US,en;q=0.9",
|
||||
}
|
||||
|
||||
# The top-level keys a first page (contents) and a continuation page (onResponseReceivedCommands)
|
||||
# put their result list under.
|
||||
_RESULT_FRAMES = {"contents", "onResponseReceivedCommands"}
|
||||
_KEY_RE = re.compile(r'"INNERTUBE_API_KEY":"([^"]+)"')
|
||||
_VER_RE = re.compile(r'"INNERTUBE_CLIENT_VERSION":"([^"]+)"')
|
||||
|
||||
# Cached (api_key, client_version) extracted from a results page; refreshed on demand.
|
||||
_config: tuple[str, str] | None = None
|
||||
|
||||
|
||||
class ScrapeError(Exception):
|
||||
"""A scrape-based search could not be completed (network, blocked, or unexpected shape)."""
|
||||
|
||||
|
||||
def _runs_text(node: dict | None) -> str | None:
|
||||
if not node:
|
||||
return None
|
||||
if node.get("simpleText"):
|
||||
return node["simpleText"]
|
||||
runs = node.get("runs") or []
|
||||
if runs:
|
||||
return "".join(r.get("text", "") for r in runs)
|
||||
return None
|
||||
|
||||
|
||||
def _get_config(client: httpx.Client) -> tuple[str, str]:
|
||||
"""The current InnerTube (api_key, client_version), cached after the first fetch that FOUND them.
|
||||
|
||||
The fallback pair is never cached: it used to be, so one failed fetch (or a consent page with no
|
||||
keys on it) at the wrong moment pinned every later search to a hard-coded key and version for
|
||||
the life of the process — and when those went stale, search returned nothing, with no error
|
||||
anywhere. Now the next search simply tries the live pair again."""
|
||||
global _config
|
||||
if _config is not None:
|
||||
return _config
|
||||
try:
|
||||
html = client.get(_RESULTS_URL, params={"search_query": "music"}).text
|
||||
except httpx.HTTPError as exc:
|
||||
log.warning(
|
||||
"the InnerTube config could not be fetched; falling back to the pinned key",
|
||||
extra=logs.event("youtube.scrape.config_fallback", reason=type(exc).__name__),
|
||||
)
|
||||
return (_FALLBACK_KEY, _FALLBACK_CLIENT_VERSION)
|
||||
key = _KEY_RE.search(html)
|
||||
ver = _VER_RE.search(html)
|
||||
if key and ver:
|
||||
_config = (key.group(1), ver.group(1))
|
||||
return _config
|
||||
log.warning(
|
||||
"the results page carried no InnerTube config; falling back to the pinned key",
|
||||
extra=logs.event("youtube.scrape.config_fallback", reason="not_on_page"),
|
||||
)
|
||||
return (
|
||||
key.group(1) if key else _FALLBACK_KEY,
|
||||
ver.group(1) if ver else _FALLBACK_CLIENT_VERSION,
|
||||
)
|
||||
|
||||
|
||||
def _video_item(vr: dict) -> dict | None:
|
||||
"""Flatten a YouTube `videoRenderer` into the same shape as YouTubeClient.search_videos."""
|
||||
vid = vr.get("videoId")
|
||||
if not vid:
|
||||
return None
|
||||
owner = vr.get("ownerText") or vr.get("longBylineText") or {}
|
||||
runs = owner.get("runs") or []
|
||||
channel_id = channel_title = None
|
||||
if runs:
|
||||
channel_title = runs[0].get("text")
|
||||
channel_id = runs[0].get("navigationEndpoint", {}).get("browseEndpoint", {}).get("browseId")
|
||||
thumbs = (vr.get("thumbnail") or {}).get("thumbnails") or []
|
||||
return {
|
||||
"id": vid,
|
||||
"channel_id": channel_id,
|
||||
"channel_title": channel_title,
|
||||
"title": _runs_text(vr.get("title")),
|
||||
"published_at": None, # scrape exposes only a relative time; enrich fills the real date
|
||||
"thumbnail_url": thumbs[-1]["url"] if thumbs else None,
|
||||
"live_broadcast": "none", # live/upcoming filtered post-enrich via live_status
|
||||
}
|
||||
|
||||
|
||||
def _collect_videos(obj, out: list[dict], seen: set[str]) -> None:
|
||||
@@ -130,7 +36,7 @@ def _collect_videos(obj, out: list[dict], seen: set[str]) -> None:
|
||||
if isinstance(obj, dict):
|
||||
vr = obj.get("videoRenderer")
|
||||
if isinstance(vr, dict):
|
||||
item = _video_item(vr)
|
||||
item = video_renderer(vr)
|
||||
if item and item["id"] not in seen:
|
||||
seen.add(item["id"])
|
||||
out.append(item)
|
||||
@@ -144,11 +50,9 @@ def _collect_videos(obj, out: list[dict], seen: set[str]) -> None:
|
||||
def _find_continuation(obj) -> str | None:
|
||||
"""First continuationItemRenderer token (the 'load more' cursor), or None at the end."""
|
||||
if isinstance(obj, dict):
|
||||
cir = obj.get("continuationItemRenderer")
|
||||
if isinstance(cir, dict):
|
||||
tok = cir.get("continuationEndpoint", {}).get("continuationCommand", {}).get("token")
|
||||
if tok:
|
||||
return tok
|
||||
tok = continuation_token(obj.get("continuationItemRenderer"))
|
||||
if tok:
|
||||
return tok
|
||||
for v in obj.values():
|
||||
tok = _find_continuation(v)
|
||||
if tok:
|
||||
@@ -167,34 +71,14 @@ def search(q: str, continuation: str | None = None) -> dict:
|
||||
`continuation` is the InnerTube continuation token from a previous page (None for the first
|
||||
page). Returns ``{"items": [...], "next_page_token": str | None}`` — the same shape as
|
||||
YouTubeClient.search_videos so the route handles both sources identically."""
|
||||
with httpx.Client(timeout=20.0, headers=_HEADERS) as client:
|
||||
api_key, client_version = _get_config(client)
|
||||
context = {
|
||||
"client": {
|
||||
"clientName": "WEB",
|
||||
"clientVersion": client_version,
|
||||
"hl": "en",
|
||||
"gl": "US",
|
||||
}
|
||||
}
|
||||
body: dict = {"context": context}
|
||||
if continuation:
|
||||
body["continuation"] = continuation
|
||||
else:
|
||||
body["query"] = q
|
||||
body["params"] = _TYPE_VIDEO
|
||||
try:
|
||||
resp = client.post(_SEARCH_URL, params={"key": api_key}, json=body)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
except httpx.HTTPError as exc:
|
||||
raise ScrapeError(f"InnerTube request failed: {exc}") from exc
|
||||
except ValueError as exc: # non-JSON body (blocked / consent / captcha)
|
||||
raise ScrapeError("InnerTube returned a non-JSON response") from exc
|
||||
body: dict = (
|
||||
{"continuation": continuation} if continuation else {"query": q, "params": _TYPE_VIDEO}
|
||||
)
|
||||
data = post("search", body)
|
||||
|
||||
# Even a search with no results carries its result list's frame. Without one this is not "no
|
||||
# results" but a shape we do not know (YouTube moved, or a block page in JSON) — say so.
|
||||
if not isinstance(data, dict) or not _RESULT_FRAMES & data.keys():
|
||||
if not _RESULT_FRAMES & data.keys():
|
||||
raise ScrapeError("InnerTube returned an unexpected shape")
|
||||
items: list[dict] = []
|
||||
_collect_videos(data, items, set())
|
||||
|
||||
@@ -6,9 +6,10 @@
|
||||
# bumped in place instead of a full regeneration, which would move every other package too — then
|
||||
# `pip install -r requirements.lock && pip check` must pass. In place so far: urllib3 2.7.0 -> 2.8.0 (PYSEC-2026-4175/4176/4177); yt-dlp 2026.7.4 -> 2026.8.19
|
||||
# (it marks the clients that need a stream PO token, so the downloader stops fetching into a 403);
|
||||
# certifi 2026.7.22 -> 2026.10.19 (GHSA-6q48-6c7w-9gw2); brotli 1.2.0 -> 1.2.1 (PYSEC-2026-4322).
|
||||
# certifi 2026.7.22 -> 2026.10.19 (GHSA-6q48-6c7w-9gw2); brotli 1.2.0 -> 1.2.1 (PYSEC-2026-4322);
|
||||
# Authlib 1.7.2 -> 1.9.1 (CVE-2026-96760, CVE-2026-114616).
|
||||
APScheduler==3.11.3
|
||||
Authlib==1.7.2
|
||||
Authlib==1.9.1
|
||||
Mako==1.4.1
|
||||
MarkupSafe==3.0.3
|
||||
PyYAML==6.0.3
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
{
|
||||
"onResponseReceivedEndpoints": [
|
||||
{
|
||||
"appendContinuationItemsAction": {
|
||||
"continuationItems": [
|
||||
{
|
||||
"lockupViewModel": {
|
||||
"contentImage": {
|
||||
"thumbnailViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/_HfdncCbMOE/hqdefault.jpg?sqp=-oaymwEiCKgBEF5IWvKriqkDFQgBFQAAAAAYASUAAMhCPQCAokN4AQ==&rs=AOn4CLARvB39pkdsiuUUQTsZjkhvbKrfcQ",
|
||||
"width": 168,
|
||||
"height": 94
|
||||
},
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/_HfdncCbMOE/hqdefault.jpg?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLB15aZU5-tzwYCEbNTnZK3UX6ZCzQ",
|
||||
"width": 336,
|
||||
"height": 188
|
||||
}
|
||||
]
|
||||
},
|
||||
"overlays": [
|
||||
{
|
||||
"thumbnailBottomOverlayViewModel": {
|
||||
"badges": [
|
||||
{
|
||||
"thumbnailBadgeViewModel": {
|
||||
"text": "1:08:18",
|
||||
"badgeStyle": "THUMBNAIL_OVERLAY_BADGE_STYLE_DEFAULT",
|
||||
"animationActivationTargetId": "_HfdncCbMOE",
|
||||
"animatedText": "Now playing",
|
||||
"animationActivationEntitySelectorType": "THUMBNAIL_BADGE_ANIMATION_ENTITY_SELECTOR_TYPE_PLAYER_STATE"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"lockupMetadataViewModel": {
|
||||
"title": {
|
||||
"content": "MIT 6.S191 (2025): Large Language Models (Liquid AI)"
|
||||
},
|
||||
"image": {
|
||||
"decoratedAvatarViewModel": {
|
||||
"avatar": {
|
||||
"avatarViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://yt3.ggpht.com/ytc/AIdro_k517G0Dt8QgsF86GKzYkG3Rs8jSGCiYGJw04lx4_1KXQ=s68-c-k-c0x00ffffff-no-rj",
|
||||
"width": 68,
|
||||
"height": 68
|
||||
}
|
||||
]
|
||||
},
|
||||
"avatarImageSize": "AVATAR_SIZE_M"
|
||||
}
|
||||
},
|
||||
"a11yLabel": "Go to channel Alexander Amini",
|
||||
"rendererContext": {
|
||||
"commandContext": {
|
||||
"onTap": {
|
||||
"innertubeCommand": {
|
||||
"browseEndpoint": {
|
||||
"browseId": "UCtslD4DGH6PKyG_1gFAX7sg"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"contentMetadataViewModel": {
|
||||
"metadataRows": [
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "Alexander Amini"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "62K"
|
||||
},
|
||||
"accessibilityLabel": "62 thousand views",
|
||||
"leadingIcon": {
|
||||
"name": "PLAY_ARROW_OUTLINED",
|
||||
"height": 12,
|
||||
"width": 12,
|
||||
"marginEndToken": {
|
||||
"spacing": 2
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"text": {
|
||||
"content": "1y ago"
|
||||
},
|
||||
"accessibilityLabel": "1 year ago"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"delimiter": " "
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"contentId": "_HfdncCbMOE",
|
||||
"contentType": "LOCKUP_CONTENT_TYPE_VIDEO",
|
||||
"themedPalette": {
|
||||
"lightThemePalette": {
|
||||
"baseBackground": 4294964720,
|
||||
"raisedBackground": 4294964720,
|
||||
"additiveBackground": 566850118,
|
||||
"textPrimary": 4281800969,
|
||||
"textSecondary": 4285876787,
|
||||
"outline": 860759827,
|
||||
"keyLight": 4292983720,
|
||||
"collectionStack": 4291337092,
|
||||
"invertedBackground": 4287578649,
|
||||
"textPrimaryInverse": 4294964720,
|
||||
"textDisabled": 2135828243,
|
||||
"dropShadow": 432632390,
|
||||
"cardOutline": 180974150,
|
||||
"overlayBackground": 3426162953,
|
||||
"overlayTextPrimary": 4294964720,
|
||||
"solidWash": 4283311891,
|
||||
"solidRim": 4281800969,
|
||||
"overlaySolidWash": 4294699488,
|
||||
"overlaySolidRim": 4294964720,
|
||||
"tonalWash": 2583688688,
|
||||
"tonalRim": 202310912,
|
||||
"overlayTonalWash": 436205040,
|
||||
"overlayTonalRim": 436205040,
|
||||
"outlineRim": 1280190227,
|
||||
"overlayOutlineRim": 871618504,
|
||||
"solidWashInverse": 4294170568,
|
||||
"solidRimInverse": 2147215840,
|
||||
"tonalWashInverse": 654308848,
|
||||
"tonalRimInverse": 654043616,
|
||||
"outlineRimInverse": 654308848,
|
||||
"solidBackground": 4283311891,
|
||||
"solidBackgroundInverse": 4291337092,
|
||||
"tonalBackground": 868785028,
|
||||
"tonalBackgroundInverse": 435410888,
|
||||
"outlineInverse": 872147424,
|
||||
"directionalLightStopPrimary": 4294699488,
|
||||
"directionalLightStopSecondary": 4294964720,
|
||||
"primary": 4279174400,
|
||||
"filledStateLayer": 4281800969,
|
||||
"tonalTouchLight": 4294964720,
|
||||
"tonalHoverLight": 3439061472,
|
||||
"tonalStateLayer": 420414720,
|
||||
"overlayDisabledContainer": 871618504,
|
||||
"overlayTonalTouchLight": 1291577824,
|
||||
"overlayTonalHoverLight": 1291577824,
|
||||
"overlayTonalStateLayer": 436205040,
|
||||
"disabledContainer": 420414720,
|
||||
"filledTouchLight": 4285876787,
|
||||
"filledHoverLight": 4284627235,
|
||||
"onOverlayDisabledContainer": 2583688688,
|
||||
"overlayTonalContainer": 2583423456,
|
||||
"overlayOutline": 872412656,
|
||||
"onFilledContainer": 4294964720,
|
||||
"filledContainer": 4280027906,
|
||||
"tonalContainer": 641145097,
|
||||
"overlayPrimary": 4294964720,
|
||||
"onOverlayFilledContainer": 4279174400,
|
||||
"overlayFilledTouchLight": 4294964720,
|
||||
"overlayFilledHoverLight": 4294699488,
|
||||
"overlayFilledStateLayer": 4292983720,
|
||||
"overlayFilledContainer": 4294170568,
|
||||
"onDisabledContainer": 1712260352,
|
||||
"temporaryOutline": 860759827
|
||||
},
|
||||
"darkThemePalette": {
|
||||
"baseBackground": 4280027906,
|
||||
"raisedBackground": 4281800969,
|
||||
"additiveBackground": 734622278,
|
||||
"textPrimary": 4294699488,
|
||||
"textSecondary": 4292983720,
|
||||
"outline": 1072945096,
|
||||
"keyLight": 4284627235,
|
||||
"collectionStack": 4285876787,
|
||||
"invertedBackground": 4293107837,
|
||||
"textPrimaryInverse": 4280027906,
|
||||
"textDisabled": 2146686920,
|
||||
"dropShadow": 432632390,
|
||||
"cardOutline": 180974150,
|
||||
"overlayBackground": 3426162953,
|
||||
"overlayTextPrimary": 4294964720,
|
||||
"solidWash": 4294699488,
|
||||
"solidRim": 4294964720,
|
||||
"overlaySolidWash": 4294699488,
|
||||
"overlaySolidRim": 4294964720,
|
||||
"tonalWash": 217307080,
|
||||
"tonalRim": 218101232,
|
||||
"overlayTonalWash": 436205040,
|
||||
"overlayTonalRim": 436205040,
|
||||
"outlineRim": 871618504,
|
||||
"overlayOutlineRim": 871618504,
|
||||
"solidWashInverse": 4285876787,
|
||||
"solidRimInverse": 871618504,
|
||||
"tonalWashInverse": 872412656,
|
||||
"tonalRimInverse": 870431656,
|
||||
"outlineRimInverse": 1291843056,
|
||||
"solidBackground": 4291337092,
|
||||
"solidBackgroundInverse": 4283311891,
|
||||
"tonalBackground": 435410888,
|
||||
"tonalBackgroundInverse": 868785028,
|
||||
"outlineInverse": 860759827,
|
||||
"directionalLightStopPrimary": 4281800969,
|
||||
"directionalLightStopSecondary": 4280027906,
|
||||
"primary": 4294964720,
|
||||
"filledStateLayer": 4292983720,
|
||||
"tonalTouchLight": 1073474016,
|
||||
"tonalHoverLight": 654043616,
|
||||
"tonalStateLayer": 436205040,
|
||||
"overlayDisabledContainer": 871618504,
|
||||
"overlayTonalTouchLight": 1291577824,
|
||||
"overlayTonalHoverLight": 1291577824,
|
||||
"overlayTonalStateLayer": 436205040,
|
||||
"disabledContainer": 436205040,
|
||||
"filledTouchLight": 4294964720,
|
||||
"filledHoverLight": 4294699488,
|
||||
"onOverlayDisabledContainer": 2583688688,
|
||||
"overlayTonalContainer": 2583423456,
|
||||
"overlayOutline": 872412656,
|
||||
"onFilledContainer": 4279174400,
|
||||
"filledContainer": 4294170568,
|
||||
"tonalContainer": 435410888,
|
||||
"overlayPrimary": 4294964720,
|
||||
"onOverlayFilledContainer": 4279174400,
|
||||
"overlayFilledTouchLight": 4294964720,
|
||||
"overlayFilledHoverLight": 4294699488,
|
||||
"overlayFilledStateLayer": 4292983720,
|
||||
"overlayFilledContainer": 4294170568,
|
||||
"onDisabledContainer": 1728050672,
|
||||
"temporaryOutline": 871618504
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"lockupViewModel": {
|
||||
"contentImage": {
|
||||
"thumbnailViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/P7Hkh2zOGQ0/hqdefault.jpg?sqp=-oaymwEiCKgBEF5IWvKriqkDFQgBFQAAAAAYASUAAMhCPQCAokN4AQ==&rs=AOn4CLAHInNtMierSAgtrGl5rLSKc-vdzQ",
|
||||
"width": 168,
|
||||
"height": 94
|
||||
},
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/P7Hkh2zOGQ0/hqdefault.jpg?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDXrm5g-rdjRIqqK309ImTdqpw4CA",
|
||||
"width": 336,
|
||||
"height": 188
|
||||
}
|
||||
]
|
||||
},
|
||||
"overlays": [
|
||||
{
|
||||
"thumbnailBottomOverlayViewModel": {
|
||||
"badges": [
|
||||
{
|
||||
"thumbnailBadgeViewModel": {
|
||||
"text": "1:08:19",
|
||||
"badgeStyle": "THUMBNAIL_OVERLAY_BADGE_STYLE_DEFAULT",
|
||||
"animationActivationTargetId": "P7Hkh2zOGQ0",
|
||||
"animatedText": "Now playing",
|
||||
"animationActivationEntitySelectorType": "THUMBNAIL_BADGE_ANIMATION_ENTITY_SELECTOR_TYPE_PLAYER_STATE"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"lockupMetadataViewModel": {
|
||||
"title": {
|
||||
"content": "MIT 6.S191 (2024): Google - Generative AI for Media"
|
||||
},
|
||||
"image": {
|
||||
"decoratedAvatarViewModel": {
|
||||
"avatar": {
|
||||
"avatarViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://yt3.ggpht.com/ytc/AIdro_k517G0Dt8QgsF86GKzYkG3Rs8jSGCiYGJw04lx4_1KXQ=s68-c-k-c0x00ffffff-no-rj",
|
||||
"width": 68,
|
||||
"height": 68
|
||||
}
|
||||
]
|
||||
},
|
||||
"avatarImageSize": "AVATAR_SIZE_M"
|
||||
}
|
||||
},
|
||||
"a11yLabel": "Go to channel Alexander Amini",
|
||||
"rendererContext": {
|
||||
"commandContext": {
|
||||
"onTap": {
|
||||
"innertubeCommand": {
|
||||
"browseEndpoint": {
|
||||
"browseId": "UCtslD4DGH6PKyG_1gFAX7sg"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"contentMetadataViewModel": {
|
||||
"metadataRows": [
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "Alexander Amini"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "49K"
|
||||
},
|
||||
"accessibilityLabel": "49 thousand views",
|
||||
"leadingIcon": {
|
||||
"name": "PLAY_ARROW_OUTLINED",
|
||||
"height": 12,
|
||||
"width": 12,
|
||||
"marginEndToken": {
|
||||
"spacing": 2
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"text": {
|
||||
"content": "2y ago"
|
||||
},
|
||||
"accessibilityLabel": "2 years ago"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"delimiter": " "
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"contentId": "P7Hkh2zOGQ0",
|
||||
"contentType": "LOCKUP_CONTENT_TYPE_VIDEO",
|
||||
"themedPalette": {
|
||||
"lightThemePalette": {
|
||||
"baseBackground": 4293981951,
|
||||
"raisedBackground": 4293981951,
|
||||
"additiveBackground": 558201801,
|
||||
"textPrimary": 4278655801,
|
||||
"textSecondary": 4280831104,
|
||||
"outline": 856631890,
|
||||
"keyLight": 4288855783,
|
||||
"collectionStack": 4286094803,
|
||||
"invertedBackground": 4279847311,
|
||||
"textPrimaryInverse": 4293981951,
|
||||
"textDisabled": 2131700306,
|
||||
"dropShadow": 423984073,
|
||||
"cardOutline": 172325833,
|
||||
"overlayBackground": 3423017785,
|
||||
"overlayTextPrimary": 4293981951,
|
||||
"solidWash": 4279183954,
|
||||
"solidRim": 4278655801,
|
||||
"overlaySolidWash": 4292864764,
|
||||
"overlaySolidRim": 4293981951,
|
||||
"tonalWash": 2582705919,
|
||||
"tonalRim": 201328143,
|
||||
"overlayTonalWash": 435222271,
|
||||
"overlayTonalRim": 435222271,
|
||||
"outlineRim": 1276062290,
|
||||
"overlayOutlineRim": 868669942,
|
||||
"solidWashInverse": 4291222006,
|
||||
"solidRimInverse": 2145381116,
|
||||
"tonalWashInverse": 653326079,
|
||||
"tonalRimInverse": 652208892,
|
||||
"outlineRimInverse": 653326079,
|
||||
"solidBackground": 4279183954,
|
||||
"solidBackgroundInverse": 4286094803,
|
||||
"tonalBackground": 863542739,
|
||||
"tonalBackgroundInverse": 432462326,
|
||||
"outlineInverse": 870312700,
|
||||
"directionalLightStopPrimary": 4292864764,
|
||||
"directionalLightStopSecondary": 4293981951,
|
||||
"primary": 4278191631,
|
||||
"filledStateLayer": 4278655801,
|
||||
"tonalTouchLight": 4293981951,
|
||||
"tonalHoverLight": 3437226748,
|
||||
"tonalStateLayer": 419431951,
|
||||
"overlayDisabledContainer": 868669942,
|
||||
"overlayTonalTouchLight": 1289743100,
|
||||
"overlayTonalHoverLight": 1289743100,
|
||||
"overlayTonalStateLayer": 435222271,
|
||||
"disabledContainer": 419431951,
|
||||
"filledTouchLight": 4280831104,
|
||||
"filledHoverLight": 4280040297,
|
||||
"onOverlayDisabledContainer": 2582705919,
|
||||
"overlayTonalContainer": 2581588732,
|
||||
"overlayOutline": 871429887,
|
||||
"onFilledContainer": 4293981951,
|
||||
"filledContainer": 4278324509,
|
||||
"tonalContainer": 637999929,
|
||||
"overlayPrimary": 4293981951,
|
||||
"onOverlayFilledContainer": 4278191631,
|
||||
"overlayFilledTouchLight": 4293981951,
|
||||
"overlayFilledHoverLight": 4292864764,
|
||||
"overlayFilledStateLayer": 4288855783,
|
||||
"overlayFilledContainer": 4291222006,
|
||||
"onDisabledContainer": 1711277583,
|
||||
"temporaryOutline": 856631890
|
||||
},
|
||||
"darkThemePalette": {
|
||||
"baseBackground": 4278324509,
|
||||
"raisedBackground": 4278655801,
|
||||
"additiveBackground": 725973961,
|
||||
"textPrimary": 4292864764,
|
||||
"textSecondary": 4288855783,
|
||||
"outline": 1069996534,
|
||||
"keyLight": 4280040297,
|
||||
"collectionStack": 4280831104,
|
||||
"invertedBackground": 4286359267,
|
||||
"textPrimaryInverse": 4278324509,
|
||||
"textDisabled": 2143738358,
|
||||
"dropShadow": 423984073,
|
||||
"cardOutline": 172325833,
|
||||
"overlayBackground": 3423017785,
|
||||
"overlayTextPrimary": 4293981951,
|
||||
"solidWash": 4292864764,
|
||||
"solidRim": 4293981951,
|
||||
"overlaySolidWash": 4292864764,
|
||||
"overlaySolidRim": 4293981951,
|
||||
"tonalWash": 214358518,
|
||||
"tonalRim": 217118463,
|
||||
"overlayTonalWash": 435222271,
|
||||
"overlayTonalRim": 435222271,
|
||||
"outlineRim": 868669942,
|
||||
"overlayOutlineRim": 868669942,
|
||||
"solidWashInverse": 4280831104,
|
||||
"solidRimInverse": 868669942,
|
||||
"tonalWashInverse": 871429887,
|
||||
"tonalRimInverse": 866303719,
|
||||
"outlineRimInverse": 1290860287,
|
||||
"solidBackground": 4286094803,
|
||||
"solidBackgroundInverse": 4279183954,
|
||||
"tonalBackground": 432462326,
|
||||
"tonalBackgroundInverse": 863542739,
|
||||
"outlineInverse": 856631890,
|
||||
"directionalLightStopPrimary": 4278655801,
|
||||
"directionalLightStopSecondary": 4278324509,
|
||||
"primary": 4293981951,
|
||||
"filledStateLayer": 4288855783,
|
||||
"tonalTouchLight": 1071639292,
|
||||
"tonalHoverLight": 652208892,
|
||||
"tonalStateLayer": 435222271,
|
||||
"overlayDisabledContainer": 868669942,
|
||||
"overlayTonalTouchLight": 1289743100,
|
||||
"overlayTonalHoverLight": 1289743100,
|
||||
"overlayTonalStateLayer": 435222271,
|
||||
"disabledContainer": 435222271,
|
||||
"filledTouchLight": 4293981951,
|
||||
"filledHoverLight": 4292864764,
|
||||
"onOverlayDisabledContainer": 2582705919,
|
||||
"overlayTonalContainer": 2581588732,
|
||||
"overlayOutline": 871429887,
|
||||
"onFilledContainer": 4278191631,
|
||||
"filledContainer": 4291222006,
|
||||
"tonalContainer": 432462326,
|
||||
"overlayPrimary": 4293981951,
|
||||
"onOverlayFilledContainer": 4278191631,
|
||||
"overlayFilledTouchLight": 4293981951,
|
||||
"overlayFilledHoverLight": 4292864764,
|
||||
"overlayFilledStateLayer": 4288855783,
|
||||
"overlayFilledContainer": 4291222006,
|
||||
"onDisabledContainer": 1727067903,
|
||||
"temporaryOutline": 868669942
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"continuationItemRenderer": {
|
||||
"trigger": "CONTINUATION_TRIGGER_ON_ITEM_SHOWN",
|
||||
"continuationEndpoint": {
|
||||
"commandMetadata": {
|
||||
"webCommandMetadata": {
|
||||
"sendPost": true,
|
||||
"apiUrl": "/youtubei/v1/next"
|
||||
}
|
||||
},
|
||||
"continuationCommand": {
|
||||
"token": "CCgSDRILU2RUWkFNREtyTlkYACqPDE1nb0lodVQ4eG9EdXVLSUYyczZMNnd6NENBcjFDQW9EOGo0QUNnN0NQZ3NJbk1XcnZzbWo2Y2UyQVFvRDhqNEFDZzNDUGdvSW90N0czWnVCMy1KSENnUHlQZ0FLRGNJLUNnaTVfOGVUbjV5cTJSd0tBX0ktQUFvT3dqNExDSkQydWJfNXp2ZXZfUUVLQV9JLUFBb053ajRLQ1BXWjVQakt2cjZWU2dvRDhqNEFDZzNDUGdvSW9aTDd1OUtGdF85NkNnUHlQZ0FLRGNJLUNnaUh3N2FLMzd6YzVIZ0tBX0ktQUFvT3dqNExDUE94aHRQTWtfVzB1UUVLQV9JLUFBb093ajRMQ092eTBzaXNsSWZScGdFS0FfSS1BQW9Pd2o0TENKS1FxdHpBeE5lZHJBRUtBX0ktQUFvTndqNEtDTFdteWE2cHNPMkJPZ29EOGo0QUNnM0NQZ29JanYtdy1wQ3k1YVozQ2dQeVBnQUtEc0ktQ3dqMmtmVF9tYlB1XzRvQkNnUHlQZ0FLRHNJLUN3aVpuYWZjc0tQVmpZUUJDZ1B5UGdBS0RjSS1DZ2lxM3BxM3FyX2s0U0VLQV9JLUFBb053ajRLQ0phNXU5eVJvTmJOS0FvRDhqNEFDZzNDUGdvSXFMeWR3T1NhNGJkV0NnUHlQZ0FLRGNJLUNnakh3X2ZucktlSDdXUUtBX0ktQUFvTndqNEtDUG4xak1mcXg4QzJNQW9EOGo0QUNnM0NQZ29JeWRpdXV0VDQ3UHNhQ2dQeVBnQUtEc0ktQ3dqaDRleUUzTFAzdV93QkNnUHlQZ0FLRGNJLUNnaU5zcmptOXBENTJEOEtBX0ktQUFvTndqNEtDTExudjR5ZXg3U1dTUW9EOGo0QUNnM0NQZ29JNnZHODhaR1JpTWNnQ2dQeVBnQUtEc0ktQ3dpRF85S3Z5WS1hbThJQkNnUHlQZ0FLRHNJLUN3alppNmJYbWR6YWxZb0JDZ1B5UGdBS0RzSS1Dd2lkemJfS2dPdWN0YUFCQ2dQeVBnQUtEY0ktQ2dqMXktMjYyb2JQeFdNS0FfSS1BQW9Pd2o0TENPLUE4SWVaMUlESXJRRUtBX0ktQUFvTndqNEtDUHlZNDVhUzhkeWpJZ29EOGo0QUNnM0NQZ29Jb191aWtfSE05ZHdTQ2dQeVBnQUtEc0ktQ3dqaTBiemlrdnpBbkxvQkNnUHlQZ0FLRHNJLUN3aW05cXI1eXNtTWlzOEJDZ1B5UGdBS0RjSS1DZ2k3M2V5NXlzQ1pzMG9LQV9JLUFBb093ajRMQ0xmT281WFU1X2JPbFFFS0FfSS1BQW9Od2o0S0NLTEVwYXlXOTliWkdnb0Q4ajRBQ2c3Q1Bnc0k2dWZSMnRPM3hLem9BUW9EOGo0QUNnN0NQZ3NJN2ZlZXZQRHV2WlRXQVFvRDhqNEFDZzNDUGdvSXFibS0zYXVBdDVWcUNnUHlQZ0FLRGNJLUNnaUc1UHpHZ082NG9nVVNLQUFDQkFZSUNnd09FQklVRmhnYUhCNGdJaVFtS0Nvc0xqQXlORFk0T2p3LVFFSkVSa2hLVEU0YUJBZ0FFQUVhQkFnQ0VBTWFCQWdFRUFVYUJBZ0dFQWNhQkFnSUVBa2FCQWdLRUFzYUJBZ01FQTBhQkFnT0VBOGFCQWdRRUJFYUJBZ1NFQk1hQkFnVUVCVWFCQWdXRUJjYUJBZ1lFQmthQkFnYUVCc2FCQWdjRUIwYUJBZ2VFQjhhQkFnZ0VDRWFCQWdpRUNNYUJBZ2tFQ1VhQkFnbUVDY2FCQWdvRUNrYUJBZ3FFQ3NhQkFnc0VDMGFCQWd1RUM4YUJBZ3dFREVhQkFneUVETWFCQWcwRURVYUJBZzJFRGNhQkFnNEVEa2FCQWc2RURzYUJBZzhFRDBhQkFnLUVEOGFCQWhBRUVFYUJBaENFRU1hQkFoRUVFVWFCQWhHRUVjYUJBaElFRWthQkFoS0VFc2FCQWhNRUUwYUJBaE9FRThxS0FBQ0JBWUlDZ3dPRUJJVUZoZ2FIQjRnSWlRbUtDb3NMakF5TkRZNE9qdy1RRUpFUmtoS1RFNGoPd2F0Y2gtbmV4dC1mZWVk",
|
||||
"request": "CONTINUATION_REQUEST_TYPE_WATCH_NEXT"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+805
@@ -0,0 +1,805 @@
|
||||
{
|
||||
"contents": {
|
||||
"twoColumnWatchNextResults": {
|
||||
"secondaryResults": {
|
||||
"secondaryResults": {
|
||||
"results": [
|
||||
{
|
||||
"lockupViewModel": {
|
||||
"contentImage": {
|
||||
"thumbnailViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/to-lHJfK4pw/hqdefault.jpg?sqp=-oaymwEiCKgBEF5IWvKriqkDFQgBFQAAAAAYASUAAMhCPQCAokN4AQ==&rs=AOn4CLBKP_oFChvoqvwVrKAy_PG9bn2_AA",
|
||||
"width": 168,
|
||||
"height": 94
|
||||
},
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/to-lHJfK4pw/hqdefault.jpg?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDyH3Z8DJhXMmFJ5eKEWMufk7ql9g",
|
||||
"width": 336,
|
||||
"height": 188
|
||||
}
|
||||
]
|
||||
},
|
||||
"overlays": [
|
||||
{
|
||||
"thumbnailBottomOverlayViewModel": {
|
||||
"badges": [
|
||||
{
|
||||
"thumbnailBadgeViewModel": {
|
||||
"text": "1:02:00",
|
||||
"badgeStyle": "THUMBNAIL_OVERLAY_BADGE_STYLE_DEFAULT",
|
||||
"animationActivationTargetId": "to-lHJfK4pw",
|
||||
"animatedText": "Now playing",
|
||||
"animationActivationEntitySelectorType": "THUMBNAIL_BADGE_ANIMATION_ENTITY_SELECTOR_TYPE_PLAYER_STATE"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"lockupMetadataViewModel": {
|
||||
"title": {
|
||||
"content": "MIT 6.S191 (2025): Reinforcement Learning"
|
||||
},
|
||||
"image": {
|
||||
"decoratedAvatarViewModel": {
|
||||
"avatar": {
|
||||
"avatarViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://yt3.ggpht.com/ytc/AIdro_k517G0Dt8QgsF86GKzYkG3Rs8jSGCiYGJw04lx4_1KXQ=s68-c-k-c0x00ffffff-no-rj",
|
||||
"width": 68,
|
||||
"height": 68
|
||||
}
|
||||
]
|
||||
},
|
||||
"avatarImageSize": "AVATAR_SIZE_M"
|
||||
}
|
||||
},
|
||||
"a11yLabel": "Go to channel Alexander Amini",
|
||||
"rendererContext": {
|
||||
"commandContext": {
|
||||
"onTap": {
|
||||
"innertubeCommand": {
|
||||
"browseEndpoint": {
|
||||
"browseId": "UCtslD4DGH6PKyG_1gFAX7sg"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"contentMetadataViewModel": {
|
||||
"metadataRows": [
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "Alexander Amini"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "128K"
|
||||
},
|
||||
"accessibilityLabel": "128 thousand views",
|
||||
"leadingIcon": {
|
||||
"name": "PLAY_ARROW_OUTLINED",
|
||||
"height": 12,
|
||||
"width": 12,
|
||||
"marginEndToken": {
|
||||
"spacing": 2
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"text": {
|
||||
"content": "1y ago"
|
||||
},
|
||||
"accessibilityLabel": "1 year ago"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"delimiter": " "
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"contentId": "to-lHJfK4pw",
|
||||
"contentType": "LOCKUP_CONTENT_TYPE_VIDEO",
|
||||
"themedPalette": {
|
||||
"lightThemePalette": {
|
||||
"baseBackground": 4293981439,
|
||||
"raisedBackground": 4293981439,
|
||||
"additiveBackground": 558196425,
|
||||
"textPrimary": 4278850870,
|
||||
"textSecondary": 4282009454,
|
||||
"outline": 857088843,
|
||||
"keyLight": 4289509597,
|
||||
"collectionStack": 4287338944,
|
||||
"invertedBackground": 4279842703,
|
||||
"textPrimaryInverse": 4293981439,
|
||||
"textDisabled": 2132157259,
|
||||
"dropShadow": 423978697,
|
||||
"cardOutline": 172320457,
|
||||
"overlayBackground": 3423212854,
|
||||
"overlayTextPrimary": 4293981439,
|
||||
"solidWash": 4279640907,
|
||||
"solidRim": 4278850870,
|
||||
"overlaySolidWash": 4292929530,
|
||||
"overlaySolidRim": 4293981439,
|
||||
"tonalWash": 2582705407,
|
||||
"tonalRim": 201327631,
|
||||
"overlayTonalWash": 435221759,
|
||||
"overlayTonalRim": 435221759,
|
||||
"outlineRim": 1276519243,
|
||||
"overlayOutlineRim": 868930802,
|
||||
"solidWashInverse": 4291482866,
|
||||
"solidRimInverse": 2145445882,
|
||||
"tonalWashInverse": 653325567,
|
||||
"tonalRimInverse": 652273658,
|
||||
"outlineRimInverse": 653325567,
|
||||
"solidBackground": 4279640907,
|
||||
"solidBackgroundInverse": 4287338944,
|
||||
"tonalBackground": 864786880,
|
||||
"tonalBackgroundInverse": 432723186,
|
||||
"outlineInverse": 870377466,
|
||||
"directionalLightStopPrimary": 4292929530,
|
||||
"directionalLightStopSecondary": 4293981439,
|
||||
"primary": 4278191119,
|
||||
"filledStateLayer": 4278850870,
|
||||
"tonalTouchLight": 4293981439,
|
||||
"tonalHoverLight": 3437291514,
|
||||
"tonalStateLayer": 419431439,
|
||||
"overlayDisabledContainer": 868930802,
|
||||
"overlayTonalTouchLight": 1289807866,
|
||||
"overlayTonalHoverLight": 1289807866,
|
||||
"overlayTonalStateLayer": 435221759,
|
||||
"disabledContainer": 419431439,
|
||||
"filledTouchLight": 4282009454,
|
||||
"filledHoverLight": 4280825181,
|
||||
"onOverlayDisabledContainer": 2582705407,
|
||||
"overlayTonalContainer": 2581653498,
|
||||
"overlayOutline": 871429375,
|
||||
"onFilledContainer": 4293981439,
|
||||
"filledContainer": 4278323484,
|
||||
"tonalContainer": 638194998,
|
||||
"overlayPrimary": 4293981439,
|
||||
"onOverlayFilledContainer": 4278191119,
|
||||
"overlayFilledTouchLight": 4293981439,
|
||||
"overlayFilledHoverLight": 4292929530,
|
||||
"overlayFilledStateLayer": 4289509597,
|
||||
"overlayFilledContainer": 4291482866,
|
||||
"onDisabledContainer": 1711277071,
|
||||
"temporaryOutline": 857088843
|
||||
},
|
||||
"darkThemePalette": {
|
||||
"baseBackground": 4278323484,
|
||||
"raisedBackground": 4278850870,
|
||||
"additiveBackground": 725968585,
|
||||
"textPrimary": 4292929530,
|
||||
"textSecondary": 4289509597,
|
||||
"outline": 1070257394,
|
||||
"keyLight": 4280825181,
|
||||
"collectionStack": 4282009454,
|
||||
"invertedBackground": 4286355427,
|
||||
"textPrimaryInverse": 4278323484,
|
||||
"textDisabled": 2143999218,
|
||||
"dropShadow": 423978697,
|
||||
"cardOutline": 172320457,
|
||||
"overlayBackground": 3423212854,
|
||||
"overlayTextPrimary": 4293981439,
|
||||
"solidWash": 4292929530,
|
||||
"solidRim": 4293981439,
|
||||
"overlaySolidWash": 4292929530,
|
||||
"overlaySolidRim": 4293981439,
|
||||
"tonalWash": 214619378,
|
||||
"tonalRim": 217117951,
|
||||
"overlayTonalWash": 435221759,
|
||||
"overlayTonalRim": 435221759,
|
||||
"outlineRim": 868930802,
|
||||
"overlayOutlineRim": 868930802,
|
||||
"solidWashInverse": 4282009454,
|
||||
"solidRimInverse": 868930802,
|
||||
"tonalWashInverse": 871429375,
|
||||
"tonalRimInverse": 866957533,
|
||||
"outlineRimInverse": 1290859775,
|
||||
"solidBackground": 4287338944,
|
||||
"solidBackgroundInverse": 4279640907,
|
||||
"tonalBackground": 432723186,
|
||||
"tonalBackgroundInverse": 864786880,
|
||||
"outlineInverse": 857088843,
|
||||
"directionalLightStopPrimary": 4278850870,
|
||||
"directionalLightStopSecondary": 4278323484,
|
||||
"primary": 4293981439,
|
||||
"filledStateLayer": 4289509597,
|
||||
"tonalTouchLight": 1071704058,
|
||||
"tonalHoverLight": 652273658,
|
||||
"tonalStateLayer": 435221759,
|
||||
"overlayDisabledContainer": 868930802,
|
||||
"overlayTonalTouchLight": 1289807866,
|
||||
"overlayTonalHoverLight": 1289807866,
|
||||
"overlayTonalStateLayer": 435221759,
|
||||
"disabledContainer": 435221759,
|
||||
"filledTouchLight": 4293981439,
|
||||
"filledHoverLight": 4292929530,
|
||||
"onOverlayDisabledContainer": 2582705407,
|
||||
"overlayTonalContainer": 2581653498,
|
||||
"overlayOutline": 871429375,
|
||||
"onFilledContainer": 4278191119,
|
||||
"filledContainer": 4291482866,
|
||||
"tonalContainer": 432723186,
|
||||
"overlayPrimary": 4293981439,
|
||||
"onOverlayFilledContainer": 4278191119,
|
||||
"overlayFilledTouchLight": 4293981439,
|
||||
"overlayFilledHoverLight": 4292929530,
|
||||
"overlayFilledStateLayer": 4289509597,
|
||||
"overlayFilledContainer": 4291482866,
|
||||
"onDisabledContainer": 1727067391,
|
||||
"temporaryOutline": 868930802
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"lockupViewModel": {
|
||||
"contentImage": {
|
||||
"thumbnailViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/R8V8CbuxryI/hqdefault.jpg?sqp=-oaymwEiCKgBEF5IWvKriqkDFQgBFQAAAAAYASUAAMhCPQCAokN4AQ==&rs=AOn4CLDqXMjrpgDyQKHL2lWrxczwxKoefw",
|
||||
"width": 168,
|
||||
"height": 94
|
||||
},
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/R8V8CbuxryI/hqdefault.jpg?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLB7JX9Z238s6DGqIS5-fhcEIkUxKw",
|
||||
"width": 336,
|
||||
"height": 188
|
||||
}
|
||||
]
|
||||
},
|
||||
"overlays": [
|
||||
{
|
||||
"thumbnailBottomOverlayViewModel": {
|
||||
"badges": [
|
||||
{
|
||||
"thumbnailBadgeViewModel": {
|
||||
"text": "49:36",
|
||||
"badgeStyle": "THUMBNAIL_OVERLAY_BADGE_STYLE_DEFAULT",
|
||||
"animationActivationTargetId": "R8V8CbuxryI",
|
||||
"animatedText": "Now playing",
|
||||
"animationActivationEntitySelectorType": "THUMBNAIL_BADGE_ANIMATION_ENTITY_SELECTOR_TYPE_PLAYER_STATE"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"lockupMetadataViewModel": {
|
||||
"title": {
|
||||
"content": "MIT 6.S191: Deep Generative Modeling"
|
||||
},
|
||||
"image": {
|
||||
"decoratedAvatarViewModel": {
|
||||
"avatar": {
|
||||
"avatarViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://yt3.ggpht.com/ytc/AIdro_k517G0Dt8QgsF86GKzYkG3Rs8jSGCiYGJw04lx4_1KXQ=s68-c-k-c0x00ffffff-no-rj",
|
||||
"width": 68,
|
||||
"height": 68
|
||||
}
|
||||
]
|
||||
},
|
||||
"avatarImageSize": "AVATAR_SIZE_M"
|
||||
}
|
||||
},
|
||||
"a11yLabel": "Go to channel Alexander Amini",
|
||||
"rendererContext": {
|
||||
"commandContext": {
|
||||
"onTap": {
|
||||
"innertubeCommand": {
|
||||
"browseEndpoint": {
|
||||
"browseId": "UCtslD4DGH6PKyG_1gFAX7sg"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"contentMetadataViewModel": {
|
||||
"metadataRows": [
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "Alexander Amini"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "38K"
|
||||
},
|
||||
"accessibilityLabel": "38 thousand views",
|
||||
"leadingIcon": {
|
||||
"name": "PLAY_ARROW_OUTLINED",
|
||||
"height": 12,
|
||||
"width": 12,
|
||||
"marginEndToken": {
|
||||
"spacing": 2
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"text": {
|
||||
"content": "6mo ago"
|
||||
},
|
||||
"accessibilityLabel": "6 months ago"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"delimiter": " "
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"contentId": "R8V8CbuxryI",
|
||||
"contentType": "LOCKUP_CONTENT_TYPE_VIDEO",
|
||||
"themedPalette": {
|
||||
"lightThemePalette": {
|
||||
"baseBackground": 4294965488,
|
||||
"raisedBackground": 4294965488,
|
||||
"additiveBackground": 566856261,
|
||||
"textPrimary": 4281737226,
|
||||
"textSecondary": 4285420858,
|
||||
"outline": 860565782,
|
||||
"keyLight": 4292724140,
|
||||
"collectionStack": 4290815883,
|
||||
"invertedBackground": 4287583769,
|
||||
"textPrimaryInverse": 4294965488,
|
||||
"textDisabled": 2135634198,
|
||||
"dropShadow": 432638533,
|
||||
"cardOutline": 180980293,
|
||||
"overlayBackground": 3426099210,
|
||||
"overlayTextPrimary": 4294965488,
|
||||
"solidWash": 4283117846,
|
||||
"solidRim": 4281737226,
|
||||
"overlaySolidWash": 4294635232,
|
||||
"overlaySolidRim": 4294965488,
|
||||
"tonalWash": 2583689456,
|
||||
"tonalRim": 202311680,
|
||||
"overlayTonalWash": 436205808,
|
||||
"overlayTonalRim": 436205808,
|
||||
"outlineRim": 1279996182,
|
||||
"overlayOutlineRim": 871554762,
|
||||
"solidWashInverse": 4294106826,
|
||||
"solidRimInverse": 2147151584,
|
||||
"tonalWashInverse": 654309616,
|
||||
"tonalRimInverse": 653979360,
|
||||
"outlineRimInverse": 654309616,
|
||||
"solidBackground": 4283117846,
|
||||
"solidBackgroundInverse": 4290815883,
|
||||
"tonalBackground": 868263819,
|
||||
"tonalBackgroundInverse": 435347146,
|
||||
"outlineInverse": 872083168,
|
||||
"directionalLightStopPrimary": 4294635232,
|
||||
"directionalLightStopSecondary": 4294965488,
|
||||
"primary": 4279175168,
|
||||
"filledStateLayer": 4281737226,
|
||||
"tonalTouchLight": 4294965488,
|
||||
"tonalHoverLight": 3438997216,
|
||||
"tonalStateLayer": 420415488,
|
||||
"overlayDisabledContainer": 871554762,
|
||||
"overlayTonalTouchLight": 1291513568,
|
||||
"overlayTonalHoverLight": 1291513568,
|
||||
"overlayTonalStateLayer": 436205808,
|
||||
"disabledContainer": 420415488,
|
||||
"filledTouchLight": 4285420858,
|
||||
"filledHoverLight": 4284302120,
|
||||
"onOverlayDisabledContainer": 2583689456,
|
||||
"overlayTonalContainer": 2583359200,
|
||||
"overlayOutline": 872413424,
|
||||
"onFilledContainer": 4294965488,
|
||||
"filledContainer": 4280029186,
|
||||
"tonalContainer": 641081354,
|
||||
"overlayPrimary": 4294965488,
|
||||
"onOverlayFilledContainer": 4279175168,
|
||||
"overlayFilledTouchLight": 4294965488,
|
||||
"overlayFilledHoverLight": 4294635232,
|
||||
"overlayFilledStateLayer": 4292724140,
|
||||
"overlayFilledContainer": 4294106826,
|
||||
"onDisabledContainer": 1712261120,
|
||||
"temporaryOutline": 860565782
|
||||
},
|
||||
"darkThemePalette": {
|
||||
"baseBackground": 4280029186,
|
||||
"raisedBackground": 4281737226,
|
||||
"additiveBackground": 734628421,
|
||||
"textPrimary": 4294635232,
|
||||
"textSecondary": 4292724140,
|
||||
"outline": 1072881354,
|
||||
"keyLight": 4284302120,
|
||||
"collectionStack": 4285420858,
|
||||
"invertedBackground": 4293112700,
|
||||
"textPrimaryInverse": 4280029186,
|
||||
"textDisabled": 2146623178,
|
||||
"dropShadow": 432638533,
|
||||
"cardOutline": 180980293,
|
||||
"overlayBackground": 3426099210,
|
||||
"overlayTextPrimary": 4294965488,
|
||||
"solidWash": 4294635232,
|
||||
"solidRim": 4294965488,
|
||||
"overlaySolidWash": 4294635232,
|
||||
"overlaySolidRim": 4294965488,
|
||||
"tonalWash": 217243338,
|
||||
"tonalRim": 218102000,
|
||||
"overlayTonalWash": 436205808,
|
||||
"overlayTonalRim": 436205808,
|
||||
"outlineRim": 871554762,
|
||||
"overlayOutlineRim": 871554762,
|
||||
"solidWashInverse": 4285420858,
|
||||
"solidRimInverse": 871554762,
|
||||
"tonalWashInverse": 872413424,
|
||||
"tonalRimInverse": 870172076,
|
||||
"outlineRimInverse": 1291843824,
|
||||
"solidBackground": 4290815883,
|
||||
"solidBackgroundInverse": 4283117846,
|
||||
"tonalBackground": 435347146,
|
||||
"tonalBackgroundInverse": 868263819,
|
||||
"outlineInverse": 860565782,
|
||||
"directionalLightStopPrimary": 4281737226,
|
||||
"directionalLightStopSecondary": 4280029186,
|
||||
"primary": 4294965488,
|
||||
"filledStateLayer": 4292724140,
|
||||
"tonalTouchLight": 1073409760,
|
||||
"tonalHoverLight": 653979360,
|
||||
"tonalStateLayer": 436205808,
|
||||
"overlayDisabledContainer": 871554762,
|
||||
"overlayTonalTouchLight": 1291513568,
|
||||
"overlayTonalHoverLight": 1291513568,
|
||||
"overlayTonalStateLayer": 436205808,
|
||||
"disabledContainer": 436205808,
|
||||
"filledTouchLight": 4294965488,
|
||||
"filledHoverLight": 4294635232,
|
||||
"onOverlayDisabledContainer": 2583689456,
|
||||
"overlayTonalContainer": 2583359200,
|
||||
"overlayOutline": 872413424,
|
||||
"onFilledContainer": 4279175168,
|
||||
"filledContainer": 4294106826,
|
||||
"tonalContainer": 435347146,
|
||||
"overlayPrimary": 4294965488,
|
||||
"onOverlayFilledContainer": 4279175168,
|
||||
"overlayFilledTouchLight": 4294965488,
|
||||
"overlayFilledHoverLight": 4294635232,
|
||||
"overlayFilledStateLayer": 4292724140,
|
||||
"overlayFilledContainer": 4294106826,
|
||||
"onDisabledContainer": 1728051440,
|
||||
"temporaryOutline": 871554762
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"lockupViewModel": {
|
||||
"contentImage": {
|
||||
"thumbnailViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/HLKo4fJx_7k/hqdefault.jpg?sqp=-oaymwEiCKgBEF5IWvKriqkDFQgBFQAAAAAYASUAAMhCPQCAokN4AQ==&rs=AOn4CLAQcvMQEX1ny9Z8qu2mIMogpEMaVA",
|
||||
"width": 168,
|
||||
"height": 94
|
||||
},
|
||||
{
|
||||
"url": "https://i.ytimg.com/vi/HLKo4fJx_7k/hqdefault.jpg?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLCkoPSkHifs5ifpWXXcb96XG_Ly1w",
|
||||
"width": 336,
|
||||
"height": 188
|
||||
}
|
||||
]
|
||||
},
|
||||
"overlays": [
|
||||
{
|
||||
"thumbnailBottomOverlayViewModel": {
|
||||
"badges": [
|
||||
{
|
||||
"thumbnailBadgeViewModel": {
|
||||
"text": "47:36",
|
||||
"badgeStyle": "THUMBNAIL_OVERLAY_BADGE_STYLE_DEFAULT",
|
||||
"animationActivationTargetId": "HLKo4fJx_7k",
|
||||
"animatedText": "Now playing",
|
||||
"animationActivationEntitySelectorType": "THUMBNAIL_BADGE_ANIMATION_ENTITY_SELECTOR_TYPE_PLAYER_STATE"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"lockupMetadataViewModel": {
|
||||
"title": {
|
||||
"content": "MIT 6.S191 (2025): Language Models and New Frontiers"
|
||||
},
|
||||
"image": {
|
||||
"decoratedAvatarViewModel": {
|
||||
"avatar": {
|
||||
"avatarViewModel": {
|
||||
"image": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://yt3.ggpht.com/ytc/AIdro_k517G0Dt8QgsF86GKzYkG3Rs8jSGCiYGJw04lx4_1KXQ=s68-c-k-c0x00ffffff-no-rj",
|
||||
"width": 68,
|
||||
"height": 68
|
||||
}
|
||||
]
|
||||
},
|
||||
"avatarImageSize": "AVATAR_SIZE_M"
|
||||
}
|
||||
},
|
||||
"a11yLabel": "Go to channel Alexander Amini",
|
||||
"rendererContext": {
|
||||
"commandContext": {
|
||||
"onTap": {
|
||||
"innertubeCommand": {
|
||||
"browseEndpoint": {
|
||||
"browseId": "UCtslD4DGH6PKyG_1gFAX7sg"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"contentMetadataViewModel": {
|
||||
"metadataRows": [
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "Alexander Amini"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"metadataParts": [
|
||||
{
|
||||
"text": {
|
||||
"content": "63K"
|
||||
},
|
||||
"accessibilityLabel": "63 thousand views",
|
||||
"leadingIcon": {
|
||||
"name": "PLAY_ARROW_OUTLINED",
|
||||
"height": 12,
|
||||
"width": 12,
|
||||
"marginEndToken": {
|
||||
"spacing": 2
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"text": {
|
||||
"content": "1y ago"
|
||||
},
|
||||
"accessibilityLabel": "1 year ago"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"delimiter": " "
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"contentId": "HLKo4fJx_7k",
|
||||
"contentType": "LOCKUP_CONTENT_TYPE_VIDEO",
|
||||
"themedPalette": {
|
||||
"lightThemePalette": {
|
||||
"baseBackground": 4294964208,
|
||||
"raisedBackground": 4294964208,
|
||||
"additiveBackground": 566847045,
|
||||
"textPrimary": 4281734410,
|
||||
"textSecondary": 4285417018,
|
||||
"outline": 860561942,
|
||||
"keyLight": 4292720812,
|
||||
"collectionStack": 4290812043,
|
||||
"invertedBackground": 4287575065,
|
||||
"textPrimaryInverse": 4294964208,
|
||||
"textDisabled": 2135630358,
|
||||
"dropShadow": 432629317,
|
||||
"cardOutline": 180971077,
|
||||
"overlayBackground": 3426096394,
|
||||
"overlayTextPrimary": 4294964208,
|
||||
"solidWash": 4283114006,
|
||||
"solidRim": 4281734410,
|
||||
"overlaySolidWash": 4294633184,
|
||||
"overlaySolidRim": 4294964208,
|
||||
"tonalWash": 2583688176,
|
||||
"tonalRim": 202310656,
|
||||
"overlayTonalWash": 436204528,
|
||||
"overlayTonalRim": 436204528,
|
||||
"outlineRim": 1279992342,
|
||||
"overlayOutlineRim": 871551946,
|
||||
"solidWashInverse": 4294104010,
|
||||
"solidRimInverse": 2147149536,
|
||||
"tonalWashInverse": 654308336,
|
||||
"tonalRimInverse": 653977312,
|
||||
"outlineRimInverse": 654308336,
|
||||
"solidBackground": 4283114006,
|
||||
"solidBackgroundInverse": 4290812043,
|
||||
"tonalBackground": 868259979,
|
||||
"tonalBackgroundInverse": 435344330,
|
||||
"outlineInverse": 872081120,
|
||||
"directionalLightStopPrimary": 4294633184,
|
||||
"directionalLightStopSecondary": 4294964208,
|
||||
"primary": 4279174144,
|
||||
"filledStateLayer": 4281734410,
|
||||
"tonalTouchLight": 4294964208,
|
||||
"tonalHoverLight": 3438995168,
|
||||
"tonalStateLayer": 420414464,
|
||||
"overlayDisabledContainer": 871551946,
|
||||
"overlayTonalTouchLight": 1291511520,
|
||||
"overlayTonalHoverLight": 1291511520,
|
||||
"overlayTonalStateLayer": 436204528,
|
||||
"disabledContainer": 420414464,
|
||||
"filledTouchLight": 4285417018,
|
||||
"filledHoverLight": 4284298280,
|
||||
"onOverlayDisabledContainer": 2583688176,
|
||||
"overlayTonalContainer": 2583357152,
|
||||
"overlayOutline": 872412144,
|
||||
"onFilledContainer": 4294964208,
|
||||
"filledContainer": 4280027394,
|
||||
"tonalContainer": 641078538,
|
||||
"overlayPrimary": 4294964208,
|
||||
"onOverlayFilledContainer": 4279174144,
|
||||
"overlayFilledTouchLight": 4294964208,
|
||||
"overlayFilledHoverLight": 4294633184,
|
||||
"overlayFilledStateLayer": 4292720812,
|
||||
"overlayFilledContainer": 4294104010,
|
||||
"onDisabledContainer": 1712260096,
|
||||
"temporaryOutline": 860561942
|
||||
},
|
||||
"darkThemePalette": {
|
||||
"baseBackground": 4280027394,
|
||||
"raisedBackground": 4281734410,
|
||||
"additiveBackground": 734619205,
|
||||
"textPrimary": 4294633184,
|
||||
"textSecondary": 4292720812,
|
||||
"outline": 1072878538,
|
||||
"keyLight": 4284298280,
|
||||
"collectionStack": 4285417018,
|
||||
"invertedBackground": 4293105020,
|
||||
"textPrimaryInverse": 4280027394,
|
||||
"textDisabled": 2146620362,
|
||||
"dropShadow": 432629317,
|
||||
"cardOutline": 180971077,
|
||||
"overlayBackground": 3426096394,
|
||||
"overlayTextPrimary": 4294964208,
|
||||
"solidWash": 4294633184,
|
||||
"solidRim": 4294964208,
|
||||
"overlaySolidWash": 4294633184,
|
||||
"overlaySolidRim": 4294964208,
|
||||
"tonalWash": 217240522,
|
||||
"tonalRim": 218100720,
|
||||
"overlayTonalWash": 436204528,
|
||||
"overlayTonalRim": 436204528,
|
||||
"outlineRim": 871551946,
|
||||
"overlayOutlineRim": 871551946,
|
||||
"solidWashInverse": 4285417018,
|
||||
"solidRimInverse": 871551946,
|
||||
"tonalWashInverse": 872412144,
|
||||
"tonalRimInverse": 870168748,
|
||||
"outlineRimInverse": 1291842544,
|
||||
"solidBackground": 4290812043,
|
||||
"solidBackgroundInverse": 4283114006,
|
||||
"tonalBackground": 435344330,
|
||||
"tonalBackgroundInverse": 868259979,
|
||||
"outlineInverse": 860561942,
|
||||
"directionalLightStopPrimary": 4281734410,
|
||||
"directionalLightStopSecondary": 4280027394,
|
||||
"primary": 4294964208,
|
||||
"filledStateLayer": 4292720812,
|
||||
"tonalTouchLight": 1073407712,
|
||||
"tonalHoverLight": 653977312,
|
||||
"tonalStateLayer": 436204528,
|
||||
"overlayDisabledContainer": 871551946,
|
||||
"overlayTonalTouchLight": 1291511520,
|
||||
"overlayTonalHoverLight": 1291511520,
|
||||
"overlayTonalStateLayer": 436204528,
|
||||
"disabledContainer": 436204528,
|
||||
"filledTouchLight": 4294964208,
|
||||
"filledHoverLight": 4294633184,
|
||||
"onOverlayDisabledContainer": 2583688176,
|
||||
"overlayTonalContainer": 2583357152,
|
||||
"overlayOutline": 872412144,
|
||||
"onFilledContainer": 4279174144,
|
||||
"filledContainer": 4294104010,
|
||||
"tonalContainer": 435344330,
|
||||
"overlayPrimary": 4294964208,
|
||||
"onOverlayFilledContainer": 4279174144,
|
||||
"overlayFilledTouchLight": 4294964208,
|
||||
"overlayFilledHoverLight": 4294633184,
|
||||
"overlayFilledStateLayer": 4292720812,
|
||||
"overlayFilledContainer": 4294104010,
|
||||
"onDisabledContainer": 1728050160,
|
||||
"temporaryOutline": 871551946
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"continuationItemRenderer": {
|
||||
"trigger": "CONTINUATION_TRIGGER_ON_ITEM_SHOWN",
|
||||
"continuationEndpoint": {
|
||||
"commandMetadata": {
|
||||
"webCommandMetadata": {
|
||||
"sendPost": true,
|
||||
"apiUrl": "/youtubei/v1/next"
|
||||
}
|
||||
},
|
||||
"continuationCommand": {
|
||||
"token": "CBQSDRILU2RUWkFNREtyTlkYACqXBk1nb0l5ZGl1dXRUNDdQc2EyczZMNnd5LUJBcTdCQW9EOGo0QUNnN0NQZ3NJbk1XcnZzbWo2Y2UyQVFvRDhqNEFDZzNDUGdvSW90N0czWnVCMy1KSENnUHlQZ0FLRGNJLUNnaTVfOGVUbjV5cTJSd0tBX0ktQUFvT3dqNExDSkQydWJfNXp2ZXZfUUVLQV9JLUFBb053ajRLQ1BXWjVQakt2cjZWU2dvRDhqNEFDZzNDUGdvSW9aTDd1OUtGdF85NkNnUHlQZ0FLRGNJLUNnaUh3N2FLMzd6YzVIZ0tBX0ktQUFvT3dqNExDUE94aHRQTWtfVzB1UUVLQV9JLUFBb093ajRMQ092eTBzaXNsSWZScGdFS0FfSS1BQW9Pd2o0TENKS1FxdHpBeE5lZHJBRUtBX0ktQUFvTndqNEtDTFdteWE2cHNPMkJPZ29EOGo0QUNnM0NQZ29JanYtdy1wQ3k1YVozQ2dQeVBnQUtEc0ktQ3dqMmtmVF9tYlB1XzRvQkNnUHlQZ0FLRHNJLUN3aVpuYWZjc0tQVmpZUUJDZ1B5UGdBS0RjSS1DZ2lxM3BxM3FyX2s0U0VLQV9JLUFBb053ajRLQ0phNXU5eVJvTmJOS0FvRDhqNEFDZzNDUGdvSXFMeWR3T1NhNGJkV0NnUHlQZ0FLRGNJLUNnakh3X2ZucktlSDdXUUtBX0ktQUFvTndqNEtDUG4xak1mcXg4QzJNQW9EOGo0QUNnM0NQZ29JeWRpdXV0VDQ3UHNhRWhRQUFnUUdDQW9NRGhBU0ZCWVlHaHdlSUNJa0pob0VDQUFRQVJvRUNBSVFBeG9FQ0FRUUJSb0VDQVlRQnhvRUNBZ1FDUm9FQ0FvUUN4b0VDQXdRRFJvRUNBNFFEeG9FQ0JBUUVSb0VDQklRRXhvRUNCUVFGUm9FQ0JZUUZ4b0VDQmdRR1JvRUNCb1FHeG9FQ0J3UUhSb0VDQjRRSHhvRUNDQVFJUm9FQ0NJUUl4b0VDQ1FRSlJvRUNDWVFKeW9VQUFJRUJnZ0tEQTRRRWhRV0dCb2NIaUFpSkNZag93YXRjaC1uZXh0LWZlZWQ%3D",
|
||||
"request": "CONTINUATION_REQUEST_TYPE_WATCH_NEXT"
|
||||
}
|
||||
},
|
||||
"button": {
|
||||
"buttonRenderer": {
|
||||
"style": "STYLE_SUGGESTIVE",
|
||||
"size": "SIZE_DEFAULT",
|
||||
"isDisabled": false,
|
||||
"text": {
|
||||
"runs": [
|
||||
{
|
||||
"text": "Show more"
|
||||
}
|
||||
]
|
||||
},
|
||||
"command": {
|
||||
"commandMetadata": {
|
||||
"webCommandMetadata": {
|
||||
"sendPost": true,
|
||||
"apiUrl": "/youtubei/v1/next"
|
||||
}
|
||||
},
|
||||
"continuationCommand": {
|
||||
"token": "CBQSDRILU2RUWkFNREtyTlkYACqXBk1nb0l5ZGl1dXRUNDdQc2EyczZMNnd5LUJBcTdCQW9EOGo0QUNnN0NQZ3NJbk1XcnZzbWo2Y2UyQVFvRDhqNEFDZzNDUGdvSW90N0czWnVCMy1KSENnUHlQZ0FLRGNJLUNnaTVfOGVUbjV5cTJSd0tBX0ktQUFvT3dqNExDSkQydWJfNXp2ZXZfUUVLQV9JLUFBb053ajRLQ1BXWjVQakt2cjZWU2dvRDhqNEFDZzNDUGdvSW9aTDd1OUtGdF85NkNnUHlQZ0FLRGNJLUNnaUh3N2FLMzd6YzVIZ0tBX0ktQUFvT3dqNExDUE94aHRQTWtfVzB1UUVLQV9JLUFBb093ajRMQ092eTBzaXNsSWZScGdFS0FfSS1BQW9Pd2o0TENKS1FxdHpBeE5lZHJBRUtBX0ktQUFvTndqNEtDTFdteWE2cHNPMkJPZ29EOGo0QUNnM0NQZ29JanYtdy1wQ3k1YVozQ2dQeVBnQUtEc0ktQ3dqMmtmVF9tYlB1XzRvQkNnUHlQZ0FLRHNJLUN3aVpuYWZjc0tQVmpZUUJDZ1B5UGdBS0RjSS1DZ2lxM3BxM3FyX2s0U0VLQV9JLUFBb053ajRLQ0phNXU5eVJvTmJOS0FvRDhqNEFDZzNDUGdvSXFMeWR3T1NhNGJkV0NnUHlQZ0FLRGNJLUNnakh3X2ZucktlSDdXUUtBX0ktQUFvTndqNEtDUG4xak1mcXg4QzJNQW9EOGo0QUNnM0NQZ29JeWRpdXV0VDQ3UHNhRWhRQUFnUUdDQW9NRGhBU0ZCWVlHaHdlSUNJa0pob0VDQUFRQVJvRUNBSVFBeG9FQ0FRUUJSb0VDQVlRQnhvRUNBZ1FDUm9FQ0FvUUN4b0VDQXdRRFJvRUNBNFFEeG9FQ0JBUUVSb0VDQklRRXhvRUNCUVFGUm9FQ0JZUUZ4b0VDQmdRR1JvRUNCb1FHeG9FQ0J3UUhSb0VDQjRRSHhvRUNDQVFJUm9FQ0NJUUl4b0VDQ1FRSlJvRUNDWVFKeW9VQUFJRUJnZ0tEQTRRRWhRV0dCb2NIaUFpSkNZag93YXRjaC1uZXh0LWZlZWQ%3D",
|
||||
"request": "CONTINUATION_REQUEST_TYPE_WATCH_NEXT"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ from datetime import datetime, timedelta, timezone
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.catalog import queries, search, service
|
||||
from app.db import SessionLocal
|
||||
from app.catalog.models import (
|
||||
BlockedChannel,
|
||||
Channel,
|
||||
@@ -22,6 +23,8 @@ from app.catalog.models import (
|
||||
)
|
||||
from app.reader import queries as reader_queries
|
||||
from app.reader import service as reader_service
|
||||
from app.sync import explore as sync_explore
|
||||
from app.sync import subscriptions as sync_subscriptions
|
||||
|
||||
|
||||
def _channel(db, cid="UCc", **kw):
|
||||
@@ -141,6 +144,89 @@ def test_subscribing_keeps_an_explored_channel_and_its_videos(db, make_user):
|
||||
assert queries.subscription(db, user, "UCc") is None
|
||||
|
||||
|
||||
def test_exploring_a_channel_someone_follows_brings_its_uploads_in_as_the_catalogs_own(
|
||||
db, make_user, monkeypatch
|
||||
):
|
||||
follower, explorer = make_user(), make_user()
|
||||
ch = _channel(db, uploads_playlist_id="UUc")
|
||||
db.add(Subscription(user_id=follower.id, channel_id="UCc"))
|
||||
db.commit()
|
||||
service.explore(db, explorer, ch)
|
||||
db.commit()
|
||||
|
||||
class _Yt:
|
||||
def get_playlist_items(self, playlist_id, page_token):
|
||||
item = {"contentDetails": {"videoId": "v1", "videoPublishedAt": "2026-05-01T00:00:00Z"}}
|
||||
return {"items": [item]}
|
||||
|
||||
monkeypatch.setattr(sync_explore, "_enrich_new", lambda session, yt, ids: 0)
|
||||
sync_explore.explore_ingest_page(db, _Yt(), ch)
|
||||
db.commit()
|
||||
db.expire_all()
|
||||
# The channel is followed, so not the exploration's: a video flagged as one would stay flagged
|
||||
# (subscribing clears only an explored channel's) and its watched marks would wait for good.
|
||||
assert (ch.from_explore, db.get(Video, "v1").via_explore) == (False, False)
|
||||
|
||||
|
||||
def test_a_follow_pulled_in_from_youtube_makes_an_explored_channel_the_catalogs_own(
|
||||
db, make_user, monkeypatch
|
||||
):
|
||||
explorer, follower = make_user(), make_user()
|
||||
ch = _channel(db, details_synced_at=datetime.now(timezone.utc))
|
||||
service.explore(db, explorer, ch)
|
||||
db.commit()
|
||||
_video(db, "v1", via_explore=True)
|
||||
|
||||
class _Yt:
|
||||
def __init__(self, session, user):
|
||||
pass
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def iter_subscriptions(self):
|
||||
yield {"channel_id": "UCc", "title": "UCc", "yt_subscription_id": "sub-UCc"}
|
||||
|
||||
def get_channels(self, ids):
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(sync_subscriptions, "YouTubeClient", _Yt)
|
||||
sync_subscriptions.import_subscriptions(db, follower)
|
||||
db.commit()
|
||||
db.expire_all()
|
||||
# Followed on youtube.com is followed all the same: left flagged, the channel's later videos
|
||||
# came in as an exploration's, hidden from the Library and their watched marks waiting for good.
|
||||
assert (db.get(Channel, "UCc").from_explore, db.get(Video, "v1").via_explore) == (False, False)
|
||||
|
||||
|
||||
def test_a_follow_landing_while_an_explored_page_comes_in_leaves_none_of_it_flagged(
|
||||
db, make_user, monkeypatch
|
||||
):
|
||||
explorer, follower = make_user(), make_user()
|
||||
ch = _channel(db, uploads_playlist_id="UUc")
|
||||
service.explore(db, explorer, ch)
|
||||
db.commit()
|
||||
|
||||
class _Yt:
|
||||
def get_playlist_items(self, playlist_id, page_token):
|
||||
# Someone subscribes, in a request of their own, while YouTube answers this one.
|
||||
with SessionLocal() as other:
|
||||
service.record_subscription(other, follower, other.get(Channel, "UCc"), "sub-UCc")
|
||||
other.commit()
|
||||
item = {"contentDetails": {"videoId": "v1", "videoPublishedAt": "2026-05-01T00:00:00Z"}}
|
||||
return {"items": [item]}
|
||||
|
||||
monkeypatch.setattr(sync_explore, "_enrich_new", lambda session, yt, ids: 0)
|
||||
sync_explore.explore_ingest_page(db, _Yt(), ch)
|
||||
db.commit()
|
||||
db.expire_all()
|
||||
# The subscribe cleared what was flagged before it; a page that lands after it must not be.
|
||||
assert (db.get(Channel, "UCc").from_explore, db.get(Video, "v1").via_explore) == (False, False)
|
||||
|
||||
|
||||
def test_a_block_is_once_and_ends_the_exploration(db, make_user):
|
||||
user = make_user()
|
||||
ch = _channel(db)
|
||||
|
||||
@@ -1105,10 +1105,16 @@ def test_two_overlapping_reorders_never_share_a_slot(db, as_user):
|
||||
|
||||
worker = threading.Thread(target=second_tab)
|
||||
worker.start()
|
||||
# Commit A only once B is blocked on a row lock, so B's read is the stale snapshot.
|
||||
# Commit A only once B is blocked on a row lock, so B's read is the stale snapshot. pg_locks is
|
||||
# the whole server's: only a wait in this database is B's (a parallel worker's is not).
|
||||
waiting = 0
|
||||
for _ in range(200):
|
||||
waiting = probe.scalar(text("SELECT count(*) FROM pg_locks WHERE NOT granted"))
|
||||
waiting = probe.scalar(
|
||||
text(
|
||||
"SELECT count(*) FROM pg_locks WHERE NOT granted AND pid IN"
|
||||
" (SELECT pid FROM pg_stat_activity WHERE datname = current_database())"
|
||||
)
|
||||
)
|
||||
probe.rollback()
|
||||
if waiting:
|
||||
break
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""`/api/me` names the live-search source, so the search button's tooltip can say what a search costs
|
||||
under the source that actually runs (the default website source spends no API quota)."""
|
||||
under the source that actually runs (the default website source spends no API quota), and says
|
||||
whether live search and related videos are on at all."""
|
||||
|
||||
from app import sysconfig
|
||||
|
||||
@@ -24,3 +25,24 @@ def test_me_names_the_running_search_source(client, db, make_user):
|
||||
sysconfig.set_value(db, "search_source", "api")
|
||||
db.commit()
|
||||
assert _me(client)["search_source"] == "api"
|
||||
|
||||
|
||||
def test_me_says_whether_live_search_and_related_videos_are_on(client, db, make_user):
|
||||
# A daily limit of 0 turns the feature off; the UI leaves it out instead of offering a refusal.
|
||||
user = make_user(password=_PW)
|
||||
login = client.post("/auth/password-login", json={"email": user.email, "password": _PW})
|
||||
assert login.status_code == 200
|
||||
|
||||
me = _me(client)
|
||||
assert (me["search_enabled"], me["related_enabled"]) == (True, True)
|
||||
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 0)
|
||||
db.commit()
|
||||
me = _me(client)
|
||||
assert (me["search_enabled"], me["related_enabled"]) == (False, True)
|
||||
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 5)
|
||||
sysconfig.set_value(db, "related_daily_limit_per_user", 0)
|
||||
db.commit()
|
||||
me = _me(client)
|
||||
assert (me["search_enabled"], me["related_enabled"]) == (True, False)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Migration 0116's data step, DB-lane: an explored channel someone already follows becomes the
|
||||
catalog's own, and no video stays flagged as an exploration's on a channel that is not one.
|
||||
|
||||
The schema half is checked by test_migrations.py; a flag left on is invisible there.
|
||||
"""
|
||||
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.db import engine
|
||||
|
||||
|
||||
def test_followed_explored_channels_and_their_videos_are_the_catalogs_own(db, make_user):
|
||||
follower = make_user().id
|
||||
cfg = Config("alembic.ini")
|
||||
command.downgrade(cfg, "0115_takeout_channels")
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
|
||||
def channel(cid, explored):
|
||||
conn.execute(
|
||||
text("INSERT INTO channels (id, from_explore) VALUES (:c, :e)"),
|
||||
{"c": cid, "e": explored},
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO videos (id, channel_id, published_at, via_explore)"
|
||||
" VALUES (:v, :c, now(), true)"
|
||||
),
|
||||
{"v": f"v-{cid}", "c": cid},
|
||||
)
|
||||
|
||||
channel("UCfollowed", True) # explored, then followed on youtube.com
|
||||
channel("UCexplored", True) # explored, nobody follows it: stays the exploration's
|
||||
channel("UCorganic", False) # a video flagged after a subscribe had cleared the channel
|
||||
conn.execute(
|
||||
text("INSERT INTO subscriptions (user_id, channel_id) VALUES (:u, 'UCfollowed')"),
|
||||
{"u": follower},
|
||||
)
|
||||
finally:
|
||||
command.upgrade(cfg, "head")
|
||||
|
||||
with engine.connect() as conn:
|
||||
channels = dict(conn.execute(text("SELECT id, from_explore FROM channels")).tuples().all())
|
||||
videos = dict(
|
||||
conn.execute(text("SELECT channel_id, via_explore FROM videos")).tuples().all()
|
||||
)
|
||||
assert channels == {"UCfollowed": False, "UCexplored": True, "UCorganic": False}
|
||||
assert videos == {"UCfollowed": False, "UCexplored": True, "UCorganic": False}
|
||||
@@ -75,9 +75,9 @@ def test_trimming_read_notifications_trims_only_mine(db, make_user):
|
||||
|
||||
def test_todays_actions_count_only_mine(db, make_user):
|
||||
me, other = make_user(), make_user()
|
||||
quota.log_action(me.id, quota.QuotaAction.VIDEOS_SEARCH)
|
||||
quota.log_action(other.id, quota.QuotaAction.VIDEOS_SEARCH)
|
||||
quota.log_action(other.id, quota.QuotaAction.VIDEOS_SEARCH)
|
||||
quota.claim_action(me.id, quota.QuotaAction.VIDEOS_SEARCH, 5)
|
||||
quota.claim_action(other.id, quota.QuotaAction.VIDEOS_SEARCH, 5)
|
||||
quota.claim_action(other.id, quota.QuotaAction.VIDEOS_SEARCH, 5)
|
||||
assert quota.actions_today(db, me.id, quota.QuotaAction.VIDEOS_SEARCH) == 1
|
||||
|
||||
|
||||
|
||||
@@ -89,9 +89,13 @@ def test_a_claim_is_released_when_its_block_raises(db, make_user):
|
||||
except RuntimeError:
|
||||
pass
|
||||
# Asked of pg_locks, not by claiming again: a lock leaked on a pooled connection would be granted
|
||||
# again to that same connection (advisory locks are re-entrant per session).
|
||||
# again to that same connection (advisory locks are re-entrant per session). pg_locks is the whole
|
||||
# server's, so only this database's: a parallel worker's own claim on the same id counted here.
|
||||
held = db.scalar(
|
||||
text("SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' AND objid = :id"),
|
||||
text(
|
||||
"SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' AND objid = :id"
|
||||
" AND database = (SELECT oid FROM pg_database WHERE datname = current_database())"
|
||||
),
|
||||
{"id": pl.id},
|
||||
)
|
||||
assert held == 0
|
||||
|
||||
@@ -44,15 +44,15 @@ def test_reads_see_separate_session_spend_mid_transaction(db):
|
||||
assert after - before == 7
|
||||
|
||||
|
||||
def test_log_action_survives_caller_rollback(db):
|
||||
def test_a_claimed_slot_survives_caller_rollback(db):
|
||||
user = User(email="searcher@example.com")
|
||||
db.add(user)
|
||||
db.commit() # a committed user to attribute the (free) action to
|
||||
db.add(User(email="pending@example.com")) # uncommitted caller work
|
||||
quota.log_action(user.id, quota.QuotaAction.VIDEOS_SEARCH)
|
||||
assert quota.claim_action(user.id, quota.QuotaAction.VIDEOS_SEARCH, 5) is not None
|
||||
db.rollback()
|
||||
|
||||
# The zero-cost action event survived (per-user daily caps must still count it) ...
|
||||
# The zero-cost claim event survived (per-user daily caps must still count it) ...
|
||||
events = db.execute(select(QuotaEvent)).scalars().all()
|
||||
assert len(events) == 1
|
||||
assert events[0].user_id == user.id
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
"""`GET /api/search/related/{video_id}` — a video's related videos, without what the user has seen.
|
||||
|
||||
The scrape is replaced by pages the test hands out, and YouTube's videos.list by an offline enrich
|
||||
(30-minute videos, so no Shorts probe goes out). What is held: the list leaves out what this user
|
||||
watched or hid — here or in their Takeout history, unless taken back to "new" since — blocked
|
||||
channels and the video itself; it pages on until it has enough; it lands in the catalog the way
|
||||
search finds do; and a failure, or the day's cap, says so instead of answering an empty list."""
|
||||
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import func, select, text
|
||||
|
||||
from app import quota, sysconfig
|
||||
from app.catalog.models import BlockedChannel, Channel, Subscription, Video
|
||||
from app.models import QuotaEvent
|
||||
from app.reader.models import TakeoutItem, TakeoutKind, VideoState, VideoUnmark
|
||||
from app.routes import search as search_routes
|
||||
from app.youtube.client import YouTubeError
|
||||
from app.youtube.innertube import ScrapeError
|
||||
|
||||
T0 = datetime(2026, 10, 1, tzinfo=timezone.utc)
|
||||
SOURCE = "srcvideo001"
|
||||
|
||||
|
||||
def _vid(n: int) -> str:
|
||||
return f"rel{n:08d}"
|
||||
|
||||
|
||||
def _item(n: int, channel: str = "UCrelated01") -> dict:
|
||||
return {
|
||||
"id": _vid(n),
|
||||
"channel_id": channel,
|
||||
"channel_title": f"Chan {channel}",
|
||||
"title": f"Related {n}",
|
||||
"published_at": None,
|
||||
"thumbnail_url": None,
|
||||
"live_broadcast": "none",
|
||||
}
|
||||
|
||||
|
||||
class _FakeYT:
|
||||
def __init__(self, *_a, **_kw):
|
||||
pass
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def get_channels(self, ids):
|
||||
return []
|
||||
|
||||
def get_videos(self, ids):
|
||||
return [
|
||||
{
|
||||
"id": i,
|
||||
"snippet": {"title": f"T {i}", "publishedAt": "2025-01-01T00:00:00Z"},
|
||||
"contentDetails": {"duration": "PT30M"},
|
||||
"statistics": {},
|
||||
"status": {},
|
||||
}
|
||||
for i in ids
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pages(monkeypatch, db):
|
||||
"""The scrape answers with the pages in `state["pages"]`, one per call, recording each call."""
|
||||
sysconfig.set_value(db, "shorts_probe_max_seconds", 60)
|
||||
state: dict = {"pages": [], "calls": []}
|
||||
|
||||
def related(video_id, continuation=None, *, hl="en", gl="US"):
|
||||
state["calls"].append((video_id, continuation, hl, gl))
|
||||
page = state["pages"].pop(0)
|
||||
if isinstance(page, Exception):
|
||||
raise page
|
||||
return page
|
||||
|
||||
monkeypatch.setattr(search_routes.related_scrape, "related", related)
|
||||
monkeypatch.setattr(search_routes, "YouTubeClient", _FakeYT)
|
||||
return state
|
||||
|
||||
|
||||
def _page(items: list[dict], token: str | None = "NEXT") -> dict:
|
||||
return {"items": items, "next_page_token": token}
|
||||
|
||||
|
||||
def _ids(resp) -> list[str]:
|
||||
assert resp.status_code == 200, resp.text
|
||||
return [it["id"] for it in resp.json()["items"]]
|
||||
|
||||
|
||||
def _known(db, *ns: int, channel: str = "UCrelated01") -> None:
|
||||
"""These related videos already in the catalog (a state needs the row)."""
|
||||
if db.get(Channel, channel) is None:
|
||||
db.add(Channel(id=channel, title="Chan"))
|
||||
for n in ns:
|
||||
db.add(Video(id=_vid(n), channel_id=channel, title=f"Related {n}", published_at=T0))
|
||||
db.commit()
|
||||
|
||||
|
||||
def test_a_related_list_comes_into_the_catalog_as_search_finds_do(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
pages["pages"] = [_page([_item(n) for n in range(1, 21)])]
|
||||
resp = as_user(user).get(f"/api/search/related/{SOURCE}")
|
||||
assert _ids(resp) == [_vid(n) for n in range(1, 21)]
|
||||
assert resp.json()["next_cursor"] == "NEXT" and resp.json()["has_more"] is True
|
||||
video = db.get(Video, _vid(1))
|
||||
# Flagged like a search find: hidden from the shared Library, reclaimed when nobody keeps it.
|
||||
assert video.via_search is True and video.enriched_at is not None
|
||||
assert pages["calls"] == [(SOURCE, None, "en", "US")]
|
||||
|
||||
|
||||
def test_what_the_user_watched_or_hid_here_is_left_out(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
other = make_user()
|
||||
_known(db, 1, 2, 3, 4)
|
||||
db.add_all(
|
||||
[
|
||||
VideoState(user_id=user.id, video_id=_vid(1), status="watched", watched_at=T0),
|
||||
VideoState(user_id=user.id, video_id=_vid(2), status="hidden"),
|
||||
# In progress is not "seen": it stays, to be finished.
|
||||
VideoState(user_id=user.id, video_id=_vid(3), status="new", position_seconds=120),
|
||||
# Someone else's watch is theirs.
|
||||
VideoState(user_id=other.id, video_id=_vid(4), status="watched", watched_at=T0),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
pages["pages"] = [_page([_item(n) for n in range(1, 6)], token=None)]
|
||||
assert _ids(as_user(user).get(f"/api/search/related/{SOURCE}")) == [_vid(3), _vid(4), _vid(5)]
|
||||
|
||||
|
||||
def test_what_the_takeout_history_shows_watched_is_left_out_unless_taken_back(
|
||||
db, make_user, as_user, pages
|
||||
):
|
||||
user = make_user()
|
||||
other = make_user()
|
||||
_known(db, 2)
|
||||
db.add_all(
|
||||
[
|
||||
# Not in the catalog at all: the history alone names it.
|
||||
TakeoutItem(user_id=user.id, kind=TakeoutKind.WATCHED, video_id=_vid(1), at=T0),
|
||||
# Watched on YouTube, then taken back to "new" here: it may come again.
|
||||
TakeoutItem(user_id=user.id, kind=TakeoutKind.WATCHED, video_id=_vid(2), at=T0),
|
||||
VideoUnmark(user_id=user.id, video_id=_vid(2), at=T0 + timedelta(days=1)),
|
||||
# Only in Watch later: not watched.
|
||||
TakeoutItem(user_id=user.id, kind=TakeoutKind.WATCH_LATER, video_id=_vid(3), at=T0),
|
||||
# Another user's history.
|
||||
TakeoutItem(user_id=other.id, kind=TakeoutKind.WATCHED, video_id=_vid(4), at=T0),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
pages["pages"] = [_page([_item(n) for n in range(1, 5)], token=None)]
|
||||
assert _ids(as_user(user).get(f"/api/search/related/{SOURCE}")) == [_vid(2), _vid(3), _vid(4)]
|
||||
# Left out before the ingest: what the user has seen is not stored for a list that hides it.
|
||||
assert db.get(Video, _vid(1)) is None
|
||||
|
||||
|
||||
def test_an_unmark_older_than_the_history_row_does_not_bring_it_back(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
_known(db, 1)
|
||||
db.add_all(
|
||||
[
|
||||
VideoUnmark(user_id=user.id, video_id=_vid(1), at=T0 - timedelta(days=1)),
|
||||
TakeoutItem(user_id=user.id, kind=TakeoutKind.WATCHED, video_id=_vid(1), at=T0),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
pages["pages"] = [_page([_item(1), _item(2)], token=None)]
|
||||
assert _ids(as_user(user).get(f"/api/search/related/{SOURCE}")) == [_vid(2)]
|
||||
|
||||
|
||||
def test_another_users_unmark_does_not_bring_it_back(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
other = make_user()
|
||||
_known(db, 1)
|
||||
db.add_all(
|
||||
[
|
||||
TakeoutItem(user_id=user.id, kind=TakeoutKind.WATCHED, video_id=_vid(1), at=T0),
|
||||
VideoUnmark(user_id=other.id, video_id=_vid(1), at=T0 + timedelta(days=1)),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
pages["pages"] = [_page([_item(1), _item(2)], token=None)]
|
||||
assert _ids(as_user(user).get(f"/api/search/related/{SOURCE}")) == [_vid(2)]
|
||||
|
||||
|
||||
def test_blocked_channels_and_the_video_itself_are_left_out_and_never_stored(
|
||||
db, make_user, as_user, pages
|
||||
):
|
||||
user = make_user()
|
||||
db.add(Channel(id="UCblocked01", title="Blocked"))
|
||||
db.commit()
|
||||
db.add(BlockedChannel(user_id=user.id, channel_id="UCblocked01"))
|
||||
db.commit()
|
||||
own = {**_item(9), "id": SOURCE}
|
||||
pages["pages"] = [_page([_item(1), _item(2, "UCblocked01"), own], token=None)]
|
||||
assert _ids(as_user(user).get(f"/api/search/related/{SOURCE}")) == [_vid(1)]
|
||||
assert db.get(Video, _vid(2)) is None
|
||||
|
||||
|
||||
def test_it_pages_on_until_enough_unseen_videos_are_gathered(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
_known(db, *range(1, 16))
|
||||
for n in range(1, 16):
|
||||
db.add(VideoState(user_id=user.id, video_id=_vid(n), status="watched", watched_at=T0))
|
||||
db.commit()
|
||||
pages["pages"] = [
|
||||
_page([_item(n) for n in range(1, 21)], token="page2"), # 15 seen, 5 new
|
||||
_page([_item(n) for n in range(21, 41)], token="page3"), # 20 new: 25 now
|
||||
_page([_item(n) for n in range(41, 61)], token="page4"), # never asked
|
||||
]
|
||||
ids = _ids(resp := as_user(user).get(f"/api/search/related/{SOURCE}"))
|
||||
assert ids == [_vid(n) for n in range(16, 41)]
|
||||
assert [c[1] for c in pages["calls"]] == [None, "page2"]
|
||||
assert resp.json()["next_cursor"] == "page3"
|
||||
|
||||
|
||||
def test_a_repeat_on_a_later_page_counts_once(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
pages["pages"] = [
|
||||
_page([_item(n) for n in range(1, 11)], token="page2"),
|
||||
_page([_item(n) for n in range(5, 25)], token=None),
|
||||
]
|
||||
assert _ids(as_user(user).get(f"/api/search/related/{SOURCE}")) == [
|
||||
_vid(n) for n in range(1, 25)
|
||||
]
|
||||
|
||||
|
||||
def test_it_reads_at_most_four_pages(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
pages["pages"] = [_page([_item(n)], token=f"page{n + 1}") for n in range(1, 7)]
|
||||
ids = _ids(resp := as_user(user).get(f"/api/search/related/{SOURCE}"))
|
||||
assert ids == [_vid(n) for n in range(1, 5)]
|
||||
assert len(pages["calls"]) == 4 and resp.json()["next_cursor"] == "page5"
|
||||
|
||||
|
||||
def test_the_cursor_and_the_hungarian_locale_reach_the_scrape(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
pages["pages"] = [_page([_item(1)], token=None)]
|
||||
resp = as_user(user).get(f"/api/search/related/{SOURCE}?cursor=C1®ion=hu")
|
||||
assert _ids(resp) == [_vid(1)]
|
||||
assert pages["calls"] == [(SOURCE, "C1", "hu", "HU")]
|
||||
assert resp.json()["has_more"] is False
|
||||
|
||||
|
||||
def test_an_unknown_region_is_refused(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
assert as_user(user).get(f"/api/search/related/{SOURCE}?region=xx").status_code == 422
|
||||
assert pages["calls"] == []
|
||||
|
||||
|
||||
def test_a_failed_scrape_says_youtube_is_unavailable(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
pages["pages"] = [ScrapeError("blocked")]
|
||||
resp = as_user(user).get(f"/api/search/related/{SOURCE}")
|
||||
assert resp.status_code == 422
|
||||
assert resp.json()["detail"] == {"code": "youtube", "reason": "unavailable"}
|
||||
|
||||
|
||||
def test_a_failure_on_a_later_page_keeps_what_came_before(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
pages["pages"] = [_page([_item(1), _item(2)], token="page2"), ScrapeError("blocked")]
|
||||
assert _ids(as_user(user).get(f"/api/search/related/{SOURCE}")) == [_vid(1), _vid(2)]
|
||||
|
||||
|
||||
def test_one_list_is_one_event_against_the_days_cap(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "related_daily_limit_per_user", 1)
|
||||
pages["pages"] = [
|
||||
_page([_item(1)], token="page2"),
|
||||
_page([_item(2)], token=None),
|
||||
]
|
||||
client = as_user(user)
|
||||
assert client.get(f"/api/search/related/{SOURCE}").status_code == 200
|
||||
events = db.scalars(
|
||||
select(QuotaEvent).where(
|
||||
QuotaEvent.user_id == user.id, QuotaEvent.action == quota.QuotaAction.VIDEOS_RELATED
|
||||
)
|
||||
).all()
|
||||
assert len(events) == 1
|
||||
refused = client.get(f"/api/search/related/{SOURCE}")
|
||||
assert refused.status_code == 429
|
||||
assert refused.json()["detail"] == {
|
||||
"code": "refused",
|
||||
"reason": "related_daily_limit",
|
||||
"limit": 1,
|
||||
}
|
||||
assert len(pages["calls"]) == 2 # the refused one asked YouTube nothing
|
||||
|
||||
|
||||
def test_reading_further_takes_a_slot_too(db, make_user, as_user, pages):
|
||||
# Each request scrapes and enriches; a cursor is a free string, so one that cost nothing let a
|
||||
# replayed cursor read without end.
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "related_daily_limit_per_user", 1)
|
||||
pages["pages"] = [_page([_item(1)], token=None), _page([_item(2)], token=None)]
|
||||
client = as_user(user)
|
||||
assert client.get(f"/api/search/related/{SOURCE}").status_code == 200
|
||||
refused = client.get(f"/api/search/related/{SOURCE}?cursor=more")
|
||||
assert refused.status_code == 429
|
||||
assert refused.json()["detail"]["reason"] == "related_daily_limit"
|
||||
assert len(pages["calls"]) == 1
|
||||
|
||||
|
||||
def test_a_list_that_failed_gives_its_slot_back(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "related_daily_limit_per_user", 1)
|
||||
pages["pages"] = [ScrapeError("blocked"), _page([_item(1)], token=None)]
|
||||
client = as_user(user)
|
||||
assert client.get(f"/api/search/related/{SOURCE}").status_code == 422
|
||||
assert quota.actions_today(db, user.id, quota.QuotaAction.VIDEOS_RELATED) == 0
|
||||
assert _ids(client.get(f"/api/search/related/{SOURCE}")) == [_vid(1)]
|
||||
|
||||
|
||||
def test_failures_past_the_hours_refunds_keep_their_slot(db, make_user, as_user, pages):
|
||||
# A cursor is a free string: a request built to fail would otherwise read YouTube without end.
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "related_daily_limit_per_user", 50)
|
||||
n = search_routes.REFUNDS_PER_HOUR
|
||||
pages["pages"] = [ScrapeError("bad cursor") for _ in range(n + 1)]
|
||||
client = as_user(user)
|
||||
for _ in range(n + 1):
|
||||
assert client.get(f"/api/search/related/{SOURCE}?cursor=bogus").status_code == 422
|
||||
assert quota.actions_today(db, user.id, quota.QuotaAction.VIDEOS_RELATED) == 1
|
||||
|
||||
|
||||
def test_a_zero_limit_turns_related_videos_off(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "related_daily_limit_per_user", 0)
|
||||
resp = as_user(user).get(f"/api/search/related/{SOURCE}")
|
||||
assert resp.status_code == 409
|
||||
assert resp.json()["detail"] == {"code": "refused", "reason": "related_disabled"}
|
||||
assert pages["calls"] == []
|
||||
|
||||
|
||||
def test_the_last_slot_is_taken_under_a_lock(db, make_user):
|
||||
# Checked first and logged after seconds of scraping, requests sent together at the last free
|
||||
# slot all passed. The claim waits for one already taking a slot for this user and action.
|
||||
user = make_user()
|
||||
action = quota.QuotaAction.VIDEOS_RELATED
|
||||
db.execute(select(func.pg_advisory_xact_lock(func.hashtext(action), user.id)))
|
||||
got: list[int | None] = []
|
||||
t = threading.Thread(target=lambda: got.append(quota.claim_action(user.id, action, 1)))
|
||||
t.start()
|
||||
t.join(timeout=1)
|
||||
assert t.is_alive() # it waits for the one holding the lock
|
||||
# ...and counts only once it has the lock: the one holding it takes the last slot meanwhile.
|
||||
db.add(QuotaEvent(user_id=user.id, action=action, units=0))
|
||||
db.commit()
|
||||
t.join(timeout=10)
|
||||
assert got == [None]
|
||||
|
||||
|
||||
def _videos_list_fails(monkeypatch, *, on_call: int = 1, reason: str = "quotaExceeded") -> None:
|
||||
"""YouTube's videos.list refuses from its `on_call`-th call on."""
|
||||
calls = {"n": 0}
|
||||
real = _FakeYT.get_videos
|
||||
|
||||
def get_videos(self, ids):
|
||||
calls["n"] += 1
|
||||
if calls["n"] >= on_call:
|
||||
raise YouTubeError("videos -> 403", reason=reason, path="videos")
|
||||
return real(self, ids)
|
||||
|
||||
monkeypatch.setattr(_FakeYT, "get_videos", get_videos)
|
||||
|
||||
|
||||
def test_a_lookup_that_fails_says_why_not_no_videos(db, make_user, as_user, pages, monkeypatch):
|
||||
# Nothing it found can be kept unenriched; an empty list would read as "nothing related".
|
||||
user = make_user()
|
||||
_videos_list_fails(monkeypatch)
|
||||
pages["pages"] = [_page([_item(1)], token=None)]
|
||||
resp = as_user(user).get(f"/api/search/related/{SOURCE}")
|
||||
assert resp.status_code == 422
|
||||
assert resp.json()["detail"] == {"code": "youtube", "reason": "quota"}
|
||||
assert quota.actions_today(db, user.id, quota.QuotaAction.VIDEOS_RELATED) == 0
|
||||
|
||||
|
||||
def test_a_lookup_failing_on_a_later_page_keeps_what_came_before(
|
||||
db, make_user, as_user, pages, monkeypatch
|
||||
):
|
||||
user = make_user()
|
||||
_videos_list_fails(monkeypatch, on_call=2)
|
||||
pages["pages"] = [_page([_item(1)], token="page2"), _page([_item(2)], token=None)]
|
||||
assert _ids(as_user(user).get(f"/api/search/related/{SOURCE}")) == [_vid(1)]
|
||||
|
||||
|
||||
def test_an_ingest_that_breaks_the_session_is_rolled_back(
|
||||
db, make_user, as_user, pages, monkeypatch
|
||||
):
|
||||
# A database error leaves the session unusable until it is rolled back: the rows of the pages
|
||||
# before could not be read for the answer.
|
||||
user = make_user()
|
||||
real = search_routes.catalog_search.ingest_candidates
|
||||
calls = {"n": 0}
|
||||
|
||||
def ingest(db_, yt, user_, candidates):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 2:
|
||||
db_.execute(text("SELECT 1/0"))
|
||||
return real(db_, yt, user_, candidates)
|
||||
|
||||
monkeypatch.setattr(search_routes.catalog_search, "ingest_candidates", ingest)
|
||||
pages["pages"] = [_page([_item(1)], token="page2"), _page([_item(2)], token=None)]
|
||||
assert _ids(as_user(user).get(f"/api/search/related/{SOURCE}")) == [_vid(1)]
|
||||
|
||||
|
||||
def test_each_row_says_whether_the_user_follows_its_channel(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
stranger = make_user()
|
||||
_known(db, 1, channel="UCfollowed1")
|
||||
_known(db, 2, channel="UCstranger1")
|
||||
db.add(Subscription(user_id=user.id, channel_id="UCfollowed1"))
|
||||
db.add(Subscription(user_id=stranger.id, channel_id="UCstranger1"))
|
||||
db.commit()
|
||||
pages["pages"] = [
|
||||
_page([_item(1, "UCfollowed1"), _item(2, "UCstranger1"), _item(3, "UCnobody01")], None)
|
||||
]
|
||||
rows = as_user(user).get(f"/api/search/related/{SOURCE}").json()["items"]
|
||||
assert {r["id"]: r["followed"] for r in rows} == {
|
||||
_vid(1): True,
|
||||
_vid(2): False, # another user's follow is not this one's
|
||||
_vid(3): False,
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
"""youtube/related_scrape — a video's related videos from the InnerTube `next` endpoint.
|
||||
|
||||
The two pages under `fixtures/` are real answers (2026-10-24), trimmed to three items and the
|
||||
continuation: they hold the `lockupViewModel` shape YouTube draws today. Everything here breaks
|
||||
silently when YouTube moves — a parser that stops finding videos, a cursor that stops paging — so a
|
||||
shape it does not know must say so, never read as "nothing related". The network is an httpx
|
||||
MockTransport."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.youtube import innertube, related_scrape
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
FIRST = json.loads((FIXTURES / "innertube_next_first.json").read_text(encoding="utf-8"))
|
||||
CONTINUATION = json.loads(
|
||||
(FIXTURES / "innertube_next_continuation.json").read_text(encoding="utf-8")
|
||||
)
|
||||
RESULTS_HTML = (
|
||||
'<script>{"INNERTUBE_API_KEY":"live-key","INNERTUBE_CLIENT_VERSION":"2.20261001"}</script>'
|
||||
)
|
||||
|
||||
|
||||
def _results(page: dict) -> list:
|
||||
return page["contents"]["twoColumnWatchNextResults"]["secondaryResults"]["secondaryResults"][
|
||||
"results"
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def net(monkeypatch):
|
||||
"""Route every httpx.Client the InnerTube module opens through a handler the test sets."""
|
||||
calls: list[httpx.Request] = []
|
||||
state: dict = {"handler": None, "calls": calls}
|
||||
|
||||
def transport(request: httpx.Request) -> httpx.Response:
|
||||
calls.append(request)
|
||||
if request.url.path == "/results":
|
||||
return httpx.Response(200, text=RESULTS_HTML)
|
||||
return state["handler"](request)
|
||||
|
||||
real = httpx.Client
|
||||
monkeypatch.setattr(
|
||||
innertube.httpx,
|
||||
"Client",
|
||||
lambda **kw: real(transport=httpx.MockTransport(transport), **kw),
|
||||
)
|
||||
monkeypatch.setattr(innertube, "_config", None)
|
||||
return state
|
||||
|
||||
|
||||
def _answer(net, page, status=200):
|
||||
net["handler"] = lambda request: (
|
||||
httpx.Response(status, text=page)
|
||||
if isinstance(page, str)
|
||||
else httpx.Response(status, json=page)
|
||||
)
|
||||
|
||||
|
||||
def test_a_first_page_gives_its_videos_with_their_channel_and_the_next_cursor(net):
|
||||
_answer(net, FIRST)
|
||||
page = related_scrape.related("SdTZAMDKrNY")
|
||||
assert [it["id"] for it in page["items"]] == ["to-lHJfK4pw", "R8V8CbuxryI", "HLKo4fJx_7k"]
|
||||
first = page["items"][0]
|
||||
assert first["channel_id"] == "UCtslD4DGH6PKyG_1gFAX7sg"
|
||||
assert first["channel_title"] == "Alexander Amini"
|
||||
assert first["title"] == "MIT 6.S191 (2025): Reinforcement Learning"
|
||||
assert first["thumbnail_url"].startswith("https://i.ytimg.com/vi/to-lHJfK4pw/")
|
||||
assert first["published_at"] is None and first["live_broadcast"] == "none"
|
||||
assert page["next_page_token"]
|
||||
body = json.loads(net["calls"][-1].content)
|
||||
assert body["videoId"] == "SdTZAMDKrNY" and "continuation" not in body
|
||||
assert net["calls"][-1].url.path == "/youtubei/v1/next"
|
||||
|
||||
|
||||
def test_the_largest_thumbnail_is_taken(net):
|
||||
_answer(net, FIRST)
|
||||
item = related_scrape.related("SdTZAMDKrNY")["items"][0]
|
||||
sources = _results(FIRST)[0]["lockupViewModel"]["contentImage"]["thumbnailViewModel"]["image"][
|
||||
"sources"
|
||||
]
|
||||
assert item["thumbnail_url"] == sources[-1]["url"]
|
||||
|
||||
|
||||
def test_a_continuation_page_reads_its_videos_and_sends_only_the_cursor(net):
|
||||
_answer(net, CONTINUATION)
|
||||
page = related_scrape.related("SdTZAMDKrNY", continuation="TOKEN", hl="hu", gl="HU")
|
||||
assert len(page["items"]) == 2
|
||||
assert all(it["channel_id"].startswith("UC") for it in page["items"])
|
||||
assert page["next_page_token"]
|
||||
body = json.loads(net["calls"][-1].content)
|
||||
assert body["continuation"] == "TOKEN" and "videoId" not in body
|
||||
assert body["context"]["client"]["hl"] == "hu" and body["context"]["client"]["gl"] == "HU"
|
||||
|
||||
|
||||
def test_the_locale_defaults_to_the_topical_one(net):
|
||||
_answer(net, FIRST)
|
||||
related_scrape.related("SdTZAMDKrNY")
|
||||
client = json.loads(net["calls"][-1].content)["context"]["client"]
|
||||
assert (client["hl"], client["gl"]) == ("en", "US")
|
||||
|
||||
|
||||
def test_a_video_by_several_channels_is_left_out(net):
|
||||
page = copy.deepcopy(FIRST)
|
||||
meta = _results(page)[1]["lockupViewModel"]["metadata"]["lockupMetadataViewModel"]
|
||||
meta["image"] = {"avatarStackViewModel": {"avatars": []}}
|
||||
_answer(net, page)
|
||||
ids = [it["id"] for it in related_scrape.related("SdTZAMDKrNY")["items"]]
|
||||
assert ids == ["to-lHJfK4pw", "HLKo4fJx_7k"]
|
||||
|
||||
|
||||
def test_what_is_not_a_video_is_left_out_and_a_repeat_counts_once(net):
|
||||
page = copy.deepcopy(FIRST)
|
||||
results = _results(page)
|
||||
playlist = copy.deepcopy(results[0])
|
||||
playlist["lockupViewModel"]["contentType"] = "LOCKUP_CONTENT_TYPE_PLAYLIST"
|
||||
playlist["lockupViewModel"]["contentId"] = "PLxyz"
|
||||
results.insert(0, playlist)
|
||||
results.insert(2, copy.deepcopy(results[1]))
|
||||
results.insert(0, {"adSlotRenderer": {}})
|
||||
_answer(net, page)
|
||||
ids = [it["id"] for it in related_scrape.related("SdTZAMDKrNY")["items"]]
|
||||
assert ids == ["to-lHJfK4pw", "R8V8CbuxryI", "HLKo4fJx_7k"]
|
||||
|
||||
|
||||
def test_the_previous_compact_renderer_is_still_read(net):
|
||||
page = copy.deepcopy(FIRST)
|
||||
_results(page).insert(
|
||||
0,
|
||||
{
|
||||
"compactVideoRenderer": {
|
||||
"videoId": "oldshape001",
|
||||
"title": {"simpleText": "Old shape"},
|
||||
"longBylineText": {
|
||||
"runs": [
|
||||
{
|
||||
"text": "Old Chan",
|
||||
"navigationEndpoint": {"browseEndpoint": {"browseId": "UColdchan"}},
|
||||
}
|
||||
]
|
||||
},
|
||||
"thumbnail": {"thumbnails": [{"url": "s.jpg"}, {"url": "b.jpg"}]},
|
||||
}
|
||||
},
|
||||
)
|
||||
_answer(net, page)
|
||||
first = related_scrape.related("SdTZAMDKrNY")["items"][0]
|
||||
assert first == {
|
||||
"id": "oldshape001",
|
||||
"channel_id": "UColdchan",
|
||||
"channel_title": "Old Chan",
|
||||
"title": "Old shape",
|
||||
"published_at": None,
|
||||
"thumbnail_url": "b.jpg",
|
||||
"live_broadcast": "none",
|
||||
}
|
||||
|
||||
|
||||
def test_the_last_page_has_no_cursor(net):
|
||||
page = copy.deepcopy(FIRST)
|
||||
_results(page).pop() # the continuationItemRenderer
|
||||
_answer(net, page)
|
||||
assert related_scrape.related("SdTZAMDKrNY")["next_page_token"] is None
|
||||
|
||||
|
||||
def test_a_video_youtube_no_longer_has_is_an_empty_page(net):
|
||||
_answer(
|
||||
net,
|
||||
{
|
||||
"contents": {
|
||||
"twoColumnWatchNextResults": {
|
||||
"results": {
|
||||
"results": {
|
||||
"contents": [
|
||||
{
|
||||
"itemSectionRenderer": {
|
||||
"contents": [{"backgroundPromoRenderer": {}}]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
assert related_scrape.related("aaaaaaaaaaa") == {"items": [], "next_page_token": None}
|
||||
|
||||
|
||||
def test_a_watch_frame_with_no_related_column_and_no_word_why_is_an_error(net):
|
||||
# The frame alone, its related column moved somewhere this does not look: a lost shape, not
|
||||
# "nothing related".
|
||||
page = copy.deepcopy(FIRST)
|
||||
watch = page["contents"]["twoColumnWatchNextResults"]
|
||||
watch["sideColumn"] = watch.pop("secondaryResults")
|
||||
_answer(net, page)
|
||||
with pytest.raises(related_scrape.ScrapeError):
|
||||
related_scrape.related("SdTZAMDKrNY")
|
||||
|
||||
|
||||
def test_a_related_list_drawn_by_renderers_this_does_not_read_is_an_error(net):
|
||||
page = copy.deepcopy(FIRST)
|
||||
results = _results(page)
|
||||
results[:] = [{"videoTileViewModel": entry} for entry in results]
|
||||
_answer(net, page)
|
||||
with pytest.raises(related_scrape.ScrapeError):
|
||||
related_scrape.related("SdTZAMDKrNY")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"answer",
|
||||
[
|
||||
{"responseContext": {}}, # no watch page frame at all
|
||||
{"onResponseReceivedEndpoints": [{"somethingElse": {}}]}, # a continuation we do not know
|
||||
"<html>consent</html>", # not JSON
|
||||
[1, 2], # JSON, not an object
|
||||
],
|
||||
)
|
||||
def test_an_answer_of_an_unknown_shape_is_an_error_not_an_empty_list(net, answer):
|
||||
_answer(net, answer)
|
||||
with pytest.raises(related_scrape.ScrapeError):
|
||||
related_scrape.related("SdTZAMDKrNY")
|
||||
|
||||
|
||||
def test_a_refused_request_is_an_error_whatever_its_body_says(net):
|
||||
_answer(net, FIRST, status=429)
|
||||
with pytest.raises(related_scrape.ScrapeError):
|
||||
related_scrape.related("SdTZAMDKrNY")
|
||||
@@ -291,6 +291,23 @@ def test_search_results_cleared_through_the_route_are_gone(db, make_user, as_use
|
||||
assert db.execute(select(SearchFind)).first() is None
|
||||
|
||||
|
||||
def test_clearing_leaves_a_video_the_caller_never_found(db, make_user, as_user):
|
||||
# A related list ingests its rows with no find: they are in someone's list right now, and an id
|
||||
# any user could name must not delete them from under it.
|
||||
user = make_user()
|
||||
_video(db, "s1", via_search=True)
|
||||
_video(db, "s2", via_search=True)
|
||||
db.add(SearchFind(user_id=user.id, video_id="s1"))
|
||||
db.commit()
|
||||
r = as_user(user).post("/api/search/clear", json={"video_ids": ["s1", "s2"]})
|
||||
assert r.json() == {"ok": True, "removed": 1}
|
||||
db.expire_all()
|
||||
assert db.get(Video, "s1") is None and db.get(Video, "s2") is not None
|
||||
# Naming only ids it never found removes nothing.
|
||||
r = as_user(user).post("/api/search/clear", json={"video_ids": ["s2"]})
|
||||
assert r.json() == {"ok": True, "removed": 0}
|
||||
|
||||
|
||||
# --- Plex show and season marks ---------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
"""`GET /api/search/youtube` — the per-user daily cap of the live search, both sources.
|
||||
|
||||
The scrape and search.list are replaced by pages the test hands out, and YouTube's videos.list by an
|
||||
offline enrich. What is held: every request takes a slot, a cursor's too; a search that failed
|
||||
outright gives its slot back; a zero limit turns live search off, which says so instead of "try
|
||||
again tomorrow"; a lookup that fails says why instead of answering "no results"; only a few
|
||||
failures an hour get their slot back; and the API source — 100 units a page — reads one page per
|
||||
request, is refused before the call when the shared budget cannot pay for it (checked again under
|
||||
one lock with the call, whose wait is bounded), counts one slot per search though search.list logs
|
||||
its own event, and keeps the slot of a search search.list was already paid for — but not of one
|
||||
that never reached YouTube."""
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from app import quota, sysconfig
|
||||
from app.routes import search as search_routes
|
||||
from app.youtube.client import YouTubeError
|
||||
from app.youtube.innertube import ScrapeError
|
||||
|
||||
ACTION = quota.QuotaAction.VIDEOS_SEARCH
|
||||
|
||||
|
||||
def _item(n: int) -> dict:
|
||||
return {
|
||||
"id": f"srch{n:07d}",
|
||||
"channel_id": "UCsearch001",
|
||||
"channel_title": "Chan",
|
||||
"title": f"Found {n}",
|
||||
"published_at": None,
|
||||
"thumbnail_url": None,
|
||||
"live_broadcast": "none",
|
||||
}
|
||||
|
||||
|
||||
class _FakeYT:
|
||||
fail_videos = False
|
||||
|
||||
def __init__(self, *_a, **_kw):
|
||||
self.spent = 0
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def get_channels(self, ids):
|
||||
return []
|
||||
|
||||
# search.list: the pages the test hands out, each logged as the real client does (100 units,
|
||||
# under the action the route attributes it to) — a refusal YouTube answered too, but not a
|
||||
# failure no endpoint answered (no connection, no token).
|
||||
api_pages: list = []
|
||||
api_calls = 0
|
||||
|
||||
def search_videos(self, q, page_token=None, order="relevance"):
|
||||
_FakeYT.api_calls += 1
|
||||
page = _FakeYT.api_pages.pop(0)
|
||||
if not (isinstance(page, YouTubeError) and not page.path):
|
||||
quota.record_usage(100)
|
||||
self.spent += 100
|
||||
if isinstance(page, Exception):
|
||||
raise page
|
||||
return page
|
||||
|
||||
def get_videos(self, ids):
|
||||
if _FakeYT.fail_videos:
|
||||
raise YouTubeError("videos -> 403", reason="quotaExceeded", path="videos")
|
||||
return [
|
||||
{
|
||||
"id": i,
|
||||
"snippet": {"title": f"T {i}", "publishedAt": "2025-01-01T00:00:00Z"},
|
||||
"contentDetails": {"duration": "PT30M"},
|
||||
"statistics": {},
|
||||
"status": {},
|
||||
}
|
||||
for i in ids
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pages(monkeypatch, db):
|
||||
"""The scrape answers with the pages in `state["pages"]`, one per call."""
|
||||
sysconfig.set_value(db, "shorts_probe_max_seconds", 60)
|
||||
sysconfig.set_value(db, "search_source", "scrape")
|
||||
state: dict = {"pages": [], "calls": 0}
|
||||
|
||||
def search(term, continuation=None):
|
||||
state["calls"] += 1
|
||||
page = state["pages"].pop(0)
|
||||
if isinstance(page, Exception):
|
||||
raise page
|
||||
return page
|
||||
|
||||
monkeypatch.setattr(search_routes.search_scrape, "search", search)
|
||||
monkeypatch.setattr(search_routes, "YouTubeClient", _FakeYT)
|
||||
monkeypatch.setattr(_FakeYT, "fail_videos", False)
|
||||
monkeypatch.setattr(_FakeYT, "api_pages", [])
|
||||
monkeypatch.setattr(_FakeYT, "api_calls", 0)
|
||||
return state
|
||||
|
||||
|
||||
def _page(n: int) -> dict:
|
||||
return {"items": [_item(n)], "next_page_token": None}
|
||||
|
||||
|
||||
def test_every_request_takes_a_slot_a_cursors_too(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 1)
|
||||
pages["pages"] = [_page(1), _page(2)]
|
||||
client = as_user(user)
|
||||
assert client.get("/api/search/youtube?q=cats").status_code == 200
|
||||
refused = client.get("/api/search/youtube?q=cats&cursor=more")
|
||||
assert refused.status_code == 429
|
||||
assert refused.json()["detail"]["reason"] == "search_daily_limit"
|
||||
assert pages["calls"] == 1
|
||||
|
||||
|
||||
def test_a_search_that_failed_gives_its_slot_back(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 1)
|
||||
pages["pages"] = [ScrapeError("blocked"), _page(1)]
|
||||
client = as_user(user)
|
||||
assert client.get("/api/search/youtube?q=cats").status_code == 422
|
||||
assert quota.actions_today(db, user.id, ACTION) == 0
|
||||
assert client.get("/api/search/youtube?q=cats").status_code == 200
|
||||
assert quota.actions_today(db, user.id, ACTION) == 1
|
||||
|
||||
|
||||
def test_a_zero_limit_turns_live_search_off(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 0)
|
||||
resp = as_user(user).get("/api/search/youtube?q=cats")
|
||||
assert resp.status_code == 409
|
||||
assert resp.json()["detail"] == {"code": "refused", "reason": "search_disabled"}
|
||||
assert pages["calls"] == 0
|
||||
|
||||
|
||||
def test_a_zero_limit_turns_the_api_source_off_too(db, make_user, as_user, pages):
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "search_source", "api")
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 0)
|
||||
resp = as_user(user).get("/api/search/youtube?q=cats")
|
||||
assert resp.status_code == 409
|
||||
assert resp.json()["detail"]["reason"] == "search_disabled"
|
||||
|
||||
|
||||
def test_a_lookup_that_fails_says_why_not_no_results(db, make_user, as_user, pages, monkeypatch):
|
||||
user = make_user()
|
||||
monkeypatch.setattr(_FakeYT, "fail_videos", True)
|
||||
pages["pages"] = [_page(1)]
|
||||
resp = as_user(user).get("/api/search/youtube?q=cats")
|
||||
assert resp.status_code == 422
|
||||
assert resp.json()["detail"] == {"code": "youtube", "reason": "quota"}
|
||||
assert quota.actions_today(db, user.id, ACTION) == 0
|
||||
|
||||
|
||||
def _api(db) -> None:
|
||||
sysconfig.set_value(db, "search_source", "api")
|
||||
sysconfig.set_value(db, "quota_daily_budget", 10000)
|
||||
|
||||
|
||||
def test_the_api_source_reads_one_page_per_request(db, make_user, as_user, pages):
|
||||
# Each page is 100 units: a short page is answered as it is, with its cursor, never paged on.
|
||||
_api(db)
|
||||
_FakeYT.api_pages = [{"items": [_item(1)], "next_page_token": "nextpage"}, _page(2)]
|
||||
resp = as_user(make_user()).get("/api/search/youtube?q=cats&limit=20")
|
||||
assert resp.status_code == 200
|
||||
assert _FakeYT.api_calls == 1
|
||||
assert resp.json()["next_cursor"] == "nextpage"
|
||||
|
||||
|
||||
def test_the_api_source_counts_one_slot_per_search(db, make_user, as_user, pages):
|
||||
# search.list logs its own event under the action (record_usage): accounting, not a second slot.
|
||||
user = make_user()
|
||||
_api(db)
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 2)
|
||||
_FakeYT.api_pages = [_page(1), _page(2), _page(3)]
|
||||
client = as_user(user)
|
||||
assert client.get("/api/search/youtube?q=cats").status_code == 200
|
||||
assert quota.actions_today(db, user.id, ACTION) == 1
|
||||
assert client.get("/api/search/youtube?q=dogs").status_code == 200
|
||||
refused = client.get("/api/search/youtube?q=birds")
|
||||
assert refused.status_code == 429
|
||||
assert refused.json()["detail"]["reason"] == "search_daily_limit"
|
||||
assert _FakeYT.api_calls == 2
|
||||
|
||||
|
||||
def test_the_api_source_takes_its_slot_under_the_lock(db, make_user, as_user, pages, monkeypatch):
|
||||
user = make_user()
|
||||
_api(db)
|
||||
claimed: list = []
|
||||
real = quota.claim_action
|
||||
|
||||
def claim(uid, action, limit):
|
||||
claimed.append(action)
|
||||
return real(uid, action, limit)
|
||||
|
||||
monkeypatch.setattr(search_routes.quota, "claim_action", claim)
|
||||
_FakeYT.api_pages = [_page(1)]
|
||||
assert as_user(user).get("/api/search/youtube?q=cats").status_code == 200
|
||||
assert claimed == [ACTION]
|
||||
|
||||
|
||||
def test_the_api_source_is_refused_before_the_call_when_the_budget_cannot_pay(
|
||||
db, make_user, as_user, pages
|
||||
):
|
||||
user = make_user()
|
||||
_api(db)
|
||||
sysconfig.set_value(db, "quota_daily_budget", 50)
|
||||
_FakeYT.api_pages = [_page(1)]
|
||||
resp = as_user(user).get("/api/search/youtube?q=cats")
|
||||
assert resp.status_code == 429
|
||||
assert resp.json()["detail"]["reason"] == "quota_spent"
|
||||
assert _FakeYT.api_calls == 0
|
||||
assert quota.actions_today(db, user.id, ACTION) == 0
|
||||
|
||||
|
||||
def test_an_api_search_that_search_list_refused_keeps_its_slot(db, make_user, as_user, pages):
|
||||
# YouTube charges a refused call too (the client records the units first), so a search that
|
||||
# reached search.list has spent the shared budget: refunding it let a bogus cursor spend it all.
|
||||
user = make_user()
|
||||
_api(db)
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 1)
|
||||
_FakeYT.api_pages = [
|
||||
YouTubeError("search -> 400", reason="invalidPageToken", path="search"),
|
||||
_page(1),
|
||||
]
|
||||
client = as_user(user)
|
||||
assert client.get("/api/search/youtube?q=cats&cursor=bogus").status_code == 422
|
||||
assert quota.actions_today(db, user.id, ACTION) == 1
|
||||
refused = client.get("/api/search/youtube?q=cats")
|
||||
assert refused.status_code == 429
|
||||
assert refused.json()["detail"]["reason"] == "search_daily_limit"
|
||||
assert _FakeYT.api_calls == 1
|
||||
|
||||
|
||||
def test_an_api_search_the_budget_refused_at_the_call_gives_its_slot_back(
|
||||
db, make_user, as_user, pages, monkeypatch
|
||||
):
|
||||
user = make_user()
|
||||
_api(db)
|
||||
answers = iter([True, False]) # the pre-check passes; the budget is gone by the call
|
||||
monkeypatch.setattr(search_routes.quota, "can_spend", lambda _db, _u: next(answers))
|
||||
_FakeYT.api_pages = [_page(1)]
|
||||
resp = as_user(user).get("/api/search/youtube?q=cats")
|
||||
assert resp.status_code == 429
|
||||
assert resp.json()["detail"]["reason"] == "quota_spent"
|
||||
assert _FakeYT.api_calls == 0
|
||||
assert quota.actions_today(db, user.id, ACTION) == 0
|
||||
|
||||
|
||||
def test_the_budget_check_and_the_call_it_pays_for_hold_one_lock(
|
||||
db, make_user, as_user, pages, monkeypatch
|
||||
):
|
||||
# Checked apart, searches sent together at the last 100 units all passed, and all spent: the
|
||||
# check and the call sit inside ONE hold of the lock, not two.
|
||||
user = make_user()
|
||||
_api(db)
|
||||
events: list[str] = []
|
||||
real_check = quota.can_spend
|
||||
real_call = _FakeYT.search_videos
|
||||
|
||||
class _Recorded:
|
||||
def __init__(self):
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def acquire(self, timeout=-1):
|
||||
events.append("acquire")
|
||||
return self._lock.acquire(timeout=timeout)
|
||||
|
||||
def release(self):
|
||||
events.append("release")
|
||||
self._lock.release()
|
||||
|
||||
def can_spend(db_, units):
|
||||
events.append("check")
|
||||
return real_check(db_, units)
|
||||
|
||||
def search_videos(self, q, page_token=None, order="relevance"):
|
||||
events.append("call")
|
||||
return real_call(self, q, page_token=page_token, order=order)
|
||||
|
||||
monkeypatch.setattr(search_routes, "_api_search", _Recorded())
|
||||
monkeypatch.setattr(search_routes.quota, "can_spend", can_spend)
|
||||
monkeypatch.setattr(_FakeYT, "search_videos", search_videos)
|
||||
_FakeYT.api_pages = [_page(1)]
|
||||
assert as_user(user).get("/api/search/youtube?q=cats").status_code == 200
|
||||
assert events == ["check", "acquire", "check", "call", "release"]
|
||||
|
||||
|
||||
def test_a_search_kept_waiting_for_the_lock_is_refused_as_busy_and_keeps_nothing(
|
||||
db, make_user, as_user, pages, monkeypatch
|
||||
):
|
||||
# Each waiter holds a request worker: a slow YouTube must not park them all behind one another.
|
||||
user = make_user()
|
||||
_api(db)
|
||||
monkeypatch.setattr(search_routes, "API_SEARCH_WAIT_SECONDS", 0.05)
|
||||
_FakeYT.api_pages = [_page(1)]
|
||||
# Held by another search for a while: a wait without its bound would get it, and be answered.
|
||||
assert search_routes._api_search.acquire(timeout=1)
|
||||
later = threading.Timer(2.0, search_routes._api_search.release)
|
||||
later.start()
|
||||
try:
|
||||
resp = as_user(user).get("/api/search/youtube?q=cats")
|
||||
finally:
|
||||
later.join()
|
||||
assert resp.status_code == 429
|
||||
assert resp.json()["detail"]["reason"] == "search_busy"
|
||||
assert _FakeYT.api_calls == 0
|
||||
assert quota.actions_today(db, user.id, ACTION) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure",
|
||||
[
|
||||
YouTubeError("YouTube API unreachable (ConnectError)", reason="transport"),
|
||||
YouTubeError("User has no stored OAuth token"),
|
||||
],
|
||||
ids=["no-connection", "no-token"],
|
||||
)
|
||||
def test_an_api_search_that_never_reached_youtube_gives_its_slot_back(
|
||||
db, make_user, as_user, pages, failure
|
||||
):
|
||||
user = make_user()
|
||||
_api(db)
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 1)
|
||||
_FakeYT.api_pages = [failure, _page(1)]
|
||||
client = as_user(user)
|
||||
assert client.get("/api/search/youtube?q=cats").status_code == 422
|
||||
assert quota.actions_today(db, user.id, ACTION) == 0
|
||||
assert client.get("/api/search/youtube?q=cats").status_code == 200
|
||||
|
||||
|
||||
def test_an_api_search_whose_answer_never_came_keeps_its_slot(db, make_user, as_user, pages):
|
||||
# The request went out (a read timeout): YouTube may have counted it.
|
||||
user = make_user()
|
||||
_api(db)
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 1)
|
||||
_FakeYT.api_pages = [
|
||||
YouTubeError("YouTube API unreachable (ReadTimeout)", reason="transport", sent=True),
|
||||
_page(1),
|
||||
]
|
||||
client = as_user(user)
|
||||
assert client.get("/api/search/youtube?q=cats").status_code == 422
|
||||
assert quota.actions_today(db, user.id, ACTION) == 1
|
||||
assert client.get("/api/search/youtube?q=cats").status_code == 429
|
||||
|
||||
|
||||
def test_failures_past_the_hours_refunds_keep_their_slot(db, make_user, as_user, pages):
|
||||
# A cursor is a free string: a request built to fail would otherwise read YouTube without end.
|
||||
user = make_user()
|
||||
sysconfig.set_value(db, "search_daily_limit_per_user", 50)
|
||||
n = search_routes.REFUNDS_PER_HOUR
|
||||
pages["pages"] = [ScrapeError("bad cursor") for _ in range(n + 1)]
|
||||
client = as_user(user)
|
||||
for _ in range(n + 1):
|
||||
assert client.get("/api/search/youtube?q=cats&cursor=bogus").status_code == 422
|
||||
assert quota.actions_today(db, user.id, ACTION) == 1
|
||||
@@ -9,7 +9,7 @@ import json
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.youtube import search_scrape
|
||||
from app.youtube import innertube, search_scrape
|
||||
|
||||
RESULTS_HTML = (
|
||||
'<script>{"INNERTUBE_API_KEY":"live-key","INNERTUBE_CLIENT_VERSION":"2.20261001"}</script>'
|
||||
@@ -79,11 +79,11 @@ def net(monkeypatch):
|
||||
|
||||
real = httpx.Client
|
||||
monkeypatch.setattr(
|
||||
search_scrape.httpx,
|
||||
innertube.httpx,
|
||||
"Client",
|
||||
lambda **kw: real(transport=httpx.MockTransport(transport), **kw),
|
||||
)
|
||||
monkeypatch.setattr(search_scrape, "_config", None)
|
||||
monkeypatch.setattr(innertube, "_config", None)
|
||||
state["calls"] = calls
|
||||
return state
|
||||
|
||||
@@ -171,7 +171,7 @@ def test_a_failed_key_fetch_falls_back_for_now_and_tries_again_next_time(net, re
|
||||
with no error anywhere."""
|
||||
net["handler"] = _serve(results_html=results_html)
|
||||
search_scrape.search("a")
|
||||
assert net["calls"][-1].url.params["key"] == search_scrape._FALLBACK_KEY
|
||||
assert net["calls"][-1].url.params["key"] == innertube._FALLBACK_KEY
|
||||
|
||||
net["handler"] = _serve()
|
||||
search_scrape.search("b")
|
||||
|
||||
@@ -13,10 +13,13 @@ a placeholder never becomes the video's permanent date.
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from app import sysconfig
|
||||
from app.models import User
|
||||
from app.catalog.models import Video
|
||||
from app.catalog.search import ingest_candidates
|
||||
from app.youtube.client import YouTubeError
|
||||
|
||||
|
||||
class _FakeYT:
|
||||
@@ -97,6 +100,25 @@ def test_scrape_ingest_enrich_miss_keeps_nonnull_placeholder(db):
|
||||
assert c.enriched_at is None
|
||||
|
||||
|
||||
class _FailingYT(_FakeYT):
|
||||
def get_videos(self, ids):
|
||||
raise YouTubeError("videos -> 403", reason="quotaExceeded", path="videos")
|
||||
|
||||
|
||||
def test_a_videos_list_failure_raises_and_keeps_the_stubs(db):
|
||||
# Swallowed, it answered as a page with nothing on it — "no results" for a search whose lookup
|
||||
# never ran. The stubs stay: the FK targets, backfilled later.
|
||||
user = User(email="searcher3@example.com")
|
||||
db.add(user)
|
||||
db.commit()
|
||||
|
||||
with pytest.raises(YouTubeError):
|
||||
ingest_candidates(db, _FailingYT({}), user, [_candidate("vid_ddddddd", "UC_chan_d")])
|
||||
|
||||
db.rollback() # what the caller does: the stubs were committed before the lookup
|
||||
assert db.get(Video, "vid_ddddddd") is not None
|
||||
|
||||
|
||||
def test_search_youtube_route_returns_422_when_ingest_fails(db, monkeypatch, override_dep):
|
||||
# Route-level guard (B-core-1): an ingest failure with nothing yet collected must surface as a 422
|
||||
# + message on this JSON endpoint (the FE hides 5xx behind a generic "connection lost" + auto-retry,
|
||||
|
||||
@@ -45,6 +45,7 @@ UNIT_MODELS = {
|
||||
"SavedView",
|
||||
"ComfortPin",
|
||||
"TakeoutItem",
|
||||
"TakeoutChannelDismissal",
|
||||
"VideoUnmark",
|
||||
"Tag",
|
||||
"ChannelTag",
|
||||
@@ -367,6 +368,8 @@ UNIT_COMMITS = {
|
||||
"reader/takeout.py:run_import",
|
||||
# Run inside the Shorts job, on its session: each user's waiting rows land on their own.
|
||||
"reader/takeout.py:apply_waiting",
|
||||
# Inside either of those: the lengths YouTube gave land before the channels are asked for.
|
||||
"reader/takeout.py:_channel_list",
|
||||
},
|
||||
# The catalog's ingest jobs commit per page or batch, a YouTube call between each: a page
|
||||
# fetched and stored is not lost when the next call fails, and an enrich that fails rolls back
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""A catalog video as the feed lists it, the row a player opened from an address starts from. DB lane."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.catalog.models import Channel, Video
|
||||
from app.reader.models import VideoState
|
||||
|
||||
|
||||
def _video(db, vid="v1"):
|
||||
db.add(Channel(id="UCo", title="Owner", handle="@owner"))
|
||||
db.flush()
|
||||
db.add(
|
||||
Video(
|
||||
id=vid,
|
||||
title="A talk",
|
||||
channel_id="UCo",
|
||||
published_at=datetime.now(timezone.utc),
|
||||
duration_seconds=3600,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def test_a_video_comes_as_the_feed_row_with_my_own_state(db, make_user, as_user):
|
||||
me, other = make_user(), make_user()
|
||||
_video(db)
|
||||
db.add(VideoState(user_id=me.id, video_id="v1", status="new", position_seconds=600))
|
||||
db.add(VideoState(user_id=other.id, video_id="v1", status="watched", position_seconds=90))
|
||||
db.commit()
|
||||
r = as_user(me).get("/api/videos/v1/row")
|
||||
assert r.status_code == 200, r.text
|
||||
row = r.json()
|
||||
assert (row["id"], row["title"], row["channel_title"]) == ("v1", "A talk", "Owner")
|
||||
assert (row["status"], row["position_seconds"]) == ("new", 600)
|
||||
assert row["watch_url"] == "https://www.youtube.com/watch?v=v1"
|
||||
|
||||
|
||||
def test_a_video_never_opened_has_no_state(db, make_user, as_user):
|
||||
_video(db)
|
||||
row = as_user(make_user()).get("/api/videos/v1/row").json()
|
||||
assert (row["status"], row["position_seconds"], row["saved"]) == ("new", 0, False)
|
||||
|
||||
|
||||
def test_a_video_outside_the_catalog_is_not_found(db, make_user, as_user):
|
||||
r = as_user(make_user()).get("/api/videos/nope/row")
|
||||
assert r.status_code == 404
|
||||
assert r.json()["detail"]["code"] == "not_found"
|
||||
@@ -0,0 +1,538 @@
|
||||
"""The channels a user's Takeout history shows them watching but not following: which channels make
|
||||
the list (five videos of five minutes or more, none they follow, block, put out or own), what the
|
||||
import asks YouTube for it and when, and the channel's watched videos made ready to play."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select, update
|
||||
|
||||
from app import quota
|
||||
from app.catalog import service as catalog_service
|
||||
from app.catalog.models import BlockedChannel, Channel, ExploredChannel, Subscription, Video
|
||||
from app.db import SessionLocal
|
||||
from app.reader import queries, service, takeout
|
||||
from app.reader.models import TakeoutChannelDismissal, TakeoutItem, TakeoutKind
|
||||
from app.routes import feed as feed_routes
|
||||
from app.sync import explore as sync_explore
|
||||
from app.sync import videos as sync_videos
|
||||
from app.youtube.client import YouTubeError
|
||||
|
||||
T0 = datetime(2026, 5, 1, 12, 0, tzinfo=timezone.utc)
|
||||
LONG = 600
|
||||
SHORT = 120
|
||||
|
||||
|
||||
def _ch(n: int) -> str:
|
||||
return f"UC{n:022d}"
|
||||
|
||||
|
||||
def _vid(channel: int, n: int) -> str:
|
||||
return f"c{channel:02d}v{n:07d}"
|
||||
|
||||
|
||||
def _watched(db, user, channel: int, lengths: list[int | None], *, at=T0, asked=True):
|
||||
"""Stage `len(lengths)` watched videos of a channel, the newest first, each with its length
|
||||
already asked (None: YouTube no longer has it) — or not asked yet."""
|
||||
service.stage_takeout(
|
||||
db,
|
||||
user,
|
||||
TakeoutKind.WATCHED,
|
||||
{_vid(channel, i): (at - timedelta(days=i), _ch(channel)) for i in range(len(lengths))},
|
||||
)
|
||||
db.flush()
|
||||
if asked:
|
||||
ids = [_vid(channel, i) for i in range(len(lengths))]
|
||||
service.record_takeout_lengths(
|
||||
db, user, ids, {v: s for v, s in zip(ids, lengths, strict=True) if s is not None}
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _channel(db, n: int, title: str | None = None):
|
||||
db.add(Channel(id=_ch(n), title=title or f"Channel {n}", details_synced_at=T0))
|
||||
db.commit()
|
||||
|
||||
|
||||
def _listed(db, user) -> list[tuple[str, int]]:
|
||||
return [(ch.id, n) for ch, n, _ in queries.watched_channels(db, user)]
|
||||
|
||||
|
||||
# --- which channels make the list --------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_channel_makes_the_list_with_five_watched_videos_of_five_minutes_or_more(db, make_user):
|
||||
user = make_user("list@example.com")
|
||||
for n in (1, 2, 3):
|
||||
_channel(db, n)
|
||||
_watched(db, user, 1, [LONG] * 5 + [SHORT] * 3) # five long, three short: on it with 5
|
||||
_watched(db, user, 2, [LONG] * 4 + [SHORT] * 6) # ten watched, only four long: off it
|
||||
_watched(db, user, 3, [299, 300, 300, 300, 300, 300]) # five at exactly five minutes: on it
|
||||
# A tie: channel 1's counted videos were watched later (channel 3's newest is under five minutes).
|
||||
assert _listed(db, user) == [(_ch(1), 5), (_ch(3), 5)]
|
||||
|
||||
|
||||
def test_a_video_youtube_no_longer_has_does_not_count(db, make_user):
|
||||
user = make_user("gone@example.com")
|
||||
_channel(db, 1)
|
||||
_watched(db, user, 1, [LONG] * 4 + [None] * 3)
|
||||
assert _listed(db, user) == []
|
||||
|
||||
|
||||
def test_the_most_watched_lead_and_a_tie_goes_to_the_one_watched_more_lately(db, make_user):
|
||||
user = make_user("order@example.com")
|
||||
for n in (1, 2, 3):
|
||||
_channel(db, n)
|
||||
_watched(db, user, 1, [LONG] * 6, at=T0 - timedelta(days=100))
|
||||
_watched(db, user, 2, [LONG] * 9, at=T0 - timedelta(days=300))
|
||||
_watched(db, user, 3, [LONG] * 6, at=T0)
|
||||
assert _listed(db, user) == [(_ch(2), 9), (_ch(3), 6), (_ch(1), 6)]
|
||||
last = {ch.id: when for ch, _, when in queries.watched_channels(db, user)}
|
||||
assert last[_ch(3)] == T0 # the last watched of the counted ones
|
||||
|
||||
|
||||
def test_a_channel_the_user_follows_blocked_put_out_or_owns_is_not_on_the_list(db, make_user):
|
||||
user = make_user("off@example.com", yt_channel_id=_ch(4))
|
||||
for n in (1, 2, 3, 4, 5):
|
||||
_channel(db, n)
|
||||
_watched(db, user, n, [LONG] * 5)
|
||||
db.add(Subscription(user_id=user.id, channel_id=_ch(1)))
|
||||
db.add(BlockedChannel(user_id=user.id, channel_id=_ch(2)))
|
||||
db.commit()
|
||||
service.dismiss_watched_channel(db, user, _ch(3))
|
||||
db.commit()
|
||||
assert _listed(db, user) == [(_ch(5), 5)]
|
||||
|
||||
|
||||
def test_one_users_follows_and_dismissals_leave_anothers_list_alone(db, make_user):
|
||||
me, other = make_user("me@example.com"), make_user("other@example.com")
|
||||
_channel(db, 1)
|
||||
for user in (me, other):
|
||||
_watched(db, user, 1, [LONG] * 5)
|
||||
db.add(Subscription(user_id=other.id, channel_id=_ch(1)))
|
||||
db.commit()
|
||||
service.dismiss_watched_channel(db, other, _ch(1))
|
||||
db.commit()
|
||||
assert _listed(db, me) == [(_ch(1), 5)]
|
||||
assert _listed(db, other) == []
|
||||
|
||||
|
||||
def test_a_channel_whose_lengths_are_not_all_known_is_pending_until_they_are(db, make_user):
|
||||
user = make_user("pending@example.com")
|
||||
_channel(db, 1)
|
||||
_watched(db, user, 1, [LONG] * 6, asked=False)
|
||||
_watched(db, user, 2, [LONG] * 4, asked=False) # four watched: it can never make the list
|
||||
assert queries.watched_channels_pending(db, user) == 1
|
||||
assert _listed(db, user) == []
|
||||
ids = [_vid(1, i) for i in range(6)]
|
||||
service.record_takeout_lengths(db, user, ids, dict.fromkeys(ids, LONG))
|
||||
db.commit()
|
||||
assert queries.watched_channels_pending(db, user) == 0
|
||||
assert _listed(db, user) == [(_ch(1), 6)]
|
||||
|
||||
|
||||
def test_a_new_upload_of_the_history_keeps_the_lengths_already_asked(db, make_user):
|
||||
user = make_user("again@example.com")
|
||||
_channel(db, 1)
|
||||
_watched(db, user, 1, [LONG] * 5)
|
||||
_watched(db, user, 1, [LONG] * 5, at=T0 + timedelta(days=1), asked=False)
|
||||
assert _listed(db, user) == [(_ch(1), 5)]
|
||||
assert queries.takeout_lengths_to_ask(db, user) == []
|
||||
|
||||
|
||||
# --- what the import asks YouTube for ----------------------------------------------------------
|
||||
|
||||
|
||||
class FakeYouTube:
|
||||
"""Stands in for `YouTubeClient`: answers `videos.list` with the lengths it was given and
|
||||
`channels.list` with a title per channel, and records what it was asked."""
|
||||
|
||||
def __init__(self, lengths: dict[str, int] | None = None, *, fail: bool = False):
|
||||
self.lengths = lengths or {}
|
||||
self.fail = fail
|
||||
self.fail_channels = False
|
||||
self.videos_asked: list[list[str]] = []
|
||||
self.channels_asked: list[list[str]] = []
|
||||
self.actions: list[tuple[int | None, str]] = []
|
||||
|
||||
def __call__(self, db, user):
|
||||
return self
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def get_videos(self, ids):
|
||||
self.videos_asked.append(list(ids))
|
||||
self.actions.append((quota._actor_id.get(), quota._action.get()))
|
||||
if self.fail:
|
||||
raise YouTubeError("refused", reason="quotaExceeded", path="videos")
|
||||
return [
|
||||
{"id": v, "contentDetails": {"duration": f"PT{self.lengths[v]}S"}}
|
||||
for v in ids
|
||||
if v in self.lengths
|
||||
]
|
||||
|
||||
def get_channels(self, ids):
|
||||
self.channels_asked.append(list(ids))
|
||||
self.actions.append((quota._actor_id.get(), quota._action.get()))
|
||||
if self.fail_channels:
|
||||
raise YouTubeError("refused", reason="backendError", path="channels")
|
||||
return [{"id": c, "snippet": {"title": f"Named {c[-2:]}"}} for c in ids]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def youtube(monkeypatch, db, make_user):
|
||||
fetcher = make_user("fetcher@example.com")
|
||||
fake = FakeYouTube()
|
||||
monkeypatch.setattr(takeout, "YouTubeClient", fake)
|
||||
monkeypatch.setattr(takeout, "get_service_user", lambda session: fetcher)
|
||||
monkeypatch.setattr(takeout.quota, "backfill_reserve_reached", lambda: False)
|
||||
return fake
|
||||
|
||||
|
||||
def test_the_import_asks_the_lengths_the_list_needs_and_names_its_channels(db, make_user, youtube):
|
||||
user = make_user("import@example.com")
|
||||
_watched(db, user, 1, [None] * 7, asked=False) # the most watched channel
|
||||
_watched(db, user, 2, [None] * 5, asked=False)
|
||||
_watched(db, user, 3, [None] * 4, asked=False) # too few to ever make it: not asked about
|
||||
youtube.lengths = {_vid(1, i): LONG for i in range(6)} | {_vid(2, i): SHORT for i in range(5)}
|
||||
|
||||
result = takeout.run_import(user.id)
|
||||
|
||||
asked = [_vid(1, i) for i in range(7)] + [_vid(2, i) for i in range(5)]
|
||||
assert youtube.videos_asked == [asked] # the top channel first
|
||||
assert result["lengths_asked"] == 12
|
||||
# Only channel 1 made it (six long; its seventh is gone, channel 2's are short): it is named.
|
||||
assert youtube.channels_asked == [[_ch(1)]]
|
||||
assert result["channels_described"] == 1
|
||||
assert {
|
||||
(user.id, quota.QuotaAction.VIDEOS_LOOKUP),
|
||||
(user.id, quota.QuotaAction.CHANNELS_DISCOVER),
|
||||
} == set(youtube.actions)
|
||||
db.expire_all()
|
||||
assert [(ch.title, n) for ch, n, _ in queries.watched_channels(db, user)] == [("Named 01", 6)]
|
||||
assert queries.watched_channels_pending(db, user) == 0
|
||||
# Asked once: a second run asks nothing again, the gone video included.
|
||||
youtube.videos_asked.clear()
|
||||
youtube.channels_asked.clear()
|
||||
assert "lengths_asked" not in takeout.run_import(user.id)
|
||||
assert youtube.videos_asked == [] and youtube.channels_asked == []
|
||||
|
||||
|
||||
def test_the_lookups_stop_at_the_users_daily_share_and_the_rest_wait(
|
||||
db, make_user, youtube, monkeypatch
|
||||
):
|
||||
user = make_user("share@example.com")
|
||||
_watched(db, user, 1, [None] * 8, asked=False)
|
||||
_watched(db, user, 2, [None] * 6, asked=False)
|
||||
monkeypatch.setattr(takeout, "_lengths", takeout.RateLimiter(10, 3600))
|
||||
takeout.run_import(user.id)
|
||||
assert youtube.videos_asked == [[_vid(1, i) for i in range(8)] + [_vid(2, 0), _vid(2, 1)]]
|
||||
db.expire_all()
|
||||
assert queries.watched_channels_pending(db, user) == 1 # channel 2 still has some to ask
|
||||
youtube.videos_asked.clear()
|
||||
takeout.run_import(user.id)
|
||||
assert youtube.videos_asked == [] # the share is spent for today
|
||||
|
||||
|
||||
@pytest.mark.parametrize("why", ["no_fetcher", "reserve"])
|
||||
def test_nothing_is_asked_without_a_connected_account_or_past_the_reserve(
|
||||
db, make_user, youtube, monkeypatch, why
|
||||
):
|
||||
user = make_user(f"{why}@example.com")
|
||||
_watched(db, user, 1, [None] * 5, asked=False)
|
||||
if why == "no_fetcher":
|
||||
monkeypatch.setattr(takeout, "get_service_user", lambda session: None)
|
||||
else:
|
||||
monkeypatch.setattr(takeout.quota, "backfill_reserve_reached", lambda: True)
|
||||
assert "lengths_asked" not in takeout.run_import(user.id)
|
||||
assert youtube.videos_asked == []
|
||||
assert queries.watched_channels_pending(db, user) == 1
|
||||
|
||||
|
||||
def test_a_youtube_failure_asking_lengths_fails_neither_the_import_nor_its_marks(
|
||||
db, make_user, youtube
|
||||
):
|
||||
user = make_user("fail@example.com")
|
||||
_watched(db, user, 1, [None] * 5, asked=False)
|
||||
youtube.fail = True
|
||||
result = takeout.run_import(user.id)
|
||||
assert "lengths_asked" not in result
|
||||
assert queries.takeout_lengths_to_ask(db, user) == [_vid(1, i) for i in range(5)]
|
||||
db.expire_all()
|
||||
rows = db.execute(select(TakeoutItem).where(TakeoutItem.user_id == user.id)).scalars()
|
||||
assert all(r.looked_up_at is None for r in rows) # left to ask again
|
||||
|
||||
|
||||
def test_the_shorts_job_asks_what_an_import_could_not(db, make_user, youtube):
|
||||
user = make_user("later@example.com")
|
||||
_watched(db, user, 1, [None] * 5, asked=False)
|
||||
youtube.lengths = {_vid(1, i): LONG for i in range(5)}
|
||||
assert takeout.apply_waiting(db)["takeout_lengths_asked"] == 5
|
||||
db.expire_all()
|
||||
assert [n for _, n, _ in queries.watched_channels(db, user)] == [5]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("why", ["follows", "blocked", "dismissed", "own"])
|
||||
def test_a_channel_off_the_list_is_not_asked_about_nor_looked_at_again(
|
||||
db, make_user, youtube, monkeypatch, why
|
||||
):
|
||||
user = make_user(f"off-{why}@example.com", yt_channel_id=_ch(1) if why == "own" else None)
|
||||
_channel(db, 1)
|
||||
_watched(db, user, 1, [None] * 5, asked=False)
|
||||
if why == "follows":
|
||||
db.add(Subscription(user_id=user.id, channel_id=_ch(1)))
|
||||
elif why == "blocked":
|
||||
db.add(BlockedChannel(user_id=user.id, channel_id=_ch(1)))
|
||||
elif why == "dismissed":
|
||||
service.dismiss_watched_channel(db, user, _ch(1))
|
||||
db.commit()
|
||||
runs = []
|
||||
monkeypatch.setattr(takeout, "_channel_list", lambda session, u: runs.append(u.id) or {})
|
||||
assert takeout.apply_waiting(db) == {}
|
||||
# Its rows are never asked about, so they would stay "to ask" for good: the Shorts job must not
|
||||
# take the user up again for them on every run.
|
||||
assert runs == []
|
||||
assert youtube.videos_asked == []
|
||||
|
||||
|
||||
def test_naming_the_channels_is_tried_again_and_meanwhile_the_list_says_it_is_not_complete(
|
||||
db, make_user, youtube
|
||||
):
|
||||
user = make_user("unnamed@example.com")
|
||||
_watched(db, user, 1, [None] * 5, asked=False)
|
||||
youtube.lengths = {_vid(1, i): LONG for i in range(5)}
|
||||
youtube.fail_channels = True
|
||||
takeout.run_import(user.id)
|
||||
db.expire_all()
|
||||
# Every length is known, the channel could not be named: not on the list, and not complete.
|
||||
assert queries.takeout_lengths_to_ask(db, user) == []
|
||||
assert _listed(db, user) == []
|
||||
assert queries.watched_channels_pending(db, user) == 1
|
||||
youtube.fail_channels = False
|
||||
takeout.apply_waiting(db)
|
||||
db.expire_all()
|
||||
assert [(ch.title, n) for ch, n, _ in queries.watched_channels(db, user)] == [("Named 01", 5)]
|
||||
assert queries.watched_channels_pending(db, user) == 0
|
||||
|
||||
|
||||
def test_a_listed_channel_still_to_be_described_is_not_counted_as_one_to_come(db, make_user):
|
||||
user = make_user("stub@example.com")
|
||||
# A stub the catalog made when one of its videos came in: a title, no details yet.
|
||||
db.add(Channel(id=_ch(1), title="From a video"))
|
||||
db.commit()
|
||||
_watched(db, user, 1, [LONG] * 5)
|
||||
assert queries.watched_channels_to_describe(db, user) == [_ch(1)]
|
||||
assert _listed(db, user) == [(_ch(1), 5)]
|
||||
# It is on the list already: "the list may grow" would promise one more that cannot come.
|
||||
assert queries.watched_channels_pending(db, user) == 0
|
||||
|
||||
|
||||
def test_the_lengths_leave_the_watch_later_lookups_their_own_share(
|
||||
db, make_user, youtube, monkeypatch
|
||||
):
|
||||
user = make_user("shares@example.com")
|
||||
monkeypatch.setattr(takeout, "_lookups", takeout.RateLimiter(10, 3600))
|
||||
monkeypatch.setattr(takeout, "_lengths", takeout.RateLimiter(10, 3600))
|
||||
_watched(db, user, 1, [None] * 15, asked=False)
|
||||
takeout.run_import(user.id) # the history: its lengths spend all they may today
|
||||
youtube.videos_asked.clear()
|
||||
service.stage_takeout(db, user, TakeoutKind.WATCH_LATER, {"later000001": (T0, None)})
|
||||
db.commit()
|
||||
takeout.run_import(user.id) # then the export's Watch later file
|
||||
assert ["later000001"] in youtube.videos_asked
|
||||
|
||||
|
||||
# --- the channel's watched videos, ready to play ------------------------------------------------
|
||||
|
||||
|
||||
def _fake_ensure(calls):
|
||||
def ensure(session, yt, ids, *, explore=False):
|
||||
calls.append((list(ids), explore))
|
||||
for vid in ids:
|
||||
if vid.endswith("4"):
|
||||
continue # gone from YouTube since its length was asked
|
||||
session.add(Video(id=vid, channel_id=_ch(1), published_at=T0, via_explore=explore))
|
||||
session.commit()
|
||||
|
||||
return ensure
|
||||
|
||||
|
||||
def test_a_channels_watched_videos_come_ready_to_play_and_explored(
|
||||
db, make_user, as_user, monkeypatch
|
||||
):
|
||||
user = make_user("play@example.com")
|
||||
_channel(db, 1)
|
||||
_watched(db, user, 1, [LONG, SHORT, LONG, None, LONG, LONG, LONG])
|
||||
db.add(Video(id=_vid(1, 0), channel_id=_ch(1), published_at=T0)) # already in the catalog
|
||||
db.commit()
|
||||
calls = []
|
||||
monkeypatch.setattr(feed_routes, "ensure_videos", _fake_ensure(calls))
|
||||
monkeypatch.setattr(feed_routes.quota, "backfill_reserve_reached", lambda: False)
|
||||
|
||||
resp = as_user(user).post(f"/api/takeout/channels/{_ch(1)}/videos")
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
# Only the counted ones, newest first; the short one and the gone ones are left out.
|
||||
assert calls == [([_vid(1, 2), _vid(1, 4), _vid(1, 5), _vid(1, 6)], True)]
|
||||
assert [it["id"] for it in body["items"]] == [_vid(1, 0), _vid(1, 2), _vid(1, 5), _vid(1, 6)]
|
||||
assert body["items"][0]["takeout_watched_at"].startswith("2026-05-01")
|
||||
assert body["gone"] == 2 # one YouTube had lost before, one since
|
||||
assert body["ok"] is True
|
||||
db.expire_all()
|
||||
assert db.execute(
|
||||
select(ExploredChannel).where(
|
||||
ExploredChannel.user_id == user.id, ExploredChannel.channel_id == _ch(1)
|
||||
)
|
||||
).scalar_one()
|
||||
assert (
|
||||
db.get(Channel, _ch(1)).from_explore is True
|
||||
) # nobody follows it: the cleanup's to reclaim
|
||||
|
||||
|
||||
def test_a_followed_channels_watched_videos_come_in_as_the_catalogs_own(
|
||||
db, make_user, as_user, monkeypatch
|
||||
):
|
||||
user, follower = make_user("viewer@example.com"), make_user("follower@example.com")
|
||||
_channel(db, 1)
|
||||
_watched(db, user, 1, [LONG] * 5)
|
||||
db.add(Subscription(user_id=follower.id, channel_id=_ch(1)))
|
||||
db.commit()
|
||||
calls = []
|
||||
monkeypatch.setattr(feed_routes, "ensure_videos", _fake_ensure(calls))
|
||||
monkeypatch.setattr(feed_routes.quota, "backfill_reserve_reached", lambda: False)
|
||||
assert as_user(user).post(f"/api/takeout/channels/{_ch(1)}/videos").status_code == 200
|
||||
# Someone follows it, so it is no exploration's to reclaim: a video flagged as one would never
|
||||
# be cleared again (subscribing clears only an explored channel's) and never marked watched.
|
||||
assert calls == [([_vid(1, i) for i in range(5)], False)]
|
||||
db.expire_all()
|
||||
assert db.get(Channel, _ch(1)).from_explore is False
|
||||
|
||||
|
||||
def test_a_follow_landing_while_the_videos_come_in_leaves_none_of_them_flagged(
|
||||
db, make_user, as_user, monkeypatch
|
||||
):
|
||||
user, follower = make_user("racer@example.com"), make_user("late@example.com")
|
||||
_channel(db, 1)
|
||||
_watched(db, user, 1, [LONG] * 5)
|
||||
fake = _fake_ensure(calls := [])
|
||||
|
||||
def ensure(session, yt, ids, *, explore=False):
|
||||
# Someone subscribes, in a request of their own, while YouTube answers this one.
|
||||
with SessionLocal() as other:
|
||||
ch = other.get(Channel, _ch(1))
|
||||
catalog_service.record_subscription(other, follower, ch, "sub-late")
|
||||
other.commit()
|
||||
fake(session, yt, ids, explore=explore)
|
||||
|
||||
monkeypatch.setattr(feed_routes, "ensure_videos", ensure)
|
||||
monkeypatch.setattr(feed_routes.quota, "backfill_reserve_reached", lambda: False)
|
||||
assert as_user(user).post(f"/api/takeout/channels/{_ch(1)}/videos").status_code == 200
|
||||
assert calls[0][1] is True # asked as the exploration's
|
||||
db.expire_all()
|
||||
flagged = db.scalars(select(Video.id).where(Video.via_explore.is_(True))).all()
|
||||
assert (db.get(Channel, _ch(1)).from_explore, flagged) == (False, [])
|
||||
|
||||
|
||||
def test_the_cleanup_keeps_a_channel_a_watch_history_lists_and_reclaims_its_videos(db, make_user):
|
||||
user = make_user("kept@example.com")
|
||||
_channel(db, 1)
|
||||
_watched(db, user, 1, [LONG] * 5)
|
||||
catalog_service.explore(db, user, db.get(Channel, _ch(1)))
|
||||
db.add(Video(id=_vid(1, 0), channel_id=_ch(1), published_at=T0, via_explore=True))
|
||||
db.add(Channel(id=_ch(2), from_explore=True)) # explored, in nobody's history
|
||||
db.commit()
|
||||
db.execute(update(ExploredChannel).values(created_at=T0 - timedelta(days=365)))
|
||||
db.commit()
|
||||
out = sync_explore.purge_unkept_explored(db)
|
||||
# The unplayed video goes (opening the list's videos brings it back); the channel stays listed.
|
||||
assert (out["videos_deleted"], out["channels_deleted"]) == (1, 1)
|
||||
db.expire_all()
|
||||
assert db.get(Channel, _ch(2)) is None
|
||||
assert _listed(db, user) == [(_ch(1), 5)]
|
||||
|
||||
|
||||
def test_a_blocked_or_unknown_channels_videos_are_refused(db, make_user, as_user):
|
||||
user = make_user("refused@example.com")
|
||||
_channel(db, 1)
|
||||
db.add(BlockedChannel(user_id=user.id, channel_id=_ch(1)))
|
||||
db.commit()
|
||||
client = as_user(user)
|
||||
assert client.post(f"/api/takeout/channels/{_ch(1)}/videos").status_code == 403
|
||||
assert client.post(f"/api/takeout/channels/{_ch(9)}/videos").status_code == 404
|
||||
|
||||
|
||||
def test_ensure_videos_adds_an_explorations_videos_as_its_own(db):
|
||||
db.add(Channel(id=_ch(1), title="C"))
|
||||
db.commit()
|
||||
|
||||
class YT:
|
||||
def get_videos(self, ids):
|
||||
return [{"id": v, "snippet": {"channelId": _ch(1)}} for v in ids]
|
||||
|
||||
sync_videos.ensure_videos(db, YT(), ["exploredvid"], explore=True)
|
||||
sync_videos.ensure_videos(db, YT(), ["organicvid0"])
|
||||
db.expire_all()
|
||||
assert db.get(Video, "exploredvid").via_explore is True
|
||||
assert db.get(Video, "organicvid0").via_explore is False
|
||||
|
||||
|
||||
# --- the routes -----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_list_route_says_what_it_holds_and_whether_a_history_was_uploaded(
|
||||
db, make_user, as_user
|
||||
):
|
||||
user = make_user("route@example.com")
|
||||
client = as_user(user)
|
||||
assert client.get("/api/takeout/channels").json() == {
|
||||
"imported": False,
|
||||
"pending": 0,
|
||||
"channels": [],
|
||||
}
|
||||
_channel(db, 1, "Some channel")
|
||||
_watched(db, user, 1, [LONG] * 5)
|
||||
_watched(db, user, 2, [None] * 5, asked=False)
|
||||
body = client.get("/api/takeout/channels").json()
|
||||
assert body["imported"] is True and body["pending"] == 1
|
||||
assert [(c["id"], c["title"], c["watched"]) for c in body["channels"]] == [
|
||||
(_ch(1), "Some channel", 5)
|
||||
]
|
||||
assert body["channels"][0]["last_watched_at"].startswith("2026-05-01")
|
||||
|
||||
|
||||
def test_a_channel_put_out_of_the_list_comes_back_when_restored(db, make_user, as_user):
|
||||
user = make_user("dismiss@example.com")
|
||||
_channel(db, 1)
|
||||
_watched(db, user, 1, [LONG] * 5)
|
||||
client = as_user(user)
|
||||
url = f"/api/takeout/channels/{_ch(1)}/dismissal"
|
||||
assert client.put(url).json() == {"ok": True, "channel_id": _ch(1)}
|
||||
assert client.put(url).status_code == 200 # again: no error
|
||||
assert client.get("/api/takeout/channels").json()["channels"] == []
|
||||
assert client.delete(url).json() == {"ok": True, "channel_id": _ch(1)}
|
||||
assert [c["id"] for c in client.get("/api/takeout/channels").json()["channels"]] == [_ch(1)]
|
||||
db.expire_all()
|
||||
assert db.execute(select(TakeoutChannelDismissal)).scalars().all() == []
|
||||
|
||||
|
||||
def test_only_a_channel_of_the_users_own_history_can_be_put_out_of_the_list(db, make_user, as_user):
|
||||
user, other = make_user("mine@example.com"), make_user("theirs@example.com")
|
||||
_channel(db, 1)
|
||||
_watched(db, other, 1, [LONG] * 5)
|
||||
client = as_user(user)
|
||||
assert client.put(f"/api/takeout/channels/{_ch(1)}/dismissal").status_code == 404
|
||||
assert client.put(f"/api/takeout/channels/{_ch(9)}/dismissal").status_code == 404
|
||||
db.expire_all()
|
||||
assert db.execute(select(TakeoutChannelDismissal)).scalars().all() == []
|
||||
|
||||
|
||||
def test_a_dismissal_of_an_overlong_channel_id_is_refused_before_the_database(
|
||||
db, make_user, as_user
|
||||
):
|
||||
user = make_user("long@example.com")
|
||||
assert as_user(user).put(f"/api/takeout/channels/{'U' * 33}/dismissal").status_code == 422
|
||||
@@ -193,3 +193,45 @@ def test_any_other_token_refusal_keeps_the_grant(monkeypatch):
|
||||
c._access_token()
|
||||
assert tok.scopes == "s"
|
||||
assert refusal_reason(caught.value) == "unavailable"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("failure", "sent"),
|
||||
[
|
||||
(httpx.ConnectError("refused"), False),
|
||||
(httpx.ConnectTimeout("slow connect"), False),
|
||||
(httpx.ProxyError("proxy down"), False),
|
||||
(httpx.ReadTimeout("no answer"), True),
|
||||
(httpx.RemoteProtocolError("dropped"), True),
|
||||
],
|
||||
)
|
||||
def test_a_transport_failure_says_whether_the_request_went_out(failure, sent):
|
||||
"""A search that never reached YouTube spent nothing and gets its slot back; one whose answer
|
||||
never came may have been counted, and keeps it (`routes/search`)."""
|
||||
|
||||
def request(*_a, **_k):
|
||||
raise failure
|
||||
|
||||
c = yt.YouTubeClient.__new__(yt.YouTubeClient)
|
||||
c._http = SimpleNamespace(request=request)
|
||||
with pytest.raises(YouTubeError) as caught:
|
||||
c._send("GET", "https://example.invalid")
|
||||
assert caught.value.reason == "transport"
|
||||
assert caught.value.sent is sent
|
||||
|
||||
|
||||
def test_a_call_youtube_answered_is_spent_a_refused_one_too(monkeypatch):
|
||||
resp = httpx.Response(
|
||||
400,
|
||||
json={"error": {"errors": [{"reason": "invalidPageToken"}]}},
|
||||
request=httpx.Request("GET", f"{yt.API_BASE}/search"),
|
||||
)
|
||||
recorded: list[int] = []
|
||||
c = yt.YouTubeClient.__new__(yt.YouTubeClient)
|
||||
c.db, c.spent = None, 0
|
||||
monkeypatch.setattr(yt.sysconfig, "get_str", lambda d, key: "a-key")
|
||||
monkeypatch.setattr(yt.quota, "record_usage", recorded.append)
|
||||
monkeypatch.setattr(c, "_send", lambda *a, **k: resp)
|
||||
with pytest.raises(YouTubeError):
|
||||
c._get("search", {}, cost=100)
|
||||
assert (recorded, c.spent) == ([100], 100)
|
||||
|
||||
+34
-5
@@ -225,7 +225,10 @@ Also in force:
|
||||
tag chip is `Chip`; a sortable row's grip is `DragHandle`. On the always-dark player chrome both
|
||||
`Button` and `IconButton` use the `overlay` variant (white, a white layer), whatever the theme; the Plex
|
||||
control row is IconButton's `player` rung (36, a 20px glyph, round, 44 on touch). A pressed toggle is
|
||||
`pressed`: the solid accent on a `Button`, the accent glyph on an `IconButton`. A raw `<button>` (or a bare
|
||||
`pressed`: the solid accent on a `Button`, the accent glyph on an `IconButton`, kept under the pointer
|
||||
(no hover layer or hover colour over it). A mode cycle (the player's auto-advance and loop) is no
|
||||
two-state switch: `lit` gives it the same look when it is not off, without `aria-pressed`, and its name
|
||||
says the mode. A raw `<button>` (or a bare
|
||||
`FocusSafeButton`) outside the control primitives (eslint `BUTTON_PRIMITIVES`) is a lint error. A text-less button must have an accessible name, and the type enforces
|
||||
it. [WCAG 4.1.2]
|
||||
- **The chip family** (`Chip`, E28 S3b): rounded-full, never under 24 (A3 grows it to 44 on touch).
|
||||
@@ -251,8 +254,13 @@ Also in force:
|
||||
- A button that starts slow work shows `loading` (a spinner, `aria-busy`) and can't be pressed twice.
|
||||
[Nielsen #1]
|
||||
- **A glyph means one thing.** Play (▷) starts playback, or resumes a paused transfer; a retry is the
|
||||
refresh arrow (`RefreshCw`); a reset or revert is the counter-clockwise arrow (`RotateCcw`). A failed
|
||||
download's Retry had worn the Play glyph, which promised a video. [Nielsen #4]
|
||||
refresh arrow (`RefreshCw`), and so is doing a download again; a reset or revert is the
|
||||
counter-clockwise arrow (`RotateCcw`), and so is playing from the beginning, on the card and in its
|
||||
menu alike; clearing a video's progress and status is the eraser (`Eraser`). A failed download's Retry
|
||||
had worn the Play glyph, which promised a video. The skip arrows (⏮ ⏭) are Previous /
|
||||
Next; the auto-advance mode beside them wears list glyphs (`ListEnd` next, `ListStart` previous,
|
||||
`Shuffle` random; off is `ListEnd`, not lit) — a mode in the skip arrows put two identical ⏭ on the
|
||||
panel's glyph-only row. [Nielsen #4]
|
||||
|
||||
## Surfaces and page chrome — _Decided_ (batch B)
|
||||
|
||||
@@ -498,7 +506,10 @@ of a full-width panel and nothing on the right.
|
||||
## Interaction rules — _Decided_
|
||||
|
||||
- **Keyboard:** everything works by keyboard, in visual order, with no traps. A shortcut is a row in
|
||||
`lib/keymap.ts`; list and grid navigation is `NavGrid`/`keyboardNav`. [WCAG 2.1.1, 2.4.3, 2.1.2]
|
||||
`lib/keymap.ts`; list and grid navigation is `NavGrid`/`keyboardNav`. An open dialog or player
|
||||
silences the page's list keys, but a list inside the topmost one walks while the focus is in it
|
||||
(the player's related videos); the walk stays inside that layer, and its arrows there move the list,
|
||||
not the video. [WCAG 2.1.1, 2.4.3, 2.1.2]
|
||||
- **Focus:** every control has a visible focus ring (the base ring in `index.css`; don't add a second). A
|
||||
sticky or fixed layer never covers the focused element. A list item the keyboard lands on rings 2 px
|
||||
outside itself where it has a gap round it (a card); a table row, a log line or a row flush in a
|
||||
@@ -556,7 +567,8 @@ of a full-width panel and nothing on the right.
|
||||
row is not a card and keeps its one play button: started, that button continues, its "…" has Continue +
|
||||
"Play from the beginning", and its picture carries the cards' progress bar.
|
||||
- **The YouTube modal:** its chrome uses the `Button` rungs (44 on touch); Previous / Next live in the panel
|
||||
(its transport row, or the shut panel's strip) and on Shift+← / →, with no strips beside the card. Close is
|
||||
(its transport row: glyphs only — Previous, the count, Next, auto-advance, loop on one line, each named in
|
||||
its tooltip, the modes with their current one — or the shut panel's strip) and on Shift+← / →, with no strips beside the card. Close is
|
||||
an icon at the top right of the panel (wide: its head, or its strip) and at the end of the title row
|
||||
under the video (stacked). Wide, the panel shows the description outright, clamped to three
|
||||
lines with a More (`ClampedText`; a Tab onto a link below the cut opens it), and collapses to a 2.75rem
|
||||
@@ -564,6 +576,18 @@ of a full-width panel and nothing on the right.
|
||||
open. Stacked, the description opens from an ⓘ, because a hover popover never opens on a tap (measured
|
||||
live). The wheel: over the video it sets the volume; over a panel with something to scroll it scrolls
|
||||
only, never the volume, even at its end; over one with nothing to scroll it sets the volume. [WCAG 1.4.13]
|
||||
- **Related videos (owner's picks A, A, a, a):** on demand, never open by itself — the modal has no room to
|
||||
spare. Wide, a "Related" tab beside the description in the side panel; stacked, a button beside the ⓘ
|
||||
opens them in a drawer over the player. A row is the thumbnailed video row in its narrow form (a 6rem
|
||||
picture, the relative time only, the "…" its one control — every toggle is a row of that menu), with
|
||||
a check before the channel the user follows (named on hover). A click plays it in the same player
|
||||
(Back returns to the opened video), and the list stays the opened video's. Played, it is the item it
|
||||
now is (owner's pick D1 a): its title, its own watched / playlist / download controls, its progress
|
||||
kept, marked watched at its end — and its end does not step the queue. What the user watched or hid
|
||||
is never in it; a list read so far with nothing unseen says so above Show more. Over it, a two-way
|
||||
switch: on topic or trending (the Hungarian chart, labelled just "Trending"), kept on the account. Turned off on the instance (a daily
|
||||
limit of 0, owner's pick D2 a), there is no tab and no button; a refusal a retry cannot answer (the
|
||||
day's cap, turned off, the shared budget) offers no Retry.
|
||||
- **Clip mode (both players, owner's picks A + P1 + a):** a scissors in the control row (Plex: the C5 row,
|
||||
before the ⋯; YouTube: the actions beside Download, and the docked bar) or `C` opens a clip panel IN the
|
||||
player; `[` / `]` mark the start / end at the playhead and open it when shut. The video being watched is the
|
||||
@@ -795,3 +819,8 @@ of a full-width panel and nothing on the right.
|
||||
| 2026-10-17 | Text on glass (owner ★) | Light `--muted` 15% toward `--fg` in every scheme (≥ 6:1 on the bare page); the item count, the badges and the current Files row on opaque tints mixed into the surface | Only the two failing components; the item count's number in `--fg` | Pixel-measured over every scheme × mode × backdrop, the count fell to 3.8:1 (dark too: thumbnails scroll under the toolbar's glass) and Channels' tabs to 4.1:1; an `--fg` count outshouts the filters beside it |
|
||||
| 2026-10-18 | Scheduler run history (owner D4, E1, E2 ★) | A row's last three runs as dots, newest first (interrupted: a hollow warn ring, set apart from skipped and failed), and a history button that opens the job's runs on the Activity page; a user's ad-hoc runs in their own block under the jobs, with no interval and no run button | An inline expandable history per row; a dark-grey interrupted dot; ad-hoc runs only on the Activity page | Three dots answer "did it run, did it work" at a glance; the whole history needs filters, which the Activity page has |
|
||||
| 2026-10-18 | Activity page (owner D1, D2, G1–G3 ★) | One page, "Napló" / "Activity": four tabs (Runs, Admin actions, Server log, Quota) under one filter bar (text, a period of 1 h · 24 h · 7 d · 30 d · 90 d defaulting to 7 days, an account), the view in the URL; runs and admin actions as dense rows that open in place as a log line does, filtered and paged on the server; a run's or a request's log lines one pivot away, as a history entry | One merged timeline; a page per source; a default period per tab; card rows; the audit log's client-side table | Each source keeps its own table and retention, read in one place; one bar keeps what you narrowed across tabs; about 1.8k runs a day need a log's density and a server-side filter |
|
||||
| 2026-10-24 | Related videos (owner U1–U3 ★, D1 A, D3) | On demand: a tab beside the description (wide), a drawer (stacked); the narrow thumbnailed row, its menu alone, a followed check; plays in place and the list stays the opened video's; an on-topic / Hungarian-trending switch kept on the account | Always shown; the end-of-video grid alone; a dialog; a big card or a text row; a list that follows the playing video | The modal is full on a small screen; a picture is what a choice among strangers rests on; a list that stays put is tried one by one, and spends no more of the day's cap |
|
||||
| 2026-10-25 | Related: one played; off (owner D1 a, D2 a) | Played from the list, it is the player's item: its title, controls and progress, marked watched at its end, the queue left where it was; a daily limit of 0 takes the tab and the button away | A linked video's in-place play (no controls, nothing kept); a tab that only shows a refusal | What is watched should count as watched, wherever it was started from; a control that can only be refused is not offered |
|
||||
| 2026-10-25 | Player panel glyphs (owner 1A, 2A, 3) | In the side panel the queue row is glyph-only on one line, and Mark watched is a glyph toggle among the actions (✓ / ✓✓); the docked bar keeps its labels; the related switch at the default size, "Trending" | Labelled buttons wrapping onto three lines; glyphs on the docked bar too; Mark watched on its own line | The panel is narrow and the list controls are the same few every time; each glyph keeps its full name and shortcut in its tooltip; the docked bar has the width for words |
|
||||
| 2026-10-25 | Auto-advance glyphs (owner E A, H a) | Auto-advance wears list glyphs (`ListEnd` next and off, `ListStart` previous, `Shuffle` random), in the panel and the docked bar; the auto-advance and loop cycles are `lit`, not `pressed` | The skip arrows for the mode; an X'd list for off; `aria-pressed` on a cycle | Beside Previous / Next the skip arrows read as a second Next; a cycle of three or four modes is no two-state switch, and its name already says which |
|
||||
| 2026-10-25 | Restart and Reset glyphs (owner L A) | A menu's Play from the beginning wears `RotateCcw`, as the card's own Restart does; Reset (clear progress and status) wears `Eraser`; Redownload wears `RefreshCw`, the retry arrow | The skip arrow ⏮ on the menu's Restart; `RotateCcw` on both Restart and Reset; `TimerReset` for Restart | ⏮ is Previous beside the player; one action wore two glyphs, and two actions in one menu would have worn one |
|
||||
|
||||
+16
-2
@@ -45,7 +45,18 @@ A frontend page is one folder, `frontend/src/modules/<id>/` (the layering is in
|
||||
page renders into the floating header itself through `PageHeader`; the shell knows no page.
|
||||
2. `module.ts`: its `ModuleDef` (`lib/moduleDef.ts`): id, label keys, icon, an optional `gate`, the page as a
|
||||
`lazyWithPreload(() => import(…))`, and optionally a rail and a `Store`. Of its own folder it imports statically
|
||||
only its store (a `…Provider` / `…Store` file); the page and the rail load lazily.
|
||||
only its store (a `…Provider` / `…Store` file); the page and the rail load lazily. `urlKeys` names every
|
||||
address-bar key its view writes (the URL is the view: a bookmark reopens it), its list kept in `lib/` beside
|
||||
its codec; the shell clears them on a page switch and opens a page without another page's keys.
|
||||
Every setting the page shows — a tab, a sort, a filter, a search, the item open in it — goes there: a codec
|
||||
in `lib/<id>UrlState.ts` (read the params into the view, write the view as updates, a default left out —
|
||||
or always written, when an address naming none falls back to a view remembered elsewhere), written with
|
||||
`useUrlMirror` (a sub-view through `useHistorySubview`'s `url`, an overlay through `useBackToClose`'s),
|
||||
always as the codec's result: a writer outside `lib/` computes no key of its own. Read back first on mount
|
||||
(a link wins over anything remembered). A key that carries typed text — a search box's, a column filter
|
||||
map with a text filter — is also in `typedUrlKeys` (the client log keeps what was typed out). Add its round
|
||||
trip to `e2e/bookmark.spec.ts`, tagged with the page (`{ tag: "@<id>" }`). Only what an address cannot promise to
|
||||
reopen stays out, said in its codec (Home's draw, `lib/homeUrlState`).
|
||||
3. `index.ts`, the module's public face: the definition, and only what other folders must read (its store's
|
||||
hooks). Another folder reaches the module through this file or not at all.
|
||||
4. The id in `lib/urlState`'s `PAGES`, and the definition in `features/navigation/moduleRegistry.ts`, in
|
||||
@@ -58,7 +69,10 @@ A frontend page is one folder, `frontend/src/modules/<id>/` (the layering is in
|
||||
returns to `ui/FilterRail`; tsc names each table still missing the new id.
|
||||
|
||||
What holds it: `moduleRegistry.contract.test.ts` (every id defined once, from its own folder, lazily),
|
||||
`moduleStores.contract.test.tsx` (no store reads another module), the `local/layers` lint rule (imports only go
|
||||
`moduleStores.contract.test.tsx` (no store reads another module), `moduleUrl.contract.test.ts` (each URL key
|
||||
belongs to one module and matches what its codec writes; a writer outside `lib/` is handed a literal or a `lib/`
|
||||
function's result, never a key of its own; no key literal written or read from the live query undeclared; every key
|
||||
sorted as typed or not; every page with keys in a tagged bookmark round trip), the `local/layers` lint rule (imports only go
|
||||
down, a module only through its face) and `chunkGuard` in the build (no lazy page on the boot path), plus the
|
||||
i18n parity test.
|
||||
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
import { test, expect, type Browser, type Page } from "@playwright/test";
|
||||
import {
|
||||
clickVisibleChannelLink,
|
||||
expectContentType,
|
||||
gotoPage,
|
||||
openApp,
|
||||
openFirstVideo,
|
||||
toggleContentType,
|
||||
} from "./helpers";
|
||||
|
||||
// The address is the view: a view set through the UI, its address opened as a bookmark — in a NEW
|
||||
// browser context, so nothing this tab remembered (its history entries, sessionStorage, the view
|
||||
// storage it wrote) can stand in for what the address says. One round trip per page that names its
|
||||
// view, tagged with the page (moduleUrl.contract.test holds the tags to the module definitions),
|
||||
// plus the overlays the shell opens over any page (the channel page, the player) and the live
|
||||
// search. Not Plex: what it shows is the instance's own library, which a test stack may not have.
|
||||
|
||||
const STORAGE_STATE = "e2e/.auth/state.json";
|
||||
|
||||
/** The page's address, opened as a bookmark in a fresh context of the same account. */
|
||||
async function bookmarked(browser: Browser, page: Page, prepare?: (p: Page) => Promise<void>) {
|
||||
const url = page.url();
|
||||
const ctx = await browser.newContext({ storageState: STORAGE_STATE, locale: "en-US" });
|
||||
const fresh = await ctx.newPage();
|
||||
await prepare?.(fresh);
|
||||
await openApp(fresh, url);
|
||||
return fresh;
|
||||
}
|
||||
|
||||
const tab = (p: Page, name: string) => p.getByRole("tab", { name, exact: true });
|
||||
const column = (p: Page, name: string) =>
|
||||
p.getByRole("columnheader", { name: new RegExp(`^${name}`) });
|
||||
|
||||
async function gotoAdminPage(page: Page, id: string): Promise<void> {
|
||||
await page.getByTestId("nav-admin").click();
|
||||
await page.getByTestId(`nav-admin-${id}`).click();
|
||||
}
|
||||
|
||||
test.describe("a bookmark reopens the view it was taken of", () => {
|
||||
test("the feed's filters", { tag: "@feed" }, async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await toggleContentType(page, "includeLive");
|
||||
await expect(page).toHaveURL(/[?&]live=/);
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expectContentType(fresh, "includeLive", true);
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
test("Home's time budget", { tag: "@home" }, async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=home");
|
||||
await page.getByRole("button", { name: "An evening", exact: true }).click();
|
||||
await expect(page).toHaveURL(/[?&]hb=long/);
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(fresh.getByRole("button", { name: "An evening", exact: true })).toHaveAttribute(
|
||||
"aria-pressed",
|
||||
"true",
|
||||
);
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
test("a Settings tab", { tag: "@settings" }, async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await gotoPage(page, "settings");
|
||||
await tab(page, "Notifications").click();
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(tab(fresh, "Notifications")).toHaveAttribute("aria-selected", "true");
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
test("an admin page's tab", { tag: "@users" }, async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await gotoAdminPage(page, "users");
|
||||
await tab(page, "Access requests").click();
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(tab(fresh, "Access requests")).toHaveAttribute("aria-selected", "true");
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
test("a Configuration group", { tag: "@config" }, async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await gotoAdminPage(page, "config");
|
||||
const second = page.getByRole("tab").nth(1);
|
||||
const name = (await second.textContent()) ?? "";
|
||||
await second.click();
|
||||
await expect(page).toHaveURL(/[?&]cfgtab=/);
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(fresh.getByRole("tab", { name, exact: true })).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"true",
|
||||
);
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
test("the Activity tab and its time window", { tag: "@activity" }, async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await gotoAdminPage(page, "activity");
|
||||
await tab(page, "Server log").click();
|
||||
await page.getByRole("button", { name: "30 days", exact: true }).click();
|
||||
await expect(page).toHaveURL(/[?&]aw=30d/);
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(tab(fresh, "Server log")).toHaveAttribute("aria-selected", "true");
|
||||
await expect(fresh.getByRole("button", { name: "30 days", exact: true })).toHaveAttribute(
|
||||
"aria-pressed",
|
||||
"true",
|
||||
);
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
test("a playlist and its sort", { tag: "@playlists" }, async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await gotoPage(page, "playlists");
|
||||
await expect(column(page, "Title")).toBeVisible();
|
||||
await column(page, "Title").getByRole("button").first().click();
|
||||
await expect(page).toHaveURL(/[?&]plsort=/);
|
||||
const sorted = await column(page, "Title").getAttribute("aria-sort");
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(column(fresh, "Title")).toHaveAttribute("aria-sort", sorted ?? "");
|
||||
expect(new URL(fresh.url()).searchParams.get("pl")).toBe(
|
||||
new URL(page.url()).searchParams.get("pl"),
|
||||
);
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
test(
|
||||
"the Channels manager's tab and name search",
|
||||
{ tag: "@channels" },
|
||||
async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await gotoPage(page, "channels");
|
||||
await tab(page, "Hidden").click();
|
||||
await page.getByPlaceholder("Search channels…").fill("zz");
|
||||
await expect(page).toHaveURL(/zz/); // written once the typing settles
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(tab(fresh, "Hidden")).toHaveAttribute("aria-selected", "true");
|
||||
await expect(fresh.getByPlaceholder("Search channels…")).toHaveValue("zz");
|
||||
await fresh.context().close();
|
||||
},
|
||||
);
|
||||
|
||||
test("the Files search", { tag: "@files" }, async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await gotoPage(page, "files");
|
||||
await page.getByPlaceholder("Search files…").fill("zz");
|
||||
await expect(page).toHaveURL(/zz/);
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(fresh.getByPlaceholder("Search files…")).toHaveValue("zz");
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
// A file of the test's own, uploaded for it and deleted after, and the account's sort put back:
|
||||
// the account is left as it was found.
|
||||
test(
|
||||
"the Files sort, and the file open in the viewer",
|
||||
{ tag: "@files" },
|
||||
async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
const NAME = "bookmark-note";
|
||||
// One a run cut short left behind goes first.
|
||||
const left = (await (await page.request.get("/api/files")).json()) as Record<
|
||||
string,
|
||||
unknown
|
||||
>[];
|
||||
for (const f of left.filter((f) => JSON.stringify(f).includes(`"${NAME}`)))
|
||||
await page.request.delete(`/api/files/${String(f.id)}`);
|
||||
const up = await page.request.post("/api/files/upload", {
|
||||
headers: { "X-Upload-Filename": `${NAME}.txt` },
|
||||
data: Buffer.from("a note the bookmark reopens\n"),
|
||||
});
|
||||
expect(up.ok(), await up.text()).toBeTruthy();
|
||||
const { id } = (await up.json()) as { id: number };
|
||||
// The account's own sort, put back after: a header press cycles it (asc, desc, none), so the
|
||||
// case starts from none, as the address names it, whatever an earlier run left.
|
||||
const me = (await (await page.request.get("/api/me")).json()) as {
|
||||
preferences?: Record<string, unknown>;
|
||||
};
|
||||
const ownSort = me.preferences?.filesSort ?? null;
|
||||
try {
|
||||
await openApp(page, "/?page=files&fsort=none");
|
||||
await column(page, "Name").getByRole("button").first().click();
|
||||
await expect(page).toHaveURL(/[?&]fsort=name/);
|
||||
const sorted = await column(page, "Name").getAttribute("aria-sort");
|
||||
await page.getByText(NAME, { exact: true }).first().click();
|
||||
await expect(page).toHaveURL(new RegExp(`[?&]fview=${id}`));
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(fresh.getByRole("dialog", { name: NAME })).toBeVisible();
|
||||
await fresh.keyboard.press("Escape");
|
||||
await expect(column(fresh, "Name")).toHaveAttribute("aria-sort", sorted ?? "");
|
||||
await fresh.context().close();
|
||||
} finally {
|
||||
await page.request.delete(`/api/files/${id}`);
|
||||
await page.request.put("/api/me/preferences", { data: { filesSort: ownSort } });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("a channel page's own tab, over the page it was opened from", async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await expect(page.getByTestId("video-card").first()).toBeVisible();
|
||||
expect(await clickVisibleChannelLink(page)).toBe(true);
|
||||
const title = await page.getByTestId("channel-title").textContent();
|
||||
await tab(page, "About").click();
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(fresh.getByTestId("channel-title")).toHaveText(title ?? "");
|
||||
await expect(tab(fresh, "About")).toHaveAttribute("aria-selected", "true");
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
test("the player and the video it plays", async ({ page, browser }) => {
|
||||
await openApp(page, "/?page=feed");
|
||||
await openFirstVideo(page);
|
||||
await expect(page).toHaveURL(/[?&]watch=/);
|
||||
const watch = new URL(page.url()).searchParams.get("watch");
|
||||
const fresh = await bookmarked(browser, page);
|
||||
await expect(fresh.getByTestId("player-modal")).toBeVisible();
|
||||
expect(new URL(fresh.url()).searchParams.get("watch")).toBe(watch);
|
||||
await fresh.context().close();
|
||||
});
|
||||
|
||||
// The search itself never reaches YouTube here: the answer is the server's shape, served by the
|
||||
// test, and the request it answers is what the address named. The instance's search settings are
|
||||
// pinned too (the free source, switched on): a stack left on the API source reopens the search
|
||||
// waiting for its press, by design, and one with search off offers none.
|
||||
test(
|
||||
"a live YouTube search, its term and its count",
|
||||
{ tag: "@feed" },
|
||||
async ({ page, browser }) => {
|
||||
const answer = async (p: Page, seen: string[]) => {
|
||||
await p.route("**/api/me", async (route) => {
|
||||
const me = (await (await route.fetch()).json()) as Record<string, unknown>;
|
||||
return route.fulfill({ json: { ...me, search_source: "scrape", search_enabled: true } });
|
||||
});
|
||||
await p.route("**/api/search/youtube?**", (route) => {
|
||||
seen.push(route.request().url());
|
||||
return route.fulfill({ json: { items: [], next_cursor: null, source: "scrape" } });
|
||||
});
|
||||
};
|
||||
await answer(page, []);
|
||||
await openApp(page, "/?page=feed");
|
||||
await page.getByPlaceholder("Search your subscriptions…").fill("lofi");
|
||||
await page.getByRole("button", { name: "Search YouTube", exact: true }).click();
|
||||
await expect(page.getByText("YouTube results for “lofi”")).toBeVisible();
|
||||
await expect(page).toHaveURL(/[?&]yt=lofi/); // named as it opens, not only once the count is set
|
||||
await page.getByRole("button", { name: "40", exact: true }).click();
|
||||
await expect(page).toHaveURL(/[?&]ytn=40/);
|
||||
|
||||
const seen: string[] = [];
|
||||
const fresh = await bookmarked(browser, page, (p) => answer(p, seen));
|
||||
await expect(fresh.getByText("YouTube results for “lofi”")).toBeVisible();
|
||||
await expect(fresh.getByRole("button", { name: "40", exact: true })).toHaveAttribute(
|
||||
"aria-pressed",
|
||||
"true",
|
||||
);
|
||||
await expect.poll(() => seen.length).toBeGreaterThan(0);
|
||||
const asked = new URL(seen[0]!).searchParams;
|
||||
expect([asked.get("q"), asked.get("limit")]).toEqual(["lofi", "40"]);
|
||||
await fresh.context().close();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -898,7 +898,8 @@ export default tseslint.config(
|
||||
plugins: { playwright },
|
||||
rules: {
|
||||
"playwright/no-focused-test": "error",
|
||||
"playwright/no-skipped-test": "error",
|
||||
// fixme too: a test Playwright never runs, which the bookmark net would still count.
|
||||
"playwright/no-skipped-test": ["error", { disallowFixme: true }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -34,6 +34,7 @@ import AddToPlaylist, { AddToPlaylistAt } from "./features/video/AddToPlaylist";
|
||||
import PlexPlaylistAdd from "./features/plexCards/PlexPlaylistAdd";
|
||||
import TagManager from "./features/channel/TagManager";
|
||||
import { api, HttpError, type PlexCard } from "./lib/api";
|
||||
import { qk } from "./lib/queryKeys";
|
||||
|
||||
beforeAll(() => {
|
||||
class Stub {
|
||||
@@ -157,6 +158,52 @@ describe("the add-to-playlist popover", () => {
|
||||
await waitFor(() => expect(lists.mock.calls.length).toBeGreaterThan(1));
|
||||
});
|
||||
|
||||
// The built-in Watch later list's items ARE the bookmark: ticked here, the video is saved wherever
|
||||
// it is shown (a related list, a live search), and a user list's tick marks nothing.
|
||||
it("marks the video saved when Watch later is ticked, and unsaved when it is unticked", async () => {
|
||||
// The server's side: the lists the video is on, so the refetch after a write agrees with it.
|
||||
const on = new Set<number>();
|
||||
vi.spyOn(api, "playlists").mockImplementation(
|
||||
async () =>
|
||||
[
|
||||
{ id: 9, name: "Watch later", kind: "watch_later", has_video: on.has(9) },
|
||||
{ id: 3, name: "Mix", kind: "user", has_video: on.has(3) },
|
||||
] as never,
|
||||
);
|
||||
vi.spyOn(api, "addToPlaylist").mockImplementation(async (id: number) => {
|
||||
on.add(id);
|
||||
return {} as never;
|
||||
});
|
||||
vi.spyOn(api, "removeFromPlaylist").mockImplementation(async (id: number) => {
|
||||
on.delete(id);
|
||||
return {} as never;
|
||||
});
|
||||
const qc = client();
|
||||
const saved = () =>
|
||||
qc.getQueryData<Record<string, { saved?: { value: boolean } }>>(qk.videoMarks())?.v1?.saved
|
||||
?.value;
|
||||
render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<AddToPlaylist videoId="v1" />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
fireEvent.click(screen.getByLabelText("playlists.addToPlaylist"));
|
||||
const row = async (name: string) =>
|
||||
(await screen.findAllByRole("menuitemcheckbox", { hidden: true })).find((r) =>
|
||||
r.textContent?.includes(name),
|
||||
)!;
|
||||
fireEvent.click(await row("Mix"));
|
||||
await waitFor(() => expect(api.addToPlaylist).toHaveBeenCalledTimes(1));
|
||||
expect(saved()).toBeUndefined();
|
||||
fireEvent.click(await row("playlists.watchLater"));
|
||||
await waitFor(() => expect(saved()).toBe(true));
|
||||
await waitFor(async () =>
|
||||
expect((await row("playlists.watchLater")).getAttribute("aria-checked")).toBe("true"),
|
||||
);
|
||||
fireEvent.click(await row("playlists.watchLater"));
|
||||
await waitFor(() => expect(saved()).toBe(false));
|
||||
});
|
||||
|
||||
it("says a failed load of the playlists as one, not as 'no playlists yet'", async () => {
|
||||
vi.spyOn(api, "playlists").mockRejectedValue(new Error("down"));
|
||||
render(
|
||||
|
||||
@@ -52,6 +52,18 @@ describe("Button primitive", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("a lit cycle paints the pressed look without announcing a toggle", () => {
|
||||
render(
|
||||
<Button variant="overlay" lit>
|
||||
Loop: All
|
||||
</Button>,
|
||||
);
|
||||
const btn = screen.getByRole("button", { name: "Loop: All" });
|
||||
expect(btn.hasAttribute("aria-pressed")).toBe(false);
|
||||
expect(btn.hasAttribute("data-lit")).toBe(true);
|
||||
expect(btn.className).toContain("data-lit:bg-accent");
|
||||
});
|
||||
|
||||
it("a toggle announces aria-pressed and paints the pressed state", () => {
|
||||
const { rerender } = render(
|
||||
<Button variant="outline" pressed={false}>
|
||||
|
||||
@@ -30,6 +30,9 @@ interface ButtonOwnProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "
|
||||
loading?: boolean;
|
||||
/** A toggle: sets aria-pressed and paints the pressed state (the solid accent). */
|
||||
pressed?: boolean;
|
||||
/** A mode cycle that is not off: the pressed look without aria-pressed — its name says the mode (a
|
||||
* cycle is no two-state switch). */
|
||||
lit?: boolean;
|
||||
/** Not accepted: a toggle is `pressed` (JSX lets any undeclared `aria-*` through, so it is `never`). */
|
||||
"aria-pressed"?: never;
|
||||
/** Sits on a picture (a thumbnail, a poster) or inside a pill field: the pill shape. Implied by the
|
||||
@@ -55,6 +58,7 @@ const ButtonImpl = forwardRef<HTMLButtonElement, ButtonOwnProps>(function Button
|
||||
label,
|
||||
loading = false,
|
||||
pressed,
|
||||
lit,
|
||||
round = false,
|
||||
fullWidth = false,
|
||||
className,
|
||||
@@ -84,9 +88,10 @@ const ButtonImpl = forwardRef<HTMLButtonElement, ButtonOwnProps>(function Button
|
||||
onBlur={onBlur}
|
||||
aria-label={label}
|
||||
aria-pressed={pressed}
|
||||
data-lit={lit || undefined}
|
||||
title={label}
|
||||
className={clsx(
|
||||
buttonClass({ variant, size: resolvedSize, round, fullWidth, pressed }),
|
||||
buttonClass({ variant, size: resolvedSize, round, fullWidth, pressed, lit }),
|
||||
className,
|
||||
)}
|
||||
{...rest}
|
||||
|
||||
@@ -59,6 +59,25 @@ describe("IconButton", () => {
|
||||
expect(screen.getByRole("button", { name: "Saved" }).getAttribute("aria-pressed")).toBe("true");
|
||||
});
|
||||
|
||||
// A mode cycle (auto-advance, loop) is no two-state switch: it looks on, its name says the mode.
|
||||
it("a lit cycle tints its glyph without announcing a toggle", () => {
|
||||
const { rerender } = render(
|
||||
<IconButton label="Auto: Next" lit>
|
||||
<svg />
|
||||
</IconButton>,
|
||||
);
|
||||
const btn = screen.getByRole("button", { name: "Auto: Next" });
|
||||
expect(btn.hasAttribute("aria-pressed")).toBe(false);
|
||||
expect(btn.hasAttribute("data-lit")).toBe(true);
|
||||
expect(btn.className).toContain("data-lit:text-chosen");
|
||||
rerender(
|
||||
<IconButton label="Auto: Off" lit={false}>
|
||||
<svg />
|
||||
</IconButton>,
|
||||
);
|
||||
expect(btn.hasAttribute("data-lit")).toBe(false);
|
||||
});
|
||||
|
||||
it("loading swaps the glyph for a spinner and swallows the click", () => {
|
||||
const onClick = vi.fn();
|
||||
render(
|
||||
|
||||
@@ -23,6 +23,9 @@ export interface IconButtonProps
|
||||
/** A toggle: sets aria-pressed and tints the glyph with the chosen colour (the accent; the media
|
||||
* amber on the player chrome). */
|
||||
pressed?: boolean;
|
||||
/** A mode cycle that is not off: the pressed tint without aria-pressed — its `label` says the mode
|
||||
* (a cycle is no two-state switch). */
|
||||
lit?: boolean;
|
||||
/** Not accepted: a toggle is `pressed` (JSX lets any undeclared `aria-*` through, so it is `never`). */
|
||||
"aria-pressed"?: never;
|
||||
/** Sits on a picture or inside a pill field: round (A2). Implied by the `media` variant. */
|
||||
@@ -40,6 +43,7 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
|
||||
variant = "ghost",
|
||||
size = "sm",
|
||||
pressed,
|
||||
lit,
|
||||
round = false,
|
||||
loading = false,
|
||||
noTitle = false,
|
||||
@@ -56,8 +60,9 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
|
||||
busy={loading}
|
||||
aria-label={label}
|
||||
aria-pressed={pressed}
|
||||
data-lit={lit || undefined}
|
||||
title={noTitle ? undefined : label}
|
||||
className={clsx(iconButtonClass({ variant, size, round, pressed }), className)}
|
||||
className={clsx(iconButtonClass({ variant, size, round, pressed, lit }), className)}
|
||||
{...rest}
|
||||
>
|
||||
{loading ? <Loader2 className="animate-spin" /> : children}
|
||||
|
||||
@@ -9,6 +9,7 @@ import KeyboardHelp from "./KeyboardHelp";
|
||||
import { useContextMenu } from "./useContextMenu";
|
||||
import {
|
||||
closeKeyboardHelp,
|
||||
setScopeCoveredProbe,
|
||||
useGlobalKeymap,
|
||||
useHelpConditions,
|
||||
useKeyScope,
|
||||
@@ -16,7 +17,8 @@ import {
|
||||
} from "../../lib/keymap";
|
||||
import { pushLayer, removeLayer } from "../../lib/layerStack";
|
||||
import { useMediaKeys } from "../../lib/mediaKeys";
|
||||
import { useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { navItemAttrs, useListNav } from "../../lib/listNav";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-i18next")>();
|
||||
@@ -144,6 +146,67 @@ describe("KeyboardHelp", () => {
|
||||
expect(descriptions()).toContain("keys.help");
|
||||
});
|
||||
|
||||
// The player's related videos are a list inside the layer: their keys work there (`inTopLayer`), so
|
||||
// the sheet opened over the player lists them — and over a layer with no list, still does not.
|
||||
it("lists the list and menu keys over a layer that holds a list of its own", () => {
|
||||
function LayerList() {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useListNav(ref, { enabled: true });
|
||||
useContextMenu<string>();
|
||||
return (
|
||||
<div data-testid="layer">
|
||||
<div ref={ref}>
|
||||
<div {...navItemAttrs(0)}>row</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
render(
|
||||
<Host>
|
||||
<LayerList />
|
||||
</Host>,
|
||||
);
|
||||
const withList = pushLayer({ root: () => screen.getByTestId("layer") });
|
||||
pressH();
|
||||
expect(descriptions()).toContain("keys.listStep");
|
||||
expect(descriptions()).toContain("keys.contextMenu");
|
||||
act(() => closeKeyboardHelp());
|
||||
removeLayer(withList);
|
||||
|
||||
const bare = pushLayer();
|
||||
pressH();
|
||||
removeLayer(bare);
|
||||
expect(descriptions()).not.toContain("keys.listStep");
|
||||
expect(descriptions()).not.toContain("keys.contextMenu");
|
||||
});
|
||||
|
||||
// The YouTube player's keys wait while a layer sits above it (its related drawer, a dialog): a
|
||||
// sheet opened there leaves them out, and one opened over the player itself lists them.
|
||||
it("leaves out a surface's keys while a layer above it has them waiting", () => {
|
||||
let covered = true;
|
||||
setScopeCoveredProbe("ytPlayer", () => covered);
|
||||
try {
|
||||
render(
|
||||
<Host>
|
||||
<Surface scope="ytPlayer" />
|
||||
</Host>,
|
||||
);
|
||||
const id = pushLayer();
|
||||
pressH();
|
||||
removeLayer(id);
|
||||
expect(descriptions()).not.toContain("keys.playPause");
|
||||
expect(descriptions()).toContain("keys.help");
|
||||
act(() => closeKeyboardHelp());
|
||||
covered = false;
|
||||
pressH();
|
||||
expect(descriptions()).toContain("keys.playPause");
|
||||
} catch (e) {
|
||||
setScopeCoveredProbe("ytPlayer", null);
|
||||
throw e;
|
||||
}
|
||||
setScopeCoveredProbe("ytPlayer", null);
|
||||
});
|
||||
|
||||
// Two live context menus (the Playlists page mounts one, its rail another) must not double the row.
|
||||
it("lists the context-menu chords once however many surfaces register", () => {
|
||||
function WithMenu() {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
useHelpConditionValues,
|
||||
useKeyboardHelpOpen,
|
||||
useKeyboardHelpOverLayer,
|
||||
useKeyboardHelpCovered,
|
||||
useNavigablePages,
|
||||
} from "../../lib/keymap";
|
||||
|
||||
@@ -33,6 +34,7 @@ export default function KeyboardHelp() {
|
||||
const scopes = useActiveScopes();
|
||||
const conditions = useHelpConditionValues();
|
||||
const overLayer = useKeyboardHelpOverLayer();
|
||||
const covered = useKeyboardHelpCovered();
|
||||
const pages = useNavigablePages();
|
||||
|
||||
if (!open) return null;
|
||||
@@ -41,11 +43,16 @@ export default function KeyboardHelp() {
|
||||
// Opened over a player or a dialog, the page-level keys (`s`, `g …`, `j`/`k`) are quiet — listing
|
||||
// them there would promise keys that do nothing until the overlay closes. And a `g` chord is listed
|
||||
// only for a module this account can actually reach.
|
||||
// The context-menu key goes too: every `useContextMenu` is a page list, and with an overlay up the
|
||||
// focus Shift+F10 needs is inside the overlay (found in UAT).
|
||||
const live = overLayer
|
||||
? scopes.filter((s) => !isPageLevelScope(s) && s !== "contextMenu")
|
||||
: scopes;
|
||||
// The context-menu key goes too, with the page's lists. Over a layer that holds a list of its own
|
||||
// (the player's related videos) the list keys and the menu key work on THAT list, so they stay —
|
||||
// but not Delete: no list inside a layer takes it, and a page's remover behind does not reach.
|
||||
const inLayer = (s: (typeof scopes)[number]) =>
|
||||
(!isPageLevelScope(s) && s !== "contextMenu") ||
|
||||
(overLayer === "layerWithList" && (s === "list" || s === "contextMenu"));
|
||||
// A surface under a layer of its own (the player under its related drawer) waits: not listed.
|
||||
const live = (overLayer === "page" ? scopes : scopes.filter(inLayer)).filter(
|
||||
(s) => !covered.has(s),
|
||||
);
|
||||
const lines = helpLines(live, pages).filter((l) => !l.when || !!conditions[l.when]);
|
||||
const words = { Space: t("keys.cap.space"), ContextMenu: t("keys.cap.menu") };
|
||||
return (
|
||||
|
||||
@@ -65,6 +65,7 @@ export default function Modal({
|
||||
placement = "center",
|
||||
initialFocus,
|
||||
headerActions,
|
||||
url,
|
||||
}: {
|
||||
title: ReactNode;
|
||||
initialFocus: ModalFocus;
|
||||
@@ -81,10 +82,14 @@ export default function Modal({
|
||||
placement?: "center" | "drawer" | "drawer-start" | "top";
|
||||
/** Controls beside the ✕ in the header (a side panel's pin and customize, C2). */
|
||||
headerActions?: ReactNode;
|
||||
/** What the dialog names in the address while it is open, when it is part of the view (a viewer, a
|
||||
* player): written into its own history entry, so a reload or a bookmark reopens it and Back lands
|
||||
* on the address without it (lib/history). */
|
||||
url?: Record<string, string | null>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// Browser/mouse Back closes the topmost modal instead of navigating away.
|
||||
useBackToClose(onClose);
|
||||
useBackToClose(onClose, url);
|
||||
// ONE container element for the dialog's whole life, re-parented between <body> and the fullscreen
|
||||
// element — and attached before the children commit, so an `autoFocus` child
|
||||
// still gets the focus. Both rules live in the hook; `ui/AnchoredPopover` shares it.
|
||||
@@ -147,7 +152,7 @@ export default function Modal({
|
||||
// An effect event, so a new handler each render never re-registers: the stack id is assigned once per mount.
|
||||
const close = useEffectEvent(onClose);
|
||||
useEffect(() => {
|
||||
const id = pushLayer();
|
||||
const id = pushLayer({ root: () => rootRef.current });
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (takeEscape(e, id)) {
|
||||
e.stopPropagation();
|
||||
|
||||
@@ -10,8 +10,9 @@ import { MEDIA_CHOSEN } from "./mediaChrome";
|
||||
// Below it a side rail leaves a phone too little width for the content beside it (measured at 390 px:
|
||||
// the rail clipped its own labels and Settings → Account pushed its buttons over their text), so there
|
||||
// it is a horizontal row that scrolls. A page whose sub-tab is worth keeping persists it with
|
||||
// lib/storage's useTabPersistedState (per browser tab: Admin Users, Config, Settings, Stats):
|
||||
// a reload keeps the user where they were, and a fresh tab opens on the first sub-tab. Not every
|
||||
// lib/storage's useTabPersistedState (per browser tab: Admin Users, Config, Settings) and names it in
|
||||
// the address: a reload keeps the user where they were, a link opens its tab, and a fresh tab opens on
|
||||
// the first sub-tab. Not every
|
||||
// caller: the channel manager's view is account-wide (ChannelsProvider), and Downloads, a channel page
|
||||
// and the player settings start on their first tab each time.
|
||||
//
|
||||
|
||||
@@ -57,9 +57,16 @@ const BUTTON_VARIANTS: Record<ButtonVariant, string> = {
|
||||
};
|
||||
|
||||
// A pressed toggle (`pressed`) is the solid accent in every variant (B3: "selected stays the solid
|
||||
// accent"); the layer utilities leave it alone, so it stays solid under the pointer too.
|
||||
// accent"); the layer utilities leave it alone, and its colours are marked important (`!`) because a
|
||||
// variant's hover colour (`act:hover:text-fg`, the overlay's `act:hover:bg-white/15`) is the more
|
||||
// specific selector — without it the accent turned grey, or white, under the pointer.
|
||||
const PRESSED =
|
||||
"aria-pressed:bg-accent aria-pressed:text-accent-fg aria-pressed:border-accent aria-pressed:no-underline";
|
||||
"aria-pressed:bg-accent! aria-pressed:text-accent-fg! aria-pressed:border-accent! aria-pressed:no-underline!";
|
||||
// A mode cycle that is not off (`lit`: auto-advance Next, loop One) looks pressed but is no toggle —
|
||||
// its name says the mode, and aria-pressed would announce a two-state switch whose name changes on
|
||||
// every press. The same look as PRESSED, under the pointer too: the layers stand down on `[data-lit]`.
|
||||
const LIT =
|
||||
"data-lit:bg-accent! data-lit:text-accent-fg! data-lit:border-accent! data-lit:no-underline!";
|
||||
|
||||
// B1, the whole ladder: explicit heights, so a toolbar's `sm` button, search pill, dropdown trigger and
|
||||
// small icon button all line up at 28. A call site picks a rung; it does not invent one. rem-derived, so
|
||||
@@ -120,8 +127,10 @@ const ICON_VARIANTS: Record<IconButtonVariant, string> = {
|
||||
};
|
||||
|
||||
// An icon toggle that is on shows it in the glyph (watched, saved, a selected track), not as a solid
|
||||
// fill: a solid accent square in a row of quiet glyphs outshouts the row's primary action.
|
||||
const ICON_PRESSED = "aria-pressed:text-chosen";
|
||||
// fill: a solid accent square in a row of quiet glyphs outshouts the row's primary action. Important
|
||||
// for the same reason as PRESSED: the variant's hover colour would take the tint off under the pointer.
|
||||
const ICON_PRESSED = "aria-pressed:text-chosen!";
|
||||
const ICON_LIT = "data-lit:text-chosen!";
|
||||
|
||||
const ICON_SIZES: Record<IconButtonSize, string> = {
|
||||
sm: "size-7 [&>svg]:size-4",
|
||||
@@ -138,17 +147,20 @@ export function buttonClass({
|
||||
round = false,
|
||||
fullWidth = false,
|
||||
pressed,
|
||||
lit,
|
||||
}: {
|
||||
variant: ButtonVariant;
|
||||
size: ButtonSize;
|
||||
round?: boolean;
|
||||
fullWidth?: boolean;
|
||||
pressed?: boolean;
|
||||
lit?: boolean;
|
||||
}) {
|
||||
return clsx(
|
||||
BASE,
|
||||
BUTTON_VARIANTS[variant],
|
||||
pressed !== undefined && PRESSED,
|
||||
lit !== undefined && LIT,
|
||||
SIZES[size],
|
||||
size !== "none" && (round || variant === "media" ? "rounded-full" : "rounded-lg"),
|
||||
// The coarse-pointer target (DESIGN.md A3) lives HERE, not in the call sites — on every variant.
|
||||
@@ -165,17 +177,20 @@ export function iconButtonClass({
|
||||
size,
|
||||
round = false,
|
||||
pressed,
|
||||
lit,
|
||||
}: {
|
||||
variant: IconButtonVariant;
|
||||
size: IconButtonSize;
|
||||
round?: boolean;
|
||||
pressed?: boolean;
|
||||
lit?: boolean;
|
||||
}) {
|
||||
return clsx(
|
||||
"inline-grid shrink-0 place-items-center transition touch-target aria-expanded:text-chosen disabled:opacity-50 disabled:cursor-not-allowed aria-disabled:opacity-50 aria-disabled:cursor-not-allowed",
|
||||
ICON_VARIANTS[variant],
|
||||
round || variant === "media" ? "rounded-full" : "rounded-lg",
|
||||
pressed !== undefined && ICON_PRESSED,
|
||||
lit !== undefined && ICON_LIT,
|
||||
ICON_SIZES[size],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -56,6 +56,7 @@ const PLAIN: Record<string, [number, string]> = {
|
||||
"modules/files/VideoEditor.tsx": [2, "timeline glyphs"],
|
||||
"shell/Welcome.tsx": [1, "a screenshot (zoom)"],
|
||||
"modules/playlists/playlistColumns.tsx": [1, "the thumbnail"],
|
||||
"modules/channels/WatchedVideosDialog.tsx": [1, "the thumbnail (its title sits beside it)"],
|
||||
"modules/plex/plexDetailUi.tsx": [2, "a switch row and the poster"],
|
||||
"modules/plex/plexViews.tsx": [1, "the rating filter (a number)"],
|
||||
"components/ui/ActionMenu.tsx": [1, "a menu row"],
|
||||
|
||||
@@ -1,4 +1,49 @@
|
||||
[
|
||||
{
|
||||
"version": "0.113.0",
|
||||
"date": "2026-10-28",
|
||||
"new": [
|
||||
"The address names what you see: tabs, list views, sorts and searches (the live YouTube search too), the YouTube player and the file viewer. A reload, a bookmark or a shared link opens the same view.",
|
||||
"A link to a video reopens the player over its page once; Back closes it. A video the page no longer lists plays on its own and says so."
|
||||
],
|
||||
"fixed": [
|
||||
"Back and Forward step through the views as you saw them, across dialogs, players and reloads: a reload under an open player no longer leaves a Back step that does nothing.",
|
||||
"Signed out on a Plex page, the sign-in card could show a button with no text.",
|
||||
"The channel page's address names the channel and its own view, not the page under it.",
|
||||
"A reload during a Plex binge reopens the episode playing now, not the one it started from."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.112.1",
|
||||
"date": "2026-10-27",
|
||||
"new": [],
|
||||
"fixed": ["Security: the sign-in library is updated, closing two published vulnerabilities."]
|
||||
},
|
||||
{
|
||||
"version": "0.112.0",
|
||||
"date": "2026-10-25",
|
||||
"new": [
|
||||
"Player: a Related tab lists videos related to the one playing, leaving out what you have already watched (your uploaded YouTube history included). Channels you follow are marked, and you can switch between On topic and Trending.",
|
||||
"Play a related video in place; Back returns to the one you opened. Admins set a daily per-user limit in Config › Quota (default 200, 0 turns it off).",
|
||||
"Side panel: the list controls and the watched toggle are glyphs on one line, and Auto and Loop show when they are on, also under the pointer."
|
||||
],
|
||||
"fixed": [
|
||||
"Live search: a search that never reached YouTube no longer uses up a daily slot, a busy moment says so after a few seconds instead of waiting on, and a first page that failed offers Retry.",
|
||||
"Menus: Play from the beginning wears the same ↺ glyph everywhere, and Reset its own eraser glyph.",
|
||||
"On the day of this update, API searches made earlier that day stop counting toward the daily search limit, until Pacific midnight."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.111.0",
|
||||
"date": "2026-10-24",
|
||||
"new": [
|
||||
"Channels › Discover from your history: the channels your uploaded YouTube history shows you watching often (five videos of five minutes or more) but not following.",
|
||||
"Follow one, put it out of the list (with Undo), or open the videos you watched there and play them one by one or all in a row."
|
||||
],
|
||||
"fixed": [
|
||||
"A channel someone explored and then followed on YouTube is now part of the shared Library like any followed channel, and so are its videos; before, they could stay hidden and their watched marks never applied."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.110.0",
|
||||
"date": "2026-10-23",
|
||||
|
||||
@@ -1,4 +1,51 @@
|
||||
[
|
||||
{
|
||||
"version": "0.113.0",
|
||||
"date": "2026-10-28",
|
||||
"new": [
|
||||
"A cím megnevezi, amit látsz: a füleket, a listanézeteket, a rendezést és a kereséseket (az élő YouTube-keresést is), a YouTube-lejátszót és a fájlnézőt. Újratöltés, könyvjelző vagy megosztott link ugyanazt a nézetet nyitja meg.",
|
||||
"Egy videóra mutató link egyszer újranyitja a lejátszót az oldala fölött, a Vissza bezárja. Ha az oldal már nem listázza a videót, a lejátszó csak azt az egyet játssza le, és ezt jelzi is."
|
||||
],
|
||||
"fixed": [
|
||||
"A Vissza és az Előre úgy lép végig a nézeteken, ahogy láttad őket, párbeszédablakokon, lejátszókon és újratöltésen át: nyitott lejátszó alatti újratöltés után nem marad semmit sem csináló Vissza-lépés.",
|
||||
"Plex-oldalon kijelentkezve a bejelentkező kártyán felirat nélküli gomb jelenhetett meg.",
|
||||
"A csatornaoldal címe a csatornát és annak saját nézetét nevezi meg, nem az alatta lévő oldalt.",
|
||||
"Plexben sorozatnézés közben az újratöltés az épp futó epizódot nyitja meg, nem azt, amelyikkel kezdted."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.112.1",
|
||||
"date": "2026-10-27",
|
||||
"new": [],
|
||||
"fixed": [
|
||||
"Biztonság: frissült a bejelentkezési könyvtár, ami két nyilvánosan ismert sérülékenységet zár be."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.112.0",
|
||||
"date": "2026-10-25",
|
||||
"new": [
|
||||
"Lejátszó: a Kapcsolódók fül a lejátszott videóhoz kapcsolódó videókat mutatja, a már megnézettek nélkül (a feltöltött YouTube-előzményeiddel együtt). A követett csatornák jelölve vannak, és válthatsz a Témába vágó és a Trend között.",
|
||||
"A kapcsolódó videó helyben játszható, a Vissza a megnyitott videóhoz visz. Az adminok a Konfig › Kvóta alatt adhatnak napi felhasználónkénti limitet (alapból 200, a 0 kikapcsolja).",
|
||||
"Oldalpanel: a listavezérlők és a megnézve-kapcsoló glifként egy sorban vannak, az Auto és a Loop bekapcsolt állapota az egérmutató alatt is látszik."
|
||||
],
|
||||
"fixed": [
|
||||
"Élő keresés: a YouTube-ig el sem jutott keresés már nem fogyaszt napi keretet, túlterheléskor pár másodperc után üzenet jön a végtelen várakozás helyett, a hibás első oldal pedig Újra gombot ad.",
|
||||
"Menük: a Lejátszás az elejétől mindenhol ugyanazt a ↺ glifet kapta, az Alaphelyzet saját radír glifet.",
|
||||
"A frissítés napján az aznap korábban indított API-s keresések nem számítanak bele a napi keresési limitbe, a csendes-óceáni éjfélig."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.111.0",
|
||||
"date": "2026-10-24",
|
||||
"new": [
|
||||
"Csatornák › Felfedezés az előzményekből: azok a csatornák, amelyeket a feltöltött YouTube-előzményeid szerint sokat nézel (öt legalább ötperces videó), de nem követsz.",
|
||||
"Követheted, kiveheted a listából (visszavonható), vagy megnyithatod az ott megnézett videóit, és egyenként vagy sorban lejátszhatod őket."
|
||||
],
|
||||
"fixed": [
|
||||
"Ha egy felfedezett csatornát valaki a YouTube-on kezd követni, az most a többi követett csatornához hasonlóan a közös Könyvtár része lesz a videóival együtt; eddig rejtve maradhattak, és a megnézett jelöléseik sem érvényesültek."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.110.0",
|
||||
"date": "2026-10-23",
|
||||
|
||||
@@ -27,6 +27,8 @@ vi.mock("react-i18next", async (importOriginal) => {
|
||||
|
||||
import { NavigationProvider } from "./NavigationProvider";
|
||||
import { useNavigation, useNavigationActions } from "./navigationContext";
|
||||
import { urlPage } from "./urlPage";
|
||||
import { channelUrl } from "../../lib/urlState";
|
||||
import { useBackToClose } from "../../lib/history";
|
||||
import { PageHeading } from "../../components/ui/Headings";
|
||||
|
||||
@@ -167,6 +169,19 @@ describe("NavigationProvider · setPage's same-page guard", () => {
|
||||
expect(window.location.search).toBe("?page=plex&keep=1");
|
||||
});
|
||||
|
||||
it("leaves the keys of the modules it does not list by hand behind too: Files and the feed's", () => {
|
||||
// Each module declares its keys (`urlKeys`), and the switch clears the union of them: a key
|
||||
// missing from a hand-kept list rode along onto the next page's entry.
|
||||
window.history.replaceState(
|
||||
{ sfPage: "files" },
|
||||
"",
|
||||
"/?page=files&folder=all&item=5&q=music&sort=oldest&keep=1",
|
||||
);
|
||||
const { result } = render();
|
||||
act(() => result.current.setPage("plex"));
|
||||
expect(window.location.search).toBe("?page=plex&keep=1");
|
||||
});
|
||||
|
||||
it("pushes nothing when it is already that page", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.setPage("plex"));
|
||||
@@ -195,6 +210,93 @@ describe("NavigationProvider · setPage's same-page guard", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("NavigationProvider · a link carrying another page's keys", () => {
|
||||
it("opens with only its own page's keys: what the page does not show, its address does not say", () => {
|
||||
window.history.replaceState(
|
||||
{},
|
||||
"",
|
||||
"/?page=activity&at=logs&folder=all&ctab=hidden&q=music&pscope=movie&pl=3&keep=1",
|
||||
);
|
||||
render();
|
||||
expect(window.location.search).toBe("?page=activity&at=logs&keep=1");
|
||||
});
|
||||
|
||||
it("keeps the channel page open over any page", () => {
|
||||
window.history.replaceState({}, "", "/?page=stats&chan=UC1&folder=all");
|
||||
const { result } = render();
|
||||
expect(window.location.search).toBe("?page=stats&chan=UC1");
|
||||
expect(result.current.channelView?.id).toBe("UC1");
|
||||
});
|
||||
|
||||
it("opens a channel link with only the channel page's keys, even over the page they belong to", () => {
|
||||
window.history.replaceState({}, "", "/?q=music&sort=oldest&chan=UC1&chtab=about&chtypes=ns");
|
||||
render();
|
||||
expect(window.location.search).toBe("?chan=UC1&chtab=about&chtypes=ns&page=feed");
|
||||
});
|
||||
});
|
||||
|
||||
// The channel page has an address of its own (the owner, 2026-10-05): it used to take the feed's
|
||||
// filters along (`?q=music&sort=oldest&chan=…`), naming a sort the channel did not show.
|
||||
describe("NavigationProvider · the channel page's address", () => {
|
||||
it("names only the channel; the page under it keeps its own address for Back", async () => {
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?q=music&sort=oldest");
|
||||
const { result } = render();
|
||||
act(() => result.current.openChannel("UC1", "One"));
|
||||
expect(window.location.search).toBe("?page=feed&chan=UC1");
|
||||
act(() => window.history.back());
|
||||
await vi.waitFor(() => expect(result.current.channelView).toBeNull());
|
||||
expect(window.location.search).toBe("?q=music&sort=oldest&page=feed");
|
||||
});
|
||||
|
||||
it("says no page owns the address while the channel stands over it", () => {
|
||||
window.history.replaceState({ sfPage: "plex" }, "", "/?page=plex");
|
||||
const { result } = render();
|
||||
expect(result.current.page).toBe("plex");
|
||||
expect(urlPage(result.current)).toBe("plex");
|
||||
act(() => result.current.openChannel("UC1", "One"));
|
||||
expect(urlPage(result.current)).toBeNull();
|
||||
});
|
||||
|
||||
it("another channel opened from it starts fresh", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.openChannel("UC1", "One"));
|
||||
window.history.replaceState(window.history.state, "", "/?chan=UC1&chtab=about&chsort=oldest");
|
||||
act(() => result.current.openChannel("UC2", "Two"));
|
||||
expect(window.location.search).toBe("?chan=UC2");
|
||||
});
|
||||
|
||||
it("a page switch takes the channel page's keys with it", () => {
|
||||
window.history.replaceState({}, "", "/?chan=UC1&chtab=about&chsort=oldest&chtypes=n");
|
||||
const { result } = render();
|
||||
act(() => result.current.setPage("stats"));
|
||||
expect(window.location.search).toBe("?page=stats");
|
||||
});
|
||||
|
||||
it("closing it in place takes its keys with it", () => {
|
||||
window.history.replaceState({}, "", "/?chan=UC1&chtab=about&chtypes=n");
|
||||
const { result } = render();
|
||||
stubNavigation([false]);
|
||||
act(() => result.current.closeChannel());
|
||||
expect(window.location.search).toBe("?page=feed");
|
||||
});
|
||||
});
|
||||
|
||||
// The YouTube player opens over any page and names itself in its own entry (lib/playerUrlState).
|
||||
describe("NavigationProvider · the player's address", () => {
|
||||
it("a page switch takes a player the address still names with it", () => {
|
||||
window.history.replaceState({}, "", "/?q=music&watch=v1&wrel=v2&wtab=related");
|
||||
const { result } = render();
|
||||
act(() => result.current.setPage("stats"));
|
||||
expect(window.location.search).toBe("?page=stats");
|
||||
});
|
||||
|
||||
it("a channel link names no player: opening the channel closes it", () => {
|
||||
window.history.replaceState({}, "", "/?q=music&watch=v1&wrel=v2&wtab=related");
|
||||
render();
|
||||
expect(channelUrl("UC1")).toBe("/?page=feed&chan=UC1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("NavigationProvider · Back", () => {
|
||||
// A tab that had a since-removed module open, reloaded onto the new build: its older history
|
||||
// entries still name that page, and Back lands on one of them.
|
||||
@@ -208,7 +310,7 @@ describe("NavigationProvider · Back", () => {
|
||||
expect(result.current.page).toBe("feed");
|
||||
// …and the entry says so too, so the address bar and a later Feed click agree with the screen.
|
||||
expect(window.history.state).toMatchObject({ sfPage: "feed" });
|
||||
expect(window.location.search).toBe("?keep=1");
|
||||
expect(window.location.search).toBe("?page=feed&keep=1");
|
||||
});
|
||||
|
||||
it("lands where a retired page's content went, and the entry names that page", () => {
|
||||
@@ -325,7 +427,7 @@ describe("NavigationProvider · a page the account cannot open", () => {
|
||||
window.history.replaceState(null, "", "/?page=scheduler&keep=1");
|
||||
const { result } = render();
|
||||
expect(result.current.page).toBe("feed");
|
||||
expect(window.location.search).toBe("?keep=1");
|
||||
expect(window.location.search).toBe("?page=feed&keep=1");
|
||||
expect(window.history.state).toMatchObject({ sfPage: "feed" });
|
||||
});
|
||||
|
||||
@@ -361,7 +463,7 @@ describe("NavigationProvider · a page the account cannot open", () => {
|
||||
qc.setQueryData(qk.me(), member);
|
||||
});
|
||||
await settle();
|
||||
expect(window.location.search).toBe("");
|
||||
expect(window.location.search).toBe("?page=feed");
|
||||
expect(window.history.state).toMatchObject({ sfPage: "feed" });
|
||||
expect(getAccountRaw(PAGE_KEY)).toBe("feed");
|
||||
act(() => {
|
||||
@@ -381,7 +483,7 @@ describe("NavigationProvider · a page the account cannot open", () => {
|
||||
});
|
||||
await settle();
|
||||
expect(result.current.channelView).toBeNull();
|
||||
expect(window.location.search).toBe("");
|
||||
expect(window.location.search).toBe("?page=feed");
|
||||
expect(window.history.state?._chan).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// A reload under a dialog that does not reopen (About) loads on the dialog's entry, its overlay mark
|
||||
// still on it. A view rewritten in place there (the search refined) is another view: the next overlay
|
||||
// pushes its own entry over it rather than taking this one over — taken over, closing it stepped back
|
||||
// onto the entry below, and the screen went back to the search before the refine. Its own file: the
|
||||
// entry is read as the history module loads, so it is set up before the import.
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("react-i18next")>()),
|
||||
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
|
||||
}));
|
||||
|
||||
describe("a view rewritten in place on the entry a reload under a dialog started from", () => {
|
||||
it("is where an overlay over it closes to", async () => {
|
||||
window.history.replaceState({ sfPage: "feed", _yt: "dogs" }, "", "/?page=feed&yt=dogs");
|
||||
window.history.pushState(
|
||||
{ sfPage: "feed", _yt: "dogs", _ov: 1, _ovd: 1 },
|
||||
"",
|
||||
"/?page=feed&yt=dogs",
|
||||
);
|
||||
const { NavigationProvider } = await import("./NavigationProvider");
|
||||
const { useNavigation, useNavigationActions } = await import("./navigationContext");
|
||||
const { useBackToClose } = await import("../../lib/history");
|
||||
const { qk } = await import("../../lib/queryKeys");
|
||||
const { claimLocalData } = await import("../../lib/storage");
|
||||
const qc = new QueryClient();
|
||||
qc.setQueryData(qk.me(), { id: 1, role: "admin" });
|
||||
claimLocalData(1);
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={qc}>
|
||||
<NavigationProvider>{children}</NavigationProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
const nav = renderHook(() => ({ ...useNavigation(), ...useNavigationActions() }), { wrapper });
|
||||
act(() => nav.result.current.enterYtSearch("cats"));
|
||||
|
||||
const depth = window.history.length;
|
||||
const overlay = renderHook(() => useBackToClose(() => {}));
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(window.history.length).toBe(depth + 1);
|
||||
|
||||
await act(async () => {
|
||||
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
|
||||
overlay.unmount();
|
||||
await landed;
|
||||
});
|
||||
expect(new URLSearchParams(window.location.search).get("yt")).toBe("cats");
|
||||
expect(nav.result.current.ytSearch).toBe("cats");
|
||||
}, 30_000); // the provider's whole import graph loads inside the case (see the header)
|
||||
});
|
||||
@@ -2,8 +2,13 @@ import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react
|
||||
import { useLatest } from "../../lib/useLatest";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useMe } from "../../lib/useMe";
|
||||
import { resolvePage, retiredParams, urlWithParams, type Page } from "../../lib/urlState";
|
||||
import { ACTIVITY_KEYS } from "../../lib/activityUrlState";
|
||||
import {
|
||||
channelUrl,
|
||||
resolvePage,
|
||||
retiredParams,
|
||||
urlWithParams,
|
||||
type Page,
|
||||
} from "../../lib/urlState";
|
||||
import { useDocumentObjectTitle } from "../../lib/documentTitle";
|
||||
import { getAccountRaw, setAccountRaw } from "../../lib/storage";
|
||||
import {
|
||||
@@ -12,8 +17,17 @@ import {
|
||||
nextNavId,
|
||||
notifyNav,
|
||||
rememberNavPosition,
|
||||
replaceView,
|
||||
} from "../../lib/history";
|
||||
import { pageTitleKey, reachablePage } from "./moduleRegistry";
|
||||
import { foreignUrlKeys, moduleUrlKeys, pageTitleKey, reachablePage } from "./moduleRegistry";
|
||||
import { CHANNEL_PAGE_KEYS } from "../../lib/channelPageUrlState";
|
||||
import { PLAYER_KEYS } from "../../lib/playerUrlState";
|
||||
import {
|
||||
DEFAULT_YT_COUNT,
|
||||
ytCountFrom,
|
||||
ytSearchFrom,
|
||||
ytSearchParams,
|
||||
} from "../../lib/ytSearchUrlState";
|
||||
import {
|
||||
channelViewFrom,
|
||||
loadInitialPage,
|
||||
@@ -37,24 +51,35 @@ import {
|
||||
//
|
||||
// The contexts, their value types and the hooks live in navigationContext.ts.
|
||||
|
||||
/** The address bar of `page`'s root: the page (feed implicit) with every view-specific key cleared. */
|
||||
/** The address bar of `page`'s root: the page — the feed too: a bare address is the landing (Home, or
|
||||
* the remembered page), so a feed left unnamed reloaded or bookmarked as another page — no channel or
|
||||
* player over it, and every module's own keys cleared — a page switch resets to that module's root,
|
||||
* and its store mirrors what it holds back in. */
|
||||
function pageRootParams(page: Page): Record<string, string | null> {
|
||||
return {
|
||||
page: page === "feed" ? null : page,
|
||||
chan: null,
|
||||
v: null,
|
||||
pl: null,
|
||||
pscope: null,
|
||||
psort: null,
|
||||
pshow: null,
|
||||
pf: null,
|
||||
ctab: null,
|
||||
csort: null,
|
||||
cf: null,
|
||||
...Object.fromEntries(ACTIVITY_KEYS.map((k) => [k, null])),
|
||||
page,
|
||||
...closedChannelParams(),
|
||||
...nulls(PLAYER_KEYS),
|
||||
...nulls(moduleUrlKeys()),
|
||||
};
|
||||
}
|
||||
|
||||
/** The address of the page under a live search, the search ended: no search, player or channel. */
|
||||
const searchEndParams = (): Record<string, string | null> => ({
|
||||
...closedChannelParams(),
|
||||
...nulls(PLAYER_KEYS),
|
||||
...ytSearchParams(null, DEFAULT_YT_COUNT),
|
||||
});
|
||||
|
||||
const nulls = (keys: readonly string[]) => Object.fromEntries(keys.map((k) => [k, null]));
|
||||
|
||||
/** No channel page: neither `chan` nor its view's keys, which the page itself writes (ChannelPage) —
|
||||
* a closed channel leaves none behind. (An opened one gets its address from `channelUrl`.) */
|
||||
const closedChannelParams = (): Record<string, string | null> => ({
|
||||
chan: null,
|
||||
...nulls(CHANNEL_PAGE_KEYS),
|
||||
});
|
||||
|
||||
export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
// Held here as well as in Settings: this is the instance mounted on every boot, so a value only
|
||||
@@ -66,18 +91,30 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
// and the address bar (stamped from it below) agree.
|
||||
const me = useMe();
|
||||
const page = reachablePage(chosenPage, me);
|
||||
// Ephemeral: not persisted and not in the URL, so a reload returns to the normal feed (a search
|
||||
// spends quota, so we never auto-replay it) — UNLESS it was zero-quota scrape-sourced, which rides
|
||||
// in history.state and is free to re-fetch. The popstate handler derives it from history.state so
|
||||
// Back steps player → search → feed instead of the search vanishing without a history entry.
|
||||
const [ytSearch, setYtSearch] = useState<string | null>(() => {
|
||||
const st = window.history.state;
|
||||
return st?._yt && st?._ytScrape ? (st._yt as string) : null;
|
||||
});
|
||||
// The live YouTube search: named in the address (`yt`, and `ytn` for its count, lib/ytSearchUrlState)
|
||||
// so a reload or a link opens it again; its own history entry, so Back steps player → search → feed.
|
||||
// Whether it RUNS by itself is not the address's to say: `ytAsked` is the term this document was
|
||||
// asked to search for (sent from the search box, or "Search YouTube" pressed), on the entries
|
||||
// it has stayed on since — leaving the search ends it. Anything else — a reload, a link, a Back or
|
||||
// a Forward onto a search — runs only when it costs no quota (Feed decides).
|
||||
const [ytSearch, setYtSearch] = useState<string | null>(() =>
|
||||
page === "feed" ? ytSearchFrom(new URLSearchParams(window.location.search)) : null,
|
||||
);
|
||||
const [ytCount, setYtCountState] = useState(() =>
|
||||
ytCountFrom(new URLSearchParams(window.location.search)),
|
||||
);
|
||||
const [ytAsked, setYtAsked] = useState<string | null>(null);
|
||||
const ytSearchRef = useLatest(ytSearch);
|
||||
const ytCountRef = useLatest(ytCount);
|
||||
// The search ends: off the screen, and no longer asked for.
|
||||
const endYtSearch = useCallback(() => {
|
||||
setYtSearch(null);
|
||||
setYtAsked(null);
|
||||
}, []);
|
||||
// The open channel page rides in history.state (_chan = id, _chanName = a name to show before the
|
||||
// detail loads) AND is mirrored to the address bar as ?chan=<id>, so Back closes it, a reload restores
|
||||
// it, and a bookmarked ?chan link opens it (unlike ytSearch, which is dropped). Reload of an in-app
|
||||
// entry reads history.state._chan; a fresh bookmark has only the ?chan param.
|
||||
// it, and a bookmarked ?chan link opens it. Reload of an in-app entry reads history.state._chan; a
|
||||
// fresh bookmark has only the ?chan param.
|
||||
const [channelView, setChannelView] = useState<ChannelView | null>(() =>
|
||||
channelViewFrom(window.history.state, window.location.search),
|
||||
);
|
||||
@@ -107,31 +144,36 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
closeOverlaysThenNavigate(() => {
|
||||
// A channel page overlays the content column, so a nav click must close it even when the
|
||||
// underlying page is unchanged (e.g. "Feed" while a channel opened from the feed).
|
||||
if (next === pageRef.current && !channelViewRef.current) {
|
||||
// So must a live search on it, though that press ends only the search: the page's view stays.
|
||||
const samePage = next === pageRef.current && !channelViewRef.current;
|
||||
if (samePage && ytSearchRef.current == null) {
|
||||
then?.();
|
||||
return;
|
||||
}
|
||||
setChannelView(null); // leave any open channel page when navigating via the rail
|
||||
// A live search under that channel ends too: the page opens at its root, which the address
|
||||
// below names — the Feed press over a channel opened from a search included.
|
||||
endYtSearch();
|
||||
setPageState(next);
|
||||
setAccountRaw(PAGE_KEY, next);
|
||||
// Push an in-app history entry so browser/mouse Back steps through pages instead of leaving
|
||||
// the app. A fresh { sfPage } (no carried-over _yt/_chan markers) so each page starts at its
|
||||
// root, and the address bar reflects the page (feed is implicit) while clearing the
|
||||
// view-specific params (chan/v/pl and the plex content keys pscope/psort/pshow/pf) — a page
|
||||
// switch resets to that module's root. Feed filters (owned by FeedFiltersProvider) are left
|
||||
// intact; the plex/channels keys re-mirror from PlexProvider / ChannelsProvider on return to
|
||||
// their page. The item it was opened from is still focused: the state setters above have not
|
||||
// re-rendered anything yet.
|
||||
// root, and the address bar reflects the page (the feed too) while clearing `chan` and
|
||||
// every module's own keys (pageRootParams) — a page switch resets to that module's root, and
|
||||
// each module's store mirrors its state back in on its page. The item it was opened from is
|
||||
// still focused: the state setters above have not re-rendered anything yet.
|
||||
// The press on a search over its own page ends only the search: the page's view is the one
|
||||
// on screen and stays named — its store, unchanged, writes nothing back in.
|
||||
rememberNavPosition();
|
||||
window.history.pushState(
|
||||
{ sfPage: next, sfScroll: nextNavId() },
|
||||
"",
|
||||
urlWithParams(pageRootParams(next)),
|
||||
urlWithParams(samePage ? searchEndParams() : pageRootParams(next)),
|
||||
);
|
||||
notifyNav();
|
||||
then?.();
|
||||
}),
|
||||
[pageRef, channelViewRef],
|
||||
[pageRef, channelViewRef, ytSearchRef, endYtSearch],
|
||||
);
|
||||
|
||||
// A sub-view (channel / YT search) is an OVERLAY, not a page change. Like setPage it never lands
|
||||
@@ -139,10 +181,12 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
// inside one.
|
||||
const openChannel = useCallback((id: string, name?: string) => {
|
||||
closeOverlaysThenNavigate(() => {
|
||||
const url = urlWithParams({ chan: id });
|
||||
// The channel's address names the channel alone: the page under it keeps its own keys on its
|
||||
// own entry, where Back finds them, and writes none while the channel stands over it (urlPage).
|
||||
const url = channelUrl(id);
|
||||
if (window.history.state?._chan) {
|
||||
const st = window.history.state;
|
||||
window.history.replaceState({ ...st, _chan: id, _chanName: name ?? null }, "", url);
|
||||
replaceView({ ...st, _chan: id, _chanName: name ?? null }, url);
|
||||
} else {
|
||||
const st = rememberNavPosition();
|
||||
window.history.pushState({ ...st, _chan: id, _chanName: name ?? null }, "", url);
|
||||
@@ -157,36 +201,67 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
// No owned history entry (e.g. opened straight from a ?chan bookmark), or none of this document
|
||||
// below it to step back to (a full tab, see backStaysInDocument): clear it in place — the
|
||||
// entry's channel marks and the ?chan param.
|
||||
// A live search under it (the channel opened from its results) is on screen again, and named
|
||||
// again: the channel's address carried none of it.
|
||||
setChannelView(null);
|
||||
const { _chan: _id, _chanName: _name, ...st } = window.history.state ?? {};
|
||||
window.history.replaceState(st, "", urlWithParams({ chan: null }));
|
||||
replaceView(
|
||||
st,
|
||||
urlWithParams({
|
||||
...closedChannelParams(),
|
||||
...ytSearchParams(ytSearchRef.current, ytCountRef.current),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}, []);
|
||||
}, [ytSearchRef, ytCountRef]);
|
||||
|
||||
const enterYtSearch = useCallback((q: string) => {
|
||||
setYtSearch(q);
|
||||
// Drop any prior _ytScrape marker — the new search's source isn't known yet; Feed re-stamps it
|
||||
// once the results resolve, so a reload only restores a confirmed scrape-sourced search.
|
||||
const { _ytScrape: _drop, ...st } = window.history.state || {};
|
||||
if (st._yt)
|
||||
window.history.replaceState({ ...st, _yt: q }, ""); // refine current search
|
||||
else {
|
||||
// New sub-view entry.
|
||||
const { _ytScrape: _dropToo, ...left } = rememberNavPosition();
|
||||
window.history.pushState({ ...left, sfPage: "feed", _yt: q }, "");
|
||||
setYtAsked(q);
|
||||
const st = window.history.state ?? {};
|
||||
const here = new URLSearchParams(window.location.search);
|
||||
if (st._yt || ytSearchFrom(here) != null) {
|
||||
// Refine the search on screen, in place, at the count it shows (one a link opened too: it
|
||||
// is the first entry of this document, so its new `_yt` mark has nothing of ours below it).
|
||||
replaceView({ ...st, _yt: q }, urlWithParams(ytSearchParams(q, ytCountFrom(here))));
|
||||
} else {
|
||||
// New sub-view entry, at the default count — ours (`_ytOwn`): leaving it steps back off it.
|
||||
setYtCountState(DEFAULT_YT_COUNT);
|
||||
const left = rememberNavPosition();
|
||||
window.history.pushState(
|
||||
{ ...left, sfPage: "feed", _yt: q, _ytOwn: 1 },
|
||||
"",
|
||||
urlWithParams(ytSearchParams(q, DEFAULT_YT_COUNT)),
|
||||
);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// The press that runs the search on screen, where it did not run by itself.
|
||||
const askYtSearch = useCallback(() => setYtAsked(ytSearchRef.current), [ytSearchRef]);
|
||||
|
||||
const setYtCount = useCallback(
|
||||
(n: number) => {
|
||||
setYtCountState(n);
|
||||
replaceView(
|
||||
window.history.state ?? {},
|
||||
urlWithParams(ytSearchParams(ytSearchRef.current, n)),
|
||||
);
|
||||
},
|
||||
[ytSearchRef],
|
||||
);
|
||||
|
||||
const exitYtSearch = useCallback(() => {
|
||||
// Pop our search entry (so Forward still works); fall back to a clear in place if we don't own
|
||||
// one, or there is no entry of this document below it (a full tab, see backStaysInDocument).
|
||||
if (window.history.state?._yt && backStaysInDocument()) window.history.back();
|
||||
// one — a search a link or a reload opened is marked (`_yt`) but was pushed by nobody: below it is
|
||||
// another site, or nothing — or there is no entry of this document below it (a full tab, see
|
||||
// backStaysInDocument).
|
||||
if (window.history.state?._ytOwn && backStaysInDocument()) window.history.back();
|
||||
else {
|
||||
setYtSearch(null);
|
||||
const { _yt: _q, _ytScrape: _scrape, ...st } = window.history.state ?? {};
|
||||
window.history.replaceState(st, "");
|
||||
endYtSearch();
|
||||
const { _yt: _q, _ytOwn: _own, ...st } = window.history.state ?? {};
|
||||
replaceView(st, urlWithParams(ytSearchParams(null, DEFAULT_YT_COUNT)));
|
||||
}
|
||||
}, []);
|
||||
}, [endYtSearch]);
|
||||
|
||||
// Leaving the feed ends any live YouTube search, so coming back shows the normal feed. Adjusted
|
||||
// DURING the render that changes the page, against the page we were last on: as an effect it ran
|
||||
@@ -196,7 +271,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
const [pageSearchWasOn, setPageSearchWasOn] = useState(page);
|
||||
if (pageSearchWasOn !== page) {
|
||||
setPageSearchWasOn(page);
|
||||
if (page !== "feed") setYtSearch(null);
|
||||
if (page !== "feed") endYtSearch();
|
||||
}
|
||||
|
||||
// The browser tab names the place and the object in it (DESIGN § Composition, "Where am I"):
|
||||
@@ -233,25 +308,33 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
// then sync state from history.state on popstate — the browser restores each entry's URL for us, so
|
||||
// the popstate handler only needs to read history.state.
|
||||
useEffect(() => {
|
||||
// A reload drops a stale _yt EXCEPT when scrape-sourced (zero quota): then keep _yt + _ytScrape
|
||||
// so it restores and re-fetches free (ytSearch above already initialised from it). _chan/_chanName
|
||||
// are always kept so a channel page survives F5.
|
||||
// The entry of a search the address names carries its `_yt` mark, whichever way it opened (sent
|
||||
// from the box, a reload, a link): a channel opened from its results reads the search under it
|
||||
// from that mark. A mark left without one (an older build's entry) goes. _chan/_chanName are
|
||||
// always kept so a channel page survives F5.
|
||||
const st = window.history.state || {};
|
||||
// Mirror the resolved initial page to the address bar (feed implicit) so a page reached from the
|
||||
// stored landing pref — not just from the URL — is itself bookmarkable. urlWithParams preserves any
|
||||
// ?chan / ?v / ?pl / filter params the loaders already read.
|
||||
// Mirror the resolved initial page to the address bar (the feed too) so a page reached from the
|
||||
// stored landing pref — not just from the URL — is itself bookmarkable. urlWithParams keeps the
|
||||
// shell's keys (?chan, a player's) and the page's own; other pages' go (below).
|
||||
// A retired page's link — or the remembered last page, when that is what opened — also opens its
|
||||
// part of the page that replaced it (an `at` tab).
|
||||
const linked = new URLSearchParams(window.location.search).get("page");
|
||||
const remembered = getAccountRaw(PAGE_KEY);
|
||||
// A link can carry another page's keys (hand-edited, or written by an older build): the page
|
||||
// opens without them, so its address names only what it shows — and a channel page open over it
|
||||
// shows none of the page's own (an older build's channel links carried the feed's filters).
|
||||
const shown = channelViewFrom(st, window.location.search);
|
||||
const url = urlWithParams({
|
||||
...nulls(shown ? moduleUrlKeys() : foreignUrlKeys(mountPage)),
|
||||
...retiredParams(linked ?? (resolvePage(remembered) === mountPage ? remembered : null)),
|
||||
page: mountPage === "feed" ? null : mountPage,
|
||||
page: mountPage,
|
||||
});
|
||||
if (st._yt && st._ytScrape) {
|
||||
window.history.replaceState({ ...st, sfPage: mountPage }, "", url);
|
||||
const named =
|
||||
mountPage === "feed" ? ytSearchFrom(new URLSearchParams(window.location.search)) : null;
|
||||
if (named != null) {
|
||||
window.history.replaceState({ ...st, _yt: named, sfPage: mountPage }, "", url);
|
||||
} else {
|
||||
const { _yt: _staleYt, _ytScrape: _staleScrape, ...rest } = st;
|
||||
const { _yt: _staleYt, _ytScrape: _staleScrape, _ytOwn: _staleOwn, ...rest } = st;
|
||||
window.history.replaceState({ ...rest, sfPage: mountPage }, "", url);
|
||||
}
|
||||
function onPop(e: PopStateEvent) {
|
||||
@@ -267,13 +350,22 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
window.history.replaceState(
|
||||
{ ...window.history.state, sfPage: p },
|
||||
"",
|
||||
urlWithParams({ ...retiredParams(sf), page: p === "feed" ? null : p }),
|
||||
urlWithParams({ ...retiredParams(sf), page: p }),
|
||||
);
|
||||
setPageState(p);
|
||||
setAccountRaw(PAGE_KEY, p);
|
||||
// The YouTube-search sub-view and the channel page ride in history.state, so Back/Forward
|
||||
// restores or clears them to match the entry we landed on.
|
||||
setYtSearch((e.state?._yt as string) ?? null);
|
||||
// The YouTube search is read from the address the browser restored, so Back/Forward opens or
|
||||
// clears it to match the entry we landed on. One landed on without it has ended: a Forward back
|
||||
// onto it is not asked for, and an API search waits for a press.
|
||||
// A channel page opened from its results stands over it: its entry carries the search's mark
|
||||
// (its address does not), and the search stays under it — closing a player over that channel
|
||||
// lands there, and is no leaving of the search.
|
||||
const here = new URLSearchParams(window.location.search);
|
||||
const under = e.state?._chan && typeof e.state._yt === "string" ? e.state._yt : null;
|
||||
const landed = p === "feed" ? (ytSearchFrom(here) ?? under) : null;
|
||||
setYtSearch(landed);
|
||||
if (landed == null) setYtAsked(null);
|
||||
setYtCountState(ytCountFrom(here));
|
||||
// The channel page rides in history.state._chan, with a ?chan URL fallback for a fresh bookmark
|
||||
// entry (URL-only, no _chan) — reading e.state alone would wrongly close the channel when a
|
||||
// popstate lands here (e.g. after an overlay's programmatic history.back()). channelViewFrom
|
||||
@@ -285,12 +377,26 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
}, [mountPage]);
|
||||
|
||||
const state = useMemo<NavigationState>(
|
||||
() => ({ page, channelView, ytSearch }),
|
||||
[page, channelView, ytSearch],
|
||||
() => ({
|
||||
page,
|
||||
channelView,
|
||||
ytSearch,
|
||||
ytCount,
|
||||
ytSearchAsked: ytSearch != null && ytAsked === ytSearch,
|
||||
}),
|
||||
[page, channelView, ytSearch, ytCount, ytAsked],
|
||||
);
|
||||
const actions = useMemo<NavigationActions>(
|
||||
() => ({ setPage, openChannel, closeChannel, enterYtSearch, exitYtSearch }),
|
||||
[setPage, openChannel, closeChannel, enterYtSearch, exitYtSearch],
|
||||
() => ({
|
||||
setPage,
|
||||
openChannel,
|
||||
closeChannel,
|
||||
enterYtSearch,
|
||||
exitYtSearch,
|
||||
askYtSearch,
|
||||
setYtCount,
|
||||
}),
|
||||
[setPage, openChannel, closeChannel, enterYtSearch, exitYtSearch, askYtSearch, setYtCount],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// The live YouTube search in the address: sent from the search box it gets its own entry naming the
|
||||
// term (and its count), a reload or a link opens it again, Back/Forward read it from the address the
|
||||
// browser restored — and only a search asked for in this document counts as asked (an API search
|
||||
// reopened any other way waits for a press, Feed's part).
|
||||
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
|
||||
import { renderHook, act, cleanup } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-i18next")>();
|
||||
return {
|
||||
...actual,
|
||||
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
|
||||
};
|
||||
});
|
||||
|
||||
import { NavigationProvider } from "./NavigationProvider";
|
||||
import { useNavigation, useNavigationActions } from "./navigationContext";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
import { claimLocalData } from "../../lib/storage";
|
||||
|
||||
let qc = new QueryClient();
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={qc}>
|
||||
<NavigationProvider>{children}</NavigationProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
const render = () =>
|
||||
renderHook(() => ({ ...useNavigation(), ...useNavigationActions() }), { wrapper });
|
||||
const search = () => new URLSearchParams(window.location.search);
|
||||
|
||||
/** No entry of this document under the current one (a bookmark opened in a new tab). */
|
||||
function stubNoEntryBelow() {
|
||||
Object.defineProperty(window, "navigation", {
|
||||
configurable: true,
|
||||
value: {
|
||||
currentEntry: { index: 1 },
|
||||
entries: () => [{ sameDocument: false }, { sameDocument: true }],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
qc = new QueryClient();
|
||||
qc.setQueryData(qk.me(), { id: 1, role: "admin", plex_enabled: true });
|
||||
localStorage.clear();
|
||||
claimLocalData(1);
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&q=lofi");
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
Reflect.deleteProperty(window, "navigation");
|
||||
});
|
||||
|
||||
describe("NavigationProvider · the YouTube search in the address", () => {
|
||||
it("names a search sent from the box on an entry of its own, over the feed's", () => {
|
||||
const { result } = render();
|
||||
const depth = window.history.length;
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
expect(window.history.length).toBe(depth + 1);
|
||||
expect(search().get("yt")).toBe("lofi");
|
||||
expect(search().get("q")).toBe("lofi"); // the feed's own keys stay
|
||||
expect(search().get("ytn")).toBeNull(); // the default count is left out
|
||||
expect(result.current.ytSearch).toBe("lofi");
|
||||
expect(result.current.ytSearchAsked).toBe(true);
|
||||
});
|
||||
|
||||
it("refines the search on screen in place, at the count it shows", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
act(() => result.current.setYtCount(60));
|
||||
expect(search().get("ytn")).toBe("60");
|
||||
const depth = window.history.length;
|
||||
act(() => result.current.enterYtSearch("lofi beats"));
|
||||
expect(window.history.length).toBe(depth);
|
||||
expect(search().get("yt")).toBe("lofi beats");
|
||||
expect(search().get("ytn")).toBe("60");
|
||||
expect(result.current.ytCount).toBe(60);
|
||||
});
|
||||
|
||||
it("a new search starts at the default count", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
act(() => result.current.setYtCount(40));
|
||||
stubNoEntryBelow(); // left in place, so the next search is a new entry
|
||||
vi.spyOn(window.history, "back").mockImplementation(() => {});
|
||||
act(() => result.current.exitYtSearch());
|
||||
act(() => result.current.enterYtSearch("jazz"));
|
||||
expect(result.current.ytCount).toBe(20);
|
||||
expect(search().get("ytn")).toBeNull();
|
||||
});
|
||||
|
||||
it("writes the count, and clears it back at the default", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
act(() => result.current.setYtCount(100));
|
||||
expect(search().get("ytn")).toBe("100");
|
||||
act(() => result.current.setYtCount(20));
|
||||
expect(search().get("ytn")).toBeNull();
|
||||
});
|
||||
|
||||
it("reopens the search a reload or a link names, not as asked", () => {
|
||||
window.history.replaceState(null, "", "/?page=feed&yt=lofi&ytn=40");
|
||||
const { result } = render();
|
||||
expect(result.current.ytSearch).toBe("lofi");
|
||||
expect(result.current.ytCount).toBe(40);
|
||||
expect(result.current.ytSearchAsked).toBe(false);
|
||||
expect(search().get("yt")).toBe("lofi"); // the mount's own stamp keeps it
|
||||
act(() => result.current.askYtSearch());
|
||||
expect(result.current.ytSearchAsked).toBe(true);
|
||||
});
|
||||
|
||||
it("refines a search a link opened in place too, at the count it shows", () => {
|
||||
window.history.replaceState(null, "", "/?page=feed&yt=lofi&ytn=40");
|
||||
const { result } = render();
|
||||
const depth = window.history.length;
|
||||
act(() => result.current.enterYtSearch("jazz"));
|
||||
expect(window.history.length).toBe(depth);
|
||||
expect([search().get("yt"), search().get("ytn")]).toEqual(["jazz", "40"]);
|
||||
});
|
||||
|
||||
it("Back onto an entry whose address alone names the search reopens it", () => {
|
||||
const { result } = render();
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&yt=lofi");
|
||||
act(() => {
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
});
|
||||
expect(result.current.ytSearch).toBe("lofi");
|
||||
});
|
||||
|
||||
it("keeps the search mark of an entry the reload started from", () => {
|
||||
window.history.replaceState({ sfPage: "feed", _yt: "lofi" }, "", "/?page=feed&yt=lofi");
|
||||
render();
|
||||
expect(window.history.state?._yt).toBe("lofi");
|
||||
});
|
||||
|
||||
it("marks the entry of a search the address opened (a reload, a link)", () => {
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&yt=lofi");
|
||||
render();
|
||||
expect(window.history.state?._yt).toBe("lofi");
|
||||
});
|
||||
|
||||
it("drops an older build's search mark the address does not name", () => {
|
||||
window.history.replaceState(
|
||||
{ sfPage: "feed", _yt: "lofi", _ytScrape: true },
|
||||
"",
|
||||
"/?page=feed",
|
||||
);
|
||||
const { result } = render();
|
||||
expect(result.current.ytSearch).toBeNull();
|
||||
expect(window.history.state?._yt).toBeUndefined();
|
||||
expect(window.history.state?._ytScrape).toBeUndefined();
|
||||
});
|
||||
|
||||
it("names no search under another page", () => {
|
||||
window.history.replaceState(null, "", "/?page=plex&yt=lofi");
|
||||
const { result } = render();
|
||||
expect(result.current.page).toBe("plex");
|
||||
expect(result.current.ytSearch).toBeNull();
|
||||
expect(search().get("yt")).toBeNull();
|
||||
});
|
||||
|
||||
it("Back/Forward read the search from the address the browser restored, not as asked", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
window.history.replaceState({ sfPage: "feed", _yt: "jazz" }, "", "/?page=feed&yt=jazz&ytn=60");
|
||||
act(() => {
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
});
|
||||
expect(result.current.ytSearch).toBe("jazz");
|
||||
expect(result.current.ytCount).toBe(60);
|
||||
expect(result.current.ytSearchAsked).toBe(false);
|
||||
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&q=lofi");
|
||||
act(() => {
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
});
|
||||
expect(result.current.ytSearch).toBeNull();
|
||||
});
|
||||
|
||||
it("leaving a search with no entry of this document below clears it from the address", () => {
|
||||
window.history.replaceState(null, "", "/?page=feed&yt=lofi&ytn=40");
|
||||
const { result } = render();
|
||||
stubNoEntryBelow();
|
||||
const back = vi.spyOn(window.history, "back").mockImplementation(() => {});
|
||||
act(() => result.current.exitYtSearch());
|
||||
expect(back).not.toHaveBeenCalled();
|
||||
expect(result.current.ytSearch).toBeNull();
|
||||
expect(search().get("yt")).toBeNull();
|
||||
expect(search().get("ytn")).toBeNull();
|
||||
});
|
||||
|
||||
it("a search left by Back and reached again by Forward is not asked for", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
expect(result.current.ytSearchAsked).toBe(true);
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&q=lofi");
|
||||
act(() => {
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
});
|
||||
window.history.replaceState({ sfPage: "feed", _yt: "lofi" }, "", "/?page=feed&yt=lofi");
|
||||
act(() => {
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
});
|
||||
expect(result.current.ytSearch).toBe("lofi");
|
||||
expect(result.current.ytSearchAsked).toBe(false);
|
||||
});
|
||||
|
||||
it("a search left in place is not asked for when it is opened again by a link", () => {
|
||||
window.history.replaceState(null, "", "/?page=feed&yt=lofi");
|
||||
const { result } = render();
|
||||
act(() => result.current.askYtSearch());
|
||||
stubNoEntryBelow();
|
||||
act(() => result.current.exitYtSearch());
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&yt=lofi");
|
||||
act(() => {
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
});
|
||||
expect(result.current.ytSearchAsked).toBe(false);
|
||||
});
|
||||
|
||||
it("the Feed press over a channel opened from the search opens the plain feed", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
act(() => result.current.openChannel("UC1"));
|
||||
act(() => result.current.setPage("feed"));
|
||||
expect(result.current.channelView).toBeNull();
|
||||
expect(result.current.ytSearch).toBeNull();
|
||||
expect(search().get("yt")).toBeNull();
|
||||
});
|
||||
|
||||
it("the Feed press on the search itself opens the plain feed, as over a channel", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
const depth = window.history.length;
|
||||
act(() => result.current.setPage("feed"));
|
||||
expect(result.current.ytSearch).toBeNull();
|
||||
expect(search().get("yt")).toBeNull();
|
||||
expect(window.history.length).toBe(depth + 1); // its own entry: Back returns to the search
|
||||
});
|
||||
|
||||
it("the Feed press on the search keeps the feed's own view in the address", () => {
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&show=all&sort=oldest");
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
act(() => result.current.setPage("feed"));
|
||||
expect(search().get("yt")).toBeNull();
|
||||
expect([search().get("show"), search().get("sort")]).toEqual(["all", "oldest"]);
|
||||
});
|
||||
|
||||
it("a search sent from the box is left by a step back off its own entry", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
const back = vi.spyOn(window.history, "back").mockImplementation(() => {});
|
||||
act(() => result.current.exitYtSearch());
|
||||
expect(back).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("a search a link opened is left in place, not by a step back off the document", () => {
|
||||
window.history.replaceState(null, "", "/?page=feed&yt=lofi");
|
||||
const { result } = render();
|
||||
const back = vi.spyOn(window.history, "back");
|
||||
act(() => result.current.exitYtSearch());
|
||||
expect(back).not.toHaveBeenCalled();
|
||||
expect(result.current.ytSearch).toBeNull();
|
||||
expect(search().get("yt")).toBeNull();
|
||||
});
|
||||
|
||||
it("a landing on a channel opened from the search (an overlay over it closing) keeps the search", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
act(() => result.current.openChannel("UC1"));
|
||||
// A player over the channel closed: the step back lands on the channel's own entry.
|
||||
act(() => {
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
});
|
||||
expect(result.current.ytSearch).toBe("lofi");
|
||||
expect(result.current.ytSearchAsked).toBe(true);
|
||||
// Back off the channel: the search it stood over is still the one asked for.
|
||||
window.history.replaceState({ sfPage: "feed", _yt: "lofi" }, "", "/?page=feed&yt=lofi");
|
||||
act(() => {
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
});
|
||||
expect(result.current.ytSearchAsked).toBe(true);
|
||||
});
|
||||
|
||||
it("a landing on a channel opened from a search the address opened keeps the search", () => {
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&yt=lofi");
|
||||
const { result } = render();
|
||||
act(() => result.current.openChannel("UC1"));
|
||||
act(() => {
|
||||
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
||||
});
|
||||
expect(result.current.ytSearch).toBe("lofi");
|
||||
});
|
||||
|
||||
it("a channel closed in place over the search names the search again", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
act(() => result.current.setYtCount(40));
|
||||
act(() => result.current.openChannel("UC1"));
|
||||
expect(search().get("yt")).toBeNull();
|
||||
stubNoEntryBelow();
|
||||
act(() => result.current.closeChannel());
|
||||
expect(result.current.ytSearch).toBe("lofi");
|
||||
expect([search().get("yt"), search().get("ytn")]).toEqual(["lofi", "40"]);
|
||||
});
|
||||
|
||||
it("a page switch takes the search off the address", () => {
|
||||
const { result } = render();
|
||||
act(() => result.current.enterYtSearch("lofi"));
|
||||
act(() => result.current.setPage("home"));
|
||||
expect(result.current.ytSearch).toBeNull();
|
||||
expect(search().get("yt")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// The channel page opens over any page, and its address names the channel alone (the owner, 2026-10-05:
|
||||
// it used to carry the feed's filters, naming a sort the channel did not show). The page under it is
|
||||
// still mounted — its store lives at the root — and a change in it while the channel stands over it
|
||||
// (a background refetch, the header search) must not write its keys onto the channel's address. Closing
|
||||
// the channel brings them back. The real provider and the real stores; only the network is absent.
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { act, cleanup, render, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("react-i18next")>()),
|
||||
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
|
||||
}));
|
||||
|
||||
import { NavigationProvider } from "./NavigationProvider";
|
||||
import { ModuleStores } from "./ModuleStores";
|
||||
import { useNavigationActions, type NavigationActions } from "./navigationContext";
|
||||
import { useFeedFilters, useFeedFiltersActions } from "../../modules/feed";
|
||||
import { usePlexActions } from "../../modules/plex";
|
||||
import { useChannelsActions } from "../../modules/channels";
|
||||
import { useFilesActions } from "../../modules/files";
|
||||
import { usePlaylistsActions } from "../../modules/playlists";
|
||||
import { claimLocalData } from "../../lib/storage";
|
||||
|
||||
type Probe = {
|
||||
nav: NavigationActions;
|
||||
change: Record<string, () => void>;
|
||||
};
|
||||
const probe: { current: Probe | null } = { current: null };
|
||||
|
||||
function Probe() {
|
||||
const nav = useNavigationActions();
|
||||
const filters = useFeedFilters();
|
||||
const { setFilters } = useFeedFiltersActions();
|
||||
const plex = usePlexActions();
|
||||
const channels = useChannelsActions();
|
||||
const files = useFilesActions();
|
||||
const playlists = usePlaylistsActions();
|
||||
// Handed out after each render (an effect, not the render itself, may write outside it).
|
||||
useEffect(() => {
|
||||
probe.current = {
|
||||
nav,
|
||||
change: {
|
||||
feed: () => setFilters({ ...filters, sort: "oldest" }),
|
||||
plex: () => plex.setScope("movie"),
|
||||
channels: () => channels.setView("hidden"),
|
||||
files: () => files.setView({ kind: "folder", id: 3 }),
|
||||
playlists: () => playlists.setSelectedId(5),
|
||||
"plex search": () => plex.setQ("poirot"),
|
||||
"channels search": () => channels.setSearch("tom"),
|
||||
"files search": () => files.setSearch("notes"),
|
||||
"playlists search": () => playlists.setSearch("jazz"),
|
||||
},
|
||||
};
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
// What each change above writes, once its page is what the address shows: [page, key, value]. A
|
||||
// search is written once the typing pauses.
|
||||
const WRITTEN: Record<string, [string, string, string]> = {
|
||||
feed: ["feed", "sort", "oldest"],
|
||||
plex: ["plex", "pscope", "movie"],
|
||||
channels: ["channels", "ctab", "hidden"],
|
||||
files: ["files", "folder", "3"],
|
||||
playlists: ["playlists", "pl", "5"],
|
||||
"plex search": ["plex", "pq", "poirot"],
|
||||
"channels search": ["channels", "cq", "tom"],
|
||||
"files search": ["files", "fq", "notes"],
|
||||
"playlists search": ["playlists", "plq", "jazz"],
|
||||
};
|
||||
const PAUSE = () => new Promise((r) => setTimeout(r, 400));
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
claimLocalData(3);
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
window.history.replaceState(null, "", "/");
|
||||
});
|
||||
|
||||
const search = () => new URLSearchParams(window.location.search);
|
||||
|
||||
describe.each(Object.keys(WRITTEN))("a channel page over %s", (change) => {
|
||||
it("keeps the page's keys off its address, and they come back when it closes", async () => {
|
||||
const [page, key, value] = WRITTEN[change]!;
|
||||
// The page named even for the feed: a bare address opens on Home (the account's default).
|
||||
window.history.replaceState({ sfPage: page }, "", `/?page=${page}`);
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<NavigationProvider>
|
||||
<ModuleStores>
|
||||
<Probe />
|
||||
</ModuleStores>
|
||||
</NavigationProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
act(() => probe.current!.nav.openChannel("UC1", "One"));
|
||||
act(() => probe.current!.change[change]!());
|
||||
await act(PAUSE);
|
||||
expect(search().get(key)).toBeNull();
|
||||
expect(search().get("chan")).toBe("UC1");
|
||||
act(() => probe.current!.nav.closeChannel());
|
||||
await waitFor(() => expect(search().get("chan")).toBeNull());
|
||||
await waitFor(() => expect(search().get(key)).toBe(value));
|
||||
});
|
||||
});
|
||||
@@ -48,6 +48,21 @@ export const REGISTERED_PAGES: readonly Page[] = ALL.map((m) => m.id);
|
||||
|
||||
const BY_ID = Object.fromEntries(ALL.map((m) => [m.id, m])) as Record<Page, ModuleDef>;
|
||||
|
||||
// Every module's address-bar keys, and those of every module but `page`: what a page switch clears and
|
||||
// what a page opens without (NavigationProvider). Derived from the definitions, so a new module's keys
|
||||
// are cleared the day it declares them.
|
||||
const ALL_URL_KEYS: readonly string[] = ALL.flatMap((m) => m.urlKeys);
|
||||
export function moduleUrlKeys(): readonly string[] {
|
||||
return ALL_URL_KEYS;
|
||||
}
|
||||
/** Every module's address-bar keys that carry typed text — what the client log keeps out (main.tsx). */
|
||||
export function typedUrlKeys(): readonly string[] {
|
||||
return ALL.flatMap((m) => m.typedUrlKeys ?? []);
|
||||
}
|
||||
export function foreignUrlKeys(page: Page): readonly string[] {
|
||||
return ALL.filter((m) => m.id !== page).flatMap((m) => m.urlKeys);
|
||||
}
|
||||
|
||||
// Look up a module's definition by page id (every Page is covered, incl. settings).
|
||||
export function moduleDef(id: Page): ModuleDef {
|
||||
return BY_ID[id];
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createContext, useContext } from "react";
|
||||
import type { Page } from "../../lib/urlState";
|
||||
import { DEFAULT_YT_COUNT } from "../../lib/ytSearchUrlState";
|
||||
import type { ChannelView } from "./navigationInit";
|
||||
|
||||
// The navigation contexts + their hooks, split out of NavigationProvider so that file exports only
|
||||
@@ -15,8 +16,13 @@ export interface NavigationState {
|
||||
page: Page;
|
||||
/** The open channel page (null = none). Overlays `page`; rides in history.state._chan. */
|
||||
channelView: ChannelView | null;
|
||||
/** Live YouTube search term (null = normal feed). A feed sub-view; rides in history.state._yt. */
|
||||
/** Live YouTube search term (null = normal feed). A feed sub-view, named in the address (`yt`). */
|
||||
ytSearch: string | null;
|
||||
/** How many results the search gathers (`ytn`). */
|
||||
ytCount: number;
|
||||
/** The search on screen was asked for in this document (sent from the search box, or run again by
|
||||
* a press), not only reopened by a reload, a link or Back. An API search runs only when asked. */
|
||||
ytSearchAsked: boolean;
|
||||
}
|
||||
|
||||
export interface NavigationActions {
|
||||
@@ -33,12 +39,17 @@ export interface NavigationActions {
|
||||
closeChannel: () => void;
|
||||
enterYtSearch: (q: string) => void;
|
||||
exitYtSearch: () => void;
|
||||
/** Run the search on screen: the "Search YouTube" press. */
|
||||
askYtSearch: () => void;
|
||||
setYtCount: (n: number) => void;
|
||||
}
|
||||
|
||||
export const NavigationStateContext = createContext<NavigationState>({
|
||||
page: "feed",
|
||||
channelView: null,
|
||||
ytSearch: null,
|
||||
ytCount: DEFAULT_YT_COUNT,
|
||||
ytSearchAsked: false,
|
||||
});
|
||||
export const NavigationActionsContext = createContext<NavigationActions>({
|
||||
setPage: () => {},
|
||||
@@ -46,6 +57,8 @@ export const NavigationActionsContext = createContext<NavigationActions>({
|
||||
closeChannel: () => {},
|
||||
enterYtSearch: () => {},
|
||||
exitYtSearch: () => {},
|
||||
askYtSearch: () => {},
|
||||
setYtCount: () => {},
|
||||
});
|
||||
|
||||
export function useNavigation(): NavigationState {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { Page } from "../../lib/urlState";
|
||||
import type { NavigationState } from "./navigationContext";
|
||||
|
||||
/** The page whose own keys the address bar carries: none while the channel page stands over it, so
|
||||
* every module store writes its keys (`useUrlMirror`) only while its page is what the screen shows.
|
||||
* A plain function beside the context, not a hook in it: the stores' tests mock that module. */
|
||||
export function urlPage(nav: Pick<NavigationState, "page" | "channelView">): Page | null {
|
||||
return nav.channelView ? null : nav.page;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { type Video, type VideoStatus } from "../../lib/api";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
import { notifyActionError } from "../../lib/actionErrors";
|
||||
import { useStableCallback } from "../../lib/useLatest";
|
||||
import { writeVideoState } from "../video/videoWrites";
|
||||
import { useOpenLinkedPlayer } from "./useOpenLinkedPlayer";
|
||||
|
||||
const PlayerModal = lazy(() => import("./PlayerModal"));
|
||||
|
||||
/** The shell's player, for an address that names one over a page that hosts none of its own (the
|
||||
* channel manager, where the watched-videos dialog played it; any page a link names): the video
|
||||
* alone. Decided at boot, once — `hosted` is whether the page on screen then opens it itself. */
|
||||
export function LinkedPlayer({ hosted }: { hosted: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [own] = useState(!hosted);
|
||||
const [video, setVideo] = useState<Video | null>(null);
|
||||
useOpenLinkedPlayer(
|
||||
own,
|
||||
() => undefined,
|
||||
(v) => setVideo(v),
|
||||
);
|
||||
const onState = useStableCallback((id: string, status: VideoStatus) => {
|
||||
const write = writeVideoState(qc, id, status);
|
||||
write
|
||||
.then(() => qc.invalidateQueries({ queryKey: qk.feed() }))
|
||||
.catch((e: unknown) => notifyActionError(e, t("errors.writeFailed.videoState")));
|
||||
return write;
|
||||
});
|
||||
const close = useStableCallback(() => setVideo(null));
|
||||
if (!video) return null;
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<PlayerModal video={video} startAt={null} onClose={close} onState={onState} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -23,6 +23,7 @@ import {
|
||||
CheckCheck,
|
||||
ExternalLink,
|
||||
Info,
|
||||
ListVideo,
|
||||
Maximize,
|
||||
Minimize,
|
||||
Minimize2,
|
||||
@@ -49,11 +50,13 @@ import {
|
||||
anyLayerAbove,
|
||||
escapeHandled,
|
||||
} from "../../lib/layerStack";
|
||||
import { focusInNavList } from "../../lib/listNav";
|
||||
import { trapTab, useDialogChrome } from "../../components/ui/dialogFocus";
|
||||
import DownloadButton from "../downloads/DownloadButton";
|
||||
import ClipPanel, { ClipCropFrame, type ClipCrop } from "./ClipPanel";
|
||||
import { markInAt, markOutAt, openAt, type ClipRange } from "../../lib/clipRange";
|
||||
import { api, type Video, type VideoStatus } from "../../lib/api";
|
||||
import { markedValue, useVideoMarks } from "../../lib/progressCache";
|
||||
import type { YTPlayer } from "../../lib/youtube";
|
||||
import {
|
||||
channelYouTubeUrl,
|
||||
@@ -63,8 +66,9 @@ import {
|
||||
relativeTime,
|
||||
} from "../../lib/format";
|
||||
import { canFullscreenElements, fullscreenElement } from "../../lib/fullscreen";
|
||||
import { dispatch, isActivationTarget, useKeyScope } from "../../lib/keymap";
|
||||
import { dispatch, isActivationTarget, setScopeCoveredProbe, useKeyScope } from "../../lib/keymap";
|
||||
import { useBackToClose } from "../../lib/history";
|
||||
import { linkedPlayer, playerParamUpdates, type PlayerPanelTab } from "../../lib/playerUrlState";
|
||||
import ChannelNameLink from "../video/ChannelNameLink";
|
||||
import Toaster from "../../components/ui/Toaster";
|
||||
import { useOverlayOrder } from "../../components/ui/overlayOrder";
|
||||
@@ -83,6 +87,11 @@ import { SURFACE } from "../../components/ui/surfaces";
|
||||
import { IconLink, LinkButton } from "../../components/ui/LinkButton";
|
||||
import { SectionLabel } from "../../components/ui/Headings";
|
||||
import { useMediaQuery } from "../../lib/useMediaQuery";
|
||||
import { useMe } from "../../lib/useMe";
|
||||
import Modal from "../../components/ui/Modal";
|
||||
import Tabs from "../../components/ui/Tabs";
|
||||
import { useTabPanel } from "../../components/ui/tabPanel";
|
||||
import { RelatedVideos } from "./RelatedVideos";
|
||||
|
||||
// Experiment (branch experiment/inline-player): play the video in-app via the
|
||||
// YouTube IFrame Player API (not a bare embed) so we can read playback position
|
||||
@@ -155,6 +164,25 @@ const META_OWN_LINE = "w-full [&>span:first-child>[data-meta-sep]]:hidden";
|
||||
// the line wraps and the meta, or the actions after it, move down instead of squeezing.
|
||||
const META_MIN = "min-w-48 flex-1";
|
||||
|
||||
// The watched toggle's own word on an item: what it last asked for (`seq`, its write), and when — its
|
||||
// click, then the server's last answer to any of its writes.
|
||||
type OwnMark = { status: VideoStatus; seq: number; at: number };
|
||||
|
||||
// One of the toggle's writes was answered. Its answer has just come back as a session mark too (the
|
||||
// write marks before it resolves), so the toggle's word is stamped after it and outranks it; a later
|
||||
// mark from elsewhere still outranks the toggle. The latest write refused, the toggle's word is
|
||||
// dropped and the item shows what the server holds.
|
||||
function settled(marks: Record<string, OwnMark>, id: string, seq: number, ok: boolean) {
|
||||
const own = marks[id];
|
||||
if (!own) return marks;
|
||||
if (!ok && own.seq === seq) {
|
||||
const rest = { ...marks };
|
||||
delete rest[id];
|
||||
return rest;
|
||||
}
|
||||
return { ...marks, [id]: { ...own, at: Date.now() } };
|
||||
}
|
||||
|
||||
export default function PlayerModal({
|
||||
video,
|
||||
startAt,
|
||||
@@ -162,6 +190,7 @@ export default function PlayerModal({
|
||||
startIndex,
|
||||
onClose,
|
||||
onState,
|
||||
onWrite,
|
||||
onRemoveFromList,
|
||||
}: {
|
||||
video: Video;
|
||||
@@ -174,7 +203,13 @@ export default function PlayerModal({
|
||||
queue?: Video[];
|
||||
startIndex?: number;
|
||||
onClose: () => void;
|
||||
onState: (id: string, status: VideoStatus) => void;
|
||||
/** The player's own marks (its watched toggle, the auto-mark at the end), for the item it is on —
|
||||
* named by `video`, which may be none of the host's (a related video played in place). Returns
|
||||
* the write: the toggle weighs its own word at the server's answer, and drops a refused one. */
|
||||
onState: (id: string, status: VideoStatus, video?: Video) => Promise<unknown>;
|
||||
/** A write the related list made itself, for a host that refetches once the player closes and its
|
||||
* writes have landed (the feed's player session). */
|
||||
onWrite?: (write: Promise<unknown>) => void;
|
||||
/** Remove the playing video from the list it was opened from (the Playlists module passes its own
|
||||
* `removeItem`; the feed passes nothing — there is no list to remove it from). Returns whether it
|
||||
* actually happened, because the CONSEQUENCE is the player's: its launch queue is frozen, so it
|
||||
@@ -188,8 +223,6 @@ export default function PlayerModal({
|
||||
const { openChannel } = useNavigationActions();
|
||||
const qc = useQueryClient();
|
||||
const { ref: descFadeRef, style: descFadeStyle } = useScrollFade();
|
||||
// Browser/mouse Back closes the player instead of leaving the page.
|
||||
useBackToClose(onClose);
|
||||
// Freeze the launch queue: the player steps through the SAME filtered + sorted list it was
|
||||
// opened with, for its whole session. The live feed refetches and reorders/drops items under
|
||||
// us — e.g. auto-marking each video watched near its end removes it from a filtered feed — which
|
||||
@@ -230,6 +263,42 @@ export default function PlayerModal({
|
||||
// startAt only applies to the item we opened with; advanced items resume their own pos.
|
||||
const resumeAt =
|
||||
startAt != null && active.id === video.id ? startAt : active.position_seconds || 0;
|
||||
// A related video played in place (the owner's pick) is the item it now is: its progress is
|
||||
// checkpointed, it is marked watched at its end, and its own watched / playlist / download
|
||||
// controls show — while the queue stays where it was, and Back returns to the opened item. It is
|
||||
// the SUBJECT of the player from here down; `active` stays the queue's item, which the related
|
||||
// list, the counter and prev/next belong to. A queue step leaves it.
|
||||
// `startAt` null resumes it where it was left (this session's stored position first); a number is
|
||||
// where the user asked it to start — Restart's 0 — and beats that position.
|
||||
const [related, setRelated] = useState<{ video: Video; startAt: number | null } | null>(null);
|
||||
const [relatedOf, setRelatedOf] = useState(active.id);
|
||||
if (relatedOf !== active.id) {
|
||||
setRelatedOf(active.id);
|
||||
setRelated(null);
|
||||
}
|
||||
// An address that names the item this player opens on (a reload, a bookmark) names its view too: the
|
||||
// related video playing in place over it and the panel's tab come back with it. Read once.
|
||||
const [linked] = useState(() => {
|
||||
const here = linkedPlayer();
|
||||
return here && here.watch === video.id ? here : null;
|
||||
});
|
||||
const linkedRelated = useQuery({
|
||||
queryKey: qk.videoRow(linked?.related ?? ""),
|
||||
queryFn: () => api.videoRow(linked!.related!),
|
||||
enabled: !!linked?.related,
|
||||
retry: false,
|
||||
});
|
||||
const [relatedAdopted, setRelatedAdopted] = useState(false);
|
||||
if (!relatedAdopted && linkedRelated.data) {
|
||||
setRelatedAdopted(true);
|
||||
// Only over the item it was named with: a step of the queue before it arrived left that one.
|
||||
if (active.id === linked?.watch && !related)
|
||||
setRelated({ video: linkedRelated.data, startAt: null });
|
||||
}
|
||||
const subject = related?.video ?? active;
|
||||
const subjectResume = related
|
||||
? (related.startAt ?? related.video.position_seconds ?? 0)
|
||||
: resumeAt;
|
||||
const mountRef = useRef<HTMLDivElement | null>(null);
|
||||
const playerRef = useRef<YTPlayer | null>(null);
|
||||
// Keyboard/wheel controls. We keep focus on the modal card (not the cross-origin player
|
||||
@@ -245,11 +314,16 @@ export default function PlayerModal({
|
||||
// useYtNativeControls, useYtBigView) where a fresh identity each render would spread into their
|
||||
// dep lists too.
|
||||
const focusModal = useCallback(() => cardRef.current?.focus(), []);
|
||||
// The player's place on the layer stack (registered below), for what must defer to a layer above.
|
||||
const layerIdRef = useRef<number | null>(null);
|
||||
// What the player does on its own (turning ready, the pointer leaving the video, the window
|
||||
// regaining focus, a wheel over it, leaving fullscreen) takes the focus back only when it may have
|
||||
// slipped into the iframe or off the card. Taking it off a control the viewer tabbed to restarted
|
||||
// their Tab from the first button.
|
||||
// their Tab from the first button. Nor while a layer that owns the keyboard is open above the
|
||||
// player (the related drawer, a dialog): its focus is outside the card by design, and the window
|
||||
// regaining focus pulled it onto the card behind the scrim.
|
||||
const reclaimFocus = useCallback(() => {
|
||||
if (layerIdRef.current != null && anyBlockingLayerAbove(layerIdRef.current)) return;
|
||||
const card = cardRef.current;
|
||||
const active = document.activeElement;
|
||||
if (
|
||||
@@ -345,7 +419,7 @@ export default function PlayerModal({
|
||||
// currently-playing id may differ from the active item.
|
||||
const [currentVideoId, setCurrentVideoId] = useState(active.id);
|
||||
const currentIdRef = useRef(active.id);
|
||||
const navigated = currentVideoId !== active.id;
|
||||
const navigated = currentVideoId !== subject.id;
|
||||
// Clip mode: the range being marked of the video that is playing, or null. Its panel sits under
|
||||
// the video, which is its preview; another video starts without one.
|
||||
const [clip, setClip] = useState<ClipRange | null>(null);
|
||||
@@ -365,7 +439,7 @@ export default function PlayerModal({
|
||||
// The picture the crop frame is drawn on. The iframe never tells its video's size: a short is
|
||||
// 9:16, anything else is taken as the player's 16:9, and the cut fits the frame to the real picture
|
||||
// (downloads/clip) — so a 4:3 video's frame drawn over its bars loses only what lies on the bars.
|
||||
const picture = !navigated && active.is_short ? 9 / 16 : 16 / 9;
|
||||
const picture = !navigated && subject.is_short ? 9 / 16 : 16 / 9;
|
||||
// The docked clip panel's height, measured (it wraps with the window and the text size): the video
|
||||
// above it ends there.
|
||||
const clipDockRef = useRef<HTMLDivElement>(null);
|
||||
@@ -482,7 +556,7 @@ export default function PlayerModal({
|
||||
// Title/author of a navigated-to video, read from the player (free, no API call).
|
||||
const [liveData, setLiveData] = useState<{ title?: string; author?: string } | null>(null);
|
||||
// What is playing, by name: the panel's title, and the dialog's name (`titleId`) in either layout.
|
||||
const heading = navigated ? (liveData?.title ?? t("player.loading")) : active.title;
|
||||
const heading = navigated ? (liveData?.title ?? t("player.loading")) : subject.title;
|
||||
// IFrame Player API error code, when the current video can't play in the embed (e.g. an
|
||||
// auto-generated Topic "Art Track" with embedding disabled → 101/150, or removed/private →
|
||||
// 100). We overlay a friendly message + "Open on YouTube" instead of YouTube's bare error.
|
||||
@@ -493,9 +567,13 @@ export default function PlayerModal({
|
||||
const loadVideo = useStableCallback((id: string, start: number | null) => {
|
||||
const p = playerRef.current;
|
||||
if (!p || typeof p.loadVideoById !== "function") return;
|
||||
// Explicit start wins; otherwise resume the active item, start others at 0.
|
||||
// Explicit start wins; otherwise resume the item the player is on, start others at 0.
|
||||
const startSeconds =
|
||||
start != null ? start : id === active.id ? (sessionPosRef.current.get(id) ?? resumeAt) : 0;
|
||||
start != null
|
||||
? start
|
||||
: id === subject.id
|
||||
? (sessionPosRef.current.get(id) ?? subjectResume)
|
||||
: 0;
|
||||
setPlayerError(null);
|
||||
p.loadVideoById({ videoId: id, startSeconds: startSeconds || 0 });
|
||||
currentIdRef.current = id;
|
||||
@@ -504,23 +582,41 @@ export default function PlayerModal({
|
||||
});
|
||||
|
||||
// Local mirror of watch status so the toggle reacts instantly; changes are propagated to the feed
|
||||
// (and server) via onState. The mirror carries the id it DESCRIBES, and a write for any other id
|
||||
// is ignored rather than displayed — that is the enforcement, and it has to be in code because
|
||||
// one writer arrives late by construction: useYtProgress's cleanup for the OUTGOING item runs
|
||||
// after the commit that already advanced `active`, and near the end of a clip it auto-marks that
|
||||
// item watched (playerModalHooks.ts `maybeAutoWatch`). Keyed, that stray write is simply not this
|
||||
// item's, so the toggle falls back to `active.status` and no ordering has to be argued about.
|
||||
// Unkeyed it landed last and painted the NEXT video as watched; a corrective click then sent
|
||||
// onState(next, "new") for an item that was already new.
|
||||
const [status, setStatus] = useState<{ id: string; value: VideoStatus }>({
|
||||
id: active.id,
|
||||
value: active.status,
|
||||
});
|
||||
const watched = (status.id === active.id ? status.value : active.status) === "watched";
|
||||
// (and server) via onState. Each mark is kept under the id it was MADE for, and that has to be in
|
||||
// code because one writer arrives late by construction: useYtProgress's cleanup for the OUTGOING
|
||||
// item runs after the commit that already advanced `active`, and near the end of a clip it
|
||||
// auto-marks that item watched (playerModalHooks.ts `maybeAutoWatch`). Keyed, that late write is
|
||||
// recorded for the item it belongs to (shown again if the user steps back to it) and never
|
||||
// painted on the next one; unkeyed it landed last and painted the NEXT video as watched, and a
|
||||
// corrective click then sent onState(next, "new") for an item that was already new.
|
||||
// The newest word wins: this toggle's own mark, or one the session confirmed elsewhere since the
|
||||
// player opened (the related row's own menu, a notice's Undo — `useVideoMarks`), else the item as
|
||||
// it was opened. The toggle alone missed those, and its first click re-sent the same status.
|
||||
// The toggle's own writes come back as session marks too, stamped at their answer, so a click
|
||||
// weighed only at its own time lost to the late answer of the click before it: each answer stamps
|
||||
// the toggle's word again (`settled`). A refused one is dropped, so the toggle does not keep showing
|
||||
// what the server turned down.
|
||||
const [marks, setMarks] = useState<Record<string, OwnMark>>({});
|
||||
const ownSeq = useRef(0);
|
||||
const [openedAt] = useState(() => Date.now());
|
||||
const sessionMarks = useVideoMarks();
|
||||
const own = marks[subject.id];
|
||||
const confirmed = markedValue(sessionMarks, subject.id, "status");
|
||||
const elsewhere = confirmed && confirmed.at >= openedAt ? confirmed : undefined;
|
||||
const status =
|
||||
own && (!elsewhere || own.at >= elsewhere.at)
|
||||
? own.status
|
||||
: (elsewhere?.value ?? subject.status);
|
||||
const watched = status === "watched";
|
||||
const setWatched = (on: boolean) => {
|
||||
const id = subject.id;
|
||||
const next = on ? "watched" : "new";
|
||||
setStatus({ id: active.id, value: next });
|
||||
onState(active.id, next);
|
||||
const seq = ++ownSeq.current;
|
||||
setMarks((m) => ({ ...m, [id]: { status: next, seq, at: Date.now() } }));
|
||||
Promise.resolve(onState(id, next, subject)).then(
|
||||
() => setMarks((m) => settled(m, id, seq, true)),
|
||||
() => setMarks((m) => settled(m, id, seq, false)),
|
||||
);
|
||||
};
|
||||
|
||||
// On queue advance (active changes), point `currentVideoId` at the new item — DURING that render,
|
||||
@@ -531,9 +627,9 @@ export default function PlayerModal({
|
||||
// The watch status is NOT synced here: it is keyed by id above, which is both stale-proof and
|
||||
// immune to the late writer this block cannot see (see that comment).
|
||||
const [syncedTo, setSyncedTo] = useState(active.id);
|
||||
if (syncedTo !== active.id) {
|
||||
setSyncedTo(active.id);
|
||||
setCurrentVideoId(active.id);
|
||||
if (syncedTo !== subject.id) {
|
||||
setSyncedTo(subject.id);
|
||||
setCurrentVideoId(subject.id);
|
||||
}
|
||||
|
||||
// `currentIdRef` must NOT move into the block above, and the reason is EFFECT ORDERING, which the
|
||||
@@ -547,8 +643,8 @@ export default function PlayerModal({
|
||||
// frozen launch queue's stale position — which is the exact bug the session-position map exists
|
||||
// to prevent (748 instead of 830, in the test's numbers).
|
||||
useEffect(() => {
|
||||
currentIdRef.current = active.id;
|
||||
}, [active.id]);
|
||||
currentIdRef.current = subject.id;
|
||||
}, [subject.id]);
|
||||
|
||||
const seekTo = useStableCallback((seconds: number) => {
|
||||
const p = playerRef.current;
|
||||
@@ -640,6 +736,8 @@ export default function PlayerModal({
|
||||
if (clipOpenRef.current) return;
|
||||
const { autoMode: a, loopMode: l } = modeRef.current;
|
||||
if (l === "one") return replayCurrent();
|
||||
// A related video's end is not the queue's: the list beside it is where the next one is picked.
|
||||
if (related) return;
|
||||
const { queue: q, index: i } = navRef.current;
|
||||
if (!q || q.length === 0) return;
|
||||
const wrap = l === "all";
|
||||
@@ -669,6 +767,46 @@ export default function PlayerModal({
|
||||
// a tablet could not read a description at all. Anchored ABOVE, so it grows upward over the player
|
||||
// rather than off-screen; `flip` still rescues it when there is no room up there.
|
||||
const [showDesc, setShowDesc] = useState(false);
|
||||
// The related videos, on demand (the owner's pick: the modal has little room to spare). Wide, they
|
||||
// take the side panel's place of the description, a tab beside it; stacked, a drawer over the video
|
||||
// opened from a button beside the ⓘ. The list is the OPENED video's: one played from it leaves the
|
||||
// list in place, to try the next one (the owner's pick).
|
||||
const [panelTab, setPanelTab] = useState<PlayerPanelTab>(linked?.panel ?? "description");
|
||||
const [relatedOpen, setRelatedOpen] = useState(false);
|
||||
// The drawer is the stacked layout's: going wide while it is open, the list moves into the panel's
|
||||
// tab instead. Left open, it reopened unasked when the window narrowed again.
|
||||
if (wide && relatedOpen) {
|
||||
setRelatedOpen(false);
|
||||
setPanelTab("related");
|
||||
}
|
||||
const panelTabs = useTabPanel();
|
||||
// Browser/mouse Back closes the player instead of leaving the page. Its entry's address names what
|
||||
// it plays (the queue's item, a related one over it) and the wide panel's tab, so a reload or a
|
||||
// bookmark reopens it as it is; the page's own entry under it never carries them.
|
||||
useBackToClose(
|
||||
onClose,
|
||||
playerParamUpdates({
|
||||
watch: active.id,
|
||||
related: related?.video.id ?? null,
|
||||
panel: wide ? panelTab : "description",
|
||||
}),
|
||||
);
|
||||
// Turned off on this instance (a daily limit of 0): no tab, no button — nothing that could only
|
||||
// be refused.
|
||||
const relatedOn = useMe().related_enabled;
|
||||
const playRelated = (v: Video, startAt: number | null) => {
|
||||
setRelatedOpen(false);
|
||||
// The video already playing (its row stays in the list): a new player for the same id would
|
||||
// never be built (one per video), so a Restart is a seek, and a plain pick just keeps playing.
|
||||
// Unless a description link put another video in the player meanwhile (`navigated`): then the
|
||||
// pick goes back to this one — the seek moved the linked video, and the pick did nothing.
|
||||
if (v.id === subject.id) {
|
||||
if (navigated) loadVideo(subject.id, startAt);
|
||||
else if (startAt != null) seekTo(startAt);
|
||||
return;
|
||||
}
|
||||
setRelated({ video: v, startAt });
|
||||
};
|
||||
const descPop = useAnchoredPopover({
|
||||
open: showDesc,
|
||||
onOpenChange: setShowDesc,
|
||||
@@ -693,10 +831,10 @@ export default function PlayerModal({
|
||||
// over the player by doing so.
|
||||
const overlayOrder = useOverlayOrder();
|
||||
// This player is a dismissable layer: register it so a Modal or popover opened ABOVE it (e.g. the
|
||||
// download dialog, or an anchored menu) takes Escape first and this player defers.
|
||||
const layerIdRef = useRef<number | null>(null);
|
||||
// download dialog, or an anchored menu) takes Escape first and this player defers. Its root lets
|
||||
// the keyboard walk a list inside it (the related videos).
|
||||
useEffect(() => {
|
||||
const id = pushLayer();
|
||||
const id = pushLayer({ root: () => dialogRef.current });
|
||||
layerIdRef.current = id;
|
||||
return () => {
|
||||
removeLayer(id);
|
||||
@@ -705,6 +843,15 @@ export default function PlayerModal({
|
||||
}, []);
|
||||
|
||||
useKeyScope("ytPlayer");
|
||||
// Its keys wait under a layer above it (the drawer, a dialog — see onPlayerKey), so the help sheet
|
||||
// opened there must not list them.
|
||||
useEffect(() => {
|
||||
setScopeCoveredProbe(
|
||||
"ytPlayer",
|
||||
() => layerIdRef.current != null && anyBlockingLayerAbove(layerIdRef.current),
|
||||
);
|
||||
return () => setScopeCoveredProbe("ytPlayer", null);
|
||||
}, []);
|
||||
|
||||
// Keyboard shortcuts. The chords live in the shared keymap (`ytPlayer`
|
||||
// scope) so the help sheet lists them; only the behaviour behind each id is here.
|
||||
@@ -724,7 +871,9 @@ export default function PlayerModal({
|
||||
// there: deferring would scroll something invisible and leave the viewer with no volume control at
|
||||
// all. Both flags, not just fullscreen: since F stopped taking the browser's lock, maximise is the
|
||||
// common case and checking only `isFullscreen` made the keys dead exactly where they matter most.
|
||||
// On a row of a list in the player (the related videos) the arrows walk the list instead.
|
||||
const volume = (e: KeyboardEvent, up: boolean) => {
|
||||
if (focusInNavList()) return;
|
||||
const covered = isFullscreenRef.current || maximized;
|
||||
if (!covered && canScrollBy(document.activeElement as HTMLElement | null, up ? -1 : 1))
|
||||
return;
|
||||
@@ -732,6 +881,7 @@ export default function PlayerModal({
|
||||
nudgeVolume(up ? 5 : -5);
|
||||
};
|
||||
const seek = (e: KeyboardEvent, secs: number) => {
|
||||
if (focusInNavList()) return;
|
||||
e.preventDefault();
|
||||
nudgeSeek(secs);
|
||||
};
|
||||
@@ -743,6 +893,15 @@ export default function PlayerModal({
|
||||
if (dialogRef.current) trapTab(e, dialogRef.current, cardRef.current);
|
||||
return;
|
||||
}
|
||||
// A layer that owns the keyboard above the player (the related drawer, a menu, a dialog) has the
|
||||
// keys: on its ✕ the arrows changed the volume and seeked the video behind it. Escape is the
|
||||
// exception, and `close` decides for itself which layer it closes.
|
||||
if (
|
||||
e.key !== "Escape" &&
|
||||
layerIdRef.current != null &&
|
||||
anyBlockingLayerAbove(layerIdRef.current)
|
||||
)
|
||||
return;
|
||||
dispatch(e, "ytPlayer", {
|
||||
clip: () => {
|
||||
if (clip) closeClip();
|
||||
@@ -817,8 +976,9 @@ export default function PlayerModal({
|
||||
// the end — recreated per active item. The once-bound event closures read fresh queue/mode/volume via
|
||||
// the refs passed in. See lib/playerModalHooks.
|
||||
useYtProgress({
|
||||
activeId: active.id,
|
||||
resumeAt,
|
||||
activeId: subject.id,
|
||||
resumeAt: subjectResume,
|
||||
exactStart: related?.startAt != null,
|
||||
mountRef,
|
||||
playerRef,
|
||||
currentIdRef,
|
||||
@@ -1030,9 +1190,9 @@ export default function PlayerModal({
|
||||
{/* Both work in fullscreen now: add-to-playlist's popover and download's Modal both
|
||||
portal into the fullscreen element rather than <body> (a body-portaled node is
|
||||
painted underneath the element holding the lock, i.e. invisible). */}
|
||||
{!navigated && <AddToPlaylist videoId={active.id} variant="overlay" />}
|
||||
{!navigated && <AddToPlaylist videoId={subject.id} variant="overlay" />}
|
||||
{!navigated && (
|
||||
<DownloadButton videoId={active.id} title={active.title} variant="overlay" />
|
||||
<DownloadButton videoId={subject.id} title={subject.title} variant="overlay" />
|
||||
)}
|
||||
{/* Clip mode here: the clip panel takes this bar's place. */}
|
||||
{playerError == null && (
|
||||
@@ -1212,7 +1372,7 @@ export default function PlayerModal({
|
||||
</div>
|
||||
)}
|
||||
{hasQueue && (
|
||||
<div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-1.5 px-4 py-2 border-b border-border text-sm">
|
||||
<div className="flex flex-wrap items-center justify-center gap-x-2 gap-y-1.5 px-4 py-2 border-b border-border text-sm">
|
||||
<PlayerTransportControls
|
||||
variant="modal"
|
||||
index={index}
|
||||
@@ -1245,11 +1405,36 @@ export default function PlayerModal({
|
||||
<Info />
|
||||
</IconButton>
|
||||
)}
|
||||
{navigated && (
|
||||
{!wide && relatedOn && (
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
onClick={() => setRelatedOpen(true)}
|
||||
aria-expanded={relatedOpen}
|
||||
label={t("player.related.title")}
|
||||
>
|
||||
<ListVideo />
|
||||
</IconButton>
|
||||
)}
|
||||
{/* Inside the card, whose click stops at its edge: a portal's events still bubble
|
||||
along the React tree, and from the backdrop a click on a row closed the player. */}
|
||||
{relatedOpen && !wide && (
|
||||
<Modal
|
||||
title={t("player.related.title")}
|
||||
onClose={() => setRelatedOpen(false)}
|
||||
placement="drawer"
|
||||
maxWidth="max-w-sm"
|
||||
initialFocus="close"
|
||||
>
|
||||
<RelatedVideos videoId={active.id} onPlay={playRelated} onWrite={onWrite} />
|
||||
</Modal>
|
||||
)}
|
||||
{(navigated || related) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => loadVideo(active.id, null)}
|
||||
// One step back: from a linked video to the one it was linked from, from a
|
||||
// related video to the opened item.
|
||||
onClick={() => (navigated ? loadVideo(subject.id, null) : setRelated(null))}
|
||||
title={t("player.backToOriginal")}
|
||||
icon={<ArrowLeft />}
|
||||
>
|
||||
@@ -1282,8 +1467,8 @@ export default function PlayerModal({
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 mt-3">
|
||||
{!navigated && (
|
||||
<Avatar
|
||||
src={active.channel_thumbnail}
|
||||
fallback={active.channel_title ?? ""}
|
||||
src={subject.channel_thumbnail}
|
||||
fallback={subject.channel_title ?? ""}
|
||||
className="w-9 h-9 rounded-full shrink-0"
|
||||
/>
|
||||
)}
|
||||
@@ -1309,19 +1494,19 @@ export default function PlayerModal({
|
||||
className={`flex items-center gap-1.5 min-w-0 ${wide ? "flex-1" : "shrink-0"}`}
|
||||
>
|
||||
<ChannelNameLink
|
||||
channelId={active.channel_id}
|
||||
title={active.channel_title}
|
||||
channelId={subject.channel_id}
|
||||
title={subject.channel_title}
|
||||
onOpenInApp={() => {
|
||||
// openChannel closes this player first and pushes only once its
|
||||
// Back-to-close entry is reclaimed — otherwise that reclaim undoes the push
|
||||
// and clicking the name merely closes the player
|
||||
// (lib/history.closeOverlaysThenNavigate).
|
||||
openChannel(active.channel_id, active.channel_title ?? undefined);
|
||||
openChannel(subject.channel_id, subject.channel_title ?? undefined);
|
||||
}}
|
||||
className="font-medium hover:text-accent truncate text-left"
|
||||
/>
|
||||
<IconLink
|
||||
href={active.channel_url}
|
||||
href={subject.channel_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
label={t("channels.row.openOnYouTube")}
|
||||
@@ -1335,27 +1520,27 @@ export default function PlayerModal({
|
||||
<div
|
||||
className={`flex flex-wrap items-center gap-x-2 gap-y-0.5 text-sm text-muted ${wide ? META_OWN_LINE : META_MIN}`}
|
||||
>
|
||||
{active.view_count != null && (
|
||||
{subject.view_count != null && (
|
||||
<span>
|
||||
{metaSep}
|
||||
{t("player.views", {
|
||||
count: active.view_count,
|
||||
formattedCount: formatCompact(active.view_count, lang),
|
||||
count: subject.view_count,
|
||||
formattedCount: formatCompact(subject.view_count, lang),
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
<span>
|
||||
{metaSep}
|
||||
{relativeTime(active.published_at, lang, t)}
|
||||
{active.published_at && ` · ${fullDate(active.published_at)}`}
|
||||
{relativeTime(subject.published_at, lang, t)}
|
||||
{subject.published_at && ` · ${fullDate(subject.published_at)}`}
|
||||
</span>
|
||||
{active.duration_seconds != null && (
|
||||
{subject.duration_seconds != null && (
|
||||
<span>
|
||||
{metaSep}
|
||||
{formatDuration(active.duration_seconds)}
|
||||
{formatDuration(subject.duration_seconds)}
|
||||
</span>
|
||||
)}
|
||||
{active.live_status === "was_live" && (
|
||||
{subject.live_status === "was_live" && (
|
||||
<span className="bg-accent text-accent-fg text-3xs font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded-sm">
|
||||
{t("player.stream")}
|
||||
</span>
|
||||
@@ -1408,10 +1593,10 @@ export default function PlayerModal({
|
||||
>
|
||||
<Maximize />
|
||||
</IconButton>
|
||||
<AddToPlaylist videoId={active.id} variant="outline" size="md" />
|
||||
<AddToPlaylist videoId={subject.id} variant="outline" size="md" />
|
||||
<DownloadButton
|
||||
videoId={active.id}
|
||||
title={active.title}
|
||||
videoId={subject.id}
|
||||
title={subject.title}
|
||||
variant="outline"
|
||||
size="md"
|
||||
/>
|
||||
@@ -1428,7 +1613,16 @@ export default function PlayerModal({
|
||||
<Scissors />
|
||||
</IconButton>
|
||||
)}
|
||||
{onRemoveFromList && (
|
||||
<IconButton
|
||||
variant="outline"
|
||||
size="md"
|
||||
pressed={watched}
|
||||
onClick={() => setWatched(!watched)}
|
||||
label={watched ? t("player.watchedUnmark") : t("player.markWatched")}
|
||||
>
|
||||
{watched ? <CheckCheck /> : <Check />}
|
||||
</IconButton>
|
||||
{onRemoveFromList && !related && (
|
||||
<IconButton
|
||||
variant="outline-danger"
|
||||
size="md"
|
||||
@@ -1441,20 +1635,10 @@ export default function PlayerModal({
|
||||
<Trash2 />
|
||||
</IconButton>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
pressed={watched}
|
||||
onClick={() => setWatched(!watched)}
|
||||
title={watched ? t("player.watchedUnmark") : t("player.markWatched")}
|
||||
icon={watched ? <CheckCheck /> : <Check />}
|
||||
>
|
||||
{watched ? t("player.watched") : t("player.markWatched")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{wide && (
|
||||
{wide && !relatedOn && (
|
||||
<section className="mt-5" data-testid="player-description">
|
||||
<SectionLabel level={3} className="mb-2">
|
||||
{t("player.description")}
|
||||
@@ -1466,6 +1650,43 @@ export default function PlayerModal({
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
{wide && relatedOn && (
|
||||
<div className="mt-5">
|
||||
{/* The class replaces Tabs' own, so it keeps the row's layout and gap with
|
||||
its tighter margin. */}
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ id: "description", label: t("player.description") },
|
||||
{ id: "related", label: t("player.related.title") },
|
||||
]}
|
||||
active={panelTab}
|
||||
onChange={(id) => setPanelTab(id === "related" ? "related" : "description")}
|
||||
idBase={panelTabs.idBase}
|
||||
label={t("player.panelTabs")}
|
||||
className="flex flex-wrap gap-1 mb-3"
|
||||
/>
|
||||
<div {...panelTabs.panelProps(panelTab)}>
|
||||
{panelTab === "description" ? (
|
||||
<section data-testid="player-description">
|
||||
<PlayerDescription
|
||||
className="text-sm whitespace-pre-wrap wrap-break-word leading-relaxed"
|
||||
clamp
|
||||
{...descriptionProps}
|
||||
/>
|
||||
</section>
|
||||
) : (
|
||||
// Out into the panel's padding: in 20rem, every rem is the title's.
|
||||
<div className="-mx-3">
|
||||
<RelatedVideos
|
||||
videoId={active.id}
|
||||
onPlay={playRelated}
|
||||
onWrite={onWrite}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// The URL is the view: the YouTube player names what it plays in its own history entry — the item of
|
||||
// the queue, a related video played in place over it, the wide panel's tab — so a reload or a bookmark
|
||||
// reopens it as it was, and Back lands on the page's address without it. Its own file: the overlay
|
||||
// history is module state, and these read the address the closed players of other tests step back over.
|
||||
//
|
||||
// `window.YT` is a fake installed before the player's API loader first runs (see PlayerModal.dom.test).
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("react-i18next")>()),
|
||||
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
|
||||
}));
|
||||
vi.mock("../navigation/navigationContext", () => ({
|
||||
useNavigationActions: () => ({ openChannel: vi.fn() }),
|
||||
}));
|
||||
vi.mock("../video/AddToPlaylist", () => ({ default: () => null }));
|
||||
vi.mock("../downloads/DownloadButton", () => ({ default: () => null }));
|
||||
|
||||
import PlayerModal from "./PlayerModal";
|
||||
import { api, type Me, type Video } from "../../lib/api";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
|
||||
beforeAll(() => {
|
||||
class Stub {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
takeRecords() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
globalThis.ResizeObserver ??= Stub as unknown as typeof ResizeObserver;
|
||||
globalThis.IntersectionObserver ??= Stub as unknown as typeof IntersectionObserver;
|
||||
});
|
||||
|
||||
const started: { videoId: string; start: number | undefined }[] = [];
|
||||
let playerEvents: { onReady?: () => void } = {};
|
||||
const fakePlayer = new Proxy(
|
||||
{ getCurrentTime: () => 0, getDuration: () => 3000, getVideoData: () => null },
|
||||
{ get: (t, k) => (k in t ? t[k as keyof typeof t] : k === "then" ? undefined : () => undefined) },
|
||||
);
|
||||
window.YT = {
|
||||
Player: function (
|
||||
_el: unknown,
|
||||
opts: { videoId: string; playerVars: { start?: number }; events?: typeof playerEvents },
|
||||
) {
|
||||
started.push({ videoId: opts.videoId, start: opts.playerVars.start });
|
||||
playerEvents = opts.events ?? {};
|
||||
return fakePlayer;
|
||||
} as never,
|
||||
};
|
||||
const lastStart = () => started[started.length - 1];
|
||||
|
||||
const vid = (id: string, position_seconds = 0): Video =>
|
||||
({
|
||||
id,
|
||||
title: `Video ${id}`,
|
||||
channel_id: "UCx",
|
||||
channel_title: "Channel",
|
||||
status: "new",
|
||||
position_seconds,
|
||||
duration_seconds: 3000,
|
||||
watch_url: `https://www.youtube.com/watch?v=${id}`,
|
||||
}) as unknown as Video;
|
||||
const related = (id: string, position_seconds = 0) => ({
|
||||
...vid(id, position_seconds),
|
||||
followed: false,
|
||||
});
|
||||
|
||||
// The wide layout (the side panel with its tabs): jsdom has no matchMedia, so one is put in.
|
||||
function wideWindow() {
|
||||
window.matchMedia = ((q: string) => ({
|
||||
matches: q === "(min-width: 1280px)",
|
||||
media: q,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
})) as unknown as typeof window.matchMedia;
|
||||
}
|
||||
|
||||
function renderModal(video: Video, queue: Video[]) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
qc.setQueryData(qk.me(), { related_enabled: true } as Me);
|
||||
return render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<PlayerModal
|
||||
video={video}
|
||||
queue={queue}
|
||||
onClose={() => {}}
|
||||
onState={() => Promise.resolve()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
// A closed player steps back over its entry a task later (jsdom's back(), like a browser's).
|
||||
async function closeAndLand(unmount: () => void) {
|
||||
const landed = new Promise((r) => window.addEventListener("popstate", r, { once: true }));
|
||||
unmount();
|
||||
await act(() => landed);
|
||||
}
|
||||
|
||||
const here = () => new URLSearchParams(window.location.search);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(api, "videoDetail").mockReturnValue(new Promise(() => {}));
|
||||
vi.spyOn(api, "related").mockResolvedValue({
|
||||
items: [related("rel1"), related("rel2", 120)],
|
||||
has_more: false,
|
||||
next_cursor: null,
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
delete (window as { matchMedia?: unknown }).matchMedia;
|
||||
started.length = 0;
|
||||
});
|
||||
|
||||
describe("the player's address", () => {
|
||||
it("names the item playing now in its own entry, a step of the queue too", async () => {
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?q=talks");
|
||||
const r = renderModal(vid("A"), [vid("A"), vid("B")]);
|
||||
await waitFor(() => expect(here().get("watch")).toBe("A"));
|
||||
expect(here().get("q")).toBe("talks");
|
||||
fireEvent.click(screen.getAllByRole("button", { name: "player.next" })[0]!);
|
||||
await waitFor(() => expect(here().get("watch")).toBe("B"));
|
||||
await closeAndLand(r.unmount);
|
||||
expect(window.location.search).toBe("?q=talks");
|
||||
});
|
||||
|
||||
it("wide: names the related video playing over it and the panel's tab, and Back drops it", async () => {
|
||||
wideWindow();
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/");
|
||||
const r = renderModal(vid("A", 40), [vid("A", 40)]);
|
||||
act(() => playerEvents.onReady?.());
|
||||
fireEvent.click(screen.getByRole("tab", { name: "player.related.title" }));
|
||||
await waitFor(() => expect(here().get("wtab")).toBe("related"));
|
||||
const rows = await screen.findAllByRole("link", { name: "Video rel2" });
|
||||
fireEvent.click(rows.find((a) => a.hasAttribute("data-nav-open"))!);
|
||||
await waitFor(() => expect(here().get("wrel")).toBe("rel2"));
|
||||
expect(here().get("watch")).toBe("A");
|
||||
fireEvent.click(screen.getByRole("button", { name: "player.back" }));
|
||||
await waitFor(() => expect(here().has("wrel")).toBe(false));
|
||||
expect(here().get("watch")).toBe("A");
|
||||
await closeAndLand(r.unmount);
|
||||
expect(window.location.search).toBe("");
|
||||
});
|
||||
|
||||
it("wide: a link's related video and panel tab come back over the item it names", async () => {
|
||||
wideWindow();
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?watch=A&wrel=rel2&wtab=related");
|
||||
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("rel2", 120));
|
||||
const r = renderModal(vid("A", 40), [vid("A", 40)]);
|
||||
await waitFor(() => expect(lastStart()).toEqual({ videoId: "rel2", start: 120 }));
|
||||
expect(row).toHaveBeenCalledWith("rel2");
|
||||
const tab = screen.getByRole("tab", { name: "player.related.title" });
|
||||
expect(tab.getAttribute("aria-selected")).toBe("true");
|
||||
expect(screen.getByRole("button", { name: "player.back" })).toBeTruthy();
|
||||
expect(here().get("wrel")).toBe("rel2");
|
||||
await closeAndLand(r.unmount);
|
||||
// The entry the link opened at named the player; once the player is gone, so is its name.
|
||||
expect(window.location.search).toBe("");
|
||||
});
|
||||
|
||||
it("a link's related video that arrives after the queue stepped on stays off the next item", async () => {
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?watch=A&wrel=rel2");
|
||||
let arrive: (v: Video) => void = () => {};
|
||||
vi.spyOn(api, "videoRow").mockReturnValue(new Promise<Video>((r) => (arrive = r)));
|
||||
const r = renderModal(vid("A"), [vid("A"), vid("B")]);
|
||||
fireEvent.click(screen.getAllByRole("button", { name: "player.next" })[0]!);
|
||||
await waitFor(() => expect(here().get("watch")).toBe("B"));
|
||||
await act(async () => {
|
||||
arrive(vid("rel2", 120));
|
||||
await new Promise((r) => setTimeout(r, 50)); // the query hands its answer on a tick later
|
||||
});
|
||||
expect(screen.getByRole("heading", { name: "Video B" })).toBeTruthy();
|
||||
expect(here().has("wrel")).toBe(false);
|
||||
await closeAndLand(r.unmount);
|
||||
});
|
||||
|
||||
it("wide: a link naming another item brings none of its view", async () => {
|
||||
wideWindow();
|
||||
window.history.replaceState({ sfPage: "feed" }, "", "/?watch=Z&wrel=rel2&wtab=related");
|
||||
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("rel2", 120));
|
||||
const r = renderModal(vid("A", 40), [vid("A", 40)]);
|
||||
await waitFor(() => expect(here().get("watch")).toBe("A"));
|
||||
expect(row).not.toHaveBeenCalled();
|
||||
expect(here().has("wrel")).toBe(false);
|
||||
expect(here().has("wtab")).toBe(false);
|
||||
expect(lastStart()?.videoId).toBe("A");
|
||||
await closeAndLand(r.unmount);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,410 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// A video's related videos, as the player shows them. What is held: a row says when the user follows
|
||||
// its channel; the region the user picks is asked for and kept on the account; a video marked seen
|
||||
// here leaves the list (and comes back when the server refuses the mark); reading further sends the
|
||||
// cursor; and a failure says so rather than drawing an empty list.
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { FloatingTree } from "@floating-ui/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-i18next")>();
|
||||
return {
|
||||
...actual,
|
||||
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),
|
||||
};
|
||||
});
|
||||
vi.mock("../navigation/navigationContext", () => ({
|
||||
useNavigationActions: () => ({ openChannel: vi.fn() }),
|
||||
}));
|
||||
vi.mock("../video/AddToPlaylist", () => ({ default: () => null }));
|
||||
|
||||
import { RelatedVideos } from "./RelatedVideos";
|
||||
import { api, HttpError, type RelatedVideo, type Video } from "../../lib/api";
|
||||
import { clearAll, getNotifications } from "../../lib/notifications";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
import { setHintsEnabled } from "../../lib/hints";
|
||||
import { writeVideoState } from "../video/videoWrites";
|
||||
|
||||
beforeAll(() => {
|
||||
class Stub {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
takeRecords() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
globalThis.ResizeObserver ??= Stub as unknown as typeof ResizeObserver;
|
||||
globalThis.IntersectionObserver ??= Stub as unknown as typeof IntersectionObserver;
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
clearAll();
|
||||
});
|
||||
|
||||
const row = (id: string, extra: Partial<RelatedVideo> = {}): RelatedVideo =>
|
||||
({
|
||||
id,
|
||||
title: `Video ${id}`,
|
||||
channel_id: `UC${id}`,
|
||||
channel_title: `Channel ${id}`,
|
||||
watch_url: `https://www.youtube.com/watch?v=${id}`,
|
||||
status: "new",
|
||||
saved: false,
|
||||
position_seconds: 0,
|
||||
followed: false,
|
||||
...extra,
|
||||
}) as RelatedVideo;
|
||||
|
||||
const page = (items: RelatedVideo[], next: string | null = null) => ({
|
||||
items,
|
||||
has_more: next != null,
|
||||
next_cursor: next,
|
||||
});
|
||||
|
||||
function setup(
|
||||
onPlay: (v: Video, startAt: number | null) => void = () => {},
|
||||
onWrite?: (write: Promise<unknown>) => void,
|
||||
qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }),
|
||||
) {
|
||||
vi.spyOn(api, "comfortPins").mockResolvedValue({ items: [] } as never);
|
||||
vi.spyOn(api, "downloadIndex").mockResolvedValue({});
|
||||
const saved = vi.spyOn(api, "savePrefs").mockResolvedValue({} as never);
|
||||
render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<FloatingTree>
|
||||
<RelatedVideos videoId="SRC" onPlay={onPlay} onWrite={onWrite} />
|
||||
</FloatingTree>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
return { saved, qc };
|
||||
}
|
||||
|
||||
// A row's title (its picture is a link of the same name).
|
||||
const title = async (name: string) =>
|
||||
(await screen.findAllByRole("link", { name })).find((a) => a.hasAttribute("data-nav-open"))!;
|
||||
const titles = () =>
|
||||
screen
|
||||
.queryAllByRole("link")
|
||||
.filter((a) => a.hasAttribute("data-nav-open"))
|
||||
.map((a) => a.textContent);
|
||||
// The menu's surface is visibility:hidden in jsdom: an item is matched on its text.
|
||||
const menuItem = (label: string) =>
|
||||
screen.queryAllByRole("menuitem", { hidden: true }).find((b) => b.textContent === label)!;
|
||||
|
||||
describe("RelatedVideos", () => {
|
||||
it("marks the rows whose channel the user follows, and only those", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(
|
||||
page([row("A", { followed: true }), row("B"), row("C", { followed: true })]),
|
||||
);
|
||||
setup();
|
||||
await title("Video A");
|
||||
const marks = screen.getAllByRole("img", { name: "player.related.followed" });
|
||||
const owners = marks.map((m) => m.closest("[data-video-id]")?.getAttribute("data-video-id"));
|
||||
expect(owners).toEqual(["A", "C"]);
|
||||
});
|
||||
|
||||
it("asks for the region picked, and keeps the pick on the account", async () => {
|
||||
const asked = vi.spyOn(api, "related").mockResolvedValue(page([row("A")]));
|
||||
const { saved } = setup();
|
||||
await title("Video A");
|
||||
expect(asked.mock.calls).toEqual([["SRC", "topical", null]]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "player.related.hu" }));
|
||||
await waitFor(() => expect(asked.mock.calls).toContainEqual(["SRC", "hu", null]));
|
||||
expect(saved).toHaveBeenCalledWith({ relatedRegion: "hu" });
|
||||
});
|
||||
|
||||
it("sets the region switch at the toolbar rung, not the 10px caption one", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A")]));
|
||||
setup();
|
||||
await title("Video A");
|
||||
const track = screen.getByRole("group", { name: "player.related.region" });
|
||||
expect(track.className).toMatch(/\btext-xs\b/);
|
||||
});
|
||||
|
||||
// A plain pick resumes (null: the player knows the freshest position); the row's own position
|
||||
// travels on the video it hands over.
|
||||
it("plays a row from where the user left it", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A", { position_seconds: 95 })]));
|
||||
const onPlay = vi.fn();
|
||||
setup(onPlay);
|
||||
fireEvent.click(await title("Video A"));
|
||||
expect(onPlay).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: "A", position_seconds: 95 }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
it("drops a video hidden here at once, and brings it back when the server refuses", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A"), row("B")]));
|
||||
let refuse: (e: Error) => void = () => {};
|
||||
const write = vi
|
||||
.spyOn(api, "setState")
|
||||
.mockReturnValue(new Promise((_, reject) => (refuse = reject)) as never);
|
||||
setup();
|
||||
fireEvent.contextMenu((await title("Video A")).closest("[data-video-id]")!);
|
||||
fireEvent.click(menuItem("card.hide"));
|
||||
await waitFor(() => expect(write).toHaveBeenCalledWith("A", "hidden"));
|
||||
expect(titles()).toEqual(["Video B"]);
|
||||
await act(async () => refuse(new Error("offline")));
|
||||
expect(titles()).toEqual(["Video A", "Video B"]);
|
||||
});
|
||||
|
||||
it("keeps a video marked watched out of the list once the server has it", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A"), row("B")]));
|
||||
vi.spyOn(api, "setState").mockResolvedValue(undefined as never);
|
||||
setup();
|
||||
fireEvent.contextMenu((await title("Video B")).closest("[data-video-id]")!);
|
||||
fireEvent.click(menuItem("card.markWatched"));
|
||||
await waitFor(() => expect(titles()).toEqual(["Video A"]));
|
||||
});
|
||||
|
||||
it("reads further with the cursor the last page gave", async () => {
|
||||
const asked = vi
|
||||
.spyOn(api, "related")
|
||||
.mockResolvedValueOnce(page([row("A")], "CUR1"))
|
||||
.mockResolvedValueOnce(page([row("B")]));
|
||||
setup();
|
||||
await title("Video A");
|
||||
fireEvent.click(screen.getByRole("button", { name: "player.related.more" }));
|
||||
await title("Video B");
|
||||
expect(asked.mock.calls[1]).toEqual(["SRC", "topical", "CUR1"]);
|
||||
expect(screen.queryByRole("button", { name: "player.related.more" })).toBeNull();
|
||||
});
|
||||
|
||||
it("says so when YouTube refuses, rather than drawing an empty list", async () => {
|
||||
vi.spyOn(api, "related").mockRejectedValue(
|
||||
new HttpError(422, "YouTube isn't reachable", undefined),
|
||||
);
|
||||
setup();
|
||||
expect((await screen.findByRole("alert")).textContent).toContain("YouTube isn't reachable");
|
||||
expect(screen.queryByText("player.related.empty")).toBeNull();
|
||||
});
|
||||
|
||||
// A deferred answer, settled when the test says.
|
||||
const deferred = () => {
|
||||
let resolve: () => void = () => {};
|
||||
let reject: (e: Error) => void = () => {};
|
||||
const promise = new Promise<never>((res, rej) => {
|
||||
resolve = res as () => void;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
};
|
||||
|
||||
it("keeps a row hidden while its hide is on its way, though an earlier save landed", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A"), row("B")]));
|
||||
const save = deferred();
|
||||
const saving = vi.spyOn(api, "watchLaterAdd").mockReturnValue(save.promise as never);
|
||||
const hide = deferred();
|
||||
const hiding = vi.spyOn(api, "setState").mockReturnValue(hide.promise as never);
|
||||
setup();
|
||||
const card = (await title("Video A")).closest("[data-video-id]")!;
|
||||
fireEvent.contextMenu(card);
|
||||
fireEvent.click(menuItem("card.saveForLater"));
|
||||
await waitFor(() => expect(saving).toHaveBeenCalledWith("A"));
|
||||
fireEvent.contextMenu(card);
|
||||
fireEvent.click(menuItem("card.hide"));
|
||||
await waitFor(() => expect(hiding).toHaveBeenCalledWith("A", "hidden"));
|
||||
expect(titles()).toEqual(["Video B"]);
|
||||
await act(async () => save.resolve());
|
||||
expect(titles()).toEqual(["Video B"]);
|
||||
});
|
||||
|
||||
it("announces a hide with the video it names, for the notification center to find", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A")]));
|
||||
vi.spyOn(api, "setState").mockResolvedValue(undefined as never);
|
||||
const writes: Promise<unknown>[] = [];
|
||||
setup(undefined, (w) => void writes.push(w));
|
||||
fireEvent.contextMenu((await title("Video A")).closest("[data-video-id]")!);
|
||||
fireEvent.click(menuItem("card.hide"));
|
||||
await waitFor(() => expect(getNotifications().length).toBeGreaterThan(0));
|
||||
expect(getNotifications().map((n) => n.meta)).toContainEqual({
|
||||
kind: "video-hidden",
|
||||
videoId: "A",
|
||||
title: "Video A",
|
||||
channelId: "UCA",
|
||||
channelName: "Channel A",
|
||||
});
|
||||
// And the write reached the host's session.
|
||||
expect(writes).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("flips a row's bookmark at once, and back when the server refuses", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A")]));
|
||||
const save = deferred();
|
||||
vi.spyOn(api, "watchLaterAdd").mockReturnValue(save.promise as never);
|
||||
setup();
|
||||
const card = (await title("Video A")).closest("[data-video-id]")!;
|
||||
// What the menu offers is the row's state: un-save once saved.
|
||||
const offers = (label: string) => {
|
||||
fireEvent.contextMenu(card);
|
||||
return !!menuItem(label);
|
||||
};
|
||||
expect(offers("card.saveForLater")).toBe(true);
|
||||
fireEvent.click(menuItem("card.saveForLater"));
|
||||
await waitFor(() => expect(offers("card.menu.unsave")).toBe(true));
|
||||
fireEvent.keyDown(document.activeElement ?? document.body, { key: "Escape" });
|
||||
await act(async () => save.reject(new Error("offline")));
|
||||
await waitFor(() => expect(offers("card.saveForLater")).toBe(true));
|
||||
});
|
||||
|
||||
it("is kept for the session, not collected when the list closes", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A")]));
|
||||
const { qc } = setup();
|
||||
await title("Video A");
|
||||
const [cached] = qc.getQueryCache().findAll({ queryKey: qk.related() });
|
||||
expect(cached!.options.gcTime).toBe(Infinity);
|
||||
});
|
||||
|
||||
it("says the next page failed under the rows it has, and retries that page", async () => {
|
||||
const asked = vi
|
||||
.spyOn(api, "related")
|
||||
.mockResolvedValueOnce(page([row("A")], "CUR1"))
|
||||
.mockRejectedValueOnce(new HttpError(422, "YouTube isn't reachable", undefined))
|
||||
.mockResolvedValueOnce(page([row("B")]));
|
||||
setup();
|
||||
await title("Video A");
|
||||
fireEvent.click(screen.getByRole("button", { name: "player.related.more" }));
|
||||
expect((await screen.findByRole("alert")).textContent).toContain("YouTube isn't reachable");
|
||||
expect(titles()).toEqual(["Video A"]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "common.retry" }));
|
||||
await title("Video B");
|
||||
expect(asked.mock.calls.map((c) => c[2])).toEqual([null, "CUR1", "CUR1"]);
|
||||
});
|
||||
|
||||
it("with nothing unseen read so far, says so above Show more, and retries the page it failed", async () => {
|
||||
const asked = vi
|
||||
.spyOn(api, "related")
|
||||
.mockResolvedValueOnce(page([], "CUR1"))
|
||||
.mockRejectedValueOnce(new HttpError(422, "YouTube isn't reachable", undefined))
|
||||
.mockResolvedValueOnce(page([row("B")]));
|
||||
setup();
|
||||
expect(await screen.findByText("player.related.emptySoFar")).toBeTruthy();
|
||||
expect(screen.queryByText("player.related.empty")).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "player.related.more" }));
|
||||
await screen.findByRole("alert");
|
||||
fireEvent.click(screen.getByRole("button", { name: "common.retry" }));
|
||||
await title("Video B");
|
||||
expect(asked.mock.calls.map((c) => c[2])).toEqual([null, "CUR1", "CUR1"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["the day's cap", { code: "refused", reason: "related_daily_limit", limit: 5 }],
|
||||
["turned off", { code: "refused", reason: "related_disabled" }],
|
||||
["the shared budget", { code: "youtube", reason: "quota" }],
|
||||
])("offers no retry a retry cannot answer: %s", async (_name, detail) => {
|
||||
vi.spyOn(api, "related").mockRejectedValue(new HttpError(429, "Refused", detail));
|
||||
setup();
|
||||
expect((await screen.findByRole("alert")).textContent).toContain("Refused");
|
||||
expect(screen.queryByRole("button", { name: "common.retry" })).toBeNull();
|
||||
});
|
||||
|
||||
it("offers a retry where trying again can help", async () => {
|
||||
vi.spyOn(api, "related").mockRejectedValue(
|
||||
new HttpError(422, "YouTube isn't reachable", { code: "youtube", reason: "unavailable" }),
|
||||
);
|
||||
setup();
|
||||
await screen.findByRole("alert");
|
||||
expect(screen.getByRole("button", { name: "common.retry" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("names the followed mark on hover", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A", { followed: true })]));
|
||||
setup();
|
||||
await title("Video A");
|
||||
const mark = screen.getByRole("img", { name: "player.related.followed" });
|
||||
fireEvent.mouseEnter(mark.parentElement!);
|
||||
fireEvent.pointerEnter(mark.parentElement!, { pointerType: "mouse" });
|
||||
expect(await screen.findByText("player.related.followed")).toBeTruthy();
|
||||
});
|
||||
|
||||
// An infinite query builds its next page from the pages it read when that fetch started: a mark
|
||||
// that landed in between was dropped with them, for the session.
|
||||
it("keeps a hide that landed while Show more was on its way", async () => {
|
||||
let land: (p: ReturnType<typeof page>) => void = () => {};
|
||||
vi.spyOn(api, "related")
|
||||
.mockResolvedValueOnce(page([row("A"), row("C")], "CUR1"))
|
||||
.mockReturnValueOnce(new Promise((r) => (land = r)) as never);
|
||||
const write = vi.spyOn(api, "setState").mockResolvedValue({ ok: true } as never);
|
||||
setup();
|
||||
await title("Video A");
|
||||
fireEvent.click(screen.getByRole("button", { name: "player.related.more" }));
|
||||
fireEvent.contextMenu((await title("Video A")).closest("[data-video-id]")!);
|
||||
fireEvent.click(menuItem("card.hide"));
|
||||
await waitFor(() => expect(write).toHaveBeenCalledWith("A", "hidden"));
|
||||
await act(async () => {});
|
||||
await act(async () => land(page([row("B")])));
|
||||
await title("Video B");
|
||||
expect(titles()).toEqual(["Video C", "Video B"]);
|
||||
});
|
||||
|
||||
// Hidden in this session, then un-hidden on another device: a list read after the mark carries
|
||||
// the server's word, and the mark does not paint over it.
|
||||
it("shows a list read after a mark as the server has it", async () => {
|
||||
vi.spyOn(api, "setState").mockResolvedValue({ ok: true } as never);
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A"), row("B")]));
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
await writeVideoState(qc, "A", "hidden");
|
||||
await new Promise((r) => setTimeout(r, 5)); // the list is read a moment after the mark
|
||||
setup(undefined, undefined, qc);
|
||||
await title("Video B");
|
||||
expect(titles()).toEqual(["Video A", "Video B"]);
|
||||
});
|
||||
|
||||
// The Notification Center's undo, the feed's reset, a card elsewhere: every write reaches it.
|
||||
it("follows a video's state written anywhere else", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A"), row("B")]));
|
||||
vi.spyOn(api, "setState").mockResolvedValue({ ok: true } as never);
|
||||
const { qc } = setup();
|
||||
await title("Video A");
|
||||
await act(async () => void (await writeVideoState(qc, "A", "hidden")));
|
||||
await waitFor(() => expect(titles()).toEqual(["Video B"]));
|
||||
await act(async () => void (await writeVideoState(qc, "A", "new")));
|
||||
await waitFor(() => expect(titles()).toEqual(["Video A", "Video B"]));
|
||||
});
|
||||
|
||||
// Show more is the request Retry would make: refused for good, it is not offered either.
|
||||
it("offers no Show more once the next page was refused for good", async () => {
|
||||
vi.spyOn(api, "related")
|
||||
.mockResolvedValueOnce(page([row("A")], "CUR1"))
|
||||
.mockRejectedValueOnce(
|
||||
new HttpError(429, "Limit", { code: "refused", reason: "related_daily_limit", limit: 3 }),
|
||||
);
|
||||
setup();
|
||||
await title("Video A");
|
||||
fireEvent.click(screen.getByRole("button", { name: "player.related.more" }));
|
||||
expect((await screen.findByRole("alert")).textContent).toContain("Limit");
|
||||
expect(screen.queryByRole("button", { name: "player.related.more" })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "common.retry" })).toBeNull();
|
||||
expect(titles()).toEqual(["Video A"]);
|
||||
});
|
||||
|
||||
it("names the followed mark on hover with hints turned off too", async () => {
|
||||
setHintsEnabled(false);
|
||||
try {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([row("A", { followed: true })]));
|
||||
setup();
|
||||
await title("Video A");
|
||||
const mark = screen.getByRole("img", { name: "player.related.followed" });
|
||||
fireEvent.mouseEnter(mark.parentElement!);
|
||||
fireEvent.pointerEnter(mark.parentElement!, { pointerType: "mouse" });
|
||||
expect(await screen.findByText("player.related.followed")).toBeTruthy();
|
||||
} catch (e) {
|
||||
setHintsEnabled(true);
|
||||
throw e;
|
||||
}
|
||||
setHintsEnabled(true);
|
||||
});
|
||||
|
||||
it("says when nothing is left that the user has not seen", async () => {
|
||||
vi.spyOn(api, "related").mockResolvedValue(page([]));
|
||||
setup();
|
||||
expect(await screen.findByText("player.related.empty")).toBeTruthy();
|
||||
expect(screen.queryByRole("alert")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { CircleCheck } from "lucide-react";
|
||||
|
||||
import {
|
||||
api,
|
||||
HttpError,
|
||||
refusalReason,
|
||||
type RelatedRegion,
|
||||
type Video,
|
||||
type VideoStatus,
|
||||
} from "../../lib/api";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
import { nextPageOnClick } from "../../lib/nextPage";
|
||||
import { usePref, type UsePrefOptions } from "../../lib/usePref";
|
||||
import { markedRows, stampFetch, useVideoMarks } from "../../lib/progressCache";
|
||||
import { notifyActionError } from "../../lib/actionErrors";
|
||||
import { Button } from "../../components/ui/Button";
|
||||
import SegmentedToggle from "../../components/ui/SegmentedToggle";
|
||||
import { LoadingState, StateMessage } from "../../components/ui/QueryState";
|
||||
import { useContextMenu } from "../../components/ui/useContextMenu";
|
||||
import NavGrid from "../../components/ui/NavGrid";
|
||||
import Tooltip from "../../components/ui/Tooltip";
|
||||
import VideoCard from "../video/VideoCard";
|
||||
import { VideoMenu } from "../video/VideoMenu";
|
||||
import { announceVideoState } from "../video/stateNotice";
|
||||
import { writeVideoState, writeWatchLater } from "../video/videoWrites";
|
||||
|
||||
/** Which list YouTube fills in — on the video's topic or with what trends in Hungary — is a mood,
|
||||
* decided at the list, and the account keeps the last one (the owner's pick). */
|
||||
const RELATED_REGION_PREF = "relatedRegion";
|
||||
const RELATED_REGION_OPTIONS: UsePrefOptions<RelatedRegion> = {
|
||||
parse: (raw) => (raw === "hu" ? "hu" : "topical"),
|
||||
};
|
||||
|
||||
// The list leaves out what the user has seen (the server does, as it fetches); a video marked here
|
||||
// leaves it the same way, at once.
|
||||
const isSeen = (v: Video) => v.status === "watched" || v.status === "hidden";
|
||||
|
||||
/** The refusals a retry cannot answer: the day's cap (tomorrow does), the feature turned off on
|
||||
* this instance and the shared budget spent (the admin, or tomorrow). */
|
||||
const FINAL_REASONS = new Set(["related_daily_limit", "related_disabled", "quota"]);
|
||||
const isFinal = (e: unknown) => FINAL_REASONS.has(refusalReason(e) ?? "");
|
||||
|
||||
// A write not yet confirmed: its change shows at once, and leaves when the server answers.
|
||||
type Pending = { seq: number; id: string; change: Partial<Video> };
|
||||
|
||||
/** The videos YouTube shows beside `videoId`, without the ones the user has watched or hidden. A
|
||||
* click plays one in this player (`onPlay`); the list stays the opened video's while it does. Its
|
||||
* rows carry the feed's whole menu. */
|
||||
export function RelatedVideos({
|
||||
videoId,
|
||||
onPlay,
|
||||
onWrite,
|
||||
}: {
|
||||
videoId: string;
|
||||
/** `startAt` null resumes the video where it was left; a number (Restart's 0) starts there. */
|
||||
onPlay: (v: Video, startAt: number | null) => void;
|
||||
/** Each write this list makes, for the host's player session (see PlayerModal `onWrite`). */
|
||||
onWrite?: (write: Promise<unknown>) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [region, setRegion] = usePref(RELATED_REGION_PREF, "topical", RELATED_REGION_OPTIONS);
|
||||
// Kept for the session — never refetched, never collected while the app is open: the list
|
||||
// unmounts whenever the drawer closes or the tab changes, and a refetch is another scrape and
|
||||
// another slot of the day's cap.
|
||||
const query = useInfiniteQuery({
|
||||
queryKey: qk.related(videoId, region),
|
||||
queryFn: ({ pageParam }) => stampFetch(() => api.related(videoId, region, pageParam)),
|
||||
initialPageParam: null as string | null,
|
||||
getNextPageParam: (last) => (last.has_more ? last.next_cursor : undefined),
|
||||
staleTime: Infinity,
|
||||
gcTime: Infinity,
|
||||
retry: false,
|
||||
});
|
||||
// The marks on their way, one entry per WRITE: a row leaves (or its bookmark flips) at once, and
|
||||
// comes back if the server refuses that write. Kept per video, the first answer to land cleared
|
||||
// the video's whole entry, and a save then a hide put the hidden row back until the hide landed.
|
||||
const [pending, setPending] = useState<Pending[]>([]);
|
||||
const seqRef = useRef(0);
|
||||
const begin = (id: string, change: Partial<Video>) => {
|
||||
const seq = ++seqRef.current;
|
||||
setPending((p) => [...p, { seq, id, change }]);
|
||||
return seq;
|
||||
};
|
||||
const settle = (seq: number) => setPending((p) => p.filter((w) => w.seq !== seq));
|
||||
|
||||
const onState = (id: string, status: VideoStatus) => {
|
||||
const v = rows.find((x) => x.id === id);
|
||||
const seq = begin(id, { status });
|
||||
const write = writeVideoState(qc, id, status);
|
||||
onWrite?.(write);
|
||||
write
|
||||
.then(() => {
|
||||
settle(seq);
|
||||
// Stale-mark the feed, as its own marks do: the video may be in it too.
|
||||
void qc.invalidateQueries({ queryKey: qk.feed(), refetchType: "none" });
|
||||
announceVideoState(id, status, v, () => onState(id, "new"));
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
notifyActionError(e, t("errors.writeFailed.videoState"));
|
||||
settle(seq);
|
||||
});
|
||||
};
|
||||
|
||||
const onToggleSave = (id: string, saved: boolean) => {
|
||||
const seq = begin(id, { saved });
|
||||
const write = writeWatchLater(qc, id, saved);
|
||||
onWrite?.(write);
|
||||
write
|
||||
.then(() => {
|
||||
settle(seq);
|
||||
void qc.invalidateQueries({ queryKey: qk.playlists() });
|
||||
void qc.invalidateQueries({ queryKey: qk.playlist() });
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
notifyActionError(
|
||||
e,
|
||||
t(saved ? "errors.writeFailed.watchLaterAdd" : "errors.writeFailed.watchLaterRemove"),
|
||||
);
|
||||
settle(seq);
|
||||
});
|
||||
};
|
||||
|
||||
const open = (v: Video, startAt?: number | null) => onPlay(v, startAt ?? null);
|
||||
const menu = useContextMenu<Video>();
|
||||
const openId = menu.open ? menu.target?.id : undefined;
|
||||
|
||||
// What this session confirmed about a row since its page was read (here or anywhere else), then
|
||||
// what is on its way.
|
||||
const marks = useVideoMarks();
|
||||
const rows = markedRows(query.data?.pages, marks)
|
||||
.map((v) => pending.reduce((acc, w) => (w.id === v.id ? { ...acc, ...w.change } : acc), v))
|
||||
.filter((v) => !isSeen(v));
|
||||
const followed = new Set(
|
||||
(query.data?.pages ?? []).flatMap((p) => p.items.filter((v) => v.followed).map((v) => v.id)),
|
||||
);
|
||||
|
||||
const error =
|
||||
query.error instanceof HttpError
|
||||
? query.error.detail || t("player.related.error")
|
||||
: query.isError
|
||||
? t("player.related.error")
|
||||
: null;
|
||||
// A refused page is the one to try again: with pages loaded, a refetch started over from the first
|
||||
// (another scrape and another slot) instead of asking for the page that failed.
|
||||
const final = isFinal(query.error);
|
||||
const retry = final
|
||||
? undefined
|
||||
: query.data?.pages.length
|
||||
? () => void query.fetchNextPage(nextPageOnClick(query.isFetchingNextPage))
|
||||
: () => void query.refetch();
|
||||
|
||||
return (
|
||||
<section data-testid="player-related" aria-label={t("player.related.title")}>
|
||||
<SegmentedToggle
|
||||
options={[
|
||||
{ value: "topical", label: t("player.related.topical") },
|
||||
{ value: "hu", label: t("player.related.hu") },
|
||||
]}
|
||||
value={region}
|
||||
onChange={setRegion}
|
||||
ariaLabel={t("player.related.region")}
|
||||
fullWidth
|
||||
className="mb-3"
|
||||
/>
|
||||
{query.isPending ? (
|
||||
<LoadingState shape="list" />
|
||||
) : error && !rows.length ? (
|
||||
<StateMessage tone="error" compact onRetry={retry}>
|
||||
{error}
|
||||
</StateMessage>
|
||||
) : !rows.length && !query.hasNextPage ? (
|
||||
<StateMessage compact>{t("player.related.empty")}</StateMessage>
|
||||
) : (
|
||||
<>
|
||||
{/* What was read so far was all seen (or marked here since): the list goes on, it is not
|
||||
empty — said, so Show more is not a lone button under nothing. */}
|
||||
{!rows.length && <StateMessage compact>{t("player.related.emptySoFar")}</StateMessage>}
|
||||
<NavGrid className="flex flex-col gap-1.5">
|
||||
{rows.map((v, i) => (
|
||||
<VideoCard
|
||||
key={v.id}
|
||||
navIndex={i}
|
||||
video={v}
|
||||
view="rows"
|
||||
narrow
|
||||
width={0}
|
||||
onState={onState}
|
||||
onToggleSave={onToggleSave}
|
||||
onOpen={open}
|
||||
menuProps={menu.triggerProps}
|
||||
menuButtonProps={menu.buttonProps}
|
||||
menuOpen={openId === v.id}
|
||||
channelMark={
|
||||
followed.has(v.id) && (
|
||||
// A bare mark means nothing to a mouse: it names itself on hover, whatever
|
||||
// the hints setting, since the caption is all it has.
|
||||
<Tooltip hint={t("player.related.followed")} always>
|
||||
<CircleCheck
|
||||
className="w-3.5 h-3.5 shrink-0 text-success"
|
||||
aria-label={t("player.related.followed")}
|
||||
role="img"
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</NavGrid>
|
||||
{/* Show more is the same request a Retry makes: refused for good, neither is offered. */}
|
||||
{query.hasNextPage && !final && (
|
||||
<div className="mt-3 flex justify-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={query.isFetchingNextPage}
|
||||
onClick={() => void query.fetchNextPage(nextPageOnClick(query.isFetchingNextPage))}
|
||||
>
|
||||
{query.isFetchingNextPage ? t("player.related.loading") : t("player.related.more")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{error && rows.length > 0 && (
|
||||
<StateMessage tone="error" compact onRetry={retry}>
|
||||
{error}
|
||||
</StateMessage>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<VideoMenu menu={menu} handlers={{ onState, onToggleSave, onOpen: open }} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// The queue transport cluster, in both of its places. The auto-advance mode wears glyphs of its own:
|
||||
// on the side panel's glyph-only row the skip arrows are Previous / Next, and a mode that wore them
|
||||
// too put two identical ⏭ side by side, the second one silently changing a saved setting. The modes
|
||||
// are cycles, not switches (lit, no aria-pressed), and every control's tooltip names it and its mode
|
||||
// in both places. i18n is key-passthrough.
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("react-i18next")>()),
|
||||
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),
|
||||
}));
|
||||
|
||||
import { PlayerTransportControls } from "./playerModalControls";
|
||||
import { AUTO_MODES, LOOP_MODES, type AutoMode, type LoopMode } from "../../lib/playerModes";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
function mount(variant: "modal" | "docked", autoMode: AutoMode, loopMode: LoopMode = "off") {
|
||||
render(
|
||||
<PlayerTransportControls
|
||||
variant={variant}
|
||||
index={1}
|
||||
queueLength={3}
|
||||
autoMode={autoMode}
|
||||
loopMode={loopMode}
|
||||
onPrev={() => {}}
|
||||
onNext={() => {}}
|
||||
onCycleAuto={() => {}}
|
||||
onCycleLoop={() => {}}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
const glyph = (el: HTMLElement) => el.querySelector("svg")!.getAttribute("class");
|
||||
const button = (name: string | RegExp) => screen.getByRole("button", { name });
|
||||
|
||||
describe("PlayerTransportControls", () => {
|
||||
for (const variant of ["modal", "docked"] as const)
|
||||
for (const mode of AUTO_MODES)
|
||||
it(`${variant}: auto-advance ${mode} wears neither Previous's glyph nor Next's`, () => {
|
||||
mount(variant, mode);
|
||||
const auto = glyph(button(/^player\.autoAdvance\.label: /));
|
||||
expect(auto).not.toBe(glyph(button("player.previous")));
|
||||
expect(auto).not.toBe(glyph(button("player.next")));
|
||||
});
|
||||
|
||||
for (const variant of ["modal", "docked"] as const)
|
||||
it(`${variant}: the modes are lit when on, and announce no toggle`, () => {
|
||||
mount(variant, "next", "off");
|
||||
const auto = button(/^player\.autoAdvance\.label: /);
|
||||
const loop = button(/^player\.loop\.label: /);
|
||||
expect(auto.hasAttribute("aria-pressed")).toBe(false);
|
||||
expect(loop.hasAttribute("aria-pressed")).toBe(false);
|
||||
expect(auto.hasAttribute("data-lit")).toBe(true);
|
||||
expect(loop.hasAttribute("data-lit")).toBe(false);
|
||||
});
|
||||
|
||||
for (const variant of ["modal", "docked"] as const)
|
||||
it(`${variant}: each mode's tooltip names it and the mode it is in`, () => {
|
||||
for (const loopMode of LOOP_MODES) {
|
||||
mount(variant, "random", loopMode);
|
||||
expect(button(/^player\.autoAdvance\.label: /).title).toBe(
|
||||
"player.autoAdvance.label: player.autoAdvance.random · player.autoAdvance.hint",
|
||||
);
|
||||
expect(button(/^player\.loop\.label: /).title).toBe(
|
||||
`player.loop.label: player.loop.${loopMode} · player.loop.hint`,
|
||||
);
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { CSSProperties, Ref } from "react";
|
||||
import type { CSSProperties, ReactNode, Ref } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Repeat, Repeat1, Shuffle, SkipBack, SkipForward } from "lucide-react";
|
||||
import { ListEnd, ListStart, Repeat, Repeat1, Shuffle, SkipBack, SkipForward } from "lucide-react";
|
||||
import type { VideoDetail } from "../../lib/api";
|
||||
import type { AutoMode, LoopMode } from "../../lib/playerModes";
|
||||
import { Button } from "../../components/ui/Button";
|
||||
import { IconButton } from "../../components/ui/IconButton";
|
||||
import { StateMessage } from "../../components/ui/QueryState";
|
||||
import { ClampedText } from "../../components/ui/ClampedText";
|
||||
import { renderDescription } from "./descriptionLinks";
|
||||
@@ -12,11 +13,16 @@ import { renderDescription } from "./descriptionLinks";
|
||||
// the sibling of plexPlayerControls.tsx. No state or effects here; all behaviour comes in via props.
|
||||
// The auto-advance / loop modes it renders are defined in `lib/playerModes`.
|
||||
|
||||
/** The queue transport cluster — prev / counter / next, then the auto-advance and loop mode toggles.
|
||||
* Rendered in two places with identical logic: the modal's queue bar (`variant:"modal"`, normal glass
|
||||
* theme, labels always shown) and the big-view docked control bar (`variant:"docked"`, white-on-dark,
|
||||
* labels hidden until a breakpoint). Only the theme + label-visibility differ; the behaviour is one,
|
||||
* so a mode/icon change lands once. The wrapper (fragment vs. bordered row) stays at the call site. */
|
||||
/** The queue transport cluster — prev / counter / next, then the auto-advance and loop modes.
|
||||
* Rendered in two places from ONE list of controls: the modal's queue bar (`variant:"modal"`, normal
|
||||
* glass theme, glyphs only so the whole cluster fits one line of the side panel) and the big-view
|
||||
* docked control bar (`variant:"docked"`, white-on-dark, labels shown from a breakpoint up). What a
|
||||
* control does, its glyph and its tooltip are said once; only the primitive and the label's
|
||||
* visibility differ. Every control's tooltip carries its full name (and the shortcut, where it has
|
||||
* one), so a glyph-only one still says what it does and which mode it is in. The modes are cycles,
|
||||
* not switches: `lit` when not off, and the name says which. Auto-advance wears list glyphs of its
|
||||
* own — the skip arrows are Previous / Next, beside it (DESIGN.md "A glyph means one thing"). The
|
||||
* wrapper (fragment vs. bordered row) stays at the call site. */
|
||||
export function PlayerTransportControls({
|
||||
variant,
|
||||
index,
|
||||
@@ -40,69 +46,105 @@ export function PlayerTransportControls({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const docked = variant === "docked";
|
||||
// The docked bar sits on the video (always dark): the overlay variant; the modal's is a page surface.
|
||||
const chrome = docked ? "overlay" : "ghost";
|
||||
const navLabel = docked ? "hidden sm:inline" : "";
|
||||
const counter = docked ? "tabular-nums text-white/70" : "text-muted tabular-nums";
|
||||
const divider = docked ? "h-4 w-px bg-white/20" : "w-px h-4 bg-border";
|
||||
const toggleLabel = docked ? "hidden md:inline" : "";
|
||||
const autoName = `${t("player.autoAdvance.label")}: ${t(`player.autoAdvance.${autoMode}`)}`;
|
||||
const loopName = `${t("player.loop.label")}: ${t(`player.loop.${loopMode}`)}`;
|
||||
type Control = {
|
||||
key: string;
|
||||
glyph: ReactNode;
|
||||
name: string;
|
||||
title: string;
|
||||
onClick: () => void;
|
||||
disabled?: boolean;
|
||||
lit?: boolean;
|
||||
/** From which width the docked bar shows the name beside the glyph. */
|
||||
labelFrom: "sm" | "md";
|
||||
/** The glyph after the name (Next points the way it goes). */
|
||||
trailing?: boolean;
|
||||
};
|
||||
const step: Control[] = [
|
||||
{
|
||||
key: "prev",
|
||||
glyph: <SkipBack />,
|
||||
name: t("player.previous"),
|
||||
title: `${t("player.previous")} · Shift+←`,
|
||||
onClick: onPrev,
|
||||
disabled: index === 0,
|
||||
labelFrom: "sm",
|
||||
},
|
||||
{
|
||||
key: "next",
|
||||
glyph: <SkipForward />,
|
||||
name: t("player.next"),
|
||||
title: `${t("player.next")} · Shift+→`,
|
||||
onClick: onNext,
|
||||
disabled: index === queueLength - 1,
|
||||
labelFrom: "sm",
|
||||
trailing: true,
|
||||
},
|
||||
];
|
||||
// Persistent playback settings — cycle on click, saved to your account.
|
||||
const modes: Control[] = [
|
||||
{
|
||||
key: "auto",
|
||||
glyph:
|
||||
autoMode === "prev" ? <ListStart /> : autoMode === "random" ? <Shuffle /> : <ListEnd />,
|
||||
name: autoName,
|
||||
title: `${autoName} · ${t("player.autoAdvance.hint")}`,
|
||||
onClick: onCycleAuto,
|
||||
lit: autoMode !== "off",
|
||||
labelFrom: "md",
|
||||
},
|
||||
{
|
||||
key: "loop",
|
||||
glyph: loopMode === "one" ? <Repeat1 /> : <Repeat />,
|
||||
name: loopName,
|
||||
title: `${loopName} · ${t("player.loop.hint")}`,
|
||||
onClick: onCycleLoop,
|
||||
lit: loopMode !== "off",
|
||||
labelFrom: "md",
|
||||
},
|
||||
];
|
||||
const render = (c: Control) =>
|
||||
docked ? (
|
||||
<Button
|
||||
key={c.key}
|
||||
variant="overlay"
|
||||
size="sm"
|
||||
icon={c.trailing ? undefined : c.glyph}
|
||||
onClick={c.onClick}
|
||||
disabled={c.disabled}
|
||||
lit={c.lit}
|
||||
label={c.name}
|
||||
title={c.title}
|
||||
>
|
||||
<span className={c.labelFrom === "sm" ? "hidden sm:inline" : "hidden md:inline"}>
|
||||
{c.name}
|
||||
</span>
|
||||
{c.trailing && c.glyph}
|
||||
</Button>
|
||||
) : (
|
||||
<IconButton
|
||||
key={c.key}
|
||||
onClick={c.onClick}
|
||||
disabled={c.disabled}
|
||||
lit={c.lit}
|
||||
label={c.name}
|
||||
title={c.title}
|
||||
>
|
||||
{c.glyph}
|
||||
</IconButton>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant={chrome}
|
||||
size="sm"
|
||||
icon={<SkipBack />}
|
||||
onClick={onPrev}
|
||||
disabled={index === 0}
|
||||
label={t("player.previous")}
|
||||
title={`${t("player.previous")} · Shift+←`}
|
||||
>
|
||||
<span className={navLabel}>{t("player.previous")}</span>
|
||||
</Button>
|
||||
{render(step[0]!)}
|
||||
<span className={counter}>
|
||||
{index + 1} / {queueLength}
|
||||
</span>
|
||||
<Button
|
||||
variant={chrome}
|
||||
size="sm"
|
||||
onClick={onNext}
|
||||
disabled={index === queueLength - 1}
|
||||
label={t("player.next")}
|
||||
title={`${t("player.next")} · Shift+→`}
|
||||
>
|
||||
<span className={navLabel}>{t("player.next")}</span>
|
||||
<SkipForward />
|
||||
</Button>
|
||||
{render(step[1]!)}
|
||||
<span className={divider} />
|
||||
{/* Persistent playback settings — cycle on click, saved to your account. */}
|
||||
<Button
|
||||
variant={chrome}
|
||||
size="sm"
|
||||
pressed={autoMode !== "off"}
|
||||
icon={
|
||||
autoMode === "prev" ? <SkipBack /> : autoMode === "random" ? <Shuffle /> : <SkipForward />
|
||||
}
|
||||
onClick={onCycleAuto}
|
||||
label={`${t("player.autoAdvance.label")}: ${t(`player.autoAdvance.${autoMode}`)}`}
|
||||
title={t("player.autoAdvance.hint")}
|
||||
>
|
||||
<span className={toggleLabel}>
|
||||
{t("player.autoAdvance.label")}: {t(`player.autoAdvance.${autoMode}`)}
|
||||
</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant={chrome}
|
||||
size="sm"
|
||||
pressed={loopMode !== "off"}
|
||||
icon={loopMode === "one" ? <Repeat1 /> : <Repeat />}
|
||||
onClick={onCycleLoop}
|
||||
label={`${t("player.loop.label")}: ${t(`player.loop.${loopMode}`)}`}
|
||||
title={t("player.loop.hint")}
|
||||
>
|
||||
<span className={toggleLabel}>
|
||||
{t("player.loop.label")}: {t(`player.loop.${loopMode}`)}
|
||||
</span>
|
||||
</Button>
|
||||
{modes.map(render)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// A reload or a bookmark of the YouTube player reopens it: the page that hosts it opens it once its list
|
||||
// is in — from the list, so it plays on through it, or alone from the catalog — and a page that hosts
|
||||
// none gets the shell's, the video alone. A video the catalog no longer has is said, not swallowed.
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render, renderHook, screen, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("react-i18next")>()),
|
||||
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
|
||||
}));
|
||||
vi.mock("../../lib/actionErrors", () => ({ notifyActionError: vi.fn() }));
|
||||
// The player itself is not what is under test: it shows what it was opened on.
|
||||
vi.mock("./PlayerModal", () => ({
|
||||
default: ({ video, queue }: { video: Video; queue?: Video[] }) => (
|
||||
<p>
|
||||
playing {video.id} {queue ? "in a list" : "alone"}
|
||||
</p>
|
||||
),
|
||||
}));
|
||||
|
||||
import { useOpenLinkedPlayer } from "./useOpenLinkedPlayer";
|
||||
import { LinkedPlayer } from "./LinkedPlayer";
|
||||
import { api, type Video } from "../../lib/api";
|
||||
import { notifyActionError } from "../../lib/actionErrors";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
|
||||
const vid = (id: string) => ({ id, title: id }) as unknown as Video;
|
||||
|
||||
function wrapper({ children }: { children: ReactNode }) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
vi.mocked(notifyActionError).mockClear();
|
||||
window.history.replaceState(null, "", "/");
|
||||
});
|
||||
|
||||
describe("useOpenLinkedPlayer", () => {
|
||||
it("opens the item from the host's list once the list is in, and only once", async () => {
|
||||
window.history.replaceState(null, "", "/?watch=B");
|
||||
const row = vi.spyOn(api, "videoRow");
|
||||
const open = vi.fn();
|
||||
const list = [vid("A"), vid("B")];
|
||||
const { rerender } = renderHook(
|
||||
({ ready, rows }) => useOpenLinkedPlayer(ready, (id) => rows.find((v) => v.id === id), open),
|
||||
{ wrapper, initialProps: { ready: false, rows: list } },
|
||||
);
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
rerender({ ready: true, rows: list });
|
||||
await waitFor(() => expect(open).toHaveBeenCalledWith(list[1], true));
|
||||
// The list refetched (new rows for the same videos): the player it opened is not opened again.
|
||||
rerender({ ready: true, rows: [vid("A"), vid("B")] });
|
||||
expect(open).toHaveBeenCalledTimes(1);
|
||||
expect(row).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("opens an item the list does not hold alone, its row from the catalog", async () => {
|
||||
window.history.replaceState(null, "", "/?watch=Z");
|
||||
vi.spyOn(api, "videoRow").mockResolvedValue(vid("Z"));
|
||||
const open = vi.fn();
|
||||
renderHook(() => useOpenLinkedPlayer(true, () => undefined, open), { wrapper });
|
||||
await waitFor(() => expect(open).toHaveBeenCalledWith(vid("Z"), false));
|
||||
});
|
||||
|
||||
it("says so when the catalog no longer has it", async () => {
|
||||
window.history.replaceState(null, "", "/?watch=Z");
|
||||
const gone = new Error("not found");
|
||||
vi.spyOn(api, "videoRow").mockRejectedValue(gone);
|
||||
const open = vi.fn();
|
||||
renderHook(() => useOpenLinkedPlayer(true, () => undefined, open), { wrapper });
|
||||
await waitFor(() =>
|
||||
expect(notifyActionError).toHaveBeenCalledWith(gone, "player.linkedFailed"),
|
||||
);
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
// Said once: the address no longer names it, so a reload or a copied link does not say it again.
|
||||
expect(new URLSearchParams(window.location.search).has("watch")).toBe(false);
|
||||
});
|
||||
|
||||
it("leaves a player opened while the row was on its way alone, and its address", async () => {
|
||||
window.history.replaceState(null, "", "/?watch=Z");
|
||||
let answer: (v: Video) => void = () => {};
|
||||
vi.spyOn(api, "videoRow").mockReturnValue(new Promise((r) => (answer = r)));
|
||||
const open = vi.fn();
|
||||
renderHook(() => useOpenLinkedPlayer(true, () => undefined, open), { wrapper });
|
||||
// A card clicked meanwhile: its player names itself in the address.
|
||||
window.history.replaceState(null, "", "/?watch=Y");
|
||||
answer(vid("Z"));
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
expect(new URLSearchParams(window.location.search).get("watch")).toBe("Y");
|
||||
});
|
||||
|
||||
it("does not clear the address of a player opened since when its catalog read fails", async () => {
|
||||
window.history.replaceState(null, "", "/?watch=Z");
|
||||
let refuse: (e: Error) => void = () => {};
|
||||
vi.spyOn(api, "videoRow").mockReturnValue(new Promise((_, r) => (refuse = r)));
|
||||
renderHook(() => useOpenLinkedPlayer(true, () => undefined, vi.fn()), { wrapper });
|
||||
window.history.replaceState(null, "", "/?watch=Y");
|
||||
refuse(new Error("not found"));
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(new URLSearchParams(window.location.search).get("watch")).toBe("Y");
|
||||
});
|
||||
|
||||
it("given up over a moved list, keeps the address of a player opened since", async () => {
|
||||
window.history.replaceState(null, "", "/?watch=Z");
|
||||
const { rerender } = renderHook(
|
||||
({ scope }) => useOpenLinkedPlayer(false, () => undefined, vi.fn(), scope),
|
||||
{ wrapper, initialProps: { scope: 1 } },
|
||||
);
|
||||
window.history.replaceState(null, "", "/?watch=Y");
|
||||
rerender({ scope: 2 });
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(new URLSearchParams(window.location.search).get("watch")).toBe("Y");
|
||||
});
|
||||
|
||||
it("stops looking once it opened: the video leaving the list asks the catalog for nothing", async () => {
|
||||
window.history.replaceState(null, "", "/?watch=B");
|
||||
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("B"));
|
||||
const find = vi.fn((id: string) => (id === "B" ? vid("B") : undefined));
|
||||
const { rerender } = renderHook(
|
||||
({ rows }) => useOpenLinkedPlayer(true, rows ? find : () => undefined, vi.fn()),
|
||||
{ wrapper, initialProps: { rows: true } },
|
||||
);
|
||||
await waitFor(() => expect(find).toHaveBeenCalled());
|
||||
find.mockClear();
|
||||
rerender({ rows: false });
|
||||
rerender({ rows: true });
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(find).not.toHaveBeenCalled();
|
||||
expect(row).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("opens nothing, and asks for nothing, for an address that names no player", async () => {
|
||||
window.history.replaceState(null, "", "/?q=talks");
|
||||
const row = vi.spyOn(api, "videoRow");
|
||||
const open = vi.fn();
|
||||
renderHook(() => useOpenLinkedPlayer(true, () => undefined, open), { wrapper });
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
expect(row).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("the shell's LinkedPlayer", () => {
|
||||
it("plays the video alone over a page that hosts no player", async () => {
|
||||
window.history.replaceState(null, "", "/?page=channels&watch=Z");
|
||||
vi.spyOn(api, "videoRow").mockResolvedValue(vid("Z"));
|
||||
render(<LinkedPlayer hosted={false} />, { wrapper });
|
||||
expect(await screen.findByText("playing Z alone")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("leaves it to a page that hosts its own, even once that page has fetched the row", async () => {
|
||||
// The page plays it alone, from the catalog row it asked for: the same cache entry this one reads.
|
||||
window.history.replaceState(null, "", "/?page=home&watch=Z");
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
qc.setQueryData(qk.videoRow("Z"), vid("Z"));
|
||||
render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<LinkedPlayer hosted />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(screen.queryByText(/playing/)).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves it to a page that hosts its own", async () => {
|
||||
window.history.replaceState(null, "", "/?watch=Z");
|
||||
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("Z"));
|
||||
render(<LinkedPlayer hosted />, { wrapper });
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(row).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText(/playing/)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useEffect, useEffectEvent, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { api, type Video } from "../../lib/api";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
import { linkedPlayer, PLAYER_KEYS } from "../../lib/playerUrlState";
|
||||
import { clearParams } from "../../lib/urlState";
|
||||
import { notifyActionError } from "../../lib/actionErrors";
|
||||
|
||||
/** Opens the player an address names (a reload, a bookmark — lib/playerUrlState) on the page that
|
||||
* hosts it, once: read as the host mounts, opened once its list is in (`ready`). From the list when the
|
||||
* item is in it (`find`), so the player plays on through the list; else alone, its row fetched from
|
||||
* the catalog. A row the catalog no longer has is said, not swallowed.
|
||||
*
|
||||
* `scope` names the list the address put it over (a playlist, a live search): when the host moves to
|
||||
* another before it opened, the address under it named something else, and the player is given up —
|
||||
* opened later, it would start over a list nobody linked, unasked. So it is when a player opened
|
||||
* meanwhile (a card clicked while the row was on its way): the address names that one now. */
|
||||
export function useOpenLinkedPlayer(
|
||||
ready: boolean,
|
||||
find: (id: string) => Video | undefined,
|
||||
open: (video: Video, inList: boolean) => void,
|
||||
scope: string | number | null = null,
|
||||
): void {
|
||||
const { t } = useTranslation();
|
||||
const [linked] = useState(() => linkedPlayer()?.watch ?? null);
|
||||
const [linkedScope] = useState(scope);
|
||||
// Opened, said to be gone or given up, once. A ref for the effect (a StrictMode re-run of it must
|
||||
// not open it twice); the state stops the lookup and the row fetch on screen after it.
|
||||
const done = useRef(linked == null);
|
||||
const [settled, setSettled] = useState(linked == null);
|
||||
const moved = scope !== linkedScope;
|
||||
const waiting = ready && !moved && !settled && linked != null;
|
||||
const listed = waiting ? find(linked) : undefined;
|
||||
const row = useQuery({
|
||||
queryKey: qk.videoRow(linked ?? ""),
|
||||
queryFn: () => api.videoRow(linked!),
|
||||
enabled: waiting && !listed,
|
||||
retry: false,
|
||||
});
|
||||
const openIt = useEffectEvent(open);
|
||||
const failed = useEffectEvent((err: unknown) => {
|
||||
notifyActionError(err, t("player.linkedFailed"));
|
||||
clearParams(...PLAYER_KEYS);
|
||||
});
|
||||
useEffect(() => {
|
||||
if (done.current) return;
|
||||
const settle = () => {
|
||||
done.current = true;
|
||||
// State, not derived: a one-way decision taken as the list or the row arrives. Derived from
|
||||
// `listed`, the lookup and the row fetch would come back whenever the video left the list.
|
||||
setSettled(true);
|
||||
};
|
||||
// A player opened since names its own: this one is not wanted any more.
|
||||
if (linkedPlayer()?.watch !== linked) return settle();
|
||||
if (moved) {
|
||||
// The address goes on naming it under the new list (a reload would open it there).
|
||||
clearParams(...PLAYER_KEYS);
|
||||
return settle();
|
||||
}
|
||||
// Not before the host is ready: the row's cache entry is shared, so another opener's fetch fills
|
||||
// it here too (a disabled query still reads the cache) — the shell's player over a page that
|
||||
// plays its own would open a second one.
|
||||
if (!ready) return;
|
||||
if (listed) openIt(listed, true);
|
||||
else if (row.data) openIt(row.data, false);
|
||||
else if (row.isError) failed(row.error);
|
||||
else return;
|
||||
settle();
|
||||
}, [linked, moved, ready, listed, row.data, row.isError, row.error]);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { useLayoutEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
import { api, HttpError, type PlexCollection } from "../../lib/api";
|
||||
import { api, refusalReason, type PlexCollection } from "../../lib/api";
|
||||
import { notifyActionError } from "../../lib/actionErrors";
|
||||
import { PopoverSurface } from "../../components/ui/AnchoredPopover";
|
||||
import { useAnchoredPopover } from "../../components/ui/anchoredPopoverHooks";
|
||||
@@ -123,8 +123,7 @@ export default function PlexCollectionAddAt({
|
||||
/** A create refused only because the read after it failed: the collection is on Plex, with this
|
||||
* title in it, and its row is kept — the name is taken now, so the field clears as on success. */
|
||||
function madeOnPlex(e: unknown): boolean {
|
||||
const d = e instanceof HttpError ? (e.detailData as { reason?: string } | undefined) : undefined;
|
||||
return d?.reason === "collection_pending_sync";
|
||||
return refusalReason(e) === "collection_pending_sync";
|
||||
}
|
||||
|
||||
function flipContains<T extends { collections: { id: string; contains: boolean }[] }>(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Check, Info, Layers, ListPlus, Play, SkipBack, Tv2, Undo2 } from "lucide-react";
|
||||
import { Check, Info, Layers, ListPlus, Play, RotateCcw, Tv2, Undo2 } from "lucide-react";
|
||||
|
||||
import { type PlexCard } from "../../lib/api";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
@@ -98,7 +98,7 @@ export function usePlexCardActions(handlers: PlexActionHandlers, open: boolean)
|
||||
{
|
||||
id: "restart",
|
||||
label: t("card.restartTitle"),
|
||||
icon: <SkipBack className={icon} />,
|
||||
icon: <RotateCcw className={icon} />,
|
||||
onSelect: () => onRestart(c),
|
||||
},
|
||||
]
|
||||
|
||||
@@ -5,6 +5,7 @@ import { qk } from "../../lib/queryKeys";
|
||||
import { ListPlus } from "lucide-react";
|
||||
import { YouTubeIcon } from "../../lib/brandIcons";
|
||||
import { api, type Playlist } from "../../lib/api";
|
||||
import { addPlaylistItem, removePlaylistItem } from "./videoWrites";
|
||||
import { notifyActionError } from "../../lib/actionErrors";
|
||||
import { playlistName } from "../../lib/playlistName";
|
||||
import { PopoverSurface } from "../../components/ui/AnchoredPopover";
|
||||
@@ -115,8 +116,8 @@ function MembershipPanel({
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
if (pl.has_video) await api.removeFromPlaylist(pl.id, videoId);
|
||||
else await api.addToPlaylist(pl.id, videoId);
|
||||
if (pl.has_video) await removePlaylistItem(qc, pl, videoId);
|
||||
else await addPlaylistItem(qc, pl, videoId);
|
||||
qc.setQueryData<Playlist[]>(qk.playlistMembership(videoId), (old) =>
|
||||
old?.map((p) => (p.id === pl.id ? { ...p, has_video: !p.has_video } : p)),
|
||||
);
|
||||
@@ -133,7 +134,7 @@ function MembershipPanel({
|
||||
let made = false;
|
||||
try {
|
||||
const pl = await api.createPlaylist(name);
|
||||
await api.addToPlaylist(pl.id, videoId);
|
||||
await addPlaylistItem(qc, pl, videoId);
|
||||
made = true;
|
||||
} catch (e) {
|
||||
notifyActionError(e, t("playlists.addFailed"));
|
||||
|
||||
@@ -48,8 +48,9 @@ describe("ChannelNameLink", () => {
|
||||
it("is an anchor whose href opens this channel on the current page", () => {
|
||||
const { link } = renderLink();
|
||||
expect(link.tagName).toBe("A");
|
||||
// The same URL openChannel pushes: the current page's query plus ?chan=<id>.
|
||||
expect(link.getAttribute("href")).toBe(`/?page=feed&show=unwatched&chan=${CH}`);
|
||||
// The same URL openChannel pushes: the current page plus ?chan=<id> — not the page's own keys,
|
||||
// which named a view the channel does not show (`show=unwatched` here).
|
||||
expect(link.getAttribute("href")).toBe(`/?page=feed&chan=${CH}`);
|
||||
});
|
||||
|
||||
it("takes the in-app path on a plain left click, and suppresses the browser navigation", () => {
|
||||
@@ -73,11 +74,16 @@ describe("ChannelNameLink", () => {
|
||||
expect(onOpenInApp).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not lose the rest of the address bar", () => {
|
||||
window.history.replaceState({}, "", "/?page=channels&q=abc");
|
||||
// The address names only what the screen shows: the channel over the page, not the page's filters
|
||||
// (a link's new tab once opened the channel under the feed's search and sort).
|
||||
it("keeps the page and the shell's keys, and leaves the page's and another channel's behind", () => {
|
||||
window.history.replaceState(
|
||||
{},
|
||||
"",
|
||||
"/?page=channels&q=abc&ctab=hidden&chtab=about&m=signup#x=1",
|
||||
);
|
||||
const { link } = renderLink();
|
||||
expect(link.getAttribute("href")).toContain("page=channels");
|
||||
expect(link.getAttribute("href")).toContain("q=abc");
|
||||
expect(link.getAttribute("href")).toBe(`/?page=channels&chan=${CH}&m=signup#x=1`);
|
||||
});
|
||||
|
||||
it("gives a channel with no title yet an accessible name", () => {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { forwardRef, type AnchorHTMLAttributes } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { isPlainLeftClick } from "../../lib/nav";
|
||||
import { urlWithParams } from "../../lib/urlState";
|
||||
import { channelUrl } from "../../lib/urlState";
|
||||
|
||||
// A channel name that is a REAL link. The player showed it as a `<button>`, so the browser's own
|
||||
// gestures did nothing on it: middle-click and Ctrl/Cmd-click opened no tab, on a thing that looks
|
||||
// exactly like a link (the YouTube icon right next to it IS an anchor and does open one). The video
|
||||
// card's channel name had the same `<button>`, so it renders through here too.
|
||||
//
|
||||
// The href is the same URL `openChannel` pushes — `?chan=<id>` on the current page — so a new tab
|
||||
// lands where the in-app navigation would have. A plain left click is still handled in-app, because
|
||||
// The href is the same URL `openChannel` pushes (`channelUrl`: the channel over the current page,
|
||||
// without the page's own keys) — so a new tab lands where the in-app navigation would have. A plain left click is still handled in-app, because
|
||||
// the SPA path does more than navigate (the player has to close first and reclaim its own
|
||||
// Back-to-close history entry; see lib/history.closeOverlaysThenNavigate).
|
||||
type Props = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "onClick" | "title"> & {
|
||||
@@ -33,7 +33,7 @@ const ChannelNameLink = forwardRef<HTMLAnchorElement, Props>(function ChannelNam
|
||||
<a
|
||||
{...rest}
|
||||
ref={ref}
|
||||
href={urlWithParams({ chan: channelId })}
|
||||
href={channelUrl(channelId)}
|
||||
title={tooltip}
|
||||
onClick={(e) => {
|
||||
if (stopPropagation) e.stopPropagation();
|
||||
|
||||
@@ -374,6 +374,8 @@ function VideoCard({
|
||||
menuOpen = false,
|
||||
navIndex,
|
||||
shelf = false,
|
||||
narrow = false,
|
||||
channelMark,
|
||||
}: {
|
||||
video: Video;
|
||||
view: FeedView;
|
||||
@@ -397,6 +399,12 @@ function VideoCard({
|
||||
navIndex?: number;
|
||||
/** On a shelf (a horizontal strip): a one-line title over the channel alone (ui/mediaCardStyles). */
|
||||
shelf?: boolean;
|
||||
/** The thumbnailed row in a side panel's ~20rem column: a smaller picture, and the "…" alone at the
|
||||
* row's end — the hover toggles leave no room for the title there, and every one of them is a row
|
||||
* of the menu. */
|
||||
narrow?: boolean;
|
||||
/** Something the list says about the channel (a "followed" mark), set before its name. */
|
||||
channelMark?: ReactNode;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const lang = i18n.language;
|
||||
@@ -610,15 +618,46 @@ function VideoCard({
|
||||
const textBlock = (
|
||||
<>
|
||||
{title}
|
||||
<div className="mt-0.5">{channelLink}</div>
|
||||
<div className="mt-0.5">
|
||||
{channelMark ? (
|
||||
<div className="flex items-center gap-1 min-w-0">
|
||||
{channelMark}
|
||||
<div className="min-w-0">{channelLink}</div>
|
||||
</div>
|
||||
) : (
|
||||
channelLink
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted mt-0.5">
|
||||
{views}
|
||||
{views && " · "}
|
||||
{published}
|
||||
{/* The narrow row keeps the relative time and moves the date into its tooltip, as the small
|
||||
card does: in a 20rem panel the full pair wrapped to a line of its own. */}
|
||||
{narrow ? <RelativeTime at={video.published_at} /> : published}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
if (spec.family === "row" && narrow) {
|
||||
return (
|
||||
<div
|
||||
data-testid="video-card"
|
||||
data-video-id={video.id}
|
||||
{...menuProps?.(video)}
|
||||
{...(navIndex !== undefined && navItemAttrs(navIndex))}
|
||||
className={clsx(rowShell, "flex gap-2 p-1.5", watched && "opacity-55")}
|
||||
>
|
||||
<Thumb video={video} className="aspect-video shrink-0 w-24" onOpen={onOpen} small />
|
||||
<div className="min-w-0 flex-1 flex flex-col">{textBlock}</div>
|
||||
{more && (
|
||||
<div className="shrink-0 self-start">
|
||||
<MoreButton label={t("card.menu.more")} expanded={more.open} menuProps={more.props} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (spec.family === "row") {
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { type Video } from "../../lib/api";
|
||||
import { ContextMenu } from "../../components/ui/ContextMenu";
|
||||
import { type ContextMenuController } from "../../components/ui/useContextMenu";
|
||||
import { useVideoActions, type VideoActionHandlers } from "../../features/video/useVideoActions";
|
||||
import { useVideoActions, type VideoActionHandlers } from "./useVideoActions";
|
||||
|
||||
/** A video list's one menu (the feed grid and a channel page): every trigger — right-click,
|
||||
* long-press, Shift+F10 and each card's "…" — opens it with the video's whole action list. Render
|
||||
@@ -0,0 +1,38 @@
|
||||
import i18n from "../../i18n";
|
||||
import { notify, resolveVideo } from "../../lib/notifications";
|
||||
import type { Video, VideoStatus } from "../../lib/api";
|
||||
|
||||
/** What a notice names the video by; any of it may be unknown to the surface that marked it. */
|
||||
export type NoticeVideo = Pick<Video, "title" | "channel_id" | "channel_title">;
|
||||
|
||||
/** Say that a video's mark landed, once the server has it: "Hidden" / "Marked watched" with the
|
||||
* Undo (`undo` puts it back to new) and the meta the Notification Center keeps it under, so the
|
||||
* notice still finds the video after a reload. A mark back to new quietly resolves a hide or watch
|
||||
* notice still standing for it, so it does not linger with a dead action. A claim of success:
|
||||
* never called before the write is confirmed. One definition, because every list that marks a
|
||||
* video must announce it the same way (the feed's cards, a related list). */
|
||||
export function announceVideoState(
|
||||
id: string,
|
||||
status: VideoStatus,
|
||||
video: NoticeVideo | undefined,
|
||||
undo: () => void,
|
||||
): void {
|
||||
if (status === "new") {
|
||||
resolveVideo(id);
|
||||
return;
|
||||
}
|
||||
const hidden = status === "hidden";
|
||||
notify({
|
||||
message: video?.title
|
||||
? i18n.t(hidden ? "feed.hiddenNamed" : "feed.markedWatchedNamed", { title: video.title })
|
||||
: i18n.t(hidden ? "feed.hidden" : "feed.markedWatched"),
|
||||
action: { label: i18n.t(hidden ? "feed.undo" : "feed.unwatch"), onClick: undo },
|
||||
meta: {
|
||||
kind: hidden ? "video-hidden" : "video-watched",
|
||||
videoId: id,
|
||||
title: video?.title ?? i18n.t("feed.thisVideo"),
|
||||
channelId: video?.channel_id ?? "",
|
||||
channelName: video?.channel_title ?? "",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Check,
|
||||
Download,
|
||||
Eye,
|
||||
Eraser,
|
||||
EyeOff,
|
||||
Filter,
|
||||
FilterX,
|
||||
@@ -14,7 +15,6 @@ import {
|
||||
ListPlus,
|
||||
Play,
|
||||
RotateCcw,
|
||||
SkipBack,
|
||||
Tv,
|
||||
Undo2,
|
||||
} from "lucide-react";
|
||||
@@ -104,7 +104,7 @@ export function useVideoActions(handlers: VideoActionHandlers, open: boolean) {
|
||||
{
|
||||
id: "restart",
|
||||
label: t("card.restartTitle"),
|
||||
icon: <SkipBack className={icon} />,
|
||||
icon: <RotateCcw className={icon} />,
|
||||
onSelect: () => onOpen(v, 0),
|
||||
},
|
||||
]
|
||||
@@ -193,7 +193,7 @@ export function useVideoActions(handlers: VideoActionHandlers, open: boolean) {
|
||||
{
|
||||
id: "reset",
|
||||
label: t("card.resetState"),
|
||||
icon: <RotateCcw className={icon} />,
|
||||
icon: <Eraser className={icon} />,
|
||||
onSelect: () => onResetState(v.id),
|
||||
},
|
||||
]
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
// The whole app source: a state write can be made from any page.
|
||||
const root = new URL("../../", import.meta.url);
|
||||
const sources = () =>
|
||||
readdirSync(root, { recursive: true, encoding: "utf8" })
|
||||
.map((f) => f.replace(/\\/g, "/"))
|
||||
.filter((f) => /\.tsx?$/.test(f) && !f.includes(".test."))
|
||||
.map((f) => ({ f, src: readFileSync(new URL(f, root), "utf8") }));
|
||||
|
||||
// The api's own definitions of these writes, and the one module that may call them.
|
||||
const ALLOWED = new Set([
|
||||
"lib/api/feed.ts",
|
||||
"lib/api/playlists.ts",
|
||||
"features/video/videoWrites.ts",
|
||||
]);
|
||||
|
||||
// A related list and a live search are never refetched, so a state, Watch-later or playlist-item
|
||||
// write that does not reach them (`markVideo`) leaves them showing the old mark for the session —
|
||||
// the built-in Watch later list's items ARE the mark. videoWrites makes those writes and the mark
|
||||
// together; a direct api call skips the mark.
|
||||
const WRITES =
|
||||
/\bapi\s*\.\s*(setState|clearState|watchLaterAdd|watchLaterRemove|addToPlaylist|removeFromPlaylist|moveToPlaylist)\b/;
|
||||
|
||||
describe("a video's state, Watch-later and playlist-item writes", () => {
|
||||
it("go through features/video/videoWrites, never the api directly", () => {
|
||||
const offenders = sources()
|
||||
.filter(({ f }) => !ALLOWED.has(f))
|
||||
// Only the api object's members count (React's own `setState` is not ours) — named, not only
|
||||
// called: `(saved ? api.watchLaterAdd : api.watchLaterRemove)(id)` makes the write too. The
|
||||
// dot may sit on the next line of a chain.
|
||||
.filter(({ src }) => WRITES.test(src))
|
||||
.map(({ f }) => f);
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
|
||||
it("catches a write named without being called on the spot, and a playlist item's", () => {
|
||||
expect(WRITES.test("(saved ? api.watchLaterAdd : api.watchLaterRemove)(id)")).toBe(true);
|
||||
expect(WRITES.test("await api\n .removeFromPlaylist(listId, id)")).toBe(true);
|
||||
expect(WRITES.test("api.moveToPlaylist(a, id, b)")).toBe(true);
|
||||
expect(WRITES.test("this.setState(next); api.playlists()")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// Each write reaches the lists that are never refetched once the server has it — and not before:
|
||||
// a refused write leaves them as they were.
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { api } from "../../lib/api";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
import {
|
||||
addPlaylistItem,
|
||||
movePlaylistItem,
|
||||
removePlaylistItem,
|
||||
resetVideoState,
|
||||
writeVideoState,
|
||||
writeWatchLater,
|
||||
} from "./videoWrites";
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
// The marks' values, without when each was confirmed.
|
||||
const marks = (qc: QueryClient) => {
|
||||
const m = qc.getQueryData<Record<string, Record<string, { value: unknown }>>>(qk.videoMarks());
|
||||
return m
|
||||
? Object.fromEntries(
|
||||
Object.entries(m).map(([id, f]) => [
|
||||
id,
|
||||
Object.fromEntries(Object.entries(f).map(([k, x]) => [k, x.value])),
|
||||
]),
|
||||
)
|
||||
: undefined;
|
||||
};
|
||||
const WATCH_LATER = { id: 1, kind: "watch_later" as const };
|
||||
const MINE = { id: 2, kind: "user" as const };
|
||||
|
||||
describe("videoWrites", () => {
|
||||
it("marks a state written", async () => {
|
||||
vi.spyOn(api, "setState").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient();
|
||||
await writeVideoState(qc, "X", "hidden");
|
||||
expect(marks(qc)).toEqual({ X: { status: "hidden" } });
|
||||
});
|
||||
|
||||
it("marks a reset as new, from the start", async () => {
|
||||
vi.spyOn(api, "clearState").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient();
|
||||
await resetVideoState(qc, "X");
|
||||
expect(marks(qc)).toEqual({ X: { status: "new", position_seconds: 0 } });
|
||||
});
|
||||
|
||||
it("marks a Watch-later save and its removal", async () => {
|
||||
vi.spyOn(api, "watchLaterAdd").mockResolvedValue({ ok: true } as never);
|
||||
vi.spyOn(api, "watchLaterRemove").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient();
|
||||
await writeWatchLater(qc, "X", true);
|
||||
expect(marks(qc)).toEqual({ X: { saved: true } });
|
||||
await writeWatchLater(qc, "X", false);
|
||||
expect(marks(qc)).toEqual({ X: { saved: false } });
|
||||
});
|
||||
|
||||
it("marks an item of the Watch later list as the bookmark it is", async () => {
|
||||
vi.spyOn(api, "addToPlaylist").mockResolvedValue({ ok: true } as never);
|
||||
vi.spyOn(api, "removeFromPlaylist").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient();
|
||||
await addPlaylistItem(qc, WATCH_LATER, "X");
|
||||
expect(marks(qc)).toEqual({ X: { saved: true } });
|
||||
await removePlaylistItem(qc, WATCH_LATER, "X");
|
||||
expect(marks(qc)).toEqual({ X: { saved: false } });
|
||||
});
|
||||
|
||||
it("marks nothing for an item of any other list", async () => {
|
||||
vi.spyOn(api, "addToPlaylist").mockResolvedValue({ ok: true } as never);
|
||||
vi.spyOn(api, "removeFromPlaylist").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient();
|
||||
await addPlaylistItem(qc, MINE, "X");
|
||||
await removePlaylistItem(qc, { id: 3, kind: undefined }, "X");
|
||||
expect(marks(qc)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("marks a move into and out of the Watch later list", async () => {
|
||||
vi.spyOn(api, "moveToPlaylist").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient();
|
||||
await movePlaylistItem(qc, MINE, "X", WATCH_LATER);
|
||||
expect(marks(qc)).toEqual({ X: { saved: true } });
|
||||
await movePlaylistItem(qc, WATCH_LATER, "X", MINE);
|
||||
expect(marks(qc)).toEqual({ X: { saved: false } });
|
||||
});
|
||||
|
||||
it("marks nothing the server refused", async () => {
|
||||
vi.spyOn(api, "setState").mockRejectedValue(new Error("offline"));
|
||||
const qc = new QueryClient();
|
||||
await expect(writeVideoState(qc, "X", "hidden")).rejects.toThrow("offline");
|
||||
expect(marks(qc)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { api, type Playlist, type VideoStatus } from "../../lib/api";
|
||||
import { markVideo } from "../../lib/progressCache";
|
||||
|
||||
// A video's user state, its Watch-later mark and its playlist items, written to the server and —
|
||||
// once it has the change — into the lists that are never refetched (`markVideo`: every related
|
||||
// list, every live search). These are the ONE way to make those writes, and
|
||||
// `videoWrites.contract.test.ts` holds it: four writes that called the api directly (the
|
||||
// Notification Center's undo, the feed's reset, the feed's and Home's Watch-later toggles) left a
|
||||
// related list hiding a video the user had un-hidden, or showing it unsaved after a save. A
|
||||
// playlist item is one of them because the built-in Watch later list IS the mark (`saved`): ticked
|
||||
// in Add to playlist or taken out on the Playlists page, it left the bookmark as it was. Each
|
||||
// returns the server's answer, so a caller keeps its own optimistic layer, notices and rollback.
|
||||
|
||||
export function writeVideoState(qc: QueryClient, id: string, status: VideoStatus) {
|
||||
return api.setState(id, status).then((r) => {
|
||||
markVideo(qc, id, { status });
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
/** Back to pristine: the state row and its resume position both go. */
|
||||
export function resetVideoState(qc: QueryClient, id: string) {
|
||||
return api.clearState(id).then((r) => {
|
||||
markVideo(qc, id, { status: "new", position_seconds: 0 });
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
export function writeWatchLater(qc: QueryClient, id: string, saved: boolean) {
|
||||
return (saved ? api.watchLaterAdd(id) : api.watchLaterRemove(id)).then((r) => {
|
||||
markVideo(qc, id, { saved });
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
/** The list a playlist item write goes to: on the built-in Watch later list (`kind`) the item IS
|
||||
* the video's Watch-later mark. A kind the caller cannot tell (undefined) marks nothing. */
|
||||
type ListRef = { id: number; kind: Playlist["kind"] | undefined };
|
||||
|
||||
const markIfWatchLater = (qc: QueryClient, list: ListRef, id: string, saved: boolean) => {
|
||||
if (list.kind === "watch_later") markVideo(qc, id, { saved });
|
||||
};
|
||||
|
||||
/** Add a video to a playlist; `position` (an index in the stored order) puts it back where a
|
||||
* removal took it from. */
|
||||
export function addPlaylistItem(qc: QueryClient, list: ListRef, id: string, position?: number) {
|
||||
return api.addToPlaylist(list.id, id, position).then((r) => {
|
||||
markIfWatchLater(qc, list, id, true);
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
export function removePlaylistItem(qc: QueryClient, list: ListRef, id: string) {
|
||||
return api.removeFromPlaylist(list.id, id).then((r) => {
|
||||
markIfWatchLater(qc, list, id, false);
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
/** Move a video from one playlist to another, in one request (see `api.moveToPlaylist`). */
|
||||
export function movePlaylistItem(qc: QueryClient, from: ListRef, id: string, to: ListRef) {
|
||||
return api.moveToPlaylist(from.id, id, to.id).then((r) => {
|
||||
markIfWatchLater(qc, from, id, false);
|
||||
markIfWatchLater(qc, to, id, true);
|
||||
return r;
|
||||
});
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
"tabs": {
|
||||
"subscribed": "Subscriptions",
|
||||
"discovery": "Discover from playlists",
|
||||
"watched": "Discover from your history",
|
||||
"hidden": "Hidden",
|
||||
"blocked": "Blocked"
|
||||
},
|
||||
@@ -154,5 +155,38 @@
|
||||
"hint": "Their videos are kept out of your personal Feed, but still appear in the shared Library.",
|
||||
"empty": "No hidden channels. Hide a subscription (the eye icon on its row) to keep its uploads out of your personal Feed without unsubscribing.",
|
||||
"unhide": "Unhide"
|
||||
},
|
||||
"watched": {
|
||||
"intro": "Channels you often watched on YouTube but don't follow, from the watch history you uploaded. Only videos of five minutes or more count, so Shorts stay out. Follow a channel to get its new uploads in your Feed, or take it off the list.",
|
||||
"loading": "Finding channels…",
|
||||
"empty": "No suggestions — you follow every channel you watched five or more longer videos from.",
|
||||
"notImported": "Upload your YouTube watch history to see the channels you watch but don't follow.",
|
||||
"openTakeout": "Open YouTube history",
|
||||
"pending_one": "{{count}} more channel is still being looked at — the list may grow.",
|
||||
"pending_other": "{{count}} more channels are still being looked at — the list may grow.",
|
||||
"more_one": "Show {{count}} more",
|
||||
"more_other": "Show {{count}} more",
|
||||
"shown": "{{shown}} of {{total}}",
|
||||
"dismiss": "Not interested",
|
||||
"dismissHint": "Take this channel off the list. You can undo it right after.",
|
||||
"dismissed": "{{name}} is off the list",
|
||||
"cols": {
|
||||
"watched": "Watched",
|
||||
"watchedHint_one": "Show the {{count}} video of five minutes or more you watched from this channel",
|
||||
"watchedHint_other": "Show the {{count}} videos of five minutes or more you watched from this channel",
|
||||
"last": "Last watched"
|
||||
},
|
||||
"videos": {
|
||||
"title": "Videos you watched from {{name}}",
|
||||
"summary_one": "{{count}} video of five minutes or more · last watched {{when}}",
|
||||
"summary_other": "{{count}} videos of five minutes or more · last watched {{when}}",
|
||||
"loading": "Getting the videos ready…",
|
||||
"gone_one": "{{count}} video is no longer on YouTube",
|
||||
"gone_other": "{{count}} videos are no longer on YouTube",
|
||||
"empty": "None of these videos is on YouTube any more.",
|
||||
"colTitle": "Video",
|
||||
"colLength": "Length",
|
||||
"colWatched": "Watched"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,10 @@
|
||||
"label": "Backfill quota reserve",
|
||||
"hint": "Units kept in reserve so scheduled backfill never starves interactive syncs / enrichment."
|
||||
},
|
||||
"related_daily_limit_per_user": {
|
||||
"label": "Related videos — daily limit per user",
|
||||
"hint": "Max related-video requests a user can make per day — opening a list counts one, and so does every “Show more”. They come from YouTube's website and spend no search quota; looking up the videos in one costs up to about 8 units (up to 4 pages, each a video and a channel lookup). A failed one doesn't count (up to 5 an hour). Set 0 to turn related videos off."
|
||||
},
|
||||
"search_daily_limit_per_user": {
|
||||
"label": "Live search — daily limit per user",
|
||||
"hint": "Max live YouTube searches per user per day. With the API source each search costs 100 units (so the shared budget affords only ~80-90/day total); with the scrape source it's a pure anti-abuse limit. Set 0 to disable live search."
|
||||
|
||||
@@ -115,7 +115,9 @@
|
||||
"apiToken": {
|
||||
"create": "Couldn't create the token",
|
||||
"revoke": "Couldn't revoke the token"
|
||||
}
|
||||
},
|
||||
"dismissWatchedChannel": "Couldn't take the channel off the list",
|
||||
"restoreWatchedChannel": "Couldn't put the channel back on the list"
|
||||
},
|
||||
"ok": "OK",
|
||||
"offline": {
|
||||
@@ -186,6 +188,10 @@
|
||||
"quota_spent": "Today's shared YouTube budget is spent. Try again tomorrow.",
|
||||
"recipient_required": "A recipient email is required",
|
||||
"registration_closed": "Registration is currently closed",
|
||||
"related_disabled": "Related videos are turned off on this instance.",
|
||||
"related_daily_limit": "You've reached today's related videos limit ({{limit}}). Opening a list counts as one request, and so does every “Show more”. Try again tomorrow.",
|
||||
"search_busy": "Too many searches are running right now. Try again in a few seconds.",
|
||||
"search_disabled": "Live YouTube search is turned off on this instance.",
|
||||
"search_daily_limit": "You've reached today's YouTube search limit ({{limit}}). Try again tomorrow.",
|
||||
"search_term_required": "Enter something to search for",
|
||||
"session_gone": "The playback session ended",
|
||||
|
||||
@@ -75,6 +75,9 @@
|
||||
"clearNow": "Clear now",
|
||||
"cleared_one": "Cleared {{count}} result",
|
||||
"cleared_other": "Cleared {{count}} results",
|
||||
"showHint": "How many results to fetch at a time — “Load more” pulls another batch of this size."
|
||||
"showHint": "How many results to fetch at a time — “Load more” pulls another batch of this size.",
|
||||
"notRunTitle": "Not searched yet",
|
||||
"notRunBody": "A YouTube API search spends 100 units of the shared daily quota, so a reload, a link, Back or Forward doesn't start one by itself.",
|
||||
"runAgain": "Search YouTube"
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user