Files
plezy/lib/utils/track_label_builder.dart
T
edde746 369c6279d6 fix(i18n): translate the player, downloads and server-setup text left in English
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
2026-08-10 15:32:43 +02:00

223 lines
7.4 KiB
Dart

import '../i18n/strings.g.dart';
import 'codec_utils.dart';
import 'language_codes.dart';
/// Two-part track label: [primary] carries the human-readable name (language
/// first when known), [secondary] the de-emphasized technical detail.
///
/// Sheet rows render the parts on two lines; single-line contexts (track
/// cycling toasts) use [joined].
class TrackLabel {
final String primary;
/// Technical detail line. Null when there is none — never an empty string.
final String? secondary;
const TrackLabel(this.primary, [this.secondary]);
String get joined => secondary == null ? primary : '$primary · $secondary';
@override
bool operator ==(Object other) => other is TrackLabel && other.primary == primary && other.secondary == secondary;
@override
int get hashCode => Object.hash(primary, secondary);
@override
String toString() => 'TrackLabel($primary, $secondary)';
}
/// Resolves the display name for a track's language.
///
/// A mappable ISO code wins ([languageCode] is the reliable field on server
/// streams, [language] carries the container code on mpv tracks). When neither
/// maps, a server-provided display name ("Filipino") beats an unmappable code,
/// and bare codes keep the legacy uppercase rendering ("und" → "UND").
String? resolveTrackLanguageDisplay({String? language, String? languageCode}) {
final code = cleanTrackMetadataValue(languageCode);
final lang = cleanTrackMetadataValue(language);
final display = _displayNameIfMapped(code) ?? _displayNameIfMapped(lang);
if (display != null) return display;
final fallback = lang ?? code;
if (fallback == null) return null;
return _looksLikeLanguageCode(fallback) ? fallback.toUpperCase() : fallback;
}
String? _displayNameIfMapped(String? value) {
if (value == null) return null;
final base = value.split(RegExp('[-_]')).first;
if (LanguageCodes.getLanguageName(base) == null) return null;
return LanguageCodes.getDisplayName(value.replaceAll('_', '-'));
}
final _languageCodePattern = RegExp(r'^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})?$');
bool _looksLikeLanguageCode(String value) => _languageCodePattern.hasMatch(value);
String? cleanTrackMetadataValue(String? value) {
if (value == null) return null;
var cleaned = value.trim();
if (cleaned.isEmpty) return null;
final prefixed = RegExp(r'^(?:title|lang|language)\s*=\s*(.*)$', caseSensitive: false).firstMatch(cleaned);
if (prefixed != null) {
cleaned = prefixed.group(1)?.trim() ?? '';
}
if ((cleaned.startsWith('"') && cleaned.endsWith('"')) || (cleaned.startsWith("'") && cleaned.endsWith("'"))) {
cleaned = cleaned.substring(1, cleaned.length - 1).trim();
}
return cleaned.isEmpty ? null : cleaned;
}
String? cleanSubtitleTitle(String? title, {String? codec}) {
var cleaned = cleanTrackMetadataValue(title);
if (cleaned == null) return null;
final codecAliases = _subtitleCodecAliases(codec);
if (codecAliases.isEmpty) return cleaned;
final parts = cleaned.split(RegExp(r'\s+-\s+'));
while (parts.isNotEmpty && codecAliases.contains(_metadataToken(parts.last))) {
parts.removeLast();
}
cleaned = parts.join(' - ').trim();
return cleaned.isEmpty ? null : cleaned;
}
Set<String> _subtitleCodecAliases(String? codec) {
final aliases = <String>{
'SUBRIP',
'SRT',
'WEBVTT',
'VTT',
'ASS',
'SSA',
'PGS',
'PGSSUB',
'HDMV_PGS_SUBTITLE',
'DVD',
'DVDSUB',
'DVD_SUBTITLE',
'DVB_SUB',
'DVB_SUBTITLE',
};
if (codec != null && codec.isNotEmpty) {
aliases.add(_metadataToken(codec));
aliases.add(_metadataToken(CodecUtils.formatSubtitleCodec(codec)));
aliases.add(_metadataToken(CodecUtils.getSubtitleExtension(codec)));
}
return aliases;
}
String _metadataToken(String value) => value.trim().toUpperCase().replaceAll(RegExp(r'[^A-Z0-9]+'), '_');
/// Whether a track title declares the stream forced ("FR Forced [ASS]",
/// "French (Forced)"). Whole-token match, so "unforced" does not qualify.
/// Plex itself treats such streams as forced even when the API flag is false.
bool titleSaysForced(String? value) => _metadataToken(value ?? '').split('_').contains('FORCED');
class TrackLabelBuilder {
TrackLabelBuilder._();
static TrackLabel audioLabel({
String? title,
String? language,
String? languageCode,
String? codec,
int? channels,
String? displayTitle,
required int index,
}) {
final tech = <String>[];
if (codec != null && codec.isNotEmpty) tech.add(CodecUtils.formatAudioCodec(codec));
final channelsLabel = CodecUtils.formatAudioChannels(channels);
if (channelsLabel != null) tech.add(channelsLabel);
return _compose(
languageDisplay: resolveTrackLanguageDisplay(language: language, languageCode: languageCode),
title: cleanTrackMetadataValue(title),
displayTitle: cleanTrackMetadataValue(displayTitle),
rawLanguageValues: [language, languageCode],
techParts: tech,
fallbackLabel: (n) => t.audioTracks.track(n: n),
index: index,
);
}
static TrackLabel subtitleLabel({
String? title,
String? language,
String? languageCode,
String? codec,
bool forced = false,
String? displayTitle,
required int index,
}) {
final cleanedTitle = cleanSubtitleTitle(title, codec: codec);
return _compose(
languageDisplay: resolveTrackLanguageDisplay(language: language, languageCode: languageCode),
title: cleanedTitle,
displayTitle: cleanSubtitleTitle(displayTitle, codec: codec),
rawLanguageValues: [language, languageCode],
techParts: [if (codec != null && codec.isNotEmpty) CodecUtils.formatSubtitleCodec(codec)],
fallbackLabel: (n) => t.videoControls.subtitleTrack(n: n),
index: index,
forced: forced || titleSaysForced(cleanedTitle),
);
}
/// Primary ladder: language → title → displayTitle → localized fallback. The
/// title joins the secondary line only when the language took the primary
/// slot and the title says more than the language/forced flag already do.
static TrackLabel _compose({
required String? languageDisplay,
required String? title,
required String? displayTitle,
required List<String?> rawLanguageValues,
required List<String> techParts,
required String Function(int number) fallbackLabel,
required int index,
bool forced = false,
}) {
String primary;
String? secondaryTitle;
if (languageDisplay != null) {
primary = languageDisplay;
if (title != null &&
_metadataToken(title) != 'FORCED' &&
!_restatesLanguage(title, languageDisplay, rawLanguageValues)) {
secondaryTitle = title;
}
} else if (title != null) {
primary = title;
} else if (displayTitle != null) {
primary = displayTitle;
} else {
primary = fallbackLabel(index + 1);
}
if (forced && !titleSaysForced(primary)) {
primary = t.videoControls.forcedTrack(label: primary);
}
final secondaryParts = [?secondaryTitle, ...techParts];
return TrackLabel(primary, secondaryParts.isEmpty ? null : secondaryParts.join(' · '));
}
static bool _restatesLanguage(String title, String languageDisplay, List<String?> rawLanguageValues) {
final normalized = title.trim().toLowerCase();
if (normalized == languageDisplay.trim().toLowerCase()) return true;
for (final raw in rawLanguageValues) {
final cleaned = cleanTrackMetadataValue(raw);
if (cleaned != null && normalized == cleaned.toLowerCase()) return true;
}
return false;
}
}