feat(emby): add Emby as a MediaBrowser backend alongside Jellyfin

Emby is Jellyfin's upstream ancestor and speaks a near-identical MediaBrowser
API, so the existing Jellyfin stack is parameterised by a `MediaBrowserDialect`
rather than forked. `JellyfinClient`, its auth service, endpoint discovery, LAN
discovery, and the add/edit connection screens all take the dialect and keep one
implementation; `MediaBackend.emby` and `ConnectionKind.emby` carry it through
the neutral models, the Drift `kind` discriminator, downloads, and caches.

Every divergence below was measured against a live Emby 4.9.5 server, not
inferred from documentation, and each is documented at its capability getter.
Jellyfin's request strings stay byte-identical so nothing about its behaviour
changes.

Routes and auth
- Emby only accepts the pre-10.9 user-scoped item routes (`/Users/{id}/Items/…`,
  `/Users/{id}/PlayedItems/…`, `/Users/{id}/FavoriteItems/…`); the unprefixed
  forms Jellyfin 10.11 added return 404.
- The API is also served under a legacy `/emby` prefix, and both dialects accept
  the token as `X-Emby-Token` or `api_key=`.
- Emby answers only its own LAN discovery datagram ("who is EmbyServer?") and
  ignores Jellyfin's; its default HTTPS port is 8920.
- No `/QuickConnect` route exists, so Quick Connect stays Jellyfin-only.

Row fields Emby withholds
- `ProductionYear`, `OfficialRating`, `PremiereDate` and `DateCreated` are absent
  from list rows unless named in `Fields`, which would otherwise strip the year
  and age-rating badge from every card in the app.
- `UserData.LastPlayedDate` never appears on a list row under `Fields=UserData`,
  `EnableUserData=true` or the user-scoped `Ids=` form — only on the single-item
  detail route, or when the Emby-specific `UserDataLastPlayedDate` token is
  requested. Without it every recency-ordered surface silently degrades to
  library-add time, and `JellyfinApiCache.applyWatchState` stamps
  `DateTime.now()` on watched rows, so an offline watch-state pull would rewrite
  the cached play time of everything it walked.

Continue Watching and Next Up
- Emby computes Next Up per series only: the library-wide `/Shows/NextUp` query
  returns nothing under every parameter combination tried. The shelf is
  therefore reconstructed from a played-episode recency scan plus one
  `/Shows/NextUp?SeriesId=` per distinct series, bounded by a shared wall clock
  that covers the scan as well — per-request timeouts cannot bound the pass
  because `MediaServerHttpClient` times the connect and receive phases
  independently. Rows are stamped with their series' newest play from the same
  response that ordered them, so no per-series enrichment request is needed.
- `/Shows/NextUp` ignores `NextUpDateCutoff`, and no server-side played-date
  filter exists to delegate to (`MinDatePlayed` and `MinDateLastPlayed` are
  ignored; `MinDateLastSaved`, `MinDateCreated` and `MinPremiereDate` filter
  unrelated dates), so the 365-day window is applied to the scanned dates.
- The resume route returns items with no saved position, including plain next
  episodes, so the Emby resume leg reads from `/Items?Filters=IsResumable`.
- Emby is ahead of Jellyfin in one place: `/Users/{id}/Items/{id}/HideFromResume`
  makes Continue Watching removal a real capability.

Everything else
- `/Sessions/Playing` and `/Sessions/Playing/Progress` reject a body with no
  `PlaySessionId` (HTTP 400), so playback reporting always sends one.
- Passing any `MediaTypes` value to the playlist query returns an empty list.
- There is no aggregate `/Items/Filters` route; the four filter facets are
  reassembled from `/Genres`, `/OfficialRatings`, `/Studios` and `/Tags`.
- Metadata writes take name-pair lists (`Genres: [{'Name': 'Action'}]`); the
  plain string array is accepted and then silently discarded.
- Custom artwork uploads must be base64 text, not raw bytes — which was broken
  for Jellyfin too and is fixed for both.
- Trickplay, media segments and lyrics 404 on Emby, so scrub previews are absent
  and intro/credit markers fall back to chapter names.

Verified against a local Emby 4.9.5 and a Jellyfin 10.11.11 control server:
onboarding, browse, detail, playable stream URLs serving real bytes, subtitle
sidecars, watch-state write and restore, hubs, cross-server aggregation and
search across both backends simultaneously.
This commit is contained in:
edde746
2026-08-05 06:09:26 +02:00
parent f36e20bcad
commit 05fd622968
128 changed files with 4917 additions and 1429 deletions
+1 -1
View File
@@ -235,7 +235,7 @@ class AppDatabase extends _$AppDatabase {
static bool _containsPlaintextConnectionCredential(String kind, Map<String, dynamic> config) {
bool isPlaintext(Object? value) => value is String && value.isNotEmpty && !CredentialVault.isProtected(value);
if (kind == 'jellyfin') return isPlaintext(config['accessToken']);
if (kind == 'jellyfin' || kind == 'emby') return isPlaintext(config['accessToken']);
if (kind != 'plex') return false;
if (isPlaintext(config['accountToken'])) return true;
final servers = config['servers'];
+1 -1
View File
@@ -4497,7 +4497,7 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
/// (one per account); for Jellyfin it's the server's machineId.
final String id;
/// Backend kind: `'plex'` or `'jellyfin'`.
/// Backend kind: `'plex'`, `'jellyfin'`, or `'emby'`.
final String kind;
/// User-visible label (account email, server name).
+37 -26
View File
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:drift/drift.dart';
import 'package:flutter/foundation.dart';
import '../media/ids.dart';
import '../media/media_backend.dart';
import 'app_database.dart';
import '../models/download_models.dart';
@@ -202,22 +203,30 @@ extension DownloadDatabaseOperations on AppDatabase {
final connectionRows = await select(connections).get();
final connectionIds = connectionRows.map((row) => row.id).toSet();
final connectionKindsById = {for (final row in connectionRows) row.id: row.kind};
final jellyfinIdentities = <String, ({String machineId, String? userId})>{};
final jellyfinMachineIds = <String>{};
for (final connection in connectionRows.where((row) => row.kind == 'jellyfin')) {
final identity = _jellyfinConnectionIdentity(connection);
jellyfinIdentities[connection.id] = identity;
jellyfinMachineIds.add(identity.machineId);
final mediaBrowserIdentities = <String, ({String machineId, String? userId, String backendId})>{};
final mediaBrowserMachineIds = <String>{};
// `Connections.kind` is the authoritative dialect discriminator; both
// MediaBrowser kinds use the same compound machine/user scope shape.
for (final connection in connectionRows.where(
(row) => row.kind == MediaBackend.jellyfin.id || row.kind == MediaBackend.emby.id,
)) {
final identity = _mediaBrowserConnectionIdentity(connection);
mediaBrowserIdentities[connection.id] = (
machineId: identity.machineId,
userId: identity.userId,
backendId: connection.kind,
);
mediaBrowserMachineIds.add(identity.machineId);
}
final jellyfinScopesByProfileAndMachine = <String, Map<String, Set<String>>>{};
final mediaBrowserScopesByProfileAndMachine = <String, Map<String, Set<({String scopeId, String backendId})>>>{};
for (final binding in await select(profileConnections).get()) {
if (binding.userIdentifier.isEmpty) continue;
final identity = jellyfinIdentities[binding.connectionId];
final identity = mediaBrowserIdentities[binding.connectionId];
if (identity == null || identity.userId != null && identity.userId != binding.userIdentifier) continue;
jellyfinScopesByProfileAndMachine
.putIfAbsent(binding.profileId, () => <String, Set<String>>{})
.putIfAbsent(identity.machineId, () => <String>{})
.add('${identity.machineId}/${binding.userIdentifier}');
mediaBrowserScopesByProfileAndMachine
.putIfAbsent(binding.profileId, () => <String, Set<({String scopeId, String backendId})>>{})
.putIfAbsent(identity.machineId, () => <({String scopeId, String backendId})>{})
.add((scopeId: '${identity.machineId}/${binding.userIdentifier}', backendId: identity.backendId));
}
final ownedKeys = <String>{
for (final owner in owners)
@@ -239,35 +248,37 @@ extension DownloadDatabaseOperations on AppDatabase {
await addDownloadOwner(
profileId: profileId,
globalKey: row.globalKey,
backendId: 'plex',
backendId: MediaBackend.plex.id,
clientScopeId: scopeId,
);
continue;
}
final jellyfinScopes = jellyfinScopesByProfileAndMachine[profileId]?[row.serverId] ?? const <String>{};
if (jellyfinScopes.length == 1) {
final adoptingScope = jellyfinScopes.single;
final mediaBrowserScopes =
mediaBrowserScopesByProfileAndMachine[profileId]?[row.serverId] ??
const <({String scopeId, String backendId})>{};
if (mediaBrowserScopes.length == 1) {
final adopting = mediaBrowserScopes.single;
await transaction(() async {
if (isStillActive != null && !isStillActive()) return;
await updateDownloadedMediaClientScope(row.globalKey, adoptingScope);
await updateDownloadedMediaClientScope(row.globalKey, adopting.scopeId);
await addDownloadOwner(
profileId: profileId,
globalKey: row.globalKey,
backendId: 'jellyfin',
clientScopeId: adoptingScope,
backendId: adopting.backendId,
clientScopeId: adopting.scopeId,
);
});
continue;
}
// A compound non-Plex scope is a legacy Jellyfin user namespace.
// A compound non-Plex scope is a legacy MediaBrowser user namespace.
// Never attach it to another profile unless that profile has exactly
// one matching Jellyfin binding. The same applies when persisted
// Jellyfin connections identify the machine but the profile has zero
// or multiple possible users.
final hasLegacyJellyfinScope = scopeId?.startsWith('${row.serverId}/') ?? false;
if (hasLegacyJellyfinScope || jellyfinMachineIds.contains(row.serverId)) continue;
// one matching MediaBrowser binding. The same applies when persisted
// MediaBrowser connections identify the machine but the profile has
// zero or multiple possible users.
final hasLegacyMediaBrowserScope = scopeId?.startsWith('${row.serverId}/') ?? false;
if (hasLegacyMediaBrowserScope || mediaBrowserMachineIds.contains(row.serverId)) continue;
final backendId = connectionKindsById[scopeId];
await addDownloadOwner(
@@ -694,7 +705,7 @@ bool _isValidDownloadOwner(
return localProfileIds.isEmpty;
}
({String machineId, String? userId}) _jellyfinConnectionIdentity(ConnectionRow connection) {
({String machineId, String? userId}) _mediaBrowserConnectionIdentity(ConnectionRow connection) {
final separator = connection.id.indexOf('/');
var machineId = separator < 0 ? connection.id : connection.id.substring(0, separator);
String? userId = separator < 0 || separator == connection.id.length - 1
+3 -3
View File
@@ -131,8 +131,8 @@ class SyncRuleDownloads extends Table {
/// Persisted media-server connections.
///
/// One row per "connection" the user has added — a Plex account (with its
/// discovered servers and active Home profile) or a single Jellyfin server.
/// The [configJson] payload is backend-specific and parsed by the
/// discovered servers and active Home profile) or a single MediaBrowser
/// server/user. The [configJson] payload is backend-specific and parsed by the
/// [Connection] sealed class.
@DataClassName('ConnectionRow')
@TableIndex(name: 'idx_connections_kind', columns: {#kind})
@@ -141,7 +141,7 @@ class Connections extends Table {
/// (one per account); for Jellyfin it's the server's machineId.
TextColumn get id => text()();
/// Backend kind: `'plex'` or `'jellyfin'`.
/// Backend kind: `'plex'`, `'jellyfin'`, or `'emby'`.
TextColumn get kind => text()();
/// User-visible label (account email, server name).