Files
plezy/lib/screens/settings/add_connection_screen.dart
T
edde746 05fd622968 feat(emby): add Emby as a MediaBrowser backend alongside Jellyfin
Emby is Jellyfin's upstream ancestor and speaks a near-identical MediaBrowser
API, so the existing Jellyfin stack is parameterised by a `MediaBrowserDialect`
rather than forked. `JellyfinClient`, its auth service, endpoint discovery, LAN
discovery, and the add/edit connection screens all take the dialect and keep one
implementation; `MediaBackend.emby` and `ConnectionKind.emby` carry it through
the neutral models, the Drift `kind` discriminator, downloads, and caches.

Every divergence below was measured against a live Emby 4.9.5 server, not
inferred from documentation, and each is documented at its capability getter.
Jellyfin's request strings stay byte-identical so nothing about its behaviour
changes.

Routes and auth
- Emby only accepts the pre-10.9 user-scoped item routes (`/Users/{id}/Items/…`,
  `/Users/{id}/PlayedItems/…`, `/Users/{id}/FavoriteItems/…`); the unprefixed
  forms Jellyfin 10.11 added return 404.
- The API is also served under a legacy `/emby` prefix, and both dialects accept
  the token as `X-Emby-Token` or `api_key=`.
- Emby answers only its own LAN discovery datagram ("who is EmbyServer?") and
  ignores Jellyfin's; its default HTTPS port is 8920.
- No `/QuickConnect` route exists, so Quick Connect stays Jellyfin-only.

Row fields Emby withholds
- `ProductionYear`, `OfficialRating`, `PremiereDate` and `DateCreated` are absent
  from list rows unless named in `Fields`, which would otherwise strip the year
  and age-rating badge from every card in the app.
- `UserData.LastPlayedDate` never appears on a list row under `Fields=UserData`,
  `EnableUserData=true` or the user-scoped `Ids=` form — only on the single-item
  detail route, or when the Emby-specific `UserDataLastPlayedDate` token is
  requested. Without it every recency-ordered surface silently degrades to
  library-add time, and `JellyfinApiCache.applyWatchState` stamps
  `DateTime.now()` on watched rows, so an offline watch-state pull would rewrite
  the cached play time of everything it walked.

Continue Watching and Next Up
- Emby computes Next Up per series only: the library-wide `/Shows/NextUp` query
  returns nothing under every parameter combination tried. The shelf is
  therefore reconstructed from a played-episode recency scan plus one
  `/Shows/NextUp?SeriesId=` per distinct series, bounded by a shared wall clock
  that covers the scan as well — per-request timeouts cannot bound the pass
  because `MediaServerHttpClient` times the connect and receive phases
  independently. Rows are stamped with their series' newest play from the same
  response that ordered them, so no per-series enrichment request is needed.
- `/Shows/NextUp` ignores `NextUpDateCutoff`, and no server-side played-date
  filter exists to delegate to (`MinDatePlayed` and `MinDateLastPlayed` are
  ignored; `MinDateLastSaved`, `MinDateCreated` and `MinPremiereDate` filter
  unrelated dates), so the 365-day window is applied to the scanned dates.
- The resume route returns items with no saved position, including plain next
  episodes, so the Emby resume leg reads from `/Items?Filters=IsResumable`.
- Emby is ahead of Jellyfin in one place: `/Users/{id}/Items/{id}/HideFromResume`
  makes Continue Watching removal a real capability.

Everything else
- `/Sessions/Playing` and `/Sessions/Playing/Progress` reject a body with no
  `PlaySessionId` (HTTP 400), so playback reporting always sends one.
- Passing any `MediaTypes` value to the playlist query returns an empty list.
- There is no aggregate `/Items/Filters` route; the four filter facets are
  reassembled from `/Genres`, `/OfficialRatings`, `/Studios` and `/Tags`.
- Metadata writes take name-pair lists (`Genres: [{'Name': 'Action'}]`); the
  plain string array is accepted and then silently discarded.
- Custom artwork uploads must be base64 text, not raw bytes — which was broken
  for Jellyfin too and is fixed for both.
- Trickplay, media segments and lyrics 404 on Emby, so scrub previews are absent
  and intro/credit markers fall back to chapter names.

Verified against a local Emby 4.9.5 and a Jellyfin 10.11.11 control server:
onboarding, browse, detail, playable stream URLs serving real bytes, subtitle
sidecars, watch-state write and restore, hubs, cross-server aggregation and
search across both backends simultaneously.
2026-08-05 06:09:26 +02:00

180 lines
6.5 KiB
Dart

import 'package:flutter/material.dart';
import 'package:plezy/widgets/app_icon.dart';
import 'package:material_symbols_icons/symbols.dart';
import '../../focus/focusable_wrapper.dart';
import '../../i18n/strings.g.dart';
import '../../media/media_backend.dart';
import '../../media/media_browser_dialect.dart';
import '../../theme/mono_tokens.dart';
import '../../profiles/profile.dart';
import '../../widgets/backend_badge.dart';
import '../../widgets/focused_scroll_scaffold.dart';
import '../profile/borrow_connection_screen.dart';
import 'add_jellyfin_screen.dart';
import 'add_plex_account_screen.dart';
/// Picker shown when the user taps "Add connection".
///
/// When [targetProfile] is provided, also offers a "Borrow from another
/// profile" option that opens [BorrowConnectionScreen] for the target. The
/// global Connections screen invokes this without a target — Plex auto-
/// surfaces its Home users as new profiles, while MediaBrowser servers bind
/// to the active profile via [AddJellyfinScreen].
///
/// Pops with `true` after the underlying flow succeeds so the parent list
/// refreshes; pops with `null` (the default) when the user backs out.
class AddConnectionScreen extends StatelessWidget {
final Profile? targetProfile;
const AddConnectionScreen({super.key, this.targetProfile});
@override
Widget build(BuildContext context) {
final scoped = targetProfile != null;
const jellyfinDialect = MediaBrowserDialect.jellyfin;
const embyDialect = MediaBrowserDialect.emby;
final options = <_BackendOption>[
_BackendOption(
backend: MediaBackend.plex,
title: t.addServer.signInWithPlexCard,
subtitle: scoped ? t.addServer.signInWithPlexCardSubtitleScoped : t.addServer.signInWithPlexCardSubtitle,
builder: (_) => AddPlexAccountScreen(targetProfile: targetProfile),
),
_BackendOption(
backend: MediaBackend.jellyfin,
title: t.addServer.connectToMediaBrowserCard(product: jellyfinDialect.productName),
subtitle: scoped
? t.addServer.connectToMediaBrowserCardSubtitleScoped(
product: jellyfinDialect.productName,
name: targetProfile!.displayName,
)
: t.addServer.connectToMediaBrowserCardSubtitle,
builder: (_) => AddJellyfinScreen(targetProfile: targetProfile, dialect: jellyfinDialect),
),
_BackendOption(
backend: MediaBackend.emby,
title: t.addServer.connectToMediaBrowserCard(product: embyDialect.productName),
subtitle: scoped
? t.addServer.connectToMediaBrowserCardSubtitleScoped(
product: embyDialect.productName,
name: targetProfile!.displayName,
)
: t.addServer.connectToMediaBrowserCardSubtitle,
builder: (_) => AddJellyfinScreen(targetProfile: targetProfile, dialect: embyDialect),
),
if (scoped)
_BackendOption(
backend: null,
title: t.addServer.borrowFromAnotherProfile,
subtitle: t.addServer.borrowFromAnotherProfileSubtitle,
builder: (_) => BorrowConnectionScreen(targetProfile: targetProfile!),
),
];
final tokensRef = tokens(context);
return FocusedScrollScaffold(
title: Text(
scoped
? t.addServer.addConnectionTitleScoped(name: targetProfile!.displayName)
: t.addServer.addConnectionTitle,
),
slivers: [
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
for (var i = 0; i < options.length; i++) ...[
if (i > 0) SizedBox(height: tokensRef.groupGap),
_BackendCard(
borderRadius: groupItemRadii(context, i, options.length),
leading: options[i].backend != null
? BackendBadge(backend: options[i].backend!, size: 28)
: const AppIcon(Symbols.share_rounded, fill: 1, size: 28),
title: options[i].title,
subtitle: options[i].subtitle,
onTap: () async {
final added = await Navigator.push<bool>(context, MaterialPageRoute(builder: options[i].builder));
if (added == true && context.mounted) {
Navigator.of(context).pop(true);
}
},
),
],
]),
),
),
],
);
}
}
class _BackendOption {
/// Null for the borrow option (renders a share icon instead of a badge).
final MediaBackend? backend;
final String title;
final String subtitle;
final WidgetBuilder builder;
const _BackendOption({required this.backend, required this.title, required this.subtitle, required this.builder});
}
class _BackendCard extends StatelessWidget {
final BorderRadius borderRadius;
final Widget leading;
final String title;
final String subtitle;
final VoidCallback onTap;
const _BackendCard({
required this.borderRadius,
required this.leading,
required this.title,
required this.subtitle,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return FocusableWrapper(
disableScale: true,
borderRadii: borderRadius,
descendantsAreFocusable: false,
onSelect: onTap,
child: Material(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: borderRadius,
child: InkWell(
onTap: onTap,
borderRadius: borderRadius,
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
leading,
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: .start,
children: [
Text(title, style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(
subtitle,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurface.withValues(alpha: 0.7),
),
),
],
),
),
const AppIcon(Symbols.chevron_right_rounded, fill: 1),
],
),
),
),
),
);
}
}