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
+55
View File
@@ -11,6 +11,9 @@ import '../services/storage_service.dart';
import '../utils/app_logger.dart';
import 'plex_home_service.dart';
import 'profile.dart';
import 'profile_avatar_source.dart';
import 'profile_connection.dart';
import 'profile_connection_registry.dart';
import 'profile_merge.dart';
import 'profile_registry.dart';
@@ -27,6 +30,7 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
required this._registry,
required this._plexHome,
required this._connections,
required this._profileConnections,
this._storage,
this._activeProfileIdWriter,
});
@@ -34,6 +38,7 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
final ProfileRegistry _registry;
final PlexHomeService _plexHome;
final ConnectionRegistry _connections;
final ProfileConnectionRegistry _profileConnections;
StorageService? _storage;
final Future<void> Function(String profileId)? _activeProfileIdWriter;
@@ -42,9 +47,12 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
List<Profile> _localProfiles = const [];
Map<String, List<PlexHomeUser>> _plexHomeUsers = const {};
Map<String, Connection> _connectionsById = const {};
Map<String, List<ProfileConnection>> _connectionsByProfile = const {};
Map<String, String?> _avatarUrls = const {};
StreamSubscription<List<Profile>>? _localSub;
StreamSubscription<List<Connection>>? _connSub;
StreamSubscription<List<ProfileConnection>>? _pcSub;
StreamSubscription<Map<String, List<PlexHomeUser>>>? _plexHomeSub;
Future<void>? _initializeFuture;
bool _initialized = false;
@@ -61,6 +69,10 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
Profile? get active => _active;
String? get activeId => _active?.id;
List<Profile> get profiles => _profiles;
/// Derived picture URL for [profileId], or null when initials should render.
String? avatarUrlFor(String profileId) => _avatarUrls[profileId];
bool get hasMultipleProfiles => _profiles.length > 1;
bool get isInitialized => _initialized;
@@ -170,6 +182,14 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
_resolveActive();
safeNotifyListeners();
});
_pcSub = _profileConnections.watchAll().listen((list) {
final byProfile = groupConnectionsByProfile(list);
if (_sameProfileConnections(byProfile, _connectionsByProfile)) return;
_connectionsByProfile = byProfile;
_recomputeProfiles();
_resolveActive();
safeNotifyListeners();
});
_plexHomeSub = _plexHome.stream.listen((cache) {
if (_samePlexHomeUsers(cache, _plexHomeUsers)) return;
_plexHomeUsers = cache;
@@ -191,6 +211,7 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
_localProfiles = await _registry.list();
final initialConns = await _connections.list();
_connectionsById = {for (final c in initialConns) c.id: c};
_connectionsByProfile = groupConnectionsByProfile(await _profileConnections.listAll());
_plexHomeUsers = _plexHome.current;
_recomputeProfiles();
_resolveActive();
@@ -209,6 +230,29 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
return true;
}
static bool _sameProfileConnections(Map<String, List<ProfileConnection>> a, Map<String, List<ProfileConnection>> b) {
if (a.length != b.length) return false;
for (final entry in a.entries) {
final other = b[entry.key];
if (other == null || entry.value.length != other.length) return false;
for (final row in entry.value) {
var hasSameFingerprint = false;
for (final candidate in other) {
if (row.profileId == candidate.profileId &&
row.connectionId == candidate.connectionId &&
row.userIdentifier == candidate.userIdentifier) {
hasSameFingerprint = true;
break;
}
}
// Only these identity fields affect avatar selection. Deliberately
// ignore tokens, default status, and binder-maintained timestamps.
if (!hasSameFingerprint) return false;
}
}
return true;
}
static bool _samePlexHomeUsers(Map<String, List<PlexHomeUser>> a, Map<String, List<PlexHomeUser>> b) {
if (a.length != b.length) return false;
for (final entry in a.entries) {
@@ -225,6 +269,12 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
connectionsById: _connectionsById,
storage: _storage,
);
_avatarUrls = resolveProfileAvatarUrls(
profiles: _profiles,
connectionsByProfile: _connectionsByProfile,
connectionsById: _connectionsById,
plexHomeByConnectionId: _plexHomeUsers,
);
}
void _resolveActive() {
@@ -487,13 +537,17 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
await _localSub?.cancel();
await _connSub?.cancel();
await _plexHomeSub?.cancel();
await _pcSub?.cancel();
_localSub = null;
_connSub = null;
_plexHomeSub = null;
_pcSub = null;
_profiles = const [];
_localProfiles = const [];
_plexHomeUsers = const {};
_connectionsById = const {};
_connectionsByProfile = const {};
_avatarUrls = const {};
_active = null;
_initializeFuture = null;
_initialized = false;
@@ -525,6 +579,7 @@ class ActiveProfileProvider extends ChangeNotifier with DisposableChangeNotifier
_localSub?.cancel();
_connSub?.cancel();
_plexHomeSub?.cancel();
_pcSub?.cancel();
super.dispose();
}
}
+15 -4
View File
@@ -12,13 +12,19 @@ class ProfileAvatar extends StatelessWidget {
final double size;
final bool showLockBadge;
const ProfileAvatar({super.key, required this.profile, this.size = 40, this.showLockBadge = true});
/// The derived picture for this profile (see [resolveProfileAvatarUrls]).
///
/// Falls back to [Profile.avatarThumbUrl] when null.
final String? avatarUrl;
const ProfileAvatar({super.key, required this.profile, this.size = 40, this.showLockBadge = true, this.avatarUrl});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final p = profile;
final lockBadgeSize = size * 0.34;
final memCacheSize = (size * MediaQuery.devicePixelRatioOf(context)).round();
return SizedBox(
width: size,
@@ -27,7 +33,7 @@ class ProfileAvatar extends StatelessWidget {
clipBehavior: Clip.none,
children: [
ClipOval(
child: SizedBox(width: size, height: size, child: _buildContent(theme, p)),
child: SizedBox(width: size, height: size, child: _buildContent(theme, p, memCacheSize)),
),
if (showLockBadge && p != null && p.isPinProtected)
Positioned(
@@ -55,16 +61,21 @@ class ProfileAvatar extends StatelessWidget {
);
}
Widget _buildContent(ThemeData theme, Profile? p) {
Widget _buildContent(ThemeData theme, Profile? p, int memCacheSize) {
if (p == null) {
return Container(color: theme.colorScheme.surfaceContainerHighest);
}
final thumb = p.avatarThumbUrl;
// An empty override means "nothing derived", not "suppress the profile's
// own picture" — same absent-or-blank rule the thumb itself uses below.
final override = avatarUrl;
final thumb = override != null && override.isNotEmpty ? override : p.avatarThumbUrl;
if (thumb != null && thumb.isNotEmpty) {
return CachedNetworkImage(
imageUrl: thumb,
cacheManager: PlexImageCacheManager.instance,
fit: BoxFit.cover,
memCacheWidth: memCacheSize,
memCacheHeight: memCacheSize,
placeholder: (_, _) => _initialFallback(theme, p),
errorBuilder: (_, _, _) => _initialFallback(theme, p),
);
+105
View File
@@ -0,0 +1,105 @@
import '../connection/connection.dart';
import '../models/plex/plex_home_user.dart';
import '../services/jellyfin_mappers.dart';
import 'profile.dart';
import 'profile_connection.dart';
/// Picture URL per profile id, `null` meaning "render initials".
///
/// A [PlexHomeProfile] owns its picture: Plex serves a per-home-user avatar
/// and [Profile.virtualPlexHome] already carries it, so those pass through
/// untouched.
///
/// A [LocalProfile] has no picture of its own. It shows the user picture of
/// the connection it was linked to **first** — the oldest by
/// [Connection.createdAt], ties broken by connection id so the choice is
/// stable. If that connection has no picture the profile falls back to
/// initials; we deliberately do *not* skip ahead to a later connection, so the
/// avatar stays a property of "the first connection" rather than of whichever
/// backend happens to have an image today.
///
/// The join row is not a usable ordering key: `profile_connections` has no
/// creation timestamp, and `tokenAcquiredAt` is rewritten every time the
/// binder re-mints a Plex Home token.
Map<String, String?> resolveProfileAvatarUrls({
required List<Profile> profiles,
required Map<String, List<ProfileConnection>> connectionsByProfile,
required Map<String, Connection> connectionsById,
required Map<String, List<PlexHomeUser>> plexHomeByConnectionId,
}) {
return {
for (final profile in profiles)
profile.id: _avatarForProfile(
profile: profile,
links: connectionsByProfile[profile.id] ?? const [],
connectionsById: connectionsById,
plexHomeByConnectionId: plexHomeByConnectionId,
),
};
}
String? _avatarForProfile({
required Profile profile,
required List<ProfileConnection> links,
required Map<String, Connection> connectionsById,
required Map<String, List<PlexHomeUser>> plexHomeByConnectionId,
}) {
final own = profile.avatarThumbUrl;
if (own != null && own.isNotEmpty) return own;
// A Plex Home user with no avatar set keeps its initials. Plex owns that
// profile's identity end to end, so it must never borrow the picture of a
// connection it happens to have been lent.
if (profile.isPlexHome) return null;
ProfileConnection? firstLink;
Connection? first;
for (final link in links) {
// A link whose connection was removed can't contribute a picture, and it
// must not win the ordering either.
final connection = connectionsById[link.connectionId];
if (connection == null) continue;
if (first == null || _isEarlier(connection, first)) {
first = connection;
firstLink = link;
}
}
if (first == null || firstLink == null) return null;
return connectionAvatarUrl(connection: first, link: firstLink, plexHomeByConnectionId: plexHomeByConnectionId);
}
bool _isEarlier(Connection candidate, Connection incumbent) {
final byCreatedAt = candidate.createdAt.compareTo(incumbent.createdAt);
if (byCreatedAt != 0) return byCreatedAt < 0;
return candidate.id.compareTo(incumbent.id) < 0;
}
/// Picture a single connection contributes to [link]'s profile, or `null`.
///
/// Plex resolves through the join row rather than the account owner: a profile
/// borrows a *specific* Home user (`userIdentifier`), and that user's live
/// [PlexHomeUser.thumb] is the picture Plex shows for it. Reading the live
/// cache also means the avatar tracks Plex's hourly refresh for free.
String? connectionAvatarUrl({
required Connection connection,
required ProfileConnection link,
required Map<String, List<PlexHomeUser>> plexHomeByConnectionId,
}) {
return switch (connection) {
JellyfinConnection(:final baseUrl, :final userId, :final primaryImageTag) => jellyfinUserImageUrl(
baseUrl: baseUrl,
userId: userId,
tag: primaryImageTag,
),
PlexAccountConnection() => _plexHomeUserThumb(plexHomeByConnectionId[connection.id], link.userIdentifier),
};
}
String? _plexHomeUserThumb(List<PlexHomeUser>? homeUsers, String homeUserUuid) {
if (homeUsers == null || homeUserUuid.isEmpty) return null;
for (final user in homeUsers) {
if (user.uuid != homeUserUuid) continue;
return user.thumb.isEmpty ? null : user.thumb;
}
return null;
}
+10
View File
@@ -2,6 +2,16 @@ import '../connection/connection.dart';
import '../models/plex/plex_home_user.dart';
import '../services/storage_service.dart';
import 'profile.dart';
import 'profile_connection.dart';
/// Groups profile-connection rows by profile id, preserving input order.
Map<String, List<ProfileConnection>> groupConnectionsByProfile(List<ProfileConnection> pcs) {
final out = <String, List<ProfileConnection>>{};
for (final pc in pcs) {
out.putIfAbsent(pc.profileId, () => []).add(pc);
}
return out;
}
/// Merge local profiles with virtual Plex Home profiles. Each Plex Home
/// user becomes a virtual profile attached to its `connectionId`. Home
+28 -11
View File
@@ -6,6 +6,7 @@ import '../models/plex/plex_home_user.dart';
import '../services/storage_service.dart';
import 'plex_home_service.dart';
import 'profile.dart';
import 'profile_avatar_source.dart';
import 'profile_connection.dart';
import 'profile_connection_registry.dart';
import 'profile_merge.dart';
@@ -25,9 +26,22 @@ class ProfilesView {
final Map<String, Connection> connectionsById;
const ProfilesView({required this.profiles, required this.connectionsByProfile, required this.connectionsById});
/// Picture URL per profile id; null means render initials. See [resolveProfileAvatarUrls].
final Map<String, String?> avatarUrlByProfile;
static const empty = ProfilesView(profiles: [], connectionsByProfile: {}, connectionsById: {});
const ProfilesView({
required this.profiles,
required this.connectionsByProfile,
required this.connectionsById,
required this.avatarUrlByProfile,
});
static const empty = ProfilesView(
profiles: [],
connectionsByProfile: {},
connectionsById: {},
avatarUrlByProfile: {},
);
}
/// Join-table rows that should be shown as explicit, user-manageable
@@ -77,21 +91,24 @@ ProfilesView _build({
required StorageService? storage,
}) {
final connectionsById = {for (final c in conns) c.id: c};
final connectionsByProfile = groupConnectionsByProfile(pcs);
final all = mergeLocalWithPlexHome(
locals: locals,
plexHomeByConnectionId: homes,
connectionsById: connectionsById,
storage: storage,
);
return ProfilesView(profiles: all, connectionsByProfile: _groupByProfile(pcs), connectionsById: connectionsById);
}
Map<String, List<ProfileConnection>> _groupByProfile(List<ProfileConnection> pcs) {
final out = <String, List<ProfileConnection>>{};
for (final pc in pcs) {
out.putIfAbsent(pc.profileId, () => []).add(pc);
}
return out;
return ProfilesView(
profiles: all,
connectionsByProfile: connectionsByProfile,
connectionsById: connectionsById,
avatarUrlByProfile: resolveProfileAvatarUrls(
profiles: all,
connectionsByProfile: connectionsByProfile,
connectionsById: connectionsById,
plexHomeByConnectionId: homes,
),
);
}
/// Lightweight `combineLatest4` — emits the combined value once each input