From 84d53845a111da957d7d933f9115b4b65564b678 Mon Sep 17 00:00:00 2001 From: Mateo Date: Fri, 4 Dec 2026 13:39:02 +0100 Subject: [PATCH 1/2] feat(api): cue sheets and Telegram audio details - GET /api/v1/channels/{id}/files/{fileId}/cue and GET /api/v1/local/cue read a cue sheet (UTF-8, UTF-16 or Windows-1252) and match each FILE line with the audio file next to it: exact name, same name with another audio extension (album.wav converted to FLAC), the audio file named like the sheet, or the only audio file in the folder. Each track carries its file with the usual URLs, and its start and end in seconds. - POST /api/v1/channels/{id}/files/audio-info returns the duration, title, performer and cover that Telegram keeps for audio documents, read in batches from the messages without downloading the files, and kept in memory. - Capabilities files.cue and files.audioInfo. --- .../Controllers/Api/V1/AudioController.cs | 242 +++++++++++++++++ .../Api/V1/LocalFilesController.cs | 41 +++ .../Mobile/MobileInfoController.cs | 4 + TelegramDownloader/Models/Api/AudioDtos.cs | 65 +++++ TelegramDownloader/Services/Audio/CueSheet.cs | 246 ++++++++++++++++++ Test/CueSheetTest.cs | 200 ++++++++++++++ Test/MobileBulkAndSearchTest.cs | 2 +- 7 files changed, 799 insertions(+), 1 deletion(-) create mode 100644 TelegramDownloader/Controllers/Api/V1/AudioController.cs create mode 100644 TelegramDownloader/Models/Api/AudioDtos.cs create mode 100644 TelegramDownloader/Services/Audio/CueSheet.cs create mode 100644 Test/CueSheetTest.cs diff --git a/TelegramDownloader/Controllers/Api/V1/AudioController.cs b/TelegramDownloader/Controllers/Api/V1/AudioController.cs new file mode 100644 index 0000000..6236b73 --- /dev/null +++ b/TelegramDownloader/Controllers/Api/V1/AudioController.cs @@ -0,0 +1,242 @@ +using System.Collections.Concurrent; +using Microsoft.AspNetCore.Mvc; +using TelegramDownloader.Data; +using TelegramDownloader.Data.db; +using TelegramDownloader.Models; +using TelegramDownloader.Models.Api; +using TelegramDownloader.Services; +using TelegramDownloader.Services.Api; +using TelegramDownloader.Services.Audio; +using TL; + +namespace TelegramDownloader.Controllers.Api.V1 +{ + /// + /// Music details of channel files that do not need the file itself: cue + /// sheets (an album in one file, split into tracks) and the title, + /// performer, duration and cover Telegram keeps for every audio document. + /// + [Route("api/v1/channels/{channelId}/files")] + [Tags("Files")] + [RequireTelegramSession] + public class AudioController : ApiV1ControllerBase + { + /// Most entries one audio-info request may ask for. + public const int MaxAudioInfoIds = 500; + + // Telegram audio attributes never change for a message: keep them. + private static readonly ConcurrentDictionary AudioCache = new(); + private const int AudioCacheLimit = 50_000; + + private readonly IDbService _db; + private readonly ITelegramService _telegram; + private readonly ILogger _logger; + + public AudioController(IDbService db, ITelegramService telegram, ILogger logger) + { + _db = db; + _telegram = telegram; + _logger = logger; + } + + /// Reads a cue sheet and matches its tracks with the audio files next to it. + /// + /// fileId is the .cue entry. Each track carries the + /// audio entry that holds it (with its contentUrl and + /// streamUrl) and where it starts and ends in that file, in + /// seconds; players clip the file to that range. The last track of a + /// file has no end: it plays to the end of the file. + /// + /// Channel that holds the files. + /// Id of the cue sheet entry. + /// Read the entries from this shared collection. + [HttpGet("{fileId}/cue")] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status404NotFound)] + public async Task Cue(string channelId, string fileId, [FromQuery] string? collectionId = null) + { + collectionId = FilesController.NormalizeCollection(collectionId); + var dbName = FilesController.DbFor(channelId, collectionId); + var collection = FilesController.CollectionFor(collectionId); + try + { + var entry = await _db.getFileById(dbName, fileId, collection); + if (entry == null || !entry.IsFile) + return NotFoundResult("File not found", ApiErrorCodes.FileNotFound); + if (!IsCue(entry.Name)) + return BadRequestResult("The file is not a cue sheet"); + if (entry.Size > CueSheet.MaxBytes) + return BadRequestResult("The file is too big for a cue sheet"); + + var bytes = await ReadSmallFile(channelId, entry); + if (bytes == null) + return NotFoundResult("The Telegram message of this file was not found", ApiErrorCodes.FileNotFound); + + var sheet = CueSheet.Parse(bytes); + var siblings = await _db.getAllFilesInDirectoryPath(dbName, entry.FilterPath, collection) ?? new List(); + var files = siblings.Where(s => s.IsFile && !string.IsNullOrEmpty(s.Name)) + .GroupBy(s => s.Name, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); + + var dto = BuildCueDto(entry.Id, entry.Name, sheet, files.Keys, + name => ApiFileDto.FromBson(files[name], channelId, BaseUrl, collectionId)); + return OkResult(dto); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error reading cue sheet {FileId} of channel {ChannelId}", fileId, channelId); + return ErrorResult("Could not read the cue sheet", ex); + } + } + + /// The audio details Telegram keeps for these files, without downloading them. + /// + /// Telegram stores the duration, title and performer of every audio + /// document, and music usually carries its cover as the document + /// thumbnail. Players can show them in lists and in the queue before + /// a byte of the file is read. Entries that are not found, folders, + /// and files whose message has no audio details come back with null + /// fields. The details are kept in memory after the first request. + /// + /// Channel that holds the files. + /// Entry ids (up to 500) and an optional shared collection. + [HttpPost("audio-info")] + [ProducesResponseType(typeof(ApiResult>), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status400BadRequest)] + public async Task AudioInfo(string channelId, [FromBody] AudioInfoRequest request) + { + var ids = request?.FileIds?.Where(id => !string.IsNullOrWhiteSpace(id)).Distinct().ToList() ?? new List(); + if (ids.Count == 0) return OkResult(new List()); + if (ids.Count > MaxAudioInfoIds) + return BadRequestResult($"At most {MaxAudioInfoIds} files per request"); + if (!long.TryParse(channelId, out var chatId)) + return BadRequestResult("Invalid channel id"); + + try + { + var collectionId = FilesController.NormalizeCollection(request!.CollectionId); + var dbName = FilesController.DbFor(channelId, collectionId); + var collection = FilesController.CollectionFor(collectionId); + + var messageOf = new Dictionary(); + foreach (var id in ids) + { + var entry = await _db.getFileById(dbName, id, collection); + if (entry == null || !entry.IsFile) continue; + var messageId = entry.MessageId ?? entry.ListMessageId?.FirstOrDefault(); + if (messageId is > 0) messageOf[id] = messageId.Value; + } + + var missing = messageOf.Values.Distinct().Where(m => !AudioCache.ContainsKey(Key(channelId, m))).ToList(); + if (missing.Count > 0) + { + var messages = await _telegram.getMessagesById(chatId, missing); + if (AudioCache.Count + missing.Count > AudioCacheLimit) AudioCache.Clear(); + var byId = messages.ToDictionary(m => m.id); + foreach (var m in missing) + AudioCache[Key(channelId, m)] = byId.TryGetValue(m, out var message) ? AudioAttributes.From(message) : AudioAttributes.None; + } + + var result = ids.Select(id => + { + var dto = new ApiAudioInfoDto { FileId = id }; + if (!messageOf.TryGetValue(id, out var messageId)) return dto; + dto.MessageId = messageId; + if (AudioCache.TryGetValue(Key(channelId, messageId), out var a)) + { + dto.Duration = a.Duration; + dto.Title = a.Title; + dto.Performer = a.Performer; + dto.HasCover = a.HasCover; + if (a.HasCover) dto.CoverUrl = MediaUrlBuilder.Thumbnail(BaseUrl, channelId, messageId); + } + return dto; + }).ToList(); + return OkResult(result); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error reading audio details of channel {ChannelId}", channelId); + return ErrorResult("Could not read the audio details", ex); + } + } + + public static bool IsCue(string? name) => + string.Equals(Path.GetExtension(name ?? string.Empty), ".cue", StringComparison.OrdinalIgnoreCase); + + public static bool IsAudio(string name) => ApiFileDto.CategoryOf(Path.GetExtension(name)) == "Audio"; + + /// The DTO of a parsed sheet, given how to describe each matched sibling. + public static ApiCueSheetDto BuildCueDto(string id, string name, CueSheet sheet, IReadOnlyCollection siblings, Func describe) + { + var matched = sheet.MatchFiles(name, siblings, IsAudio); + var described = matched.Values.Distinct(StringComparer.OrdinalIgnoreCase) + .ToDictionary(n => n, describe, StringComparer.OrdinalIgnoreCase); + return new ApiCueSheetDto + { + Id = id, + Name = name, + Title = sheet.Title, + Performer = sheet.Performer, + Date = sheet.Date, + Genre = sheet.Genre, + MissingFiles = sheet.Files.Where(f => !matched.ContainsKey(f)).Distinct(StringComparer.OrdinalIgnoreCase).ToList(), + Tracks = sheet.Tracks.Select(t => new ApiCueTrackDto + { + Number = t.Number, + Title = t.Title, + Performer = t.Performer, + Start = t.Start, + End = sheet.EndOf(t), + FileName = t.File, + File = matched.TryGetValue(t.File, out var sibling) ? described[sibling] : null + }).ToList() + }; + } + + /// The bytes of a small file, from the server cache or Telegram (then cached). + private async Task ReadSmallFile(string channelId, BsonFileManagerModel entry) + { + var folder = Path.Combine(FileService.TEMPDIR, "_temp"); + Directory.CreateDirectory(folder); + var key = entry.MessageId != null ? entry.MessageId.ToString() : entry.Id; + var cachePath = Path.Combine(folder, $"{channelId}-{key}-{entry.Name}"); + if (System.IO.File.Exists(cachePath) && new FileInfo(cachePath).Length >= entry.Size) + return await System.IO.File.ReadAllBytesAsync(cachePath); + + var messageId = entry.MessageId ?? entry.ListMessageId?.FirstOrDefault(); + if (messageId is not > 0) return null; + var message = await _telegram.getMessageFile(channelId, messageId.Value); + if (message == null) return null; + + using var buffer = new MemoryStream(); + await foreach (var chunk in _telegram.DownloadFileStreamChunks(message, 0, Math.Max(entry.Size, 1), HttpContext.RequestAborted)) + buffer.Write(chunk, 0, chunk.Length); + var bytes = buffer.ToArray(); + if (entry.Size > 0 && bytes.Length > entry.Size) bytes = bytes[..(int)entry.Size]; + try { await System.IO.File.WriteAllBytesAsync(cachePath, bytes); } + catch (Exception ex) { _logger.LogDebug(ex, "Could not cache cue sheet {Name}", entry.Name); } + return bytes; + } + + private static string Key(string channelId, int messageId) => $"{channelId}:{messageId}"; + + private sealed record AudioAttributes(int? Duration, string? Title, string? Performer, bool HasCover) + { + public static readonly AudioAttributes None = new(null, null, null, false); + + public static AudioAttributes From(Message message) + { + if (message.media is not MessageMediaDocument { document: TL.Document doc }) return None; + var audio = doc.attributes?.OfType().FirstOrDefault(); + if (audio == null) return None; + return new AudioAttributes( + audio.duration > 0 ? audio.duration : null, + string.IsNullOrWhiteSpace(audio.title) ? null : audio.title.Trim(), + string.IsNullOrWhiteSpace(audio.performer) ? null : audio.performer.Trim(), + doc.thumbs != null && doc.thumbs.Length > 0); + } + } + } +} diff --git a/TelegramDownloader/Controllers/Api/V1/LocalFilesController.cs b/TelegramDownloader/Controllers/Api/V1/LocalFilesController.cs index ade0b87..5541958 100644 --- a/TelegramDownloader/Controllers/Api/V1/LocalFilesController.cs +++ b/TelegramDownloader/Controllers/Api/V1/LocalFilesController.cs @@ -117,6 +117,47 @@ public IActionResult Info([FromQuery] string path) return NotFoundResult("Path not found"); } + /// Reads a local cue sheet and matches its tracks with the audio files next to it. + /// + /// Same answer as GET /api/v1/channels/{id}/files/{fileId}/cue: + /// each track carries the local audio file that holds it and where it + /// starts and ends in that file, in seconds. + /// + /// Relative path of the .cue file. + [HttpGet("cue")] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(ApiResult), StatusCodes.Status404NotFound)] + public async Task Cue([FromQuery] string path) + { + if (!TryResolve(path, out var absolute, out var relative, out var error)) + return BadRequestResult(error!); + if (!System.IO.File.Exists(absolute)) + return NotFoundResult("Path not found"); + if (!AudioController.IsCue(absolute)) + return BadRequestResult("The file is not a cue sheet"); + var info = new FileInfo(absolute); + if (info.Length > Services.Audio.CueSheet.MaxBytes) + return BadRequestResult("The file is too big for a cue sheet"); + + try + { + var sheet = Services.Audio.CueSheet.Parse(await System.IO.File.ReadAllBytesAsync(absolute)); + var siblings = info.Directory!.GetFiles().ToDictionary(f => f.Name, StringComparer.OrdinalIgnoreCase); + var relativeFolder = Path.GetDirectoryName(relative.Replace('\\', '/'))?.Replace('\\', '/') ?? string.Empty; + string RelativeOf(string name) => string.IsNullOrEmpty(relativeFolder) ? name : $"{relativeFolder.TrimEnd('/')}/{name}"; + + var dto = AudioController.BuildCueDto(relative, info.Name, sheet, siblings.Keys, + name => ApiFileDto.FromLocalFile(siblings[name], RelativeOf(siblings[name].Name), BaseUrl)); + return OkResult(dto); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error reading local cue sheet {Path}", path); + return ErrorResult("Could not read the cue sheet", ex); + } + } + /// Recursive size and file-type breakdown of a local directory. [HttpGet("size")] [ProducesResponseType(typeof(ApiResult), StatusCodes.Status200OK)] diff --git a/TelegramDownloader/Controllers/Mobile/MobileInfoController.cs b/TelegramDownloader/Controllers/Mobile/MobileInfoController.cs index 910d53d..61f5845 100644 --- a/TelegramDownloader/Controllers/Mobile/MobileInfoController.cs +++ b/TelegramDownloader/Controllers/Mobile/MobileInfoController.cs @@ -44,6 +44,8 @@ public class MobileInfoController : ControllerBase "library.scanFolders", // folders in POST /api/v1/library/scan "library.seriesFolders", // GET /api/v1/library/folders, PUT|DELETE /api/v1/library/folders/series "library.fileFilters", // kind and rule in GET /api/v1/library/files, GET /api/v1/library/files/facets + "files.cue", // GET /api/v1/channels/{id}/files/{fileId}/cue, GET /api/v1/local/cue + "files.audioInfo", // POST /api/v1/channels/{id}/files/audio-info (Telegram title, performer, duration, cover) }; private static readonly string ServerVersion = ResolveServerVersion(); @@ -74,6 +76,8 @@ public class MobileInfoController : ControllerBase /// - `webAuth.passkeys`: /api/v1/web-auth/passkeys/** (inicio de sesión con passkeys de la web) /// - `files.deleteOperations`: borrados en segundo plano con progreso y cancelación: POST /api/v1/channels/{id}/files/delete-operations, /// POST /api/v1/local/delete-operations, GET /api/v1/delete-operations[/{id}], POST /api/v1/delete-operations/{id}/cancel y `DeleteProgress` en /hubs/events + /// - `files.cue`: hojas CUE (un álbum en un único fichero, partido en pistas): GET /api/v1/channels/{id}/files/{fileId}/cue y GET /api/v1/local/cue + /// - `files.audioInfo`: POST /api/v1/channels/{id}/files/audio-info (título, intérprete, duración y carátula que guarda Telegram, sin descargar el fichero) /// /// Los servidores antiguos no tienen este endpoint: un **404** debe interpretarse /// como "sin funcionalidades opcionales". No accede a base de datos. diff --git a/TelegramDownloader/Models/Api/AudioDtos.cs b/TelegramDownloader/Models/Api/AudioDtos.cs new file mode 100644 index 0000000..4827dc7 --- /dev/null +++ b/TelegramDownloader/Models/Api/AudioDtos.cs @@ -0,0 +1,65 @@ +namespace TelegramDownloader.Models.Api +{ + /// A cue sheet read and matched with the audio files next to it. + public class ApiCueSheetDto + { + /// Id of the cue sheet (entry id, or relative path for local files). + public string Id { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + /// Album title (TITLE before the first track). + public string? Title { get; set; } + /// Album performer. + public string? Performer { get; set; } + /// REM DATE. + public string? Date { get; set; } + /// REM GENRE. + public string? Genre { get; set; } + public List Tracks { get; set; } = new(); + /// FILE names with no matching audio file in the folder; their tracks have no file. + public List MissingFiles { get; set; } = new(); + } + + /// One track of a cue sheet: a slice of an audio file. + public class ApiCueTrackDto + { + public int Number { get; set; } + public string? Title { get; set; } + /// The track performer, or the album one. + public string? Performer { get; set; } + /// Where the track starts in the file, in seconds. + public double Start { get; set; } + /// Where it ends, in seconds; null for the last track of a file (plays to the end). + public double? End { get; set; } + /// The file name as written in the cue sheet. + public string FileName { get; set; } = string.Empty; + /// The audio file holding the track, with its URLs; null when it was not found. + public ApiFileDto? File { get; set; } + } + + /// The audio details Telegram keeps for a document, read without downloading it. + public class ApiAudioInfoDto + { + public string FileId { get; set; } = string.Empty; + /// The message that holds the file (first part of a split file). + public int? MessageId { get; set; } + /// Seconds, when Telegram knows it. + public int? Duration { get; set; } + public string? Title { get; set; } + public string? Performer { get; set; } + /// + /// The document has a thumbnail (the album cover for music), served by + /// GET /api/v1/channels/{id}/messages/{messageId}/thumbnail. + /// + public bool HasCover { get; set; } + /// Thumbnail URL when . + public string? CoverUrl { get; set; } + } + + public class AudioInfoRequest + { + /// Entry ids (up to 500). + public List FileIds { get; set; } = new(); + /// Read the entries from this shared collection. + public string? CollectionId { get; set; } + } +} diff --git a/TelegramDownloader/Services/Audio/CueSheet.cs b/TelegramDownloader/Services/Audio/CueSheet.cs new file mode 100644 index 0000000..3b7353a --- /dev/null +++ b/TelegramDownloader/Services/Audio/CueSheet.cs @@ -0,0 +1,246 @@ +using System.Globalization; +using System.Text; + +namespace TelegramDownloader.Services.Audio +{ + /// One track of a cue sheet. + public sealed class CueTrack + { + public int Number { get; init; } + public string? Title { get; set; } + public string? Performer { get; set; } + /// Where the track starts in its file (INDEX 01), in seconds. + public double Start { get; set; } + /// The FILE line the track belongs to. + public string File { get; init; } = string.Empty; + } + + /// + /// A cue sheet: the text file that splits one long audio file (an album + /// ripped to a single FLAC, APE, WAV or MP3) into tracks. + /// + public sealed class CueSheet + { + public string? Title { get; set; } + public string? Performer { get; set; } + public string? Date { get; set; } + public string? Genre { get; set; } + /// The audio files named by FILE lines, in order. + public List Files { get; } = new(); + public List Tracks { get; } = new(); + + /// Cue sheets are small; anything bigger is not one. + public const long MaxBytes = 512 * 1024; + + static CueSheet() + { + // Windows-1252, the usual encoding of cue sheets written by EAC and foobar2000. + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + + /// + /// Text of a cue sheet: UTF-8 (with or without BOM) when the bytes are + /// valid UTF-8, UTF-16 with a BOM, Windows-1252 otherwise. + /// + public static string Decode(byte[] bytes) + { + if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) + return Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3); + if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) + return Encoding.Unicode.GetString(bytes, 2, bytes.Length - 2); + if (bytes.Length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) + return Encoding.BigEndianUnicode.GetString(bytes, 2, bytes.Length - 2); + try + { + return new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes); + } + catch (DecoderFallbackException) + { + return Encoding.GetEncoding(1252).GetString(bytes); + } + } + + public static CueSheet Parse(byte[] bytes) => Parse(Decode(bytes)); + + /// + /// Reads the commands the players need (FILE, TRACK, + /// TITLE, PERFORMER, INDEX, REM DATE and + /// REM GENRE) and ignores the rest. Only audio tracks are kept. + /// A track starts at INDEX 01, or INDEX 00 when it has + /// no 01. + /// + public static CueSheet Parse(string text) + { + var sheet = new CueSheet(); + string? file = null; + CueTrack? track = null; + bool trackIsAudio = false; + double? index00 = null; + bool hasIndex01 = false; + + void Close() + { + if (track != null && trackIsAudio && (hasIndex01 || index00 != null)) + { + if (!hasIndex01) track.Start = index00!.Value; + sheet.Tracks.Add(track); + } + track = null; + index00 = null; + hasIndex01 = false; + } + + foreach (var raw in text.Split('\n')) + { + var line = raw.Trim().TrimEnd('\r'); + if (line.Length == 0) continue; + var (command, rest) = SplitCommand(line); + + switch (command) + { + case "FILE": + Close(); + file = FileName(rest); + if (!string.IsNullOrEmpty(file)) sheet.Files.Add(file); + break; + case "TRACK": + { + Close(); + var parts = rest.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (file == null || parts.Length == 0 || !int.TryParse(parts[0], out var number)) break; + trackIsAudio = parts.Length < 2 || parts[1].Equals("AUDIO", StringComparison.OrdinalIgnoreCase); + track = new CueTrack { Number = number, File = file }; + break; + } + case "TITLE": + if (track != null) track.Title = Value(rest); + else sheet.Title = Value(rest); + break; + case "PERFORMER": + if (track != null) track.Performer = Value(rest); + else sheet.Performer = Value(rest); + break; + case "INDEX": + { + if (track == null) break; + var parts = rest.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length < 2 || !int.TryParse(parts[0], out var which)) break; + var at = ParseTime(parts[1]); + if (at == null) break; + if (which == 1) { track.Start = at.Value; hasIndex01 = true; } + else if (which == 0) index00 = at.Value; + break; + } + case "REM": + { + if (track != null) break; + var (key, value) = SplitCommand(rest); + if (key == "DATE") sheet.Date = Value(value); + else if (key == "GENRE") sheet.Genre = Value(value); + break; + } + } + } + Close(); + + // Inherit the album performer, like players do. + foreach (var t in sheet.Tracks) + t.Performer ??= sheet.Performer; + return sheet; + } + + /// mm:ss:ff (75 frames a second) in seconds. + public static double? ParseTime(string value) + { + var parts = value.Split(':'); + if (parts.Length != 3) return null; + if (!int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var m) || + !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var s) || + !int.TryParse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture, out var f)) + return null; + return Math.Round(m * 60 + s + f / 75.0, 3); + } + + private static (string Command, string Remainder) SplitCommand(string line) + { + var space = line.IndexOf(' '); + if (space < 0) return (line.ToUpperInvariant(), string.Empty); + return (line[..space].ToUpperInvariant(), line[(space + 1)..].Trim()); + } + + /// A quoted or bare value; empty values become null. + private static string? Value(string rest) + { + var v = rest.Trim(); + if (v.Length >= 2 && v[0] == '"') + { + var end = v.LastIndexOf('"'); + v = end > 0 ? v[1..end] : v[1..]; + } + v = v.Trim(); + return v.Length == 0 ? null : v; + } + + /// FILE "name.flac" WAVE: the name, without the file type. + private static string? FileName(string rest) + { + var v = rest.Trim(); + if (v.StartsWith('"')) + { + var end = v.IndexOf('"', 1); + return end > 0 ? v[1..end] : v[1..]; + } + var lastSpace = v.LastIndexOf(' '); + return lastSpace > 0 ? v[..lastSpace] : v; + } + + /// + /// Finds the audio file each FILE line names among the files + /// next to the cue sheet. + /// + /// + /// In order: the exact name (ignoring case); the same name with any + /// audio extension, because rippers often write album.wav and + /// the file was converted to FLAC later; for a sheet with one file, + /// the audio file named like the sheet, and then the only audio file + /// in the folder. + /// + /// File name of the cue sheet. + /// Names of the files in the same folder. + /// Whether a file name is an audio file. + /// The sibling for each FILE name that was found. + public Dictionary MatchFiles(string cueName, IReadOnlyCollection siblings, Func isAudio) + { + var audio = siblings.Where(isAudio).ToList(); + var found = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var name in Files.Distinct(StringComparer.OrdinalIgnoreCase)) + { + var bare = Path.GetFileName(name.Replace('\\', '/')); + var exact = siblings.FirstOrDefault(s => s.Equals(bare, StringComparison.OrdinalIgnoreCase)); + var sameBase = audio.FirstOrDefault(s => + Path.GetFileNameWithoutExtension(s).Equals(Path.GetFileNameWithoutExtension(bare), StringComparison.OrdinalIgnoreCase)); + var match = exact ?? sameBase; + if (match == null && Files.Distinct(StringComparer.OrdinalIgnoreCase).Count() == 1) + { + match = audio.FirstOrDefault(s => + Path.GetFileNameWithoutExtension(s).Equals(Path.GetFileNameWithoutExtension(cueName), StringComparison.OrdinalIgnoreCase)) + ?? (audio.Count == 1 ? audio[0] : null); + } + if (match != null) found[name] = match; + } + return found; + } + + /// + /// Where each track ends: the start of the next track of the same + /// file, or null for the last one (it plays to the end of the file). + /// + public double? EndOf(CueTrack track) + { + var i = Tracks.IndexOf(track); + if (i < 0 || i + 1 >= Tracks.Count) return null; + var next = Tracks[i + 1]; + return next.File == track.File && next.Start > track.Start ? next.Start : null; + } + } +} diff --git a/Test/CueSheetTest.cs b/Test/CueSheetTest.cs new file mode 100644 index 0000000..5904cb1 --- /dev/null +++ b/Test/CueSheetTest.cs @@ -0,0 +1,200 @@ +using System.Text; +using TelegramDownloader.Controllers.Api.V1; +using TelegramDownloader.Models.Api; +using TelegramDownloader.Services.Audio; + +namespace Test +{ + /// + /// Cue sheets split an album ripped to one file into tracks: the parser + /// reads them as EAC and foobar2000 write them, and finds the audio file + /// each FILE line means among the files next to the sheet. + /// + public class CueSheetTest + { + private const string Album = """ + REM GENRE Rock + REM DATE 1994 + PERFORMER "The Band" + TITLE "Live Album" + FILE "The Band - Live Album.wav" WAVE + TRACK 01 AUDIO + TITLE "Intro" + INDEX 01 00:00:00 + TRACK 02 AUDIO + TITLE "Second Song" + PERFORMER "The Band feat. Guest" + INDEX 00 03:10:00 + INDEX 01 03:12:37 + TRACK 03 AUDIO + TITLE "Closer" + INDEX 01 07:45:74 + """; + + private static bool IsAudio(string name) => AudioController.IsAudio(name); + + [Test] + public void ReadsTheAlbumTitle() => + Assert.That(CueSheet.Parse(Album).Title, Is.EqualTo("Live Album")); + + [Test] + public void ReadsTheAlbumPerformer() => + Assert.That(CueSheet.Parse(Album).Performer, Is.EqualTo("The Band")); + + [Test] + public void ReadsTheDateAndGenreRemarks() + { + var sheet = CueSheet.Parse(Album); + Assert.That((sheet.Date, sheet.Genre), Is.EqualTo(("1994", "Rock"))); + } + + [Test] + public void ReadsEveryAudioTrackInOrder() => + Assert.That(CueSheet.Parse(Album).Tracks.Select(t => t.Title), Is.EqualTo(new[] { "Intro", "Second Song", "Closer" })); + + [Test] + public void TrackStartsAtIndexOneNotAtThePregap() => + Assert.That(CueSheet.Parse(Album).Tracks[1].Start, Is.EqualTo(192.493).Within(0.001)); + + [Test] + public void FramesAreSeventyFifthsOfASecond() => + Assert.That(CueSheet.ParseTime("07:45:74"), Is.EqualTo(465 + 74 / 75.0).Within(0.001)); + + [Test] + public void TrackWithoutIndexOneStartsAtIndexZero() + { + var sheet = CueSheet.Parse("FILE \"a.flac\" WAVE\nTRACK 01 AUDIO\nINDEX 00 00:02:00\n"); + Assert.That(sheet.Tracks[0].Start, Is.EqualTo(2)); + } + + [Test] + public void TrackPerformerOverridesTheAlbumOne() => + Assert.That(CueSheet.Parse(Album).Tracks[1].Performer, Is.EqualTo("The Band feat. Guest")); + + [Test] + public void TrackWithoutPerformerTakesTheAlbumOne() => + Assert.That(CueSheet.Parse(Album).Tracks[0].Performer, Is.EqualTo("The Band")); + + [Test] + public void TrackEndsWhereTheNextOneStarts() + { + var sheet = CueSheet.Parse(Album); + Assert.That(sheet.EndOf(sheet.Tracks[0]), Is.EqualTo(sheet.Tracks[1].Start)); + } + + [Test] + public void LastTrackPlaysToTheEndOfTheFile() + { + var sheet = CueSheet.Parse(Album); + Assert.That(sheet.EndOf(sheet.Tracks[2]), Is.Null); + } + + [Test] + public void LastTrackOfAFileEndsWithItsFileWhenTheSheetHasSeveral() + { + var sheet = CueSheet.Parse("FILE \"cd1.flac\" WAVE\nTRACK 01 AUDIO\nINDEX 01 00:00:00\nTRACK 02 AUDIO\nINDEX 01 03:00:00\n" + + "FILE \"cd2.flac\" WAVE\nTRACK 03 AUDIO\nINDEX 01 00:00:00\n"); + Assert.That(sheet.EndOf(sheet.Tracks[1]), Is.Null); + } + + [Test] + public void SkipsDataTracks() + { + var sheet = CueSheet.Parse("FILE \"a.bin\" BINARY\nTRACK 01 MODE1/2352\nINDEX 01 00:00:00\nFILE \"a.flac\" WAVE\nTRACK 02 AUDIO\nINDEX 01 00:00:00\n"); + Assert.That(sheet.Tracks.Select(t => t.Number), Is.EqualTo(new[] { 2 })); + } + + [Test] + public void ReadsBareValuesWithoutQuotes() => + Assert.That(CueSheet.Parse("TITLE Album\nFILE album.flac WAVE\nTRACK 01 AUDIO\nINDEX 01 00:00:00\n").Files, Is.EqualTo(new[] { "album.flac" })); + + [Test] + public void HandlesWindowsLineEndings() => + Assert.That(CueSheet.Parse(Album.Replace("\n", "\r\n")).Tracks, Has.Count.EqualTo(3)); + + [Test] + public void DecodesUtf8() + { + var bytes = Encoding.UTF8.GetBytes("TITLE \"Canción\"\n"); + Assert.That(CueSheet.Parse(bytes).Title, Is.EqualTo("Canción")); + } + + [Test] + public void DecodesUtf8WithBom() + { + var bytes = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes("TITLE \"Canción\"\n")).ToArray(); + Assert.That(CueSheet.Parse(bytes).Title, Is.EqualTo("Canción")); + } + + [Test] + public void FallsBackToWindows1252() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + var bytes = Encoding.GetEncoding(1252).GetBytes("TITLE \"Canción\"\n"); + Assert.That(CueSheet.Parse(bytes).Title, Is.EqualTo("Canción")); + } + + [Test] + public void MatchesTheFileByExactNameIgnoringCase() + { + var sheet = CueSheet.Parse("FILE \"Album.FLAC\" WAVE\nTRACK 01 AUDIO\nINDEX 01 00:00:00\n"); + var found = sheet.MatchFiles("x.cue", new[] { "album.flac", "other.flac" }, IsAudio); + Assert.That(found["Album.FLAC"], Is.EqualTo("album.flac")); + } + + [Test] + public void MatchesAConvertedFileWithAnotherExtension() + { + var sheet = CueSheet.Parse(Album); + var found = sheet.MatchFiles("x.cue", new[] { "The Band - Live Album.flac", "cover.jpg" }, IsAudio); + Assert.That(found["The Band - Live Album.wav"], Is.EqualTo("The Band - Live Album.flac")); + } + + [Test] + public void MatchesTheAudioFileNamedLikeTheSheet() + { + var sheet = CueSheet.Parse("FILE \"CDImage.wav\" WAVE\nTRACK 01 AUDIO\nINDEX 01 00:00:00\n"); + var found = sheet.MatchFiles("Album.cue", new[] { "Album.flac", "Bonus.flac" }, IsAudio); + Assert.That(found["CDImage.wav"], Is.EqualTo("Album.flac")); + } + + [Test] + public void MatchesTheOnlyAudioFileInTheFolder() + { + var sheet = CueSheet.Parse("FILE \"CDImage.wav\" WAVE\nTRACK 01 AUDIO\nINDEX 01 00:00:00\n"); + var found = sheet.MatchFiles("Album.cue", new[] { "rip.flac", "Album.log" }, IsAudio); + Assert.That(found["CDImage.wav"], Is.EqualTo("rip.flac")); + } + + [Test] + public void LeavesAFileUnmatchedWhenNothingFits() + { + var sheet = CueSheet.Parse("FILE \"CDImage.wav\" WAVE\nTRACK 01 AUDIO\nINDEX 01 00:00:00\n"); + var found = sheet.MatchFiles("Album.cue", new[] { "a.flac", "b.flac" }, IsAudio); + Assert.That(found, Is.Empty); + } + + [Test] + public void DtoListsTheFilesThatWereNotFound() + { + var dto = AudioController.BuildCueDto("id", "Album.cue", CueSheet.Parse(Album), new[] { "a.flac", "b.flac" }, Describe); + Assert.That(dto.MissingFiles, Is.EqualTo(new[] { "The Band - Live Album.wav" })); + } + + [Test] + public void DtoTracksCarryTheirAudioFile() + { + var dto = AudioController.BuildCueDto("id", "Album.cue", CueSheet.Parse(Album), new[] { "The Band - Live Album.flac" }, Describe); + Assert.That(dto.Tracks.Select(t => t.File?.Name).Distinct(), Is.EqualTo(new[] { "The Band - Live Album.flac" })); + } + + [Test] + public void DtoTracksCarryTheirEnd() + { + var dto = AudioController.BuildCueDto("id", "Album.cue", CueSheet.Parse(Album), new[] { "The Band - Live Album.flac" }, Describe); + Assert.That(dto.Tracks.Select(t => t.End), Is.EqualTo(new double?[] { 192.493, 465.987, null }).Within(0.001)); + } + + private static ApiFileDto Describe(string name) => new() { Id = name, Name = name, IsFile = true }; + } +} diff --git a/Test/MobileBulkAndSearchTest.cs b/Test/MobileBulkAndSearchTest.cs index 6d3bcd1..250bc6e 100644 --- a/Test/MobileBulkAndSearchTest.cs +++ b/Test/MobileBulkAndSearchTest.cs @@ -152,7 +152,7 @@ public void CapabilitiesAdvertiseExactFeatureSet() "playlist.bulkAdd", "search.global", "channels.refresh", "channels.refreshProgress", "stream.localTranscode", "events.hub", "search.v1", "files.thumbnails", "files.content", "files.preload", "local.copyMove", "shares.browse", "setup.write", "transfers.remove", "system.admin", "webAuth.passkeys", "files.deleteOperations", "messages.content", "transfers.pauseUploads", "library.seriesFolders", "library.scanFolders", "messages.browse", "channels.refreshSequential", - "library.fileFilters" + "library.fileFilters", "files.cue", "files.audioInfo" })); } } From 81b147f4561a594f4a5898ba69ac202515e9414b Mon Sep 17 00:00:00 2001 From: Mateo Date: Fri, 4 Dec 2026 14:02:50 +0100 Subject: [PATCH 2/2] feat(web): play cue sheets and show Telegram audio details - Cue sheets: opening a .cue (channels, shared collections, local files) shows its tracks with play all, play from a track, play next and add to queue; tracks whose audio file is missing are disabled and listed. Each track is queued as a clip of its file (start/end). - Player: clip support. The elements work in file time while the store, the UI and the media session show track time; a clip stops or advances at its end, consecutive clips of one file keep the source playing, and another clip of the playing file seeks instead of reloading. - Telegram audio details: channel listings and searches ask audio-info for their audio files in the background (batches of 500, capability files.audioInfo, cached per channel/collection + file). Rows show "Performer - Title" and the duration, audio files get the Telegram cover as thumbnail, and queued tracks start with those details. - File manager: describeEntry prop (subtitle, facts and a badge per row); a CUE badge marks cue sheets and the audio file they describe. - api-client: files.cue, files.audioInfo and local.cue. --- TelegramDownloader/ClientApp/ARCHITECTURE.md | 8 + .../features/channels/lib/channelActions.ts | 2 +- .../features/channels/lib/channelProvider.ts | 17 +- .../features/channels/pages/ChannelPage.tsx | 3 + .../web/src/features/files/audioInfo.test.ts | 92 +++++++ .../apps/web/src/features/files/audioInfo.ts | 122 +++++++++ .../src/features/files/cue/CueSheetDialog.tsx | 136 ++++++++++ .../src/features/files/cue/CueSheetSlot.tsx | 15 ++ .../src/features/files/cue/cueModel.test.ts | 92 +++++++ .../web/src/features/files/cue/cueModel.ts | 86 +++++++ .../web/src/features/files/cue/cueStore.ts | 21 ++ .../features/files/deletes/deleteTracker.ts | 17 +- .../web/src/features/files/describeEntry.ts | 50 ++++ .../apps/web/src/features/files/entries.ts | 24 +- .../apps/web/src/features/files/media.ts | 33 ++- .../features/local/pages/LocalFilesPage.tsx | 3 + .../web/src/features/player/PlayerSlot.tsx | 2 + .../apps/web/src/features/player/clip.test.ts | 52 ++++ .../apps/web/src/features/player/clip.ts | 94 +++++++ .../web/src/features/player/engine.test.ts | 146 +++++++++++ .../apps/web/src/features/player/engine.ts | 238 +++++++++++++++--- .../apps/web/src/features/player/public.ts | 7 + .../src/features/player/ui/useNowPlaying.ts | 14 +- .../shared/pages/SharedCollectionPage.tsx | 5 +- .../ClientApp/apps/web/src/i18n/es/files.ts | 8 + .../ClientApp/apps/web/src/i18n/gl/files.ts | 8 + .../apps/web/src/lib/serverFeatures.ts | 25 ++ .../packages/api-client/src/index.ts | 1 + .../packages/api-client/src/modules/files.ts | 7 + .../packages/api-client/src/modules/local.ts | 3 + .../packages/api-client/src/types/audio.ts | 64 +++++ .../ClientApp/packages/file-manager/README.md | 2 + .../packages/file-manager/src/index.ts | 1 + .../packages/file-manager/src/types.ts | 10 + .../file-manager/src/ui/EntryItems.tsx | 41 ++- .../file-manager/src/ui/FileManager.test.tsx | 10 + .../file-manager/src/ui/FileManager.tsx | 9 +- .../packages/file-manager/src/ui/context.ts | 4 +- 38 files changed, 1397 insertions(+), 75 deletions(-) create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.test.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetDialog.tsx create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetSlot.tsx create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.test.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueStore.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/files/describeEntry.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/player/clip.test.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/features/player/clip.ts create mode 100644 TelegramDownloader/ClientApp/apps/web/src/lib/serverFeatures.ts create mode 100644 TelegramDownloader/ClientApp/packages/api-client/src/types/audio.ts diff --git a/TelegramDownloader/ClientApp/ARCHITECTURE.md b/TelegramDownloader/ClientApp/ARCHITECTURE.md index 93cc662..8243cd9 100644 --- a/TelegramDownloader/ClientApp/ARCHITECTURE.md +++ b/TelegramDownloader/ClientApp/ARCHITECTURE.md @@ -226,6 +226,14 @@ not import TFM code. TFM providers and actions live in the app: providers' `list`) and the listings are invalidated when it ends. `` (layout, bottom left of the content) lazy-loads the stacked cards; the transfers popover lists the running ones under "Other operations". + `files/cue/`: cue sheets (an album in one audio file). Opening a `.cue` shows its tracks + (`GET .../files/{id}/cue`, `GET /api/v1/local/cue`); each track is queued as an `AudioTrack` + with a `clip` (`start`/`end` in seconds of the file). The engine plays clips in file time and + shows track time (`player/clip.ts`); consecutive clips of one file continue without reloading. + `files/audioInfo.ts`: the channel provider asks `POST .../files/audio-info` (capability + `files.audioInfo`, batches of 500, in the background) for the audio files it lists; the rows show + "Performer – Title · duration" through the file manager's `describeEntry`, and `toTrack()` uses + title/artist/duration/cover as the initial metadata of queued tracks. - `features/channels/`: channel provider (`createChannelProvider`, also used read only for shared collections with `collectionId`), TFM actions, header (refresh with live progress, export/import index, WebDAV, statistics, delete index, link to the chat view). diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelActions.ts b/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelActions.ts index fa461ef..9822794 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelActions.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelActions.ts @@ -50,7 +50,7 @@ export function channelActions({ channelId, channelName, collectionId, openDialo order: 11, run: (entries) => openDialog({ type: 'download', entries }) }, - ...mediaActions({ channelId, sourceName: channelName }) + ...mediaActions({ channelId, collectionId, sourceName: channelName }) ]; if (!own) return actions; diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelProvider.ts b/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelProvider.ts index 4fa5011..8db3a43 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelProvider.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/channels/lib/channelProvider.ts @@ -1,5 +1,6 @@ -import type { FileEntry, FileSystemProvider, Page, ProviderCapabilities } from '@tfm/file-manager'; +import { entryMediaKind, type FileEntry, type FileSystemProvider, type Page, type ProviderCapabilities } from '@tfm/file-manager'; import { toast } from '@tfm/ui'; +import { getAudioInfo, loadAudioInfo } from '@/features/files/audioInfo'; import { downloadUrls, uploadBody, xhrUpload } from '@/features/files/browser'; import { withoutPendingDeletes } from '@/features/files/deletes/deleteStore'; import { startDelete } from '@/features/files/deletes/deleteTracker'; @@ -53,6 +54,13 @@ export function createChannelProvider({ channelId, rootName, collectionId }: Cha const id = channelProviderId(channelId, collectionId); + // Telegram's title/performer/duration/cover of the audio files shown, in the background + const withAudioInfo = (items: FileEntry[]) => { + const audio = items.filter((e) => e.kind === 'file' && entryMediaKind(e) === 'audio').map((e) => e.id); + if (audio.length) void loadAudioInfo(channelId, audio, collectionId); + return items; + }; + return { id, rootName, @@ -74,7 +82,7 @@ export function createChannelProvider({ channelId, rootName, collectionId }: Cha ); let items = withoutPendingDeletes(id, res.contents.items.map(toEntry)); if (options?.filter?.kind) items = items.filter((e) => e.kind === options.filter?.kind); - return page(items, res.page); + return page(withAudioInfo(items), res.page); }, async search(path, query, options) { @@ -91,7 +99,7 @@ export function createChannelProvider({ channelId, rootName, collectionId }: Cha }, options?.signal ); - return page(withoutPendingDeletes(id, res.items.map(toEntry)), res.page); + return page(withAudioInfo(withoutPendingDeletes(id, res.items.map(toEntry))), res.page); }, async createFolder(parentPath, name) { @@ -134,6 +142,7 @@ export function createChannelProvider({ channelId, rootName, collectionId }: Cha }, previewUrl: (entry) => (entry.kind === 'file' ? dtoOf(entry).contentUrl ?? undefined : undefined), - thumbnailUrl: (entry) => dtoOf(entry)?.thumbnailUrl ?? undefined + // Audio files show the cover Telegram keeps for them, once the details have arrived + thumbnailUrl: (entry) => dtoOf(entry)?.thumbnailUrl ?? (entry.kind === 'file' ? getAudioInfo(channelId, entry.id, collectionId)?.coverUrl : undefined) }; } diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/channels/pages/ChannelPage.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/channels/pages/ChannelPage.tsx index 5b60bdc..54c3eeb 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/channels/pages/ChannelPage.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/channels/pages/ChannelPage.tsx @@ -6,6 +6,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import { useNavigate, useParams } from 'react-router'; import { DownloadToServerDialog } from '@/features/files/DownloadToServerDialog'; import { confirmDelete, fmLocale, reportError, reportSuccess } from '@/features/files/fileManagerOptions'; +import { useEntryDescriber } from '@/features/files/describeEntry'; import { openMedia } from '@/features/files/media'; import { fileManagerStrings } from '@/features/files/strings'; import { useRoutePath } from '@/features/files/useRoutePath'; @@ -39,6 +40,7 @@ export default function ChannelPage() { }, [detail.data?.name]); const provider = useMemo(() => createChannelProvider({ channelId, rootName: name }), [channelId, name]); + const describeEntry = useEntryDescriber(channelId); const navigate = useNavigate(); const openMessage = useCallback((messageId: number) => void navigate(`/chat/${encodeURIComponent(channelId)}?message=${messageId}`), [channelId, navigate]); const actions = useMemo(() => channelActions({ channelId, channelName: name, openDialog: setDialog, openMessage }), [channelId, name, openMessage]); @@ -73,6 +75,7 @@ export default function ChannelPage() { } }) } + describeEntry={describeEntry} className="flex-1" /> ); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.test.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.test.ts new file mode 100644 index 0000000..ffe0b64 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.test.ts @@ -0,0 +1,92 @@ +import type { ApiAudioInfoDto } from '@tfm/api-client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('@/lib/api', () => ({ api: { files: { audioInfo: vi.fn() }, system: { capabilities: vi.fn() } } })); + +const { api } = await import('@/lib/api'); +const { resetServerFeatures } = await import('@/lib/serverFeatures'); +const info = await import('./audioInfo'); +const { describeEntry } = await import('./describeEntry'); +const { toTrack, toEntry } = await import('./entries'); + +const audioInfo = vi.mocked(api.files.audioInfo); +const capabilities = vi.mocked(api.system.capabilities); + +const answer = (ids: string[]): ApiAudioInfoDto[] => + ids.map((id) => ({ fileId: id, title: `T ${id}`, performer: 'P', duration: 200, hasCover: true, coverUrl: `/thumb/${id}` })); + +beforeEach(() => { + info.__resetAudioInfoForTests(); + resetServerFeatures(); + audioInfo.mockReset(); + capabilities.mockReset(); + capabilities.mockResolvedValue({ apiVersion: 1, serverVersion: 'x', features: ['files.audioInfo'] }); + audioInfo.mockImplementation(async (_c, body) => answer(body.fileIds)); +}); + +afterEach(() => vi.clearAllMocks()); + +describe('audio info', () => { + it('splits the ids into batches of 500', () => { + const ids = Array.from({ length: 1201 }, (_, i) => `f${i}`); + expect(info.batches(ids).map((b) => b.length)).toEqual([500, 500, 201]); + }); + + it('asks in batches, merges the answers and caches them per channel', async () => { + const ids = Array.from({ length: 501 }, (_, i) => `f${i}`); + await info.loadAudioInfo('42', ids); + expect(audioInfo).toHaveBeenCalledTimes(2); + expect(audioInfo.mock.calls[0][1].fileIds).toHaveLength(500); + expect(audioInfo.mock.calls[1][1].fileIds).toEqual(['f500']); + expect(info.getAudioInfo('42', 'f7')).toEqual({ title: 'T f7', performer: 'P', duration: 200, coverUrl: '/thumb/f7' }); + expect(info.getAudioInfo('43', 'f7')).toBeUndefined(); // another channel + + await info.loadAudioInfo('42', ['f1', 'f2', 'new']); + expect(audioInfo).toHaveBeenCalledTimes(3); + expect(audioInfo.mock.calls[2][1].fileIds).toEqual(['new']); // only what is not known + }); + + it('keeps collections apart and sends their id', async () => { + await info.loadAudioInfo('42', ['a'], 'col'); + expect(audioInfo.mock.calls[0][1]).toEqual({ fileIds: ['a'], collectionId: 'col' }); + expect(info.getAudioInfo('42', 'a', 'col')?.title).toBe('T a'); + expect(info.getAudioInfo('42', 'a')).toBeUndefined(); + }); + + it('remembers files Telegram has nothing for, and ignores failures', async () => { + audioInfo.mockResolvedValueOnce([{ fileId: 'a', hasCover: false }]); + await info.loadAudioInfo('42', ['a', 'b']); + expect(info.getAudioInfo('42', 'a')).toBeNull(); + expect(info.getAudioInfo('42', 'b')).toBeNull(); // missing from the answer + + audioInfo.mockRejectedValueOnce(new Error('boom')); + await expect(info.loadAudioInfo('42', ['c'])).resolves.toBeUndefined(); + expect(info.getAudioInfo('42', 'c')).toBeUndefined(); // asked again later + }); + + it('does not call an older server without the capability', async () => { + capabilities.mockResolvedValue({ apiVersion: 1, serverVersion: 'x', features: [] }); + await info.loadAudioInfo('42', ['a']); + expect(audioInfo).not.toHaveBeenCalled(); + expect(info.getAudioInfo('42', 'a')).toBeNull(); + }); + + it('labels and describes audio rows', async () => { + expect(info.audioInfoLabel({ title: 'Song', performer: 'Band' })).toBe('Band – Song'); + expect(info.audioInfoLabel({ title: 'Song' })).toBe('Song'); + const song = toEntry({ id: 's', name: 'Album.flac', path: '/', isFile: true, size: 1, category: 'Audio', type: '.flac' } as never); + const cue = toEntry({ id: 'c', name: 'album.cue', path: '/', isFile: true, size: 1, category: 'Document', type: '.cue' } as never); + const other = toEntry({ id: 'o', name: 'other.mp3', path: '/', isFile: true, size: 1, category: 'Audio', type: '.mp3' } as never); + const entries = [song, cue, other]; + expect(describeEntry(song, entries, { title: 'Song', performer: 'Band', duration: 225 })).toEqual({ subtitle: 'Band – Song', meta: ['3:45'], badge: 'CUE' }); + expect(describeEntry(cue, entries, undefined)).toEqual({ subtitle: undefined, meta: undefined, badge: 'CUE' }); + expect(describeEntry(other, entries, null)).toBeUndefined(); + }); + + it('queued tracks start with the Telegram details', async () => { + await info.loadAudioInfo('42', ['s']); + const song = toEntry({ id: 's', name: 'track01.mp3', path: '/', isFile: true, size: 1, category: 'Audio', type: '.mp3', contentUrl: '/c/s' } as never); + expect(toTrack(song, { channelId: '42' })).toMatchObject({ title: 'T s', artist: 'P', durationSeconds: 200, coverUrl: '/thumb/s', url: '/c/s' }); + expect(toTrack(song, { channelId: '99' })).toMatchObject({ title: 'track01', artist: undefined }); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.ts new file mode 100644 index 0000000..37a5e92 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/audioInfo.ts @@ -0,0 +1,122 @@ +import type { ApiAudioInfoDto } from '@tfm/api-client'; +import { create } from 'zustand'; +import { api } from '@/lib/api'; +import { hasServerFeature } from '@/lib/serverFeatures'; + +/** + * The title, performer, duration and cover Telegram keeps for audio + * documents (`POST /api/v1/channels/{id}/files/audio-info`), read without + * downloading the files. The channel listings ask for the audio files they + * show, in the background; the rows and the tracks queued from them use the + * answers. Kept in memory per channel (or shared collection) + file id. + */ + +export const AUDIO_INFO_FEATURE = 'files.audioInfo'; +/** Most ids one request may carry (the server limit). */ +export const AUDIO_INFO_BATCH = 500; + +export interface AudioInfo { + title?: string; + performer?: string; + /** Seconds. */ + duration?: number; + coverUrl?: string; +} + +interface AudioInfoState { + /** null = asked, Telegram has nothing for the file. */ + byKey: Record; +} + +export const useAudioInfo = create()(() => ({ byKey: {} })); + +const inflight = new Set(); + +/** Cache scope of a channel, or of a shared collection of it. */ +export function audioInfoScope(channelId: string, collectionId?: string): string { + return collectionId ? `${channelId}@${collectionId}` : channelId; +} + +/** Store key of a file. */ +export function audioInfoKey(scope: string, fileId: string): string { + return `${scope}:${fileId}`; +} + +/** What is known of a file: details, null (nothing) or undefined (not asked yet). */ +export function getAudioInfo(channelId: string, fileId: string, collectionId?: string): AudioInfo | null | undefined { + return useAudioInfo.getState().byKey[audioInfoKey(audioInfoScope(channelId, collectionId), fileId)]; +} + +/** The useful part of an answer, or null when Telegram has nothing. */ +export function toAudioInfo(dto: ApiAudioInfoDto): AudioInfo | null { + const info: AudioInfo = {}; + if (dto.title?.trim()) info.title = dto.title.trim(); + if (dto.performer?.trim()) info.performer = dto.performer.trim(); + if (dto.duration && dto.duration > 0) info.duration = dto.duration; + if (dto.hasCover && dto.coverUrl) info.coverUrl = dto.coverUrl; + return Object.keys(info).length ? info : null; +} + +/** "Performer – Title", or whichever of the two is known. */ +export function audioInfoLabel(info: AudioInfo | null | undefined): string | undefined { + if (!info) return undefined; + if (info.performer && info.title) return `${info.performer} – ${info.title}`; + return info.title ?? info.performer; +} + +/** Splits `items` into chunks of at most `size`. */ +export function batches(items: T[], size = AUDIO_INFO_BATCH): T[][] { + const out: T[][] = []; + for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size)); + return out; +} + +/** + * Asks the server for the details of the files not known yet (in batches of + * 500) and merges the answers into the store. Never throws: a failed batch + * is simply asked again by a later listing. Ids missing from an answer are + * remembered as "nothing". + */ +export async function loadAudioInfo(channelId: string, fileIds: string[], collectionId?: string): Promise { + if (!channelId || fileIds.length === 0) return; + const scope = audioInfoScope(channelId, collectionId); + const known = useAudioInfo.getState().byKey; + const wanted = [...new Set(fileIds)].filter((id) => { + const key = audioInfoKey(scope, id); + return !(key in known) && !inflight.has(key); + }); + if (wanted.length === 0) return; + wanted.forEach((id) => inflight.add(audioInfoKey(scope, id))); + try { + if (!(await hasServerFeature(AUDIO_INFO_FEATURE))) { + // An older server: remember "nothing" so the listings stop asking + merge(scope, wanted, []); + return; + } + await Promise.all( + batches(wanted).map(async (ids) => { + try { + const answer = await api.files.audioInfo(channelId, { fileIds: ids, collectionId }); + merge(scope, ids, answer ?? []); + } catch { + // Ignored: the listing works without the details + } + }) + ); + } finally { + wanted.forEach((id) => inflight.delete(audioInfoKey(scope, id))); + } +} + +function merge(scope: string, asked: string[], answer: ApiAudioInfoDto[]): void { + const update: Record = {}; + for (const id of asked) update[audioInfoKey(scope, id)] = null; + for (const dto of answer) if (dto?.fileId) update[audioInfoKey(scope, dto.fileId)] = toAudioInfo(dto); + useAudioInfo.setState((s) => ({ byKey: { ...s.byKey, ...update } })); +} + +/** Test helper: forget everything. */ +export function __resetAudioInfoForTests(): void { + inflight.clear(); + useAudioInfo.setState({ byKey: {} }); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetDialog.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetDialog.tsx new file mode 100644 index 0000000..00e6afd --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetDialog.tsx @@ -0,0 +1,136 @@ +import { useQuery } from '@tanstack/react-query'; +import { Button, cn, Dialog, DialogContent, IconButton, Skeleton } from '@tfm/ui'; +import { AlertTriangle, ListEnd, ListVideo, Play } from 'lucide-react'; +import { useMemo } from 'react'; +import { formatTime } from '@/features/player/format'; +import { enqueueAudio, playAudio } from '@/features/player/public'; +import { t } from '@/i18n'; +import { api, errorMessage } from '@/lib/api'; +import { cueRows, playableFrom, type CueRow } from './cueModel'; +import { closeCueSheet, useCueSheet, type CueRequest } from './cueStore'; + +function fetchSheet(request: CueRequest, signal: AbortSignal) { + if (request.local) return api.local.cue({ path: request.id }, signal); + return api.files.cue(request.channelId ?? '', request.id, { collectionId: request.collectionId }, signal); +} + +/** A cue sheet as an album: its tracks, play all / from a track, add to the queue. */ +export default function CueSheetDialog() { + const request = useCueSheet((s) => s.request); + const { data: sheet, error, isLoading } = useQuery({ + queryKey: ['files', 'cue', request?.local ? 'local' : (request?.channelId ?? ''), request?.collectionId ?? '', request?.id ?? ''], + queryFn: ({ signal }) => fetchSheet(request as CueRequest, signal), + enabled: !!request, + staleTime: 60_000 + }); + const rows = useMemo(() => (sheet && request ? cueRows(sheet, request) : []), [sheet, request]); + const playable = useMemo(() => playableFrom(rows), [rows]); + + if (!request) return null; + + const play = (fromNumber?: number) => { + const { tracks, index } = playableFrom(rows, fromNumber); + if (tracks.length === 0) return; + playAudio(tracks, index); + closeCueSheet(); + }; + const enqueue = (tracks: CueRow['track'][], position: 'next' | 'end') => { + const list = tracks.filter((x): x is NonNullable => !!x); + if (list.length) enqueueAudio(list, position); + }; + + const description = sheet + ? [sheet.performer, sheet.date, sheet.genre, t('{count} tracks', { count: sheet.tracks.length })].filter(Boolean).join(' · ') + : request.name; + + return ( + !open && closeCueSheet()}> + + + + + } + > + {error ? ( +
+ + + {t('Could not read the cue sheet')} + {errorMessage(error)} + +
+ ) : null} + + {sheet && sheet.missingFiles.length > 0 && ( +

+ + {t('Audio files not found next to the cue sheet: {names}', { names: sheet.missingFiles.join(', ') })} +

+ )} + +
    + {isLoading && + Array.from({ length: 6 }, (_, i) => ( +
  1. + +
  2. + ))} + {sheet && rows.length === 0 &&
  3. {t('The cue sheet has no tracks')}
  4. } + {rows.map((row) => { + const missing = !row.track; + return ( +
  5. + + {!missing && ( + + enqueue([row.track], 'next')}> + + + enqueue([row.track], 'end')}> + + + + )} +
  6. + ); + })} +
+
+
+ ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetSlot.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetSlot.tsx new file mode 100644 index 0000000..1bc3e73 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/CueSheetSlot.tsx @@ -0,0 +1,15 @@ +import { lazy, Suspense } from 'react'; +import { useCueSheet } from './cueStore'; + +const CueSheetDialog = lazy(() => import('./CueSheetDialog')); + +/** Mounts the cue sheet dialog (lazy) while it is open. Rendered by the player slot. */ +export function CueSheetSlot() { + const open = useCueSheet((s) => s.request !== null); + if (!open) return null; + return ( + + + + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.test.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.test.ts new file mode 100644 index 0000000..478f3b7 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.test.ts @@ -0,0 +1,92 @@ +import type { ApiCueSheetDto, ApiFileDto } from '@tfm/api-client'; +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('@/lib/api', () => ({ api: { files: { audioInfo: vi.fn() }, system: { capabilities: vi.fn() } } })); + +const { cueRows, cueTrackToAudio, isCueName, playableFrom } = await import('./cueModel'); + +const file = (id: string, name: string): ApiFileDto => + ({ + id, + name, + path: '/music/', + isFile: true, + size: 300_000_000, + category: 'Audio', + contentUrl: `/api/v1/channels/1/files/${id}/content`, + playbackUrl: `/api/v1/channels/1/files/${id}/content` + }) as ApiFileDto; + +const sheet: ApiCueSheetDto = { + id: 'cue1', + name: 'Album.cue', + title: 'The Album', + performer: 'The Band', + date: '1999', + genre: 'Rock', + missingFiles: ['bonus.wav'], + tracks: [ + { number: 1, title: 'Intro', performer: null, start: 0, end: 62.5, fileName: 'Album.wav', file: file('f1', 'Album.flac') }, + { number: 2, title: '', performer: 'Guest', start: 62.5, end: 300, fileName: 'Album.wav', file: file('f1', 'Album.flac') }, + { number: 3, title: 'Outro', start: 300, end: null, fileName: 'Album.wav', file: file('f1', 'Album.flac') }, + { number: 4, title: 'Bonus', start: 0, end: null, fileName: 'bonus.wav', file: null } + ] +}; + +describe('cue sheet → player tracks', () => { + it('maps a track to a clip of its file', () => { + const track = cueTrackToAudio(sheet, sheet.tracks[0], { channelId: '1', sourceName: 'Music' }); + expect(track).toEqual({ + id: 'cue:cue1#1', + title: 'Intro', + artist: 'The Band', + album: 'The Album', + source: 'Music', + url: '/api/v1/channels/1/files/f1/content', + channelId: '1', + fileId: 'f1', + localPath: undefined, + size: 300_000_000, + clip: { start: 0, end: 62.5 } + }); + }); + + it('falls back to "Track N" and to the track performer, and plays the last track to the end of the file', () => { + const second = cueTrackToAudio(sheet, sheet.tracks[1], { channelId: '1' }); + expect(second?.title).toBe('Track 2'); + expect(second?.artist).toBe('Guest'); + expect(cueTrackToAudio(sheet, sheet.tracks[2], { channelId: '1' })?.clip).toEqual({ start: 300, end: null }); + }); + + it('has no track for a missing file', () => { + expect(cueTrackToAudio(sheet, sheet.tracks[3], { channelId: '1' })).toBeNull(); + }); + + it('local sheets use local paths', () => { + const track = cueTrackToAudio({ ...sheet, id: 'music/Album.cue' }, { ...sheet.tracks[0], file: file('music/Album.flac', 'Album.flac') }, { local: true }); + expect(track?.id).toBe('cue:local:music/Album.cue#1'); + expect(track?.localPath).toBe('music/Album.flac'); + expect(track?.channelId).toBeUndefined(); + expect(track?.fileId).toBeUndefined(); + }); + + it('builds the rows with durations, and the playable queue from a track', () => { + const rows = cueRows(sheet, { channelId: '1' }); + expect(rows.map((r) => [r.number, r.title, r.duration])).toEqual([ + [1, 'Intro', 62.5], + [2, 'Track 2', 237.5], + [3, 'Outro', undefined], + [4, 'Bonus', undefined] + ]); + expect(rows[3].track).toBeNull(); + const all = playableFrom(rows); + expect(all.tracks.map((t) => t.id)).toEqual(['cue:cue1#1', 'cue:cue1#2', 'cue:cue1#3']); + expect(all.index).toBe(0); + expect(playableFrom(rows, 3).index).toBe(2); + }); + + it('recognises cue files', () => { + expect(isCueName('Album.CUE')).toBe(true); + expect(isCueName('Album.cue.txt')).toBe(false); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.ts new file mode 100644 index 0000000..e3dab39 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueModel.ts @@ -0,0 +1,86 @@ +import type { ApiCueSheetDto, ApiCueTrackDto } from '@tfm/api-client'; +import type { AudioTrack } from '@/features/player/public'; +import { t } from '@/i18n'; +import { audioUrlOf } from '../entries'; + +/** Where a cue sheet lives and how its tracks are labelled in the player. */ +export interface CueSource { + /** Channel of the sheet (undefined for local files). */ + channelId?: string; + /** Shared collection the sheet is read from. */ + collectionId?: string; + /** Local files: the URLs of the matched files are local ones. */ + local?: boolean; + /** Label shown by the player under the title (channel name, "Local files"...). */ + sourceName?: string; +} + +/** One row of the cue sheet dialog. */ +export interface CueRow { + number: number; + title: string; + performer?: string; + /** Seconds (end - start); undefined for the last track of a file (its end is the end of the file). */ + duration?: number; + /** The player track, or null when its audio file is missing. */ + track: AudioTrack | null; + /** The file name as written in the sheet (shown for missing files). */ + fileName: string; +} + +const clean = (s: string | null | undefined) => (s?.trim() ? s.trim() : undefined); + +/** "Track 3" when the sheet has no title for it. */ +export function cueTrackTitle(track: Pick): string { + return clean(track.title) ?? t('Track {number}', { number: track.number }); +} + +/** A cue track as a player track: the matched file clipped to the track. */ +export function cueTrackToAudio(sheet: ApiCueSheetDto, track: ApiCueTrackDto, source: CueSource): AudioTrack | null { + const file = track.file; + if (!file) return null; + const url = audioUrlOf(file); + if (!url) return null; + const end = track.end != null && track.end > track.start ? track.end : null; + return { + id: `cue:${source.local ? 'local:' : ''}${sheet.id}#${track.number}`, + title: cueTrackTitle(track), + artist: clean(track.performer) ?? clean(sheet.performer), + album: clean(sheet.title), + source: source.sourceName, + url, + channelId: source.local ? undefined : source.channelId, + fileId: source.local ? undefined : file.id, + localPath: source.local ? file.id : undefined, + size: file.size, + clip: { start: Math.max(0, track.start), end } + }; +} + +/** The rows of a sheet, in its order. */ +export function cueRows(sheet: ApiCueSheetDto, source: CueSource): CueRow[] { + return (sheet.tracks ?? []).map((track) => { + const end = track.end != null && track.end > track.start ? track.end : undefined; + return { + number: track.number, + title: cueTrackTitle(track), + performer: clean(track.performer) ?? clean(sheet.performer), + duration: end !== undefined ? end - track.start : undefined, + track: cueTrackToAudio(sheet, track, source), + fileName: track.fileName + }; + }); +} + +/** The playable tracks of `rows` and where `fromNumber` (a track number) sits among them. */ +export function playableFrom(rows: CueRow[], fromNumber?: number): { tracks: AudioTrack[]; index: number } { + const playable = rows.filter((r) => r.track); + const tracks = playable.map((r) => r.track as AudioTrack); + const index = fromNumber === undefined ? 0 : Math.max(0, playable.findIndex((r) => r.number === fromNumber)); + return { tracks, index }; +} + +/** True for a `.cue` file name. */ +export function isCueName(name: string): boolean { + return /\.cue$/i.test(name); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueStore.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueStore.ts new file mode 100644 index 0000000..adeb6f0 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/cue/cueStore.ts @@ -0,0 +1,21 @@ +import { create } from 'zustand'; +import type { CueSource } from './cueModel'; + +/** A cue sheet to open: the entry id (channel) or relative path (local) of the `.cue` file. */ +export interface CueRequest extends CueSource { + /** Channel entry id, or the relative path for local files. */ + id: string; + name: string; +} + +/** State of the cue sheet dialog (the dialog itself is lazy). */ +export const useCueSheet = create<{ request: CueRequest | null }>()(() => ({ request: null })); + +/** Opens the cue sheet dialog (tracks of the album, play / queue). */ +export function openCueSheet(request: CueRequest): void { + useCueSheet.setState({ request }); +} + +export function closeCueSheet(): void { + useCueSheet.setState({ request: null }); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/deleteTracker.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/deleteTracker.ts index 74e4b18..8f07a2f 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/deleteTracker.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/deletes/deleteTracker.ts @@ -6,6 +6,7 @@ import { api, errorMessage } from '@/lib/api'; import { queryClient } from '@/lib/queryClient'; import { queryKeys } from '@/lib/queryKeys'; import { getEventsHub, useRealtime } from '@/lib/realtime'; +import { resetServerFeatures, serverFeatures } from '@/lib/serverFeatures'; import { isActiveDelete, statusFromProgress, useDeletes, type TrackedDelete } from './deleteStore'; /** @@ -40,20 +41,6 @@ export interface StartDeleteRequest { entries: FileEntry[]; } -let capabilities: Promise> | null = null; - -/** Optional features of the server (an old server answers 404: none). Cached for the session. */ -export function serverFeatures(): Promise> { - capabilities ??= api.system - .capabilities() - .then((c) => new Set(c?.features ?? [])) - .catch(() => { - capabilities = null; // try again next time (it may have been a network blip) - return new Set(); - }); - return capabilities; -} - let nextKey = 1; export async function startDelete(request: StartDeleteRequest): Promise { @@ -262,7 +249,7 @@ export async function pollOnce(now = Date.now()): Promise { /** Test helper: forget the module state. */ export function __resetDeleteTrackerForTests(): void { - capabilities = null; + resetServerFeatures(); hubListening = false; if (pollTimer) clearInterval(pollTimer); pollTimer = null; diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/describeEntry.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/describeEntry.ts new file mode 100644 index 0000000..90e98ff --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/describeEntry.ts @@ -0,0 +1,50 @@ +import { entryMediaKind, type EntryDescription, type FileEntry } from '@tfm/file-manager'; +import { useCallback } from 'react'; +import { formatTime } from '@/features/player/format'; +import { audioInfoKey, audioInfoLabel, audioInfoScope, useAudioInfo, type AudioInfo } from './audioInfo'; +import { isCueName } from './cue/cueModel'; + +const CUE_BADGE = 'CUE'; + +const baseName = (name: string) => { + const i = name.lastIndexOf('.'); + return (i > 0 ? name.slice(0, i) : name).toLowerCase(); +}; + +// Base names of the cue sheets of a listing, computed once per listing array +const cueNamesCache = new WeakMap>(); +function cueBaseNames(entries: FileEntry[]): Set { + let names = cueNamesCache.get(entries); + if (!names) { + names = new Set(entries.filter((e) => e.kind === 'file' && isCueName(e.name)).map((e) => baseName(e.name))); + cueNamesCache.set(entries, names); + } + return names; +} + +/** + * What a row of the listing shows besides the file: "Performer – Title" and + * the duration of Telegram audio, and a "CUE" badge on cue sheets and on the + * audio file a cue sheet of the same name describes. Pure, for the tests. + */ +export function describeEntry(entry: FileEntry, entries: FileEntry[], info: AudioInfo | null | undefined): EntryDescription | undefined { + if (entry.kind !== 'file') return undefined; + const cueBadge = isCueName(entry.name) || (entryMediaKind(entry) === 'audio' && cueBaseNames(entries).has(baseName(entry.name))); + const subtitle = audioInfoLabel(info); + const meta = info?.duration ? [formatTime(info.duration)] : undefined; + if (!cueBadge && !subtitle && !meta) return undefined; + return { subtitle, meta, badge: cueBadge ? CUE_BADGE : undefined }; +} + +/** + * `describeEntry` of a file manager. With a channel it follows the audio + * details store, so the rows update when the details arrive. + */ +export function useEntryDescriber(channelId?: string, collectionId?: string) { + const byKey = useAudioInfo((s) => s.byKey); + const scope = channelId ? audioInfoScope(channelId, collectionId) : null; + return useCallback( + (entry: FileEntry, entries: FileEntry[]) => describeEntry(entry, entries, scope ? byKey[audioInfoKey(scope, entry.id)] : undefined), + [byKey, scope] + ); +} diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/entries.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/entries.ts index 189945e..5eca9e9 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/files/entries.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/entries.ts @@ -1,6 +1,7 @@ import type { ApiFileDto, BrowseFilter, BrowseSortBy } from '@tfm/api-client'; import { entryMediaKind, extensionOf, joinPath, mediaKindOf, normalizePath, type FileEntry, type ListFilter, type MediaKind, type SortSpec } from '@tfm/file-manager'; import type { AudioTrack, ViewerItem } from '@/features/player/public'; +import { getAudioInfo } from './audioInfo'; const CATEGORY_KIND: Record = { Audio: 'audio', @@ -65,18 +66,31 @@ function stripExtension(name: string) { return i > 0 ? name.slice(0, i) : name; } -/** An audio entry as a player track. */ -export function toTrack(entry: FileEntry, source: { channelId?: string; sourceName?: string; local?: boolean }): AudioTrack { +/** Playable URL of an audio DTO (same-origin). */ +export function audioUrlOf(dto: ApiFileDto): string { + return dto.playbackUrl ?? dto.streamUrl ?? dto.contentUrl ?? ''; +} + +/** + * An audio entry as a player track. Channel files take the title, artist, + * duration and cover Telegram keeps for them when the listing already has + * them (`audioInfo.ts`), so the player shows them before the file loads. + */ +export function toTrack(entry: FileEntry, source: { channelId?: string; collectionId?: string; sourceName?: string; local?: boolean }): AudioTrack { const dto = dtoOf(entry); + const info = !source.local && source.channelId ? getAudioInfo(source.channelId, dto.id, source.collectionId) : undefined; return { id: source.local ? `local:${dto.id}` : dto.id, - title: stripExtension(entry.name), + title: info?.title ?? stripExtension(entry.name), + artist: info?.performer, source: source.sourceName, - url: dto.playbackUrl ?? dto.streamUrl ?? dto.contentUrl ?? '', + url: audioUrlOf(dto), + coverUrl: info?.coverUrl, channelId: source.local ? undefined : source.channelId, fileId: source.local ? undefined : dto.id, localPath: source.local ? dto.id : undefined, - size: dto.size + size: dto.size, + durationSeconds: info?.duration }; } diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/files/media.ts b/TelegramDownloader/ClientApp/apps/web/src/features/files/media.ts index 2ea22b7..13ecdba 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/files/media.ts +++ b/TelegramDownloader/ClientApp/apps/web/src/features/files/media.ts @@ -1,16 +1,20 @@ import { createElement } from 'react'; import { entryMediaKind, type FileAction, type FileEntry } from '@tfm/file-manager'; import { toast } from '@tfm/ui'; -import { Link2, ListEnd, ListPlus, ListVideo, Play } from 'lucide-react'; +import { Disc3, Link2, ListEnd, ListPlus, ListVideo, Play } from 'lucide-react'; import { enqueueAudio, openViewer, playAudio } from '@/features/player/public'; import { openAddToPlaylist, type PlaylistCandidate } from '@/features/playlists/public'; import { t } from '@/i18n'; import { absoluteUrl, copyText } from './browser'; +import { isCueName } from './cue/cueModel'; +import { openCueSheet } from './cue/cueStore'; import { dtoOf, toTrack, toViewerItem, viewerKind } from './entries'; export interface MediaSource { /** Channel holding the files (undefined for local files). */ channelId?: string; + /** Shared collection the files are read from. */ + collectionId?: string; /** Label shown by the player under the title. */ sourceName?: string; local?: boolean; @@ -22,6 +26,19 @@ export interface MediaSource { } const isAudio = (e: FileEntry) => e.kind === 'file' && entryMediaKind(e) === 'audio'; +const isCue = (e: FileEntry) => e.kind === 'file' && isCueName(e.name); + +/** Opens the tracks of a `.cue` file (an album in one audio file). */ +function openCue(entry: FileEntry, source: MediaSource): void { + openCueSheet({ + id: dtoOf(entry).id, + name: entry.name, + channelId: source.channelId, + collectionId: source.collectionId, + local: source.local, + sourceName: source.sourceName + }); +} /** * Opens a file with the app's player/viewer: audio plays with the folder's @@ -29,6 +46,10 @@ const isAudio = (e: FileEntry) => e.kind === 'file' && entryMediaKind(e) === 'au * PDF and text in the viewer. Returns false for other files. */ export function openMedia(entry: FileEntry, folderEntries: FileEntry[], source: MediaSource): boolean { + if (isCue(entry) && (source.local || source.channelId)) { + openCue(entry, source); + return true; + } const kind = viewerKind(entry); if (kind === 'audio') { const audios = folderEntries.filter(isAudio); @@ -62,6 +83,16 @@ function playlistCandidates(entries: FileEntry[], source: MediaSource): Playlist export function mediaActions(source: MediaSource): FileAction[] { const allAudio = (entries: FileEntry[]) => entries.length > 0 && entries.every(isAudio); return [ + { + id: 'tfm:open-cue', + label: t('Open as an album'), + icon: createElement(Disc3), + selection: 'single', + group: 'a-open', + order: 1, + when: ([e]) => isCue(e) && !!(source.local || source.channelId), + run: ([e]) => openCue(e, source) + }, { id: 'tfm:play', label: t('Play'), diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx index c1775be..c389330 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/local/pages/LocalFilesPage.tsx @@ -3,6 +3,7 @@ import { CloudUpload, HardDrive } from 'lucide-react'; import { useMemo, useState } from 'react'; import { dtoOf } from '@/features/files/entries'; import { confirmDelete, fmLocale, reportError, reportSuccess } from '@/features/files/fileManagerOptions'; +import { useEntryDescriber } from '@/features/files/describeEntry'; import { mediaActions, openMedia, type MediaSource } from '@/features/files/media'; import { localRel } from '@/features/files/local'; import { fileManagerStrings } from '@/features/files/strings'; @@ -22,6 +23,7 @@ export default function LocalFilesPage() { const singleClickFolders = useUi((s) => s.singleClickFolders); const [uploading, setUploading] = useState(null); const provider = useMemo(() => createLocalProvider(t('Local files')), []); + const describeEntry = useEntryDescriber(); const source: MediaSource = useMemo( () => ({ @@ -76,6 +78,7 @@ export default function LocalFilesPage() { onError={reportError} onSuccess={reportSuccess} onOpen={(entry, fm) => openMedia(entry, fm.entries, source)} + describeEntry={describeEntry} className="mt-2 flex-1" /> setUploading(null)} /> diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/PlayerSlot.tsx b/TelegramDownloader/ClientApp/apps/web/src/features/player/PlayerSlot.tsx index 7f059c2..b87bee0 100644 --- a/TelegramDownloader/ClientApp/apps/web/src/features/player/PlayerSlot.tsx +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/PlayerSlot.tsx @@ -1,4 +1,5 @@ import { lazy, Suspense, useEffect } from 'react'; +import { CueSheetSlot } from '@/features/files/cue/CueSheetSlot'; import { PlaylistPickerSlot } from '@/features/playlists/PlaylistPickerSlot'; import { selectHasQueue, usePlayer } from './store'; import { useViewer } from './viewerStore'; @@ -43,6 +44,7 @@ export function PlayerSlot() { )} + ); } diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.test.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.test.ts new file mode 100644 index 0000000..e18f479 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { clipDuration, clipOf, continuesInSameFile, hasClip, knownDuration, toFileTime, toTrackRanges, toTrackTime } from './clip'; + +describe('clip arithmetic', () => { + it('normalises clips', () => { + expect(clipOf(undefined)).toEqual({ start: 0 }); + expect(clipOf({ clip: { start: 10, end: null } })).toEqual({ start: 10 }); + expect(clipOf({ clip: { start: -1, end: 20 } })).toEqual({ start: 0, end: 20 }); + expect(clipOf({ clip: { start: 30, end: 20 } })).toEqual({ start: 30 }); // an end before the start is ignored + expect(hasClip({})).toBe(false); + expect(hasClip({ clip: { start: 0, end: null } })).toBe(false); + expect(hasClip({ clip: { start: 0, end: 30 } })).toBe(true); + }); + + it('converts between file and track time', () => { + const c = { start: 30, end: 60 }; + expect(clipDuration(c, 100)).toBe(30); + expect(clipDuration({ start: 60 }, 100)).toBe(40); + expect(clipDuration({ start: 60 }, NaN)).toBeNaN(); + expect(toTrackTime(c, 45, 100)).toBe(15); + expect(toTrackTime(c, 10, 100)).toBe(0); + expect(toTrackTime(c, 80, 100)).toBe(30); + expect(toFileTime(c, 5, 100)).toBe(35); + expect(toFileTime(c, 500, 100)).toBe(60); + expect(toFileTime({ start: 60 }, 500, 100)).toBe(100); + }); + + it('knows the duration before loading', () => { + expect(knownDuration({ clip: { start: 30, end: 75 } })).toBe(45); + expect(knownDuration({ durationSeconds: 200 })).toBe(200); + expect(knownDuration({ clip: { start: 50 }, durationSeconds: 200 })).toBe(150); + expect(knownDuration({ clip: { start: 50 } })).toBeUndefined(); + }); + + it('detects contiguous clips of the same file', () => { + const a = { url: 'u', clip: { start: 0, end: 30 } }; + expect(continuesInSameFile(a, { url: 'u', clip: { start: 30.2 } })).toBe(true); + expect(continuesInSameFile(a, { url: 'u', clip: { start: 45 } })).toBe(false); + expect(continuesInSameFile(a, { url: 'v', clip: { start: 30 } })).toBe(false); + expect(continuesInSameFile({ url: 'u', clip: { start: 60 } }, { url: 'u', clip: { start: 60 } })).toBe(false); + expect(continuesInSameFile(a, { url: 'u' })).toBe(false); + }); + + it('maps buffered ranges into the clip', () => { + expect(toTrackRanges({ start: 30, end: 60 }, [{ start: 0, end: 40 }, { start: 55, end: 90 }], 100)).toEqual([ + { start: 0, end: 10 }, + { start: 25, end: 30 } + ]); + const whole = [{ start: 0, end: 10 }]; + expect(toTrackRanges({ start: 0 }, whole, 100)).toBe(whole); + }); +}); diff --git a/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.ts b/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.ts new file mode 100644 index 0000000..192ce06 --- /dev/null +++ b/TelegramDownloader/ClientApp/apps/web/src/features/player/clip.ts @@ -0,0 +1,94 @@ +import type { AudioTrack } from './public'; + +/** + * Clip arithmetic of the player: a track can be a slice of its audio file + * (cue sheets: one file, many tracks). The