A Portuguese user reported "Skip Intro" rendering in English on Android TV.
The locale files were not the problem - all 22 were structurally complete.
skip_marker_button.dart simply never imported strings.g.dart and assigned
'Skip Intro' / 'Skip Credits' / 'Next Episode' as plain literals. An audit of
lib/ found ~120 more sites in the same state, in four shapes that need
different fixes:
A literal in a file that never imported the i18n layer is the easy one -
skip_marker_button, performance_stats, track_label_builder and codec_utils all
render text with no `t` in the file at all. TrackLabelBuilder._compose now takes
a fallbackLabel builder instead of an English fallbackPrefix, so the caller
supplies t.audioTracks.track / t.videoControls.subtitleTrack and every unnamed
audio and subtitle row in the track menus is localized.
English reaching the user through an exception message is the widest one, and
it needs care: MediaServerException.message feeds both toString() - logs and
Sentry grouping - and verbatim UI display. Localizing it in place would make
bug-report logs follow the user's locale and split one Sentry issue into 22.
The MediaServer and Seerr families instead gain a nullable `display` alongside
the English `message`, and the six screens that print these errors read
`display ?? message`. PlaybackException keeps the opposite rule, because it
already carries a PlaybackFailureReason for logic and classifyPlaybackFailure
already builds it from t.messages: its stragglers are localized at the throw
site. That also removes the literal "Exception: " prefix Live TV users saw on
a tune failure, since PlaybackException.toString() returns the bare message.
Localized parts hand-concatenated with bare English are the shape no search for
Text('...') can find: '${t.common.pause} auto-scroll' on the home carousel,
'${day} at ${time}' on the Live TV schedule row, and an actor-screen count that
hand-rolled its plural as `n == 1 ? 'title' : 'titles'` - wrong for ru and pl
regardless of translation, now a real Slang plural.
Finally a literal assigned to provider state that a widget renders later:
DownloadProgress.errorMessage, and the four background_downloader notification
bodies, which sit inside a plugin config call where no widget-shaped search
reaches them.
Two things surfaced while converting. track_chapter_controls compared a track
label against 'Audio Track N' to swap in a localized version; once the builder
localized its own fallback that branch became unreachable, so it and the
orphaned _joinTrackLabel are gone. And discovery_view's PeerError fallback arm
looks like a leak but is not - its producers already localize, and a test says
so - so it stays as it is.
All 21 non-base locales are translated, including the 21 keys left empty by
earlier commits that were falling back to English. No locale has an empty value.
scripts/check_hardcoded_strings.py guards the three shapes a structural check
can see, and runs in ci_checks.sh after translation hygiene. Its first draft
passed its own tests while missing this very bug, because 'Skip Intro' is bound
to a local rather than handed to Text(); the name-bound rule that closes that
gap is restricted to phrase-shaped literals, or it cannot tell copy from the
identifiers this codebase binds constantly ('cast_row', 'auto', 'liveTv'). It
cannot see English inside a throw or assigned to a provider field - neither is
distinguishable from a log message without dataflow analysis - and the docstring
says so. label: and actionLabel: are deliberately unscanned: here they name a
diagnostic operation, and a check that is chronically red is a check that gets
switched off.
One commit rather than one per area: the keys, the 22 locale files and the
generated output are a single unit, and any partial split fails the repo's own
unused-key scan on the way through.
close #1856
287 lines
10 KiB
Dart
287 lines
10 KiB
Dart
import 'dart:io';
|
|
import '../media/ids.dart';
|
|
|
|
import 'package:path/path.dart' as p;
|
|
import '../i18n/strings.g.dart';
|
|
|
|
import '../database/app_database.dart';
|
|
import '../media/media_item.dart';
|
|
import '../media/media_item_types.dart';
|
|
import '../media/media_server_client.dart';
|
|
import '../media/media_source_info.dart';
|
|
import '../mpv/models.dart';
|
|
import '../utils/app_logger.dart';
|
|
import '../utils/global_key_utils.dart';
|
|
import 'cached_playback_metadata_service.dart';
|
|
import 'download_storage_service.dart';
|
|
import 'downloaded_video_source.dart';
|
|
import 'playback_initialization_types.dart';
|
|
|
|
// Re-export so existing callers (video_player_screen) can keep importing
|
|
// PlaybackException / PlaybackInitializationResult / TranscodeFallbackReason
|
|
// via this service file.
|
|
export 'playback_initialization_types.dart';
|
|
|
|
/// Coordinates playback initialization across backends and modes.
|
|
///
|
|
/// **Online (client + network):** delegates to
|
|
/// [MediaServerClient.getPlaybackInitialization] for the per-backend
|
|
/// transcode-or-direct decision.
|
|
///
|
|
/// **Downloaded/offline:** when [preferOffline] finds a local copy, opens it
|
|
/// immediately using per-backend cached [MediaSourceInfo] plus sidecar
|
|
/// subtitles. This intentionally avoids any network-first metadata call.
|
|
class PlaybackInitializationService {
|
|
final MediaServerClient? client;
|
|
final AppDatabase? database;
|
|
|
|
PlaybackInitializationService({this.client, this.database});
|
|
|
|
/// Format a video path as a URL (adds file:// prefix for file paths)
|
|
String _formatVideoUrl(String path) {
|
|
return path.contains('://') ? path : 'file://$path';
|
|
}
|
|
|
|
/// Check if content is available offline and return local path
|
|
///
|
|
/// Returns the local file path if the video is downloaded and completed.
|
|
/// Returns null if not available offline or database is not provided.
|
|
Future<String?> getOfflineVideoPath(
|
|
ServerId serverId,
|
|
String ratingKey, {
|
|
int mediaIndex = 0,
|
|
String? selectedMediaSourceId,
|
|
}) async {
|
|
final source = await _resolveOfflineVideoSource(
|
|
serverId,
|
|
ratingKey,
|
|
mediaIndex: mediaIndex,
|
|
selectedMediaSourceId: selectedMediaSourceId,
|
|
);
|
|
return source?.path;
|
|
}
|
|
|
|
/// Resolve the downloaded copy of an item to its playable local path plus
|
|
/// the version that is actually on disk.
|
|
///
|
|
/// Strict by default: a version mismatch returns null so online flows keep
|
|
/// streaming an explicitly requested non-downloaded version. With
|
|
/// [allowAnyDownloadedVersion] the single downloaded version is returned on
|
|
/// mismatch instead — for offline flows where the alternative is failing.
|
|
Future<DownloadedVideoSource?> _resolveOfflineVideoSource(
|
|
ServerId serverId,
|
|
String ratingKey, {
|
|
required int mediaIndex,
|
|
String? selectedMediaSourceId,
|
|
bool allowAnyDownloadedVersion = false,
|
|
}) async {
|
|
if (database == null) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
// Query by globalKey — the column is UNIQUE so SQLite's auto-index on it
|
|
// makes this an O(log n) lookup. Filtering by (serverId, ratingKey)
|
|
// would only use the serverId index and then linear-scan matching rows.
|
|
final query = database!.select(database!.downloadedMedia)
|
|
..where((tbl) => tbl.globalKey.equals(buildGlobalKey(ServerId(serverId), ratingKey)));
|
|
|
|
final downloadedItem = await query.getSingleOrNull();
|
|
if (downloadedItem == null) {
|
|
return null;
|
|
}
|
|
|
|
return await resolveDownloadedVideoSource(
|
|
downloadedItem,
|
|
requestedMediaIndex: mediaIndex,
|
|
requestedMediaSourceId: selectedMediaSourceId,
|
|
allowAnyDownloadedVersion: allowAnyDownloadedVersion,
|
|
);
|
|
} catch (e) {
|
|
appLogger.w('Error checking offline video path', error: e);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// Fetch playback data for the given metadata.
|
|
///
|
|
/// Online path: delegates to [MediaServerClient.getPlaybackInitialization].
|
|
///
|
|
/// Downloaded/offline path: when [preferOffline] finds a downloaded copy,
|
|
/// builds from cached [MediaSourceInfo] and local sidecars immediately.
|
|
Future<PlaybackInitializationResult> getPlaybackData(
|
|
PlaybackInitializationOptions options, {
|
|
bool preferOffline = false,
|
|
}) async {
|
|
final metadata = options.metadata;
|
|
final serverId = metadata.serverId ?? client?.serverId;
|
|
|
|
DownloadedVideoSource? offlineSource;
|
|
if (serverId != null && (preferOffline || client == null) && database != null) {
|
|
offlineSource = await _resolveOfflineVideoSource(
|
|
ServerId(serverId),
|
|
metadata.id,
|
|
mediaIndex: options.selectedMediaIndex,
|
|
selectedMediaSourceId: options.selectedMediaSourceId,
|
|
// With no client there is nothing to stream from, so any downloaded
|
|
// version beats failing. With a client the strict match must stand:
|
|
// an explicitly requested non-downloaded version streams from the
|
|
// server (issue #1440).
|
|
allowAnyDownloadedVersion: client == null,
|
|
);
|
|
}
|
|
|
|
// Downloaded playback must not wait on a live server. Cached media info
|
|
// preserves track labels where available; the local file is enough to play.
|
|
if (offlineSource != null) {
|
|
appLogger.d('Using offline playback for ${metadata.id}');
|
|
return _buildOfflineResult(
|
|
metadata: metadata,
|
|
offlineVideoPath: offlineSource.path,
|
|
selectedMediaIndex: offlineSource.mediaIndex,
|
|
selectedMediaSourceId: offlineSource.mediaSourceId,
|
|
);
|
|
}
|
|
|
|
if (client == null) {
|
|
throw PlaybackException(t.messages.noVideoUrl, reason: PlaybackFailureReason.noPlayableSource);
|
|
}
|
|
|
|
PlaybackInitializationResult result;
|
|
try {
|
|
result = await client!.getPlaybackInitialization(options);
|
|
} catch (e) {
|
|
rethrow;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
/// Assemble a pure-offline result: local file + cached media info + sidecar
|
|
/// subtitles. Used both when [client] is null and when an online fetch throws.
|
|
Future<PlaybackInitializationResult> _buildOfflineResult({
|
|
required MediaItem metadata,
|
|
required String offlineVideoPath,
|
|
required int selectedMediaIndex,
|
|
String? selectedMediaSourceId,
|
|
}) async {
|
|
MediaSourceInfo? mediaInfo;
|
|
try {
|
|
final cacheServerId = await _resolveCacheServerId(metadata);
|
|
if (cacheServerId != null) {
|
|
mediaInfo = await CachedPlaybackMetadataService.fetchMediaSourceInfo(
|
|
backend: metadata.backend,
|
|
cacheServerId: cacheServerId,
|
|
itemId: metadata.id,
|
|
mediaIndex: selectedMediaIndex,
|
|
);
|
|
}
|
|
} catch (e) {
|
|
appLogger.d('Could not load cached media info for offline playback', error: e);
|
|
}
|
|
|
|
final subtitleSidecars = await _discoverSidecarSubtitles(
|
|
offlineVideoPath,
|
|
metadata: metadata,
|
|
mediaInfo: mediaInfo,
|
|
);
|
|
|
|
return PlaybackInitializationResult(
|
|
availableVersions: const [],
|
|
videoUrl: _formatVideoUrl(offlineVideoPath),
|
|
mediaInfo: mediaInfo,
|
|
subtitleSidecars: subtitleSidecars,
|
|
isOffline: true,
|
|
playMethod: 'DirectPlay',
|
|
selectedMediaIndex: selectedMediaIndex,
|
|
selectedMediaSourceId: selectedMediaSourceId,
|
|
);
|
|
}
|
|
|
|
Future<String?> _resolveCacheServerId(MediaItem metadata) async {
|
|
final liveClient = client;
|
|
if (liveClient != null) return liveClient.cacheServerId;
|
|
|
|
final serverId = metadata.serverId;
|
|
if (serverId == null) return null;
|
|
final db = database;
|
|
if (db == null) return serverId;
|
|
|
|
try {
|
|
final row = await (db.select(
|
|
db.downloadedMedia,
|
|
)..where((tbl) => tbl.globalKey.equals(buildGlobalKey(ServerId(serverId), metadata.id)))).getSingleOrNull();
|
|
return row?.clientScopeId ?? serverId;
|
|
} catch (_) {
|
|
return serverId;
|
|
}
|
|
}
|
|
|
|
/// Find sidecar subtitle files written by the downloader. Plain file videos
|
|
/// use `{video}_subs/{trackId}.{ext}` with a legacy `{videoDir}/subtitles/*`
|
|
/// fallback. SAF videos are `content://` URIs, so sidecars live in the
|
|
/// app-managed subtitle directory keyed by server/item id.
|
|
Future<List<PlaybackSubtitleSidecar>> _discoverSidecarSubtitles(
|
|
String videoPath, {
|
|
required MediaItem metadata,
|
|
MediaSourceInfo? mediaInfo,
|
|
}) async {
|
|
final subtitles = <PlaybackSubtitleSidecar>[];
|
|
final dirs = videoPath.startsWith('content://')
|
|
? await _safSidecarSubtitleDirs(metadata)
|
|
: await _fileSidecarSubtitleDirs(videoPath);
|
|
|
|
for (final subsDir in dirs) {
|
|
if (!await subsDir.exists()) continue;
|
|
final entities = await subsDir.list().toList();
|
|
for (final entity in entities) {
|
|
if (entity is! File) continue;
|
|
final fileName = p.basenameWithoutExtension(entity.path);
|
|
final trackId = int.tryParse(fileName);
|
|
|
|
final cachedTrack = trackId != null
|
|
? mediaInfo?.subtitleTracks.where((t) => t.id == trackId).firstOrNull
|
|
: null;
|
|
|
|
subtitles.add(
|
|
PlaybackSubtitleSidecar(
|
|
sourceStreamId: trackId,
|
|
track: SubtitleTrack.uri(
|
|
Uri.file(entity.path).toString(),
|
|
title: cachedTrack?.displayTitle ?? cachedTrack?.language ?? t.videoControls.subtitleFile(name: fileName),
|
|
language: cachedTrack?.languageCode,
|
|
codec: cachedTrack?.codec,
|
|
isDefault: cachedTrack?.selected ?? false,
|
|
isForced: cachedTrack?.forced ?? false,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
return subtitles;
|
|
}
|
|
|
|
Future<List<Directory>> _fileSidecarSubtitleDirs(String videoPath) async {
|
|
final subsPath = videoPath.replaceAll(RegExp(r'\.[^.]+$'), '_subs');
|
|
final primary = Directory(subsPath);
|
|
if (await primary.exists()) return [primary];
|
|
return [Directory(p.join(File(videoPath).parent.path, 'subtitles'))];
|
|
}
|
|
|
|
Future<List<Directory>> _safSidecarSubtitleDirs(MediaItem metadata) async {
|
|
final serverId = metadata.serverId;
|
|
if (serverId == null) return const [];
|
|
|
|
final storage = DownloadStorageService.instance;
|
|
final dirs = <Directory>[];
|
|
if (metadata.isEpisode && metadata.title != null) {
|
|
dirs.add(await storage.getEpisodeSubtitlesDirectory(metadata));
|
|
} else if (metadata.isMovie && metadata.title != null) {
|
|
dirs.add(await storage.getMovieSubtitlesDirectory(metadata));
|
|
}
|
|
dirs.add(await storage.getSubtitlesDirectory(ServerId(serverId), metadata.id));
|
|
return dirs;
|
|
}
|
|
}
|