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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions lib/media/media_server_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import '../utils/app_logger.dart';
import '../utils/media_server_http_client.dart' show AbortController, MediaServerResponse, throwIfHttpError;
import '../utils/external_ids.dart';
import '../utils/watch_state_notifier.dart';
import '../models/subtitles/subtitle_search_result.dart';
import 'artist_discography.dart';
import 'download_resolution.dart';
import 'ids.dart';
Expand Down Expand Up @@ -775,6 +776,53 @@ abstract class MediaServerClient {
/// a partial resolution.
Future<DownloadResolution> resolveDownload(MediaItem item, {int mediaIndex = 0, String? mediaSourceId});

/// Search server-side remote subtitle providers for [ratingKey].
///
/// Backends that do not implement server-proxied subtitle search throw
/// [UnsupportedError].
Future<List<SubtitleSearchResult>> searchSubtitles(
String ratingKey, {
required String language,
String? title,
int mediaIndex = 0,
String? mediaSourceId,
bool? perfectMatch,
bool? forced,
bool? hearingImpaired,
});

/// Ask the server to download one remote subtitle and attach it to
/// [ratingKey].
///
/// [key] is backend-defined (Plex subtitle key, Emby subtitle id).
Future<bool> downloadSubtitle(
String ratingKey, {
required String key,
String? codec,
String? language,
bool hearingImpaired = false,
bool forced = false,
String? providerTitle,
int mediaIndex = 0,
String? mediaSourceId,
});

/// Consume a backend-reported source subtitle stream id for a subtitle that
/// was just downloaded for [ratingKey].
///
/// Returns `null` when the backend does not expose this signal or there is
/// no pending downloaded-stream id to consume.
Future<int?> consumeDownloadedSubtitleStreamId(String ratingKey, {int mediaIndex = 0, String? mediaSourceId}) async =>
null;

/// Return current source subtitle tracks for [ratingKey] so callers can
/// detect newly-attached external subtitle streams.
Future<List<MediaSubtitleTrack>> fetchSourceSubtitleTracks(
String ratingKey, {
int mediaIndex = 0,
String? mediaSourceId,
});

/// The artwork files the download pipeline should persist for [item] so
/// the offline UI can render its poster, clear logo, and background art.
/// Each entry pairs the absolute URL with a stable `localKey` the
Expand Down
14 changes: 7 additions & 7 deletions lib/media/server_capabilities.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ class ServerCapabilities {
/// playback progress. Plex exposes this directly; Jellyfin does not.
final bool continueWatchingRemoval;

/// External subtitle search/marketplace (Plex `/library/metadata/{id}/subtitles`).
/// External subtitle search/marketplace (Plex `/library/metadata/{id}/subtitles`,
/// Emby `/Items/{id}/RemoteSearch/Subtitles/{language}`).
/// Hides the "Search subtitles" affordance when false.
final bool externalSubtitleSearch;

Expand Down Expand Up @@ -137,18 +138,17 @@ class ServerCapabilities {
numericUserRating: false,
userFavorites: true,
continueWatchingRemoval: true,
externalSubtitleSearch: false,
externalSubtitleSearch: true,
richMetadataEdit: true,
scrubThumbnails: true,
folderGrouping: true,
instantMix: true,
);

/// Every flag here is fixed per backend *kind* except [videoTranscoding],
/// which Plex probes per server (`PlexClient.capabilities`) — so that is the
/// only override this type needs. Widen the parameter list if another flag
/// ever becomes a runtime probe.
ServerCapabilities copyWith({bool? videoTranscoding}) {
/// which Plex probes per server (`PlexClient.capabilities`). Emby subtitle
/// search/download is also runtime-gated by Premiere status.
ServerCapabilities copyWith({bool? videoTranscoding, bool? externalSubtitleSearch}) {
return ServerCapabilities(
liveTv: liveTv,
liveTvDvr: liveTvDvr,
Expand All @@ -157,7 +157,7 @@ class ServerCapabilities {
numericUserRating: numericUserRating,
userFavorites: userFavorites,
continueWatchingRemoval: continueWatchingRemoval,
externalSubtitleSearch: externalSubtitleSearch,
externalSubtitleSearch: externalSubtitleSearch ?? this.externalSubtitleSearch,
richMetadataEdit: richMetadataEdit,
scrubThumbnails: scrubThumbnails,
folderGrouping: folderGrouping,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import 'package:json_annotation/json_annotation.dart';

import '../../utils/json_utils.dart';

part 'plex_subtitle_search_result.g.dart';
part 'subtitle_search_result.g.dart';

@JsonSerializable()
class PlexSubtitleSearchResult {
class SubtitleSearchResult {
@JsonKey(fromJson: flexibleIntOrZero)
final int id;
@JsonKey(readValue: readStringField, defaultValue: '')
Expand Down Expand Up @@ -33,7 +33,7 @@ class PlexSubtitleSearchResult {
@JsonKey(fromJson: flexibleBool)
final bool forced;

PlexSubtitleSearchResult({
SubtitleSearchResult({
required this.id,
required this.key,
this.codec,
Expand All @@ -49,7 +49,7 @@ class PlexSubtitleSearchResult {
this.forced = false,
});

factory PlexSubtitleSearchResult.fromJson(Map<String, dynamic> json) => _$PlexSubtitleSearchResultFromJson(json);
factory SubtitleSearchResult.fromJson(Map<String, dynamic> json) => _$SubtitleSearchResultFromJson(json);

Map<String, dynamic> toJson() => _$PlexSubtitleSearchResultToJson(this);
Map<String, dynamic> toJson() => _$SubtitleSearchResultToJson(this);
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

110 changes: 108 additions & 2 deletions lib/services/jellyfin_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import '../models/media_subscription.dart';
import '../media/media_source_info.dart';
import '../media/media_sort.dart';
import '../media/media_version.dart';
import '../models/subtitles/subtitle_search_result.dart';
import '../utils/app_logger.dart';
import '../utils/device_identity.dart';
import '../utils/failover_http_client.dart';
Expand All @@ -57,6 +58,7 @@ import '../exceptions/media_server_exceptions.dart';
import '../i18n/strings.g.dart';
import '../utils/json_utils.dart';
import '../utils/jellyfin_time.dart';
import '../utils/language_codes.dart';
import 'jellyfin_auth_header.dart';
import 'jellyfin_endpoint_discovery.dart';
import '../media/download_resolution.dart';
Expand Down Expand Up @@ -88,6 +90,7 @@ part 'jellyfin_client/parts/file_info.dart';
part 'jellyfin_client/parts/live_tv.dart';
part 'jellyfin_client/parts/live_tv_dvr.dart';
part 'jellyfin_client/parts/images_downloads.dart';
part 'jellyfin_client/parts/subtitle_search.dart';
part 'jellyfin_client/parts/metadata_edit.dart';

/// Canonical declarations of the [JellyfinClient] internals that the `part`
Expand Down Expand Up @@ -138,6 +141,9 @@ mixin _JellyfinClientInternals on MediaServerCacheMixin {
});
String _withApiKey(String urlOrPath);

void rememberDownloadedSubtitleStreamId(String itemId, String mediaSourceId, int streamId);
int? consumeDownloadedSubtitleStreamIdByKey(String itemId, String mediaSourceId);

/// Positional core of the tolerant `/Items` array fetch. The browse part's
/// implementation widens it with optional retry/abort/diagnostics knobs that
/// only its own call sites pass.
Expand Down Expand Up @@ -222,6 +228,7 @@ class JellyfinClient
_JellyfinFileInfoMethods,
_JellyfinLiveTvMethods,
_JellyfinImageDownloadMethods,
_JellyfinSubtitleSearchMethods,
_JellyfinMetadataEditMethods
implements
MediaServerClient,
Expand All @@ -231,7 +238,13 @@ class JellyfinClient
GracefullyCloseable {
JellyfinClient._({required this._connection, required this._http, FavoriteChannelsRepository? favoritesRepository})
: _favoritesRepository = favoritesRepository ?? const SharedPreferencesFavoriteChannelsRepository(),
_paths = MediaBrowserPaths(dialect: _connection.dialect, userId: _connection.userId);
_paths = MediaBrowserPaths(dialect: _connection.dialect, userId: _connection.userId) {
if (_connection.dialect == MediaBrowserDialect.emby) {
// Prime policy-gated capabilities early so UI gates converge quickly
// even before the first periodic health sweep.
unawaited(_refreshEmbySubtitlePolicy(force: true));
}
}

/// Build a fully-initialised [JellyfinClient]. Endpoint reachability is
/// raced before construction by onboarding/profile binding; this factory
Expand Down Expand Up @@ -361,6 +374,13 @@ class JellyfinClient
final FailoverHttpClient _http;
final FavoriteChannelsRepository _favoritesRepository;
bool _offlineMode = false;
final Map<String, int> _downloadedSubtitleStreamIds = <String, int>{};

// Runtime gate for Emby subtitle download/search availability.
// Emby exposes this as a per-user policy flag on /Users/{id}.
bool _embyCanDownloadSubtitles = false;
DateTime? _embySubtitlePolicyCheckedAt;
Future<void>? _embySubtitlePolicyProbe;

/// Fired when the live `connection` snapshot diverges from the cached one
/// (currently only on admin-status change). [MultiServerManager] uses this
Expand All @@ -374,6 +394,25 @@ class JellyfinClient
}
}

static String _subtitleDownloadStreamKey(String itemId, String mediaSourceId) =>
'${itemId.trim()}|${mediaSourceId.trim()}';

@override
void rememberDownloadedSubtitleStreamId(String itemId, String mediaSourceId, int streamId) {
final item = itemId.trim();
final source = mediaSourceId.trim();
if (item.isEmpty || source.isEmpty) return;
_downloadedSubtitleStreamIds[_subtitleDownloadStreamKey(item, source)] = streamId;
}

@override
int? consumeDownloadedSubtitleStreamIdByKey(String itemId, String mediaSourceId) {
final item = itemId.trim();
final source = mediaSourceId.trim();
if (item.isEmpty || source.isEmpty) return null;
return _downloadedSubtitleStreamIds.remove(_subtitleDownloadStreamKey(item, source));
}

Future<void> _handleEndpointSwitch(String newBaseUrl, {required bool persist}) async {
LogRedactionManager.registerServerUrl(newBaseUrl);
final changed = connection.baseUrl != newBaseUrl;
Expand All @@ -388,6 +427,66 @@ class JellyfinClient
}
}

Future<void> _refreshEmbySubtitlePolicy({bool force = false}) async {
if (dialect != MediaBrowserDialect.emby) return;

final now = DateTime.now();
final lastChecked = _embySubtitlePolicyCheckedAt;
if (!force && lastChecked != null && now.difference(lastChecked) < const Duration(minutes: 10)) {
return;
}

final inFlight = _embySubtitlePolicyProbe;
if (inFlight != null) {
await inFlight;
return;
}

final probe = () async {
bool canDownloadSubtitles = false;
try {
// Emby user policy surfaces subtitle permissions directly.
final response = await _http.get(
'/Users/${_segment(connection.userId)}',
timeout: MediaServerTimeouts.jellyfinProbe,
);

final data = response.data;
if (response.statusCode >= 200 && response.statusCode < 300 && data is Map<String, dynamic>) {
final policy = data['Policy'];
if (policy is Map<String, dynamic>) {
canDownloadSubtitles = _embyPolicyAllowsSubtitleDownloading(policy);
}
}
} catch (_) {
canDownloadSubtitles = false;
}

_embySubtitlePolicyCheckedAt = now;
if (canDownloadSubtitles == _embyCanDownloadSubtitles) return;

_embyCanDownloadSubtitles = canDownloadSubtitles;
appLogger.i('Emby subtitle capability changed: externalSubtitleSearch=$_embyCanDownloadSubtitles');
final listener = onConnectionUpdated;
if (listener != null) {
await Future.sync(() => listener(_connection));
}
}();

_embySubtitlePolicyProbe = probe;
try {
await probe;
} finally {
if (identical(_embySubtitlePolicyProbe, probe)) {
_embySubtitlePolicyProbe = null;
}
}
}

static bool _embyPolicyAllowsSubtitleDownloading(Map<String, dynamic> policy) {
return policy['EnableSubtitleDownloading'] == true || policy['EnableSubtitleManagement'] == true;
}

/// Read-only view of the headers attached to every outgoing request.
/// Test-only entry point for asserting the SDK-style `MediaBrowser`
/// Authorization shape — Findroid (and the official SDK) sends the same
Expand Down Expand Up @@ -433,7 +532,7 @@ class JellyfinClient
@override
ServerCapabilities get capabilities => switch (dialect) {
MediaBrowserDialect.jellyfin => ServerCapabilities.jellyfin,
MediaBrowserDialect.emby => ServerCapabilities.emby,
MediaBrowserDialect.emby => ServerCapabilities.emby.copyWith(externalSubtitleSearch: _embyCanDownloadSubtitles),
};

/// Neither dialect exposes a per-server played-threshold pref, so we mirror
Expand Down Expand Up @@ -500,6 +599,13 @@ class JellyfinClient
}
}
}
if (dialect == MediaBrowserDialect.emby) {
try {
await _refreshEmbySubtitlePolicy(force: true);
} catch (e, st) {
appLogger.w('Failed to refresh Emby subtitle policy', error: e, stackTrace: st);
}
}
return HealthStatus.online;
}
if (response.statusCode == 401 || response.statusCode == 403) {
Expand Down
Loading