From 0ef73464b821c415a3ebe62a42dfc73d4d714a89 Mon Sep 17 00:00:00 2001 From: Jo-Be-Co Date: Thu, 9 Apr 2026 02:33:05 +0200 Subject: [PATCH] Extend and tags to allow different outputs like ISO-codes or names in different languages --- Source/DataLayer/EfClasses/Book.cs | 2 +- Source/DataLayer/MockLibraryBook.cs | 4 +- Source/FileLiberator/UtilityExtensions.cs | 4 +- .../NamingTemplate/CommonFormatters.cs | 40 ++++-- .../ConditionalTagCollection[TClass].cs | 2 +- .../PropertyTagCollection[TClass].cs | 2 +- .../Controls/ThemePreviewControl.axaml.cs | 2 +- .../Templates/CultureInfoDto.cs | 86 +++++++++++++ .../Templates/LibraryBookDto.cs | 4 +- .../Templates/RegionInfoDto.cs | 96 ++++++++++++++ .../Templates/TemplateEditor[T].cs | 4 +- .../Templates/TemplateTags.cs | 2 + .../Templates/Templates.cs | 8 +- .../TemplatesTests.cs | 119 +++++++++++++++++- docs/features/naming-templates.md | 6 +- 15 files changed, 348 insertions(+), 33 deletions(-) create mode 100644 Source/LibationFileManager/Templates/CultureInfoDto.cs create mode 100644 Source/LibationFileManager/Templates/RegionInfoDto.cs diff --git a/Source/DataLayer/EfClasses/Book.cs b/Source/DataLayer/EfClasses/Book.cs index 57566f3c..52801dbd 100644 --- a/Source/DataLayer/EfClasses/Book.cs +++ b/Source/DataLayer/EfClasses/Book.cs @@ -256,7 +256,7 @@ public class Book IsAbridged |= isAbridged; IsSpatial = isSpatial ?? IsSpatial; DatePublished = datePublished ?? DatePublished; - Language = language?.FirstCharToUpper() ?? Language; + Language = language?.Trim().FirstCharToUpper() ?? Language; } public override string ToString() => $"[{AudibleProductId}] {TitleWithSubtitle}"; diff --git a/Source/DataLayer/MockLibraryBook.cs b/Source/DataLayer/MockLibraryBook.cs index 26b4cfe7..e37f91b5 100644 --- a/Source/DataLayer/MockLibraryBook.cs +++ b/Source/DataLayer/MockLibraryBook.cs @@ -73,7 +73,7 @@ public class MockLibraryBook : LibraryBook public static MockLibraryBook CreateBook( string account = "someone@email.co", - bool absetFromLastScan = false, + bool absentFromLastScan = false, DateTime? dateAdded = null, DateTime? datePublished = null, DateTime? includedUntil = null, @@ -120,7 +120,7 @@ public class MockLibraryBook : LibraryBook includedUntil, isAudiblePlus) { - AbsentFromLastScan = absetFromLastScan + AbsentFromLastScan = absentFromLastScan }; } diff --git a/Source/FileLiberator/UtilityExtensions.cs b/Source/FileLiberator/UtilityExtensions.cs index 5c534a36..29f5f050 100644 --- a/Source/FileLiberator/UtilityExtensions.cs +++ b/Source/FileLiberator/UtilityExtensions.cs @@ -59,7 +59,7 @@ public static class UtilityExtensions Title = libraryBook.Book.Title, Subtitle = libraryBook.Book.Subtitle, TitleWithSubtitle = libraryBook.Book.TitleWithSubtitle, - Locale = libraryBook.Book.Locale, + Locale = new RegionInfoDto(libraryBook.Book.Locale), YearPublished = libraryBook.Book.DatePublished?.Year, DatePublished = libraryBook.Book.DatePublished, @@ -72,7 +72,7 @@ public static class UtilityExtensions IsPodcast = libraryBook.Book.IsEpisodeChild() || libraryBook.Book.IsEpisodeParent(), LengthInMinutes = TimeSpan.FromMinutes(libraryBook.Book.LengthInMinutes), - Language = libraryBook.Book.Language?.Trim(), + Language = libraryBook.Book.Language is null ? null : new CultureInfoDto(libraryBook.Book.Language), Codec = libraryBook.Book.UserDefinedItem.LastDownloadedFormat?.CodecString, BitRate = libraryBook.Book.UserDefinedItem.LastDownloadedFormat?.BitRate, SampleRate = libraryBook.Book.UserDefinedItem.LastDownloadedFormat?.SampleRate, diff --git a/Source/FileManager/NamingTemplate/CommonFormatters.cs b/Source/FileManager/NamingTemplate/CommonFormatters.cs index 5fea2f7b..ef4d8efc 100644 --- a/Source/FileManager/NamingTemplate/CommonFormatters.cs +++ b/Source/FileManager/NamingTemplate/CommonFormatters.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; +using System.Threading; namespace FileManager.NamingTemplate; @@ -32,6 +33,9 @@ public static partial class CommonFormatters public static string StringFormatter(ITemplateTag _, string? value, string? formatString, CultureInfo? culture) => _StringFormatter(value, formatString, culture); + public static string _StringFormatter(string? value, string? formatString, IFormatProvider? provider) + => _StringFormatter(value, formatString, GetCultureInfo(provider)); + private static string _StringFormatter(string? value, string? formatString, CultureInfo? culture) { if (string.IsNullOrEmpty(value)) return string.Empty; @@ -61,24 +65,36 @@ public static partial class CommonFormatters if (string.IsNullOrWhiteSpace(templateString)) return ""; // is this function is called from toString implementation of the IFormattable interface, we only get a IFormatProvider - var culture = provider as CultureInfo ?? provider?.GetFormat(typeof(CultureInfo)) as CultureInfo; - return CollapseSpacesAndTrimRegex().Replace(TagFormatRegex().Replace(templateString, GetValueForMatchingTag), ""); + var culture = GetCultureInfo(provider); + var oldUiCulture = Thread.CurrentThread.CurrentUICulture; + var result = CollapseSpacesAndTrimRegex().Replace(TagFormatRegex().Replace(templateString, GetValueForMatchingTag), ""); + Thread.CurrentThread.CurrentUICulture = oldUiCulture; + return result; string GetValueForMatchingTag(Match m) { var tag = m.Groups["tag"].Value; if (!replacements.TryGetValue(tag, out var getter)) return m.Value; + var lang = m.Groups["lang"].ValueOrNull(); + var cultureToUse = lang is null ? culture : CultureInfo.GetCultureInfo(lang); + Thread.CurrentThread.CurrentUICulture = cultureToUse ?? oldUiCulture; + var value = getter(toFormat); var format = m.Groups["format"].ValueOrNull(); return value switch { - IFormattable formattable => formattable.ToString(format, provider), - _ => _StringFormatter(value?.ToString(), format, culture), + IFormattable formattable => formattable.ToString(format, cultureToUse), + _ => _StringFormatter(value?.ToString(), format, cultureToUse), }; } } + private static CultureInfo? GetCultureInfo(IFormatProvider? provider) + { + return provider as CultureInfo ?? provider?.GetFormat(typeof(CultureInfo)) as CultureInfo; + } + // Matches runs of spaces followed by a space as well as runs of spaces at the beginning or the end of a string (does NOT touch tabs/newlines). [GeneratedRegex(@"^ +| +(?=$| )")] private static partial Regex CollapseSpacesAndTrimRegex(); @@ -87,8 +103,8 @@ public static partial class CommonFormatters // The tagname may be followed by an optional format specifier separated by a colon. // All other parts of the template string are left untouched as well as the braces where the tagname is unknown. // TemplateStringFormatter will use a dictionary to lookup the tagname and the corresponding value getter. - [GeneratedRegex("""\{(?[A-Z]+|#)(?::(?(?:\\.|'(?:[^']|'')*'|"(?:[^"]|"")*"|.)*?))?\}""", RegexOptions.IgnoreCase)] - private static partial Regex TagFormatRegex(); + [GeneratedRegex("""\{(?[A-Z0-9]+|#)(?:@(?[a-z-]+))?(?::(?(?:\\.|'(?:[^']|'')*'|"(?:[^"]|"")*"|.)*?))?\}""", RegexOptions.IgnoreCase)] + public static partial Regex TagFormatRegex(); public static string FormattableFormatter(ITemplateTag _, IFormattable? value, string? formatString, CultureInfo? culture) => value?.ToString(formatString, culture) ?? ""; @@ -100,12 +116,10 @@ public static partial class CommonFormatters { culture ??= CultureInfo.CurrentCulture; if (!int.TryParse(formatString, out var numDigits) || numDigits <= 0) return value.ToString(formatString, culture); - //Zero-pad the integer part - var strValue = value.ToString(culture); - var decIndex = culture.CompareInfo.IndexOf(strValue, culture.NumberFormat.NumberDecimalSeparator); - var zeroPad = decIndex == -1 ? int.Max(0, numDigits - strValue.Length) : int.Max(0, numDigits - decIndex); - return new string('0', zeroPad) + strValue; + //Zero-pad the integer part + formatString = new string('0', numDigits) + ".################"; + return value.ToString(formatString, culture); } public static string MinutesFormatter(ITemplateTag templateTag, TimeSpan value, string? formatString, CultureInfo? culture) @@ -163,7 +177,7 @@ public static partial class CommonFormatters [GeneratedRegex(""" (?x) # option x: ignore all unescaped whitespace in pattern and allow comments starting with # (?<=\G(?: # We lookbehind up to the start or the end of the last match for a number format. - \\. # - '\' escapes allways the next character. Especially further '\' and the closing ']' + \\. # - '\' escapes always the next character. Especially further '\' and the closing ']' | '(?:[^']|'')*' # - allow 'string' to be included in the format, with '' being an escaped ' character | "(?:[^"]|"")*" # - allow "string" to be included in the format, with "" being an escaped " character | . # - match any character. This will not catch the number format at first. Because ... @@ -172,7 +186,7 @@ public static partial class CommonFormatters (?:\#[\#,.]*)? # - For grouping a number format may start with `#` and grouping hints `,` or even a decimal point `.`. D # - At least one unescaped, unquoted uppercase D must be included in the format to indicate that this is a total days format. (?:(?: # - Before further D's, there may be any combination of escaped characters and quoted strings. - \\. # - '\' escapes allways the next character. Especially further '\' and the closing ']' + \\. # - '\' escapes always the next character. Especially further '\' and the closing ']' | '(?:[^']|'')*' # - allow 'string' to be included in the format, with '' being an escaped ' character | "(?:[^"]|"")*" # - allow "string" to be included in the format, with "" being an escaped " character )* [\#,.%‰D]+ # After escaped characters and quoted strings, there needs to be at least one more real number format character (which may be D as well). diff --git a/Source/FileManager/NamingTemplate/ConditionalTagCollection[TClass].cs b/Source/FileManager/NamingTemplate/ConditionalTagCollection[TClass].cs index 3e3bdb5f..8ed37a69 100644 --- a/Source/FileManager/NamingTemplate/ConditionalTagCollection[TClass].cs +++ b/Source/FileManager/NamingTemplate/ConditionalTagCollection[TClass].cs @@ -116,7 +116,7 @@ public partial class ConditionalTagCollection(bool caseSensitive = true) (? end with a whitepace. Otherwise "" would be matchable. (?:\s*\[\s* # optional check details enclosed in '[' and ']'. Check shall start with an operator. So match whitespace first (? # - capture inner part as - (?:\\. # - '\' escapes allways the next character. Especially further '\' and the closing ']' + (?:\\. # - '\' escapes always the next character. Especially further '\' and the closing ']' |[^\\\]])* ) # - match any character except '\' and ']'. Check may end in whitespace! \])? # - closing the check part )? # end of optional property and check part diff --git a/Source/FileManager/NamingTemplate/PropertyTagCollection[TClass].cs b/Source/FileManager/NamingTemplate/PropertyTagCollection[TClass].cs index 2d43957c..81edd5ba 100644 --- a/Source/FileManager/NamingTemplate/PropertyTagCollection[TClass].cs +++ b/Source/FileManager/NamingTemplate/PropertyTagCollection[TClass].cs @@ -194,7 +194,7 @@ public class PropertyTagCollection : TagCollection {TagNameForRegex()} # next the tagname needs to be matched with space being made optional. Also escape all '#' (?:\s* # optional whitespace \[ (? # optional format details enclosed in '[' and ']'. Capture inner part as . - (?:\\. # - '\' escapes allways the next character. Especially further '\' and the closing ']' + (?:\\. # - '\' escapes always the next character. Especially further '\' and the closing ']' |'(?:[^']|'')*' # - allow 'string' to be included in the format, with '' being an escaped ' character |"(?:[^"]|"")*" # - allow "string" to be included in the format, with "" being an escaped " character |[^\\\]])* ) # - match any character except '\' and ']'. Format may end in whitespace! diff --git a/Source/LibationAvalonia/Controls/ThemePreviewControl.axaml.cs b/Source/LibationAvalonia/Controls/ThemePreviewControl.axaml.cs index 37107296..7e70931d 100644 --- a/Source/LibationAvalonia/Controls/ThemePreviewControl.axaml.cs +++ b/Source/LibationAvalonia/Controls/ThemePreviewControl.axaml.cs @@ -53,7 +53,7 @@ public partial class ThemePreviewControl : UserControl { yield return MockLibraryBook.CreateBook(title: "Some Book 1", subtitle: "The Theming", dateAdded: System.DateTime.Now.AddDays(4)).WithBookStatus(LiberatedStatus.Liberated); yield return MockLibraryBook.CreateBook(title: "Some Book 2", dateAdded: System.DateTime.Now.AddDays(3)).WithBookStatus(LiberatedStatus.PartialDownload); - yield return MockLibraryBook.CreateBook(title: "Some Book 3", dateAdded: System.DateTime.Now.AddDays(2), absetFromLastScan: true).WithPdfStatus(LiberatedStatus.NotLiberated); + yield return MockLibraryBook.CreateBook(title: "Some Book 3", dateAdded: System.DateTime.Now.AddDays(2), absentFromLastScan: true).WithPdfStatus(LiberatedStatus.NotLiberated); yield return MockLibraryBook.CreateBook(title: "Some Book 4", dateAdded: System.DateTime.Now.AddDays(1)).WithBookStatus(LiberatedStatus.Error); yield return MockLibraryBook.CreateBook(title: "Some Series", subtitle: "", contentType: ContentType.Parent).AddSeries("Some Series", 0); yield return MockLibraryBook.CreateBook(title: "Some Episode", subtitle: "Episode 1", contentType: ContentType.Episode).AddSeries("Some Series", 1); diff --git a/Source/LibationFileManager/Templates/CultureInfoDto.cs b/Source/LibationFileManager/Templates/CultureInfoDto.cs new file mode 100644 index 00000000..0b06b9cd --- /dev/null +++ b/Source/LibationFileManager/Templates/CultureInfoDto.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using FileManager.NamingTemplate; + +namespace LibationFileManager.Templates; + +public record CultureInfoDto : IFormattable +{ + private CultureInfo? Value { get; } + private string DefaultFormat { get; } + public string Original { get; } + + public static CultureInfoDto OfCurrentUi() + { + return new CultureInfoDto(CultureInfo.DefaultThreadCurrentUICulture ?? CultureInfo.CurrentUICulture, CultureInfo.CurrentUICulture.Name, "{N}"); + } + + public static CultureInfoDto OfCurrentOs() + { + return new CultureInfoDto(CultureInfo.DefaultThreadCurrentCulture ?? CultureInfo.CurrentCulture, CultureInfo.CurrentCulture.Name, "{N}"); + } + + public CultureInfoDto(string hint) : this(hint, "{O}") + { + } + + public CultureInfoDto(string hint, string defaultFormat) : this(GetCulture(hint), hint, defaultFormat) + { + } + + public CultureInfoDto(CultureInfo value, string hint, string defaultFormat) + { + Original = hint; + DefaultFormat = defaultFormat; + Value = value; + } + + private static CultureInfo? GetCulture(string input) + { + return + GetCulture(input, CultureTypes.NeutralCultures) ?? + GetCulture(input, CultureTypes.SpecificCultures); + } + + private static CultureInfo? GetCulture(string input, CultureTypes types) + { + var cultures = CultureInfo.GetCultures(types); + return Match(cultures, input, c => c.Name) ?? + Match(cultures, input, c => c.TwoLetterISOLanguageName) ?? + Match(cultures, input, c => c.ThreeLetterISOLanguageName) ?? + Match(cultures, input, c => c.EnglishName); + } + + private static CultureInfo? Match(IEnumerable cultures, string input, Func selector, StringComparison cmp = StringComparison.OrdinalIgnoreCase) + { + return cultures.FirstOrDefault(c => string.Equals(selector(c), input, cmp)); + } + + private static readonly Dictionary> FormatReplacements = new(StringComparer.OrdinalIgnoreCase) + { + { "ID", dto => dto.Value?.Name }, + { "I", dto => dto.Value?.TwoLetterISOLanguageName }, + { "I2", dto => dto.Value?.TwoLetterISOLanguageName }, + { "I3", dto => dto.Value?.ThreeLetterISOLanguageName }, + { "W", dto => dto.Value?.ThreeLetterWindowsLanguageName }, + { "E", dto => dto.Value?.EnglishName }, + { "N", dto => dto.Value?.NativeName }, + { "O", dto => dto.Original }, + { "D", dto => dto.Value?.DisplayName }, // localized + }; + + public override string ToString() => ToString(DefaultFormat, CultureInfo.CurrentCulture); + + public string ToString(string? format, IFormatProvider? provider) + { + if (string.IsNullOrWhiteSpace(format)) format = DefaultFormat; + return format switch + { + _ when CommonFormatters.TagFormatRegex().IsMatch(format) => CommonFormatters.TemplateStringFormatter(this, format, provider, FormatReplacements), + _ when format == DefaultFormat => CommonFormatters._StringFormatter(Original, format, provider), + _ => CommonFormatters._StringFormatter(CommonFormatters.TemplateStringFormatter(this, DefaultFormat, provider, FormatReplacements), format, provider) + }; + } +} \ No newline at end of file diff --git a/Source/LibationFileManager/Templates/LibraryBookDto.cs b/Source/LibationFileManager/Templates/LibraryBookDto.cs index 29b98b01..7645089c 100644 --- a/Source/LibationFileManager/Templates/LibraryBookDto.cs +++ b/Source/LibationFileManager/Templates/LibraryBookDto.cs @@ -10,7 +10,7 @@ public class BookDto public string? Title { get; set; } public string? Subtitle { get; set; } public string? TitleWithSubtitle { get; set; } - public string? Locale { get; set; } + public RegionInfoDto? Locale { get; set; } public int? YearPublished { get; set; } public IEnumerable? Authors { get; set; } @@ -34,7 +34,7 @@ public class BookDto public string? Codec { get; set; } public DateTime FileDate { get; set; } = DateTime.Now; public DateTime? DatePublished { get; set; } - public string? Language { get; set; } + public CultureInfoDto? Language { get; set; } public string? LibationVersion { get; set; } public string? FileVersion { get; set; } } diff --git a/Source/LibationFileManager/Templates/RegionInfoDto.cs b/Source/LibationFileManager/Templates/RegionInfoDto.cs new file mode 100644 index 00000000..a2f8699e --- /dev/null +++ b/Source/LibationFileManager/Templates/RegionInfoDto.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; +using FileManager.NamingTemplate; + +namespace LibationFileManager.Templates; + +public partial record RegionInfoDto : IFormattable +{ + private RegionInfo? Value { get; } + private CultureInfo? Culture { get; } + private string DefaultFormat { get; } + public string Original { get; } + + public RegionInfoDto(string hint) : this(hint, "{O}") + { + } + + public RegionInfoDto(string hint, string defaultFormat) : this(GetRegion(hint), hint, defaultFormat) + { + } + + public RegionInfoDto(RegionInfo value, string hint, string defaultFormat) + { + Original = hint; + DefaultFormat = defaultFormat; + Value = value; + Culture = GetCultureInfo(value); + } + + private static RegionInfo? GetRegion(string input) + { + if (input.StartsWith("pre-amazon - ", StringComparison.OrdinalIgnoreCase)) input = input.Substring(13); + if (string.Equals(input, "uk", StringComparison.OrdinalIgnoreCase)) return new RegionInfo("GB"); + try + { + return new RegionInfo(input.ToUpperInvariant()); + } + catch + { + return CultureInfo.GetCultures(CultureTypes.SpecificCultures) + .Select(c => new RegionInfo(c.Name)) + .FirstOrDefault(r => + string.Equals(r.EnglishName, input, StringComparison.OrdinalIgnoreCase)); + } + } + + private string? GetLocalizedRegionName() + { + return Culture is null ? null : GetCountryName(Culture.DisplayName) ?? GetCountryName(Culture.EnglishName); + } + + private static string? GetCountryName(string localized) + { + return ExtractRegionName().Match(localized).Groups["displayName"].ValueOrNull(); + } + + [GeneratedRegex(@"\((?.+)\)")] + private static partial Regex ExtractRegionName(); + + private static CultureInfo GetCultureInfo(RegionInfo region) + { + // find culture for region + return CultureInfo.GetCultures(CultureTypes.SpecificCultures) + .First(c => Equals(new RegionInfo(c.Name), region)); + } + + + private static readonly Dictionary> FormatReplacements = new(StringComparer.OrdinalIgnoreCase) + { + { "ID", dto => dto.Value?.Name }, + { "I", dto => dto.Value?.TwoLetterISORegionName }, + { "I2", dto => dto.Value?.TwoLetterISORegionName }, + { "I3", dto => dto.Value?.ThreeLetterISORegionName }, + { "W", dto => dto.Value?.ThreeLetterWindowsRegionName }, + { "E", dto => dto.Value?.EnglishName }, + { "N", dto => dto.Value?.NativeName }, + { "O", dto => dto.Original }, + { "D", dto => dto.GetLocalizedRegionName() }, // localized + }; + + public override string ToString() => ToString(DefaultFormat, CultureInfo.CurrentCulture); + + public string ToString(string? format, IFormatProvider? provider) + { + if (string.IsNullOrWhiteSpace(format)) format = DefaultFormat; + return format switch + { + _ when CommonFormatters.TagFormatRegex().IsMatch(format) => CommonFormatters.TemplateStringFormatter(this, format, provider, FormatReplacements), + _ when format == DefaultFormat => CommonFormatters._StringFormatter(Original, format, provider), + _ => CommonFormatters._StringFormatter(CommonFormatters.TemplateStringFormatter(this, DefaultFormat, provider, FormatReplacements), format, provider) + }; + } +} \ No newline at end of file diff --git a/Source/LibationFileManager/Templates/TemplateEditor[T].cs b/Source/LibationFileManager/Templates/TemplateEditor[T].cs index bb1b435f..9205b36c 100644 --- a/Source/LibationFileManager/Templates/TemplateEditor[T].cs +++ b/Source/LibationFileManager/Templates/TemplateEditor[T].cs @@ -63,7 +63,7 @@ public class TemplateEditor : ITemplateEditor where T : Templates, ITemplate, Title = "A Study in Scarlet", TitleWithSubtitle = "A Study in Scarlet: A Sherlock Holmes Novel", Subtitle = "A Sherlock Holmes Novel", - Locale = "us", + Locale = new RegionInfoDto("us"), YearPublished = 2017, Authors = [new("Arthur Conan Doyle", "B000AQ43GQ"), new("Stephen Fry - introductions", "B000APAGVS")], Narrators = [new("Stephen Fry", null)], @@ -74,7 +74,7 @@ public class TemplateEditor : ITemplateEditor where T : Templates, ITemplate, BitRate = 128, SampleRate = 44100, Channels = 2, - Language = "English" + Language = new CultureInfoDto("English"), }; private static readonly MultiConvertFileProperties DefaultMultipartProperties diff --git a/Source/LibationFileManager/Templates/TemplateTags.cs b/Source/LibationFileManager/Templates/TemplateTags.cs index 5c6cdf68..85a8cdd1 100644 --- a/Source/LibationFileManager/Templates/TemplateTags.cs +++ b/Source/LibationFileManager/Templates/TemplateTags.cs @@ -49,6 +49,8 @@ public sealed class TemplateTags : ITemplateTag public static TemplateTags YearPublished { get; } = new("year", "Year published"); public static TemplateTags Language { get; } = new("language", "Book's language"); public static TemplateTags LanguageShort { get; } = new("language short", "Book's language abbreviated. Eg: ENG"); + public static TemplateTags UI { get; } = new("ui", "UI language"); + public static TemplateTags OS { get; } = new("os", "OS language"); public static TemplateTags FileDate { get; } = new("file date", "File date/time. e.g. yyyy-MM-dd HH-mm", $"", ""); public static TemplateTags DatePublished { get; } = new("pub date", "Publication date. e.g. yyyy-MM-dd", $"", ""); diff --git a/Source/LibationFileManager/Templates/Templates.cs b/Source/LibationFileManager/Templates/Templates.cs index 186dcfb4..3dfb9f69 100644 --- a/Source/LibationFileManager/Templates/Templates.cs +++ b/Source/LibationFileManager/Templates/Templates.cs @@ -278,12 +278,14 @@ public abstract class Templates { TemplateTags.Series, lb => lb.Series, SeriesListFormat.Formatter, SeriesListFormat.Finalizer }, { TemplateTags.FirstSeries, lb => lb.FirstSeries, CommonFormatters.FormattableFormatter }, { TemplateTags.SeriesNumber, lb => lb.FirstSeries?.Order, CommonFormatters.FormattableFormatter }, - { TemplateTags.Language, lb => lb.Language }, + { TemplateTags.Language, lb => lb.Language, CommonFormatters.FormattableFormatter }, //Don't allow formatting of LanguageShort - { TemplateTags.LanguageShort, lb => lb.Language, CommonFormatters.LanguageShortFormatter }, + { TemplateTags.LanguageShort, lb => lb.Language?.Original, CommonFormatters.LanguageShortFormatter }, + { TemplateTags.UI, _ => CultureInfoDto.OfCurrentUi(), CommonFormatters.FormattableFormatter }, + { TemplateTags.OS, _ => CultureInfoDto.OfCurrentOs(), CommonFormatters.FormattableFormatter }, { TemplateTags.Account, lb => lb.Account }, { TemplateTags.AccountNickname, lb => lb.AccountNickname }, - { TemplateTags.Locale, lb => lb.Locale }, + { TemplateTags.Locale, lb => lb.Locale, CommonFormatters.FormattableFormatter }, { TemplateTags.YearPublished, lb => lb.YearPublished }, { TemplateTags.DatePublished, lb => lb.DatePublished }, { TemplateTags.DateAdded, lb => lb.DateAdded }, diff --git a/Source/_Tests/LibationFileManager.Tests/TemplatesTests.cs b/Source/_Tests/LibationFileManager.Tests/TemplatesTests.cs index ee97d4bb..449ebe84 100644 --- a/Source/_Tests/LibationFileManager.Tests/TemplatesTests.cs +++ b/Source/_Tests/LibationFileManager.Tests/TemplatesTests.cs @@ -9,6 +9,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Threading; using static TemplatesTests.Shared; [assembly: Parallelize] @@ -43,7 +44,7 @@ namespace TemplatesTests FileDate = new DateTime(2023, 1, 28, 0, 0, 0), AudibleProductId = "asin", Title = "A Study in Scarlet: A Sherlock Holmes Novel", - Locale = "us", + Locale = new RegionInfoDto("us"), YearPublished = null, // explicitly null Authors = [new("Arthur Conan Doyle", "B000AQ43GQ"), new("Stephen Fry - introductions", "B000APAGVS")], Narrators = [], // explicitly empty list @@ -51,7 +52,7 @@ namespace TemplatesTests BitRate = 128, SampleRate = 44100, Channels = 2, - Language = "English", + Language = new CultureInfoDto("English"), Subtitle = "An Audible Original Drama", TitleWithSubtitle = "A Study in Scarlet: An Audible Original Drama", Codec = @"AAC[LC]\MP3", // special chars added @@ -761,6 +762,120 @@ namespace TemplatesTests .GetName(bookDto, new MultiConvertFileProperties { OutputFileName = string.Empty }) .Should().Be(expected); } + + [TestMethod] + [DataRow("English", "", "English")] + [DataRow("English", "", "ENGL")] + [DataRow("English", "", "ENG")] + [DataRow("English", "", "ENG")] + [DataRow("English", "", "N:en, 2:en, 3:eng, W:ENU, D:inglés, E:English, N:English, O:English")] + [DataRow("en", "", "N:en, 2:en, 3:eng, W:ENU, D:inglés, E:English, N:English, O:en")] + [DataRow("fr", "", "N:fr, 2:fr, 3:fra, W:FRA, D:francés, E:French, N:français, O:fr")] + [DataRow("fr-ca", "", + "N:fr-CA, 2:fr, 3:fra, W:FRC, D:francés (Canadá), E:French (Canada), N:français (Canada), O:fr-ca")] + [DataRow("Any", "", + "N:es-ES, 2:es, 3:spa, W:ESN, D:español (España), E:Spanish (Spain), N:español (España), O:es-ES")] + [DataRow("Any", "", + "N:sv-SE, 2:sv, 3:swe, W:SVE, D:sueco (Suecia), E:Swedish (Sweden), N:svenska (Sverige), O:sv-SE")] + // different localizations + [DataRow("fr", "", "D:Französisch, E:French, N:français, O:fr")] + [DataRow("fr", "", "D:francuski")] + [DataRow("fr", "", "D:francese")] + public void Language_test(string language, string template, string expected) + { + var bookDto = Shared.GetLibraryBook(); + bookDto.Language = new CultureInfoDto(language); + + var result = ""; + + var old = Thread.CurrentThread.CurrentCulture; + var oldUi = Thread.CurrentThread.CurrentUICulture; + try + { + Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE"); + Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES"); + Templates.TryGetTemplate(template, out var fileTemplate).Should().BeTrue(); + result = fileTemplate + .GetName(bookDto, new MultiConvertFileProperties { OutputFileName = string.Empty }); + } + finally + { + Thread.CurrentThread.CurrentCulture = old; + Thread.CurrentThread.CurrentUICulture = oldUi; + } + + result.Should().Be(expected); + } + + [TestMethod] + // test known locales + [DataRow("us", "", + "N:US, 2:US, 3:USA, W:USA, D:Estados Unidos, E:United States, N:United States, O:us")] + [DataRow("uk", "", + "N:GB, 2:GB, 3:GBR, W:GBR, D:Reino Unido, E:United Kingdom, N:United Kingdom, O:uk")] + [DataRow("canada", "", + "N:CA, 2:CA, 3:CAN, W:CAN, D:Canadá, E:Canada, N:Canada, O:canada")] + [DataRow("germany", "", + "N:DE, 2:DE, 3:DEU, W:DEU, D:Alemania, E:Germany, N:Deutschland, O:germany")] + [DataRow("france", "", + "N:FR, 2:FR, 3:FRA, W:FRA, D:Francia, E:France, N:Frañs, O:france")] + [DataRow("australia", "", + "N:AU, 2:AU, 3:AUS, W:AUS, D:Australia, E:Australia, N:Australia, O:australia")] + [DataRow("japan", "", + "N:JP, 2:JP, 3:JPN, W:JPN, D:Japón, E:Japan, N:日本, O:japan")] + [DataRow("india", "", + "N:IN, 2:IN, 3:IND, W:IND, D:India, E:India, N:ভাৰত, O:india")] + [DataRow("spain", "", + "N:ES, 2:ES, 3:ESP, W:ESP, D:España, E:Spain, N:España, O:spain")] + [DataRow("italy", "", + "N:IT, 2:IT, 3:ITA, W:ITA, D:Italia, E:Italy, N:Itàlia, O:italy")] + [DataRow("brazil", "", + "N:BR, 2:BR, 3:BRA, W:BRA, D:Brasil, E:Brazil, N:Brasil, O:brazil")] + // test historical locales + [DataRow("pre-amazon - us", "", "N:US, O:pre-amazon - us")] + [DataRow("pre-amazon - uk", "", "N:GB, O:pre-amazon - uk")] + [DataRow("pre-amazon - germany", "", "N:DE, O:pre-amazon - germany")] + // test upcoming locales + [DataRow("be", "", "N:BE, E:Belgium, O:be")] + [DataRow("nl", "", "N:NL, E:Netherlands, O:nl")] + [DataRow("se", "", "N:SE, E:Sweden, O:se")] + [DataRow("pl", "", "N:PL, E:Poland, O:pl")] + [DataRow("ie", "", "N:IE, E:Ireland, O:ie")] + [DataRow("sg", "", "N:SG, E:Singapore, O:sg")] + [DataRow("za", "", "N:ZA, E:South Africa, O:za")] + [DataRow("tr", "", "N:TR, E:Turkey, O:tr")] + [DataRow("ae", "", "N:AE, E:United Arab Emirates, O:ae")] + [DataRow("sa", "", "N:SA, E:Saudi Arabia, O:sa")] + [DataRow("eg", "", "N:EG, E:Egypt, O:eg")] + // different localizations + [DataRow("fr", "", "D:Frankreich, E:France, N:France, O:fr")] + [DataRow("fr", "", "D:Francja")] + [DataRow("fr", "", "D:Francia")] + public void Region_test(string country, string template, string expected) + { + var bookDto = Shared.GetLibraryBook(); + bookDto.Locale = new RegionInfoDto(country); + + var result = ""; + + var old = Thread.CurrentThread.CurrentCulture; + var oldUi = Thread.CurrentThread.CurrentUICulture; + try + { + Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR"); + Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES"); + Templates.TryGetTemplate(template, out var fileTemplate).Should().BeTrue(); + result = fileTemplate + .GetName(bookDto, new MultiConvertFileProperties { OutputFileName = string.Empty }); + } + finally + { + Thread.CurrentThread.CurrentCulture = old; + Thread.CurrentThread.CurrentUICulture = oldUi; + } + + result.Should().Be(expected); + } } } diff --git a/docs/features/naming-templates.md b/docs/features/naming-templates.md index 6917ec06..275b8ed5 100644 --- a/docs/features/naming-templates.md +++ b/docs/features/naming-templates.md @@ -37,9 +37,9 @@ These tags will be replaced in the template with the audiobook's values. | \ | Audible account nickname of this book | [Text](#text-formatters) | | \ | Tag(s) | [Text List](#text-list-formatters) | | \ | First tag | [Text](#text-formatters) | -| \ | Region/country | [Text](#text-formatters) | +| \ | Region/country | [Region](#region-formatters) | | \ | Year published | [Number](#number-formatters) | -| \ | Book's language | [Text](#text-formatters) | +| \ | Book's language | [Language](#language-formatters) | | \ **†** | Book's language abbreviated. Eg: ENG | Text | | \ | File creation date/time. | [DateTime](#date-formatters) | | \ | Audiobook publication date | [DateTime](#date-formatters) | @@ -185,7 +185,7 @@ Here, a number format is inserted for the desired part in accordance with [Micro |-----------|-----------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------|-------------------| | D | A number format with "D" instead of "0". Using this will output the total number of days and reduce the amount of minutes avalable for "H" and "M". | \ | 02 | | H | A number format with "H" instead of "0". Using this will output the total number of hours and reduce the amount of minutes available for "M". | \ | 62 | -| M | A number format with "H" instead of "0". Using this will output the total number of minutes. | \ | 3,762 | +| M | A number format with "M" instead of "0". Using this will output the total number of minutes. | \ | 3,762 | | D H M | A combination of the above. | \ | 02days 882minutes | ### Number Formatters