Compare commits

...
45 Commits
Author SHA1 Message Date
github-actions[bot] ddc3a4d77c chore: bump version to 2.12.1 2026-08-04 14:59:38 +00:00
edde746 58d5d3c4ef fix(plex): read external ids from legacy agent and HAMA AniDB guids
Plex only builds the `Guid` array for the Plex Movie / Plex TV Series
agents. A library still on a legacy agent answers with the scalar `guid`
alone, so `fetchExternalIds` returned nothing for it and every consumer
went quiet: trackers logged "no external IDs" and skipped the write,
manual ratings showed "Not available", the detail screen dropped its
watchlist button, and Continue Watching stopped collapsing duplicate
copies. The reverse lookup already read that scalar; only the forward
path ignored it.

Read both shapes from the one request the method already makes, with the
array winning per field and the scalar filling the rest.

HAMA identifies anime by AniDB id and nothing else, which no id set could
carry. AniDB is the Fribb mapping's own primary key, so it now travels on
`ExternalIds` and indexes those rows directly — 7177 of them expose no
tvdb/tmdb/imdb at all and were unreachable by any other path. Only plain
`anidb-` maps: `anidb2`..`anidb9` group several AniDB entries under one
TVDB-numbered show, so the guid names the root entry only.

Two guards keep the new id where it means something. It is trusted for
season 1, because that mode puts the anime there and its specials in
season 0, while a higher season means the library is numbered by TVDB
instead. And it resolves nothing for Trakt and Simkl, which never map
anime and cannot address an AniDB id, so they keep reporting no ids
rather than failing silently further down. `hasCatalogIds` marks the
callers that can only speak IMDb/TMDB/TVDB.

close #1788
2026-08-04 16:56:54 +02:00
edde746 4872adcde3 feat(player): keep the session's explicit track choices across episodes
Episode advance carried live player state, so the viewer's choice only
survived while every episode could serve it: one episode without the
picked audio or subtitle fell back, and the fallback became the carry for
the rest of the session. The screen now keeps the last explicit audio,
subtitle, and secondary-subtitle choices for its lifetime; automatic
outcomes never overwrite them, so the choice retries on every following
episode and reattaches as soon as a catalog can serve it again.

Audio catches up with the subtitle carry from #1785. The old matcher
required raw language equality (a 'sv' pick never found a 'swe' row) and
otherwise took the first same-language track, flipping a commentary or
alternate-mix pick back to the main mix on every episode. Audio now uses
the same evidence bands as subtitles: bridged language parity is
authoritative, a unique title match vouches for untagged tracks, codec
and channel-count parity only break ties, and an ambiguous catalog
declines to the server's own choice instead of guessing. The synthesized
source descriptor also prefers the row's own title over the display title
that collapses to the bare language.

Episode advance previously sent no audio hint to negotiation at all, so a
transcode baked in the server's default audio no matter what was playing.
Both backends now resolve the carried semantics against the new episode's
streams: Jellyfin sends the resolved AudioStreamIndex, Plex feeds the
transcode decision, an explicit per-part stream id always wins, and a
failed match falls back to the server's pick.

close #1785
2026-08-04 16:10:02 +02:00
edde746 61ae314c94 fix(player): tell same-language subtitle rows apart across episodes
The committed track kept the server display title, which collapses to the
bare language ("English") and is identical for every same-language row: a
carried signs/songs choice tied with the full dialogue track on the next
episode and latched onto whichever row sorted first. The row's own title
is preferred now, so the carried intent names the exact row again and the
native pass can match the right container track by title instead of
language order.

Reproduced against a live library where both English ASS rows differ only
by Title ("Styled Subtitles" vs "Signs/OP/ED").

close #1785
2026-08-04 15:22:46 +02:00
github-actions[bot] d82a5c5cd7 chore: bump version to 2.12.0 2026-08-04 13:03:59 +00:00
edde746 fdd4c661fe fix(player): carry a picked subtitle language across episodes with sparse tags
The cross-item subtitle intent required declared languages on both sides,
and a null on either side counted as a contradiction. Any untagged track -
common when a title like "Swedish" is the only signal - declined on every
episode advance, fell to the server's per-item priority, and turned the
viewer's subtitles off (a 2.11.0 regression from the #1716/#1717 hard
gates).

A unique real title match now vouches for a row when language evidence is
missing on either side. Declared languages that disagree still decline no
matter what the title says, forced-class parity is untouched, codec and
external parity only break ties within the title-matched set, and a
residual tie declines rather than guesses, so the wrong-track class of
#1716 stays closed.

A decline is also no longer laundered into a viewer decision: the resolver
keeps the unserved preference on the selection, the open flow hands it to
the track manager instead of a navigation-priority off (late native tracks
may carry the container tags the server rows lack), the next episode
boundary re-carries it instead of hardening it into an explicit off, and
progress reports withhold the -1 subtitle index that would otherwise come
back as the item's server-side default forever.

A pick the screen could not map to a source row (no subtitle catalog, or
an identity-matcher miss) previously never reached the committed session
selection at all, so the next episode carried the stale off while the
picked track was visibly on screen. Such picks now commit the raw native
track without source ids and demote to a semantic intent at the boundary.

close #1785
2026-08-04 13:51:20 +02:00
edde746 439ae1d733 perf(detail): paint a show before its on-deck episode is looked up
Jellyfin has no equivalent of Plex's bundled `?includeOnDeck=1`, so a show
detail open chained `/Shows/NextUp` behind the item fetch and the screen sat
on a spinner for both round trips. The second one is not needed to paint:
everything except the play button's episode label comes from the item.

`fetchItemWithOnDeck` now takes an `onItemReady` callback and invokes it as
soon as the item is known, when that is strictly before on-deck settles.
Plex returns both together and never invokes it.

Phone and desktop only. TV keeps its own reveal gate — `_isTvDetailReadyToReveal`
holds the foreground at opacity 0 until extras, related hubs, seasons and the
first episode page have all loaded, and those still run after the on-deck
lookup settles, so TV sees no change. Both halves are pinned by tests.

Measured on a remote Jellyfin server, 15 interleaved show-detail opens per
version: time to content 1264ms -> 1042ms (-18%), with the rest of the load
unchanged.

Seasons and extras deliberately still start after the whole lookup settles.
Starting them at the early paint measured worse (time to settled +21%)
because they contend with the on-deck request instead of overlapping it — the
same reason `/Shows/NextUp` is not fired in parallel with the item fetch.
That trade-off is also why TV was left alone rather than being unblocked by
moving those loads earlier.

Two ordering hazards the early paint introduces, both covered by
`media_detail_screen_test.dart`:

- The early call must not write on-deck. `_loadFullMetadata` runs again after
  playback, and clearing there would blank the play button for the length of
  the round trip. `onDeckSettled` marks the authoritative write, so a reload
  that finds the series finished still clears it.
- A settled empty on-deck must not drop the episode-derived fallback that
  `_ensureFallbackOnDeckEpisode` supplies.

close #1784
2026-08-04 08:38:19 +02:00
edde746 a759e8b3c6 perf(jellyfin): fetch a detail item once when several callers want it at once
Opening a detail screen issued two identical full-detail GETs for the same
id, concurrently: `_loadFullMetadata` calls `fetchItemWithOnDeck`, and
`_initWatchlistState` calls `fetchExternalIds`, which fetches the same item
purely to read `ProviderIds`. Playback start adds three more for its own id.

Each of those makes the server rebuild the entire dto — `People`, `Chapters`
and `MediaSources` cost a database query apiece and `Trickplay` costs several
plus a filesystem stat — so the duplicate is expensive on both ends.

`fetchItem` now shares an in-flight request per item id. Single-flight only:
once a request settles the next caller re-fetches, so nothing can serve a
stale item.

Measured on a remote Jellyfin server, 12 interleaved show-detail opens per
version: requests 4 -> 3, payload 28.4 KB -> 18.6 KB. Median wall time is
unchanged (1394ms -> 1386ms) because the duplicate ran alongside the first
rather than behind it; this removes duplicated work, not latency.

Two things were tried and rejected because measurement did not support them:
starting `/Shows/NextUp` in parallel with the detail fetch (the requests
contend rather than overlap — NextUp went from 380ms alone to 1395ms beside
it — and it costs a wasted request per movie), and dropping `Trickplay` /
`Chapters` from the detail field set (no measurable effect; both are real
data the playback path reads).

Refs #1784
2026-08-04 06:39:23 +02:00
edde746 74d3af3ae1 perf(home): load the home screen once instead of twice per cold start
The Discover tab fanned out its whole request set twice on every cold
start and replayed slow rows on a shrinking timeout ladder, so a healthy
remote server produced anywhere from 4s to 15s of loading.

Measured against a remote Jellyfin server with four libraries, 24
interleaved cold-start samples per side:

  requests  19 -> 9      payload  219 KB -> 94 KB
  settled   5231ms -> 2502ms median, 13222ms -> 5927ms p95

Four independent causes:

- Retry policy. `Client.send` resolves on response headers, so the
  connect budget covers the server's think time and a slow-but-alive
  query raises `connectionTimeout`. Replaying it made the server re-run
  the query with a shorter budget than the one it just missed; the
  `[10s, 8s, 5s]` ladder turned an 11s answer into an empty row after
  23s. Hub surfaces now get one whole-request deadline, retry only
  immediate connection errors, and the deadline bounds the whole call
  including the request still in flight.

- Request shape. `/Items/Latest` groups a TV library by series, so its
  rows are Series folder dtos and `RecursiveItemCount`/`ChildCount` cost
  a DB count each, per row. Hub rows now ask for `Overview` only; watch
  state survives because Jellyfin derives `UserData.Played` from
  `UnplayedItemCount` when the count fields are absent. `/Shows/NextUp`
  sends `NextUpDateCutoff` to bound the server's series-key scan, and
  `Thumb` leaves `EnableImageTypes` since nothing reads it. `UserData`
  and `PremiereDate` leave the browse set: neither is an `ItemFields`
  member, so the server dropped them anyway.

- Fan-out. Per-library hubs ran in batches of three separated by a
  barrier, so one slow library stalled every library behind it. A
  sliding window keeps the same peak concurrency without head-of-line
  blocking. Concurrent `fetchLibraries` calls now share one `/Views`
  instead of racing two identical round trips, Plex's global and music
  hub legs start together, and Jellyfin gets Plex's pool tuning.

- Duplicate pass. `DiscoverScreen.initState` starts a load and the
  online-entry hook asked for a full refresh on top of it, which
  `CoalescedLoadCoordinator` correctly queued as a trailing pass. The
  hook now calls `primeRefresh`, which rides along with a load already
  in flight; profile switches still go through `fullRefresh`.

Refs #1784
2026-08-04 04:35:06 +02:00
edde746 8624c37041 fix(profiles): notice a corrected connection creation time
ActiveProfileProvider diffed connections on toConfigJson alone, but
createdAt is a real column and now decides which connection lends a
profile its picture. A creation-time correction was therefore invisible
to the guard and left a stale avatar until the next launch.

Compare createdAt alongside the config. ConnectionRegistry pins
creation order across re-authentication, so this adds no notifications
in normal operation — it only stops an out-of-band correction, such as
a restore or a backfill, from being swallowed.
2026-08-04 02:22:44 +02:00
edde746 7a19f4149e fix(connections): keep a connection's creation time across re-authentication
ConnectionRegistry.upsert already preserved isDefault on conflict but
rewrote created_at from the in-memory model. Re-signing in rebuilds the
connection with DateTime.now() under the same stable id, so the row's
creation time jumped forward on every reauth.

That was cosmetic while created_at only drove list ordering. It is now
behaviour: it picks which connection lends a profile its picture, so
re-adding the originally-first connection could hand the avatar to a
later one. remove() also promotes the oldest remaining row to default
and was reading the same restamped value.

Preserve the existing row's created_at on conflict, reusing the lookup
upsert already performs for isDefault.
2026-08-04 02:22:44 +02:00
edde746 860ce1e11a feat(profiles): show the first linked connection's user picture
A local profile had no picture of its own and always fell back to
initials. It now borrows the user picture of the connection it was
linked to first — oldest Connection.createdAt, ties broken by
connection id, since the join table carries no creation time.

Jellyfin links resolve to /Users/{id}/Images/Primary, keyed by the
PrimaryImageTag now captured at authentication and refreshed from the
/Users/Me body checkHealth already fetches. That endpoint is anonymous
on every Jellyfin release, so the URL carries no api_key and the access
token stays out of the image cache key. Plex links resolve the Home
user the link points at against PlexHomeService's live cache, so no
account-level lookup is needed and the picture tracks Plex's own
refresh.

The picture is derived per snapshot and never written back onto a
Profile: ProfileDetailScreen upserts the model it holds, so a
persisted URL would go stale and outlive the connection it came from.
Plex Home profiles are untouched, including one whose Plex avatar is
unset — it keeps its initials rather than borrowing a lent connection's
picture.

close #1667
2026-08-04 02:22:44 +02:00
edde746 2b4875d389 fix(player): keep hidden and cycled subtitles off in the next episode
Episode navigation carries the subtitle choice this screen has committed, so
a way of turning subtitles off that the screen never sees is undone by the
next episode.

ExoPlayer has no renderer-level visibility switch, so the player's hide
toggle is emulated by deselecting the track. That emulation lasted until the
next selection: the automatic pass after an episode change put subtitles
straight back on screen while the toggle still read "hidden", and un-hiding
then restored a track id belonging to the episode that had already ended.
Hiding is now sticky across media opens the way mpv's global sub-visibility
is, selections made while hidden become what un-hiding restores, and the
toggle no longer refuses to restore because the hidden track reads as Off.

Cycling subtitles over the native track list — downloads, and items whose
server exposes no subtitle rows — went straight to the track manager, which
owns the player selection and the server write-back but not the committed
choice. The screen records the cycled track now.
2026-08-03 17:07:14 +02:00
edde746 e7aa1e4782 fix(jellyfin): stop overriding a server subtitle mode of None
Jellyfin answers PlaybackInfo with a null DefaultSubtitleStreamIndex when the
user's SubtitleMode is None: the index is the server's whole answer, and null
means it picked no subtitle. The mapper read null as "the server did not say"
and promoted the container's default/forced flags to a server selection
instead, which outranks the profile subtitle mode in the selection ladder. A
viewer who had turned subtitles off for their Jellyfin user got them switched
back on by every item that carried a default or forced row.

Only the row the server names is selected now. A stream the viewer picks, and
an explicit off, still survive per item because Plezy reports the index
through playback progress and the server hands it back as that index or -1.

close #1779
2026-08-03 17:07:05 +02:00
edde746 bbaf5f0f9e fix(music): replace the Instant Mix faders with a wand icon
The three vertical faders read as an equalizer in a music context and
are the vertical twin of the video player's settings icon. Use
wand_stars, which names what the action produces and collides with no
neighbouring affordance in the action bar or the music context menu.

close #1629
2026-08-03 13:29:27 +02:00
edde746 0f5e5c8b6e feat(music): offer File Info on tracks and other file-backed items
The context menu only offered File Info for movies and episodes, so a
track's path, container, and audio stream detail were unreachable even
though both backends already answer getFileInfo for them.

Gate the entry on the new MediaKind.hasFileInfo instead of a literal
kind list: movies, episodes, tracks, and clips are leaf items with real
files, while shows, seasons, artists, albums, collections, playlists,
and folders carry no Media/MediaSources and would only ever produce the
"not available" snackbar.

Also fix the Plex stream classifier, which mapped streamType 4 to an
embedded image although PlexStreamType.lyrics is 4. Only music tracks
carry that type, so a track's lyric stream rendered under "Embedded
Images" with the video field block. Type 5 was invented outright and is
now unknown.

close #1747
2026-08-03 02:34:37 +02:00
edde746 a9f0532f5f fix(ui): keep pushed screens clear of the Android navigation bar
Plezy is edge-to-edge on Android whether it asks to be or not: targetSdk is
36, Android 15 enforces edge-to-edge for apps targeting 35+, and Android 16
disables the windowOptOutEdgeToEdgeEnforcement escape hatch. The only
SystemUiMode.edgeToEdge call in the app fires on video-player exit, so on
API 35+ the window is edge-to-edge from the first frame and
MediaQuery.padding.bottom is a real ~48dp overlap under 3-button navigation.

MainScreen's phone layout hides that. It supplies a bottomNavigationBar and
never sets extendBody, so Flutter's Scaffold strips padding.bottom from the
body MediaQuery and every tab is already safe. Routes pushed on the profile
navigator are full-screen siblings of MainScreen with no bottom bar, so they
receive the untouched inset and nothing consumes it - the last settings card
and the final log lines render under the back, home, and recents buttons.

Three shared hosts own most of those routes, so the inset is consumed there:
FocusedScrollScaffold (25 screens, counting the SettingsPage wrapper) and
FocusableDetailScreenMixin.buildDetailScaffold (4) now append a trailing
SliverSystemBottomInset, and the four screens that build their own Scaffold
around a CustomScrollView append it directly.

The new widget codifies the convention this repository had already written
down but open-coded - insets baked into the scroll content rather than a
SafeArea around the scroll view - so content still paints under the bar while
the scroll extent grows enough to bring the last row above it. It reads
padding from its own context and collapses to zero height wherever the inset
is already zero: desktop, Android TV, tvOS via _AppleTvScale, and inside
MainScreen's tab bodies. No platform branching, and it stacks additively with
the music detail screens' existing mini-player spacers, which is correct
because the mini-player itself floats above the navigation bar on a pushed
route.

Scroll views that are not sliver lists take the inset in their own padding:
the companion remote's ListView, the auth screen's scroll container, and the
two SliverFillRemaining sign-in forms, whose children size themselves from
the extent remaining before them and so cannot be helped by a trailing
sliver. The logs empty state is left alone for the same reason inverted - it
already fills the viewport, and a trailing inset would only add scroll slack.

Verified on a Pixel 7 running Android 16 (API 36) with 3-button navigation:
Settings, Logs, and Video Playback all end clear of the bar.

close #1766
2026-08-03 00:05:21 +02:00
edde746 fb0613e3db feat(player): toggle playback on a two-finger tap without raising the chrome
A touch viewer had to raise the chrome to pause, which dims the picture and
covers the subtitle line they were trying to finish reading. A two-finger tap
now toggles playback with the chrome left down, so the frame that pauses is the
frame that was on screen. It fires the moment the chord resolves, in every
player state.

The two-finger double tap no longer resets the video zoom. Keeping it would mean
holding this toggle back for the double-tap window before acting, and pausing
late is pausing on the wrong frame. Zoom reset stays in the video settings sheet,
its presets and the keyboard shortcut, and pinching back to 100% now snaps
exactly within three percent so touch has a one-gesture path too.

Both chord actions share _mobileTouchGesturesAllowed, so the chord is inert
under screen lock, in PiP and while the content strip is open; the zoom reset
previously fired straight through a locked screen.

close #1505
2026-08-03 00:04:03 +02:00
edde746 9c08c78f6d fix(plex): stop recording a second play when the server already logged one
Plezy reported a completed playback twice: the /:/timeline heartbeats let
the server mark the item played on its own, and the in-player auto-scrobble
then sent an explicit /:/scrobble for the same watch. On PMS 1.30 that adds
a second Play History row; on 1.43 the row is suppressed but viewCount still
lands on 2 for one playback.

Measured against PMS 1.43 to find what the server acts on: a watched-threshold
crossing observed inside one session. Consecutive above-threshold reports mark
nothing, a resume point left by an earlier session does not arm a new one, and
a report at position zero is inert while one at a single second is enough. So
the explicit mark now goes out only for sessions that gave the server no
crossing to observe.

That decision cannot be made while the session is live. A session beginning
past the threshold has no crossing yet, but rewinding and playing forward
creates one, and the server records it — marking eagerly and then hitting that
path leaves viewCount at 2 again. The mark is therefore deferred to the
terminal stop, and rides its future so callers that await the stop before
tearing the player down do not drop it. Deferring also covers a crossing
coalesced away during startup and a seek back below the threshold before
stopping.

Crossing state is tracked from reports the backend actually received rather
than from PlaybackReportSession.report()'s bool, which resolves true for a
same-state snapshot dropped during startup.

The same-file sibling hook (#1500) still runs exactly once, on the transition
to a settled mark rather than at the local crossing, so sibling episodes are
never marked watched while the episode actually played is not.

Local watched state and Continue Watching removal still happen on the observed
crossing, so the only behaviour that moves is the redundant server call.

close #1740
2026-08-02 16:16:19 +02:00
edde746 95b013e155 fix(seerr): show worldwide popular titles in Explore again
Overseerr and Jellyseerr bind the `language` query parameter of
`/discover/movies` and `/discover/tv` to `originalLanguage`, which becomes
TMDB's `with_original_language`. Sending the app locale there collapsed both
shelves to titles originally made in that language, so a Portuguese UI saw
only Portuguese films. Those two routes take their display language from the
instance/user locale, which already wins over the query value, so the
parameter was pure filtering with no localization to show for it.

Drop it from the two paged discover routes. Trending, both upcoming rows,
search, details and recommendations keep it: Seerr treats it as the display
language everywhere else.

close #1763
2026-08-02 15:35:42 +02:00
edde746 d83d0790ba fix(exoplayer): match side-loaded subtitles after media3 rewrites track ids
Plex sidecar subtitles are attached as MediaItem.SubtitleConfiguration and
tagged `external_<n>`, then recovered from the Format id the track selector
reports. Since media3 1.3.0, DefaultMediaSourceFactory always merges
side-loaded subtitles with the primary source and MergingMediaPeriod rewrites
every child format id to "<periodIndex>:<originalId>", so the tag arrives as
"1:external_0" - measured on device - or "0:1:external_0" behind the
container-sidecar merge. The prefix test therefore never matched and every
sidecar reached Dart as an embedded track with no URI.

A Plex sidecar's only identity is its stream key, which the app carries in
that URI, so both matchers failed on it: a server-selected sidecar could
never resolve and left subtitle selection pending, and a manually chosen one
could not be mapped back to a stream id to write to the server. The
already-attached branch of addSubtitleTrack compared the raw id too, so
re-selecting a loaded sidecar silently did nothing.

Route every write and readback of the tag through ExternalSubtitleIds, which
matches the final id segment, and cover it with an instrumentation test that
side-loads a subtitle through the real media3 media-source factory. Also stop
claiming a saved track selection when no server stream was identified - there
is no local store, so that path silently dropped the user's choice.

close #1713
2026-08-02 12:19:28 +02:00
edde746 bbed260169 fix(player): start the TV player with its chrome down
A television raised the whole OSD and timebar on every playback start. The
chrome controller is born visible, and its auto-hide clock cannot arm until the
first frame lands, so the controls did not merely appear early: they appeared
exactly when the picture did, and then sat over the opening five seconds of
every movie and episode. The timeline is gated behind the first frame, so the
bar materialised on top of the video rather than over the loading spinner,
which is what makes it read as a pop-up rather than as chrome that was already
there.

The route now opens with no chrome on TV. Nothing is lost: the loading spinner
and buffering overlay are their own overlays, the screen focus node owns back,
and the first D-pad press raises the controls the way it already does after
every auto-hide. Pointer and touch platforms keep the chrome, where the
viewer's hand is on the surface and the title and back affordance belong over
the spinner.

Initial presentation now follows initial visibility. They were separate:
seeding only visibility would leave the route claiming its chrome was still
presented, so PlayerNavigationCoordinator would read back as "hide the chrome",
hide() would no-op against chrome that was never up, and the press would be
swallowed instead of leaving the player.

Controls that mount with the chrome already down now claim focus themselves.
Focus normally reaches them through the hide transition, and their own
autofocus cannot win it back because the screen node took it during the loading
phase. Left alone, the screen node kept primary focus and its self-heal raised
the entire OSD on the first D-pad press, which put the chrome straight back
over the picture and bypassed the transient seek and transport indicators.

Both player spinners now carry a label. They were bare progress indicators, so
a screen reader announced nothing at all while the picture was coming up, and
the TV Maestro flows had no way left to tell a loading player from a playing
one once the Pause button stopped appearing on its own.

The two TV flows are repaired to match. They waited on that button, and now
wait for the labelled spinner to clear, which cannot happen before the media is
opened. 05 additionally reaches Search by D-pad rather than a percentage
coordinate, because a tap flips InputModeTracker to pointer mode and collapses
the rail it is aiming at, and it gates on the play-next prompt's own Cancel
action: "Next Episode" is also the credits skip button, so the old assertion
could pass without the prompt ever opening.

close #1765
2026-08-02 11:45:27 +02:00
edde746 35061f9f68 fix(jellyfin): scope global search to visible libraries
Jellyfin search rows do not expose their owning collection, so hidden libraries cannot be filtered after the response. Scope searches to visible libraries, stamp the returned rows, reuse the latest loaded views, propagate cancellation, and fail closed when views cannot be loaded.

Keep full candidate budgets and split music libraries into parallel album, audio, and artist requests. Album requests disable UserData and use the existing album field set to avoid recursive per-album work from #1552; audio requests retain cheap leaf play state.

close #1770
2026-08-02 09:29:59 +02:00
edde746 1d9ffb7427 fix(search): exclude hidden libraries from global search results
searchAcrossServers was the only aggregation entry point without a
hiddenLibraryKeys parameter, so libraries hidden from home hubs, Continue
Watching and the library rail still surfaced their contents in the Search
tab. Thread the profile's hidden keys from SearchScreen through to the
aggregation, and drop matching items between the fan-out and the ranking
pass so hidden hits cannot spend the result limit and shrink what is
shown. Items the backend cannot attribute to a library, such as Plex
shared and external media, are kept.

The screen re-runs the visible query when a library is hidden or unhidden
while results are on screen. Its listener is attached only after the
provider has hydrated, so the initial load notification cannot race the
first query into running twice.

Plex search rows now go through the library-aware tagger, so a response
that names its section only via librarySectionKey or
targetLibrarySectionID is still attributable, and therefore filterable.

Jellyfin search results carry no library id at all: the mapper's
ParentLibraryId is not a Jellyfin field, and ParentId resolves to a
season or physical folder rather than a CollectionFolder. Filtering there
needs server-side ParentId scoping and is left for a follow-up.

close #1770
2026-08-02 09:29:59 +02:00
edde746 bac2a0d201 fix(player): keep Delete and Home editing text in player sheets
Bare Backspace and Home are player navigation keys, but they are also
caret editing keys. The player screen's Focus wraps its OverlaySheetHost,
so it saw them before the subtitle-search field could act: the press was
consumed on key-down, DefaultTextEditingShortcuts never turned it into a
deletion, and the back pipeline hid the chrome and then left the player.

A focused text editor now takes both keys back, but only for physical
keyboard presses — a synthesized dpad/gamepad press has no caret, and
browserHome has no editing role at all.

The screen also resolved its overlay-sheet controller from the State's
own context, which sits above the host it was querying, so the lookup
always returned null and Back skipped the sheet stage entirely. Resolve
it from a context below the host instead, matching NowPlayingScreen.

close #1741
2026-08-02 07:37:12 +02:00
edde746 2a7e5f4f9c fix(jellyfin): ask the server who may delete before offering it
Jellyfin never consults IsAdministrator when authorizing a library
delete: BaseItem.IsAuthorizedToDelete looks at EnableContentDeletion and
the per-library grant, and only the first user a server creates gets the
former for free. Gating the "Delete from server" entry on the admin bit
therefore offered a destructive action that answers 401 to later
administrators, and hid it from plain users who do hold the grant.

Ask the server per item instead, through the new
MediaDeletionPermissionClient capability: BaseItemDto.CanDelete already
folds the global grant, the per-library grant, and item state such as
missing files or an in-progress recording. The probe runs when a menu
opens on a deletable kind, costs ~0.5 KB, carries a whole-request
deadline because the client's own budget covers connect and receive
separately, and fails closed on anything unknown. Plex keeps its
account-level owner/admin gate; it has no per-item permission on the
wire.

close #1749
2026-08-02 07:08:14 +02:00
edde746 bc0d14a749 fix(explore): list every library copy of a title, not one per server
`MediaServerClient.findByExternalIds` returned `MediaItem?`, so the Explore
"In these libraries" chooser could never show more than one copy per server.
A movie held by both a 4K library and an HD library on one Plex server
therefore resolved to whichever copy came back first, with no way to reach
the other.

Return every id-verified match instead. `/library/all` is already
server-wide and each `Metadata` entry carries its own `librarySectionID`,
so both copies come back labelled with no extra request; Plex was simply
taking `Metadata[0]` and the title ladder was returning on its first hit.
An exact-guid hit no longer short-circuits the title search either — a
library still on a legacy agent has a different primary guid and is
invisible to the `guid=` filter.

Copies are deduped by global key and ordered best-first, and each row now
states its resolution, since library names need not mention it.

Resolution passes merge rather than replace: the cross-server fan-out logs
and skips per-server failures, so a later pass can come back short a server
that answered an earlier one, and a failed pass no longer claims the title
left the library. Duplicate keys fold field by field, because Jellyfin's
library stamp is a best-effort ancestors lookup that returns the item bare
when it fails and an unstamped row is indistinguishable from its sibling.
Focus nodes are keyed by copy and reclaimed after a merge re-sorts the
rows, so a dpad user is not thrown to a different copy.

close #1754
2026-08-02 06:40:04 +02:00
edde746 f78f65faf5 chore(player): report marker counts when loading playback extras
The extras loader logged only the chapter count, so a user report of
"auto skip never fires" could not be told apart from "the server has no
intro marker for this item" — the two need opposite fixes. Log the
marker count and types on all three load paths, including the cache-only
one that previously logged nothing at all.

Drop PlexVideoPlaybackData.markers while here: the playback-start parse
filled it on every item and no caller ever read it, because the player
controls fetch their own PlaybackExtras.

Document why getPlaybackExtras may serve the shared metadata cache row
without a freshness check: getPlaybackInitialization refreshes that row
network-first before the controls mount. That ordering is what makes
cache-first correct, and nothing said so.
2026-08-02 04:55:54 +02:00
edde746 957711a650 fix(startup): lead the damaged-store screen with the repair, not retry
A reporter on #1732 ran three successive builds against a preference store of
10336 bytes, every one of them zero, and reported each as "still failing". The
gate classified it correctly every time and the consented repair would have
cleared it in-process, but nothing on the failure screen said so: Retry was
first, styled `FilledButton`, and autofocused, while `Repair storage` sat beside
it as a tonal afterthought. Retry re-reads the same document, so for a
corrupt-store failure it is an action that cannot succeed however many times it
is pressed — and it was the one the screen recommended.

Repair now takes the primary styling, the focus node and first position whenever
it is offered, and the body text says plainly that retrying will not help.
Retry keeps its place for every other failure, where a locked database or a
denied directory really can change between attempts.

The consent dialog was also promising an outcome it could not always deliver.
Servers and profiles survive a repair only because their tokens are ciphertext
in the database and the key that decrypts them lives in the store, so a store
the key cannot be read out of signs the user out of everything — exactly the
all-zero case. `PrefsRecovery.previewSalvage` reads the damaged file without
touching it, and the dialog now names the real cost from that. The retained copy is
labelled as holding credentials unless the bytes prove otherwise: what the
salvage recovered says nothing about what the file still contains, because a
store truncated mid-value keeps most of a vault key in plaintext while the
salvage pattern — which needs the value's closing quote — matches nothing at
all. Only an all-zero file drops the warning, so the one case that cries wolf
is the one that provably holds no secret.

`describe()` finally carries whether a repair was on offer. That line is the
difference between a report a maintainer can act on and two days of guessing
whether the button was even on screen.

close #1732
2026-08-02 04:37:29 +02:00
edde746 2cb2c3eb95 feat(ratings): show every rating source the server already sent
Plezy rendered exactly one score per item. MediaRatingBadge._ratingDataFor
took `rating` and fell back to `audienceRating` only when it was null, so a
Plex movie carrying four attributed scores surfaced one, and which one was
whatever the server happened to put in the scalar slot. #1755 asked for a
setting to choose the source; showing all of them answers it without one.

The data was already on the wire and being thrown away. `/library/metadata/
{id}` returns a `Rating[]` child array — IMDb, both Rotten Tomatoes panels,
TMDB — with no extra query parameter, but PlexMetadataDto declared no field
for it, so json_serializable dropped the key. The identical parse already
existed in plex_catalog_source for the Explore tab and had simply never been
wired to library items.

Model the scores as a list rather than widening the scalar pair. The neutral
MediaItem gains `ratings`; PlexMediaItem loses audienceRating, ratingImage
and audienceRatingImage, which the list subsumes — Plex sends those images
on listings too, so the same field covers both response shapes and no caller
narrows to a backend type to read a score any more. CatalogRatingSource is
promoted to lib/media as MediaRatingSource instead of growing a second
near-identical type beside it, and plex_catalog_source's _ratingsFor becomes
the shared plexRatingSources so one implementation serves both paths. There
is no persistence to migrate: MediaItem.toJson has no production caller, the
offline path re-parses raw Plex JSON through the same mapper, and Plex's
audienceRating sort is server-supplied data, not a model read.

Cards and the dashboard still show fewer scores than detail screens, and
that part is a real Plex limit rather than a shortcut. Section listings send
only the scalar pair; includeRatings, includeElements=Rating,
includeFields=Rating, includeChildren and includeExtras were each probed
against a live server and none surfaced the array, while includeGuids=1
demonstrably does add Guid[] — the probe works, the parameter does not
exist. Hydrating every card would be one request per row, so listings render
whatever their own response carried, which is one or two attributed scores
rather than the single one they showed before.

Jellyfin has no per-source array at all: the server collapses whatever its
fetchers found into CommunityRating and CriticRating. CommunityRating's
provenance is unknowable from the DTO — TMDB vote_average, IMDb via OMDb or
a local NFO, last writer wins — so it stays the generic `audience` source
with no brand mark. CriticRating is the Rotten Tomatoes Tomatometer as a
0-100 percent and is divided by ten explicitly rather than folded by
magnitude, because a Tomatometer of 9 means 9% and range-sniffing would have
promoted a rotten score to fresh. Photo rows are skipped, since Jellyfin
reuses CommunityRating for the EXIF 0-5 star.

The badges share one slot on every surface. On the phone hero the scores go
in a single pill because that chip row is a height-clipped Wrap and a chip
per source would push year, certification and runtime out of the visible
band on short heroes; on the TV detail line and the dashboard spotlight the
group occupies the one metadata slot so bullet separators do not multiply.
The group announces itself as a single semantics node naming each source,
because a bare row of four percentages tells a screen reader nothing about
which score is which. rating_utils drops parseRatingImage and
isRottenTomatoes — the URI vocabulary now lives only in the Plex mapper —
and the source-key resolver and label map, previously private to the Explore
detail screen, become the shared pair both screens use. The label strings
move from explore.ratingSource to common.ratingSource accordingly, which
costs no translations because every non-English value was empty; running
clean_translations also scaffolds startup.quitPlezy and
startup.restartRequiredBody, which were already drifted.

Verified against the live server the probes came from: a detail response now
yields TMDB 83%, IMDb 8.3 and Rotten Tomatoes audience 96% through the
production mapper and badge resolver, and the listing response for the same
title yields TMDB 83% alone. Both payloads are pinned verbatim as fixtures.
Coverage adds mapper ordering, dedupe against the array's repeat of the
scalar, out-of-range rejection, the Jellyfin scale and photo guard, the
CatalogItem conversion that feeds Explore's dashboard hubs, and the three
render surfaces including the semantics announcement.

close #1755
2026-08-02 03:59:56 +02:00
edde746 395798f28e fix(player): stop handing ExoPlayer the demuxer's buffer budget on Auto
On Auto, Dart derives a buffer size for mpv's demuxer from the device heap and
sets it as `demuxer-max-bytes`. The Android player forwarded that same number to
`DefaultLoadControl.setTargetBufferBytes`, so ExoPlayer's sample allocator was
sized by a tier table written for a different consumer: 64MB on any device whose
large heap is 512MB or less, which every Shield is.

`targetBufferBytes` is a byte cap, so the media it represents collapses as
bitrate rises — 64MB is 53s of a 10 Mbit/s stream but 5.2s of a 103 Mbit/s UHD
remux. With `prioritizeTimeOverSizeThresholds` false the cap is hard:
`shouldContinueLoading` returns false the moment the allocator reaches it no
matter how little media that is, and `shouldStartPlayback` reports READY off the
same byte term. Read-ahead that short starves the audio sink in bursts, and on a
passthrough route that is enough to keep the AudioTrack from ever starting — the
track initializes, accepts one access unit and never renders a frame. Because an
enabled audio renderer owns the MediaClock, the whole player freezes and the
black-screen watchdog then blames the video decoder and drops the session to
mpv.

Size the LoadControl target natively instead, from what actually bounds
`DefaultAllocator`: the Java heap. `min(media3's own default for a video+audio
selection, largeMemoryClass/4, availMem/4)` with a 32MB floor, the lowest tier
that has already shipped. The quarter matches the threshold the Buffer Size
setting already warns at, and the media3 default is a ceiling — this is not
"buffer more than upstream", it is "stop buffering less". Deliberately not
bitrate-aware, because the LoadControl is built during initialize, before any
media is opened. `bufferSizeAuto` carries the distinction over the channel;
`bufferSizeBytes` still travels with it because the plugin's mpv fallback
replays it as a real demuxer property, and an explicit Buffer Size choice is
still honoured verbatim.

Confirmed against the hardware in the 2.9.1 passthrough report. That reporter's
own log is a natural A/B: three runs at 64MB fail with `0 frames rendered after
8002ms`, spanning both DV conversion modes and both tunneling states, while the
single run after he manually selected 128MB logs `Position advancing` and
renders. Reproduced on the same Shield model with codec and bitrate held fixed
and only the cap varied — 6s of audio demand stalls at 64MiB and plays at
128MiB, 4 of 4 predictions, with read-ahead measured off an injected
DefaultAllocator at 65 664 and 131 776 KiB. That device reports
`dalvik.vm.heapsize` 512m, so the heap term binds first at every free-memory
level in his log and Auto now derives exactly the 128MB he had to pick by hand;
the shipped path logs `Buffer: 128MB limit (auto, heap=512MB, available=568MB)`
where it previously logged 64MB.
2026-08-01 06:59:21 +02:00
edde746 3f49bcabf8 fix(prefs): replace the desktop preference store atomically
Upstream shared_preferences_windows and _linux write the whole preference
document with a bare `writeAsStringSync`. That opens with the default
`FileMode.write`, which truncates the live file before writing it, so every
single preference write has a window in which the only copy on disk is empty
or half-written. A crash, power loss, forced reboot or antivirus interception
inside that window leaves a document that fails to parse on every subsequent
launch — and the store holds the credential-vault key, so the loss is not
recoverable by rewriting it. This is the corruption class behind #1732; the
recovery path already landed is a band-aid over it.

Vendor both packages under packages/ — the convention saf_util and
wakelock_plus already follow — and stage, flush, then rename over the target.
The flush has to precede the rename or it could publish contents that were
never committed, the same corruption by another route. Staging uses one fixed
sibling name rather than a stamped one, because the file is a plaintext copy
of the vault key, tracker refresh tokens and Seerr cookies; it is created in
the target's own directory so rename stays on one volume and the mode matches
what the canonical file would have had, and a stale one is swept once the
canonical document has been read cleanly. Both deltas are marked in-source and
in provenance.json with the refresh contract.

Atomicity is proven, not asserted. A hard link to the store observes the old
document after a write, which only holds when the directory entry was replaced
— truncate-in-place would have rewritten the shared inode, and that test does
fail against unpatched upstream. Upstream's own suites still pass unchanged in
both packages and now run in CI, so the patch keeps the contract it inherited.
Windows `MoveFileExW` replacement semantics cannot be proven on a POSIX runner
or a memory file system, so they get their own test on the existing
windows-latest job, including replacement while a reader holds the file open —
antivirus and Search Indexer both do.
2026-08-01 06:59:20 +02:00
edde746 9ecf8db90f fix(startup): stop offering Retry after a repair that needs a restart
A seed-and-restart repair writes the salvaged credentials straight to disk and
leaves this process's store closed, because the plugin still holds the bad
document in memory. repairCorruptStore says so plainly — "nothing may write a
preference before that restart … the caller keeps the app on the failure
screen precisely so nothing does" — but the caller did not. Clearing the
repairing flag re-enabled Retry, and pressing it reopened onto the stale map,
whose first write would flush it back over the seed and orphan every
ciphertext token in the database.

The repair hook returned a bare bool, which cannot express the difference
between "retry now" and "never retry in this process", so replace it with
StartupRepairResult. The restart case latches terminal state on the bootstrap,
withdraws Retry and Repair rather than grey them out — a disabled control
still invites another press — and says what to do instead, which nothing did:
repairNeedsRestart was a dialog title with no body anywhere. Desktop gets a
Quit button through the existing AppExitService seam; Copy and Upload stay
live everywhere, because a stuck user still needs the diagnostic out.

close #1732
2026-08-01 06:59:20 +02:00
edde746 3ae7aa554b fix(prefs): recover a preference store whose bytes are not valid UTF-8
`File.readAsString` reports a UTF-8 decode failure as a FileSystemException,
not a FormatException, so three guards written for that case never ran. The
preflight's `on FormatException` branch was unreachable and its
`on FileSystemException` sibling waved the document through; the plugin then
threw the same FileSystemException, which failed the FormatException/TypeError
test that decides repairability; and quarantine's lossy-decode fallback sat
dead behind a rethrow. A store with one bad high byte — a UTF-16 BOM, a stray
0x80 — therefore reached the user as a failure screen with no Repair button
and no way forward at all.

Read bytes and decode explicitly instead, at both sites. Classification moves
into describeStoreDamage, so a failure that surfaces after the preflight
passed is judged by re-reading the file rather than by the error's type: a
denied or locked store is indistinguishable from a decode failure by type or
message, and offering a destructive repair for a permissions problem would
reset every setting and risk the vault key over something a chmod fixes.
isCorruptStoreError went with it, having no remaining callers.

A repair that quarantines the store and then cannot reopen it no longer
strands the process either. The repaired future was built straight from the
cache loader, bypassing the self-healing reset sharedCache installs, so a
failed reopen parked a rejected future in _cacheFuture and every later attempt
replayed that stale error — with the damaged file already moved aside, so a
restart would have booted cleanly.

CorruptPreferenceStoreException now carries reopenSafe and a derived,
content-free shape: byte length, whether it decoded, whether every byte is
zero. #1732 arrived as "FormatException at offset 0" and nothing else, which
cannot separate an all-zero file from a non-JSON first character from bytes
that are not UTF-8; these can, and never quote the document.

Cover the loop against the real desktop backend rather than a fake.
shared_preferences_linux is pure Dart, byte-identical to the Windows
implementation, and exposes fs/pathProvider, so pointing it at a temp
directory exercises the genuine read, parse, cache and write path on any host
— the join between preflight, classification and reopen where every one of
these defects lived, and which had no coverage at all.
2026-08-01 06:59:20 +02:00
edde746 3509f4b989 docs: vendor the Microsoft Store badge as a PNG
GitHub sized the hotlinked SVG from its 161x44 intrinsic box rather than the
img height attribute, so the badge rendered short beside the other three.

rsvg-convert at exactly 4x intrinsic keeps the aspect ratio bit-identical and
the rounded corners transparent, matching the neighbouring badge assets. All
four now render 60px tall, and the README no longer hotlinks any image.
2026-07-31 22:52:07 +02:00
edde746 8a46df2850 fix(player): keep live TV on its retry ladder when a stream 404s
The 404 branch added in 16668be5 ran ahead of the live-TV fallback chain, so a
transient live 404 — an HLS segment rolled off the playlist, or a transcode
session restarting under us — showed "file unavailable" and killed a stream
the bounded ladder would have recovered. Only on-demand playback can read a
404 as terminal, where it really does mean the file is unreadable. 500 stays
terminal for both, since a limit rejection is not something a retry clears.

The dispatch lived in a private extension on the screen state, where no test
could reach the decision. Extract it as resolvePlaybackFailureAction next to
runLiveStreamRetry, which already sets that precedent, and cover both the live
and on-demand paths plus the ladder's rungs.
2026-07-31 21:45:33 +02:00
edde746 56ad48824b fix(jellyfin): pin MediaSourceId on every static stream URL
Jellyfin has no DirectStreamUrl field — MediaSourceInfo carries only
TranscodingUrl, and a DirectPlay decision returns no URL at all, leaving the
client to build /Videos/{id}/stream itself. The branch reading
DirectStreamUrl was therefore dead against every Jellyfin version, along with
the 'DirectStream' play method and the doc comment promising both.

The static URL also dropped MediaSourceId whenever the item had a single
source whose Id equalled the item id — an ordinary episode. The streaming
endpoint resolves a blank MediaSourceId to its own first sorted source
(VideoFile first, then widest video), so the omission silently streamed a
different file as soon as the item gained an alternate version. Forward the
id the negotiation settled on, as jellyfin-web, Findroid, and Streamyfin all
do unconditionally.

Every "pinned" fixture used a source id that differed from the item id, so no
test exercised the shape that dropped the param; add one that does.
2026-07-31 21:45:33 +02:00
edde746 4fe4f7b1d7 fix(mpv): stop loading the ytdl hook for media-server streams
Every URL the player opens is a media-server stream or a local file, so mpv's
bundled ytdl_hook has nothing to resolve. It still ran an on_load hook per
open and, whenever an open failed, spawned yt-dlp with the full stream URL in
its argv — access token included, readable through /proc on Linux. It also
added ~700ms to every failed open and buried the real "[stream] Failed to
open" line under three ytdl_hook errors.

mpv decides whether to load the builtin script inside mpv_initialize, so this
has to be an option set beforehand rather than a property set from Dart.
Verified against mpv 0.41: --ytdl=yes logs "Loading lua script
@ytdl_hook.lua", --ytdl=no never loads it.

Apple is deliberately excluded: the bundled libmpv is built without Lua, so
the option does not exist there and setting it would only print an mpv error
on every player init.
2026-07-31 21:45:33 +02:00
edde746 86c8011b72 fix(player): tell the user when the server cannot read the media file
A 404 on the media stream means the server resolved the item but could not
open the file behind it — moved, deleted, or on storage that went away.
Jellyfin maps the resulting FileNotFoundException to 404, and PlaybackInfo
never stats the file, so negotiation succeeds and only the stream request
fails. Playback then died with a snackbar reading "Failed to open
[REDACTED_URL]" before popping the route, which tells the user nothing and
leaves nothing useful in a bug report.

Generalize the HTTP-500 log probe into PlayerError.httpStatusFromLog and
latch every status in fatalPlaybackHttpStatuses. Each latches on its own so
the 503 that stream-lavf-o deliberately retries cannot mask the fatal status
behind it. A 404 now raises a dedicated modal naming the cause and the fix.

On Android a 404 previously failed the "Response code: 500" string test and
fell through to the ExoPlayer→MPV fallback, showing "switching to compatible
player" before failing again on the same request. Read the real status off
HttpDataSource.InvalidResponseCodeException instead and skip the fallback:
an HTTP status is not a codec problem.
2026-07-31 21:45:33 +02:00
edde746 6f9edd3e93 fix(startup): make the deferred crash report survive its races
The persist-then-flush model had four ways to lose or corrupt the record
it exists to protect.

A no-op hub — which is what a failed or timed-out crash-reporting init
leaves behind, because that phase is best effort — accepts an event and
returns an empty id without throwing. "Did not throw" was treated as
delivery, so the record was marked reported and suppressed forever.
Delivery now requires a non-empty Sentry id, and init completion is
tracked explicitly rather than assumed.

Opting out, and building without a DSN, are deliberate suppression
rather than delivery failure: both mark the record resolved so it is not
rediscovered every launch. Everything else stays pending, and
consumption no longer deletes an unreported record — deleting it ended
the only retry there was, which made "the next launch tries again"
false.

The write path is now a queue. Record writes were launched unawaited
from the failure path, so a fast retry could flush before the file
existed, consume before a late write landed, or run two writers against
one file and let the older one finish last. markReported joins the same
queue and compares record identity before rewriting, because reading and
writing outside it let a concurrent record land in between and be
overwritten by the record it had just superseded. Records carry an id so
that comparison is meaningful.

Consumption also waits on a registered flush, so the success path cannot
delete the file mid-send.

Also routes the tvOS recovery marker through the tolerant read.
reconcile() runs inside AppDatabase.open, a fatal gate step, so a
wrong-typed marker vetoed the launch outright on a first-class TV
target. Both new guards have regression tests verified to fail without
the fix.
2026-07-31 21:45:33 +02:00
edde746 9555937873 fix(startup): defer crash reports until the reporter exists
Reporting the failure inline was wrong for the phase that matters most.
The gate opens preferences before SentryFlutter.init, so a corrupt or
unreadable store — the likeliest cause of #1732 — was captured by a
NoOpHub and silently discarded, which is exactly the telemetry gap the
previous commit claimed to close. Initialising the reporter earlier is
not an option either: `_beforeSend` reads the crash-reporting opt-out
from settings, so events raised before settings load would bypass a
user's choice.

Every failure is now persisted first and flushed once the reporter is up
with settings loaded, which in practice is the user's own retry seconds
later in the same process. Records carry a `reported` flag so a send
happens exactly once, and a failed send leaves the flag clear so the
next launch tries again. The flush reads without consuming, so the
record still reaches Settings > Logs.

Also routes the tvOS recovery marker through the tolerant read:
`reconcile()` runs inside `AppDatabase.open`, a fatal gate step, so a
wrong-typed marker vetoed startup outright on a first-class TV target
despite the new default-instead-of-veto behaviour. An unreadable marker
tells us nothing, which is the same position as an absent one.
2026-07-31 21:45:33 +02:00
edde746 66549e3a67 fix(prefs): route every credential read through the tolerant path
The wrong-type recovery only covered reads that went through a
BaseSharedPreferencesService instance. The three stores that hold
credentials read the shared cache directly, so a mistyped value there
still threw a raw TypeError or, for Seerr, was swallowed by a catch-all
and reported as "no session" — the registry documented protection it did
not actually provide.

readPreferenceTolerantly now takes the cache, so CredentialVault,
TrackerAccountStore and SeerrSessionStore get the same classification as
the settings layer. CredentialVault's post-write re-read moves outside
its catch: a wrong-typed value written by another isolate was swallowed
there, and the process then returned a key that never durably landed,
making every ciphertext written under it unreadable on the next launch.

Those stores are consulted long after startup, where a throw is an
unhandled provider error rather than a repair prompt, so SettingsService
initialization now walks the cached key set once and reads every
sensitive key. That puts the failure inside a fatal gate step while the
store is still open and a surgical single-key repair is possible.

The remaining direct reads in settings and storage are routed too; the
only ones left are the library-density dual-type migration, which probes
both types deliberately, and an untyped switch that is type-safe by
construction.
2026-07-31 21:45:32 +02:00
edde746 7f0cad339c fix(startup): report and repair a failed launch instead of showing "Error"
Since 2.10.0 the whole app sits behind one all-or-nothing initialization
gate, and that gate discarded the only evidence of its own failure. It
caught the error, logged nothing but `error.runtimeType`, rendered an
icon plus the word "Error" plus Retry, and never reported the error
because catching it kept the crash reporter from ever seeing it. There
is no log file on any platform, the buffer is in memory only, a
double-clicked Windows release build has no console, and the log viewer
lives in Settings, behind the gate that just failed. #1732 is the result:
a Windows 11 user whose app will not boot and who cannot produce a single
byte of diagnostic detail.

The gate now names its phases. Each step is wrapped so a throw carries
the phase it came from, replacing a `Future.wait` that discarded every
error but the first and could not attribute it to any of four concurrent
steps. The failure screen renders the phase, the exception type, the
message and an expandable stack, plus copy and upload actions that reuse
the existing log-relay flow. The record is persisted next to the database
so the next successful launch can surface it in Settings > Logs, and it
is reported to the crash reporter explicitly.

Only preferences and the database still gate the launch. Window chrome,
locale, crash-reporting init, TV/performance detection, the image-cache
budget and download storage are best-effort and time-bounded, so a
stalled platform thread degrades instead of holding the splash forever.
Sentry no longer receives the startup work as its `appRunner`: that made
a startup failure indistinguishable from a Sentry failure, and the guard
would then have re-run migrations and the database open a second time.

The two remaining fatal steps become recoverable. Preference reads
tolerate a value whose stored type no longer matches, dropping the key
and defaulting instead of failing the boot. A store that cannot be parsed
is detected before either desktop plugin backend can memoise it, which is
what makes an in-process repair possible at all. Repair is never
automatic: it states what it will cost, salvages the credential-vault key
and every tracker and Seerr session it can validate out of the damaged
bytes, reseeds them, and moves the original aside rather than deleting
it. Servers and profiles survive a salvaged key because their tokens are
ciphertext in the database; tracker and Seerr sessions are plaintext
preference entries, so the copy says they may still need reconnecting.

Nothing derived from the store reaches a diagnostic. `FormatException`
prints an excerpt of whatever it failed to parse, and during startup that
document holds the vault key, refresh tokens and session cookies while
the redaction manager still has nothing registered, so the wrapper keeps
only the cause's type and offset and the record is an allowlist of
already-redacted fields. The quarantined copy is labelled as containing
credentials, is never offered for upload, and can be deleted from the
dialog.

Also self-heals orphaned WAL/SHM sidecars on desktop rather than only
tvOS, makes every `createTable` migration step idempotent, keeps MSVC
link by-products out of the Windows bundle, and asserts bundle contents
in CI.

Refs #1732
2026-07-31 21:45:32 +02:00
edde746 7c515bf8fa feat(website): serve Windows from the Microsoft Store and tag store campaigns
The Windows button downloaded plezy-windows-installer.exe from the latest
release. It now opens the Store listing, which brings Store-managed updates.
The endpoint redirects to ms-windows-store://, so the button only resolves on
Windows; macOS and Linux keep their direct release downloads.

Store links carry campaign parameters (ct=Landing, utm_campaign=landing,
cid=landing) so landing-page traffic separates from the README's in each
store's own reporting. Play reports utm_source and utm_campaign, so no
utm_medium is sent.

Structured data keeps untagged canonical URLs: schema.org offers are consumed
by search engines, and a rich-result click is not landing-page traffic.
2026-07-31 21:21:06 +02:00
edde746 f30e2c621a docs: refresh readme features and download channels
The features section last changed substantively in 2c54baca3 (2026-05-17),
before the music and Explore subsystems shipped, so two whole feature areas
were missing and several availability notes had drifted.

Adds Music and Explore & Requests sections, and corrects claims that no
longer hold: the locale count (14 -> 21), the EPG guide is not Plex-only,
downloads include music and are unavailable on tvOS, Picture-in-Picture
excludes the TV platforms, and shaders and ambient lighting need the mpv
backend. Footnotes move from numeric to named so adding one no longer
renumbers the rest.

Windows now points at the Microsoft Store listing instead of the direct
installer and portable archives. The App Store and Play badges carry
campaign tokens so README traffic is attributable in each store's own
reporting.

The prerequisite Flutter version matches the pinned toolchain (3.44.0), and
the Maestro end-to-end suite gets the pointer it never had.
2026-07-31 21:18:53 +02:00
295 changed files with 21864 additions and 2554 deletions
+57
View File
@@ -466,6 +466,63 @@ jobs:
shell: pwsh
run: flutter build windows --release ${{ env.RELEASE_DART_DEFINES }} --dart-define=SENTRY_DIST=github-windows-${{ matrix.arch }} --split-debug-info=debug-info/windows-${{ matrix.arch }}
- name: Verify Windows bundle contents
shell: pwsh
run: |
$bundleDir = "build/windows/${{ matrix.arch }}/runner/Release"
if (-not (Test-Path -LiteralPath $bundleDir -PathType Container)) {
throw "Windows bundle directory does not exist: $bundleDir"
}
$bundlePath = (Resolve-Path -LiteralPath $bundleDir).Path
$foundFiles = @(
Get-ChildItem -LiteralPath $bundlePath -File -Recurse |
ForEach-Object {
$_.FullName.Substring($bundlePath.Length + 1).Replace('\', '/')
} |
Sort-Object
)
Write-Host "Files found in ${bundleDir}:"
$foundFiles | ForEach-Object { Write-Host " $_" }
$requiredFiles = @(
"plezy.exe"
"flutter_windows.dll"
"sqlite3.dll"
"libmpv-2.dll"
"data/app.so"
"data/icudtl.dat"
"data/flutter_assets/NativeAssetsManifest.json"
)
$forbiddenFiles = @(
"plezy.lib"
"plezy.exp"
"simdutf.lib"
)
$bundleErrors = @()
foreach ($file in $requiredFiles) {
if ($foundFiles -notcontains $file) {
Write-Output "::error::Required Windows bundle file is missing: $file"
$bundleErrors += "missing $file"
}
}
foreach ($file in $forbiddenFiles) {
if ($foundFiles -contains $file) {
Write-Output "::error::Forbidden link by-product is present in the Windows bundle: $file"
$bundleErrors += "present $file"
}
}
# sentry.dll is the inproc-backend native SDK; crashpad_handler.exe is
# intentionally absent (windows/CMakeLists.txt sets
# SENTRY_NATIVE_BACKEND=inproc), so do not assert on it here.
if ($bundleErrors.Count -gt 0) {
throw "Windows bundle verification failed: $($bundleErrors -join '; ')"
}
- name: Upload symbols to bugs.plezy.app
if: github.repository == 'edde746/plezy'
shell: pwsh
+17
View File
@@ -147,6 +147,14 @@ jobs:
working-directory: packages/wakelock_plus
run: flutter test --platform chrome --dart-define=WEB_PLUGIN_TESTS=true test/wakelock_plus_web_plugin_test.dart
# The vendored atomic-write patch has to keep the upstream contract, not
# just the new behaviour. Upstream's own suites are the check for that.
- name: Run the vendored desktop preference store tests
run: |
for pkg in shared_preferences_linux shared_preferences_windows; do
(cd "packages/$pkg" && flutter pub get --enforce-lockfile && flutter test)
done
android-test:
name: Android JVM and Native Tests
runs-on: ubuntu-latest
@@ -471,6 +479,15 @@ jobs:
shell: pwsh
run: flutter pub get --enforce-lockfile --no-example
# Windows replacement semantics (`MoveFileExW` with
# MOVEFILE_REPLACE_EXISTING) cannot be proven on the POSIX runners, and a
# memory file system proves nothing about either. The vendored
# shared_preferences_windows store write is the fix for #1732, so exercise
# it here, on a real NTFS volume, against the real backend.
- name: Run the vendored Windows preference store tests
shell: pwsh
run: flutter test test/services/prefs_store_atomic_write_windows_test.dart
- name: Install patched Flutter engine
shell: pwsh
run: |
@@ -16,13 +16,20 @@ tags:
visible: "(?s)^(Play|Resume).*$"
commands:
- pressKey: "Remote Dpad Center"
# The TV player opens with its chrome down so the OSD and timebar never sit
# over the opening seconds of the picture (#1765), so the Pause button can no
# longer stand in for "the player has finished loading". Wait for the detail
# screen to go first: the labelled spinner is necessarily up the moment the
# player route owns the frame, and it only clears once playback reports its
# first frame or gives up, so this can never advance before the media opens.
# A give-up lands on the transport assertions below, which is where it belongs.
- extendedWaitUntil:
visible: "Pause"
notVisible: "Overview"
timeout: 30000
- pressKey: "back"
- extendedWaitUntil:
notVisible: "Pause"
timeout: 10000
notVisible: "Loading video"
timeout: 30000
- assertNotVisible: "(?s)^(Play|Pause)$"
# Hardware transport keys drive playback without raising the chrome (#1676):
# the player answers with a centred disc (pause) or a side readout (seek), never the
# full chrome, so subtitles stay readable.
@@ -7,9 +7,23 @@ tags:
- playback
---
- runFlow: ../subflows/onboard_jellyfin_tv.yaml
- tapOn:
point: "6%,22%"
- tapOn: "Search"
# Reach Search with the D-pad, the way 10_tv_settings_navigation.yaml does. A
# tap here flips InputModeTracker into pointer mode, which collapses the rail
# to icons and leaves no "Search" label to hit — and a percentage coordinate
# does not survive the jump from a phone in forced TV mode to a 4K television.
- pressKey: "Remote Dpad Left"
- extendedWaitUntil:
visible: "Search"
timeout: 15000
- repeat:
times: 12
while:
notVisible:
text: "Search"
focused: true
commands:
- pressKey: "Remote Dpad Down"
- pressKey: "Remote Dpad Center"
- extendedWaitUntil:
visible: "Search movies, shows, music..."
timeout: 10000
@@ -24,13 +38,24 @@ tags:
- waitForAnimationToEnd:
timeout: 5000
- tapOn: "(?s)^Play S1E1$"
# The TV player opens with its chrome down (#1765), so the Pause button can no
# longer stand in for "the player has finished loading". Wait for the detail
# screen to go first: the labelled spinner is necessarily up the moment the
# player route owns the frame, and it only clears once playback reports its
# first frame or gives up, so this can never advance before the media opens.
- extendedWaitUntil:
visible: "Pause"
notVisible: "(?s)^Play S1E1$"
timeout: 30000
- extendedWaitUntil:
notVisible: "Loading video"
timeout: 30000
- pressKey: "Remote Media Fast Forward"
- pressKey: "Remote Media Fast Forward"
# Gate on the prompt's own Cancel action, the label the iOS branch below taps.
# "Next Episode" is the credits skip button at this point in the episode, so
# waiting on it would let Back fire before the prompt ever opened.
- extendedWaitUntil:
visible: "Next Episode"
visible: "(?s)^Cancel$"
timeout: 20000
- runFlow:
when:
@@ -42,7 +67,10 @@ tags:
platform: Android
commands:
- pressKey: "back"
- assertNotVisible: "Next Episode"
# Dismissal is animated, so give it a bounded wait rather than one instant look.
- extendedWaitUntil:
notVisible: "(?s)^Cancel$"
timeout: 10000
- assertNotVisible: "Overview"
- pressKey: "Remote Dpad Up"
- extendedWaitUntil:
+73 -29
View File
@@ -19,13 +19,13 @@ A modern client for Plex and Jellyfin on desktop, mobile, and TV. Built with Flu
## Download
<a href='https://apps.apple.com/us/app/id6754315964'><img height='60' alt='Download on the App Store' src='./assets/app-store-badge.png'/></a>
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
<a href='https://apps.apple.com/app/apple-store/id6754315964?pt=128238902&ct=GitHub&mt=8'><img height='60' alt='Download on the App Store' src='./assets/app-store-badge.png'/></a>
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy&referrer=utm_source%3Dgithub%26utm_campaign%3Dreadme_badge'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
<a href='https://www.amazon.com/gp/product/B0GK65CVS1'><img height='60' alt='Available at the Amazon App Store' src='./assets/amazon-badge.png'/></a>
<a href='https://get.microsoft.com/installer/download/9n5r1s1t68h7?referrer=appbadge&cid=github'><img height='60' alt='Get it from Microsoft' src='./assets/microsoft-badge.png'/></a>
| Platform | Download |
| --- | --- |
| Windows | [Installer (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe) · [Portable x64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-x64-portable.7z) · [Portable arm64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-arm64-portable.7z) |
| macOS | [DMG (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg) |
| Linux x64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.tar.gz) |
| Linux arm64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.tar.gz) |
@@ -50,36 +50,61 @@ Package managers:
## Features
### <img src="assets/readme_icons/browse.svg" height="20" alt="" align="center" /> Browse & Discover
- Libraries, collections, and playlists
- Libraries, collections, and playlists — video and audio
- Discover hub — Continue Watching, Next Up, trending, and recommendations
- Cross-server search
- Cross-server search across every connected Plex and Jellyfin server
- Filtering, sorting, and alphabetical jump navigation
- Folder browsing and folder playback — home-video libraries open in folder view
- Resolution, HDR/Dolby Vision, and audio-format badges on cards and detail pages
- Favorites and unwatched library filters[^jf]
- Extras — trailers, deleted scenes, behind-the-scenes
### <img src="assets/readme_icons/explore.svg" height="20" alt="" align="center" /> Explore & Requests
- Explore tab — watchlist, trending, popular, and recommendation rows from Plex Discover[^plex], Trakt, MyAnimeList, AniList, Simkl, and Seerr[^connect]
- Search any connected catalog source
- Catalog titles matched back to your own libraries by external ID
- Seerr — request movies and shows with per-season, 4K, and advanced destination options, and see request status inline
- Watchlist sync — add and remove titles on Plex, Trakt, MyAnimeList, AniList, and Simkl from anywhere in the app
### <img src="assets/readme_icons/playback.svg" height="20" alt="" align="center" /> Playback
- Wide codec support (HEVC, AV1, VP9, and more)
- HDR and Dolby Vision[^1]
- HDR and Dolby Vision[^hdr]
- Direct play, or transcode presets from 240p/320 kbps to 1080p/20 Mbps
- Multi-version switching with per-version file details
- Full ASS/SSA subtitles with customizable styling
- Online subtitle search & download[^2]
- Audio & subtitle choices remembered per title
- Online subtitle search & download[^plex]
- Audio & subtitle choices remembered per title, or follow the server's per-episode selections
- Progress sync and resume
- Auto-play next episode with skip intro / skip credits
- Chapter navigation with thumbnail scrub previews
- Playback speed, audio sync offset, sleep timer
- Ambient lighting and GLSL shader presets[^3]
- Picture-in-Picture[^4]
- Refresh-rate matching[^5]
- External player launch (VLC, MX Player, etc.)
- Playback speed from 0.25x to 8x, audio sync offset, sleep timer (fixed durations or end of video)
- Video zoom 50-200% with pinch, presets, and hotkeys
- Audio passthrough[^pass], stereo downmix with center-channel boost, and loudness normalization
- File Info sheet — every version, file, and stream the server reports
- Ambient lighting and GLSL shader presets[^mpv]
- Picture-in-Picture[^pip]
- Refresh-rate matching[^rrm]
- External player launch (VLC, MX Player, etc.) with progress sync back[^android]
### <img src="assets/readme_icons/music.svg" height="20" alt="" align="center" /> Music
- Music libraries — artist, album, and track browsing with square artwork
- Album and artist screens with play, shuffle, and Instant Mix
- Gapless playback with a full play queue — reorder, remove, play next, add to queue
- Now Playing with synced lyrics[^lyrics], persistent mini-player, and sleep timer
- Background playback with lock-screen, media-key, and notification controls[^bgaudio]
- Offline playback of downloaded albums and tracks
- Streaming quality presets — Original, 320, 192, or 128 kbps
### <img src="assets/readme_icons/live-tv.svg" height="20" alt="" align="center" /> Live TV & DVR
- Live TV channel browsing with favorites
- DVR support with EPG guide, recording rules, and scheduled recordings[^2]
- Live TV channel browsing, tuning, and favorites
- EPG guide with What's On and per-show schedules
- DVR recording rules, scheduled recordings, and a rememberable recording target library[^plex]
- Multi-server Live TV support where available
### <img src="assets/readme_icons/downloads.svg" height="20" alt="" align="center" /> Downloads & Offline
- Download media for offline viewing
- Download movies, shows, and music for offline playback[^dl]
- Background queue with pause / resume
- Sync rules for automatic downloads
- Sync rules for automatic downloads, with per-show "Include Specials"
- Offline browsing with watch state sync-back on reconnect
### <img src="assets/readme_icons/watch-together.svg" height="20" alt="" align="center" /> Watch Together
@@ -87,29 +112,42 @@ Package managers:
- Real-time play / pause / seek sync
### <img src="assets/readme_icons/integrations.svg" height="20" alt="" align="center" /> Integrations
- Discord Rich Presence[^6]
- Trakt, MyAnimeList, AniList, and Simkl tracking & rating
- Discord Rich Presence[^desktop]
- Trakt, MyAnimeList, AniList, and Simkl — ratings, watched sync, and real-time scrobbling[^rt]
- Plezy Remote — control desktop and TV from mobile
- Watch Next row
- Watch Next row and tvOS Top Shelf[^shelf]
### <img src="assets/readme_icons/customization.svg" height="20" alt="" align="center" /> Platform & Customization
- Desktop, mobile, and TV — full D-pad, keyboard, and gamepad support
- Customizable keyboard shortcuts[^6]
- Multiple servers at once — Plex and Jellyfin side by side
- Profiles with per-profile downloads, watch state, and settings; Plex Home switching with PIN
- Jellyfin local-server discovery, multiple URLs per server, and Quick Connect sign-in
- TV layout options — corner spotlight backdrop, full-card artwork, and Force TV mode on desktop
- Customizable keyboard shortcuts[^desktop]
- Metadata and artwork editing
- Settings import/export
- Localized in English plus 14 translations
- Localized in English plus 21 translations
[^1]: Not available on Linux.
[^2]: Plex only.
[^3]: Not available on iOS or tvOS.
[^4]: Android, iOS, and macOS.
[^5]: Windows, Android, and tvOS.
[^6]: Desktop only.
[^jf]: Jellyfin only.
[^plex]: Plex only.
[^connect]: Requires connecting the service under Settings > Services.
[^hdr]: In-app HDR toggle on Windows, macOS, iOS, and tvOS. Dolby Vision on Android and Apple TV.
[^pass]: Desktop, Android TV, and Apple TV.
[^mpv]: Requires the mpv player backend — unavailable on iOS and tvOS, and Android defaults to ExoPlayer.
[^pip]: Android, iOS, and macOS — not on Android TV or Apple TV.
[^rrm]: Windows, Android, and tvOS.
[^android]: Progress sync on Android.
[^lyrics]: Where your server provides lyrics.
[^bgaudio]: tvOS pauses music when the app is backgrounded.
[^dl]: Not available on tvOS.
[^desktop]: Desktop only.
[^rt]: Real-time scrobbling on Trakt and Simkl; MyAnimeList and AniList update on completion.
[^shelf]: Android TV / Fire TV and tvOS.
## Building from Source
### Prerequisites
- Flutter SDK 3.38.4+
- Flutter SDK 3.44.0+
- A Plex account or Jellyfin server with user credentials
### Setup
@@ -148,6 +186,12 @@ To install the same pre-commit checks locally:
scripts/setup_hooks.sh
```
End-to-end tests (Android emulator plus a Dockerized Jellyfin fixture):
```bash
python3 scripts/run_maestro.py basic
```
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md) for development workflow, formatting, tests, and translation guidelines.
@@ -0,0 +1,152 @@
package com.edde746.plezy.exoplayer
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.MimeTypes
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.common.Tracks
import androidx.media3.exoplayer.ExoPlayer
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* Pins the side-loaded subtitle identity contract against the real media3 the
* app links, on a real device.
*
* `ExoPlayerCore` tags each `MediaItem.SubtitleConfiguration` with
* [ExternalSubtitleIds.idFor] and recovers it from the `Format` the track
* selector reports. media3 does not hand that id back verbatim:
* `DefaultMediaSourceFactory` merges side-loaded subtitles with the primary
* source, and `MergingMediaPeriod` prefixes every child format id with its
* period index. Matching the raw id therefore classifies every sidecar as an
* embedded track and drops its URI, which is what broke Plex sidecar
* subtitles (#1713).
*
* A JVM test can only assert the parsing rule. This asserts that the rule
* still matches what media3 actually emits.
*/
@RunWith(AndroidJUnit4::class)
class ExternalSubtitleIdentityTest {
private companion object {
const val TAG = "ExternalSubtitleIdentityTest"
const val SRT = "1\n00:00:00,500 --> 00:00:05,000\nplezy sidecar identity\n\n"
}
@Test
fun sideLoadedSubtitleIdSurvivesMedia3Merging() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
val media = copyAsset(instrumentation.context, context, "ffmpeg/planar_5_1.m4a")
val subtitle = File.createTempFile("sidecar-", ".srt", context.cacheDir).apply {
writeText(SRT)
}
val thread = HandlerThread("plezy-sidecar-identity-test").apply { start() }
val handler = Handler(thread.looper)
val settled = CountDownLatch(1)
val playerRef = AtomicReference<ExoPlayer>()
val errorRef = AtomicReference<Throwable>()
val textFormatId = AtomicReference<String>()
val textGroupCount = AtomicReference(0)
handler.post {
try {
val player = ExoPlayer.Builder(context).setLooper(thread.looper).build()
playerRef.set(player)
player.addListener(object : Player.Listener {
override fun onPlayerError(error: PlaybackException) {
errorRef.set(error)
settled.countDown()
}
override fun onTracksChanged(tracks: Tracks) {
val text = tracks.groups.filter { it.type == C.TRACK_TYPE_TEXT }
if (text.isEmpty()) return
textGroupCount.set(text.size)
textFormatId.set(text.first().mediaTrackGroup.getFormat(0).id)
settled.countDown()
}
})
// setMediaItem (not setMediaSource) so DefaultMediaSourceFactory owns
// the subtitle configuration exactly as ExoPlayerCore.open does.
player.setMediaItem(
MediaItem.Builder()
.setUri(Uri.fromFile(media))
.setSubtitleConfigurations(
listOf(
MediaItem.SubtitleConfiguration.Builder(Uri.fromFile(subtitle))
.setId(ExternalSubtitleIds.idFor(0))
.setLabel("Plezy sidecar")
.setLanguage("en")
.setMimeType(MimeTypes.APPLICATION_SUBRIP)
.setSelectionFlags(C.SELECTION_FLAG_DEFAULT)
.build()
)
)
.build()
)
player.prepare()
} catch (error: Throwable) {
errorRef.set(error)
settled.countDown()
}
}
val finished = settled.await(30, TimeUnit.SECONDS)
val released = CountDownLatch(1)
handler.post {
playerRef.get()?.release()
thread.quitSafely()
released.countDown()
}
val teardownFinished = released.await(5, TimeUnit.SECONDS)
thread.join(5_000)
media.delete()
subtitle.delete()
assertTrue("Player teardown timed out", teardownFinished)
assertNull("Playback failed", errorRef.get())
assertTrue("Timed out before any text track group was reported", finished)
assertEquals("Expected exactly one side-loaded text group", 1, textGroupCount.get())
val reportedId = textFormatId.get()
Log.i(TAG, "media3 reported side-loaded subtitle Format.id=$reportedId")
assertNotNull("Side-loaded subtitle reported a null Format.id", reportedId)
// The contract ExoPlayerCore depends on.
assertTrue(
"Side-loaded subtitle was not recognised as external (Format.id=$reportedId)",
ExternalSubtitleIds.isExternal(reportedId)
)
assertEquals(
"Side-loaded subtitle did not resolve to its configuration index (Format.id=$reportedId)",
0,
ExternalSubtitleIds.indexOf(reportedId)
)
}
private fun copyAsset(instrumentationContext: Context, targetContext: Context, asset: String): File {
val output = File.createTempFile("sidecar-primary-", null, targetContext.cacheDir)
instrumentationContext.assets.open(asset).use { input ->
output.outputStream().use(input::copyTo)
}
return output
}
}
@@ -120,6 +120,10 @@ class ExoPlayerCore(private val activity: Activity) :
private const val FPS_SAMPLE_COUNT = 8
private const val AUDIO_BOUNCE_TIMEOUT_MS = 1000L
/** Fallback for stacks that only stringify the status instead of raising
* [HttpDataSource.InvalidResponseCodeException]. */
private val RESPONSE_CODE_PATTERN = Regex("""\bResponse code: (\d{3})\b""")
/** Per-frame "video is at X" logcat stream (tag AssFrameCb) for diagnosing
* ASS subtitle lag against the libass pipeline's render/swap lines. */
private const val ASS_FRAME_LOGS = false
@@ -519,6 +523,7 @@ class ExoPlayerCore(private val activity: Activity) :
fun initialize(
bufferSizeBytes: Int? = null,
bufferSizeAuto: Boolean = false,
tunnelingEnabled: Boolean = true,
audioPassthroughEnabled: Boolean = false
): Boolean {
@@ -727,23 +732,20 @@ class ExoPlayerCore(private val activity: Activity) :
.toTypedArray()
}
// Compute memory-aware buffer limits to prevent CCodec OOM crashes
// Buffer budget. `bufferSizeBytes` carries the user's explicit Buffer Size choice; on
// Auto it still arrives (Dart derives it for mpv's demuxer, which shares the property)
// but `bufferSizeAuto` says to ignore it here, because mpv's demuxer and ExoPlayer's
// sample allocator have different shapes and different failure modes.
val activityManager = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val memoryInfo = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(memoryInfo)
val availableMB = memoryInfo.availMem / (1024 * 1024)
val availableMB = (memoryInfo.availMem / (1024 * 1024)).toInt()
val largeHeapMB = activityManager.largeMemoryClass
val targetBufferBytes = if (bufferSizeBytes != null && bufferSizeBytes > 0) {
val targetBufferBytes = if (!bufferSizeAuto && bufferSizeBytes != null && bufferSizeBytes > 0) {
bufferSizeBytes
} else {
// Scale buffer to available memory to reduce hardware decoder pressure.
// Larger buffers reduce oscillation frequency at high bitrates (50-100Mbps).
when {
availableMB <= 512 -> 30 * 1024 * 1024
availableMB <= 1024 -> 80 * 1024 * 1024
availableMB <= 2048 -> 120 * 1024 * 1024
else -> 200 * 1024 * 1024
}
LoadControlPolicy.autoTargetBufferBytes(largeHeapMB, availableMB)
}
val loadControl = DefaultLoadControl.Builder().apply {
@@ -755,7 +757,12 @@ class ExoPlayerCore(private val activity: Activity) :
setBufferDurationsMs(30_000, 60_000, 1_000, 5_000)
}
}.build()
emitLog("info", "init", "Buffer: ${targetBufferBytes / 1024 / 1024}MB limit, available=${availableMB}MB, tunneling=$tunnelingUserEnabled, dataSource=$dataSourceLabel")
emitLog(
"info",
"init",
"Buffer: ${targetBufferBytes / 1024 / 1024}MB limit (${if (bufferSizeAuto) "auto" else "manual"}, " +
"heap=${largeHeapMB}MB, available=${availableMB}MB), tunneling=$tunnelingUserEnabled, dataSource=$dataSourceLabel"
)
exoPlayer = ExoPlayer.Builder(activity)
.setTrackSelector(trackSelector!!)
@@ -1204,18 +1211,24 @@ class ExoPlayerCore(private val activity: Activity) :
// If native DV7 failed, retry with conversion before falling to MPV
if (error.errorCode in 4001..4005 && retryWithDvConversion("decoder error ${error.errorCode}")) return
// Server returned HTTP 500 — typically a shared-user bandwidth/transcoding limit
// set by the server owner. MPV will hit the same rejection, so skip the fallback.
// Keep the "server-http-500" tag in sync with PlayerError.serverHttp500 in Dart.
val isHttp500 =
causeChain.contains("Response code: 500") ||
(error.message?.contains("Response code: 500") == true)
if (isHttp500) {
Log.w(TAG, "Server returned HTTP 500 - skipping MPV fallback (unrecoverable until server-side change)")
// A server-side HTTP status is not a codec problem: MPV would replay the
// same request and fail identically, so skip the fallback (and its
// "switching to compatible player" toast) and report the status instead.
// Keep these tags in sync with PlayerError.serverHttp500/404 in Dart.
val httpStatus = resolveHttpStatus(error, causeChain)
val statusCause = when (httpStatus) {
// Shared-user bandwidth/transcoding limit rejection set by the server owner.
500 -> "server-http-500"
// The server resolved the item but cannot read the file behind it.
404 -> "server-http-404"
else -> null
}
if (statusCause != null) {
Log.w(TAG, "Server returned HTTP $httpStatus - skipping MPV fallback (unrecoverable until server-side change)")
emitPlaybackErrorOnce(
mediaGeneration,
error.message ?: "HTTP 500",
cause = "server-http-500"
error.message ?: "HTTP $httpStatus",
cause = statusCause
)
return
}
@@ -1249,6 +1262,22 @@ class ExoPlayerCore(private val activity: Activity) :
emitPlaybackErrorOnce(mediaGeneration, error.message ?: "Unknown error")
}
/**
* HTTP status the failed request came back with, or null when this is not an
* HTTP failure. [HttpDataSource.InvalidResponseCodeException] carries the
* real code (both DefaultHttpDataSource and CronetDataSource raise it);
* [causeChain] is the already-built string fallback.
*/
private fun resolveHttpStatus(error: PlaybackException, causeChain: String): Int? {
var cause: Throwable? = error
while (cause != null) {
if (cause is HttpDataSource.InvalidResponseCodeException) return cause.responseCode
cause = cause.cause
}
return RESPONSE_CODE_PATTERN.find(causeChain)?.groupValues?.get(1)?.toIntOrNull()
?: error.message?.let { RESPONSE_CODE_PATTERN.find(it)?.groupValues?.get(1)?.toIntOrNull() }
}
/**
* media3 reports [StuckPlayerException.STUCK_PLAYING_NOT_ENDING] when the
* player sits in STATE_READY past the declared duration without any renderer
@@ -1848,14 +1877,15 @@ class ExoPlayerCore(private val activity: Activity) :
subtitleTrackGroupMap[trackId] = trackGroup
val isSelected = group.isSelected
// Detect external (side-loaded) subtitle by the ID prefix set in open()
val isExternal = format.id?.startsWith("external_") == true
val externalIndex = if (isExternal) format.id?.removePrefix("external_")?.toIntOrNull() else null
// Detect external (side-loaded) subtitle by the ID set in open(). media3
// rewrites merged child ids, so the tag is not the whole id.
val isExternal = ExternalSubtitleIds.isExternal(format.id)
val externalIndex = ExternalSubtitleIds.indexOf(format.id)
val externalUri = externalIndex?.takeIf { it in externalSubtitleUris.indices }?.let { externalSubtitleUris[it] }
val isContainer = !isExternal && externalSubtitleContainerUris.isNotEmpty()
val containerUri = if (isContainer) externalSubtitleContainerUris.first() else null
Log.d(TAG, "Subtitle track $groupIndex: codec=${format.codecs}, lang=${format.language}, selected=$isSelected, external=$isExternal")
Log.d(TAG, "Subtitle track $groupIndex: formatId=${format.id}, codec=${format.codecs}, lang=${format.language}, selected=$isSelected, external=$isExternal")
val track = mutableMapOf<String, Any?>(
"type" to "sub",
@@ -3193,7 +3223,7 @@ class ExoPlayerCore(private val activity: Activity) :
(if (isDefault) C.SELECTION_FLAG_DEFAULT else 0) or
(if (isForced) C.SELECTION_FLAG_FORCED else 0)
val config = MediaItem.SubtitleConfiguration.Builder(Uri.parse(subUri))
.setId("external_$index")
.setId(ExternalSubtitleIds.idFor(index))
.setLabel(title ?: "External")
.setLanguage(language)
.setMimeType(mimeType ?: subtitleMimeTypeForCodec(codec) ?: detectSubtitleMimeType(subUri))
@@ -3556,7 +3586,7 @@ class ExoPlayerCore(private val activity: Activity) :
val existingIndex = externalSubtitleUris.indexOf(uri)
val isNew = existingIndex < 0
val index = if (isNew) externalSubtitles.size else existingIndex
val formatId = "external_$index"
val formatId = ExternalSubtitleIds.idFor(index)
if (isNew) {
// SELECTION_FLAG_DEFAULT marks this as the preferred text track so ExoPlayer's
@@ -3603,9 +3633,10 @@ class ExoPlayerCore(private val activity: Activity) :
player.prepare()
player.playWhenReady = savedPlayWhenReady
} else {
// Already attached — select the existing track via override.
// Already attached — select the existing track via override. The
// reported id carries media3's merge prefixes, so compare the tag.
val trackId = subtitleTrackGroupMap.entries
.firstOrNull { (_, group) -> group.getFormat(0).id == formatId }
.firstOrNull { (_, group) -> ExternalSubtitleIds.indexOf(group.getFormat(0).id) == index }
?.key
if (trackId != null) {
selectSubtitleTrack(trackId)
@@ -285,6 +285,10 @@ class ExoPlayerPlugin :
}
val bufferSizeBytes = call.argument<Int>("bufferSizeBytes")
// Auto sizing is decided natively (LoadControlPolicy). `bufferSizeBytes` still arrives
// on Auto because Dart derives one for mpv's demuxer, which shares the property, and
// the fallback replay below needs it.
val bufferSizeAuto = call.argument<Boolean>("bufferSizeAuto") ?: false
val tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: true
val dvConversionMode = call.argument<String>("dvConversionMode") ?: "auto"
val audioPassthroughEnabled = call.argument<Boolean>("audioPassthroughEnabled") ?: false
@@ -323,6 +327,7 @@ class ExoPlayerPlugin :
playerCore = core
val success = core.initialize(
bufferSizeBytes = bufferSizeBytes,
bufferSizeAuto = bufferSizeAuto,
tunnelingEnabled = tunnelingEnabled,
audioPassthroughEnabled = audioPassthroughEnabled
)
@@ -0,0 +1,40 @@
package com.edde746.plezy.exoplayer
/**
* Identity of a side-loaded subtitle across media3's media-source merging.
*
* Each `MediaItem.SubtitleConfiguration` is tagged with [idFor], and the tag is
* read back off the `Format` the track selector reports. The tag does not
* survive verbatim: `DefaultMediaSourceFactory.createMediaSource` always wraps
* the primary source plus one source per subtitle configuration in a
* `MergingMediaSource`, and since media3 1.3.0 `MergingMediaPeriod.onPrepared`
* rewrites every child format id to `"<periodIndex>:<originalId>"`. A second
* merge — the one this player builds for container sidecars — prefixes it
* again. So the same configuration can surface as `external_0`,
* `1:external_0`, or `0:1:external_0`.
*
* Only the final `:`-separated segment carries the tag, which is why matching
* on the whole id silently classifies every sidecar as an embedded track.
*/
internal object ExternalSubtitleIds {
private const val PREFIX = "external_"
/** Tag written onto the [index]th side-loaded subtitle configuration. */
fun idFor(index: Int): String = "$PREFIX$index"
/** Whether [formatId] identifies a side-loaded subtitle. */
fun isExternal(formatId: String?): Boolean = tagOf(formatId) != null
/**
* Index passed to [idFor], or null when [formatId] is not a side-loaded
* subtitle or carries a tag this build did not write.
*/
fun indexOf(formatId: String?): Int? = tagOf(formatId)?.toIntOrNull()
private fun tagOf(formatId: String?): String? {
// substringAfterLast returns the whole string when no ':' is present, which
// is the unmerged case.
val segment = formatId?.substringAfterLast(':') ?: return null
return if (segment.startsWith(PREFIX)) segment.removePrefix(PREFIX) else null
}
}
@@ -0,0 +1,60 @@
package com.edde746.plezy.exoplayer
/**
* Auto sizing for [androidx.media3.exoplayer.DefaultLoadControl]'s `targetBufferBytes` (#1618).
*
* A byte cap collapses as bitrate rises: 64 MiB is 53s of a 10 Mbit/s stream but 5.2s of a
* 103 Mbit/s UHD remux. With `prioritizeTimeOverSizeThresholds = false` the cap is hard, so
* read-ahead that short starves the audio sink in bursts — enough, on some routes, to keep a
* passthrough AudioTrack from ever starting.
*
* The tiers this replaced came from mpv demuxer OOM tuning and handed ExoPlayer a flat
* 64 MiB, under half of what media3 would pick for the same selection
* ([MEDIA3_DEFAULT_TARGET_BYTES]). The fix is not "buffer more than upstream", it is "stop
* buffering less unless the heap requires it".
*
* Not bitrate-aware: the `LoadControl` is built during `initialize`, before any media is
* opened, so a byte budget is all that is knowable.
*/
internal object LoadControlPolicy {
private const val MIB = 1024 * 1024
/**
* media3's own `calculateTargetBufferBytes` for a video + audio selection: 2000 + 200
* segments at `C.DEFAULT_BUFFER_SEGMENT_SIZE` (64 KiB). A ceiling, never exceeded here.
*/
const val MEDIA3_DEFAULT_TARGET_BYTES = 2200 * 64 * 1024
/**
* Floor, kept at the lowest tier that has already shipped, and it wins over the budgets
* below — going under it reintroduces the starvation this policy exists to prevent.
*/
const val MIN_TARGET_BYTES = 32 * MIB
/**
* Fraction of a memory budget the allocator may claim. Matches the threshold the Buffer
* Size setting already warns at (`value > heapMB / 4`).
*/
private const val BUDGET_DIVISOR = 4
/**
* @param largeHeapMB `ActivityManager.largeMemoryClass` — the hard Java-heap ceiling for
* this process, which is what bounds `DefaultAllocator` (it hands out `byte[]`).
* Non-positive when unknown.
* @param availableMB `ActivityManager.MemoryInfo.availMem`, so a device that is currently
* under pressure does not get sized purely off its theoretical heap. Non-positive when
* unknown.
*/
fun autoTargetBufferBytes(largeHeapMB: Int, availableMB: Int): Int {
var budget = MEDIA3_DEFAULT_TARGET_BYTES.toLong()
if (largeHeapMB > 0) budget = minOf(budget, largeHeapMB.toLong() / BUDGET_DIVISOR * MIB)
if (availableMB > 0) budget = minOf(budget, availableMB.toLong() / BUDGET_DIVISOR * MIB)
return maxOf(budget, MIN_TARGET_BYTES.toLong()).toInt()
}
/** Seconds of media a budget covers at [bitrateBps], for logs. Null when unknown. */
fun readAheadSeconds(targetBufferBytes: Int, bitrateBps: Long): Double? {
if (bitrateBps <= 0L) return null
return targetBufferBytes * 8.0 / bitrateBps
}
}
@@ -308,6 +308,12 @@ class MpvPlayerCore private constructor(
// Pause on the last frame at EOF instead of unloading the file, so a
// seek after the video ends still works (matches Linux/Windows).
setOption("keep-open", "yes")
// Plezy only ever opens media-server streams and local files, so
// mpv's bundled ytdl_hook has nothing to resolve: it costs an
// on_load hook per open and, on a failed open, spawns yt-dlp with
// the access token in its argv. mpv decides whether to load the
// builtin script during mpv_initialize, hence an option here.
setOption("ytdl", "no")
}
if (displayFpsOverride != null) {
Log.d(TAG, "Initial display-fps-override=$displayFpsOverride")
@@ -0,0 +1,61 @@
package com.edde746.plezy.exoplayer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class ExternalSubtitleIdsTest {
@Test
fun unmergedTagResolves() {
assertTrue(ExternalSubtitleIds.isExternal("external_0"))
assertEquals(0, ExternalSubtitleIds.indexOf("external_0"))
assertEquals(7, ExternalSubtitleIds.indexOf("external_7"))
}
@Test
fun mediaSourceFactoryMergePrefixResolves() {
// DefaultMediaSourceFactory always merges side-loaded subtitles with the
// primary source, so MergingMediaPeriod prefixes the period index.
assertTrue(ExternalSubtitleIds.isExternal("1:external_0"))
assertEquals(0, ExternalSubtitleIds.indexOf("1:external_0"))
assertEquals(2, ExternalSubtitleIds.indexOf("3:external_2"))
}
@Test
fun containerSidecarOuterMergePrefixResolves() {
// The container-sidecar path wraps that merge in a second MergingMediaSource.
assertTrue(ExternalSubtitleIds.isExternal("0:1:external_0"))
assertEquals(0, ExternalSubtitleIds.indexOf("0:1:external_0"))
assertEquals(4, ExternalSubtitleIds.indexOf("0:2:external_4"))
}
@Test
fun embeddedAndUnknownIdsAreNotExternal() {
assertFalse(ExternalSubtitleIds.isExternal(null))
assertFalse(ExternalSubtitleIds.isExternal("1:2"))
assertFalse(ExternalSubtitleIds.isExternal("0:"))
// A container child whose own id merely ends in the tag's text.
assertFalse(ExternalSubtitleIds.isExternal("1:not_external_0"))
assertNull(ExternalSubtitleIds.indexOf("1:2"))
}
@Test
fun malformedTagIsExternalWithoutAnIndex() {
// Still a side-loaded track, but no usable URI lookup.
assertTrue(ExternalSubtitleIds.isExternal("1:external_x"))
assertNull(ExternalSubtitleIds.indexOf("1:external_x"))
}
@Test
fun writtenIdRoundTrips() {
for (index in 0..3) {
val id = ExternalSubtitleIds.idFor(index)
assertEquals(index, ExternalSubtitleIds.indexOf(id))
assertEquals(index, ExternalSubtitleIds.indexOf("1:$id"))
assertEquals(index, ExternalSubtitleIds.indexOf("0:1:$id"))
}
}
}
@@ -0,0 +1,87 @@
package com.edde746.plezy.exoplayer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
private const val MIB = 1024 * 1024
class LoadControlPolicyTest {
// autoTargetBufferBytes
@Test
fun neverExceedsMedia3sOwnTargetEvenWithHugeMemory() {
assertEquals(
LoadControlPolicy.MEDIA3_DEFAULT_TARGET_BYTES,
LoadControlPolicy.autoTargetBufferBytes(largeHeapMB = 4096, availableMB = 8192)
)
}
@Test
fun heapBoundsTheTargetOnAShieldClassDevice() {
// The actual #1618 defect: the shipped tiers handed this device a flat 64MB, under half
// of media3's own choice. largeMemoryClass 512MB, ~1GB free, so the heap binds at
// 512/4 = 128MB — exactly what the reporter had to select by hand.
assertEquals(
128 * MIB,
LoadControlPolicy.autoTargetBufferBytes(largeHeapMB = 512, availableMB = 990)
)
}
@Test
fun freeMemoryBoundsTheTargetWhenItIsTighterThanTheHeap() {
assertEquals(
64 * MIB,
LoadControlPolicy.autoTargetBufferBytes(largeHeapMB = 512, availableMB = 256)
)
}
@Test
fun floorWinsOverBothBudgetsSoReadAheadCannotCollapse() {
// Going under the floor is what starves the sink on high-bitrate content; the
// allocator only grows into the target when the content is dense enough to need it.
assertEquals(
LoadControlPolicy.MIN_TARGET_BYTES,
LoadControlPolicy.autoTargetBufferBytes(largeHeapMB = 64, availableMB = 48)
)
}
@Test
fun unknownMemoryFallsBackToMedia3sTarget() {
assertEquals(
LoadControlPolicy.MEDIA3_DEFAULT_TARGET_BYTES,
LoadControlPolicy.autoTargetBufferBytes(largeHeapMB = 0, availableMB = 0)
)
}
@Test
fun unknownHeapStillRespectsFreeMemory() {
assertEquals(
64 * MIB,
LoadControlPolicy.autoTargetBufferBytes(largeHeapMB = -1, availableMB = 256)
)
}
// readAheadSeconds
@Test
fun readAheadReportsSecondsAtAKnownBitrate() {
// 64MiB of the #1618 stream (103_341 kbps) is ~5.2s — under the 15s minBufferMs, so the
// byte cap, not the time threshold, is what stops the loader.
val seconds = LoadControlPolicy.readAheadSeconds(64 * MIB, 103_341_000L)!!
assertEquals(5.19, seconds, 0.01)
}
@Test
fun readAheadDoublesWithTheTarget() {
val seconds = LoadControlPolicy.readAheadSeconds(128 * MIB, 103_341_000L)!!
assertEquals(10.39, seconds, 0.01)
}
@Test
fun readAheadIsUnknownWithoutABitrate() {
assertNull(LoadControlPolicy.readAheadSeconds(64 * MIB, 0L))
assertNull(LoadControlPolicy.readAheadSeconds(64 * MIB, -1L))
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><linearGradient id="g" x1="0" y1="24" x2="24" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ab543a"/><stop offset="1" stop-color="#ff7e57"/></linearGradient></defs><path fill="url(#g)" d="M19.3 16.9c.4-.7.7-1.5.7-2.4c0-2.5-2-4.5-4.5-4.5S11 12 11 14.5s2 4.5 4.5 4.5c.9 0 1.7-.3 2.4-.7l3.2 3.2l1.4-1.4zm-3.8.1c-1.4 0-2.5-1.1-2.5-2.5s1.1-2.5 2.5-2.5s2.5 1.1 2.5 2.5s-1.1 2.5-2.5 2.5M12 20v2C6.48 22 2 17.52 2 12S6.48 2 12 2c4.84 0 8.87 3.44 9.8 8h-2.07A8 8 0 0 0 15 4.59V5c0 1.1-.9 2-2 2h-2v2c0 .55-.45 1-1 1H8v2h2v3H9l-4.79-4.79C4.08 10.79 4 11.38 4 12c0 4.41 3.59 8 8 8"/></svg>

After

Width:  |  Height:  |  Size: 666 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><linearGradient id="g" x1="0" y1="24" x2="24" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ab543a"/><stop offset="1" stop-color="#ff7e57"/></linearGradient></defs><path fill="url(#g)" d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2m-2 5h-3v5.5a2.5 2.5 0 0 1-5 0a2.5 2.5 0 0 1 2.5-2.5c.57 0 1.08.19 1.5.51V5h4zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4z"/></svg>

After

Width:  |  Height:  |  Size: 471 B

+31
View File
@@ -1,6 +1,7 @@
import '../media/media_backend.dart';
import '../models/plex/plex_home_user.dart';
import '../services/plex_auth_service.dart';
import '../utils/json_utils.dart';
import '../utils/url_utils.dart';
/// Identifier of a backend kind a [Connection] points at. Lighter-weight than
@@ -232,6 +233,13 @@ class JellyfinConnection extends Connection {
/// match/unmatch, edit metadata) without an extra round-trip.
final bool isAdministrator;
/// The authenticated user's `PrimaryImageTag`, or `null` when they have no
/// profile picture. Jellyfin omits the key entirely in that case, and the
/// tag is `MD5(imagePath + lastModified)` so it changes on every upload —
/// which makes the derived avatar URL self-invalidating. Captured at auth
/// time and refreshed by [JellyfinClient.checkHealth].
final String? primaryImageTag;
JellyfinConnection({
required this.id,
required String baseUrl,
@@ -243,6 +251,7 @@ class JellyfinConnection extends Connection {
required this.accessToken,
required this.deviceId,
this.isAdministrator = false,
this.primaryImageTag,
this.status = ConnectionStatus.unknown,
required this.createdAt,
this.lastAuthenticatedAt,
@@ -298,6 +307,12 @@ class JellyfinConnection extends Connection {
String? accessToken,
String? deviceId,
bool? isAdministrator,
String? primaryImageTag,
/// Deleting a Jellyfin profile picture drops `PrimaryImageTag` from the
/// user DTO, so a refresh must be able to null the cached value — a bare
/// `primaryImageTag: null` is indistinguishable from "unchanged".
bool clearPrimaryImageTag = false,
ConnectionStatus? status,
DateTime? createdAt,
DateTime? lastAuthenticatedAt,
@@ -314,6 +329,7 @@ class JellyfinConnection extends Connection {
accessToken: accessToken ?? this.accessToken,
deviceId: deviceId ?? this.deviceId,
isAdministrator: isAdministrator ?? this.isAdministrator,
primaryImageTag: clearPrimaryImageTag ? null : (primaryImageTag ?? this.primaryImageTag),
status: status ?? this.status,
createdAt: createdAt ?? this.createdAt,
lastAuthenticatedAt: lastAuthenticatedAt ?? this.lastAuthenticatedAt,
@@ -332,6 +348,7 @@ class JellyfinConnection extends Connection {
'accessToken': accessToken,
'deviceId': deviceId,
'isAdministrator': isAdministrator,
'primaryImageTag': primaryImageTag,
};
}
@@ -359,9 +376,23 @@ class JellyfinConnection extends Connection {
accessToken: json['accessToken'] as String? ?? '',
deviceId: json['deviceId'] as String? ?? '',
isAdministrator: json['isAdministrator'] as bool? ?? false,
primaryImageTag: normalizePrimaryImageTag(json['primaryImageTag']),
status: status,
createdAt: createdAt,
lastAuthenticatedAt: lastAuthenticatedAt,
);
}
/// Tolerant read of a Jellyfin user DTO's `PrimaryImageTag`.
///
/// The tag is decorative — a fork or a drifted scalar type must never brick
/// sign-in — so this coerces through [readStringField] rather than casting,
/// and collapses absent/blank to `null` ("no picture").
static String? readPrimaryImageTag(Map<String, Object?> userDto) =>
normalizePrimaryImageTag(readStringField(userDto, 'PrimaryImageTag'));
static String? normalizePrimaryImageTag(Object? raw) {
final tag = raw?.toString().trim();
return tag == null || tag.isEmpty ? null : tag;
}
}
+12 -3
View File
@@ -42,14 +42,22 @@ class ConnectionRegistry {
/// Insert or replace [connection]. If this is the first stored connection
/// it is automatically marked default; re-upserting an existing row keeps
/// the row's current `isDefault` (so token/metadata refreshes don't clear
/// the default flag).
/// the row's current `isDefault` and `createdAt` (so token/metadata
/// refreshes don't clear the default flag or restamp creation order).
///
/// Creation order is behaviour, not bookkeeping: it decides which
/// connection lends a profile its picture, and `remove` promotes the oldest
/// remaining row to default. Re-authenticating rebuilds the model with
/// `DateTime.now()` and reuses the same stable id, so without this the
/// originally-first connection would jump to last on every re-sign-in.
Future<void> upsert(Connection connection) async {
await _db.runIdentityMutation(() async {
final existing = await (_db.select(_db.connections)..where((t) => t.id.equals(connection.id))).getSingleOrNull();
final bool isDefault;
final int createdAt;
if (existing != null) {
isDefault = existing.isDefault;
createdAt = existing.createdAt;
} else {
final any =
await (_db.selectOnly(_db.connections)
@@ -57,6 +65,7 @@ class ConnectionRegistry {
..limit(1))
.getSingleOrNull();
isDefault = any == null;
createdAt = connection.createdAt.millisecondsSinceEpoch;
}
final protectedConfig = await CredentialVault.protectConnectionConfig(
connection.kind.id,
@@ -68,7 +77,7 @@ class ConnectionRegistry {
displayName: Value(connection.displayName),
configJson: Value(jsonEncode(protectedConfig)),
isDefault: Value(isDefault),
createdAt: Value(connection.createdAt.millisecondsSinceEpoch),
createdAt: Value(createdAt),
lastAuthenticatedAt: Value(connection.lastAuthenticatedAt?.millisecondsSinceEpoch),
);
await _db.into(_db.connections).insertOnConflictUpdate(row);
+18 -10
View File
@@ -85,9 +85,10 @@ class AppDatabase extends _$AppDatabase {
static final Object _durabilityZoneKey = Object();
static final SerialFutureQueue _tvosRecoveryQueue = SerialFutureQueue();
/// Resolves and opens the production database, eagerly completing Drift
/// setup and migrations on non-tvOS before returning. tvOS recovery retains
/// ownership of database access ordering.
/// Resolves and opens the production database, removing orphaned WAL/SHM
/// sidecars when the main database is absent (#1732), then eagerly completing
/// Drift setup and migrations on non-tvOS. tvOS recovery retains ownership
/// of database access ordering.
static Future<AppDatabaseBootstrap> open({
bool isTvos = const bool.fromEnvironment('TVOS_BUILD'),
File? databaseFile,
@@ -105,7 +106,7 @@ class AppDatabase extends _$AppDatabase {
}
final databaseExisted = await file.exists();
if (isTvos && !databaseExisted) {
if (!databaseExisted) {
await _removeOrphanedDatabaseSidecars(file);
}
@@ -379,7 +380,7 @@ class AppDatabase extends _$AppDatabase {
onUpgrade: (Migrator m, int from, int to) async {
if (from < 7) {
appLogger.i('Adding OfflineWatchProgress table (v7 migration)');
await m.createTable(offlineWatchProgress);
await _ignoreAlreadyExists('OfflineWatchProgress table', () => m.createTable(offlineWatchProgress));
}
if (from < 8) {
appLogger.i('Adding bgTaskId column to DownloadedMedia (v8 migration)');
@@ -397,7 +398,7 @@ class AppDatabase extends _$AppDatabase {
}
if (from < 10) {
appLogger.i('Adding SyncRules table (v10 migration)');
await m.createTable(syncRules);
await _ignoreAlreadyExists('SyncRules table', () => m.createTable(syncRules));
}
if (from < 11) {
appLogger.i('Adding enabled column to SyncRules (v11 migration)');
@@ -427,13 +428,13 @@ class AppDatabase extends _$AppDatabase {
'Adding Connections, Profiles, ProfileConnections, DownloadOwners + scope/profile columns (v14 migration)',
);
await m.createTable(connections);
await _ignoreAlreadyExists('Connections table', () => m.createTable(connections));
await _ignoreAlreadyExists('Index idx_connections_kind', () => m.create(idxConnectionsKind));
await m.createTable(profiles);
await _ignoreAlreadyExists('Profiles table', () => m.createTable(profiles));
await _ignoreAlreadyExists('Index idx_profiles_kind', () => m.create(idxProfilesKind));
await m.createTable(profileConnections);
await _ignoreAlreadyExists('ProfileConnections table', () => m.createTable(profileConnections));
await _ignoreAlreadyExists(
'Index idx_profile_connections_connection_id',
() => m.create(idxProfileConnectionsConnectionId),
@@ -1292,10 +1293,17 @@ Future<File> _resolveProductionDatabaseFile() async {
return File(p.join(dbFolder.path, 'plezy_downloads.db'));
}
/// Best-effort removal for sidecars left without a main database after an
/// interrupted write. This runs on every platform but only when the caller has
/// confirmed the main database is absent (#1732).
Future<void> _removeOrphanedDatabaseSidecars(File databaseFile) async {
for (final suffix in const ['-wal', '-shm']) {
final sidecar = File('${databaseFile.path}$suffix');
if (await sidecar.exists()) await sidecar.delete();
try {
if (await sidecar.exists()) await sidecar.delete();
} on FileSystemException catch (error, stackTrace) {
appLogger.w('Unable to remove orphaned database sidecar ${sidecar.path}', error: error, stackTrace: stackTrace);
}
}
}
@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/app_logger.dart';
import '../services/base_shared_preferences_service.dart';
/// Startup result after reconciling the purgeable tvOS database with its
/// bounded standard-domain recovery image.
@@ -98,7 +99,14 @@ final class TvosDatabaseRecoveryStore {
}) async {
if (!isTvos) return TvosDatabaseRecoveryOutcome.notApplicable;
final recoveryRequired = _preferences.getBool(recoveryRequiredKey) ?? false;
// Tolerant read: `reconcile` runs inside `AppDatabase.open`, a fatal
// startup step, so a wrong-typed marker would veto the launch outright on
// a first-class TV target. An unreadable marker tells us nothing, which is
// the same position as an absent one — default false and drop the key
// (#1732). The manifest reads below are already inside catch-alls.
final recoveryRequired =
readPreferenceTolerantly(_preferences, recoveryRequiredKey, () => _preferences.getBool(recoveryRequiredKey)) ??
false;
if (recoveryRequired) {
await _reloadManifestCacheIfNeeded();
final snapshot = _readCommittedSnapshot();
+17
View File
@@ -123,6 +123,23 @@ KeyEventResult handleOneShotSelect(KeyEvent event, VoidCallback onActivate) {
return KeyEventResult.handled;
}
/// Whether the primary focus currently belongs to an active text editor.
///
/// Ancestor key handlers use this to stay off keys a focused field owns.
/// Flutter dispatches a key event from the focused node upwards, and the
/// editing shortcuts that turn Backspace into a deletion live in
/// [DefaultTextEditingShortcuts] at the very top of the app — *above* any
/// screen. An ancestor that claims Backspace as "back" therefore both steals
/// the navigation and stops the character from ever being deleted (#1741).
///
/// [EditableText] builds its [Focus] internally, so the focused node's context
/// resolves to the owning [EditableTextState].
bool isTextEditingFocused() {
final context = FocusManager.instance.primaryFocus?.context;
if (context == null) return false;
return context.findAncestorStateOfType<EditableTextState>() != null;
}
/// Expands a UTF-16 [range] to whole extended grapheme clusters in [text].
///
/// Flutter selections use UTF-16 code-unit offsets. Custom editors must pass a
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Yüklənir...",
"fullscreen": "Tam ekran",
"exitFullscreen": "Tam ekrandan çıx",
"pressBackAgainToExit": "Çıxmaq üçün geri düyməsinə bir daha basın"
"pressBackAgainToExit": "Çıxmaq üçün geri düyməsinə bir daha basın",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Lisenziyalar",
@@ -585,6 +598,7 @@
"pauseButton": "Fasilə",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Oynatma idarəetmələrini göstər",
"hidePlaybackControls": "Oynatma idarəetmələrini gizlət",
"seekBackwardButton": "${seconds} saniyə geri sar",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Uyğun oynadıcıya keçilir...",
"serverLimitTitle": "Oynatma uğursuz oldu",
"serverLimitBody": "Server xətası (HTTP 500). Məhdudiyyət bu seansı rədd etdi.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Jurnallar yükləndi",
"logsUploadFailed": "Jurnallar yüklənə bilmədi",
"logId": "Jurnal ID-si"
@@ -969,6 +985,38 @@
"copyLogs": "Jurnalları kopyala",
"uploadLogs": "Jurnalları yüklə"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Əlaqəli paketlər",
"license": "Lisenziya",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Зареждане...",
"fullscreen": "На цял екран",
"exitFullscreen": "Изход от цял екран",
"pressBackAgainToExit": "Натиснете Назад отново, за да излезете"
"pressBackAgainToExit": "Натиснете Назад отново, за да излезете",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Лицензи",
@@ -585,6 +598,7 @@
"pauseButton": "Пауза",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Покажи контролите за възпроизвеждане",
"hidePlaybackControls": "Скрий контролите за възпроизвеждане",
"seekBackwardButton": "Превърти назад ${seconds} секунди",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Превключване към съвместим плейър...",
"serverLimitTitle": "Възпроизвеждането е неуспешно",
"serverLimitBody": "Грешка на сървъра (HTTP 500). Вероятно лимит за пропускателна способност/транскодиране е отхвърлил тази сесия. Помолете собственика да го коригира.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Логовете са качени",
"logsUploadFailed": "Неуспешно качване на логовете",
"logId": "ID на лога"
@@ -969,6 +985,38 @@
"copyLogs": "Копирай логовете",
"uploadLogs": "Качи логовете"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Свързани пакети",
"license": "Лиценз",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Indlæser...",
"fullscreen": "Fuldskærm",
"exitFullscreen": "Forlad fuldskærm",
"pressBackAgainToExit": "Tryk på tilbage igen for at afslutte"
"pressBackAgainToExit": "Tryk på tilbage igen for at afslutte",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Licenser",
@@ -585,6 +598,7 @@
"pauseButton": "Pause",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Vis afspilningsknapper",
"hidePlaybackControls": "Skjul afspilningsknapper",
"seekBackwardButton": "Spol ${seconds} sekunder tilbage",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Skifter til kompatibel afspiller...",
"serverLimitTitle": "Afspilning mislykkedes",
"serverLimitBody": "Serverfejl (HTTP 500). En båndbredde- eller transkodningsgrænse afviste sandsynligvis sessionen. Bed ejeren om at justere den.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Logfilerne blev uploadet",
"logsUploadFailed": "Logfilerne kunne ikke uploades",
"logId": "Log-ID"
@@ -969,6 +985,38 @@
"copyLogs": "Kopiér logfiler",
"uploadLogs": "Upload logfiler"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Relaterede pakker",
"license": "Licens",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Wird geladen …",
"fullscreen": "Vollbild",
"exitFullscreen": "Vollbild verlassen",
"pressBackAgainToExit": "Zum Beenden erneut Zurück drücken"
"pressBackAgainToExit": "Zum Beenden erneut Zurück drücken",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Lizenzen",
@@ -585,6 +598,7 @@
"pauseButton": "Pause",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Wiedergabesteuerung anzeigen",
"hidePlaybackControls": "Wiedergabesteuerung ausblenden",
"seekBackwardButton": "${seconds} Sekunden zurück",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Wechsel zu einem kompatiblen Player …",
"serverLimitTitle": "Wiedergabe fehlgeschlagen",
"serverLimitBody": "Serverfehler (HTTP 500). Vermutlich hat ein Bandbreiten- oder Transkodierungslimit diese Sitzung abgelehnt. Bitte den Besitzer, das Limit anzupassen.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Protokolle hochgeladen",
"logsUploadFailed": "Protokolle konnten nicht hochgeladen werden",
"logId": "Protokoll-ID"
@@ -969,6 +985,38 @@
"copyLogs": "Protokolle kopieren",
"uploadLogs": "Protokolle hochladen"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Verwandte Pakete",
"license": "Lizenz",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Loading...",
"fullscreen": "Fullscreen",
"exitFullscreen": "Exit fullscreen",
"pressBackAgainToExit": "Press back again to exit"
"pressBackAgainToExit": "Press back again to exit",
"ratingSource": {
"critic": "Critics",
"audience": "Audience",
"imdb": "IMDb",
"tmdb": "TMDB",
"rottenTomatoes": "Rotten Tomatoes",
"simkl": "Simkl",
"mal": "MyAnimeList",
"anilist": "AniList",
"trakt": "Trakt",
"rottenTomatoesCritic": "Rotten Tomatoes critics",
"rottenTomatoesAudience": "Rotten Tomatoes audience"
}
},
"screens": {
"licenses": "Licenses",
@@ -585,6 +598,7 @@
"pauseButton": "Pause",
"playbackPaused": "Paused",
"playbackResumed": "Playing",
"loadingVideo": "Loading video",
"showPlaybackControls": "Show playback controls",
"hidePlaybackControls": "Hide playback controls",
"seekBackwardButton": "Seek backward ${seconds} seconds",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Switching to compatible player...",
"serverLimitTitle": "Playback failed",
"serverLimitBody": "Server error (HTTP 500). A bandwidth/transcoding limit likely rejected this session. Ask the owner to adjust it.",
"mediaUnreadableTitle": "File unavailable",
"mediaUnreadableBody": "The server found this item but could not read its file (HTTP 404). The file was probably moved, deleted, or its storage is offline. Ask the server owner to check the file and rescan the library.",
"logsUploaded": "Logs uploaded",
"logsUploadFailed": "Failed to upload logs",
"logId": "Log ID"
@@ -969,6 +985,38 @@
"copyLogs": "Copy Logs",
"uploadLogs": "Upload Logs"
},
"startup": {
"failedTitle": "Plezy could not start",
"failedBody": "Something went wrong during startup. The details below identify what failed.",
"failedBodyRepairable": "Plezy's saved settings file is damaged and has to be rebuilt before Plezy can start. Retrying will not help — choose Repair storage.",
"phaseLabel": "Step",
"showDetails": "Show details",
"hideDetails": "Hide details",
"copyDetails": "Copy details",
"detailsCopied": "Details copied to clipboard",
"uploadDetails": "Upload details",
"repairStorage": "Repair storage",
"repairTitle": "Repair stored data?",
"repairBodyCommon": "Plezy's settings file is damaged and cannot be read. Repairing resets every setting to its default.",
"repairBodyOneCredential": "One saved sign-in is damaged and cannot be read. Repairing removes just that one; your other settings are left alone.",
"repairBodySignInsKept": "Your servers and profiles should stay signed in.",
"repairBodySignInsLost": "The key protecting your saved sign-ins cannot be recovered from this file, so you will have to sign in to every server and profile again. Nothing on your media server is affected.",
"repairBodySessionsUncertain": "Trackers (MAL, AniList, Simkl, Trakt) and Seerr are stored separately and may or may not survive. Plezy will tell you exactly what it kept.",
"repairConfirm": "Repair",
"repairSucceeded": "Storage repaired",
"repairNeedsRestart": "Storage repaired — restart required",
"restartRequiredBody": "Your data was repaired, but Plezy has to start fresh before it can use it. Close Plezy and open it again.",
"quitPlezy": "Quit Plezy",
"repairFailed": "Repair failed",
"repairKeptSignIns": "Your servers and profiles are still signed in.",
"repairLostSignIns": "The key protecting your saved sign-ins could not be recovered. You will have to sign in to every server and profile again.",
"repairLostSessions": "At least one tracker or Seerr connection was lost and has to be reconnected.",
"backupTitle": "A copy of the damaged file was kept",
"backupWarning": "It contains your sign-in credentials. Do not upload or share it.",
"deleteBackup": "Delete copy",
"backupDeleted": "Copy deleted.",
"previousFailureTitle": "Plezy failed to start last time"
},
"licenses": {
"relatedPackages": "Related Packages",
"license": "License",
@@ -1103,18 +1151,16 @@
"creator": "Creator",
"composer": "Composer"
},
"ratingSource": {
"critic": "Critics",
"audience": "Audience",
"imdb": "IMDb",
"tmdb": "TMDB",
"rottenTomatoes": "Rotten Tomatoes",
"simkl": "Simkl",
"mal": "MyAnimeList",
"anilist": "AniList",
"trakt": "Trakt",
"rottenTomatoesCritic": "Rotten Tomatoes critics",
"rottenTomatoesAudience": "Rotten Tomatoes audience"
"relation": {
"prequel": "Prequel",
"sequel": "Sequel",
"sideStory": "Side story",
"spinOff": "Spin-off",
"alternativeVersion": "Alternative version",
"summary": "Summary",
"parentStory": "Parent story",
"adaptation": "Adaptation",
"other": "Related"
},
"broadcast": "Airs ${day} at ${time}",
"broadcastWithZone": "Airs ${day} at ${time} ${timezone}",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "${n} result",
"other": "${n} results"
},
"relation": {
"prequel": "Prequel",
"sequel": "Sequel",
"sideStory": "Side story",
"spinOff": "Spin-off",
"alternativeVersion": "Alternative version",
"summary": "Summary",
"parentStory": "Parent story",
"adaptation": "Adaptation",
"other": "Related"
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Cargando...",
"fullscreen": "Pantalla completa",
"exitFullscreen": "Salir de pantalla completa",
"pressBackAgainToExit": "Pulsa Atrás de nuevo para salir"
"pressBackAgainToExit": "Pulsa Atrás de nuevo para salir",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Licencias",
@@ -585,6 +598,7 @@
"pauseButton": "Pausar",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Mostrar controles de reproducción",
"hidePlaybackControls": "Ocultar controles de reproducción",
"seekBackwardButton": "Retroceder ${seconds} segundos",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Cambiando a reproductor compatible...",
"serverLimitTitle": "Error de reproducción",
"serverLimitBody": "Error del servidor (HTTP 500). Un límite de ancho de banda/transcodificación probablemente rechazó esta sesión. Pide al propietario que lo ajuste.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Registros subidos",
"logsUploadFailed": "Error al subir registros",
"logId": "ID de registro"
@@ -969,6 +985,38 @@
"copyLogs": "Copiar registros",
"uploadLogs": "Subir registros"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Paquetes relacionados",
"license": "Licencia",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Chargement...",
"fullscreen": "Plein écran",
"exitFullscreen": "Quitter le plein écran",
"pressBackAgainToExit": "Appuyez à nouveau sur retour pour quitter"
"pressBackAgainToExit": "Appuyez à nouveau sur retour pour quitter",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Licences",
@@ -585,6 +598,7 @@
"pauseButton": "Pause",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Afficher les commandes de lecture",
"hidePlaybackControls": "Masquer les commandes de lecture",
"seekBackwardButton": "Reculer de ${seconds} secondes",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Passage au lecteur compatible...",
"serverLimitTitle": "Échec de la lecture",
"serverLimitBody": "Erreur serveur (HTTP 500). Une limite de bande passante/transcodage a probablement rejeté cette session. Demandez au propriétaire de l'ajuster.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Journaux envoyés",
"logsUploadFailed": "Échec de l’envoi des journaux",
"logId": "Identifiant du journal"
@@ -969,6 +985,38 @@
"copyLogs": "Copier les journaux",
"uploadLogs": "Envoyer les journaux"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Paquets associés",
"license": "Licence",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Betöltés...",
"fullscreen": "Teljes képernyő",
"exitFullscreen": "Kilépés a teljes képernyőből",
"pressBackAgainToExit": "A kilépéshez nyomd meg újra a Vissza gombot"
"pressBackAgainToExit": "A kilépéshez nyomd meg újra a Vissza gombot",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Licencek",
@@ -585,6 +598,7 @@
"pauseButton": "Szünet",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Lejátszásvezérlők megjelenítése",
"hidePlaybackControls": "Lejátszásvezérlők elrejtése",
"seekBackwardButton": "Tekerés hátra ${seconds} másodperccel",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Váltás kompatibilis lejátszóra...",
"serverLimitTitle": "A lejátszás nem sikerült",
"serverLimitBody": "Szerverhiba (HTTP 500). A munkamenetet valószínűleg egy sávszélességi vagy átkódolási korlát utasította el. Kérd meg a tulajdonost a korlát módosítására.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Naplók feltöltve",
"logsUploadFailed": "Nem sikerült a naplók feltöltése",
"logId": "Naplóazonosító"
@@ -969,6 +985,38 @@
"copyLogs": "Naplók másolása",
"uploadLogs": "Naplók feltöltése"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Kapcsolódó csomagok",
"license": "Licenc",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Caricamento...",
"fullscreen": "Schermo intero",
"exitFullscreen": "Esci dalla modalità a schermo intero",
"pressBackAgainToExit": "Premi di nuovo Indietro per uscire"
"pressBackAgainToExit": "Premi di nuovo Indietro per uscire",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Licenze",
@@ -585,6 +598,7 @@
"pauseButton": "Pausa",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Mostra i controlli di riproduzione",
"hidePlaybackControls": "Nascondi i controlli di riproduzione",
"seekBackwardButton": "Riavvolgi di ${seconds} secondi",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Passaggio al lettore compatibile...",
"serverLimitTitle": "Riproduzione non riuscita",
"serverLimitBody": "Errore del server (HTTP 500). È probabile che un limite di banda o transcodifica abbia impedito questa sessione. Chiedi al proprietario di modificare il limite.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Log caricati",
"logsUploadFailed": "Impossibile caricare i log",
"logId": "ID log"
@@ -969,6 +985,38 @@
"copyLogs": "Copia log",
"uploadLogs": "Carica log"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Pacchetti correlati",
"license": "Licenza",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "読み込み中…",
"fullscreen": "フルスクリーン",
"exitFullscreen": "フルスクリーンを終了",
"pressBackAgainToExit": "もう一度押すと終了します"
"pressBackAgainToExit": "もう一度押すと終了します",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "ライセンス",
@@ -585,6 +598,7 @@
"pauseButton": "一時停止",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "再生コントロールを表示",
"hidePlaybackControls": "再生コントロールを非表示",
"seekBackwardButton": "${seconds}秒戻る",
@@ -694,6 +708,8 @@
"switchingToCompatiblePlayer": "互換性のあるプレーヤーに切り替え中…",
"serverLimitTitle": "再生に失敗しました",
"serverLimitBody": "サーバーエラー(HTTP 500)。帯域幅/トランスコード制限により拒否された可能性があります。所有者に調整を依頼してください。",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "ログをアップロードしました",
"logsUploadFailed": "ログのアップロードに失敗しました",
"logId": "ログID"
@@ -968,6 +984,38 @@
"copyLogs": "ログをコピー",
"uploadLogs": "ログをアップロード"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "関連パッケージ",
"license": "ライセンス",
@@ -1100,18 +1148,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1150,17 +1196,6 @@
},
"totalResults": {
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Жүктелуде...",
"fullscreen": "Толық экран",
"exitFullscreen": "Толық экраннан шығу",
"pressBackAgainToExit": "Шығу үшін артқа түймесін қайтадан басыңыз"
"pressBackAgainToExit": "Шығу үшін артқа түймесін қайтадан басыңыз",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Лицензиялар",
@@ -585,6 +598,7 @@
"pauseButton": "Кідірту",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Басқару элементтерін көрсету",
"hidePlaybackControls": "Басқару элементтерін жасыру",
"seekBackwardButton": "${seconds} секунд артқа айналдыру",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Үйлесімді ойнатқышқа ауысуда...",
"serverLimitTitle": "Ойнату қатесі",
"serverLimitBody": "Сервер қатесі (HTTP 500). Шектеу бұл сеансты қабылдамады.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Журналдар жүктелді",
"logsUploadFailed": "Журналдарды жүктеу мүмкін болмады",
"logId": "Журнал ID-сі"
@@ -969,6 +985,38 @@
"copyLogs": "Журналдарды көшіру",
"uploadLogs": "Журналдарды жүктеу"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Байланысты пакеттер",
"license": "Лицензия",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "로딩 중...",
"fullscreen": "전체 화면",
"exitFullscreen": "전체 화면 종료",
"pressBackAgainToExit": "한 번 더 누르면 종료됩니다"
"pressBackAgainToExit": "한 번 더 누르면 종료됩니다",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "라이선스",
@@ -585,6 +598,7 @@
"pauseButton": "일시정지",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "재생 컨트롤 표시",
"hidePlaybackControls": "재생 컨트롤 숨기기",
"seekBackwardButton": "${seconds}초 뒤로 이동",
@@ -694,6 +708,8 @@
"switchingToCompatiblePlayer": "호환되는 플레이어로 전환 중...",
"serverLimitTitle": "재생 실패",
"serverLimitBody": "서버 오류(HTTP 500). 대역폭/트랜스코딩 제한으로 세션이 거부된 것 같습니다. 소유자에게 조정을 요청하세요.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "로그 업로드 완료",
"logsUploadFailed": "로그 업로드 실패",
"logId": "로그 ID"
@@ -968,6 +984,38 @@
"copyLogs": "로그 복사",
"uploadLogs": "로그 업로드"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "관련 소프트웨어 패키지",
"license": "라이선스",
@@ -1100,18 +1148,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1150,17 +1196,6 @@
},
"totalResults": {
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Laster...",
"fullscreen": "Fullskjerm",
"exitFullscreen": "Avslutt fullskjerm",
"pressBackAgainToExit": "Trykk på Tilbake en gang til for å avslutte"
"pressBackAgainToExit": "Trykk på Tilbake en gang til for å avslutte",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Lisenser",
@@ -585,6 +598,7 @@
"pauseButton": "Pause",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Vis avspillingskontroller",
"hidePlaybackControls": "Skjul avspillingskontroller",
"seekBackwardButton": "Spol tilbake ${seconds} sekunder",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Bytter til kompatibel spiller...",
"serverLimitTitle": "Avspilling mislyktes",
"serverLimitBody": "Serverfeil (HTTP 500). En båndbredde-/transkodingsgrense avviste trolig økten. Be eieren justere den.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Logger lastet opp",
"logsUploadFailed": "Kunne ikke laste opp logger",
"logId": "Logg-ID"
@@ -969,6 +985,38 @@
"copyLogs": "Kopier logger",
"uploadLogs": "Last opp logger"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Relaterte pakker",
"license": "Lisens",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Laden...",
"fullscreen": "Volledig scherm",
"exitFullscreen": "Volledig scherm verlaten",
"pressBackAgainToExit": "Druk nogmaals op terug om af te sluiten"
"pressBackAgainToExit": "Druk nogmaals op terug om af te sluiten",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Licenties",
@@ -585,6 +598,7 @@
"pauseButton": "Pauzeren",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Afspeelbediening tonen",
"hidePlaybackControls": "Afspeelbediening verbergen",
"seekBackwardButton": "${seconds} seconden terugspoelen",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Overschakelen naar compatibele speler...",
"serverLimitTitle": "Afspelen mislukt",
"serverLimitBody": "Serverfout (HTTP 500). Waarschijnlijk weigerde een bandbreedte-/transcodeerlimiet deze sessie. Vraag de eigenaar dit aan te passen.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Logbestanden geüpload",
"logsUploadFailed": "Uploaden van logbestanden mislukt",
"logId": "Logboek-ID"
@@ -969,6 +985,38 @@
"copyLogs": "Logbestanden kopiëren",
"uploadLogs": "Logbestanden uploaden"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Gerelateerde pakketten",
"license": "Licentie",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Ładowanie...",
"fullscreen": "Pełny ekran",
"exitFullscreen": "Wyjdź z pełnego ekranu",
"pressBackAgainToExit": "Naciśnij ponownie przycisk Wstecz, aby wyjść"
"pressBackAgainToExit": "Naciśnij ponownie przycisk Wstecz, aby wyjść",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Licencje",
@@ -585,6 +598,7 @@
"pauseButton": "Pauza",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Pokaż elementy sterujące odtwarzaniem",
"hidePlaybackControls": "Ukryj elementy sterujące odtwarzaniem",
"seekBackwardButton": "Przewiń do tyłu o ${seconds} sekund",
@@ -697,6 +711,8 @@
"switchingToCompatiblePlayer": "Przełączanie na kompatybilny odtwarzacz...",
"serverLimitTitle": "Odtwarzanie nie powiodło się",
"serverLimitBody": "Błąd serwera (HTTP 500). Limit przepustowości/transkodowania prawdopodobnie odrzucił tę sesję. Poproś właściciela o zmianę.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Logi przesłane",
"logsUploadFailed": "Nie udało się przesłać logów",
"logId": "ID logu"
@@ -971,6 +987,38 @@
"copyLogs": "Kopiuj logi",
"uploadLogs": "Prześlij logi"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Powiązane pakiety",
"license": "Licencja",
@@ -1109,18 +1157,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1165,17 +1211,6 @@
"few": "",
"many": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Carregando...",
"fullscreen": "Tela cheia",
"exitFullscreen": "Sair da tela cheia",
"pressBackAgainToExit": "Pressione voltar novamente para sair"
"pressBackAgainToExit": "Pressione voltar novamente para sair",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Licenças",
@@ -585,6 +598,7 @@
"pauseButton": "Pausar",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Mostrar controles de reprodução",
"hidePlaybackControls": "Ocultar controles de reprodução",
"seekBackwardButton": "Retroceder ${seconds} segundos",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Alternando para um reprodutor compatível...",
"serverLimitTitle": "Falha na reprodução",
"serverLimitBody": "Erro do servidor (HTTP 500). Um limite de largura de banda ou transcodificação provavelmente rejeitou esta sessão. Peça ao proprietário do servidor para ajustá-lo.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Logs enviados",
"logsUploadFailed": "Falha ao enviar logs",
"logId": "ID do log"
@@ -969,6 +985,38 @@
"copyLogs": "Copiar Logs",
"uploadLogs": "Enviar Logs"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Pacotes Relacionados",
"license": "Licença",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Загрузка...",
"fullscreen": "Полноэкранный режим",
"exitFullscreen": "Выйти из полноэкранного режима",
"pressBackAgainToExit": "Нажмите ещё раз для выхода"
"pressBackAgainToExit": "Нажмите ещё раз для выхода",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Лицензии",
@@ -585,6 +598,7 @@
"pauseButton": "Пауза",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Показать элементы управления воспроизведением",
"hidePlaybackControls": "Скрыть элементы управления воспроизведением",
"seekBackwardButton": "Перемотать назад на ${seconds} с",
@@ -697,6 +711,8 @@
"switchingToCompatiblePlayer": "Переключение на совместимый плеер...",
"serverLimitTitle": "Ошибка воспроизведения",
"serverLimitBody": "Ошибка сервера (HTTP 500). Лимит пропускной способности/транскодирования, вероятно, отклонил сессию. Попросите владельца изменить настройки.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Логи загружены",
"logsUploadFailed": "Не удалось загрузить логи",
"logId": "ID лога"
@@ -971,6 +987,38 @@
"copyLogs": "Скопировать логи",
"uploadLogs": "Загрузить логи"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Связанные пакеты",
"license": "Лицензия",
@@ -1109,18 +1157,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1165,17 +1211,6 @@
"few": "",
"many": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+1 -1
View File
@@ -4,7 +4,7 @@
/// To regenerate, run: `dart run slang`
///
/// Locales: 22
/// Strings: 32913 (1496 per locale)
/// Strings: 32946 (1497 per locale)
// coverage:ignore-file
// ignore_for_file: type=lint, unused_import
+234 -92
View File
@@ -68,6 +68,7 @@ class Translations with BaseTranslations<AppLocale, Translations> {
late final Translations$serverSelection$en serverSelection = Translations$serverSelection$en.internal(_root);
late final Translations$hubDetail$en hubDetail = Translations$hubDetail$en.internal(_root);
late final Translations$logs$en logs = Translations$logs$en.internal(_root);
late final Translations$startup$en startup = Translations$startup$en.internal(_root);
late final Translations$licenses$en licenses = Translations$licenses$en.internal(_root);
late final Translations$navigation$en navigation = Translations$navigation$en.internal(_root);
late final Translations$explore$en explore = Translations$explore$en.internal(_root);
@@ -299,6 +300,8 @@ class Translations$common$en {
/// en: 'Press back again to exit'
String get pressBackAgainToExit => 'Press back again to exit';
late final Translations$common$ratingSource$en ratingSource = Translations$common$ratingSource$en.internal(_root);
}
// Path: screens
@@ -1817,6 +1820,9 @@ class Translations$videoControls$en {
/// en: 'Playing'
String get playbackResumed => 'Playing';
/// en: 'Loading video'
String get loadingVideo => 'Loading video';
/// en: 'Show playback controls'
String get showPlaybackControls => 'Show playback controls';
@@ -2116,6 +2122,12 @@ class Translations$messages$en {
/// en: 'Server error (HTTP 500). A bandwidth/transcoding limit likely rejected this session. Ask the owner to adjust it.'
String get serverLimitBody => 'Server error (HTTP 500). A bandwidth/transcoding limit likely rejected this session. Ask the owner to adjust it.';
/// en: 'File unavailable'
String get mediaUnreadableTitle => 'File unavailable';
/// en: 'The server found this item but could not read its file (HTTP 404). The file was probably moved, deleted, or its storage is offline. Ask the server owner to check the file and rescan the library.'
String get mediaUnreadableBody => 'The server found this item but could not read its file (HTTP 404). The file was probably moved, deleted, or its storage is offline. Ask the server owner to check the file and rescan the library.';
/// en: 'Logs uploaded'
String get logsUploaded => 'Logs uploaded';
@@ -2830,6 +2842,105 @@ class Translations$logs$en {
String get uploadLogs => 'Upload Logs';
}
// Path: startup
class Translations$startup$en {
Translations$startup$en.internal(this._root);
final Translations _root; // ignore: unused_field
// Translations
/// en: 'Plezy could not start'
String get failedTitle => 'Plezy could not start';
/// en: 'Something went wrong during startup. The details below identify what failed.'
String get failedBody => 'Something went wrong during startup. The details below identify what failed.';
/// en: 'Plezy's saved settings file is damaged and has to be rebuilt before Plezy can start. Retrying will not help — choose Repair storage.'
String get failedBodyRepairable => 'Plezy\'s saved settings file is damaged and has to be rebuilt before Plezy can start. Retrying will not help — choose Repair storage.';
/// en: 'Step'
String get phaseLabel => 'Step';
/// en: 'Show details'
String get showDetails => 'Show details';
/// en: 'Hide details'
String get hideDetails => 'Hide details';
/// en: 'Copy details'
String get copyDetails => 'Copy details';
/// en: 'Details copied to clipboard'
String get detailsCopied => 'Details copied to clipboard';
/// en: 'Upload details'
String get uploadDetails => 'Upload details';
/// en: 'Repair storage'
String get repairStorage => 'Repair storage';
/// en: 'Repair stored data?'
String get repairTitle => 'Repair stored data?';
/// en: 'Plezy's settings file is damaged and cannot be read. Repairing resets every setting to its default.'
String get repairBodyCommon => 'Plezy\'s settings file is damaged and cannot be read. Repairing resets every setting to its default.';
/// en: 'One saved sign-in is damaged and cannot be read. Repairing removes just that one; your other settings are left alone.'
String get repairBodyOneCredential => 'One saved sign-in is damaged and cannot be read. Repairing removes just that one; your other settings are left alone.';
/// en: 'Your servers and profiles should stay signed in.'
String get repairBodySignInsKept => 'Your servers and profiles should stay signed in.';
/// en: 'The key protecting your saved sign-ins cannot be recovered from this file, so you will have to sign in to every server and profile again. Nothing on your media server is affected.'
String get repairBodySignInsLost => 'The key protecting your saved sign-ins cannot be recovered from this file, so you will have to sign in to every server and profile again. Nothing on your media server is affected.';
/// en: 'Trackers (MAL, AniList, Simkl, Trakt) and Seerr are stored separately and may or may not survive. Plezy will tell you exactly what it kept.'
String get repairBodySessionsUncertain => 'Trackers (MAL, AniList, Simkl, Trakt) and Seerr are stored separately and may or may not survive. Plezy will tell you exactly what it kept.';
/// en: 'Repair'
String get repairConfirm => 'Repair';
/// en: 'Storage repaired'
String get repairSucceeded => 'Storage repaired';
/// en: 'Storage repaired — restart required'
String get repairNeedsRestart => 'Storage repaired — restart required';
/// en: 'Your data was repaired, but Plezy has to start fresh before it can use it. Close Plezy and open it again.'
String get restartRequiredBody => 'Your data was repaired, but Plezy has to start fresh before it can use it. Close Plezy and open it again.';
/// en: 'Quit Plezy'
String get quitPlezy => 'Quit Plezy';
/// en: 'Repair failed'
String get repairFailed => 'Repair failed';
/// en: 'Your servers and profiles are still signed in.'
String get repairKeptSignIns => 'Your servers and profiles are still signed in.';
/// en: 'The key protecting your saved sign-ins could not be recovered. You will have to sign in to every server and profile again.'
String get repairLostSignIns => 'The key protecting your saved sign-ins could not be recovered. You will have to sign in to every server and profile again.';
/// en: 'At least one tracker or Seerr connection was lost and has to be reconnected.'
String get repairLostSessions => 'At least one tracker or Seerr connection was lost and has to be reconnected.';
/// en: 'A copy of the damaged file was kept'
String get backupTitle => 'A copy of the damaged file was kept';
/// en: 'It contains your sign-in credentials. Do not upload or share it.'
String get backupWarning => 'It contains your sign-in credentials. Do not upload or share it.';
/// en: 'Delete copy'
String get deleteBackup => 'Delete copy';
/// en: 'Copy deleted.'
String get backupDeleted => 'Copy deleted.';
/// en: 'Plezy failed to start last time'
String get previousFailureTitle => 'Plezy failed to start last time';
}
// Path: licenses
class Translations$licenses$en {
Translations$licenses$en.internal(this._root);
@@ -2943,7 +3054,7 @@ class Translations$explore$en {
late final Translations$explore$format$en format = Translations$explore$format$en.internal(_root);
late final Translations$explore$sourceMaterial$en sourceMaterial = Translations$explore$sourceMaterial$en.internal(_root);
late final Translations$explore$creditRole$en creditRole = Translations$explore$creditRole$en.internal(_root);
late final Translations$explore$ratingSource$en ratingSource = Translations$explore$ratingSource$en.internal(_root);
late final Translations$explore$relation$en relation = Translations$explore$relation$en.internal(_root);
/// en: 'Airs ${day} at ${time}'
String broadcast({required Object day, required Object time}) => 'Airs ${day} at ${time}';
@@ -2958,8 +3069,6 @@ class Translations$explore$en {
one: '${n} result',
other: '${n} results',
);
late final Translations$explore$relation$en relation = Translations$explore$relation$en.internal(_root);
}
// Path: liveTv
@@ -4723,6 +4832,48 @@ class Translations$addServer$en {
String get borrowFromAnotherProfileSubtitle => 'Reuse another profile\'s connection. PIN-protected profiles require a PIN.';
}
// Path: common.ratingSource
class Translations$common$ratingSource$en {
Translations$common$ratingSource$en.internal(this._root);
final Translations _root; // ignore: unused_field
// Translations
/// en: 'Critics'
String get critic => 'Critics';
/// en: 'Audience'
String get audience => 'Audience';
/// en: 'IMDb'
String get imdb => 'IMDb';
/// en: 'TMDB'
String get tmdb => 'TMDB';
/// en: 'Rotten Tomatoes'
String get rottenTomatoes => 'Rotten Tomatoes';
/// en: 'Simkl'
String get simkl => 'Simkl';
/// en: 'MyAnimeList'
String get mal => 'MyAnimeList';
/// en: 'AniList'
String get anilist => 'AniList';
/// en: 'Trakt'
String get trakt => 'Trakt';
/// en: 'Rotten Tomatoes critics'
String get rottenTomatoesCritic => 'Rotten Tomatoes critics';
/// en: 'Rotten Tomatoes audience'
String get rottenTomatoesAudience => 'Rotten Tomatoes audience';
}
// Path: hotkeys.actions
class Translations$hotkeys$actions$en {
Translations$hotkeys$actions$en.internal(this._root);
@@ -5317,46 +5468,40 @@ class Translations$explore$creditRole$en {
String get composer => 'Composer';
}
// Path: explore.ratingSource
class Translations$explore$ratingSource$en {
Translations$explore$ratingSource$en.internal(this._root);
// Path: explore.relation
class Translations$explore$relation$en {
Translations$explore$relation$en.internal(this._root);
final Translations _root; // ignore: unused_field
// Translations
/// en: 'Critics'
String get critic => 'Critics';
/// en: 'Prequel'
String get prequel => 'Prequel';
/// en: 'Audience'
String get audience => 'Audience';
/// en: 'Sequel'
String get sequel => 'Sequel';
/// en: 'IMDb'
String get imdb => 'IMDb';
/// en: 'Side story'
String get sideStory => 'Side story';
/// en: 'TMDB'
String get tmdb => 'TMDB';
/// en: 'Spin-off'
String get spinOff => 'Spin-off';
/// en: 'Rotten Tomatoes'
String get rottenTomatoes => 'Rotten Tomatoes';
/// en: 'Alternative version'
String get alternativeVersion => 'Alternative version';
/// en: 'Simkl'
String get simkl => 'Simkl';
/// en: 'Summary'
String get summary => 'Summary';
/// en: 'MyAnimeList'
String get mal => 'MyAnimeList';
/// en: 'Parent story'
String get parentStory => 'Parent story';
/// en: 'AniList'
String get anilist => 'AniList';
/// en: 'Adaptation'
String get adaptation => 'Adaptation';
/// en: 'Trakt'
String get trakt => 'Trakt';
/// en: 'Rotten Tomatoes critics'
String get rottenTomatoesCritic => 'Rotten Tomatoes critics';
/// en: 'Rotten Tomatoes audience'
String get rottenTomatoesAudience => 'Rotten Tomatoes audience';
/// en: 'Related'
String get other => 'Related';
}
// Path: explore.detail
@@ -5458,42 +5603,6 @@ class Translations$explore$detail$en {
String get background => 'Background';
}
// Path: explore.relation
class Translations$explore$relation$en {
Translations$explore$relation$en.internal(this._root);
final Translations _root; // ignore: unused_field
// Translations
/// en: 'Prequel'
String get prequel => 'Prequel';
/// en: 'Sequel'
String get sequel => 'Sequel';
/// en: 'Side story'
String get sideStory => 'Side story';
/// en: 'Spin-off'
String get spinOff => 'Spin-off';
/// en: 'Alternative version'
String get alternativeVersion => 'Alternative version';
/// en: 'Summary'
String get summary => 'Summary';
/// en: 'Parent story'
String get parentStory => 'Parent story';
/// en: 'Adaptation'
String get adaptation => 'Adaptation';
/// en: 'Related'
String get other => 'Related';
}
// Path: downloads.backgroundWarning
class Translations$downloads$backgroundWarning$en {
Translations$downloads$backgroundWarning$en.internal(this._root);
@@ -5986,6 +6095,17 @@ extension on Translations {
'common.fullscreen' => 'Fullscreen',
'common.exitFullscreen' => 'Exit fullscreen',
'common.pressBackAgainToExit' => 'Press back again to exit',
'common.ratingSource.critic' => 'Critics',
'common.ratingSource.audience' => 'Audience',
'common.ratingSource.imdb' => 'IMDb',
'common.ratingSource.tmdb' => 'TMDB',
'common.ratingSource.rottenTomatoes' => 'Rotten Tomatoes',
'common.ratingSource.simkl' => 'Simkl',
'common.ratingSource.mal' => 'MyAnimeList',
'common.ratingSource.anilist' => 'AniList',
'common.ratingSource.trakt' => 'Trakt',
'common.ratingSource.rottenTomatoesCritic' => 'Rotten Tomatoes critics',
'common.ratingSource.rottenTomatoesAudience' => 'Rotten Tomatoes audience',
'screens.licenses' => 'Licenses',
'screens.switchProfile' => 'Switch Profile',
'screens.subtitleStyling' => 'Subtitle Styling',
@@ -6426,6 +6546,8 @@ extension on Translations {
'rateSheet.notAvailable' => 'No match found',
'rateSheet.noConnectedServices' => 'Connect a service in Settings to rate there.',
'accessibility.mediaCardMovie' => ({required Object title}) => '${title}, movie',
_ => null,
} ?? switch (path) {
'accessibility.mediaCardShow' => ({required Object title}) => '${title}, TV show',
'accessibility.mediaCardEpisode' => ({required Object title, required Object episodeInfo}) => '${title}, ${episodeInfo}',
'accessibility.mediaCardSeason' => ({required Object title, required Object seasonInfo}) => '${title}, ${seasonInfo}',
@@ -6437,8 +6559,6 @@ extension on Translations {
'accessibility.increase' => 'Increase',
'accessibility.decreaseValue' => ({required Object label}) => 'Decrease ${label}',
'accessibility.increaseValue' => ({required Object label}) => 'Increase ${label}',
_ => null,
} ?? switch (path) {
'accessibility.hue' => 'Hue',
'accessibility.saturation' => 'Saturation',
'accessibility.brightness' => 'Brightness',
@@ -6482,6 +6602,7 @@ extension on Translations {
'videoControls.pauseButton' => 'Pause',
'videoControls.playbackPaused' => 'Paused',
'videoControls.playbackResumed' => 'Playing',
'videoControls.loadingVideo' => 'Loading video',
'videoControls.showPlaybackControls' => 'Show playback controls',
'videoControls.hidePlaybackControls' => 'Hide playback controls',
'videoControls.seekBackwardButton' => ({required Object seconds}) => 'Seek backward ${seconds} seconds',
@@ -6584,6 +6705,8 @@ extension on Translations {
'messages.switchingToCompatiblePlayer' => 'Switching to compatible player...',
'messages.serverLimitTitle' => 'Playback failed',
'messages.serverLimitBody' => 'Server error (HTTP 500). A bandwidth/transcoding limit likely rejected this session. Ask the owner to adjust it.',
'messages.mediaUnreadableTitle' => 'File unavailable',
'messages.mediaUnreadableBody' => 'The server found this item but could not read its file (HTTP 404). The file was probably moved, deleted, or its storage is offline. Ask the server owner to check the file and rescan the library.',
'messages.logsUploaded' => 'Logs uploaded',
'messages.logsUploadFailed' => 'Failed to upload logs',
'messages.logId' => 'Log ID',
@@ -6825,6 +6948,36 @@ extension on Translations {
'logs.clearLogs' => 'Clear Logs',
'logs.copyLogs' => 'Copy Logs',
'logs.uploadLogs' => 'Upload Logs',
'startup.failedTitle' => 'Plezy could not start',
'startup.failedBody' => 'Something went wrong during startup. The details below identify what failed.',
'startup.failedBodyRepairable' => 'Plezy\'s saved settings file is damaged and has to be rebuilt before Plezy can start. Retrying will not help — choose Repair storage.',
'startup.phaseLabel' => 'Step',
'startup.showDetails' => 'Show details',
'startup.hideDetails' => 'Hide details',
'startup.copyDetails' => 'Copy details',
'startup.detailsCopied' => 'Details copied to clipboard',
'startup.uploadDetails' => 'Upload details',
'startup.repairStorage' => 'Repair storage',
'startup.repairTitle' => 'Repair stored data?',
'startup.repairBodyCommon' => 'Plezy\'s settings file is damaged and cannot be read. Repairing resets every setting to its default.',
'startup.repairBodyOneCredential' => 'One saved sign-in is damaged and cannot be read. Repairing removes just that one; your other settings are left alone.',
'startup.repairBodySignInsKept' => 'Your servers and profiles should stay signed in.',
'startup.repairBodySignInsLost' => 'The key protecting your saved sign-ins cannot be recovered from this file, so you will have to sign in to every server and profile again. Nothing on your media server is affected.',
'startup.repairBodySessionsUncertain' => 'Trackers (MAL, AniList, Simkl, Trakt) and Seerr are stored separately and may or may not survive. Plezy will tell you exactly what it kept.',
'startup.repairConfirm' => 'Repair',
'startup.repairSucceeded' => 'Storage repaired',
'startup.repairNeedsRestart' => 'Storage repaired — restart required',
'startup.restartRequiredBody' => 'Your data was repaired, but Plezy has to start fresh before it can use it. Close Plezy and open it again.',
'startup.quitPlezy' => 'Quit Plezy',
'startup.repairFailed' => 'Repair failed',
'startup.repairKeptSignIns' => 'Your servers and profiles are still signed in.',
'startup.repairLostSignIns' => 'The key protecting your saved sign-ins could not be recovered. You will have to sign in to every server and profile again.',
'startup.repairLostSessions' => 'At least one tracker or Seerr connection was lost and has to be reconnected.',
'startup.backupTitle' => 'A copy of the damaged file was kept',
'startup.backupWarning' => 'It contains your sign-in credentials. Do not upload or share it.',
'startup.deleteBackup' => 'Delete copy',
'startup.backupDeleted' => 'Copy deleted.',
'startup.previousFailureTitle' => 'Plezy failed to start last time',
'licenses.relatedPackages' => 'Related Packages',
'licenses.license' => 'License',
'licenses.licenseNumber' => ({required Object number}) => 'License ${number}',
@@ -6907,6 +7060,8 @@ extension on Translations {
'explore.stats.dropped' => ({required Object n}) => '${n} dropped',
'explore.season.winter' => 'Winter',
'explore.season.spring' => 'Spring',
_ => null,
} ?? switch (path) {
'explore.season.summer' => 'Summer',
'explore.season.fall' => 'Fall',
'explore.season.withYear' => ({required Object season, required Object year}) => '${season} ${year}',
@@ -6932,17 +7087,15 @@ extension on Translations {
'explore.creditRole.producer' => 'Producer',
'explore.creditRole.creator' => 'Creator',
'explore.creditRole.composer' => 'Composer',
'explore.ratingSource.critic' => 'Critics',
'explore.ratingSource.audience' => 'Audience',
'explore.ratingSource.imdb' => 'IMDb',
'explore.ratingSource.tmdb' => 'TMDB',
'explore.ratingSource.rottenTomatoes' => 'Rotten Tomatoes',
'explore.ratingSource.simkl' => 'Simkl',
'explore.ratingSource.mal' => 'MyAnimeList',
'explore.ratingSource.anilist' => 'AniList',
'explore.ratingSource.trakt' => 'Trakt',
'explore.ratingSource.rottenTomatoesCritic' => 'Rotten Tomatoes critics',
'explore.ratingSource.rottenTomatoesAudience' => 'Rotten Tomatoes audience',
'explore.relation.prequel' => 'Prequel',
'explore.relation.sequel' => 'Sequel',
'explore.relation.sideStory' => 'Side story',
'explore.relation.spinOff' => 'Spin-off',
'explore.relation.alternativeVersion' => 'Alternative version',
'explore.relation.summary' => 'Summary',
'explore.relation.parentStory' => 'Parent story',
'explore.relation.adaptation' => 'Adaptation',
'explore.relation.other' => 'Related',
'explore.broadcast' => ({required Object day, required Object time}) => 'Airs ${day} at ${time}',
'explore.broadcastWithZone' => ({required Object day, required Object time, required Object timezone}) => 'Airs ${day} at ${time} ${timezone}',
'explore.detail.originalTitle' => 'Original title',
@@ -6951,8 +7104,6 @@ extension on Translations {
'explore.detail.country' => 'Country',
'explore.detail.language' => 'Language',
'explore.detail.released' => 'Released',
_ => null,
} ?? switch (path) {
'explore.detail.physicalRelease' => 'On disc',
'explore.detail.ended' => 'Ended',
'explore.detail.addedOn' => ({required Object date}) => 'Added ${date}',
@@ -6977,15 +7128,6 @@ extension on Translations {
'explore.detail.relatedTitles' => 'Related titles',
'explore.detail.background' => 'Background',
'explore.totalResults' => ({required num n}) => (_root.$meta.cardinalResolver ?? PluralResolvers.cardinal('en'))(n, one: '${n} result', other: '${n} results', ),
'explore.relation.prequel' => 'Prequel',
'explore.relation.sequel' => 'Sequel',
'explore.relation.sideStory' => 'Side story',
'explore.relation.spinOff' => 'Spin-off',
'explore.relation.alternativeVersion' => 'Alternative version',
'explore.relation.summary' => 'Summary',
'explore.relation.parentStory' => 'Parent story',
'explore.relation.adaptation' => 'Adaptation',
'explore.relation.other' => 'Related',
'liveTv.title' => 'Live TV',
'liveTv.guide' => 'Guide',
'liveTv.noChannels' => 'No channels available',
@@ -7432,6 +7574,8 @@ extension on Translations {
'externalPlayer.playerUrlScheme' => 'URL Scheme',
'externalPlayer.off' => 'Off',
'externalPlayer.launchFailed' => 'Failed to open external player',
_ => null,
} ?? switch (path) {
'externalPlayer.appNotInstalled' => ({required Object name}) => '${name} is not installed',
'externalPlayer.playInExternalPlayer' => 'Play in External Player',
'metadataEdit.editMetadata' => 'Edit...',
@@ -7465,8 +7609,6 @@ extension on Translations {
'metadataEdit.artworkUpdateFailed' => 'Failed to update artwork',
'metadataEdit.noArtworkAvailable' => 'No artwork available',
'metadataEdit.artworkOption' => ({required Object index}) => 'Artwork option ${index}',
_ => null,
} ?? switch (path) {
'metadataEdit.selectedArtworkOption' => ({required Object index}) => 'Artwork option ${index}, selected',
'metadataEdit.notSet' => 'Not set',
'metadataEdit.libraryDefault' => 'Library default',
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Laddar...",
"fullscreen": "Helskärm",
"exitFullscreen": "Avsluta helskärm",
"pressBackAgainToExit": "Tryck bakåt igen för att avsluta"
"pressBackAgainToExit": "Tryck bakåt igen för att avsluta",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Licenser",
@@ -585,6 +598,7 @@
"pauseButton": "Pausa",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Visa uppspelningskontroller",
"hidePlaybackControls": "Dölj uppspelningskontroller",
"seekBackwardButton": "Spola bakåt ${seconds} sekunder",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Byter till kompatibel spelare...",
"serverLimitTitle": "Uppspelningen misslyckades",
"serverLimitBody": "Serverfel (HTTP 500). En bandbredds-/transkodningsgräns avvisade troligen sessionen. Be ägaren justera den.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Loggarna har laddats upp",
"logsUploadFailed": "Det gick inte att ladda upp loggarna",
"logId": "Logg-ID"
@@ -969,6 +985,38 @@
"copyLogs": "Kopiera loggar",
"uploadLogs": "Ladda upp loggar"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Relaterade paket",
"license": "Licens",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Yükleniyor...",
"fullscreen": "Tam Ekran",
"exitFullscreen": "Tam Ekrandan Çık",
"pressBackAgainToExit": "Çıkmak için tekrar geri tuşuna basın"
"pressBackAgainToExit": "Çıkmak için tekrar geri tuşuna basın",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Lisanslar",
@@ -585,6 +598,7 @@
"pauseButton": "Duraklat",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Oynatma kontrollerini göster",
"hidePlaybackControls": "Oynatma kontrollerini gizle",
"seekBackwardButton": "${seconds} saniye geri sar",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Uyumlu oynatıcıya geçiliyor...",
"serverLimitTitle": "Oynatma başarısız oldu",
"serverLimitBody": "Sunucu hatası (HTTP 500). Muhtemelen bir bant genişliği/kod dönüştürme sınırı bu oturumu reddetti. Sunucu sahibinden bunu ayarlamasını isteyin.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Günlükler yüklendi",
"logsUploadFailed": "Günlükler yüklenemedi",
"logId": "Günlük Kimliği (ID)"
@@ -969,6 +985,38 @@
"copyLogs": "Günlükleri Kopyala",
"uploadLogs": "Günlükleri Yükle"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "İlgili Paketler",
"license": "Lisans",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "Yuklanmoqda...",
"fullscreen": "Toʻliq ekran",
"exitFullscreen": "Toʻliq ekrandan chiqish",
"pressBackAgainToExit": "Chiqish uchun orqaga tugmasini yana bir bor bosing"
"pressBackAgainToExit": "Chiqish uchun orqaga tugmasini yana bir bor bosing",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "Litsenziyalar",
@@ -585,6 +598,7 @@
"pauseButton": "Pauza",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "Boshqaruv tugmalarini koʻrsatish",
"hidePlaybackControls": "Boshqaruv tugmalarini yashirish",
"seekBackwardButton": "${seconds} soniya orqaga oʻtkazish",
@@ -695,6 +709,8 @@
"switchingToCompatiblePlayer": "Mos keluvchi pleyerga oʻtilmoqda...",
"serverLimitTitle": "Ijro etishda xatolik",
"serverLimitBody": "Server xatoligi (HTTP 500). Cheklov ushbu seansni rad etdi.",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "Jurnallar yuklandi",
"logsUploadFailed": "Jurnallarni yuklab boʻlmadi",
"logId": "Jurnal ID-si"
@@ -969,6 +985,38 @@
"copyLogs": "Jurnallarni nusxalash",
"uploadLogs": "Jurnallarni yuklash"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "Bogʻliq paketlar",
"license": "Litsenziya",
@@ -1103,18 +1151,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1155,17 +1201,6 @@
"totalResults": {
"one": "",
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "載入中…",
"fullscreen": "全螢幕",
"exitFullscreen": "退出全螢幕",
"pressBackAgainToExit": "再按一次返回以退出"
"pressBackAgainToExit": "再按一次返回以退出",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "授權條款",
@@ -585,6 +598,7 @@
"pauseButton": "暫停",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "顯示播放控制項",
"hidePlaybackControls": "隱藏播放控制項",
"seekBackwardButton": "後退 ${seconds} 秒",
@@ -694,6 +708,8 @@
"switchingToCompatiblePlayer": "正在切換至相容的播放器…",
"serverLimitTitle": "播放失敗",
"serverLimitBody": "伺服器錯誤(HTTP 500)。伺服器的頻寬或轉碼限制可能拒絕此播放要求。請聯絡伺服器擁有者調整設定。",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "日誌已上傳",
"logsUploadFailed": "上傳日誌失敗",
"logId": "日誌 ID"
@@ -968,6 +984,38 @@
"copyLogs": "複製日誌",
"uploadLogs": "上傳日誌"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "相關套件",
"license": "授權",
@@ -1100,18 +1148,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1150,17 +1196,6 @@
},
"totalResults": {
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+59 -24
View File
@@ -64,7 +64,20 @@
"loading": "加载中…",
"fullscreen": "全屏",
"exitFullscreen": "退出全屏",
"pressBackAgainToExit": "再按一次返回键退出"
"pressBackAgainToExit": "再按一次返回键退出",
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
}
},
"screens": {
"licenses": "许可证",
@@ -585,6 +598,7 @@
"pauseButton": "暂停",
"playbackPaused": "",
"playbackResumed": "",
"loadingVideo": "",
"showPlaybackControls": "显示播放控制项",
"hidePlaybackControls": "隐藏播放控制项",
"seekBackwardButton": "快退 ${seconds} 秒",
@@ -694,6 +708,8 @@
"switchingToCompatiblePlayer": "正在切换到兼容的播放器…",
"serverLimitTitle": "播放失败",
"serverLimitBody": "服务器错误(HTTP 500)。此次会话可能因带宽或转码限制而被拒绝。请联系服务器所有者调整限制。",
"mediaUnreadableTitle": "",
"mediaUnreadableBody": "",
"logsUploaded": "日志已上传",
"logsUploadFailed": "上传日志失败",
"logId": "日志 ID"
@@ -968,6 +984,38 @@
"copyLogs": "复制日志",
"uploadLogs": "上传日志"
},
"startup": {
"failedTitle": "",
"failedBody": "",
"failedBodyRepairable": "",
"phaseLabel": "",
"showDetails": "",
"hideDetails": "",
"copyDetails": "",
"detailsCopied": "",
"uploadDetails": "",
"repairStorage": "",
"repairTitle": "",
"repairBodyCommon": "",
"repairBodyOneCredential": "",
"repairBodySignInsKept": "",
"repairBodySignInsLost": "",
"repairBodySessionsUncertain": "",
"repairConfirm": "",
"repairSucceeded": "",
"repairNeedsRestart": "",
"restartRequiredBody": "",
"quitPlezy": "",
"repairFailed": "",
"repairKeptSignIns": "",
"repairLostSignIns": "",
"repairLostSessions": "",
"backupTitle": "",
"backupWarning": "",
"deleteBackup": "",
"backupDeleted": "",
"previousFailureTitle": ""
},
"licenses": {
"relatedPackages": "相关软件包",
"license": "许可证",
@@ -1100,18 +1148,16 @@
"creator": "",
"composer": ""
},
"ratingSource": {
"critic": "",
"audience": "",
"imdb": "",
"tmdb": "",
"rottenTomatoes": "",
"simkl": "",
"mal": "",
"anilist": "",
"trakt": "",
"rottenTomatoesCritic": "",
"rottenTomatoesAudience": ""
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
},
"broadcast": "",
"broadcastWithZone": "",
@@ -1150,17 +1196,6 @@
},
"totalResults": {
"other": ""
},
"relation": {
"prequel": "",
"sequel": "",
"sideStory": "",
"spinOff": "",
"alternativeVersion": "",
"summary": "",
"parentStory": "",
"adaptation": "",
"other": ""
}
},
"liveTv": {
+505 -81
View File
@@ -76,7 +76,6 @@ import 'i18n/app_locale_utils.dart';
import 'i18n/strings.g.dart';
import 'widgets/app_icon.dart';
import 'focus/input_mode_tracker.dart';
import 'focus/focusable_button.dart';
import 'focus/key_event_utils.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'utils/navigation_transitions.dart';
@@ -84,6 +83,13 @@ import 'utils/log_redaction_manager.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'utils/android_exit_diagnostics.dart';
import 'utils/storage_failure.dart';
import 'services/base_shared_preferences_service.dart';
import 'services/prefs_recovery.dart';
import 'services/sensitive_prefs.dart';
import 'services/startup_diagnostics.dart';
import 'utils/dialogs.dart';
import 'widgets/dialog_action_button.dart';
import 'widgets/startup_failure_view.dart';
const bool _enableSentry = bool.fromEnvironment('ENABLE_SENTRY', defaultValue: false);
const String _sentryDsn = 'https://6a1a6ef8c72140099b2798973c1bfb2f@bugs.plezy.app/1';
@@ -142,6 +148,9 @@ void _bootstrapApp() {
return const ColoredBox(color: Color(0xFF000000));
};
// Off the critical path: the version label only decorates a diagnostic.
unawaited(_primeDiagnosticsVersion());
AndroidExitDiagnostics.markStartupPhase(AndroidStartupPhase.runApp);
runApp(
StartupBootstrap<_StartupDependencies>(
@@ -160,44 +169,397 @@ void _bootstrapApp() {
);
}
/// Wraps [step] so a failure names the gate phase it came from.
///
/// `Future.wait` keeps only the first error and discards the rest, and the old
/// catch-all reported a bare `error.runtimeType`, so a startup failure could
/// not even be attributed to one of four concurrent steps (#1732).
Future<T> _gatePhase<T>(StartupPhase phase, Future<T> Function() step) async {
try {
return await step();
} catch (error, stackTrace) {
Error.throwWithStackTrace(StartupPhaseException(phase, error), stackTrace);
}
}
/// How long a degradable startup step may block the launch before it is
/// abandoned. Generous next to the sub-second these normally take, but bounded:
/// `windowManager.ensureInitialized()` is a platform-channel round trip and the
/// Windows runner puts the UI on its own thread, so a stalled platform thread
/// would otherwise hold the splash forever with no error to report.
const Duration _optionalPhaseTimeout = Duration(seconds: 10);
/// Runs a startup step that the app can survive without.
///
/// Window chrome, locale selection, crash reporting and the artwork cache are
/// all degradable; before #1732 any one of them could veto the whole boot —
/// by throwing, or by never completing.
Future<void> _optionalGatePhase(
StartupPhase phase,
Future<void> Function() step, {
Duration timeout = _optionalPhaseTimeout,
}) async {
// Keep a handler on the original future. `timeout` abandons the work rather
// than cancelling it, so a late failure would otherwise land as an unhandled
// async error long after the gate moved on.
final work = Future<void>.sync(step).catchError((Object error, StackTrace stackTrace) {
appLogger.w('Optional startup phase "${phase.id}" failed', error: error, stackTrace: stackTrace);
});
try {
await work.timeout(timeout);
} on TimeoutException {
appLogger.w('Optional startup phase "${phase.id}" did not finish in ${timeout.inSeconds}s; continuing without it');
}
}
Future<_StartupDependencies> _initializeApplication() async {
final settings = await SettingsService.getInstance();
final settings = await _gatePhase(StartupPhase.preferences, SettingsService.getInstance);
setLoggerLevel(settings.read(SettingsService.enableDebugLogging));
_StartupDependencies? dependencies;
Future<void> initializeStartup() async {
AndroidExitDiagnostics.markTelemetryReady();
dependencies = await _initializeStartup(settings);
if (_enableSentry) {
// Crash reporting is observability: it must never veto the launch it
// exists to report on. `Sentry.init` runs its integrations eagerly, so an
// integration throwing used to fail the gate before any Plezy code ran.
//
// Deliberately no `appRunner`. On every non-web platform `Sentry.init`
// reduces it to `await appRunner()` after the integrations — error capture
// comes from `OnErrorIntegration`/`PlatformDispatcher.onError`, installed
// during init either way. Passing the startup work in would make a startup
// failure indistinguishable from a Sentry failure, and this guard would
// then run the whole gate — migrations, native recovery, database open —
// a second time.
await _optionalGatePhase(StartupPhase.crashReporting, () async {
await SentryFlutter.init((options) {
options.dsn = _sentryDsn;
options.release = _sentryRelease();
if (_sentryEnvironment.isNotEmpty) options.environment = _sentryEnvironment;
if (_sentryDist.isNotEmpty) options.dist = _sentryDist;
options.tracesSampleRate = 0;
options.attachStacktrace = true;
options.enableAutoSessionTracking = false;
options.recordHttpBreadcrumbs = false;
options.captureNativeFailedRequests = false;
options.enableAppHangTracking = !kDebugMode;
options.appHangTimeoutInterval = const Duration(seconds: 3);
options.beforeSend = _beforeSend;
options.beforeBreadcrumb = _beforeBreadcrumb;
});
// Only reached when init really completed; the phase above swallows a
// failure or a timeout and would otherwise leave a no-op hub that
// accepts events and drops them.
_crashReporterReady = true;
});
}
if (_enableSentry) {
final packageInfo = await PackageInfo.fromPlatform();
await SentryFlutter.init((options) {
options.dsn = _sentryDsn;
options.release = gitCommit.isNotEmpty
? 'plezy@${gitCommit.substring(0, 7)}'
: 'plezy@${packageInfo.version}+${packageInfo.buildNumber}';
if (_sentryEnvironment.isNotEmpty) options.environment = _sentryEnvironment;
if (_sentryDist.isNotEmpty) options.dist = _sentryDist;
options.tracesSampleRate = 0;
options.attachStacktrace = true;
options.enableAutoSessionTracking = false;
options.recordHttpBreadcrumbs = false;
options.captureNativeFailedRequests = false;
options.enableAppHangTracking = !kDebugMode;
options.appHangTimeoutInterval = const Duration(seconds: 3);
options.beforeSend = _beforeSend;
options.beforeBreadcrumb = _beforeBreadcrumb;
}, appRunner: initializeStartup);
} else {
await initializeStartup();
}
return dependencies!;
// Registered rather than awaited: sending must not sit on the critical path,
// but it must finish before the success path consumes the record off disk.
// Runs even without Sentry so a build that can never report still resolves
// the record instead of carrying it forever.
StartupDiagnosticsStore.holdForFlush(flushPendingStartupFailure());
AndroidExitDiagnostics.markTelemetryReady();
return _initializeStartup(settings);
}
/// Release identifier for Sentry.
///
/// `PackageInfo.fromPlatform()` reads the executable's Win32 version resource
/// and throws `WindowsException`/`ArgumentError` when that read fails (UNC
/// launch, antivirus interception). Official builds always define
/// `GIT_COMMIT`, so resolve that first and only pay the platform read — inside
/// a guard — when there is no commit to use.
String _sentryRelease() {
if (gitCommit.length >= 7) return 'plezy@${gitCommit.substring(0, 7)}';
if (gitCommit.isNotEmpty) return 'plezy@$gitCommit';
return 'plezy@unknown';
}
const startupBootstrapProgressKey = Key('startup-bootstrap-progress');
const startupBootstrapFailureKey = Key('startup-bootstrap-failure');
const startupBootstrapRetryKey = Key('startup-bootstrap-retry');
/// Human-readable build label for a failure record, primed off the critical
/// path by [_primeDiagnosticsVersion].
String _diagnosticsVersion = gitCommit.isEmpty ? 'unknown' : gitCommit.substring(0, gitCommit.length.clamp(0, 7));
/// Resolves the package version for diagnostics without putting it in the gate.
///
/// `PackageInfo.fromPlatform()` reads the executable's Win32 version resource
/// and throws `WindowsException`/`ArgumentError` when that read fails (a UNC
/// launch, antivirus interception). It used to run inside the startup gate for
/// a value only Sentry consumed; here a failure just leaves the commit label.
Future<void> _primeDiagnosticsVersion() async {
try {
final info = await PackageInfo.fromPlatform();
final commit = gitCommit.isEmpty ? '' : ' (${gitCommit.substring(0, gitCommit.length.clamp(0, 7))})';
_diagnosticsVersion = '${info.version}+${info.buildNumber}$commit';
} catch (error, stackTrace) {
appLogger.d('Could not resolve the package version for diagnostics', error: error, stackTrace: stackTrace);
}
}
/// Platform label for a failure record. Deliberately coarse — enough to
/// triage a report, never enough to identify a machine.
String _diagnosticsPlatform() => '${Platform.operatingSystem} ${Platform.operatingSystemVersion}';
/// Whether an in-app repair can address [error].
///
/// Only preference-store damage qualifies. Everything else — a denied
/// directory, a locked database, a native library that will not load — needs
/// the environment to change, and offering a destructive repair for it would
/// be worse than offering nothing.
bool _isRepairable(Object error) {
final cause = StartupPhaseException.unwrap(error);
return cause is CorruptPreferenceStoreException || cause is UnreadableSensitivePreferenceException;
}
/// Default [StartupBootstrap.describeFailure].
@visibleForTesting
StartupFailureRecord describeStartupFailure(Object error, StackTrace stackTrace) => StartupFailureRecord.fromError(
error: error,
stackTrace: stackTrace,
appVersion: _diagnosticsVersion,
platform: _diagnosticsPlatform(),
repairable: _isRepairable(error),
);
/// Whether `SentryFlutter.init` actually completed this launch.
///
/// The crash-reporting phase is best-effort, so init can fail or time out and
/// leave a no-op hub behind. A no-op hub accepts `captureMessage` and returns
/// an empty id *without throwing*, so "the send did not throw" is not evidence
/// that anything was sent.
var _crashReporterReady = false;
@visibleForTesting
void debugSetCrashReporterReady(bool ready) => _crashReporterReady = ready;
/// Sends a persisted startup failure to the crash reporter, once.
///
/// Reporting cannot happen where the failure is caught. The gate opens
/// preferences — the likeliest thing to fail, and the whole reason #1732 has
/// no telemetry — before crash reporting exists, so a capture there goes to a
/// no-op hub and is silently dropped. Initialising the reporter first is not
/// an option either: `_beforeSend` reads the crash-reporting opt-out from
/// settings, which are not loaded yet, so early events would bypass a user's
/// choice.
///
/// So every failure is persisted first and flushed here, immediately after
/// the reporter comes up with settings loaded. In practice that is the user's
/// own retry, seconds later, in the same process.
///
/// The record is only marked reported on proof of delivery — a non-empty
/// Sentry id — or when the user has opted out, which is a deliberate
/// suppression rather than a failure to retry. Anything else leaves it
/// pending for the next launch.
@visibleForTesting
Future<void> flushPendingStartupFailure({
Future<SentryId> Function(StartupFailureRecord record)? send,
bool? reporterReady,
bool? crashReportingEnabled,
bool? reportingCompiledIn,
}) async {
final record = await StartupDiagnosticsStore.peekPersisted();
if (record == null || record.reported) return;
final optedIn = crashReportingEnabled ?? SettingsService.instanceOrNull?.read(SettingsService.crashReporting) ?? true;
final canEverReport = reportingCompiledIn ?? _enableSentry;
if (!optedIn || !canEverReport) {
// Deliberate suppression, not a delivery failure. Marking it reported is
// what lets `consumePrevious` eventually drop the file; without this a
// fork build with no DSN, or an opted-out user, would carry the record
// forever.
appLogger.d(
optedIn
? 'Startup failure not reported: crash reporting is not available in this build'
: 'Startup failure not reported: crash reporting is disabled',
);
await StartupDiagnosticsStore.markReported(record);
return;
}
if (!(reporterReady ?? _crashReporterReady)) {
// Kept on disk deliberately: `consumePrevious` retains an unreported
// record so the next launch can try again.
appLogger.d('Startup failure kept for the next launch: crash reporting is not initialised');
return;
}
try {
final id = await (send ?? _captureStartupFailure)(record);
if (id == const SentryId.empty()) {
// A no-op hub, a disabled client, or an event dropped in `beforeSend`.
appLogger.d('Startup failure was not accepted by the crash reporter; keeping it for the next launch');
return;
}
await StartupDiagnosticsStore.markReported(record);
} catch (error, stackTrace) {
// Leave it unreported so the next launch tries again.
appLogger.d('Could not report the startup failure', error: error, stackTrace: stackTrace);
}
}
Future<SentryId> _captureStartupFailure(StartupFailureRecord record) {
// The original error object is long gone by now; the record is the
// allowlisted, already-redacted rendering of it.
return Sentry.captureMessage(
'Startup failed: ${record.headline}',
level: SentryLevel.fatal,
withScope: (scope) {
scope.setTag('startup.phase', record.phaseId);
scope.setContexts('startup', {
'phase': record.phaseId,
'errorType': record.errorType,
'repairable': record.repairable,
'when': record.timestamp.toUtc().toIso8601String(),
'stackTrace': ?record.stackTrace,
});
},
);
}
/// Default [StartupBootstrap.repair]: states the cost, runs the repair that
/// matches the failure, then reports what was kept and what was lost.
///
/// The result tells the bootstrap what it may do next; see
/// [StartupRepairResult]. Never returns [StartupRepairResult.retry] for a
/// repair that requires a restart — re-running initialization in that state
/// would destroy the salvage.
@visibleForTesting
Future<StartupRepairResult> repairStartupStorage(
BuildContext context,
StartupFailureRecord record,
Object error,
) async {
final cause = StartupPhaseException.unwrap(error);
final unreadableKey = cause is UnreadableSensitivePreferenceException ? cause.key : null;
final reopenSafe = cause is! CorruptPreferenceStoreException || cause.reopenSafe;
// Name the real cost before touching anything, not the usual one. Servers
// and profiles survive a repair only because their tokens are ciphertext in
// the database and the key that decrypts them lives in the store — so a
// store the key cannot be read out of signs the user out of everything. An
// all-zero file is exactly that case (#1732), and telling them their
// sign-ins are safe would be a promise the outcome dialog then contradicts.
final signInsSurvive = unreadableKey != null
? unreadableKey != credentialVaultKeyPref
: (await PrefsRecovery.previewSalvage()).vaultKey != null;
if (!context.mounted) return StartupRepairResult.none;
final confirmed = await showConfirmDialog(
context,
title: t.startup.repairTitle,
message: repairConsentMessage(oneCredential: unreadableKey != null, signInsSurvive: signInsSurvive),
confirmText: t.startup.repairConfirm,
isDestructive: true,
);
if (!confirmed || !context.mounted) return StartupRepairResult.none;
final outcome = unreadableKey != null
? await BaseSharedPreferencesService.dropUnreadableCredential(unreadableKey)
: await BaseSharedPreferencesService.repairCorruptStore(reopenSafe: reopenSafe);
final result = outcome.requiresRestart ? StartupRepairResult.restart : StartupRepairResult.retry;
if (!context.mounted) return result;
await showRepairOutcomeDialog(context, outcome);
return result;
}
/// The consent dialog's body: what is being repaired, then what it costs.
///
/// Separated from [repairStartupStorage] because the two halves fail
/// differently. Deciding whether the sign-ins survive is I/O against a
/// damaged file; deciding what to *tell* the user about it is a promise, and
/// #1732 is what happens when the promise is written once, optimistically,
/// for a case that does not always hold.
///
/// [signInsSurvive] covers servers and profiles only. Their tokens are
/// ciphertext in the database, so they live or die with the vault key —
/// which is exactly why that one value decides this sentence.
///
/// Tracker and Seerr sessions are plaintext preference entries, salvaged and
/// reseeded one by one and untouched entirely by the single-credential
/// repair. They therefore do not follow the vault key in either direction,
/// and get one cautious sentence in both branches rather than a promise
/// borrowed from a value that does not govern them.
@visibleForTesting
String repairConsentMessage({required bool oneCredential, required bool signInsSurvive}) => [
oneCredential ? t.startup.repairBodyOneCredential : t.startup.repairBodyCommon,
signInsSurvive ? t.startup.repairBodySignInsKept : t.startup.repairBodySignInsLost,
t.startup.repairBodySessionsUncertain,
].join('\n\n');
/// Reports a completed repair, including the retained copy of the damaged
/// store.
///
/// The backup path is shown so the user can find and delete it, never so it
/// can be attached to a report: it can hold the credential-vault key, tracker
/// refresh tokens and Seerr cookies in plaintext. The warning is suppressed
/// only when the quarantined *bytes* prove there is nothing in them — an
/// all-zero file (#1732) — never on the strength of what the salvage managed
/// to recover, which says nothing about what is still in the file. A warning
/// on a file of zeros is the one that teaches users to ignore the warning
/// that matters.
@visibleForTesting
Future<void> showRepairOutcomeDialog(
BuildContext context,
PrefsRepairOutcome outcome, {
// Test seam: the widget-test binding's fake-async zone never completes a
// `dart:io` future, so a real delete cannot be driven from a widget test.
Future<void> Function(String path) deleteBackup = PrefsRecovery.deleteBackup,
}) {
final backupPath = outcome.backupPath;
// Outside the builder: a `StatefulBuilder` re-runs its closure on every
// rebuild, so state declared inside it would reset the moment the rebuild it
// triggered arrives — leaving the sensitive path on screen after deletion.
var deleted = false;
return showScopedDialog<void>(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (dialogContext, setDialogState) {
return AlertDialog(
title: Text(outcome.requiresRestart ? t.startup.repairNeedsRestart : t.startup.repairSucceeded),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(outcome.vaultKeySalvaged ? t.startup.repairKeptSignIns : t.startup.repairLostSignIns),
if (outcome.sessionsAffected) ...[const SizedBox(height: 8), Text(t.startup.repairLostSessions)],
if (backupPath != null && !deleted) ...[
const SizedBox(height: 16),
Text(t.startup.backupTitle, style: Theme.of(dialogContext).textTheme.titleSmall),
const SizedBox(height: 4),
SelectableText(backupPath, style: const TextStyle(fontFamily: 'monospace', fontSize: 12)),
if (outcome.backupHoldsCredentials) ...[
const SizedBox(height: 4),
Text(t.startup.backupWarning, style: TextStyle(color: Theme.of(dialogContext).colorScheme.error)),
],
const SizedBox(height: 8),
DialogActionButton(
label: t.startup.deleteBackup,
onPressed: () async {
await deleteBackup(backupPath);
// The barrier can dismiss this dialog while the delete is
// in flight; the file is gone either way.
if (!dialogContext.mounted) return;
setDialogState(() => deleted = true);
},
),
],
if (deleted) ...[const SizedBox(height: 8), Text(t.startup.backupDeleted)],
],
),
actions: [
DialogActionButton(
autofocus: true,
isPrimary: true,
onPressed: () => Navigator.of(dialogContext).pop(),
label: t.common.close,
),
],
);
},
),
);
}
/// Mounts a Flutter-owned startup frame before invoking the asynchronous
/// initialization gate. The generic seam keeps frame ordering, failure, and
@@ -210,6 +572,8 @@ class StartupBootstrap<T> extends StatefulWidget {
required this.buildApp,
this.discard,
this.onCommitted,
this.describeFailure = describeStartupFailure,
this.repair = repairStartupStorage,
this.lightTheme,
this.darkTheme,
this.themeMode = material.ThemeMode.system,
@@ -219,6 +583,17 @@ class StartupBootstrap<T> extends StatefulWidget {
final Widget Function(BuildContext context, T value) buildApp;
final FutureOr<void> Function(T value)? discard;
final FutureOr<void> Function(T value)? onCommitted;
/// Reduces a thrown error to the allowlisted record the failure screen,
/// the persisted diagnostic and the crash report all share.
final StartupFailureRecord Function(Object error, StackTrace stackTrace) describeFailure;
/// Offers the user a consented repair for a recoverable failure and reports
/// what the gate may do next. [StartupRepairResult.retry] re-runs
/// [initialize]; [StartupRepairResult.restart] parks the app on the failure
/// screen, because nothing may touch preferences until the process restarts.
final Future<StartupRepairResult> Function(BuildContext context, StartupFailureRecord record, Object error)? repair;
final ThemeData? lightTheme;
final ThemeData? darkTheme;
final material.ThemeMode themeMode;
@@ -229,9 +604,19 @@ class StartupBootstrap<T> extends StatefulWidget {
class _StartupBootstrapState<T> extends State<StartupBootstrap<T>> {
T? _value;
Object? _error;
StartupFailureRecord? _failure;
/// Retained alongside [_failure] so the repair hook can classify the real
/// cause; the record is a redacted allowlist and deliberately cannot.
Object? _failureError;
bool _completed = false;
bool _initializing = false;
bool _repairing = false;
/// Terminal: the store was repaired but the plugin still holds the bad
/// document, so this process can never open it. Latched, never cleared —
/// re-running the gate from here would flush the stale map over the seed.
bool _restartRequired = false;
int _generation = 0;
@override
@@ -248,7 +633,7 @@ class _StartupBootstrapState<T> extends State<StartupBootstrap<T>> {
final generation = ++_generation;
setState(() {
_error = null;
_failure = null;
_initializing = true;
});
@@ -264,17 +649,55 @@ class _StartupBootstrapState<T> extends State<StartupBootstrap<T>> {
_completed = true;
_initializing = false;
});
// A launch that got through is the first chance to surface a record
// written by one that did not. Consuming it takes the file off disk and
// holds the contents in memory for Settings › Logs, so the user can
// upload the failure that had no other way out (#1732).
unawaited(StartupDiagnosticsStore.consumePrevious());
unawaited(Future.sync(() => widget.onCommitted?.call(value)));
} catch (error, stackTrace) {
final failure = widget.describeFailure(error, stackTrace);
// `headline` is the sanitised rendering; the raw error is deliberately
// not passed, because `FormatException.toString()` embeds an excerpt of
// whatever document failed to parse.
appLogger.e('Startup initialization failed: ${failure.headline}', stackTrace: stackTrace);
// Persist first: this record is the only thing that survives the
// process. On Windows there is no log file and no console for a
// double-clicked release build.
unawaited(StartupDiagnosticsStore.record(failure));
// Not reported from here: the earliest phases run before the crash
// reporter exists, so the record is persisted and flushed by
// `flushPendingStartupFailure` once it is up — on the retry below, or on
// the next launch.
if (!mounted || generation != _generation) return;
appLogger.e('Startup initialization failed (${error.runtimeType})', stackTrace: stackTrace);
setState(() {
_error = error;
_failure = failure;
_failureError = error;
_initializing = false;
});
}
}
Future<void> _repair(StartupFailureRecord failure) async {
final repair = widget.repair;
final error = _failureError;
if (repair == null || error == null || _repairing || _restartRequired) return;
setState(() => _repairing = true);
var result = StartupRepairResult.none;
try {
result = await repair(context, failure, error);
} catch (error, stackTrace) {
appLogger.e('Startup storage repair failed', error: error, stackTrace: stackTrace);
if (mounted) showErrorSnackBar(context, t.startup.repairFailed);
}
if (!mounted) return;
setState(() {
_repairing = false;
if (result == StartupRepairResult.restart) _restartRequired = true;
});
if (result == StartupRepairResult.retry) unawaited(_initialize());
}
Future<void> _discard(T value) async {
try {
await widget.discard?.call(value);
@@ -309,30 +732,17 @@ class _StartupBootstrapState<T> extends State<StartupBootstrap<T>> {
}
Widget _buildBootstrapHome(BuildContext context) {
final failure = _failure;
return Scaffold(
body: Center(
child: _error == null
? const CircularProgressIndicator(key: startupBootstrapProgressKey)
: Column(
key: startupBootstrapFailureKey,
mainAxisSize: MainAxisSize.min,
children: [
const AppIcon(Symbols.error_rounded, size: 48),
const SizedBox(height: 16),
Text(t.common.error, style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 16),
FocusableButton(
autofocus: true,
onPressed: _initializing ? null : () => unawaited(_initialize()),
child: FilledButton(
key: startupBootstrapRetryKey,
onPressed: _initializing ? null : () => unawaited(_initialize()),
child: Text(t.common.retry),
),
),
],
),
),
body: failure == null
? const Center(child: CircularProgressIndicator(key: startupBootstrapProgressKey))
: StartupFailureView(
failure: failure,
busy: _initializing || _repairing,
restartRequired: _restartRequired,
onRetry: () => unawaited(_initialize()),
onRepair: failure.repairable && widget.repair != null ? () => _repair(failure) : null,
),
);
}
}
@@ -394,45 +804,58 @@ Future<_StartupDependencies> _initializeStartup(SettingsService settings) async
AppDatabase? openedDatabase;
try {
final savedLocale = settings.read(SettingsService.appLocale);
await LocaleSettings.setLocale(savedLocale);
await initializeDateFormatting(savedLocale.intlLocaleName, null);
// Slang builds the base locale eagerly, so `t` already resolves before
// this runs; a failure here degrades to English rather than no app.
await _optionalGatePhase(StartupPhase.locale, () async {
final savedLocale = settings.read(SettingsService.appLocale);
await LocaleSettings.setLocale(savedLocale);
await initializeDateFormatting(savedLocale.intlLocaleName, null);
});
markStartupPhase('locale');
final futures = <Future<void>>[];
// Window chrome is cosmetic; losing it costs the custom titlebar and the
// remembered size, not the app. It is also the step most exposed to a
// stalled platform thread, so it must not sit in the same combined future
// as the services the first build genuinely needs.
if (PlatformDetector.isDesktopOS()) {
if (Platform.isMacOS) {
futures.add(windowManager.ensureInitialized().then((_) => MacOSWindowService.setupCustomTitlebar()));
} else {
futures.add(windowManager.ensureInitialized());
}
await _optionalGatePhase(StartupPhase.windowManager, () async {
await windowManager.ensureInitialized();
if (Platform.isMacOS) await MacOSWindowService.setupCustomTitlebar();
});
}
// MainApp reads both synchronous facades during its first build.
futures.add(TvDetectionService.getInstance(forceTv: settings.read(SettingsService.forceTvMode)));
futures.add(DevicePerformance.getInstance(override: settings.read(SettingsService.visualEffects)));
// MainApp reads both synchronous facades during its first build, and both
// have a working sync fallback, so a detection failure is not fatal.
await _optionalGatePhase(StartupPhase.deviceCapabilities, () async {
await (
TvDetectionService.getInstance(forceTv: settings.read(SettingsService.forceTvMode)),
DevicePerformance.getInstance(override: settings.read(SettingsService.visualEffects)),
).wait;
});
final storageFuture = StorageService.getInstance();
futures.add(storageFuture);
await Future.wait(futures);
final storage = await storageFuture;
final storage = await _gatePhase(StartupPhase.storage, StorageService.getInstance);
markStartupPhase('platform-services');
AndroidExitDiagnostics.markStartupPhase(AndroidStartupPhase.databaseOpenStarted);
final databaseBootstrap = await openAppDatabaseWithDownloadRecovery(
openDatabase: () => AppDatabase.open(isTvos: PlatformDetector.isAppleTV()),
recoverNativeDownloads: DownloadManagerService.discardInterruptedNativeDownloadsAfterStorageFailure,
storageFullMessage: t.downloads.storageFull,
final databaseBootstrap = await _gatePhase(
StartupPhase.database,
() => openAppDatabaseWithDownloadRecovery(
openDatabase: () => AppDatabase.open(isTvos: PlatformDetector.isAppleTV()),
recoverNativeDownloads: DownloadManagerService.discardInterruptedNativeDownloadsAfterStorageFailure,
storageFullMessage: t.downloads.storageFull,
),
);
openedDatabase = databaseBootstrap.database;
AndroidExitDiagnostics.markStartupPhase(AndroidStartupPhase.databaseReady);
markStartupPhase('database-recovery');
DevicePerformance.applyImageCacheBudget();
await _optionalGatePhase(StartupPhase.imageCache, () async => DevicePerformance.applyImageCacheBudget());
// DownloadManagerService reads this singleton synchronously in MainApp's
// initState, so its recoverable storage check remains in the explicit gate.
await DownloadStorageService.instance.initialize(settings);
// initState, but `getArtworkPathSync` already models "not ready" by
// returning null and the path re-resolves lazily, so offline artwork is
// not a launch requirement.
await _optionalGatePhase(StartupPhase.downloadStorage, () => DownloadStorageService.instance.initialize(settings));
markStartupPhase('download-storage');
return _StartupDependencies(
@@ -1049,6 +1472,7 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
registry: context.read<ProfileRegistry>(),
plexHome: context.read<PlexHomeService>(),
connections: context.read<ConnectionRegistry>(),
profileConnections: context.read<ProfileConnectionRegistry>(),
storage: context.read<StorageService>(),
);
unawaited(provider.initialize());
+23 -3
View File
@@ -10,6 +10,7 @@ import 'media_backend.dart';
import 'media_kind.dart';
import 'media_role.dart';
import 'media_version.dart';
import 'media_rating.dart';
part 'media_item.freezed.dart';
part 'media_item.g.dart';
@@ -66,6 +67,7 @@ sealed class MediaItem with _$MediaItem {
int? addedAt,
int? updatedAt,
double? rating,
List<MediaRatingSource>? ratings,
double? userRating,
bool? isFavorite,
List<String>? genres,
@@ -128,6 +130,7 @@ sealed class MediaItem with _$MediaItem {
addedAt: addedAt,
updatedAt: updatedAt,
rating: rating,
ratings: ratings,
userRating: userRating,
isFavorite: isFavorite,
genres: genres,
@@ -189,6 +192,7 @@ sealed class MediaItem with _$MediaItem {
addedAt: addedAt,
updatedAt: updatedAt,
rating: rating,
ratings: ratings,
userRating: userRating,
isFavorite: isFavorite,
genres: genres,
@@ -257,11 +261,14 @@ sealed class MediaItem with _$MediaItem {
@JsonKey(fromJson: flexibleInt) int? addedAt,
@JsonKey(fromJson: flexibleInt) int? updatedAt,
@JsonKey(fromJson: flexibleDouble) double? rating,
@JsonKey(fromJson: flexibleDouble) double? audienceRating,
@JsonKey(fromJson: flexibleDouble) double? userRating,
/// Every attributed score the response carried, headline first. Plex
/// listings yield one or two (the `rating`/`audienceRating` pair with
/// their source images); `/library/metadata/{id}` adds the `Rating[]`
/// array, so IMDb and TMDB join Rotten Tomatoes on detail screens.
@JsonKey(fromJson: _mediaItemRatingsFromJson) List<MediaRatingSource>? ratings,
bool? isFavorite,
String? ratingImage,
String? audienceRatingImage,
@JsonKey(fromJson: _mediaItemStringList) List<String>? genres,
@JsonKey(fromJson: _mediaItemStringList) List<String>? directors,
@JsonKey(fromJson: _mediaItemStringList) List<String>? writers,
@@ -335,6 +342,10 @@ sealed class MediaItem with _$MediaItem {
@JsonKey(fromJson: flexibleInt) int? updatedAt,
@JsonKey(fromJson: flexibleDouble) double? rating,
@JsonKey(fromJson: flexibleDouble) double? userRating,
/// `CommunityRating` and the `CriticRating` Tomatometer, in that order.
/// Jellyfin exposes no per-source array, so this is at most two entries.
@JsonKey(fromJson: _mediaItemRatingsFromJson) List<MediaRatingSource>? ratings,
bool? isFavorite,
@JsonKey(fromJson: _mediaItemStringList) List<String>? genres,
@JsonKey(fromJson: _mediaItemStringList) List<String>? directors,
@@ -749,4 +760,13 @@ List<MediaVersion>? _mediaItemVersionsFromJson(Object? raw) {
: null;
}
List<MediaRatingSource>? _mediaItemRatingsFromJson(Object? raw) {
return raw is List
? [
for (final rating in raw)
if (rating is Map<String, Object?>) ?MediaRatingSource.fromJson(rating),
]
: null;
}
Map<String, Object?>? _mediaItemRawFromJson(Object? raw) => raw is Map ? Map<String, Object?>.from(raw) : null;
File diff suppressed because one or more lines are too long
+4 -6
View File
@@ -51,11 +51,9 @@ PlexMediaItem _$PlexMediaItemFromJson(Map<String, dynamic> json) =>
addedAt: flexibleInt(json['addedAt']),
updatedAt: flexibleInt(json['updatedAt']),
rating: flexibleDouble(json['rating']),
audienceRating: flexibleDouble(json['audienceRating']),
userRating: flexibleDouble(json['userRating']),
ratings: _mediaItemRatingsFromJson(json['ratings']),
isFavorite: json['isFavorite'] as bool?,
ratingImage: json['ratingImage'] as String?,
audienceRatingImage: json['audienceRatingImage'] as String?,
genres: _mediaItemStringList(json['genres']),
directors: _mediaItemStringList(json['directors']),
writers: _mediaItemStringList(json['writers']),
@@ -123,11 +121,9 @@ Map<String, dynamic> _$PlexMediaItemToJson(PlexMediaItem instance) =>
'addedAt': ?instance.addedAt,
'updatedAt': ?instance.updatedAt,
'rating': ?instance.rating,
'audienceRating': ?instance.audienceRating,
'userRating': ?instance.userRating,
'ratings': ?instance.ratings?.map((e) => e.toJson()).toList(),
'isFavorite': ?instance.isFavorite,
'ratingImage': ?instance.ratingImage,
'audienceRatingImage': ?instance.audienceRatingImage,
'genres': ?instance.genres,
'directors': ?instance.directors,
'writers': ?instance.writers,
@@ -200,6 +196,7 @@ JellyfinMediaItem _$JellyfinMediaItemFromJson(Map<String, dynamic> json) =>
updatedAt: flexibleInt(json['updatedAt']),
rating: flexibleDouble(json['rating']),
userRating: flexibleDouble(json['userRating']),
ratings: _mediaItemRatingsFromJson(json['ratings']),
isFavorite: json['isFavorite'] as bool?,
genres: _mediaItemStringList(json['genres']),
directors: _mediaItemStringList(json['directors']),
@@ -262,6 +259,7 @@ Map<String, dynamic> _$JellyfinMediaItemToJson(JellyfinMediaItem instance) =>
'updatedAt': ?instance.updatedAt,
'rating': ?instance.rating,
'userRating': ?instance.userRating,
'ratings': ?instance.ratings?.map((e) => e.toJson()).toList(),
'isFavorite': ?instance.isFavorite,
'genres': ?instance.genres,
'directors': ?instance.directors,
+61
View File
@@ -1,5 +1,6 @@
import 'ids.dart';
import 'media_item.dart';
import 'media_version.dart';
/// Merge freshly fetched metadata with identity and library context already
/// known by the caller. The fetched item owns descriptive fields, while
@@ -12,3 +13,63 @@ MediaItem mergeFetchedMediaItem({required MediaItem fetched, required ServerId f
libraryTitle: fetched.libraryTitle ?? existing?.libraryTitle,
);
}
/// Tallest version height an item exposes, or 0 when the backend reported
/// none.
int _bestResolutionHeight(MediaItem item) {
var best = 0;
for (final version in item.mediaVersions ?? const <MediaVersion>[]) {
final height = version.resolutionHeight;
if (height != null && height > best) best = height;
}
return best;
}
/// Order the library copies of one title best-first: highest resolution, then
/// library title, then server name, then global key.
///
/// Total and derived purely from the items, so a chooser can re-sort after
/// merging a later resolution pass without its rows jumping around.
int compareLibraryCopies(MediaItem a, MediaItem b) {
final byResolution = _bestResolutionHeight(b).compareTo(_bestResolutionHeight(a));
if (byResolution != 0) return byResolution;
final byLibrary = (a.libraryTitle ?? '').compareTo(b.libraryTitle ?? '');
if (byLibrary != 0) return byLibrary;
final byServer = (a.serverName ?? '').compareTo(b.serverName ?? '');
if (byServer != 0) return byServer;
return a.globalKey.compareTo(b.globalKey);
}
/// Fold a re-resolved copy into the one already on screen.
///
/// The addition is fresher, but a degraded pass must not erase context. The
/// Jellyfin library stamp is a best-effort `/Items/{id}/Ancestors` call that
/// hands back an unstamped item when it fails, and a copy that lost its
/// library title is indistinguishable from its sibling in the same server's
/// other library — exactly the ambiguity the chooser exists to resolve. The
/// version list behind the resolution hint is treated the same way.
MediaItem _mergeCopy(MediaItem existing, MediaItem addition) {
final versions = addition.mediaVersions;
return addition.copyWith(
libraryId: addition.libraryId ?? existing.libraryId,
libraryTitle: addition.libraryTitle ?? existing.libraryTitle,
serverName: addition.serverName ?? existing.serverName,
mediaVersions: versions == null || versions.isEmpty ? existing.mediaVersions : versions,
);
}
/// Union [additions] into [current] by [MediaItem.globalKey], then re-sort
/// with [compareLibraryCopies]. A key on both sides is folded by [_mergeCopy].
///
/// Never removes a copy, and never downgrades one. The cross-server fan-out
/// behind these lists logs and skips per-server failures, so a later pass can
/// legitimately come back short a server, or short the best-effort library
/// stamp of a copy it did return.
List<MediaItem> mergeLibraryCopies(Iterable<MediaItem> current, Iterable<MediaItem> additions) {
final byKey = <String, MediaItem>{for (final item in current) item.globalKey: item};
for (final item in additions) {
final existing = byKey[item.globalKey];
byKey[item.globalKey] = existing == null ? item : _mergeCopy(existing, item);
}
return byKey.values.toList()..sort(compareLibraryCopies);
}
+9
View File
@@ -30,6 +30,15 @@ enum MediaKind {
bool get isPlayable => isVideo || this == track;
/// Whether this kind maps to one or more files on disk, i.e. the server can
/// answer `MediaServerClient.getFileInfo` for it.
///
/// Deliberately not folded into [isPlayable] even though the member sets
/// coincide today: container kinds (show, season, artist, album, collection,
/// playlist, folder) aggregate leaves and carry no `Media`/`MediaSources` of
/// their own, while a non-playable kind can still be file-backed.
bool get hasFileInfo => this == movie || this == episode || this == track || this == clip;
/// Whether this container kind derives watched state from aggregate leaves.
bool get usesLeafWatchCounts => switch (this) {
show || season || artist || album || collection || playlist || folder => true,
+37
View File
@@ -0,0 +1,37 @@
/// One attributed score for a media item.
///
/// Backends routinely return several: Plex's `/library/metadata/{id}` carries
/// an IMDb score next to both Rotten Tomatoes panels and TMDB, Simkl carries
/// Simkl/IMDb/MAL side by side, Jellyfin carries a community score next to a
/// Tomatometer. `MediaItem.rating` keeps the backend's headline number; this
/// list keeps every score with attribution so the UI can badge and label them.
///
/// Serialization is hand-written rather than `json_serializable` because
/// catalog objects round-trip through `MediaItem.raw` maps rather than a
/// generated codec.
library;
class MediaRatingSource {
/// Stable, lowercase source key: `imdb`, `tmdb`, `rottenTomatoesCritic`,
/// `rottenTomatoesAudience`, `simkl`, `mal`, `anilist`, `trakt`, `critic`,
/// `audience`. Rendered through a label map, never raw.
final String source;
/// Normalized to 0-10 by the mapper, matching `MediaItem.rating`. Percentage
/// sources (Rotten Tomatoes, TMDB) are rendered back as `value * 10`%.
final double value;
/// How many users the score is based on, when the backend says.
final int? votes;
const MediaRatingSource({required this.source, required this.value, this.votes});
Map<String, Object?> toJson() => {'source': source, 'value': value, if (votes != null) 'votes': votes};
static MediaRatingSource? fromJson(Map<String, Object?> json) {
final source = json['source'] as String?;
final value = (json['value'] as num?)?.toDouble();
if (source == null || value == null) return null;
return MediaRatingSource(source: source, value: value, votes: json['votes'] as int?);
}
}
+94 -22
View File
@@ -167,13 +167,24 @@ abstract class MediaServerClient {
Future<MediaItem?> fetchItem(String id);
/// Fetch a single item *and* its on-deck episode (the next unwatched /
/// in-progress episode) in one round-trip when the backend supports it.
/// The item follows [fetchItem]'s error contract: an online HTTP 404 returns
/// both nullable fields as `null`, while every other HTTP status throws.
/// Plex bundles both via `/library/metadata/{id}?includeOnDeck=1`;
/// Jellyfin has no equivalent endpoint and returns `onDeckEpisode: null`,
/// leaving callers to fetch on-deck separately if they need it.
Future<({MediaItem? item, MediaItem? onDeckEpisode})> fetchItemWithOnDeck(String id);
/// in-progress episode). The item follows [fetchItem]'s error contract: an
/// online HTTP 404 returns both nullable fields as `null`, while every other
/// HTTP status throws.
///
/// Plex bundles both via `/library/metadata/{id}?includeOnDeck=1`. Jellyfin
/// has no equivalent endpoint and needs a second request for on-deck, so it
/// would otherwise hold the item behind a round trip the detail screen does
/// not need in order to paint.
///
/// [onItemReady] exists for exactly that case: implementations invoke it as
/// soon as the item is known, *if* that is strictly before the on-deck
/// lookup finishes. Backends that return both together never invoke it, and
/// neither does a null item. Callers must therefore treat it as an optional
/// early paint and still handle the returned record.
Future<({MediaItem? item, MediaItem? onDeckEpisode})> fetchItemWithOnDeck(
String id, {
void Function(MediaItem item)? onItemReady,
});
/// Direct children of [parentId] — episodes of a season, seasons of a
/// show, tracks of an album, items of a collection.
@@ -272,7 +283,18 @@ abstract class MediaServerClient {
/// candidate budget; a backend may supplement omitted media categories and
/// return more candidates for cross-server ranking. [abort] cancels every
/// backend request owned by this search pass.
Future<List<MediaItem>> searchItems(String query, {int limit = 100, AbortController? abort});
///
/// [excludedLibraryIds] names server-local libraries the user has hidden. A
/// backend whose search rows carry a library id may ignore it, because the
/// caller drops those rows by id. A backend whose rows cannot be attributed
/// to a library MUST scope the request server-side instead — the caller has
/// nothing to filter on.
Future<List<MediaItem>> searchItems(
String query, {
int limit = 100,
AbortController? abort,
Set<String> excludedLibraryIds = const {},
});
/// Items the user has started but not finished. Plex calls this "On Deck"
/// internally; the neutral name matches the Continue Watching UI surface.
@@ -504,7 +526,7 @@ abstract class MediaServerClient {
/// has no external mapping for the item.
Future<ExternalIds> fetchExternalIds(String itemId);
/// Reverse lookup: find a library movie/show matching any of [ids].
/// Reverse lookup: find every library movie/show matching any of [ids].
///
/// Neither backend can filter by external id — Plex's `guid=` matches only
/// the primary `plex://` guid (verified on PMS 1.43) and Jellyfin dropped
@@ -512,7 +534,16 @@ abstract class MediaServerClient {
/// title and verify candidates against their exact external ids. Title
/// alone never produces a match.
///
/// [titles] are tried in order until one yields an id-verified candidate;
/// One title can own several library items: a server with a 4K section and
/// an HD section holds two rating keys for the same movie, and a library
/// still on a legacy agent carries a different primary guid than its modern
/// sibling. Implementations MUST return every id-verified copy rather than
/// the first, and MUST NOT truncate — external-id verification is the only
/// bound, so a long list means the user genuinely owns that many copies and
/// the caller (the Explore "In these libraries" chooser) exists to show
/// them. Ordering is the implementation's, and callers re-sort.
///
/// [titles] are tried in order until one yields id-verified candidates;
/// pass the entry's own title first and broader forms after (see
/// `titleMatchCandidates`). A sequel entry's own title never matches its
/// parent show, which is why more than one is needed. [year] applies a ±1
@@ -520,22 +551,21 @@ abstract class MediaServerClient {
/// season's, not the show's.
///
/// [plexGuid] is a Plex-only escape hatch: a `plex://show/…` guid the caller
/// already holds, which the local server *can* filter on exactly, skipping
/// the title search. It is never resolved over the network — only Plex
/// Discover catalog items carry one, in their own rating key. Other backends
/// ignore it.
/// already holds, which the local server *can* filter on exactly. It is
/// never resolved over the network — only Plex Discover catalog items carry
/// one, in their own rating key. Other backends ignore it.
///
/// [season] gates the result: when the entry maps to season 2+ of a longer
/// series, a match is only returned if the server actually has that season.
/// [season] gates the results: when the entry maps to season 2+ of a longer
/// series, a candidate is only kept if the server actually has that season.
/// Implementations MUST gate only on [ExternalSeasonRef.agreedSeason] — the
/// provider a library numbers its seasons by is a server-side setting no
/// dataset supplies, so a disagreeing ref is left ungated rather than gated
/// on a guess.
///
/// Returns null when this server has no match or [kind] is not movie/show.
/// Used to match external catalog items (Explore tab) back to the user's
/// libraries.
Future<MediaItem?> findByExternalIds(
/// Returns an empty list when this server has no match or [kind] is not
/// movie/show. Used to match external catalog items (Explore tab) back to
/// the user's libraries.
Future<List<MediaItem>> findByExternalIds(
ExternalIds ids, {
required MediaKind kind,
List<String> titles = const [],
@@ -716,20 +746,41 @@ extension MediaServerClientScope on MediaServerClient {
_ => serverId,
};
/// Mark [item] watched because it crossed [watchedThreshold] during playback,
/// when a playback-stopped report is/was also sent for the same playback.
/// Mark [item] watched because playback crossed [watchedThreshold], for paths
/// where the backend cannot mark it from the playback reports themselves:
/// queued offline replay, external players, Plex same-file siblings, and
/// in-player sessions whose crossing the backend never observed.
///
/// Backends that mark played from the stop report
/// ([marksWatchedOnPlaybackStopped]) skip the server call — issuing
/// [markWatched] too would double-scrobble via the Jellyfin Trakt plugin
/// (#1287). The single local event emitted here keeps the UI and Plezy's
/// own Trakt sync (which key on `watched` events, not progress) in sync;
/// the stop report syncs the server.
///
/// In-player sessions that *did* give the backend an observable crossing use
/// [notifyWatchedFromPlaybackSession] instead.
Future<void> markWatchedFromPlaybackStop(MediaItem item) async {
if (!marksWatchedOnPlaybackStopped) {
await markWatched(item);
}
WatchStateNotifier().notifyWatched(item: item, isNowWatched: true, cacheServerId: cacheServerId);
}
/// Emit the local watched event for [item] without touching the server.
///
/// Used when a live playback-reporting session has already given the backend
/// everything it needs to mark the item itself — a report below
/// [watchedThreshold] followed by one at or above it. Both backends act on
/// that crossing: Jellyfin through `/Sessions/Playing/Stopped`
/// (`MaxResumePct`), Plex through `/:/timeline` past
/// `LibraryVideoPlayedThreshold`. Adding an explicit [markWatched] on top
/// records the same watch twice — a second Trakt-plugin scrobble on Jellyfin
/// (#1287), a second Play History row and an inflated `viewCount` on Plex
/// (#1740).
void notifyWatchedFromPlaybackSession(MediaItem item) {
WatchStateNotifier().notifyWatched(item: item, isNowWatched: true, cacheServerId: cacheServerId);
}
}
extension MediaServerClientLiveTv on MediaServerClient {
@@ -752,6 +803,27 @@ abstract interface class SeasonEpisodePagingClient {
});
}
/// Optional capability for clients whose server can answer "may the signed-in
/// user delete *this* item?" per item.
///
/// Jellyfin-only by nature: `BaseItemDto.CanDelete` folds the global
/// `EnableContentDeletion` grant, the per-library
/// `EnableContentDeletionFromFolders` grant, and item state (virtual/missing
/// files, in-progress recordings) into one server-computed boolean — none of
/// which a client can reproduce. Plex exposes no per-item delete permission,
/// so it deliberately does not implement this and callers keep using their
/// account-level owner/admin gate for it.
abstract interface class MediaDeletionPermissionClient {
/// `true`/`false` as reported by the server for [item], or `null` when the
/// server did not answer (item not visible to this user, unexpected shape).
///
/// Never served from cache: the answer changes server-side with no
/// client-visible event, and a stale `true` puts a destructive action back in
/// front of a user who lost the grant. Callers must fail closed on `null`
/// and on throw.
Future<bool?> fetchDeletePermission(MediaItem item);
}
/// Cache-aware fetch helpers shared by both backends so the offline-first /
/// network-then-cache pattern lives in one place.
///
+19
View File
@@ -68,6 +68,25 @@ class MediaVersion {
/// them when metadata is fetched with `checkFiles=1`.
bool get isPlayable => parts.isEmpty || parts.any((part) => part.isPlayable);
/// Approximate vertical resolution, for ordering versions best-first.
///
/// Plex reports either a numeric height (`"1080"`) or a named tier
/// (`"sd"`, `"4k"`) and usually both; Jellyfin reports [height] directly.
/// Null when the backend gave neither.
int? get resolutionHeight {
final reported = height;
if (reported != null && reported > 0) return reported;
final named = (videoResolution ?? '').trim().toLowerCase();
return switch (named) {
'' => null,
'sd' => 480,
'hd' => 720,
'4k' => 2160,
'8k' => 4320,
_ => int.tryParse(named),
};
}
/// Display label with detailed information: "1080p H.264 MKV (8.5 Mbps)".
/// When [name] is set, it prefixes the technical label so a user can tell
/// "Director's Cut · 1080p H.264 MKV" apart from "Theatrical Cut · 1080p
+10
View File
@@ -4,6 +4,16 @@ mixin Refreshable {
mixin FullRefreshable {
void fullRefresh();
/// Online-entry variant, used by `main_screen._primeOnlineServices` on cold
/// start and on reconnect-from-offline. Its job is to guarantee the tab
/// loads once servers are up — not to force a refetch.
///
/// Screens that already kick off their own load in `initState` override this
/// to skip while that pass is still in flight; otherwise the prime queues an
/// identical trailing pass and the tab fetches everything twice (#1784).
/// Profile switches go through [fullRefresh] instead, which always refetches.
void primeRefresh() => fullRefresh();
}
mixin FocusableTab {
+4 -2
View File
@@ -1,6 +1,7 @@
import '../../media/media_backend.dart';
import '../../media/media_item.dart';
import '../../media/media_kind.dart';
import '../../media/media_rating.dart';
import '../../utils/external_ids.dart';
import 'catalog_cast_member.dart';
import 'catalog_metadata.dart';
@@ -213,7 +214,7 @@ class CatalogItem {
final String? accentColor;
/// Scores beyond [rating], each with its own source label.
final List<CatalogRatingSource>? ratings;
final List<MediaRatingSource>? ratings;
/// Leaderboard positions. A list because providers return several windows
/// at once (all-time and seasonal).
@@ -493,6 +494,7 @@ class CatalogItem {
contentRating: certification,
durationMs: runtimeMinutes == null ? null : Duration(minutes: runtimeMinutes!).inMilliseconds,
rating: rating,
ratings: ratings,
genres: genres,
thumbPath: posterUrl,
artPath: backdropUrl,
@@ -594,7 +596,7 @@ class CatalogItem {
logoUrl: json['logoUrl'] as String?,
bannerUrl: json['bannerUrl'] as String?,
accentColor: json['accentColor'] as String?,
ratings: decodeCatalogList(json['ratings'], CatalogRatingSource.fromJson),
ratings: decodeCatalogList(json['ratings'], MediaRatingSource.fromJson),
ranks: decodeCatalogList(json['ranks'], CatalogRank.fromJson),
audience: _decodeObject(json['audience'], CatalogAudience.fromJson),
broadcast: _decodeObject(json['broadcast'], CatalogBroadcast.fromJson),
-29
View File
@@ -8,35 +8,6 @@
/// round-trip through `MediaItem.raw` inside a single session.
library;
/// One provider score with its own source label.
///
/// Providers routinely return several: Simkl carries Simkl/IMDb/MAL side by
/// side, Plex carries a critic score next to an audience score. The neutral
/// [CatalogItem.rating] keeps the provider's headline number; this list keeps
/// the rest with attribution so the UI can label them.
class CatalogRatingSource {
/// Stable, lowercase source key: `simkl`, `imdb`, `mal`, `anilist`, `tmdb`,
/// `trakt`, `critic`, `audience`. Rendered through a label map, never raw.
final String source;
/// Normalized to 0-10 by the mapper, matching [CatalogItem.rating].
final double value;
/// How many users the score is based on, when the provider says.
final int? votes;
const CatalogRatingSource({required this.source, required this.value, this.votes});
Map<String, Object?> toJson() => {'source': source, 'value': value, if (votes != null) 'votes': votes};
static CatalogRatingSource? fromJson(Map<String, Object?> json) {
final source = json['source'] as String?;
final value = (json['value'] as num?)?.toDouble();
if (source == null || value == null) return null;
return CatalogRatingSource(source: source, value: value, votes: json['votes'] as int?);
}
}
/// What a leaderboard position is a position *in*.
///
/// MAL returns one rank per ranking endpoint, AniList returns a `rankings`
@@ -10,8 +10,6 @@ class PlexVideoPlaybackData {
final List<MediaVersion> availableVersions;
final List<MediaMarker> markers;
final int selectedMediaIndex;
final int selectedPartIndex;
@@ -20,7 +18,6 @@ class PlexVideoPlaybackData {
required this.videoUrl,
required this.mediaInfo,
required this.availableVersions,
this.markers = const [],
this.selectedMediaIndex = 0,
this.selectedPartIndex = 0,
});
+24
View File
@@ -8,6 +8,13 @@ sealed class BufferRange with _$BufferRange {
const factory BufferRange({required Duration start, required Duration end}) = _BufferRange;
}
final RegExp _httpStatusPattern = RegExp(r'\b(?:HTTP error |Response code: )(\d{3})\b');
/// Server statuses that end playback outright: nothing client-side recovers a
/// transcoding-limit rejection or a file the server cannot read. Everything
/// else (notably the 503 the reconnect path retries) is transient.
const Set<int> fatalPlaybackHttpStatuses = {404, 500};
/// [cause] is an optional machine-readable tag (e.g. `server-http-500`),
/// letting the UI branch without parsing [message].
@Freezed(toStringOverride: false)
@@ -20,6 +27,23 @@ sealed class PlayerError with _$PlayerError {
/// transcoding limit rejection set by the server owner.
static const String serverHttp500 = 'server-http-500';
/// Cause tag for a server-side HTTP 404 on the media stream. The server
/// resolved the item but cannot read the file behind it (moved, deleted, or
/// on unavailable storage), so no retry or backend switch can recover it.
static const String serverHttp404 = 'server-http-404';
/// HTTP status [logText] reports, or null when it names none.
///
/// A [PlayerError] carries no status field: mpv only ever tells us the
/// end-file reason. ffmpeg does log the status, one warn-level line ahead of
/// the error-level failure (`http: HTTP error 404 Not Found`), and media3's
/// exception chain stringifies it as `Response code: 404`, so scanning the
/// player's own log stream is the only way to recover it.
static int? httpStatusFromLog(String logText) {
final match = _httpStatusPattern.firstMatch(logText);
return match == null ? null : int.tryParse(match.group(1)!);
}
@override
String toString() => message;
}
+49 -10
View File
@@ -12,6 +12,7 @@ class PlayerAndroid extends PlayerBase {
static const _eventChannel = EventChannel('com.plezy/exo_player/events');
int? _bufferSizeBytes;
bool _bufferSizeIsAuto = false;
bool _tunnelingEnabled = true;
String _dvConversionMode = 'auto';
bool _audioNormalizationEnabled = false;
@@ -27,6 +28,13 @@ class PlayerAndroid extends PlayerBase {
bool get usingMpvFallback => _usingMpvFallback;
/// Subtitles are hidden through the player's visibility toggle. Sticky
/// across media opens, like mpv's global `sub-visibility`, so an episode
/// change cannot put them back on screen.
bool _subtitlesHidden = false;
/// Track that un-hiding restores: whatever was selected when subtitles were
/// hidden, then whatever was selected for the current media while hidden.
String? _hiddenSubtitleTrackId;
@override
@@ -100,6 +108,7 @@ class PlayerAndroid extends PlayerBase {
try {
final result = await invoke<bool>('initialize', {
'bufferSizeBytes': _bufferSizeBytes,
'bufferSizeAuto': _bufferSizeIsAuto,
'tunnelingEnabled': _tunnelingEnabled,
'dvConversionMode': _dvConversionMode,
'audioPassthroughEnabled': _audioPassthroughEnabled,
@@ -246,14 +255,36 @@ class PlayerAndroid extends PlayerBase {
await invoke('selectAudioTrack', {'trackId': track.id});
}
/// ExoPlayer has no renderer-level subtitle visibility switch, so hiding is
/// implemented as deselection (see [setProperty]'s `sub-visibility` case).
/// A selection arriving while subtitles are hidden — the automatic pass
/// after an episode change, or a manual pick — becomes what un-hiding
/// restores instead of putting subtitles back on screen, matching how mpv's
/// global `sub-visibility` keeps hiding across files (#1779).
@override
Future<void> selectSubtitleTrack(SubtitleTrack track) async {
if (_subtitlesHidden) {
_hiddenSubtitleTrackId = track.id == SubtitleTrack.off.id ? null : track.id;
return _selectSubtitleTrackNatively(SubtitleTrack.off);
}
return _selectSubtitleTrackNatively(track);
}
Future<void> _selectSubtitleTrackNatively(SubtitleTrack track) async {
await invoke('selectSubtitleTrack', {'trackId': track.id});
}
/// A sidecar flagged default must not draw itself onto a hidden renderer
/// either; the selection pass that follows the add records it the same way
/// [selectSubtitleTrack] does.
@override
Future<void> addSubtitleTrack({required String uri, String? title, String? language, bool select = false}) async {
await invoke('addSubtitleTrack', {'uri': uri, 'title': title, 'language': language, 'select': select});
await invoke('addSubtitleTrack', {
'uri': uri,
'title': title,
'language': language,
'select': select && !_subtitlesHidden,
});
}
@override
@@ -287,6 +318,12 @@ class PlayerAndroid extends PlayerBase {
case 'demuxer-max-bytes':
_bufferSizeBytes = int.tryParse(value);
break;
// Not an mpv property. The heap tiers Dart derives for mpv's demuxer are the wrong
// shape for ExoPlayer's sample allocator, so on Auto the native side sizes its own
// LoadControl target instead of reusing `demuxer-max-bytes` (#1618).
case 'demuxer-max-bytes-auto':
_bufferSizeIsAuto = value != 'no';
break;
case 'tunneled-playback':
_tunnelingEnabled = value != 'no';
break;
@@ -299,19 +336,21 @@ class PlayerAndroid extends PlayerBase {
break;
case 'sub-visibility':
if (value == 'no') {
if (_subtitlesHidden) break;
_subtitlesHidden = true;
final current = state.track.subtitle;
if (current != null && current.id != 'no') {
_hiddenSubtitleTrackId = current.id;
await selectSubtitleTrack(SubtitleTrack.off);
_hiddenSubtitleTrackId = current != null && current.id != SubtitleTrack.off.id ? current.id : null;
if (_hiddenSubtitleTrackId != null) {
await _selectSubtitleTrackNatively(SubtitleTrack.off);
}
} else {
if (!_subtitlesHidden) break;
_subtitlesHidden = false;
final storedId = _hiddenSubtitleTrackId;
if (storedId != null) {
_hiddenSubtitleTrackId = null;
final track = state.tracks.subtitle.firstWhereOrNull((t) => t.id == storedId);
if (track != null) {
await selectSubtitleTrack(track);
}
_hiddenSubtitleTrackId = null;
final track = storedId == null ? null : state.tracks.subtitle.firstWhereOrNull((t) => t.id == storedId);
if (track != null) {
await _selectSubtitleTrackNatively(track);
}
}
break;
+13 -10
View File
@@ -929,19 +929,22 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
}
/// Injects the log + error events that would fire when the server rejects the
/// stream with HTTP 500 (shared-user bandwidth / transcoding limit). Used by
/// the in-player debug button to preview the end-to-end detection path
/// without needing a real misbehaving server.
void debugSimulateServer500() {
/// stream with [status]. Used by the in-player debug buttons to preview the
/// end-to-end detection path without needing a real misbehaving server: 500
/// is a shared-user bandwidth/transcoding limit, 404 a file the server can no
/// longer read. The warn-level log mirrors ffmpeg's real wording, which is
/// what [PlayerError.httpStatusFromLog] parses.
void debugSimulateServerHttpError(int status) {
if (_disposed) return;
logController.add(
const PlayerLog(
level: PlayerLogLevel.warn,
prefix: 'ffmpeg',
text: 'https: HTTP error 500 Internal Server Error',
),
PlayerLog(level: PlayerLogLevel.warn, prefix: 'ffmpeg', text: 'https: HTTP error $status Simulated'),
);
errorController.add(const PlayerError('HTTP 500', cause: PlayerError.serverHttp500));
final cause = switch (status) {
500 => PlayerError.serverHttp500,
404 => PlayerError.serverHttp404,
_ => null,
};
errorController.add(PlayerError('HTTP $status', cause: cause));
}
Future<bool> _waitForNativeOwnershipForDispose() async {
+65 -2
View File
@@ -11,6 +11,9 @@ import '../services/storage_service.dart';
import '../utils/app_logger.dart';
import 'plex_home_service.dart';
import 'profile.dart';
import 'profile_avatar_source.dart';
import 'profile_connection.dart';
import 'profile_connection_registry.dart';
import 'profile_merge.dart';
import 'profile_registry.dart';
@@ -27,6 +30,7 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
required this._registry,
required this._plexHome,
required this._connections,
required this._profileConnections,
this._storage,
this._activeProfileIdWriter,
});
@@ -34,6 +38,7 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
final ProfileRegistry _registry;
final PlexHomeService _plexHome;
final ConnectionRegistry _connections;
final ProfileConnectionRegistry _profileConnections;
StorageService? _storage;
final Future<void> Function(String profileId)? _activeProfileIdWriter;
@@ -42,9 +47,12 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
List<Profile> _localProfiles = const [];
Map<String, List<PlexHomeUser>> _plexHomeUsers = const {};
Map<String, Connection> _connectionsById = const {};
Map<String, List<ProfileConnection>> _connectionsByProfile = const {};
Map<String, String?> _avatarUrls = const {};
StreamSubscription<List<Profile>>? _localSub;
StreamSubscription<List<Connection>>? _connSub;
StreamSubscription<List<ProfileConnection>>? _pcSub;
StreamSubscription<Map<String, List<PlexHomeUser>>>? _plexHomeSub;
Future<void>? _initializeFuture;
bool _initialized = false;
@@ -61,6 +69,10 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
Profile? get active => _active;
String? get activeId => _active?.id;
List<Profile> get profiles => _profiles;
/// Derived picture URL for [profileId], or null when initials should render.
String? avatarUrlFor(String profileId) => _avatarUrls[profileId];
bool get hasMultipleProfiles => _profiles.length > 1;
bool get isInitialized => _initialized;
@@ -170,6 +182,14 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
_resolveActive();
safeNotifyListeners();
});
_pcSub = _profileConnections.watchAll().listen((list) {
final byProfile = groupConnectionsByProfile(list);
if (_sameProfileConnections(byProfile, _connectionsByProfile)) return;
_connectionsByProfile = byProfile;
_recomputeProfiles();
_resolveActive();
safeNotifyListeners();
});
_plexHomeSub = _plexHome.stream.listen((cache) {
if (_samePlexHomeUsers(cache, _plexHomeUsers)) return;
_plexHomeUsers = cache;
@@ -191,24 +211,56 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
_localProfiles = await _registry.list();
final initialConns = await _connections.list();
_connectionsById = {for (final c in initialConns) c.id: c};
_connectionsByProfile = groupConnectionsByProfile(await _profileConnections.listAll());
_plexHomeUsers = _plexHome.current;
_recomputeProfiles();
_resolveActive();
}
/// [Connection] has no value equality; its persisted config is the
/// cheapest faithful comparison key for the handful of rows involved.
/// [Connection] has no value equality; its persisted config is the cheapest
/// faithful comparison key for the handful of rows involved.
///
/// `createdAt` is compared separately because it is a real column rather
/// than part of `toConfigJson`, and avatar selection reads it: a profile
/// shows the picture of its oldest linked connection. `ConnectionRegistry`
/// pins creation order across re-authentication, so this costs no extra
/// notifications — it only stops a genuine correction (a restore, a
/// backfill) from being swallowed until the next launch.
static bool _sameConnections(Map<String, Connection> a, Map<String, Connection> b) {
if (a.length != b.length) return false;
for (final entry in a.entries) {
final other = b[entry.key];
if (other == null) return false;
if (identical(entry.value, other)) continue;
if (entry.value.createdAt != other.createdAt) return false;
if (jsonEncode(entry.value.toConfigJson()) != jsonEncode(other.toConfigJson())) return false;
}
return true;
}
static bool _sameProfileConnections(Map<String, List<ProfileConnection>> a, Map<String, List<ProfileConnection>> b) {
if (a.length != b.length) return false;
for (final entry in a.entries) {
final other = b[entry.key];
if (other == null || entry.value.length != other.length) return false;
for (final row in entry.value) {
var hasSameFingerprint = false;
for (final candidate in other) {
if (row.profileId == candidate.profileId &&
row.connectionId == candidate.connectionId &&
row.userIdentifier == candidate.userIdentifier) {
hasSameFingerprint = true;
break;
}
}
// Only these identity fields affect avatar selection. Deliberately
// ignore tokens, default status, and binder-maintained timestamps.
if (!hasSameFingerprint) return false;
}
}
return true;
}
static bool _samePlexHomeUsers(Map<String, List<PlexHomeUser>> a, Map<String, List<PlexHomeUser>> b) {
if (a.length != b.length) return false;
for (final entry in a.entries) {
@@ -225,6 +277,12 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
connectionsById: _connectionsById,
storage: _storage,
);
_avatarUrls = resolveProfileAvatarUrls(
profiles: _profiles,
connectionsByProfile: _connectionsByProfile,
connectionsById: _connectionsById,
plexHomeByConnectionId: _plexHomeUsers,
);
}
void _resolveActive() {
@@ -487,13 +545,17 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
await _localSub?.cancel();
await _connSub?.cancel();
await _plexHomeSub?.cancel();
await _pcSub?.cancel();
_localSub = null;
_connSub = null;
_plexHomeSub = null;
_pcSub = null;
_profiles = const [];
_localProfiles = const [];
_plexHomeUsers = const {};
_connectionsById = const {};
_connectionsByProfile = const {};
_avatarUrls = const {};
_active = null;
_initializeFuture = null;
_initialized = false;
@@ -525,6 +587,7 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
_localSub?.cancel();
_connSub?.cancel();
_plexHomeSub?.cancel();
_pcSub?.cancel();
super.dispose();
}
}
+15 -4
View File
@@ -12,13 +12,19 @@ class ProfileAvatar extends StatelessWidget {
final double size;
final bool showLockBadge;
const ProfileAvatar({super.key, required this.profile, this.size = 40, this.showLockBadge = true});
/// The derived picture for this profile (see [resolveProfileAvatarUrls]).
///
/// Falls back to [Profile.avatarThumbUrl] when null.
final String? avatarUrl;
const ProfileAvatar({super.key, required this.profile, this.size = 40, this.showLockBadge = true, this.avatarUrl});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final p = profile;
final lockBadgeSize = size * 0.34;
final memCacheSize = (size * MediaQuery.devicePixelRatioOf(context)).round();
return SizedBox(
width: size,
@@ -27,7 +33,7 @@ class ProfileAvatar extends StatelessWidget {
clipBehavior: Clip.none,
children: [
ClipOval(
child: SizedBox(width: size, height: size, child: _buildContent(theme, p)),
child: SizedBox(width: size, height: size, child: _buildContent(theme, p, memCacheSize)),
),
if (showLockBadge && p != null && p.isPinProtected)
Positioned(
@@ -55,16 +61,21 @@ class ProfileAvatar extends StatelessWidget {
);
}
Widget _buildContent(ThemeData theme, Profile? p) {
Widget _buildContent(ThemeData theme, Profile? p, int memCacheSize) {
if (p == null) {
return Container(color: theme.colorScheme.surfaceContainerHighest);
}
final thumb = p.avatarThumbUrl;
// An empty override means "nothing derived", not "suppress the profile's
// own picture" — same absent-or-blank rule the thumb itself uses below.
final override = avatarUrl;
final thumb = override != null && override.isNotEmpty ? override : p.avatarThumbUrl;
if (thumb != null && thumb.isNotEmpty) {
return CachedNetworkImage(
imageUrl: thumb,
cacheManager: PlexImageCacheManager.instance,
fit: BoxFit.cover,
memCacheWidth: memCacheSize,
memCacheHeight: memCacheSize,
placeholder: (_, _) => _initialFallback(theme, p),
errorBuilder: (_, _, _) => _initialFallback(theme, p),
);
+105
View File
@@ -0,0 +1,105 @@
import '../connection/connection.dart';
import '../models/plex/plex_home_user.dart';
import '../services/jellyfin_mappers.dart';
import 'profile.dart';
import 'profile_connection.dart';
/// Picture URL per profile id, `null` meaning "render initials".
///
/// A [PlexHomeProfile] owns its picture: Plex serves a per-home-user avatar
/// and [Profile.virtualPlexHome] already carries it, so those pass through
/// untouched.
///
/// A [LocalProfile] has no picture of its own. It shows the user picture of
/// the connection it was linked to **first** — the oldest by
/// [Connection.createdAt], ties broken by connection id so the choice is
/// stable. If that connection has no picture the profile falls back to
/// initials; we deliberately do *not* skip ahead to a later connection, so the
/// avatar stays a property of "the first connection" rather than of whichever
/// backend happens to have an image today.
///
/// The join row is not a usable ordering key: `profile_connections` has no
/// creation timestamp, and `tokenAcquiredAt` is rewritten every time the
/// binder re-mints a Plex Home token.
Map<String, String?> resolveProfileAvatarUrls({
required List<Profile> profiles,
required Map<String, List<ProfileConnection>> connectionsByProfile,
required Map<String, Connection> connectionsById,
required Map<String, List<PlexHomeUser>> plexHomeByConnectionId,
}) {
return {
for (final profile in profiles)
profile.id: _avatarForProfile(
profile: profile,
links: connectionsByProfile[profile.id] ?? const [],
connectionsById: connectionsById,
plexHomeByConnectionId: plexHomeByConnectionId,
),
};
}
String? _avatarForProfile({
required Profile profile,
required List<ProfileConnection> links,
required Map<String, Connection> connectionsById,
required Map<String, List<PlexHomeUser>> plexHomeByConnectionId,
}) {
final own = profile.avatarThumbUrl;
if (own != null && own.isNotEmpty) return own;
// A Plex Home user with no avatar set keeps its initials. Plex owns that
// profile's identity end to end, so it must never borrow the picture of a
// connection it happens to have been lent.
if (profile.isPlexHome) return null;
ProfileConnection? firstLink;
Connection? first;
for (final link in links) {
// A link whose connection was removed can't contribute a picture, and it
// must not win the ordering either.
final connection = connectionsById[link.connectionId];
if (connection == null) continue;
if (first == null || _isEarlier(connection, first)) {
first = connection;
firstLink = link;
}
}
if (first == null || firstLink == null) return null;
return connectionAvatarUrl(connection: first, link: firstLink, plexHomeByConnectionId: plexHomeByConnectionId);
}
bool _isEarlier(Connection candidate, Connection incumbent) {
final byCreatedAt = candidate.createdAt.compareTo(incumbent.createdAt);
if (byCreatedAt != 0) return byCreatedAt < 0;
return candidate.id.compareTo(incumbent.id) < 0;
}
/// Picture a single connection contributes to [link]'s profile, or `null`.
///
/// Plex resolves through the join row rather than the account owner: a profile
/// borrows a *specific* Home user (`userIdentifier`), and that user's live
/// [PlexHomeUser.thumb] is the picture Plex shows for it. Reading the live
/// cache also means the avatar tracks Plex's hourly refresh for free.
String? connectionAvatarUrl({
required Connection connection,
required ProfileConnection link,
required Map<String, List<PlexHomeUser>> plexHomeByConnectionId,
}) {
return switch (connection) {
JellyfinConnection(:final baseUrl, :final userId, :final primaryImageTag) => jellyfinUserImageUrl(
baseUrl: baseUrl,
userId: userId,
tag: primaryImageTag,
),
PlexAccountConnection() => _plexHomeUserThumb(plexHomeByConnectionId[connection.id], link.userIdentifier),
};
}
String? _plexHomeUserThumb(List<PlexHomeUser>? homeUsers, String homeUserUuid) {
if (homeUsers == null || homeUserUuid.isEmpty) return null;
for (final user in homeUsers) {
if (user.uuid != homeUserUuid) continue;
return user.thumb.isEmpty ? null : user.thumb;
}
return null;
}
+10
View File
@@ -2,6 +2,16 @@ import '../connection/connection.dart';
import '../models/plex/plex_home_user.dart';
import '../services/storage_service.dart';
import 'profile.dart';
import 'profile_connection.dart';
/// Groups profile-connection rows by profile id, preserving input order.
Map<String, List<ProfileConnection>> groupConnectionsByProfile(List<ProfileConnection> pcs) {
final out = <String, List<ProfileConnection>>{};
for (final pc in pcs) {
out.putIfAbsent(pc.profileId, () => []).add(pc);
}
return out;
}
/// Merge local profiles with virtual Plex Home profiles. Each Plex Home
/// user becomes a virtual profile attached to its `connectionId`. Home
+28 -11
View File
@@ -6,6 +6,7 @@ import '../models/plex/plex_home_user.dart';
import '../services/storage_service.dart';
import 'plex_home_service.dart';
import 'profile.dart';
import 'profile_avatar_source.dart';
import 'profile_connection.dart';
import 'profile_connection_registry.dart';
import 'profile_merge.dart';
@@ -25,9 +26,22 @@ class ProfilesView {
final Map<String, Connection> connectionsById;
const ProfilesView({required this.profiles, required this.connectionsByProfile, required this.connectionsById});
/// Picture URL per profile id; null means render initials. See [resolveProfileAvatarUrls].
final Map<String, String?> avatarUrlByProfile;
static const empty = ProfilesView(profiles: [], connectionsByProfile: {}, connectionsById: {});
const ProfilesView({
required this.profiles,
required this.connectionsByProfile,
required this.connectionsById,
required this.avatarUrlByProfile,
});
static const empty = ProfilesView(
profiles: [],
connectionsByProfile: {},
connectionsById: {},
avatarUrlByProfile: {},
);
}
/// Join-table rows that should be shown as explicit, user-manageable
@@ -77,21 +91,24 @@ ProfilesView _build({
required StorageService? storage,
}) {
final connectionsById = {for (final c in conns) c.id: c};
final connectionsByProfile = groupConnectionsByProfile(pcs);
final all = mergeLocalWithPlexHome(
locals: locals,
plexHomeByConnectionId: homes,
connectionsById: connectionsById,
storage: storage,
);
return ProfilesView(profiles: all, connectionsByProfile: _groupByProfile(pcs), connectionsById: connectionsById);
}
Map<String, List<ProfileConnection>> _groupByProfile(List<ProfileConnection> pcs) {
final out = <String, List<ProfileConnection>>{};
for (final pc in pcs) {
out.putIfAbsent(pc.profileId, () => []).add(pc);
}
return out;
return ProfilesView(
profiles: all,
connectionsByProfile: connectionsByProfile,
connectionsById: connectionsById,
avatarUrlByProfile: resolveProfileAvatarUrls(
profiles: all,
connectionsByProfile: connectionsByProfile,
connectionsById: connectionsById,
plexHomeByConnectionId: homes,
),
);
}
/// Lightweight `combineLatest4` — emits the combined value once each input
+5
View File
@@ -167,6 +167,11 @@ class DiscoverProvider extends ChangeNotifier with DisposableChangeNotifierMixin
return _loadCoordinator.requestFull();
}
/// Whether a [load] pass is already running. The startup online-entry hook
/// uses this to skip a prime that would only duplicate the load the screen
/// started in `initState`.
bool get isLoadInFlight => _loadCoordinator.isBusy;
Future<void> _loadOnce() async {
// Yield to the microtask queue before the first notify so a load()
// kicked off during build (the screen's initState) doesn't mark
+1 -1
View File
@@ -263,7 +263,7 @@ class _AuthScreenState extends State<AuthScreen> {
body: Center(
child: Container(
constraints: BoxConstraints(maxWidth: isDesktop ? 800 : 400),
padding: const EdgeInsets.all(24),
padding: .fromLTRB(24, 24, 24, 24 + MediaQuery.paddingOf(context).bottom),
child: isDesktop
? Row(
crossAxisAlignment: .center,
+79 -45
View File
@@ -19,6 +19,9 @@ import '../i18n/app_locale_utils.dart';
import '../i18n/strings.g.dart';
import '../media/media_hub.dart';
import '../media/media_item.dart';
import '../media/media_item_merge.dart';
import '../media/media_rating.dart';
import '../media/media_version.dart';
import '../models/catalog/catalog_cast_member.dart';
import '../models/catalog/catalog_item.dart';
import '../models/catalog/catalog_metadata.dart';
@@ -76,6 +79,12 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
List<CatalogLink> _streamingLinks = const [];
List<CatalogLink> _otherLinks = const [];
bool _showSpoilerTags = false;
/// Focus node per library copy, keyed by [MediaItem.globalKey] so a later
/// resolution pass that adds a copy keeps the nodes — and therefore the
/// focus — of the rows already on screen. [_libraryMatchFocusNodes] is the
/// same nodes in display order, for index-based dpad traversal.
final Map<String, FocusNode> _libraryMatchNodesByKey = {};
List<FocusNode> _libraryMatchFocusNodes = const [];
CatalogSource? _watchlistSource;
SeerrCatalogSource? _requestSource;
@@ -134,7 +143,7 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
node.dispose();
}
_watchlistSource?.watchlistChanges.removeListener(_onWatchlistChanged);
for (final node in _libraryMatchFocusNodes) {
for (final node in _libraryMatchNodesByKey.values) {
node.dispose();
}
for (final node in _relationFocusNodes) {
@@ -149,37 +158,60 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
setState(() {});
}
/// Monotonic guard for match resolution: the bare row item and its
/// detail-enriched form resolve concurrently, and only the latest-issued
/// resolution may publish (a slow bare lookup must not overwrite the
/// enriched verdict with its own).
int _matchGeneration = 0;
Future<void> _resolveMatches(CatalogItem item) async {
final generation = ++_matchGeneration;
List<MediaItem> matches;
try {
matches = await context.read<CatalogLibraryMatcher>().match(item);
} catch (e) {
appLogger.w('Catalog library match failed for ${item.identityKey}', error: e);
matches = const [];
// A failed pass is no evidence about copies an earlier pass already
// found; only claim "not in your library" when nothing has resolved.
if (_matches == null) _mergeMatches(const []);
return;
}
if (generation == _matchGeneration) _setMatches(matches);
_mergeMatches(matches);
}
void _setMatches(List<MediaItem> matches) {
/// Fold a resolution pass into the visible copies.
///
/// Union, never replace. The bare row item and its detail-enriched form
/// resolve concurrently, and `findByExternalIdsAcrossServers` logs and skips
/// per-server failures — so a later pass can legitimately come back short a
/// server that answered the first one. Replacing would drop rows for copies
/// that are still there.
void _mergeMatches(List<MediaItem> matches) {
if (!mounted) return;
for (final node in _libraryMatchFocusNodes) {
node.dispose();
final focused = _libraryMatchNodesByKey.values.firstWhereOrNull((node) => node.hasPrimaryFocus);
final merged = mergeLibraryCopies(_matches ?? const [], matches);
final keys = {for (final match in merged) match.globalKey};
for (final key in _libraryMatchNodesByKey.keys.toList()) {
if (!keys.contains(key)) _libraryMatchNodesByKey.remove(key)!.dispose();
}
_libraryMatchFocusNodes = [
for (var index = 0; index < matches.length; index++)
FocusNode(
debugLabel: 'catalog_library_match_$index',
onKeyEvent: (node, event) => _handleLibraryMatchKey(index, event),
for (final match in merged)
_libraryMatchNodesByKey.putIfAbsent(
match.globalKey,
() => FocusNode(
debugLabel: 'catalog_library_match_${match.globalKey}',
// Resolved live: merging a pass can reorder the rows, so a
// captured index would steer the wrong copy.
onKeyEvent: (node, event) {
final index = _libraryMatchFocusNodes.indexOf(node);
return index < 0 ? KeyEventResult.ignored : _handleLibraryMatchKey(index, event);
},
),
),
];
setState(() => _matches = matches);
setState(() => _matches = merged);
// A merge re-sorts, and SettingsGroup shapes its cards by list index, so
// the tile holding the focused node can be rebuilt from scratch and drop
// it. Reclaim it rather than dumping a dpad user on another copy.
if (focused != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || focused.hasPrimaryFocus || focused.context == null) return;
focused.requestFocus();
});
}
}
CatalogSource? get _ownSource =>
@@ -231,11 +263,14 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
_relationEntries = relationEntries;
});
// The row form of a Plex Discover item carries only its rating key;
// the detail body brings the external ids (#1715). When enrichment
// added id forms and the bare lookup found nothing, ask again with
// the full set.
// the detail body brings the external ids (#1715). Ask again with the
// full set whenever enrichment added id forms — not just when the bare
// lookup came back empty: the exact `plex://` guid finds only copies in
// libraries on the modern agent, while a legacy-agent sibling is
// reachable solely through the imdb/tmdb forms (#1754). The result
// merges, so a re-ask can only add copies.
final gainedIds = !widget.item.ids.allKeys.toSet().containsAll(detail.item.ids.allKeys);
if (gainedIds && (_matches?.isEmpty ?? true)) {
if (gainedIds) {
unawaited(_resolveMatches(detail.item));
}
} catch (e) {
@@ -499,14 +534,30 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
}
}
/// The technical label of a copy's best version, e.g. "4K HEVC MKV
/// (45.0 Mbps)". Library names are user-chosen and need not mention
/// resolution, which is exactly the question two copies of one movie pose
/// (#1754), so the row states it outright. Omitted when the backend
/// reported no resolution at all, rather than showing "Unknown".
static String? _libraryMatchQuality(MediaItem match) {
MediaVersion? best;
for (final version in match.mediaVersions ?? const <MediaVersion>[]) {
if (version.resolutionHeight == null) continue;
if (best == null || version.resolutionHeight! > best.resolutionHeight!) best = version;
}
return best?.displayLabel;
}
Widget _buildLibraryMatchTile(MediaItem match, int index) {
// Plex matches carry their library title; Jellyfin's search-based lookup
// only does when the ancestors call succeeded, so fall back to the server
// name alone. The subtitle carries whatever else tells two copies apart.
final details = [?_libraryMatchQuality(match), ?(match.libraryTitle == null ? null : match.serverName)];
return FocusableListTile(
focusNode: _libraryMatchFocusNodes[index],
leading: BackendBadge(backend: match.backend, size: 24),
// Plex matches carry their library title; Jellyfin's search-based
// lookup doesn't, so fall back to the server name alone.
title: Text(match.libraryTitle ?? match.serverName ?? match.backend.name),
subtitle: match.libraryTitle != null && match.serverName != null ? Text(match.serverName!) : null,
subtitle: details.isEmpty ? null : Text(details.join(' • ')),
trailing: const AppIcon(Symbols.chevron_right_rounded, fill: 1),
onTap: () => unawaited(navigateToMediaItemDetails(context, match)),
);
@@ -617,23 +668,6 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
CatalogCreditRole.composer => t.explore.creditRole.composer,
};
static String? _ratingSourceLabel(String source) => switch (source) {
'critic' => t.explore.ratingSource.critic,
'audience' => t.explore.ratingSource.audience,
'imdb' => t.explore.ratingSource.imdb,
'tmdb' => t.explore.ratingSource.tmdb,
'rottenTomatoes' => t.explore.ratingSource.rottenTomatoes,
// Plex splits Rotten Tomatoes into its two panels, so both the provenance
// and the critic/audience distinction survive.
'rottenTomatoesCritic' => t.explore.ratingSource.rottenTomatoesCritic,
'rottenTomatoesAudience' => t.explore.ratingSource.rottenTomatoesAudience,
'simkl' => t.explore.ratingSource.simkl,
'mal' => t.explore.ratingSource.mal,
'anilist' => t.explore.ratingSource.anilist,
'trakt' => t.explore.ratingSource.trakt,
_ => null,
};
static String _relationLabel(CatalogRelationType type) => switch (type) {
CatalogRelationType.prequel => t.explore.relation.prequel,
CatalogRelationType.sequel => t.explore.relation.sequel,
@@ -795,9 +829,9 @@ class _CatalogItemDetailScreenState extends State<CatalogItemDetailScreen> {
Widget? _buildRatingsSection(ThemeData theme) {
final compact = NumberFormat.compact(locale: LocaleSettings.currentLocale.intlLocaleName);
final chips = <Widget>[];
for (final rating in _item.ratings ?? const <CatalogRatingSource>[]) {
final source = _ratingSourceLabel(rating.source);
final badge = catalogRatingInfo(rating.source, rating.value);
for (final rating in _item.ratings ?? const <MediaRatingSource>[]) {
final source = ratingSourceLabel(rating.source);
final badge = ratingInfoForSource(rating.source, rating.value);
if (source == null && badge == null) continue;
var label = badge == null ? '$source ${rating.value.toStringAsFixed(1)}' : badge.formattedValue;
if (rating.votes case final votes?) {
@@ -203,7 +203,7 @@ class _RemoteControlContentState extends State<_RemoteControlContent> {
),
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
padding: .fromLTRB(16, 16, 16, 16 + MediaQuery.paddingOf(context).bottom),
children: [
SegmentedButton<int>(
showSelectedIcon: false,
+16 -3
View File
@@ -600,6 +600,17 @@ class _DiscoverScreenState extends State<DiscoverScreen>
unawaited(_discover.load());
}
@override
void primeRefresh() {
// `initState` already fired `load()`. On cold start that pass is still
// running when the online-entry hook primes the tab, and asking again only
// queues an identical trailing pass — the whole home fan-out twice (#1784).
// When nothing is in flight (reconnect-from-offline, or a first pass that
// gave up because no server was online yet) a real refresh is still owed.
if (_discover.isLoadInFlight) return;
fullRefresh();
}
/// Whether the loaded hubs span more than one connected server.
bool _hubsSpanMultipleServers() {
final serverIds = _hubs.where((hub) => hub.serverId != null).map((hub) => hub.serverId).toSet();
@@ -652,12 +663,13 @@ class _DiscoverScreenState extends State<DiscoverScreen>
key: _userMenuKey,
enabled: !_switchingProfile,
icon: active != null
? ProfileAvatar(profile: active, size: 32)
? ProfileAvatar(profile: active, size: 32, avatarUrl: activeProvider.avatarUrlFor(active.id))
: const AppIcon(Symbols.account_circle_rounded, fill: 1, size: 32, color: Colors.white),
tooltip: t.profiles.sectionTitle,
anchorAlignment: AppMenuAnchorAlignment.end,
onSelected: (value) => unawaited(_handleUserMenuAction(context, value)),
entriesBuilder: (context) => _userMenuItems(context, activeProfile: active, profiles: profiles),
entriesBuilder: (context) =>
_userMenuItems(context, activeProfile: active, profiles: profiles, activeProvider: activeProvider),
),
);
}
@@ -666,6 +678,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
BuildContext context, {
required Profile? activeProfile,
required List<Profile> profiles,
required ActiveProfileProvider activeProvider,
}) {
final theme = Theme.of(context);
final switchable = profiles.where((p) => p.id != activeProfile?.id).toList();
@@ -674,7 +687,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
for (final p in switchable)
AppMenuItem<String>(
value: 'profile:${p.id}',
leading: ProfileAvatar(profile: p, size: 24),
leading: ProfileAvatar(profile: p, size: 24, avatarUrl: activeProvider.avatarUrlFor(p.id)),
label: p.displayName,
trailing: p.isPinProtected
? AppIcon(Symbols.lock_rounded, fill: 1, size: 14, color: theme.colorScheme.onSurfaceVariant)
@@ -13,6 +13,7 @@ import '../widgets/focusable_media_card.dart';
import '../widgets/media_card_sliver_layout.dart';
import '../widgets/overlay_sheet.dart';
import '../widgets/skeleton_media_card.dart';
import '../widgets/system_bottom_inset.dart';
/// Mixin that provides common focus navigation functionality for detail screens.
/// Handles app bar focus, back navigation, scroll-to-top, and grid item focus management.
@@ -86,7 +87,10 @@ mixin FocusableDetailScreenMixin<T extends StatefulWidget> on State<T>, GridFocu
/// host that defers route back to [handleBackNavigation], plus a Scaffold
/// with a CustomScrollView bound as the primary scroll view. Callers build
/// the slivers themselves (typically
/// `[appBar, ...header, ...buildStateSlivers(), grid]`).
/// `[appBar, ...header, ...buildStateSlivers(), grid]`); a trailing
/// [SliverSystemBottomInset] is appended so the last row clears the system
/// navigation bar. Screens that add their own trailing spacer (the music
/// detail screens reserve the floating mini-player) stack on top of it.
Widget buildDetailScaffold({required List<Widget> slivers}) {
return PrimaryScrollController(
controller: scrollController,
@@ -100,7 +104,9 @@ mixin FocusableDetailScreenMixin<T extends StatefulWidget> on State<T>, GridFocu
Navigator.pop(context);
}
},
child: Scaffold(body: CustomScrollView(primary: true, slivers: slivers)),
child: Scaffold(
body: CustomScrollView(primary: true, slivers: [...slivers, const SliverSystemBottomInset()]),
),
),
),
);
+2
View File
@@ -12,6 +12,7 @@ import '../media/media_server_client.dart';
import '../media/media_sort.dart';
import '../services/settings_service.dart';
import '../widgets/settings_builder.dart';
import '../widgets/system_bottom_inset.dart';
import '../utils/app_logger.dart';
import '../utils/continuation_pagination_coordinator.dart';
import '../utils/error_message_utils.dart';
@@ -611,6 +612,7 @@ class _HubDetailScreenState extends State<HubDetailScreen>
onNavigateUp: () => _focusNodeForIndex(_filteredItems.length - 1).requestFocus(),
onBack: handleBackFromContent,
),
const SliverSystemBottomInset(),
],
),
),
+16 -5
View File
@@ -520,7 +520,7 @@ class _MainScreenState extends State<MainScreen>
}
if (!mounted) return;
_fullRefreshContentTabs();
_primeContentTabs();
}
/// Single-shot "resume queued downloads once any client is online" rule,
@@ -1634,15 +1634,26 @@ class _MainScreenState extends State<MainScreen>
if (_screenKeys[tab]?.currentState case final T state) fn(state);
}
/// Full-refresh the primary content tabs. Shared by the online-entry hook
/// ([_primeOnlineServices]) and the profile-switch invalidation
/// ([_invalidateAllScreens]), which refresh the same set.
/// Full-refresh the primary content tabs. Used by the profile-switch
/// invalidation ([_invalidateAllScreens]), which must refetch everything for
/// the new identity.
void _fullRefreshContentTabs() {
for (final tab in const [NavigationTabId.discover, NavigationTabId.libraries, NavigationTabId.search]) {
for (final tab in _contentTabs) {
_onScreen<FullRefreshable>(tab, (screen) => screen.fullRefresh());
}
}
/// Online-entry variant used by [_primeOnlineServices] on cold start and on
/// reconnect-from-offline. Screens that already started their own load skip
/// it; see [FullRefreshable.primeRefresh].
void _primeContentTabs() {
for (final tab in _contentTabs) {
_onScreen<FullRefreshable>(tab, (screen) => screen.primeRefresh());
}
}
static const _contentTabs = [NavigationTabId.discover, NavigationTabId.libraries, NavigationTabId.search];
Widget _buildBottomNavigationBar(BuildContext context, {required bool hideLabels}) {
final tabs = _getBottomNavigationTabs(context);
final selectedIndex = tabs.indexWhere((tab) => tab.id == _currentTab);
+84 -123
View File
@@ -50,7 +50,6 @@ import '../services/plex_client.dart';
import '../media/media_server_client.dart';
import '../services/media_list_playback_launcher.dart';
import '../utils/content_utils.dart';
import '../utils/rating_utils.dart';
import '../models/download_models.dart';
import '../services/download_storage_service.dart';
import '../utils/download_version_utils.dart';
@@ -208,6 +207,12 @@ class _SeasonEpisodePager {
}
}
/// Identifies the TV reveal gate's opacity wrapper. The detail tree builds
/// other [AnimatedOpacity] widgets (the scroll-linked app-bar scrim is 0 at
/// rest), so tests must target this one specifically.
@visibleForTesting
const tvDetailRevealGateKey = ValueKey<String>('tvDetailRevealGate');
class MediaDetailScreen extends StatefulWidget {
final MediaItem metadata;
final bool isOffline;
@@ -838,6 +843,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
child: IgnorePointer(
ignoring: !revealed,
child: AnimatedOpacity(
// Keyed so tests can assert this specific gate rather than
// whichever AnimatedOpacity happens to be lowest on screen.
key: tvDetailRevealGateKey,
opacity: revealed ? 1 : 0,
duration: const Duration(milliseconds: 160),
curve: Curves.easeOutCubic,
@@ -961,59 +969,28 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
);
}
/// Build a rating chip that shows a source icon when available,
/// falling back to a generic Material icon.
Widget _buildRatingChip(String? imageUri, double value, IconData fallbackIcon) {
/// Every attributed score in one pill, then the tappable user-rating chip.
///
/// The scores share a single pill rather than taking a chip each: this row
/// is a height-clipped [Wrap], so a per-source chip would push the year,
/// certification, and runtime out of the visible band on short heroes.
List<Widget> _buildRatingChips(MediaItem metadata) {
final colorScheme = Theme.of(context).colorScheme;
final isTv = PlatformDetector.isTV();
return MediaRatingBadge.chip(
imageUri: imageUri,
value: value,
fallbackIcon: fallbackIcon,
foregroundColor: colorScheme.onSecondaryContainer,
backgroundColor: colorScheme.secondaryContainer.withValues(alpha: 0.8),
iconSize: isTv ? 20 : 16,
spacing: isTv ? 6 : 4,
padding: EdgeInsets.symmetric(horizontal: isTv ? 14 : 12, vertical: isTv ? 8 : 6),
textStyle: TextStyle(color: colorScheme.onSecondaryContainer, fontSize: isTv ? 16 : 13, fontWeight: .w600),
);
}
/// Build all rating chips for the metadata.
/// When both critic and audience ratings are from Rotten Tomatoes,
/// they are combined into a single badge.
List<Widget> _buildRatingChips(MediaItem metadata) {
final chips = <Widget>[];
// Plex-only fields (audienceRating / ratingImage / audienceRatingImage)
// — Jellyfin lacks rating-source attribution. Pull them via a typed
// narrow so the rest of the chip layout stays backend-neutral.
final plex = metadata is PlexMediaItem ? metadata : null;
final audienceRating = plex?.audienceRating;
final ratingImage = plex?.ratingImage;
final audienceRatingImage = plex?.audienceRatingImage;
final bothRT =
metadata.rating != null &&
audienceRating != null &&
isRottenTomatoes(ratingImage) &&
isRottenTomatoes(audienceRatingImage);
if (bothRT) {
chips.add(_buildCombinedRtChip(ratingImage, metadata.rating!, audienceRatingImage, audienceRating));
} else {
if (metadata.rating != null) {
chips.add(_buildRatingChip(ratingImage, metadata.rating!, Symbols.star_rounded));
}
if (audienceRating != null) {
chips.add(_buildRatingChip(audienceRatingImage, audienceRating, Symbols.people_rounded));
}
}
// User rating chip (tappable)
if (!widget.isOffline) {
chips.add(_buildUserRatingChip(metadata));
}
return chips;
return [
if (mediaRatingsFor(metadata).isNotEmpty)
MediaRatingBadgeGroup.chip(
item: metadata,
foregroundColor: colorScheme.onSecondaryContainer,
backgroundColor: colorScheme.secondaryContainer.withValues(alpha: 0.8),
iconSize: isTv ? 20 : 16,
spacing: isTv ? 6 : 4,
entrySpacing: isTv ? 12 : 10,
padding: EdgeInsets.symmetric(horizontal: isTv ? 14 : 12, vertical: isTv ? 8 : 6),
textStyle: TextStyle(color: colorScheme.onSecondaryContainer, fontSize: isTv ? 16 : 13, fontWeight: .w600),
),
if (!widget.isOffline) _buildUserRatingChip(metadata),
];
}
Widget _buildUserRatingChip(MediaItem metadata) {
@@ -1111,49 +1088,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
);
}
/// Build a combined RT chip showing critic + audience side by side.
Widget _buildCombinedRtChip(
String? criticImageUri,
double criticValue,
String? audienceImageUri,
double audienceValue,
) {
final colorScheme = Theme.of(context).colorScheme;
final textStyle = TextStyle(color: colorScheme.onSecondaryContainer, fontSize: 13, fontWeight: .w500);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: colorScheme.secondaryContainer.withValues(alpha: 0.8),
borderRadius: const BorderRadius.all(Radius.circular(100)),
),
child: Row(
mainAxisSize: .min,
children: [
MediaRatingBadge.inline(
imageUri: criticImageUri,
value: criticValue,
fallbackIcon: Symbols.star_rounded,
foregroundColor: colorScheme.onSecondaryContainer,
iconSize: 16,
spacing: 4,
textStyle: textStyle,
),
const SizedBox(width: 10),
MediaRatingBadge.inline(
imageUri: audienceImageUri,
value: audienceValue,
fallbackIcon: Symbols.people_rounded,
foregroundColor: colorScheme.onSecondaryContainer,
iconSize: 16,
spacing: 4,
textStyle: textStyle,
),
],
),
);
}
/// Backend-neutral counterpart of [getServerBoundPlexClient]. Returns a
/// [MediaServerClient] for Jellyfin items too, so image URLs use the
/// right server's transcoder.
@@ -1355,35 +1289,59 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
return;
}
final result = await client.fetchItemWithOnDeck(_metadata.id);
// Normalises a freshly fetched item against the row we navigated from
// (which owns serverId/library) and paints it. Called once from
// [onItemReady] on backends that learn the item before on-deck, and once
// from the settled result.
//
// [onDeckSettled] separates "on-deck not looked up yet" from "on-deck
// looked up and there is none". Only the settled call may write it, so
// the early paint leaves whatever is on screen alone — this method runs
// again after playback, and clearing there would blank the play button
// for the length of the on-deck round trip — while a reload that finds
// the series finished still clears it.
MediaItem publish(MediaItem source, {MediaItem? onDeckEpisode, bool onDeckSettled = false}) {
final serverId = _metadata.serverId;
final serverName = _metadata.serverName;
final base = _withFallbackLibrary(
source.copyWith(serverId: serverId ?? source.serverId, serverName: serverName ?? source.serverName),
_metadata,
);
final onDeckWithServerId = onDeckEpisode == null
? null
: _withFallbackLibrary(
onDeckEpisode.copyWith(
serverId: serverId ?? onDeckEpisode.serverId,
serverName: serverName ?? onDeckEpisode.serverName,
),
base,
);
setState(() {
_fullMetadata = base;
if (onDeckSettled) _onDeckEpisode = onDeckWithServerId;
_isLoadingMetadata = false;
});
return base;
}
// Jellyfin needs a second round trip for on-deck, which the screen does
// not need in order to paint. Publishing the item as soon as it lands
// takes that round trip off the critical path (#1784).
//
// Seasons/extras deliberately still start after the whole lookup
// settles: starting them at the early paint measured *worse*, because
// they contend with the on-deck request rather than overlapping it.
final result = await client.fetchItemWithOnDeck(
_metadata.id,
onItemReady: (item) {
if (mounted) publish(item);
},
);
final metadata = result.item;
final onDeckEpisode = result.onDeckEpisode;
if (!mounted) return;
// Preserve serverId from original metadata
final serverId = _metadata.serverId;
final serverName = _metadata.serverName;
final source = metadata ?? _metadata;
final base = _withFallbackLibrary(
source.copyWith(serverId: serverId ?? source.serverId, serverName: serverName ?? source.serverName),
_metadata,
);
final onDeckWithServerId = onDeckEpisode == null
? null
: _withFallbackLibrary(
onDeckEpisode.copyWith(
serverId: serverId ?? onDeckEpisode.serverId,
serverName: serverName ?? onDeckEpisode.serverName,
),
base,
);
setState(() {
_fullMetadata = base;
_onDeckEpisode = onDeckWithServerId;
_isLoadingMetadata = false;
});
final base = publish(metadata ?? _metadata, onDeckEpisode: result.onDeckEpisode, onDeckSettled: true);
if (base.isShow) {
unawaited(_loadSeasons());
@@ -3625,7 +3583,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final fields = _tvDetailMetadataParts<String>(
metadata,
text: (value) => value,
rating: (item) => MediaRatingBadge.semanticLabelForMedia(item, fallbackItem: metadata),
rating: (item) => MediaRatingBadgeGroup.semanticLabelForMedia(item, fallbackItem: metadata),
);
for (final field in fields) {
add(field);
@@ -3694,12 +3652,15 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final fields = _tvDetailMetadataParts<Widget>(
metadata,
text: (value) => Text(value, maxLines: 1, style: textStyle),
rating: (item) => MediaRatingBadge.inlineForMedia(
// Every score shares the one metadata slot, so the bullet separators
// don't multiply with the number of sources.
rating: (item) => MediaRatingBadgeGroup.inlineForMedia(
item: item,
fallbackItem: metadata,
foregroundColor: textStyle.color,
iconSize: textStyle.fontSize,
spacing: 4 * scale,
entrySpacing: 12 * scale,
textStyle: textStyle,
),
);
@@ -36,6 +36,7 @@ import '../focusable_detail_screen_mixin.dart';
import '../libraries/content_state_builder.dart';
import '../../mixins/grid_focus_node_mixin.dart';
import '../../widgets/overlay_sheet.dart';
import '../../widgets/system_bottom_inset.dart';
/// Screen to display the contents of a playlist
class PlaylistDetailScreen extends StatefulWidget {
@@ -757,6 +758,7 @@ class _PlaylistDetailScreenState extends BaseMediaListDetailScreen<PlaylistDetai
onBack: handleBackFromContent,
),
],
const SliverSystemBottomInset(),
],
);
@@ -10,6 +10,7 @@ import '../../i18n/strings.g.dart';
import '../../mixins/controller_disposer_mixin.dart';
import '../../models/plex/plex_home_user.dart';
import '../../profiles/active_profile_binder.dart';
import '../../profiles/active_profile_provider.dart';
import '../../profiles/plex_home_service.dart';
import '../../profiles/profile.dart';
import '../../profiles/profile_avatar.dart';
@@ -269,6 +270,7 @@ class _ProfileDetailScreenState extends State<ProfileDetailScreen> with Controll
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isLocal = _profile.isLocal;
final avatarUrl = context.watch<ActiveProfileProvider>().avatarUrlFor(_profile.id);
return FocusedScrollScaffold(
title: Text(_profile.displayName),
@@ -277,7 +279,9 @@ class _ProfileDetailScreenState extends State<ProfileDetailScreen> with Controll
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
sliver: SliverList(
delegate: SliverChildListDelegate([
Center(child: ProfileAvatar(profile: _profile, size: 96)),
Center(
child: ProfileAvatar(profile: _profile, size: 96, avatarUrl: avatarUrl),
),
const SizedBox(height: 24),
Text(t.profiles.profileNameLabel, style: theme.textTheme.labelLarge),
const SizedBox(height: 8),
@@ -266,6 +266,7 @@ class _ProfileSwitchScreenState extends State<ProfileSwitchScreen> with MountedS
child: _ProfileTile(
borderRadius: tileRadii,
profile: profile,
avatarUrl: view.avatarUrlByProfile[profile.id],
isActive: isActive && !widget.requireSelection,
chips: _chipsFor(profile, view),
onTap: () => _switchTo(profile),
@@ -363,6 +364,7 @@ class _ProfileSwitchScreenState extends State<ProfileSwitchScreen> with MountedS
class _ProfileTile extends StatelessWidget {
final Profile profile;
final String? avatarUrl;
final bool isActive;
final BorderRadius borderRadius;
final List<_ChipData> chips;
@@ -377,6 +379,7 @@ class _ProfileTile extends StatelessWidget {
const _ProfileTile({
required this.profile,
required this.avatarUrl,
required this.isActive,
required this.borderRadius,
required this.chips,
@@ -403,7 +406,7 @@ class _ProfileTile extends StatelessWidget {
padding: const EdgeInsets.all(12),
child: Row(
children: [
ProfileAvatar(profile: profile, size: 44),
ProfileAvatar(profile: profile, size: 44, avatarUrl: avatarUrl),
const SizedBox(width: 14),
Expanded(
child: Column(
+50 -1
View File
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:provider/provider.dart';
@@ -10,6 +12,7 @@ import '../media/media_item.dart';
import '../mixins/debounced_media_search.dart';
import '../mixins/mounted_set_state_mixin.dart';
import '../mixins/refreshable.dart';
import '../providers/hidden_libraries_provider.dart';
import '../providers/multi_server_provider.dart';
import '../services/data_aggregation_service.dart';
import '../utils/app_logger.dart';
@@ -38,10 +41,45 @@ class _SearchScreenState extends State<SearchScreen>
AbortController? _activeSearchAbort;
({String query, SearchAggregationResult result})? _pendingSearchOutcome;
HiddenLibrariesProvider? _hiddenLibraries;
Set<String> _lastSeenHiddenKeys = const {};
@override
void initState() {
super.initState();
FocusUtils.requestFocusAfterBuild(this, searchFocusNode);
unawaited(_bindHiddenLibraries());
}
@override
void dispose() {
_hiddenLibraries?.removeListener(_onHiddenLibrariesChanged);
super.dispose();
}
/// Re-run the visible query when a library is hidden or unhidden while
/// results are on screen. The listener is attached only after the provider
/// has hydrated, so its initial load notification cannot race the first
/// query — which awaits that same hydration — into running twice.
Future<void> _bindHiddenLibraries() async {
final hiddenLibraries = context.read<HiddenLibrariesProvider>();
await hiddenLibraries.ensureInitialized();
if (!mounted) return;
_lastSeenHiddenKeys = Set.of(hiddenLibraries.hiddenLibraryKeys);
_hiddenLibraries = hiddenLibraries..addListener(_onHiddenLibrariesChanged);
}
void _onHiddenLibrariesChanged() {
final hiddenLibraries = _hiddenLibraries;
if (hiddenLibraries == null || !mounted) return;
final currentKeys = hiddenLibraries.hiddenLibraryKeys;
if (currentKeys.length == _lastSeenHiddenKeys.length && currentKeys.containsAll(_lastSeenHiddenKeys)) {
return;
}
_lastSeenHiddenKeys = Set.of(currentKeys);
final query = searchController.text.trim();
if (query.isEmpty || !hasSearched) return;
unawaited(runSearch(query));
}
@override
@@ -54,10 +92,21 @@ class _SearchScreenState extends State<SearchScreen>
throw const _SearchUnavailableException();
}
// Hidden-library keys must be hydrated before the first query, or a cold
// start would filter nothing. Read before any await: the profile subtree
// can be torn down mid-search.
final hiddenLibraries = context.read<HiddenLibrariesProvider>();
await hiddenLibraries.ensureInitialized();
if (!mounted) return const [];
final abort = AbortController();
_activeSearchAbort = abort;
try {
final result = await multiServerProvider.aggregationService.searchAcrossServers(query, abort: abort);
final result = await multiServerProvider.aggregationService.searchAcrossServers(
query,
hiddenLibraryKeys: hiddenLibraries.hiddenLibraryKeys,
abort: abort,
);
abort.throwIfAborted();
if (result.succeededServerIds.isEmpty && result.failedServerIds.isNotEmpty) {
throw const _SearchUnavailableException();
@@ -461,7 +461,7 @@ class _AddJellyfinScreenState extends State<AddJellyfinScreen> with AsyncFormSta
SliverFillRemaining(
hasScrollBody: false,
child: Padding(
padding: const EdgeInsets.all(24),
padding: .fromLTRB(24, 24, 24, 24 + MediaQuery.paddingOf(context).bottom),
child: Center(child: _buildQuickConnectPanel(theme)),
),
)
@@ -138,7 +138,7 @@ class _AddPlexAccountScreenState extends State<AddPlexAccountScreen> with AsyncF
SliverFillRemaining(
hasScrollBody: false,
child: Padding(
padding: const EdgeInsets.all(24),
padding: .fromLTRB(24, 24, 24, 24 + MediaQuery.paddingOf(context).bottom),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 420),
+83 -46
View File
@@ -1,5 +1,4 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
@@ -19,44 +18,17 @@ import '../../utils/dialogs.dart';
import '../../main.dart' show gitCommit;
import '../../services/background_work_diagnostics_service.dart';
import '../../services/device_performance.dart';
import '../../services/log_upload_service.dart';
import '../../services/startup_diagnostics.dart';
import '../../utils/app_logger.dart';
import '../../utils/formatters.dart';
import '../../utils/platform_detector.dart';
import '../../utils/snackbar_helper.dart';
import '../../widgets/desktop_app_bar.dart';
import '../../widgets/ios_status_bar_tap_scroll_to_top.dart';
import '../../widgets/system_bottom_inset.dart';
/// Relay `/logs` accepts 1 MiB. The in-memory buffer intentionally remains
/// larger for local viewing and copying; uploads retain the device header and
/// newest log lines within this transport contract.
const int maxLogUploadBytes = 1 * 1024 * 1024;
String constrainLogUploadPayload({required String header, required String logs, int maxBytes = maxLogUploadBytes}) {
if (maxBytes <= 0) return '';
final headerBytes = utf8.encode(header);
if (headerBytes.length >= maxBytes) {
var end = maxBytes;
while (end > 0 && end < headerBytes.length && (headerBytes[end] & 0xC0) == 0x80) {
end--;
}
return utf8.decode(headerBytes.sublist(0, end));
}
final logBytes = utf8.encode(logs);
final availableLogBytes = maxBytes - headerBytes.length;
if (logBytes.length <= availableLogBytes) return '$header$logs';
var start = logBytes.length - availableLogBytes;
while (start < logBytes.length && (logBytes[start] & 0xC0) == 0x80) {
start++;
}
final nextLine = logBytes.indexOf(0x0A, start);
if (nextLine >= 0 && nextLine + 1 < logBytes.length) {
start = nextLine + 1;
}
return header + utf8.decode(logBytes.sublist(start));
}
const previousStartupFailureKey = Key('logs-previous-startup-failure');
class LogsScreen extends StatefulWidget {
const LogsScreen({super.key, this.httpClient, this.deviceInfoPlugin});
@@ -152,7 +124,20 @@ class _LogsScreenState extends State<LogsScreen> with MountedSetStateMixin {
return '$hour:$minute:$second.$millisecond';
}
void _clearLogs() {
/// Whether there is anything worth copying, uploading or clearing.
///
/// A launch that failed the startup gate leaves an empty in-memory buffer —
/// that process is gone — but does leave a persisted record. Gating the
/// actions on the buffer alone would show that record and then refuse to let
/// the user do anything with it, which is the whole point of #1732.
bool get _hasDiagnostics => _logs.isNotEmpty || StartupDiagnosticsStore.pending != null;
Future<void> _clearLogs() async {
// The startup record is part of the same diagnostic payload, so clearing
// logs drops it too, or it would silently reappear in the next upload.
// Awaited before rebuilding so the banner cannot survive the clear.
await StartupDiagnosticsStore.clear();
if (!mounted) return;
setState(() {
MemoryLogOutput.clearLogs();
_logs = [];
@@ -161,7 +146,14 @@ class _LogsScreenState extends State<LogsScreen> with MountedSetStateMixin {
}
String _formatAllLogs({int? maxBytes}) {
final header = _deviceInfo.isEmpty ? '' : '$_deviceInfo\n---\n';
final sections = <String>[
if (_deviceInfo.isNotEmpty) _deviceInfo,
// A launch that failed the startup gate leaves no in-memory log at all —
// the buffer died with that process. This is the only place its record
// can reach a maintainer (#1732).
?StartupDiagnosticsStore.pending?.describe(),
];
final header = sections.isEmpty ? '' : '${sections.join('\n\n')}\n---\n';
final logs = StringBuffer();
var isFirst = true;
for (final log in _logs.reversed) {
@@ -195,18 +187,11 @@ class _LogsScreenState extends State<LogsScreen> with MountedSetStateMixin {
showLoadingDialog(context);
try {
final response = await _httpClient.post(
'https://ice.plezy.app/logs',
body: logText,
headers: {'Content-Type': 'text/plain'},
);
final id = await uploadDiagnosticText(logText, client: _httpClient);
if (!mounted) return;
Navigator.of(context).pop(); // dismiss loading
final data = response.data is String ? jsonDecode(response.data) : response.data;
final id = (data as Map<String, dynamic>)['id'] as String;
unawaited(
showScopedDialog<void>(
context: context,
@@ -330,6 +315,50 @@ class _LogsScreenState extends State<LogsScreen> with MountedSetStateMixin {
return spans;
}
/// Banner for a startup failure recorded by an earlier launch.
///
/// Returns null when there is none, so the caller can splice it in with a
/// null-aware element.
Widget? _buildPreviousFailureBanner(ThemeData theme) {
final failure = StartupDiagnosticsStore.pending;
if (failure == null) return null;
return SliverToBoxAdapter(
key: previousStartupFailureKey,
child: Container(
margin: const EdgeInsets.fromLTRB(12, 12, 12, 0),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(color: theme.colorScheme.errorContainer, borderRadius: BorderRadius.circular(8)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
AppIcon(Symbols.error_rounded, size: 18, color: theme.colorScheme.onErrorContainer),
const SizedBox(width: 8),
Expanded(
child: Text(
t.startup.previousFailureTitle,
style: theme.textTheme.titleSmall?.copyWith(color: theme.colorScheme.onErrorContainer),
),
),
],
),
const SizedBox(height: 8),
SelectableText(
failure.describe(),
style: theme.textTheme.bodySmall?.copyWith(
fontFamily: 'monospace',
fontSize: 12,
color: theme.colorScheme.onErrorContainer,
),
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
@@ -369,25 +398,29 @@ class _LogsScreenState extends State<LogsScreen> with MountedSetStateMixin {
FocusableAction(
icon: Symbols.upload_rounded,
tooltip: t.logs.uploadLogs,
onPressed: _logs.isNotEmpty ? _uploadLogs : null,
onPressed: _hasDiagnostics ? _uploadLogs : null,
),
FocusableAction(
icon: Symbols.content_copy_rounded,
tooltip: t.logs.copyLogs,
onPressed: _logs.isNotEmpty ? _copyAllLogs : null,
onPressed: _hasDiagnostics ? _copyAllLogs : null,
),
FocusableAction(
icon: Symbols.delete_outline_rounded,
tooltip: t.logs.clearLogs,
onPressed: _logs.isNotEmpty ? _clearLogs : null,
onPressed: _hasDiagnostics ? _clearLogs : null,
),
],
),
],
),
// A launch that failed the startup gate leaves nothing in the
// in-memory buffer — that process is gone. Show its record
// here, where the user can actually act on it (#1732).
?_buildPreviousFailureBanner(theme),
if (_logs.isEmpty)
SliverFillRemaining(child: Center(child: Text(t.messages.noLogsAvailable)))
else
else ...[
SliverPadding(
padding: const EdgeInsets.all(12),
sliver: SliverToBoxAdapter(
@@ -403,6 +436,10 @@ class _LogsScreenState extends State<LogsScreen> with MountedSetStateMixin {
),
),
),
// Only the log body needs it: the empty state already fills
// the viewport, so a trailing inset would just add slack.
const SliverSystemBottomInset(),
],
],
),
),
@@ -43,6 +43,7 @@ import '../../widgets/overlay_sheet.dart';
import '../../widgets/setting_tile.dart';
import '../../widgets/settings_builder.dart';
import '../../widgets/settings_section.dart';
import '../../widgets/system_bottom_inset.dart';
import '../../profiles/active_profile_provider.dart';
import '../../profiles/profile.dart';
import '../../watch_together/services/watch_together_relay_endpoint.dart';
@@ -224,6 +225,7 @@ class _SettingsScreenState extends State<SettingsScreen> with FocusableTab, Moun
const SizedBox(height: 24),
]),
),
const SliverSystemBottomInset(),
],
),
),
+7 -3
View File
@@ -79,7 +79,7 @@ extension _VideoPlayerBuildMethods on VideoPlayerScreenState {
Widget _buildLoadingSpinner() {
return const Scaffold(
backgroundColor: Colors.black,
body: Center(child: CircularProgressIndicator(color: Colors.white)),
body: Center(child: PlayerLoadingIndicator()),
);
}
@@ -95,7 +95,7 @@ extension _VideoPlayerBuildMethods on VideoPlayerScreenState {
fit: StackFit.expand,
children: [
Video(player: bootstrapPlayer, hasFirstFrame: _hasFirstFrame),
const Center(child: CircularProgressIndicator(color: Colors.white)),
const Center(child: PlayerLoadingIndicator()),
],
);
}
@@ -186,7 +186,11 @@ extension _VideoPlayerBuildMethods on VideoPlayerScreenState {
final startZoom = _pinchStartZoomScale;
final filterManager = _videoFilterManager;
if (!_isPinchZooming || startZoom == null || filterManager == null) return;
final nextZoomScale = VideoFilterManager.normalizeZoomScale(startZoom * details.scale);
// Snap through 100% so pinching back undoes a zoom exactly, which is
// the touch path to an unzoomed picture (#1505).
final nextZoomScale = VideoFilterManager.normalizeZoomScale(
VideoFilterManager.snapPinchZoomScale(startZoom * details.scale),
);
if (!_pinchZoomChanged) {
if ((details.scale - 1.0).abs() <= _pinchZoomActivationThreshold) {
@@ -109,7 +109,20 @@ extension _VideoPlayerCompanionRemoteMethods on VideoPlayerScreenState {
if (!_subtitleCycleDrainActive) unawaited(_drainSubtitleCycles());
return;
}
_trackManager?.cycleSubtitleTrack();
_cycleSubtitleTrackNatively();
}
/// Cycle through the native track list, for playback with no source
/// catalog to advance through (downloads, and items whose server exposes no
/// subtitle rows).
///
/// The manager owns the selection and the server write-back; the committed
/// choice is this screen's, and the episode carry-over reads it, so a cycle
/// that lands on Off has to be recorded here or the next episode inherits
/// the choice this one started with.
void _cycleSubtitleTrackNatively() {
final cycled = _trackManager?.cycleSubtitleTrack();
if (cycled != null) _rememberNativeSubtitleSelection(cycled);
}
Future<void> _drainSubtitleCycles() async {
@@ -127,7 +140,7 @@ extension _VideoPlayerCompanionRemoteMethods on VideoPlayerScreenState {
if (_isOfflinePlayback || sourceTracks.isEmpty) {
_pendingSubtitleCycleCount -= advances;
for (var i = 0; i < advances; i++) {
_trackManager?.cycleSubtitleTrack();
_cycleSubtitleTrackNatively();
}
continue;
}
@@ -159,6 +159,8 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
hasCommittedSelection: committedSubtitleSelection != null,
committedTrack: committedSubtitleSelection?.primaryTrack,
nativeTrack: currentPlayer.state.track.subtitle,
declinedPreference: committedSubtitleSelection?.declinedPreference,
sessionPreference: _sessionSubtitlePreference,
);
final secondarySubtitlePreference = followServerSelections
? null
@@ -166,6 +168,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
hasCommittedSelection: committedSubtitleSelection != null,
committedTrack: committedSubtitleSelection?.secondaryTrack,
nativeTrack: currentPlayer.state.track.secondarySubtitle,
sessionPreference: _sessionSecondarySubtitlePreference,
);
await _reloadMediaInPlace(
metadata: episodeMetadata,
@@ -177,6 +180,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
// meaningless on the new item, so let preferences pick the track.
useCurrentAudioStreamSelection: false,
preserveCurrentTrackSelection: !followServerSelections,
preservedAudioTrack: _sessionAudioPreference,
preservedSubtitleTrack: primarySubtitlePreference,
preservedSecondarySubtitleTrack: secondarySubtitlePreference,
reason: 'episode navigation',
@@ -221,6 +225,28 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
player == currentPlayer &&
_ownsPlaybackTransition(transitionLease, expected: _PlaybackTransition.switchingSource);
bool sourceSwitchWasSuperseded() => !mounted || player != currentPlayer || transitionLease.wasSuperseded;
void rememberSourceAudioPreference() {
final streamId = newAudioStreamId;
final mediaInfo = _currentMediaInfo;
if (streamId == null || mediaInfo == null) return;
for (final row in mediaInfo.audioTracks) {
if (row.id == streamId) {
_sessionAudioPreference = PlaybackSubtitleResolver.audioTrackForSource(row);
return;
}
}
}
void rememberSourceSubtitlePreference() {
final choice = newSubtitleChoice;
final mediaInfo = _currentMediaInfo;
if (choice == null || mediaInfo == null) return;
// The local-switch path records through the screen's remember chain;
// this covers picks that had to reload, whose resolved outcome never
// reaches _rememberNativeSubtitleSelectionForSlot.
final preference = sessionPreferenceForSourceSubtitleChoice(choice, mediaInfo.subtitleTracks);
if (preference != null) _sessionSubtitlePreference = preference;
}
// Snapshot the backend client before subtitle selection can cross an
// async boundary or the profile-scoped context can disappear.
@@ -275,6 +301,8 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
final isAudioChange = effectiveAudioStreamId != _selectedAudioStreamId;
final isSubtitleChange = newSubtitleChoice != null && newSubtitleChoice != currentSubtitleChoice;
if (!isVersionChange && !isPresetChange && !isAudioChange && !isSubtitleChange) {
rememberSourceAudioPreference();
rememberSourceSubtitlePreference();
return PlaybackSourceChangeOutcome.unchanged;
}
@@ -322,6 +350,10 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
transitionLease: transitionLease,
reason: 'source switch',
);
if (outcome == _MediaReloadOutcome.opened) {
rememberSourceAudioPreference();
rememberSourceSubtitlePreference();
}
return switch (outcome) {
_MediaReloadOutcome.opened => PlaybackSourceChangeOutcome.applied,
_MediaReloadOutcome.rejected => PlaybackSourceChangeOutcome.busy,
@@ -561,6 +593,13 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
final initializationSubtitleTrack = preservesRequestedSubtitleSource
? currentSubtitleTrack
: SubtitlePreference.demoteToIntent(currentSubtitleTrack);
// Same boundary rule for audio: native and Jellyfin stream ids are
// reused per item, so a cross-source carry keeps only its semantics —
// an identity match against a reused id would latch by ordinal and
// bypass the evidence bands' ambiguity decline.
final initializationAudioTrack = preservesRequestedSubtitleSource || currentAudioTrack == null
? currentAudioTrack
: itemAgnosticAudioCarry(currentAudioTrack);
try {
// Eager identity-only: the loading UI shows the new title immediately,
// while the selection/source state flips with the session commit at
@@ -597,6 +636,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
preferredVersionSignature: preferredVersionSignature,
qualityPreset: targetQualityPreset,
selectedAudioStreamId: targetAudioStreamId,
preferredAudioTrack: initializationAudioTrack,
preferredSubtitleTrack: initializationSubtitleTrack,
sessionIdentifier: _playbackSessionIdentifier,
transcodeSessionId: _playbackTranscodeSessionId,
@@ -616,7 +656,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
var subtitleSelection = await _resolveSubtitleSelectionForOpen(
metadata: metadata,
result: result,
preferredAudioTrack: currentAudioTrack,
preferredAudioTrack: initializationAudioTrack,
preferredSubtitleTrack: currentSubtitleTrack,
preferredSecondarySubtitleTrack: currentSecondarySubtitleTrack,
preserveSubtitleSourceIdentity:
@@ -770,8 +810,12 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
metadata: metadata,
plexClient: plexClient,
getProfileSettings: () => userProfileProvider.profileSettings,
preferredAudioTrack: currentAudioTrack,
preferredSubtitleTrack: SubtitlePreference.trackOrNull(subtitleSelection.primaryTrack),
preferredAudioTrack: initializationAudioTrack,
// A declined carry stays alive for the native passes: freezing the
// resolver's off verdict here would turn a metadata mismatch into a
// navigation-priority off that no late track can undo (#1785).
preferredSubtitleTrack:
subtitleSelection.declinedPreference ?? SubtitlePreference.trackOrNull(subtitleSelection.primaryTrack),
preferredSecondarySubtitleTrack: SubtitlePreference.trackOrNull(subtitleSelection.secondaryTrack),
);
_trackManager = trackManager;
+39 -25
View File
@@ -14,43 +14,51 @@ extension _VideoPlayerErrorMethods on VideoPlayerScreenState {
appLogger.e('[Player ERROR] ${err.message}');
if (!mounted || _isExiting.value) return;
// Fatal, unrecoverable until server-side fix — show modal instead of a snackbar.
if (err.cause == PlayerError.serverHttp500 || _sawServer500) {
_hasFatalPlaybackError = true;
_progressTracker?.stopTracking();
unawaited(_showServerLimitDialog());
return;
}
// A sidecar subtitle fetch can also log a status, but it never raises the
// end-file error this handler is wired to, so a latched status belongs to
// the primary media open.
final action = resolvePlaybackFailureAction(
cause: err.cause,
fatalHttpStatuses: _fatalHttpStatuses,
isLive: widget.isLive,
liveRetrying: _live.retrying,
liveFallbackLevel: _live.fallbackLevel,
liveRetryFailed: _live.retryFailed,
);
// Live TV: retry with progressively degraded stream settings
// (mirrors Plex web client fallback chain).
if (widget.isLive) {
switch (action) {
// Both dialogs are unrecoverable until the server side changes, so they
// replace the snackbar rather than joining it.
case PlaybackFailureAction.serverLimitDialog:
_hasFatalPlaybackError = true;
_progressTracker?.stopTracking();
unawaited(_showServerLimitDialog());
case PlaybackFailureAction.mediaUnreadableDialog:
_hasFatalPlaybackError = true;
_progressTracker?.stopTracking();
unawaited(_showMediaUnreadableDialog());
// The bounded retry operation owns errors raised while applying/opening
// its replacement stream. Do not let the same error close the route.
if (_live.retrying) return;
if (_live.fallbackLevel < 2) {
case PlaybackFailureAction.ignore:
return;
case PlaybackFailureAction.liveRetry:
_live.fallbackLevel++;
_live.retrying = true;
appLogger.w('Live stream failed, retrying with fallback level ${_live.fallbackLevel}');
unawaited(_retryLiveStream());
return;
}
if (_live.retryFailed) {
case PlaybackFailureAction.liveInterrupted:
showGlobalErrorSnackBar(t.messages.liveStreamInterrupted);
return;
}
case PlaybackFailureAction.fatal:
_hasFatalPlaybackError = true;
_progressTracker?.stopTracking();
showGlobalErrorSnackBar(_redactPlayerError(_lastLogError ?? err.message));
unawaited(_handleBackButton());
}
_hasFatalPlaybackError = true;
_progressTracker?.stopTracking();
showGlobalErrorSnackBar(_redactPlayerError(_lastLogError ?? err.message));
unawaited(_handleBackButton());
}
void _onPlayerLog(PlayerLog log) {
if (!_sawServer500 && VideoPlayerScreenState._server500Pattern.hasMatch(log.text)) {
_sawServer500 = true;
}
final status = PlayerError.httpStatusFromLog(log.text);
if (status != null && fatalPlaybackHttpStatuses.contains(status)) _fatalHttpStatuses.add(status);
if (log.level == PlayerLogLevel.error || log.level == PlayerLogLevel.fatal) {
appLogger.e('[Player LOG ERROR] [${log.prefix}] ${log.text}');
_lastLogError = _redactPlayerError(log.text.trim());
@@ -65,6 +73,12 @@ extension _VideoPlayerErrorMethods on VideoPlayerScreenState {
if (mounted) unawaited(_handleBackButton());
}
Future<void> _showMediaUnreadableDialog() async {
if (!mounted) return;
await showMediaUnreadableDialog(context);
if (mounted) unawaited(_handleBackButton());
}
/// Handle notification when native player switched from ExoPlayer to MPV
Future<void> _onBackendSwitched() async {
_playerBackendLabel = 'mpv';
@@ -532,7 +532,7 @@ extension _VideoPlayerOpenMethods on VideoPlayerScreenState {
// that gets an HTTP error and the truncated body surfaces as a clean
// mid-file EOF (#1520 — PMS answers 503 while restarting/maintenance).
// Deliberately 503 only: a persistent 500 must keep failing fast so the
// server-limit dialog (_server500Pattern) appears promptly, and a
// server-limit dialog (_httpStatusPattern) appears promptly, and a
// multi-code list would need mpv's %len% quoting to survive the
// comma-separated option string. While ffmpeg retries, mpv reports
// buffering, which also makes the server-online reconnect hook in
@@ -105,7 +105,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
_errorSubscription = currentPlayer.streams.error.listen(_onPlayerError);
// warn is included so we can catch ffmpeg's "HTTP error 500" line in
// warn is included so we can catch ffmpeg's "HTTP error 4xx/5xx" line in
// _onPlayerLog — the error-level log that follows omits the status code.
_logSubscription = currentPlayer.streams.log
.where((log) => const {PlayerLogLevel.fatal, PlayerLogLevel.error, PlayerLogLevel.warn}.contains(log.level))
@@ -147,7 +147,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
_playbackRestartSubscription = currentPlayer.streams.playbackRestart.listen((_) async {
if (!mounted || player != currentPlayer) return;
_lastLogError = null;
_sawServer500 = false;
_fatalHttpStatuses.clear();
_live.fallbackLevel = 0;
_live.retryFailed = false;
final markFirstFrameReady = _markFirstFrameReady(currentPlayer, settingsService);
@@ -414,6 +414,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
mediaInfo: mediaInfo,
canReportPlayback: () => _hasRenderedFirstFrame && !_hasFatalPlaybackError,
hasRenderedPlayback: () => _hasRenderedFirstFrame,
subtitleOffIsDeliberate: () => _playbackSession?.subtitleSelection.declinedPreference == null,
onPausedKeepalive: mediaClient is PlexClient && effectivePlayMethod == 'Transcode'
? () => mediaClient.pingTranscodeSession(_playbackTranscodeSessionId)
: null,
@@ -123,6 +123,7 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
selectedMediaSourceId: _requestedMediaSourceId,
qualityPreset: _selectedQualityPreset,
selectedAudioStreamId: _selectedAudioStreamId,
preferredAudioTrack: _preferredAudioTrack,
preferredSubtitleTrack: _preferredSubtitleTrack,
sessionIdentifier: _playbackSessionIdentifier,
transcodeSessionId: _playbackTranscodeSessionId,
@@ -346,7 +347,10 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
plexClient: mediaClient is PlexClient ? mediaClient : null,
getProfileSettings: () => context.read<UserProfileProvider>().profileSettings,
preferredAudioTrack: _preferredAudioTrack,
preferredSubtitleTrack: SubtitlePreference.trackOrNull(subtitleSelection.primaryTrack),
// Same rule as the reload flow: a declined preference is retried by
// the native passes instead of being frozen into off (#1785).
preferredSubtitleTrack:
subtitleSelection.declinedPreference ?? SubtitlePreference.trackOrNull(subtitleSelection.primaryTrack),
preferredSecondarySubtitleTrack: SubtitlePreference.trackOrNull(subtitleSelection.secondaryTrack),
);
@@ -0,0 +1,61 @@
import '../../mpv/models.dart';
/// Highest fallback level the live-TV ladder will climb before giving up.
const int maxLiveFallbackLevel = 2;
/// What the player screen should do about one playback error.
enum PlaybackFailureAction {
/// Server rejected the session with HTTP 500 — a bandwidth/transcoding limit.
serverLimitDialog,
/// Server could not read the file behind the item (HTTP 404).
mediaUnreadableDialog,
/// A live retry already owns the player and its error UI.
ignore,
/// Climb one rung of the live-TV fallback ladder.
liveRetry,
/// Live ladder is exhausted and its last retry failed.
liveInterrupted,
/// Show the raw player error and leave the route.
fatal,
}
/// Decides what [cause] plus the statuses seen on this open mean for playback.
///
/// Pure so the policy is testable without a live player screen, mirroring
/// [runLiveStreamRetry]. [fatalHttpStatuses] is the set of
/// [fatalPlaybackHttpStatuses] entries the player's log stream reported.
///
/// Live TV deliberately diverges on 404: an HLS segment that has rolled off the
/// playlist, or a transcode session restarting under us, answers 404 mid-stream,
/// and the bounded ladder exists to ride that out. Only on-demand playback
/// treats 404 as terminal, where it does mean the file is unreadable. 500 stays
/// terminal for both — a limit rejection is not something a retry clears.
PlaybackFailureAction resolvePlaybackFailureAction({
required String? cause,
required Set<int> fatalHttpStatuses,
required bool isLive,
required bool liveRetrying,
required int liveFallbackLevel,
required bool liveRetryFailed,
}) {
if (cause == PlayerError.serverHttp500 || fatalHttpStatuses.contains(500)) {
return PlaybackFailureAction.serverLimitDialog;
}
if (!isLive && (cause == PlayerError.serverHttp404 || fatalHttpStatuses.contains(404))) {
return PlaybackFailureAction.mediaUnreadableDialog;
}
if (isLive) {
if (liveRetrying) return PlaybackFailureAction.ignore;
if (liveFallbackLevel < maxLiveFallbackLevel) return PlaybackFailureAction.liveRetry;
if (liveRetryFailed) return PlaybackFailureAction.liveInterrupted;
}
return PlaybackFailureAction.fatal;
}
@@ -46,6 +46,28 @@ class VideoPlayerMacPipPlaceholder extends StatelessWidget {
}
}
/// The player's loading spinner.
///
/// Labelled rather than silent: a bare [CircularProgressIndicator] contributes
/// no semantics at all, so a screen reader announced nothing while the picture
/// was still coming up. The label also makes "the first frame has not rendered
/// yet" an observable state instead of something inferred from the chrome,
/// which a television no longer raises on startup (#1765).
class PlayerLoadingIndicator extends StatelessWidget {
final double strokeWidth;
const PlayerLoadingIndicator({super.key, this.strokeWidth = 4});
@override
Widget build(BuildContext context) {
return CircularProgressIndicator(
color: Colors.white,
strokeWidth: strokeWidth,
semanticsLabel: t.videoControls.loadingVideo,
);
}
}
class VideoPlayerBufferingOverlay extends StatelessWidget {
final ValueListenable<bool> isBuffering;
final ValueListenable<bool> hasFirstFrame;
@@ -77,7 +99,7 @@ class VideoPlayerBufferingOverlay extends StatelessWidget {
child: Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.5), shape: BoxShape.circle),
child: const CircularProgressIndicator(color: Colors.white, strokeWidth: 3),
child: const PlayerLoadingIndicator(strokeWidth: 3),
),
),
),
+192 -41
View File
@@ -89,6 +89,7 @@ import 'video_player/frame_rate_matcher.dart';
import 'video_player/live_stream_retry.dart';
import 'video_player/live_timeline_report.dart';
import 'video_player/wakelock_controller.dart';
import 'video_player/playback_failure_action.dart';
import 'video_player/live_tv_session_args.dart';
import 'video_player/live_tv_session_state.dart';
import 'video_player/tv_background_suspend_policy.dart';
@@ -134,17 +135,40 @@ bool shouldAutoStartReloadedMedia({
required bool startPaused,
}) => wasPlayingBeforeReload && !watchTogetherOwnsStart && !startPaused;
/// Whether a freshly opened player route starts with its chrome up.
///
/// A television starts with the controls down. Auto-hide cannot even arm until
/// the first frame lands, so chrome raised by the route opening would park the
/// whole OSD and timebar over the first seconds of picture (#1765). The route
/// keeps its own loading surface and buffering overlay, the screen focus node
/// owns back, and the first D-pad press raises the chrome, so a remote loses
/// nothing. Pointer and touch platforms keep it: the viewer's hand is already
/// on the surface, and the title and back affordance belong over the spinner.
bool playerChromeStartsVisible({required bool isTv}) => !isTv;
/// Builds an item-agnostic subtitle preference for an episode replacement.
///
/// Source ids and sidecar URIs belong to the current media item. Only the
/// committed semantic choice — a [SubtitleIntent] — may cross the item
/// boundary; native state is a fallback for sessions created before
/// source-backed selection was recorded.
///
/// [sessionPreference] is the screen's last explicit viewer choice and wins
/// outright: automatic outcomes never overwrite it, so a catalog-gap episode
/// cannot reset the choice for the rest of the session.
///
/// [declinedPreference] is the committed selection's unserved carry: its off
/// is fallout from a metadata mismatch, not a viewer choice, so it must not
/// harden into an explicit off on the next item (#1785).
SubtitlePreference? subtitlePreferenceForItemChange({
required bool hasCommittedSelection,
required SubtitleTrack? committedTrack,
required SubtitleTrack? nativeTrack,
SubtitlePreference? declinedPreference,
SubtitlePreference? sessionPreference,
}) {
final sessionIntent = SubtitlePreference.demoteToIntent(sessionPreference);
if (sessionIntent != null) return sessionIntent;
SubtitlePreference? normalize(SubtitleTrack? track, {required bool preserveOff}) {
if (track == null) return null;
if (track.id == SubtitleTrack.off.id) return preserveOff ? const SubtitlePreference.off() : null;
@@ -157,6 +181,15 @@ SubtitlePreference? subtitlePreferenceForItemChange({
return normalize(nativeTrack, preserveOff: true);
}
final committedIsOff = committedTrack == null || committedTrack.id == SubtitleTrack.off.id;
if (declinedPreference != null && committedIsOff) {
// Live native state wins — a late native pass may have served the
// declined carry — otherwise the declined preference itself keeps
// crossing item boundaries until the viewer or a richer catalog
// settles it.
return normalize(nativeTrack, preserveOff: false) ?? SubtitlePreference.demoteToIntent(declinedPreference);
}
if (committedTrack == null) return const SubtitlePreference.off();
final committedPreference = normalize(committedTrack, preserveOff: true);
@@ -164,6 +197,59 @@ SubtitlePreference? subtitlePreferenceForItemChange({
return normalize(nativeTrack, preserveOff: false);
}
/// Builds the committed [PlaybackSubtitleSelection] for a user's subtitle
/// pick in one slot, leaving the other slot untouched.
///
/// [sourceTrack] and [sidecar] are null when the pick has no source-catalog
/// identity — items without subtitle rows, or a native track the identity
/// matcher cannot map. The raw native [track] is committed then (without
/// source ids), so the session still reflects what is on screen and the next
/// item boundary demotes it to a semantic intent instead of hardening the
/// stale previous selection into an explicit off (#1785).
PlaybackSubtitleSelection subtitleSelectionForUserPick({
required PlaybackSubtitleSelection currentSelection,
required bool isPrimarySlot,
required SubtitleTrack track,
MediaSubtitleTrack? sourceTrack,
PlaybackSubtitleSidecar? sidecar,
}) {
final resolvedTrack = sourceTrack == null
? track
: PlaybackSubtitleResolver.subtitleTrackForSource(sourceTrack, sidecar: sidecar);
return PlaybackSubtitleSelection(
primaryTrack: isPrimarySlot ? resolvedTrack : currentSelection.primaryTrack,
primarySourceStreamId: isPrimarySlot ? sourceTrack?.id : currentSelection.primarySourceStreamId,
primarySidecar: isPrimarySlot ? sidecar : currentSelection.primarySidecar,
secondaryTrack: isPrimarySlot ? currentSelection.secondaryTrack : resolvedTrack,
secondarySourceStreamId: isPrimarySlot ? currentSelection.secondarySourceStreamId : sourceTrack?.id,
secondarySidecar: isPrimarySlot ? currentSelection.secondarySidecar : sidecar,
// A primary pick is a decision that retires any unresolved carry; a
// secondary-only change must not relabel the primary's declined off as
// deliberate (that would persist -1 and harden the next boundary).
declinedPreference: isPrimarySlot ? null : currentSelection.declinedPreference,
);
}
/// Session-preference form of a source-catalog subtitle choice that had to
/// go through a reload instead of a local track switch.
///
/// The authoritative row — not the reload's outcome — becomes the session
/// preference: a failed resolution must not turn the viewer's pick into a
/// carried off. Returns null when the row is absent from [rows] so a stale
/// id never overwrites the existing session preference.
SubtitlePreference? sessionPreferenceForSourceSubtitleChoice(
PlaybackSourceSubtitleChoice choice,
List<MediaSubtitleTrack> rows,
) {
if (choice.isOff) return const SubtitlePreference.off();
for (final row in rows) {
if (row.id == choice.sourceStreamId) {
return SubtitlePreference.track(PlaybackSubtitleResolver.subtitleTrackForSource(row));
}
}
return null;
}
/// The in-place media-source transitions a [VideoPlayerScreenState] can run.
/// They are mutually exclusive by construction — entry points bail while a
/// transition is in flight.
@@ -250,8 +336,7 @@ _PlaybackOpenTiming _playbackOpenTiming({
/// change should not silently rewrite the whole series' Plex prefs. The
/// explicit path for that lives in the metadata-edit UI.
TrackPreferencePersister _plexTrackPersister(PlexClient? Function() resolve) {
return ({required int partId, required String trackType, int? streamID}) async {
if (streamID == null) return;
return ({required int partId, required String trackType, required int streamID}) async {
final client = resolve();
if (client == null) return;
await (trackType == 'audio'
@@ -367,6 +452,14 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
AudioTrack? _preferredAudioTrack;
SubtitlePreference? _preferredSubtitleTrack;
SubtitlePreference? _preferredSecondarySubtitleTrack;
/// Last explicit track choices made on this screen. They survive in-place
/// reloads but not route replacement. Automatic selections never overwrite
/// them, so an episode with a catalog gap cannot reset the viewer's choice
/// for the rest of the session (#1785).
AudioTrack? _sessionAudioPreference;
SubtitlePreference? _sessionSubtitlePreference;
SubtitlePreference? _sessionSecondarySubtitlePreference;
bool _serverSupportsTranscoding = false;
// Kicked off early in the player initialization attempt for online non-live playback so
// the metadata fetch (and transcode-decision HTTP, if non-original preset)
@@ -465,6 +558,14 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
// key events never escape the video player route.
late final FocusNode _screenFocusNode;
/// Key for a context below this screen's own [OverlaySheetHost]. The State's
/// context sits ABOVE the host, so resolving the controller with `context`
/// always misses it and the screen would walk its back pipeline (hide chrome,
/// then exit the player) while a sheet is still open (#1741).
final GlobalKey _overlayChildKey = GlobalKey();
BuildContext get _sheetContext => _overlayChildKey.currentContext ?? context;
// VLC-style in-player toast controller (rate changes, backend switch, etc.).
final PlayerToastController _toastController = PlayerToastController();
bool _reclaimingFocus = false;
@@ -728,7 +829,15 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
bool _hasFatalPlaybackError = false;
final ValueNotifier<bool> _isExiting = ValueNotifier<bool>(false);
final PlayerChromeController _chromeController = PlayerChromeController();
final PlayerChromeController _chromeController = PlayerChromeController(
initiallyVisible: playerChromeStartsVisible(isTv: PlatformDetector.isTV()),
);
/// Lets startup-policy coverage assert the chrome this route actually opened
/// with, rather than a controller the test seeded itself.
@visibleForTesting
PlayerChromeController get chromeController => _chromeController;
late final PlayerNavigationCoordinator _playerNavigationCoordinator;
@override
@@ -1074,6 +1183,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
preferredVersionSignature: widget.preferredVersionSignature,
qualityPreset: _selectedQualityPreset,
selectedAudioStreamId: _selectedAudioStreamId,
preferredAudioTrack: _preferredAudioTrack,
preferredSubtitleTrack: _preferredSubtitleTrack,
sessionIdentifier: _playbackSessionIdentifier,
transcodeSessionId: _playbackTranscodeSessionId,
@@ -1134,6 +1244,11 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
await currentPlayer.setProperty('demuxer-max-bytes', '${autoForwardMB * 1024 * 1024}');
await currentPlayer.setProperty('demuxer-max-back-bytes', '${autoBackMB * 1024 * 1024}');
// These tiers size mpv's demuxer. ExoPlayer's LoadControl allocator is a
// different consumer — a flat byte cap there collapses to a few seconds of
// read-ahead on a 100 Mbps remux — so let the native side derive its own
// target on Auto (#1618).
await currentPlayer.setProperty('demuxer-max-bytes-auto', 'yes');
} else {
// Manual mode: cap back-buffer relative to heap if 1/4 ratio is too high
final maxBackBytes = min(bufferSizeMB * 1024 * 1024 ~/ 4, autoBackMB * 1024 * 1024);
@@ -1448,7 +1563,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
void _handleScreenPlayerNavigation(PlayerNavigationKey navigationKey) {
if (navigationKey != PlayerNavigationKey.home) {
final sheetController = OverlaySheetController.maybeOf(context);
final sheetController = OverlaySheetController.maybeOf(_sheetContext);
if (sheetController?.isOpen ?? false) {
sheetController!.pop();
return;
@@ -1772,9 +1887,12 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
String? _lastLogError;
bool _sawServer500 = false;
static final RegExp _server500Pattern = RegExp(r'\b(?:HTTP error |Response code: )500\b');
/// Statuses in [fatalPlaybackHttpStatuses] the player's own log stream
/// reported for this open. Each latches independently: the reconnect path
/// deliberately retries a 503 (see `_applyNetworkStreamTuning`), and a
/// transient status must never mask the fatal one that follows.
final Set<int> _fatalHttpStatuses = <int>{};
// OS Media Controls Integration
@@ -1812,7 +1930,12 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
}
Future<void> _onAudioTrackChanged(AudioTrack track) async => _trackManager?.onAudioTrackSelectedByUser(track);
Future<void> _onAudioTrackChanged(AudioTrack track) async {
if (track.id != AudioTrack.auto.id && track.id != AudioTrack.off.id) {
_sessionAudioPreference = track;
}
await _trackManager?.onAudioTrackSelectedByUser(track);
}
Future<void> _onSubtitleTrackChanged(SubtitleTrack track, {int? sourceStreamId}) async {
_rememberNativeSubtitleSelection(track, sourceStreamId: sourceStreamId);
@@ -1837,25 +1960,37 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
required _SubtitleSelectionSlot slot,
int? sourceStreamId,
}) {
final session = _playbackSession;
if (session == null) return;
final currentSelection = session.subtitleSelection;
if (track.id == SubtitleTrack.off.id) {
switch (slot) {
case _SubtitleSelectionSlot.primary:
_sessionSubtitlePreference = const SubtitlePreference.off();
case _SubtitleSelectionSlot.secondary:
_sessionSecondarySubtitlePreference = const SubtitlePreference.off();
}
final session = _playbackSession;
if (session == null) return;
final currentSelection = session.subtitleSelection;
_updatePlaybackSessionSubtitleSelection(session, switch (slot) {
_SubtitleSelectionSlot.primary => const PlaybackSubtitleSelection.off(),
// Dropping only the secondary must not relabel the primary's
// declined off as deliberate.
_SubtitleSelectionSlot.secondary => PlaybackSubtitleSelection(
primaryTrack: currentSelection.primaryTrack,
primarySourceStreamId: currentSelection.primarySourceStreamId,
primarySidecar: currentSelection.primarySidecar,
declinedPreference: currentSelection.declinedPreference,
),
});
if (mounted) _setPlayerState(() {});
return;
}
final session = _playbackSession;
if (session == null) return;
final currentSelection = session.subtitleSelection;
final info = _currentMediaInfo;
final currentPlayer = player;
if (info == null || currentPlayer == null) return;
MediaSubtitleTrack? sourceTrack;
final currentSourceId = switch (slot) {
@@ -1866,42 +2001,57 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_SubtitleSelectionSlot.primary => currentSelection.primarySidecar,
_SubtitleSelectionSlot.secondary => currentSelection.secondarySidecar,
};
if (sourceStreamId != null) {
for (final candidate in info.subtitleTracks) {
if (candidate.id == sourceStreamId) {
sourceTrack = candidate;
break;
if (info != null) {
if (sourceStreamId != null) {
for (final candidate in info.subtitleTracks) {
if (candidate.id == sourceStreamId) {
sourceTrack = candidate;
break;
}
}
} else if (track.isExternal && currentSourceId != null && currentSidecar?.track.uri == track.uri) {
for (final candidate in info.subtitleTracks) {
if (candidate.id == currentSourceId) {
sourceTrack = candidate;
break;
}
}
}
} else if (track.isExternal && currentSourceId != null && currentSidecar?.track.uri == track.uri) {
for (final candidate in info.subtitleTracks) {
if (candidate.id == currentSourceId) {
sourceTrack = candidate;
break;
}
if (sourceTrack == null && currentPlayer != null) {
sourceTrack = findPlexTrackForMpvSubtitle(
track,
info.subtitleTracks,
allMpvTracks: currentPlayer.state.tracks.subtitle,
);
}
}
sourceTrack ??= findPlexTrackForMpvSubtitle(
track,
info.subtitleTracks,
allMpvTracks: currentPlayer.state.tracks.subtitle,
);
if (sourceTrack == null) return;
final sidecar = _sidecarForSourceStreamId(session, sourceTrack.id);
final resolvedTrack = PlaybackSubtitleResolver.subtitleTrackForSource(sourceTrack, sidecar: sidecar);
final selection = PlaybackSubtitleSelection(
primaryTrack: slot == _SubtitleSelectionSlot.primary ? resolvedTrack : currentSelection.primaryTrack,
primarySourceStreamId: slot == _SubtitleSelectionSlot.primary
? sourceTrack.id
: currentSelection.primarySourceStreamId,
primarySidecar: slot == _SubtitleSelectionSlot.primary ? sidecar : currentSelection.primarySidecar,
secondaryTrack: slot == _SubtitleSelectionSlot.secondary ? resolvedTrack : currentSelection.secondaryTrack,
secondarySourceStreamId: slot == _SubtitleSelectionSlot.secondary
? sourceTrack.id
: currentSelection.secondarySourceStreamId,
secondarySidecar: slot == _SubtitleSelectionSlot.secondary ? sidecar : currentSelection.secondarySidecar,
// No source identity (no catalog, or a native track the identity matcher
// cannot map) still commits the raw pick: an uncommitted selection reads
// as the session's previous choice — usually the initial off — and the
// next episode boundary would harden that into an explicit off while the
// viewer visibly watches with subtitles on (#1785). The raw track carries
// no source ids, so it demotes to a semantic intent at the boundary.
final sidecar = sourceTrack == null ? null : _sidecarForSourceStreamId(session, sourceTrack.id);
final selection = subtitleSelectionForUserPick(
currentSelection: currentSelection,
isPrimarySlot: slot == _SubtitleSelectionSlot.primary,
track: track,
sourceTrack: sourceTrack,
sidecar: sidecar,
);
final resolvedTrack = switch (slot) {
_SubtitleSelectionSlot.primary => selection.primaryTrack,
_SubtitleSelectionSlot.secondary => selection.secondaryTrack,
};
if (resolvedTrack != null) {
switch (slot) {
case _SubtitleSelectionSlot.primary:
_sessionSubtitlePreference = SubtitlePreference.track(resolvedTrack);
case _SubtitleSelectionSlot.secondary:
_sessionSecondarySubtitlePreference = SubtitlePreference.track(resolvedTrack);
}
}
_updatePlaybackSessionSubtitleSelection(session, selection);
if (mounted) _setPlayerState(() {});
}
@@ -1989,6 +2139,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_handleScreenPlayerNavigation(PlayerNavigationKey.back);
},
child: Builder(
key: _overlayChildKey,
builder: (sheetContext) => _isPlayerInitialized && player != null
? _buildVideoPlayer(sheetContext)
: (_playerInitializationError != null
@@ -1,8 +1,13 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences/util/legacy_to_async_migration_util.dart';
import '../utils/app_logger.dart';
import 'prefs_recovery.dart';
import 'sensitive_prefs.dart';
/// Base class for services that use SharedPreferences singleton pattern.
///
/// This class handles the boilerplate for singleton initialization and
@@ -81,6 +86,30 @@ abstract class BaseSharedPreferencesService {
}
static Future<SharedPreferencesWithCache> _loadSharedCache() async {
// Validate before the plugin reads anything: the desktop backends memoise
// the document they parse and never re-read it, so a store rejected only
// after the fact could not be repaired in-process (#1732).
await PrefsRecovery.assertStoreReadable();
try {
return await _openSharedCache();
} catch (error, stackTrace) {
// The preflight accepted this document and the plugin still rejected it.
// Classify by re-reading the bytes, never by the error's type: the
// desktop backends surface a UTF-8 decode failure as a
// `FileSystemException`, which is indistinguishable from a denied or
// locked file, and a permission error must never be offered a
// destructive repair. A null result means the document on disk is fine,
// so whatever went wrong keeps its own type and its own path.
final damage = await PrefsRecovery.describeCurrentStoreDamage(reopenSafe: false);
if (damage == null) rethrow;
// The plugin has now cached something we cannot reason about. Repair can
// still quarantine the file, but the process has to restart afterwards.
appLogger.e('Preference store could not be parsed', error: error, stackTrace: stackTrace);
throw damage;
}
}
static Future<SharedPreferencesWithCache> _openSharedCache() async {
final legacy = await SharedPreferences.getInstance();
await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary(
legacySharedPreferencesInstance: legacy,
@@ -90,6 +119,123 @@ abstract class BaseSharedPreferencesService {
return SharedPreferencesWithCache.create(cacheOptions: const SharedPreferencesWithCacheOptions());
}
/// Quarantines an *unparseable* store, opens a fresh one and reseeds every
/// credential that could be salvaged.
///
/// Never call this without an explicit user decision: it resets settings,
/// and any credential that could not be salvaged is gone. The salvaged vault
/// key is written before this future completes, which is what makes the
/// reseed safe — `CredentialVault` memoises the first key it sees, so a
/// single read landing before the seed would generate a replacement and
/// permanently orphan every token stored in the database. Nothing can read
/// preferences until [sharedCache] resolves, so doing the work here closes
/// that window entirely.
///
/// Only valid for [CorruptPreferenceStoreException]. The desktop plugins
/// memoise the parsed document in a private `_cachedPreferences` map and
/// never re-read it without an explicit reload; that map is only empty here
/// because the parse threw before it could be populated. Use
/// [dropUnreadableCredential] for a store that parsed but holds one
/// unreadable value — quarantining that one would reopen onto the stale
/// in-memory map and write the bad value straight back.
static Future<PrefsRepairOutcome> repairCorruptStore({bool reopenSafe = true}) async {
final (:salvaged, :backupPath, :shape) = await PrefsRecovery.quarantine();
// Conservative by construction: the warning is dropped only for bytes
// proven to contain nothing. What the salvage recovered cannot stand in
// for that — a store truncated mid-value matches no entry at all while
// still holding most of a vault key in plaintext.
final backupHoldsCredentials = !(shape?.allZero ?? false);
_resetGeneration++;
_initializations.clear();
_instances.clear();
if (!reopenSafe) {
// The plugin memoised the bad document before it threw, so reopening
// would hand that copy back and the first write would persist it over
// the repaired file. Write the salvage straight to disk for the next
// process instead, and leave this one's store closed.
//
// Nothing may write a preference before that restart or the plugin's
// stale map would overwrite the seed; the caller keeps the app on the
// failure screen precisely so nothing does.
final seeded = await PrefsRecovery.seedStore(salvaged);
appLogger.w('Preference store quarantined; a restart is required before it can be reopened');
return PrefsRepairOutcome(
backupPath: backupPath,
backupHoldsCredentials: backupHoldsCredentials,
vaultKeySalvaged: seeded && salvaged.vaultKey != null,
sessionsSalvaged: seeded ? salvaged.sessions.length : 0,
sessionsLost: seeded ? salvaged.losses : salvaged.losses + salvaged.sessions.length,
requiresRestart: true,
);
}
_cacheFuture = null;
late final Future<SharedPreferencesWithCache> repaired;
repaired = _cacheLoader()
.then((cache) async {
final vaultKey = salvaged.vaultKey;
if (vaultKey != null) await cache.setString(credentialVaultKeyPref, vaultKey);
for (final entry in salvaged.sessions.entries) {
await cache.setString(entry.key, entry.value);
}
return cache;
})
.onError<Object>((error, stackTrace) {
// The same self-healing reset `sharedCache` installs, for the same
// reason. Without it a reopen that fails *after* the store was
// already quarantined would leave a permanently rejected future in
// `_cacheFuture`, and every later retry would replay that stale error
// for the rest of the process — with the on-disk cause already gone.
if (identical(_cacheFuture, repaired)) _cacheFuture = null;
Error.throwWithStackTrace(error, stackTrace);
});
_cacheFuture = repaired;
await repaired;
return PrefsRepairOutcome(
backupPath: backupPath,
backupHoldsCredentials: backupHoldsCredentials,
vaultKeySalvaged: salvaged.vaultKey != null,
sessionsSalvaged: salvaged.sessions.length,
sessionsLost: salvaged.losses,
);
}
/// Removes one credential preference whose stored type is unreadable.
///
/// The store itself parsed here, so the plugin's `_cachedPreferences` map is
/// already populated and a quarantine-and-reopen would hand back that stale
/// map and persist the bad value again. Delete through the live cache
/// instead: that updates both the in-memory map and the file, and leaves
/// every other credential in place.
///
/// The file is *copied* first, not moved — it is still the app's live store,
/// and the copy is the only record of the pre-repair state.
static Future<PrefsRepairOutcome> dropUnreadableCredential(String key) async {
final backupPath = await PrefsRecovery.backupStore();
final cache = await sharedCache();
await cache.remove(key);
// Force `onInit` to run again against the repaired store; the cache future
// stays as-is because the store was never reopened.
_resetGeneration++;
_initializations.clear();
_instances.clear();
appLogger.w('Removed unreadable credential preference "$key"');
return PrefsRepairOutcome(
backupPath: backupPath,
// The vault key survives unless it was the unreadable value itself.
vaultKeySalvaged: key != credentialVaultKeyPref,
sessionsSalvaged: 0,
sessionsLost: key == credentialVaultKeyPref ? 0 : 1,
settingsReset: false,
);
}
@visibleForTesting
static void setCacheLoaderForTesting(Future<SharedPreferencesWithCache> Function() loader) {
_cacheFuture = null;
@@ -108,13 +254,40 @@ abstract class BaseSharedPreferencesService {
_cacheLoader = _loadSharedCache;
}
/// Reads a stored value, tolerating one whose type no longer matches the
/// declaration.
///
/// `SharedPreferencesWithCache.getX` is an `as T?` cast, so a value written
/// by an older build, hand-edited, or partially recovered throws `TypeError`
/// rather than returning null. A value we cannot read is indistinguishable
/// from one that was never written, so drop the key and fall back to the
/// declared default instead of letting it propagate — before #1732 a single
/// mistyped preference could fail the entire startup gate.
///
/// Credential slots are exempt: silently dropping one would sign the user
/// out with no explanation. Those raise
/// [UnreadableSensitivePreferenceException], which the startup gate
/// classifies as repairable so the user gets the same consented repair as an
/// unparseable store.
T? _readTolerant<T>(String key, T? Function() read) => readPreferenceTolerantly(_cache, key, read);
/// Nullable reads routed through [readPreferenceTolerantly]. Use these
/// instead of `prefs.getX(...)` wherever a mistyped stored value must not
/// throw — which is everywhere except a call site that deliberately probes
/// two types to migrate between them.
String? readNullableString(String key) => readTolerantString(_cache, key);
bool? readNullableBool(String key) => _readTolerant(key, () => _cache.getBool(key));
int? readNullableInt(String key) => _readTolerant(key, () => _cache.getInt(key));
/// Typed read helpers — return the stored value or [defaultValue] when missing.
bool readBool(String key, {bool defaultValue = false}) => _cache.getBool(key) ?? defaultValue;
int readInt(String key, {int defaultValue = 0}) => _cache.getInt(key) ?? defaultValue;
double readDouble(String key, {double defaultValue = 0.0}) => _cache.getDouble(key) ?? defaultValue;
String readString(String key, {String defaultValue = ''}) => _cache.getString(key) ?? defaultValue;
bool readBool(String key, {bool defaultValue = false}) =>
_readTolerant(key, () => _cache.getBool(key)) ?? defaultValue;
int readInt(String key, {int defaultValue = 0}) => _readTolerant(key, () => _cache.getInt(key)) ?? defaultValue;
double readDouble(String key, {double defaultValue = 0.0}) =>
_readTolerant(key, () => _cache.getDouble(key)) ?? defaultValue;
String readString(String key, {String defaultValue = ''}) => readNullableString(key) ?? defaultValue;
List<String> readStringList(String key, {List<String> defaultValue = const []}) =>
_cache.getStringList(key) ?? defaultValue;
_readTolerant(key, () => _cache.getStringList(key)) ?? defaultValue;
/// Typed write helpers — symmetric with the read helpers above; use these
/// instead of `prefs.setX(...)` so call sites stay terse.
@@ -277,7 +450,7 @@ class NullableStringPref extends Pref<String?> {
final String? Function(String?)? transform;
const NullableStringPref(super.key, {this.transform});
@override
String? readFrom(BaseSharedPreferencesService svc) => svc.prefs.getString(key);
String? readFrom(BaseSharedPreferencesService svc) => svc.readNullableString(key);
@override
Future<void> writeTo(BaseSharedPreferencesService svc, String? value) async {
final normalized = transform == null ? value : transform!(value);
@@ -313,7 +486,7 @@ class EnumPref<T extends Enum> extends Pref<T> {
T get _default => defaultValueProvider?.call() ?? defaultValue!;
@override
T readFrom(BaseSharedPreferencesService svc) {
final stored = svc.prefs.getString(key);
final stored = svc.readNullableString(key);
if (stored == null) return _default;
return values.firstWhere((v) => v.name == stored, orElse: () => _default);
}
@@ -332,7 +505,7 @@ class JsonPref<T> extends Pref<T> {
@override
T readFrom(BaseSharedPreferencesService svc) {
final s = svc.prefs.getString(key);
final s = svc.readNullableString(key);
if (s == null) return defaultValue;
try {
return decode(json.decode(s));
@@ -344,3 +517,43 @@ class JsonPref<T> extends Pref<T> {
@override
Future<void> writeTo(BaseSharedPreferencesService svc, T value) => svc.writeString(key, encode(value));
}
/// Reads a preference, tolerating a stored value whose type no longer matches
/// the declaration.
///
/// `SharedPreferencesWithCache.getX` is an `as T?` cast, so a value written by
/// an older build, hand-edited, or partially recovered throws `TypeError`
/// rather than returning null. A value we cannot read is indistinguishable
/// from one that was never written, so drop the key and fall back to the
/// declared default instead of letting it propagate — before #1732 a single
/// mistyped preference could fail the entire startup gate.
///
/// Credential slots are exempt: silently dropping one would sign the user out
/// with no explanation. Those raise [UnreadableSensitivePreferenceException],
/// which the startup gate classifies as repairable so the user gets the same
/// consented repair as an unparseable store.
///
/// Takes the cache directly so the credential stores — which hold a
/// [SharedPreferencesWithCache] rather than a [BaseSharedPreferencesService] —
/// get the same treatment as the settings layer.
T? readPreferenceTolerantly<T>(SharedPreferencesWithCache cache, String key, T? Function() read) {
try {
return read();
} on TypeError catch (error, stackTrace) {
if (isSensitivePrefKey(key)) {
appLogger.e('Credential preference "$key" is unreadable', error: error, stackTrace: stackTrace);
Error.throwWithStackTrace(UnreadableSensitivePreferenceException(key, error), stackTrace);
}
appLogger.w('Dropping preference "$key" with an unreadable stored type', error: error, stackTrace: stackTrace);
unawaited(
cache.remove(key).catchError((Object e, StackTrace s) {
appLogger.d('Could not drop unreadable preference "$key"', error: e, stackTrace: s);
}),
);
return null;
}
}
/// Tolerant string read for a bare [SharedPreferencesWithCache].
String? readTolerantString(SharedPreferencesWithCache cache, String key) =>
readPreferenceTolerantly(cache, key, () => cache.getString(key));
@@ -1,5 +1,6 @@
import 'package:collection/collection.dart';
import '../../media/media_rating.dart';
import '../../media/media_kind.dart';
import '../../models/anilist/anilist_media.dart';
import '../../models/catalog/catalog_cast_member.dart';
@@ -218,8 +219,8 @@ class AnilistCatalogSource with CatalogWatchlistMachinery implements CatalogSour
CatalogCastMember(name: character.name, secondary: character.role, imageUrl: character.imageUrl),
];
static List<CatalogRatingSource>? _ratingsFor(double? meanRating) =>
meanRating == null ? null : [CatalogRatingSource(source: 'anilist', value: meanRating)];
static List<MediaRatingSource>? _ratingsFor(double? meanRating) =>
meanRating == null ? null : [MediaRatingSource(source: 'anilist', value: meanRating)];
static CatalogNextEpisode? _nextEpisodeFor(AnilistNextAiringEpisode? airing) => airing == null
? null
@@ -363,7 +364,12 @@ class AnilistCatalogSource with CatalogWatchlistMachinery implements CatalogSour
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async {
if (!external.hasAny) return null;
final rows = await _fribb.lookup(tvdbId: external.tvdb, tmdbId: external.tmdb, imdbId: external.imdb);
final rows = await _fribb.lookup(
anidbId: external.anidb,
tvdbId: external.tvdb,
tmdbId: external.tmdb,
imdbId: external.imdb,
);
final row = _pickRow(kind, rows);
if (row?.anilistId == null) return null;
return CatalogItemIds(
+6 -1
View File
@@ -368,7 +368,12 @@ class MalCatalogSource with CatalogWatchlistMachinery implements CatalogSource {
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async {
if (!external.hasAny) return null;
final rows = await _fribb.lookup(tvdbId: external.tvdb, tmdbId: external.tmdb, imdbId: external.imdb);
final rows = await _fribb.lookup(
anidbId: external.anidb,
tvdbId: external.tvdb,
tmdbId: external.tmdb,
imdbId: external.imdb,
);
final malId = _pickRow(kind, rows)?.malId;
if (malId == null) return null;
return CatalogItemIds(mal: malId, imdb: external.imdb, tmdb: external.tmdb, tvdb: external.tvdb);
+18 -43
View File
@@ -1,3 +1,4 @@
import '../../media/media_rating.dart';
import '../../media/media_kind.dart';
import '../../models/catalog/catalog_cast_member.dart';
import '../../models/catalog/catalog_item.dart';
@@ -7,6 +8,7 @@ import '../../utils/app_logger.dart';
import '../../utils/country_codes.dart';
import '../../utils/json_utils.dart';
import '../plex_discover_client.dart';
import '../plex_mappers.dart';
import 'catalog_source.dart';
import 'catalog_watchlist_machinery.dart';
@@ -101,7 +103,9 @@ class PlexCatalogSource with CatalogWatchlistMachinery implements CatalogSource,
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async {
if (!external.hasAny) return null;
// Plex Discover matches on imdb/tmdb/tvdb only; an AniDB-only item has
// nothing to send it.
if (!external.hasCatalogIds) return null;
final metadata = await _client.match(external);
final matchedKind = metadata == null ? null : _kindFor(metadata['type']);
if (metadata == null || matchedKind != kind) return null;
@@ -259,8 +263,8 @@ class PlexCatalogSource with CatalogWatchlistMachinery implements CatalogSource,
}
}
final headlineRating = _normalizedRating(metadata['rating']);
final audienceRating = _normalizedRating(metadata['audienceRating']);
final headlineRating = normalizedPlexRating(metadata['rating']);
final audienceRating = normalizedPlexRating(metadata['audienceRating']);
return CatalogItem(
source: CatalogSourceId.plex,
kind: kind,
@@ -343,46 +347,17 @@ class PlexCatalogSource with CatalogWatchlistMachinery implements CatalogSource,
return credits.isEmpty ? null : credits;
}
static List<CatalogRatingSource>? _ratingsFor(Map<String, dynamic> metadata) {
final ratings = <CatalogRatingSource>[];
final imdbVotes = flexibleInt(metadata['imdbRatingCount']);
void add(Object? rawValue, {required String fallbackSource, Object? image, Object? type}) {
final value = _normalizedRating(rawValue);
if (value == null) return;
final source = _ratingSource(image: image, type: type, fallback: fallbackSource);
if (ratings.any((rating) => rating.source == source && rating.value == value)) return;
ratings.add(CatalogRatingSource(source: source, value: value, votes: source == 'imdb' ? imdbVotes : null));
}
add(metadata['rating'], fallbackSource: 'critic', image: metadata['ratingImage']);
add(metadata['audienceRating'], fallbackSource: 'audience', image: metadata['audienceRatingImage']);
for (final rating in flexibleMapList(metadata['Rating'])) {
add(rating['value'], fallbackSource: 'audience', image: rating['image'], type: rating['type']);
}
return ratings.isEmpty ? null : ratings;
}
static String _ratingSource({Object? image, Object? type, required String fallback}) {
final scheme = Uri.tryParse(_nonEmptyString(image) ?? '')?.scheme.toLowerCase();
if (scheme == 'imdb') return 'imdb';
if (scheme == 'themoviedb' || scheme == 'tmdb') return 'tmdb';
final ratingType = _nonEmptyString(type)?.toLowerCase() ?? fallback;
if (scheme == 'rottentomatoes') {
return ratingType == 'critic' ? 'rottenTomatoesCritic' : 'rottenTomatoesAudience';
}
return switch (ratingType) {
'critic' => 'critic',
'audience' => 'audience',
_ => fallback,
};
}
static double? _normalizedRating(Object? value) {
final rating = flexibleDouble(value);
if (rating == null || !rating.isFinite || rating < 0 || rating > 100) return null;
return rating > 10 ? rating / 10 : rating;
}
static List<MediaRatingSource>? _ratingsFor(Map<String, dynamic> metadata) => plexRatingSources(
rating: metadata['rating'],
ratingImage: metadata['ratingImage'],
audienceRating: metadata['audienceRating'],
audienceRatingImage: metadata['audienceRatingImage'],
ratingSources: [
for (final rating in flexibleMapList(metadata['Rating']))
(image: rating['image'], type: rating['type'], value: rating['value']),
],
imdbVotes: flexibleInt(metadata['imdbRatingCount']),
);
static String? _overviewFor(Map<String, dynamic> metadata) {
var overview = _nonEmptyString(metadata['summary']);
@@ -1,3 +1,4 @@
import '../../media/media_rating.dart';
import '../../media/media_kind.dart';
import '../../models/catalog/catalog_metadata.dart';
import '../../models/catalog/catalog_item.dart';
@@ -211,14 +212,14 @@ class SimklCatalogSource with CatalogWatchlistMachinery implements CatalogSource
if (type == SimklCatalogType.anime && simklId != null) _animeIds.add(simklId);
}
static List<CatalogRatingSource>? _ratingsFor(SimklRatings? ratings) {
static List<MediaRatingSource>? _ratingsFor(SimklRatings? ratings) {
if (ratings == null) return null;
final result = <CatalogRatingSource>[];
final result = <MediaRatingSource>[];
for (final (source, rating) in [('simkl', ratings.simkl), ('imdb', ratings.imdb), ('mal', ratings.mal)]) {
final value = rating?.rating;
if (value == null || value < 0 || value > 10) continue;
final votes = rating!.votes;
result.add(CatalogRatingSource(source: source, value: value, votes: votes != null && votes >= 0 ? votes : null));
result.add(MediaRatingSource(source: source, value: value, votes: votes != null && votes >= 0 ? votes : null));
}
return result.isEmpty ? null : result;
}
@@ -564,7 +565,7 @@ class SimklCatalogSource with CatalogWatchlistMachinery implements CatalogSource
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async =>
external.hasAny ? CatalogItemIds.fromExternal(external) : null;
external.hasCatalogIds ? CatalogItemIds.fromExternal(external) : null;
@override
Future<WatchlistKeyPage> fetchWatchlistKeyPage(int page, int limit) async {
@@ -117,7 +117,7 @@ class TraktCatalogSource with CatalogWatchlistMachinery implements CatalogSource
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async =>
external.hasAny ? CatalogItemIds.fromExternal(external) : null;
external.hasCatalogIds ? CatalogItemIds.fromExternal(external) : null;
@override
Future<CatalogDetail> fetchDetail(CatalogItem item, {int castLimit = 20, int relatedLimit = 20}) async {
+14 -6
View File
@@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart' show visibleForTesting;
import '../utils/app_logger.dart';
import 'base_shared_preferences_service.dart';
import 'sensitive_prefs.dart';
/// Encrypts credentials before they are persisted in Drift config/token
/// columns. The database no longer stores raw server tokens; registries
@@ -18,7 +19,7 @@ import 'base_shared_preferences_service.dart';
class CredentialVault {
CredentialVault._();
static const String _keyPref = 'credential_vault_key_v1';
static const String _keyPref = credentialVaultKeyPref;
static const String _prefix = 'enc:v1:';
static final AesGcm _algorithm = AesGcm.with256bits();
static Future<SecretKey>? _secretKey;
@@ -152,7 +153,10 @@ class CredentialVault {
} catch (e) {
appLogger.d('CredentialVault: prefs reload before key check failed', error: e);
}
final stored = prefs.getString(_keyPref);
// Tolerant read: a wrong-typed key must surface as a repairable
// failure, not be mistaken for 'no key yet' and silently replaced —
// that would orphan every ciphertext in the database (#1732).
final stored = readTolerantString(prefs, _keyPref);
if (stored != null && stored.isNotEmpty) {
return SecretKey(base64Decode(stored));
}
@@ -160,13 +164,17 @@ class CredentialVault {
await prefs.setString(_keyPref, base64Encode(bytes));
try {
await prefs.reloadCache();
final settled = prefs.getString(_keyPref);
if (settled != null && settled.isNotEmpty) {
return SecretKey(base64Decode(settled));
}
} catch (e) {
appLogger.d('CredentialVault: prefs re-read after key write failed', error: e);
}
// Outside the catch: if another isolate raced us and left a wrong-typed
// value, swallowing it here would return a key that never durably
// landed, and every ciphertext written under it would be unreadable on
// the next launch. Surface it for repair instead (#1732).
final settled = readTolerantString(prefs, _keyPref);
if (settled != null && settled.isNotEmpty) {
return SecretKey(base64Decode(settled));
}
return SecretKey(bytes);
}();
}

Some files were not shown because too many files have changed in this diff Show More