Jellyfin end to end: per-viewer playback, progress, episodes, swap browser
- Host/swap send refs only; pasted Jellyfin links become refs; the host hands the relay its own app-obtained credential. - Each viewer resolves with their own account (token in a header) or via the relay, else a clear blocked card with Link account. - Per-account progress reporting (Playing/Progress/Stopped), 401 marks the account expired. - Previous/next episode in the controls (< > / Shift+P/N), floating Next episode pill near the end, auto-advance countdown (one designated swapper), track carry-over per series. - Swap panel uses the shared MediaPicker; browser location remembered per server and opens on the current series. - Fix: states are applied one at a time (a stale pause could land after a newer play). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
773a04369e
commit
ae4edc29e8
33 files changed
+3541
-175
No files matched your search
@@ -23,6 +23,7 @@ const _keyDeviceId = 'deviceId';
|
||||
const _keyAccounts = 'accounts';
|
||||
const _keyDefault = 'defaultServer';
|
||||
const _keyLastPick = 'lastPick';
|
||||
const _keyBrowsePrefix = 'browse:';
|
||||
|
||||
/// One signed-in user on one server.
|
||||
class JellyfinAccount {
|
||||
@@ -124,10 +125,12 @@ abstract class JellyfinStore {
|
||||
}
|
||||
|
||||
class HiveJellyfinStore implements JellyfinStore {
|
||||
HiveJellyfinStore({this.boxName = jellyfinBoxName});
|
||||
final String boxName;
|
||||
Box? _box;
|
||||
|
||||
@override
|
||||
Future<void> open() async => _box ??= await Hive.openBox(jellyfinBoxName);
|
||||
Future<void> open() async => _box ??= await Hive.openBox(boxName);
|
||||
|
||||
@override
|
||||
Object? get(String key) => _box?.get(key);
|
||||
@@ -461,6 +464,26 @@ class JellyfinAccounts extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser's last location on [serverId] (encoded route stack, see
|
||||
/// `browse_scope.dart`), restored by every browser and across restarts.
|
||||
Object? browseLocation(String serverId) {
|
||||
try {
|
||||
final v = _store.get('$_keyBrowsePrefix$serverId');
|
||||
return v is String ? _tryJson(v) : null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveBrowseLocation(String serverId, Object? location) async {
|
||||
try {
|
||||
await _store.put(
|
||||
'$_keyBrowsePrefix$serverId', location == null ? null : jsonEncode(location));
|
||||
} catch (e) {
|
||||
debugPrint('save browse location failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- cache
|
||||
|
||||
/// Short-lived memo for browse calls, so going back does not refetch.
|
||||
|
||||
@@ -53,6 +53,94 @@ final class DetailRoute extends BrowseRoute {
|
||||
String get key => 'item:${item.id}';
|
||||
}
|
||||
|
||||
/// A route stack as JSON for [JellyfinAccounts.saveBrowseLocation]: only
|
||||
/// ids, names and the fields the pages start from (each page loads the
|
||||
/// full item itself).
|
||||
List<Map<String, Object?>> encodeBrowseStack(List<BrowseRoute> stack) => [
|
||||
for (final r in stack)
|
||||
switch (r) {
|
||||
HomeRoute() => {'r': 'home'},
|
||||
LibraryRoute(:final folder) => {'r': 'lib', ..._itemJson(folder)},
|
||||
SeriesRoute(:final series, :final seasonId) => {
|
||||
'r': 'series',
|
||||
..._itemJson(series),
|
||||
'seasonId': ?seasonId,
|
||||
},
|
||||
DetailRoute(:final item) => {'r': 'item', ..._itemJson(item)},
|
||||
}
|
||||
];
|
||||
|
||||
/// Inverse of [encodeBrowseStack]; always starts with Home. Null when
|
||||
/// [raw] is not a stack.
|
||||
List<BrowseRoute>? decodeBrowseStack(Object? raw) {
|
||||
if (raw is! List) return null;
|
||||
final out = <BrowseRoute>[const HomeRoute()];
|
||||
for (final e in raw) {
|
||||
if (e is! Map) return null;
|
||||
final item = _itemFrom(e);
|
||||
final route = switch (e['r']) {
|
||||
'home' => null,
|
||||
'lib' when item != null => LibraryRoute(item),
|
||||
'series' when item != null =>
|
||||
SeriesRoute(item, seasonId: e['seasonId'] is String ? e['seasonId'] as String : null),
|
||||
'item' when item != null => DetailRoute(item),
|
||||
_ => null,
|
||||
};
|
||||
if (route != null && out.every((r) => r.key != route.key)) out.add(route);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Map<String, Object?> _itemJson(JellyfinItem i) => {
|
||||
'id': i.id,
|
||||
'name': i.name,
|
||||
'type': i.type,
|
||||
if (i.isFolder) 'isFolder': true,
|
||||
'collectionType': ?i.collectionType,
|
||||
'seriesId': ?i.seriesId,
|
||||
'seriesName': ?i.seriesName,
|
||||
'seasonId': ?i.seasonId,
|
||||
'indexNumber': ?i.indexNumber,
|
||||
'parentIndexNumber': ?i.parentIndexNumber,
|
||||
};
|
||||
|
||||
JellyfinItem? _itemFrom(Map e) {
|
||||
String? s(String k) => e[k] is String && (e[k] as String).isNotEmpty ? e[k] as String : null;
|
||||
final id = s('id');
|
||||
if (id == null) return null;
|
||||
return JellyfinItem(
|
||||
id: id,
|
||||
name: s('name') ?? '',
|
||||
type: s('type') ?? '',
|
||||
isFolder: e['isFolder'] == true,
|
||||
collectionType: s('collectionType'),
|
||||
seriesId: s('seriesId'),
|
||||
seriesName: s('seriesName'),
|
||||
seasonId: e['r'] == 'series' ? null : s('seasonId'),
|
||||
indexNumber: e['indexNumber'] is int ? e['indexNumber'] as int : null,
|
||||
parentIndexNumber: e['parentIndexNumber'] is int ? e['parentIndexNumber'] as int : null,
|
||||
);
|
||||
}
|
||||
|
||||
/// Where a browser opens instead of the remembered location: a server and
|
||||
/// a route stack (e.g. the series of the episode playing).
|
||||
class BrowseStart {
|
||||
final String serverId;
|
||||
final List<BrowseRoute> stack;
|
||||
const BrowseStart(this.serverId, this.stack);
|
||||
|
||||
/// The series page of [episode] with its season selected.
|
||||
static BrowseStart? seriesOf(String serverId, JellyfinItem episode) {
|
||||
final sid = episode.seriesId;
|
||||
if (sid == null) return null;
|
||||
return BrowseStart(serverId, [
|
||||
const HomeRoute(),
|
||||
SeriesRoute(JellyfinItem(id: sid, name: episode.seriesName ?? '', type: 'Series'),
|
||||
seasonId: episode.seasonId),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/// What every browser page needs, provided by [JellyfinBrowser].
|
||||
class BrowseScope extends InheritedWidget {
|
||||
final JellyfinAccounts accounts;
|
||||
|
||||
@@ -36,7 +36,11 @@ class JellyfinBrowser extends StatefulWidget {
|
||||
final bool expanded;
|
||||
final VoidCallback? onOpenIntegrations;
|
||||
final Duration searchDebounce;
|
||||
/// Opens here instead of the remembered location (the series of the
|
||||
/// episode playing, in the session's swap panel).
|
||||
final BrowseStart? start;
|
||||
const JellyfinBrowser({
|
||||
this.start,
|
||||
super.key,
|
||||
required this.accounts,
|
||||
required this.onPick,
|
||||
@@ -67,12 +71,32 @@ class _JellyfinBrowserState extends State<JellyfinBrowser> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_serverId = widget.selected != null && _accounts.account(widget.selected!.serverId) != null
|
||||
? widget.selected!.serverId
|
||||
: _accounts.defaultServerId;
|
||||
final start = widget.start;
|
||||
if (start != null && _accounts.account(start.serverId) != null) {
|
||||
_serverId = start.serverId;
|
||||
_stack = start.stack.isEmpty ? const [HomeRoute()] : start.stack;
|
||||
_remember();
|
||||
} else {
|
||||
_serverId = widget.selected != null && _accounts.account(widget.selected!.serverId) != null
|
||||
? widget.selected!.serverId
|
||||
: _accounts.defaultServerId;
|
||||
_stack = _restored(_serverId);
|
||||
}
|
||||
_accounts.addListener(_changed);
|
||||
}
|
||||
|
||||
/// The remembered location on [serverId], else Home.
|
||||
List<BrowseRoute> _restored(String? serverId) =>
|
||||
(serverId == null ? null : decodeBrowseStack(_accounts.browseLocation(serverId))) ??
|
||||
const [HomeRoute()];
|
||||
|
||||
/// Every navigation is saved per server (Hive), so the next browser
|
||||
/// (Host tab, swap panel, next start) opens where this one was.
|
||||
void _remember() {
|
||||
final id = _account?.serverId;
|
||||
if (id != null) unawaited(_accounts.saveBrowseLocation(id, encodeBrowseStack(_stack)));
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(JellyfinBrowser old) {
|
||||
super.didUpdateWidget(old);
|
||||
@@ -104,7 +128,7 @@ class _JellyfinBrowserState extends State<JellyfinBrowser> {
|
||||
if (serverId == _account?.serverId) return;
|
||||
setState(() {
|
||||
_serverId = serverId;
|
||||
_stack = const [HomeRoute()];
|
||||
_stack = _restored(serverId);
|
||||
_peek.value = null;
|
||||
_clearSearch();
|
||||
});
|
||||
@@ -117,12 +141,14 @@ class _JellyfinBrowserState extends State<JellyfinBrowser> {
|
||||
_clearSearch();
|
||||
if (_stack.last.key != route.key) _stack = [..._stack, route];
|
||||
});
|
||||
_remember();
|
||||
_body.requestFocus();
|
||||
}
|
||||
|
||||
bool _back() {
|
||||
if (_stack.length <= 1) return false;
|
||||
setState(() => _stack = _stack.sublist(0, _stack.length - 1));
|
||||
_remember();
|
||||
_body.requestFocus();
|
||||
return true;
|
||||
}
|
||||
@@ -132,6 +158,7 @@ class _JellyfinBrowserState extends State<JellyfinBrowser> {
|
||||
_clearSearch();
|
||||
_stack = _stack.sublist(0, index + 1);
|
||||
});
|
||||
_remember();
|
||||
_body.requestFocus();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
|
||||
import '../screens/home/picked_media.dart';
|
||||
import '../screens/home/ui.dart';
|
||||
import 'accounts.dart';
|
||||
import 'browse_scope.dart';
|
||||
import 'browser.dart';
|
||||
import 'sign_in_panel.dart';
|
||||
|
||||
@@ -15,8 +16,10 @@ class JellyfinPickerSource extends StatefulWidget {
|
||||
final VoidCallback? onOpenIntegrations;
|
||||
final VoidCallback? onToggleExpanded;
|
||||
final bool expanded;
|
||||
final BrowseStart? start;
|
||||
const JellyfinPickerSource({
|
||||
super.key,
|
||||
this.start,
|
||||
required this.accounts,
|
||||
required this.onPick,
|
||||
this.selected,
|
||||
@@ -54,6 +57,7 @@ class _JellyfinPickerSourceState extends State<JellyfinPickerSource> {
|
||||
onOpenIntegrations: widget.onOpenIntegrations,
|
||||
onToggleExpanded: widget.onToggleExpanded,
|
||||
expanded: widget.expanded,
|
||||
start: widget.start,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:sync_relay_core/core.dart';
|
||||
|
||||
/// What the player shows, sampled about once a second. [aid] / [sid] are
|
||||
/// mpv track ids (null = none / subtitles off).
|
||||
class PlayerSnapshot {
|
||||
final double position;
|
||||
final bool paused;
|
||||
final int? aid;
|
||||
final int? sid;
|
||||
const PlayerSnapshot({required this.position, required this.paused, this.aid, this.sid});
|
||||
|
||||
@override
|
||||
String toString() => 'PlayerSnapshot($position, paused: $paused, aid: $aid, sid: $sid)';
|
||||
}
|
||||
|
||||
/// Playing / Progress / Stopped for one item played with this viewer's own
|
||||
/// account, so Jellyfin's watched state and Continue Watching follow what
|
||||
/// this viewer saw. Fed a [PlayerSnapshot] every tick ([update]); sends
|
||||
/// Progress every [interval] and at once on pause, resume, seek (a jump of
|
||||
/// more than 3 s from where playback should be) or a track change. Reports
|
||||
/// go out one after another; a failure is logged and handed to [onError]
|
||||
/// (the session shows one quiet toast) and never touches playback. A 401
|
||||
/// calls [onUnauthorized] and ends reporting.
|
||||
class JellyfinProgressReporter {
|
||||
final JellyfinClient client;
|
||||
final String itemId;
|
||||
final JellyfinMediaSource source;
|
||||
final String playSessionId;
|
||||
final Duration interval;
|
||||
final DateTime Function() _clock;
|
||||
final void Function(Object error)? onError;
|
||||
final VoidCallback? onUnauthorized;
|
||||
|
||||
JellyfinProgressReporter({
|
||||
required this.client,
|
||||
required this.itemId,
|
||||
required this.source,
|
||||
required this.playSessionId,
|
||||
this.interval = const Duration(seconds: 10),
|
||||
this.onError,
|
||||
this.onUnauthorized,
|
||||
DateTime Function()? clock,
|
||||
}) : _clock = clock ?? DateTime.now;
|
||||
|
||||
Future<void> _chain = Future.value();
|
||||
bool _playing = false;
|
||||
bool _dead = false;
|
||||
PlayerSnapshot? _last;
|
||||
DateTime? _lastAt;
|
||||
DateTime? _lastSentAt;
|
||||
|
||||
/// Between [start] and [stop].
|
||||
bool get active => _playing && !_dead;
|
||||
|
||||
/// The report body for [s]: ticks, pause, and mpv's aid/sid mapped to
|
||||
/// Jellyfin stream indices (-1 = subtitles off).
|
||||
JellyfinPlaybackReport reportFor(PlayerSnapshot s) => JellyfinPlaybackReport(
|
||||
itemId: itemId,
|
||||
mediaSourceId: source.id,
|
||||
playSessionId: playSessionId,
|
||||
positionTicks: (s.position * jellyfinTicksPerSecond).round(),
|
||||
isPaused: s.paused,
|
||||
audioStreamIndex: s.aid == null
|
||||
? null
|
||||
: source.jellyfinIndexForMpvTrack(JellyfinStreamType.audio, s.aid!),
|
||||
subtitleStreamIndex: s.sid == null
|
||||
? -1
|
||||
: source.jellyfinIndexForMpvTrack(JellyfinStreamType.subtitle, s.sid!),
|
||||
);
|
||||
|
||||
/// Playing: once the media is open. Again after [stop] (played to the
|
||||
/// end, then someone seeked back) starts reporting anew.
|
||||
void start(PlayerSnapshot s) {
|
||||
if (_playing || _dead) return;
|
||||
_playing = true;
|
||||
_mark(s);
|
||||
_send('Playing', () => client.reportPlaybackStart(reportFor(s)));
|
||||
}
|
||||
|
||||
/// Progress when due (see the class doc).
|
||||
void update(PlayerSnapshot s, {bool force = false}) {
|
||||
if (!_playing || _dead) return;
|
||||
final last = _last, lastAt = _lastAt, sentAt = _lastSentAt;
|
||||
final now = _clock();
|
||||
var due = force || last == null || lastAt == null || sentAt == null;
|
||||
if (!due) {
|
||||
final elapsed = now.difference(lastAt).inMilliseconds / 1000;
|
||||
final expected = last.position + (last.paused ? 0 : elapsed);
|
||||
due = s.paused != last.paused ||
|
||||
s.aid != last.aid ||
|
||||
s.sid != last.sid ||
|
||||
(s.position - expected).abs() > 3 ||
|
||||
now.difference(sentAt) >= interval;
|
||||
}
|
||||
_last = s;
|
||||
_lastAt = now;
|
||||
if (!due) return;
|
||||
_lastSentAt = now;
|
||||
_send('Progress', () => client.reportPlaybackProgress(reportFor(s)));
|
||||
}
|
||||
|
||||
/// Stopped (swap, leave, kick, window close, played to the end).
|
||||
/// Completes when it and everything before it went out.
|
||||
Future<void> stop(PlayerSnapshot s) {
|
||||
if (!_playing || _dead) return _chain;
|
||||
_playing = false;
|
||||
_send('Stopped', () => client.reportPlaybackStopped(reportFor(s)));
|
||||
return _chain;
|
||||
}
|
||||
|
||||
void _mark(PlayerSnapshot s) {
|
||||
_last = s;
|
||||
_lastAt = _lastSentAt = _clock();
|
||||
}
|
||||
|
||||
void _send(String what, Future<void> Function() call) {
|
||||
_chain = _chain.then((_) async {
|
||||
if (_dead) return;
|
||||
try {
|
||||
await call().timeout(const Duration(seconds: 10));
|
||||
} catch (e) {
|
||||
debugPrint('jellyfin $what report for $itemId failed: $e');
|
||||
if (e is JellyfinException && e.isUnauthorized) {
|
||||
_dead = true;
|
||||
onUnauthorized?.call();
|
||||
}
|
||||
onError?.call(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:sync_relay_core/core.dart';
|
||||
|
||||
import '../screens/home/picked_media.dart';
|
||||
import 'accounts.dart';
|
||||
import 'format.dart';
|
||||
|
||||
// Jellyfin media in a session: turning picks and pasted links into refs
|
||||
// (the wire carries only `{serverId, itemId, ...}`), the hosted server's
|
||||
// relay credential, and how this viewer plays a ref (own account, relay,
|
||||
// or neither).
|
||||
|
||||
/// The wire ref of a browser pick.
|
||||
JellyfinRef refForPick(JellyfinMedia m) => JellyfinRef(
|
||||
serverId: m.serverId,
|
||||
itemId: m.itemId,
|
||||
mediaSourceId: m.mediaSourceId,
|
||||
title: m.title,
|
||||
subtitle: m.subtitle.isEmpty ? null : m.subtitle,
|
||||
runtimeSecs: m.runtime == null ? null : m.runtime!.inMilliseconds / 1000,
|
||||
);
|
||||
|
||||
/// The `swap` media for a browser pick: a ref, never a URL.
|
||||
HelloMedia mediaForPick(JellyfinMedia m) => HelloMedia(
|
||||
name: m.title.isEmpty ? 'Jellyfin item' : m.title,
|
||||
size: 0,
|
||||
duration: 0,
|
||||
jellyfin: refForPick(m));
|
||||
|
||||
/// The pick a ref stands for on a linked server (for highlighting it in
|
||||
/// the browser); null when this install has no account there.
|
||||
JellyfinMedia? pickForRef(JellyfinAccounts accounts, JellyfinRef ref) {
|
||||
final a = accounts.account(ref.serverId);
|
||||
if (a == null) return null;
|
||||
return JellyfinMedia(
|
||||
serverId: ref.serverId,
|
||||
baseUrl: a.baseUrl,
|
||||
itemId: ref.itemId,
|
||||
mediaSourceId: ref.mediaSourceId,
|
||||
title: ref.title,
|
||||
subtitle: ref.subtitle ?? '',
|
||||
runtime: ref.runtimeSecs == null
|
||||
? null
|
||||
: Duration(milliseconds: (ref.runtimeSecs! * 1000).round()),
|
||||
);
|
||||
}
|
||||
|
||||
/// The ref in a `state.media` map, or null for other media.
|
||||
JellyfinRef? refOfStateMedia(Map<String, Object?>? media) {
|
||||
final jf = media?['jellyfin'];
|
||||
if (jf is! Map) return null;
|
||||
try {
|
||||
final ref = JellyfinRef.fromJson(Map<String, Object?>.from(jf));
|
||||
return ref.serverId.isEmpty || ref.itemId.isEmpty ? null : ref;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Same item (server, item, source); titles may differ.
|
||||
bool sameJellyfinItem(JellyfinRef? a, JellyfinRef? b) =>
|
||||
a != null &&
|
||||
b != null &&
|
||||
a.serverId == b.serverId &&
|
||||
a.itemId == b.itemId &&
|
||||
a.mediaSourceId == b.mediaSourceId;
|
||||
|
||||
final _sourceId = RegExp(r'^[A-Za-z0-9-]{1,64}$');
|
||||
|
||||
/// What a pasted link becomes on the wire. A recognised Jellyfin item link
|
||||
/// (`parseJellyfinLink`) becomes a ref when its ServerId is known (in the
|
||||
/// link or from `/System/Info/Public`); its `api_key` is never shared then.
|
||||
/// Anything else, or a server that does not answer, stays a plain link.
|
||||
/// The title comes from this install's account on that server when there
|
||||
/// is one.
|
||||
Future<HelloMedia> mediaForLink(JellyfinAccounts accounts, String url,
|
||||
{Duration timeout = const Duration(seconds: 6)}) async {
|
||||
final plain = HelloMedia(name: linkName(url), size: 0, duration: 0, url: url);
|
||||
final link = parseJellyfinLink(url);
|
||||
if (link == null) return plain;
|
||||
await accounts.ensureLoaded();
|
||||
var serverId = link.serverId;
|
||||
if (serverId == null || serverId.isEmpty) {
|
||||
final probe = accounts.anonymousClient(link.baseUrl);
|
||||
try {
|
||||
serverId = (await probe.publicInfo().timeout(timeout)).id;
|
||||
} catch (e) {
|
||||
debugPrint('jellyfin link: no server id from ${link.baseUrl}: $e');
|
||||
return plain;
|
||||
} finally {
|
||||
probe.close();
|
||||
}
|
||||
if (serverId.isEmpty) return plain;
|
||||
}
|
||||
final src = Uri.tryParse(url)?.queryParameters['mediaSourceId'];
|
||||
var ref = JellyfinRef(
|
||||
serverId: serverId,
|
||||
itemId: link.itemId,
|
||||
mediaSourceId: src != null && _sourceId.hasMatch(src) && src != link.itemId ? src : null,
|
||||
);
|
||||
final account = accounts.account(serverId);
|
||||
final client = accounts.clientFor(serverId);
|
||||
if (account != null && client != null) {
|
||||
try {
|
||||
final pick = pickFor(account, await client.item(link.itemId).timeout(timeout));
|
||||
ref = refForPick(JellyfinMedia(
|
||||
serverId: serverId,
|
||||
baseUrl: account.baseUrl,
|
||||
itemId: link.itemId,
|
||||
mediaSourceId: ref.mediaSourceId,
|
||||
title: pick.title,
|
||||
subtitle: pick.subtitle,
|
||||
runtime: pick.runtime,
|
||||
));
|
||||
} catch (e) {
|
||||
if (e is JellyfinException && e.isUnauthorized) accounts.markExpired(serverId);
|
||||
}
|
||||
}
|
||||
return HelloMedia(
|
||||
name: ref.title.isEmpty ? 'Jellyfin item' : ref.title, size: 0, duration: 0, jellyfin: ref);
|
||||
}
|
||||
|
||||
/// Display name for a link: last path segment, decoded, never the query
|
||||
/// (Jellyfin-style links carry api_key there and names are broadcast).
|
||||
String linkName(String url) {
|
||||
final uri = Uri.tryParse(url.trim());
|
||||
if (uri == null) return 'link';
|
||||
final segs = uri.pathSegments.where((s) => s.isNotEmpty).toList();
|
||||
if (segs.isNotEmpty) {
|
||||
try {
|
||||
return Uri.decodeComponent(segs.last);
|
||||
} catch (_) {
|
||||
return segs.last;
|
||||
}
|
||||
}
|
||||
return uri.host.isNotEmpty ? uri.host : 'link';
|
||||
}
|
||||
|
||||
/// The hosted server's relay login: the account for [serverId] (the
|
||||
/// hosted item's server), else the default account, when its token is not
|
||||
/// known to be expired. The device fields are exactly the ones this app
|
||||
/// sends with that token ([JellyfinAccounts.clientInfo]): Jellyfin rewrites
|
||||
/// a token's device from the request header, so the relay must not differ.
|
||||
JellyfinCredential? relayCredentialFor(JellyfinAccounts accounts, {String? serverId}) {
|
||||
bool usable(JellyfinAccount? a) =>
|
||||
a != null && accounts.statusOf(a.serverId) != JellyfinAccountStatus.expired;
|
||||
var a = serverId == null ? null : accounts.account(serverId);
|
||||
if (!usable(a)) a = accounts.defaultAccount;
|
||||
if (!usable(a)) return null;
|
||||
final info = accounts.clientInfo;
|
||||
return JellyfinCredential(
|
||||
baseUrl: a!.baseUrl,
|
||||
serverId: a.serverId,
|
||||
token: a.token,
|
||||
client: info.client,
|
||||
device: info.device,
|
||||
deviceId: info.deviceId,
|
||||
version: info.version,
|
||||
);
|
||||
}
|
||||
|
||||
/// `/j/...` URL of the current Jellyfin media on the host this client
|
||||
/// dialled, built like the `/m/...` one.
|
||||
String relayUrlFor(String host, int port, String token, String itemId) =>
|
||||
'http://$host:$port/j/default/$token/${Uri.encodeComponent(itemId)}';
|
||||
|
||||
// ---------------------------------------------------------------- playing
|
||||
|
||||
/// How this viewer plays a ref.
|
||||
sealed class JellyfinPlan {
|
||||
const JellyfinPlan();
|
||||
|
||||
/// `report.jf` for this plan; null when it plays nothing.
|
||||
bool? get jfAccess;
|
||||
}
|
||||
|
||||
/// Direct play with this install's account: the static stream, the token
|
||||
/// in [headers] (not in the URL), progress reported per [info].
|
||||
final class OwnPlay extends JellyfinPlan {
|
||||
final JellyfinClient client;
|
||||
final JellyfinAccount account;
|
||||
final JellyfinPlaybackInfo info;
|
||||
final JellyfinMediaSource source;
|
||||
/// Full item (series, episode numbers); null if that call failed.
|
||||
final JellyfinItem? item;
|
||||
final String url;
|
||||
final Map<String, String> headers;
|
||||
const OwnPlay({
|
||||
required this.client,
|
||||
required this.account,
|
||||
required this.info,
|
||||
required this.source,
|
||||
required this.item,
|
||||
required this.url,
|
||||
required this.headers,
|
||||
});
|
||||
|
||||
@override
|
||||
bool get jfAccess => true;
|
||||
}
|
||||
|
||||
/// Through the sync server's relay (`/j/...`).
|
||||
final class RelayPlay extends JellyfinPlan {
|
||||
final String url;
|
||||
const RelayPlay(this.url);
|
||||
|
||||
@override
|
||||
bool get jfAccess => false;
|
||||
}
|
||||
|
||||
/// Neither: no (usable) account here and the server cannot relay.
|
||||
final class BlockedPlay extends JellyfinPlan {
|
||||
final String serverId;
|
||||
/// Known only when this install has (had) an account there.
|
||||
final String? serverName;
|
||||
/// Why the own account did not work, if there is one.
|
||||
final String? problem;
|
||||
const BlockedPlay({required this.serverId, this.serverName, this.problem});
|
||||
|
||||
@override
|
||||
bool? get jfAccess => null;
|
||||
|
||||
String get message {
|
||||
final where = serverName == null || serverName!.isEmpty ? 'that Jellyfin server' : serverName!;
|
||||
final base = 'This needs a Jellyfin account on $where (or the host can relay)';
|
||||
return problem == null ? base : '$base — $problem';
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks how to play [ref]: this install's account first (PlaybackInfo
|
||||
/// with its own user; a 401 marks the account expired), else the relay
|
||||
/// when the server offers it ([relay] = `state.relay`, [relayUrl] this
|
||||
/// member's `/j/...` URL), else [BlockedPlay].
|
||||
Future<JellyfinPlan> resolveJellyfinRef(
|
||||
JellyfinAccounts accounts,
|
||||
JellyfinRef ref, {
|
||||
required bool relay,
|
||||
required String? relayUrl,
|
||||
Duration timeout = const Duration(seconds: 15),
|
||||
}) async {
|
||||
await accounts.ensureLoaded();
|
||||
final account = accounts.account(ref.serverId);
|
||||
String? problem;
|
||||
if (account != null && accounts.statusOf(ref.serverId) == JellyfinAccountStatus.expired) {
|
||||
problem = 'your sign-in expired, reconnect it in Integrations';
|
||||
} else if (account != null) {
|
||||
final client = accounts.clientFor(ref.serverId)!;
|
||||
try {
|
||||
final infoF = client.playbackInfo(ref.itemId, mediaSourceId: ref.mediaSourceId).timeout(timeout);
|
||||
final itemF = client
|
||||
.item(ref.itemId)
|
||||
.timeout(timeout)
|
||||
.then<JellyfinItem?>((i) => i, onError: (Object _) => null);
|
||||
final info = await infoF;
|
||||
final item = await itemF;
|
||||
final source = (ref.mediaSourceId == null
|
||||
? null
|
||||
: info.mediaSources.where((s) => s.id == ref.mediaSourceId).firstOrNull) ??
|
||||
info.primarySource;
|
||||
if (source == null) throw const JellyfinException('no playable source');
|
||||
return OwnPlay(
|
||||
client: client,
|
||||
account: account,
|
||||
info: info,
|
||||
source: source,
|
||||
item: item,
|
||||
url: client.shareableStreamUrl(ref.itemId, mediaSourceId: source.id).toString(),
|
||||
headers: client.authHeaders,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('jellyfin resolve ${ref.itemId} with own account failed: $e');
|
||||
if (e is JellyfinException && e.isUnauthorized) {
|
||||
accounts.markExpired(ref.serverId);
|
||||
problem = 'your sign-in expired, reconnect it in Integrations';
|
||||
} else if (e is JellyfinException && e.statusCode == 404) {
|
||||
problem = 'your account cannot see this item';
|
||||
} else {
|
||||
problem = 'could not reach it';
|
||||
}
|
||||
}
|
||||
}
|
||||
if (relay && relayUrl != null && relayUrl.isNotEmpty) return RelayPlay(relayUrl);
|
||||
return BlockedPlay(serverId: ref.serverId, serverName: account?.displayName, problem: problem);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ next episode
|
||||
|
||||
/// A neighbouring episode as this viewer can put it up.
|
||||
class EpisodeLink {
|
||||
final JellyfinItem item;
|
||||
final JellyfinMedia pick;
|
||||
const EpisodeLink(this.item, this.pick);
|
||||
|
||||
/// "S1E7 Battle with the Heroes".
|
||||
String get label => [?item.episodeLabel, item.name].join(' ');
|
||||
}
|
||||
|
||||
/// The episodes before and after the one [plan] plays, with its account.
|
||||
/// Both null for movies, at the ends of a series, or on failure.
|
||||
Future<({EpisodeLink? previous, EpisodeLink? next})> findAdjacentEpisodes(OwnPlay plan,
|
||||
{Duration timeout = const Duration(seconds: 15)}) async {
|
||||
const none = (previous: null, next: null);
|
||||
final item = plan.item;
|
||||
if (item == null || item.kind != JellyfinItemKind.episode || item.seriesId == null) return none;
|
||||
try {
|
||||
final around = await plan.client.adjacentEpisodes(item).timeout(timeout);
|
||||
EpisodeLink? link(JellyfinItem? i) => i == null ? null : EpisodeLink(i, pickFor(plan.account, i));
|
||||
return (previous: link(around.previous), next: link(around.next));
|
||||
} catch (e) {
|
||||
debugPrint('episode lookup failed: $e');
|
||||
return none;
|
||||
}
|
||||
}
|
||||
|
||||
/// When the floating "Next episode" pill appears: the last two minutes of
|
||||
/// [runtime] (all of it for shorter media). One place to switch it to the
|
||||
/// item's outro / credits segment later.
|
||||
Duration nextPromptStart(JellyfinItem? item, Duration runtime) {
|
||||
const lead = Duration(minutes: 2);
|
||||
return runtime > lead ? runtime - lead : Duration.zero;
|
||||
}
|
||||
|
||||
/// Who performs the auto-advance swap, so several counting clients do not
|
||||
/// swap twice: the lowest member id among members that play the item with
|
||||
/// their own account (`jf[serverId] == true`, not stale). Only what every
|
||||
/// client sees in `state` decides (who put the item up is not in it: a
|
||||
/// late joiner never saw that swap), so all clients agree.
|
||||
String? autoAdvanceSwapper(List<MemberView> members, String serverId) {
|
||||
final eligible = [
|
||||
for (final m in members)
|
||||
if (!m.stale && m.jf[serverId] == true) m
|
||||
];
|
||||
if (eligible.isEmpty) return null;
|
||||
eligible.sort((a, b) => compareMemberIds(a.id, b.id));
|
||||
return eligible.first.id;
|
||||
}
|
||||
|
||||
/// "m2" before "m10": numeric suffix order, then plain text.
|
||||
int compareMemberIds(String a, String b) {
|
||||
final na = int.tryParse(a.replaceFirst(RegExp(r'^\D+'), ''));
|
||||
final nb = int.tryParse(b.replaceFirst(RegExp(r'^\D+'), ''));
|
||||
if (na != null && nb != null && na != nb) return na.compareTo(nb);
|
||||
return a.compareTo(b);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:sync_relay_core/core.dart';
|
||||
|
||||
import 'accounts.dart';
|
||||
|
||||
// Per-viewer audio/subtitle carry-over: the last choice is kept per series
|
||||
// (and as a global fallback) and matched against the next Jellyfin item's
|
||||
// tracks with core's `matchTrack`. Local only; nothing goes on the wire.
|
||||
|
||||
const trackPrefsBoxName = 'track_prefs';
|
||||
const _keyGlobal = 'global';
|
||||
|
||||
/// One mpv track as media_kit lists it ([id] is mpv's `aid` / `sid`).
|
||||
class MpvTrack {
|
||||
final int id;
|
||||
final JellyfinStreamType type;
|
||||
final String? language;
|
||||
final String? title;
|
||||
final String? codec;
|
||||
final int? channels;
|
||||
final bool isDefault;
|
||||
const MpvTrack({
|
||||
required this.id,
|
||||
required this.type,
|
||||
this.language,
|
||||
this.title,
|
||||
this.codec,
|
||||
this.channels,
|
||||
this.isDefault = false,
|
||||
});
|
||||
|
||||
/// As a stream for [matchTrack]; its index is the mpv id.
|
||||
JellyfinMediaStream get asStream => JellyfinMediaStream(
|
||||
index: id,
|
||||
type: type,
|
||||
language: language,
|
||||
title: title,
|
||||
codec: codec,
|
||||
channels: channels,
|
||||
isDefault: isDefault);
|
||||
|
||||
/// Menu text: "English (eac3 2ch)", "Track 2".
|
||||
String get label {
|
||||
final name = title ?? language ?? 'Track $id';
|
||||
final extra = [?codec, if (channels != null) '${channels}ch'].join(' ');
|
||||
final lang = title != null && language != null ? ' [$language]' : '';
|
||||
return extra.isEmpty ? '$name$lang' : '$name$lang ($extra)';
|
||||
}
|
||||
}
|
||||
|
||||
/// A viewer's audio/subtitle choice as traits (indices shift between
|
||||
/// files). [subtitlesOff] wins over [subtitle].
|
||||
class TrackChoice {
|
||||
final TrackPreference? audio;
|
||||
final TrackPreference? subtitle;
|
||||
final bool subtitlesOff;
|
||||
const TrackChoice({this.audio, this.subtitle, this.subtitlesOff = false});
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'audio': ?_prefToJson(audio),
|
||||
'subtitle': ?_prefToJson(subtitle),
|
||||
'subtitlesOff': subtitlesOff,
|
||||
};
|
||||
|
||||
static TrackChoice? fromJson(Object? j) {
|
||||
if (j is! Map) return null;
|
||||
return TrackChoice(
|
||||
audio: _prefFromJson(j['audio'], JellyfinStreamType.audio),
|
||||
subtitle: _prefFromJson(j['subtitle'], JellyfinStreamType.subtitle),
|
||||
subtitlesOff: j['subtitlesOff'] == true,
|
||||
);
|
||||
}
|
||||
|
||||
/// The choice behind mpv's [aid] / [sid] (null = none / off): traits from
|
||||
/// the Jellyfin [source] when this viewer has it (title, channels,
|
||||
/// forced/HI flags), else from mpv's [tracks].
|
||||
factory TrackChoice.of({
|
||||
required int? aid,
|
||||
required int? sid,
|
||||
JellyfinMediaSource? source,
|
||||
List<MpvTrack> tracks = const [],
|
||||
}) {
|
||||
TrackPreference? pref(JellyfinStreamType type, int? id) {
|
||||
if (id == null) return null;
|
||||
if (source != null) {
|
||||
final index = source.jellyfinIndexForMpvTrack(type, id);
|
||||
final s = index == null ? null : source.streamAt(index);
|
||||
if (s != null) return TrackPreference.fromStream(s);
|
||||
}
|
||||
final t = tracks.where((t) => t.type == type && t.id == id).firstOrNull;
|
||||
return t == null ? null : TrackPreference.fromStream(t.asStream);
|
||||
}
|
||||
|
||||
return TrackChoice(
|
||||
audio: pref(JellyfinStreamType.audio, aid),
|
||||
subtitle: pref(JellyfinStreamType.subtitle, sid),
|
||||
subtitlesOff: sid == null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object?>? _prefToJson(TrackPreference? p) => p == null
|
||||
? null
|
||||
: {
|
||||
'language': ?p.language,
|
||||
'title': ?p.title,
|
||||
'codec': ?p.codec,
|
||||
'channels': ?p.channels,
|
||||
if (p.isForced) 'forced': true,
|
||||
if (p.isHearingImpaired) 'hi': true,
|
||||
};
|
||||
|
||||
TrackPreference? _prefFromJson(Object? j, JellyfinStreamType type) {
|
||||
if (j is! Map) return null;
|
||||
String? s(Object? v) => v is String && v.isNotEmpty ? v : null;
|
||||
return TrackPreference(
|
||||
type: type,
|
||||
language: s(j['language']),
|
||||
title: s(j['title']),
|
||||
codec: s(j['codec']),
|
||||
channels: j['channels'] is int ? j['channels'] as int : null,
|
||||
isForced: j['forced'] == true,
|
||||
isHearingImpaired: j['hi'] == true,
|
||||
);
|
||||
}
|
||||
|
||||
/// mpv tracks to select for [choice] on a new item. Matches against the
|
||||
/// Jellyfin [source]'s streams when this viewer has them (mapped to mpv ids
|
||||
/// with [JellyfinMediaSource.mpvTrackId]), else against mpv's [tracks].
|
||||
/// Null fields keep the player's default; [subtitlesOff] turns them off.
|
||||
({int? aid, int? sid, bool subtitlesOff}) chooseTracks(TrackChoice choice,
|
||||
{JellyfinMediaSource? source, List<MpvTrack> tracks = const []}) {
|
||||
int? pick(TrackPreference? pref) {
|
||||
if (pref == null) return null;
|
||||
if (source != null) {
|
||||
final s = matchTrack(pref, source.mediaStreams);
|
||||
return s == null ? null : source.mpvTrackId(s.index);
|
||||
}
|
||||
return matchTrack(pref, [for (final t in tracks) t.asStream])?.index;
|
||||
}
|
||||
|
||||
return (
|
||||
aid: pick(choice.audio),
|
||||
sid: choice.subtitlesOff ? null : pick(choice.subtitle),
|
||||
subtitlesOff: choice.subtitlesOff,
|
||||
);
|
||||
}
|
||||
|
||||
/// The last choice per series and overall, in their own Hive box.
|
||||
class TrackPrefs {
|
||||
TrackPrefs({JellyfinStore? store}) : _store = store ?? HiveJellyfinStore(boxName: trackPrefsBoxName);
|
||||
final JellyfinStore _store;
|
||||
Future<void>? _open;
|
||||
|
||||
Future<void> _ready() => _open ??= _store.open().catchError((Object e) {
|
||||
debugPrint('open track prefs failed: $e');
|
||||
});
|
||||
|
||||
/// The series' choice, else the global one.
|
||||
Future<TrackChoice?> load({String? seriesId}) async {
|
||||
await _ready();
|
||||
try {
|
||||
Object? read(String key) {
|
||||
final v = _store.get(key);
|
||||
return v is String ? jsonDecode(v) : null;
|
||||
}
|
||||
|
||||
return (seriesId == null ? null : TrackChoice.fromJson(read('series:$seriesId'))) ??
|
||||
TrackChoice.fromJson(read(_keyGlobal));
|
||||
} catch (e) {
|
||||
debugPrint('read track prefs failed: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves [choice] as the global one and, with [seriesId], the series'.
|
||||
Future<void> save(TrackChoice choice, {String? seriesId}) async {
|
||||
await _ready();
|
||||
try {
|
||||
final v = jsonEncode(choice.toJson());
|
||||
await _store.put(_keyGlobal, v);
|
||||
if (seriesId != null) await _store.put('series:$seriesId', v);
|
||||
} catch (e) {
|
||||
debugPrint('save track prefs failed: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import 'package:flutter/widgets.dart';
|
||||
import 'package:media_kit/media_kit.dart';
|
||||
import 'package:media_kit_video/media_kit_video.dart';
|
||||
import 'package:signals/signals_flutter.dart';
|
||||
import 'package:sync_relay_core/core.dart' show JellyfinStreamType;
|
||||
|
||||
import '../jellyfin/track_prefs.dart' show MpvTrack;
|
||||
|
||||
import '../shaders/shader_assets.dart';
|
||||
import '../shaders/shader_presets.dart';
|
||||
@@ -356,16 +359,89 @@ class PlaybackController {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> openUrl(String url) async {
|
||||
/// Opens [url] paused. [headers] go with every request for it (mpv
|
||||
/// `http-header-fields`): a Jellyfin token travels there, not in the URL.
|
||||
Future<void> openUrl(String url, {Map<String, String>? headers}) async {
|
||||
if (!_ready) return;
|
||||
try {
|
||||
await player.open(Media(url), play: false);
|
||||
// An empty map, not null: media_kit caches headers per URI.
|
||||
await player.open(Media(url, httpHeaders: headers ?? const {}), play: false);
|
||||
} catch (e, st) {
|
||||
debugPrint('open $url failed: $e\n$st');
|
||||
debugPrint('open ${Uri.tryParse(url)?.replace(query: '') ?? 'media'} failed: $e\n$st');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// The audio / subtitle tracks of the open file (mpv's track-list).
|
||||
List<MpvTrack> get tracks {
|
||||
final p = _player;
|
||||
if (p == null) return const [];
|
||||
MpvTrack? of(dynamic t, JellyfinStreamType type) {
|
||||
final id = int.tryParse('${t.id}');
|
||||
if (id == null) return null;
|
||||
return MpvTrack(
|
||||
id: id,
|
||||
type: type,
|
||||
language: t.language as String?,
|
||||
title: t.title as String?,
|
||||
codec: t.codec as String?,
|
||||
channels: (t.channelscount ?? t.audiochannels) as int?,
|
||||
isDefault: t.isDefault == true,
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
for (final t in p.state.tracks.audio) ?of(t, JellyfinStreamType.audio),
|
||||
for (final t in p.state.tracks.subtitle) ?of(t, JellyfinStreamType.subtitle),
|
||||
];
|
||||
}
|
||||
|
||||
/// Waits (bounded) until the open file's tracks are listed and mpv has
|
||||
/// selected its audio track, so a report or a carried-over choice sees
|
||||
/// the real selection.
|
||||
Future<List<MpvTrack>> waitForTracks({Duration timeout = const Duration(seconds: 5)}) async {
|
||||
final end = DateTime.now().add(timeout);
|
||||
while (_player != null && DateTime.now().isBefore(end)) {
|
||||
final t = tracks;
|
||||
final hasAudio = t.any((x) => x.type == JellyfinStreamType.audio);
|
||||
if (t.isNotEmpty && (!hasAudio || (await currentTrackIds()).aid != null)) return t;
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
/// mpv's selected audio and subtitle track ids (null = none / off).
|
||||
Future<({int? aid, int? sid})> currentTrackIds() async {
|
||||
final p = _player;
|
||||
if (p == null) return (aid: null, sid: null);
|
||||
try {
|
||||
final dynamic platform = p.platform;
|
||||
final aid = int.tryParse('${await platform?.getProperty('current-tracks/audio/id')}');
|
||||
final sid = int.tryParse('${await platform?.getProperty('current-tracks/sub/id')}');
|
||||
return (aid: aid, sid: sid);
|
||||
} catch (_) {
|
||||
return (aid: null, sid: null);
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects tracks by mpv id; a null [aid] keeps audio, [subtitlesOff]
|
||||
/// turns subtitles off, else a null [sid] keeps them.
|
||||
Future<void> selectTracks({int? aid, int? sid, bool subtitlesOff = false}) async {
|
||||
final p = _player;
|
||||
if (p == null) return;
|
||||
try {
|
||||
final dynamic platform = p.platform;
|
||||
if (aid != null) await platform?.setProperty('aid', '$aid');
|
||||
if (subtitlesOff) {
|
||||
await platform?.setProperty('sid', 'no');
|
||||
} else if (sid != null) {
|
||||
await platform?.setProperty('sid', '$sid');
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('select tracks failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
double get positionSecs {
|
||||
final p = _player;
|
||||
if (p == null) return 0;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:sync_relay_core/core.dart' show HelloMedia;
|
||||
|
||||
import '../../session/session_coordinator.dart';
|
||||
import '../../state/session_state.dart';
|
||||
@@ -91,11 +92,11 @@ class ConnectFlow extends ChangeNotifier {
|
||||
}
|
||||
|
||||
/// [edit] fills the card's fields into a copy of the last form, so the
|
||||
/// other card's saved values survive. [linkOverride] (host only) is played
|
||||
/// as the link but never stored in the form: the interim Jellyfin stream
|
||||
/// URL carries a token.
|
||||
/// other card's saved values survive. [media] (host only) is put up
|
||||
/// instead of the form's link or file (a Jellyfin ref; the pick itself is
|
||||
/// remembered in the Jellyfin box, not the form).
|
||||
Future<void> submit(ConnectMode mode, void Function(ConnectForm f) edit,
|
||||
{String? linkOverride}) async {
|
||||
{HelloMedia? media}) async {
|
||||
if (busy != null) return;
|
||||
final myAttempt = ++_attempt;
|
||||
final form = _session.lastForm.copy();
|
||||
@@ -113,15 +114,10 @@ class ConnectFlow extends ChangeNotifier {
|
||||
notices[mode] = null;
|
||||
_notify();
|
||||
|
||||
final ConnectParams params;
|
||||
ConnectParams params;
|
||||
try {
|
||||
params = await buildParams(
|
||||
mode,
|
||||
linkOverride == null || mode != ConnectMode.host
|
||||
? form
|
||||
: (form.copy()
|
||||
..mediaPath = ''
|
||||
..linkUrl = linkOverride));
|
||||
params = await buildParams(mode, form);
|
||||
if (media != null && mode == ConnectMode.host) params = params.withMedia(media);
|
||||
} catch (e) {
|
||||
if (myAttempt != _attempt) return;
|
||||
busy = null;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:signals/signals_flutter.dart';
|
||||
import 'package:sync_relay_core/core.dart' show HelloMedia;
|
||||
|
||||
import '../../jellyfin/accounts.dart';
|
||||
import '../../jellyfin/session_media.dart';
|
||||
import '../../state/session_state.dart';
|
||||
import 'connect_flow.dart';
|
||||
import 'connect_status.dart';
|
||||
@@ -48,20 +50,17 @@ class HostFields {
|
||||
}
|
||||
}
|
||||
|
||||
/// INTERIM(jellyfin-protocol): until the protocol carries a Jellyfin item,
|
||||
/// the host plays it as a link: this install's authorised static stream URL
|
||||
/// (token in the query, so viewers stream with the host's sign-in and the
|
||||
/// URL must not be persisted). Throws [FormatException] with a user-facing
|
||||
/// message when the server is not linked any more.
|
||||
String interimJellyfinLink(JellyfinAccounts accounts, JellyfinMedia media) {
|
||||
final client = accounts.clientFor(media.serverId);
|
||||
if (client == null) {
|
||||
/// What hosting a picked Jellyfin item sends: its ref (no URL, no token).
|
||||
/// Throws [FormatException] with a user-facing message when the server is
|
||||
/// not linked any more or its sign-in expired.
|
||||
HelloMedia hostJellyfinMedia(JellyfinAccounts accounts, JellyfinMedia media) {
|
||||
if (accounts.account(media.serverId) == null) {
|
||||
throw const FormatException('that Jellyfin server is not linked any more — pick again');
|
||||
}
|
||||
if (accounts.statusOf(media.serverId) == JellyfinAccountStatus.expired) {
|
||||
throw const FormatException('Jellyfin sign-in expired — reconnect it in Integrations');
|
||||
}
|
||||
return client.streamUrl(media.itemId, mediaSourceId: media.mediaSourceId).toString();
|
||||
return mediaForPick(media);
|
||||
}
|
||||
|
||||
/// Below this width the server column moves under the media picker.
|
||||
@@ -79,10 +78,10 @@ class HostTab extends StatelessWidget {
|
||||
void _host() {
|
||||
if (flow.busy != null) return;
|
||||
final media = fields.media.selection;
|
||||
String? link;
|
||||
HelloMedia? jellyfinMedia;
|
||||
if (media is JellyfinMedia) {
|
||||
try {
|
||||
link = interimJellyfinLink(fields.jellyfin, media);
|
||||
jellyfinMedia = hostJellyfinMedia(fields.jellyfin, media);
|
||||
} on FormatException catch (e) {
|
||||
flow.showError(ConnectMode.host, CardError('Check the form', e.message));
|
||||
return;
|
||||
@@ -96,7 +95,7 @@ class HostTab extends StatelessWidget {
|
||||
..hostSecret = fields.secret.text
|
||||
..mediaPath = media is FileMedia ? media.path : ''
|
||||
..linkUrl = media is LinkMedia ? media.url : '',
|
||||
linkOverride: link,
|
||||
media: jellyfinMedia,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../jellyfin/accounts.dart';
|
||||
import '../../jellyfin/browse_scope.dart' show BrowseStart;
|
||||
import '../../jellyfin/picker_source.dart';
|
||||
import '../../widgets/media_input.dart';
|
||||
import 'picked_media.dart';
|
||||
@@ -114,8 +115,17 @@ class MediaPicker extends StatefulWidget {
|
||||
/// Jellyfin source only: the browser's "bigger" toggle.
|
||||
final VoidCallback? onToggleExpanded;
|
||||
final bool expanded;
|
||||
/// Where the Jellyfin browser opens instead of its remembered location.
|
||||
final BrowseStart? jellyfinStart;
|
||||
/// False hides the File source (only the host can serve a file).
|
||||
final bool allowFile;
|
||||
/// Shown under the Link field instead of the default help.
|
||||
final String? linkHelp;
|
||||
const MediaPicker({
|
||||
super.key,
|
||||
this.jellyfinStart,
|
||||
this.allowFile = true,
|
||||
this.linkHelp,
|
||||
required this.controller,
|
||||
this.onChanged,
|
||||
this.onSubmit,
|
||||
@@ -221,6 +231,7 @@ class _MediaPickerState extends State<MediaPicker> {
|
||||
onOpenIntegrations: widget.onOpenIntegrations,
|
||||
onToggleExpanded: widget.onToggleExpanded,
|
||||
expanded: widget.expanded,
|
||||
start: widget.jellyfinStart,
|
||||
),
|
||||
MediaKind.link => _FieldRow(
|
||||
key: const ValueKey('media-link'),
|
||||
@@ -236,7 +247,9 @@ class _MediaPickerState extends State<MediaPicker> {
|
||||
icon: const Icon(Icons.content_paste, size: 18),
|
||||
label: const Text('Paste'),
|
||||
),
|
||||
help: 'A direct http(s) link to a video file; everyone streams it from there.',
|
||||
help: widget.linkHelp ??
|
||||
'A direct http(s) link to a video file; everyone streams it from there. '
|
||||
'Jellyfin links are shared as the item, without your sign-in.',
|
||||
notice: _c.notice,
|
||||
),
|
||||
MediaKind.file => _FieldRow(
|
||||
@@ -260,17 +273,17 @@ class _MediaPickerState extends State<MediaPicker> {
|
||||
child: SegmentedButton<MediaKind>(
|
||||
key: const ValueKey('media-source'),
|
||||
showSelectedIcon: false,
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
segments: [
|
||||
const ButtonSegment(
|
||||
value: MediaKind.jellyfin,
|
||||
icon: Icon(Icons.video_library_outlined),
|
||||
label: Text('Jellyfin')),
|
||||
ButtonSegment(value: MediaKind.link, icon: Icon(Icons.link), label: Text('Link')),
|
||||
ButtonSegment(
|
||||
const ButtonSegment(value: MediaKind.link, icon: Icon(Icons.link), label: Text('Link')),
|
||||
const ButtonSegment(
|
||||
value: MediaKind.file,
|
||||
icon: Icon(Icons.insert_drive_file_outlined),
|
||||
label: Text('File')),
|
||||
],
|
||||
].where((s) => widget.allowFile || s.value != MediaKind.file).toList(),
|
||||
selected: {source},
|
||||
onSelectionChanged: (s) => _c.source = s.first,
|
||||
),
|
||||
|
||||
@@ -17,6 +17,7 @@ const sessionShortcuts = [
|
||||
('F', 'Toggle fullscreen'),
|
||||
('Tab', 'Open / close the people & chat panel'),
|
||||
('Ctrl+R', 'Reload the video'),
|
||||
('> or Shift+N', 'Put up the next Jellyfin episode'),
|
||||
('Ctrl+1…6', 'Shaders: Anime4K mode A, B, C, A+A, B+B, C+A'),
|
||||
('Ctrl+0', 'Shaders off'),
|
||||
('Esc', 'Close panel or fullscreen, else ask to leave'),
|
||||
@@ -34,6 +35,7 @@ class SettingsPage extends StatelessWidget {
|
||||
const PageTitle('Settings'),
|
||||
const _Section(title: 'Profile', child: ProfileEditor()),
|
||||
const _Section(title: 'Player', child: _HwdecSetting()),
|
||||
const _Section(title: 'Jellyfin', child: _AutoAdvanceSetting()),
|
||||
_Section(title: 'Updates', child: _UpdateSettings(controller: updates)),
|
||||
const _Section(title: 'Keyboard shortcuts', child: _ShortcutList()),
|
||||
const _Section(title: 'Video quality & shaders', child: _ShaderSettings()),
|
||||
@@ -290,6 +292,26 @@ class _UpdateSettings extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
class _AutoAdvanceSetting extends StatelessWidget {
|
||||
const _AutoAdvanceSetting();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = AppSettings.instance;
|
||||
return SignalBuilder(
|
||||
builder: (context) => SwitchListTile(
|
||||
key: const ValueKey('auto-advance'),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('Play the next episode automatically'),
|
||||
subtitle: const Text('When an episode ends, a 10 s countdown puts up the next one; '
|
||||
'anyone can cancel it on their screen.'),
|
||||
value: s.autoAdvance.value,
|
||||
onChanged: s.setAutoAdvance,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ShortcutList extends StatelessWidget {
|
||||
const _ShortcutList();
|
||||
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:sync_relay_core/core.dart' show JellyfinStreamType;
|
||||
|
||||
import '../../jellyfin/session_media.dart';
|
||||
import '../../jellyfin/track_prefs.dart';
|
||||
import '../../session/session_coordinator.dart' show AutoAdvance, autoAdvanceSecs;
|
||||
|
||||
// Jellyfin pieces of the session screen. Plain widgets fed by the
|
||||
// coordinator's signals, so tests can pump them without the player.
|
||||
|
||||
/// Previous / next episode in the video controls. Nothing when there is
|
||||
/// no such episode or this viewer cannot put it up (no account).
|
||||
class EpisodeSkipButton extends StatelessWidget {
|
||||
final EpisodeLink? episode;
|
||||
final bool next;
|
||||
final VoidCallback onPressed;
|
||||
final FocusNode? focusNode;
|
||||
const EpisodeSkipButton(
|
||||
{super.key, required this.episode, required this.next, required this.onPressed, this.focusNode});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final e = episode;
|
||||
if (e == null) return const SizedBox.shrink();
|
||||
return Tooltip(
|
||||
message: '${next ? 'Next' : 'Previous'}: ${e.label} (${next ? '> or Shift+N' : '< or Shift+P'})',
|
||||
child: IconButton(
|
||||
key: ValueKey(next ? 'episode-next' : 'episode-previous'),
|
||||
focusNode: focusNode,
|
||||
color: Colors.white,
|
||||
iconSize: 22,
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: Icon(next ? Icons.skip_next_rounded : Icons.skip_previous_rounded),
|
||||
onPressed: onPressed,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Floating "Next episode ›" near the end of an episode: faint at rest,
|
||||
/// lit on hover. Lives outside the auto-hiding controls, so it shows in
|
||||
/// fullscreen and with the controls hidden.
|
||||
class NextEpisodePill extends StatefulWidget {
|
||||
final EpisodeLink episode;
|
||||
final VoidCallback onPressed;
|
||||
const NextEpisodePill({super.key, required this.episode, required this.onPressed});
|
||||
|
||||
@override
|
||||
State<NextEpisodePill> createState() => _NextEpisodePillState();
|
||||
}
|
||||
|
||||
class _NextEpisodePillState extends State<NextEpisodePill> {
|
||||
bool _hover = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final primary = Theme.of(context).colorScheme.primary;
|
||||
return MouseRegion(
|
||||
cursor: SystemMouseCursors.click,
|
||||
onEnter: (_) => setState(() => _hover = true),
|
||||
onExit: (_) => setState(() => _hover = false),
|
||||
child: Tooltip(
|
||||
message: 'Next: ${widget.episode.label}',
|
||||
child: AnimatedScale(
|
||||
duration: const Duration(milliseconds: 150),
|
||||
scale: _hover ? 1.06 : 1,
|
||||
child: AnimatedOpacity(
|
||||
duration: const Duration(milliseconds: 150),
|
||||
opacity: _hover ? 1 : 0.45,
|
||||
child: GestureDetector(
|
||||
key: const ValueKey('next-episode-pill'),
|
||||
onTap: widget.onPressed,
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 150),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 9),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.75),
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
border: Border.all(color: _hover ? primary : Colors.white24),
|
||||
boxShadow: _hover
|
||||
? [BoxShadow(color: primary.withValues(alpha: 0.45), blurRadius: 16)]
|
||||
: const [],
|
||||
),
|
||||
child: const Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('Next episode', style: TextStyle(color: Colors.white, fontSize: 13)),
|
||||
SizedBox(width: 4),
|
||||
Icon(Icons.chevron_right, color: Colors.white, size: 18),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// At the end of an episode: "Next: S1E7 title" with Play now, and while
|
||||
/// the auto-advance countdown runs, the seconds left and Cancel.
|
||||
class EndOfEpisodeCard extends StatelessWidget {
|
||||
final EpisodeLink next;
|
||||
final AutoAdvance? countdown;
|
||||
final VoidCallback onPlayNow;
|
||||
final VoidCallback onCancel;
|
||||
const EndOfEpisodeCard({
|
||||
super.key,
|
||||
required this.next,
|
||||
required this.countdown,
|
||||
required this.onPlayNow,
|
||||
required this.onCancel,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final t = Theme.of(context).textTheme;
|
||||
final c = countdown;
|
||||
return Card(
|
||||
key: const ValueKey('end-of-episode'),
|
||||
color: Colors.black.withValues(alpha: 0.85),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 12, 12),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 380),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(c == null ? 'Up next' : 'Next episode in ${c.secondsLeft} s',
|
||||
style: t.labelLarge?.copyWith(color: Colors.white70)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Next: ${next.label}',
|
||||
maxLines: 2, overflow: TextOverflow.ellipsis, style: t.titleMedium),
|
||||
if (c != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
LinearProgressIndicator(value: c.secondsLeft / autoAdvanceSecs),
|
||||
],
|
||||
const SizedBox(height: 10),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
if (c != null)
|
||||
TextButton(
|
||||
key: const ValueKey('auto-advance-cancel'),
|
||||
onPressed: onCancel,
|
||||
child: const Text('Cancel')),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton.icon(
|
||||
key: const ValueKey('play-next'),
|
||||
onPressed: onPlayNow,
|
||||
icon: const Icon(Icons.skip_next_rounded, size: 18),
|
||||
label: Text(c == null ? 'Play next' : 'Play now'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// This viewer cannot play the Jellyfin media: say why and offer to link
|
||||
/// an account (never a silent stall).
|
||||
class JellyfinBlockedCard extends StatelessWidget {
|
||||
final BlockedPlay blocked;
|
||||
final VoidCallback onLinkAccount;
|
||||
final VoidCallback onRetry;
|
||||
const JellyfinBlockedCard(
|
||||
{super.key, required this.blocked, required this.onLinkAccount, required this.onRetry});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final t = Theme.of(context).textTheme;
|
||||
return Card(
|
||||
key: const ValueKey('jellyfin-blocked'),
|
||||
color: Colors.black.withValues(alpha: 0.85),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 440),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.lock_outline, color: Colors.orange, size: 32),
|
||||
const SizedBox(height: 10),
|
||||
Text(blocked.message, textAlign: TextAlign.center, style: t.titleSmall),
|
||||
const SizedBox(height: 6),
|
||||
Text('Link your own account in Integrations, or ask the host to relay it.',
|
||||
textAlign: TextAlign.center, style: t.bodySmall?.copyWith(color: Colors.grey)),
|
||||
const SizedBox(height: 14),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
FilledButton(
|
||||
key: const ValueKey('link-jellyfin-account'),
|
||||
onPressed: onLinkAccount,
|
||||
child: const Text('Link a Jellyfin account')),
|
||||
TextButton(onPressed: onRetry, child: const Text('Try again')),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Small member-list badge: plays the Jellyfin item through the host.
|
||||
class ViaHostBadge extends StatelessWidget {
|
||||
const ViaHostBadge({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Tooltip(
|
||||
message: 'No Jellyfin account here: watches through the host',
|
||||
child: Container(
|
||||
key: const ValueKey('via-host'),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white10,
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
border: Border.all(color: Colors.white24),
|
||||
),
|
||||
child: const Text('via host', style: TextStyle(fontSize: 10, color: Colors.white70)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A track pick from [TracksControlButton]: audio id, subtitle id, or off.
|
||||
typedef TrackPick = ({int? aid, int? sid, bool subtitlesOff});
|
||||
|
||||
/// Audio / subtitle menu for the controls bar. The choice is remembered
|
||||
/// for the next Jellyfin item (per viewer).
|
||||
class TracksControlButton extends StatelessWidget {
|
||||
final FocusNode? focusNode;
|
||||
final List<MpvTrack> Function() tracks;
|
||||
final Future<({int? aid, int? sid})> Function() current;
|
||||
final void Function(TrackPick pick) onPick;
|
||||
final ValueChanged<bool>? onMenuOpen;
|
||||
const TracksControlButton({
|
||||
super.key,
|
||||
this.focusNode,
|
||||
required this.tracks,
|
||||
required this.current,
|
||||
required this.onPick,
|
||||
this.onMenuOpen,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Tooltip(
|
||||
message: 'Audio and subtitles',
|
||||
child: IconButton(
|
||||
key: const ValueKey('tracks-button'),
|
||||
focusNode: focusNode,
|
||||
color: Colors.white,
|
||||
iconSize: 20,
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.subtitles_outlined),
|
||||
onPressed: () => _open(context),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _open(BuildContext context) async {
|
||||
final list = tracks();
|
||||
final button = context.findRenderObject() as RenderBox;
|
||||
final overlay = Navigator.of(context).overlay!.context.findRenderObject() as RenderBox;
|
||||
final position = RelativeRect.fromRect(
|
||||
Rect.fromPoints(
|
||||
button.localToGlobal(Offset.zero, ancestor: overlay),
|
||||
button.localToGlobal(button.size.bottomRight(Offset.zero), ancestor: overlay),
|
||||
),
|
||||
Offset.zero & overlay.size,
|
||||
);
|
||||
final navigator = Navigator.of(context);
|
||||
final now = await current();
|
||||
if (!navigator.mounted) return;
|
||||
final audio = list.where((t) => t.type == JellyfinStreamType.audio).toList();
|
||||
final subs = list.where((t) => t.type == JellyfinStreamType.subtitle).toList();
|
||||
PopupMenuItem<TrackPick> header(String text) => PopupMenuItem(
|
||||
enabled: false,
|
||||
height: 28,
|
||||
child: Text(text, style: const TextStyle(fontSize: 12, color: Colors.grey)));
|
||||
onMenuOpen?.call(true);
|
||||
final pick = await showMenu<TrackPick>(
|
||||
context: navigator.context,
|
||||
position: position,
|
||||
popUpAnimationStyle: AnimationStyle.noAnimation,
|
||||
constraints: const BoxConstraints(minWidth: 280, maxWidth: 420),
|
||||
items: [
|
||||
header('Audio'),
|
||||
if (audio.isEmpty)
|
||||
const PopupMenuItem(enabled: false, height: 32, child: Text('None')),
|
||||
for (final t in audio)
|
||||
CheckedPopupMenuItem(
|
||||
value: (aid: t.id, sid: null, subtitlesOff: false),
|
||||
checked: now.aid == t.id,
|
||||
height: 36,
|
||||
child: Text(t.label, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
const PopupMenuDivider(),
|
||||
header('Subtitles'),
|
||||
CheckedPopupMenuItem(
|
||||
value: (aid: null, sid: null, subtitlesOff: true),
|
||||
checked: now.sid == null,
|
||||
height: 36,
|
||||
child: const Text('Off'),
|
||||
),
|
||||
for (final t in subs)
|
||||
CheckedPopupMenuItem(
|
||||
value: (aid: null, sid: t.id, subtitlesOff: false),
|
||||
checked: now.sid == t.id,
|
||||
height: 36,
|
||||
child: Text(t.label, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
],
|
||||
);
|
||||
onMenuOpen?.call(false);
|
||||
if (pick != null) onPick(pick);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../jellyfin/accounts.dart';
|
||||
import '../../jellyfin/browse_scope.dart' show BrowseStart;
|
||||
import '../home/media_picker.dart';
|
||||
|
||||
/// "Change video" in a session: the same [MediaPicker] as Home's Host tab
|
||||
/// (Jellyfin browser, Link, File) and a button that puts the pick up for
|
||||
/// everyone. File is offered to the host only (the file streams from the
|
||||
/// host's disk). [onSwap] returns an error text, or null when sent.
|
||||
class SwapPanel extends StatefulWidget {
|
||||
final MediaPickerController controller;
|
||||
final JellyfinAccounts accounts;
|
||||
final bool isHost;
|
||||
final BrowseStart? jellyfinStart;
|
||||
final Future<String?> Function(PickedMedia media) onSwap;
|
||||
final VoidCallback onClose;
|
||||
final VoidCallback? onOpenIntegrations;
|
||||
const SwapPanel({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.accounts,
|
||||
required this.isHost,
|
||||
required this.onSwap,
|
||||
required this.onClose,
|
||||
this.jellyfinStart,
|
||||
this.onOpenIntegrations,
|
||||
});
|
||||
|
||||
@override
|
||||
State<SwapPanel> createState() => _SwapPanelState();
|
||||
}
|
||||
|
||||
class _SwapPanelState extends State<SwapPanel> {
|
||||
bool _busy = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final c = widget.controller;
|
||||
if (!widget.isHost && c.source == MediaKind.file) c.source = MediaKind.link;
|
||||
}
|
||||
|
||||
Future<void> _swap() async {
|
||||
final media = widget.controller.selection;
|
||||
if (media == null || _busy) return;
|
||||
setState(() {
|
||||
_busy = true;
|
||||
_error = null;
|
||||
});
|
||||
String? error;
|
||||
try {
|
||||
error = await widget.onSwap(media);
|
||||
} catch (e) {
|
||||
error = '$e';
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_error = error;
|
||||
});
|
||||
if (error == null) widget.onClose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final t = Theme.of(context).textTheme;
|
||||
return Material(
|
||||
key: const ValueKey('swap-panel'),
|
||||
elevation: 12,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 12, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: Text('Change video', style: t.titleLarge)),
|
||||
IconButton(
|
||||
tooltip: 'Close (Esc)', icon: const Icon(Icons.close), onPressed: widget.onClose),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: MediaPicker(
|
||||
controller: widget.controller,
|
||||
jellyfin: widget.accounts,
|
||||
enabled: !_busy,
|
||||
allowFile: widget.isHost,
|
||||
jellyfinStart: widget.jellyfinStart,
|
||||
onOpenIntegrations: widget.onOpenIntegrations,
|
||||
onSubmit: _swap,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ListenableBuilder(
|
||||
listenable: widget.controller,
|
||||
builder: (context, _) {
|
||||
final sel = widget.controller.selection;
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
_error ?? (sel == null ? 'Pick something to watch' : 'Put up: ${sel.label}'),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: t.bodyMedium?.copyWith(
|
||||
color: _error != null ? Theme.of(context).colorScheme.error : null),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
FilledButton.icon(
|
||||
key: const ValueKey('swap-go'),
|
||||
onPressed: sel == null || _busy ? null : _swap,
|
||||
icon: _busy
|
||||
? const SizedBox(
|
||||
width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Icon(Icons.swap_horiz),
|
||||
label: const Text('Put it up for everyone'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import 'package:media_kit_video/media_kit_video.dart';
|
||||
import 'package:signals/signals_flutter.dart';
|
||||
import 'package:sync_relay_core/core.dart';
|
||||
|
||||
import '../jellyfin/browse_scope.dart' show BrowseStart;
|
||||
import '../jellyfin/session_media.dart';
|
||||
import '../session/health.dart';
|
||||
import '../session/session_coordinator.dart';
|
||||
import '../shaders/shader_menu.dart';
|
||||
@@ -17,6 +19,10 @@ import '../widgets/shown_frame_probe.dart';
|
||||
import '../widgets/text_focus.dart';
|
||||
import '../widgets/window_buttons.dart';
|
||||
import '../widgets/window_drag_layer.dart';
|
||||
import 'home/integrations_page.dart';
|
||||
import 'home/media_picker.dart';
|
||||
import 'session/jellyfin_widgets.dart';
|
||||
import 'session/swap_panel.dart';
|
||||
|
||||
class SessionScreen extends StatefulWidget {
|
||||
const SessionScreen({super.key});
|
||||
@@ -38,7 +44,10 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
DateTime? _lastKeyAt;
|
||||
final _chat = TextEditingController();
|
||||
final _chatFocus = FocusNode();
|
||||
final _swapLink = TextEditingController();
|
||||
// "Change video": the shared media picker over the video.
|
||||
final _swapOpen = signal(false);
|
||||
MediaPickerController? _swapPicker;
|
||||
bool _integrationsOpen = false;
|
||||
late final void Function() _stopKickWatch;
|
||||
late final void Function() _stopSheetWatch;
|
||||
late final void Function() _stopPlayerWatch;
|
||||
@@ -54,6 +63,7 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
super.initState();
|
||||
final session = SessionState.instance;
|
||||
_noFocus = FocusNode(skipTraversal: true, canRequestFocus: false);
|
||||
session.coordinator.jellyfin.ensureLoaded();
|
||||
session.coordinator.playback.shownFrame = _frameProbe.sample;
|
||||
HardwareKeyboard.instance.addHandler(_globalKey);
|
||||
_stopKickWatch = effect(() {
|
||||
@@ -144,14 +154,70 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
_stopShaderWatch();
|
||||
_chat.dispose();
|
||||
_chatFocus.dispose();
|
||||
_swapLink.dispose();
|
||||
_swapPicker?.dispose();
|
||||
_noFocus.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Opens the swap panel: the browser starts on the series of the
|
||||
/// episode playing (season selected, episode highlighted), else where it
|
||||
/// was last.
|
||||
void _openSwap() {
|
||||
final coord = SessionState.instance.coordinator;
|
||||
coord.markInput();
|
||||
final ref = coord.currentRef.peek();
|
||||
final accounts = coord.jellyfin;
|
||||
final pick = ref == null ? null : pickForRef(accounts, ref);
|
||||
final plan = coord.jellyfinPlan.peek();
|
||||
_swapPicker?.dispose();
|
||||
_swapPicker = MediaPickerController(
|
||||
jellyfin: pick,
|
||||
source: pick != null || (accounts.loaded && !accounts.isEmpty)
|
||||
? MediaKind.jellyfin
|
||||
: MediaKind.link,
|
||||
);
|
||||
_swapStart = ref != null && plan is OwnPlay && plan.item != null
|
||||
? BrowseStart.seriesOf(ref.serverId, plan.item!)
|
||||
: null;
|
||||
_sheetOpen.value = false;
|
||||
_swapOpen.value = true;
|
||||
}
|
||||
|
||||
BrowseStart? _swapStart;
|
||||
|
||||
void _closeSwap() {
|
||||
_swapOpen.value = false;
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
}
|
||||
|
||||
/// Integrations over the session (link an account for a blocked item).
|
||||
Future<void> _openIntegrations() async {
|
||||
if (_integrationsOpen) return;
|
||||
_integrationsOpen = true;
|
||||
try {
|
||||
await Navigator.of(context, rootNavigator: true).push(MaterialPageRoute<void>(
|
||||
builder: (_) => Scaffold(
|
||||
appBar: AppBar(title: const Text('Integrations')),
|
||||
body: IntegrationsPage(jellyfin: SessionState.instance.coordinator.jellyfin),
|
||||
),
|
||||
));
|
||||
} finally {
|
||||
_integrationsOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool _globalKey(KeyEvent event) {
|
||||
if (event is! KeyDownEvent) return false;
|
||||
if (SessionState.instance.route.peek() != AppRoute.session) return false;
|
||||
if (_integrationsOpen) return false;
|
||||
if (_swapOpen.peek()) {
|
||||
// The picker owns the keyboard; Esc outside a field closes it.
|
||||
if (event.logicalKey == LogicalKeyboardKey.escape && !textInputFocused()) {
|
||||
_closeSwap();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (textInputFocused()) return false;
|
||||
final now = DateTime.now().toUtc();
|
||||
if (_lastKeyAt != null && now.difference(_lastKeyAt!).inMilliseconds < 350) {
|
||||
@@ -177,6 +243,20 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
coord.toggleReady();
|
||||
return true;
|
||||
}
|
||||
// mpv's playlist keys (< >) and Shift+P / Shift+N: Jellyfin episodes.
|
||||
final shift = HardwareKeyboard.instance.isShiftPressed;
|
||||
if (event.character == '>' || (shift && event.logicalKey == LogicalKeyboardKey.keyN)) {
|
||||
if (coord.nextEpisode.peek() == null) return false;
|
||||
_lastKeyAt = now;
|
||||
coord.playNextEpisode();
|
||||
return true;
|
||||
}
|
||||
if (event.character == '<' || (shift && event.logicalKey == LogicalKeyboardKey.keyP)) {
|
||||
if (coord.previousEpisode.peek() == null) return false;
|
||||
_lastKeyAt = now;
|
||||
coord.playPreviousEpisode();
|
||||
return true;
|
||||
}
|
||||
if (event.logicalKey == LogicalKeyboardKey.tab) {
|
||||
_lastKeyAt = now;
|
||||
_sheetOpen.value = !_sheetOpen.peek();
|
||||
@@ -254,12 +334,35 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
),
|
||||
],
|
||||
bottomButtonBar: [
|
||||
SignalBuilder(
|
||||
builder: (context) => EpisodeSkipButton(
|
||||
focusNode: _noFocus,
|
||||
episode: coord.previousEpisode.value,
|
||||
next: false,
|
||||
onPressed: coord.playPreviousEpisode,
|
||||
),
|
||||
),
|
||||
SignalBuilder(
|
||||
builder: (context) => EpisodeSkipButton(
|
||||
focusNode: _noFocus,
|
||||
episode: coord.nextEpisode.value,
|
||||
next: true,
|
||||
onPressed: coord.playNextEpisode,
|
||||
),
|
||||
),
|
||||
const MaterialDesktopVolumeButton(),
|
||||
_ReadyControlButton(focusNode: _noFocus),
|
||||
_MarkAllReadyControlButton(focusNode: _noFocus),
|
||||
_ReloadVideoControlButton(focusNode: _noFocus, onPressed: _reloadVideo),
|
||||
const MaterialDesktopPositionIndicator(),
|
||||
const Spacer(),
|
||||
TracksControlButton(
|
||||
focusNode: _noFocus,
|
||||
tracks: () => coord.playback.tracks,
|
||||
current: coord.playback.currentTrackIds,
|
||||
onPick: (p) => coord.selectTrack(aid: p.aid, sid: p.sid, subtitlesOff: p.subtitlesOff),
|
||||
onMenuOpen: (open) => _shaderMenuOpen = open,
|
||||
),
|
||||
ShaderControlButton(
|
||||
focusNode: _noFocus,
|
||||
renderMode: coord.playback.renderMode,
|
||||
@@ -320,8 +423,10 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
MaterialDesktopVideoControls(state),
|
||||
_healthOverlay(),
|
||||
_waitingOverlay(),
|
||||
_jellyfinOverlay(),
|
||||
_toastsOverlay(),
|
||||
_sheetOverlay(),
|
||||
_swapOverlay(),
|
||||
_leaveOverlay(),
|
||||
Positioned.fill(
|
||||
child: SignalBuilder(
|
||||
@@ -329,7 +434,7 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
final sheetOpen = _sheetOpen.value;
|
||||
final confirm = _confirmLeave.value;
|
||||
return WindowDragLayer(
|
||||
enabled: !confirm,
|
||||
enabled: !confirm && !_swapOpen.value,
|
||||
exclusions: [
|
||||
(s) => Rect.fromLTWH(0, s.height - 120, s.width, 120),
|
||||
if (sheetOpen) (s) => Rect.fromLTWH(s.width - 380, 0, 380, s.height),
|
||||
@@ -469,6 +574,94 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Jellyfin: the blocked card, the end-of-episode card (countdown) and
|
||||
/// the "Next episode" pill. Outside the auto-hiding controls, so they
|
||||
/// also show in fullscreen.
|
||||
Widget _jellyfinOverlay() {
|
||||
final coord = SessionState.instance.coordinator;
|
||||
return Positioned.fill(
|
||||
child: SignalBuilder(
|
||||
builder: (context) {
|
||||
final blocked = coord.jellyfinBlocked.value;
|
||||
final next = coord.nextEpisode.value;
|
||||
final countdown = coord.autoAdvance.value;
|
||||
final finished = coord.serverState.value?.transport == 'finished';
|
||||
final pill = coord.nextPromptVisible.value;
|
||||
return Stack(
|
||||
children: [
|
||||
if (blocked != null)
|
||||
Center(
|
||||
child: JellyfinBlockedCard(
|
||||
blocked: blocked,
|
||||
onLinkAccount: _openIntegrations,
|
||||
onRetry: coord.retryJellyfin,
|
||||
),
|
||||
),
|
||||
if (next != null && (finished || countdown != null))
|
||||
Positioned(
|
||||
right: 24,
|
||||
bottom: 110,
|
||||
child: EndOfEpisodeCard(
|
||||
next: next,
|
||||
countdown: countdown,
|
||||
onPlayNow: coord.playNextEpisode,
|
||||
onCancel: coord.cancelAutoAdvance,
|
||||
),
|
||||
)
|
||||
else if (next != null && pill)
|
||||
Positioned(
|
||||
right: 24,
|
||||
bottom: 96,
|
||||
child: NextEpisodePill(episode: next, onPressed: coord.playNextEpisode),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _swapOverlay() {
|
||||
final coord = SessionState.instance.coordinator;
|
||||
return SignalBuilder(
|
||||
builder: (context) {
|
||||
final picker = _swapPicker;
|
||||
if (!_swapOpen.value || picker == null) return const SizedBox.shrink();
|
||||
return Positioned.fill(
|
||||
child: Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: GestureDetector(
|
||||
onTap: _closeSwap,
|
||||
child: Container(color: Colors.black54),
|
||||
),
|
||||
),
|
||||
Positioned.fill(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(32, 48, 32, 32),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 1400),
|
||||
child: SwapPanel(
|
||||
controller: picker,
|
||||
accounts: coord.jellyfin,
|
||||
isHost: coord.hostFile != null,
|
||||
jellyfinStart: _swapStart,
|
||||
onSwap: coord.swapPicked,
|
||||
onClose: _closeSwap,
|
||||
onOpenIntegrations: _openIntegrations,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _toastsOverlay() {
|
||||
final coord = SessionState.instance.coordinator;
|
||||
return Positioned(
|
||||
@@ -526,7 +719,7 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
child: _SheetPanel(
|
||||
chat: _chat,
|
||||
chatFocus: _chatFocus,
|
||||
swapLink: _swapLink,
|
||||
onChangeVideo: _openSwap,
|
||||
onClose: () => _sheetOpen.value = false,
|
||||
onLeave: () {
|
||||
_sheetOpen.value = false;
|
||||
@@ -697,10 +890,10 @@ class _ToastCardState extends State<_ToastCard> {
|
||||
class _SheetPanel extends StatelessWidget {
|
||||
final TextEditingController chat;
|
||||
final FocusNode chatFocus;
|
||||
final TextEditingController swapLink;
|
||||
final VoidCallback onChangeVideo;
|
||||
final VoidCallback onClose;
|
||||
final VoidCallback onLeave;
|
||||
const _SheetPanel({required this.chat, required this.chatFocus, required this.swapLink, required this.onClose, required this.onLeave});
|
||||
const _SheetPanel({required this.chat, required this.chatFocus, required this.onChangeVideo, required this.onClose, required this.onLeave});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -750,7 +943,12 @@ class _SheetPanel extends StatelessWidget {
|
||||
const Divider(height: 20),
|
||||
Text('Users (${members.length})', style: sectionStyle),
|
||||
const SizedBox(height: 2),
|
||||
for (final m in members) _MemberRow(member: m, isSelf: m.id == coord.sync.memberId),
|
||||
for (final m in members)
|
||||
_MemberRow(
|
||||
member: m,
|
||||
isSelf: m.id == coord.sync.memberId,
|
||||
viaHost: viaHostOf(m, coord.currentRef.value),
|
||||
),
|
||||
const Divider(height: 20),
|
||||
Text('Activity', style: sectionStyle),
|
||||
const SizedBox(height: 6),
|
||||
@@ -790,34 +988,14 @@ class _SheetPanel extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text('Share a link', style: sectionStyle),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: swapLink,
|
||||
decoration: const InputDecoration(labelText: 'Swap to link URL', border: OutlineInputBorder(), isDense: true),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ValueListenableBuilder<TextEditingValue>(
|
||||
valueListenable: swapLink,
|
||||
builder: (context, value, _) {
|
||||
final link = value.text.trim();
|
||||
return IconButton(
|
||||
icon: const Icon(Icons.swap_horiz),
|
||||
onPressed: link.isEmpty
|
||||
? null
|
||||
: () {
|
||||
coord.swapLink(link);
|
||||
swapLink.clear();
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
key: const ValueKey('change-video'),
|
||||
icon: const Icon(Icons.swap_horiz),
|
||||
label: const Text('Change video'),
|
||||
onPressed: onChangeVideo,
|
||||
),
|
||||
),
|
||||
const Divider(height: 20),
|
||||
SizedBox(
|
||||
@@ -880,10 +1058,14 @@ class _StatusChip extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// The member plays the current Jellyfin item through the host's relay.
|
||||
bool viaHostOf(MemberView m, JellyfinRef? ref) => ref != null && m.jf[ref.serverId] == false;
|
||||
|
||||
class _MemberRow extends StatelessWidget {
|
||||
final MemberView member;
|
||||
final bool isSelf;
|
||||
const _MemberRow({required this.member, required this.isSelf});
|
||||
final bool viaHost;
|
||||
const _MemberRow({required this.member, required this.isSelf, this.viaHost = false});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -920,6 +1102,7 @@ class _MemberRow extends StatelessWidget {
|
||||
status.$1,
|
||||
style: theme.textTheme.bodySmall?.copyWith(color: theme.textTheme.bodySmall?.color?.withValues(alpha: 0.75)),
|
||||
),
|
||||
if (viaHost) ...[const SizedBox(width: 6), const ViaHostBadge()],
|
||||
],
|
||||
),
|
||||
],
|
||||
|
||||
@@ -4,8 +4,14 @@ import 'package:flutter/widgets.dart';
|
||||
import 'package:signals/signals_flutter.dart';
|
||||
import 'package:sync_relay_core/core.dart';
|
||||
|
||||
import '../jellyfin/accounts.dart';
|
||||
import '../jellyfin/progress.dart';
|
||||
import '../jellyfin/session_media.dart';
|
||||
import '../jellyfin/track_prefs.dart';
|
||||
import '../playback/playback_controller.dart';
|
||||
import '../screens/home/picked_media.dart';
|
||||
import '../sfx/sfx.dart';
|
||||
import '../state/settings.dart';
|
||||
import '../sync/state_diff.dart';
|
||||
import '../sync/sync_client.dart';
|
||||
import '../sync/user_seek.dart';
|
||||
@@ -21,19 +27,7 @@ class ConnectCancelled implements Exception {
|
||||
|
||||
/// Display name for a link: last path segment, decoded, never the query
|
||||
/// (Jellyfin-style links carry api_key there and names are broadcast).
|
||||
String linkDisplayName(String url) {
|
||||
final uri = Uri.tryParse(url.trim());
|
||||
if (uri == null) return 'link';
|
||||
final segs = uri.pathSegments.where((s) => s.isNotEmpty).toList();
|
||||
if (segs.isNotEmpty) {
|
||||
try {
|
||||
return Uri.decodeComponent(segs.last);
|
||||
} catch (_) {
|
||||
return segs.last;
|
||||
}
|
||||
}
|
||||
return uri.host.isNotEmpty ? uri.host : 'link';
|
||||
}
|
||||
String linkDisplayName(String url) => linkName(url);
|
||||
|
||||
class ConnectParams {
|
||||
final String host;
|
||||
@@ -45,6 +39,9 @@ class ConnectParams {
|
||||
final String linkUrl;
|
||||
/// Sent in hello by the hosting app's own client (see AppConfig.hostKey).
|
||||
final String hostKey;
|
||||
/// Put up with a `swap` right after joining (a Jellyfin ref or a link);
|
||||
/// wins over [linkUrl].
|
||||
final HelloMedia? media;
|
||||
const ConnectParams({
|
||||
required this.host,
|
||||
required this.port,
|
||||
@@ -54,9 +51,37 @@ class ConnectParams {
|
||||
this.mediaPath = '',
|
||||
this.linkUrl = '',
|
||||
this.hostKey = '',
|
||||
this.media,
|
||||
});
|
||||
|
||||
ConnectParams withMedia(HelloMedia? media) => ConnectParams(
|
||||
host: host,
|
||||
port: port,
|
||||
secret: secret,
|
||||
name: name,
|
||||
avatar: avatar,
|
||||
mediaPath: mediaPath,
|
||||
linkUrl: media == null ? linkUrl : '',
|
||||
hostKey: hostKey,
|
||||
media: media,
|
||||
);
|
||||
}
|
||||
|
||||
/// The end-of-episode countdown (auto-advance). Every client with the
|
||||
/// setting on shows it; only [swapper] puts the next episode up.
|
||||
class AutoAdvance {
|
||||
final int mediaId;
|
||||
final int secondsLeft;
|
||||
final EpisodeLink next;
|
||||
/// This client performs the swap (see [autoAdvanceSwapper]).
|
||||
final bool swapper;
|
||||
const AutoAdvance(
|
||||
{required this.mediaId, required this.secondsLeft, required this.next, required this.swapper});
|
||||
}
|
||||
|
||||
/// Seconds of the end-of-episode countdown.
|
||||
const autoAdvanceSecs = 10;
|
||||
|
||||
class ToastItem {
|
||||
final int id;
|
||||
final String text;
|
||||
@@ -76,6 +101,13 @@ String? stateMediaUrl(StateBroadcast state) {
|
||||
|
||||
class SessionCoordinator {
|
||||
final SfxService sfx;
|
||||
/// Linked Jellyfin servers: how this viewer plays Jellyfin refs.
|
||||
final JellyfinAccounts jellyfin;
|
||||
/// Audio/subtitle carry-over between Jellyfin items.
|
||||
final TrackPrefs trackPrefs;
|
||||
/// Set by the hosting app: makes a local file the hosted one (File swap);
|
||||
/// null when this app is not the host.
|
||||
Future<({String name, int size})?> Function(String path)? hostFile;
|
||||
final SyncClient sync = SyncClient();
|
||||
final PlaybackController playback = PlaybackController();
|
||||
final StateDiff diff = StateDiff();
|
||||
@@ -89,6 +121,21 @@ class SessionCoordinator {
|
||||
final kickReason = signal<String?>(null);
|
||||
final starving = signal<String?>(null);
|
||||
|
||||
/// The current media's Jellyfin ref (null for links and files).
|
||||
final currentRef = signal<JellyfinRef?>(null);
|
||||
/// How this viewer plays [currentRef]; null while resolving.
|
||||
final jellyfinPlan = signal<JellyfinPlan?>(null);
|
||||
/// Set when this viewer cannot play the Jellyfin media: no account and
|
||||
/// no relay. The session shows it with a way to link an account.
|
||||
final jellyfinBlocked = signal<BlockedPlay?>(null);
|
||||
/// Neighbouring episodes this viewer can put up (own account only).
|
||||
final previousEpisode = signal<EpisodeLink?>(null);
|
||||
final nextEpisode = signal<EpisodeLink?>(null);
|
||||
/// The floating "Next episode" pill near the end of an episode.
|
||||
final nextPromptVisible = signal(false);
|
||||
/// End-of-episode countdown; null when none runs here.
|
||||
final autoAdvance = signal<AutoAdvance?>(null);
|
||||
|
||||
late final Computed<MemberView?> selfMember = computed(() {
|
||||
final r = serverState.value;
|
||||
if (r == null || sync.memberId.isEmpty) return null;
|
||||
@@ -139,8 +186,25 @@ class SessionCoordinator {
|
||||
int _toastId = 0;
|
||||
ConnectParams? _params;
|
||||
bool _everConnected = false;
|
||||
Map<String, String>? _openHeaders;
|
||||
|
||||
SessionCoordinator({this.sfx = const NoopSfxService()});
|
||||
// Jellyfin: the resolved ref, the mediaId it belongs to, a generation
|
||||
// that stale resolutions check, and the progress reporter.
|
||||
JellyfinRef? _jfRef;
|
||||
int _jfMediaId = -1;
|
||||
int _jfGen = 0;
|
||||
JellyfinProgressReporter? _reporter;
|
||||
PlayerSnapshot? _lastSnap;
|
||||
bool _jfToastShown = false;
|
||||
Timer? _advanceTimer;
|
||||
int _advanceDoneFor = -1;
|
||||
String _blockedKey = '';
|
||||
bool _jellyfinListening = false;
|
||||
|
||||
SessionCoordinator(
|
||||
{this.sfx = const NoopSfxService(), JellyfinAccounts? jellyfin, TrackPrefs? trackPrefs})
|
||||
: jellyfin = jellyfin ?? JellyfinAccounts.instance,
|
||||
trackPrefs = trackPrefs ?? TrackPrefs();
|
||||
|
||||
/// Player lifetime = one session: created here on connect, disposed by
|
||||
/// [leave]. Never reused across sessions (a GPU-side video freeze sticks
|
||||
@@ -175,9 +239,10 @@ class SessionCoordinator {
|
||||
try {
|
||||
await playback.recreate();
|
||||
final url = _openUrl;
|
||||
final headers = _openHeaders;
|
||||
_openUrl = null;
|
||||
_clearPendingSeek();
|
||||
if (url != null) await _openMedia(url);
|
||||
if (url != null) await _openMedia(url, headers: headers);
|
||||
} catch (e, st) {
|
||||
debugPrint('video reload failed: $e\n$st');
|
||||
health.value =
|
||||
@@ -221,6 +286,12 @@ class SessionCoordinator {
|
||||
_seekGate.reset();
|
||||
_clearPendingSeek();
|
||||
_lastEventId = -1;
|
||||
_resetJellyfin();
|
||||
_jfToastShown = false;
|
||||
if (!_jellyfinListening) {
|
||||
_jellyfinListening = true;
|
||||
jellyfin.addListener(_onAccountsChanged);
|
||||
}
|
||||
markInput();
|
||||
_subscribe();
|
||||
feedLog.value = [];
|
||||
@@ -252,13 +323,10 @@ class SessionCoordinator {
|
||||
health.value = const HealthStatus(
|
||||
HealthSeverity.info, 'connected — waiting for host media…');
|
||||
}
|
||||
if (params.linkUrl.isNotEmpty) {
|
||||
sync.sendSwap(HelloMedia(
|
||||
name: linkDisplayName(params.linkUrl),
|
||||
size: 0,
|
||||
duration: 0,
|
||||
url: params.linkUrl));
|
||||
}
|
||||
final media = params.media ??
|
||||
(params.linkUrl.isEmpty ? null : await mediaForLink(jellyfin, params.linkUrl));
|
||||
if (epoch != _epoch) throw const ConnectCancelled();
|
||||
if (media != null) sync.sendSwap(media);
|
||||
_startTicker();
|
||||
} catch (e) {
|
||||
if (epoch != _epoch) throw const ConnectCancelled();
|
||||
@@ -286,19 +354,23 @@ class SessionCoordinator {
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _openMedia(String url) async {
|
||||
if (url == _openUrl) return;
|
||||
/// Opens [url] (with [headers] on every request); false on failure.
|
||||
Future<bool> _openMedia(String url, {Map<String, String>? headers}) async {
|
||||
if (url == _openUrl) return true;
|
||||
_openUrl = url;
|
||||
_openHeaders = headers;
|
||||
diff.reset();
|
||||
_opening = true;
|
||||
try {
|
||||
await playback.openUrl(url);
|
||||
await playback.openUrl(url, headers: headers);
|
||||
health.value =
|
||||
const HealthStatus(HealthSeverity.ok, 'connected');
|
||||
return true;
|
||||
} catch (e) {
|
||||
debugPrint('open media failed: $e');
|
||||
health.value =
|
||||
HealthStatus(HealthSeverity.error, 'cannot open media: $e');
|
||||
return false;
|
||||
} finally {
|
||||
_opening = false;
|
||||
}
|
||||
@@ -308,28 +380,73 @@ class SessionCoordinator {
|
||||
return 'http://$_wsHost:$_wsPort/m/default/${sync.token}/${Uri.encodeComponent(name)}';
|
||||
}
|
||||
|
||||
Future<void> _onState(StateBroadcast r) async {
|
||||
StateBroadcast? _queuedState;
|
||||
bool _applying = false;
|
||||
|
||||
/// States are applied one at a time, newest first: two applies running
|
||||
/// interleaved could land an older pause after a newer play (seen with
|
||||
/// three viewers readying at once). A state that arrives meanwhile
|
||||
/// replaces any still waiting.
|
||||
void _onState(StateBroadcast r) {
|
||||
_lastStateAt = DateTime.now().toUtc();
|
||||
serverState.value = r;
|
||||
_queuedState = r;
|
||||
if (_applying) return;
|
||||
_applying = true;
|
||||
() async {
|
||||
try {
|
||||
while (_queuedState != null) {
|
||||
final next = _queuedState!;
|
||||
_queuedState = null;
|
||||
try {
|
||||
await _applyState(next);
|
||||
} catch (e, st) {
|
||||
debugPrint('apply state failed: $e\n$st');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
_applying = false;
|
||||
}
|
||||
}();
|
||||
}
|
||||
|
||||
Future<void> _applyState(StateBroadcast r) async {
|
||||
_trackSelfReady(r);
|
||||
_seekGate.observe(r, sync.memberId);
|
||||
final newEvent = r.eventId != _lastEventId;
|
||||
_lastEventId = r.eventId;
|
||||
if (r.mediaId != _mediaId) {
|
||||
_mediaId = r.mediaId;
|
||||
var url = stateMediaUrl(r);
|
||||
if ((url == null || url.isEmpty) && sync.token.isNotEmpty) {
|
||||
final name = (r.media?['name'] as String?) ?? '';
|
||||
if (name.isNotEmpty) url = _fileUrlFor(name);
|
||||
}
|
||||
if (url != null && url.isNotEmpty) {
|
||||
await _openMedia(url);
|
||||
} else {
|
||||
_openUrl = null;
|
||||
final ref = refOfStateMedia(r.media);
|
||||
// Back after a dropped connection on the same item played with our
|
||||
// own account: nothing to resolve or reopen.
|
||||
final same = ref != null &&
|
||||
r.mediaId == _jfMediaId &&
|
||||
sameJellyfinItem(ref, _jfRef) &&
|
||||
jellyfinPlan.peek() is OwnPlay;
|
||||
if (!same) {
|
||||
_seekGate.reset();
|
||||
_clearPendingSeek();
|
||||
_leaveJellyfinItem();
|
||||
if (ref != null) {
|
||||
await _playJellyfin(ref, r);
|
||||
} else {
|
||||
var url = stateMediaUrl(r);
|
||||
if ((url == null || url.isEmpty) && sync.token.isNotEmpty) {
|
||||
final name = (r.media?['name'] as String?) ?? '';
|
||||
if (name.isNotEmpty) url = _fileUrlFor(name);
|
||||
}
|
||||
if (url != null && url.isNotEmpty) {
|
||||
await _openMedia(url);
|
||||
} else {
|
||||
_openUrl = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
_seekGate.reset();
|
||||
_clearPendingSeek();
|
||||
}
|
||||
_jellyfinTransport(r);
|
||||
if (!_playerReady || _openUrl == null) {
|
||||
_wasPlayAllowed = false;
|
||||
_updateStarving(r, 0);
|
||||
@@ -475,6 +592,7 @@ class SessionCoordinator {
|
||||
// Stop, not pause: a paused player keeps filling its cache from the
|
||||
// host's media URL.
|
||||
_openUrl = null;
|
||||
await _stopJellyfin();
|
||||
try {
|
||||
await playback.stop();
|
||||
} catch (_) {}
|
||||
@@ -504,8 +622,10 @@ class SessionCoordinator {
|
||||
eventId: r.eventId,
|
||||
duration: known ? playback.durationSecs : 0,
|
||||
mediaId: known ? r.mediaId : 0,
|
||||
jf: _jfAccessFor(r),
|
||||
);
|
||||
_checkSeekLanded(r);
|
||||
unawaited(_tickJellyfin(r));
|
||||
}
|
||||
if (!_manualClose &&
|
||||
kickReason.peek() == null &&
|
||||
@@ -661,10 +781,362 @@ class SessionCoordinator {
|
||||
sync.sendKick(memberId, reason: reason);
|
||||
}
|
||||
|
||||
/// A pasted link: a recognised Jellyfin item link goes up as a ref
|
||||
/// (see [mediaForLink]), anything else as the link.
|
||||
Future<void> swapLink(String url) async {
|
||||
markInput();
|
||||
sync.sendSwap(HelloMedia(
|
||||
name: linkDisplayName(url), size: 0, duration: 0, url: url));
|
||||
sync.sendSwap(await mediaForLink(jellyfin, url));
|
||||
}
|
||||
|
||||
/// A Jellyfin pick (browser, next / previous episode) goes up as a ref.
|
||||
void swapJellyfin(JellyfinMedia media) {
|
||||
markInput();
|
||||
sync.sendSwap(mediaForPick(media));
|
||||
}
|
||||
|
||||
/// The host's File swap: the server takes the file, then the swap puts
|
||||
/// it up. Returns an error text, or null when sent.
|
||||
Future<String?> swapFile(String path) async {
|
||||
markInput();
|
||||
final host = hostFile;
|
||||
if (host == null) return 'only the host can share a file';
|
||||
final file = await host(path);
|
||||
if (file == null) return 'file not found — check the path';
|
||||
sync.sendSwap(HelloMedia(name: file.name, size: file.size, duration: 0));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Any picker selection.
|
||||
Future<String?> swapPicked(PickedMedia media) async {
|
||||
switch (media) {
|
||||
case LinkMedia(:final url):
|
||||
await swapLink(url);
|
||||
case JellyfinMedia():
|
||||
swapJellyfin(media);
|
||||
case FileMedia(:final path):
|
||||
return swapFile(path);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void playNextEpisode() {
|
||||
final n = nextEpisode.peek();
|
||||
if (n != null) swapJellyfin(n.pick);
|
||||
}
|
||||
|
||||
void playPreviousEpisode() {
|
||||
final p = previousEpisode.peek();
|
||||
if (p != null) swapJellyfin(p.pick);
|
||||
}
|
||||
|
||||
/// Hides the countdown here; this client will not auto-advance this
|
||||
/// item (if it is the swapper, nobody does).
|
||||
void cancelAutoAdvance() {
|
||||
_advanceTimer?.cancel();
|
||||
_advanceTimer = null;
|
||||
final a = autoAdvance.peek();
|
||||
if (a != null) _advanceDoneFor = a.mediaId;
|
||||
autoAdvance.value = null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- jellyfin
|
||||
|
||||
void _pushToast(String text) {
|
||||
_toastId++;
|
||||
toasts.value = [
|
||||
...toasts.peek(),
|
||||
ToastItem(id: _toastId, text: text, at: DateTime.now().toUtc())
|
||||
];
|
||||
}
|
||||
|
||||
void _resetJellyfin() {
|
||||
_jfGen++;
|
||||
_jfRef = null;
|
||||
_jfMediaId = -1;
|
||||
_reporter = null;
|
||||
_lastSnap = null;
|
||||
_openHeaders = null;
|
||||
_blockedKey = '';
|
||||
currentRef.value = null;
|
||||
jellyfinPlan.value = null;
|
||||
jellyfinBlocked.value = null;
|
||||
previousEpisode.value = null;
|
||||
nextEpisode.value = null;
|
||||
nextPromptVisible.value = false;
|
||||
_advanceTimer?.cancel();
|
||||
_advanceTimer = null;
|
||||
_advanceDoneFor = -1;
|
||||
autoAdvance.value = null;
|
||||
}
|
||||
|
||||
/// The current item is being replaced: Stopped goes out (not awaited:
|
||||
/// reports are sent in order), per-item state clears.
|
||||
void _leaveJellyfinItem() {
|
||||
final reporter = _reporter;
|
||||
final snap = _snapNow();
|
||||
_resetJellyfin();
|
||||
if (reporter != null && snap != null) unawaited(reporter.stop(snap));
|
||||
}
|
||||
|
||||
/// Leave / kick / window close: Stopped, bounded so leaving never hangs.
|
||||
Future<void> _stopJellyfin() async {
|
||||
final reporter = _reporter;
|
||||
final snap = _snapNow();
|
||||
_resetJellyfin();
|
||||
if (reporter == null || snap == null) return;
|
||||
try {
|
||||
await reporter.stop(snap).timeout(const Duration(milliseconds: 1500));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// The last sampled tracks with the position as of now.
|
||||
PlayerSnapshot? _snapNow() {
|
||||
if (!_playerReady) return _lastSnap;
|
||||
final last = _lastSnap;
|
||||
return PlayerSnapshot(
|
||||
position: playback.positionSecs,
|
||||
paused: !playback.player.state.playing,
|
||||
aid: last?.aid,
|
||||
sid: last?.sid,
|
||||
);
|
||||
}
|
||||
|
||||
Future<PlayerSnapshot?> _snapshot() async {
|
||||
if (!_playerReady) return null;
|
||||
final ids = await playback.currentTrackIds();
|
||||
if (!_playerReady) return null;
|
||||
return _lastSnap = PlayerSnapshot(
|
||||
position: playback.positionSecs,
|
||||
paused: !playback.player.state.playing,
|
||||
aid: ids.aid,
|
||||
sid: ids.sid,
|
||||
);
|
||||
}
|
||||
|
||||
String? _relayUrlFor(JellyfinRef ref) {
|
||||
if (sync.token.isEmpty) return null;
|
||||
final welcome = sync.relayUrl;
|
||||
if (welcome != null &&
|
||||
welcome.contains('/${sync.token}/') &&
|
||||
welcome.endsWith('/${Uri.encodeComponent(ref.itemId)}')) {
|
||||
return welcome;
|
||||
}
|
||||
return relayUrlFor(_wsHost, _wsPort, sync.token, ref.itemId);
|
||||
}
|
||||
|
||||
Map<String, bool>? _jfAccessFor(StateBroadcast r) {
|
||||
final ref = _jfRef;
|
||||
final access = jellyfinPlan.peek()?.jfAccess;
|
||||
if (ref == null || access == null || r.mediaId != _jfMediaId) return null;
|
||||
return {ref.serverId: access};
|
||||
}
|
||||
|
||||
/// Resolves [ref] for this viewer and opens it: own account (direct
|
||||
/// play, progress reports, neighbouring episodes), the relay, or the
|
||||
/// blocked state. Then carries the audio/subtitle choice over.
|
||||
Future<void> _playJellyfin(JellyfinRef ref, StateBroadcast r) async {
|
||||
final gen = ++_jfGen;
|
||||
_jfRef = ref;
|
||||
_jfMediaId = r.mediaId;
|
||||
currentRef.value = ref;
|
||||
// Until it resolves nothing is open: no syncing the previous media.
|
||||
final prevUrl = _openUrl;
|
||||
_openUrl = null;
|
||||
_opening = true;
|
||||
if (_playerReady) {
|
||||
try {
|
||||
await playback.player.pause();
|
||||
} catch (_) {}
|
||||
}
|
||||
final JellyfinPlan plan;
|
||||
try {
|
||||
plan = await resolveJellyfinRef(jellyfin, ref, relay: r.relay, relayUrl: _relayUrlFor(ref));
|
||||
} finally {
|
||||
if (gen == _jfGen) _opening = false;
|
||||
}
|
||||
if (gen != _jfGen) return;
|
||||
jellyfinPlan.value = plan;
|
||||
switch (plan) {
|
||||
case BlockedPlay():
|
||||
jellyfinBlocked.value = plan;
|
||||
_blockedKey = _accountKey(ref.serverId);
|
||||
try {
|
||||
await playback.stop();
|
||||
} catch (_) {}
|
||||
return;
|
||||
case RelayPlay(:final url):
|
||||
jellyfinBlocked.value = null;
|
||||
// Same relay URL (resumed member): the player still has it.
|
||||
if (url == prevUrl) {
|
||||
_openUrl = url;
|
||||
return;
|
||||
}
|
||||
if (!await _openMedia(url) || gen != _jfGen) return;
|
||||
case OwnPlay(:final url, :final headers):
|
||||
jellyfinBlocked.value = null;
|
||||
if (!await _openMedia(url, headers: headers) || gen != _jfGen) return;
|
||||
final reporter = JellyfinProgressReporter(
|
||||
client: plan.client,
|
||||
itemId: ref.itemId,
|
||||
source: plan.source,
|
||||
playSessionId: plan.info.playSessionId,
|
||||
onUnauthorized: () => jellyfin.markExpired(ref.serverId),
|
||||
onError: (e) {
|
||||
if (_jfToastShown) return;
|
||||
_jfToastShown = true;
|
||||
_pushToast('Jellyfin progress not saved: ${e is JellyfinException && e.isUnauthorized ? 'sign-in expired' : 'server unreachable'}');
|
||||
},
|
||||
);
|
||||
unawaited(_findEpisodes(plan, gen));
|
||||
// Playing carries the tracks: wait (bounded) until the file is in.
|
||||
await playback.waitForTracks();
|
||||
if (gen != _jfGen) return;
|
||||
final snap = await _snapshot();
|
||||
if (gen != _jfGen || snap == null) return;
|
||||
// Installed once started: the per-state restart (after the end)
|
||||
// must not send the first Playing without the tracks.
|
||||
_reporter = reporter..start(snap);
|
||||
}
|
||||
await _applyTrackChoice(plan, gen);
|
||||
}
|
||||
|
||||
Future<void> _findEpisodes(OwnPlay plan, int gen) async {
|
||||
final around = await findAdjacentEpisodes(plan);
|
||||
if (gen != _jfGen) return;
|
||||
previousEpisode.value = around.previous;
|
||||
nextEpisode.value = around.next;
|
||||
final r = serverState.peek();
|
||||
if (r != null) _jellyfinTransport(r);
|
||||
}
|
||||
|
||||
Future<void> _applyTrackChoice(JellyfinPlan plan, int gen) async {
|
||||
final own = plan is OwnPlay ? plan : null;
|
||||
final choice = await trackPrefs.load(seriesId: own?.item?.seriesId);
|
||||
if (choice == null || gen != _jfGen || !_playerReady) return;
|
||||
final tracks = await playback.waitForTracks();
|
||||
if (gen != _jfGen) return;
|
||||
final pick = chooseTracks(choice, source: own?.source, tracks: tracks);
|
||||
await playback.selectTracks(aid: pick.aid, sid: pick.sid, subtitlesOff: pick.subtitlesOff);
|
||||
}
|
||||
|
||||
/// A track picked in the player: applied, remembered for the next
|
||||
/// Jellyfin item (per series and overall), reported.
|
||||
Future<void> selectTrack({int? aid, int? sid, bool subtitlesOff = false}) async {
|
||||
markInput();
|
||||
await playback.selectTracks(aid: aid, sid: sid, subtitlesOff: subtitlesOff);
|
||||
final ids = await playback.currentTrackIds();
|
||||
final plan = jellyfinPlan.peek();
|
||||
final own = plan is OwnPlay ? plan : null;
|
||||
await trackPrefs.save(
|
||||
TrackChoice.of(aid: ids.aid, sid: ids.sid, source: own?.source, tracks: playback.tracks),
|
||||
seriesId: own?.item?.seriesId);
|
||||
final snap = await _snapshot();
|
||||
if (snap != null) _reporter?.update(snap, force: true);
|
||||
}
|
||||
|
||||
Future<void> _tickJellyfin(StateBroadcast r) async {
|
||||
final reporter = _reporter;
|
||||
if (_jfRef == null || r.mediaId != _jfMediaId) return;
|
||||
final snap = await _snapshot();
|
||||
if (snap == null) return;
|
||||
if (reporter != null && identical(reporter, _reporter) && r.transport != 'finished') {
|
||||
reporter.update(snap);
|
||||
}
|
||||
final next = nextEpisode.peek();
|
||||
final duration = playback.durationSecs;
|
||||
var show = false;
|
||||
if (next != null && duration > 0 && autoAdvance.peek() == null && r.transport != 'finished') {
|
||||
final item = (jellyfinPlan.peek() as OwnPlay?)?.item;
|
||||
final at = nextPromptStart(item, Duration(milliseconds: (duration * 1000).round()));
|
||||
show = snap.position * 1000 >= at.inMilliseconds;
|
||||
}
|
||||
nextPromptVisible.value = show;
|
||||
}
|
||||
|
||||
/// Per state: played to the end -> Stopped (Jellyfin marks it watched)
|
||||
/// and the auto-advance countdown; seeked back from the end -> Playing
|
||||
/// again.
|
||||
void _jellyfinTransport(StateBroadcast r) {
|
||||
final ref = _jfRef;
|
||||
if (ref == null || r.mediaId != _jfMediaId) return;
|
||||
final reporter = _reporter;
|
||||
final finished = r.transport == 'finished';
|
||||
if (reporter != null && _openUrl != null && !_opening) {
|
||||
final snap = _snapNow();
|
||||
if (finished && reporter.active && snap != null) {
|
||||
unawaited(reporter.stop(PlayerSnapshot(
|
||||
position: r.position, paused: true, aid: snap.aid, sid: snap.sid)));
|
||||
} else if (!finished && !reporter.active && snap != null) {
|
||||
reporter.start(snap);
|
||||
}
|
||||
}
|
||||
if (!finished) {
|
||||
if (autoAdvance.peek() != null) cancelAutoAdvance();
|
||||
_advanceDoneFor = -1;
|
||||
return;
|
||||
}
|
||||
nextPromptVisible.value = false;
|
||||
final next = nextEpisode.peek();
|
||||
if (next == null ||
|
||||
!AppSettings.instance.autoAdvance.peek() ||
|
||||
_advanceDoneFor == r.mediaId ||
|
||||
autoAdvance.peek()?.mediaId == r.mediaId) {
|
||||
return;
|
||||
}
|
||||
autoAdvance.value = AutoAdvance(
|
||||
mediaId: r.mediaId, secondsLeft: autoAdvanceSecs, next: next, swapper: _isSwapper(r, ref));
|
||||
_advanceTimer?.cancel();
|
||||
_advanceTimer = Timer.periodic(const Duration(seconds: 1), (_) => _advanceTick());
|
||||
}
|
||||
|
||||
bool _isSwapper(StateBroadcast r, JellyfinRef ref) =>
|
||||
autoAdvanceSwapper(r.members, ref.serverId) == sync.memberId;
|
||||
|
||||
void _advanceTick() {
|
||||
final a = autoAdvance.peek();
|
||||
final r = serverState.peek();
|
||||
final ref = _jfRef;
|
||||
if (a == null || r == null || ref == null || r.mediaId != a.mediaId || r.transport != 'finished') {
|
||||
cancelAutoAdvance();
|
||||
return;
|
||||
}
|
||||
final left = a.secondsLeft - 1;
|
||||
if (left > 0) {
|
||||
autoAdvance.value = AutoAdvance(
|
||||
mediaId: a.mediaId, secondsLeft: left, next: a.next, swapper: _isSwapper(r, ref));
|
||||
return;
|
||||
}
|
||||
// Decided on the latest state: one swapper among the clients counting.
|
||||
final swap = _isSwapper(r, ref);
|
||||
cancelAutoAdvance();
|
||||
if (swap) swapJellyfin(a.next.pick);
|
||||
}
|
||||
|
||||
String _accountKey(String serverId) =>
|
||||
'${jellyfin.account(serverId)?.token}|${jellyfin.statusOf(serverId).name}';
|
||||
|
||||
/// A blocked viewer links (or reconnects) the account: try again.
|
||||
void _onAccountsChanged() {
|
||||
final blocked = jellyfinBlocked.peek();
|
||||
if (blocked == null) return;
|
||||
final key = _accountKey(blocked.serverId);
|
||||
if (key == _blockedKey) return;
|
||||
_blockedKey = key;
|
||||
final status = jellyfin.statusOf(blocked.serverId);
|
||||
if (jellyfin.account(blocked.serverId) == null ||
|
||||
status == JellyfinAccountStatus.expired ||
|
||||
status == JellyfinAccountStatus.checking) {
|
||||
return;
|
||||
}
|
||||
retryJellyfin();
|
||||
}
|
||||
|
||||
/// "Try again" on the blocked card (and after linking an account).
|
||||
void retryJellyfin() {
|
||||
final r = serverState.peek();
|
||||
final ref = refOfStateMedia(r?.media);
|
||||
if (r == null || ref == null) return;
|
||||
unawaited(_playJellyfin(ref, r));
|
||||
}
|
||||
|
||||
void _scheduleReconnect({bool manual = false}) {
|
||||
@@ -790,6 +1262,7 @@ class SessionCoordinator {
|
||||
_seekTimer = null;
|
||||
_seekGate.reset();
|
||||
reconnecting.value = false;
|
||||
await _stopJellyfin();
|
||||
_playerReady = false;
|
||||
try {
|
||||
await playback.dispose();
|
||||
@@ -806,6 +1279,10 @@ class SessionCoordinator {
|
||||
|
||||
Future<void> dispose() async {
|
||||
await leave(silent: true);
|
||||
if (_jellyfinListening) {
|
||||
_jellyfinListening = false;
|
||||
jellyfin.removeListener(_onAccountsChanged);
|
||||
}
|
||||
await _stateSub?.cancel();
|
||||
await _feedSub?.cancel();
|
||||
await _kickSub?.cancel();
|
||||
|
||||
@@ -131,6 +131,27 @@ class ServerIsolate {
|
||||
if (!_stopping) crash?.call(_lastError ?? 'the server stopped unexpectedly');
|
||||
}
|
||||
|
||||
/// Makes [path] the hosted file (the in-session File swap). Returns its
|
||||
/// name and size for the `swap` that puts it up, or null when the file
|
||||
/// is missing or the server is gone.
|
||||
Future<({String name, int size})?> setFile(String path,
|
||||
{Duration timeout = const Duration(seconds: 5)}) async {
|
||||
if (_exited.isCompleted) return null;
|
||||
final reply = ReceivePort('server file');
|
||||
try {
|
||||
_stop.send({'t': 'file', 'path': path, 'reply': reply.sendPort});
|
||||
final msg = await reply.first.timeout(timeout);
|
||||
if (msg is Map && msg['ok'] == true) {
|
||||
return (name: msg['name'] as String, size: msg['size'] as int);
|
||||
}
|
||||
return null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
} finally {
|
||||
reply.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the server to close its sockets and exit; kills the isolate if it
|
||||
/// has not exited within [timeout].
|
||||
Future<void> stop({Duration timeout = const Duration(seconds: 3)}) async {
|
||||
|
||||
@@ -6,6 +6,8 @@ import 'package:flutter/widgets.dart';
|
||||
import 'package:signals/signals_flutter.dart';
|
||||
import 'package:sync_relay_core/core.dart';
|
||||
|
||||
import '../jellyfin/accounts.dart';
|
||||
import '../jellyfin/session_media.dart';
|
||||
import '../sfx/sfx.dart';
|
||||
import '../session/health.dart';
|
||||
import '../session/session_coordinator.dart';
|
||||
@@ -154,6 +156,7 @@ class SessionState {
|
||||
final SfxService sfx = const NoopSfxService();
|
||||
late final SessionCoordinator coordinator = SessionCoordinator(sfx: sfx);
|
||||
final lastForm = ConnectForm();
|
||||
JellyfinAccounts get jellyfin => JellyfinAccounts.instance;
|
||||
/// Set when the hosted server died mid-session; Home shows it on the
|
||||
/// Host card and clears it.
|
||||
final serverCrash = signal<String?>(null);
|
||||
@@ -232,6 +235,14 @@ class SessionState {
|
||||
if (op != _op) throw const ConnectCancelled();
|
||||
final hostKey = newHostKey();
|
||||
_setupCrash = null;
|
||||
// A pasted Jellyfin link goes up as a ref like a browser pick.
|
||||
final media = params.media ??
|
||||
(params.linkUrl.isEmpty ? null : await mediaForLink(jellyfin, params.linkUrl));
|
||||
if (op != _op) throw const ConnectCancelled();
|
||||
// Guests without an account watch through the server, with the
|
||||
// host's own sign-in (the hosted item's server, else the default).
|
||||
await jellyfin.ensureLoaded(validate: false);
|
||||
final relay = relayCredentialFor(jellyfin, serverId: media?.jellyfin?.serverId);
|
||||
late final ServerIsolate server;
|
||||
try {
|
||||
server = await ServerIsolate.start(
|
||||
@@ -241,6 +252,7 @@ class SessionState {
|
||||
name: 'server',
|
||||
mediaPath: params.mediaPath,
|
||||
hostKey: hostKey,
|
||||
jellyfin: relay,
|
||||
),
|
||||
onLog: (line) => debugPrint('[server] $line'),
|
||||
onCrash: (cause) => _onServerCrash(server, cause),
|
||||
@@ -256,6 +268,8 @@ class SessionState {
|
||||
throw const ConnectCancelled();
|
||||
}
|
||||
_server = server;
|
||||
coordinator.hostFile = (path) async =>
|
||||
identical(_server, server) ? server.setFile(path) : null;
|
||||
status.value =
|
||||
HealthStatus(HealthSeverity.ok, 'hosting on port ${server.port}');
|
||||
try {
|
||||
@@ -265,8 +279,8 @@ class SessionState {
|
||||
secret: params.secret,
|
||||
name: params.name,
|
||||
avatar: params.avatar,
|
||||
linkUrl: params.linkUrl,
|
||||
hostKey: hostKey,
|
||||
media: media,
|
||||
));
|
||||
if (op != _op) throw const ConnectCancelled();
|
||||
} catch (e) {
|
||||
@@ -353,6 +367,7 @@ class SessionState {
|
||||
}
|
||||
|
||||
Future<void> stopServer() async {
|
||||
coordinator.hostFile = null;
|
||||
_stopKickWatch?.call();
|
||||
_stopKickWatch = null;
|
||||
final server = _server;
|
||||
|
||||
@@ -16,6 +16,7 @@ const _keyAutoCheckUpdates = 'autoCheckUpdates';
|
||||
const _keyShaderPreset = 'shaderPreset';
|
||||
const _keyShaderQuality = 'shaderQuality';
|
||||
const _keyCustomShaders = 'customShaders';
|
||||
const _keyAutoAdvance = 'autoAdvance';
|
||||
|
||||
enum HwdecMode { auto, off, custom }
|
||||
|
||||
@@ -25,6 +26,8 @@ class AppSettings {
|
||||
final hwdecMode = signal(HwdecMode.auto);
|
||||
final hwdecCustom = signal('');
|
||||
final autoCheckUpdates = signal(true);
|
||||
/// Jellyfin episodes: at the end, count down 10 s and put up the next.
|
||||
final autoAdvance = signal(true);
|
||||
|
||||
/// Video shaders: one choice, used on join and changed both here and
|
||||
/// in the session (Ctrl+0..6, the shader button).
|
||||
@@ -59,6 +62,8 @@ class AppSettings {
|
||||
if (custom is String) hwdecCustom.value = custom;
|
||||
final auto = box.get(_keyAutoCheckUpdates);
|
||||
if (auto is bool) autoCheckUpdates.value = auto;
|
||||
final advance = box.get(_keyAutoAdvance);
|
||||
if (advance is bool) autoAdvance.value = advance;
|
||||
final preset = box.get(_keyShaderPreset);
|
||||
shaderPreset.value =
|
||||
ShaderPreset.values.where((p) => p.name == preset).firstOrNull ??
|
||||
@@ -91,6 +96,11 @@ class AppSettings {
|
||||
_put(_keyAutoCheckUpdates, on);
|
||||
}
|
||||
|
||||
void setAutoAdvance(bool on) {
|
||||
autoAdvance.value = on;
|
||||
_put(_keyAutoAdvance, on);
|
||||
}
|
||||
|
||||
void setShaderPreset(ShaderPreset preset) {
|
||||
shaderPreset.value = preset;
|
||||
_put(_keyShaderPreset, preset.name);
|
||||
|
||||
@@ -36,6 +36,9 @@ class SyncClient {
|
||||
String token = '';
|
||||
String memberId = '';
|
||||
String? mediaUrl;
|
||||
/// This member's `/j/...` URL from `welcome` (Jellyfin media the server
|
||||
/// relays); private like [token].
|
||||
String? relayUrl;
|
||||
StateBroadcast? lastState;
|
||||
Completer<WelcomeMessage>? _pendingWelcome;
|
||||
|
||||
@@ -89,6 +92,7 @@ class SyncClient {
|
||||
token = welcome.token;
|
||||
memberId = welcome.memberId;
|
||||
mediaUrl = welcome.mediaUrl;
|
||||
relayUrl = welcome.relayUrl;
|
||||
if (welcome.state != null) {
|
||||
try {
|
||||
lastState = StateBroadcast.fromJson(welcome.state!);
|
||||
@@ -214,6 +218,7 @@ class SyncClient {
|
||||
required int eventId,
|
||||
double duration = 0,
|
||||
int mediaId = 0,
|
||||
Map<String, bool>? jf,
|
||||
}) {
|
||||
final safeBuffered = buffered.isNaN || buffered < 0 ? 0.0 : buffered;
|
||||
_send(
|
||||
@@ -223,6 +228,7 @@ class SyncClient {
|
||||
eventId: eventId,
|
||||
duration: duration.isFinite && duration > 0 ? duration : 0,
|
||||
mediaId: mediaId,
|
||||
jf: jf,
|
||||
).toJson(),
|
||||
);
|
||||
}
|
||||
@@ -254,6 +260,7 @@ class SyncClient {
|
||||
token = '';
|
||||
memberId = '';
|
||||
mediaUrl = null;
|
||||
relayUrl = null;
|
||||
lastState = null;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user