Files
plezy/test/connection/connection_models_test.dart
T
edde746 05fd622968 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.
2026-08-05 06:09:26 +02:00

297 lines
11 KiB
Dart

import 'package:flutter_test/flutter_test.dart';
import 'package:plezy/connection/connection.dart';
import 'package:plezy/media/media_backend.dart';
import 'package:plezy/media/media_browser_dialect.dart';
/// Backend-agnostic [Connection] sealed-class tests. The
/// `connection_registry_test` already covers DB persistence; these focus on
/// the model layer's `toConfigJson` / `fromConfigJson` round-trip and the
/// derived `kind` / `backend` mappings — the bits the registry treats as a
/// black box.
void main() {
group('ConnectionKind', () {
test('id round-trips through fromId', () {
for (final k in ConnectionKind.values) {
expect(ConnectionKind.fromId(k.id), k);
}
});
test('fromId throws on unknown id (no silent fallback)', () {
expect(() => ConnectionKind.fromId('kodi'), throwsA(isA<ArgumentError>()));
});
test('backend mapping is total', () {
expect(ConnectionKind.plex.backend, MediaBackend.plex);
expect(ConnectionKind.jellyfin.backend, MediaBackend.jellyfin);
expect(ConnectionKind.emby.backend, MediaBackend.emby);
});
test('dialect maps only the MediaBrowser kinds and round-trips', () {
expect(ConnectionKind.plex.dialect, isNull);
expect(ConnectionKind.jellyfin.dialect, MediaBrowserDialect.jellyfin);
expect(ConnectionKind.emby.dialect, MediaBrowserDialect.emby);
for (final dialect in MediaBrowserDialect.values) {
expect(ConnectionKind.fromDialect(dialect).dialect, dialect);
}
});
});
group('JellyfinConnection serialization', () {
final base = JellyfinConnection(
id: 'srv-1/user-1',
baseUrl: 'https://jellyfin.example.com',
baseUrls: const ['https://jellyfin.example.com', 'https://jellyfin.lan:8096'],
serverName: 'Home',
serverMachineId: 'srv-1',
userId: 'user-1',
userName: 'edde',
accessToken: 'tok-abc',
deviceId: 'dev-xyz',
createdAt: DateTime.utc(2026, 1, 15),
lastAuthenticatedAt: DateTime.utc(2026, 4, 25),
);
test('toConfigJson + fromConfigJson round-trip preserves every field', () {
final json = base.toConfigJson();
final restored = JellyfinConnection.fromConfigJson(
id: base.id,
json: json,
status: base.status,
createdAt: base.createdAt,
lastAuthenticatedAt: base.lastAuthenticatedAt,
);
expect(restored.id, base.id);
expect(restored.baseUrl, base.baseUrl);
expect(restored.baseUrls, base.baseUrls);
expect(restored.serverName, base.serverName);
expect(restored.serverMachineId, base.serverMachineId);
expect(restored.userId, base.userId);
expect(restored.userName, base.userName);
expect(restored.accessToken, base.accessToken);
expect(restored.deviceId, base.deviceId);
expect(restored.createdAt, base.createdAt);
expect(restored.lastAuthenticatedAt, base.lastAuthenticatedAt);
});
test('primary image tag round-trips through config JSON', () {
final tagged = base.copyWith(primaryImageTag: 'avatar-tag');
final restored = JellyfinConnection.fromConfigJson(
id: tagged.id,
json: tagged.toConfigJson(),
status: tagged.status,
createdAt: tagged.createdAt,
lastAuthenticatedAt: tagged.lastAuthenticatedAt,
);
expect(restored.primaryImageTag, 'avatar-tag');
});
test('config saved before image tags decodes with no primary image tag', () {
final legacyJson = <String, Object?>{
'baseUrl': base.baseUrl,
'baseUrls': base.baseUrls,
'serverName': base.serverName,
'serverMachineId': base.serverMachineId,
'userId': base.userId,
'userName': base.userName,
'accessToken': base.accessToken,
'deviceId': base.deviceId,
'isAdministrator': base.isAdministrator,
};
expect(legacyJson.containsKey('primaryImageTag'), isFalse);
final restored = JellyfinConnection.fromConfigJson(
id: base.id,
json: legacyJson,
status: base.status,
createdAt: base.createdAt,
lastAuthenticatedAt: base.lastAuthenticatedAt,
);
expect(restored.primaryImageTag, isNull);
});
test('blank persisted primary image tags decode as null', () {
for (final tag in ['', ' \t\n ']) {
final restored = JellyfinConnection.fromConfigJson(
id: base.id,
json: {...base.toConfigJson(), 'primaryImageTag': tag},
status: base.status,
createdAt: base.createdAt,
lastAuthenticatedAt: base.lastAuthenticatedAt,
);
expect(restored.primaryImageTag, isNull, reason: 'tag: "$tag"');
}
});
test('fromConfigJson with empty payload uses safe defaults (no NPE)', () {
final restored = JellyfinConnection.fromConfigJson(
id: 'orphan',
json: const {},
status: ConnectionStatus.unknown,
createdAt: DateTime.utc(2026),
);
expect(restored.id, 'orphan');
expect(restored.baseUrl, '');
expect(restored.baseUrls, isEmpty);
expect(restored.serverName, 'Jellyfin');
expect(restored.accessToken, '');
});
test('fromConfigJson backfills baseUrls from legacy baseUrl', () {
final restored = JellyfinConnection.fromConfigJson(
id: 'legacy',
json: const {
'baseUrl': 'https://jellyfin.example.com',
'serverName': 'Home',
'serverMachineId': 'srv-1',
'userId': 'user-1',
},
status: ConnectionStatus.unknown,
createdAt: DateTime.utc(2026),
);
expect(restored.baseUrl, 'https://jellyfin.example.com');
expect(restored.baseUrls, ['https://jellyfin.example.com']);
});
test('copyWith moves the active baseUrl to the front of baseUrls', () {
final updated = base.copyWith(baseUrl: 'https://jellyfin.lan:8096');
expect(updated.baseUrl, 'https://jellyfin.lan:8096');
expect(updated.baseUrls, ['https://jellyfin.lan:8096', 'https://jellyfin.example.com']);
});
test('copyWith preserves an existing primary image tag by default', () {
final tagged = base.copyWith(primaryImageTag: 'old');
expect(tagged.copyWith().primaryImageTag, 'old');
});
test('copyWith replaces an existing primary image tag', () {
final tagged = base.copyWith(primaryImageTag: 'old');
expect(tagged.copyWith(primaryImageTag: 'new').primaryImageTag, 'new');
});
test('copyWith only clears a primary image tag through the clear sentinel', () {
final tagged = base.copyWith(primaryImageTag: 'old');
expect(tagged.copyWith(primaryImageTag: null).primaryImageTag, 'old');
expect(tagged.copyWith(clearPrimaryImageTag: true).primaryImageTag, isNull);
});
test('reads primary image tags defensively from Jellyfin user DTOs', () {
expect(JellyfinConnection.readPrimaryImageTag(const {'PrimaryImageTag': 'avatar-tag'}), 'avatar-tag');
expect(JellyfinConnection.readPrimaryImageTag(const {}), isNull);
expect(JellyfinConnection.readPrimaryImageTag(const {'PrimaryImageTag': ' \t\n '}), isNull);
expect(JellyfinConnection.readPrimaryImageTag(const {'PrimaryImageTag': 42}), '42');
});
test('kind and backend match Jellyfin', () {
expect(base.dialect, MediaBrowserDialect.jellyfin);
expect(base.kind, ConnectionKind.jellyfin);
expect(base.backend, MediaBackend.jellyfin);
});
test('an Emby dialect drives kind, backend and the persisted discriminator', () {
final emby = base.copyWith(dialect: MediaBrowserDialect.emby);
expect(emby.kind, ConnectionKind.emby);
expect(emby.kind.id, 'emby');
expect(emby.backend, MediaBackend.emby);
// The dialect lives in the `connections.kind` column, never in the
// encrypted config payload, so exactly one discriminator is on disk.
expect(emby.toConfigJson().containsKey('dialect'), isFalse);
});
test('fromConfigJson restores the dialect handed in by the registry', () {
final restored = JellyfinConnection.fromConfigJson(
id: 'srv-1/user-1',
json: base.toConfigJson(),
status: ConnectionStatus.online,
createdAt: base.createdAt,
dialect: MediaBrowserDialect.emby,
);
expect(restored.dialect, MediaBrowserDialect.emby);
expect(restored.kind, ConnectionKind.emby);
expect(restored.accessToken, 'tok-abc');
});
test('fromConfigJson defaults to Jellyfin for rows written before Emby support', () {
final restored = JellyfinConnection.fromConfigJson(
id: 'legacy',
json: const {'baseUrl': 'https://jellyfin.example.com'},
status: ConnectionStatus.unknown,
createdAt: DateTime.utc(2026),
);
expect(restored.dialect, MediaBrowserDialect.jellyfin);
expect(restored.kind, ConnectionKind.jellyfin);
});
test('empty-payload serverName falls back to the dialect product name', () {
final emby = JellyfinConnection.fromConfigJson(
id: 'orphan',
json: const {},
status: ConnectionStatus.unknown,
createdAt: DateTime.utc(2026),
dialect: MediaBrowserDialect.emby,
);
expect(emby.serverName, 'Emby');
});
});
group('PlexAccountConnection serialization', () {
final base = PlexAccountConnection(
id: 'plex.client-uuid',
accountToken: 'token-xyz',
clientIdentifier: 'client-uuid',
accountLabel: 'edde',
servers: const [],
activeProfile: null,
createdAt: DateTime.utc(2026, 1, 15),
lastAuthenticatedAt: DateTime.utc(2026, 4, 25),
);
test('toConfigJson + fromConfigJson round-trip preserves identity fields', () {
final json = base.toConfigJson();
final restored = PlexAccountConnection.fromConfigJson(
id: base.id,
json: json,
status: base.status,
createdAt: base.createdAt,
lastAuthenticatedAt: base.lastAuthenticatedAt,
);
expect(restored.id, base.id);
expect(restored.accountToken, base.accountToken);
expect(restored.clientIdentifier, base.clientIdentifier);
expect(restored.accountLabel, base.accountLabel);
expect(restored.servers, isEmpty);
expect(restored.activeProfile, isNull);
expect(restored.createdAt, base.createdAt);
expect(restored.lastAuthenticatedAt, base.lastAuthenticatedAt);
});
test('fromConfigJson with empty payload uses safe defaults (no NPE)', () {
final restored = PlexAccountConnection.fromConfigJson(
id: 'orphan',
json: const {},
status: ConnectionStatus.unknown,
createdAt: DateTime.utc(2026),
);
expect(restored.id, 'orphan');
expect(restored.accountToken, '');
expect(restored.accountLabel, 'Plex');
expect(restored.servers, isEmpty);
});
test('kind and backend match Plex', () {
expect(base.kind, ConnectionKind.plex);
expect(base.backend, MediaBackend.plex);
});
});
}