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.
1037 lines
35 KiB
Dart
1037 lines
35 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:fake_async/fake_async.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:http/testing.dart';
|
|
import 'package:plezy/connection/connection.dart';
|
|
import 'package:plezy/exceptions/media_server_exceptions.dart';
|
|
import 'package:plezy/media/media_browser_dialect.dart';
|
|
import 'package:plezy/services/jellyfin_auth_service.dart';
|
|
import 'package:plezy/services/jellyfin_endpoint_discovery.dart';
|
|
import 'package:plezy/utils/log_redaction_manager.dart';
|
|
import 'package:plezy/utils/media_server_timeouts.dart';
|
|
|
|
import '../test_helpers/backend_client_fixtures.dart';
|
|
|
|
/// Helpers for stubbing http responses keyed by request path.
|
|
typedef _Handler = FutureOr<http.Response> Function(http.BaseRequest req);
|
|
|
|
http.Response _ok(Object json) => http.Response(jsonEncode(json), 200, headers: {'content-type': 'application/json'});
|
|
http.Response _bareOk(String body) => http.Response(body, 200, headers: {'content-type': 'application/json'});
|
|
http.Response _status(int code, [Object? json]) =>
|
|
http.Response(json == null ? '' : jsonEncode(json), code, headers: {'content-type': 'application/json'});
|
|
|
|
JellyfinConnection _existingConn({
|
|
String accessToken = 'tok-old',
|
|
MediaBrowserDialect dialect = MediaBrowserDialect.jellyfin,
|
|
}) => testJellyfinConnection(
|
|
userName: 'edde',
|
|
accessToken: accessToken,
|
|
deviceId: 'dev-xyz',
|
|
createdAt: DateTime.fromMillisecondsSinceEpoch(0),
|
|
dialect: dialect,
|
|
);
|
|
|
|
JellyfinConnectionAuthService _service({
|
|
required _Handler handler,
|
|
MediaBrowserDialect dialect = MediaBrowserDialect.jellyfin,
|
|
}) {
|
|
return JellyfinConnectionAuthService(
|
|
clientName: 'Plezy',
|
|
clientVersion: 'test',
|
|
deviceName: 'TestDevice',
|
|
dialect: dialect,
|
|
testHttpClientFactory: () => MockClient((req) async => handler(req)),
|
|
);
|
|
}
|
|
|
|
Future<JellyfinConnection> _authenticateByNameWithUser(Map<String, Object?> user) {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') {
|
|
return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
}
|
|
if (req.url.path == '/Users/AuthenticateByName') {
|
|
return _ok({'AccessToken': 'tok-new', 'User': user});
|
|
}
|
|
return _status(404);
|
|
},
|
|
);
|
|
|
|
return svc.authenticateByName(
|
|
baseUrl: 'https://jf.example.com',
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: 'dev-xyz',
|
|
);
|
|
}
|
|
|
|
Future<Object> _captureError(Future<dynamic> future) async {
|
|
try {
|
|
await future;
|
|
} catch (error) {
|
|
return error;
|
|
}
|
|
throw StateError('Expected future to fail');
|
|
}
|
|
|
|
const _serverInfo = JellyfinServerInfo(serverName: 'Home', machineId: 'srv-1', version: '10.9.0');
|
|
|
|
void main() {
|
|
setUp(LogRedactionManager.clearTrackedValues);
|
|
tearDown(LogRedactionManager.clearTrackedValues);
|
|
|
|
group('JellyfinConnectionAuthService.probe', () {
|
|
test('returns server info on a well-formed /System/Info/Public response', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
expect(req.url.path, '/System/Info/Public');
|
|
expect(req.method, 'GET');
|
|
return _ok({'Id': 'srv-1', 'ServerName': 'Home', 'Version': '10.9.0'});
|
|
},
|
|
);
|
|
|
|
final info = await svc.probe('https://jf.example.com/');
|
|
expect(info.serverName, 'Home');
|
|
expect(info.machineId, 'srv-1');
|
|
expect(info.version, '10.9.0');
|
|
});
|
|
|
|
test('falls back to LocalAddress when ServerName is absent', () async {
|
|
final svc = _service(handler: (_) => _ok({'Id': 'srv-1', 'LocalAddress': 'http://192.168.1.10:8096'}));
|
|
final info = await svc.probe('https://jf.example.com');
|
|
expect(info.serverName, 'http://192.168.1.10:8096');
|
|
});
|
|
|
|
test('throws MediaServerUrlException when payload is not JSON', () async {
|
|
final svc = _service(handler: (_) => http.Response('plain text', 200));
|
|
await expectLater(svc.probe('https://jf.example.com'), throwsA(isA<MediaServerUrlException>()));
|
|
});
|
|
|
|
test('throws MediaServerUrlException when payload is missing Id/ServerName', () async {
|
|
final svc = _service(handler: (_) => _ok({'Version': '10.9.0'}));
|
|
await expectLater(svc.probe('https://jf.example.com'), throwsA(isA<MediaServerUrlException>()));
|
|
});
|
|
|
|
test('throws MediaServerUrlException on transport HTTP error', () async {
|
|
final svc = _service(handler: (_) => _status(500, {'error': 'oops'}));
|
|
await expectLater(svc.probe('https://jf.example.com'), throwsA(isA<MediaServerUrlException>()));
|
|
});
|
|
|
|
test('applies the shared jellyfinProbe timeout to the injected auth client', () {
|
|
fakeAsync((async) {
|
|
final response = Completer<http.Response>();
|
|
final svc = _service(handler: (_) => response.future);
|
|
Object? probeError;
|
|
|
|
unawaited(_captureError(svc.probe('https://jf.example.com')).then((error) => probeError = error));
|
|
async.flushMicrotasks();
|
|
|
|
async.elapse(MediaServerTimeouts.jellyfinProbe - const Duration(milliseconds: 1));
|
|
async.flushMicrotasks();
|
|
expect(probeError, isNull);
|
|
|
|
async.elapse(const Duration(milliseconds: 2));
|
|
async.flushMicrotasks();
|
|
expect(probeError, isA<MediaServerUrlException>());
|
|
});
|
|
});
|
|
|
|
test('registers base URL redaction before the first probe request', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
final redacted = LogRedactionManager.redact(req.url.toString());
|
|
expect(redacted, isNot(contains('private-jellyfin.example.com')));
|
|
return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
},
|
|
);
|
|
|
|
await svc.probe('https://private-jellyfin.example.com');
|
|
});
|
|
});
|
|
|
|
group('JellyfinConnectionAuthService.authenticateByName', () {
|
|
test('returns a JellyfinConnection on success', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') {
|
|
return _ok({'Id': 'srv-1', 'ServerName': 'Home', 'Version': '10.9.0'});
|
|
}
|
|
if (req.url.path == '/Users/AuthenticateByName') {
|
|
expect(req.method, 'POST');
|
|
return _ok({
|
|
'AccessToken': 'tok-new',
|
|
'User': {'Id': 'user-7', 'Name': 'edde'},
|
|
});
|
|
}
|
|
return _status(404);
|
|
},
|
|
);
|
|
|
|
final conn = await svc.authenticateByName(
|
|
baseUrl: 'https://jf.example.com',
|
|
baseUrls: const ['https://jf.example.com', 'https://jf.lan:8096'],
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: 'dev-xyz',
|
|
);
|
|
expect(conn.accessToken, 'tok-new');
|
|
expect(conn.baseUrl, 'https://jf.example.com');
|
|
expect(conn.baseUrls, ['https://jf.example.com', 'https://jf.lan:8096']);
|
|
expect(conn.userId, 'user-7');
|
|
expect(conn.userName, 'edde');
|
|
expect(conn.serverMachineId, 'srv-1');
|
|
// Composite id keeps multi-user-per-server unambiguous.
|
|
expect(conn.id, 'srv-1/user-7');
|
|
});
|
|
|
|
test('captures the user primary image tag', () async {
|
|
final conn = await _authenticateByNameWithUser({'Id': 'user-7', 'Name': 'edde', 'PrimaryImageTag': 'avatar-tag'});
|
|
|
|
expect(conn.primaryImageTag, 'avatar-tag');
|
|
});
|
|
|
|
test('uses no primary image tag when Jellyfin omits the key', () async {
|
|
final conn = await _authenticateByNameWithUser({'Id': 'user-7', 'Name': 'edde'});
|
|
|
|
expect(conn.primaryImageTag, isNull);
|
|
});
|
|
|
|
test('uses no primary image tag when Jellyfin returns null', () async {
|
|
final conn = await _authenticateByNameWithUser({'Id': 'user-7', 'Name': 'edde', 'PrimaryImageTag': null});
|
|
|
|
expect(conn.primaryImageTag, isNull);
|
|
});
|
|
|
|
test('ignores empty and whitespace-only primary image tags', () async {
|
|
for (final tag in ['', ' \t ']) {
|
|
final conn = await _authenticateByNameWithUser({'Id': 'user-7', 'Name': 'edde', 'PrimaryImageTag': tag});
|
|
|
|
expect(conn.primaryImageTag, isNull, reason: 'tag: "$tag"');
|
|
}
|
|
});
|
|
|
|
test('a malformed primary image tag does not fail sign-in', () async {
|
|
final cases = <(Object, String)>[
|
|
(12345, '12345'),
|
|
(['unexpected'], '[unexpected]'),
|
|
({'unexpected': 'tag'}, '{unexpected: tag}'),
|
|
];
|
|
|
|
for (final (tag, expected) in cases) {
|
|
final conn = await _authenticateByNameWithUser({'Id': 'user-7', 'Name': 'edde', 'PrimaryImageTag': tag});
|
|
|
|
expect(conn, isA<JellyfinConnection>());
|
|
expect(conn.primaryImageTag, expected, reason: 'tag: $tag');
|
|
}
|
|
});
|
|
|
|
test('throws MediaServerAuthException on 401', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') {
|
|
return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
}
|
|
return _status(401);
|
|
},
|
|
);
|
|
|
|
await expectLater(
|
|
svc.authenticateByName(
|
|
baseUrl: 'https://jf.example.com',
|
|
username: 'edde',
|
|
password: 'wrong',
|
|
deviceId: 'dev-xyz',
|
|
),
|
|
throwsA(isA<MediaServerAuthException>()),
|
|
);
|
|
});
|
|
|
|
test('throws MediaServerAuthException on malformed JSON 401', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') {
|
|
return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
}
|
|
return http.Response('{bad json', 401, headers: {'content-type': 'application/json'});
|
|
},
|
|
);
|
|
|
|
await expectLater(
|
|
svc.authenticateByName(
|
|
baseUrl: 'https://jf.example.com',
|
|
username: 'edde',
|
|
password: 'wrong',
|
|
deviceId: 'dev-xyz',
|
|
),
|
|
throwsA(isA<MediaServerAuthException>().having((e) => e.statusCode, 'statusCode', 401)),
|
|
);
|
|
});
|
|
|
|
test('throws MediaServerAuthException when AccessToken is missing', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') {
|
|
return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
}
|
|
return _ok({
|
|
'User': {'Id': 'user-7', 'Name': 'edde'},
|
|
});
|
|
},
|
|
);
|
|
|
|
await expectLater(
|
|
svc.authenticateByName(
|
|
baseUrl: 'https://jf.example.com',
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: 'dev-xyz',
|
|
),
|
|
throwsA(isA<MediaServerAuthException>()),
|
|
);
|
|
});
|
|
});
|
|
|
|
group('JellyfinConnectionAuthService.isQuickConnectEnabled', () {
|
|
test('returns true when the server replies with bare `true`', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
expect(req.url.path, '/QuickConnect/Enabled');
|
|
return _bareOk('true');
|
|
},
|
|
);
|
|
expect(await svc.isQuickConnectEnabled('https://jf.example.com'), isTrue);
|
|
});
|
|
|
|
test('returns false when the server replies with bare `false`', () async {
|
|
final svc = _service(handler: (_) => _bareOk('false'));
|
|
expect(await svc.isQuickConnectEnabled('https://jf.example.com'), isFalse);
|
|
});
|
|
|
|
test('returns false on 404 (Jellyfin <10.7)', () async {
|
|
final svc = _service(handler: (_) => _status(404));
|
|
expect(await svc.isQuickConnectEnabled('https://jf.example.com'), isFalse);
|
|
});
|
|
|
|
test('returns false on transport error', () async {
|
|
final svc = JellyfinConnectionAuthService(
|
|
clientName: 'Plezy',
|
|
clientVersion: 'test',
|
|
deviceName: 'TestDevice',
|
|
testHttpClientFactory: () => MockClient((_) async => throw http.ClientException('network down')),
|
|
);
|
|
expect(await svc.isQuickConnectEnabled('https://jf.example.com'), isFalse);
|
|
});
|
|
});
|
|
|
|
group('JellyfinConnectionAuthService.initiateQuickConnect', () {
|
|
test('returns code/secret on a successful GET', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
expect(req.url.path, '/QuickConnect/Initiate');
|
|
expect(req.method, 'GET');
|
|
return _ok({'Code': 'ABCDE', 'Secret': 'sec-xyz'});
|
|
},
|
|
);
|
|
|
|
final qc = await svc.initiateQuickConnect(baseUrl: 'https://jf.example.com', deviceId: 'dev-xyz');
|
|
expect(qc.code, 'ABCDE');
|
|
expect(qc.secret, 'sec-xyz');
|
|
});
|
|
|
|
test('falls back to POST on 405', () async {
|
|
var sawGet = false;
|
|
final svc = _service(
|
|
handler: (req) {
|
|
expect(req.url.path, '/QuickConnect/Initiate');
|
|
if (req.method == 'GET') {
|
|
sawGet = true;
|
|
return _status(405);
|
|
}
|
|
expect(req.method, 'POST');
|
|
return _ok({'Code': 'ABCDE', 'Secret': 'sec-xyz'});
|
|
},
|
|
);
|
|
|
|
final qc = await svc.initiateQuickConnect(baseUrl: 'https://jf.example.com', deviceId: 'dev-xyz');
|
|
expect(sawGet, isTrue);
|
|
expect(qc.code, 'ABCDE');
|
|
});
|
|
|
|
test('throws MediaServerAuthException on 401/403', () async {
|
|
final svc = _service(handler: (_) => _status(403));
|
|
await expectLater(
|
|
svc.initiateQuickConnect(baseUrl: 'https://jf.example.com', deviceId: 'dev-xyz'),
|
|
throwsA(isA<MediaServerAuthException>()),
|
|
);
|
|
});
|
|
|
|
test('throws MediaServerAuthException on malformed JSON 401', () async {
|
|
final svc = _service(
|
|
handler: (_) => http.Response('{bad json', 401, headers: {'content-type': 'application/json'}),
|
|
);
|
|
|
|
await expectLater(
|
|
svc.initiateQuickConnect(baseUrl: 'https://jf.example.com', deviceId: 'dev-xyz'),
|
|
throwsA(isA<MediaServerAuthException>().having((e) => e.statusCode, 'statusCode', 401)),
|
|
);
|
|
});
|
|
});
|
|
|
|
group('JellyfinConnectionAuthService.authenticateByQuickConnect', () {
|
|
test('returns a JellyfinConnection after the user approves', () async {
|
|
var pollCount = 0;
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') {
|
|
return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
}
|
|
if (req.url.path == '/QuickConnect/Connect') {
|
|
pollCount++;
|
|
// Return Authenticated=true on second poll.
|
|
return _ok({'Authenticated': pollCount >= 2});
|
|
}
|
|
if (req.url.path == '/Users/AuthenticateWithQuickConnect') {
|
|
return _ok({
|
|
'AccessToken': 'tok-qc',
|
|
'User': {'Id': 'user-9', 'Name': 'edde'},
|
|
});
|
|
}
|
|
return _status(404);
|
|
},
|
|
);
|
|
|
|
final conn = await svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
timeout: const Duration(seconds: 30),
|
|
);
|
|
expect(conn, isNotNull);
|
|
expect(conn!.accessToken, 'tok-qc');
|
|
expect(conn.userId, 'user-9');
|
|
});
|
|
|
|
test('captures the user primary image tag', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') {
|
|
return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
}
|
|
if (req.url.path == '/QuickConnect/Connect') {
|
|
return _ok({'Authenticated': true});
|
|
}
|
|
if (req.url.path == '/Users/AuthenticateWithQuickConnect') {
|
|
return _ok({
|
|
'AccessToken': 'tok-qc',
|
|
'User': {'Id': 'user-9', 'Name': 'edde', 'PrimaryImageTag': 'quick-connect-avatar'},
|
|
});
|
|
}
|
|
return _status(404);
|
|
},
|
|
);
|
|
|
|
final conn = await svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
timeout: const Duration(seconds: 30),
|
|
);
|
|
|
|
expect(conn, isNotNull);
|
|
expect(conn!.primaryImageTag, 'quick-connect-avatar');
|
|
});
|
|
|
|
test('returns null when secret expires server-side (404 mid-poll)', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
if (req.url.path == '/QuickConnect/Connect') return _status(404);
|
|
return _status(500);
|
|
},
|
|
);
|
|
|
|
final conn = await svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
timeout: const Duration(seconds: 5),
|
|
);
|
|
expect(conn, isNull);
|
|
});
|
|
|
|
test('returns null when malformed JSON 404 happens mid-poll', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
if (req.url.path == '/QuickConnect/Connect') {
|
|
return http.Response('{bad json', 404, headers: {'content-type': 'application/json'});
|
|
}
|
|
return _status(500);
|
|
},
|
|
);
|
|
|
|
final conn = await svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
timeout: const Duration(seconds: 5),
|
|
);
|
|
expect(conn, isNull);
|
|
});
|
|
|
|
test('returns null when shouldCancel becomes true', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
return _ok({'Authenticated': false});
|
|
},
|
|
);
|
|
|
|
final conn = await svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
timeout: const Duration(seconds: 30),
|
|
shouldCancel: () => true,
|
|
);
|
|
expect(conn, isNull);
|
|
});
|
|
|
|
test('throws MediaServerAuthException when poll returns 401', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
return _status(401);
|
|
},
|
|
);
|
|
|
|
await expectLater(
|
|
svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
timeout: const Duration(seconds: 5),
|
|
),
|
|
throwsA(isA<MediaServerAuthException>()),
|
|
);
|
|
});
|
|
|
|
test('throws MediaServerAuthException when malformed JSON poll returns 401', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
return http.Response('{bad json', 401, headers: {'content-type': 'application/json'});
|
|
},
|
|
);
|
|
|
|
await expectLater(
|
|
svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
timeout: const Duration(seconds: 5),
|
|
),
|
|
throwsA(isA<MediaServerAuthException>().having((e) => e.statusCode, 'statusCode', 401)),
|
|
);
|
|
});
|
|
|
|
test('throws MediaServerAuthException when exchange returns 400', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
if (req.url.path == '/QuickConnect/Connect') return _ok({'Authenticated': true});
|
|
if (req.url.path == '/Users/AuthenticateWithQuickConnect') return _status(400);
|
|
return _status(500);
|
|
},
|
|
);
|
|
|
|
await expectLater(
|
|
svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
timeout: const Duration(seconds: 5),
|
|
),
|
|
throwsA(isA<MediaServerAuthException>().having((e) => e.statusCode, 'statusCode', 400)),
|
|
);
|
|
});
|
|
|
|
test('throws MediaServerAuthException when malformed JSON exchange returns 400', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') return _ok({'Id': 'srv-1', 'ServerName': 'Home'});
|
|
if (req.url.path == '/QuickConnect/Connect') return _ok({'Authenticated': true});
|
|
if (req.url.path == '/Users/AuthenticateWithQuickConnect') {
|
|
return http.Response('{bad json', 400, headers: {'content-type': 'application/json'});
|
|
}
|
|
return _status(500);
|
|
},
|
|
);
|
|
|
|
await expectLater(
|
|
svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
timeout: const Duration(seconds: 5),
|
|
),
|
|
throwsA(isA<MediaServerAuthException>().having((e) => e.statusCode, 'statusCode', 400)),
|
|
);
|
|
});
|
|
});
|
|
|
|
group('Jellyfin authentication response parity', () {
|
|
test('password and Quick Connect exchange use the same timeout', () {
|
|
fakeAsync((async) {
|
|
final passwordResponse = Completer<http.Response>();
|
|
final quickConnectResponse = Completer<http.Response>();
|
|
final passwordService = _service(handler: (_) => passwordResponse.future);
|
|
final quickConnectService = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/QuickConnect/Connect') return _ok({'Authenticated': true});
|
|
return quickConnectResponse.future;
|
|
},
|
|
);
|
|
|
|
Object? passwordError;
|
|
Object? quickConnectError;
|
|
unawaited(
|
|
_captureError(
|
|
passwordService.authenticateByName(
|
|
baseUrl: 'https://jf.example.com',
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: 'dev-xyz',
|
|
serverInfo: _serverInfo,
|
|
),
|
|
).then((error) => passwordError = error),
|
|
);
|
|
unawaited(
|
|
_captureError(
|
|
quickConnectService.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
serverInfo: _serverInfo,
|
|
),
|
|
).then((error) => quickConnectError = error),
|
|
);
|
|
|
|
async.flushMicrotasks();
|
|
expect(passwordError, isNull);
|
|
expect(quickConnectError, isNull);
|
|
|
|
async.elapse(MediaServerTimeouts.jellyfinProbe + const Duration(milliseconds: 1));
|
|
async.flushMicrotasks();
|
|
|
|
for (final error in [passwordError, quickConnectError]) {
|
|
expect(
|
|
error,
|
|
isA<MediaServerHttpException>().having(
|
|
(exception) => exception.type,
|
|
'type',
|
|
MediaServerHttpErrorType.connectionTimeout,
|
|
),
|
|
);
|
|
}
|
|
});
|
|
});
|
|
|
|
test('password and Quick Connect exchange preserve non-auth HTTP errors', () async {
|
|
final passwordService = _service(handler: (_) => _status(500));
|
|
final quickConnectService = _service(
|
|
handler: (req) => req.url.path == '/QuickConnect/Connect' ? _ok({'Authenticated': true}) : _status(500),
|
|
);
|
|
|
|
final errors = [
|
|
await _captureError(
|
|
passwordService.authenticateByName(
|
|
baseUrl: 'https://jf.example.com',
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: 'dev-xyz',
|
|
serverInfo: _serverInfo,
|
|
),
|
|
),
|
|
await _captureError(
|
|
quickConnectService.authenticateByQuickConnect(
|
|
baseUrl: 'https://jf.example.com',
|
|
secret: 'sec',
|
|
deviceId: 'dev-xyz',
|
|
serverInfo: _serverInfo,
|
|
),
|
|
),
|
|
];
|
|
|
|
for (final error in errors) {
|
|
expect(error, isA<MediaServerHttpException>().having((exception) => exception.statusCode, 'statusCode', 500));
|
|
}
|
|
});
|
|
});
|
|
|
|
group('JellyfinConnectionAuthService.validate', () {
|
|
test('returns true when /Users/Me responds 200', () async {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
expect(req.url.path, '/Users/Me');
|
|
return _ok({'Id': 'user-1'});
|
|
},
|
|
);
|
|
|
|
expect(await svc.validate(_existingConn()), isTrue);
|
|
});
|
|
|
|
test('returns false on 401/403', () async {
|
|
final svc = _service(handler: (_) => _status(401));
|
|
expect(await svc.validate(_existingConn()), isFalse);
|
|
});
|
|
|
|
test('returns false for non-Jellyfin connections', () async {
|
|
final svc = _service(handler: (_) => _ok({}));
|
|
// Use a Plex connection placeholder (any non-Jellyfin Connection works).
|
|
final notJellyfin = PlexAccountConnection(
|
|
id: 'plex-1',
|
|
accountToken: 'tok',
|
|
clientIdentifier: 'cid',
|
|
accountLabel: 'Plex',
|
|
createdAt: DateTime.fromMillisecondsSinceEpoch(0),
|
|
);
|
|
expect(await svc.validate(notJellyfin), isFalse);
|
|
});
|
|
});
|
|
|
|
group('JellyfinConnectionAuthService.refresh', () {
|
|
test('returns connection with online status + lastAuthenticatedAt on success', () async {
|
|
final svc = _service(handler: (_) => _ok({'Id': 'user-1'}));
|
|
final refreshed = await svc.refresh(_existingConn());
|
|
expect(refreshed, isA<JellyfinConnection>());
|
|
expect((refreshed as JellyfinConnection).status, ConnectionStatus.online);
|
|
expect(refreshed.lastAuthenticatedAt, isNotNull);
|
|
});
|
|
|
|
test('returns connection with authError status when validate fails', () async {
|
|
final svc = _service(handler: (_) => _status(401));
|
|
final refreshed = await svc.refresh(_existingConn());
|
|
expect((refreshed as JellyfinConnection).status, ConnectionStatus.authError);
|
|
});
|
|
|
|
test('returns the same Connection unchanged for non-Jellyfin', () async {
|
|
final svc = _service(handler: (_) => _ok({}));
|
|
final plex = PlexAccountConnection(
|
|
id: 'plex-1',
|
|
accountToken: 'tok',
|
|
clientIdentifier: 'cid',
|
|
accountLabel: 'Plex',
|
|
createdAt: DateTime.fromMillisecondsSinceEpoch(0),
|
|
);
|
|
expect(await svc.refresh(plex), same(plex));
|
|
});
|
|
});
|
|
|
|
group('JellyfinConnectionAuthService.signOut', () {
|
|
test('fires POST /Sessions/Logout against the right base URL', () async {
|
|
var sawLogout = false;
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/Sessions/Logout') {
|
|
sawLogout = true;
|
|
expect(req.method, 'POST');
|
|
return _ok({});
|
|
}
|
|
return _status(404);
|
|
},
|
|
);
|
|
|
|
await svc.signOut(_existingConn());
|
|
expect(sawLogout, isTrue);
|
|
});
|
|
|
|
test('does not throw when the server fails (best-effort)', () async {
|
|
final svc = _service(handler: (_) => _status(500));
|
|
await svc.signOut(_existingConn()); // expect: no throw
|
|
});
|
|
|
|
test('is a no-op for non-Jellyfin connections', () async {
|
|
var fired = false;
|
|
final svc = _service(
|
|
handler: (_) {
|
|
fired = true;
|
|
return _ok({});
|
|
},
|
|
);
|
|
|
|
final plex = PlexAccountConnection(
|
|
id: 'plex-1',
|
|
accountToken: 'tok',
|
|
clientIdentifier: 'cid',
|
|
accountLabel: 'Plex',
|
|
createdAt: DateTime.fromMillisecondsSinceEpoch(0),
|
|
);
|
|
await svc.signOut(plex);
|
|
expect(fired, isFalse);
|
|
});
|
|
});
|
|
|
|
group('Emby dialect', () {
|
|
test('validate uses the user-scoped current-user route instead of /Users/Me', () async {
|
|
final paths = <String>[];
|
|
final svc = _service(
|
|
dialect: MediaBrowserDialect.emby,
|
|
handler: (req) {
|
|
paths.add(req.url.path);
|
|
if (req.url.path == '/Users/Me') {
|
|
return _status(500, {'error': 'Unrecognized Guid format'});
|
|
}
|
|
return _ok({'Id': 'user-1'});
|
|
},
|
|
);
|
|
|
|
expect(await svc.validate(_existingConn(dialect: MediaBrowserDialect.emby)), isTrue);
|
|
expect(paths, ['/Users/user-1']);
|
|
});
|
|
|
|
test('checking Quick Connect support sends no unsupported Emby request', () async {
|
|
final paths = <String>[];
|
|
final svc = _service(
|
|
dialect: MediaBrowserDialect.emby,
|
|
handler: (req) {
|
|
paths.add(req.url.path);
|
|
expect(req.url.path, isNot(startsWith('/QuickConnect/')));
|
|
return _status(404);
|
|
},
|
|
);
|
|
|
|
expect(await svc.isQuickConnectEnabled('https://emby.example.com'), isFalse);
|
|
expect(paths, isEmpty);
|
|
});
|
|
|
|
test('initiating Quick Connect rejects locally without an Emby request', () async {
|
|
final paths = <String>[];
|
|
final svc = _service(
|
|
dialect: MediaBrowserDialect.emby,
|
|
handler: (req) {
|
|
paths.add(req.url.path);
|
|
expect(req.url.path, isNot(startsWith('/QuickConnect/')));
|
|
return _status(404);
|
|
},
|
|
);
|
|
|
|
final error = await _captureError(
|
|
svc.initiateQuickConnect(baseUrl: 'https://emby.example.com', deviceId: 'dev-xyz'),
|
|
);
|
|
|
|
expect(
|
|
error,
|
|
isA<MediaServerAuthException>()
|
|
.having((exception) => exception.message, 'message', 'Quick Connect rejected by server')
|
|
.having((exception) => exception.statusCode, 'statusCode', isNull),
|
|
);
|
|
expect(paths, isEmpty);
|
|
});
|
|
|
|
test('authenticating by Quick Connect rejects locally without an Emby request', () async {
|
|
final paths = <String>[];
|
|
final svc = _service(
|
|
dialect: MediaBrowserDialect.emby,
|
|
handler: (req) {
|
|
paths.add(req.url.path);
|
|
expect(req.url.path, isNot(startsWith('/QuickConnect/')));
|
|
return _status(404);
|
|
},
|
|
);
|
|
|
|
final error = await _captureError(
|
|
svc.authenticateByQuickConnect(
|
|
baseUrl: 'https://emby.example.com',
|
|
secret: 'quick-secret',
|
|
deviceId: 'dev-xyz',
|
|
),
|
|
);
|
|
|
|
expect(
|
|
error,
|
|
isA<MediaServerAuthException>()
|
|
.having((exception) => exception.message, 'message', 'Quick Connect rejected by server')
|
|
.having((exception) => exception.statusCode, 'statusCode', isNull),
|
|
);
|
|
expect(paths, isEmpty);
|
|
});
|
|
|
|
test('password authentication builds an Emby-persisted connection discriminator', () async {
|
|
final svc = _service(
|
|
dialect: MediaBrowserDialect.emby,
|
|
handler: (req) {
|
|
expect(req.url.path, '/Users/AuthenticateByName');
|
|
return _ok({
|
|
'AccessToken': 'tok-new',
|
|
'User': {'Id': 'user-7', 'Name': 'edde'},
|
|
});
|
|
},
|
|
);
|
|
|
|
final connection = await svc.authenticateByName(
|
|
baseUrl: 'https://emby.example.com',
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: 'dev-xyz',
|
|
serverInfo: _serverInfo,
|
|
);
|
|
|
|
expect(connection.dialect, MediaBrowserDialect.emby);
|
|
expect(connection.kind, ConnectionKind.emby);
|
|
expect(connection.kind.id, 'emby');
|
|
});
|
|
|
|
test('detected server dialect overrides the picker and an unknown response preserves it', () async {
|
|
Future<JellyfinConnection> authenticate(Map<String, Object?> publicInfo) {
|
|
final svc = _service(
|
|
handler: (req) {
|
|
if (req.url.path == '/System/Info/Public') return _ok(publicInfo);
|
|
if (req.url.path == '/Users/AuthenticateByName') {
|
|
return _ok({
|
|
'AccessToken': 'tok-new',
|
|
'User': {'Id': 'user-7', 'Name': 'edde'},
|
|
});
|
|
}
|
|
return _status(404);
|
|
},
|
|
);
|
|
return svc.authenticateByName(
|
|
baseUrl: 'https://server.example.com',
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: 'dev-xyz',
|
|
);
|
|
}
|
|
|
|
final detected = await authenticate({
|
|
'LocalAddresses': <String>[],
|
|
'RemoteAddresses': <String>[],
|
|
'ServerName': 'Emby Home',
|
|
'Version': '4.9.5.0',
|
|
'Id': 'emby-server',
|
|
});
|
|
final unknown = await authenticate({'ServerName': 'Unknown Home', 'Id': 'unknown-server', 'Version': '4.9.5.0'});
|
|
|
|
expect(detected.dialect, MediaBrowserDialect.emby);
|
|
expect(detected.kind, ConnectionKind.emby);
|
|
expect(unknown.dialect, MediaBrowserDialect.jellyfin);
|
|
expect(unknown.kind, ConnectionKind.jellyfin);
|
|
});
|
|
|
|
test('password authentication and logout remain wire-identical to Jellyfin', () async {
|
|
Future<List<(String, String, String)>> capture(MediaBrowserDialect dialect) async {
|
|
final requests = <(String, String, String)>[];
|
|
final svc = _service(
|
|
dialect: dialect,
|
|
handler: (req) {
|
|
final request = req as http.Request;
|
|
requests.add((request.method, request.url.path, request.body));
|
|
if (request.url.path == '/Users/AuthenticateByName') {
|
|
return _ok({
|
|
'AccessToken': 'tok-new',
|
|
'User': {'Id': 'user-7', 'Name': 'edde'},
|
|
});
|
|
}
|
|
if (request.url.path == '/Sessions/Logout') return _ok({});
|
|
return _status(404);
|
|
},
|
|
);
|
|
final connection = await svc.authenticateByName(
|
|
baseUrl: 'https://server.example.com',
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: 'dev-xyz',
|
|
serverInfo: _serverInfo,
|
|
);
|
|
await svc.signOut(connection);
|
|
return requests;
|
|
}
|
|
|
|
final jellyfinRequests = await capture(MediaBrowserDialect.jellyfin);
|
|
final embyRequests = await capture(MediaBrowserDialect.emby);
|
|
final expected = <(String, String, String)>[
|
|
('POST', '/Users/AuthenticateByName', '{"Username":"edde","Pw":"pw"}'),
|
|
('POST', '/Sessions/Logout', ''),
|
|
];
|
|
|
|
expect(jellyfinRequests, expected);
|
|
expect(embyRequests, expected);
|
|
expect(embyRequests, jellyfinRequests);
|
|
});
|
|
});
|
|
|
|
group('Jellyfin authentication request identity', () {
|
|
test('password login sends the complete MediaBrowser header', () async {
|
|
late http.BaseRequest request;
|
|
final svc = _service(
|
|
handler: (captured) {
|
|
request = captured;
|
|
return _ok({
|
|
'AccessToken': 'tok-new',
|
|
'User': {'Id': 'user-7', 'Name': 'edde'},
|
|
});
|
|
},
|
|
);
|
|
|
|
await svc.authenticateByName(
|
|
baseUrl: 'https://jf.example.com',
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: 'dev-xyz',
|
|
serverInfo: _serverInfo,
|
|
);
|
|
|
|
expect(request.method, 'POST');
|
|
expect(
|
|
request.headers['authorization'],
|
|
'MediaBrowser Client="Plezy", Device="TestDevice", DeviceId="dev-xyz", Version="test"',
|
|
);
|
|
expect(request.headers['content-type'], 'application/json');
|
|
});
|
|
|
|
test('Quick Connect sends the same complete MediaBrowser header', () async {
|
|
late http.BaseRequest request;
|
|
final svc = _service(
|
|
handler: (captured) {
|
|
request = captured;
|
|
return _ok({'Code': 'ABCDE', 'Secret': 'sec-xyz'});
|
|
},
|
|
);
|
|
|
|
await svc.initiateQuickConnect(baseUrl: 'https://jf.example.com', deviceId: 'dev-xyz');
|
|
|
|
expect(request.method, 'GET');
|
|
expect(
|
|
request.headers['authorization'],
|
|
'MediaBrowser Client="Plezy", Device="TestDevice", DeviceId="dev-xyz", Version="test"',
|
|
);
|
|
});
|
|
|
|
test('rejects an empty device ID before sending a request', () async {
|
|
var requests = 0;
|
|
final svc = _service(
|
|
handler: (_) {
|
|
requests++;
|
|
return _status(500);
|
|
},
|
|
);
|
|
|
|
await expectLater(
|
|
svc.authenticateByName(
|
|
baseUrl: 'https://jf.example.com',
|
|
username: 'edde',
|
|
password: 'pw',
|
|
deviceId: '',
|
|
serverInfo: _serverInfo,
|
|
),
|
|
throwsArgumentError,
|
|
);
|
|
expect(requests, 0);
|
|
});
|
|
});
|
|
}
|