jellyfin_controller.dart 16 KB

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