Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions lib/providers/trackers_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin

bool isConnecting(TrackerService service) => _connecting == service;

List<TrackerService> get reconnectRequiredServices => [
for (final slot in _slots)
if (slot.needsReconnect) slot.service,
];

/// Cancel an in-flight connect. Completing the completer both wakes the
/// blocking `Future.any` race and flips `isCompleted` for the next sync check.
void cancelConnect() {
Expand All @@ -188,6 +193,7 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
// retry queue.
for (final slot in _slots) {
slot.session = null;
slot.needsReconnect = false;
_rebind(slot);
}
// Publish the detach before awaiting: proxy consumers cache the client they
Expand All @@ -199,11 +205,13 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
// moves) rather than dropping the freshly-loaded sessions for the others.
final rebinds = [for (final slot in _slots) slot.rebindGeneration];
final results = await Future.wait<TrackerSession?>([for (final slot in _slots) slot.store.load(userUuid)]);
final reconnectRequired = await Future.wait<bool>([for (final slot in _slots) slot.store.needsReconnect(userUuid)]);
if (!_isCurrentProfileBinding(userUuid, generation)) return;
for (var i = 0; i < _slots.length; i++) {
final slot = _slots[i];
if (slot.rebindGeneration != rebinds[i]) continue;
slot.session = results[i];
slot.needsReconnect = results[i] == null && reconnectRequired[i];
_rebind(slot);
}
// Connect/disconnect may flip `needsFribb` — drop cached resolver IDs so
Expand Down Expand Up @@ -384,6 +392,7 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
assign: (session) {
if (!_isCurrentConnect(service, userUuid, generation)) return;
slot.session = session;
slot.needsReconnect = false;
_rebind(slot);
// Same ordering contract as [_clearAndRebind] and the invalidation
// teardown: the rebind above moved the account binding first, so an
Expand Down Expand Up @@ -421,6 +430,7 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
// no longer touch the shared profile-binding generation (which would also
// abort that load for the other services).
slot.session = null;
slot.needsReconnect = false;
_rebind(slot);
safeNotifyListeners();
await TrackerCoordinator.instance.purgeWriteQueueForService(slot.service);
Expand Down Expand Up @@ -514,9 +524,20 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
slot.bind(
slot.session,
onInvalidated: () {
if (!isCurrent()) return;
slot.store.clear(boundUuid);
if (!isCurrent() || slot.session == null) return;
// The client already classified this as a permanent auth failure.
// Record it here so normal tracker activity also explains the lost login.
unawaited(
slot.store.clear(boundUuid, reconnectRequired: true).catchError((Object error, StackTrace stackTrace) {
appLogger.w(
'Failed to persist ${slot.service.name} reconnect warning',
error: error,
stackTrace: stackTrace,
);
}),
);
slot.session = null;
slot.needsReconnect = true;
_rebind(slot);
// Same contract as the explicit-disconnect purge in [_clearAndRebind]:
// rows queued under the session that just died must never replay
Expand Down Expand Up @@ -567,6 +588,7 @@ class _TrackerSlot {
final TrackerAccountStore store;
final _TrackerBind bind;
TrackerSession? session;
bool needsReconnect = false;

/// Bumped on every rebind so a late callback from a disposed client (e.g. an
/// in-flight refresh that resolves after a profile switch) can't persist or
Expand Down
21 changes: 18 additions & 3 deletions lib/services/trackers/tracker_account_store.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ class TrackerAccountStore {

String _scopedKey(String userUuid) => profileScopedPrefsKey(userUuid, _baseKey);

String _reconnectKey(String userUuid) => profileScopedPrefsKey(userUuid, '${_baseKey}_needs_reconnect');

Future<bool> needsReconnect(String userUuid) async {
final prefs = await BaseSharedPreferencesService.sharedCache();
return prefs.getBool(_reconnectKey(userUuid)) ?? false;
}

Future<TrackerSession?> load(String userUuid) async {
final prefs = await BaseSharedPreferencesService.sharedCache();
final raw = readTolerantString(prefs, _scopedKey(userUuid));
Expand All @@ -42,12 +49,20 @@ class TrackerAccountStore {

Future<void> save(String userUuid, TrackerSession session) async {
final prefs = await BaseSharedPreferencesService.sharedCache();
await prefs.setString(_scopedKey(userUuid), session.encode());
await Future.wait<void>([
prefs.setString(_scopedKey(userUuid), session.encode()),
prefs.remove(_reconnectKey(userUuid)),
]);
}

Future<void> clear(String userUuid) async {
/// Keep the reason separately from the existing credential JSON. An empty
/// account slot alone cannot distinguish a lost login from a deliberate logout.
Future<void> clear(String userUuid, {bool reconnectRequired = false}) async {
final prefs = await BaseSharedPreferencesService.sharedCache();
await prefs.remove(_scopedKey(userUuid));
await Future.wait<void>([
prefs.remove(_scopedKey(userUuid)),
if (reconnectRequired) prefs.setBool(_reconnectKey(userUuid), true) else prefs.remove(_reconnectKey(userUuid)),
]);
}
}

Expand Down
34 changes: 31 additions & 3 deletions lib/widgets/auth_error_banner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import 'package:provider/provider.dart';

import '../i18n/strings.g.dart';
import '../providers/multi_server_provider.dart';
import '../providers/trackers_provider.dart';
import '../screens/settings/add_connection_screen.dart';
import '../screens/settings/tracker_service_info.dart';
import '../focus/focusable_button.dart';
import 'app_icon.dart';

/// Top-of-app banner for servers that answered and refused this account.
/// Top-of-app banner for servers that refused this account and lost tracker logins.
/// Distinct from "server offline" — the server is reachable, so empty hubs
/// need an explanation.
///
Expand All @@ -22,7 +24,9 @@ import 'app_icon.dart';
/// the same refusal, and only the server owner or the network the device is on
/// can change it.
///
/// Collapses to `SizedBox.shrink()` when no visible server refuses.
/// Tracker warnings reuse the existing session text and each service's normal
/// connection flow. They appear only after a client's auth invalidation callback.
/// Collapses to `SizedBox.shrink()` when there is nothing to reconnect or explain.
class AuthErrorBanner extends StatelessWidget {
const AuthErrorBanner({super.key});

Expand All @@ -34,7 +38,13 @@ class AuthErrorBanner extends StatelessWidget {
final deniedEntries = context.select<MultiServerProvider, List<({ServerId serverId, String displayName})>>(
(p) => p.accessDeniedServers,
);
if (signInEntries.isEmpty && deniedEntries.isEmpty) return const SizedBox.shrink();
// This banner is also used outside a profile's tracker provider scope.
final trackers = context.watch<TrackersProvider?>();
final invalidated = trackers?.reconnectRequiredServices ?? const [];
final services = invalidated.isEmpty ? const <TrackerServiceInfo>[] : TrackerServiceInfo.all;
final expiredTrackers = services.where((info) => invalidated.contains(info.service)).toList();
final trackerBusy = services.any((info) => trackers!.isConnecting(info.service));
if (signInEntries.isEmpty && deniedEntries.isEmpty && expiredTrackers.isEmpty) return const SizedBox.shrink();

final scheme = Theme.of(context).colorScheme;
return Material(
Expand Down Expand Up @@ -69,6 +79,24 @@ class AuthErrorBanner extends StatelessWidget {
? t.connections.accessDeniedOne(name: deniedEntries.first.displayName)
: t.connections.accessDeniedMany(count: deniedEntries.length),
),
for (final info in expiredTrackers)
_BannerRow(
icon: Symbols.lock_rounded,
label: t.connections.sessionExpiredOne(name: info.displayName),
action: Flexible(
child: FocusableButton(
onPressed: trackerBusy ? null : () => info.startConnection(context),
child: FilledButton.tonal(
style: FilledButton.styleFrom(
backgroundColor: scheme.onErrorContainer,
foregroundColor: scheme.errorContainer,
),
onPressed: trackerBusy ? null : () => info.startConnection(context),
child: Text(t.connections.signInAgain),
),
),
),
),
],
),
),
Expand Down
113 changes: 113 additions & 0 deletions test/providers/trackers_provider_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,111 @@ void main() {
tearDown(_resetTrackerBindings);

group('TrackersProvider', () {
group('reconnect warnings', () {
for (final service in TrackerService.values) {
test('$service invalidation is saved, restored, and isolated from another profile', () async {
final store = _store(service);
await store.save('alice', _session(service, 'alice'));
await store.save('bob', _session(service, 'bob'));
final p = TrackersProvider();
addTearDown(p.dispose);
await _bindProfile(p, 'alice');
final invalidate = _invalidationCallback(service);

invalidate();
invalidate();
expect(p.reconnectRequiredServices, [service]);
expect(_providerSession(p, service), isNull);
await TrackerCoordinator.instance.flushWriteQueue();
expect(await store.needsReconnect('alice'), isTrue);
expect(await store.load('alice'), isNull);

await _bindProfile(p, 'bob');
invalidate(); // The old client's callback must not affect Bob.
expect(p.reconnectRequiredServices, isEmpty);
expect(_providerSession(p, service)?.username, 'bob');
expect(await store.needsReconnect('bob'), isFalse);

BaseSharedPreferencesService.resetForTesting();
await _bindProfile(p, 'alice');
expect(p.reconnectRequiredServices, [service]);
expect(_providerSession(p, service), isNull);
});

test('$service keeps a failed reconnect warning and clears it after success', () async {
final store = _store(service);
await store.clear('alice', reconnectRequired: true);
var succeed = false;
final p = TrackersProvider.forTesting(
connectPipeline:
({required logLabel, required authorize, required enrich, required save, required assign}) async {
if (!succeed) return false;
final session = _session(service, 'alice');
await save(session);
assign(session);
return true;
},
);
addTearDown(p.dispose);
await _bindProfile(p, 'alice');

expect(await _connect(p, service), isFalse);
expect(p.reconnectRequiredServices, [service]);
expect(await store.needsReconnect('alice'), isTrue);

succeed = true;
expect(await _connect(p, service), isTrue);
await TrackerCoordinator.instance.flushWriteQueue();
expect(p.reconnectRequiredServices, isEmpty);
expect(await store.needsReconnect('alice'), isFalse);
expect(_providerSession(p, service)?.username, 'alice');
});
}

test('a cancelled reconnect retains the warning and deliberate disconnect clears it', () async {
await _traktStore.clear('alice', reconnectRequired: true);
final pipeline = _ControlledConnectPipeline(_trakt());
final p = TrackersProvider.forTesting(connectPipeline: pipeline.call);
addTearDown(p.dispose);
await _bindProfile(p, 'alice');

final connect = p.connectTrakt(onCodeReady: (_) {});
await pipeline.beforeSave.future;
p.cancelConnect();
pipeline.releaseBeforeSave.complete();
expect(await connect, isFalse);
expect(p.reconnectRequiredServices, [TrackerService.trakt]);
expect(await _traktStore.needsReconnect('alice'), isTrue);

await p.disconnectTrakt();
expect(p.reconnectRequiredServices, isEmpty);
expect(await _traktStore.needsReconnect('alice'), isFalse);
await _bindProfile(p, 'alice');
expect(p.reconnectRequiredServices, isEmpty);
});

for (final status in [429, 503]) {
test('a Trakt HTTP $status response does not create a reconnect warning', () async {
await _traktStore.save('alice', _trakt());
final p = TrackersProvider();
addTearDown(p.dispose);
await _bindProfile(p, 'alice');
final live = TraktTracker.instance.client!;
TraktTracker.instance.rebindSession(
live.session,
onSessionInvalidated: live.onSessionInvalidated,
httpClient: MockClient((_) async => http.Response('', status)),
);

await expectLater(TraktTracker.instance.client!.getUserSettings(), throwsException);
expect(p.reconnectRequiredServices, isEmpty);
expect(p.isTraktConnected, isTrue);
expect(await _traktStore.needsReconnect('alice'), isFalse);
expect(await _traktStore.load('alice'), isNotNull);
});
}
});

test('starts with all trackers disconnected', () {
final p = TrackersProvider();
expect(p.mal, isNull);
Expand Down Expand Up @@ -718,6 +823,14 @@ Object? _boundClient(TrackerService service) => switch (service) {
TrackerService.mdblist => MdblistTracker.instance.client,
};

void Function() _invalidationCallback(TrackerService service) => switch (service) {
TrackerService.mal => MalTracker.instance.client!.onSessionInvalidated,
TrackerService.anilist => AnilistTracker.instance.client!.onSessionInvalidated,
TrackerService.simkl => SimklTracker.instance.client!.onSessionInvalidated,
TrackerService.trakt => TraktTracker.instance.client!.onSessionInvalidated,
TrackerService.mdblist => MdblistTracker.instance.client!.onSessionInvalidated,
};

TrackerSession? _boundSession(TrackerService service) => switch (service) {
TrackerService.mal => MalTracker.instance.client?.session,
TrackerService.anilist => AnilistTracker.instance.client?.session,
Expand Down
25 changes: 25 additions & 0 deletions test/services/trackers/tracker_account_store_scope_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,30 @@ void main() {
await store.clear(_fullProfileId);
expect(await store.load(_homeUserUuid), isNull);
});

test('an invalidation survives a cache reload and stays with its service and profile', () async {
final store = trackerAccountStore(TrackerService.trakt);
await store.save(_fullProfileId, _session());
await store.clear(_fullProfileId, reconnectRequired: true);
BaseSharedPreferencesService.resetForTesting();

expect(await store.load(_homeUserUuid), isNull);
expect(await store.needsReconnect(_homeUserUuid), isTrue);
expect(await store.needsReconnect('another-profile'), isFalse);
expect(await trackerAccountStore(TrackerService.mal).needsReconnect(_homeUserUuid), isFalse);
});

test('a saved replacement or an intentional disconnect clears the warning', () async {
final store = trackerAccountStore(TrackerService.trakt);
await store.clear(_homeUserUuid, reconnectRequired: true);
await store.save(_homeUserUuid, _session());
expect(await store.load(_fullProfileId), isNotNull);
expect(await store.needsReconnect(_fullProfileId), isFalse);

await store.clear(_homeUserUuid, reconnectRequired: true);
await store.clear(_homeUserUuid);
expect(await store.load(_fullProfileId), isNull);
expect(await store.needsReconnect(_fullProfileId), isFalse);
});
});
}
Loading