feat(self-hosted): keep playlists on the server for every device (#1903)

* feat(services): server storage connection state and access token

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(services): server kind for the playlist storage backend

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(services): server storage API client

The @iptvnator/services/server-storage sub-entry keeps server mode out of
the eager services barrel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(services): playlist document store over the server API

Full documents are cached by ETag (weak tags included) and served as
private copies; an upsert whose payload is the one the store handed out
sends keepPayload=1 without it and retries in full on payload_missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(services): server-synced user data storage

Synced Xtream maps live in a write-through cache under the
iptvnator-server: prefix; writes send only the playlist entries that
changed, debounced, and flush with keepalive when the page hides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(services): server storage session and token interceptor

The session plugs the HTTP document store into PlaylistStorageBackend,
hydrates synced user data before the first read (bounded to 3 s), retries
while offline, flushes on hide, and routes to sign-in when the server
answers 401. The interceptor adds the access token to HttpClient calls to
the backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(services): move browser playlists to the server

An empty server gets the browser playlists with their ids plus the
legacy Xtream user-data maps; a server that already has playlists goes
through the backup export and import, so duplicates merge. Browser data
is never deleted; the decision is remembered per server instance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(pwa): probe for server storage and wire server mode

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(pwa): server sign-in page and migration dialog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(settings): server section for self-hosted storage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(workspace): server status in the rail and an offline banner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(settings): warn that delete-all clears the server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(i18n): server storage strings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(e2e): server storage across browsers and the migration dialog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(self-hosted): server storage mode, sign-in and the release note

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(pwa): stay in server mode when a known server does not answer

A failed start-up probe used to fall back to browser mode, which showed an
empty library while the backend restarted and let new playlists land in the
browser. The browser now remembers the server; without an answer it starts
in server mode, offline, and reloads once the server is back. Settings →
Server shows the backend address instead of the page's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): keep Xtream data, ordered sync, sign-in and stale-cache fixes

- Moving browser playlists matches them to the server's by id or source and
  carries the legacy Xtream maps under the server id; it no longer goes
  through the backup format, whose PWA export has no Xtream user data. A
  partial move stays on offer.
- User-data batches go out in order, and a re-read keeps entries edited
  while it was in flight.
- A keepPayload write keeps its cached copy only when the server replaced
  the version its payload came from (new X-Replaced-ETag header).
- 502/503/504 from the proxy count as offline.
- The start-up screen lets the sign-in page through while a token is
  required.
- Settings → Server offers a reload after a move.
- The probe detects Electron through RuntimeCapabilitiesService.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): merge user data on move, keep failed writes, sign-in route gate

- A merged playlist gains the browser document's favorites and history;
  Xtream values for one server entry are combined (lists unioned, maps
  merged, the server winning conflicts) and written once.
- A failed user-data write stays queued and survives a re-read; the
  page-hide flush waits for a batch still travelling.
- The start-up screen lets the sign-in route through whatever its check
  reports.
- The backend refuses IPTVNATOR_ACCESS_TOKEN without server storage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): positions by content, acknowledged keepalive, serial re-reads, token changes

- Moved playback positions are matched by content type and Xtream id and
  name the server playlist.
- Page-hide writes report whether the server took them; refused ones go
  back into the queue. Re-reads run one at a time.
- The access guard's 401 carries WWW-Authenticate: Bearer
  realm="iptvnator"; the interceptor and PwaService's raw fetches turn it
  into sign-in, so a token changed on the server is noticed on provider
  calls too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): Stalker keys by category, keepalive ordering, cut-off probe

- Moving Stalker favorites and history keys items by id and category, so
  a channel and a movie with one id both survive.
- Writes after a page-hide flush wait for its keepalive requests.
- A probe whose body is cut off counts as unreachable and keeps the
  remembered server.
- Settings → Server renders without @defer so settings search can reveal
  its rows on the first visit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): cache baseline before first read, versioned retries, M3U favorite ids

- Before the first user-data read finishes, an edit is compared with the
  cache, so it sends only its own playlist entry.
- Queued entries carry their edit number; a failed write is retried only
  when nothing newer replaced it.
- Moving M3U favorites and history translates channel ids through the
  stream URL (ids are random per import).
- The server-storage E2E runs in Chromium only: one shared database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): keep URL favorites, flush before moving, cache-full and cut-off bodies

- Moving M3U favorites keeps URL favorites and anything the server cannot
  resolve; only older channel ids are translated.
- Queued user-data edits are sent before the move writes combined values.
- A re-read that does not fit the cache keeps the old cache and baseline
  together.
- A response body cut off after its headers counts as offline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): unsent writes survive reloads, guarded move, lazy storage

- User-data writes the server has not confirmed are kept under
  iptvnator-server:unsent-writes and sent first on the next visit.
- Moving browser data does not start while user-data writes are unsent,
  and a duplicate of a failed upload counts as failed, not merged.
- The session reaches localStorage through the lazy adapter, so a browser
  that denies storage still boots.
- Raise launch/renderer.domMutationsToFirstCard by 2 (569 → 571): the rail
  server shortcut and the offline banner each leave an @if anchor in every
  build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): locks follow merged playlists, typed legacy Xtream ids, instance-scoped cache

- Moving a playlist under another server id takes its parental locks along
  (they stay in the browser).
- Bare legacy Xtream ids in each copy are typed from that copy's own
  snapshots before favorites, history and snapshots are combined, so a
  live channel and a movie sharing an id both survive.
- Writes still travelling are saved on page hide too; saved writes and the
  cache belong to one server database (cache owner = instanceId).
- A late successful answer no longer turns unauthorized back to online.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): apply early edits to the server value, newest unsent write, sticky sign-out

- Edits made before the first successful user-data read are kept as
  before → after and applied to the server's value once it arrives
  (applyEdit), so a new device or a stale cache adds a favorite instead of
  replacing the server's list.
- Saved unsent writes keep only the newest per entry; an answered older
  write no longer retires a newer one still travelling.
- A late failure after sign-out no longer turns unauthorized into offline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): keep early edits across reloads and tabs, numeric-string legacy ids

- Edits made before the first read are saved (before → after) and
  restored after a reload; a second early edit keeps the first one's
  baseline, even an empty one; a cache-full first read still applies them
  to the server's value.
- Queued writes are saved as soon as they are queued, and a re-read keeps
  entries another tab has not confirmed yet.
- Legacy Xtream ids stored as numeric strings are typed too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): per-tab saved writes, memory overflow cache, snapshot aliases

- Unconfirmed writes and early edits are kept in the tab's own
  sessionStorage, so tabs never clear each other's; a shared registry of
  unconfirmed entries (one record per tab, ignored after ten minutes)
  keeps a re-read in one tab from replacing another tab's values.
- A cache value too big for localStorage stays readable from memory, so
  later edits are diffed against what the app reads.
- Typing legacy Xtream ids keeps each snapshot's bare key as an alias, so
  a reference not yet rewritten still resolves and a retry can type it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): conditional user-data writes, scoped token, deletes

- User-state entries carry a content tag; PUT/DELETE accept If-Match or
  If-None-Match: * and answer 412 with the current value and tag. The PWA
  sends each edit on the tag it read and replays it (before → after) on
  the server's value after a conflict, so another device's change to the
  same playlist's favorites or positions is kept instead of overwritten.
- The access token goes only to the backend URL (same origin and path),
  never to another host or a sibling path.
- Deleting a playlist (or all) first drops its queued user-data edits and
  waits for writes in flight, so none recreates deleted data.
- The migration copy writes on the tags it read.
- The write queue moves out of ServerUserDataStorage into
  UserDataWriteQueue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(server-storage): conditional user-state writes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): keep tags with their values, rebase page-hide writes, hold deletes

- A re-read that keeps an entry from the cache (another tab's or this
  tab's unconfirmed value) no longer takes the server's tag for it, so the
  next edit conflicts and is replayed instead of overwriting another
  device's change.
- Page-hide writes behind a travelling one are taken from the queue when
  it is answered, so its new version becomes their baseline.
- A playlist delete holds that playlist's user-data edits instead of
  discarding them up front; only a successful delete drops them, a failed
  one sends them as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): replay edits behind travelling writes in order, hold writes after an offline start

- An edit queued behind a travelling write keeps its own before → after
  and carries the travelling write's edit as `prior`, also in the saved
  writes. A conflict replays both in order, so adding and then removing a
  favorite removes it whether or not the first write landed, and a lost
  write is not dropped.
- Page-hide writes now report their new tag or a 412 like normal writes:
  a confirmed one rebases the next edit, a conflict is replayed.
- After an offline start from a remembered instance, writes are held and
  the retry only checks /instance before reloading, so saved writes never
  reach another database behind the same address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): durable per-page journal, conflicts for edits on other tabs' changes, lock readability

- Unconfirmed writes and early edits are saved in localStorage per page
  load; the tab remembers its page load in sessionStorage, so a reload
  takes them over, and another tab replays a closed tab's writes once its
  record is stale. Live tabs renew their record every 30 s.
- An edit made on another tab's unsent change, and an entry a re-read
  keeps from the cache, are sent on a version no entry has, so the write
  conflicts and is replayed instead of carrying another tab's change past
  a later removal.
- Moving browser data counts the parental-lock step as failed while the
  lock store cannot be read, so the move stays on offer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): keep edits as ordered steps, treat probe refusals as transient, read the cache through memory

- A queued write keeps its edits as steps: an edit continuing the last one
  joins it, one made behind a travelling write or on another tab's change
  stays apart, and a conflict replays them in order. Saved writes and
  early edits store the steps too.
- The instance probe treats any refusal but 404 (a proxy's 429 or 403) as
  unreachable, so a browser keeps its remembered server.
- Cache reads that browser storage refuses fall back to memory, so a
  re-read and later edits still work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): keep steps of possibly-landed writes apart, queue closed tabs' edits even when the cache shows them

- Steps of a write whose answer was lost, of saved writes taken over after
  a reload, and of a closed tab's saved edits are marked uncertain, so a
  later edit never joins them: adding and then removing an item after a
  lost answer still removes it.
- A closed tab's saved edits are queued ahead of this tab's own even when
  the cache already shows them, so a conflict replays them too.
- The tag map moves into UserStateTags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(workspace): style the server banner from the shell, baseline 570

The offline banner's own stylesheet added a <style> element to every
launch, one of the two mutations the launch journey counted on top of
master. Its rules move into the workspace shell's stylesheet.

The other one is a parser-inserted modulepreload link: the new lazy
server-storage chunks split one shared initial chunk in two. A/B on
macOS: master 555, this branch 556 (was 557); the baseline note now
says so instead of blaming @if anchors, which cost nothing here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): apply a caller's edits to the cache as it is now

ServerUserDataStorage remembers the map getItem handed out. When the
cache changed since (another tab saved, a re-read), a write applies only
the entries the caller changed to the current cache, so a map read
before another tab's save no longer reads as deleting that save. The
cache moves into UserDataCache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): retry unsynced user data while online, keep newer typed snapshots, explain a refused token store

- The 30 s retry also re-reads and flushes while online when the first
  user-data read failed or writes the server refused (a 5xx) are queued;
  the same failure notice shows at most every five minutes.
- Moving browser data adds a legacy snapshot alias only where no typed
  snapshot exists, so a newer typed copy is not overwritten.
- writeServerAccessToken reports whether storage kept the token; the
  sign-in page says so (SERVER_STORAGE.SIGN_IN_STORAGE, 19 locales)
  instead of calling a right token rejected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): conditional playlist metadata writes, retried on a fresh read

A favorite or rename (keepPayload PUT) is sent with If-Match on the
version it was read at. The server answers 412 when another device wrote
since; the store throws PlaylistWriteConflict and PlaylistsService's
per-playlist write queue runs the mutation again, which reads the
playlist afresh, so two devices' metadata edits both survive. A retry on
the same unread copy writes unconditionally, as before; refresh and
import writes stay last write wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): conditional writes for every playlist mutation, ordered adoption, keep journals until copied

- Every playlist mutation is sent on the version it was read at: the
  payload's ETag, else the playlist's last read (portal documents have no
  payload). Refused versions are tracked per playlist, so a conflict on
  one never disables the check on another at the same revision. Imports
  and start-up migrations (dbUpsertAppPlaylists) stay unconditional.
- A closed tab's adopted edits replay before this tab's queued ones, from
  the base of its first step, so newer progress is not replaced by older.
- A reload or adoption removes the old page load's saved writes only when
  this page saved its copy; each closed tab is adopted once per page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): copy-bound portal versions, stale 401s, unreadable browser maps, early edits on recovered writes

- A served copy carries the version it came from (a symbol property that
  spreads keep and JSON drops), so a mutation of a portal document names
  the version it was built on, not the latest read.
- A 401 for a token replaced since (a new sign-in) neither clears the new
  token nor reports unauthorized, in the API client, the HttpClient
  interceptor and PwaService's proxy calls.
- Moving browser data counts a browser user-data map that cannot be read
  as a failure, so the move stays on offer.
- An edit made before the first read on top of this tab's recovered
  unsent write is applied to that write, not to the server's value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): favorite toggles as deltas, early edits as steps on recovered writes, release kept journal copies

- PlaylistEffects.updateFavorites$ applies the toggled channel through
  transformPlaylistFavorites, on the favorites read at write time, instead
  of writing the reducer's whole array: a conflict retry keeps another
  device's favorites (#1919).
- Edits made before the first read on top of this tab's recovered unsent
  write are appended to it as their own steps, so a removal of an item the
  recovered write adds survives a conflict replay.
- Journal copies of earlier page loads kept because this page could not
  save its own are removed once it can.
- adopt/extend move into server-user-data-adopt.ts over a small queue API
  (unsent, isQueued, put); the queue exposes its tag map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): refuse user state for deleted playlists

PUT /v1/user-state/:namespace/:playlistId answers 404 playlist_missing
when the server has no such playlist, so an edit queued on another device
(including its conflict replay with If-None-Match: *) cannot recreate the
state of a playlist deleted meanwhile. The client drops such an edit and
its cache entry instead of retrying; page-hide writes report it as gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): keep duplicated tabs off live journals, drain writes around remove-all, normalize legacy Stalker rows on the move

- A page marks its unconfirmed-writes record closed on pagehide (not into
  the back-forward cache); a new page takes over the previous page load's
  saved writes only when that record is closed, stale or missing, so a
  duplicated tab, which copies sessionStorage, leaves the running tab its
  writes.
- PlaylistsService.removeAll lets queued playlist writes land first and
  makes writes issued meanwhile wait until it finished; the server store
  refuses a document without an id.
- Moving browser data sets the explicit Stalker portal-mode flag on rows
  from before it (withExplicitStalkerPortalFlag, now shared with
  PlaylistsService).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): take over a reload's writes once the previous page load stops looking live

When the close flag could not be saved (storage full), a reload took the
previous page load for a running duplicated tab and left its saved writes
unsent. The page now remembers that page load and its 30 s touch takes it
over as soon as its record is closed, stale or gone, so the session's
retry sends the writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): adopt a late previous page load instead of restoring it

When touch() finds that the previous page load no longer looks live, this
page may already have read and queued newer edits. Its saved writes and
early edits are now adopted like a closed tab's (their steps ahead of this
page's newer ones, queued at once) instead of restored as if this page
had just started, which replaced newer progress with older and parked
early edits that were never sent after the first read. Cache forgetting
moves into UserDataCache.forget().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): adopted writes without a known version conflict instead of overwriting

A page that never read the server has no version tags, so an adopted
write went out unconditionally and replaced newer server data with its
cached value. Adopted edits now use the never-matching version when this
page knows none (and for a queued write without a tag), so the server
answers 412 and the edits are replayed on its value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a re-read sent before a playlist delete skips that playlist

ServerUserDataStorage records each successful delete; a re-read sent
before it drops the deleted playlist's entries and tags from the server's
answer (withoutDeleted), so a late answer cannot write the deleted
favorites and positions back into the cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): keep a playlist id like __proto__ when filtering a read

withoutDeleted() builds its maps without a prototype, so a surviving
playlist whose id is __proto__ stays a key instead of changing the
object's prototype and losing its favorites and tag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): reorders on the stored favorites, URL-insensitive remembered server, prototype-free id maps

- PlaylistEffects.setFavorites$ applies the drag's order through
  transformPlaylistFavorites (reorderFavorites): favorites added on another
  device stay, ones removed there stay out.
- The remembered server matches the backend URL by origin and path
  without trailing slashes, so /api and /api/ start offline in server
  mode alike.
- Maps keyed by playlist id are built without a prototype (idMap), so an
  id such as __proto__ is an ordinary key in the cache, conflict replays,
  re-reads and tags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): one registry key per page load, server token only in server mode

- The unconfirmed-writes registry stores each page load's record under
  its own key (iptvnator-server:unconfirmed:<instance>:<page>), listed
  through a new keys() on the user-data storage adapter, so tabs never
  overwrite each other's records. Saved writes without a fresh record,
  also when the record was lost, are adopted as a closed tab's (#1920).
- PwaService sends the stored server token on its raw fetch calls only
  while server mode runs, and a backend that answers without server
  storage makes the browser forget the token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): forget the token for another server, listen before sign-in, adopt only stale records

- A server that answers as another backend URL or instance id than the
  remembered one makes the browser forget the stored token, so server A's
  token never reaches server B.
- The session installs its page-hide and heartbeat listeners before it
  returns for sign-in, so a page holding another page load's writes still
  marks itself closed on unload.
- Closed tabs are found by stale records only again: saved writes without
  a record may belong to a running tab whose record storage refused, and
  are left to that tab's own reload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): no token for an unverified instance, sign-in remembers its server

- ServerStorageStatusService.accessToken() returns the stored token only
  while server mode runs on an instance this start verified. The API
  client, the HttpClient interceptor and PwaService's raw fetch calls use
  it, so after an offline start from a remembered instance no request
  (including the /instance reachability check) carries the token to
  whatever answers at that address, and a 401 then does not clear it.
- Sign-in remembers the server along with the token; when storage refuses
  either, it reports SIGN_IN_STORAGE instead of reloading into a start
  that would drop the token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): check a remembered instance before sign-in sends the token

A page started from memory (startedOffline) withholds the token until the
instance is verified, so sign-in on that page sent no token and the
server's 401 cleared the right one. Sign-in now first calls
ServerStorageSession.ensureVerified(): it reads /instance without a
token, marks the status verified when the instance id matches, and
reloads the page when another server answers at the address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): read migration maps by own playlist ids only

The browser's legacy maps and the server's user-state entries are read
into null-prototype maps, so a playlist id such as `toString` is not
taken for an entry and a missing server value no longer resolves to an
inherited function.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): bind the token to its instance; adopted edits yield to newer changes

The access token is stored with the instance id it was given for, and a
page reads it only for its own instance: a tab still open on the old
backend after BACKEND_URL changed no longer sends the new server's
token there. The API client hands every 401 to reportAccessDenied(),
which now also sends a page without a token for its instance to sign-in,
while one that holds its token back until the instance is checked keeps
it.

A closed tab's adopted edits carry `yields`: replayed, they change only
what is still as that tab saw it, so they never replace progress this
tab or another device saved since. The flag survives the journal.

The sync spec's fake server and memory storage move to a test-helpers
file to keep the spec under its line limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): per-instance cache, idle tabs adopt closed ones, backups wait for the first read

The user-data cache is keyed by server instance
(`iptvnator-server:cache:<instanceId>:<namespace>`): a tab still open on
the old backend after BACKEND_URL changed no longer writes over the new
server's cache, which the new tab's next edit would have sent there.
claimCache also removes the old owner's keys and the unscoped keys of
earlier builds.

touch(), which runs every 30 s, adopts closed tabs' saved writes once
this tab has read: a tab with nothing to sync never re-reads, so they
waited until a tab switch or reload.

UserDataStorage gains an optional ready(); the server storage resolves
it after its first read and rejects while that fails. A PWA backup
export awaits it, so a fresh browser whose /user-state read is slow or
failed cannot export empty favorites, history and positions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): token only to backend URLs in raw fetches; Stalker series keys in the move

PwaService joins paths to the backend URL without its trailing slashes,
so BACKEND_URL=/ no longer yields a protocol-relative //… URL that names
another host, and it attaches the server token only when the request URL
resolves to the backend (isBackendUrl), like the interceptor.

The move's item key adds the Stalker series flag to id and category: a
provider category can hold a movie and a series of one id, and the
series favorite was dropped as a duplicate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): Xtream reads and backups wait for the first read; keepalive deadline

Startup waits for the first user-data read only a few seconds. ready()
now waits for a first read in flight without starting one (an offline
page is not held up) and tells whether one succeeded:

- PwaXtreamDataSource awaits it before reading favorites, recent items
  and playback positions, so a new device whose /user-state read is slow
  does not show empty lists or start playback without its resume point.
- A PWA backup export and restore fail while no read succeeded; the
  restore stays parked, since its replacement lists would otherwise
  merge into the server's (an empty favorites list changed nothing).

A page-hide keepalive write gets the request timeout: a server that
takes it and never answers no longer holds every later write, re-read
and delete behind it until reload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a failed sign-in keeps another tab's token; moved history newest first

A sign-in that fails clears the token only while it is still the one
this attempt stored: another tab that signed in meanwhile keeps its
valid token.

The move orders the combined Xtream recent items by viewedAt, newest
first, as the app keeps them: browser views appended after the server's
history were cut by the next view once the server held 50.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): recheck the instance after offline, back-forward cache pages, Stalker server rows

Going offline now marks the instance unchecked: the token and writes
wait until /instance answers with this page's instance (another one
reloads the page). A replaced volume at the same address no longer gets
the old token and queued user-state writes on reconnect. The session
checks as soon as it goes offline, so a blip costs no retry interval.

A page restored from the back-forward cache whose record another tab
adopted meanwhile (its timers were frozen, so the record went stale)
reloads instead of sending those writes again after newer edits.

The Stalker playlist metadata migration also runs on server rows, once
per server: a desktop database copied to the server can predate it, and
its Stalker rows lacked isFullStalkerPortal.

The take-over and change-diff loops move out of the user-data facade,
and the adoption specs get their own file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): adopted edits keep yielding through conflicts; newest view per item; same-token sign-ins

A conflict replay collapsed every step into one edit, so a closed tab's
adopted step lost `yields` after the first conflict and a second one
replayed its old position over a newer one. Its steps now stay as they
are, and only this page's own collapse into one edit on top of them.

The move combines recently viewed items one per item, keeping the newest
view and its artwork, then newest first; before, the server's older copy
of an item won over a later browser view.

A failed sign-in clears the stored token only on a 401: a network
failure says nothing about the token, and another tab may have stored
the same one meanwhile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): suspended tabs give up adopted writes; history stays newest first; favorite checks wait

A background tab the browser suspended past the record lifetime can have
its writes adopted elsewhere, like a back-forward cache page: shown
again, it now checks resumed() and reloads instead of sending them.

Conflict replays appended a newly viewed item at the end of the history,
where the next 50-item cut dropped it; a replayed recently viewed list is
now kept newest first.

isFavorite() waits for the first user-data read like the list reads, so
a detail page opened during a slow first read does not toggle an
existing favorite the wrong way. A parked backup restore replayed when
the playlist opens waits too, and stays parked while no read succeeded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): offline recheck checks only the instance; sign-out always navigates

The recheck on going offline ran a full refresh: when /instance answered
but /user-state kept failing, each failed read set the page offline
again and started the next one at once, bypassing the retry interval.
It now checks the instance only; reads wait for the retry.

Sign-out navigates to sign-in itself, also when the page is signed out
already: a guard (unsaved Settings) may have cancelled the redirect the
first time, and the state change that drives it does not repeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a superseded page sends and saves nothing; re-reads keep other tabs' newer saves

A suspended tab's retry timer could run before it was shown again: touch()
recreated the record another tab had removed when it adopted the page's
writes, so the page sent them again over newer edits. The facade now
treats a page whose record is gone as superseded: the queue sends nothing
(maySend hook), its journal and record are not written again, and the
retry timer reloads it like a page shown again.

A re-read answered after another tab saved an entry no longer writes the
older answer over the shared cache: entries changed while the read
travelled are kept, with an unknown tag, so the next write here
conflicts and replays instead of removing what the other tab saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(web-e2e): never reuse another backend as the storage E2E backend

server-storage.e2e.ts deletes every playlist before each test. Reusing a
backend already listening on STORAGE_BACKEND_PORT outside CI could have
wiped a real library; an occupied port now fails the run instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): an outage on the sign-in page also unverifies the instance

reportOffline() left `verified` set while the page was unauthorized, so
a sign-in retried after an outage skipped the instance check and could
send the old instance's token to a replacement database. Verification
is now cleared on any outage; only the state change stays guarded, so
the workspace remains locked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): interceptor and raw fetches report backend outages too

Only the storage API client reported an unreachable backend as offline.
When the first sign of an outage was an HttpClient call through the
interceptor (provider targets, playlist parsing) or one of PwaService's
raw fetches (Stalker, connectivity reset), the instance stayed verified,
and the next request after a replacement instance came up at the same
address would carry the old token.

Both now report no answer (status 0, a failed fetch) and a gateway's
502/503/504 as offline, so the session checks /instance first. The
backend's own JSON 502 for a failed provider is an answer and changes
nothing; neither does a fetch this page aborted on its own timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): the immediate offline check runs once per retry interval

A response whose headers arrived but whose body was cut off reports
success and then offline, which started the next immediate instance
check at once: repeated cut-off answers kept requests going and the
connection indicator flickering. The check on going offline now runs at
most once per retry interval; later failures wait for the timed retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a saved write without a readable tag counts as saved; unverified online pages keep retrying

A write whose headers said saved but whose body (with the new tag) was
cut off was retired without confirmation: a newer queued edit kept its
steps and old tag, and a later conflict replayed the saved step over a
newer value from another device. It now counts as saved on an unknown
version: the landed steps drop out and the next write conflicts, so
only edits made after it replay. Writes that were unconditional stay so.
The keepalive path does the same.

A late answer to a request sent before an outage can set an unverified
page online; with nothing to sync the retry then never ran and the token
stayed withheld. The retry now also runs for online pages that are not
verified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): keep server storage off the startup bundle; form-field defaults on sign-in

PwaService imported isBackendUrl from the @iptvnator/services/server-storage
barrel, which pulled the whole storage subsystem (sync, migration, API
client) into main, though server mode loads it by dynamic import. The
helper now lives with the token helpers in @iptvnator/services
(re-exported from the interceptor): renderer.initialBytes 1,392,902 ->
1,357,795 bytes locally.

The remaining 11,988 bytes over #1931's baseline are what must run
before the first route (instance probe, connection status, token bound to
its instance, storage backend and write serialization); the baseline is
raised with a note, under the PR's perf-baseline-increase label.

The sign-in component provides the form-field defaults per component, as
master's check (#1928) now requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): conflict-safe Stalker metadata migration on the server; newest document views in the move

The Stalker metadata migration wrote server rows back through the
unconditional bulk upsert, from the list read: a device that edited a
Stalker playlist in between (or a second browser migrating the same
copied database) lost its change. Server rows are now read again one by
one and written as conditional mutations on that version; a conflict
leaves the flag unset, so the next start retries.

Moving a document's history kept the server's copy of an item both held,
even when the browser had viewed it later, and skipped the write when the
length did not change. The combined history is now newest first by
added_at, one entry per item, and any content change is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): M3U favorites by URL and history channel ids in the move; restores wait for the server

The move's M3U remap swapped references for server channel ids, but the
app looks favorites up by stream URL and history entries carry the URL
as their id: legacy favorites became invisible and history duplicated.
Legacy id favorites now become their channel's URL on both sides, and
history keeps its URL id with the server's channel id as channel_id.

A restore in server mode reported success once its lists were queued:
a list the server refused (413) left the old data while the parked
restore was consumed. Both restore paths now wait for that playlist's
writes (UserDataStorage.flushed, a few flush rounds for conflict
replays) and stay parked when the server did not take them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a closed page record stays closed when a late write rewrites it

On pagehide the page flushes with keepalive and then marks its record
closed. When writes were held (offline), the keepalive write fails at
once and its requeue saved the journal again a microtask later, which
rewrote the record without `closed`: the reload took the previous page
load for live and left its favorites and progress unsent until the
record aged out (ten minutes). markUnconfirmed now keeps an existing
record's closed flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): the move uploads playlists create-only and merges into a copy moved first

Two tabs or devices moving browser copies with the same playlist id both
planned an upload; the browser documents carry no served version, so
both PUTs were unconditional and the later one overwrote the first copy
(and any change made on it since), with both moves reporting success.

The backend's playlist PUT now honours `If-None-Match: *` (412 when the
playlist exists; checked and written in one synchronous handler). The
move uploads with it through ServerPlaylistDocumentStore
.dbCreateAppPlaylist, and an upload that finds its id taken merges its
favorites and history into that copy instead, counted as merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): Delete All waits for repairs holding a reservation; backups read the server again

Delete All raised its write barrier before it held the exclusive
authority reset. A Stalker repair already holding its row reservation
then waited on that barrier for its conditional write, while the reset
waited for the reservation: neither finished, and later playlist
operations stalled behind them. The barrier now goes up inside the
reset, once repairs in flight have finished; writes queued so far land
first and new ones wait for the delete, as before.

ready() said yes after any earlier read, so an export could miss what
another device added since, and restoring an empty list did nothing
when the cache was already empty. Backup export, restore and the
restore replay now ask for a fresh read (ready(true)) and fail, the
restore staying parked, when it does not succeed.

The facade's adoption loop moves to the adopt module to keep the
facade under its line limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(services): Delete All drains queued writes before its reset; reserved writes skip its barrier

The previous commit raised Delete All's barrier inside the exclusive
authority reset and drained queued writes there, but a queued deletion
or import takes the shared side of that lock: the reset waited for it
while it waited for the reset.

Delete All drains the writes queued before it outside the lock again,
then takes the reset, with its barrier up from the start. The deadlock
with a Stalker repair (or Edit) that holds a row reservation and writes
under it is broken on the other side: such a write does not wait for
the barrier (holdsPlaylistAuthority, counted per reservation in this
context), and the reset waits for the reservation as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a re-read keeps writes another tab had unconfirmed when it went out

A re-read checked other tabs' unconfirmed entries only after its answer
arrived. A tab whose write was unconfirmed when the read went out (its
edit already in the snapshot) and confirmed before the old answer came
back matched neither check, so the stale answer replaced its saved value
in the shared cache; that tab's next edit, holding the newer tag, then
wrote the stale list and deleted the item on the server. The entries
unconfirmed when the read is sent are kept too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(services): writes wait for Delete All before they queue; restores replace only settled lists

Delete All, third variant: a write that arrived after Delete All waited
for it inside its playlist's queue. A Stalker repair that reserved that
playlist meanwhile skipped the barrier, but its write still queued
behind that waiting one, while the reset waited for the repair's
reservation. While a Delete All runs, writes now wait for it before they
join their queue, so no queue holds work blocked on the reset; a write
under a reservation held here joins at once.

A restore replaced lists while this page's own write for the playlist
was still unsent (refused, or lost): that write's edits joined the
replacement and a conflict replay kept items the backup did not have.
Both restore paths now require the playlist's writes to be on the
server first (flushed), and otherwise stay parked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a reload finds page loads a reload before it kept; restore master's tick baselines

When storage refused a reload's copy of the last page load's saved
writes, the old copy stayed but only this page's memory named it: the
tab's pointer already named the new page, so a second reload before any
copy was saved recovered from the empty new page, and without a
registry record no other tab could find the old one. The pointer now
also lists the page loads a page keeps (keepPages), and a reload takes
them over, oldest first, before its last page load. The pointer helpers
move to server-page-pointer.ts.

Both merges of master resolved journey-baselines.json by taking this
branch's whole file, which dropped #1929's cdTicksToFirstCard,
cdTicksIdle30s and cdTicksToFirstPage. The file is master's again with
only this branch's initialBytes and domMutationsToFirstCard raises.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a duplicate leaves a running tab's kept page loads to it

A duplicated tab copies the tab's session storage, so after a reload
that kept older page loads its pointer lists them too, and the duplicate
took them over at once, although the tab still running owns those edits
and may have newer ones queued; its replay could then write older watch
progress over newer. When the previous page load still runs, the kept
ones now wait with it and `touch` adopts them, oldest first, once it no
longer looks live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a restore merged by a conflict stays parked; first-read tests wait for the read

A restore whose write conflicted with an edit another device made during
it had the conflict replay merge that edit in, and flushed() still said
the lists were taken, so the restore was consumed with lists that were
not the backup's. Both restore paths now compare the stored lists with
the ones they wrote once the server took them, and a difference keeps
the restore parked to run again on a fresh read.

The two first-read tests released the mocked read after a fixed number
of microtask turns, which could come before the read started; they now
wait until it has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): page-hide keepalive writes report an outage too

sendKeepalive() turned a failed fetch, a timeout or a gateway's
502/503/504 into a failed outcome without telling the status, so the
instance stayed verified: when the hidden tab came back, its refresh
skipped the /instance check and resent the queued writes, which could
reach a replacement database behind the same address. Like requests, a
keepalive write now reports these as offline, so the instance is
checked before anything goes out again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a keepalive answer cut off after its headers counts as offline

A page-hide write whose headers said saved but whose body broke off was
returned as saved with the read error dropped, so the instance stayed
verified. Like readJson() for requests, it now reports offline (the
outcome stays saved on an unknown version), and the instance is checked
before the next token or write goes out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): kept page loads replay oldest first; restore checks compare normalized reads

A page load and an older one it kept could both hold steps for one
entry. Adopting them, each adopted page went ahead of what was queued,
so adopting the oldest first put the newer page's steps before the
older's; restoring them after a reload collapsed the newer page's steps
into one, so its removal of an item the older page had added was lost
on a conflict replay. Adoption now goes newest first, and a reload
appends a later page's steps (and early edits) after an older copy's.

restoreUserData() compared the lists it wrote with reads that drop
duplicate favorites, so a saved restore listing one twice never
finished, also in browser-only mode. It now compares reads right after
writing with reads after the save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): flushes wait for a page-hide batch sent at once; keepalive 401s; parked restores move

A flush scheduled in the same turn as a page-hide flush was chained on
the queue before the keepalive batch, which went out at once beside it:
a later edit (removing a favorite the keepalive batch added) could land
first and be undone when the keepalive write arrived. A scheduled flush
now waits for a page-hide batch sent at once before it takes entries.

A keepalive write refused with 401 returned failed without telling the
status; like requests it now reports the token it sent as refused.

The move copies a parked Xtream restore (a browser backup import that
could not finish) to the server playlist id a playlist merged into, so
it is applied and exported there; one parked there already wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server-storage): a slow server does not reload a page started from memory forever

The start probe gives /v1/instance 2.5 s. A remembered server slower
than that started the page from memory; the recovery check (with the
request timeout) then got an answer and reloaded, and the reloaded page
timed out again: an endless reload loop for a server answering in 2.5
to 20 s. The reload now leaves a one-time mark in sessionStorage, and
the next probe waits as long as requests do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
4grayandClaude Opus 5.5 authored and GitHub committed 2026-10-15 07:57:15 +02:00
1 parent 2139ddd5c0
commit 8098ea8bb8
147 files changed
+15337 -189

No files matched your search

@@ -1,7 +0,0 @@
---
type: feature
area: self-hosted
issues: [305]
---
The Docker image now keeps a server database on a `/data` volume, the groundwork for sharing playlists and watch progress across devices. Mount a volume to keep it; nothing changes in the browser yet.
+8
View File
@@ -0,0 +1,8 @@
---
type: feature
area: self-hosted
issues: [305]
highlight: Playlists on your server
---
The Docker version now keeps playlists, favorites and watch progress on the server, so every phone, TV and computer that opens it shares one library. Playlists already in a browser move over with one click, and an optional access token keeps the library private.
+4
View File
@@ -135,6 +135,10 @@ The application is available at <http://localhost:4333>. See
compose file and [`docker/README.md`](./docker/README.md) for environment
variables, reverse proxy notes, PWA limitations, and build details.
The image keeps playlists, favorites and watch progress on the server, so
every browser that opens it shares one library. The first browser that opens
an updated instance offers to move the playlists it already has.
The self-hosted image runs the browser PWA rather than the Electron desktop app:
EPG/XMLTV panels, Embedded MPV, managed MPV/VLC launching, the download manager,
and Electron remote-control features are not available there. If browser
@@ -41,9 +41,25 @@ describe('Playwright web-backend launch', () => {
expect(source).not.toMatch(/\bnx\b[^'"`\n]*web-backend/);
expect(start).toBeGreaterThan(-1);
expect(
source.indexOf(launchCommand, start + launchCommand.length)
).toBe(-1);
// One stateless backend, plus at most one storage-enabled one.
const second = source.indexOf(
`'${launchCommand}'`,
start + launchCommand.length
);
if (second !== -1) {
const storageEntry = source.slice(
second,
source.indexOf('url:', second)
);
expect(storageEntry).toContain(`IPTVNATOR_STORAGE: 'server'`);
expect(storageEntry).toContain('PORT: storageBackendPort,');
expect(
source.indexOf(
`'${launchCommand}'`,
second + launchCommand.length
)
).toBe(-1);
}
// WEB_BACKEND_PORT relocates the run; its default is the target's.
const { PORT: port, ...fixedEnv } = serveEnv;
@@ -30,6 +30,13 @@ describe('createAccessGuard', () => {
code: 'unauthorized',
});
expect(wrong.status).toBe(401);
// Lets the PWA tell it from a provider's 401 on a proxy route.
expect(wrong.headers.get('www-authenticate')).toBe(
'Bearer realm="iptvnator"'
);
expect(wrong.headers.get('access-control-expose-headers')).toBe(
'WWW-Authenticate'
);
}));
it('accepts the right token and lets preflight through', () =>
@@ -1,5 +1,6 @@
import { createHash, timingSafeEqual } from 'node:crypto';
import type { RequestHandler } from 'express';
import { SERVER_ACCESS_CHALLENGE } from '@iptvnator/shared/interfaces';
/** Routes a browser must reach before it has a token. */
const PUBLIC_PATHS = new Set(['/', '/health', '/config.js', '/v1/instance']);
@@ -24,11 +25,14 @@ export function createAccessGuard(token: string): RequestHandler {
return;
}
res.status(401).json({
message: 'This IPTVnator server requires an access token.',
status: 401,
code: 'unauthorized',
});
res.status(401)
.set('WWW-Authenticate', SERVER_ACCESS_CHALLENGE)
.set('Access-Control-Expose-Headers', 'WWW-Authenticate')
.json({
message: 'This IPTVnator server requires an access token.',
status: 401,
code: 'unauthorized',
});
};
}
@@ -1,4 +1,5 @@
import express, { Router, type Response } from 'express';
import { SERVER_REPLACED_ETAG_HEADER as REPLACED_ETAG_HEADER } from '@iptvnator/shared/interfaces';
import { matchesEtag } from './etag-match';
import {
deleteAllPlaylistsWithState,
@@ -53,11 +54,34 @@ export function createPlaylistsRouter(
router.put('/playlists/:id', json, (req, res) => {
const id = requirePlaylistId(req.params.id);
const replaced = revisions.etag(id);
// An edit built on a version another device has replaced since.
const ifMatch = req.get('if-match');
if (ifMatch && !matchesEtag(ifMatch, replaced)) {
throw new StorageRequestError(
412,
'conflict',
'The playlist changed since it was read.'
);
}
// A create-only upload (a move from browser storage) that another
// tab or device made first. Checked and written in one handler.
if (req.get('if-none-match')?.trim() === '*' && playlists.exists(id)) {
throw new StorageRequestError(
412,
'conflict',
'A playlist with this id exists already.'
);
}
playlists.upsert(
{ ...requireDocument(req.body), _id: id },
{ keepPayload: req.query['keepPayload'] === '1' }
);
withEtag(res, revisions.bump(id)).json({ success: true });
// With keepPayload a client caches its copy only if the payload it
// holds is the one this write replaced.
withEtag(res, revisions.bump(id))
.set(REPLACED_ETAG_HEADER, replaced)
.json({ success: true });
});
router.delete('/playlists/:id', (req, res) => {
@@ -76,7 +100,7 @@ export function createPlaylistsRouter(
function withEtag(res: Response, etag: string): Response {
return res
.set('ETag', etag)
.set('Access-Control-Expose-Headers', 'ETag')
.set('Access-Control-Expose-Headers', `ETag, ${REPLACED_ETAG_HEADER}`)
.set('Cache-Control', 'no-cache');
}
@@ -1,16 +1,88 @@
import { createHash } from 'node:crypto';
import { and, eq } from 'drizzle-orm';
import type { DatabaseInstance } from '@iptvnator/shared/database';
import {
SERVER_USER_STATE_NAMESPACES,
type ServerUserStateCurrent,
type ServerUserStateNamespace,
type ServerUserStateResponse,
} from '@iptvnator/shared/interfaces';
import { serverUserState } from './server-user-state.table';
/**
* What a conditional write is based on: `undefined` writes unconditionally,
* `null` expects no entry, a string expects that tag.
*/
export type ExpectedTag = string | null | undefined;
export type ConditionalWriteResult =
| { readonly tag: string | null }
| { readonly conflict: ServerUserStateCurrent };
/** Version tag of a stored value: its content, so equal values match. */
export function userStateTag(serialized: string): string {
return createHash('sha256').update(serialized).digest('hex').slice(0, 16);
}
/** Xtream PWA user data, one JSON value per namespace and playlist. */
export class ServerUserStateRepository {
constructor(private readonly db: DatabaseInstance) {}
/** Every entry with its tag, as `GET /v1/user-state` serves them. */
allWithTags(): Required<ServerUserStateResponse> {
const tags = Object.fromEntries(
SERVER_USER_STATE_NAMESPACES.map((namespace) => [
namespace,
Object.create(null) as Record<string, string>,
])
) as Required<ServerUserStateResponse>['tags'];
for (const row of this.db.select().from(serverUserState).all()) {
const bucket = tags[row.namespace as ServerUserStateNamespace];
if (bucket) {
bucket[row.playlistId] = userStateTag(row.value);
}
}
return { entries: this.all(), tags };
}
/**
* Writes (`value`) or deletes (`undefined`) one entry if it still has
* the expected tag; otherwise reports the current entry. Synchronous on
* the single connection, so the check and the write cannot interleave.
*/
writeIf(
namespace: ServerUserStateNamespace,
playlistId: string,
value: unknown,
expected: ExpectedTag
): ConditionalWriteResult {
if (expected !== undefined) {
const row = this.db
.select({ value: serverUserState.value })
.from(serverUserState)
.where(
and(
eq(serverUserState.namespace, namespace),
eq(serverUserState.playlistId, playlistId)
)
)
.get();
const tag = row ? userStateTag(row.value) : null;
if (tag !== expected) {
return {
conflict: row
? { value: JSON.parse(row.value), tag }
: { tag: null },
};
}
}
if (value === undefined) {
this.delete(namespace, playlistId);
return { tag: null };
}
return { tag: this.put(namespace, playlistId, value) };
}
all(): ServerUserStateResponse['entries'] {
// Prototype-free buckets: a playlist id such as `__proto__` must be
// stored as an own key, not change the bucket's prototype.
@@ -30,11 +102,12 @@ export class ServerUserStateRepository {
return entries;
}
/** Returns the stored value's tag. */
put(
namespace: ServerUserStateNamespace,
playlistId: string,
value: unknown
): void {
): string {
const serialized = JSON.stringify(value ?? null);
const updatedAt = new Date().toISOString();
this.db
@@ -45,6 +118,7 @@ export class ServerUserStateRepository {
set: { value: serialized, updatedAt },
})
.run();
return userStateTag(serialized);
}
delete(namespace: ServerUserStateNamespace, playlistId: string): void {
@@ -1,4 +1,7 @@
import { readServerStorageConfig } from './storage-config';
import {
readServerStorageConfig,
serverStorageConfigProblem,
} from './storage-config';
describe('readServerStorageConfig', () => {
it('keeps storage off and the API open by default', () => {
@@ -42,4 +45,20 @@ describe('readServerStorageConfig', () => {
.maxDocumentBytes
).toBe(64 * 1024 * 1024);
});
it('refuses an access token without server storage', () => {
const problem = (env: Record<string, string>) =>
serverStorageConfigProblem(readServerStorageConfig(env));
expect(problem({ IPTVNATOR_ACCESS_TOKEN: 's3cret' })).toContain(
'IPTVNATOR_STORAGE=server'
);
expect(
problem({
IPTVNATOR_ACCESS_TOKEN: 's3cret',
IPTVNATOR_STORAGE: 'server',
})
).toBeNull();
expect(problem({})).toBeNull();
});
});
@@ -10,6 +10,19 @@ export interface ServerStorageConfig {
const DEFAULT_MAX_DOCUMENT_MB = 64;
const BYTES_PER_MB = 1024 * 1024;
/**
* A combination the browser app cannot use, as a start-up message, or
* `null`. The PWA asks for the access token only in server storage mode,
* so a token on a stateless backend would lock every browser out.
*/
export function serverStorageConfigProblem(
config: ServerStorageConfig
): string | null {
return config.accessToken && !config.enabled
? 'IPTVNATOR_ACCESS_TOKEN needs IPTVNATOR_STORAGE=server: the browser app asks for the token only when the server stores its playlists. Unset the token, or protect a stateless backend in your reverse proxy.'
: null;
}
export function readServerStorageConfig(
env: Record<string, string | undefined> = process.env
): ServerStorageConfig {
@@ -91,6 +91,17 @@ describe('server storage routes', () => {
headers: { 'if-none-match': `W/${etag}` },
});
expect(weakened.status).toBe(304);
// A write names the version it replaced.
const next = await fetch(
`${baseUrl}/v1/playlists/p1?keepPayload=1`,
json({ _id: 'p1', title: 'Renamed' }, { method: 'PUT' })
);
expect(next.headers.get('x-replaced-etag')).toBe(etag);
expect(next.headers.get('etag')).not.toBe(etag);
expect(
next.headers.get('access-control-expose-headers')
).toContain('X-Replaced-ETag');
})
));
@@ -194,6 +205,154 @@ describe('server storage routes', () => {
})
));
it('refuses user state for a playlist it does not have', () =>
withTempStorage((storage) =>
withServer(app(storage), async (baseUrl) => {
const entry = `${baseUrl}/v1/user-state/xtream-favorites/gone`;
const put = await fetch(
entry,
json({ value: ['live:1'] }, { method: 'PUT' })
);
expect(put.status).toBe(404);
await expect(put.json()).resolves.toMatchObject({
code: 'playlist_missing',
});
// Removing what is not there stays harmless.
expect((await fetch(entry, { method: 'DELETE' })).status).toBe(
200
);
})
));
it('refuses a playlist write built on a replaced version', () =>
withTempStorage((storage) =>
withServer(app(storage), async (baseUrl) => {
const first = await fetch(
`${baseUrl}/v1/playlists/p1`,
json(m3uDocument('p1'), { method: 'PUT' })
);
const read = first.headers.get('etag') ?? '';
const edit = (ifMatch: string) =>
fetch(
`${baseUrl}/v1/playlists/p1?keepPayload=1`,
json(
{ _id: 'p1', title: 'Renamed' },
{ method: 'PUT', headers: { 'if-match': ifMatch } }
)
);
expect((await edit(read)).status).toBe(200);
// Another device wrote since `read`.
const stale = await edit(read);
expect(stale.status).toBe(412);
await expect(stale.json()).resolves.toMatchObject({
code: 'conflict',
});
})
));
it('creates a playlist create-only, refused once it exists', () =>
withTempStorage((storage) =>
withServer(app(storage), async (baseUrl) => {
const create = (title: string) =>
fetch(
`${baseUrl}/v1/playlists/p1`,
json(
{ ...m3uDocument('p1'), title },
{
method: 'PUT',
headers: { 'if-none-match': '*' },
}
)
);
expect((await create('First')).status).toBe(200);
// Another tab or device moved the same playlist first.
const second = await create('Second');
expect(second.status).toBe(412);
await expect(second.json()).resolves.toMatchObject({
code: 'conflict',
});
const stored = await fetch(`${baseUrl}/v1/playlists/p1`);
await expect(stored.json()).resolves.toMatchObject({
title: 'First',
});
})
));
it('writes user state only on the tag it was read at', () =>
withTempStorage((storage) =>
withServer(app(storage), async (baseUrl) => {
await fetch(
`${baseUrl}/v1/playlists/p1`,
json(m3uDocument('p1'), { method: 'PUT' })
);
const entry = `${baseUrl}/v1/user-state/xtream-favorites/p1`;
// Created only while absent.
const created = await fetch(
entry,
json(
{ value: ['live:1'] },
{ method: 'PUT', headers: { 'if-none-match': '*' } }
)
);
const { tag } = (await created.json()) as { tag: string };
expect(tag).toMatch(/^[0-9a-f]{16}$/);
const again = await fetch(
entry,
json(
{ value: ['live:2'] },
{ method: 'PUT', headers: { 'if-none-match': '*' } }
)
);
expect(again.status).toBe(412);
await expect(again.json()).resolves.toMatchObject({
code: 'conflict',
current: { value: ['live:1'], tag },
});
const read = (await (
await fetch(`${baseUrl}/v1/user-state`)
).json()) as ServerUserStateResponse;
expect(read.tags?.['xtream-favorites']['p1']).toBe(tag);
// Another device wrote meanwhile: a stale tag is refused.
const next = await fetch(
entry,
json(
{ value: ['live:1', 'live:9'] },
{ method: 'PUT', headers: { 'if-match': `"${tag}"` } }
)
);
const nextTag = ((await next.json()) as { tag: string }).tag;
const stale = await fetch(
entry,
json(
{ value: ['live:1', 'live:5'] },
{ method: 'PUT', headers: { 'if-match': `"${tag}"` } }
)
);
expect(stale.status).toBe(412);
await expect(stale.json()).resolves.toMatchObject({
current: { value: ['live:1', 'live:9'], tag: nextTag },
});
const removed = await fetch(entry, {
method: 'DELETE',
headers: { 'if-match': `"${nextTag}"` },
});
await expect(removed.json()).resolves.toMatchObject({
tag: null,
});
// Unconditional writes keep working for older clients.
const plain = await fetch(
entry,
json({ value: ['x'] }, { method: 'PUT' })
);
expect(plain.status).toBe(200);
})
));
it('keeps browser app state away from server-owned keys', () =>
withTempStorage((storage) =>
withServer(app(storage), async (baseUrl) => {
@@ -1,8 +1,9 @@
import express, { Router } from 'express';
import express, { Router, type Request, type Response } from 'express';
import {
isServerUserStateNamespace,
type ServerUserStateNamespace,
} from '@iptvnator/shared/interfaces';
import type { ExpectedTag } from './server-user-state-repository';
import type { ServerStorage } from './server-storage';
import { StorageRequestError } from './storage-route-errors';
@@ -18,11 +19,41 @@ export function createUserStateRouter(storage: ServerStorage): Router {
const json = express.json({ limit: USER_STATE_BODY_LIMIT });
router.get('/user-state', (_req, res) => {
res.set('Cache-Control', 'no-store').json({
entries: storage.userState.all(),
});
res.set('Cache-Control', 'no-store').json(
storage.userState.allWithTags()
);
});
const write = (req: Request, res: Response, value: unknown) => {
const namespace = requireNamespace(String(req.params['namespace']));
const playlistId = String(req.params['playlistId']);
// An edit another device queued before the playlist was deleted
// must not bring its user state back.
if (value !== undefined && !storage.playlists.exists(playlistId)) {
throw new StorageRequestError(
404,
'playlist_missing',
'The playlist does not exist.'
);
}
const result = storage.userState.writeIf(
namespace,
playlistId,
value,
expectedTag(req)
);
if ('conflict' in result) {
res.status(412).json({
message: 'The entry changed since it was read.',
status: 412,
code: 'conflict',
current: result.conflict,
});
return;
}
res.json({ success: true, tag: result.tag });
};
router.put('/user-state/:namespace/:playlistId', json, (req, res) => {
const body = req.body as { value?: unknown } | undefined;
if (!body || typeof body !== 'object' || !('value' in body)) {
@@ -32,20 +63,11 @@ export function createUserStateRouter(storage: ServerStorage): Router {
'Expected { value }.'
);
}
storage.userState.put(
requireNamespace(req.params.namespace),
req.params.playlistId,
body.value
);
res.json({ success: true });
write(req, res, body.value ?? null);
});
router.delete('/user-state/:namespace/:playlistId', (req, res) => {
storage.userState.delete(
requireNamespace(req.params.namespace),
req.params.playlistId
);
res.json({ success: true });
write(req, res, undefined);
});
router.get('/app-state/:key', (req, res) => {
@@ -75,6 +97,18 @@ export function createUserStateRouter(storage: ServerStorage): Router {
return router;
}
/**
* `If-Match: "<tag>"` expects that tag, `If-None-Match: *` expects no
* entry; without either the write is unconditional, as older clients send.
*/
function expectedTag(req: Request): ExpectedTag {
const ifMatch = req.get('if-match')?.trim();
if (ifMatch) {
return ifMatch.replace(/^W\//, '').replace(/^"|"$/g, '');
}
return req.get('if-none-match')?.trim() === '*' ? null : undefined;
}
function requireNamespace(value: string): ServerUserStateNamespace {
if (!isServerUserStateNamespace(value)) {
throw new StorageRequestError(
+9 -1
View File
@@ -4,7 +4,10 @@ import {
} from '@iptvnator/shared/host-health';
import { closeGracefully } from './app/graceful-shutdown';
import { createWebBackendApp } from './app/web-backend-app';
import { readServerStorageConfig } from './app/storage/storage-config';
import {
readServerStorageConfig,
serverStorageConfigProblem,
} from './app/storage/storage-config';
import {
openServerStorage,
type ServerStorage,
@@ -20,6 +23,11 @@ async function start(): Promise<void> {
}
const config = readServerStorageConfig();
const problem = serverStorageConfigProblem(config);
if (problem) {
console.error(`[web-backend] ${problem}`);
process.exit(1);
}
let storage: ServerStorage | null = null;
if (config.enabled) {
try {
+28
View File
@@ -1,3 +1,5 @@
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { defineConfig, devices } from '@playwright/test';
import { nxE2EPreset } from '@nx/playwright/preset';
import { workspaceRoot } from '@nx/devkit';
@@ -16,6 +18,12 @@ const webServerCommand =
: 'pnpm nx run web:serve';
const reuseExistingWebServer = isStaticPwaE2E ? false : !process.env['CI'];
const webBackendPort = process.env['WEB_BACKEND_PORT'] ?? '3333';
const storageBackendPort = process.env['STORAGE_BACKEND_PORT'] ?? '3334';
// Path only; the backend creates it. A new pid gives every run an empty store.
const storageBackendDataDir = join(
tmpdir(),
`iptvnator-web-e2e-storage-${process.pid}`
);
/**
* Read environment variables from file.
@@ -106,6 +114,26 @@ export default defineConfig({
reuseExistingServer: !process.env['CI'],
cwd: workspaceRoot,
},
/* A second backend with server storage, used only by
* server-storage.e2e.ts; the specs above keep the stateless one.
* STORAGE_BACKEND_PORT relocates it like WEB_BACKEND_PORT. */
{
command: 'node --import tsx apps/web-backend/src/main.ts',
env: {
PORT: storageBackendPort,
CLIENT_URL: `http://localhost:4200,http://localhost:${staticPwaPort}`,
BACKEND_URL: '/api',
IPTVNATOR_PROXY_ALLOW_PRIVATE_NETWORKS: '1',
TSX_TSCONFIG_PATH: 'tsconfig.base.json',
IPTVNATOR_STORAGE: 'server',
IPTVNATOR_DATA_DIR: storageBackendDataDir,
},
url: `http://localhost:${storageBackendPort}/health`,
// Never another backend on that port: the specs delete every
// playlist before each test, which would wipe its library.
reuseExistingServer: false,
cwd: workspaceRoot,
},
],
projects: [
{
+173
View File
@@ -0,0 +1,173 @@
import type { Browser, Page } from '@playwright/test';
import { expect, test } from './fixtures';
import {
addM3uUrlPlaylist,
openSources,
sourceRowByTitle,
} from './sources-pwa.helpers';
/** The storage-enabled backend from playwright.config.ts. */
const STORAGE_BACKEND_URL = `http://localhost:${
process.env['STORAGE_BACKEND_PORT'] ?? '3334'
}`;
/** A fresh browser profile (a "device") whose runtime config points at it. */
async function newServerPage(browser: Browser): Promise<Page> {
const context = await browser.newContext();
const page = await context.newPage();
await page.route('**/assets/app-config.js', (route) =>
route.fulfill({
contentType: 'application/javascript',
body: `window.__IPTVNATOR_CONFIG__ = { BACKEND_URL: ${JSON.stringify(STORAGE_BACKEND_URL)} };\n`,
})
);
return page;
}
/** A legacy browser playlist, written before the app boots. */
async function seedBrowserPlaylist(
page: Page,
id: string,
title: string
): Promise<void> {
await page.route('**/__indexeddb-seed__', (route) =>
route.fulfill({ contentType: 'text/html', body: '<!doctype html>' })
);
await page.goto('/__indexeddb-seed__');
await page.evaluate(
([playlistId, playlistTitle]) =>
new Promise<void>((resolve, reject) => {
const request = indexedDB.open('iptvnator', 1);
request.onerror = () => reject(request.error);
request.onupgradeneeded = () => {
const store = request.result.createObjectStore(
'playlists',
{ keyPath: '_id', autoIncrement: false }
);
for (const name of [
'_id',
'filename',
'title',
'count',
'playlist',
'importDate',
'lastUsage',
'favorites',
'recentlyViewed',
'autoRefresh',
'url',
'filePath',
]) {
store.createIndex(name, name, { unique: false });
}
};
request.onsuccess = () => {
const db = request.result;
const transaction = db.transaction(
'playlists',
'readwrite'
);
transaction.oncomplete = () => {
db.close();
resolve();
};
transaction.onabort = () => {
db.close();
reject(transaction.error);
};
transaction.objectStore('playlists').add({
_id: playlistId,
title: playlistTitle,
importDate: '2026-01-01T00:00:00.000Z',
lastUsage: '2026-01-01T00:00:00.000Z',
count: 1,
autoRefresh: false,
favorites: [],
recentlyViewed: [],
playlist: {
header: { attrs: {}, raw: '#EXTM3U' },
items: [
{
id: 'c1',
name: 'Channel',
url: 'https://example.invalid/c1.m3u8',
},
],
},
});
};
}),
[id, title] as const
);
}
test.describe('server storage @self-hosted @persistence', () => {
// Both tests share one server database, and so would the other browser
// projects: keep it to one browser.
test.describe.configure({ mode: 'serial' });
test.skip(
({ browserName }) => browserName !== 'chromium',
'One shared server database'
);
test.beforeEach(async ({ request }) => {
const response = await request.delete(
`${STORAGE_BACKEND_URL}/v1/playlists`
);
expect(response.ok()).toBe(true);
});
test('a playlist added on one device appears on another', async ({
browser,
}) => {
const first = await newServerPage(browser);
await openSources(first);
await addM3uUrlPlaylist(first, 'Shared M3U');
const second = await newServerPage(browser);
await openSources(second);
await expect(sourceRowByTitle(second, 'Shared M3U')).toBeVisible();
await first.context().close();
await second.context().close();
});
test('moves browser playlists to an empty server', async ({
browser,
request,
}) => {
const page = await newServerPage(browser);
await seedBrowserPlaylist(page, 'browser-only', 'Browser only');
await page.goto('/workspace/sources');
const dialog = page.locator('mat-dialog-container');
await expect(dialog).toContainText('Browser only');
await dialog.locator('[data-test-id="server-migration-move"]').click();
await expect(
dialog.locator('[data-test-id="server-migration-reload"]')
).toBeVisible();
const response = await request.get(
`${STORAGE_BACKEND_URL}/v1/playlists?view=meta`
);
const metas = (await response.json()) as {
_id: string;
title: string;
}[];
expect(metas).toEqual([
expect.objectContaining({
_id: 'browser-only',
title: 'Browser only',
}),
]);
// After the reload the library comes from the server.
await dialog
.locator('[data-test-id="server-migration-reload"]')
.click();
await expect(sourceRowByTitle(page, 'Browser only')).toBeVisible();
await expect(page.locator('mat-dialog-container')).toHaveCount(0);
await page.context().close();
});
});
@@ -6,6 +6,7 @@ import {
selectPlaylistsLoadFailed,
selectPlaylistsLoadingFlag,
} from '@iptvnator/m3u-state';
import { provideRouter, Router } from '@angular/router';
import { AppStartupStatusComponent } from './app-startup-status.component';
describe('AppStartupStatusComponent', () => {
@@ -13,6 +14,7 @@ describe('AppStartupStatusComponent', () => {
TestBed.configureTestingModule({
imports: [AppStartupStatusComponent, TranslateModule.forRoot()],
providers: [
provideRouter([{ path: 'server-sign-in', children: [] }]),
provideMockStore({
selectors: [
{ selector: selectPlaylistsLoadingFlag, value: false },
@@ -48,6 +50,23 @@ describe('AppStartupStatusComponent', () => {
expect(fixture.componentInstance.complete()).toBe(true);
});
it('shows the server sign-in page although sources could not load', async () => {
TestBed.inject(MockStore).overrideSelector(
selectPlaylistsLoadFailed,
true
);
const fixture = TestBed.createComponent(AppStartupStatusComponent);
fixture.componentRef.setInput('routeReady', true);
fixture.detectChanges();
expect(fixture.componentInstance.complete()).toBe(false);
await TestBed.inject(Router).navigateByUrl('/server-sign-in');
fixture.detectChanges();
expect(fixture.componentInstance.complete()).toBe(true);
expect(fixture.nativeElement.querySelector('section')).toBeNull();
});
it('offers a retry on failure without rendering raw storage errors', () => {
TestBed.inject(MockStore).overrideSelector(
selectPlaylistsLoadFailed,
@@ -5,14 +5,18 @@ import {
inject,
input,
} from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { NavigationEnd, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { TranslatePipe } from '@ngx-translate/core';
import { filter, map } from 'rxjs';
import {
PlaylistActions,
selectPlaylistsLoadFailed,
selectPlaylistsLoadingFlag,
} from '@iptvnator/m3u-state';
import { SERVER_SIGN_IN_PATH } from '@iptvnator/services';
/** The first route also waits for settings and XMLTV source reconciliation. */
@Component({
@@ -304,8 +308,23 @@ export class AppStartupStatusComponent {
selectPlaylistsLoadingFlag
);
readonly failed = this.store.selectSignal(selectPlaylistsLoadFailed);
private readonly router = inject(Router);
private readonly url = toSignal(
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map((event) => event.urlAfterRedirects)
),
{ initialValue: this.router.url }
);
/**
* Server storage asking for a token: the playlists cannot load, and the
* sign-in page must stay up whatever its check reports.
*/
private readonly onSignInPage = computed(() =>
this.url().startsWith(SERVER_SIGN_IN_PATH)
);
readonly complete = computed(
() => this.routeReady() && this.sourcesReady()
() => this.routeReady() && (this.sourcesReady() || this.onSignInPage())
);
retry(): void {
+13
View File
@@ -6,6 +6,10 @@ import {
SettingsStore,
} from '@iptvnator/services';
import { WorkspaceStartupPreferencesService } from '@iptvnator/workspace/shell/util';
import {
serverAccessGuard,
serverSignInGuard,
} from './server-storage/server-access.guard';
import { settingsUnsavedChangesGuard } from './settings/settings-unsaved-changes.guard';
// The workspace activates only once settings AND the parental lock state
@@ -77,6 +81,7 @@ export const routes: Routes = [
},
{
path: 'workspace',
canActivate: [serverAccessGuard],
resolve: {
settingsReady: settingsReadyResolver,
},
@@ -207,6 +212,14 @@ export const routes: Routes = [
},
],
},
{
path: 'server-sign-in',
canActivate: [serverSignInGuard],
loadComponent: () =>
import('./server-storage/server-sign-in.component').then(
(c) => c.ServerSignInComponent
),
},
{
path: 'settings',
redirectTo: '/workspace/settings',
@@ -0,0 +1,47 @@
import { TestBed } from '@angular/core/testing';
import { provideRouter, Router, UrlTree } from '@angular/router';
import { ServerStorageStatusService } from '@iptvnator/services';
import { serverAccessGuard, serverSignInGuard } from './server-access.guard';
describe('server access guards', () => {
function run(guard: typeof serverAccessGuard, state: string) {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
provideRouter([]),
{
provide: ServerStorageStatusService,
useValue: { state: () => state },
},
],
});
return TestBed.runInInjectionContext(() =>
guard({} as never, {} as never)
);
}
const serialize = (result: unknown) =>
TestBed.inject(Router).serializeUrl(result as UrlTree);
afterEach(() => TestBed.resetTestingModule());
it('sends an unauthorized workspace visit to the sign-in page', () => {
expect(serialize(run(serverAccessGuard, 'unauthorized'))).toBe(
'/server-sign-in'
);
});
it('lets everyone else into the workspace', () => {
expect(run(serverAccessGuard, 'online')).toBe(true);
expect(run(serverAccessGuard, 'offline')).toBe(true);
expect(run(serverAccessGuard, 'inactive')).toBe(true);
});
it('opens the sign-in page only while unauthorized', () => {
expect(run(serverSignInGuard, 'unauthorized')).toBe(true);
expect(serialize(run(serverSignInGuard, 'online'))).toBe('/workspace');
expect(serialize(run(serverSignInGuard, 'inactive'))).toBe(
'/workspace'
);
});
});
@@ -0,0 +1,17 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import {
SERVER_SIGN_IN_PATH,
ServerStorageStatusService,
} from '@iptvnator/services';
/** Without a valid token the workspace would show an empty library. */
export const serverAccessGuard: CanActivateFn = () =>
inject(ServerStorageStatusService).state() === 'unauthorized'
? inject(Router).parseUrl(SERVER_SIGN_IN_PATH)
: true;
export const serverSignInGuard: CanActivateFn = () =>
inject(ServerStorageStatusService).state() === 'unauthorized'
? true
: inject(Router).parseUrl('/workspace');
@@ -0,0 +1,120 @@
import { markSlowStart } from '@iptvnator/services';
import { probeServerInstance } from './server-instance-probe';
const instance = {
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i-1',
storage: 'server',
auth: 'none',
};
describe('probeServerInstance', () => {
const answer = (body: unknown, status = 200) =>
jest.fn().mockResolvedValue({
ok: status >= 200 && status < 300,
status,
json: async () => body,
});
const config = {
runtimeConfig: { BACKEND_URL: '/api' },
isElectron: false,
};
it('skips the probe without a runtime backend URL', async () => {
const fetchFn = answer(instance);
await expect(
probeServerInstance({
runtimeConfig: {},
fetchFn: fetchFn as never,
})
).resolves.toEqual({ kind: 'skipped' });
expect(fetchFn).not.toHaveBeenCalled();
});
it('skips the probe in Electron', async () => {
const fetchFn = answer(instance);
await expect(
probeServerInstance({
...config,
isElectron: true,
fetchFn: fetchFn as never,
})
).resolves.toEqual({ kind: 'skipped' });
expect(fetchFn).not.toHaveBeenCalled();
});
it('returns the instance when it reports server storage', async () => {
const fetchFn = answer(instance);
await expect(
probeServerInstance({
runtimeConfig: { BACKEND_URL: '/api/' },
isElectron: false,
fetchFn: fetchFn as never,
})
).resolves.toEqual({ kind: 'server', instance });
expect(fetchFn.mock.calls[0][0]).toBe('/api/v1/instance');
});
it('waits longer once after a reload for a server that answered late', async () => {
const timeout = jest.spyOn(AbortSignal, 'timeout');
try {
markSlowStart();
await probeServerInstance({
...config,
fetchFn: answer(instance) as never,
});
await probeServerInstance({
...config,
fetchFn: answer(instance) as never,
});
// A slow server otherwise times out again and reloads forever.
expect(timeout.mock.calls.map(([ms]) => ms)).toEqual([
20_000, 2_500,
]);
} finally {
timeout.mockRestore();
}
});
it('reports no server storage for an answer without it', async () => {
for (const fetchFn of [
answer({ ...instance, storage: 'none' }),
answer({ hello: 1 }),
answer({ error: 'not found' }, 404),
jest.fn().mockResolvedValue({
ok: true,
status: 200,
json: async () => {
throw new SyntaxError('not json');
},
}),
]) {
await expect(
probeServerInstance({ ...config, fetchFn: fetchFn as never })
).resolves.toEqual({ kind: 'none' });
}
});
it('reports an unreachable server for failures, 5xx and refusals', async () => {
for (const fetchFn of [
jest.fn().mockRejectedValue(new TypeError('Failed to fetch')),
answer('Bad Gateway', 502),
answer('Too Many Requests', 429),
answer('Forbidden', 403),
// Headers arrived, then the body was cut off.
jest.fn().mockResolvedValue({
ok: true,
status: 200,
json: async () => {
throw new DOMException('aborted', 'AbortError');
},
}),
]) {
await expect(
probeServerInstance({ ...config, fetchFn: fetchFn as never })
).resolves.toEqual({ kind: 'unreachable' });
}
});
});
@@ -0,0 +1,92 @@
import { RuntimeCapabilitiesService, takeSlowStart } from '@iptvnator/services';
import type { ServerInstanceInfo } from '@iptvnator/shared/interfaces';
import type { IptvnatorRuntimeConfig } from '../services/runtime-config';
const PROBE_TIMEOUT_MS = 2_500;
/** After a reload for a server that answered later: as long as requests. */
const SLOW_PROBE_TIMEOUT_MS = 20_000;
/**
* - `skipped`: no runtime backend URL, or Electron.
* - `server` / `none`: the backend answered (a 404 is an older backend).
* - `unreachable`: no answer, a timeout, a 5xx (nginx answers 502 while
* the backend restarts) or another refusal such as a proxy's 429, so the
* result says nothing about storage.
*/
export type ServerInstanceProbe =
| { readonly kind: 'skipped' | 'none' | 'unreachable' }
| { readonly kind: 'server'; readonly instance: ServerInstanceInfo };
export interface ServerInstanceProbeOptions {
readonly runtimeConfig?: IptvnatorRuntimeConfig;
readonly isElectron?: boolean;
readonly fetchFn?: typeof fetch;
}
/**
* Asks the backend whether it offers server storage. Runs only when the
* deployment wrote a runtime `BACKEND_URL` (the Docker entrypoint does), so
* hosted builds never call an external parser API for it.
*/
export async function probeServerInstance(
options: ServerInstanceProbeOptions = {}
): Promise<ServerInstanceProbe> {
const runtimeConfig =
options.runtimeConfig ?? globalThis.window?.__IPTVNATOR_CONFIG__;
// The capability service has no dependencies, so it works before
// bootstrap and keeps one definition of the desktop runtime.
const isElectron =
options.isElectron ?? new RuntimeCapabilitiesService().isElectron;
const baseUrl = runtimeConfig?.BACKEND_URL?.trim();
if (isElectron || !baseUrl) {
return { kind: 'skipped' };
}
let response: Response;
try {
const fetchFn = options.fetchFn ?? globalThis.fetch.bind(globalThis);
response = await fetchFn(`${baseUrl.replace(/\/+$/, '')}/v1/instance`, {
cache: 'no-store',
signal:
typeof AbortSignal.timeout === 'function'
? AbortSignal.timeout(
takeSlowStart()
? SLOW_PROBE_TIMEOUT_MS
: PROBE_TIMEOUT_MS
)
: undefined,
});
} catch {
return { kind: 'unreachable' };
}
if (response.status === 404) {
// A backend from before server storage has no /v1 routes.
return { kind: 'none' };
}
if (!response.ok) {
return { kind: 'unreachable' };
}
try {
const body: unknown = await response.json();
return isServerInstance(body) && body.storage === 'server'
? { kind: 'server', instance: body }
: { kind: 'none' };
} catch (error) {
// Unparseable JSON is an answer; a cut-off body is an outage.
return error instanceof SyntaxError
? { kind: 'none' }
: { kind: 'unreachable' };
}
}
function isServerInstance(value: unknown): value is ServerInstanceInfo {
const record = value as Partial<ServerInstanceInfo> | null;
return (
!!record &&
record.service === 'iptvnator' &&
typeof record.apiVersion === 'number' &&
typeof record.instanceId === 'string' &&
(record.storage === 'server' || record.storage === 'none') &&
(record.auth === 'none' || record.auth === 'token')
);
}
@@ -0,0 +1,69 @@
<h2 mat-dialog-title>
{{
'SERVER_STORAGE.MIGRATION_TITLE'
| translate: { count: playlists.length }
}}
</h2>
<mat-dialog-content class="server-migration">
@if (result(); as done) {
<p data-test-id="server-migration-result">
{{ 'SERVER_STORAGE.MIGRATION_DONE' | translate: done }}
</p>
} @else {
<p>{{ 'SERVER_STORAGE.MIGRATION_DESCRIPTION' | translate }}</p>
<ul class="server-migration__list">
@for (playlist of playlists; track playlist.id) {
<li>
<mat-icon aria-hidden="true">{{
icons[playlist.kind]
}}</mat-icon>
<span>{{ playlist.title }}</span>
</li>
}
</ul>
<p class="server-migration__hint">
{{ 'SERVER_STORAGE.MIGRATION_LATER_HINT' | translate }}
</p>
@if (failed()) {
<p class="server-migration__error" role="status">
{{ 'SERVER_STORAGE.MIGRATION_FAILED' | translate }}
</p>
}
}
</mat-dialog-content>
<mat-dialog-actions align="end">
@if (result()) {
<button
mat-flat-button
type="button"
(click)="reload()"
data-test-id="server-migration-reload"
>
{{ 'SERVER_STORAGE.MIGRATION_RELOAD' | translate }}
</button>
} @else {
<button
mat-button
type="button"
[disabled]="busy()"
(click)="notNow()"
data-test-id="server-migration-not-now"
>
{{ 'SERVER_STORAGE.MIGRATION_NOT_NOW' | translate }}
</button>
<button
mat-flat-button
type="button"
[disabled]="busy()"
(click)="move()"
data-test-id="server-migration-move"
>
@if (busy()) {
<mat-progress-spinner diameter="16" mode="indeterminate" />
}
{{ 'SERVER_STORAGE.MIGRATION_MOVE' | translate }}
</button>
}
</mat-dialog-actions>
@@ -0,0 +1,46 @@
.server-migration {
p {
margin: 0 0 12px;
color: var(--app-body-color);
}
}
.server-migration__list {
list-style: none;
margin: 0 0 12px;
padding: 0;
display: flex;
flex-direction: column;
gap: 6px;
li {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 10px 12px;
border-radius: 12px;
background: var(--app-card-hover-bg);
color: var(--app-heading-color);
mat-icon {
flex-shrink: 0;
}
span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
}
.server-migration .server-migration__hint {
color: var(--app-muted-color);
font-size: 0.8rem;
}
.server-migration .server-migration__error {
color: var(--app-expiry-expired-text);
}
@@ -0,0 +1,72 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { ServerMigrationService } from '@iptvnator/services/server-storage';
import { ServerMigrationDialogComponent } from './server-migration-dialog.component';
describe('ServerMigrationDialogComponent', () => {
let fixture: ComponentFixture<ServerMigrationDialogComponent>;
const migration = { skip: jest.fn(), moveBrowserData: jest.fn() };
const dialogRef = { close: jest.fn() };
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
ServerMigrationDialogComponent,
TranslateModule.forRoot(),
],
providers: [
{
provide: MAT_DIALOG_DATA,
useValue: [{ id: 'm', title: 'Family', kind: 'm3u' }],
},
{ provide: ServerMigrationService, useValue: migration },
{ provide: MatDialogRef, useValue: dialogRef },
],
}).compileComponents();
fixture = TestBed.createComponent(ServerMigrationDialogComponent);
fixture.detectChanges();
});
afterEach(() => jest.resetAllMocks());
const byTestId = (id: string) =>
fixture.nativeElement.querySelector(`[data-test-id="${id}"]`);
it('lists the browser playlists', () => {
expect(fixture.nativeElement.textContent).toContain('Family');
});
it('records "not now" and closes', () => {
byTestId('server-migration-not-now').click();
expect(migration.skip).toHaveBeenCalled();
expect(dialogRef.close).toHaveBeenCalled();
});
it('moves the data and offers a reload', async () => {
const result = { imported: 1, merged: 0, failed: 0 };
migration.moveBrowserData.mockResolvedValue(result);
await fixture.componentInstance.move();
fixture.detectChanges();
expect(fixture.componentInstance.result()).toEqual(result);
expect(byTestId('server-migration-result')).not.toBeNull();
expect(byTestId('server-migration-reload')).not.toBeNull();
expect(byTestId('server-migration-move')).toBeNull();
});
it('keeps the dialog open with a message when moving fails', async () => {
migration.moveBrowserData.mockRejectedValue(new Error('offline'));
await fixture.componentInstance.move();
fixture.detectChanges();
expect(fixture.componentInstance.failed()).toBe(true);
expect(fixture.nativeElement.textContent).toContain(
'SERVER_STORAGE.MIGRATION_FAILED'
);
expect(dialogRef.close).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,70 @@
import {
ChangeDetectionStrategy,
Component,
inject,
signal,
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { TranslatePipe } from '@ngx-translate/core';
import {
ServerMigrationService,
type ServerMigrationPlaylist,
type ServerMigrationResult,
} from '@iptvnator/services/server-storage';
import { SOURCE_TYPE_ICONS } from '@iptvnator/shared/interfaces';
@Component({
selector: 'app-server-migration-dialog',
imports: [
MatButtonModule,
MatDialogModule,
MatIconModule,
MatProgressSpinnerModule,
TranslatePipe,
],
templateUrl: './server-migration-dialog.component.html',
styleUrl: './server-migration-dialog.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ServerMigrationDialogComponent {
private readonly migration = inject(ServerMigrationService);
private readonly dialogRef = inject(
MatDialogRef<ServerMigrationDialogComponent>
);
readonly playlists =
inject<readonly ServerMigrationPlaylist[]>(MAT_DIALOG_DATA);
readonly icons = SOURCE_TYPE_ICONS;
readonly busy = signal(false);
readonly failed = signal(false);
readonly result = signal<ServerMigrationResult | null>(null);
notNow(): void {
this.migration.skip();
this.dialogRef.close();
}
async move(): Promise<void> {
this.busy.set(true);
this.failed.set(false);
try {
this.result.set(await this.migration.moveBrowserData());
} catch {
this.failed.set(true);
} finally {
this.busy.set(false);
}
}
/** The library was replaced underneath every open view. */
reload(): void {
window.location.reload();
}
}
@@ -0,0 +1,50 @@
import { inject, Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { NavigationEnd, Router } from '@angular/router';
import { filter, take } from 'rxjs';
import { ServerStorageStatusService } from '@iptvnator/services';
import {
ServerMigrationService,
type ServerMigrationPlaylist,
} from '@iptvnator/services/server-storage';
/** Opens the migration dialog once, after the first navigation settles. */
@Injectable({ providedIn: 'root' })
export class ServerMigrationPrompt {
private readonly router = inject(Router);
private readonly dialog = inject(MatDialog);
private readonly status = inject(ServerStorageStatusService);
private readonly migration = inject(ServerMigrationService);
schedule(): void {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
take(1)
)
.subscribe(() => void this.offer());
}
private async offer(): Promise<void> {
if (this.status.state() !== 'online') {
return;
}
let playlists: ServerMigrationPlaylist[] | null;
try {
playlists = await this.migration.offerOnStartup();
} catch {
return; // IndexedDB or server unreadable: ask again next start.
}
if (!playlists) {
return;
}
const { ServerMigrationDialogComponent } =
await import('./server-migration-dialog.component');
this.dialog.open(ServerMigrationDialogComponent, {
data: playlists,
width: '540px',
maxWidth: 'calc(100vw - 32px)',
disableClose: true,
});
}
}
@@ -0,0 +1,65 @@
<main class="server-sign-in">
<form class="server-sign-in__card" (submit)="submit($event)">
<img
class="server-sign-in__logo"
src="./assets/icons/icon-tv-256.png"
alt=""
width="40"
height="40"
/>
<h1>{{ 'SERVER_STORAGE.SIGN_IN_TITLE' | translate }}</h1>
<p>{{ 'SERVER_STORAGE.SIGN_IN_DESCRIPTION' | translate }}</p>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{
'SERVER_STORAGE.SIGN_IN_TOKEN_LABEL' | translate
}}</mat-label>
<input
matInput
id="server-access-token"
autocomplete="current-password"
[type]="tokenToggle.inputType()"
[value]="token()"
(input)="edit($any($event.target).value)"
data-test-id="server-sign-in-token"
/>
<button
mat-icon-button
matSuffix
appPasswordVisibilityToggle
#tokenToggle="appPasswordVisibilityToggle"
[attr.aria-label]="'HOME.SHOW_PASSWORD' | translate"
>
<mat-icon>{{ tokenToggle.icon() }}</mat-icon>
</button>
<mat-hint>{{ 'SERVER_STORAGE.SIGN_IN_HINT' | translate }}</mat-hint>
</mat-form-field>
<p
class="server-sign-in__feedback"
role="status"
data-test-id="server-sign-in-feedback"
>
@switch (feedback()) {
@case ('rejected') {
{{ 'SERVER_STORAGE.SIGN_IN_REJECTED' | translate }}
}
@case ('unreachable') {
{{ 'SERVER_STORAGE.SIGN_IN_UNREACHABLE' | translate }}
}
@case ('storage') {
{{ 'SERVER_STORAGE.SIGN_IN_STORAGE' | translate }}
}
}
</p>
<button
mat-flat-button
type="submit"
[disabled]="busy() || !token().trim()"
data-test-id="server-sign-in-submit"
>
{{ 'SERVER_STORAGE.SIGN_IN_CONTINUE' | translate }}
</button>
</form>
</main>
@@ -0,0 +1,56 @@
:host {
display: block;
min-height: 100%;
background: var(--app-shell-bg);
}
.server-sign-in {
min-height: 100vh;
display: grid;
place-items: center;
padding: 16px;
box-sizing: border-box;
}
.server-sign-in__card {
width: min(100%, 420px);
display: flex;
flex-direction: column;
gap: 14px;
padding: 28px;
box-sizing: border-box;
border-radius: 20px;
background: var(--app-widget-bg);
box-shadow: var(--app-widget-shadow);
color: var(--app-on-surface);
h1 {
margin: 0;
font-size: 1.3rem;
font-weight: 600;
color: var(--app-heading-color);
}
p {
margin: 0;
color: var(--app-body-color);
font-size: 0.9rem;
line-height: 1.45;
}
button[type='submit'] {
align-self: flex-end;
}
}
.server-sign-in__logo {
border-radius: 12px;
}
.server-sign-in .server-sign-in__feedback {
color: var(--app-expiry-expired-text);
&:empty {
display: none;
}
}
@@ -0,0 +1,202 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import {
readServerAccessToken,
writeServerAccessToken,
} from '@iptvnator/services';
import {
SERVER_STORAGE_CONFIG,
ServerApiError,
ServerStorageSession,
} from '@iptvnator/services/server-storage';
import { REMEMBERED_SERVER_KEY } from './server-storage-start';
import { ServerSignInComponent } from './server-sign-in.component';
const TOKEN_KEY = 'iptvnator-server:access-token';
describe('ServerSignInComponent', () => {
let fixture: ComponentFixture<ServerSignInComponent>;
let component: ServerSignInComponent;
const session = { fetchStatus: jest.fn(), ensureVerified: jest.fn() };
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ServerSignInComponent, TranslateModule.forRoot()],
providers: [
{ provide: ServerStorageSession, useValue: session },
{
provide: SERVER_STORAGE_CONFIG,
useValue: {
baseUrl: '/api',
instance: {
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i-1',
storage: 'server',
auth: 'token',
},
},
},
],
}).compileComponents();
fixture = TestBed.createComponent(ServerSignInComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
afterEach(() => {
localStorage.clear();
jest.resetAllMocks();
});
const feedbackText = () =>
fixture.nativeElement
.querySelector('[data-test-id="server-sign-in-feedback"]')
.textContent.trim();
it('keeps an accepted token and reloads into the workspace', async () => {
session.fetchStatus.mockResolvedValue({ playlists: 0 });
const open = jest
.spyOn(component, 'openWorkspace')
.mockImplementation(() => undefined);
component.edit(' right ');
await component.submit(new Event('submit'));
expect(localStorage.getItem(TOKEN_KEY)).toBe('right');
// Only for the instance it was given for.
expect(readServerAccessToken('i-1')).toBe('right');
expect(readServerAccessToken('i-2')).toBeNull();
expect(open).toHaveBeenCalled();
});
it('says the token was refused and forgets it', async () => {
session.fetchStatus.mockRejectedValue(
new ServerApiError(401, 'unauthorized', 'refused')
);
component.edit('wrong');
await component.submit(new Event('submit'));
fixture.detectChanges();
expect(component.feedback()).toBe('rejected');
expect(feedbackText()).toBe('SERVER_STORAGE.SIGN_IN_REJECTED');
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
});
it("keeps another tab's newer sign-in when this attempt fails", async () => {
session.fetchStatus.mockImplementation(async () => {
// Another tab signs in while this answer is on its way.
writeServerAccessToken('right', 'i-1');
throw new ServerApiError(401, 'unauthorized', 'refused');
});
component.edit('wrong');
await component.submit(new Event('submit'));
expect(component.feedback()).toBe('rejected');
expect(readServerAccessToken('i-1')).toBe('right');
});
it('leaves a token another tab stored to it after a network failure', async () => {
session.fetchStatus.mockImplementation(async () => {
// Another tab signs in with the same token meanwhile.
writeServerAccessToken('right', 'i-1');
throw new ServerApiError(0, 'network', 'offline');
});
component.edit('right');
await component.submit(new Event('submit'));
expect(component.feedback()).toBe('unreachable');
expect(readServerAccessToken('i-1')).toBe('right');
});
it('tells an unreachable server apart and clears the message on edit', async () => {
session.fetchStatus.mockRejectedValue(
new ServerApiError(0, undefined, 'offline')
);
component.edit('token');
await component.submit(new Event('submit'));
fixture.detectChanges();
expect(feedbackText()).toBe('SERVER_STORAGE.SIGN_IN_UNREACHABLE');
component.edit('token2');
fixture.detectChanges();
expect(feedbackText()).toBe('');
});
it('does not submit an empty token', async () => {
component.edit(' ');
await component.submit(new Event('submit'));
expect(session.fetchStatus).not.toHaveBeenCalled();
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
});
it('says when the browser will not keep the token', async () => {
const refuse = jest
.spyOn(Storage.prototype, 'setItem')
.mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError');
});
try {
component.edit('right');
await component.submit(new Event('submit'));
fixture.detectChanges();
} finally {
refuse.mockRestore();
}
expect(session.fetchStatus).not.toHaveBeenCalled();
expect(feedbackText()).toBe('SERVER_STORAGE.SIGN_IN_STORAGE');
});
it('remembers the server the token was accepted for', async () => {
session.fetchStatus.mockResolvedValue({ playlists: 0 });
jest.spyOn(component, 'openWorkspace').mockImplementation(
() => undefined
);
component.edit('right');
await component.submit(new Event('submit'));
expect(
JSON.parse(localStorage.getItem(REMEMBERED_SERVER_KEY) ?? '{}')
).toMatchObject({ baseUrl: '/api', instance: { instanceId: 'i-1' } });
});
it('signs in only when the server can be remembered too', async () => {
const refuse = jest
.spyOn(Storage.prototype, 'setItem')
.mockImplementation((key: string) => {
if (key === REMEMBERED_SERVER_KEY) {
throw new DOMException('full', 'QuotaExceededError');
}
});
try {
component.edit('right');
await component.submit(new Event('submit'));
fixture.detectChanges();
} finally {
refuse.mockRestore();
}
expect(session.fetchStatus).not.toHaveBeenCalled();
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
expect(feedbackText()).toBe('SERVER_STORAGE.SIGN_IN_STORAGE');
});
it('sends the token only after the server proved to be the remembered one', async () => {
session.ensureVerified.mockRejectedValue(new Error('another server'));
component.edit('right');
await component.submit(new Event('submit'));
fixture.detectChanges();
expect(session.fetchStatus).not.toHaveBeenCalled();
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
expect(feedbackText()).toBe('SERVER_STORAGE.SIGN_IN_UNREACHABLE');
});
});
@@ -0,0 +1,115 @@
import {
ChangeDetectionStrategy,
Component,
inject,
signal,
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { TranslatePipe } from '@ngx-translate/core';
import {
clearServerAccessToken,
readServerAccessToken,
writeServerAccessToken,
} from '@iptvnator/services';
import {
SERVER_STORAGE_CONFIG,
ServerApiError,
ServerStorageSession,
} from '@iptvnator/services/server-storage';
import { rememberServer } from './server-storage-start';
import { provideFormFieldDefaults } from '@iptvnator/ui/components/form-field-defaults';
import { PasswordVisibilityToggleDirective } from '@iptvnator/ui/components/password-visibility-toggle';
export type ServerSignInFeedback = 'rejected' | 'unreachable' | 'storage';
@Component({
selector: 'app-server-sign-in',
imports: [
MatButtonModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
PasswordVisibilityToggleDirective,
TranslatePipe,
],
providers: [provideFormFieldDefaults()],
templateUrl: './server-sign-in.component.html',
styleUrl: './server-sign-in.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ServerSignInComponent {
private readonly session = inject(ServerStorageSession);
private readonly config = inject(SERVER_STORAGE_CONFIG);
readonly token = signal('');
readonly busy = signal(false);
readonly feedback = signal<ServerSignInFeedback | null>(null);
edit(value: string): void {
this.token.set(value);
this.feedback.set(null);
}
async submit(event: Event): Promise<void> {
event.preventDefault();
const token = this.token().trim();
if (!token || this.busy()) {
return;
}
this.busy.set(true);
this.feedback.set(null);
try {
// A page started from memory checks the server first: the token
// must reach only the one it is meant for.
await this.session.ensureVerified();
} catch {
this.feedback.set('unreachable');
this.busy.set(false);
return;
}
// Every request and the reload read the token from storage, and the
// next start keeps it only for the server it remembers.
if (
!writeServerAccessToken(token, this.config.instance.instanceId) ||
!rememberServer(this.config.baseUrl, this.config.instance)
) {
forgetAttempt(token);
this.feedback.set('storage');
this.busy.set(false);
return;
}
try {
await this.session.fetchStatus();
this.openWorkspace();
} catch (error) {
const rejected =
error instanceof ServerApiError && error.status === 401;
// A refused token is no one's. A network failure says nothing
// about it, and another tab may have stored the same one since.
if (rejected) {
forgetAttempt(token);
}
this.feedback.set(rejected ? 'rejected' : 'unreachable');
} finally {
this.busy.set(false);
}
}
/** Full reload so every service starts with the token. */
openWorkspace(): void {
window.location.assign(new URL('workspace', document.baseURI).href);
}
}
/**
* Forgets a token whose sign-in failed, unless another tab has signed in
* since: its token replaced this one and is not this attempt's to clear.
*/
function forgetAttempt(token: string): void {
if (readServerAccessToken() === token) {
clearServerAccessToken();
}
}
@@ -0,0 +1,119 @@
import type { ServerInstanceInfo } from '@iptvnator/shared/interfaces';
import {
REMEMBERED_SERVER_KEY,
resolveServerStorageStart,
} from './server-storage-start';
const instance: ServerInstanceInfo = {
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i-1',
storage: 'server',
auth: 'none',
};
describe('resolveServerStorageStart', () => {
afterEach(() => localStorage.clear());
it('starts online and remembers a server that answered', () => {
expect(
resolveServerStorageStart({ kind: 'server', instance }, '/api')
).toEqual({ instance, startedOffline: false });
expect(
JSON.parse(localStorage.getItem(REMEMBERED_SERVER_KEY) ?? '')
).toEqual({ baseUrl: '/api', instance });
});
it('starts offline when a remembered server does not answer', () => {
resolveServerStorageStart({ kind: 'server', instance }, '/api');
expect(
resolveServerStorageStart({ kind: 'unreachable' }, '/api')
).toEqual({ instance, startedOffline: true });
});
it('matches the remembered server however its URL is written', () => {
resolveServerStorageStart({ kind: 'server', instance }, '/api');
for (const spelling of ['/api/', ' /api', `${location.origin}/api//`]) {
expect(
resolveServerStorageStart({ kind: 'unreachable' }, spelling)
).toEqual({ instance, startedOffline: true });
}
expect(
resolveServerStorageStart({ kind: 'unreachable' }, '/apis')
).toBeNull();
});
it('keeps the token only for the same server and database', () => {
const token = 'iptvnator-server:access-token';
resolveServerStorageStart({ kind: 'server', instance }, '/api');
localStorage.setItem(token, 'secret');
resolveServerStorageStart({ kind: 'server', instance }, '/api/');
expect(localStorage.getItem(token)).toBe('secret');
resolveServerStorageStart(
{ kind: 'server', instance: { ...instance, instanceId: 'i-2' } },
'/api'
);
expect(localStorage.getItem(token)).toBeNull();
localStorage.setItem(token, 'secret');
resolveServerStorageStart(
{ kind: 'server', instance: { ...instance, instanceId: 'i-2' } },
'/other'
);
expect(localStorage.getItem(token)).toBeNull();
});
it('forgets the token of a server that no longer offers storage', () => {
localStorage.setItem('iptvnator-server:access-token', 'old');
resolveServerStorageStart({ kind: 'none' }, '/api');
expect(
localStorage.getItem('iptvnator-server:access-token')
).toBeNull();
});
it('uses browser mode for an unknown or different server', () => {
expect(
resolveServerStorageStart({ kind: 'unreachable' }, '/api')
).toBeNull();
resolveServerStorageStart({ kind: 'server', instance }, '/api');
expect(
resolveServerStorageStart(
{ kind: 'unreachable' },
'http://other:3000'
)
).toBeNull();
});
it('forgets the server once it answers without server storage', () => {
resolveServerStorageStart({ kind: 'server', instance }, '/api');
expect(resolveServerStorageStart({ kind: 'none' }, '/api')).toBeNull();
expect(localStorage.getItem(REMEMBERED_SERVER_KEY)).toBeNull();
expect(
resolveServerStorageStart({ kind: 'unreachable' }, '/api')
).toBeNull();
});
it('ignores a skipped probe and unreadable memory', () => {
resolveServerStorageStart({ kind: 'server', instance }, '/api');
expect(
resolveServerStorageStart({ kind: 'skipped' }, '/api')
).toBeNull();
expect(localStorage.getItem(REMEMBERED_SERVER_KEY)).not.toBeNull();
localStorage.setItem(REMEMBERED_SERVER_KEY, '{broken');
expect(
resolveServerStorageStart({ kind: 'unreachable' }, '/api')
).toBeNull();
expect(
resolveServerStorageStart({ kind: 'unreachable' }, '/api', null)
).toBeNull();
});
});
@@ -0,0 +1,137 @@
import { clearServerAccessToken } from '@iptvnator/services';
import type { ServerInstanceInfo } from '@iptvnator/shared/interfaces';
import type { ServerInstanceProbe } from './server-instance-probe';
/** Last instance this browser saw, per backend URL. */
export const REMEMBERED_SERVER_KEY = 'iptvnator-server:instance';
export interface ServerStorageStart {
readonly instance: ServerInstanceInfo;
/** No answer at start; the instance comes from this browser's memory. */
readonly startedOffline: boolean;
}
interface RememberedServer {
readonly baseUrl: string;
readonly instance: ServerInstanceInfo;
}
/**
* Decides whether the app starts in server mode. A browser that has used
* this server before stays in server mode while it does not answer (shown
* as offline), so it never falls back to an empty browser library and
* collects playlists the server will not see. An answer without server
* storage forgets the server.
*/
export function resolveServerStorageStart(
probe: ServerInstanceProbe,
baseUrl: string,
storage: Pick<
Storage,
'getItem' | 'setItem' | 'removeItem'
> | null = safeLocalStorage()
): ServerStorageStart | null {
switch (probe.kind) {
case 'server': {
const remembered = read(storage);
// Another server, or another database behind this one: the
// stored token was not given for it.
if (
!remembered ||
backendIdentity(remembered.baseUrl) !==
backendIdentity(baseUrl) ||
remembered.instance.instanceId !== probe.instance.instanceId
) {
clearServerAccessToken();
}
write(storage, { baseUrl, instance: probe.instance });
return { instance: probe.instance, startedOffline: false };
}
case 'none':
remove(storage);
// The token belonged to that server; another must not see it.
clearServerAccessToken();
return null;
case 'unreachable': {
const remembered = read(storage);
return remembered &&
backendIdentity(remembered.baseUrl) === backendIdentity(baseUrl)
? { instance: remembered.instance, startedOffline: true }
: null;
}
default:
return null;
}
}
/**
* Origin and path of a backend URL, without trailing slashes: `/api` and
* `/api/` (or the same URL written absolute) name one server, as they do
* for the probe and the API client.
*/
function backendIdentity(url: string): string {
try {
const resolved = new URL(url.trim(), globalThis.location?.href);
return `${resolved.origin}${resolved.pathname.replace(/\/+$/, '')}`;
} catch {
return url.trim().replace(/\/+$/, '');
}
}
function read(
storage: Pick<Storage, 'getItem'> | null
): RememberedServer | null {
try {
const raw = storage?.getItem(REMEMBERED_SERVER_KEY);
const parsed = raw ? (JSON.parse(raw) as RememberedServer) : null;
return parsed &&
typeof parsed.baseUrl === 'string' &&
parsed.instance?.storage === 'server' &&
typeof parsed.instance.instanceId === 'string'
? parsed
: null;
} catch {
return null;
}
}
/**
* Remembers the server a token was accepted for; false when storage
* refused it (the next start would take the token for another server's).
*/
export function rememberServer(
baseUrl: string,
instance: ServerInstanceInfo,
storage: Pick<Storage, 'setItem'> | null = safeLocalStorage()
): boolean {
return write(storage, { baseUrl, instance });
}
function write(
storage: Pick<Storage, 'setItem'> | null,
value: RememberedServer
): boolean {
try {
storage?.setItem(REMEMBERED_SERVER_KEY, JSON.stringify(value));
return !!storage;
} catch {
// Without storage an offline start falls back to browser mode.
return false;
}
}
function remove(storage: Pick<Storage, 'removeItem'> | null): void {
try {
storage?.removeItem(REMEMBERED_SERVER_KEY);
} catch {
// Nothing stored.
}
}
function safeLocalStorage(): Storage | null {
try {
return globalThis.localStorage ?? null;
} catch {
return null;
}
}
@@ -0,0 +1,43 @@
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import {
EnvironmentProviders,
inject,
provideAppInitializer,
Provider,
} from '@angular/core';
import { USER_DATA_STORAGE } from '@iptvnator/services';
import {
SERVER_STORAGE_CONFIG,
ServerAccessTokenInterceptor,
ServerStorageSession,
} from '@iptvnator/services/server-storage';
import { ServerMigrationPrompt } from './server-migration-prompt.service';
import type { ServerStorageStart } from './server-storage-start';
/** Loaded with a dynamic import from `main.ts`, only in server mode. */
export function provideServerStorage(
start: ServerStorageStart,
baseUrl: string
): (Provider | EnvironmentProviders)[] {
return [
{
provide: SERVER_STORAGE_CONFIG,
useValue: {
instance: start.instance,
startedOffline: start.startedOffline,
baseUrl,
},
},
{
provide: USER_DATA_STORAGE,
useFactory: () => inject(ServerStorageSession).userData,
},
{
provide: HTTP_INTERCEPTORS,
useClass: ServerAccessTokenInterceptor,
multi: true,
},
provideAppInitializer(() => inject(ServerStorageSession).start()),
provideAppInitializer(() => inject(ServerMigrationPrompt).schedule()),
];
}
@@ -20,6 +20,11 @@ import {
getStalkerRequestErrorStatus,
isStalkerProbeTimeout,
} from '@iptvnator/portal/stalker/data-access';
import {
clearServerAccessToken,
ServerStorageStatusService,
writeServerAccessToken,
} from '@iptvnator/services';
import { PwaService } from './pwa.service';
describe('PwaService', () => {
@@ -328,6 +333,103 @@ describe('PwaService', () => {
globalThis.fetch = originalFetch;
});
it('sends a stored server token only while server mode runs', async () => {
writeServerAccessToken('kept-token', 'i');
const originalFetch = globalThis.fetch;
const fetchMock = jest.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
headers: new Headers(),
json: async () => ({ js: [] }),
} as unknown as Response);
globalThis.fetch = fetchMock as unknown as typeof fetch;
const call = async () => {
const outcome = (
service.sendIpcEvent(STALKER_REQUEST, {
url: 'http://portal.example/portal.php',
macAddress: '00:1A:79:AA:BB:CC',
params: { action: 'get_genres' },
silent: true,
}) as Promise<unknown>
).catch((error: unknown) => error);
await Promise.resolve();
for (const request of http.match((candidate) =>
candidate.url.endsWith('/provider-targets')
)) {
request.flush({ targetId: 'target-1' });
}
await outcome;
};
try {
// A token kept from another backend: server mode is not active.
await call();
expect(fetchMock.mock.calls[0][1].headers).not.toHaveProperty(
'Authorization'
);
TestBed.inject(ServerStorageStatusService).activate(
{
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i',
storage: 'server',
auth: 'token',
},
() => undefined
);
await call();
expect(fetchMock.mock.calls[1][1].headers).toMatchObject({
Authorization: 'Bearer kept-token',
});
} finally {
globalThis.fetch = originalFetch;
clearServerAccessToken();
}
});
it('asks for a new server token when the access guard refuses a Stalker call', async () => {
const status = TestBed.inject(ServerStorageStatusService);
status.activate(
{
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i',
storage: 'server',
auth: 'token',
},
() => undefined
);
const originalFetch = globalThis.fetch;
globalThis.fetch = jest.fn().mockResolvedValue({
ok: false,
status: 401,
statusText: 'Unauthorized',
headers: new Headers({
'WWW-Authenticate': 'Bearer realm="iptvnator"',
}),
json: async () => ({ code: 'unauthorized' }),
} as unknown as Response) as unknown as typeof fetch;
const outcome = (
service.sendIpcEvent(STALKER_REQUEST, {
url: 'http://portal.example/portal.php',
macAddress: '00:1A:79:AA:BB:CC',
params: { action: 'get_genres' },
silent: true,
}) as Promise<unknown>
).catch((error: unknown) => error);
await Promise.resolve();
http.expectOne((candidate) =>
candidate.url.endsWith('/provider-targets')
).flush({ targetId: 'target-1' });
await outcome;
expect(status.state()).toBe('unauthorized');
globalThis.fetch = originalFetch;
});
it('sends Stalker credentials as /stalker control params, including the serial', async () => {
// JSDOM ships no fetch; install one for the proxy call.
const fetchMock = jest.fn().mockResolvedValue({
@@ -518,6 +620,118 @@ describe('PwaService', () => {
}
});
it('sends the server token to the backend only, also with BACKEND_URL=/', async () => {
writeServerAccessToken('kept-token', 'i');
TestBed.inject(ServerStorageStatusService).activate(
{
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i',
storage: 'server',
auth: 'token',
},
() => undefined
);
window.__IPTVNATOR_CONFIG__ = { BACKEND_URL: '/' };
const atRoot = TestBed.runInInjectionContext(() => new PwaService());
delete window.__IPTVNATOR_CONFIG__;
const originalFetch = globalThis.fetch;
const fetchMock = jest.fn().mockResolvedValue({
ok: true,
status: 200,
headers: new Headers(),
json: async () => ({ reset: true }),
} as unknown as Response);
globalThis.fetch = fetchMock as unknown as typeof fetch;
const reset = () =>
atRoot.sendIpcEvent(CONNECTIVITY_GUARD_RESET, {
url: 'http://portal.example:8080/portal.php',
});
try {
await reset();
// Not `//connectivity-guard/reset`: that is another host.
expect(fetchMock.mock.calls[0][0]).toBe(
'/connectivity-guard/reset'
);
expect(fetchMock.mock.calls[0][1].headers).toMatchObject({
Authorization: 'Bearer kept-token',
});
atRoot.corsProxyUrl = 'https://elsewhere.example';
await reset();
expect(fetchMock.mock.calls[1][1].headers).not.toHaveProperty(
'Authorization'
);
} finally {
globalThis.fetch = originalFetch;
clearServerAccessToken();
}
});
it('reports a backend outage seen by its raw fetches', async () => {
const status = TestBed.inject(ServerStorageStatusService);
const activate = () =>
status.activate(
{
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i',
storage: 'server',
auth: 'none',
},
() => undefined
);
const originalFetch = globalThis.fetch;
const reset = () =>
(
service.sendIpcEvent(CONNECTIVITY_GUARD_RESET, {
url: 'http://portal.example:8080/portal.php',
}) as Promise<unknown>
).catch(() => undefined);
const answer = (code: number, contentType: string) =>
({
ok: false,
status: code,
headers: new Headers({ 'content-type': contentType }),
json: async () => ({}),
}) as unknown as Response;
try {
activate();
// The backend's own JSON error: it answered.
globalThis.fetch = jest
.fn()
.mockResolvedValue(
answer(502, 'application/json')
) as unknown as typeof fetch;
await reset();
expect(status.state()).toBe('online');
// A gateway's page in front of a backend that is down.
globalThis.fetch = jest
.fn()
.mockResolvedValue(
answer(502, 'text/html')
) as unknown as typeof fetch;
await reset();
expect(status.state()).toBe('offline');
expect(status.isVerified()).toBe(false);
// No answer at all.
activate();
globalThis.fetch = jest
.fn()
.mockRejectedValue(
new TypeError('Failed to fetch')
) as unknown as typeof fetch;
await reset();
expect(status.state()).toBe('offline');
} finally {
globalThis.fetch = originalFetch;
}
});
it('asks the backend to forget a host when the connectivity guard is reset', async () => {
const fetchMock = jest.fn().mockResolvedValue({
ok: true,
+82 -5
View File
@@ -13,7 +13,13 @@ import {
switchMap,
throwError,
} from 'rxjs';
import { DataService } from '@iptvnator/services';
import {
DataService,
isBackendUrl,
isGatewayOutage,
isServerAccessChallenge,
ServerStorageStatusService,
} from '@iptvnator/services';
import {
CONNECTIVITY_GUARD_RESET,
ERROR,
@@ -83,6 +89,7 @@ export class PwaService extends DataService {
private readonly store = inject(Store);
private readonly swUpdate = inject(SwUpdate);
private readonly translateService = inject(TranslateService);
private readonly serverStatus = inject(ServerStorageStatusService);
private readonly logger = createLogger('PwaService');
private readonly providerTargetIds = new Map<string, Promise<string>>();
private readonly silentXtreamActions = new Set<string>([
@@ -95,8 +102,15 @@ export class PwaService extends DataService {
XtreamCodeActions.GetSimpleDateTable,
]);
/** Proxy URL to avoid CORS issues */
corsProxyUrl = getRuntimeBackendUrl();
/** The backend's URL as configured: `/` for the page's own origin. */
private readonly backendUrl = getRuntimeBackendUrl();
/**
* Proxy URL to avoid CORS issues, without trailing slashes: paths are
* appended to it, and `BACKEND_URL=/` must give `/xtream`, never the
* protocol-relative `//xtream` (another host).
*/
corsProxyUrl = this.backendUrl.replace(/\/+$/, '');
constructor() {
super();
@@ -197,7 +211,7 @@ export class PwaService extends DataService {
);
try {
const response = await fetch(
const response = await this.backendFetch(
`${this.corsProxyUrl}/connectivity-guard/reset`,
{
body: JSON.stringify({ url: payload.url }),
@@ -647,7 +661,7 @@ export class PwaService extends DataService {
logPortalDebugRequest(context);
// Make the fetch request
const response = await fetch(requestUrl);
const response = await this.backendFetch(requestUrl, {});
if (!response.ok) {
throw new Error(
@@ -799,4 +813,67 @@ export class PwaService extends DataService {
getAppEnvironment(): string {
return 'pwa';
}
/**
* The stored server token, only while server mode runs for this
* backend and only for a request that goes to it: a token kept from
* another backend must not reach this one, nor any other host.
*/
private serverAccessToken(url: string): string | null {
return isBackendUrl(url, this.backendUrl)
? this.serverStatus.accessToken()
: null;
}
/**
* `fetch` to the backend with the server token, telling the server
* session what any backend call can show: a token changed on the
* server, or an outage (no answer, or a gateway's 502/503/504), after
* which the instance is checked before the token goes out again. A
* timeout of this page's own is no outage: the backend may be slow.
*/
private async backendFetch(
url: string,
init: RequestInit
): Promise<Response> {
const token = this.serverAccessToken(url);
let response: Response;
try {
response = await fetch(url, {
...init,
headers: {
...(init.headers as Record<string, string> | undefined),
...bearer(token),
},
});
} catch (error) {
if (!(
error instanceof DOMException && error.name === 'AbortError'
)) {
this.serverStatus.reportOffline();
}
throw error;
}
if (
isGatewayOutage(
response.status,
response.headers?.get('content-type')
)
) {
this.serverStatus.reportOffline();
} else if (
response.status === 401 &&
isServerAccessChallenge(
response.status,
response.headers.get('WWW-Authenticate')
)
) {
this.serverStatus.reportAccessDenied(token);
}
return response;
}
}
function bearer(token: string | null): Record<string, string> {
return token ? { Authorization: `Bearer ${token}` } : {};
}
@@ -9,6 +9,14 @@
| translate: { count: dialogData.summary.total }
}}
</p>
@if (clearsServer()) {
<p
class="settings-delete-dialog__lead"
data-test-id="delete-all-server-warning"
>
{{ 'SERVER_STORAGE.DELETE_ALL_WARNING' | translate }}
</p>
}
<section class="settings-delete-dialog__section">
<h3 class="settings-delete-dialog__section-title">
@@ -2,6 +2,7 @@ import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { ServerStorageStatusService } from '@iptvnator/services';
import { SettingsDeleteAllPlaylistsDialogComponent } from './settings-delete-all-playlists-dialog.component';
describe('SettingsDeleteAllPlaylistsDialogComponent', () => {
@@ -93,4 +94,26 @@ describe('SettingsDeleteAllPlaylistsDialogComponent', () => {
expect(buttons).toEqual(['Cancel', 'Delete everything']);
});
it('warns about every device only with server storage', () => {
const warning = () =>
fixture.nativeElement.querySelector(
'[data-test-id="delete-all-server-warning"]'
);
expect(warning()).toBeNull();
TestBed.inject(ServerStorageStatusService).activate(
{
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i',
storage: 'server',
auth: 'none',
},
() => undefined
);
fixture.detectChanges();
expect(warning()).not.toBeNull();
});
});
@@ -9,6 +9,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { TranslateModule } from '@ngx-translate/core';
import { ServerStorageStatusService } from '@iptvnator/services';
import { SOURCE_TYPE_ICONS } from '@iptvnator/shared/interfaces';
export interface SettingsDeleteAllPlaylistsDialogData {
@@ -43,6 +44,8 @@ type SettingsDeleteSummaryItem = {
export class SettingsDeleteAllPlaylistsDialogComponent {
readonly dialogData =
inject<SettingsDeleteAllPlaylistsDialogData>(MAT_DIALOG_DATA);
/** Self-hosted server storage: the playlists go for every device. */
readonly clearsServer = inject(ServerStorageStatusService).isActive;
readonly summaryItems = computed<SettingsDeleteSummaryItem[]>(() => [
{
@@ -42,10 +42,12 @@ describe('buildSettingsSectionNavItems', () => {
const supportedItems = buildSettingsSectionNavItems({
supportsEpg: true,
supportsRemoteControl: true,
supportsServerStorage: true,
});
const unsupportedItems = buildSettingsSectionNavItems({
supportsEpg: false,
supportsRemoteControl: false,
supportsServerStorage: false,
});
expect(supportedItems.map((item) => item.id)).toEqual(
@@ -65,6 +67,7 @@ describe('buildSettingsSectionNavItems', () => {
buildSettingsSectionNavItems({
supportsEpg: true,
supportsRemoteControl: true,
supportsServerStorage: true,
}).map((item) => item.id)
);
const renderableIds = collectRenderableSectionIds();
@@ -86,6 +89,7 @@ describe('buildSettingsSectionNavItems', () => {
buildSettingsSectionNavItems({
supportsEpg: true,
supportsRemoteControl: true,
supportsServerStorage: true,
}).map((item) => item.id)
).toEqual([
'general',
@@ -95,6 +99,7 @@ describe('buildSettingsSectionNavItems', () => {
'tmdb',
'parental',
'remote-control',
'server',
'backup',
'about',
]);
@@ -104,6 +109,7 @@ describe('buildSettingsSectionNavItems', () => {
const items = buildSettingsSectionNavItems({
supportsEpg: true,
supportsRemoteControl: true,
supportsServerStorage: true,
});
const groupOf = (id: string) =>
items.find((item) => item.id === id)?.group;
@@ -111,7 +117,24 @@ describe('buildSettingsSectionNavItems', () => {
expect(groupOf('general')).toBe('app');
expect(groupOf('tmdb')).toBe('library');
expect(groupOf('remote-control')).toBe('devices');
expect(groupOf('server')).toBe('data');
expect(groupOf('backup')).toBe('data');
expect(groupOf('about')).toBeUndefined();
});
it('shows the server section only with server storage', () => {
const build = (supportsServerStorage: boolean) =>
buildSettingsSectionNavItems({
supportsEpg: false,
supportsRemoteControl: false,
supportsServerStorage,
}).find((item) => item.id === 'server');
expect(build(true)).toMatchObject({
visible: true,
group: 'data',
icon: 'dns',
});
expect(build(false)?.visible).toBe(false);
});
});
@@ -162,15 +162,18 @@ export function buildSettingsPlayerOptions({
export interface SettingsSectionVisibility {
supportsEpg: boolean;
supportsRemoteControl: boolean;
supportsServerStorage: boolean;
}
export function buildSettingsSectionNavItems({
supportsEpg,
supportsRemoteControl,
supportsServerStorage,
}: SettingsSectionVisibility): SettingsSection[] {
const capabilities = {
epg: supportsEpg,
'remote-control': supportsRemoteControl,
'server-storage': supportsServerStorage,
};
return SETTINGS_SECTION_DEFINITIONS.map((section) => ({
id: section.id,
@@ -0,0 +1,156 @@
<section class="settings-group" id="server">
<header class="settings-group__header">
<h2>{{ 'SETTINGS.NAV_SERVER' | translate }}</h2>
<p>{{ 'SETTINGS.SERVER_DESCRIPTION' | translate }}</p>
</header>
<div class="settings-card">
<div class="setting-item" data-setting-id="server-connection">
<div class="setting-item__meta">
<h4>{{ 'SETTINGS.SERVER_CONNECTION' | translate }}</h4>
<p>
{{ 'SETTINGS.SERVER_CONNECTION_DESCRIPTION' | translate }}
</p>
<p class="server-detail" data-test-id="server-address">
{{ address }}
</p>
</div>
<div class="setting-item__control">
<span
class="server-state"
[attr.data-state]="state()"
data-test-id="server-state"
>
{{
(state() === 'online'
? 'SETTINGS.SERVER_CONNECTED'
: 'SETTINGS.SERVER_OFFLINE'
) | translate
}}
</span>
</div>
</div>
<div class="setting-item" data-setting-id="server-storage">
<div class="setting-item__meta">
<h4>{{ 'SETTINGS.SERVER_STORAGE' | translate }}</h4>
<p>{{ 'SETTINGS.SERVER_STORAGE_DESCRIPTION' | translate }}</p>
@if (details(); as info) {
<p class="server-detail" data-test-id="server-summary">
{{
'SETTINGS.SERVER_STORAGE_SUMMARY'
| translate
: {
playlists: info.playlists,
size: sizeLabel(),
}
}}
</p>
<p class="server-detail server-detail--path">
{{ info.databasePath }}
</p>
}
</div>
<div class="setting-item__control inline-actions">
<button
mat-stroked-button
type="button"
class="inline-actions__button"
(click)="exportData.emit()"
data-test-id="server-export-backup"
>
{{ 'SETTINGS.SERVER_EXPORT_BACKUP' | translate }}
</button>
</div>
</div>
@if (showBrowserImport()) {
<div class="setting-item" data-setting-id="server-import-browser">
<div class="setting-item__meta">
<h4>{{ 'SETTINGS.SERVER_IMPORT_BROWSER' | translate }}</h4>
<p>
{{
'SETTINGS.SERVER_IMPORT_BROWSER_DESCRIPTION'
| translate
}}
</p>
<p class="server-detail" role="status">
@if (importResult(); as done) {
{{
'SERVER_STORAGE.MIGRATION_DONE'
| translate: done
}}
} @else if (importFailed()) {
{{ 'SERVER_STORAGE.MIGRATION_FAILED' | translate }}
} @else {
{{
'SETTINGS.SERVER_IMPORT_BROWSER_COUNT'
| translate
: { count: browserPlaylistCount() }
}}
}
</p>
</div>
<div class="setting-item__control inline-actions">
@if (movedSomething()) {
<!-- The library on screen predates the move. -->
<button
mat-stroked-button
type="button"
(click)="reload()"
data-test-id="server-import-reload"
>
{{ 'SERVER_STORAGE.MIGRATION_RELOAD' | translate }}
</button>
}
@if (browserPlaylistCount() > 0) {
<button
mat-flat-button
type="button"
[disabled]="importing()"
[attr.aria-busy]="importing()"
(click)="importBrowserPlaylists()"
data-test-id="server-import-browser"
>
@if (importing()) {
<mat-progress-spinner
class="button-spinner"
diameter="16"
mode="indeterminate"
/>
}
{{ 'SERVER_STORAGE.MIGRATION_MOVE' | translate }}
</button>
}
</div>
</div>
}
<div class="setting-item" data-setting-id="server-access">
<div class="setting-item__meta">
<h4>{{ 'SETTINGS.SERVER_ACCESS' | translate }}</h4>
<p>{{ 'SETTINGS.SERVER_ACCESS_DESCRIPTION' | translate }}</p>
<p class="server-detail">
{{
(usesToken()
? 'SETTINGS.SERVER_ACCESS_TOKEN'
: 'SETTINGS.SERVER_ACCESS_OPEN'
) | translate
}}
</p>
</div>
@if (usesToken()) {
<div class="setting-item__control">
<button
mat-stroked-button
type="button"
(click)="signOut()"
data-test-id="server-sign-out"
>
{{ 'SETTINGS.SERVER_SIGN_OUT' | translate }}
</button>
</div>
}
</div>
</div>
</section>
@@ -0,0 +1,128 @@
import { signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { ServerStorageStatusService } from '@iptvnator/services';
import {
SERVER_STORAGE_CONFIG,
ServerMigrationService,
ServerStorageSession,
} from '@iptvnator/services/server-storage';
import { SettingsServerSectionComponent } from './settings-server-section.component';
describe('SettingsServerSectionComponent', () => {
let fixture: ComponentFixture<SettingsServerSectionComponent>;
const session = { fetchStatus: jest.fn(), signOut: jest.fn() };
const migration = {
browserPlaylists: jest.fn(),
browserDataMoved: jest.fn(),
moveBrowserData: jest.fn(),
};
async function render(
auth: 'none' | 'token',
browserPlaylists = [{ id: 'a', title: 'A', kind: 'm3u' }]
) {
session.fetchStatus.mockResolvedValue({
playlists: 4,
databaseBytes: 38 * 1024 * 1024,
databasePath: '/data/databases/iptvnator.db',
startedAt: '2026-10-11T08:00:00.000Z',
});
migration.browserDataMoved.mockReturnValue(false);
migration.browserPlaylists.mockResolvedValue(browserPlaylists);
await TestBed.configureTestingModule({
imports: [
SettingsServerSectionComponent,
TranslateModule.forRoot(),
],
providers: [
{ provide: ServerStorageSession, useValue: session },
{ provide: ServerMigrationService, useValue: migration },
{
provide: SERVER_STORAGE_CONFIG,
useValue: { baseUrl: 'http://nas.local:4333/api' },
},
{
provide: ServerStorageStatusService,
useValue: {
state: signal('online'),
instance: signal({ auth, instanceId: 'i-1' }),
},
},
],
}).compileComponents();
fixture = TestBed.createComponent(SettingsServerSectionComponent);
await fixture.componentInstance.load();
fixture.detectChanges();
}
const byTestId = (id: string): HTMLElement | null =>
fixture.nativeElement.querySelector(`[data-test-id="${id}"]`);
afterEach(() => {
TestBed.resetTestingModule();
jest.resetAllMocks();
});
it('shows the storage figures and the database path', async () => {
await render('none');
const text = fixture.nativeElement.textContent;
expect(text).toContain('/data/databases/iptvnator.db');
expect(byTestId('server-address')?.textContent?.trim()).toBe(
'http://nas.local:4333'
);
expect(byTestId('server-state')?.dataset['state']).toBe('online');
expect(fixture.componentInstance.sizeLabel()).toBe('38.0 MB');
expect(byTestId('server-sign-out')).toBeNull();
});
it('moves browser playlists and reports the result', async () => {
await render('none');
migration.moveBrowserData.mockResolvedValue({
imported: 1,
merged: 0,
failed: 0,
});
migration.browserDataMoved.mockReturnValue(true);
byTestId('server-import-browser')?.click();
await fixture.whenStable();
fixture.detectChanges();
expect(migration.moveBrowserData).toHaveBeenCalled();
expect(byTestId('server-import-browser')).toBeNull();
expect(byTestId('server-import-reload')).not.toBeNull();
expect(fixture.nativeElement.textContent).toContain(
'SERVER_STORAGE.MIGRATION_DONE'
);
});
it('hides the browser import when there is nothing to move', async () => {
await render('none', []);
expect(
fixture.nativeElement.querySelector(
'[data-setting-id="server-import-browser"]'
)
).toBeNull();
});
it('offers sign out when a token is in use', async () => {
await render('token');
byTestId('server-sign-out')?.click();
expect(session.signOut).toHaveBeenCalled();
});
it('asks the page to export a backup', async () => {
await render('none');
const exported = jest.fn();
fixture.componentInstance.exportData.subscribe(exported);
byTestId('server-export-backup')?.click();
expect(exported).toHaveBeenCalled();
});
});
@@ -0,0 +1,122 @@
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
output,
signal,
ViewEncapsulation,
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { TranslatePipe } from '@ngx-translate/core';
import { ServerStorageStatusService } from '@iptvnator/services';
import {
SERVER_STORAGE_CONFIG,
ServerMigrationService,
ServerStorageSession,
type ServerMigrationResult,
} from '@iptvnator/services/server-storage';
import type { ServerStorageStatusResponse } from '@iptvnator/shared/interfaces';
/**
* Settings → Server: shown only when the PWA runs against self-hosted
* server storage. Rendered without `@defer` so settings search can reveal
* its rows on the first visit; the code rides in the lazy settings chunk.
*/
@Component({
selector: 'app-settings-server-section',
imports: [
MatButtonModule,
MatIconModule,
MatProgressSpinnerModule,
TranslatePipe,
],
templateUrl: './settings-server-section.component.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SettingsServerSectionComponent {
private readonly status = inject(ServerStorageStatusService);
private readonly session = inject(ServerStorageSession);
private readonly migration = inject(ServerMigrationService);
readonly exportData = output<void>();
readonly state = this.status.state;
readonly usesToken = computed(
() => this.status.instance()?.auth === 'token'
);
/** The backend's origin; the page's own in Docker (`/api`). */
readonly address = backendOrigin(inject(SERVER_STORAGE_CONFIG).baseUrl);
readonly details = signal<ServerStorageStatusResponse | null>(null);
readonly browserPlaylistCount = signal(0);
readonly importing = signal(false);
readonly importFailed = signal(false);
readonly importResult = signal<ServerMigrationResult | null>(null);
readonly sizeLabel = computed(() =>
formatMegabytes(this.details()?.databaseBytes ?? 0)
);
readonly showBrowserImport = computed(
() => this.browserPlaylistCount() > 0 || this.importResult() !== null
);
readonly movedSomething = computed(() => {
const result = this.importResult();
return !!result && result.imported + result.merged > 0;
});
constructor() {
void this.load();
}
async load(): Promise<void> {
try {
this.details.set(await this.session.fetchStatus());
} catch {
this.details.set(null);
}
try {
this.browserPlaylistCount.set(
this.migration.browserDataMoved()
? 0
: (await this.migration.browserPlaylists()).length
);
} catch {
this.browserPlaylistCount.set(0);
}
}
async importBrowserPlaylists(): Promise<void> {
this.importing.set(true);
this.importFailed.set(false);
try {
this.importResult.set(await this.migration.moveBrowserData());
await this.load();
} catch {
this.importFailed.set(true);
} finally {
this.importing.set(false);
}
}
signOut(): void {
this.session.signOut();
}
reload(): void {
window.location.reload();
}
}
function backendOrigin(baseUrl: string): string {
try {
return new URL(baseUrl, globalThis.location?.href).origin;
} catch {
return baseUrl;
}
}
function formatMegabytes(bytes: number): string {
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
@@ -119,6 +119,11 @@
(unlock)="parentalLock.unlock()"
/>
}
@case ('server') {
<app-settings-server-section
(exportData)="exportData()"
/>
}
@case ('backup') {
<!-- Backup & data: the former Reset page is this
page's last card, since it is one action. -->
@@ -606,3 +606,31 @@
display: none;
}
}
.server-state {
display: inline-flex;
align-items: center;
padding: 3px 10px;
border-radius: 999px;
font-size: 0.8rem;
font-weight: 600;
color: var(--app-selection-color);
background: var(--app-selection-surface);
&[data-state='offline'],
&[data-state='unauthorized'] {
color: var(--app-expiry-warn-text);
background: var(--app-expiry-warn-surface);
}
}
.setting-item__meta .server-detail {
color: var(--app-muted-color);
overflow-wrap: anywhere;
}
.setting-item__meta .server-detail--path {
font-family: 'JetBrains Mono', 'Roboto Mono', monospace;
font-weight: 500;
font-size: 0.78rem;
}
@@ -22,6 +22,7 @@ import { TranslateModule, TranslateService } from '@ngx-translate/core';
import {
EpgSourceReconciliationError,
RuntimeCapabilitiesService,
ServerStorageStatusService,
injectTranslationTick,
} from '@iptvnator/services';
import { VodSourceDiscoveryService } from '@iptvnator/portal/shared/data-access';
@@ -61,6 +62,7 @@ import { SettingsParentalLockSectionComponent } from './settings-parental-sectio
import { SettingsPlaybackSectionComponent } from './settings-playback-section.component';
import { SettingsRemoteControlFacade } from './settings-remote-control.facade';
import { SettingsRemoteControlSectionComponent } from './settings-remote-control-section.component';
import { SettingsServerSectionComponent } from './settings-server-section.component';
import { SettingsSearchFacade } from './settings-search.facade';
import { SettingsSearchResultsComponent } from './settings-search-results.component';
import { SettingsTmdbSectionComponent } from './settings-tmdb-section.component';
@@ -108,6 +110,7 @@ export const SETTINGS_DEFAULT_SECTION = 'general';
SettingsPlaybackSectionComponent,
SettingsRemoteControlSectionComponent,
SettingsSearchResultsComponent,
SettingsServerSectionComponent,
SettingsTmdbSectionComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush,
@@ -166,6 +169,9 @@ export class SettingsComponent
this.runtime.supportsExternalPlayerPathSettings;
readonly supportsVodMultiSource = this.vodSourceDiscovery.isAvailable;
readonly supportsRemoteControl = this.runtime.supportsRemoteControl;
readonly supportsServerStorage = inject(
ServerStorageStatusService
).isActive();
readonly supportsStartupWindowMode = this.runtime.supportsStartupWindowMode;
readonly supportsPortalConnectivityGuard =
this.runtime.supportsPortalConnectivityGuard;
@@ -230,6 +236,7 @@ export class SettingsComponent
readonly sectionNavItems: SettingsSection[] = buildSettingsSectionNavItems({
supportsEpg: this.supportsEpg,
supportsRemoteControl: this.supportsRemoteControl,
supportsServerStorage: this.supportsServerStorage,
});
get sectionNav(): SettingsSection[] {
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "عن بعد",
"NAV_DATA": "البيانات",
"NAV_BACKUP": "النسخ الاحتياطي والبيانات",
"NAV_SERVER": "الخادم",
"SERVER_DESCRIPTION": "تُحفظ قوائم التشغيل والمفضلة وتقدّم المشاهدة على هذا الخادم وتتشاركها كل الأجهزة التي تفتحه.",
"SERVER_CONNECTION": "الاتصال",
"SERVER_CONNECTION_DESCRIPTION": "خادم IPTVnator الذي يحفظ فيه هذا التطبيق بياناته.",
"SERVER_CONNECTED": "متصل",
"SERVER_OFFLINE": "غير متاح",
"SERVER_STORAGE": "التخزين",
"SERVER_STORAGE_DESCRIPTION": "تُحفظ كل البيانات في ملف قاعدة بيانات واحد على الخادم. صدّر نسخة احتياطية للاحتفاظ بنسخة في مكان آخر.",
"SERVER_STORAGE_SUMMARY": "قوائم التشغيل: {{playlists}} · {{size}}",
"SERVER_EXPORT_BACKUP": "تصدير نسخة احتياطية",
"SERVER_IMPORT_BROWSER": "قوائم التشغيل في هذا المتصفح",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "قوائم تشغيل حُفظت في هذا المتصفح قبل أن يستخدم الخادم. انقلها لتظهر على كل الأجهزة؛ وتُدمج القوائم الموجودة على الخادم مسبقًا.",
"SERVER_IMPORT_BROWSER_COUNT": "قوائم التشغيل المحفوظة في هذا المتصفح فقط: {{count}}.",
"SERVER_ACCESS": "الوصول",
"SERVER_ACCESS_DESCRIPTION": "من يمكنه فتح مكتبة هذا الخادم.",
"SERVER_ACCESS_OPEN": "يمكن لأي شخص يصل إلى هذا العنوان استخدامه. اضبط IPTVNATOR_ACCESS_TOKEN على الخادم لطلب رمز وصول.",
"SERVER_ACCESS_TOKEN": "يتطلب هذا الخادم رمز وصول.",
"SERVER_SIGN_OUT": "تسجيل الخروج",
"NAV_ABOUT": "حول",
"NAV_GROUP_APP": "التطبيق",
"NAV_GROUP_LIBRARY": "المكتبة",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "تم القفل"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "تعذّر الحفظ على الخادم. تحقق من الاتصال وحاول مرة أخرى.",
"TOO_LARGE": "قائمة التشغيل هذه أكبر مما يقبله الخادم.",
"MIGRATION_TITLE": "تم العثور على قوائم تشغيل في هذا المتصفح: {{count}}",
"MIGRATION_DESCRIPTION": "إنها محفوظة في هذا المتصفح فقط. انقلها إلى الخادم لتراها كل الأجهزة التي تفتح هذا العنوان. لن يُحذف شيء من هذا المتصفح.",
"MIGRATION_LATER_HINT": "يمكنك فعل ذلك لاحقًا من الإعدادات ← الخادم.",
"MIGRATION_NOT_NOW": "ليس الآن",
"MIGRATION_MOVE": "نقل إلى الخادم",
"MIGRATION_DONE": "تم النقل: {{imported}}، الدمج: {{merged}}، الفشل: {{failed}}.",
"MIGRATION_FAILED": "فشل النقل. ما زالت قوائم التشغيل في هذا المتصفح؛ حاول مجددًا من الإعدادات ← الخادم.",
"MIGRATION_RELOAD": "إعادة التحميل",
"SIGN_IN_TITLE": "مطلوب رمز وصول",
"SIGN_IN_DESCRIPTION": "يطلب خادم IPTVnator هذا رمز وصول قبل عرض قوائم التشغيل.",
"SIGN_IN_TOKEN_LABEL": "رمز الوصول",
"SIGN_IN_HINT": "تجده في إعداد IPTVNATOR_ACCESS_TOKEN على الخادم.",
"SIGN_IN_REJECTED": "تم رفض الرمز. تحقق منه وحاول مرة أخرى.",
"SIGN_IN_UNREACHABLE": "تعذّر الوصول إلى الخادم. تحقق من الاتصال وحاول مرة أخرى.",
"SIGN_IN_STORAGE": "لا يسمح هذا المتصفح لـ IPTVnator بحفظ الرمز. اسمح ببيانات الموقع لهذه الصفحة وحاول مرة أخرى.",
"SIGN_IN_CONTINUE": "متابعة",
"STATUS_ONLINE": "الخادم متصل",
"STATUS_OFFLINE": "الخادم غير متاح",
"STATUS_UNAUTHORIZED": "الخادم يحتاج إلى رمز وصول",
"OFFLINE_BANNER": "الخادم غير متاح. لا يمكن حفظ التغييرات حتى يعود.",
"RETRY": "إعادة المحاولة",
"DELETE_ALL_WARNING": "سيؤدي هذا إلى حذف قوائم التشغيل من الخادم لكل الأجهزة."
},
"THEMES": {
"DARK_THEME": "داكن",
"LIGHT_THEME": "فاتح",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "التحكم عن بعد",
"NAV_DATA": "البيانات",
"NAV_BACKUP": "النسخة الاحتياطية والمعطيات",
"NAV_SERVER": "السيرفر",
"SERVER_DESCRIPTION": "لوائح التشغيل والمفضلة وفين وصلتي فالمشاهدة كيتحفظو فهاد السيرفر وكيتشاركو مع كاع الأجهزة اللي كتحلو.",
"SERVER_CONNECTION": "الاتصال",
"SERVER_CONNECTION_DESCRIPTION": "سيرفر IPTVnator اللي كيحفظ فيه هاد التطبيق.",
"SERVER_CONNECTED": "متاصل",
"SERVER_OFFLINE": "ماشي متوفر",
"SERVER_STORAGE": "التخزين",
"SERVER_STORAGE_DESCRIPTION": "كلشي محفوظ فملف واحد ديال قاعدة المعطيات فالسيرفر. صدّر نسخة احتياطية باش تخلي نسخة فبلاصة خرا.",
"SERVER_STORAGE_SUMMARY": "لوائح التشغيل: {{playlists}} · {{size}}",
"SERVER_EXPORT_BACKUP": "صدّر نسخة احتياطية",
"SERVER_IMPORT_BROWSER": "لوائح التشغيل فهاد المتصفح",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "لوائح تشغيل تحفظو فهاد المتصفح قبل ما يولي يخدم بالسيرفر. نقلهم باش يبانو فكاع الأجهزة؛ اللوائح اللي ديجا كاينين فالسيرفر كيتجمعو.",
"SERVER_IMPORT_BROWSER_COUNT": "لوائح التشغيل المحفوظين غير فهاد المتصفح: {{count}}.",
"SERVER_ACCESS": "الدخول",
"SERVER_ACCESS_DESCRIPTION": "شكون يقدر يحل المكتبة ديال هاد السيرفر.",
"SERVER_ACCESS_OPEN": "أي واحد يوصل لهاد العنوان يقدر يستعملو. حط IPTVNATOR_ACCESS_TOKEN فالسيرفر باش تطلب رمز.",
"SERVER_ACCESS_TOKEN": "هاد السيرفر كيطلب رمز الدخول.",
"SERVER_SIGN_OUT": "خرج",
"NAV_ABOUT": "حول",
"NAV_GROUP_APP": "التطبيق",
"NAV_GROUP_LIBRARY": "المكتبة",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "تقفل"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "ما قدرناش نحفظو فالسيرفر. شوف الاتصال وعاود جرب.",
"TOO_LARGE": "هاد لائحة التشغيل كبيرة على اللي كيقبل السيرفر.",
"MIGRATION_TITLE": "لقينا لوائح تشغيل فهاد المتصفح: {{count}}",
"MIGRATION_DESCRIPTION": "محفوظين غير فهاد المتصفح. نقلهم للسيرفر باش يشوفهم كاع الأجهزة اللي كتحل هاد العنوان. والو ما غادي يتحيد من هاد المتصفح.",
"MIGRATION_LATER_HINT": "تقدر دير هادشي من بعد فالإعدادات ← السيرفر.",
"MIGRATION_NOT_NOW": "ماشي دابا",
"MIGRATION_MOVE": "نقل للسيرفر",
"MIGRATION_DONE": "تنقلو: {{imported}}، تجمعو: {{merged}}، فشلو: {{failed}}.",
"MIGRATION_FAILED": "النقل فشل. لوائح التشغيل ديالك باقيين فهاد المتصفح؛ عاود جرب من الإعدادات ← السيرفر.",
"MIGRATION_RELOAD": "عاود التحميل",
"SIGN_IN_TITLE": "خاص رمز الدخول",
"SIGN_IN_DESCRIPTION": "هاد سيرفر IPTVnator كيطلب رمز الدخول قبل ما يوريك لوائح التشغيل ديالك.",
"SIGN_IN_TOKEN_LABEL": "رمز الدخول",
"SIGN_IN_HINT": "تلقاه فالإعداد IPTVNATOR_ACCESS_TOKEN ديال السيرفر.",
"SIGN_IN_REJECTED": "الرمز ترفض. تأكد منو وعاود جرب.",
"SIGN_IN_UNREACHABLE": "ما قدرناش نوصلو للسيرفر. شوف الاتصال وعاود جرب.",
"SIGN_IN_STORAGE": "هاد المتصفح ما كيخليش IPTVnator يحفظ الرمز. سمح بداتا ديال الموقع لهاد الصفحة وعاود جرب.",
"SIGN_IN_CONTINUE": "كمّل",
"STATUS_ONLINE": "السيرفر متاصل",
"STATUS_OFFLINE": "السيرفر ماشي متوفر",
"STATUS_UNAUTHORIZED": "السيرفر خاصو رمز الدخول",
"OFFLINE_BANNER": "السيرفر ماشي متوفر. التغييرات ما يمكنش تتحفظ حتى يرجع.",
"RETRY": "عاود جرب",
"DELETE_ALL_WARNING": "هادشي غادي يحيد لوائح التشغيل من السيرفر لكاع الأجهزة."
},
"THEMES": {
"DARK_THEME": "داكن",
"LIGHT_THEME": "فاتح",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Кіраванне",
"NAV_DATA": "Дадзеныя",
"NAV_BACKUP": "Рэзервовая копія і дадзеныя",
"NAV_SERVER": "Сервер",
"SERVER_DESCRIPTION": "Плэйлісты, выбранае і прагрэс прагляду захоўваюцца на гэтым серверы і даступныя на кожнай прыладзе, якая яго адкрывае.",
"SERVER_CONNECTION": "Злучэнне",
"SERVER_CONNECTION_DESCRIPTION": "Сервер IPTVnator, на які гэта праграма захоўвае даныя.",
"SERVER_CONNECTED": "Падключана",
"SERVER_OFFLINE": "Недаступны",
"SERVER_STORAGE": "Сховішча",
"SERVER_STORAGE_DESCRIPTION": "Усё захоўваецца ў адным файле базы даных на серверы. Экспартуйце рэзервовую копію, каб мець копію ў іншым месцы.",
"SERVER_STORAGE_SUMMARY": "Плэйлістоў: {{playlists}} · {{size}}",
"SERVER_EXPORT_BACKUP": "Экспартаваць копію",
"SERVER_IMPORT_BROWSER": "Плэйлісты ў гэтым браўзеры",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Плэйлісты, захаваныя ў гэтым браўзеры да пераходу на сервер. Перанясіце іх, каб іх бачыла кожная прылада; плэйлісты, якія ўжо ёсць на серверы, будуць аб’яднаны.",
"SERVER_IMPORT_BROWSER_COUNT": "Плэйлістоў, захаваных толькі ў гэтым браўзеры: {{count}}.",
"SERVER_ACCESS": "Доступ",
"SERVER_ACCESS_DESCRIPTION": "Хто можа адкрыць бібліятэку гэтага сервера.",
"SERVER_ACCESS_OPEN": "Карыстацца можа кожны, хто мае доступ да гэтага адраса. Задайце IPTVNATOR_ACCESS_TOKEN на серверы, каб патрабаваць токен.",
"SERVER_ACCESS_TOKEN": "Гэты сервер патрабуе токен доступу.",
"SERVER_SIGN_OUT": "Выйсці",
"NAV_ABOUT": "Аб праграме",
"NAV_GROUP_APP": "Праграма",
"NAV_GROUP_LIBRARY": "Бібліятэка",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Заблакіравана"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Не ўдалося захаваць на сервер. Праверце злучэнне і паспрабуйце зноў.",
"TOO_LARGE": "Гэты плэйліст большы, чым прымае сервер.",
"MIGRATION_TITLE": "У гэтым браўзеры знойдзена плэйлістоў: {{count}}",
"MIGRATION_DESCRIPTION": "Яны захоўваюцца толькі ў гэтым браўзеры. Перанясіце іх на сервер, каб іх бачыла кожная прылада, што адкрывае гэты адрас. З гэтага браўзера нічога не выдаляецца.",
"MIGRATION_LATER_HINT": "Гэта можна зрабіць пазней у Налады → Сервер.",
"MIGRATION_NOT_NOW": "Не зараз",
"MIGRATION_MOVE": "Перанесці на сервер",
"MIGRATION_DONE": "Перанесена: {{imported}}, аб’яднана: {{merged}}, з памылкай: {{failed}}.",
"MIGRATION_FAILED": "Не ўдалося перанесці. Плэйлісты засталіся ў гэтым браўзеры; паспрабуйце зноў у Налады → Сервер.",
"MIGRATION_RELOAD": "Перазагрузіць",
"SIGN_IN_TITLE": "Патрэбны токен доступу",
"SIGN_IN_DESCRIPTION": "Гэты сервер IPTVnator патрабуе токен доступу, перш чым паказаць вашы плэйлісты.",
"SIGN_IN_TOKEN_LABEL": "Токен доступу",
"SIGN_IN_HINT": "Ён зададзены ў наладзе IPTVNATOR_ACCESS_TOKEN на серверы.",
"SIGN_IN_REJECTED": "Токен адхілены. Праверце яго і паспрабуйце зноў.",
"SIGN_IN_UNREACHABLE": "Сервер недаступны. Праверце злучэнне і паспрабуйце зноў.",
"SIGN_IN_STORAGE": "Браўзер не дазваляе IPTVnator захаваць токен. Дазвольце даныя сайта для гэтай старонкі і паспрабуйце зноў.",
"SIGN_IN_CONTINUE": "Працягнуць",
"STATUS_ONLINE": "Сервер падключаны",
"STATUS_OFFLINE": "Сервер недаступны",
"STATUS_UNAUTHORIZED": "Серверу патрэбны токен доступу",
"OFFLINE_BANNER": "Сервер недаступны. Змены нельга захаваць, пакуль ён не вернецца.",
"RETRY": "Паўтарыць",
"DELETE_ALL_WARNING": "Плэйлісты будуць выдалены з сервера для ўсіх прылад."
},
"THEMES": {
"DARK_THEME": "Цёмная",
"LIGHT_THEME": "Светлая",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Remote",
"NAV_DATA": "Daten",
"NAV_BACKUP": "Datensicherung & Daten",
"NAV_SERVER": "Server",
"SERVER_DESCRIPTION": "Wiedergabelisten, Favoriten und Wiedergabefortschritt werden auf diesem Server gespeichert und mit jedem Gerät geteilt, das ihn öffnet.",
"SERVER_CONNECTION": "Verbindung",
"SERVER_CONNECTION_DESCRIPTION": "Der IPTVnator-Server, auf dem diese App speichert.",
"SERVER_CONNECTED": "Verbunden",
"SERVER_OFFLINE": "Nicht erreichbar",
"SERVER_STORAGE": "Speicher",
"SERVER_STORAGE_DESCRIPTION": "Alles liegt in einer Datenbankdatei auf dem Server. Exportieren Sie eine Datensicherung, um eine Kopie an anderer Stelle aufzubewahren.",
"SERVER_STORAGE_SUMMARY": "{{playlists}} Wiedergabelisten · {{size}}",
"SERVER_EXPORT_BACKUP": "Sicherung exportieren",
"SERVER_IMPORT_BROWSER": "Wiedergabelisten in diesem Browser",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Wiedergabelisten, die in diesem Browser gespeichert wurden, bevor er den Server nutzte. Verschieben Sie sie, damit jedes Gerät sie sieht; Wiedergabelisten, die der Server schon hat, werden zusammengeführt.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} Wiedergabelisten sind nur in diesem Browser gespeichert.",
"SERVER_ACCESS": "Zugriff",
"SERVER_ACCESS_DESCRIPTION": "Wer die Bibliothek dieses Servers öffnen kann.",
"SERVER_ACCESS_OPEN": "Jeder, der diese Adresse erreicht, kann ihn nutzen. Setzen Sie IPTVNATOR_ACCESS_TOKEN auf dem Server, um ein Token zu verlangen.",
"SERVER_ACCESS_TOKEN": "Dieser Server verlangt ein Zugriffstoken.",
"SERVER_SIGN_OUT": "Abmelden",
"NAV_ABOUT": "Info",
"NAV_GROUP_APP": "App",
"NAV_GROUP_LIBRARY": "Bibliothek",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Gesperrt"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Speichern auf dem Server fehlgeschlagen. Prüfen Sie die Verbindung und versuchen Sie es erneut.",
"TOO_LARGE": "Diese Wiedergabeliste ist größer, als der Server annimmt.",
"MIGRATION_TITLE": "{{count}} Wiedergabelisten in diesem Browser gefunden",
"MIGRATION_DESCRIPTION": "Sie sind nur in diesem Browser gespeichert. Verschieben Sie sie auf den Server, damit jedes Gerät, das diese Adresse öffnet, sie sieht. In diesem Browser wird nichts gelöscht.",
"MIGRATION_LATER_HINT": "Das geht auch später unter Einstellungen → Server.",
"MIGRATION_NOT_NOW": "Nicht jetzt",
"MIGRATION_MOVE": "Auf den Server verschieben",
"MIGRATION_DONE": "Verschoben: {{imported}}, zusammengeführt: {{merged}}, fehlgeschlagen: {{failed}}.",
"MIGRATION_FAILED": "Verschieben fehlgeschlagen. Ihre Wiedergabelisten sind weiterhin in diesem Browser; versuchen Sie es unter Einstellungen → Server erneut.",
"MIGRATION_RELOAD": "Neu laden",
"SIGN_IN_TITLE": "Zugriffstoken erforderlich",
"SIGN_IN_DESCRIPTION": "Dieser IPTVnator-Server verlangt ein Zugriffstoken, bevor er Ihre Wiedergabelisten zeigt.",
"SIGN_IN_TOKEN_LABEL": "Zugriffstoken",
"SIGN_IN_HINT": "Es steht in der Einstellung IPTVNATOR_ACCESS_TOKEN des Servers.",
"SIGN_IN_REJECTED": "Token abgelehnt. Prüfen Sie es und versuchen Sie es erneut.",
"SIGN_IN_UNREACHABLE": "Server nicht erreichbar. Prüfen Sie die Verbindung und versuchen Sie es erneut.",
"SIGN_IN_STORAGE": "Dieser Browser lässt IPTVnator das Token nicht speichern. Erlauben Sie Websitedaten für diese Seite und versuchen Sie es erneut.",
"SIGN_IN_CONTINUE": "Weiter",
"STATUS_ONLINE": "Server verbunden",
"STATUS_OFFLINE": "Server nicht erreichbar",
"STATUS_UNAUTHORIZED": "Server verlangt ein Zugriffstoken",
"OFFLINE_BANNER": "Server nicht erreichbar. Änderungen können erst gespeichert werden, wenn er wieder verfügbar ist.",
"RETRY": "Erneut versuchen",
"DELETE_ALL_WARNING": "Damit werden die Wiedergabelisten für alle Geräte vom Server entfernt."
},
"THEMES": {
"DARK_THEME": "Dunkel",
"LIGHT_THEME": "Hell",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Τηλεχειριστήριο",
"NAV_DATA": "Δεδομένα",
"NAV_BACKUP": "Αντίγραφο ασφαλείας και δεδομένα",
"NAV_SERVER": "Διακομιστής",
"SERVER_DESCRIPTION": "Οι λίστες αναπαραγωγής, τα αγαπημένα και η πρόοδος παρακολούθησης αποθηκεύονται σε αυτόν τον διακομιστή και είναι κοινά για κάθε συσκευή που τον ανοίγει.",
"SERVER_CONNECTION": "Σύνδεση",
"SERVER_CONNECTION_DESCRIPTION": "Ο διακομιστής IPTVnator στον οποίο αποθηκεύει αυτή η εφαρμογή.",
"SERVER_CONNECTED": "Συνδεδεμένος",
"SERVER_OFFLINE": "Μη διαθέσιμος",
"SERVER_STORAGE": "Αποθήκευση",
"SERVER_STORAGE_DESCRIPTION": "Όλα φυλάσσονται σε ένα αρχείο βάσης δεδομένων στον διακομιστή. Εξαγάγετε αντίγραφο ασφαλείας για να κρατήσετε ένα αντίγραφο αλλού.",
"SERVER_STORAGE_SUMMARY": "{{playlists}} λίστες αναπαραγωγής · {{size}}",
"SERVER_EXPORT_BACKUP": "Εξαγωγή αντιγράφου",
"SERVER_IMPORT_BROWSER": "Λίστες σε αυτό το πρόγραμμα περιήγησης",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Λίστες αναπαραγωγής που αποθηκεύτηκαν σε αυτό το πρόγραμμα περιήγησης πριν χρησιμοποιήσει τον διακομιστή. Μεταφέρετέ τες ώστε να τις βλέπει κάθε συσκευή· όσες έχει ήδη ο διακομιστής συγχωνεύονται.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} λίστες αναπαραγωγής είναι αποθηκευμένες μόνο σε αυτό το πρόγραμμα περιήγησης.",
"SERVER_ACCESS": "Πρόσβαση",
"SERVER_ACCESS_DESCRIPTION": "Ποιος μπορεί να ανοίξει τη βιβλιοθήκη αυτού του διακομιστή.",
"SERVER_ACCESS_OPEN": "Όποιος φτάνει σε αυτή τη διεύθυνση μπορεί να τον χρησιμοποιήσει. Ορίστε IPTVNATOR_ACCESS_TOKEN στον διακομιστή για να απαιτείται διακριτικό.",
"SERVER_ACCESS_TOKEN": "Αυτός ο διακομιστής απαιτεί διακριτικό πρόσβασης.",
"SERVER_SIGN_OUT": "Αποσύνδεση",
"NAV_ABOUT": "Πληροφορίες",
"NAV_GROUP_APP": "Εφαρμογή",
"NAV_GROUP_LIBRARY": "Βιβλιοθήκη",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Κλειδώθηκε"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Δεν ήταν δυνατή η αποθήκευση στον διακομιστή. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.",
"TOO_LARGE": "Αυτή η λίστα αναπαραγωγής είναι μεγαλύτερη από όσο δέχεται ο διακομιστής.",
"MIGRATION_TITLE": "Βρέθηκαν {{count}} λίστες αναπαραγωγής σε αυτό το πρόγραμμα περιήγησης",
"MIGRATION_DESCRIPTION": "Είναι αποθηκευμένες μόνο σε αυτό το πρόγραμμα περιήγησης. Μεταφέρετέ τες στον διακομιστή ώστε να τις βλέπει κάθε συσκευή που ανοίγει αυτή τη διεύθυνση. Τίποτα δεν διαγράφεται από αυτό το πρόγραμμα περιήγησης.",
"MIGRATION_LATER_HINT": "Μπορείτε να το κάνετε αργότερα από Ρυθμίσεις → Διακομιστής.",
"MIGRATION_NOT_NOW": "Όχι τώρα",
"MIGRATION_MOVE": "Μεταφορά στον διακομιστή",
"MIGRATION_DONE": "Μεταφέρθηκαν {{imported}}, συγχωνεύτηκαν {{merged}}, απέτυχαν {{failed}}.",
"MIGRATION_FAILED": "Η μεταφορά απέτυχε. Οι λίστες σας παραμένουν σε αυτό το πρόγραμμα περιήγησης· δοκιμάστε ξανά από Ρυθμίσεις → Διακομιστής.",
"MIGRATION_RELOAD": "Επαναφόρτωση",
"SIGN_IN_TITLE": "Απαιτείται διακριτικό πρόσβασης",
"SIGN_IN_DESCRIPTION": "Αυτός ο διακομιστής IPTVnator ζητά διακριτικό πρόσβασης πριν εμφανίσει τις λίστες αναπαραγωγής σας.",
"SIGN_IN_TOKEN_LABEL": "Διακριτικό πρόσβασης",
"SIGN_IN_HINT": "Θα το βρείτε στη ρύθμιση IPTVNATOR_ACCESS_TOKEN του διακομιστή.",
"SIGN_IN_REJECTED": "Το διακριτικό απορρίφθηκε. Ελέγξτε το και δοκιμάστε ξανά.",
"SIGN_IN_UNREACHABLE": "Ο διακομιστής δεν είναι προσβάσιμος. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.",
"SIGN_IN_STORAGE": "Αυτό το πρόγραμμα περιήγησης δεν επιτρέπει στο IPTVnator να αποθηκεύσει το διακριτικό. Επιτρέψτε τα δεδομένα ιστότοπου για αυτή τη σελίδα και δοκιμάστε ξανά.",
"SIGN_IN_CONTINUE": "Συνέχεια",
"STATUS_ONLINE": "Ο διακομιστής είναι συνδεδεμένος",
"STATUS_OFFLINE": "Ο διακομιστής δεν είναι διαθέσιμος",
"STATUS_UNAUTHORIZED": "Ο διακομιστής χρειάζεται διακριτικό πρόσβασης",
"OFFLINE_BANNER": "Ο διακομιστής δεν είναι διαθέσιμος. Οι αλλαγές δεν μπορούν να αποθηκευτούν μέχρι να επανέλθει.",
"RETRY": "Επανάληψη",
"DELETE_ALL_WARNING": "Αυτό αφαιρεί τις λίστες αναπαραγωγής από τον διακομιστή για κάθε συσκευή."
},
"THEMES": {
"DARK_THEME": "Σκούρο",
"LIGHT_THEME": "Ανοιχτό",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Remote",
"NAV_DATA": "Data",
"NAV_BACKUP": "Backup & data",
"NAV_SERVER": "Server",
"SERVER_DESCRIPTION": "Playlists, favorites and watch progress are stored on this server and shared by every device that opens it.",
"SERVER_CONNECTION": "Connection",
"SERVER_CONNECTION_DESCRIPTION": "The IPTVnator server this app saves to.",
"SERVER_CONNECTED": "Connected",
"SERVER_OFFLINE": "Unavailable",
"SERVER_STORAGE": "Storage",
"SERVER_STORAGE_DESCRIPTION": "Everything is kept in one database file on the server. Export a backup to keep a copy elsewhere.",
"SERVER_STORAGE_SUMMARY": "{{playlists}} playlists · {{size}}",
"SERVER_EXPORT_BACKUP": "Export backup",
"SERVER_IMPORT_BROWSER": "Playlists in this browser",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Playlists saved in this browser before it used the server. Move them so every device sees them; playlists the server already has are merged.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} playlists are stored only in this browser.",
"SERVER_ACCESS": "Access",
"SERVER_ACCESS_DESCRIPTION": "Who can open this server's library.",
"SERVER_ACCESS_OPEN": "Anyone who can reach this address can use it. Set IPTVNATOR_ACCESS_TOKEN on the server to require a token.",
"SERVER_ACCESS_TOKEN": "This server requires an access token.",
"SERVER_SIGN_OUT": "Sign out",
"NAV_ABOUT": "About",
"NAV_GROUP_APP": "App",
"NAV_GROUP_LIBRARY": "Library",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Locked"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Could not save to the server. Check the connection and try again.",
"TOO_LARGE": "This playlist is larger than the server accepts.",
"MIGRATION_TITLE": "Found {{count}} playlists in this browser",
"MIGRATION_DESCRIPTION": "They are stored only in this browser. Move them to the server so every device that opens this address sees them. Nothing is deleted from this browser.",
"MIGRATION_LATER_HINT": "You can do this later in Settings → Server.",
"MIGRATION_NOT_NOW": "Not now",
"MIGRATION_MOVE": "Move to server",
"MIGRATION_DONE": "Moved {{imported}}, merged {{merged}}, failed {{failed}}.",
"MIGRATION_FAILED": "Moving failed. Your playlists are still in this browser; try again from Settings → Server.",
"MIGRATION_RELOAD": "Reload",
"SIGN_IN_TITLE": "Access token required",
"SIGN_IN_DESCRIPTION": "This IPTVnator server asks for an access token before it shows your playlists.",
"SIGN_IN_TOKEN_LABEL": "Access token",
"SIGN_IN_HINT": "Find it in the server's IPTVNATOR_ACCESS_TOKEN setting.",
"SIGN_IN_REJECTED": "Token rejected. Check it and try again.",
"SIGN_IN_UNREACHABLE": "Cannot reach the server. Check the connection and try again.",
"SIGN_IN_STORAGE": "This browser does not let IPTVnator keep the token. Allow site data for this page and try again.",
"SIGN_IN_CONTINUE": "Continue",
"STATUS_ONLINE": "Server connected",
"STATUS_OFFLINE": "Server unavailable",
"STATUS_UNAUTHORIZED": "Server needs an access token",
"OFFLINE_BANNER": "Server unavailable. Changes cannot be saved until it is back.",
"RETRY": "Retry",
"DELETE_ALL_WARNING": "This removes the playlists from the server for every device."
},
"THEMES": {
"DARK_THEME": "Dark",
"LIGHT_THEME": "Light",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Remoto",
"NAV_DATA": "Datos",
"NAV_BACKUP": "Copia de seguridad y datos",
"NAV_SERVER": "Servidor",
"SERVER_DESCRIPTION": "Las listas de reproducción, los favoritos y el progreso de visualización se guardan en este servidor y los comparten todos los dispositivos que lo abren.",
"SERVER_CONNECTION": "Conexión",
"SERVER_CONNECTION_DESCRIPTION": "El servidor de IPTVnator en el que guarda esta aplicación.",
"SERVER_CONNECTED": "Conectado",
"SERVER_OFFLINE": "No disponible",
"SERVER_STORAGE": "Almacenamiento",
"SERVER_STORAGE_DESCRIPTION": "Todo se guarda en un único archivo de base de datos en el servidor. Exporte una copia de seguridad para conservar una copia en otro lugar.",
"SERVER_STORAGE_SUMMARY": "{{playlists}} listas de reproducción · {{size}}",
"SERVER_EXPORT_BACKUP": "Exportar copia",
"SERVER_IMPORT_BROWSER": "Listas en este navegador",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Listas de reproducción guardadas en este navegador antes de que usara el servidor. Muévalas para que todos los dispositivos las vean; las que el servidor ya tiene se combinan.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} listas de reproducción solo están guardadas en este navegador.",
"SERVER_ACCESS": "Acceso",
"SERVER_ACCESS_DESCRIPTION": "Quién puede abrir la biblioteca de este servidor.",
"SERVER_ACCESS_OPEN": "Cualquiera que llegue a esta dirección puede usarlo. Defina IPTVNATOR_ACCESS_TOKEN en el servidor para exigir un token.",
"SERVER_ACCESS_TOKEN": "Este servidor requiere un token de acceso.",
"SERVER_SIGN_OUT": "Cerrar sesión",
"NAV_ABOUT": "Acerca de",
"NAV_GROUP_APP": "Aplicación",
"NAV_GROUP_LIBRARY": "Biblioteca",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Bloqueado"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "No se pudo guardar en el servidor. Compruebe la conexión e inténtelo de nuevo.",
"TOO_LARGE": "Esta lista de reproducción supera el tamaño que acepta el servidor.",
"MIGRATION_TITLE": "Se encontraron {{count}} listas de reproducción en este navegador",
"MIGRATION_DESCRIPTION": "Solo están guardadas en este navegador. Muévalas al servidor para que las vean todos los dispositivos que abren esta dirección. No se borra nada de este navegador.",
"MIGRATION_LATER_HINT": "Puede hacerlo más tarde en Ajustes → Servidor.",
"MIGRATION_NOT_NOW": "Ahora no",
"MIGRATION_MOVE": "Mover al servidor",
"MIGRATION_DONE": "Movidas: {{imported}}, combinadas: {{merged}}, fallidas: {{failed}}.",
"MIGRATION_FAILED": "No se pudieron mover. Sus listas siguen en este navegador; inténtelo de nuevo en Ajustes → Servidor.",
"MIGRATION_RELOAD": "Recargar",
"SIGN_IN_TITLE": "Se necesita un token de acceso",
"SIGN_IN_DESCRIPTION": "Este servidor de IPTVnator pide un token de acceso antes de mostrar sus listas de reproducción.",
"SIGN_IN_TOKEN_LABEL": "Token de acceso",
"SIGN_IN_HINT": "Lo encontrará en el ajuste IPTVNATOR_ACCESS_TOKEN del servidor.",
"SIGN_IN_REJECTED": "Token rechazado. Compruébelo e inténtelo de nuevo.",
"SIGN_IN_UNREACHABLE": "No se puede contactar con el servidor. Compruebe la conexión e inténtelo de nuevo.",
"SIGN_IN_STORAGE": "Este navegador no permite que IPTVnator guarde el token. Permita los datos del sitio para esta página e inténtelo de nuevo.",
"SIGN_IN_CONTINUE": "Continuar",
"STATUS_ONLINE": "Servidor conectado",
"STATUS_OFFLINE": "Servidor no disponible",
"STATUS_UNAUTHORIZED": "El servidor necesita un token de acceso",
"OFFLINE_BANNER": "Servidor no disponible. Los cambios no se pueden guardar hasta que vuelva.",
"RETRY": "Reintentar",
"DELETE_ALL_WARNING": "Esto elimina las listas de reproducción del servidor para todos los dispositivos."
},
"THEMES": {
"DARK_THEME": "Oscuro",
"LIGHT_THEME": "Claro",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Télécommande",
"NAV_DATA": "Données",
"NAV_BACKUP": "Sauvegarde et données",
"NAV_SERVER": "Serveur",
"SERVER_DESCRIPTION": "Les playlists, les favoris et la progression de lecture sont stockés sur ce serveur et partagés par tous les appareils qui l’ouvrent.",
"SERVER_CONNECTION": "Connexion",
"SERVER_CONNECTION_DESCRIPTION": "Le serveur IPTVnator sur lequel cette application enregistre.",
"SERVER_CONNECTED": "Connecté",
"SERVER_OFFLINE": "Indisponible",
"SERVER_STORAGE": "Stockage",
"SERVER_STORAGE_DESCRIPTION": "Tout est conservé dans un seul fichier de base de données sur le serveur. Exportez une sauvegarde pour en garder une copie ailleurs.",
"SERVER_STORAGE_SUMMARY": "Playlists : {{playlists}} · {{size}}",
"SERVER_EXPORT_BACKUP": "Exporter une sauvegarde",
"SERVER_IMPORT_BROWSER": "Playlists de ce navigateur",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Playlists enregistrées dans ce navigateur avant qu’il utilise le serveur. Déplacez-les pour que tous les appareils les voient ; celles que le serveur possède déjà sont fusionnées.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} playlists sont stockées uniquement dans ce navigateur.",
"SERVER_ACCESS": "Accès",
"SERVER_ACCESS_DESCRIPTION": "Qui peut ouvrir la bibliothèque de ce serveur.",
"SERVER_ACCESS_OPEN": "Toute personne qui atteint cette adresse peut l’utiliser. Définissez IPTVNATOR_ACCESS_TOKEN sur le serveur pour exiger un jeton.",
"SERVER_ACCESS_TOKEN": "Ce serveur exige un jeton d’accès.",
"SERVER_SIGN_OUT": "Se déconnecter",
"NAV_ABOUT": "À propos",
"NAV_GROUP_APP": "Application",
"NAV_GROUP_LIBRARY": "Bibliothèque",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Verrouillé"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Impossible d’enregistrer sur le serveur. Vérifiez la connexion et réessayez.",
"TOO_LARGE": "Cette playlist dépasse la taille acceptée par le serveur.",
"MIGRATION_TITLE": "{{count}} playlists trouvées dans ce navigateur",
"MIGRATION_DESCRIPTION": "Elles ne sont stockées que dans ce navigateur. Déplacez-les vers le serveur pour que tous les appareils qui ouvrent cette adresse les voient. Rien n’est supprimé de ce navigateur.",
"MIGRATION_LATER_HINT": "Vous pourrez le faire plus tard dans Paramètres → Serveur.",
"MIGRATION_NOT_NOW": "Plus tard",
"MIGRATION_MOVE": "Déplacer vers le serveur",
"MIGRATION_DONE": "Déplacées : {{imported}}, fusionnées : {{merged}}, en échec : {{failed}}.",
"MIGRATION_FAILED": "Le déplacement a échoué. Vos playlists sont toujours dans ce navigateur ; réessayez depuis Paramètres → Serveur.",
"MIGRATION_RELOAD": "Recharger",
"SIGN_IN_TITLE": "Jeton d’accès requis",
"SIGN_IN_DESCRIPTION": "Ce serveur IPTVnator demande un jeton d’accès avant d’afficher vos playlists.",
"SIGN_IN_TOKEN_LABEL": "Jeton d’accès",
"SIGN_IN_HINT": "Il figure dans le paramètre IPTVNATOR_ACCESS_TOKEN du serveur.",
"SIGN_IN_REJECTED": "Jeton refusé. Vérifiez-le et réessayez.",
"SIGN_IN_UNREACHABLE": "Serveur injoignable. Vérifiez la connexion et réessayez.",
"SIGN_IN_STORAGE": "Ce navigateur ne permet pas à IPTVnator d’enregistrer le jeton. Autorisez les données de site pour cette page et réessayez.",
"SIGN_IN_CONTINUE": "Continuer",
"STATUS_ONLINE": "Serveur connecté",
"STATUS_OFFLINE": "Serveur indisponible",
"STATUS_UNAUTHORIZED": "Le serveur demande un jeton d’accès",
"OFFLINE_BANNER": "Serveur indisponible. Les modifications ne peuvent pas être enregistrées avant son retour.",
"RETRY": "Réessayer",
"DELETE_ALL_WARNING": "Cela supprime les playlists du serveur pour tous les appareils."
},
"THEMES": {
"DARK_THEME": "Sombre",
"LIGHT_THEME": "Clair",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Távvezérlés",
"NAV_DATA": "Adatok",
"NAV_BACKUP": "Biztonsági mentés és adatok",
"NAV_SERVER": "Szerver",
"SERVER_DESCRIPTION": "A lejátszási listák, a kedvencek és a megtekintési előrehaladás ezen a szerveren tárolódik, és minden eszköz ugyanazt látja, amely megnyitja.",
"SERVER_CONNECTION": "Kapcsolat",
"SERVER_CONNECTION_DESCRIPTION": "Az IPTVnator szerver, amelyre ez az alkalmazás ment.",
"SERVER_CONNECTED": "Csatlakozva",
"SERVER_OFFLINE": "Nem érhető el",
"SERVER_STORAGE": "Tárhely",
"SERVER_STORAGE_DESCRIPTION": "Minden egyetlen adatbázisfájlban van a szerveren. Exportáljon biztonsági mentést, hogy máshol is legyen másolata.",
"SERVER_STORAGE_SUMMARY": "{{playlists}} lejátszási lista · {{size}}",
"SERVER_EXPORT_BACKUP": "Mentés exportálása",
"SERVER_IMPORT_BROWSER": "Lejátszási listák ebben a böngészőben",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Lejátszási listák, amelyeket ebben a böngészőben mentett, mielőtt az a szervert használta volna. Helyezze át őket, hogy minden eszköz lássa; a szerveren már meglévők összevonásra kerülnek.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} lejátszási lista csak ebben a böngészőben van tárolva.",
"SERVER_ACCESS": "Hozzáférés",
"SERVER_ACCESS_DESCRIPTION": "Ki nyithatja meg a szerver könyvtárát.",
"SERVER_ACCESS_OPEN": "Bárki használhatja, aki eléri ezt a címet. Token megköveteléséhez állítsa be az IPTVNATOR_ACCESS_TOKEN értéket a szerveren.",
"SERVER_ACCESS_TOKEN": "Ez a szerver hozzáférési tokent kér.",
"SERVER_SIGN_OUT": "Kijelentkezés",
"NAV_ABOUT": "Névjegy",
"NAV_GROUP_APP": "Alkalmazás",
"NAV_GROUP_LIBRARY": "Médiatár",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Zárolva"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Nem sikerült menteni a szerverre. Ellenőrizze a kapcsolatot, és próbálja újra.",
"TOO_LARGE": "Ez a lejátszási lista nagyobb, mint amit a szerver elfogad.",
"MIGRATION_TITLE": "{{count}} lejátszási lista található ebben a böngészőben",
"MIGRATION_DESCRIPTION": "Ezek csak ebben a böngészőben vannak tárolva. Helyezze át őket a szerverre, hogy minden eszköz lássa őket, amely megnyitja ezt a címet. Ebből a böngészőből semmi sem törlődik.",
"MIGRATION_LATER_HINT": "Ezt később is megteheti a Beállítások → Szerver menüben.",
"MIGRATION_NOT_NOW": "Most nem",
"MIGRATION_MOVE": "Áthelyezés a szerverre",
"MIGRATION_DONE": "Áthelyezve: {{imported}}, összevonva: {{merged}}, sikertelen: {{failed}}.",
"MIGRATION_FAILED": "Az áthelyezés nem sikerült. A lejátszási listák továbbra is ebben a böngészőben vannak; próbálja újra a Beállítások → Szerver menüben.",
"MIGRATION_RELOAD": "Újratöltés",
"SIGN_IN_TITLE": "Hozzáférési token szükséges",
"SIGN_IN_DESCRIPTION": "Ez az IPTVnator szerver hozzáférési tokent kér, mielőtt megjeleníti a lejátszási listáit.",
"SIGN_IN_TOKEN_LABEL": "Hozzáférési token",
"SIGN_IN_HINT": "A szerver IPTVNATOR_ACCESS_TOKEN beállításában találja.",
"SIGN_IN_REJECTED": "A tokent elutasította a szerver. Ellenőrizze, és próbálja újra.",
"SIGN_IN_UNREACHABLE": "A szerver nem érhető el. Ellenőrizze a kapcsolatot, és próbálja újra.",
"SIGN_IN_STORAGE": "Ez a böngésző nem engedi, hogy az IPTVnator megőrizze a tokent. Engedélyezze a webhelyadatokat ehhez az oldalhoz, és próbálja újra.",
"SIGN_IN_CONTINUE": "Tovább",
"STATUS_ONLINE": "Szerver csatlakoztatva",
"STATUS_OFFLINE": "A szerver nem érhető el",
"STATUS_UNAUTHORIZED": "A szerver hozzáférési tokent kér",
"OFFLINE_BANNER": "A szerver nem érhető el. A módosítások nem menthetők, amíg újra elérhető nem lesz.",
"RETRY": "Újra",
"DELETE_ALL_WARNING": "Ez minden eszközön eltávolítja a lejátszási listákat a szerverről."
},
"THEMES": {
"DARK_THEME": "Sötét",
"LIGHT_THEME": "Világos",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Remote",
"NAV_DATA": "Dati",
"NAV_BACKUP": "Copia di sicurezza e dati",
"NAV_SERVER": "Server",
"SERVER_DESCRIPTION": "Playlist, preferiti e avanzamento della visione sono salvati su questo server e condivisi da ogni dispositivo che lo apre.",
"SERVER_CONNECTION": "Connessione",
"SERVER_CONNECTION_DESCRIPTION": "Il server IPTVnator su cui salva questa app.",
"SERVER_CONNECTED": "Connesso",
"SERVER_OFFLINE": "Non disponibile",
"SERVER_STORAGE": "Archiviazione",
"SERVER_STORAGE_DESCRIPTION": "Tutto è conservato in un unico file di database sul server. Esporta una copia di sicurezza per tenerne una copia altrove.",
"SERVER_STORAGE_SUMMARY": "{{playlists}} playlist · {{size}}",
"SERVER_EXPORT_BACKUP": "Esporta copia",
"SERVER_IMPORT_BROWSER": "Playlist in questo browser",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Playlist salvate in questo browser prima che usasse il server. Spostale perché ogni dispositivo le veda; quelle già presenti sul server vengono unite.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} playlist sono salvate solo in questo browser.",
"SERVER_ACCESS": "Accesso",
"SERVER_ACCESS_DESCRIPTION": "Chi può aprire la libreria di questo server.",
"SERVER_ACCESS_OPEN": "Chiunque raggiunga questo indirizzo può usarlo. Imposta IPTVNATOR_ACCESS_TOKEN sul server per richiedere un token.",
"SERVER_ACCESS_TOKEN": "Questo server richiede un token di accesso.",
"SERVER_SIGN_OUT": "Esci",
"NAV_ABOUT": "Info",
"NAV_GROUP_APP": "App",
"NAV_GROUP_LIBRARY": "Libreria",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Bloccato"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Impossibile salvare sul server. Controlla la connessione e riprova.",
"TOO_LARGE": "Questa playlist è più grande di quanto il server accetti.",
"MIGRATION_TITLE": "Trovate {{count}} playlist in questo browser",
"MIGRATION_DESCRIPTION": "Sono salvate solo in questo browser. Spostale sul server perché le veda ogni dispositivo che apre questo indirizzo. Da questo browser non viene eliminato nulla.",
"MIGRATION_LATER_HINT": "Puoi farlo più tardi in Impostazioni → Server.",
"MIGRATION_NOT_NOW": "Non ora",
"MIGRATION_MOVE": "Sposta sul server",
"MIGRATION_DONE": "Spostate: {{imported}}, unite: {{merged}}, non riuscite: {{failed}}.",
"MIGRATION_FAILED": "Spostamento non riuscito. Le tue playlist sono ancora in questo browser; riprova da Impostazioni → Server.",
"MIGRATION_RELOAD": "Ricarica",
"SIGN_IN_TITLE": "Token di accesso richiesto",
"SIGN_IN_DESCRIPTION": "Questo server IPTVnator chiede un token di accesso prima di mostrare le tue playlist.",
"SIGN_IN_TOKEN_LABEL": "Token di accesso",
"SIGN_IN_HINT": "Lo trovi nell’impostazione IPTVNATOR_ACCESS_TOKEN del server.",
"SIGN_IN_REJECTED": "Token rifiutato. Controllalo e riprova.",
"SIGN_IN_UNREACHABLE": "Impossibile raggiungere il server. Controlla la connessione e riprova.",
"SIGN_IN_STORAGE": "Questo browser non consente a IPTVnator di salvare il token. Consenti i dati del sito per questa pagina e riprova.",
"SIGN_IN_CONTINUE": "Continua",
"STATUS_ONLINE": "Server connesso",
"STATUS_OFFLINE": "Server non disponibile",
"STATUS_UNAUTHORIZED": "Il server richiede un token di accesso",
"OFFLINE_BANNER": "Server non disponibile. Le modifiche non possono essere salvate finché non torna disponibile.",
"RETRY": "Riprova",
"DELETE_ALL_WARNING": "Questo rimuove le playlist dal server per tutti i dispositivi."
},
"THEMES": {
"DARK_THEME": "Scuro",
"LIGHT_THEME": "Chiaro",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "リモート",
"NAV_DATA": "データ",
"NAV_BACKUP": "バックアップとデータ",
"NAV_SERVER": "サーバー",
"SERVER_DESCRIPTION": "プレイリスト、お気に入り、視聴の進行状況はこのサーバーに保存され、このサーバーを開くすべてのデバイスで共有されます。",
"SERVER_CONNECTION": "接続",
"SERVER_CONNECTION_DESCRIPTION": "このアプリの保存先の IPTVnator サーバーです。",
"SERVER_CONNECTED": "接続済み",
"SERVER_OFFLINE": "利用不可",
"SERVER_STORAGE": "ストレージ",
"SERVER_STORAGE_DESCRIPTION": "すべてサーバー上の 1 つのデータベースファイルに保存されます。別の場所にコピーを残すには、バックアップをエクスポートしてください。",
"SERVER_STORAGE_SUMMARY": "プレイリスト {{playlists}} 件 · {{size}}",
"SERVER_EXPORT_BACKUP": "バックアップをエクスポート",
"SERVER_IMPORT_BROWSER": "このブラウザーのプレイリスト",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "サーバーを使う前にこのブラウザーに保存されたプレイリストです。移動するとすべてのデバイスで表示されます。サーバーに既にあるプレイリストは統合されます。",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} 件のプレイリストがこのブラウザーにのみ保存されています。",
"SERVER_ACCESS": "アクセス",
"SERVER_ACCESS_DESCRIPTION": "このサーバーのライブラリを開けるユーザー。",
"SERVER_ACCESS_OPEN": "このアドレスにアクセスできる人は誰でも利用できます。トークンを必須にするには、サーバーで IPTVNATOR_ACCESS_TOKEN を設定してください。",
"SERVER_ACCESS_TOKEN": "このサーバーにはアクセストークンが必要です。",
"SERVER_SIGN_OUT": "サインアウト",
"NAV_ABOUT": "アプリについて",
"NAV_GROUP_APP": "アプリ",
"NAV_GROUP_LIBRARY": "ライブラリ",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "ロックしました"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "サーバーに保存できませんでした。接続を確認して、もう一度お試しください。",
"TOO_LARGE": "このプレイリストはサーバーが受け付けるサイズを超えています。",
"MIGRATION_TITLE": "このブラウザーに {{count}} 件のプレイリストが見つかりました",
"MIGRATION_DESCRIPTION": "これらはこのブラウザーにのみ保存されています。サーバーに移動すると、このアドレスを開くすべてのデバイスで表示されます。このブラウザーからは何も削除されません。",
"MIGRATION_LATER_HINT": "後で「設定 → サーバー」から実行できます。",
"MIGRATION_NOT_NOW": "後で",
"MIGRATION_MOVE": "サーバーに移動",
"MIGRATION_DONE": "移動 {{imported}} 件、統合 {{merged}} 件、失敗 {{failed}} 件。",
"MIGRATION_FAILED": "移動に失敗しました。プレイリストはこのブラウザーに残っています。「設定 → サーバー」からもう一度お試しください。",
"MIGRATION_RELOAD": "再読み込み",
"SIGN_IN_TITLE": "アクセストークンが必要です",
"SIGN_IN_DESCRIPTION": "この IPTVnator サーバーは、プレイリストを表示する前にアクセストークンを求めます。",
"SIGN_IN_TOKEN_LABEL": "アクセストークン",
"SIGN_IN_HINT": "サーバーの IPTVNATOR_ACCESS_TOKEN 設定で確認できます。",
"SIGN_IN_REJECTED": "トークンが拒否されました。確認して、もう一度お試しください。",
"SIGN_IN_UNREACHABLE": "サーバーに接続できません。接続を確認して、もう一度お試しください。",
"SIGN_IN_STORAGE": "このブラウザーでは IPTVnator がトークンを保存できません。このページのサイトデータを許可して、もう一度お試しください。",
"SIGN_IN_CONTINUE": "続行",
"STATUS_ONLINE": "サーバーに接続済み",
"STATUS_OFFLINE": "サーバーを利用できません",
"STATUS_UNAUTHORIZED": "サーバーにアクセストークンが必要です",
"OFFLINE_BANNER": "サーバーを利用できません。復旧するまで変更を保存できません。",
"RETRY": "再試行",
"DELETE_ALL_WARNING": "すべてのデバイスで、サーバーからプレイリストが削除されます。"
},
"THEMES": {
"DARK_THEME": "ダーク",
"LIGHT_THEME": "ライト",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "원격",
"NAV_DATA": "데이터",
"NAV_BACKUP": "백업 및 데이터",
"NAV_SERVER": "서버",
"SERVER_DESCRIPTION": "플레이리스트, 즐겨찾기, 시청 진행 상황이 이 서버에 저장되며 이 서버를 여는 모든 기기에서 공유됩니다.",
"SERVER_CONNECTION": "연결",
"SERVER_CONNECTION_DESCRIPTION": "이 앱이 데이터를 저장하는 IPTVnator 서버입니다.",
"SERVER_CONNECTED": "연결됨",
"SERVER_OFFLINE": "사용할 수 없음",
"SERVER_STORAGE": "저장소",
"SERVER_STORAGE_DESCRIPTION": "모든 데이터는 서버의 데이터베이스 파일 하나에 보관됩니다. 다른 곳에 사본을 두려면 백업을 내보내세요.",
"SERVER_STORAGE_SUMMARY": "플레이리스트 {{playlists}}개 · {{size}}",
"SERVER_EXPORT_BACKUP": "백업 내보내기",
"SERVER_IMPORT_BROWSER": "이 브라우저의 플레이리스트",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "서버를 사용하기 전에 이 브라우저에 저장된 플레이리스트입니다. 옮기면 모든 기기에서 볼 수 있으며, 서버에 이미 있는 플레이리스트는 병합됩니다.",
"SERVER_IMPORT_BROWSER_COUNT": "플레이리스트 {{count}}개가 이 브라우저에만 저장되어 있습니다.",
"SERVER_ACCESS": "접근",
"SERVER_ACCESS_DESCRIPTION": "이 서버의 라이브러리를 열 수 있는 사람.",
"SERVER_ACCESS_OPEN": "이 주소에 접속할 수 있는 누구나 사용할 수 있습니다. 토큰을 요구하려면 서버에 IPTVNATOR_ACCESS_TOKEN을 설정하세요.",
"SERVER_ACCESS_TOKEN": "이 서버는 액세스 토큰이 필요합니다.",
"SERVER_SIGN_OUT": "로그아웃",
"NAV_ABOUT": "정보",
"NAV_GROUP_APP": "앱",
"NAV_GROUP_LIBRARY": "라이브러리",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "잠겼습니다"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "서버에 저장하지 못했습니다. 연결을 확인하고 다시 시도하세요.",
"TOO_LARGE": "이 플레이리스트는 서버가 허용하는 크기보다 큽니다.",
"MIGRATION_TITLE": "이 브라우저에서 플레이리스트 {{count}}개를 찾았습니다",
"MIGRATION_DESCRIPTION": "이 브라우저에만 저장되어 있습니다. 서버로 옮기면 이 주소를 여는 모든 기기에서 볼 수 있습니다. 이 브라우저에서는 아무것도 삭제되지 않습니다.",
"MIGRATION_LATER_HINT": "나중에 설정 → 서버에서 할 수 있습니다.",
"MIGRATION_NOT_NOW": "나중에",
"MIGRATION_MOVE": "서버로 옮기기",
"MIGRATION_DONE": "이동 {{imported}}개, 병합 {{merged}}개, 실패 {{failed}}개.",
"MIGRATION_FAILED": "옮기지 못했습니다. 플레이리스트는 이 브라우저에 그대로 있습니다. 설정 → 서버에서 다시 시도하세요.",
"MIGRATION_RELOAD": "새로고침",
"SIGN_IN_TITLE": "액세스 토큰 필요",
"SIGN_IN_DESCRIPTION": "이 IPTVnator 서버는 플레이리스트를 보여 주기 전에 액세스 토큰을 요청합니다.",
"SIGN_IN_TOKEN_LABEL": "액세스 토큰",
"SIGN_IN_HINT": "서버의 IPTVNATOR_ACCESS_TOKEN 설정에서 확인할 수 있습니다.",
"SIGN_IN_REJECTED": "토큰이 거부되었습니다. 확인하고 다시 시도하세요.",
"SIGN_IN_UNREACHABLE": "서버에 연결할 수 없습니다. 연결을 확인하고 다시 시도하세요.",
"SIGN_IN_STORAGE": "이 브라우저에서는 IPTVnator가 토큰을 저장할 수 없습니다. 이 페이지의 사이트 데이터를 허용하고 다시 시도하세요.",
"SIGN_IN_CONTINUE": "계속",
"STATUS_ONLINE": "서버 연결됨",
"STATUS_OFFLINE": "서버를 사용할 수 없음",
"STATUS_UNAUTHORIZED": "서버에 액세스 토큰이 필요함",
"OFFLINE_BANNER": "서버를 사용할 수 없습니다. 서버가 다시 연결될 때까지 변경 사항을 저장할 수 없습니다.",
"RETRY": "다시 시도",
"DELETE_ALL_WARNING": "모든 기기에서 서버의 플레이리스트가 삭제됩니다."
},
"THEMES": {
"DARK_THEME": "어둡게",
"LIGHT_THEME": "밝게",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Afstandsbediening",
"NAV_DATA": "Gegevens",
"NAV_BACKUP": "Back-up en gegevens",
"NAV_SERVER": "Server",
"SERVER_DESCRIPTION": "Afspeellijsten, favorieten en kijkvoortgang worden op deze server bewaard en gedeeld met elk apparaat dat hem opent.",
"SERVER_CONNECTION": "Verbinding",
"SERVER_CONNECTION_DESCRIPTION": "De IPTVnator-server waarop deze app opslaat.",
"SERVER_CONNECTED": "Verbonden",
"SERVER_OFFLINE": "Niet bereikbaar",
"SERVER_STORAGE": "Opslag",
"SERVER_STORAGE_DESCRIPTION": "Alles staat in één databasebestand op de server. Exporteer een back-up om ergens anders een kopie te bewaren.",
"SERVER_STORAGE_SUMMARY": "{{playlists}} afspeellijsten · {{size}}",
"SERVER_EXPORT_BACKUP": "Back-up exporteren",
"SERVER_IMPORT_BROWSER": "Afspeellijsten in deze browser",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Afspeellijsten die in deze browser zijn opgeslagen voordat hij de server gebruikte. Verplaats ze zodat elk apparaat ze ziet; afspeellijsten die de server al heeft, worden samengevoegd.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} afspeellijsten staan alleen in deze browser.",
"SERVER_ACCESS": "Toegang",
"SERVER_ACCESS_DESCRIPTION": "Wie de bibliotheek van deze server kan openen.",
"SERVER_ACCESS_OPEN": "Iedereen die dit adres kan bereiken, kan hem gebruiken. Stel IPTVNATOR_ACCESS_TOKEN in op de server om een token te vereisen.",
"SERVER_ACCESS_TOKEN": "Deze server vereist een toegangstoken.",
"SERVER_SIGN_OUT": "Afmelden",
"NAV_ABOUT": "Over",
"NAV_GROUP_APP": "App",
"NAV_GROUP_LIBRARY": "Bibliotheek",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Vergrendeld"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Opslaan op de server is mislukt. Controleer de verbinding en probeer het opnieuw.",
"TOO_LARGE": "Deze afspeellijst is groter dan de server accepteert.",
"MIGRATION_TITLE": "{{count}} afspeellijsten gevonden in deze browser",
"MIGRATION_DESCRIPTION": "Ze staan alleen in deze browser. Verplaats ze naar de server zodat elk apparaat dat dit adres opent ze ziet. Er wordt niets uit deze browser verwijderd.",
"MIGRATION_LATER_HINT": "Je kunt dit later doen via Instellingen → Server.",
"MIGRATION_NOT_NOW": "Niet nu",
"MIGRATION_MOVE": "Naar server verplaatsen",
"MIGRATION_DONE": "Verplaatst: {{imported}}, samengevoegd: {{merged}}, mislukt: {{failed}}.",
"MIGRATION_FAILED": "Verplaatsen is mislukt. Je afspeellijsten staan nog in deze browser; probeer het opnieuw via Instellingen → Server.",
"MIGRATION_RELOAD": "Opnieuw laden",
"SIGN_IN_TITLE": "Toegangstoken vereist",
"SIGN_IN_DESCRIPTION": "Deze IPTVnator-server vraagt om een toegangstoken voordat hij je afspeellijsten toont.",
"SIGN_IN_TOKEN_LABEL": "Toegangstoken",
"SIGN_IN_HINT": "Je vindt het in de instelling IPTVNATOR_ACCESS_TOKEN van de server.",
"SIGN_IN_REJECTED": "Token geweigerd. Controleer het en probeer het opnieuw.",
"SIGN_IN_UNREACHABLE": "De server is niet bereikbaar. Controleer de verbinding en probeer het opnieuw.",
"SIGN_IN_STORAGE": "Deze browser laat IPTVnator het token niet bewaren. Sta sitegegevens voor deze pagina toe en probeer het opnieuw.",
"SIGN_IN_CONTINUE": "Doorgaan",
"STATUS_ONLINE": "Server verbonden",
"STATUS_OFFLINE": "Server niet bereikbaar",
"STATUS_UNAUTHORIZED": "Server vraagt om een toegangstoken",
"OFFLINE_BANNER": "Server niet bereikbaar. Wijzigingen kunnen pas worden opgeslagen als hij weer bereikbaar is.",
"RETRY": "Opnieuw proberen",
"DELETE_ALL_WARNING": "Hiermee worden de afspeellijsten voor alle apparaten van de server verwijderd."
},
"THEMES": {
"DARK_THEME": "Donker",
"LIGHT_THEME": "Licht",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Pilot",
"NAV_DATA": "Dane",
"NAV_BACKUP": "Kopia zapasowa i dane",
"NAV_SERVER": "Serwer",
"SERVER_DESCRIPTION": "Listy odtwarzania, ulubione i postęp oglądania są przechowywane na tym serwerze i współdzielone przez każde urządzenie, które go otwiera.",
"SERVER_CONNECTION": "Połączenie",
"SERVER_CONNECTION_DESCRIPTION": "Serwer IPTVnator, na którym ta aplikacja zapisuje dane.",
"SERVER_CONNECTED": "Połączono",
"SERVER_OFFLINE": "Niedostępny",
"SERVER_STORAGE": "Pamięć",
"SERVER_STORAGE_DESCRIPTION": "Wszystko jest przechowywane w jednym pliku bazy danych na serwerze. Wyeksportuj kopię zapasową, aby mieć kopię w innym miejscu.",
"SERVER_STORAGE_SUMMARY": "Listy odtwarzania: {{playlists}} · {{size}}",
"SERVER_EXPORT_BACKUP": "Eksportuj kopię",
"SERVER_IMPORT_BROWSER": "Listy w tej przeglądarce",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Listy odtwarzania zapisane w tej przeglądarce, zanim zaczęła korzystać z serwera. Przenieś je, aby każde urządzenie je widziało; listy, które serwer już ma, zostaną scalone.",
"SERVER_IMPORT_BROWSER_COUNT": "Listy odtwarzania zapisane tylko w tej przeglądarce: {{count}}.",
"SERVER_ACCESS": "Dostęp",
"SERVER_ACCESS_DESCRIPTION": "Kto może otworzyć bibliotekę tego serwera.",
"SERVER_ACCESS_OPEN": "Może z niego korzystać każdy, kto dotrze pod ten adres. Ustaw IPTVNATOR_ACCESS_TOKEN na serwerze, aby wymagać tokenu.",
"SERVER_ACCESS_TOKEN": "Ten serwer wymaga tokenu dostępu.",
"SERVER_SIGN_OUT": "Wyloguj",
"NAV_ABOUT": "O aplikacji",
"NAV_GROUP_APP": "Aplikacja",
"NAV_GROUP_LIBRARY": "Biblioteka",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Zablokowano"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Nie udało się zapisać na serwerze. Sprawdź połączenie i spróbuj ponownie.",
"TOO_LARGE": "Ta lista odtwarzania jest większa, niż akceptuje serwer.",
"MIGRATION_TITLE": "Znaleziono listy odtwarzania w tej przeglądarce: {{count}}",
"MIGRATION_DESCRIPTION": "Są zapisane tylko w tej przeglądarce. Przenieś je na serwer, aby widziało je każde urządzenie otwierające ten adres. Nic nie zostanie usunięte z tej przeglądarki.",
"MIGRATION_LATER_HINT": "Możesz to zrobić później w Ustawienia → Serwer.",
"MIGRATION_NOT_NOW": "Nie teraz",
"MIGRATION_MOVE": "Przenieś na serwer",
"MIGRATION_DONE": "Przeniesiono: {{imported}}, scalono: {{merged}}, błędy: {{failed}}.",
"MIGRATION_FAILED": "Przenoszenie nie powiodło się. Twoje listy odtwarzania nadal są w tej przeglądarce; spróbuj ponownie w Ustawienia → Serwer.",
"MIGRATION_RELOAD": "Odśwież",
"SIGN_IN_TITLE": "Wymagany token dostępu",
"SIGN_IN_DESCRIPTION": "Ten serwer IPTVnator prosi o token dostępu, zanim pokaże Twoje listy odtwarzania.",
"SIGN_IN_TOKEN_LABEL": "Token dostępu",
"SIGN_IN_HINT": "Znajdziesz go w ustawieniu IPTVNATOR_ACCESS_TOKEN serwera.",
"SIGN_IN_REJECTED": "Token odrzucony. Sprawdź go i spróbuj ponownie.",
"SIGN_IN_UNREACHABLE": "Brak połączenia z serwerem. Sprawdź połączenie i spróbuj ponownie.",
"SIGN_IN_STORAGE": "Ta przeglądarka nie pozwala IPTVnator zapisać tokenu. Zezwól na dane witryny dla tej strony i spróbuj ponownie.",
"SIGN_IN_CONTINUE": "Dalej",
"STATUS_ONLINE": "Serwer połączony",
"STATUS_OFFLINE": "Serwer niedostępny",
"STATUS_UNAUTHORIZED": "Serwer wymaga tokenu dostępu",
"OFFLINE_BANNER": "Serwer niedostępny. Zmian nie można zapisać, dopóki nie będzie znowu dostępny.",
"RETRY": "Ponów",
"DELETE_ALL_WARNING": "Spowoduje to usunięcie list odtwarzania z serwera dla wszystkich urządzeń."
},
"THEMES": {
"DARK_THEME": "Ciemny",
"LIGHT_THEME": "Jasny",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Remoto",
"NAV_DATA": "Dados",
"NAV_BACKUP": "Cópia de segurança e dados",
"NAV_SERVER": "Servidor",
"SERVER_DESCRIPTION": "Playlists, favoritos e progresso de exibição ficam neste servidor e são compartilhados por todos os dispositivos que o abrem.",
"SERVER_CONNECTION": "Conexão",
"SERVER_CONNECTION_DESCRIPTION": "O servidor IPTVnator onde este app salva os dados.",
"SERVER_CONNECTED": "Conectado",
"SERVER_OFFLINE": "Indisponível",
"SERVER_STORAGE": "Armazenamento",
"SERVER_STORAGE_DESCRIPTION": "Tudo fica em um único arquivo de banco de dados no servidor. Exporte uma cópia de segurança para manter uma cópia em outro lugar.",
"SERVER_STORAGE_SUMMARY": "Playlists: {{playlists}} · {{size}}",
"SERVER_EXPORT_BACKUP": "Exportar cópia",
"SERVER_IMPORT_BROWSER": "Playlists neste navegador",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Playlists salvas neste navegador antes de ele usar o servidor. Mova-as para que todos os dispositivos as vejam; as que o servidor já tem são mescladas.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} playlists estão salvas apenas neste navegador.",
"SERVER_ACCESS": "Acesso",
"SERVER_ACCESS_DESCRIPTION": "Quem pode abrir a biblioteca deste servidor.",
"SERVER_ACCESS_OPEN": "Qualquer pessoa que alcance este endereço pode usá-lo. Defina IPTVNATOR_ACCESS_TOKEN no servidor para exigir um token.",
"SERVER_ACCESS_TOKEN": "Este servidor exige um token de acesso.",
"SERVER_SIGN_OUT": "Sair",
"NAV_ABOUT": "Sobre",
"NAV_GROUP_APP": "Aplicativo",
"NAV_GROUP_LIBRARY": "Biblioteca",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Bloqueado"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Não foi possível salvar no servidor. Verifique a conexão e tente novamente.",
"TOO_LARGE": "Esta playlist é maior do que o servidor aceita.",
"MIGRATION_TITLE": "{{count}} playlists encontradas neste navegador",
"MIGRATION_DESCRIPTION": "Elas estão salvas apenas neste navegador. Mova-as para o servidor para que todos os dispositivos que abrem este endereço as vejam. Nada é apagado deste navegador.",
"MIGRATION_LATER_HINT": "Você pode fazer isso depois em Configurações → Servidor.",
"MIGRATION_NOT_NOW": "Agora não",
"MIGRATION_MOVE": "Mover para o servidor",
"MIGRATION_DONE": "Movidas: {{imported}}, mescladas: {{merged}}, com falha: {{failed}}.",
"MIGRATION_FAILED": "Falha ao mover. Suas playlists continuam neste navegador; tente novamente em Configurações → Servidor.",
"MIGRATION_RELOAD": "Recarregar",
"SIGN_IN_TITLE": "Token de acesso necessário",
"SIGN_IN_DESCRIPTION": "Este servidor IPTVnator pede um token de acesso antes de mostrar suas playlists.",
"SIGN_IN_TOKEN_LABEL": "Token de acesso",
"SIGN_IN_HINT": "Ele está na configuração IPTVNATOR_ACCESS_TOKEN do servidor.",
"SIGN_IN_REJECTED": "Token recusado. Verifique e tente novamente.",
"SIGN_IN_UNREACHABLE": "Não foi possível acessar o servidor. Verifique a conexão e tente novamente.",
"SIGN_IN_STORAGE": "Este navegador não permite que o IPTVnator salve o token. Permita os dados do site para esta página e tente novamente.",
"SIGN_IN_CONTINUE": "Continuar",
"STATUS_ONLINE": "Servidor conectado",
"STATUS_OFFLINE": "Servidor indisponível",
"STATUS_UNAUTHORIZED": "O servidor precisa de um token de acesso",
"OFFLINE_BANNER": "Servidor indisponível. As alterações não podem ser salvas até que ele volte.",
"RETRY": "Tentar novamente",
"DELETE_ALL_WARNING": "Isso remove as playlists do servidor para todos os dispositivos."
},
"THEMES": {
"DARK_THEME": "Escuro",
"LIGHT_THEME": "Claro",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Пульт",
"NAV_DATA": "Данные",
"NAV_BACKUP": "Резервная копия и данные",
"NAV_SERVER": "Сервер",
"SERVER_DESCRIPTION": "Плейлисты, избранное и прогресс просмотра хранятся на этом сервере и доступны на каждом устройстве, которое его открывает.",
"SERVER_CONNECTION": "Подключение",
"SERVER_CONNECTION_DESCRIPTION": "Сервер IPTVnator, на котором это приложение хранит данные.",
"SERVER_CONNECTED": "Подключено",
"SERVER_OFFLINE": "Недоступен",
"SERVER_STORAGE": "Хранилище",
"SERVER_STORAGE_DESCRIPTION": "Всё хранится в одном файле базы данных на сервере. Экспортируйте резервную копию, чтобы сохранить копию в другом месте.",
"SERVER_STORAGE_SUMMARY": "Плейлистов: {{playlists}} · {{size}}",
"SERVER_EXPORT_BACKUP": "Экспортировать копию",
"SERVER_IMPORT_BROWSER": "Плейлисты в этом браузере",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Плейлисты, сохранённые в этом браузере до перехода на сервер. Перенесите их, чтобы их видели все устройства; плейлисты, которые уже есть на сервере, будут объединены.",
"SERVER_IMPORT_BROWSER_COUNT": "Плейлистов, сохранённых только в этом браузере: {{count}}.",
"SERVER_ACCESS": "Доступ",
"SERVER_ACCESS_DESCRIPTION": "Кто может открыть библиотеку этого сервера.",
"SERVER_ACCESS_OPEN": "Пользоваться может любой, кто может открыть этот адрес. Задайте IPTVNATOR_ACCESS_TOKEN на сервере, чтобы требовать токен.",
"SERVER_ACCESS_TOKEN": "Этот сервер требует токен доступа.",
"SERVER_SIGN_OUT": "Выйти",
"NAV_ABOUT": "Инфо",
"NAV_GROUP_APP": "Приложение",
"NAV_GROUP_LIBRARY": "Библиотека",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Заблокировано"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Не удалось сохранить на сервер. Проверьте подключение и попробуйте снова.",
"TOO_LARGE": "Этот плейлист больше, чем принимает сервер.",
"MIGRATION_TITLE": "В этом браузере найдено плейлистов: {{count}}",
"MIGRATION_DESCRIPTION": "Они хранятся только в этом браузере. Перенесите их на сервер, чтобы их видели все устройства, которые открывают этот адрес. Из этого браузера ничего не удаляется.",
"MIGRATION_LATER_HINT": "Это можно сделать позже в Настройки → Сервер.",
"MIGRATION_NOT_NOW": "Не сейчас",
"MIGRATION_MOVE": "Перенести на сервер",
"MIGRATION_DONE": "Перенесено: {{imported}}, объединено: {{merged}}, с ошибкой: {{failed}}.",
"MIGRATION_FAILED": "Не удалось перенести. Плейлисты остались в этом браузере; попробуйте снова в Настройки → Сервер.",
"MIGRATION_RELOAD": "Перезагрузить",
"SIGN_IN_TITLE": "Нужен токен доступа",
"SIGN_IN_DESCRIPTION": "Этот сервер IPTVnator запрашивает токен доступа, прежде чем показать ваши плейлисты.",
"SIGN_IN_TOKEN_LABEL": "Токен доступа",
"SIGN_IN_HINT": "Он задан в настройке IPTVNATOR_ACCESS_TOKEN на сервере.",
"SIGN_IN_REJECTED": "Токен отклонён. Проверьте его и попробуйте снова.",
"SIGN_IN_UNREACHABLE": "Сервер недоступен. Проверьте подключение и попробуйте снова.",
"SIGN_IN_STORAGE": "Браузер не даёт IPTVnator сохранить токен. Разрешите данные сайта для этой страницы и попробуйте снова.",
"SIGN_IN_CONTINUE": "Продолжить",
"STATUS_ONLINE": "Сервер подключён",
"STATUS_OFFLINE": "Сервер недоступен",
"STATUS_UNAUTHORIZED": "Серверу нужен токен доступа",
"OFFLINE_BANNER": "Сервер недоступен. Изменения нельзя сохранить, пока он не вернётся.",
"RETRY": "Повторить",
"DELETE_ALL_WARNING": "Плейлисты будут удалены с сервера для всех устройств."
},
"THEMES": {
"DARK_THEME": "Тёмная",
"LIGHT_THEME": "Светлая",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "Uzaktan",
"NAV_DATA": "Veri",
"NAV_BACKUP": "Yedekleme ve veriler",
"NAV_SERVER": "Sunucu",
"SERVER_DESCRIPTION": "Oynatma listeleri, favoriler ve izleme ilerlemesi bu sunucuda saklanır ve onu açan her cihazla paylaşılır.",
"SERVER_CONNECTION": "Bağlantı",
"SERVER_CONNECTION_DESCRIPTION": "Bu uygulamanın verileri kaydettiği IPTVnator sunucusu.",
"SERVER_CONNECTED": "Bağlı",
"SERVER_OFFLINE": "Kullanılamıyor",
"SERVER_STORAGE": "Depolama",
"SERVER_STORAGE_DESCRIPTION": "Her şey sunucudaki tek bir veritabanı dosyasında tutulur. Başka bir yerde kopya saklamak için yedeği dışa aktarın.",
"SERVER_STORAGE_SUMMARY": "{{playlists}} oynatma listesi · {{size}}",
"SERVER_EXPORT_BACKUP": "Yedeği dışa aktar",
"SERVER_IMPORT_BROWSER": "Bu tarayıcıdaki oynatma listeleri",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "Bu tarayıcı sunucuyu kullanmadan önce burada kaydedilmiş oynatma listeleri. Her cihazın görmesi için bunları taşıyın; sunucuda zaten olan listeler birleştirilir.",
"SERVER_IMPORT_BROWSER_COUNT": "{{count}} oynatma listesi yalnızca bu tarayıcıda saklanıyor.",
"SERVER_ACCESS": "Erişim",
"SERVER_ACCESS_DESCRIPTION": "Bu sunucunun kitaplığını kimlerin açabileceği.",
"SERVER_ACCESS_OPEN": "Bu adrese ulaşabilen herkes kullanabilir. Belirteç istemek için sunucuda IPTVNATOR_ACCESS_TOKEN ayarlayın.",
"SERVER_ACCESS_TOKEN": "Bu sunucu bir erişim belirteci gerektiriyor.",
"SERVER_SIGN_OUT": "Oturumu kapat",
"NAV_ABOUT": "Hakkında",
"NAV_GROUP_APP": "Uygulama",
"NAV_GROUP_LIBRARY": "Kitaplık",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "Kilitlendi"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "Sunucuya kaydedilemedi. Bağlantıyı kontrol edip tekrar deneyin.",
"TOO_LARGE": "Bu oynatma listesi sunucunun kabul ettiğinden büyük.",
"MIGRATION_TITLE": "Bu tarayıcıda {{count}} oynatma listesi bulundu",
"MIGRATION_DESCRIPTION": "Bunlar yalnızca bu tarayıcıda saklanıyor. Bu adresi açan her cihazın görmesi için sunucuya taşıyın. Bu tarayıcıdan hiçbir şey silinmez.",
"MIGRATION_LATER_HINT": "Bunu daha sonra Ayarlar → Sunucu bölümünden yapabilirsiniz.",
"MIGRATION_NOT_NOW": "Şimdi değil",
"MIGRATION_MOVE": "Sunucuya taşı",
"MIGRATION_DONE": "Taşınan: {{imported}}, birleştirilen: {{merged}}, başarısız: {{failed}}.",
"MIGRATION_FAILED": "Taşıma başarısız oldu. Oynatma listeleriniz hâlâ bu tarayıcıda; Ayarlar → Sunucu bölümünden tekrar deneyin.",
"MIGRATION_RELOAD": "Yeniden yükle",
"SIGN_IN_TITLE": "Erişim belirteci gerekli",
"SIGN_IN_DESCRIPTION": "Bu IPTVnator sunucusu oynatma listelerinizi göstermeden önce bir erişim belirteci istiyor.",
"SIGN_IN_TOKEN_LABEL": "Erişim belirteci",
"SIGN_IN_HINT": "Sunucunun IPTVNATOR_ACCESS_TOKEN ayarında bulabilirsiniz.",
"SIGN_IN_REJECTED": "Belirteç reddedildi. Kontrol edip tekrar deneyin.",
"SIGN_IN_UNREACHABLE": "Sunucuya ulaşılamıyor. Bağlantıyı kontrol edip tekrar deneyin.",
"SIGN_IN_STORAGE": "Bu tarayıcı IPTVnator'ın belirteci saklamasına izin vermiyor. Bu sayfa için site verilerine izin verip tekrar deneyin.",
"SIGN_IN_CONTINUE": "Devam",
"STATUS_ONLINE": "Sunucu bağlı",
"STATUS_OFFLINE": "Sunucu kullanılamıyor",
"STATUS_UNAUTHORIZED": "Sunucu erişim belirteci istiyor",
"OFFLINE_BANNER": "Sunucu kullanılamıyor. Sunucu geri gelene kadar değişiklikler kaydedilemez.",
"RETRY": "Tekrar dene",
"DELETE_ALL_WARNING": "Bu işlem oynatma listelerini tüm cihazlar için sunucudan kaldırır."
},
"THEMES": {
"DARK_THEME": "Koyu",
"LIGHT_THEME": "Açık",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "远程",
"NAV_DATA": "数据",
"NAV_BACKUP": "备份与数据",
"NAV_SERVER": "服务器",
"SERVER_DESCRIPTION": "播放列表、收藏和观看进度保存在此服务器上,所有打开它的设备共享这些数据。",
"SERVER_CONNECTION": "连接",
"SERVER_CONNECTION_DESCRIPTION": "此应用保存数据的 IPTVnator 服务器。",
"SERVER_CONNECTED": "已连接",
"SERVER_OFFLINE": "不可用",
"SERVER_STORAGE": "存储",
"SERVER_STORAGE_DESCRIPTION": "所有数据都保存在服务器上的一个数据库文件中。导出备份可在其他位置保留一份副本。",
"SERVER_STORAGE_SUMMARY": "{{playlists}} 个播放列表 · {{size}}",
"SERVER_EXPORT_BACKUP": "导出备份",
"SERVER_IMPORT_BROWSER": "此浏览器中的播放列表",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "此浏览器在使用服务器之前保存的播放列表。移到服务器后,所有设备都能看到;服务器上已有的播放列表会被合并。",
"SERVER_IMPORT_BROWSER_COUNT": "有 {{count}} 个播放列表仅保存在此浏览器中。",
"SERVER_ACCESS": "访问",
"SERVER_ACCESS_DESCRIPTION": "谁可以打开此服务器的媒体库。",
"SERVER_ACCESS_OPEN": "任何能访问此地址的人都可以使用。在服务器上设置 IPTVNATOR_ACCESS_TOKEN 即可要求令牌。",
"SERVER_ACCESS_TOKEN": "此服务器需要访问令牌。",
"SERVER_SIGN_OUT": "退出登录",
"NAV_ABOUT": "关于",
"NAV_GROUP_APP": "应用",
"NAV_GROUP_LIBRARY": "媒体库",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "已锁定"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "无法保存到服务器。请检查连接后重试。",
"TOO_LARGE": "此播放列表超出服务器可接受的大小。",
"MIGRATION_TITLE": "在此浏览器中找到 {{count}} 个播放列表",
"MIGRATION_DESCRIPTION": "它们仅保存在此浏览器中。移到服务器后,所有打开此地址的设备都能看到。此浏览器中的内容不会被删除。",
"MIGRATION_LATER_HINT": "您也可以稍后在“设置 → 服务器”中完成。",
"MIGRATION_NOT_NOW": "暂不",
"MIGRATION_MOVE": "移到服务器",
"MIGRATION_DONE": "已移动 {{imported}} 个,已合并 {{merged}} 个,失败 {{failed}} 个。",
"MIGRATION_FAILED": "移动失败。您的播放列表仍在此浏览器中;请在“设置 → 服务器”中重试。",
"MIGRATION_RELOAD": "重新加载",
"SIGN_IN_TITLE": "需要访问令牌",
"SIGN_IN_DESCRIPTION": "此 IPTVnator 服务器在显示您的播放列表前需要访问令牌。",
"SIGN_IN_TOKEN_LABEL": "访问令牌",
"SIGN_IN_HINT": "可在服务器的 IPTVNATOR_ACCESS_TOKEN 设置中找到。",
"SIGN_IN_REJECTED": "令牌被拒绝。请检查后重试。",
"SIGN_IN_UNREACHABLE": "无法连接到服务器。请检查连接后重试。",
"SIGN_IN_STORAGE": "此浏览器不允许 IPTVnator 保存令牌。请允许此页面的网站数据后重试。",
"SIGN_IN_CONTINUE": "继续",
"STATUS_ONLINE": "服务器已连接",
"STATUS_OFFLINE": "服务器不可用",
"STATUS_UNAUTHORIZED": "服务器需要访问令牌",
"OFFLINE_BANNER": "服务器不可用。服务器恢复之前无法保存更改。",
"RETRY": "重试",
"DELETE_ALL_WARNING": "这会从服务器上删除播放列表,所有设备都会受影响。"
},
"THEMES": {
"DARK_THEME": "深色",
"LIGHT_THEME": "浅色",
+44
View File
@@ -316,6 +316,24 @@
"NAV_REMOTE": "遠端",
"NAV_DATA": "資料",
"NAV_BACKUP": "備份與資料",
"NAV_SERVER": "伺服器",
"SERVER_DESCRIPTION": "播放清單、我的最愛和觀看進度會儲存在此伺服器上,並由所有開啟它的裝置共用。",
"SERVER_CONNECTION": "連線",
"SERVER_CONNECTION_DESCRIPTION": "此應用程式儲存資料的 IPTVnator 伺服器。",
"SERVER_CONNECTED": "已連線",
"SERVER_OFFLINE": "無法使用",
"SERVER_STORAGE": "儲存空間",
"SERVER_STORAGE_DESCRIPTION": "所有資料都保存在伺服器上的一個資料庫檔案中。匯出備份即可在其他地方保留一份副本。",
"SERVER_STORAGE_SUMMARY": "{{playlists}} 個播放清單 · {{size}}",
"SERVER_EXPORT_BACKUP": "匯出備份",
"SERVER_IMPORT_BROWSER": "此瀏覽器中的播放清單",
"SERVER_IMPORT_BROWSER_DESCRIPTION": "此瀏覽器在使用伺服器之前儲存的播放清單。移到伺服器後,所有裝置都能看到;伺服器上已有的播放清單會合併。",
"SERVER_IMPORT_BROWSER_COUNT": "有 {{count}} 個播放清單只儲存在此瀏覽器中。",
"SERVER_ACCESS": "存取",
"SERVER_ACCESS_DESCRIPTION": "誰可以開啟此伺服器的媒體庫。",
"SERVER_ACCESS_OPEN": "任何能連到此位址的人都可以使用。在伺服器上設定 IPTVNATOR_ACCESS_TOKEN 即可要求權杖。",
"SERVER_ACCESS_TOKEN": "此伺服器需要存取權杖。",
"SERVER_SIGN_OUT": "登出",
"NAV_ABOUT": "關於",
"NAV_GROUP_APP": "應用程式",
"NAV_GROUP_LIBRARY": "媒體庫",
@@ -643,6 +661,32 @@
"LOCKED_TOAST": "已鎖定"
}
},
"SERVER_STORAGE": {
"WRITE_FAILED": "無法儲存到伺服器。請檢查連線後再試一次。",
"TOO_LARGE": "此播放清單超出伺服器可接受的大小。",
"MIGRATION_TITLE": "在此瀏覽器中找到 {{count}} 個播放清單",
"MIGRATION_DESCRIPTION": "它們只儲存在此瀏覽器中。移到伺服器後,所有開啟此位址的裝置都能看到。此瀏覽器中的內容不會被刪除。",
"MIGRATION_LATER_HINT": "您也可以稍後在「設定 → 伺服器」中完成。",
"MIGRATION_NOT_NOW": "暫時不要",
"MIGRATION_MOVE": "移到伺服器",
"MIGRATION_DONE": "已移動 {{imported}} 個,已合併 {{merged}} 個,失敗 {{failed}} 個。",
"MIGRATION_FAILED": "移動失敗。您的播放清單仍在此瀏覽器中;請在「設定 → 伺服器」中再試一次。",
"MIGRATION_RELOAD": "重新載入",
"SIGN_IN_TITLE": "需要存取權杖",
"SIGN_IN_DESCRIPTION": "此 IPTVnator 伺服器在顯示您的播放清單前需要存取權杖。",
"SIGN_IN_TOKEN_LABEL": "存取權杖",
"SIGN_IN_HINT": "可在伺服器的 IPTVNATOR_ACCESS_TOKEN 設定中找到。",
"SIGN_IN_REJECTED": "權杖遭拒。請檢查後再試一次。",
"SIGN_IN_UNREACHABLE": "無法連線到伺服器。請檢查連線後再試一次。",
"SIGN_IN_STORAGE": "此瀏覽器不允許 IPTVnator 儲存權杖。請允許此頁面的網站資料後再試一次。",
"SIGN_IN_CONTINUE": "繼續",
"STATUS_ONLINE": "伺服器已連線",
"STATUS_OFFLINE": "伺服器無法使用",
"STATUS_UNAUTHORIZED": "伺服器需要存取權杖",
"OFFLINE_BANNER": "伺服器無法使用。伺服器恢復之前無法儲存變更。",
"RETRY": "重試",
"DELETE_ALL_WARNING": "這會從伺服器上刪除播放清單,所有裝置都會受影響。"
},
"THEMES": {
"DARK_THEME": "深色",
"LIGHT_THEME": "淺色",
+28 -3
View File
@@ -1,8 +1,12 @@
import { ApplicationConfig, mergeApplicationConfig } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { resolveRestoredRendererRoute } from '@iptvnator/shared/interfaces';
import { registerAppDateLocale } from './app/app-date-locales';
import { AppComponent } from './app/app.component';
import { appConfig, getInitialLanguage } from './app/app.config';
import { probeServerInstance } from './app/server-storage/server-instance-probe';
import { resolveServerStorageStart } from './app/server-storage/server-storage-start';
import { getRuntimeBackendUrl } from './app/services/runtime-config';
// A reloaded packaged renderer arrives on index.html with the route it was
// on carried in the query string (the Electron main process recovers the
@@ -16,12 +20,33 @@ if (restoredHref !== null) {
window.history.replaceState(window.history.state, '', restoredHref);
}
/**
* Adds server storage when the self-hosted backend offers it, or when this
* browser has used it before and it does not answer right now.
*/
async function resolveAppConfig(): Promise<ApplicationConfig> {
const baseUrl = getRuntimeBackendUrl();
const start = resolveServerStorageStart(
await probeServerInstance(),
baseUrl
);
if (!start) {
return appConfig;
}
const { provideServerStorage } =
await import('./app/server-storage/server-storage.providers');
return mergeApplicationConfig(appConfig, {
providers: provideServerStorage(start, baseUrl),
});
}
// Angular ships only English locale data; the preferred language's data is a
// lazy chunk. It is awaited before bootstrapping because the first route
// renders dates with that locale, and a locale without data throws. English
// (the default) resolves immediately.
registerAppDateLocale(getInitialLanguage())
.then(() => bootstrapApplication(AppComponent, appConfig))
// (the default) resolves immediately. The server-storage probe runs in
// parallel and only when the deployment provides a runtime backend URL.
Promise.all([registerAppDateLocale(getInitialLanguage()), resolveAppConfig()])
.then(([, config]) => bootstrapApplication(AppComponent, config))
.then(() => {
// Splash is rendered eagerly by index.html so the user sees something
// immediately instead of a blank Material-grey background. Once Angular
+20 -12
View File
@@ -18,9 +18,12 @@ The Docker image runs the browser PWA, not the Electron desktop application.
That means:
- EPG/XMLTV panels and multi-EPG views are not available in the self-hosted PWA.
- Playlist metadata is stored in the browser through IndexedDB, and Xtream user
data is stored by the PWA data source in localStorage. The PWA does not use
the Electron SQLite database or DB worker.
- With server storage (the image default) playlists, M3U favorites and
history, and Xtream favorites, recently viewed items and playback positions
live on the server, and every browser that opens the instance shares them.
Settings, parental locks, the global favorites order and UI preferences stay
per browser. With `IPTVNATOR_STORAGE=none` each browser keeps its own data
in IndexedDB and localStorage.
- Docker cannot launch local desktop players or Embedded MPV. If a stream does
not play inline in the browser, use the in-app copy URL action and open the
stream manually in an external player such as MPV, VLC, or IINA.
@@ -100,7 +103,7 @@ safe local defaults shown below.
| `NODE_EXTRA_CA_CERTS` | unset | Optional Node.js CA bundle path for providers using private certificate authorities. Mount the CA file into the container and set this path. |
| `IPTVNATOR_STORAGE` | `server` in the image | `server` opens the server storage database under `IPTVNATOR_DATA_DIR` and its `/api/v1` routes; `none` keeps the backend stateless. |
| `IPTVNATOR_DATA_DIR` | `/data` in the image | Data root; the database is `<root>/databases/iptvnator.db`. Mount a volume here. |
| `IPTVNATOR_ACCESS_TOKEN` | unset | When set, every route except `/`, `/health`, `/config.js` and `/v1/instance` requires `Authorization: Bearer <token>`, proxy routes included. The browser app cannot send a token yet: leave it unset until it can. |
| `IPTVNATOR_ACCESS_TOKEN` | unset | When set, every route except `/`, `/health`, `/config.js` and `/v1/instance` requires `Authorization: Bearer <token>`, proxy routes included. Each browser asks for the token once and keeps it. Needs `IPTVNATOR_STORAGE=server`; the backend refuses to start otherwise. |
| `IPTVNATOR_MAX_DOCUMENT_MB` | `64` | Largest playlist document the backend accepts. Keep the nginx `client_max_body_size` in step. |
| `IPTVNATOR_BACKEND_START_TIMEOUT` | `300` | Seconds the entrypoint waits for the backend's `/health` before giving up. Database migrations run before the backend listens. |
@@ -136,16 +139,21 @@ the `restart: unless-stopped` policy.
The image opens a server storage database on the `/data` volume
(`IPTVNATOR_STORAGE=server`, `IPTVNATOR_DATA_DIR=/data`) and serves its API
under `/api/v1`. It is the backend half of keeping playlists, favorites,
history and playback positions on the server for every device; the PWA
starts using it in a follow-up change. Until then the volume holds an empty
database and each browser keeps its own data.
under `/api/v1`. The PWA finds it on start and keeps playlists, favorites,
history and playback positions there, so every phone, TV and computer that
opens the instance sees the same library. Settings → Server shows the
connection, the database size and path, and exports a backup.
Provider credentials will be stored unencrypted in that database, as the
The first browser that opens an instance with an empty database offers to
move the playlists it already kept, with their Xtream favorites and
progress; nothing is deleted from the browser. Later browsers can merge
theirs from Settings → Server.
Provider credentials are stored unencrypted in that database, as the
desktop app does. Do not expose an instance with server storage to the
internet without authentication in your reverse proxy. The backend already
supports `IPTVNATOR_ACCESS_TOKEN`, but the browser app cannot send the
token yet, so setting it now makes the app unusable. Back up the volume like any database: stop the container, or copy
internet without authentication. Set `IPTVNATOR_ACCESS_TOKEN` to require a
token: each browser then asks for it once on a sign-in page. Back up the
volume like any database: stop the container, or copy
`databases/iptvnator.db` together with its `-wal` file.
## IPv6, VPNs, And Connection Fallback
+2
View File
@@ -16,6 +16,8 @@ services:
# Server storage database on the /data volume. Set to "none" to keep
# the backend stateless.
IPTVNATOR_STORAGE: server
# Ask every browser for this token once before it shows the library.
# IPTVNATOR_ACCESS_TOKEN: change-me
volumes:
- iptvnator-data:/data
healthcheck:
@@ -252,6 +252,12 @@ self-hosted server storage is covered too.
browser tracks neither.
- An unreadable map (storage error, malformed JSON, a playlist entry that is
not a list) fails the export instead of being written as an empty list.
So does server mode when it cannot read the server's user data: the
export reads it again (`UserDataStorage.ready(true)`, as another device
may have changed it since this page's first read) and fails when that
read does not succeed. A restore does the same and stays parked, since its
replacement lists would otherwise merge into the server's; it also stays
parked until the server took that playlist's lists.
- A pending restore snapshot still wins over the stored maps, as on desktop.
- Import parks the restore state like the desktop does, then applies it at
once through `XtreamPendingRestoreService.applyAndConsume`: the browser has
+256 -10
View File
@@ -73,8 +73,8 @@ The current self-hosted PWA uses these `apps/web-backend` routes:
- `GET /xtream?targetId=<id>&username=<u>&password=<p>&action=<action>`
- `GET /stalker?targetId=<id>&macAddress=<mac>&action=<action>`
Server storage adds versioned routes under `/v1`; the PWA does not call them
yet:
Server storage adds versioned routes under `/v1`, which the PWA uses in
[server storage mode](#server-storage-mode):
- `GET /v1/instance` (always public): `{ service, apiVersion, instanceId,
storage: 'server' | 'none', auth: 'none' | 'token' }`
@@ -83,10 +83,19 @@ yet:
`DELETE /v1/playlists`: whole playlist documents; `GET` sends an `ETag`
and answers `304` to a matching `If-None-Match`, and
`PUT ...?keepPayload=1` keeps the stored `playlist`, `items` and
`header` fields (`409 payload_missing` without a stored row)
`header` fields (`409 payload_missing` without a stored row); every `PUT`
answers with the new `ETag` and `X-Replaced-ETag`, the version it
replaced, and one with `If-Match` answers `412 conflict` when another
write replaced that version, one with `If-None-Match: *` when the
playlist exists already
- `GET /v1/user-state`, `PUT|DELETE /v1/user-state/:namespace/:playlistId`:
Xtream favorites, recently viewed, collection snapshots and playback
positions, one JSON value per namespace and playlist
positions, one JSON value per namespace and playlist; `GET` adds a
content tag per entry (`tags`), and a write with `If-Match: "<tag>"` or
`If-None-Match: *` answers `412` with the current value and tag when the
entry changed since, and a `PUT` for a playlist the server does not have
answers `404 playlist_missing` (the client drops that edit), so an edit
queued on another device cannot bring a deleted playlist's state back
- `GET|PUT /v1/app-state/:key`
Server storage lives in `apps/web-backend/src/app/storage/`. With
@@ -102,8 +111,10 @@ its database. Storage errors are logged by error name and code only, because
Drizzle messages can carry bound values such as portal credentials. With
`IPTVNATOR_ACCESS_TOKEN`, every route except `/`, `/health`, `/config.js`
and `/v1/instance` requires `Authorization: Bearer <token>`, the proxy
routes included. The PWA cannot send that token yet, so the variable must
stay unset until the browser side lands. Browser app state written through
routes included; its 401 carries `WWW-Authenticate: Bearer
realm="iptvnator"`, which a provider error passed on by the proxy never
does; the PWA sends it once its sign-in page has stored it.
Browser app state written through
`/v1/app-state` is stored under a `client:` key prefix, apart from
server-owned keys such as the instance id.
@@ -119,7 +130,11 @@ reached only `pnpm`/`nx`, and the orphaned server kept port 3333 after the run.
launches the backend through Nx or its `env` drifts from the `serve` target.
`WEB_BACKEND_PORT` (default 3333) relocates the E2E backend and the
`self-hosted.e2e.ts` URLs, like `MOCK_PORT` does for the mocks. Use it when
another worktree holds 3333. The `web:serve` entry can stay on Nx:
another worktree holds 3333. `server-storage.e2e.ts` talks to a second
backend from the same config, launched with `IPTVNATOR_STORAGE=server` on
`STORAGE_BACKEND_PORT` (default 3334) and a data directory named after the
Playwright process, so every run starts with an empty store; the spec
accepts at most that one extra launch. The `web:serve` entry can stay on Nx:
`@angular/build:dev-server` runs inside the Nx process, so the group kill
stops it. Playwright launches that command itself even outside CI: the
web-e2e targets carry no Nx `serve` dependency, because Nx refuses a
@@ -160,6 +175,235 @@ MPV and VLC preload launch methods (`openInMpv` and `openInVlc`), and
(`setMpvPlayerPath` and `setVlcPlayerPath`); a partial Electron bridge must not
expose desktop-only actions in the PWA/shared UI.
## Server Storage Mode
`main.ts` probes `GET /v1/instance` before bootstrapping, and only when the
deployment wrote a runtime `BACKEND_URL` into `window.__IPTVNATOR_CONFIG__`
(the Docker entrypoint does; hosted builds and Electron never probe). On
`storage: 'server'` it imports `apps/web/src/app/server-storage/` lazily and
merges `provideServerStorage()` into the app config, and remembers the
instance under `iptvnator-server:instance`. When the probe gets no answer
(network error, timeout, a 5xx such as nginx's 502 while the backend
restarts, or a refusal other than 404, such as a proxy's 429), a browser that remembers this backend still starts in server
mode, offline, and reloads once the server answers; it never falls back to
an empty browser library. Until that reload it sends no writes
(`holdWrites`) and no token anywhere (`ServerStorageStatusService.accessToken()`
is null for an unverified instance): the address may lead to another
server or database by then, which the reload's probe finds out. An answer without server storage, or a 404 from
an older backend, forgets it (`server-storage-start.ts`). Everything else of the
client lives behind the `@iptvnator/services/server-storage` sub-entry, so
other builds never load it; `ServerStorageStatusService` and the token
helpers stay in the main `@iptvnator/services` barrel because the rail,
settings and guards read them in every build.
- **Playlists.** `ServerStorageSession.start()` (an app initializer) plugs
`ServerPlaylistDocumentStore` into `PlaylistStorageBackend` (kinds
`electron`, `server`, `indexeddb`). The store caches full documents by
ETag and uploads a document whose payload it served unchanged with
`keepPayload=1`, so a favorite or a rename does not resend a large M3U.
A mutation carries `If-Match` with the version it was read at (of its
payload, else of the served copy it was built from, as for portal
documents): when
another device wrote in between, the server answers `412`, the store
throws `PlaylistWriteConflict`, and `PlaylistsService`'s per-playlist
write queue runs the mutation again on a fresh read (a retry on the same,
unread copy writes unconditionally, as before). Imports and start-up
migrations (`dbUpsertAppPlaylists`) write unconditionally, and the store
refuses a document without an id. "Remove all" first lets queued
playlist writes land, and writes issued meanwhile wait until it is done.
An M3U favorite
toggle or reorder goes through `transformPlaylistFavorites`: a toggle adds
or removes that one channel, a reorder applies its order, on the
favorites read at write time. After a write the store
keeps its copy only when `X-Replaced-ETag` names the version its payload
came from.
- **Xtream user data.** `USER_DATA_STORAGE` becomes `ServerUserDataStorage`:
the four synced namespaces are cached per server instance, under
`iptvnator-server:cache:<instanceId>:<namespace>` (the legacy unprefixed
keys are never written in server mode; a tab still open on another
server never writes over this one's cache) and
each change sends only the playlist entries that differ, debounced, with a
`keepalive` flush when the page hides. A change is compared with the map
the caller read: when the cache changed since (another tab, a re-read),
only the entries the caller changed are applied to it. Batches go out one after another
(the page-hide flush waits for a batch still travelling, and a flush
scheduled before it waits for the page-hide batch it sent at once), a failed write,
including a refused `keepalive` one or one the server took and never
answered (it ends after the request timeout), stays queued for the next
flush (a write saved whose answer was cut off counts as saved on an
unknown version: only later edits replay on the next conflict), and
every unconfirmed write (queued or travelling) is saved in `localStorage`
per page load (`iptvnator-server:unsent-writes:<instanceId>:<page>`). The
tab remembers its page load in `sessionStorage`, so a reload takes its
writes over and sends them first (the old copy goes only once the new one
is saved, at the latest with this page's next saved copy; until then the
tab's pointer names the kept page loads too, so another reload finds
them even without their registry records; a duplicate of a tab that
still runs leaves them, like that tab's page load, to it). A page marks
its record closed on `pagehide`, and it stays closed when a page-hide
write failing afterwards rewrites it (not into the back-forward cache, where
its record goes stale, as in a background tab the browser suspends;
restored or shown again after another tab adopted it, the page reloads
rather than send those writes again, and until then it neither sends nor
saves them, also when its retry timer runs first), and
only a closed, stale or missing record is taken over: a duplicated tab,
which copies `sessionStorage`, leaves the running tab its writes. A page
load that still looked live (or whose close flag storage refused) is
checked again every 30 s and, once it does not, adopted like a closed
tab's: its edits go ahead of this page's newer ones, and without a
server version this page read they are sent so that they conflict and
replay; the writes of a tab closed before it
could send them are queued, ahead of its own, by another tab once that
tab's record has gone stale (at its next re-read, or its 30 s check when
it has nothing to sync and never re-reads); the result replays the
closed tab's edits first and this tab's newer ones last. An adopted edit
changes only what is still as its page saw it (`EditStep.yields`), also
at every later conflict: an item or key changed since, by this tab or
another device, keeps its newer value. Tabs never clear each other's.
Cache and saved writes belong to one server database
(`iptvnator-server:cache-owner`); another one behind the same address
starts clean. Startup waits for the first read only a few seconds;
`UserDataStorage.ready()` waits for a first read in flight (it starts
none, so an offline page is not held up) and tells whether one
succeeded. The Xtream data source's favorites, favorite checks, history
and position reads wait for it, so a new device does not show empty
lists or start playback without its resume position. A backup export or
restore (also its replay when the playlist opens) reads the server again
first (`ready(true)`: another device may have changed the lists since) and
fails when that read does not succeed: unread maps would export as empty lists, and a restore's lists
would merge into the server's instead of replacing them (the restore
stays parked). A restore also replaces nothing while this page's own
writes for the playlist are unsent (they would join the replacement) and
counts only once the server took its lists (`UserDataStorage.flushed`)
as they are: a conflict that merged another device's edit in leaves it
parked to run again on a fresh read. Replayed edits keep recently viewed lists newest first,
as the app cuts them at their limit from the end. Also,
re-reads run one at a time and keep entries edited while they were in
flight or not yet saved, and entries another tab saved meanwhile or had
unconfirmed when the read went out (the answer predates them; their next
write here conflicts and replays). A response body cut off after its headers counts
as offline. Each write is sent on the tag of the entry it was made
against (`UserDataWriteQueue`); after a `412` the edit (before → after) is
replayed on the server's current value, so another device's change to the
same playlist's entry is kept. A queued write keeps its edits as steps
(before → after, also in the saved writes): an edit continuing the last
one joins it; one made behind a travelling write, after a write whose
answer was lost, or on another tab's change is kept apart; and a
conflict replays them in order. So a lost
write is not dropped, and adding and then removing an item still removes
it when the addition landed. When two tabs edit one entry before either
write lands, a removal of the other tab's unsent item holds if that tab's
write lands first, as it does when a tab is left (its writes go out on
hide); otherwise the item can come back. An edit made on another tab's unsent change, and an entry a
re-read keeps from the cache, are sent on a version no entry has
(`UNKNOWN_TAG`), so they conflict and are replayed too. Page-hide writes report their
new tag or conflict like any other, and one behind a travelling write is
taken from the queue only when that one is answered. While a playlist is
being deleted its edits wait; the delete drops them only when it
succeeds, and a re-read sent before it skips the deleted playlist. Edits made before the first successful read
are held as before → after and applied to the server's value once it
arrives (`applyEdit`): a new device or a stale cache adds its favorite
instead of replacing the server's list. On this tab's recovered unsent
write they are kept as their own steps after it. They are saved per page load too
(`iptvnator-server:deferred-edits:<instanceId>:<page>`). Records in
`localStorage` (`iptvnator-server:unconfirmed:<instanceId>:<page>`, one
key per page load so tabs never overwrite each other's, renewed every
30 s while it has unsent writes, stale after ten minutes) let a re-read
in one tab keep the cache values another tab is still sending, and a
stale record marks a closed tab whose writes another tab adopts (the
storage adapter lists its keys for this). Saved writes without any record
are left to the tab's own reload: that tab may still run. A value too big for `localStorage`, or any
value when the browser refuses storage access, stays readable from
memory, so callers and the diff baseline agree. A re-read
updates the cache; views already open show another device's changes on
their next load (no live push). Start-up waits
up to 3 s for the first read.
- **Connection state.** `ServerStorageStatusService` is `online`, `offline`
(a request did not reach the server, or a proxy answered 502, 503 or 504
for it; retried every 30 s and when the tab returns, as are writes the
server refused and a first read that failed while it is `online`) or
`unauthorized` (a 401 clears the stored token; only a reload after a new
token leaves it, so a late answer cannot undo sign-out). The rail shows a status
shortcut, an offline banner sits above the workspace content, and failed
writes raise a snackbar (`SERVER_STORAGE.WRITE_FAILED`, or `TOO_LARGE` for
a 413), the same one at most every five minutes.
- **Access token.** With `IPTVNATOR_ACCESS_TOKEN` the instance reports
`auth: 'token'` (the backend refuses a token without server storage: the
PWA has no sign-in flow for a stateless backend); without a stored token, or after a 401, the guards route to
`/server-sign-in` (the start-up screen lets it through although the
playlists could not load), which checks the token against `/v1/instance/status`
before it stores it under `iptvnator-server:access-token` and reloads (a
browser that refuses to store it is told so instead). The token is stored
with the instance id it was given for, and a page sends it only to that
instance: a tab still open on the old backend after `BACKEND_URL` changed
does not send the new server's token there, and goes to sign-in instead.
`ServerAccessTokenInterceptor` adds the header to `HttpClient` calls to the
backend, and `PwaService` adds it to its two raw `fetch` calls only while
server mode runs on a verified instance and only when the URL resolves
to the backend (`isBackendUrl`); it joins paths to the backend URL
without its trailing slashes, so `BACKEND_URL=/` never yields a
protocol-relative `//…` URL that names another host. The browser forgets the token
when the backend answers without server storage, or as another server or
database (backend URL or instance id) than the one it remembers; sign-in
therefore remembers the server along with the token, or reports storage
trouble. A page started from memory first checks that the instance at the
address is the remembered one (`ensureVerified`), and reloads if not
(a reload after a server answered late gives the next start probe as
long as requests take, once, so a slow server does not reload forever),
before sign-in sends the token. So does a page that went offline (any
backend call can tell: the storage API with its page-hide `keepalive`
writes, `HttpClient` calls through the interceptor and `PwaService`'s raw
fetches report no answer, or a
gateway's 502/503/504 that is not the backend's own JSON, as offline)
before its next read: until then it sends neither the token nor writes (a
replaced volume at the same address is another database), and it checks
the instance as soon as it goes offline, so a blip costs no retry
interval (only the instance, and once per retry interval: a read or a
check that keeps failing waits for the retry; the retry also runs while a
late answer set an unchecked page online). Sign-out always navigates to sign-in, also when a guard kept the
page the first time. Both turn
the guard's 401 (`isServerAccessChallenge`) into `reportAccessDenied()`,
as the storage API client does with any 401, so a token changed on the
server sends an open page back to sign-in; a late 401 for a token
replaced since (a new sign-in) changes nothing, nor does one for a page
that holds its token back until the instance is checked.
- **Moving browser data.** `ServerMigrationService` offers, once per server
instance (marker `iptvnator-server:migration:<instanceId>`), to move the
playlists this browser kept in IndexedDB (`planServerMigration`), Stalker
rows from before the portal-mode flag normalized first (server rows get
the same Stalker metadata migration once per server, as a desktop
database copied there can predate it: each row read again and written as
a conditional mutation, a conflict retried at the next start). A
playlist the server already has, by id or by source (Xtream server and
user, Stalker portal and MAC, M3U URL), merges into the server's copy; the
others upload with their ids, create-only (`If-None-Match: *`): one that
another tab or device moved first is merged into instead of overwritten. A merged playlist gains the browser
document's favorites and history (M3U favorites name channels by stream
URL, as the app looks them up; older ones by a channel id that is random
per import, which becomes its URL on both sides; history entries keep
their URL id and get the server's channel id as `channel_id`; recently viewed newest first by `added_at`,
one per item with its newest view; Stalker items by id, category and series
flag, since one provider category can hold a movie and a series of one
id; nothing is dropped), and the legacy Xtream maps follow under
the server id; each copy's bare legacy Xtream ids are typed from its own
snapshots first (`typeLegacyXtreamRefs`; snapshots keep their bare key as
an alias), then `combineUserData` unions
lists (playback positions by content type and Xtream id, renamed to the
server playlist; recently viewed items newest first and one per item,
its newest view, since the app cuts history from the end) and merges
maps, the server's value winning on a
conflict. Parental locks stay in the browser but move to the server
playlist id with it; while the lock store or a browser user-data map
cannot be read the move counts as failed. A parked Xtream restore (a
browser backup import that could not finish) is copied to the server
playlist id it merged into, unless that one has its own. Browser data is never
deleted, the move does not start while user-data writes are unsent, and
the marker is written only when nothing failed, so Settings → Server
keeps offering a partial move.
What stays per device: settings, parental lock PINs and locked groups,
the global favorites order and other UI preferences in browser storage.
## Runtime Limitations
The self-hosted build is the browser PWA, not the Electron desktop app. Keep
@@ -172,7 +416,9 @@ these limitations explicit in UI, troubleshooting, and release notes:
metadata uses `PlaylistsService` with IndexedDB, which
`PlaylistStorageBackend` selects when no SQLite bridge exists; Xtream
favorites, recently viewed items, playback positions, and cached collection
snapshots use `PwaXtreamDataSource` browser storage.
snapshots use `PwaXtreamDataSource` browser storage. In
[server storage mode](#server-storage-mode) both live on the server
instead.
- Browser playlist deletion must go through `PlaylistsService`, not
`DatabaseService`. `PlaylistsService.deletePlaylist()` runs registered
cleanup hooks such as the PWA Xtream cleanup so localStorage sidecar data does
@@ -271,8 +517,8 @@ and sidecar state in localStorage:
`PwaXtreamDataSource` and `PwaCollectionStorage` reach these keys through the
`USER_DATA_STORAGE` token from `@iptvnator/services` (default:
`localStorage`), never through `localStorage` directly, so a deployment can
substitute a server-synced storage. The key names are shared as
`localStorage`), never through `localStorage` directly, so server storage
mode can substitute `ServerUserDataStorage`. The key names are shared as
`XTREAM_USER_DATA_KEYS` with the playlist backup, which exports and restores
the favorites, recent items, positions and snapshots through the same token
(`PwaXtreamBackupStateService`; see
+6 -1
View File
@@ -242,7 +242,12 @@ barrier and row reservation before its persisted-source preflight; contention
or unavailable PWA locking declines repair without discovery, while an acquired
reservation stays held through its conditional row transform. The reservation
blocks every new authentication (including a URL edit with the same normalized
fingerprint) and repair, and drains any work already in flight.
fingerprint) and repair, and drains any work already in flight. Delete All
drains the playlist writes queued before it, then takes the exclusive reset;
later writes wait for the delete before they join their playlist's queue, so
no queue holds work blocked on the reset, except a write under a reservation
this tab holds (`holdsPlaylistAuthority`), which joins at once since the
reset waits for that reservation.
When Save follows a lazy repair in the same tab, Edit publishes its local
authentication owner first, drains that repair through the actual Web Lock
request completion, and only then requests the row reservation itself. Repair
+7 -2
View File
@@ -89,7 +89,10 @@ The shell is intentionally split into four persistent regions:
recently viewed. The routed global-search rail link is Electron-only
because its data source is the SQLite worker bridge.
2. Provider-aware context links derived from the active or current playlist.
3. Settings remains a persistent footer shortcut in the rail.
3. Settings remains a persistent footer shortcut in the rail. In
[server storage mode](pwa-self-hosted.md#server-storage-mode) a server
status shortcut sits above it: its dot shows online, offline or
sign-in needed, and it opens Settings → Server.
4. No brand mark: it only repeated the first workspace link (Dashboard,
or Sources when the dashboard is off).
2. Top header:
@@ -103,7 +106,9 @@ The shell is intentionally split into four persistent regions:
6. Downloads shortcut in Electron.
3. Main body:
1. Optional left context panel.
2. Main router outlet content.
2. Main router outlet content. In server storage mode an offline banner
with Retry takes the first row of `.workspace-content-frame`, above
the scroller, so full-height pages keep their height.
4. Optional footer:
1. External playback session bar when a docked session is visible.
@@ -79,9 +79,16 @@ on the server. Adding a playlist stays the ordinary "Add playlist" flow.
this instance): a dialog offers "Move to server". Playlists are copied
with their ids, then the four Xtream user-data maps for those ids.
- Any later device (server already has playlists): Settings → Server
offers "Import this browser's playlists", which runs the existing backup
export (browser) and import (server) with fingerprint merging, so the
same provider added on two devices is not duplicated.
offers "Import this browser's playlists". A browser playlist the server
already has (same id, or same source: Xtream server and user, Stalker
portal and MAC, M3U URL) merges into the server's copy, so the same
provider added on two devices is not duplicated; the others upload with
their ids. A merged playlist gains the browser's favorites and history,
and the Xtream maps follow under the server id, combined with what the
server has (lists unioned, maps merged, the server winning conflicts). The backup format is not used: its
PWA export carries no Xtream user data.
- The decision marker is written only when nothing failed, so a partial
move stays on offer and can run again.
- Browser data is never deleted. The server-mode cache uses its own
localStorage key prefix, so legacy keys stay intact.
5. Offline: reads and writes fail with a visible state. The rail shows an
@@ -125,8 +132,8 @@ All JSON. Errors: `{ message, status, code? }`.
| `DELETE /v1/playlists/:id` | Delete the row and its user-state entries. |
| `DELETE /v1/playlists` | Delete all playlists and all user state. |
| `GET/PUT /v1/app-state/:key` | `{ value }`. |
| `GET /v1/user-state` | `{ entries: { [namespace]: { [playlistId]: value } } }`. |
| `PUT/DELETE /v1/user-state/:namespace/:playlistId` | One entry. Namespaces are an allow-list. |
| `GET /v1/user-state` | `{ entries: { [namespace]: { [playlistId]: value } }, tags }`, a content tag per entry. |
| `PUT/DELETE /v1/user-state/:namespace/:playlistId` | One entry. Namespaces are an allow-list. `If-Match: "<tag>"` or `If-None-Match: *` makes it conditional: `412` with the current value and tag. A `PUT` for a playlist the server does not have answers `404 playlist_missing`. |
ETags are `"<bootId>-<revision>"` from an in-memory per-playlist revision
counter; the server is the only writer of its database.
@@ -143,8 +150,7 @@ closes it on `SIGTERM`. Storage errors are logged by name and route only.
- `PlaylistStorageBackend` (libs/services) resolves the document store:
server store in server mode, Electron bridge when `supportsSqlite`, else
IndexedDB. It can switch to browser storage temporarily for the migration
export.
IndexedDB.
- `@iptvnator/services/server-storage` (sub-entry, kept out of the eager
barrel): API client, document store, user-data storage, session, migration.
- `ServerStorageStatusService` (main barrel, tiny): connection state for the
@@ -170,7 +176,7 @@ https://claude.ai/artifact/3WheJAgeNL5ag6kmtPrJcD
| Situation | Behavior |
| --- | --- |
| Probe fails or times out (2.5 s) | Browser mode, no server UI. |
| Probe gets no answer (network error, 2.5 s timeout, 5xx) | Server mode, offline, if this browser used this backend before (`iptvnator-server:instance`); the page reloads once the server answers. Otherwise browser mode. An answer without server storage, or a 404, forgets the server. |
| Request fails after boot | Status `offline`, banner, write failures show a snackbar; retry on `visibilitychange` and every 30 s. |
| `401` | Status `unauthorized`, stored token cleared, redirect to sign-in. |
| `413` | Snackbar names the limit. |
@@ -203,9 +209,12 @@ https://claude.ai/artifact/3WheJAgeNL5ag6kmtPrJcD
## 11. Risks
- **Concurrent edits on two devices**: last write wins per document or per
Xtream map entry. Every playlist mutation re-reads first, so the window is
one round trip.
- **Concurrent edits on two devices**: a playlist mutation is sent with
`If-Match` on the version it was read at; on a `412` the per-playlist
write queue runs the mutation again on a fresh read. Imports and start-up
migrations stay last write wins.
Xtream map entries are written on the tag they were read at and replayed
on the server's value after a `412`, so both devices' edits are kept.
- **Large payloads**: M3U global favorites and backup export read all full
documents, as IndexedDB does today.
- **Open instances**: storing credentials raises the cost of an unprotected
+35 -6
View File
@@ -89,9 +89,21 @@ export class PlaylistEffects {
this.store.select(selectActivePlaylistId)
),
filter(([, , playlistId]) => !!playlistId),
switchMap(([, favorites, playlistId]) =>
this.playlistsService.updateFavorites(playlistId, favorites)
),
// The toggle, applied to the favorites as stored at write
// time: another device's changes to other channels stay, also
// when a conflict makes the write run again on a fresh read.
mergeMap(([{ channel }, favorites, playlistId]) => {
const added = favorites.includes(channel.url);
return this.playlistsService.transformPlaylistFavorites(
playlistId,
(current) => {
const others = current.filter(
(favorite) => favorite !== channel.url
);
return added ? [...others, channel.url] : others;
}
);
}),
tap(() => {
this.snackBar.open(
this.translate.instant('CHANNELS.FAVORITES_UPDATED'),
@@ -110,10 +122,13 @@ export class PlaylistEffects {
ofType(FavoritesActions.setFavorites),
withLatestFrom(this.store.select(selectActivePlaylistId)),
filter(([, playlistId]) => !!playlistId),
switchMap(([action, playlistId]) =>
this.playlistsService.setFavorites(
// The new order, applied to the favorites as stored at write
// time: another device's additions stay, its removals hold.
mergeMap(([action, playlistId]) =>
this.playlistsService.transformPlaylistFavorites(
playlistId,
action.channelIds
(current) =>
reorderFavorites(current, action.channelIds)
)
)
);
@@ -582,3 +597,17 @@ export class PlaylistEffects {
return normalizeEpgUrls(this.settingsStore.getSettings().epgUrl ?? []);
}
}
/**
* `current` in the order of `order`: entries `order` no longer has stay out
* of its part, entries it never had (added elsewhere) follow it.
*/
export function reorderFavorites<T>(
current: readonly T[],
order: readonly T[]
): T[] {
const present = new Set(current);
const ordered = order.filter((id) => present.has(id));
const placed = new Set(ordered);
return [...ordered, ...current.filter((id) => !placed.has(id))];
}
@@ -0,0 +1,108 @@
import { Injector, runInInjectionContext } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { Actions } from '@ngrx/effects';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { EpgService } from '@iptvnator/epg/data-access';
import { PlaylistsService, SettingsStore } from '@iptvnator/services';
import type { Channel } from '@iptvnator/shared/interfaces';
import { of, Subject } from 'rxjs';
import { FavoritesActions } from './actions';
import { PlaylistEffects } from './effects';
import { selectActivePlaylistId, selectFavorites } from './selectors';
describe('PlaylistEffects updateFavorites$', () => {
let actions$: Subject<unknown>;
let transformPlaylistFavorites: jest.Mock;
let storedFavorites: string[];
function setup(afterToggle: string[]) {
actions$ = new Subject();
transformPlaylistFavorites = jest.fn(
(_id: string, transform: (current: string[]) => string[]) => {
storedFavorites = transform(storedFavorites);
return of(undefined);
}
);
const injector = Injector.create({
parent: { get: () => ({}) } as unknown as Injector,
providers: [
{ provide: Actions, useValue: new Actions(actions$) },
{
provide: Store,
useValue: {
select: (selector: unknown) =>
of(
selector === selectFavorites
? afterToggle
: selector === selectActivePlaylistId
? 'p1'
: undefined
),
},
},
{
provide: PlaylistsService,
useValue: { transformPlaylistFavorites },
},
{ provide: EpgService, useValue: { fetchEpg: jest.fn() } },
{ provide: Router, useValue: {} },
{ provide: MatSnackBar, useValue: { open: jest.fn() } },
{
provide: TranslateService,
useValue: { instant: (key: string) => key },
},
{
provide: SettingsStore,
useValue: { getSettings: () => ({ epgUrl: [] }) },
},
],
});
const effects = runInInjectionContext(
injector,
() => new PlaylistEffects()
);
effects.updateFavorites$.subscribe();
effects.setFavorites$.subscribe();
}
const channel = { url: 'http://a' } as Channel;
it("adds the toggled channel to the stored favorites, keeping others'", () => {
// This device's state did not know about 'http://b' yet.
storedFavorites = ['http://b'];
setup(['http://a']);
actions$.next(FavoritesActions.updateFavorites({ channel }));
expect(transformPlaylistFavorites).toHaveBeenCalledWith(
'p1',
expect.any(Function)
);
expect(storedFavorites).toEqual(['http://b', 'http://a']);
});
it('removes only the toggled channel', () => {
storedFavorites = ['http://a', 'http://b'];
setup([]);
actions$.next(FavoritesActions.updateFavorites({ channel }));
expect(storedFavorites).toEqual(['http://b']);
});
it('applies a reorder to the stored favorites', () => {
// Another device added 'http://new' and removed 'http://gone'.
storedFavorites = ['http://a', 'http://b', 'http://new'];
setup([]);
actions$.next(
FavoritesActions.setFavorites({
channelIds: ['http://b', 'http://gone', 'http://a'],
})
);
expect(storedFavorites).toEqual(['http://b', 'http://a', 'http://new']);
});
});
@@ -953,5 +953,247 @@ describe('PwaXtreamDataSource', () => {
);
expect(localStorage.getItem('xtream-favorites')).toBeNull();
});
it('reads positions once the first server read settled', async () => {
const values = new Map<string, string>();
let firstRead = (): void => undefined;
const storage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => {
values.set(key, value);
},
removeItem: (key: string) => {
values.delete(key);
},
// Server mode: the server's data lands in the cache later.
ready: () =>
new Promise<boolean>((resolve) => {
firstRead = () => {
values.set(
'xtream-playback-positions',
JSON.stringify({
p1: [
{
contentXtreamId: 501,
contentType: 'vod',
positionSeconds: 120,
},
],
})
);
resolve(true);
};
}),
};
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
PwaXtreamDataSource,
{ provide: USER_DATA_STORAGE, useValue: storage },
{ provide: ParentalLockService, useValue: parentalLock },
{ provide: XtreamApiService, useValue: apiService },
{ provide: PlaylistsService, useValue: playlistsService },
],
});
const source = TestBed.inject(PwaXtreamDataSource);
const position = source.getPlaybackPosition('p1', 501, 'vod');
// The read is still running while other work goes on.
for (let turn = 0; turn < 5; turn += 1) {
await Promise.resolve();
}
firstRead();
await expect(position).resolves.toMatchObject({
positionSeconds: 120,
});
});
it('keeps a restore parked while the server user data is unread', async () => {
const values = new Map<string, string>([
['xtream-favorites', JSON.stringify({ p1: ['live:1'] })],
]);
const storage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => {
values.set(key, value);
},
removeItem: (key: string) => {
values.delete(key);
},
ready: jest.fn(async () => false),
};
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
PwaXtreamDataSource,
{ provide: USER_DATA_STORAGE, useValue: storage },
{ provide: ParentalLockService, useValue: parentalLock },
{ provide: XtreamApiService, useValue: apiService },
{ provide: PlaylistsService, useValue: playlistsService },
],
});
const source = TestBed.inject(PwaXtreamDataSource);
await expect(
source.restoreUserData('p1', {
hiddenCategories: [],
favorites: [],
recentlyViewed: [],
playbackPositions: [],
} as never)
).rejects.toThrow(/restore waits/);
// A fresh read: the restore replaces the current lists.
expect(storage.ready).toHaveBeenCalledWith(true);
expect(values.get('xtream-favorites')).toBe(
JSON.stringify({ p1: ['live:1'] })
);
});
it('keeps a restore parked while the server refuses its lists', async () => {
const values = new Map<string, string>();
// Nothing unsent before; the restored lists are refused.
const flushed = jest
.fn()
.mockResolvedValueOnce(true)
.mockResolvedValue(false);
const storage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => {
values.set(key, value);
},
removeItem: (key: string) => {
values.delete(key);
},
ready: async () => true,
flushed,
};
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
PwaXtreamDataSource,
{ provide: USER_DATA_STORAGE, useValue: storage },
{ provide: ParentalLockService, useValue: parentalLock },
{ provide: XtreamApiService, useValue: apiService },
{ provide: PlaylistsService, useValue: playlistsService },
],
});
const source = TestBed.inject(PwaXtreamDataSource);
await expect(
source.restoreUserData('p1', {
hiddenCategories: [],
favorites: [],
recentlyViewed: [],
playbackPositions: [],
} as never)
).rejects.toThrow(/did not take the restored lists/);
expect(flushed).toHaveBeenCalledWith('p1');
});
it('replaces the lists, and runs again when a conflict merged them', async () => {
const values = new Map<string, string>([
['xtream-favorites', JSON.stringify({ p1: ['live:1'] })],
]);
let merge = false;
const storage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => {
values.set(key, value);
},
removeItem: (key: string) => {
values.delete(key);
},
ready: async () => true,
flushed: jest.fn(async () => {
if (merge) {
// Another device added one meanwhile: replayed in.
values.set(
'xtream-favorites',
JSON.stringify({ p1: ['live:9', 'movie:5'] })
);
}
return true;
}),
};
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
PwaXtreamDataSource,
{ provide: USER_DATA_STORAGE, useValue: storage },
{ provide: ParentalLockService, useValue: parentalLock },
{ provide: XtreamApiService, useValue: apiService },
{ provide: PlaylistsService, useValue: playlistsService },
],
});
const source = TestBed.inject(PwaXtreamDataSource);
const state = {
hiddenCategories: [],
favorites: [{ xtreamId: 5, contentType: 'movie' }],
recentlyViewed: [],
playbackPositions: [],
} as never;
await source.restoreUserData('p1', state);
expect(JSON.parse(values.get('xtream-favorites') ?? '{}')).toEqual({
p1: ['movie:5'],
});
// A saved restore may list one favorite twice: reads drop the
// copy on both sides of the comparison.
await expect(
source.restoreUserData('p1', {
...(state as object),
favorites: [
{ xtreamId: 5, contentType: 'movie' },
{ xtreamId: 5, contentType: 'movie' },
],
} as never)
).resolves.toBeUndefined();
merge = true;
await expect(source.restoreUserData('p1', state)).rejects.toThrow(
/changed elsewhere/
);
});
it('replaces nothing while earlier changes to the playlist are unsent', async () => {
const values = new Map<string, string>([
['xtream-favorites', JSON.stringify({ p1: ['live:1'] })],
]);
const storage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => {
values.set(key, value);
},
removeItem: (key: string) => {
values.delete(key);
},
ready: async () => true,
flushed: jest.fn().mockResolvedValueOnce(false),
};
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
PwaXtreamDataSource,
{ provide: USER_DATA_STORAGE, useValue: storage },
{ provide: ParentalLockService, useValue: parentalLock },
{ provide: XtreamApiService, useValue: apiService },
{ provide: PlaylistsService, useValue: playlistsService },
],
});
const source = TestBed.inject(PwaXtreamDataSource);
await expect(
source.restoreUserData('p1', {
hiddenCategories: [],
favorites: [],
recentlyViewed: [],
playbackPositions: [],
} as never)
).rejects.toThrow(/not on the server yet/);
expect(values.get('xtream-favorites')).toBe(
JSON.stringify({ p1: ['live:1'] })
);
});
});
});
@@ -695,6 +695,7 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
// =========================================================================
async getFavorites(playlistId: string): Promise<XtreamContentItem[]> {
await this.userDataRead();
await this.getCollectionItemsWithHydration(
playlistId,
this.collectionStorage.getFavoritesFromStorage()[playlistId] || []
@@ -766,6 +767,7 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
contentId: XtreamCollectionRef,
playlistId: string
): Promise<boolean> {
await this.userDataRead();
const normalizedContentId = await this.resolveCollectionKey(
playlistId,
contentId
@@ -820,6 +822,7 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
contentXtreamId: number,
contentType: 'vod' | 'episode'
): Promise<PlaybackPositionData | null> {
await this.userDataRead();
const allPositions = this.getPlaybackPositionsFromStorage();
const playlistPositions = allPositions[playlistId] || [];
@@ -836,6 +839,7 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
playlistId: string,
seriesXtreamId: number
): Promise<PlaybackPositionData[]> {
await this.userDataRead();
const allPositions = this.getPlaybackPositionsFromStorage();
const playlistPositions = allPositions[playlistId] || [];
@@ -850,6 +854,7 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
playlistId: string,
limit?: number
): Promise<PlaybackPositionData[]> {
await this.userDataRead();
const allPositions = this.getPlaybackPositionsFromStorage();
const playlistPositions = allPositions[playlistId] || [];
@@ -866,6 +871,7 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
async getAllPlaybackPositions(
playlistId: string
): Promise<PlaybackPositionData[]> {
await this.userDataRead();
const allPositions = this.getPlaybackPositionsFromStorage();
return allPositions[playlistId] || [];
}
@@ -941,6 +947,17 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
this.savePlaybackPositionsToStorage(allPositions);
}
/**
* Server mode: favorites, history and positions show the server's data
* once its first read settled, which startup does not wait for beyond a
* few seconds. A read before it would show a new device empty lists.
* Whether a read succeeded (always true outside server mode); `fresh`
* reads again first, for a restore that replaces the current lists.
*/
private async userDataRead(fresh = false): Promise<boolean> {
return (await this.userDataStorage.ready?.(fresh)) ?? true;
}
private getPlaybackPositionsFromStorage(): Record<
string,
PlaybackPositionData[]
@@ -975,6 +992,7 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
// =========================================================================
async getRecentItems(playlistId: string): Promise<XtreamContentItem[]> {
await this.userDataRead();
await this.getCollectionItemsWithHydration(
playlistId,
(
@@ -1388,6 +1406,20 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
options?: XtreamOperationOptions
): Promise<void> {
void options;
// Its lists replace the server's: before the server's are read they
// would merge into them instead. The restore stays parked.
if (!(await this.userDataRead(true))) {
throw new Error(
"The server's user data could not be read yet; the restore waits."
);
}
// This page's unsent writes for the playlist would join the
// replacement: they go first, or the restore waits.
if ((await this.userDataStorage.flushed?.(playlistId)) === false) {
throw new Error(
'Earlier changes to this playlist are not on the server yet; the restore waits.'
);
}
// Restore favorites
const favorites = this.collectionStorage.getFavoritesFromStorage();
favorites[playlistId] = restoreState.favorites
@@ -1426,6 +1458,28 @@ export class PwaXtreamDataSource implements IXtreamDataSource {
})
);
this.savePlaybackPositionsToStorage(playbackPositions);
// The lists as reads return them (deduplicated, normalized).
const restoredLists = () =>
JSON.stringify([
this.collectionStorage.getFavoritesFromStorage()[playlistId],
this.collectionStorage.getRecentItemsFromStorage()[playlistId],
this.getPlaybackPositionsFromStorage()[playlistId],
]);
const restored = restoredLists();
// Server mode: done once the server took the lists, else it stays
// parked for the next open.
if ((await this.userDataStorage.flushed?.(playlistId)) === false) {
throw new Error(
'The server did not take the restored lists; the restore waits.'
);
}
// A conflict merges an edit another device made meanwhile into the
// lists: the restore replaces them, so it runs again on a fresh read.
if (restoredLists() !== restored) {
throw new Error(
'The lists changed elsewhere during the restore; it runs again.'
);
}
}
// =========================================================================
+3
View File
@@ -33,3 +33,6 @@ export * from './lib/source-health-evidence.service';
export * from './lib/source-activity.service';
export * from './lib/translation-tick';
export * from './lib/user-data-storage';
export * from './lib/server-storage-status.service';
export * from './lib/server-access-token';
export * from './lib/server-slow-start';
@@ -269,6 +269,46 @@ describe('PlaylistBackupService Xtream user state in the PWA', () => {
await expect(service.exportBackup()).rejects.toThrow('denied');
});
it('waits for server user data before it reads the lists', async () => {
// Server mode: the maps hold the server's data once it was read.
const ready = jest.fn(async () => {
seed();
return true;
});
const service = createPlaylistBackupService({
playlistsService: playlistsService([existingXtreamPlaylist]),
pwaXtream: createPwaXtreamBackupState({
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
ready,
}),
});
const { manifest } = await service.exportBackup();
// A fresh read: another device may have changed them since.
expect(ready).toHaveBeenCalledWith(true);
expect(ready).toHaveBeenCalledTimes(1);
expect(xtreamEntry(manifest).userState.favorites).not.toEqual([]);
});
it('refuses to export server user data it could not read', async () => {
const service = createPlaylistBackupService({
playlistsService: playlistsService([existingXtreamPlaylist]),
pwaXtream: createPwaXtreamBackupState({
getItem: () => null,
setItem: jest.fn(),
removeItem: jest.fn(),
ready: async () => false,
}),
});
await expect(service.exportBackup()).rejects.toThrow(
/user data could not be read/
);
});
});
describe('import', () => {
@@ -472,6 +512,130 @@ describe('PlaylistBackupService Xtream user state in the PWA', () => {
});
});
it('keeps the restore parked until server user data was read', async () => {
const manifest = await exportSeeded();
localStorage.clear();
localStorage.setItem(
KEYS.favorites,
JSON.stringify({ 'xtream-1': ['live:1'] })
);
const service = createPlaylistBackupService({
playlistsService: playlistsService([existingXtreamPlaylist]),
pwaXtream: createPwaXtreamBackupState({
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
ready: async () => false,
}),
});
const summary = await service.importBackup(xtreamOnly(manifest));
expect(summary.failed).toBe(1);
// Nothing merged into lists the server may still replace.
expect(read(KEYS.favorites)).toEqual({ 'xtream-1': ['live:1'] });
expect(
pendingRestore(service).getOrThrow('xtream-1')
).not.toBeNull();
});
it('keeps the restore parked when a conflict merged other lists in', async () => {
const manifest = await exportSeeded();
localStorage.clear();
// Taken, but merged with an edit another device made meanwhile.
const flushed = jest
.fn()
.mockResolvedValueOnce(true)
.mockImplementation(async () => {
const map = JSON.parse(
localStorage.getItem(KEYS.favorites) ?? '{}'
);
map['xtream-1'] = [...map['xtream-1'], 'live:9'];
localStorage.setItem(KEYS.favorites, JSON.stringify(map));
return true;
});
const service = createPlaylistBackupService({
playlistsService: playlistsService([existingXtreamPlaylist]),
pwaXtream: createPwaXtreamBackupState({
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
ready: async () => true,
flushed,
}),
});
const summary = await service.importBackup(xtreamOnly(manifest));
expect(summary.failed).toBe(1);
expect(summary.errors[0]).toContain('changed elsewhere');
expect(
pendingRestore(service).getOrThrow('xtream-1')
).not.toBeNull();
});
it('replaces nothing while earlier changes to the playlist are unsent', async () => {
const manifest = await exportSeeded();
localStorage.clear();
localStorage.setItem(
KEYS.favorites,
JSON.stringify({ 'xtream-1': ['live:1'] })
);
// A write of this page for the playlist that the server refused.
const flushed = jest.fn().mockResolvedValueOnce(false);
const service = createPlaylistBackupService({
playlistsService: playlistsService([existingXtreamPlaylist]),
pwaXtream: createPwaXtreamBackupState({
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
ready: async () => true,
flushed,
}),
});
const summary = await service.importBackup(xtreamOnly(manifest));
expect(summary.failed).toBe(1);
// Its edits would have joined the replacement lists.
expect(read(KEYS.favorites)).toEqual({ 'xtream-1': ['live:1'] });
expect(
pendingRestore(service).getOrThrow('xtream-1')
).not.toBeNull();
});
it('keeps the restore parked until the server took the lists', async () => {
const manifest = await exportSeeded();
localStorage.clear();
// Nothing unsent before; the restored lists are refused.
const flushed = jest
.fn()
.mockResolvedValueOnce(true)
.mockResolvedValue(false);
const service = createPlaylistBackupService({
playlistsService: playlistsService([existingXtreamPlaylist]),
pwaXtream: createPwaXtreamBackupState({
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
ready: async () => true,
flushed,
}),
});
const summary = await service.importBackup(xtreamOnly(manifest));
expect(flushed).toHaveBeenCalledWith('xtream-1');
expect(summary.failed).toBe(1);
expect(
pendingRestore(service).getOrThrow('xtream-1')
).not.toBeNull();
// Titles are merged regardless: the replay carries none.
expect(read(KEYS.collectionItems)).toEqual({
'xtream-1': { 'movie:501': heat, 'series:77': legacyShow },
});
});
it('replaces a damaged title cache but refuses an unreadable storage', async () => {
const manifest = await exportSeeded();
localStorage.setItem(KEYS.collectionItems, '{"xtream-1": {');
@@ -91,6 +91,9 @@ export class PlaylistBackupService {
'The parental lock store could not be read; the backup would omit its locks.'
);
}
if (!this.runtime.supportsXtreamSqliteDataSource) {
await this.pwaXtream.ready();
}
const playlists = await firstValueFrom(
this.playlistsService.getAllData()
);
@@ -69,6 +69,17 @@ export async function runWithPlaylistAuthorityReset<T>(
);
}
/** Row reservations this browsing context holds now, per playlist. */
const heldHere = new Map<string, number>();
/**
* Whether this context holds a reservation on the playlist: a store-wide
* reset waits for it, so its own writes must not wait for the reset.
*/
export function holdsPlaylistAuthority(playlistId: string): boolean {
return (heldHere.get(playlistId) ?? 0) > 0;
}
/** Tries to hold one origin-wide row reservation until its owner releases it. */
export async function reservePlaylistAuthority(
playlistId: string
@@ -120,11 +131,18 @@ export async function reservePlaylistAuthority(
}
let released = false;
heldHere.set(playlistId, (heldHere.get(playlistId) ?? 0) + 1);
return {
status: 'acquired',
release: () => {
if (!released) {
released = true;
const count = (heldHere.get(playlistId) ?? 1) - 1;
if (count > 0) {
heldHere.set(playlistId, count);
} else {
heldHere.delete(playlistId);
}
releaseHeldLock();
}
},
@@ -41,4 +41,15 @@ describe('PlaylistStorageBackend', () => {
expect(backend.kind()).toBe('indexeddb');
expect(backend.documentStore()).toBeNull();
});
it('prefers the server store once it is set', () => {
testWindow.electron = undefined;
const backend = create(false);
const store = { dbGetAppPlaylists: jest.fn() } as never;
backend.useServerStore(store);
expect(backend.kind()).toBe('server');
expect(backend.documentStore()).toBe(store);
});
});
@@ -28,20 +28,44 @@ export type PlaylistDocumentStore = Pick<
>
>;
export type PlaylistStorageKind = 'electron' | 'indexeddb';
/**
* The server refused a write built on a playlist version another device has
* replaced since; the write queue runs the mutation again on a fresh read.
*/
export class PlaylistWriteConflict extends Error {
constructor(readonly playlistId: string) {
super(`Playlist ${playlistId} changed since it was read.`);
this.name = 'PlaylistWriteConflict';
}
}
export type PlaylistStorageKind = 'electron' | 'server' | 'indexeddb';
/** Single place that decides where `PlaylistsService` persists playlists. */
@Injectable({ providedIn: 'root' })
export class PlaylistStorageBackend {
private readonly runtime = inject(RuntimeCapabilitiesService);
private serverStore: PlaylistDocumentStore | null = null;
/** Server mode: set once by the server storage session at startup. */
useServerStore(store: PlaylistDocumentStore): void {
this.serverStore = store;
}
kind(): PlaylistStorageKind {
if (this.serverStore) {
return 'server';
}
return this.runtime.supportsSqlite ? 'electron' : 'indexeddb';
}
/** The document store for `kind()`, or `null` for IndexedDB. */
documentStore(): PlaylistDocumentStore | null {
if (this.kind() !== 'electron' || typeof window === 'undefined') {
const kind = this.kind();
if (kind === 'server') {
return this.serverStore;
}
if (kind !== 'electron' || typeof window === 'undefined') {
return null;
}
return (window.electron as PlaylistDocumentStore | undefined) ?? null;
@@ -54,6 +54,8 @@ describe('PlaylistsService inventory reads', () => {
},
electronMigrationPromise: null,
playlistWriteQueues: new Map(),
deletingAll: Promise.resolve(),
resets: 0,
});
const settle = async (index: number, playlists: Playlist[]) => {
// The read starts after the memoized migration's awaits.
+431 -32
View File
@@ -1,5 +1,7 @@
import { EMPTY, firstValueFrom, from, of } from 'rxjs';
import { DbStores, Playlist, PlaylistMeta } from '@iptvnator/shared/interfaces';
import { reservePlaylistAuthority } from './playlist-cross-context-lock';
import { PlaylistWriteConflict } from './playlist-storage-backend';
import { PlaylistsService, resolvePlaylistParser } from './playlists.service';
const SQLITE_PLAYLIST_MIGRATION_FLAG = 'm3u-playlists-indexeddb-to-sqlite-v1';
@@ -66,6 +68,8 @@ describe('PlaylistsService', () => {
electronMigrationPromise: null,
indexedDbMigrationPromise: null,
playlistWriteQueues: new Map(),
deletingAll: Promise.resolve(),
resets: 0,
playlistDeleteCleanups: [],
});
@@ -73,7 +77,10 @@ describe('PlaylistsService', () => {
}
it('announces a committed SQLite connection edit', async () => {
const playlist = { _id: 'source', url: 'https://old.test/list' } as Playlist;
const playlist = {
_id: 'source',
url: 'https://old.test/list',
} as Playlist;
testWindow.electron = {
dbGetAppState: jest.fn().mockResolvedValue('1'),
dbSetAppState: jest.fn(),
@@ -84,8 +91,22 @@ describe('PlaylistsService', () => {
const service = createService();
const next = jest.fn();
Object.assign(service, { healthEvidence: { connections: { next } } });
await firstValueFrom(service.updatePlaylistMeta({ ...playlist, title: 'Source', count: 0, importDate: '', autoRefresh: false, serverUrl: 'https://new.test' }));
expect(next).toHaveBeenCalledWith({ id: 'source', playlist: expect.objectContaining({ serverUrl: 'https://new.test' }) });
await firstValueFrom(
service.updatePlaylistMeta({
...playlist,
title: 'Source',
count: 0,
importDate: '',
autoRefresh: false,
serverUrl: 'https://new.test',
})
);
expect(next).toHaveBeenCalledWith({
id: 'source',
playlist: expect.objectContaining({
serverUrl: 'https://new.test',
}),
});
});
it('announces committed deletion but does not retire health after a failed write', async () => {
@@ -95,9 +116,15 @@ describe('PlaylistsService', () => {
await firstValueFrom(service.deletePlaylist('retired'));
expect(next).toHaveBeenCalledWith({ id: 'retired' });
next.mockClear();
const failed = createService({ delete: jest.fn(() => { throw new Error('write failed'); }) });
const failed = createService({
delete: jest.fn(() => {
throw new Error('write failed');
}),
});
Object.assign(failed, { healthEvidence: { connections: { next } } });
await expect(firstValueFrom(failed.deletePlaylist('kept'))).rejects.toThrow();
await expect(
firstValueFrom(failed.deletePlaylist('kept'))
).rejects.toThrow();
expect(next).not.toHaveBeenCalled();
});
@@ -554,6 +581,85 @@ describe('PlaylistsService', () => {
);
});
describe('legacy Stalker portal flags on the server', () => {
// A desktop database copied to the server, from before the flag.
const copied = {
_id: 'stalker-1',
title: 'Copied Stalker',
count: 0,
importDate: new Date('2026-03-28T00:00:00.000Z').toISOString(),
lastUsage: new Date('2026-03-28T00:00:00.000Z').toISOString(),
autoRefresh: false,
macAddress: '00:1A:79:AA:BB:CC',
portalUrl: 'http://example.com/stalker_portal/c/',
} as Playlist;
function serverService(
fresh: Playlist,
upsert: jest.Mock = jest.fn(async () => ({ success: true }))
) {
const appState = new Map<string, string>();
const server = {
dbGetAppPlaylists: jest.fn(async () => [copied]),
// Another device may have changed it since the list read.
dbGetAppPlaylist: jest.fn(async () => fresh),
dbGetAppState: jest.fn(
async (key: string) => appState.get(key) ?? null
),
dbSetAppState: jest.fn(async (key: string, value: string) => {
appState.set(key, value);
}),
dbUpsertAppPlaylist: upsert,
dbUpsertAppPlaylists: jest.fn(),
dbRecoverLegacyPlaylists: jest.fn(),
};
testWindow.electron = undefined;
const service = createService();
Object.assign(service as object, {
storageBackend: {
kind: () => 'server',
documentStore: () => server,
},
});
return { service, server, appState };
}
it('are written per row on a fresh read, as conditional mutations', async () => {
const edited = { ...copied, title: 'Renamed elsewhere' };
const { service, server, appState } = serverService(edited);
await firstValueFrom(service.getAllPlaylists());
// Never the stale list copy, never an unconditional bulk write.
expect(server.dbUpsertAppPlaylists).not.toHaveBeenCalled();
expect(server.dbUpsertAppPlaylist).toHaveBeenCalledWith({
...edited,
isFullStalkerPortal: true,
});
expect(appState.get(STALKER_PLAYLIST_METADATA_MIGRATION_FLAG)).toBe(
'1'
);
// The desktop-only steps stay with the desktop.
expect(server.dbRecoverLegacyPlaylists).not.toHaveBeenCalled();
});
it('stay unflagged for the next start after a conflict', async () => {
const { service, appState } = serverService(
copied,
jest.fn(async () => {
throw new PlaylistWriteConflict('stalker-1');
})
);
jest.spyOn(console, 'error').mockImplementation(() => undefined);
await firstValueFrom(service.getAllPlaylists());
expect(
appState.get(STALKER_PLAYLIST_METADATA_MIGRATION_FLAG)
).toBeUndefined();
});
});
it('does not rerun the SQLite Stalker metadata migration after the flag is set', async () => {
const electron = {
dbGetAppPlaylists: jest.fn(async () => []),
@@ -1109,7 +1215,9 @@ describe('PlaylistsService', () => {
] as Playlist[];
const dbService = {
getAll: jest.fn(() => of([])),
getByID: jest.fn((_store: string, id: string) => of(playlists.find((p) => p._id === id))),
getByID: jest.fn((_store: string, id: string) =>
of(playlists.find((p) => p._id === id))
),
update: jest.fn((_storeName: string, playlist: Playlist) =>
of(playlist)
),
@@ -1142,19 +1250,32 @@ describe('PlaylistsService', () => {
);
});
it.each([false, true])('does not resurrect a deleted source when startup refresh finishes (SQLite=%s)', async (sqlite) => {
const upsert = jest.fn();
testWindow.electron = sqlite ? {
dbGetAppState: jest.fn().mockResolvedValue('1'), dbSetAppState: jest.fn(),
dbGetAppPlaylists: jest.fn().mockResolvedValue([]), dbGetAppPlaylist: jest.fn().mockResolvedValue(null),
dbUpsertAppPlaylist: upsert,
} : undefined;
const update = jest.fn(() => of(undefined));
const service = createService({ update });
expect(await firstValueFrom(service.updateManyPlaylists([{ _id: 'deleted', autoRefresh: true } as Playlist]))).toEqual([]);
expect(update).not.toHaveBeenCalled();
expect(upsert).not.toHaveBeenCalled();
});
it.each([false, true])(
'does not resurrect a deleted source when startup refresh finishes (SQLite=%s)',
async (sqlite) => {
const upsert = jest.fn();
testWindow.electron = sqlite
? {
dbGetAppState: jest.fn().mockResolvedValue('1'),
dbSetAppState: jest.fn(),
dbGetAppPlaylists: jest.fn().mockResolvedValue([]),
dbGetAppPlaylist: jest.fn().mockResolvedValue(null),
dbUpsertAppPlaylist: upsert,
}
: undefined;
const update = jest.fn(() => of(undefined));
const service = createService({ update });
expect(
await firstValueFrom(
service.updateManyPlaylists([
{ _id: 'deleted', autoRefresh: true } as Playlist,
])
)
).toEqual([]);
expect(update).not.toHaveBeenCalled();
expect(upsert).not.toHaveBeenCalled();
}
);
it('short-circuits updateManyPlaylists when no playlists are provided', async () => {
const dbService = {
@@ -1635,6 +1756,273 @@ describe('PlaylistsService', () => {
);
});
it('deletes everything only after queued writes, before later ones', async () => {
const order: string[] = [];
let finishWrite: () => void = () => undefined;
const electron = {
dbGetAppPlaylist: jest.fn(async () => {
order.push('read');
return { _id: 'p9', title: 'P', favorites: [] };
}),
dbGetAppPlaylists: jest.fn(async () => []),
dbGetAppState: jest.fn(async (key: string) =>
key === SQLITE_PLAYLIST_MIGRATION_FLAG ? '1' : null
),
dbSetAppState: jest.fn(),
dbUpsertAppPlaylist: jest.fn(
() =>
new Promise<void>((resolve) => {
order.push('write');
finishWrite = () => resolve();
})
),
dbUpsertAppPlaylists: jest.fn(),
dbDeleteAllPlaylists: jest.fn(async () => {
order.push('delete all');
}),
};
testWindow.electron = electron;
const service = createService();
// Microtasks only: a real timer would let other tests' late errors in.
const settle = async () => {
for (let i = 0; i < 50; i += 1) {
await Promise.resolve();
}
};
const first = firstValueFrom(
service.transformPlaylistFavorites('p9', (f) => [...f, 'a'])
);
await settle();
const removed = firstValueFrom(service.removeAll());
const later = firstValueFrom(
service.transformPlaylistFavorites('p9', (f) => [...f, 'b'])
);
await settle();
expect(order).toEqual(['read', 'write']);
finishWrite();
await first;
await removed;
await settle();
finishWrite();
await later;
expect(order).toEqual(['read', 'write', 'delete all', 'read', 'write']);
});
describe('Delete All with cross-context locks', () => {
/** Web Locks as far as these tests need: the barrier and free rows. */
function fakeLocks() {
let shared = 0;
let exclusive = false;
const waiting: (() => void)[] = [];
const changed = () => waiting.splice(0).forEach((wake) => wake());
const until = async (free: () => boolean) => {
while (!free()) {
await new Promise<void>((wake) => waiting.push(wake));
}
};
const request = jest.fn(
async <T>(
name: string,
options: LockOptions,
callback: (lock: Lock | null) => Promise<T>
) => {
const lock = {
name,
mode: options.mode ?? 'exclusive',
} as Lock;
if (name !== 'iptvnator:playlist-authority') {
return callback(lock);
}
if (options.mode === 'shared') {
await until(() => !exclusive);
shared += 1;
try {
return await callback(lock);
} finally {
shared -= 1;
changed();
}
}
await until(() => !exclusive && shared === 0);
exclusive = true;
try {
return await callback(lock);
} finally {
exclusive = false;
changed();
}
}
);
Object.defineProperty(globalThis.navigator, 'locks', {
configurable: true,
value: { request },
});
}
let finishWrite: () => void = () => undefined;
function store(slowWrites = false) {
const electron = {
dbGetAppPlaylist: jest.fn(async () => ({
_id: 'p9',
title: 'P',
favorites: [],
})),
dbGetAppPlaylists: jest.fn(async () => []),
dbGetAppState: jest.fn(async (key: string) =>
key === SQLITE_PLAYLIST_MIGRATION_FLAG ? '1' : null
),
dbSetAppState: jest.fn(),
// Only the first write is slow.
dbUpsertAppPlaylist: jest.fn(() => {
if (!slowWrites) {
return Promise.resolve();
}
slowWrites = false;
return new Promise<void>(
(resolve) => (finishWrite = resolve)
);
}),
dbUpsertAppPlaylists: jest.fn(),
dbDeletePlaylist: jest.fn(async () => undefined),
dbDeleteAllPlaylists: jest.fn(async () => undefined),
};
testWindow.electron = electron;
return electron;
}
const settle = async () => {
for (let i = 0; i < 100; i += 1) {
await Promise.resolve();
}
};
it('lets a repair holding its reservation write first', async () => {
fakeLocks();
const electron = store();
const service = createService();
const reservation = await reservePlaylistAuthority('p9');
if (reservation.status !== 'acquired') {
throw new Error('expected a reservation');
}
const removed = firstValueFrom(service.removeAll());
// The repair's conditional row write, under its reservation.
let written = false;
const repair = firstValueFrom(
service.transformPlaylistFavorites('p9', (f) => [...f, 'a'])
).then(() => (written = true));
await settle();
expect(written).toBe(true);
expect(electron.dbDeleteAllPlaylists).not.toHaveBeenCalled();
reservation.release();
await repair;
await removed;
expect(electron.dbDeleteAllPlaylists).toHaveBeenCalled();
});
it('lets a repair write past later writes waiting for the reset', async () => {
fakeLocks();
const electron = store(true);
const service = createService();
// An earlier slow write that Delete All waits for.
const slow = firstValueFrom(
service.transformPlaylistFavorites('q1', (f) => [...f, 'a'])
);
await settle();
const removed = firstValueFrom(service.removeAll());
// A later write for P, which waits for the reset.
const later = firstValueFrom(
service.transformPlaylistFavorites('p9', (f) => [...f, 'b'])
);
// A repair reserves P before the reset takes its lock.
const reservation = await reservePlaylistAuthority('p9');
if (reservation.status !== 'acquired') {
throw new Error('expected a reservation');
}
let repaired = false;
const repair = firstValueFrom(
service.transformPlaylistFavorites('p9', (f) => [...f, 'r'])
).then(() => {
repaired = true;
reservation.release();
});
await settle();
expect(repaired).toBe(true);
finishWrite();
await Promise.all([slow, repair, removed, later]);
expect(electron.dbDeleteAllPlaylists).toHaveBeenCalled();
});
it('lets a deletion queued behind a slow write finish first', async () => {
fakeLocks();
const electron = store(true);
const service = createService();
const slow = firstValueFrom(
service.transformPlaylistFavorites('p9', (f) => [...f, 'a'])
);
await settle();
const deleted = firstValueFrom(service.deletePlaylist('p9'));
let done = false;
const removed = firstValueFrom(service.removeAll()).then(
() => (done = true)
);
await settle();
finishWrite();
await settle();
// The deletion needs the shared lock: it cannot wait for a
// reset that waits for it.
expect(done).toBe(true);
await slow;
await deleted;
await removed;
expect(electron.dbDeletePlaylist).toHaveBeenCalledWith('p9');
expect(electron.dbDeleteAllPlaylists).toHaveBeenCalled();
});
});
it('runs a mutation again on a fresh read when the server refused it', async () => {
const versions = [
{ _id: 'p9', title: 'P', favorites: ['a'] },
{ _id: 'p9', title: 'P', favorites: ['a', 'theirs'] },
] as unknown as Playlist[];
let reads = 0;
const electron = {
dbGetAppPlaylist: jest.fn(
async () => versions[Math.min(reads++, 1)]
),
dbGetAppPlaylists: jest.fn(async () => []),
dbGetAppState: jest.fn(async (key: string) =>
key === SQLITE_PLAYLIST_MIGRATION_FLAG ? '1' : null
),
dbSetAppState: jest.fn(),
dbUpsertAppPlaylist: jest
.fn()
.mockRejectedValueOnce(new PlaylistWriteConflict('p9'))
.mockResolvedValue(undefined),
dbUpsertAppPlaylists: jest.fn(),
};
testWindow.electron = electron;
await firstValueFrom(
createService().transformPlaylistFavorites('p9', (favorites) => [
...favorites,
'mine',
])
);
expect(electron.dbUpsertAppPlaylist).toHaveBeenCalledTimes(2);
expect(electron.dbUpsertAppPlaylist).toHaveBeenLastCalledWith(
expect.objectContaining({ favorites: ['a', 'theirs', 'mine'] })
);
});
it('short-circuits removeFromPlaylistRecentlyViewedBatch when identities is empty', async () => {
const existingPlaylist: Playlist = {
_id: 'playlist-5',
@@ -1813,19 +2201,30 @@ describe('PlaylistsService', () => {
);
});
it.each([false, true])('does not recreate a removed source on singular refresh (SQLite: %s)', async (sqlite) => {
const upsert = jest.fn();
testWindow.electron = sqlite ? {
dbGetAllPlaylists: jest.fn().mockResolvedValue([]),
dbGetAppPlaylist: jest.fn().mockResolvedValue(null),
dbUpsertAppPlaylist: upsert,
} as unknown as typeof testWindow.electron : undefined;
const update = jest.fn(() => of(undefined));
const service = createService({ update });
await expect(firstValueFrom(service.updatePlaylist('deleted', { _id: 'deleted' } as Playlist))).rejects.toThrow('Playlist no longer exists');
expect(update).not.toHaveBeenCalled();
expect(upsert).not.toHaveBeenCalled();
});
it.each([false, true])(
'does not recreate a removed source on singular refresh (SQLite: %s)',
async (sqlite) => {
const upsert = jest.fn();
testWindow.electron = sqlite
? ({
dbGetAllPlaylists: jest.fn().mockResolvedValue([]),
dbGetAppPlaylist: jest.fn().mockResolvedValue(null),
dbUpsertAppPlaylist: upsert,
} as unknown as typeof testWindow.electron)
: undefined;
const update = jest.fn(() => of(undefined));
const service = createService({ update });
await expect(
firstValueFrom(
service.updatePlaylist('deleted', {
_id: 'deleted',
} as Playlist)
)
).rejects.toThrow('Playlist no longer exists');
expect(update).not.toHaveBeenCalled();
expect(upsert).not.toHaveBeenCalled();
}
);
it('keeps hiddenGroupTitles when refreshing a playlist payload', async () => {
const existingPlaylist: Playlist = {
_id: 'playlist-2',
+109 -42
View File
@@ -28,7 +28,6 @@ import {
Channel,
DbStores,
extractStalkerItemId,
isFullStalkerPortalUrl,
isM3uRecentlyViewedItem,
M3uFavoriteChannel,
M3uRecentlyViewedItem,
@@ -38,15 +37,18 @@ import {
PlaylistUpdateState,
StalkerPortalItem,
normalizeStalkerDate,
withExplicitStalkerPortalFlag,
} from '@iptvnator/shared/interfaces';
import { PLAYLIST_DELETE_CLEANUP } from './playlist-delete-cleanup.token';
import {
runWithPlaylistAuthorityMutation,
holdsPlaylistAuthority,
runWithPlaylistAuthorityReset,
} from './playlist-cross-context-lock';
import {
PlaylistDocumentStore,
PlaylistStorageBackend,
PlaylistWriteConflict,
} from './playlist-storage-backend';
const SQLITE_PLAYLIST_MIGRATION_FLAG = 'm3u-playlists-indexeddb-to-sqlite-v1';
@@ -83,7 +85,9 @@ export function resolvePlaylistParser(parserModule: PlaylistParserModule) {
providedIn: 'root',
})
export class PlaylistsService {
private readonly healthEvidence = inject(SourceHealthEvidenceService, { optional: true });
private readonly healthEvidence = inject(SourceHealthEvidenceService, {
optional: true,
});
private readonly dbService = inject(NgxIndexedDBService);
private readonly databaseService = inject(DatabaseService);
private readonly snackBar = inject(MatSnackBar);
@@ -100,6 +104,10 @@ export class PlaylistsService {
private startupMetas?: Promise<Playlist[]> | null;
private indexedDbMigrationPromise: Promise<void> | null = null;
private readonly playlistWriteQueues = new Map<string, Promise<unknown>>();
/** "Remove all" in progress: every playlist write waits for it. */
private deletingAll: Promise<void> = Promise.resolve();
/** Delete All runs in progress (see serializePlaylistWrite). */
private resets = 0;
/** Electron bridge or server store; `null` means IndexedDB. */
private get documentStore(): PlaylistDocumentStore | null {
@@ -128,14 +136,18 @@ export class PlaylistsService {
}
private async ensureElectronPlaylistMigrations(): Promise<void> {
if (!this.usesElectronStorage) {
if (!this.usesDocumentStore) {
return;
}
if (!this.electronMigrationPromise) {
this.electronMigrationPromise = (async () => {
await this.migrateIndexedDbPlaylistsToSqlite();
await this.documentStore?.dbRecoverLegacyPlaylists?.();
if (this.usesElectronStorage) {
await this.migrateIndexedDbPlaylistsToSqlite();
await this.documentStore?.dbRecoverLegacyPlaylists?.();
}
// Server rows too, once per server: a desktop database
// copied to the server can predate this migration.
await this.migrateStalkerPlaylistMetadataInSqlite();
})().catch((error) => {
this.electronMigrationPromise = null;
@@ -241,19 +253,7 @@ export class PlaylistsService {
}
private withExplicitLegacyStalkerPortalFlag(playlist: Playlist): Playlist {
if (
!playlist?.macAddress ||
playlist.isFullStalkerPortal !== undefined
) {
return playlist;
}
const portalUrl = playlist.portalUrl ?? playlist.url ?? '';
return {
...playlist,
isFullStalkerPortal: isFullStalkerPortalUrl(portalUrl),
};
return withExplicitStalkerPortalFlag(playlist);
}
private collectStalkerMetadataMigrationUpdates(
@@ -307,7 +307,20 @@ export class PlaylistsService {
const updates =
this.collectStalkerMetadataMigrationUpdates(storedPlaylists);
if (updates.length > 0) {
if (this.storageBackend.kind() === 'server') {
// Shared with other devices: each row is read again and
// written on that version, never over a newer copy. A
// conflict leaves the flag unset, so the next start retries.
for (const { _id } of updates) {
const fresh = await store.dbGetAppPlaylist(_id);
const [update] = fresh
? this.collectStalkerMetadataMigrationUpdates([fresh])
: [];
if (update) {
await store.dbUpsertAppPlaylist(update);
}
}
} else if (updates.length > 0) {
await store.dbUpsertAppPlaylists(updates);
}
@@ -384,7 +397,10 @@ export class PlaylistsService {
} else {
await store.dbUpsertAppPlaylist(playlist, operationId);
}
this.healthEvidence?.connections.next({ id: playlist._id, playlist });
this.healthEvidence?.connections.next({
id: playlist._id,
playlist,
});
return playlist;
});
}
@@ -398,7 +414,12 @@ export class PlaylistsService {
this.startupMetas = null;
await store.dbUpsertAppPlaylists(playlists);
playlists.forEach((playlist) => this.healthEvidence?.connections.next({ id: playlist._id, playlist }));
playlists.forEach((playlist) =>
this.healthEvidence?.connections.next({
id: playlist._id,
playlist,
})
);
return playlists;
});
}
@@ -411,9 +432,21 @@ export class PlaylistsService {
operation: () => Promise<T>
): Observable<T> {
return defer(() => {
const previous =
this.playlistWriteQueues.get(playlistId) ?? Promise.resolve();
const next = previous.then(() => operation());
// While Delete All runs, a write waits for it before it joins
// its playlist's queue, so no queue holds work blocked on the
// reset; a write under a reservation held here (a Stalker repair
// or Edit) joins at once, as the reset waits for that reservation.
if (this.resets > 0 && !holdsPlaylistAuthority(playlistId)) {
return this.deletingAll.then(() =>
firstValueFrom(
this.serializePlaylistWrite(playlistId, operation)
)
);
}
const previous = Promise.resolve(
this.playlistWriteQueues.get(playlistId)
);
const next = previous.then(() => retryOnConflict(operation));
const tail = next.then(
() => undefined,
() => undefined
@@ -572,7 +605,9 @@ export class PlaylistsService {
);
return delete$.pipe(
tap(() => this.healthEvidence?.connections.next({ id: playlistId })),
tap(() =>
this.healthEvidence?.connections.next({ id: playlistId })
),
switchMap(() => from(this.runPlaylistDeleteCleanups(playlistId))),
map((cleanupWarnings) =>
cleanupWarnings
@@ -1039,7 +1074,9 @@ export class PlaylistsService {
return nextPlaylist;
})
)
).pipe(map((rows) => rows.filter((row): row is Playlist => row !== null)));
).pipe(
map((rows) => rows.filter((row): row is Playlist => row !== null))
);
}
getFavoriteChannels(playlistId: string) {
@@ -1318,23 +1355,37 @@ export class PlaylistsService {
}
removeAll(): Observable<void> {
return defer(() =>
runWithPlaylistAuthorityReset(async () => {
if (this.usesDocumentStore) {
await this.ensureElectronPlaylistMigrations();
const store = this.documentStore;
if (store) {
this.startupMetas = null;
await store.dbDeleteAllPlaylists();
this.healthEvidence?.connections.next({});
}
return undefined;
}
// Writes queued so far land first, outside the reset (some take the
// shared side of its lock); new ones wait for the delete before they
// queue, except those under a reservation held here.
return defer(() => {
const pending = [...this.playlistWriteQueues.values()];
this.resets += 1;
const run = Promise.all(pending)
.then(() =>
runWithPlaylistAuthorityReset(() => this.deleteAllRows())
)
.finally(() => (this.resets -= 1));
this.deletingAll = run.then(
() => undefined,
() => undefined
);
return run;
});
}
await firstValueFrom(this.dbService.clear(DbStores.Playlists));
return undefined;
})
);
private async deleteAllRows(): Promise<void> {
if (this.usesDocumentStore) {
await this.ensureElectronPlaylistMigrations();
const store = this.documentStore;
if (store) {
this.startupMetas = null;
await store.dbDeleteAllPlaylists();
this.healthEvidence?.connections.next({});
}
return;
}
await firstValueFrom(this.dbService.clear(DbStores.Playlists));
}
private normalizePortalRecentIdentity(value: unknown): string {
@@ -1553,3 +1604,19 @@ export class PlaylistsService {
return this.clearPlaylistRecentlyViewed(playlistId);
}
}
/**
* A mutation the server refused as built on an older version (another device
* wrote since) runs again: it reads the playlist afresh first.
*/
async function retryOnConflict<T>(operation: () => Promise<T>): Promise<T> {
for (let attempt = 1; ; attempt += 1) {
try {
return await operation();
} catch (error) {
if (!(error instanceof PlaylistWriteConflict) || attempt >= 3) {
throw error;
}
}
}
}
@@ -31,6 +31,22 @@ const CONTENT_TYPES: readonly unknown[] = ['live', 'movie', 'series'];
export class PwaXtreamBackupStateService {
private readonly storage = inject(USER_DATA_STORAGE);
/**
* Before an export or a restore: in server mode the maps show the
* server's data only after the first read, which may still run or have
* failed at start. An export would write unread lists as empty, and a
* restore's replacement lists would merge into the server's instead.
*/
async ready(): Promise<void> {
// Read again: another device may have changed them since this
// page's first read, and a restore must replace the current lists.
if ((await this.storage.ready?.(true)) === false) {
throw new Error(
"The server's user data could not be read yet; try again once the server answers."
);
}
}
/**
* The entry with the playlist's stored lists and snapshots filled in;
* hidden categories and pins, which the browser build does not track,
@@ -103,13 +119,28 @@ export class PwaXtreamBackupStateService {
state: XtreamPendingRestoreState,
entry: XtreamPlaylistBackupEntry
): Promise<void> {
await this.ready();
// A user-supplied file: the field may be anything.
const archived: unknown = entry.userState.collectionItems;
const snapshots = snapshotsByKey(
Array.isArray(archived) ? archived : []
);
// The lists replace what the server has now: this page's own unsent
// writes for the playlist would join them, so they go first or the
// restore waits (titles merged regardless, as below).
if ((await this.storage.flushed?.(playlistId)) === false) {
try {
this.mergeSnapshots(playlistId, snapshots);
} catch {
// The unsent writes are the failure to report.
}
throw new Error(
'Earlier changes to this playlist are not on the server yet; the restore waits.'
);
}
let written: Map<UserDataMap, unknown[]>;
try {
this.replaceLists(playlistId, state);
written = this.replaceLists(playlistId, state);
} catch (error) {
if (!isQuotaExceeded(error)) {
try {
@@ -120,17 +151,46 @@ export class PwaXtreamBackupStateService {
}
throw error;
}
// Server mode: the lists count once the server took them; a refused
// one keeps the restore parked (titles merged regardless, as above).
const saved = (await this.storage.flushed?.(playlistId)) !== false;
// A conflict merges an edit another device made meanwhile into the
// lists: the backup replaces them, so it waits and runs again on a
// fresh read.
const replaced =
saved &&
[...written].every(
([name, list]) =>
JSON.stringify(this.listFor(name, playlistId)) ===
JSON.stringify(list)
);
this.mergeSnapshots(playlistId, snapshots);
if (!saved) {
throw new Error(
'The server did not take the restored lists; the restore waits.'
);
}
if (!replaced) {
throw new Error(
'The lists changed elsewhere during the restore; it runs again.'
);
}
}
/** The lists it wrote, by map. */
private replaceLists(
playlistId: string,
state: XtreamPendingRestoreState
): void {
): Map<UserDataMap, unknown[]> {
const written = new Map<UserDataMap, unknown[]>();
const write = (name: UserDataMap, list: unknown[]) => {
this.writeFor(name, playlistId, list);
written.set(name, list);
};
const favorites = state.favorites
.map((item) => typedKey(item.contentType, item.xtreamId))
.filter((key): key is string => key !== null);
this.writeFor('favorites', playlistId, [...new Set(favorites)]);
write('favorites', [...new Set(favorites)]);
const recent: StoredMap[] = [];
for (const item of state.recentlyViewed) {
@@ -143,18 +203,18 @@ export class PwaXtreamBackupStateService {
});
}
}
this.writeFor('recentItems', playlistId, recent);
write('recentItems', recent);
const now = new Date().toISOString();
this.writeFor(
write(
'playbackPositions',
playlistId,
state.playbackPositions.filter(isPlaybackPosition).map((item) => ({
...item,
playlistId,
updatedAt: item.updatedAt ?? now,
}))
);
return written;
}
/**
@@ -0,0 +1,54 @@
import {
clearServerAccessToken,
readServerAccessToken,
SERVER_ACCESS_TOKEN_OWNER_KEY,
SERVER_ACCESS_TOKEN_STORAGE_KEY,
writeServerAccessToken,
} from './server-access-token';
describe('server access token', () => {
afterEach(() => localStorage.clear());
it('has no token until one is stored', () => {
expect(readServerAccessToken()).toBeNull();
expect(readServerAccessToken('i-1')).toBeNull();
});
it('stores a trimmed token for the instance it was given for', () => {
writeServerAccessToken(' s3cret ', 'i-1');
expect(localStorage.getItem(SERVER_ACCESS_TOKEN_STORAGE_KEY)).toBe(
's3cret'
);
expect(readServerAccessToken('i-1')).toBe('s3cret');
expect(readServerAccessToken()).toBe('s3cret');
clearServerAccessToken();
expect(readServerAccessToken()).toBeNull();
expect(localStorage.getItem(SERVER_ACCESS_TOKEN_OWNER_KEY)).toBeNull();
});
it("never hands another instance's token out", () => {
writeServerAccessToken('new-server', 'i-2');
expect(readServerAccessToken('i-1')).toBeNull();
// A token stored without its instance belongs to none.
localStorage.removeItem(SERVER_ACCESS_TOKEN_OWNER_KEY);
expect(readServerAccessToken('i-2')).toBeNull();
});
it('reports a token browser storage refuses', () => {
const refuse = jest
.spyOn(Storage.prototype, 'setItem')
.mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError');
});
try {
expect(writeServerAccessToken('s3cret', 'i-1')).toBe(false);
expect(readServerAccessToken()).toBeNull();
} finally {
refuse.mockRestore();
}
expect(writeServerAccessToken('s3cret', 'i-1')).toBe(true);
});
});
@@ -0,0 +1,103 @@
import { SERVER_ACCESS_CHALLENGE } from '@iptvnator/shared/interfaces';
export const SERVER_ACCESS_TOKEN_STORAGE_KEY = 'iptvnator-server:access-token';
/**
* A gateway's answer for a backend that is down (nginx's 502/503/504 page),
* not the backend's own JSON error for a provider that failed.
*/
export function isGatewayOutage(
status: number,
contentType: string | null | undefined
): boolean {
return (
[502, 503, 504].includes(status) &&
!contentType?.includes('application/json')
);
}
/** A 401 from the backend's access guard, not one a provider sent. */
export function isServerAccessChallenge(
status: number,
challenge: string | null
): boolean {
return status === 401 && challenge === SERVER_ACCESS_CHALLENGE;
}
/** The instance the stored token was given for. */
export const SERVER_ACCESS_TOKEN_OWNER_KEY =
'iptvnator-server:access-token-instance';
/**
* The stored token; with `instanceId`, only when it was given for that
* instance: a tab still open on another server (a changed backend URL)
* never sends it there.
*/
export function readServerAccessToken(
instanceId?: string | null
): string | null {
try {
const token = localStorage
.getItem(SERVER_ACCESS_TOKEN_STORAGE_KEY)
?.trim();
return token &&
(instanceId === undefined ||
localStorage.getItem(SERVER_ACCESS_TOKEN_OWNER_KEY) ===
(instanceId ?? ''))
? token
: null;
} catch {
return null;
}
}
/** False when browser storage refused it (private mode, full). */
export function writeServerAccessToken(
token: string,
instanceId: string | null
): boolean {
try {
// The owner goes last: a token stored without one is sent nowhere.
localStorage.removeItem(SERVER_ACCESS_TOKEN_OWNER_KEY);
localStorage.setItem(SERVER_ACCESS_TOKEN_STORAGE_KEY, token.trim());
localStorage.setItem(SERVER_ACCESS_TOKEN_OWNER_KEY, instanceId ?? '');
return true;
} catch {
return false;
}
}
export function clearServerAccessToken(): void {
try {
localStorage.removeItem(SERVER_ACCESS_TOKEN_STORAGE_KEY);
localStorage.removeItem(SERVER_ACCESS_TOKEN_OWNER_KEY);
} catch {
// Nothing stored.
}
}
/**
* Whether `url` goes to the backend: the same origin as the backend URL and
* a path inside it. A plain prefix check fails for `BACKEND_URL=/`, where
* every URL, other origins included, would carry the token.
*/
export function isBackendUrl(
url: string,
baseUrl: string,
pageUrl = globalThis.location?.href ?? 'http://localhost/'
): boolean {
try {
const base = new URL(baseUrl, pageUrl);
const target = new URL(url, pageUrl);
const root = base.pathname.endsWith('/')
? base.pathname
: `${base.pathname}/`;
return (
target.origin === base.origin &&
(target.pathname === base.pathname ||
target.pathname.startsWith(root))
);
} catch {
return false;
}
}
@@ -0,0 +1,26 @@
/**
* A page started from memory reloads once the server answers
* (`ServerStorageSession`), but a server slower than the start probe would
* time it out again and reload forever: the reloaded page's probe waits as
* long as requests do, once.
*/
const SLOW_START_KEY = 'iptvnator-server:slow-start';
export function markSlowStart(): void {
try {
sessionStorage.setItem(SLOW_START_KEY, '1');
} catch {
// Without session storage the next probe keeps its short wait.
}
}
/** Whether this page load follows such a reload; asks only once. */
export function takeSlowStart(): boolean {
try {
const slow = sessionStorage.getItem(SLOW_START_KEY) !== null;
sessionStorage.removeItem(SLOW_START_KEY);
return slow;
} catch {
return false;
}
}
@@ -0,0 +1,106 @@
import { TestBed } from '@angular/core/testing';
import type { ServerInstanceInfo } from '@iptvnator/shared/interfaces';
import {
readServerAccessToken,
SERVER_ACCESS_TOKEN_STORAGE_KEY,
writeServerAccessToken,
} from './server-access-token';
import { ServerStorageStatusService } from './server-storage-status.service';
const instance: ServerInstanceInfo = {
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i-1',
storage: 'server',
auth: 'none',
};
describe('ServerStorageStatusService', () => {
let status: ServerStorageStatusService;
beforeEach(() => {
status = TestBed.inject(ServerStorageStatusService);
});
it('stays inactive and ignores reports until activated', () => {
status.reportOffline();
status.reportUnauthorized();
expect(status.state()).toBe('inactive');
expect(status.isActive()).toBe(false);
});
it('tracks online, offline and unauthorized after activation', () => {
const retry = jest.fn();
status.activate(instance, retry);
expect(status.state()).toBe('online');
expect(status.instance()).toEqual(instance);
status.reportOffline();
expect(status.state()).toBe('offline');
status.retry();
expect(retry).toHaveBeenCalledTimes(1);
status.reportSuccess();
expect(status.state()).toBe('online');
expect(status.lastSuccessAt()).toBeInstanceOf(Date);
status.reportUnauthorized();
expect(status.state()).toBe('unauthorized');
// Late answers to requests sent with the old token.
status.reportSuccess();
status.reportOffline();
expect(status.state()).toBe('unauthorized');
});
it('ignores a refusal of a token replaced since', () => {
status.activate(instance, jest.fn());
writeServerAccessToken('new', 'i-1');
status.reportAccessDenied('old');
expect(status.state()).toBe('online');
expect(localStorage.getItem(SERVER_ACCESS_TOKEN_STORAGE_KEY)).toBe(
'new'
);
status.reportAccessDenied('new');
expect(status.state()).toBe('unauthorized');
expect(
localStorage.getItem(SERVER_ACCESS_TOKEN_STORAGE_KEY)
).toBeNull();
});
it("sends no other instance's token and asks for this one's", () => {
status.activate(instance, jest.fn());
// Another tab signed in to the server a new backend URL leads to.
writeServerAccessToken('new-server', 'i-2');
expect(status.accessToken()).toBeNull();
status.reportAccessDenied(null);
expect(status.state()).toBe('unauthorized');
expect(readServerAccessToken('i-2')).toBe('new-server');
});
it('keeps the token of a page that holds it back on a refusal', () => {
status.activate(instance, jest.fn(), false);
writeServerAccessToken('kept', 'i-1');
expect(status.accessToken()).toBeNull();
status.reportAccessDenied(null);
expect(status.state()).toBe('online');
expect(readServerAccessToken('i-1')).toBe('kept');
});
it('checks the instance again after an outage on the sign-in page', () => {
status.activate(instance, jest.fn());
status.reportUnauthorized();
status.reportOffline();
expect(status.state()).toBe('unauthorized');
expect(status.isVerified()).toBe(false);
});
});
@@ -0,0 +1,124 @@
import { computed, Injectable, signal } from '@angular/core';
import type { ServerInstanceInfo } from '@iptvnator/shared/interfaces';
import {
clearServerAccessToken,
readServerAccessToken,
} from './server-access-token';
export type ServerConnectionState =
'inactive' | 'online' | 'offline' | 'unauthorized';
/** Where server mode asks for the access token. */
export const SERVER_SIGN_IN_PATH = '/server-sign-in';
/**
* Connection state of the self-hosted server storage. `inactive` in Electron
* and in a PWA without server storage; the server session activates it.
*/
@Injectable({ providedIn: 'root' })
export class ServerStorageStatusService {
private readonly stateSignal = signal<ServerConnectionState>('inactive');
private readonly instanceSignal = signal<ServerInstanceInfo | null>(null);
private readonly lastSuccessSignal = signal<Date | null>(null);
private retryHandler: (() => void) | null = null;
private verified = true;
readonly state = this.stateSignal.asReadonly();
readonly instance = this.instanceSignal.asReadonly();
readonly lastSuccessAt = this.lastSuccessSignal.asReadonly();
readonly isActive = computed(() => this.stateSignal() !== 'inactive');
/**
* `verified` is false for a start from a remembered instance that did
* not answer: the address may lead to another server by now. So it is
* after going offline, until the instance is checked again.
*/
activate(
instance: ServerInstanceInfo,
retry: () => void,
verified = true
): void {
this.instanceSignal.set(instance);
this.retryHandler = retry;
this.verified = verified;
this.stateSignal.set('online');
}
/** The instance at the address turned out to be the remembered one. */
markVerified(): void {
this.verified = true;
}
/** Whether the token and writes may go out (see `activate`). */
isVerified(): boolean {
return this.verified;
}
/**
* The stored token, only while server mode runs on an instance this
* start verified: a token must never reach a server it was not given
* for.
*/
accessToken(): string | null {
const instance = this.instanceSignal();
return instance && this.isActive() && this.verified
? readServerAccessToken(instance.instanceId)
: null;
}
reportSuccess(): void {
// A late answer to a request sent with the old token must not undo
// sign-out; only a reload after a new token leaves this state.
if (!this.isActive() || this.stateSignal() === 'unauthorized') {
return;
}
this.stateSignal.set('online');
this.lastSuccessSignal.set(new Date());
}
reportOffline(): void {
if (!this.isActive()) {
return;
}
// It may come back as another database (a replaced volume at the
// same address): no token, no writes until it is checked, also
// from the sign-in page.
this.verified = false;
// A late failure after sign-out must not unlock the workspace.
if (this.stateSignal() !== 'unauthorized') {
this.stateSignal.set('offline');
}
}
reportUnauthorized(): void {
if (this.isActive()) {
this.stateSignal.set('unauthorized');
}
}
/**
* The access guard refused a request sent with `sentToken`: the token
* stored for this instance is stale or missing, ask for a new one.
*/
reportAccessDenied(sentToken: string | null): void {
const instance = this.instanceSignal();
// A late answer to a token replaced since (a new sign-in) is moot,
// and so is one to a page that held its token back until the
// instance is checked.
if (
!instance ||
!this.isActive() ||
readServerAccessToken(instance.instanceId) !== sentToken
) {
return;
}
if (sentToken) {
clearServerAccessToken();
}
this.stateSignal.set('unauthorized');
}
retry(): void {
this.retryHandler?.();
}
}
@@ -0,0 +1,7 @@
export * from './server-storage.config';
export * from './server-api-client';
export * from './server-playlist-document-store';
export * from './server-user-data-storage';
export * from './server-access-token.interceptor';
export * from './server-storage-session';
export * from './server-migration.service';
@@ -0,0 +1,190 @@
import {
HTTP_INTERCEPTORS,
HttpClient,
provideHttpClient,
withInterceptorsFromDi,
} from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import {
SERVER_ACCESS_TOKEN_STORAGE_KEY,
writeServerAccessToken,
} from '../server-access-token';
import { ServerStorageStatusService } from '../server-storage-status.service';
import {
isBackendUrl,
ServerAccessTokenInterceptor,
} from './server-access-token.interceptor';
import { SERVER_STORAGE_CONFIG } from './server-storage.config';
describe('ServerAccessTokenInterceptor', () => {
beforeEach(() => {
writeServerAccessToken('t', 'i');
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
{
provide: HTTP_INTERCEPTORS,
useClass: ServerAccessTokenInterceptor,
multi: true,
},
{
provide: SERVER_STORAGE_CONFIG,
useValue: { baseUrl: '/api', instance: {} },
},
],
});
});
afterEach(() => localStorage.clear());
const activate = (verified = true) =>
TestBed.inject(ServerStorageStatusService).activate(
{
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i',
storage: 'server',
auth: 'token',
},
() => undefined,
verified
);
it('adds the token to backend calls only', () => {
activate();
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
http.get('/api/parse').subscribe();
http.get('https://provider.example/list.m3u').subscribe();
expect(
controller
.expectOne('/api/parse')
.request.headers.get('Authorization')
).toBe('Bearer t');
expect(
controller
.expectOne('https://provider.example/list.m3u')
.request.headers.has('Authorization')
).toBe(false);
});
it('withholds the token from an instance not checked yet', () => {
activate(false);
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
http.get('/api/v1/instance').subscribe();
expect(
controller
.expectOne('/api/v1/instance')
.request.headers.has('Authorization')
).toBe(false);
controller.verify();
});
it('asks for a new token when the backend refuses the stored one', () => {
const status = TestBed.inject(ServerStorageStatusService);
status.activate(
{
service: 'iptvnator',
apiVersion: 1,
instanceId: 'i',
storage: 'server',
auth: 'token',
},
() => undefined
);
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
// A provider's own 401 passed on by the proxy changes nothing.
http.get('/api/xtream').subscribe({ error: () => undefined });
controller
.expectOne('/api/xtream')
.flush({ message: 'bad login' }, { status: 401, statusText: 'x' });
expect(status.state()).toBe('online');
http.get('/api/xtream').subscribe({ error: () => undefined });
controller.expectOne('/api/xtream').flush(
{ code: 'unauthorized' },
{
status: 401,
statusText: 'Unauthorized',
headers: { 'WWW-Authenticate': 'Bearer realm="iptvnator"' },
}
);
expect(status.state()).toBe('unauthorized');
expect(
localStorage.getItem(SERVER_ACCESS_TOKEN_STORAGE_KEY)
).toBeNull();
});
it('reports a backend that does not answer as offline, not a provider failing', () => {
const status = TestBed.inject(ServerStorageStatusService);
activate();
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
// The backend's own JSON error for a provider that failed.
http.get('/api/xtream').subscribe({ error: () => undefined });
controller.expectOne('/api/xtream').flush(
{ message: 'provider down' },
{
status: 502,
statusText: 'Bad Gateway',
headers: { 'Content-Type': 'application/json' },
}
);
expect(status.state()).toBe('online');
expect(status.isVerified()).toBe(true);
// No answer at all: it may come back as another instance.
http.get('/api/parse').subscribe({ error: () => undefined });
controller
.expectOne('/api/parse')
.error(new ProgressEvent('error'), { status: 0 });
expect(status.state()).toBe('offline');
expect(status.accessToken()).toBeNull();
});
});
describe('isBackendUrl', () => {
const page = 'http://nas.local:4333/workspace';
it('matches the backend path and nothing else', () => {
expect(isBackendUrl('/api/xtream', '/api', page)).toBe(true);
expect(isBackendUrl('/api', '/api', page)).toBe(true);
expect(isBackendUrl('/apiary', '/api', page)).toBe(false);
expect(isBackendUrl('https://other.test/api/x', '/api', page)).toBe(
false
);
});
it('keeps other origins out for a root deployment', () => {
expect(isBackendUrl('/v1/playlists', '/', page)).toBe(true);
expect(
isBackendUrl('https://api.github.com/repos/x/releases', '/', page)
).toBe(false);
});
it('handles an absolute backend URL', () => {
expect(
isBackendUrl(
'http://nas.local:3000/parse',
'http://nas.local:3000',
page
)
).toBe(true);
expect(isBackendUrl('/parse', 'http://nas.local:3000', page)).toBe(
false
);
});
});
@@ -0,0 +1,74 @@
import {
HttpErrorResponse,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Observable, tap } from 'rxjs';
import {
isBackendUrl,
isGatewayOutage,
isServerAccessChallenge,
} from '../server-access-token';
// Lives with the token helpers so the startup bundle can check URLs
// without loading the server storage code.
export { isBackendUrl } from '../server-access-token';
import { ServerStorageStatusService } from '../server-storage-status.service';
import { SERVER_STORAGE_CONFIG } from './server-storage.config';
/**
* Adds the server access token to `HttpClient` calls to the backend, sends
* the user to sign-in when the backend refuses it (a token changed on the
* server while this page was open), and reports a backend that does not
* answer as offline, like the storage API client does.
*/
@Injectable()
export class ServerAccessTokenInterceptor implements HttpInterceptor {
private readonly status = inject(ServerStorageStatusService);
private readonly baseUrl = inject(SERVER_STORAGE_CONFIG).baseUrl;
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
if (!isBackendUrl(request.url, this.baseUrl)) {
return next.handle(request);
}
const token = this.status.accessToken();
const sent = token
? request.clone({
setHeaders: { Authorization: `Bearer ${token}` },
})
: request;
return next.handle(sent).pipe(
tap({
error: (error: unknown) => {
if (!(error instanceof HttpErrorResponse)) {
return;
}
if (
error.status === 0 ||
isGatewayOutage(
error.status,
error.headers.get('Content-Type')
)
) {
// No answer: it may come back as another instance,
// checked before the token goes out again.
this.status.reportOffline();
} else if (
isServerAccessChallenge(
error.status,
error.headers.get('WWW-Authenticate')
)
) {
this.status.reportAccessDenied(token);
}
},
})
);
}
}
@@ -0,0 +1,273 @@
import { ServerApiClient, ServerApiError } from './server-api-client';
// jsdom has Headers but no Response or fetch.
function response(status: number, body?: unknown) {
return {
status,
ok: status >= 200 && status < 300,
statusText: '',
headers: new Headers(),
json: async () => body,
} as unknown as Response;
}
describe('ServerApiClient', () => {
const status = {
reportSuccess: jest.fn(),
reportOffline: jest.fn(),
reportAccessDenied: jest.fn(),
};
let token: string | null = null;
const onWriteFailure = jest.fn();
afterEach(() => {
jest.clearAllMocks();
token = null;
});
function client(fetchFn: jest.Mock) {
return new ServerApiClient({
baseUrl: '/api/',
status,
onWriteFailure,
fetchFn: fetchFn as unknown as typeof fetch,
accessToken: () => token,
});
}
it('calls /v1 with the token and reports success', async () => {
token = 't';
const fetchFn = jest
.fn()
.mockResolvedValue(response(200, { ok: true }));
await expect(client(fetchFn).getJson('/instance')).resolves.toEqual({
ok: true,
});
const [url, init] = fetchFn.mock.calls[0];
expect(url).toBe('/api/v1/instance');
expect(init.headers).toMatchObject({ Authorization: 'Bearer t' });
expect(status.reportSuccess).toHaveBeenCalled();
});
it('reports offline on a network error and announces failed writes', async () => {
const fetchFn = jest
.fn()
.mockRejectedValue(new TypeError('Failed to fetch'));
await expect(
client(fetchFn).sendJson('PUT', '/playlists/a', {})
).rejects.toMatchObject({ status: 0, code: 'network' });
expect(status.reportOffline).toHaveBeenCalled();
expect(onWriteFailure).toHaveBeenCalledTimes(1);
});
it('reports offline when a proxy answers for a down backend', async () => {
for (const code of [502, 503, 504]) {
const fetchFn = jest
.fn()
.mockResolvedValue(response(code, 'Bad Gateway'));
await expect(
client(fetchFn).getJson('/user-state')
).rejects.toMatchObject({ status: code });
}
expect(status.reportOffline).toHaveBeenCalledTimes(3);
// A backend error is not an outage.
status.reportOffline.mockClear();
await expect(
client(
jest.fn().mockResolvedValue(response(500, { code: 'x' }))
).getJson('/user-state')
).rejects.toMatchObject({ status: 500 });
expect(status.reportOffline).not.toHaveBeenCalled();
});
it('gives up on a keepalive write the server never answers', async () => {
const hanging = jest.fn(
(_url: string, init: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init.signal?.addEventListener('abort', () =>
reject(new DOMException('Timed out', 'TimeoutError'))
);
})
);
const slow = new ServerApiClient({
baseUrl: '/api',
status,
fetchFn: hanging as unknown as typeof fetch,
accessToken: () => null,
timeoutMs: 10,
});
// Later writes queue behind it: it must end, as a failed one.
await expect(
slow.sendKeepalive('PUT', '/user-state/a/b', { value: 1 })
).resolves.toEqual({ status: 'failed' });
// An outage: the instance is checked before the next write.
expect(status.reportOffline).toHaveBeenCalledTimes(1);
});
it('reports a keepalive answer cut off after its headers as offline', async () => {
const cutOff = jest.fn().mockResolvedValue({
...response(200),
json: async () => {
throw new TypeError('body cut off');
},
});
// Saved, on a version it cannot tell (see the write queue).
await expect(
client(cutOff).sendKeepalive('PUT', '/user-state/a/b', {
value: 1,
})
).resolves.toEqual({ status: 'saved', tag: undefined });
expect(status.reportOffline).toHaveBeenCalled();
});
it('reports a keepalive write refused by the access guard', async () => {
token = 'old';
const refused = jest.fn().mockResolvedValue(response(401));
await expect(
client(refused).sendKeepalive('PUT', '/user-state/a/b', {
value: 1,
})
).resolves.toEqual({ status: 'failed' });
// With the token it sent: one replaced since is not refused.
expect(status.reportAccessDenied).toHaveBeenCalledWith('old');
});
it('reports a gateway answering for a down backend on a keepalive write', async () => {
const down = jest.fn().mockResolvedValue(response(502));
await expect(
client(down).sendKeepalive('PUT', '/user-state/a/b', { value: 1 })
).resolves.toEqual({ status: 'failed' });
expect(status.reportOffline).toHaveBeenCalled();
});
it('reports how a keepalive write ended', async () => {
const ok = jest.fn().mockResolvedValue(response(200, { tag: 't2' }));
await expect(
client(ok).sendKeepalive('PUT', '/user-state/a/b', { value: 1 })
).resolves.toEqual({ status: 'saved', tag: 't2' });
expect(ok.mock.calls[0][1]).toMatchObject({ keepalive: true });
const conflict = jest.fn().mockResolvedValue(
response(412, {
code: 'conflict',
message: 'changed',
current: { value: [2], tag: 't3' },
})
);
await expect(
client(conflict).sendKeepalive('PUT', '/user-state/a/b', {
value: 1,
})
).resolves.toEqual({
status: 'conflict',
current: { value: [2], tag: 't3' },
});
const gone = jest
.fn()
.mockResolvedValue(
response(404, { code: 'playlist_missing', message: 'gone' })
);
await expect(
client(gone).sendKeepalive('PUT', '/user-state/a/b', { value: 1 })
).resolves.toEqual({ status: 'gone' });
const refused = jest
.fn()
.mockRejectedValue(new TypeError('body too large'));
await expect(
client(refused).sendKeepalive('DELETE', '/user-state/a/b')
).resolves.toEqual({ status: 'failed' });
});
it('holds writes, not reads, until the instance is checked', async () => {
const fetchFn = jest.fn().mockResolvedValue(response(200, {}));
const held = new ServerApiClient({
baseUrl: '/api',
status,
fetchFn: fetchFn as unknown as typeof fetch,
accessToken: () => null,
holdWrites: () => true,
});
await expect(
held.sendJson('PUT', '/user-state/a/b', { value: 1 })
).rejects.toMatchObject({ status: 0, code: 'network' });
await expect(
held.sendKeepalive('DELETE', '/user-state/a/b')
).resolves.toEqual({ status: 'failed' });
await held.getJson('/instance');
expect(fetchFn).toHaveBeenCalledTimes(1);
expect(fetchFn.mock.calls[0][0]).toBe('/api/v1/instance');
});
it('reports offline when a body is cut off after the headers', async () => {
const cut = {
...response(200),
json: async () => {
throw new TypeError('network error');
},
} as unknown as Response;
await expect(
client(jest.fn().mockResolvedValue(cut)).getJson('/user-state')
).rejects.toMatchObject({ status: 0, code: 'network' });
expect(status.reportOffline).toHaveBeenCalled();
// Malformed JSON is an answer, not an outage.
status.reportOffline.mockClear();
const malformed = {
...response(200),
json: async () => {
throw new SyntaxError('Unexpected token');
},
} as unknown as Response;
await expect(
client(jest.fn().mockResolvedValue(malformed)).getJson('/x')
).rejects.toBeInstanceOf(SyntaxError);
expect(status.reportOffline).not.toHaveBeenCalled();
});
it('reports the refused token on 401', async () => {
token = 'old';
const fetchFn = jest
.fn()
.mockResolvedValue(response(401, { code: 'unauthorized' }));
await expect(
client(fetchFn).getJson('/playlists')
).rejects.toBeInstanceOf(ServerApiError);
// The status decides: it ignores a token replaced since.
expect(status.reportAccessDenied).toHaveBeenCalledWith('old');
expect(status.reportOffline).not.toHaveBeenCalled();
});
it('passes 304 through and maps error bodies', async () => {
const fetchFn = jest
.fn()
.mockResolvedValueOnce(response(304))
.mockResolvedValueOnce(
response(409, { message: 'x', code: 'payload_missing' })
);
const api = client(fetchFn);
expect((await api.request('/playlists/a')).status).toBe(304);
await expect(
api.sendJson('PUT', '/playlists/a', {})
).rejects.toMatchObject({
status: 409,
code: 'payload_missing',
});
expect(onWriteFailure).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,266 @@
import type {
ServerStorageErrorBody,
ServerUserStateCurrent,
ServerUserStateWriteResponse,
} from '@iptvnator/shared/interfaces';
import type { ServerStorageStatusService } from '../server-storage-status.service';
const REQUEST_TIMEOUT_MS = 20_000;
/** A user-state write for a playlist the server no longer has. */
export const PLAYLIST_MISSING = 'playlist_missing';
/** nginx answers these while the backend behind it is down. */
const GATEWAY_UNAVAILABLE = new Set([502, 503, 504]);
export class ServerApiError extends Error {
constructor(
readonly status: number,
readonly code: string | undefined,
message: string,
/** A `412` conflict's user-state entry as the server has it. */
readonly current?: ServerUserStateCurrent
) {
super(message);
this.name = 'ServerApiError';
}
}
/** How a page-hide write ended, as far as the page could see. */
export type KeepaliveOutcome =
| { readonly status: 'saved'; readonly tag?: string | null }
| { readonly status: 'conflict'; readonly current: ServerUserStateCurrent }
| { readonly status: 'gone' }
| { readonly status: 'failed' };
export interface ServerApiClientOptions {
readonly baseUrl: string;
readonly status: Pick<
ServerStorageStatusService,
'reportSuccess' | 'reportOffline' | 'reportAccessDenied'
>;
/** Failed writes the user should hear about: network, 413, 5xx. */
readonly onWriteFailure?: (error: ServerApiError) => void;
readonly fetchFn?: typeof fetch;
readonly timeoutMs?: number;
/**
* Refuse writes as if offline while true: an instance not checked yet
* (a start from memory, or one that went offline), whose address may
* lead to another database by the time it answers.
*/
readonly holdWrites?: () => boolean;
/** The token to send (`ServerStorageStatusService.accessToken`). */
readonly accessToken: () => string | null;
}
/** `fetch` for `/v1`: token, timeout, error mapping, connection state. */
export class ServerApiClient {
private readonly root: string;
constructor(private readonly options: ServerApiClientOptions) {
this.root = `${options.baseUrl.replace(/\/+$/, '')}/v1`;
}
private token(): string | null {
return this.options.accessToken();
}
url(path: string): string {
return `${this.root}${path}`;
}
async request(path: string, init: RequestInit = {}): Promise<Response> {
const isWrite = (init.method ?? 'GET') !== 'GET';
const token = this.token();
let response: Response;
try {
if (isWrite && this.options.holdWrites?.()) {
throw new Error('Writes wait for the instance to answer.');
}
response = await this.fetchFn()(this.url(path), {
...init,
cache: 'no-store',
headers: {
...bearer(token),
...(init.headers as Record<string, string> | undefined),
},
signal: init.signal ?? this.timeoutSignal(),
});
} catch {
this.options.status.reportOffline();
const error = new ServerApiError(
0,
'network',
'The server is not reachable.'
);
if (isWrite) {
this.options.onWriteFailure?.(error);
}
throw error;
}
if (response.status === 401) {
this.options.status.reportAccessDenied(token);
throw new ServerApiError(
401,
'unauthorized',
'The server needs an access token.'
);
}
if (GATEWAY_UNAVAILABLE.has(response.status)) {
// A proxy in front of a backend that is down or restarting.
this.options.status.reportOffline();
}
if (!response.ok && response.status !== 304) {
const body = await readErrorBody(response);
const error = new ServerApiError(
response.status,
body.code,
body.message,
body.current
);
if (
isWrite &&
(response.status === 413 || response.status >= 500)
) {
this.options.onWriteFailure?.(error);
}
throw error;
}
this.options.status.reportSuccess();
return response;
}
async getJson<T>(path: string): Promise<T> {
return this.readJson<T>(await this.request(path));
}
/**
* A body cut off after the headers arrived is an outage too; malformed
* JSON is not.
*/
async readJson<T>(response: Response): Promise<T> {
try {
return (await response.json()) as T;
} catch (error) {
if (error instanceof SyntaxError) {
throw error;
}
this.options.status.reportOffline();
throw new ServerApiError(
0,
'network',
'The server is not reachable.'
);
}
}
sendJson(
method: 'PUT' | 'POST',
path: string,
body: unknown,
headers: Record<string, string> = {}
): Promise<Response> {
return this.request(path, {
method,
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json', ...headers },
});
}
/**
* A write that survives the page. Browsers reject keepalive bodies
* above 64 KiB, which ends as `failed`.
*/
async sendKeepalive(
method: 'PUT' | 'DELETE',
path: string,
body?: unknown,
headers: Record<string, string> = {}
): Promise<KeepaliveOutcome> {
if (this.options.holdWrites?.()) {
return { status: 'failed' };
}
const token = this.token();
try {
const response = await this.fetchFn()(this.url(path), {
method,
keepalive: true,
headers: {
...bearer(token),
...headers,
...(body === undefined
? {}
: { 'Content-Type': 'application/json' }),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
// A server that takes the request and never answers would
// hold every later write behind it.
signal: this.timeoutSignal(),
});
if (response.ok) {
const body = (await response.json().catch(() => {
// Saved, on a version it cannot tell: cut off after its
// headers, which counts as offline, as for requests.
this.options.status.reportOffline();
return {};
})) as Partial<ServerUserStateWriteResponse>;
return { status: 'saved', tag: body?.tag };
}
if (GATEWAY_UNAVAILABLE.has(response.status)) {
// As for requests: the backend may come back as another
// instance, checked before the next write goes out.
this.options.status.reportOffline();
}
if (response.status === 401) {
// As for requests: a token replaced since is not refused.
this.options.status.reportAccessDenied(token);
}
const { code, current } =
response.status === 412 || response.status === 404
? await readErrorBody(response)
: {};
if (code === PLAYLIST_MISSING) {
return { status: 'gone' };
}
return current
? { status: 'conflict', current }
: { status: 'failed' };
} catch {
this.options.status.reportOffline();
return { status: 'failed' };
}
}
private fetchFn(): typeof fetch {
return this.options.fetchFn ?? globalThis.fetch.bind(globalThis);
}
private timeoutSignal(): AbortSignal | undefined {
return typeof AbortSignal.timeout === 'function'
? AbortSignal.timeout(this.options.timeoutMs ?? REQUEST_TIMEOUT_MS)
: undefined;
}
}
async function readErrorBody(
response: Response
): Promise<Pick<ServerStorageErrorBody, 'message' | 'code' | 'current'>> {
try {
const body = (await response.json()) as Partial<ServerStorageErrorBody>;
return {
message: body.message ?? response.statusText,
code: body.code,
current: body.current,
};
} catch {
return { message: response.statusText };
}
}
function bearer(token: string | null): Record<string, string> {
return token ? { Authorization: `Bearer ${token}` } : {};
}
@@ -0,0 +1,172 @@
import {
combineUserData,
remapChannelReferences,
retargetUserData,
unionItems,
} from './server-migration-merge';
describe('combineUserData', () => {
it('unions lists, server entries first', () => {
expect(
combineUserData([
['live:1', 'live:2'],
['live:2', 'live:3'],
])
).toEqual(['live:1', 'live:2', 'live:3']);
});
it('merges maps and keeps the first value of a key', () => {
expect(
combineUserData([
{ a: { position: 10 } },
{ a: { position: 99 }, b: { position: 5 } },
])
).toEqual({ a: { position: 10 }, b: { position: 5 } });
});
it('ignores missing values and keeps the first of mixed kinds', () => {
expect(combineUserData([undefined, ['x']])).toEqual(['x']);
expect(combineUserData([undefined])).toBeUndefined();
expect(combineUserData([['x'], { a: 1 }])).toEqual(['x']);
});
});
describe('unionItems', () => {
it('identifies items by content id or URL', () => {
expect(
unionItems(
[{ id: 1, title: 'Server' }, { url: 'http://a' }],
[{ id: 1, title: 'Browser' }, { url: 'http://b' }]
)
).toEqual([
{ id: 1, title: 'Server' },
{ url: 'http://a' },
{ url: 'http://b' },
]);
});
});
describe('Stalker items', () => {
it('keep the same id in different categories apart', () => {
expect(
unionItems(
[{ id: 7, category_id: 'itv', name: 'Channel' }],
[
{ id: 7, category_id: 'vod', name: 'Movie' },
{ id: 7, category_id: 'itv', name: 'Channel again' },
]
)
).toEqual([
{ id: 7, category_id: 'itv', name: 'Channel' },
{ id: 7, category_id: 'vod', name: 'Movie' },
]);
});
it('keep a movie and a series of one provider category apart', () => {
expect(
unionItems<Record<string, unknown>>(
[{ id: 7, category_id: '12', name: 'Movie' }],
[
{ id: 7, category_id: '12', is_series: 1, name: 'Show' },
{
id: 7,
category_id: '12',
is_series: true,
name: 'Again',
},
]
)
).toEqual([
{ id: 7, category_id: '12', name: 'Movie' },
{ id: 7, category_id: '12', is_series: 1, name: 'Show' },
]);
});
});
describe('playback positions', () => {
it('keep the server position of the same item', () => {
expect(
combineUserData([
[
{
contentType: 'vod',
contentXtreamId: 7,
positionSeconds: 60,
},
],
[
{
contentType: 'vod',
contentXtreamId: 7,
positionSeconds: 900,
},
{
contentType: 'episode',
contentXtreamId: 7,
positionSeconds: 5,
},
],
])
).toEqual([
{ contentType: 'vod', contentXtreamId: 7, positionSeconds: 60 },
{ contentType: 'episode', contentXtreamId: 7, positionSeconds: 5 },
]);
});
it('name the server playlist after a move', () => {
expect(
retargetUserData(
[{ contentXtreamId: 1, playlistId: 'b' }, 'live:1'],
'b',
's'
)
).toEqual([{ contentXtreamId: 1, playlistId: 's' }, 'live:1']);
const same = [{ playlistId: 'b' }];
expect(retargetUserData(same, 'b', 'b')).toBe(same);
});
});
describe('remapChannelReferences', () => {
const browser = [
{ id: 'b1', url: 'http://s/1' },
{ id: 'b2', url: 'http://s/2' },
{ id: 'b3', url: 'http://s/gone' },
];
const server = [
{ id: 's1', url: 'http://s/1' },
{ id: 's2', url: 'http://s/2' },
];
it('turns legacy channel-id favorites into their stream URL', () => {
expect(
remapChannelReferences(['b2', 'b1', 'http://s/1'], browser, server)
).toEqual(['http://s/2', 'http://s/1', 'http://s/1']);
// The server's own legacy ids, against its own channels.
expect(remapChannelReferences(['s1'], server, server)).toEqual([
'http://s/1',
]);
});
it('keeps URL favorites and anything it cannot resolve', () => {
expect(
remapChannelReferences(
['http://elsewhere/9', 'b9', 'b3'],
browser,
server
)
).toEqual(['http://elsewhere/9', 'b9', 'http://s/gone']);
});
it("keeps a history entry's URL id and names the server's channel", () => {
const portal = { id: 7, category_id: 'itv' };
const entry = {
source: 'm3u',
id: 'http://s/1',
url: 'http://s/1',
channel_id: 'b1',
};
expect(
remapChannelReferences([entry, portal], browser, server)
).toEqual([{ ...entry, channel_id: 's1' }, portal]);
});
});
@@ -0,0 +1,177 @@
import { isStalkerSeriesFlag } from '@iptvnator/shared/interfaces';
/**
* How the move to the server combines user data that two places hold for
* one playlist: the server's value comes first and wins, the browser only
* adds. Lists are unioned, maps keep the first value of each key.
*/
export function combineUserData(values: readonly unknown[]): unknown {
const present = values.filter((value) => value !== undefined);
if (present.length === 0) {
return undefined;
}
if (present.every(Array.isArray)) {
return unionItems(...(present as unknown[][]));
}
if (present.every(isPlainObject)) {
const merged: Record<string, unknown> = {};
for (const value of present as Record<string, unknown>[]) {
for (const [key, entry] of Object.entries(value)) {
if (!(key in merged)) {
merged[key] = entry;
}
}
}
return merged;
}
return present[0];
}
/** Items in order of first appearance, without duplicates. */
export function unionItems<T>(...lists: readonly (readonly T[])[]): T[] {
const seen = new Set<string>();
const result: T[] = [];
for (const list of lists) {
for (const item of list) {
const key = itemKey(item);
if (!seen.has(key)) {
seen.add(key);
result.push(item);
}
}
}
return result;
}
/**
* Content ids or URLs identify favorites and history entries; a playback
* position is identified by its content type and Xtream id.
*/
export function itemKey(item: unknown): string {
if (!isPlainObject(item)) {
return `value:${JSON.stringify(item)}`;
}
if (
typeof item['contentType'] === 'string' &&
(typeof item['contentXtreamId'] === 'number' ||
typeof item['contentXtreamId'] === 'string')
) {
return `position:${item['contentType']}:${item['contentXtreamId']}`;
}
// Stalker ids repeat across content types; the category tells them
// apart, and the series flag where a provider category holds both.
const category = item['category_id'];
const scope =
(typeof category === 'string' || typeof category === 'number'
? `|category:${category}`
: '') + (isStalkerSeriesFlag(item['is_series']) ? '|series' : '');
for (const field of ['id', 'stream_id', 'series_id', 'movie_id', 'url']) {
const value = item[field];
if (typeof value === 'string' || typeof value === 'number') {
return `${field}:${value}${scope}`;
}
}
return `json:${JSON.stringify(item)}`;
}
interface ChannelRef {
readonly id?: unknown;
readonly url?: unknown;
}
/**
* M3U favorites and history as the app reads them, moved to the server's
* copy of a playlist. Favorites name channels by stream URL; older ones by
* a channel id that every import makes up anew, which becomes that
* channel's URL here (`ownChannels`: the playlist the favorite came from).
* History entries keep their URL id and get the server's channel id as
* `channel_id`. Anything else passes through, never dropped.
*/
export function remapChannelReferences<T>(
references: readonly T[],
ownChannels: readonly ChannelRef[],
serverChannels: readonly ChannelRef[]
): T[] {
const urlById = new Map<unknown, unknown>(
ownChannels.map((channel) => [channel.id, channel.url])
);
const idByUrl = new Map<unknown, unknown>(
serverChannels.map((channel) => [channel.url, channel.id])
);
return references.map((reference) => {
if (typeof reference === 'string') {
const url = urlById.get(reference);
return (typeof url === 'string' ? url : reference) as T;
}
if (isPlainObject(reference) && reference['source'] === 'm3u') {
const channelId = idByUrl.get(reference['url']);
return (
typeof channelId === 'string'
? { ...reference, channel_id: channelId }
: reference
) as T;
}
return reference;
});
}
/**
* A browser value moved under another playlist id: list items that name
* their playlist (playback positions do) name the server's instead.
*/
export function retargetUserData(
value: unknown,
browserId: string,
serverId: string
): unknown {
if (browserId === serverId || !Array.isArray(value)) {
return value;
}
return value.map((item) =>
isPlainObject(item) && item['playlistId'] === browserId
? { ...item, playlistId: serverId }
: item
);
}
/**
* Recently viewed items as the app keeps them: newest first, since it cuts
* the list at its limit from the end, and one per item, its newest view
* with that view's artwork. Undated items follow the dated ones in order.
*/
export function combineRecentViews(values: readonly unknown[]): unknown {
const present = values.filter((value) => value !== undefined);
if (present.length === 0 || !present.every(Array.isArray)) {
return combineUserData(values);
}
return unionItems(
newestViewsFirst(([] as unknown[]).concat(...(present as unknown[][])))
);
}
/**
* Recently viewed items newest first, by `viewedAt` (Xtream maps) or
* `added_at` (playlist documents: an ISO date or epoch milliseconds);
* stable, undated items after dated ones.
*/
export function newestViewsFirst<T>(
items: readonly T[],
field: 'viewedAt' | 'added_at' = 'viewedAt'
): T[] {
const viewedAt = (item: unknown) => {
const value = isPlainObject(item) ? item[field] : undefined;
const at =
typeof value === 'number' ? value : Date.parse(String(value));
return Number.isNaN(at) ? 0 : at;
};
return [...items].sort((a, b) => viewedAt(b) - viewedAt(a));
}
/** Whether a list holds recently viewed items, which stay newest first. */
export function isViewHistory(items: readonly unknown[]): boolean {
return items.some((item) => isPlainObject(item) && 'viewedAt' in item);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more