Prima parte della tappa E3 (formati e fotogrammi), solo nel nucleo: il pianificatore, il copiatore e l'archivio delle esportazioni restano alla parte successiva. - Foto: ImageConverter.Check dice prima che cosa succede (copia identica, conversione, copia così com'è con il motivo: HEIC, AVIF, raw, animazioni, file danneggiati, CMYK e oltre 8 bit verso PNG/WEBP, oltre il limite di pixel); la conversione riporta come note ciò che non può portare invece di fermarsi, e la trasparenza verso JPG diventa bianco. I lettori segnalano animazioni, CMYK e segmenti non letti. VP8L usa un logaritmo in virgola fissa, così lo stesso file dà gli stessi byte su ogni sistema. - Video: i lettori ISO e Matroska leggono elenco dei montaggi, lingue, tipo di AAC, MP3 e i vecchi codici AAC di Matroska; Mp4Writer prepara la disposizione e ne conosce la lunghezza prima di scrivere; il nuovo Mp4Remuxer porta in MP4 senza ricodificare, sempre con gli stessi byte. - Fotogrammi: VideoFrameReader trova il campione mostrato a un istante come lo mostra il lettore, lo decodifica esatto a piena risoluzione e lo raddrizza; ExportFrames calcola istanti, suffissi e etichette. - Nomi: il suffisso del fotogramma non si accorcia mai e la numerazione dei nomi liberi viene dopo di lui; SafeFileWriter scrive anche contenuti prodotti mentre li scrive. - MediaConverter e ConversionThrottle preparano una conversione senza sapere dove andrà, una alla volta in tutto il processo. Nuove prove per determinismo, istanti, rotazione, rimux e nomi; tutte le prove di Febe.Tests passano. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
8.7 KiB
C#
174 lines
8.7 KiB
C#
using System.Globalization;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Library;
|
|
|
|
namespace Febe.Core.Export;
|
|
|
|
/// <summary>
|
|
/// How the file name of a copy differs from the library's (tappa E3): the extension of the effective format
|
|
/// («.jpg»; null keeps the source's) and the suffix of a frame («_t0m12s340»; null for none), appended to the stem.
|
|
/// </summary>
|
|
public sealed record ExportNameOptions(string? Extension, string? Suffix);
|
|
|
|
/// <summary>Paths and content types of the export (spec §4.10).</summary>
|
|
public static class ExportPaths
|
|
{
|
|
/// <summary>Folders compare without case on Windows (and its shares), exactly elsewhere, as the import does.</summary>
|
|
public static StringComparison PathComparison { get; } = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
|
|
|
/// <summary>True when <paramref name="path"/> is <paramref name="folder"/> or inside it, as text (full paths).</summary>
|
|
public static bool IsSameOrInside(string path, string folder)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(path);
|
|
ArgumentNullException.ThrowIfNull(folder);
|
|
var p = Trim(path);
|
|
var f = Trim(folder);
|
|
return string.Equals(p, f, PathComparison)
|
|
|| p.StartsWith(f.EndsWith(Path.DirectorySeparatorChar) || f.EndsWith(Path.AltDirectorySeparatorChar) ? f : f + Path.DirectorySeparatorChar, PathComparison);
|
|
}
|
|
|
|
/// <summary>The same folder, as text.</summary>
|
|
public static bool Same(string a, string b) => string.Equals(Trim(a), Trim(b), PathComparison);
|
|
|
|
/// <summary>A full path without its trailing separator (a root such as <c>C:\</c> or <c>/</c> keeps it).</summary>
|
|
public static string Trim(string path)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(path);
|
|
return path.Length > 1 ? Path.TrimEndingDirectorySeparator(path) : path;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The content type of a file (decision D4 of tappa E2): a post photo or video, a story (also a highlight when the
|
|
/// story is in a collection), a highlight, a tagged post, a profile picture. The «Copie» filter repeats it in SQL.
|
|
/// </summary>
|
|
public static ContentTypes TypeOf(EntryKind kind, MediaKind media, bool inHighlight) => kind switch
|
|
{
|
|
EntryKind.Post => media == MediaKind.Photo ? ContentTypes.PostPhotos : ContentTypes.PostVideos,
|
|
EntryKind.Story => inHighlight ? ContentTypes.Stories | ContentTypes.Highlights : ContentTypes.Stories,
|
|
EntryKind.Highlight => ContentTypes.Highlights,
|
|
EntryKind.Tagged => ContentTypes.Tagged,
|
|
EntryKind.ProfilePicture => ContentTypes.ProfilePicture,
|
|
_ => ContentTypes.None,
|
|
};
|
|
|
|
/// <summary>Folder of imported files without a known date or code (as the import names it).</summary>
|
|
public const string ImportedFolder = "importati";
|
|
|
|
/// <summary>
|
|
/// The path of a copy below the destination root, as sanitized segments, before <see cref="RelativePathFor"/>
|
|
/// (decision D18 of tappa E2). «Come la libreria» (a null scheme) renders the library's current scheme again, except
|
|
/// for a file the import left in <c>importati/</c>, which keeps its path. A story in a highlight collection takes the
|
|
/// highlight scheme only when the destination takes highlights and not stories. In the general folder the account
|
|
/// segment comes first.
|
|
/// </summary>
|
|
public static IReadOnlyList<string> Segments(
|
|
ExportDestination d,
|
|
LibraryNaming library,
|
|
Account account,
|
|
Entry entry,
|
|
Media media,
|
|
string? highlightTitle,
|
|
bool inHighlight,
|
|
TimeZoneInfo zone,
|
|
ExportNameOptions? name = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(d);
|
|
ArgumentNullException.ThrowIfNull(library);
|
|
ArgumentNullException.ThrowIfNull(account);
|
|
ArgumentNullException.ThrowIfNull(entry);
|
|
ArgumentNullException.ThrowIfNull(media);
|
|
ArgumentNullException.ThrowIfNull(zone);
|
|
var stored = media.RelativePath is { Length: > 0 } path
|
|
? LibraryLayout.ToStored(path)
|
|
: throw new ArgumentException("Il file non è nella libreria: non ha un percorso.", nameof(media));
|
|
|
|
var renderAs = entry.Kind == EntryKind.Story && inHighlight
|
|
&& d.ContentTypes.HasFlag(ContentTypes.Highlights) && !d.ContentTypes.HasFlag(ContentTypes.Stories)
|
|
? EntryKind.Highlight
|
|
: entry.Kind;
|
|
var use = UseOf(renderAs);
|
|
var text = use switch
|
|
{
|
|
NamingSchemeUse.Highlight => d.HighlightNamingScheme,
|
|
NamingSchemeUse.ProfilePicture => d.ProfileNamingScheme,
|
|
_ => d.NamingScheme,
|
|
};
|
|
|
|
IReadOnlyList<string> segments;
|
|
if (text is null && stored.StartsWith(ImportedFolder + "/", StringComparison.Ordinal))
|
|
{
|
|
segments = stored.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(WindowsFileNames.SanitizeSegment).ToList();
|
|
}
|
|
else
|
|
{
|
|
var scheme = (text is null ? null : NamingScheme.Validate(text, use).Scheme) ?? library.For(renderAs);
|
|
var extension = Path.GetExtension(stored).TrimStart('.').ToLowerInvariant();
|
|
var values = NamingValues.For(
|
|
account.Username,
|
|
entry with { Kind = renderAs },
|
|
media.Position,
|
|
extension,
|
|
renderAs == EntryKind.Highlight ? highlightTitle : null,
|
|
media.Sha256);
|
|
segments = scheme.Render(values, zone);
|
|
}
|
|
|
|
segments = Renamed(segments, name);
|
|
return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments;
|
|
}
|
|
|
|
/// <summary>The last segment with the suffix appended to its stem and the extension of <paramref name="name"/>.</summary>
|
|
private static IReadOnlyList<string> Renamed(IReadOnlyList<string> segments, ExportNameOptions? name)
|
|
{
|
|
if (name is null || segments.Count == 0 || (name.Extension is null && string.IsNullOrEmpty(name.Suffix)))
|
|
{
|
|
return segments;
|
|
}
|
|
|
|
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
|
var fileName = WindowsFileNames.SanitizeSegment(stem + (name.Suffix ?? string.Empty) + (name.Extension ?? extension));
|
|
return [.. segments.Take(segments.Count - 1), fileName];
|
|
}
|
|
|
|
/// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary>
|
|
/// <param name="d">The destination.</param>
|
|
/// <param name="segments">The segments of <see cref="Segments"/>.</param>
|
|
/// <param name="maxPath">The longest full path.</param>
|
|
/// <param name="keepSuffix">The frame suffix of the file name, never cut by the shortening.</param>
|
|
/// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception>
|
|
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(d);
|
|
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath, keepSuffix));
|
|
}
|
|
|
|
/// <summary>
|
|
/// The name the safe writer gives a file at its <paramref name="attempt"/>-th try when the planned name is taken
|
|
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. With
|
|
/// <paramref name="keepSuffix"/> (a frame suffix, <see cref="SafeWriteOptions.KeepSuffix"/>) the number comes after
|
|
/// it and both survive the shortening: «x_f001 (2).png».
|
|
/// </summary>
|
|
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
|
|
var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries);
|
|
if (attempt <= 1)
|
|
{
|
|
return string.Join('/', segments);
|
|
}
|
|
|
|
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
|
var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"));
|
|
var keep = keepSuffix is null ? null : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})");
|
|
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath, keep));
|
|
}
|
|
|
|
/// <summary>The scheme that names an entry kind.</summary>
|
|
public static NamingSchemeUse UseOf(EntryKind kind) => kind switch
|
|
{
|
|
EntryKind.Highlight => NamingSchemeUse.Highlight,
|
|
EntryKind.ProfilePicture => NamingSchemeUse.ProfilePicture,
|
|
_ => NamingSchemeUse.General,
|
|
};
|
|
}
|