jellyfin_controller.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. import 'dart:async';
  2. import 'package:flutter/foundation.dart';
  3. import '../../data/models/jellyfin_library.dart';
  4. import '../../data/models/jellyfin_models.dart';
  5. import '../../data/repositories/settings_repository.dart';
  6. import '../../data/services/jellyfin_service.dart';
  7. import '../../data/services/secure_store.dart';
  8. enum JellyfinStatus {
  9. disabled,
  10. needsSetup,
  11. connecting,
  12. pairing,
  13. connected,
  14. offline,
  15. error,
  16. }
  17. /// Owns the optional Jellyfin session. Quick Connect is the only sign-in path:
  18. /// the user approves a code in Jellyfin and CarDash keeps the returned token in
  19. /// secure storage. A rejected token disables the integration and clears it so
  20. /// the user has to pair again; an unreachable server is treated as a temporary
  21. /// outage and retried with backoff.
  22. class JellyfinController extends ChangeNotifier {
  23. JellyfinController(
  24. this._settings,
  25. this._gateway,
  26. this._secureStore, {
  27. this.pollInterval = const Duration(seconds: 3),
  28. this.pairingLifetime = const Duration(minutes: 10),
  29. this.healthInterval = const Duration(minutes: 1),
  30. List<Duration>? retryDelays,
  31. }) : retryDelays =
  32. retryDelays ??
  33. const [
  34. Duration(seconds: 5),
  35. Duration(seconds: 10),
  36. Duration(seconds: 20),
  37. Duration(seconds: 30),
  38. Duration(seconds: 60),
  39. ];
  40. static const tokenKey = 'jellyfin.accessToken';
  41. final SettingsRepository _settings;
  42. final JellyfinGateway _gateway;
  43. final SecureStore _secureStore;
  44. final Duration pollInterval;
  45. final Duration pairingLifetime;
  46. final Duration healthInterval;
  47. final List<Duration> retryDelays;
  48. bool _enabled = false;
  49. bool _needsRepair = false;
  50. bool _busy = false;
  51. bool _polling = false;
  52. bool _started = false;
  53. bool _disposed = false;
  54. JellyfinStatus _status = JellyfinStatus.disabled;
  55. String _serverUrl = '';
  56. String? _serverName;
  57. String? _userName;
  58. String? _error;
  59. String? _code;
  60. String? _secret;
  61. String? _token;
  62. String _deviceId = '';
  63. int _generation = 0;
  64. int _retryAttempt = 0;
  65. Timer? _pollTimer;
  66. Timer? _pairingTimer;
  67. Timer? _healthTimer;
  68. Timer? _retryTimer;
  69. bool get enabled => _enabled;
  70. bool get connected => _status == JellyfinStatus.connected;
  71. bool get busy => _busy;
  72. bool get pairing => _status == JellyfinStatus.pairing;
  73. bool get needsRepair => _needsRepair;
  74. bool get hasServerUrl => _serverUrl.isNotEmpty;
  75. bool get hasSession => _token != null;
  76. List<JellyfinGenreSelection> get genreSelections =>
  77. _settings.jellyfinGenreSelections;
  78. Future<void> setGenreSelections(
  79. List<JellyfinGenreSelection> selections,
  80. ) async {
  81. await _settings.setJellyfinGenreSelections(selections);
  82. _notify();
  83. }
  84. /// A saved server URL plus an access token. Unlike [connected] this stays
  85. /// true during a temporary outage, so the Home button and dashboard can show
  86. /// an offline state instead of disappearing.
  87. bool get configured => _enabled && _serverUrl.isNotEmpty && _token != null;
  88. /// Authenticated details for the library and playback services. Never pass
  89. /// this to a widget; use it only inside controllers/services.
  90. JellyfinConnection? get connection {
  91. final base = normalizeJellyfinUrl(_serverUrl);
  92. final token = _token;
  93. final userId = _settings.jellyfinUserId;
  94. if (!_enabled || base == null || token == null || userId == null) {
  95. return null;
  96. }
  97. return JellyfinConnection(
  98. baseUrl: base,
  99. accessToken: token,
  100. userId: userId,
  101. deviceId: _deviceId,
  102. userName: _userName ?? '',
  103. );
  104. }
  105. JellyfinStatus get status => _status;
  106. String get serverUrl => _serverUrl;
  107. String? get serverName => _serverName;
  108. String? get userName => _userName;
  109. String? get error => _error;
  110. String? get quickConnectCode => _code;
  111. String get statusLabel {
  112. if (!_enabled) {
  113. return _needsRepair ? 'Pairing needed' : 'Off';
  114. }
  115. switch (_status) {
  116. case JellyfinStatus.disabled:
  117. return 'Off';
  118. case JellyfinStatus.needsSetup:
  119. return 'Not connected';
  120. case JellyfinStatus.connecting:
  121. return 'Connecting…';
  122. case JellyfinStatus.pairing:
  123. return 'Waiting for approval';
  124. case JellyfinStatus.connected:
  125. return _serverName == null ? 'Connected' : 'Connected to $_serverName';
  126. case JellyfinStatus.offline:
  127. return 'No internet — retrying';
  128. case JellyfinStatus.error:
  129. return 'Not connected';
  130. }
  131. }
  132. /// Loads persisted state. Does not touch the network; call [start] once the
  133. /// app is running so a cold start is never delayed by Jellyfin.
  134. Future<void> initialize() async {
  135. _enabled = _settings.jellyfinEnabled;
  136. _serverUrl = _settings.jellyfinServerUrl;
  137. _serverName = _settings.jellyfinServerName;
  138. _userName = _settings.jellyfinUserName;
  139. _deviceId = await _settings.ensureJellyfinDeviceId();
  140. _token = await _secureStore.read(tokenKey);
  141. if (!_enabled) {
  142. _status = JellyfinStatus.disabled;
  143. return;
  144. }
  145. if (_serverUrl.isEmpty || _token == null) {
  146. _status = JellyfinStatus.needsSetup;
  147. return;
  148. }
  149. _status = JellyfinStatus.connecting;
  150. }
  151. /// Starts the first health check. Safe to call more than once.
  152. void start() {
  153. if (_started || _disposed) return;
  154. _started = true;
  155. if (_enabled && _token != null && _serverUrl.isNotEmpty) {
  156. unawaited(_validate());
  157. }
  158. }
  159. Future<void> setEnabled(bool value) async {
  160. if (_disposed || value == _enabled) return;
  161. if (!value) {
  162. _generation++;
  163. _cancelTimers();
  164. _enabled = false;
  165. _needsRepair = false;
  166. _busy = false;
  167. _code = null;
  168. _secret = null;
  169. _error = null;
  170. _status = JellyfinStatus.disabled;
  171. await _settings.setJellyfinEnabled(false);
  172. _notify();
  173. return;
  174. }
  175. _enabled = true;
  176. _needsRepair = false;
  177. _error = null;
  178. await _settings.setJellyfinEnabled(true);
  179. if (_serverUrl.isEmpty) {
  180. _status = JellyfinStatus.needsSetup;
  181. _notify();
  182. return;
  183. }
  184. if (_token != null) {
  185. await _validate();
  186. } else {
  187. _status = JellyfinStatus.needsSetup;
  188. _notify();
  189. }
  190. }
  191. /// Saves the URL and connects. With a saved token the session is reused;
  192. /// otherwise a Quick Connect code is requested.
  193. Future<void> connect(String rawUrl) async {
  194. final normalized = displayJellyfinUrl(rawUrl);
  195. if (normalized == null) {
  196. _error = 'Enter a valid http or https server URL.';
  197. _status = _enabled ? JellyfinStatus.needsSetup : JellyfinStatus.disabled;
  198. _notify();
  199. return;
  200. }
  201. final changed = _serverUrl.isNotEmpty && _serverUrl != normalized;
  202. _serverUrl = normalized;
  203. _error = null;
  204. await _settings.setJellyfinServerUrl(normalized);
  205. if (!_enabled) {
  206. _enabled = true;
  207. await _settings.setJellyfinEnabled(true);
  208. }
  209. if (changed) {
  210. await _clearSavedSession();
  211. _serverName = null;
  212. _userName = null;
  213. }
  214. if (_token != null) {
  215. await _validate();
  216. } else {
  217. await _beginQuickConnect();
  218. }
  219. }
  220. /// Re-enables Jellyfin and starts pairing again after the token was rejected.
  221. Future<void> pairAgain() async {
  222. _needsRepair = false;
  223. _error = null;
  224. if (!_enabled) {
  225. _enabled = true;
  226. await _settings.setJellyfinEnabled(true);
  227. }
  228. if (_serverUrl.isEmpty) {
  229. _status = JellyfinStatus.needsSetup;
  230. _notify();
  231. return;
  232. }
  233. await _beginQuickConnect();
  234. }
  235. /// Forgets the server entirely. The URL and device id stay for convenience.
  236. Future<void> removePairing() async {
  237. _generation++;
  238. _cancelTimers();
  239. await _clearSavedSession();
  240. _enabled = false;
  241. _busy = false;
  242. _needsRepair = false;
  243. _error = null;
  244. _code = null;
  245. _secret = null;
  246. _serverName = null;
  247. _userName = null;
  248. _status = JellyfinStatus.disabled;
  249. await _settings.setJellyfinEnabled(false);
  250. _notify();
  251. }
  252. /// Stops the current Quick Connect attempt without disabling the section.
  253. void cancelPairing() {
  254. if (_status != JellyfinStatus.pairing) return;
  255. _generation++;
  256. _cancelTimers();
  257. _code = null;
  258. _secret = null;
  259. _error = null;
  260. _busy = false;
  261. _status = JellyfinStatus.needsSetup;
  262. _notify();
  263. }
  264. /// Manual retry used by the card and when the app returns to the foreground.
  265. Future<void> checkNow() async {
  266. if (_disposed || !_enabled) return;
  267. if (_status == JellyfinStatus.pairing) {
  268. await _poll(_generation);
  269. return;
  270. }
  271. if (_token != null) {
  272. await _validate();
  273. } else if (_serverUrl.isNotEmpty) {
  274. await _beginQuickConnect();
  275. }
  276. }
  277. void onAppResumed() {
  278. if (_disposed || !_enabled) return;
  279. if (_status == JellyfinStatus.connected ||
  280. _status == JellyfinStatus.connecting) {
  281. return;
  282. }
  283. unawaited(checkNow());
  284. }
  285. Future<void> _beginQuickConnect() async {
  286. final base = normalizeJellyfinUrl(_serverUrl);
  287. if (base == null) {
  288. _error = 'Enter a valid http or https server URL.';
  289. _status = JellyfinStatus.needsSetup;
  290. _notify();
  291. return;
  292. }
  293. final generation = ++_generation;
  294. _cancelTimers();
  295. _busy = true;
  296. _code = null;
  297. _secret = null;
  298. _error = null;
  299. _status = JellyfinStatus.connecting;
  300. _notify();
  301. try {
  302. final info = await _gateway.serverInfo(base);
  303. if (_stale(generation)) return;
  304. _serverName = info.name;
  305. await _settings.setJellyfinServerName(info.name);
  306. final ticket = await _gateway.startQuickConnect(
  307. base,
  308. deviceId: _deviceId,
  309. );
  310. if (_stale(generation)) return;
  311. _code = ticket.code;
  312. _secret = ticket.secret;
  313. _busy = false;
  314. _status = JellyfinStatus.pairing;
  315. _notify();
  316. _startPairingTimers(generation);
  317. } on JellyfinUnreachable catch (exception) {
  318. if (_stale(generation)) return;
  319. _goOffline(exception.message, _beginQuickConnect);
  320. } on JellyfinException catch (exception) {
  321. if (_stale(generation)) return;
  322. _failPairing(exception.message);
  323. }
  324. }
  325. void _startPairingTimers(int generation) {
  326. _pollTimer = Timer.periodic(
  327. pollInterval,
  328. (_) => unawaited(_poll(generation)),
  329. );
  330. _pairingTimer = Timer(pairingLifetime, () {
  331. if (_stale(generation)) return;
  332. _failPairing('The Quick Connect code expired. Try again.');
  333. });
  334. }
  335. Future<void> _poll(int generation) async {
  336. if (_disposed || _polling || _stale(generation)) return;
  337. final base = normalizeJellyfinUrl(_serverUrl);
  338. final secret = _secret;
  339. if (base == null || secret == null) return;
  340. _polling = true;
  341. try {
  342. final approved = await _gateway.isQuickConnectApproved(base, secret);
  343. if (_stale(generation)) return;
  344. if (!approved) {
  345. if (_error != null) {
  346. _error = null;
  347. _notify();
  348. }
  349. return;
  350. }
  351. _pollTimer?.cancel();
  352. _pairingTimer?.cancel();
  353. _busy = true;
  354. _status = JellyfinStatus.connecting;
  355. _notify();
  356. final session = await _gateway.authenticateQuickConnect(
  357. base,
  358. secret,
  359. deviceId: _deviceId,
  360. );
  361. if (_stale(generation)) return;
  362. _token = session.accessToken;
  363. _userName = session.userName;
  364. await _secureStore.write(tokenKey, session.accessToken);
  365. await _settings.setJellyfinSession(
  366. userId: session.userId,
  367. userName: session.userName,
  368. );
  369. _code = null;
  370. _secret = null;
  371. _busy = false;
  372. _error = null;
  373. _status = JellyfinStatus.connected;
  374. _retryAttempt = 0;
  375. _notify();
  376. _startHealthTimer();
  377. } on JellyfinUnreachable {
  378. // Keep the code alive; the next poll retries once the network is back.
  379. if (_stale(generation)) return;
  380. _error = 'No connection — waiting to retry.';
  381. _notify();
  382. } on JellyfinAuthException catch (exception) {
  383. if (_stale(generation)) return;
  384. _failPairing(exception.message);
  385. } on JellyfinException catch (exception) {
  386. if (_stale(generation)) return;
  387. _failPairing(exception.message);
  388. } finally {
  389. _polling = false;
  390. }
  391. }
  392. Future<void> _validate({bool silent = false}) async {
  393. final base = normalizeJellyfinUrl(_serverUrl);
  394. final token = _token;
  395. if (base == null) {
  396. _status = JellyfinStatus.needsSetup;
  397. _notify();
  398. return;
  399. }
  400. if (token == null) {
  401. _status = JellyfinStatus.needsSetup;
  402. _notify();
  403. return;
  404. }
  405. final generation = ++_generation;
  406. _cancelTimers();
  407. if (!silent) {
  408. _busy = true;
  409. _status = JellyfinStatus.connecting;
  410. }
  411. _error = null;
  412. if (!silent) _notify();
  413. try {
  414. final info = await _gateway.serverInfo(base);
  415. if (_stale(generation)) return;
  416. final user = await _gateway.currentUser(base, token);
  417. if (_stale(generation)) return;
  418. final changed =
  419. _serverName != info.name ||
  420. _userName != user.name ||
  421. _status != JellyfinStatus.connected;
  422. _serverName = info.name;
  423. _userName = user.name;
  424. _busy = false;
  425. _status = JellyfinStatus.connected;
  426. _error = null;
  427. _retryAttempt = 0;
  428. unawaited(_settings.setJellyfinServerName(info.name));
  429. unawaited(_settings.setJellyfinUserName(user.name));
  430. if (changed || !silent) _notify();
  431. _startHealthTimer();
  432. } on JellyfinUnreachable catch (exception) {
  433. if (_stale(generation)) return;
  434. _goOffline(exception.message, _validate);
  435. } on JellyfinAuthException {
  436. if (_stale(generation)) return;
  437. await _invalidateSession('The saved pairing is no longer valid.');
  438. } on JellyfinException catch (exception) {
  439. if (_stale(generation)) return;
  440. await _invalidateSession(exception.message);
  441. }
  442. }
  443. void _goOffline(String message, Future<void> Function() resume) {
  444. _cancelTimers();
  445. _busy = false;
  446. _status = JellyfinStatus.offline;
  447. _error = message;
  448. _notify();
  449. final index = _retryAttempt < retryDelays.length
  450. ? _retryAttempt
  451. : retryDelays.length - 1;
  452. _retryAttempt++;
  453. _retryTimer = Timer(retryDelays[index], () {
  454. _retryTimer = null;
  455. if (_disposed || !_enabled) return;
  456. unawaited(resume());
  457. });
  458. }
  459. void _failPairing(String message) {
  460. _cancelTimers();
  461. _code = null;
  462. _secret = null;
  463. _busy = false;
  464. _status = JellyfinStatus.error;
  465. _error = message;
  466. _notify();
  467. }
  468. /// The token was rejected: turn Jellyfin off, clear the token and profile,
  469. /// and leave the card asking for a fresh Quick Connect.
  470. Future<void> _invalidateSession(String message) async {
  471. _generation++;
  472. _cancelTimers();
  473. await _clearSavedSession();
  474. _enabled = false;
  475. _needsRepair = true;
  476. _busy = false;
  477. _code = null;
  478. _secret = null;
  479. _serverName = null;
  480. _userName = null;
  481. _status = JellyfinStatus.error;
  482. _error = message;
  483. await _settings.setJellyfinEnabled(false);
  484. _notify();
  485. }
  486. Future<void> _clearSavedSession() async {
  487. _token = null;
  488. await _secureStore.delete(tokenKey);
  489. await _settings.clearJellyfinSession();
  490. }
  491. void _startHealthTimer() {
  492. _healthTimer?.cancel();
  493. _healthTimer = Timer.periodic(healthInterval, (_) {
  494. if (_disposed || !_enabled || _token == null) return;
  495. unawaited(_validate(silent: true));
  496. });
  497. }
  498. void _cancelTimers() {
  499. _pollTimer?.cancel();
  500. _pollTimer = null;
  501. _pairingTimer?.cancel();
  502. _pairingTimer = null;
  503. _healthTimer?.cancel();
  504. _healthTimer = null;
  505. _retryTimer?.cancel();
  506. _retryTimer = null;
  507. }
  508. bool _stale(int generation) {
  509. return _disposed || generation != _generation || !_enabled;
  510. }
  511. void _notify() {
  512. if (!_disposed) notifyListeners();
  513. }
  514. @override
  515. void dispose() {
  516. _disposed = true;
  517. _cancelTimers();
  518. _gateway.close();
  519. super.dispose();
  520. }
  521. }