Commit graph

11 commits

Author SHA1 Message Date
0c439259ac Add server-side logging of the party lifecycle
All checks were successful
Publier l'image Docker / publish (push) Successful in 6s
Requested now that the app is actually running on real infrastructure:
visibility from docker logs/journalctl into what's happening (parties
created/destroyed, who joined/left, play/pause, pause requests) without
needing to reproduce a bug through the UI first.

server/src/logger.js: a deliberately tiny partyLog(message) - plain
console.log, prefixed [watchparty:party], ISO timestamp - plus a
who(userId, userName) formatter shared by every call site. No logging
library; this app runs as a single container, not behind a log
aggregator, so a consistent grep-able prefix is what actually helps here.

Covers the party's business lifecycle end to end, logged at the source so
every caller (REST and socket) is covered without repeating the check:
- partyManager.js: create, join, leave (also covers a host handoff or the
  party being destroyed, both fall out of leave), advanceQueue,
  removeIdleParties.
- socketHandler.js: playstate and requestPause, since those two mutate
  member state directly rather than through a PartyManager method.

The one thing that needed real care: the host's player re-sends its
CURRENT play/pause state every 3 seconds regardless of whether anything
changed (the heartbeat), on top of firing per actual play/pause/seeked
event. Logging every "playstate" message as it arrives would mean one log
line every 3 seconds per active party, forever. The handler instead
compares incoming isPaused against the member's previous value and only
logs on an actual flip - so a party generates exactly one line per real
pause or resume, never one per heartbeat tick.

Verified directly against the real shipped modules, not reimplemented
mocks: a scripted create/join/advanceQueue/leave/idle-sweep sequence
against the real partyManager.js produced exactly the expected line at
every step; a fake io/socket pair driving the real socketHandler.js
through start -> 5 unchanged heartbeats -> pause -> 3 unchanged
heartbeats -> resume logged exactly 3 playstate lines (not 9) at exactly
the right points, and a throttled repeat requestPause produced no second
line - all assertions passed, counted programmatically.

docs/architecture.md has the full writeup.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-14 00:53:55 +02:00
85bcf946b4 Filter sidebar to films/musique/clips vidéos/TV, fix music videos not being playable
All checks were successful
Publier l'image Docker / publish (push) Successful in 7s
server/src/index.js: GET /api/catalog/libraries now filters Emby's /Views
response to VISIBLE_COLLECTION_TYPES (movies/tvshows/music/musicvideos)
before returning it. Emby's /Views can return all sorts of things this app
has no UI for at all - boxset collections, playlists, live TV, photos,
books, a mixed-content folder with no CollectionType - none of which
should ever have shown up in the sidebar. Filtering once at the source
means every consumer (the sidebar, home.js's per-library carousels, direct
navigation to /library/:id) is restricted the same way without repeating
the check in each place; a stale link to a now-hidden library's id just
falls into library.js's existing "Bibliothèque introuvable" state, since
it looks the id up in this same filtered list.

Found while making musicvideos a real visible category: its items are
Emby's own 'MusicVideo' type (distinct from the generic 'Video'), which
WATCH_PARTY_TYPES didn't include - every tile in a music-videos library
would have rendered with no "Lancer une watch party" button at all, only
"Voir sur Emby". Added it.

Also fixed two stale doc/comment references while touching this code:
the sidebar hasn't shown per-type icons since the earlier "no emoji"
request (plain text links only), and views/home.js's party carousel has
used the live lobby Socket.IO subscription instead of a GET /api/parties
fetch since that endpoint was removed - both docs/architecture.md and an
inline comment still described the old behavior.

Verified: a plain filter/map unit test confirms exactly
movies/tvshows/music/musicvideos survive against a mock /Views response
seeded with one of every excluded type (photos/livetv/boxsets/playlists/
books/homevideos/mixed/no-type-at-all); WATCH_PARTY_TYPES.has('MusicVideo')
checked directly; and mounting shell.js + library.js against a mocked
already-filtered libraries response renders exactly the 4 expected sidebar
links and a working "Lancer une watch party" button on a MusicVideo tile.

docs/architecture.md has the full writeup.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-14 00:40:07 +02:00
669873e41c Presence overlay (avatars) + "request pause" in the player
All checks were successful
Publier l'image Docker / publish (push) Successful in 7s
Two features requested together: a semi-transparent overlay showing who's
in the party, and a way for a non-host to ask the host to pause.

- server/src/socketHandler.js: new "requestPause" event (anyone, throttled
  5s per member server-side via member.lastPauseRequestUtc - the real
  guard, independent of whatever the client does) broadcasts
  "pauseRequested" {userId, userName} to the whole party room, not just the
  host, so everyone sees why playback is about to pause.
- client/js/party.js: connectParty() grows an onPauseRequested callback and
  the returned connection a requestPause() method, same shape as the
  existing next()/sendPlaystate().
- client/js/views/player.js: renderMembers() now also rebuilds a
  #presenceOverlay of one circle per member (initials from userName,
  colorForName() picks a deterministic background from a small palette by
  hashing the name - same person, same color, no server-side assignment
  needed). "Which circle is mine" compares userName against the auth
  singleton embyApi.js already populates, matching how the rest of the
  client avoids keying UI logic on userId directly. Your own circle, only
  when you're not host, is clickable and calls requestPause() (client-side
  cooldown too, purely to avoid a click that would visibly do nothing - the
  server-side one is what actually matters). Receiving pauseRequested shows
  a short auto-clearing banner and pulses the matching circle for everyone,
  including the requester and the host.
- client/css/app.css: .presenceOverlay/.avatar (bottom-left, opacity .75 is
  the "semi transparence" itself) and the clickable/sent/pulse states,
  .pauseRequestBanner.

Verified with mocked members/pauseRequested Socket.IO events against the
real running local server (see session history): initials/colors render
correctly, the host's own circle never gets the clickable affordance,
rapid repeat clicks collapse to exactly one requestPause emission (three
synchronous clicks -> one new emitted event), a pauseRequested event
banners and pulses the right circle. Re-checked the pre-existing host path
(becomeHost, settings menu, next-episode button) still works unchanged -
this pass only touched renderMembers() and init()'s connectParty() call.

docs/architecture.md has the full writeup. Also fixed two roadmap
checkboxes in README.md that should have been checked off by the previous
commit (live lobby/host handoff/no join codes) but were missed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-14 00:05:40 +02:00
b6019bd211 Live lobby, host handoff reflected live, remove join codes, fix player scroll
All checks were successful
Publier l'image Docker / publish (push) Successful in 7s
Three requested changes plus one found-in-passing bug fix:

1. Home page's "watch parties en cours" is now a live Socket.IO
   subscription (connectLobby -> "lobby" room), not a one-shot fetch -
   updates the instant anything changes anywhere (create/join/leave).
   Host name + member count come from the snapshot; elapsed time ticks
   purely client-side from a createdUtc timestamp (no point pushing a
   recomputed duration every second for every viewer). home.js returns
   this subscription from its router cleanup, same leak-prevention
   pattern as the player's socket.

2. Host handoff is now live end to end, not just correct in the data
   model. PartyManager.leave already promoted another member and
   destroyed an empty party (that part predates this change) - what
   was missing was any way for an already-open follower player to find
   out it became host. applyLeave (shared by the socket leave/
   disconnect handlers and the REST leave endpoint, so this and the
   lobby broadcast only live in one place) now emits a personal
   "hostChanged" to the new host's own socket; player.js's becomeHost()
   unlocks controls live. becomeHost is written to tolerate being
   called more than once safely (addEventListener no-ops on a repeat
   identical listener; the heartbeat setInterval is explicitly guarded
   since it has no such idempotence - calling it twice would leak the
   first interval, the exact bug class the previous pass fixed).

3. No more join codes - PartyManager no longer generates or tracks
   one. The live lobby list is the only discovery mechanism now; a
   code copied out of band doesn't add anything on top of a list
   that's already always current. POST /api/parties/:partyId/join
   replaces :joinCode; the "Rejoindre avec un code" UI is gone.

Found while touching this: the home page's "Rejoindre" button used to
navigate to the player WITHOUT ever calling the join endpoint first -
it loaded fine (GET /api/parties/:id never checked membership) but the
realtime "join" was silently rejected server-side (not an actual
member), so sync never worked for anyone joining this way. Fixed to
await joinParty() before navigating, matching how the library grid's
tiles already did it.

Also: .playerWrap was width:100%/height:100vh inside .mainContent's own
padding, so the two stacked and made the page taller than the
viewport - an outer scrollbar despite the video already being full-
height. Changed to position:fixed/inset:0 so it fills the real
viewport regardless of ancestor padding.

Verified live against a real running server (see session history):
lobby subscription renders host/member-count/ticking-elapsed correctly
from a faked "parties" push (createdUtc 2:05 in the past rendered
"2:06" after ~1s more, proving the client-side tick is real, not
static); the join-then-navigate fix calls the join endpoint before
navigating; .playerWrap computes to position:fixed with all four
insets at 0.

docs/architecture.md has the full writeup.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 23:47:12 +02:00
5d535d18d8 Switch to Socket.IO; fix two real memory leaks
All checks were successful
Publier l'image Docker / publish (push) Successful in 10s
Requested: Socket.IO instead of raw WebSockets, and explicit attention
to memory leaks. Auditing for the second turned up two real, concrete
leaks, independent of the transport library:

1. Server-side: a raw `ws` server has no idea a client is gone unless
   it gets a proper close frame - a sleeping laptop, a network drop, a
   killed tab never fire 'close', so the PartyMember's socket
   reference (and everything it closes over) sat in memory forever,
   and the party was never cleaned up by anything else either
   (removeIdleParties only looks at lastActivityUtc). Socket.IO's
   built-in heartbeat (pingInterval/pingTimeout) detects and closes
   these out on its own - a real, not just cosmetic, reason to prefer
   it here.

2. Client-side: router.js only ever did currentRoot.innerHTML = ''
   between routes, destroying DOM but never telling the outgoing
   view's JS to stop. Leaving the player any way other than its own
   "Quitter" button (a sidebar link, browser back) left the 3s
   heartbeat setInterval, the realtime connection, and the hls.js
   instance all running against a detached <video> indefinitely, for
   as long as the tab stayed open.

Fixes:
- server/src/socketHandler.js replaces wsHandler.js: same protocol
  (see its own top comment), over Socket.IO. Rooms (socket.join/
  io.to) replace manually iterating party.members to broadcast.
  Error event renamed to "errorMessage" - Socket.IO reserves "error".
- server/src/index.js: socket.io server instead of a raw
  WebSocketServer, same-origin (no CORS config needed).
- client/js/party.js: socket.io-client (window.io, loaded via
  <script> in index.html) instead of hand-rolled WebSocket + JSON
  framing - also gets automatic reconnection for free.
- router.js: route() handlers may now return a cleanup function;
  render() calls whatever the previous view returned before switching
  to the next route, regardless of how navigation happened.
- player.js returns a cleanup that clears the heartbeat, destroys
  hls, disconnects the socket, and removes its document-level click
  listener (now named, not inline-anonymous, specifically so it CAN
  be removed - an anonymous one added fresh per visit would itself
  have been a slow leak even with everything else fixed). The
  "Quitter" button is now just navigate('/home') - cleanup runs the
  same way regardless of how you leave.

Verified for real (see session history): a real Socket.IO client
connected to a really-running local server end to end. Then, with
document.addEventListener/removeEventListener and setInterval/
clearInterval instrumented, drove the router through repeated "join a
party, then navigate away without clicking Quitter" cycles - adds and
removes matched exactly every time (3/3 listeners over three cycles,
2/2 intervals over two), nothing left pending.

docs/architecture.md has the full writeup under "Realtime transport:
Socket.IO, and two real memory leaks".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 23:07:51 +02:00
f563f5b0a2 Emby-style UI: sidebar, carousels, series drill-down, episode queue, player tracks
All checks were successful
Publier l'image Docker / publish (push) Successful in 7s
Big UI pass towards looking/behaving like Emby. Deferred: music (needs
its own player + a real-time collaborative playlist - different enough
subsystem to be its own pass; sidebar/routing already treat it as a
first-class collectionType, page just says "not yet" for now).

Layout:
- client/js/shell.js: persistent sidebar (one entry per Emby library,
  from GET /api/catalog/libraries which now also returns
  collectionType) + a #mainContent the router swaps on navigation.
  router.js made idempotent (start() safe to call more than once) so
  a login -> shell boot can happen twice in one page lifetime (logout
  then back in) without piling up duplicate hashchange listeners.
- app.js's boot() renders either the bare login screen or the full
  shell depending on session state; login.js calls it again on
  success instead of navigate() (no router running yet at that point).

Browsing, by collection type:
- views/home.js (route /home): a carousel of every active party
  server-wide, a join-by-code fallback, then one "recently added"
  carousel per non-music library (GET /api/catalog/libraries/:id/recent,
  Emby's Items/Latest).
- views/library.js (route /library/:id): dispatches on collectionType -
  movies/tvshows get the tile grid (Series tiles link into /series/:id
  instead of starting a party directly), music gets an honest
  placeholder.
- views/series.js (route /series/:id): season tabs + episode list
  (new GET /api/catalog/series/:id/seasons and .../episodes, Emby's
  /Shows/{id}/Seasons and /Episodes).
- tiles.js: poster-tile rendering shared by home.js and library.js so
  they can't drift apart.

Episode queue / "next episode":
- POST /api/parties now builds a queue when starting from an episode
  (fetches the rest of the series, from that episode onward) -
  partyManager.js gained queue/queueIndex/advanceQueue.
- New WS message {type:"next"} (host-only) advances the queue and
  broadcasts {type:"itemChanged", itemId, itemName, ...}; every client
  reloads the player against the new item. player.js shows "Épisode
  suivant" when hasNext, and auto-sends next() on the video's `ended`
  event.

Player: language/subtitles/quality:
- New GET /api/catalog/item/:id/playback-options exposes PlaybackInfo's
  MediaStreams as audio/subtitle track lists.
- master.m3u8 now forwards AudioStreamIndex/SubtitleStreamIndex/
  MaxStreamingBitrate to PlaybackInfo; player.js has three <select>s
  (host-only) that reload the stream at the same position on change.
  Subtitles end up burned into the transcode (via SubtitleStreamIndex),
  not a toggleable track - simpler than sidecar WebVTT for this pass.
  "Quality" is a MaxStreamingBitrate ceiling, not true adaptive bitrate.

Verified by driving a browser against mocked /api/* responses (see
session history): sidebar renders/highlights correctly, home carousels
render (parties + one row per non-music library, music correctly
skipped), library grid dispatch works, series page season-tab
switching + episode list render and the season/episode navigation
flow works end to end. Real Emby response shapes for all of this
(Views' CollectionType, Seasons/Episodes, Items/Latest, PlaybackInfo's
MediaStreams) and the queue/track-picker protocol are NOT yet
confirmed against a live server - see docs/architecture.md.

Removed client/js/views/browse.js, superseded by home.js + library.js.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 22:44:49 +02:00
b6818655b1 Proxy all Emby access through our own backend; drop server-url field; use Emby's real theme colors
All checks were successful
Publier l'image Docker / publish (push) Successful in 6s
Three changes requested:

1. Server proxies Emby, browser never talks to it directly. Login is
   now POST /api/auth/login {username,password} on our own backend;
   the backend calls Emby's AuthenticateByName server-side and mints
   its own opaque session (httpOnly cookie), storing
   {embyToken,userId,userName} in memory. The browser never sees or
   holds a real Emby access token. Every other call - search, item
   details, images, HLS streaming, party actions - goes to our own
   /api/* origin, authenticated by that cookie; server/src/embyProxy.js
   forwards to Emby server-side and streams the response back
   (including a playlist-rewrite pass for HLS .m3u8 so hls.js never
   gets handed a URL pointing at Emby directly). This also sidesteps
   the CORS problem the previous direct-to-Emby design had.

2. EMBY_SERVER_URL is backend-only config (.env.example); the login
   form no longer asks for a server address at all.

3. client/css/app.css now uses colors read directly off the live Emby
   server's own dark theme (--theme-primary-color-* etc, fetched via a
   JS probe against the running client, not guessed): accent green
   #52b54b/#6ccf65, near-black background #151216.

Tested for real: ran the server locally against the actual
EMBY_SERVER_URL and submitted intentionally-wrong credentials through
the UI - confirmed the full round trip (browser -> our backend -> real
Emby -> real 401 -> our error message) with no CORS issue, since it's
all server-to-server now. Login itself hasn't been exercised with real
credentials, so catalog/streaming remain unverified - see
docs/architecture.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 21:36:26 +02:00
6ff9aa29e2 Pivot to a standalone app - Emby plugin hit a hard wall
No plugin API exists for adding a button to Emby's player or item
detail page (confirmed by an Emby developer on their own forum, and
by research since). The only way to reach that would be patching
Emby's shipped web client files directly - outside the plugin,
breaks on every image update, needs manual reapplication. Not worth
the ongoing cost, per discussion.

New direction: a standalone app with its own player. Reads Emby's
catalog/streams directly from the browser (no plugin, no menu
integration fights); a small Node backend only coordinates party
membership and relays playback state over WebSocket - it never
touches a media byte. Auth is Emby-only, as chosen: the browser signs
in against Emby directly and this backend validates whatever token it
gets handed by asking Emby itself (GET /Users/{userId}), never seeing
a password.

Control model changed too: now that we own the player, host controls
playback and everyone else follows (event-driven play/pause/seek +
a 3s heartbeat, drift-corrected on the follower side) - the old
plugin's "everyone keeps their own controls, shared reference
position" was specifically a concession to nudging pre-existing Emby
app sessions we didn't control, which no longer applies.

- server/: Express + ws backend (party lifecycle, WebSocket protocol,
  Emby token validation)
- client/: plain-JS/ES-modules frontend (login, search, item detail,
  party player) - no build step
- Smoke-tested locally end to end against a stubbed Emby URL: server
  starts, routing/auth-gating works, error handling degrades
  gracefully (network failure, invalid token) - see the session
  transcript for the actual browser test run
- docs/architecture.md rewritten around the new design, including why
  the plugin was abandoned and a fresh "assumptions to verify" list
  (CORS between this app's origin and Emby's is the biggest unknown)
- src/WatchParty/ (the Emby plugin) kept as-is for reference, no
  longer the active direction

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 20:48:55 +02:00
6f22f72532 Integrate Watch Party into Emby's own UI instead of a standalone app
Per user feedback: no separate control panel, no chat. Found that
PluginPageInfo has EnableInUserMenu/EnableInMainMenu (confirmed via
reflection on the real MediaBrowser.Model assembly, plus an Emby
community thread showing another plugin using EnableInUserMenu=true)
- a real, if barely documented, way to surface a plugin page to
regular users, not just admins, through the exact same
IHasWebPages/GetPages() mechanism as the admin settings page.

- Plugin.cs now registers a second page (partyPage.html) with
  EnableInUserMenu=true + EnableInMainMenu=true
- partyPage.html replaces the old standalone control panel: no login
  form, it runs inside the already-authenticated Emby web client and
  calls the REST API via the global ApiClient
- Removed web/control-panel/ (the standalone app, its own login flow,
  and the custom GET /WatchParty/app* static file routes in
  WatchPartyService.cs) - no longer needed
- docs/architecture.md and README.md updated: the new mechanism, and
  the honest limitation that comes with it (reaches Web/Electron
  clients, not official mobile/TV apps - those allowlist plugin pages
  client-side)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 19:44:31 +02:00
db815df7d5 Fix plugin to build clean against real Emby 4.9.1.90 SDK
Installed .NET 8 SDK (per-user, winget needed admin elevation this
machine doesn't have) and restored the real MediaBrowser.Server.Core /
MediaBrowser.Common packages, then fixed everything the compiler and
a bit of reflection surfaced:

- PlaybackProgressEventArgs/PlaybackStopEventArgs are in
  MediaBrowser.Controller.Library, not ...Session
- IAuthorizationContext/AuthorizationInfo are in MediaBrowser.Controller.Net
- Item/user/session ids (SessionInfo.Id/UserId, BaseItemDto.Id) are plain
  string on this SDK version, not Guid - Party/PartyMember updated
  accordingly (Party.Id stays a Guid; it's minted by this plugin, not Emby)
- Reading the calling user needed an extra step:
  IAuthorizationContext.GetAuthorizationInfo(Request).UserId is a `long`
  (internal row id); .User.Id is the one matching SessionInfo.UserId,
  but it's a Guid so it's reformatted with .ToString("N")

docs/architecture.md's "Assumptions to verify" now reflects what was
actually confirmed vs. what's still only compile-checked (HTTP status
codes, content-type headers, the JS auth header format, the dashboard
config page) pending a run against a real server.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 14:40:17 +02:00
66af05f259 Scaffold Emby Watch Party plugin
Design: coordinate parties on top of Emby's existing session
remote-control commands (SendPlaystateCommand) rather than building a
new player. Each member keeps their own Emby app/controls; the server
periodically corrects drift and mirrors pause/unpause against one
reference member's reported position.

- src/WatchParty: plugin skeleton (BasePlugin, IServerEntryPoint,
  IService/[Route] API, in-memory party store, drift-correction loop)
- web/control-panel: plain HTML/JS/CSS companion page to create/join
  parties and resync, served by the plugin itself
- docs/architecture.md: full design, sources consulted, and an
  explicit list of SDK details that still need verifying against a
  real build (no .NET SDK / Emby SDK assemblies available in this
  environment to compile against)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 14:02:43 +02:00