feat(profiles): show the first linked connection's user picture

A local profile had no picture of its own and always fell back to
initials. It now borrows the user picture of the connection it was
linked to first — oldest Connection.createdAt, ties broken by
connection id, since the join table carries no creation time.

Jellyfin links resolve to /Users/{id}/Images/Primary, keyed by the
PrimaryImageTag now captured at authentication and refreshed from the
/Users/Me body checkHealth already fetches. That endpoint is anonymous
on every Jellyfin release, so the URL carries no api_key and the access
token stays out of the image cache key. Plex links resolve the Home
user the link points at against PlexHomeService's live cache, so no
account-level lookup is needed and the picture tracks Plex's own
refresh.

The picture is derived per snapshot and never written back onto a
Profile: ProfileDetailScreen upserts the model it holds, so a
persisted URL would go stale and outlive the connection it came from.
Plex Home profiles are untouched, including one whose Plex avatar is
unset — it keeps its initials rather than borrowing a lent connection's
picture.

close #1667
This commit is contained in:
edde746
2026-08-04 02:22:44 +02:00
parent 2b4875d389
commit 860ce1e11a
32 changed files with 1469 additions and 46 deletions
@@ -62,6 +62,58 @@ void main() {
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',
@@ -99,6 +151,32 @@ void main() {
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.kind, ConnectionKind.jellyfin);
expect(base.backend, MediaBackend.jellyfin);
@@ -49,6 +49,7 @@ void main() {
registry: profileRegistry,
plexHome: plexHome,
connections: connectionRegistry,
profileConnections: profileConnectionRegistry,
storage: storage,
);
final serverManager = MultiServerManager();
@@ -71,6 +71,7 @@ void main() {
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
manager = MultiServerManager();
+161 -4
View File
@@ -9,6 +9,7 @@ import 'package:plezy/models/plex/plex_home_user.dart';
import 'package:plezy/profiles/active_profile_provider.dart';
import 'package:plezy/profiles/plex_home_service.dart';
import 'package:plezy/profiles/profile.dart';
import 'package:plezy/profiles/profile_connection.dart';
import 'package:plezy/profiles/profile_connection_registry.dart';
import 'package:plezy/profiles/profile_registry.dart';
import 'package:plezy/services/storage_service.dart';
@@ -78,12 +79,12 @@ final class _RecordingPreferencesPlatform extends SharedPreferencesAsyncPlatform
delegate.getKeys(parameters, options);
}
PlexHomeUser _homeUser(String uuid, {String name = 'Home User'}) {
PlexHomeUser _homeUser(String uuid, {int id = 1, String name = 'Home User', String thumb = ''}) {
return PlexHomeUser(
id: 1,
id: id,
uuid: uuid,
title: name,
thumb: '',
thumb: thumb,
hasPassword: false,
restricted: false,
updatedAt: null,
@@ -103,10 +104,26 @@ PlexAccountConnection _account(String id) {
);
}
JellyfinConnection _jellyfin(String id, {required DateTime createdAt, required String primaryImageTag}) {
return JellyfinConnection(
id: id,
baseUrl: 'https://jellyfin.example',
serverName: 'Jellyfin',
serverMachineId: 'machine-$id',
userId: 'user-$id',
userName: 'User $id',
accessToken: 'token-$id',
deviceId: 'device-$id',
primaryImageTag: primaryImageTag,
createdAt: createdAt,
);
}
void main() {
late AppDatabase db;
late ProfileRegistry registry;
late ConnectionRegistry connections;
late ProfileConnectionRegistry profileConnections;
late PlexHomeService plexHome;
late ActiveProfileProvider provider;
late StorageService storage;
@@ -122,9 +139,10 @@ void main() {
connections = ConnectionRegistry(db);
storage = await StorageService.getInstance();
fetchedHomeUsers = const [];
profileConnections = ProfileConnectionRegistry(db);
plexHome = PlexHomeService(
connections: connections,
profileConnections: ProfileConnectionRegistry(db),
profileConnections: profileConnections,
storage: storage,
plexHomeUserFetcher: (_) async => fetchedHomeUsers,
);
@@ -132,6 +150,7 @@ void main() {
registry: registry,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
});
@@ -219,6 +238,144 @@ void main() {
expect(notifications, 0);
});
group('avatarUrlFor', () {
test('returns the linked Jellyfin user picture after initialize', () async {
final profile = Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1));
final connection = _jellyfin('first', createdAt: DateTime(2025, 1, 1), primaryImageTag: 'avatar-tag');
await registry.upsert(profile);
await connections.upsert(connection);
await profileConnections.upsert(
const ProfileConnection(profileId: 'p1', connectionId: 'first', userIdentifier: 'user-first'),
);
await provider.initialize();
expect(
provider.avatarUrlFor(profile.id),
'https://jellyfin.example/Users/user-first/Images/Primary'
'?tag=avatar-tag&maxWidth=240&maxHeight=240',
);
});
test('returns null for profiles without links and unknown profile ids', () async {
await registry.upsert(Profile.local(id: 'unlinked', displayName: 'Owner', createdAt: DateTime(2026, 1, 1)));
await provider.initialize();
expect(provider.avatarUrlFor('unlinked'), isNull);
expect(provider.avatarUrlFor('unknown'), isNull);
});
test('linking an older connection updates the selected picture', () async {
final profile = Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1));
final newer = _jellyfin('newer', createdAt: DateTime(2026, 1, 2), primaryImageTag: 'newer-tag');
final older = _jellyfin('older', createdAt: DateTime(2025, 12, 31), primaryImageTag: 'older-tag');
await registry.upsert(profile);
await connections.upsert(newer);
await connections.upsert(older);
await profileConnections.upsert(
const ProfileConnection(profileId: 'p1', connectionId: 'newer', userIdentifier: 'user-newer'),
);
await provider.initialize();
expect(
provider.avatarUrlFor(profile.id),
'https://jellyfin.example/Users/user-newer/Images/Primary'
'?tag=newer-tag&maxWidth=240&maxHeight=240',
);
final changed = Completer<void>();
void listener() {
if (provider.avatarUrlFor(profile.id)?.contains('older-tag') ?? false) {
if (!changed.isCompleted) changed.complete();
}
}
provider.addListener(listener);
addTearDown(() => provider.removeListener(listener));
await profileConnections.upsert(
const ProfileConnection(profileId: 'p1', connectionId: 'older', userIdentifier: 'user-older'),
);
await changed.future.timeout(const Duration(seconds: 2));
expect(
provider.avatarUrlFor(profile.id),
'https://jellyfin.example/Users/user-older/Images/Primary'
'?tag=older-tag&maxWidth=240&maxHeight=240',
);
});
test('token and timestamp churn on a link does not notify listeners', () async {
await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1)));
await connections.upsert(_jellyfin('jellyfin', createdAt: DateTime(2025, 1, 1), primaryImageTag: 'avatar-tag'));
await profileConnections.upsert(
const ProfileConnection(
profileId: 'p1',
connectionId: 'jellyfin',
userToken: 'initial-token',
userIdentifier: 'user-jellyfin',
),
);
await provider.initialize();
var notifications = 0;
void listener() => notifications++;
provider.addListener(listener);
addTearDown(() => provider.removeListener(listener));
final churnObserved = Completer<void>();
final rowSubscription = profileConnections.watchAll().listen((rows) {
final row = rows.single;
if (row.userToken == 'refreshed-token' && row.tokenAcquiredAt != null && !churnObserved.isCompleted) {
churnObserved.complete();
}
});
addTearDown(rowSubscription.cancel);
await profileConnections.recordToken('p1', 'jellyfin', 'refreshed-token');
await churnObserved.future.timeout(const Duration(seconds: 2));
await Future<void>(() {});
expect(notifications, 0);
});
test('changing a Plex link user changes the picture and notifies listeners', () async {
final profile = Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1));
final account = _account('plex.acct');
final firstUser = _homeUser('home-1', thumb: 'https://images.example/first.jpg');
final secondUser = _homeUser('home-2', id: 2, thumb: 'https://images.example/second.jpg');
fetchedHomeUsers = [firstUser, secondUser];
await registry.upsert(profile);
await connections.upsert(account);
await profileConnections.upsert(
const ProfileConnection(profileId: 'p1', connectionId: 'plex.acct', userIdentifier: 'home-1'),
);
expect(await plexHome.refresh(account), isTrue);
await provider.initialize();
expect(provider.avatarUrlFor(profile.id), firstUser.thumb);
var notifications = 0;
final changed = Completer<void>();
void listener() {
notifications++;
if (provider.avatarUrlFor(profile.id) == secondUser.thumb && !changed.isCompleted) {
changed.complete();
}
}
provider.addListener(listener);
addTearDown(() => provider.removeListener(listener));
await profileConnections.upsert(
const ProfileConnection(profileId: 'p1', connectionId: 'plex.acct', userIdentifier: 'home-2'),
);
await changed.future.timeout(const Duration(seconds: 2));
expect(provider.avatarUrlFor(profile.id), secondUser.thumb);
expect(notifications, greaterThan(0));
});
});
test('initialize resolves the stored active profile id', () async {
await registry.upsert(Profile.local(id: 'p1', displayName: 'Owner', createdAt: DateTime(2026, 1, 1)));
await registry.upsert(Profile.local(id: 'p2', displayName: 'Kids', createdAt: DateTime(2026, 1, 2)));
@@ -118,6 +118,7 @@ class _ThrowingActiveProfileProvider extends ActiveProfileProvider {
required super.registry,
required super.plexHome,
required super.connections,
required super.profileConnections,
required super.storage,
super.activeProfileIdWriter,
});
@@ -515,6 +516,7 @@ void main() {
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
activeProfileIdWriter: writer,
);
@@ -623,6 +625,7 @@ Future<_Harness> _pumpHarness(
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
activeProfileIdWriter: gateOwnerRestoreWrite || failNewerIdentityWrite ? activeProfileIdWriter : null,
);
@@ -0,0 +1,266 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:plezy/connection/connection.dart';
import 'package:plezy/models/plex/plex_home_user.dart';
import 'package:plezy/profiles/profile.dart';
import 'package:plezy/profiles/profile_avatar_source.dart';
import 'package:plezy/profiles/profile_connection.dart';
JellyfinConnection _jellyfin(
String id, {
required DateTime createdAt,
String? primaryImageTag,
String userId = 'jf-user',
String baseUrl = 'https://jelly.example',
}) {
return JellyfinConnection(
id: id,
baseUrl: baseUrl,
serverName: 'Jelly',
serverMachineId: 'machine-$id',
userId: userId,
userName: 'Agent',
accessToken: 'secret-token',
deviceId: 'device-1',
primaryImageTag: primaryImageTag,
createdAt: createdAt,
);
}
PlexAccountConnection _plex(String id, {required DateTime createdAt}) {
return PlexAccountConnection(
id: id,
accountToken: 'token-$id',
clientIdentifier: 'client-$id',
accountLabel: 'Plex',
createdAt: createdAt,
);
}
PlexHomeUser _homeUser(String uuid, {String thumb = ''}) {
return PlexHomeUser(
id: 1,
uuid: uuid,
title: 'Home $uuid',
thumb: thumb,
hasPassword: false,
restricted: false,
updatedAt: null,
admin: false,
guest: false,
protected: false,
);
}
ProfileConnection _link(String connectionId, {String profileId = 'local-1', String userIdentifier = 'jf-user'}) {
return ProfileConnection(profileId: profileId, connectionId: connectionId, userIdentifier: userIdentifier);
}
Profile _local([String id = 'local-1']) => Profile.local(id: id, displayName: 'Owner', createdAt: DateTime(2026, 1, 1));
String? _resolve({
required List<Profile> profiles,
required Map<String, List<ProfileConnection>> links,
required Map<String, Connection> connections,
Map<String, List<PlexHomeUser>> plexHome = const {},
String profileId = 'local-1',
}) {
return resolveProfileAvatarUrls(
profiles: profiles,
connectionsByProfile: links,
connectionsById: connections,
plexHomeByConnectionId: plexHome,
)[profileId];
}
void main() {
group('resolveProfileAvatarUrls', () {
test('uses the picture of the oldest linked connection', () {
final older = _jellyfin('jf-older', createdAt: DateTime(2026, 1, 1), primaryImageTag: 'older-tag');
final newer = _jellyfin('jf-newer', createdAt: DateTime(2026, 6, 1), primaryImageTag: 'newer-tag');
final url = _resolve(
profiles: [_local()],
// Deliberately newest-first: the registry stream has no ordering
// guarantee, so resolution must sort rather than take the head.
links: {
'local-1': [_link('jf-newer'), _link('jf-older')],
},
connections: {'jf-older': older, 'jf-newer': newer},
);
expect(url, contains('tag=older-tag'));
});
test('falls back to initials when the first connection has no picture', () {
final first = _jellyfin('jf-first', createdAt: DateTime(2026, 1, 1));
final second = _jellyfin('jf-second', createdAt: DateTime(2026, 6, 1), primaryImageTag: 'second-tag');
final url = _resolve(
profiles: [_local()],
links: {
'local-1': [_link('jf-first'), _link('jf-second')],
},
connections: {'jf-first': first, 'jf-second': second},
);
// "First wins" is literal: we do not skip ahead to a later connection
// that happens to have an image.
expect(url, isNull);
});
test('breaks a createdAt tie on connection id so the choice is stable', () {
final sameInstant = DateTime(2026, 1, 1);
final b = _jellyfin('jf-b', createdAt: sameInstant, primaryImageTag: 'b-tag');
final a = _jellyfin('jf-a', createdAt: sameInstant, primaryImageTag: 'a-tag');
final url = _resolve(
profiles: [_local()],
links: {
'local-1': [_link('jf-b'), _link('jf-a')],
},
connections: {'jf-b': b, 'jf-a': a},
);
expect(url, contains('tag=a-tag'));
});
test('ignores links whose connection is gone, including for ordering', () {
final survivor = _jellyfin('jf-survivor', createdAt: DateTime(2026, 6, 1), primaryImageTag: 'survivor-tag');
final url = _resolve(
profiles: [_local()],
links: {
'local-1': [_link('jf-removed'), _link('jf-survivor')],
},
connections: {'jf-survivor': survivor},
);
expect(url, contains('tag=survivor-tag'));
});
test('resolves a Plex link through the home user the link points at', () {
final plex = _plex('plex-1', createdAt: DateTime(2026, 1, 1));
final url = _resolve(
profiles: [_local()],
links: {
'local-1': [_link('plex-1', userIdentifier: 'home-b')],
},
connections: {'plex-1': plex},
plexHome: {
'plex-1': [
_homeUser('home-a', thumb: 'https://plex.tv/users/home-a/avatar'),
_homeUser('home-b', thumb: 'https://plex.tv/users/home-b/avatar'),
],
},
);
expect(url, 'https://plex.tv/users/home-b/avatar');
});
test('gives no picture for a Plex link with no home user selected', () {
final plex = _plex('plex-1', createdAt: DateTime(2026, 1, 1));
final url = _resolve(
profiles: [_local()],
links: {
'local-1': [_link('plex-1', userIdentifier: '')],
},
connections: {'plex-1': plex},
plexHome: {
'plex-1': [_homeUser('home-a', thumb: 'https://plex.tv/users/home-a/avatar')],
},
);
expect(url, isNull);
});
test('gives no picture when the selected home user has a blank thumb', () {
final plex = _plex('plex-1', createdAt: DateTime(2026, 1, 1));
final url = _resolve(
profiles: [_local()],
links: {
'local-1': [_link('plex-1', userIdentifier: 'home-a')],
},
connections: {'plex-1': plex},
plexHome: {
'plex-1': [_homeUser('home-a')],
},
);
expect(url, isNull);
});
test('mixed Jellyfin and Plex links still resolve by creation order', () {
final plexFirst = _plex('plex-1', createdAt: DateTime(2026, 1, 1));
final jellyfinSecond = _jellyfin('jf-1', createdAt: DateTime(2026, 6, 1), primaryImageTag: 'jf-tag');
final url = _resolve(
profiles: [_local()],
links: {
'local-1': [_link('jf-1'), _link('plex-1', userIdentifier: 'home-a')],
},
connections: {'plex-1': plexFirst, 'jf-1': jellyfinSecond},
plexHome: {
'plex-1': [_homeUser('home-a', thumb: 'https://plex.tv/users/home-a/avatar')],
},
);
expect(url, 'https://plex.tv/users/home-a/avatar');
});
test('leaves a Plex Home profile on its own thumb', () {
final plexHomeProfile = Profile.virtualPlexHome(
connectionId: 'plex-1',
homeUser: _homeUser('home-a', thumb: 'https://plex.tv/users/home-a/avatar'),
);
final borrowed = _jellyfin('jf-1', createdAt: DateTime(2026, 1, 1), primaryImageTag: 'jf-tag');
final url = _resolve(
profiles: [plexHomeProfile],
links: {
plexHomeProfile.id: [_link('jf-1', profileId: plexHomeProfile.id)],
},
connections: {'jf-1': borrowed},
profileId: plexHomeProfile.id,
);
expect(url, 'https://plex.tv/users/home-a/avatar');
});
test('a Plex Home profile with no avatar keeps its initials rather than borrowing one', () {
final plexHomeProfile = Profile.virtualPlexHome(connectionId: 'plex-1', homeUser: _homeUser('home-a'));
final borrowed = _jellyfin('jf-1', createdAt: DateTime(2026, 1, 1), primaryImageTag: 'jf-tag');
final url = _resolve(
profiles: [plexHomeProfile],
links: {
plexHomeProfile.id: [_link('jf-1', profileId: plexHomeProfile.id)],
},
connections: {'jf-1': borrowed},
profileId: plexHomeProfile.id,
);
// Plex owns this identity end to end; "nothing changes" for Plex Home
// profiles means a blank thumb stays blank, not that it picks up the
// picture of a lent connection.
expect(url, isNull);
});
test('gives no picture to a profile with no links', () {
expect(_resolve(profiles: [_local()], links: const {}, connections: const {}), isNull);
});
test('covers every profile so callers can look up by id', () {
final map = resolveProfileAvatarUrls(
profiles: [_local('local-1'), _local('local-2')],
connectionsByProfile: const {},
connectionsById: const {},
plexHomeByConnectionId: const {},
);
expect(map.keys, containsAll(['local-1', 'local-2']));
});
});
}
+132
View File
@@ -0,0 +1,132 @@
import 'package:cached_network_image_ce/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:plezy/profiles/profile.dart';
import 'package:plezy/profiles/profile_avatar.dart';
import 'package:plezy/utils/initials_palette.dart';
void main() {
Future<void> pumpAvatar(
WidgetTester tester, {
required Profile profile,
String? avatarUrl,
double size = 40,
double devicePixelRatio = 1,
}) {
return tester.pumpWidget(
MaterialApp(
theme: ThemeData(),
home: MediaQuery(
data: MediaQueryData(devicePixelRatio: devicePixelRatio),
child: Center(
child: ProfileAvatar(profile: profile, avatarUrl: avatarUrl, size: size),
),
),
),
);
}
Profile localProfile({String? avatarThumbUrl, String? pinHash}) {
return Profile.local(
id: 'local-owner',
displayName: 'Owner',
avatarThumbUrl: avatarThumbUrl,
pinHash: pinHash,
createdAt: DateTime(2026, 1, 1),
);
}
testWidgets('avatarUrl renders the derived network image', (tester) async {
const avatarUrl = 'https://jellyfin.example/Users/user-1/Images/Primary?tag=derived';
await pumpAvatar(tester, profile: localProfile(), avatarUrl: avatarUrl);
final image = tester.widget<CachedNetworkImage>(find.byType(CachedNetworkImage));
expect(image.imageUrl, avatarUrl);
});
testWidgets('avatarUrl takes precedence over the profile thumbnail', (tester) async {
const derivedUrl = 'https://jellyfin.example/Users/user-1/Images/Primary?tag=derived';
const profileThumbUrl = 'https://plex.example/profile-thumb.jpg';
await pumpAvatar(
tester,
profile: localProfile(avatarThumbUrl: profileThumbUrl),
avatarUrl: derivedUrl,
);
final image = tester.widget<CachedNetworkImage>(find.byType(CachedNetworkImage));
expect(image.imageUrl, derivedUrl);
});
testWidgets('a null avatarUrl preserves the profile thumbnail fallback', (tester) async {
const profileThumbUrl = 'https://plex.example/profile-thumb.jpg';
await pumpAvatar(tester, profile: localProfile(avatarThumbUrl: profileThumbUrl));
final image = tester.widget<CachedNetworkImage>(find.byType(CachedNetworkImage));
expect(image.imageUrl, profileThumbUrl);
});
testWidgets('a profile without a picture renders its display-name initial', (tester) async {
final profile = localProfile();
await pumpAvatar(tester, profile: profile);
expect(find.byType(CachedNetworkImage), findsNothing);
expect(find.text(initialOf(profile.displayName)), findsOneWidget);
});
testWidgets('an empty avatarUrl falls through to the profile picture rather than suppressing it', (tester) async {
const plexThumb = 'https://plex.tv/users/abc/avatar';
// An empty override means "nothing derived". Treating it as a value would
// blank out a Plex Home profile that owns a perfectly good thumb.
await pumpAvatar(
tester,
profile: localProfile(avatarThumbUrl: plexThumb),
avatarUrl: '',
);
expect(tester.widget<CachedNetworkImage>(find.byType(CachedNetworkImage)).imageUrl, plexThumb);
});
testWidgets('an empty avatarUrl renders initials instead of requesting an empty URL', (tester) async {
final profile = localProfile();
await pumpAvatar(tester, profile: profile, avatarUrl: '');
expect(find.byType(CachedNetworkImage), findsNothing);
expect(find.text(initialOf(profile.displayName)), findsOneWidget);
});
testWidgets('network image decoding is bounded by the physical avatar size', (tester) async {
const size = 44.0;
const devicePixelRatio = 2.5;
await pumpAvatar(
tester,
profile: localProfile(),
avatarUrl: 'https://jellyfin.example/Users/user-1/Images/Primary?tag=large-original',
size: size,
devicePixelRatio: devicePixelRatio,
);
final image = tester.widget<CachedNetworkImage>(find.byType(CachedNetworkImage));
final expectedDecodeSize = (size * devicePixelRatio).round();
expect(image.memCacheWidth, expectedDecodeSize);
expect(image.memCacheHeight, expectedDecodeSize);
});
testWidgets('a derived avatar keeps the PIN lock badge visible', (tester) async {
await pumpAvatar(
tester,
profile: localProfile(pinHash: 'stored-pin-hash'),
avatarUrl: 'https://jellyfin.example/Users/user-1/Images/Primary?tag=derived',
);
expect(find.byType(CachedNetworkImage), findsOneWidget);
expect(find.byIcon(Symbols.lock_rounded), findsOneWidget);
});
}
+80
View File
@@ -1,8 +1,13 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:plezy/connection/connection.dart';
import 'package:plezy/models/plex/plex_home_user.dart';
import 'package:plezy/profiles/profile.dart';
import 'package:plezy/profiles/profile_connection.dart';
import 'package:plezy/profiles/profiles_view.dart';
import '../test_helpers/prefs.dart';
import '../test_helpers/profile_stack.dart';
void main() {
group('visibleProfileConnections', () {
test('keeps all local profile connection rows', () {
@@ -33,4 +38,79 @@ void main() {
expect(visible.single.connectionId, 'jellyfin-1');
});
});
group('avatarUrlByProfile', () {
late ProfileStack stack;
setUp(() async {
resetSharedPreferencesForTest();
stack = await ProfileStack.create(
homeUsers: [
PlexHomeUser(
id: 1,
uuid: 'home-user',
title: 'Home User',
thumb: 'https://images.example/home.jpg',
hasPassword: false,
restricted: false,
updatedAt: null,
admin: true,
guest: false,
protected: false,
),
],
);
});
tearDown(() => stack.dispose());
test('maps linked pictures, unlinked initials, and Plex Home pictures', () async {
final linked = Profile.local(id: 'linked', displayName: 'Linked', createdAt: DateTime(2026, 1, 1));
final unlinked = Profile.local(id: 'unlinked', displayName: 'Unlinked', createdAt: DateTime(2026, 1, 2));
final jellyfin = JellyfinConnection(
id: 'jellyfin',
baseUrl: 'https://jellyfin.example',
serverName: 'Jellyfin',
serverMachineId: 'machine-id',
userId: 'jellyfin-user',
userName: 'Jellyfin User',
accessToken: 'token',
deviceId: 'device-id',
primaryImageTag: 'image-tag',
createdAt: DateTime(2025, 1, 1),
);
final plex = PlexAccountConnection(
id: 'plex',
accountToken: 'account-token',
clientIdentifier: 'client-id',
accountLabel: 'Plex',
createdAt: DateTime(2025, 1, 2),
);
await stack.profiles.upsert(linked);
await stack.profiles.upsert(unlinked);
await stack.connections.upsert(jellyfin);
await stack.connections.upsert(plex);
await stack.profileConnections.upsert(
const ProfileConnection(profileId: 'linked', connectionId: 'jellyfin', userIdentifier: 'jellyfin-user'),
);
expect(await stack.plexHome.refresh(plex), isTrue);
final view = await watchProfilesView(
profiles: stack.profiles,
profileConnections: stack.profileConnections,
connections: stack.connections,
plexHome: stack.plexHome,
storage: stack.storage,
).first.timeout(const Duration(seconds: 2));
final plexHomeId = plexHomeProfileId(accountConnectionId: plex.id, homeUserUuid: 'home-user');
expect(
view.avatarUrlByProfile[linked.id],
'https://jellyfin.example/Users/jellyfin-user/Images/Primary'
'?tag=image-tag&maxWidth=240&maxHeight=240',
);
expect(view.avatarUrlByProfile[unlinked.id], isNull);
expect(view.avatarUrlByProfile[plexHomeId], 'https://images.example/home.jpg');
});
});
}
+3
View File
@@ -104,6 +104,7 @@ void main() {
registry: profileRegistry,
plexHome: plexHome,
connections: connectionRegistry,
profileConnections: profileConnectionRegistry,
storage: storage,
);
final discoverProvider = DiscoverProvider(
@@ -295,6 +296,7 @@ void main() {
registry: profileRegistry,
plexHome: plexHome,
connections: connectionRegistry,
profileConnections: profileConnectionRegistry,
storage: storage,
);
final discoverProvider = DiscoverProvider(
@@ -406,6 +408,7 @@ void main() {
registry: profileRegistry,
plexHome: plexHome,
connections: connectionRegistry,
profileConnections: profileConnectionRegistry,
storage: storage,
);
final discoverProvider = DiscoverProvider(
@@ -7,6 +7,7 @@ import 'package:plezy/connection/connection_registry.dart';
import 'package:plezy/database/app_database.dart';
import 'package:plezy/focus/input_mode_tracker.dart';
import 'package:plezy/i18n/strings.g.dart';
import 'package:plezy/profiles/active_profile_provider.dart';
import 'package:plezy/profiles/plex_home_service.dart';
import 'package:plezy/profiles/profile.dart';
import 'package:plezy/profiles/profile_connection.dart';
@@ -49,7 +50,19 @@ void main() {
storage: storage,
plexHomeUserFetcher: (_) async => const [],
);
// The screen reads its avatar through this provider, exactly as it does
// under the app-lifetime scope in main.dart. Left uninitialized: this test
// is about TV back handling, and an idle provider yields no avatar without
// opening stream subscriptions the test would have to settle.
final activeProfile = ActiveProfileProvider(
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
addTearDown(() async {
activeProfile.dispose();
await plexHome.dispose();
await db.close();
});
@@ -62,6 +75,7 @@ void main() {
Provider<ProfileConnectionRegistry>.value(value: profileConnections),
Provider<ConnectionRegistry>.value(value: connections),
Provider<PlexHomeService>.value(value: plexHome),
ChangeNotifierProvider<ActiveProfileProvider>.value(value: activeProfile),
],
child: InputModeTracker(
child: MaterialApp(
@@ -9,6 +9,7 @@ import 'package:plezy/i18n/strings.g.dart';
import 'package:plezy/profiles/active_profile_provider.dart';
import 'package:plezy/profiles/plex_home_service.dart';
import 'package:plezy/profiles/profile.dart';
import 'package:plezy/profiles/profile_avatar.dart';
import 'package:plezy/profiles/profile_connection.dart';
import 'package:plezy/profiles/profile_connection_registry.dart';
import 'package:plezy/profiles/profile_registry.dart';
@@ -44,6 +45,7 @@ void main() {
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
addTearDown(() async {
@@ -106,6 +108,7 @@ void main() {
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
addTearDown(() async {
@@ -132,6 +135,87 @@ void main() {
expect(tester.getTopLeft(find.text('Kids')).dy, lessThan(tester.getTopLeft(find.text('Owner')).dy));
});
testWidgets('passes derived Jellyfin avatar URLs only to linked profile tiles', (tester) async {
final db = AppDatabase.forTesting(NativeDatabase.memory());
final linkedProfile = Profile.local(id: 'local-linked', displayName: 'Linked', createdAt: DateTime(2026, 1, 1));
final unlinkedProfile = Profile.local(
id: 'local-unlinked',
displayName: 'Unlinked',
createdAt: DateTime(2026, 1, 2),
);
final jellyfin = JellyfinConnection(
id: 'jf-machine/jf-user',
baseUrl: 'https://jellyfin.example',
serverName: 'Jellyfin',
serverMachineId: 'jf-machine',
userId: 'jf-user',
userName: 'Linked',
accessToken: 'secret-token',
deviceId: 'device-1',
primaryImageTag: 'primary-tag',
createdAt: DateTime(2025, 12, 1),
);
final link = ProfileConnection(
profileId: linkedProfile.id,
connectionId: jellyfin.id,
userIdentifier: jellyfin.userId,
);
final profiles = _FakeProfileRegistry(db, [linkedProfile, unlinkedProfile]);
final connections = _FakeConnectionRegistry(db, [jellyfin]);
final profileConnections = _FakeProfileConnectionRegistry(db, [link]);
final storage = await StorageService.getInstance();
final plexHome = PlexHomeService(
connections: connections,
profileConnections: profileConnections,
storage: storage,
plexHomeUserFetcher: (_) async => const [],
);
final activeProfile = ActiveProfileProvider(
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
addTearDown(() async {
activeProfile.dispose();
await plexHome.dispose();
await db.close();
});
await tester.pumpWidget(
TranslationProvider(
child: MultiProvider(
providers: [
Provider<ProfileRegistry>.value(value: profiles),
Provider<ProfileConnectionRegistry>.value(value: profileConnections),
Provider<ConnectionRegistry>.value(value: connections),
Provider<PlexHomeService>.value(value: plexHome),
ChangeNotifierProvider<ActiveProfileProvider>.value(value: activeProfile),
],
child: MaterialApp(theme: monoTheme(dark: true), home: const ProfileSwitchScreen()),
),
),
);
await tester.pumpAndSettle();
final linkedAvatar = tester.widget<ProfileAvatar>(
find.byWidgetPredicate((widget) => widget is ProfileAvatar && widget.profile?.id == linkedProfile.id),
);
final unlinkedAvatar = tester.widget<ProfileAvatar>(
find.byWidgetPredicate((widget) => widget is ProfileAvatar && widget.profile?.id == unlinkedProfile.id),
);
expect(linkedAvatar.avatarUrl, isNotNull);
expect(
linkedAvatar.avatarUrl,
'https://jellyfin.example/Users/jf-user/Images/Primary?tag=primary-tag&maxWidth=240&maxHeight=240',
);
expect(unlinkedAvatar.avatarUrl, isNull);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
}
class _FakeProfileRegistry extends ProfileRegistry {
@@ -147,18 +231,22 @@ class _FakeProfileRegistry extends ProfileRegistry {
}
class _FakeConnectionRegistry extends ConnectionRegistry {
_FakeConnectionRegistry(super.db);
final List<Connection> _connections;
_FakeConnectionRegistry(super.db, [this._connections = const []]);
@override
Stream<List<Connection>> watchConnections() => Stream.value(const []);
Stream<List<Connection>> watchConnections() => Stream.value(_connections);
@override
Future<List<Connection>> list() async => const [];
Future<List<Connection>> list() async => _connections;
}
class _FakeProfileConnectionRegistry extends ProfileConnectionRegistry {
_FakeProfileConnectionRegistry(super.db);
final List<ProfileConnection> _profileConnections;
_FakeProfileConnectionRegistry(super.db, [this._profileConnections = const []]);
@override
Stream<List<ProfileConnection>> watchAll() => Stream.value(const []);
Stream<List<ProfileConnection>> watchAll() => Stream.value(_profileConnections);
}
@@ -268,6 +268,7 @@ Future<_Harness> _pumpHarness(
registry: profileRegistry,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
final profile = Profile.local(id: 'active', displayName: 'Active', createdAt: DateTime(2026, 1, 1));
@@ -168,6 +168,7 @@ class _NoWatchActiveProfileProvider extends ActiveProfileProvider {
required super.registry,
required super.plexHome,
required super.connections,
required super.profileConnections,
required super.storage,
});
@@ -242,6 +243,7 @@ class _RouteHarness {
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
final manager = _CountingJellyfinManager();
@@ -79,6 +79,7 @@ class _RejectingActiveProfileProvider extends ActiveProfileProvider {
required super.registry,
required super.plexHome,
required super.connections,
required super.profileConnections,
required super.storage,
});
@@ -91,6 +92,7 @@ class _ThrowingActiveProfileProvider extends ActiveProfileProvider {
required super.registry,
required super.plexHome,
required super.connections,
required super.profileConnections,
required super.storage,
});
@@ -184,7 +186,13 @@ void main() {
);
activeProfiles =
activeFactory?.call(profiles, plexHome, connections, storage) ??
ActiveProfileProvider(registry: profiles, plexHome: plexHome, connections: connections, storage: storage);
ActiveProfileProvider(
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
if (initializeActive) await tester.runAsync(activeProfiles.initialize);
await tester.pumpWidget(
MultiProvider(
@@ -347,6 +355,7 @@ void main() {
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
),
);
@@ -388,6 +397,7 @@ void main() {
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
),
);
@@ -642,7 +642,12 @@ Future<_SettingsHarness> _pumpSettingsScreen(
profileConnections: profileConnections,
plexHomeUserFetcher: (_) async => const [],
);
final activeProfile = ActiveProfileProvider(registry: profiles, plexHome: plexHome, connections: connections);
final activeProfile = ActiveProfileProvider(
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
);
final libraries = LibrariesProvider();
final hiddenLibraries = HiddenLibrariesProvider(storageService: _FakeHiddenLibrariesStorage());
await hiddenLibraries.ensureInitialized();
@@ -38,6 +38,27 @@ JellyfinConnectionAuthService _service({required _Handler handler}) {
);
}
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;
@@ -157,6 +178,47 @@ void main() {
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) {
@@ -343,6 +405,36 @@ void main() {
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) {
+51
View File
@@ -697,4 +697,55 @@ void main() {
);
});
});
group('jellyfinUserImageUrl', () {
test('builds an absolute, tag-keyed user image URL', () {
final url = jellyfinUserImageUrl(baseUrl: 'https://jelly.example', userId: 'user-1', tag: 'abc123');
final uri = Uri.parse(url!);
expect(uri.origin, 'https://jelly.example');
expect(uri.path, '/Users/user-1/Images/Primary');
expect(uri.queryParameters['tag'], 'abc123');
});
test('carries no api_key — the user image endpoint is anonymous', () {
final url = jellyfinUserImageUrl(baseUrl: 'https://jelly.example', userId: 'user-1', tag: 'abc123')!;
// Item artwork self-authenticates via api_key; baking the access token
// into an avatar URL would put it in the image cache key for no reason.
expect(url, isNot(contains('api_key')));
expect(url, isNot(contains('secret')));
});
test('returns null when the user has no picture', () {
expect(jellyfinUserImageUrl(baseUrl: 'https://jelly.example', userId: 'user-1', tag: null), isNull);
expect(jellyfinUserImageUrl(baseUrl: 'https://jelly.example', userId: 'user-1', tag: ''), isNull);
});
test('returns null when the connection is missing a base URL or user id', () {
expect(jellyfinUserImageUrl(baseUrl: '', userId: 'user-1', tag: 'abc123'), isNull);
expect(jellyfinUserImageUrl(baseUrl: 'https://jelly.example', userId: '', tag: 'abc123'), isNull);
});
test('joins a base URL that carries a subpath and a trailing slash', () {
final url = jellyfinUserImageUrl(baseUrl: 'https://host.example/jellyfin/', userId: 'user-1', tag: 'abc123');
expect(Uri.parse(url!).path, '/jellyfin/Users/user-1/Images/Primary');
});
test('escapes a user id that would otherwise break the path', () {
final url = jellyfinUserImageUrl(baseUrl: 'https://jelly.example', userId: 'a/b', tag: 'abc123');
expect(Uri.parse(url!).pathSegments, ['Users', 'a/b', 'Images', 'Primary']);
});
test('requests a bounded size for servers that still honour it', () {
final uri = Uri.parse(
jellyfinUserImageUrl(baseUrl: 'https://jelly.example', userId: 'user-1', tag: 'abc123', maxSize: 96)!,
);
expect(uri.queryParameters['maxWidth'], '96');
expect(uri.queryParameters['maxHeight'], '96');
});
});
}
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:plezy/media/ids.dart';
import 'package:plezy/media/media_server_client.dart';
import 'package:drift/native.dart';
import 'package:fake_async/fake_async.dart';
@@ -1016,6 +1017,150 @@ void main() {
expect(persisted.single.isAdministrator, isTrue);
});
test('persists a changed profile picture tag discovered during health checks', () async {
final persisted = <JellyfinConnection>[];
var requestCount = 0;
final client = JellyfinClient.forTesting(
connection: _jellyfinConnection('user-a').copyWith(primaryImageTag: 'cached-tag'),
httpClient: MockClient((request) async {
requestCount++;
expect(request.url.path, '/Users/Me');
return http.Response(
'{"Policy":{"IsAdministrator":false},"PrimaryImageTag":"fresh-tag"}',
200,
headers: {'content-type': 'application/json'},
);
}),
);
addTearDown(client.close);
final m = MultiServerManager()..onJellyfinConnectionUpdated = persisted.add;
addTearDown(m.dispose);
m.debugRegisterJellyfinClientForTesting(client);
final status = await client.checkHealth();
expect(status, HealthStatus.online);
expect(requestCount, 1);
expect(persisted, hasLength(1));
expect(persisted.single.primaryImageTag, 'fresh-tag');
});
test('clears the cached profile picture tag when the user deletes their avatar', () async {
final persisted = <JellyfinConnection>[];
var requestCount = 0;
final client = JellyfinClient.forTesting(
connection: _jellyfinConnection('user-a').copyWith(primaryImageTag: 'cached-tag'),
httpClient: MockClient((request) async {
requestCount++;
expect(request.url.path, '/Users/Me');
return http.Response(
'{"Policy":{"IsAdministrator":false}}',
200,
headers: {'content-type': 'application/json'},
);
}),
);
addTearDown(client.close);
final m = MultiServerManager()..onJellyfinConnectionUpdated = persisted.add;
addTearDown(m.dispose);
m.debugRegisterJellyfinClientForTesting(client);
final status = await client.checkHealth();
expect(status, HealthStatus.online);
expect(requestCount, 1);
expect(persisted, hasLength(1));
expect(persisted.single.primaryImageTag, isNull);
});
test('does not persist when the admin flag and profile picture tag are unchanged', () async {
final persisted = <JellyfinConnection>[];
var requestCount = 0;
final client = JellyfinClient.forTesting(
connection: _jellyfinConnection('user-a').copyWith(primaryImageTag: 'same-tag'),
httpClient: MockClient((request) async {
requestCount++;
expect(request.url.path, '/Users/Me');
return http.Response(
'{"Policy":{"IsAdministrator":false},"PrimaryImageTag":"same-tag"}',
200,
headers: {'content-type': 'application/json'},
);
}),
);
addTearDown(client.close);
final m = MultiServerManager()..onJellyfinConnectionUpdated = persisted.add;
addTearDown(m.dispose);
m.debugRegisterJellyfinClientForTesting(client);
final status = await client.checkHealth();
expect(status, HealthStatus.online);
expect(requestCount, 1);
expect(persisted, isEmpty);
});
test('persists one connection update when the admin flag and profile picture tag both change', () async {
final persisted = <JellyfinConnection>[];
var requestCount = 0;
final client = JellyfinClient.forTesting(
connection: _jellyfinConnection('user-a').copyWith(primaryImageTag: 'cached-tag'),
httpClient: MockClient((request) async {
requestCount++;
expect(request.url.path, '/Users/Me');
return http.Response(
'{"Policy":{"IsAdministrator":true},"PrimaryImageTag":"fresh-tag"}',
200,
headers: {'content-type': 'application/json'},
);
}),
);
addTearDown(client.close);
final m = MultiServerManager()..onJellyfinConnectionUpdated = persisted.add;
addTearDown(m.dispose);
m.debugRegisterJellyfinClientForTesting(client);
final status = await client.checkHealth();
expect(status, HealthStatus.online);
expect(requestCount, 1);
expect(persisted, hasLength(1));
expect(persisted.single.isAdministrator, isTrue);
expect(persisted.single.primaryImageTag, 'fresh-tag');
});
test('refreshes the profile picture tag when Policy is missing or malformed', () async {
final responses = <Map<String, Object?>>[
{'PrimaryImageTag': 'fresh-tag'},
{'Policy': 'not-a-map', 'PrimaryImageTag': 'fresh-tag'},
];
for (final responseBody in responses) {
final persisted = <JellyfinConnection>[];
var requestCount = 0;
final client = JellyfinClient.forTesting(
connection: _jellyfinConnection('user-a').copyWith(primaryImageTag: 'cached-tag'),
httpClient: MockClient((request) async {
requestCount++;
expect(request.url.path, '/Users/Me');
return http.Response(jsonEncode(responseBody), 200, headers: {'content-type': 'application/json'});
}),
);
addTearDown(client.close);
final m = MultiServerManager()..onJellyfinConnectionUpdated = persisted.add;
addTearDown(m.dispose);
m.debugRegisterJellyfinClientForTesting(client);
final status = await client.checkHealth();
expect(status, HealthStatus.online, reason: 'response: $responseBody');
expect(requestCount, 1, reason: 'response: $responseBody');
expect(persisted, hasLength(1), reason: 'response: $responseBody');
expect(persisted.single.primaryImageTag, 'fresh-tag', reason: 'response: $responseBody');
expect(persisted.single.isAdministrator, isFalse, reason: 'response: $responseBody');
}
});
test('health remains online when persisting refreshed admin status fails', () async {
final client = JellyfinClient.forTesting(
connection: _jellyfinConnection('user-a'),
+7 -1
View File
@@ -59,7 +59,13 @@ class ProfileStack {
profileConnections: profileConnections,
profiles: profiles,
plexHome: plexHome,
active: ActiveProfileProvider(registry: profiles, plexHome: plexHome, connections: connections, storage: storage),
active: ActiveProfileProvider(
registry: profiles,
plexHome: plexHome,
connections: connections,
profileConnections: profileConnections,
storage: storage,
),
storage: storage,
ownsDatabase: db == null,
);