using System.Text; using EvilEngine.Formats; using EvilEngine.Formats.Records; using EvilEngine.Mounts; namespace EvilEngine.Conversion; public sealed record SoundtrackFolder(VirtualPath Folder, bool Tagged = false); public sealed record SoundtrackGame(string Title, string? Store = null); public sealed class SoundtrackRecords( IReadOnlyList folders, Func game, IReadOnlyList? lists = null) : IConverter { private static readonly string[] CoverNames = ["cover", "folder", "front", "album", "albumart", "albumartlarge"]; private static readonly string[] ImageExtensions = ["png", "jpg", "jpeg"]; private readonly Dictionary listed = (lists ?? []).ToDictionary(list => list.Game, StringComparer.Ordinal); public string Id => "soundtracks"; public int Version => 2; public ContentKind Produces => ContentKind.Record; public bool Accepts(ConversionContext context) { return context.Id.Name == AlbumRecords.Set; } public void Convert(ConversionContext context, Stream output) { var albums = new Dictionary<(string Game, string Title), List<(string Relative, VirtualPath Path, bool Tagged)>>(); var stores = new Dictionary(StringComparer.Ordinal); var images = new List(); var listedFiles = new Dictionary>(StringComparer.Ordinal); foreach (var folder in folders) foreach (var entry in context.List(folder.Folder, true)) { if (ImageExtensions.Contains(entry.Path.Extension, StringComparer.OrdinalIgnoreCase)) images.Add(entry.Path); if (!MusicFileConverter.IsMusic(entry.Path) || !entry.Path.TryRelativeTo(folder.Folder, CaseRule.Insensitive, out var relative) || context.Copies(entry.Path).FirstOrDefault() is not { } layer || game(layer) is not { } owner) continue; var title = owner.Title; stores.TryAdd(title, owner.Store); if (listed.ContainsKey(title)) { if (!listedFiles.TryGetValue(title, out var found)) listedFiles[title] = found = new Dictionary(StringComparer.OrdinalIgnoreCase); found.TryAdd(entry.Path.Value, entry.Path); continue; } var slash = relative.Value.IndexOf(VirtualPath.Separator); var sub = slash < 0 ? null : relative.Value[..slash]; var album = (folder.Tagged, sub) switch { (_, null) => title, (true, _) => sub, _ => $"{title} ({sub})" }; if (!albums.TryGetValue((title, album), out var tracks)) albums[(title, album)] = tracks = []; tracks.Add((relative.Value, entry.Path, folder.Tagged)); } var records = albums.Select(pair => new AlbumRecord( ContentId.Create(context.Id.Namespace, $"{Slug(pair.Key.Game)}/{Slug(pair.Key.Title)}"), pair.Key.Title, pair.Key.Game) { Cover = Cover(context, images, pair.Value[0].Path.Parent), Store = stores[pair.Key.Game], Tracks = pair.Value.OrderBy(track => track.Relative, NaturalOrder.Instance) .Select(track => new AlbumTrack(ContentId.Create(context.Id.Namespace, track.Path.Value)) { Title = track.Tagged ? null : Path.GetFileNameWithoutExtension(track.Path.Name) }).ToArray() }).Concat(listedFiles.SelectMany(pair => Listed(context, images, listed[pair.Key], pair.Value, stores[pair.Key]))) .ToArray(); output.Write(Encoding.UTF8.GetBytes(RecordText.Write(RecordSet.Empty with { Albums = records }))); } private static IEnumerable Listed(ConversionContext context, List images, MusicList list, Dictionary found, string? store) { foreach (var album in list.Albums) { var tracks = album.Tracks .Select((track, at) => (Track: track, Number: at + 1, Path: found.TryGetValue(track.File.Value, out var path) ? path : (VirtualPath?)null)) .Where(track => track.Path is not null) .ToArray(); if (tracks.Length == 0) continue; yield return new AlbumRecord( ContentId.Create(context.Id.Namespace, $"{Slug(list.Game)}/{Slug(album.Title)}"), album.Title, list.Game) { Cover = Cover(context, images, tracks[0].Path!.Value.Parent), Store = store, Tracks = tracks.Select(track => new AlbumTrack(ContentId.Create(context.Id.Namespace, track.Path!.Value.Value)) { Title = track.Track.Title, Number = track.Number }).ToArray() }; } } private static ContentId? Cover(ConversionContext context, List images, VirtualPath folder) { VirtualPath[] here = [ .. images.Where(image => image.Parent.Equals(folder, CaseRule.Insensitive)) .OrderBy(image => image.Value, StringComparer.OrdinalIgnoreCase) ]; VirtualPath? cover = null; foreach (var name in CoverNames) if (cover is null) foreach (var image in here) if (image.WithoutExtension.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { cover = image; break; } if (cover is null && here.Length == 1) cover = here[0]; return cover is { } found ? context.Reference(ContentKind.Texture, ContentId.Create(context.Id.Namespace, found.WithoutExtension.Value)) : null; } public static string Slug(string text) { var slug = new StringBuilder(); foreach (var c in text.ToLowerInvariant()) if (char.IsAsciiLetterOrDigit(c)) slug.Append(c); else if (slug.Length > 0 && slug[^1] != '-') slug.Append('-'); return slug.ToString().TrimEnd('-'); } private sealed class NaturalOrder : IComparer { public static readonly NaturalOrder Instance = new(); public int Compare(string? a, string? b) { if (a is null || b is null) return string.CompareOrdinal(a, b); int i = 0, j = 0; while (i < a.Length && j < b.Length) { if (char.IsAsciiDigit(a[i]) && char.IsAsciiDigit(b[j])) { var startA = i; var startB = j; while (i < a.Length && char.IsAsciiDigit(a[i])) i++; while (j < b.Length && char.IsAsciiDigit(b[j])) j++; var numberA = a[startA..i].TrimStart('0'); var numberB = b[startB..j].TrimStart('0'); var order = numberA.Length != numberB.Length ? numberA.Length.CompareTo(numberB.Length) : string.CompareOrdinal(numberA, numberB); if (order != 0) return order; continue; } var letters = char.ToLowerInvariant(a[i]).CompareTo(char.ToLowerInvariant(b[j])); if (letters != 0) return letters; i++; j++; } var rest = (a.Length - i).CompareTo(b.Length - j); return rest != 0 ? rest : string.CompareOrdinal(a, b); } } }