E5: «Riconosci le copie già presenti» per tutta una cartella
«Riconosci» parte da una cartella (ExportService.RecognizeAsync) come lavoro di Alberto: sposta una copia automatica, non gira con importazione, ricostruzione o «Copia in…», aspetta fuori dalle sessioni ed è riprendibile. Registra un lavoro di tipo «Riconosci» su ogni file dovuto alla cartella che non è «Copiato» e sui fotogrammi che hanno già una riga lì. Per ogni file la copia guarda il percorso dello schema e «nome (2)» … «nome (50)», nella forma chiesta adesso e come originale, ciascuna con la sua identità; prima i percorsi, poi lunghezza e SHA-256, con la conversione rifatta solo se un file c'è. Un file uguale diventa «Adottato»: la riga «Non riuscito» diventa la copia, l'orfana si ricollega, la «Superato» con gli stessi byte torna «Copiato». Un «Tolto» resta «Tolto» anche se il file è tornato identico (risposta 51 b). L'adozione per percorso è estratta da WriteAsync (TryAdoptAsync) e serve a entrambi. Non scrive né toglie file, neppure i .part di altri; una cartella che non risponde mette in pausa senza segnare nulla; scrive solo l'evento esportazione-riconosci. Il resoconto conta «Non c'è nella cartella» e «Nel percorso c'è un altro file», e solo il secondo è un problema. Un «Riconosci» in pausa non chiede spazio libero. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0f69a01f88
commit
0ff4a0d632
9 files changed
+1370
-63
No files matched your search
@@ -681,3 +681,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-12-04 | Tappa E5, **risposte di Alberto del 4 dicembre 2026 alle domande 48–55 di §16**, date prima del codice. 48: una copia fatta a mano rimasta «In pausa» resta di Alberto anche quando il giro di recupero trova di nuovo la cartella: la Dashboard dice «la cartella risponde di nuovo, riprendi quando vuoi» e riparte solo con «Riprendi» o «Riprova». 49: la copia automatica cede sempre il passo a importazione, ricostruzione, «Copia in…», «Riprendi», «Riconosci le copie già presenti», zip di fotogrammi e «Cerca i video fermi», e riparte da sola dopo; mai durante una sessione del motore, e se era già partita aspetta senza bloccare nulla. 50 (**non la proposta**): ogni giro di recupero, all'avvio e ogni ora, riprova tutti i «Non riuscito» delle copie automatiche, anche quelli che non possono cambiare (oltre 4 GB su FAT32, percorso troppo lungo): niente classe di errori permanenti, niente ritmo giornaliero; fra un giro e l'altro, i passaggi che partono dopo un salvataggio in libreria non li riprovano. 51 (**non la proposta**): «Riconosci le copie già presenti» come proposto (file dovuti non «Copiato», percorso dello schema e «nome (2)»…«(50)», forma di adesso e originale, lunghezza e poi SHA-256, nessun file scritto o tolto, fotogrammi solo se già registrati), ma un «Tolto» resta «Tolto» anche se il file è tornato identico: non adotta mai un file, o un fotogramma, la cui ultima copia in quella cartella è «Tolto»; «Superato» e «Non riuscito» sì. 52: spegnere «Automatica» ferma subito la copia automatica di quella cartella; i file già copiati restano, le copie a mano non si toccano. 53: «Interrompi» su una copia automatica ferma le copie automatiche fino al giro di recupero dopo (almeno un'ora), con «Riprendi ora»; dopo un riavvio ripartono all'avvio. 54: un lavoro per cartella due minuti dopo l'ultimo file salvato, e comunque al giro; «Copia automatica in … finita» in cronologia solo se ha copiato qualcosa o qualcosa non è riuscito. 55: allargare ciò che spetta a una cartella automatica non chiede di nuovo: vale la scelta dell'accensione, e la finestra, la conferma o l'avviso dice quanti file in più partiranno. **Letture** che il progetto della tappa ha fatto di tre punti che sembravano in contrasto: (a) la riga del 27/11 sulle copie rimaste «In corso» («si riprendono dalla Dashboard, mai da sole») vale per le copie fatte a mano; i lavori automatici riprendono da soli (§4.10, «il giro orario riprova»); (b) «alla prima accensione» della risposta 6 del 18/11 vuol dire a ogni passaggio da spenta ad accesa, come dicono già la riga del 26/11 («la prossima accensione chiede di nuovo»), §4.10 e §8.3; (c) nella riga del 26/11 su «Solo i nuovi», `media.downloaded_at` non è «l'ora della riga di `_febe.jsonl`» ma l'ora in cui Febe ha salvato il file in libreria, scaricato o importato (`MediaStore`, `ImportCopier`), che la ricostruzione rimette dalla riga: «nuovo» vuol dire salvato in libreria dopo l'accensione, anche un file arrivato in ritardo (righe del 28/11) | Le domande 48–55 sono le scelte che la tappa E5 non poteva prendere da sola (§16); le tre letture tolgono contraddizioni solo apparenti fra specifica, decisioni e schema, senza cambiare nulla di deciso. 50: Alberto preferisce il lavoro ripetuto e i resoconti con gli stessi errori a una classe di errori da tenere aggiornata; fuori dal giro i «Non riuscito» aspettano perché ogni lavoro finito risveglia la copia automatica, e un file che non riesce mai farebbe un lavoro ogni due minuti invece che ogni ora. 51: un «Tolto» è una scelta di Alberto, che un file rimesso nella cartella non deve annullare |
|
||||
| 2026-12-04 | Tappa E5: la copia automatica prende il cancello dei lavori lunghi (`LongWorkGate`) con un **permesso che cede** (`TryEnterYielding`): esclude gli altri come ogni permesso, e la conversione della libreria la aspetta come aspetta le copie. Importazione, ricostruzione, zip di fotogrammi (e, con la tappa, «Copia in…», «Riprendi», «Riconosci») lo prendono con `EnterAsync` **prima del proprio lucchetto e prima di registrare qualcosa**: chi entra diventa subito il titolare, la copia automatica riceve l'ordine di fermarsi e si aspetta che lasci, in tempo reale, al più `YieldWait` = 15 s; passato il limite il lavoro è rifiutato con il messaggio della copia e la copia resta titolare finché non lascia. «Cerca i video fermi», che non prende permessi, la ferma con `CancelYielding` e aspetta come per ogni lavoro lungo. `TryEnter` sincrono resta e rifiuta anche un titolare che cede; `BusyFirm` (il titolare se non cede) decide i rifiuti anticipati, `Busy` resta per chi aspetta. La sonda del controllo delle cartelle è riservata come i file temporanei della scrittura sicura | Risposta 49 di Alberto (la copia automatica cede sempre il passo). Un'attesa bloccante dentro `TryEnter` sotto i lucchetti di chi chiama avrebbe bloccato le richieste e rischiato lo stallo con chi pubblica l'avanzamento; installare subito il nuovo titolare chiude la finestra in cui il lavoro automatico potrebbe ripartire. Il tempo reale è un limite di consegna, non una misura del motore (come l'attesa del salvataggio della conversione e la risposta della radice delle copie); lasciare la copia titolare dopo il limite evita di partire sopra una copia che, ferma su una condivisione caduta, potrebbe ancora scrivere. La riserva della sonda impedisce che la pulizia dei resti di un altro lavoro nella stessa cartella la tolga mentre è in uso |
|
||||
| 2026-12-04 | Tappa E5, il servizio delle copie (`ExportService`): le partenze automatiche (`TryStartAutomaticAsync`, `TryResumeAutomaticAsync`) **non lanciano mai eccezioni perché Febe è occupata**: rispondono «occupato» (un lavoro, una sessione del motore, un cambio di cartella, un altro lavoro lungo), «niente da fare» (senza prendere il cancello, così la conversione della libreria non si ferma per nulla) o «ferme»; registrano solo i file da scrivere (niente «già copiato», «Tolto», «Superato»), un lavoro per cartella, e riprendono solo lavori automatici di cartelle ancora automatiche e non in pausa. Le partenze di Alberto («Copia in…», «Riprendi», «Controlla le copie», «Riprova») prendono il cancello con `EnterAsync` e aspettano che il lavoro automatico spostato abbia salvato i suoi stati (al più `StopWait` = 10 s, tempo reale). **I cambi di cartella passano da `ChangeDestinationAsync`**: le partenze automatiche stanno lontane dal primo momento, il lavoro automatico di quella cartella si ferma, poi il cambio, poi i lavori automatici di cartelle non più automatiche o tolte diventano «annullato»; un lavoro automatico non finito non blocca più il cambio di cartella né «Togli la cartella» (uno di Alberto sì). La copia stessa annulla un lavoro automatico la cui cartella non è più automatica, all'inizio e a ogni gruppo. **«Interrompi»** di una copia automatica ferma le copie automatiche per un'ora (`AutomaticHoldTime`), in memoria nel servizio; «Riprendi ora» toglie la sosta. Una cartella in pausa con un lavoro in pausa torna disponibile solo se il disco ha posto per il prossimo file più il margine; senza misura dello spazio la pausa si toglie come prima. «Copia automatica in … finita» solo se il lavoro ha copiato, adottato o non è riuscito qualcosa. Il segnale della copia automatica parte dal nucleo quando una cartella si accende, prende tipi in più, si toglie una cartella propria o si riaccende «Esporta questo account» (`ExportEnvironment.AutoSignal`), non dall'API. Un percorso troppo lungo dà la nota `PathTooLong`. La fine di Febe aspetta il lavoro al più `StopWait` | Risposte 48, 49, 50, 52, 53 e 54 di Alberto. Un rifiuto con eccezione non serve a chi riprova da solo a ogni passata; una partenza che non trova nulla non deve fermare la conversione. Serializzare i cambi nel nucleo chiude la finestra in cui la copia automatica potrebbe ripartire fra l'arresto e il salvataggio. La sosta sta nel servizio, che le partenze consultano, perché il servizio è l'unico punto da cui partono; in memoria come chiede la risposta 53. Riprendere una pausa per spazio senza posto la rimetterebbe subito in pausa. Il segnale nel nucleo vale per ogni via di salvataggio, non solo per l'API, e le prove lo osservano con un'istanza loro. Un limite in tempo reale alla chiusura evita che una lettura bloccata su una condivisione caduta tenga aperta Febe; il lavoro rimasto «in corso» diventa «interrotto» all'avvio dopo, come dopo un arresto improvviso |
|
||||
| 2026-12-04 | Tappa E5, «Riconosci le copie già presenti» (`ExportService.RecognizeAsync`, partenza di Alberto da una cartella): un lavoro di tipo «Riconosci», riprendibile, su ogni file dovuto alla cartella che non è «Copiato» (senza «da quando»; «Una copia sola» vale) e sui fotogrammi che hanno già una riga lì. Per ogni file Febe guarda il percorso dello schema e «nome (2)» … «nome (50)», nella forma che la cartella chiede adesso e come originale, ciascuna con la sua identità (una copia byte per byte si registra Intera/Originale); prima i percorsi, poi la lunghezza, poi lo SHA-256 (con la conversione rifatta solo se un file c'è), mai per dimensione o nome soltanto. Un file uguale si registra «Adottato»: la riga «Non riuscito» della stessa identità diventa la copia, una riga orfana si ricollega, una «Superato» con gli stessi byte torna «Copiato». **Un «Tolto» resta «Tolto»** anche se il file è tornato identico (non si guarda nemmeno; un lavoro ripreso dopo un «Tolto» lo salta). Un fotogramma si confronta con i byte che la sua riga ha registrato, altrimenti si ricava di nuovo dal video; i fotogrammi mai registrati non si cercano. Non scrive, non rinomina e non toglie file (neppure i `.part` lasciati da altri), una cartella che non risponde mette in pausa senza segnare nulla, e scrive solo il suo evento (`esportazione-riconosci`: «Riconosciute N copie già presenti in …», informazione quando nessuna). Il resoconto conta «Non c'è nella cartella» e «Nel percorso c'è un altro file»; solo il secondo è fra i problemi. Lo spazio libero non si chiede per un «Riconosci» in pausa | Risposta 51 di Alberto (b: come proposto, ma un «Tolto» resta «Tolto»). Provare prima i percorsi evita letture e conversioni dove non c'è nulla; ogni forma con la sua identità rispetta il vincolo fra variante e SHA-256 della copia; riusare la riga «Non riuscito» evita una seconda riga corrente. Contare «Non c'è» fra i problemi riempirebbe il resoconto di una cartella che non ha mai avuto copie. Una conversione fatta da codificatori più vecchi esce «diversa»: la copia successiva scrive il file accanto, con un nome libero, e quello che c'era resta |
|
||||
@@ -0,0 +1,396 @@
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Codecs.Images;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Library.Conversion;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// «Riconosci le copie già presenti» (tappa E5, D13; answer 51 of 4 December 2026): each item of a Recognize run is a due
|
||||
/// file of the destination that is not «Copiato», or a frame of it already recorded there. Febe looks at the path its
|
||||
/// naming scheme gives and at «nome (2)» … «nome (50)», in the form the destination asks now and as the original; a file
|
||||
/// is recognised by its length, then its SHA-256 (never by size or name alone), and recorded «Adottato». It never writes,
|
||||
/// renames or deletes a file: it only reads the destination (plus the usual probe). A «Tolto» stays «Tolto» even when its
|
||||
/// file came back identical: only «Copia di nuovo» copies it again.
|
||||
/// </summary>
|
||||
public sealed partial class ExportCopier
|
||||
{
|
||||
/// <summary>The highest number of «nome (n)» looked at after the planned name.</summary>
|
||||
private const int RecognizeSiblings = 50;
|
||||
|
||||
/// <summary>One item of a Recognize run: the file itself (<see cref="RecognizeFileAsync"/>) or one of its frames.</summary>
|
||||
private async Task<ItemResult> RecognizeItemAsync(RunContext x, ExportItem item, CancellationToken ct)
|
||||
{
|
||||
var check = await SourceAsync(x, item, ct).ConfigureAwait(false);
|
||||
if (check.File is not { } library)
|
||||
{
|
||||
return await FinishAsync(item with { State = check.State, Note = check.Note, LastError = null }, check.Bytes, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (item.Variant == ExportVariant.Frame)
|
||||
{
|
||||
if (!string.Equals(item.SourceSha256, library.Sha256, StringComparison.Ordinal))
|
||||
{
|
||||
// The row was of a file the library no longer has: a frame of the new file was never recorded.
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.SourceChanged, LastError = null }, 0, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await RecognizeFrameAsync(x, item, library, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!string.Equals(item.SourceSha256, library.Sha256, StringComparison.Ordinal))
|
||||
{
|
||||
item = item with { SourceSha256 = library.Sha256 };
|
||||
}
|
||||
|
||||
return await RecognizeFileAsync(x, item, library, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A file in the form the destination asks now, then as it is: the paths first (with no file at any of them nothing is
|
||||
/// hashed or converted), then the bytes. The newest row decides as in the plan: a copy there ends the item, a «Tolto»
|
||||
/// stays «Tolto» (answer 51), «Una copia sola» is respected.
|
||||
/// </summary>
|
||||
private async Task<ItemResult> RecognizeFileAsync(RunContext x, ExportItem item, LibraryFile library, CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var none = CancellationToken.None;
|
||||
var destination = x.Destination;
|
||||
var root = destination.RootPath;
|
||||
var account = library.Account.Id;
|
||||
var sha = library.Sha256;
|
||||
var media = library.Media;
|
||||
|
||||
// What the plan saw may have changed since (a run resumed later): a copy there now ends the item, and one whose
|
||||
// file is gone is «Tolto» as in any job (only once the root answered).
|
||||
var copied = (await exports.ListCurrentCopiesAnyFormAsync(destination.Id, account, sha, ct).ConfigureAwait(false))
|
||||
.Where(c => c.State == ExportCopyState.Copied)
|
||||
.ToList();
|
||||
if (copied.Count > 0)
|
||||
{
|
||||
var (present, gone) = await PresentCopyAsync(x, copied, ct).ConfigureAwait(false);
|
||||
if (gone is not null)
|
||||
{
|
||||
return ItemResult.Paused(gone);
|
||||
}
|
||||
|
||||
if (present is not null)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = null, LastError = null }, library.Bytes, present.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var copy in copied)
|
||||
{
|
||||
await exports.UpdateCopyAsync(copy with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = copied[0].Id, LastError = null }, library.Bytes, copied[0].RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Answer 51: a file whose newest copy here is «Tolto» is never recognised, even if its file came back identical.
|
||||
if (await exports.FindLatestCopyAnyFormAsync(destination.Id, account, sha, ct).ConfigureAwait(false) is { State: ExportCopyState.Removed } removed)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = removed.Id, LastError = null }, library.Bytes, removed.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (x.OneOnly
|
||||
&& await exports.FindCopiedElsewhereAsync(sha, account, ct).ConfigureAwait(false) is { RelativePath: { } elsewherePath } elsewhere
|
||||
&& await x.DestinationAsync(_env.Storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where
|
||||
&& Exists(where.RootPath, elsewherePath))
|
||||
{
|
||||
return await FinishAsync(
|
||||
item with { State = ExportItemState.AlreadyCopied, Note = ExportText.Notes.CopiedForAnotherAccount, CopyId = elsewhere.Id, LastError = null },
|
||||
library.Bytes,
|
||||
null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The forms looked for, each with the files at its paths: the one asked now, then the original (copied by an older
|
||||
// setting, or by hand). A form predicted as it is (same format, HEIC, raw…) is the original's.
|
||||
var target = item.Variant == ExportVariant.Whole ? ExportFormat.Original : item.Format;
|
||||
var forms = new List<(ExportFormat Format, IReadOnlyList<string> Paths)>();
|
||||
foreach (var asked in target == ExportFormat.Original ? new[] { ExportFormat.Original } : new[] { target, ExportFormat.Original })
|
||||
{
|
||||
var form = asked != ExportFormat.Original && ExportConversions.Predict(media.RelativePath!, media.Kind, asked) == ExportPrediction.Converted
|
||||
? asked
|
||||
: ExportFormat.Original;
|
||||
if (forms.Any(f => f.Format == form))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string planned;
|
||||
try
|
||||
{
|
||||
planned = PlannedPath(x, library, form == ExportFormat.Original ? null : MediaConverter.ExtensionOf(form), null);
|
||||
}
|
||||
catch (PathTooLongException)
|
||||
{
|
||||
continue; // nothing of ours can be there
|
||||
}
|
||||
|
||||
if (PresentNames(root, planned, null) is { Count: > 0 } paths)
|
||||
{
|
||||
forms.Add((form, paths));
|
||||
}
|
||||
}
|
||||
|
||||
if (forms.Count == 0)
|
||||
{
|
||||
return await NotFoundAsync(x, item, library.Bytes, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (format, paths) in forms)
|
||||
{
|
||||
MediaConversionResult? conversion = null;
|
||||
Output output;
|
||||
if (format == ExportFormat.Original)
|
||||
{
|
||||
output = Output.Whole(library, []);
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
conversion = await ExportConversion.PrepareAsync(_env, library.Source, media, format, sha, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (ContentChangedException ex)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Failed, Note = ExportText.Notes.SourceChanged, LastError = ex.Message }, library.Bytes, null).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Failed, Note = null, LastError = ExportText.ErrorText(ex) }, library.Bytes, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (conversion.Variant == ExportVariant.Whole)
|
||||
{
|
||||
conversion.Dispose(); // kept as it is after all: the original's form looks for it
|
||||
continue;
|
||||
}
|
||||
|
||||
output = new Output(conversion.Variant, conversion.Format, null, conversion.Extension, null, conversion.Length, conversion.Sha256, conversion.Produce, conversion.Notes);
|
||||
}
|
||||
|
||||
using (conversion)
|
||||
{
|
||||
// Each form has its own identity (engineering B7a): an original's bytes are recorded Whole/Original.
|
||||
var identity = new ExportCopyIdentity(destination.Id, account, sha, output.Variant, output.Format, null);
|
||||
var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false);
|
||||
var failed = current is { State: ExportCopyState.Failed } ? current : null;
|
||||
var result = await TryAdoptAsync(x, item, new FileContext(library, identity), output, failed, paths, ExportItemState.Adopted, ct).ConfigureAwait(false);
|
||||
if (result is not null)
|
||||
{
|
||||
if (result.State is ExportItemState.Adopted or ExportItemState.AlreadyCopied)
|
||||
{
|
||||
// A copy of the file is there now: the «Non riuscito» rows of its other forms have no use.
|
||||
await exports.ClearFailedAsync(destination.Id, account, sha, identity, none).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The report shows the path where another file is (the first one looked at).
|
||||
var different = forms[0].Paths[0];
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Different, RelativePath = different, LastError = null }, library.Bytes, different).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A frame already recorded in the destination (its instant is known): at the path of its row, or the one «Questo
|
||||
/// istante» or «Salva il fotogramma» gives. Its bytes are those its row recorded (an orphan, a «Superato»), or the
|
||||
/// frame taken again from the video (a «Non riuscito» row has none).
|
||||
/// </summary>
|
||||
private async Task<ItemResult> RecognizeFrameAsync(RunContext x, ExportItem item, LibraryFile library, CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var destination = x.Destination;
|
||||
var root = destination.RootPath;
|
||||
var at = item.FrameAt ?? TimeSpan.Zero;
|
||||
var format = item.Format;
|
||||
var identity = new ExportCopyIdentity(destination.Id, library.Account.Id, library.Sha256, ExportVariant.Frame, format, at);
|
||||
var file = new FileContext(library with { Bytes = 0 }, identity);
|
||||
var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false);
|
||||
if (current is { State: ExportCopyState.Copied })
|
||||
{
|
||||
var (present, gone) = await PresentCopyAsync(x, [current], ct).ConfigureAwait(false);
|
||||
if (gone is not null)
|
||||
{
|
||||
return ItemResult.Paused(gone);
|
||||
}
|
||||
|
||||
if (present is not null)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = null, LastError = null }, 0, present.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, 0, current.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (current is null && await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false) is { State: ExportCopyState.Removed } removed)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = removed.Id, LastError = null }, 0, removed.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var failed = current is { State: ExportCopyState.Failed } ? current : null;
|
||||
var extension = MediaConverter.ExtensionOf(format);
|
||||
var paths = new List<string>();
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (item.RelativePath is { } recorded && Exists(root, recorded) && seen.Add(recorded))
|
||||
{
|
||||
paths.Add(recorded);
|
||||
}
|
||||
|
||||
foreach (var suffix in new[] { ExportFrames.Suffix(FrameMode.At, at, 0, 1), ExportFrames.SingleSuffix })
|
||||
{
|
||||
try
|
||||
{
|
||||
paths.AddRange(PresentNames(root, PlannedPath(x, library, extension, suffix), suffix).Where(seen.Add));
|
||||
}
|
||||
catch (PathTooLongException)
|
||||
{
|
||||
// That name does not fit: nothing of ours can be there.
|
||||
}
|
||||
}
|
||||
|
||||
if (paths.Count == 0)
|
||||
{
|
||||
return await NotFoundAsync(x, item, 0, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The bytes a row of this very frame recorded at the path: compared without taking the frame again.
|
||||
var others = new List<string>();
|
||||
foreach (var path in paths)
|
||||
{
|
||||
if (await exports.FindCopyByPathAsync(destination.Id, path, ct).ConfigureAwait(false) is { Variant: ExportVariant.Frame, CopySha256: { } copySha, Bytes: { } bytes } holder
|
||||
&& string.Equals(holder.SourceSha256, library.Sha256, StringComparison.Ordinal) && holder.Format == format && holder.FrameAt == at)
|
||||
{
|
||||
var known = new Output(ExportVariant.Frame, format, at, extension, null, bytes, copySha, null, []);
|
||||
if (await TryAdoptAsync(x, item, file, known, failed, [path], ExportItemState.Adopted, ct).ConfigureAwait(false) is { } adopted)
|
||||
{
|
||||
return adopted;
|
||||
}
|
||||
|
||||
continue; // another file at the row's path: the frame taken again could not be adopted there either
|
||||
}
|
||||
|
||||
others.Add(path);
|
||||
}
|
||||
|
||||
if (others.Count > 0)
|
||||
{
|
||||
if (await FrameOutputAsync(library, format, at, ct).ConfigureAwait(false) is not { } taken)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.FrameNotAvailable, LastError = null }, 0, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (await TryAdoptAsync(x, item, file, taken, failed, others, ExportItemState.Adopted, ct).ConfigureAwait(false) is { } adopted)
|
||||
{
|
||||
return adopted;
|
||||
}
|
||||
}
|
||||
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Different, RelativePath = paths[0], LastError = null }, 0, paths[0]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Nothing at the paths looked at: «Non c'è nella cartella», unless the root itself went away meanwhile (the run then
|
||||
/// pauses and marks nothing).
|
||||
/// </summary>
|
||||
private async Task<ItemResult> NotFoundAsync(RunContext x, ExportItem item, long bytes, CancellationToken ct)
|
||||
{
|
||||
if (!Directory.Exists(x.Destination.RootPath) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } away)
|
||||
{
|
||||
return ItemResult.Paused(away);
|
||||
}
|
||||
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.NotFound, LastError = null }, bytes, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The files of the destination at <paramref name="planned"/> and at its numbered names («nome (2)» … «nome (50)»,
|
||||
/// numbered as the writer numbers them), these until the first one that is not there.
|
||||
/// </summary>
|
||||
private List<string> PresentNames(string root, string planned, string? keepSuffix)
|
||||
{
|
||||
var found = new List<string>();
|
||||
for (var attempt = 1; attempt <= RecognizeSiblings; attempt++)
|
||||
{
|
||||
string name;
|
||||
try
|
||||
{
|
||||
name = ExportPaths.NumberedName(root, planned, attempt, MaxPath, keepSuffix);
|
||||
}
|
||||
catch (PathTooLongException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (Exists(root, name))
|
||||
{
|
||||
found.Add(name);
|
||||
}
|
||||
else if (attempt > 1)
|
||||
{
|
||||
break; // the writer takes the first free name: nothing of ours after it
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frame of the library video at <paramref name="at"/> in <paramref name="format"/>, encoded as a copy encodes it
|
||||
/// (no metadata); null when the video is not the one recorded, cannot be read, or shows no frame at that instant.
|
||||
/// </summary>
|
||||
private async Task<Output?> FrameOutputAsync(LibraryFile library, ExportFormat format, TimeSpan at, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.Equals(await _env.FileSystem.ComputeSha256Async(library.Source, ct).ConfigureAwait(false), library.Sha256, StringComparison.Ordinal))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var stream = _env.FileSystem.OpenRandomAccess(library.Source);
|
||||
await using (stream.ConfigureAwait(false))
|
||||
{
|
||||
var reader = await Task.Run(() => VideoFrameReader.Open(stream, out _, ct), ct).ConfigureAwait(false);
|
||||
using (reader)
|
||||
{
|
||||
var targets = reader.Locate([at]);
|
||||
if (targets.Count != 1 || ExportFrames.ActualMs(targets[0].Actual) != (long)at.TotalMilliseconds)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var frames = reader.Decode([targets[0]], ct).GetEnumerator();
|
||||
if (!await Task.Run(frames.MoveNext, ct).ConfigureAwait(false))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var frame = frames.Current;
|
||||
var image = MediaConverter.ImageFormatOf(format)!.Value;
|
||||
var data = await _env.Throttle.RunAsync(_ => ImageConverter.Encode(frame.Image, image, null), ct).ConfigureAwait(false);
|
||||
return new Output(
|
||||
ExportVariant.Frame,
|
||||
format,
|
||||
at,
|
||||
MediaConverter.ExtensionOf(format),
|
||||
null,
|
||||
data.Length,
|
||||
Convert.ToHexStringLower(SHA256.HashData(data)),
|
||||
(target, token) => target.WriteAsync(data, token).AsTask(),
|
||||
[]);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ImageDecodeException or ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,10 @@ namespace Febe.Core.Export;
|
||||
/// Tappa E3: a file is converted (before the space check) into the format its item asks, or copied as it is with a
|
||||
/// note; a file already copied in any form but a frame is «già copiato» (D3); the frames of a video are taken in one
|
||||
/// batch, each one with its exact instant as identity (D4, D12).
|
||||
/// Tappa E5: a run of kind Recognize («Riconosci le copie già presenti», D13) only reads the destination and records the
|
||||
/// files already there (ExportCopier.Recognize.cs).
|
||||
/// </summary>
|
||||
public sealed class ExportCopier(ExportEnvironment env)
|
||||
public sealed partial class ExportCopier(ExportEnvironment env)
|
||||
{
|
||||
private const int PageSize = 500;
|
||||
private const int MaxSiblings = 1000;
|
||||
@@ -65,10 +67,16 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
run = run with { State = ExportRunState.Running, LastError = null };
|
||||
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
|
||||
var x = new RunContext(run, destination, progress);
|
||||
var recognize = run.Kind == ExportRunKind.Recognize;
|
||||
try
|
||||
{
|
||||
x.Report(_env, ExportPhase.Preparing, null);
|
||||
await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false);
|
||||
if (!recognize)
|
||||
{
|
||||
// «Riconosci» writes no .part, so it has none to clean: it only reads the destination (D13 of tappa E5).
|
||||
await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var layout = _env.Layout();
|
||||
var library = await LibrarySettings.LoadAsync(_env.Storage.Settings, layout.Root, ct).ConfigureAwait(false);
|
||||
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||
@@ -89,7 +97,7 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
while (await pending.PeekAsync(ct).ConfigureAwait(false) is { } item)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (item.Variant == ExportVariant.Frame)
|
||||
if (item.Variant == ExportVariant.Frame && !recognize)
|
||||
{
|
||||
// The following frames of the same video and format are one batch, also across pages (WP1.7).
|
||||
var batch = new List<ExportItem> { pending.Take() };
|
||||
@@ -113,7 +121,9 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
return await PauseAsync(x, problem).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var result = await ProcessItemAsync(x, item, ct).ConfigureAwait(false);
|
||||
var result = recognize
|
||||
? await RecognizeItemAsync(x, item, ct).ConfigureAwait(false)
|
||||
: await ProcessItemAsync(x, item, ct).ConfigureAwait(false);
|
||||
if (result.Pause is { } pause)
|
||||
{
|
||||
return await PauseAsync(x, pause).ConfigureAwait(false);
|
||||
@@ -126,7 +136,21 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
run = run with { State = ExportRunState.Completed, CompletedAt = _env.Clock.Now, LastError = null };
|
||||
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
|
||||
var automatic = run.Origin == ExportRunOrigin.Automatic;
|
||||
if (!automatic || ExportText.AutomaticRunIsWorthAnEvent(final))
|
||||
if (recognize)
|
||||
{
|
||||
// «Riconosci» writes only its own event, never «esportazione-completata» (D13 of tappa E5).
|
||||
await _env.Storage.Events.AppendAsync(
|
||||
new EventRecord
|
||||
{
|
||||
At = _env.Clock.Now,
|
||||
Code = ExportText.RecognizeEventCode,
|
||||
Message = ExportText.RecognizeMessage(final, x.Destination),
|
||||
Severity = ExportText.RecognizeSeverity(final),
|
||||
AccountId = x.Destination.AccountId,
|
||||
},
|
||||
none).ConfigureAwait(false);
|
||||
}
|
||||
else if (!automatic || ExportText.AutomaticRunIsWorthAnEvent(final))
|
||||
{
|
||||
// Answer 54: an automatic run that copied, adopted and failed nothing leaves no trace in the history.
|
||||
await _env.Storage.Events.AppendAsync(
|
||||
@@ -854,12 +878,7 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
string planned;
|
||||
try
|
||||
{
|
||||
var name = output.Extension is null && output.Suffix is null ? null : new ExportNameOptions(output.Extension, output.Suffix);
|
||||
planned = ExportPaths.RelativePathFor(
|
||||
destination,
|
||||
ExportPaths.Segments(destination, x.Naming!, library.Account, library.Entry, library.Media, library.HighlightTitle, library.InHighlight, _env.Clock.LocalZone, name),
|
||||
MaxPath,
|
||||
output.Suffix);
|
||||
planned = PlannedPath(x, library, output.Extension, output.Suffix);
|
||||
}
|
||||
catch (PathTooLongException ex)
|
||||
{
|
||||
@@ -879,51 +898,9 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
|
||||
// Adoption by path (D10 of tappa E3): the planned file, and after a crash the name it was given («nome (2).jpg»,
|
||||
// …), when its length and then its SHA-256 are those of this output. Never by size alone.
|
||||
string? expected = output.Sha256;
|
||||
foreach (var candidate in AdoptionCandidates(root, planned, item.RelativePath, output.Suffix))
|
||||
if (await TryAdoptAsync(x, item, file, output, failed, AdoptionCandidates(root, planned, item.RelativePath, output.Suffix), ExportItemState.AlreadyCopied, ct).ConfigureAwait(false) is { } adopted)
|
||||
{
|
||||
var full = LibraryLayout.FullPath(root, candidate);
|
||||
if (_env.FileSystem.FileLength(full) != output.Length)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (expected is null)
|
||||
{
|
||||
// A remux: its bytes are known once written, so they are written nowhere first (the length matched).
|
||||
var (hash, length) = await ExportConversion.HashAsync(output.Produce!, ct).ConfigureAwait(false);
|
||||
if (length != output.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
expected = hash;
|
||||
}
|
||||
|
||||
if (!string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), expected, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var holder = await exports.FindCopyByPathAsync(destination.Id, candidate, ct).ConfigureAwait(false);
|
||||
if (holder is null || (holder.AccountId is null && SameForm(holder, file, expected)))
|
||||
{
|
||||
return await RecordAsync(item, file, failed, holder, candidate, output.Length, expected, ExportCopyOrigin.Adopted, Notes(output, null)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (holder.Identity == file.Identity)
|
||||
{
|
||||
if (holder.State == ExportCopyState.Superseded)
|
||||
{
|
||||
// Our own bytes, recorded as superseded (the file came back to the library without the change that
|
||||
// would have revived the row): the copy is copied, not superseded, and must not stay stuck.
|
||||
return await ReviveAsync(item, file, failed, holder, candidate, output, expected).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, library.Bytes, candidate).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The same bytes, recorded for another copy: not ours to take.
|
||||
return adopted;
|
||||
}
|
||||
|
||||
// The name the record can take: free on the disk and in the database. A path recorded for another copy whose
|
||||
@@ -1013,6 +990,93 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, saved.Sha256, ExportCopyOrigin.Written, Notes(output, taken)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path the naming scheme gives a library file in the destination, with the extension of a converted output and
|
||||
/// the suffix of a frame.
|
||||
/// </summary>
|
||||
/// <exception cref="PathTooLongException">It does not fit the destination.</exception>
|
||||
private string PlannedPath(RunContext x, LibraryFile library, string? extension, string? suffix)
|
||||
{
|
||||
var destination = x.Destination;
|
||||
var name = extension is null && suffix is null ? null : new ExportNameOptions(extension, suffix);
|
||||
return ExportPaths.RelativePathFor(
|
||||
destination,
|
||||
ExportPaths.Segments(destination, x.Naming!, library.Account, library.Entry, library.Media, library.HighlightTitle, library.InHighlight, _env.Clock.LocalZone, name),
|
||||
MaxPath,
|
||||
suffix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adoption by path (D10 of tappa E3; «Riconosci», D13 of tappa E5): the first of <paramref name="candidates"/> whose
|
||||
/// length and then SHA-256 are those of <paramref name="output"/> (never by size alone) and whose path is free in the
|
||||
/// database, or held by an orphan row of this very copy, is recorded «Adottato»; one held by a «Superato» row of this
|
||||
/// identity revives it (the item then ends <paramref name="revived"/>); one held by this identity's own copy is
|
||||
/// «Già copiato». A file with the same bytes recorded for another copy is not ours to take. Null when none is adopted.
|
||||
/// Reads files only: nothing is written, renamed or deleted.
|
||||
/// </summary>
|
||||
private async Task<ItemResult?> TryAdoptAsync(
|
||||
RunContext x,
|
||||
ExportItem item,
|
||||
FileContext file,
|
||||
Output output,
|
||||
ExportCopy? failed,
|
||||
IEnumerable<string> candidates,
|
||||
ExportItemState revived,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var destination = x.Destination;
|
||||
var root = destination.RootPath;
|
||||
string? expected = output.Sha256;
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
var full = LibraryLayout.FullPath(root, candidate);
|
||||
if (_env.FileSystem.FileLength(full) != output.Length)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (expected is null)
|
||||
{
|
||||
// A remux: its bytes are known once written, so they are written nowhere first (the length matched).
|
||||
var (hash, length) = await ExportConversion.HashAsync(output.Produce!, ct).ConfigureAwait(false);
|
||||
if (length != output.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
expected = hash;
|
||||
}
|
||||
|
||||
if (!string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), expected, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var holder = await exports.FindCopyByPathAsync(destination.Id, candidate, ct).ConfigureAwait(false);
|
||||
if (holder is null || (holder.AccountId is null && SameForm(holder, file, expected)))
|
||||
{
|
||||
return await RecordAsync(item, file, failed, holder, candidate, output.Length, expected, ExportCopyOrigin.Adopted, Notes(output, null)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (holder.Identity == file.Identity)
|
||||
{
|
||||
if (holder.State == ExportCopyState.Superseded)
|
||||
{
|
||||
// Our own bytes, recorded as superseded (the file came back to the library without the change that
|
||||
// would have revived the row): the copy is copied, not superseded, and must not stay stuck.
|
||||
return await ReviveAsync(item, file, failed, holder, candidate, output, expected, revived).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, file.Library.Bytes, candidate).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The same bytes, recorded for another copy: not ours to take.
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>An orphan row is adopted only when it records this very copy: same bytes, variant, format and instant (D10).</summary>
|
||||
private static bool SameForm(ExportCopy holder, FileContext file, string copySha256) =>
|
||||
string.Equals(holder.SourceSha256, file.Library.Sha256, StringComparison.Ordinal)
|
||||
@@ -1086,8 +1150,10 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
/// <summary>
|
||||
/// A Superseded row of this very identity whose bytes are at its path: it becomes the Copied row again. When the
|
||||
/// identity has a current «Non riuscito» row, that one becomes the Copied row and the old one stays as history.
|
||||
/// <paramref name="revived"/>: the state of the item when the row itself is revived («Già copiato» for a copy job,
|
||||
/// «Adottato» for «Riconosci»).
|
||||
/// </summary>
|
||||
private async Task<ItemResult> ReviveAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy holder, string path, Output output, string copySha256)
|
||||
private async Task<ItemResult> ReviveAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy holder, string path, Output output, string copySha256, ExportItemState revived)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var none = CancellationToken.None;
|
||||
@@ -1095,7 +1161,7 @@ public sealed class ExportCopier(ExportEnvironment env)
|
||||
if (failed is null && await exports.FindCurrentCopyAsync(file.Identity, none).ConfigureAwait(false) is null)
|
||||
{
|
||||
await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Copied, SupersededBySha256 = null, MediaId = file.Library.Media.Id, StateChangedAt = now }, none).ConfigureAwait(false);
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = path, Note = null, LastError = null }, file.Library.Bytes, path).ConfigureAwait(false);
|
||||
return await FinishAsync(item with { State = revived, CopyId = holder.Id, RelativePath = path, Note = null, LastError = null }, file.Library.Bytes, path).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Removed, StateChangedAt = now }, none).ConfigureAwait(false);
|
||||
|
||||
@@ -19,6 +19,15 @@ public sealed record ExportReport(
|
||||
/// are, what a conversion did not keep, a free name).
|
||||
/// </summary>
|
||||
public IReadOnlyList<ExportReportLine> Notes { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// «Riconosci le copie già presenti» (tappa E5, D13): the files with nothing at the paths looked at («Non c'è nella
|
||||
/// cartella»). Not problem lines: on a folder that never had copies they would be every file.
|
||||
/// </summary>
|
||||
public int NotFound { get; init; }
|
||||
|
||||
/// <summary>«Riconosci»: the files with another file at their path («Nel percorso c'è un altro file»), also problem lines.</summary>
|
||||
public int Different { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The files of one account in a job («Copiato» counts written and adopted files).</summary>
|
||||
@@ -61,6 +70,9 @@ public sealed class ExportReports(ExportEnvironment env)
|
||||
var problems = new List<ExportReportLine>();
|
||||
var notes = new List<ExportReportLine>();
|
||||
var asIs = new Dictionary<long, Dictionary<string, int>>();
|
||||
var recognize = run.Kind == ExportRunKind.Recognize;
|
||||
var notFound = 0;
|
||||
var different = 0;
|
||||
long bytes = 0;
|
||||
long after = 0;
|
||||
while (true)
|
||||
@@ -116,8 +128,16 @@ public sealed class ExportReports(ExportEnvironment env)
|
||||
break;
|
||||
}
|
||||
|
||||
var unseen = false;
|
||||
if (recognize && item.State == ExportItemState.Skipped)
|
||||
{
|
||||
unseen = item.Note == ExportText.Notes.NotFound;
|
||||
notFound += unseen ? 1 : 0;
|
||||
different += item.Note == ExportText.Notes.Different ? 1 : 0;
|
||||
}
|
||||
|
||||
var problem = item.State is ExportItemState.Failed or ExportItemState.Missing
|
||||
|| (item.State == ExportItemState.Skipped && item.Note is not null);
|
||||
|| (item.State == ExportItemState.Skipped && item.Note is not null && !unseen);
|
||||
if (problem && problems.Count < MaxProblems)
|
||||
{
|
||||
var text = item.State == ExportItemState.Failed
|
||||
@@ -135,7 +155,12 @@ public sealed class ExportReports(ExportEnvironment env)
|
||||
})
|
||||
.OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems) { Notes = notes };
|
||||
return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems)
|
||||
{
|
||||
Notes = notes,
|
||||
NotFound = notFound,
|
||||
Different = different,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The kind of a file copied as it is, from the codes of its note; null when it was not.</summary>
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// «Riconosci le copie già presenti» (tappa E5, D13; answer 51 of 4 December 2026), started by Alberto from a destination:
|
||||
/// a resumable job of kind Recognize over every due file of the destination that is not «Copiato» (whatever «Solo i
|
||||
/// nuovi» says), and over the frames already recorded there. A file whose newest copy there is «Tolto» is left out: a
|
||||
/// «Tolto» stays «Tolto». It is Alberto's work: it displaces an automatic copy, never runs with an import, a rebuild or
|
||||
/// «Copia in…», and waits outside engine sessions.
|
||||
/// </summary>
|
||||
public sealed partial class ExportService
|
||||
{
|
||||
/// <summary>
|
||||
/// «Riconosci le copie già presenti»: records a Recognize job over every due file of the destination that is not
|
||||
/// «Copiato», and its frames already recorded there, and starts it in the background. A job without files is still
|
||||
/// recorded: it ends at once and says so.
|
||||
/// </summary>
|
||||
/// <exception cref="KeyNotFoundException">No such destination.</exception>
|
||||
/// <exception cref="InvalidOperationException">The destination was retired, or a copy, an import or a rebuild is running (Italian message).</exception>
|
||||
public async Task<ExportRun> RecognizeAsync(long destinationId, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfManualJob();
|
||||
await RecognizableAsync(destinationId, ct).ConfigureAwait(false);
|
||||
return await RunManualAsync(
|
||||
async held =>
|
||||
{
|
||||
// Read again under the lease: the folder may have been taken away meanwhile.
|
||||
var destination = await RecognizableAsync(destinationId, ct).ConfigureAwait(false);
|
||||
var run = await RecordRecognizeRunAsync(destination, ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_starting = false;
|
||||
StartCopyJob([run.Id], held.Lease);
|
||||
held.Lease = null; // the job owns it now
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
await StopRunsAsync([run]).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
|
||||
return run;
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The destination, when «Riconosci» can look in it.</summary>
|
||||
private async Task<ExportDestination> RecognizableAsync(long destinationId, CancellationToken ct)
|
||||
{
|
||||
var destination = await _env.Storage.Exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException($"Destinazione di esportazione {destinationId} non trovata.");
|
||||
return destination.IsRetired
|
||||
? throw new InvalidOperationException("Questa cartella è stata tolta: non c'è niente da riconoscere.")
|
||||
: destination;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The run and its items, a page of files at a time: each file in the form the destination asks now (D13: the
|
||||
/// original is looked for too), then its frames with the path of their row.
|
||||
/// </summary>
|
||||
private async Task<ExportRun> RecordRecognizeRunAsync(ExportDestination destination, CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var none = CancellationToken.None;
|
||||
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||
var run = await exports.CreateRunAsync(
|
||||
new ExportRun { DestinationId = destination.Id, Kind = ExportRunKind.Recognize, Origin = ExportRunOrigin.Manual, State = ExportRunState.Running, StartedAt = _env.Clock.Now },
|
||||
none).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// A run id can be used again after DeleteRunAsync: no key of an older job may apply to this one.
|
||||
await ExportRunSettings.ClearAsync(_env.Storage.Settings, run.Id, none).ConfigureAwait(false);
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await exports.ListRecognizeCandidatesAsync(destination.Id, after, ItemBatch, ct).ConfigureAwait(false);
|
||||
if (page.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
after = page[^1].File.MediaId;
|
||||
var items = page.Select(candidate =>
|
||||
{
|
||||
var file = candidate.File;
|
||||
if (candidate.Frame is { } frame)
|
||||
{
|
||||
return new ExportItem
|
||||
{
|
||||
RunId = run.Id,
|
||||
MediaId = file.MediaId,
|
||||
AccountId = file.AccountId,
|
||||
SourceSha256 = file.Sha256,
|
||||
Variant = ExportVariant.Frame,
|
||||
Format = frame.Format,
|
||||
FrameAt = frame.FrameAt ?? TimeSpan.Zero,
|
||||
State = ExportItemState.Pending,
|
||||
RelativePath = frame.RelativePath,
|
||||
};
|
||||
}
|
||||
|
||||
var target = ExportConversions.Resolve(file.MediaKind, null, destination, settings);
|
||||
return new ExportItem
|
||||
{
|
||||
RunId = run.Id,
|
||||
MediaId = file.MediaId,
|
||||
AccountId = file.AccountId,
|
||||
SourceSha256 = file.Sha256,
|
||||
Variant = ExportConversions.VariantOf(target),
|
||||
Format = target,
|
||||
State = ExportItemState.Pending,
|
||||
};
|
||||
}).ToList();
|
||||
await exports.AddItemsAsync(items, none).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
await StopRunsAsync([run]).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
|
||||
return run;
|
||||
}
|
||||
}
|
||||
@@ -222,6 +222,38 @@ public static class ExportText
|
||||
+ summary.ByState.GetValueOrDefault(ExportItemState.Failed) > 0;
|
||||
}
|
||||
|
||||
/// <summary>The code of the event of «Riconosci le copie già presenti» (tappa E5, D13): its only event.</summary>
|
||||
public const string RecognizeEventCode = "esportazione-riconosci";
|
||||
|
||||
/// <summary>
|
||||
/// The event written when «Riconosci le copie già presenti» ends: «Riconosciute 12 copie già presenti in Disco USB.»,
|
||||
/// with the files that did not succeed when there are any.
|
||||
/// </summary>
|
||||
public static string RecognizeMessage(ExportRunSummary summary, ExportDestination destination)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(summary);
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
var adopted = summary.ByState.GetValueOrDefault(ExportItemState.Adopted);
|
||||
var failed = summary.ByState.GetValueOrDefault(ExportItemState.Failed);
|
||||
var label = ExportDestinations.Label(destination);
|
||||
var text = adopted switch
|
||||
{
|
||||
0 => $"Nessuna copia già presente da riconoscere in {label}",
|
||||
1 => $"Riconosciuta 1 copia già presente in {label}",
|
||||
_ => $"Riconosciute {ItalianText.Number(adopted)} copie già presenti in {label}",
|
||||
};
|
||||
return failed > 0 ? $"{text}; {Count(failed, "non riuscito", "non riusciti")}." : text + ".";
|
||||
}
|
||||
|
||||
/// <summary>The severity of the event of «Riconosci»: a warning with failures, information when nothing was recognised.</summary>
|
||||
public static EventSeverity RecognizeSeverity(ExportRunSummary summary)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(summary);
|
||||
return summary.ByState.GetValueOrDefault(ExportItemState.Failed) > 0 ? EventSeverity.Warning
|
||||
: summary.ByState.GetValueOrDefault(ExportItemState.Adopted) > 0 ? EventSeverity.Success
|
||||
: EventSeverity.Info;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why an automatic run was cancelled (tappa E5, answer 52): its destination was switched off, retired, or lost its
|
||||
/// account meanwhile. The copies made stay.
|
||||
|
||||
@@ -285,8 +285,9 @@ public interface IExportStore
|
||||
Task<IReadOnlyList<ExportRecognizeCandidate>> ListRecognizeCandidatesAsync(long destinationId, long afterMediaId, int limit, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The bytes of the library file of the first item still «In attesa» of the oldest paused job of a destination (D11:
|
||||
/// a pause for space is cleared only when it fits); null without such an item or without its size.
|
||||
/// The bytes of the library file of the first item still «In attesa» of the oldest paused copy job of a destination
|
||||
/// (D11: a pause for space is cleared only when it fits; a «Riconosci» writes nothing); null without such an item or
|
||||
/// without its size.
|
||||
/// </summary>
|
||||
Task<long?> GetFirstPendingBytesAsync(long destinationId, CancellationToken ct = default);
|
||||
|
||||
|
||||
@@ -1361,10 +1361,13 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
||||
ct);
|
||||
}
|
||||
|
||||
/// <summary>The bytes of the first pending item of the oldest paused job of a destination (@d).</summary>
|
||||
/// <summary>
|
||||
/// The bytes of the first pending item of the oldest paused copy job of a destination (@d). A paused «Riconosci»
|
||||
/// writes nothing, so it needs no room (D13 of tappa E5).
|
||||
/// </summary>
|
||||
internal const string FirstPendingBytesSql = """
|
||||
SELECT m.bytes FROM export_run r JOIN export_item i ON i.run_id = r.id JOIN media m ON m.id = i.media_id
|
||||
WHERE r.destination_id = @d AND r.state = 'Paused' AND i.state = 'Pending'
|
||||
WHERE r.destination_id = @d AND r.state = 'Paused' AND r.kind = 'Copy' AND i.state = 'Pending'
|
||||
ORDER BY r.id, i.id LIMIT 1
|
||||
""";
|
||||
|
||||
|
||||
@@ -0,0 +1,654 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Codecs.Containers;
|
||||
using Febe.Tests.Export.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Export;
|
||||
|
||||
/// <summary>
|
||||
/// «Riconosci le copie già presenti» (tappa E5, D13; answer 51 of 4 December 2026) on real folders: a file already in the
|
||||
/// destination at the path of the naming scheme or at «nome (2)», in the form asked now or as the original, is recorded
|
||||
/// «Adottato» by length and SHA-256, never by size alone; a «Non riuscito» row becomes the copy, an orphan row is linked
|
||||
/// again, a «Superato» row of these very bytes is revived; a frame already recorded is recognised; a «Tolto» stays
|
||||
/// «Tolto» even when its file came back identical; nothing is written or deleted; an unreachable folder pauses and marks
|
||||
/// nothing; the run is resumable, Alberto's work (it displaces an automatic copy), and writes only its own event.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ExportRecognizeTests
|
||||
{
|
||||
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public async Task AByteCopyAtThePlannedPathIsAdopted()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r01", 1);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var copy = PutCopy(bed, bed.Marta, media);
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
Assert.AreEqual((ExportRunKind.Recognize, ExportRunOrigin.Manual, ExportRunState.Completed), (run.Kind, run.Origin, run.State));
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, "marta.demo/" + media.RelativePath), (item.State, item.RelativePath));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
|
||||
Assert.AreEqual(
|
||||
(ExportCopyState.Copied, ExportCopyOrigin.Adopted, ExportVariant.Whole, ExportFormat.Original, media.Sha256, media.Sha256, bed.Marta.Id),
|
||||
(row.State, row.Origin, row.Variant, row.Format, row.SourceSha256, row.CopySha256, row.AccountId));
|
||||
Assert.AreEqual(new FileInfo(copy).Length, row.Bytes);
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "recognised, not written");
|
||||
|
||||
// Now it is «Copiato»: «Copia in…» has nothing to write.
|
||||
Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct)).Files);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ANumberedSiblingIsAdopted()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r02", 2);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var planned = "marta.demo/" + media.RelativePath;
|
||||
|
||||
// The planned name holds another file; ours went to «(3)» after «(2)» was taken too.
|
||||
var taken = Full(bed, planned);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(taken)!);
|
||||
await File.WriteAllBytesAsync(taken, [1, 2, 3], ct);
|
||||
await File.WriteAllBytesAsync(Full(bed, ExportPaths.NumberedName(bed.Usb, planned, 2)), [4, 5, 6], ct);
|
||||
var third = ExportPaths.NumberedName(bed.Usb, planned, 3);
|
||||
File.Copy(bed.LibraryFile(bed.Marta, media), Full(bed, third));
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, third), (item.State, item.RelativePath));
|
||||
Assert.AreEqual(third, (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.RelativePath);
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written or renamed");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AConvertedCopyIsRecognisedByConvertingAgain()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r03", 3);
|
||||
var media = post.Media[0];
|
||||
var usb = await GeneralInPngAsync(bed, ct);
|
||||
|
||||
// A PNG copy made earlier, at the name the scheme gives a converted file.
|
||||
var path = "marta.demo/" + Path.ChangeExtension(media.RelativePath!, ".png");
|
||||
string converted;
|
||||
using (var conversion = await MediaConverter.PrepareAsync(() => File.OpenRead(bed.LibraryFile(bed.Marta, media)), media.RelativePath!, media.Kind, ExportFormat.Png, media.Sha256!, new ConversionThrottle(), ct))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Full(bed, path))!);
|
||||
await using (var file = File.Create(Full(bed, path)))
|
||||
{
|
||||
await conversion.Produce(file, ct);
|
||||
}
|
||||
|
||||
converted = conversion.Sha256!;
|
||||
}
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, ExportVariant.Converted, ExportFormat.Png, path), (item.State, item.Variant, item.Format, item.RelativePath));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
|
||||
Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png, converted, ExportCopyOrigin.Adopted), (row.Variant, row.Format, row.CopySha256, row.Origin));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnOriginalCopyIsRecordedAsWholeOriginalWhenTheDestinationNowConverts()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r04", 4);
|
||||
var media = post.Media[0];
|
||||
var usb = await GeneralInPngAsync(bed, ct);
|
||||
PutCopy(bed, bed.Marta, media); // copied as it was, before the folder asked PNG
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, ExportVariant.Converted, ExportFormat.Png), (item.State, item.Variant, item.Format), "the item keeps the form asked");
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
|
||||
Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, media.Sha256), (row.Variant, row.Format, row.CopySha256), "the bytes say Whole/Original");
|
||||
Assert.AreEqual("marta.demo/" + media.RelativePath, row.RelativePath);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADifferentFileAtThePathIsNotAdopted_NoteDifferent()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r05", 5);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var copy = PutCopy(bed, bed.Marta, media);
|
||||
var bytes = await File.ReadAllBytesAsync(copy, ct);
|
||||
bytes[^3] ^= 0x01; // same size, other bytes
|
||||
await File.WriteAllBytesAsync(copy, bytes, ct);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Different, (long?)null), (item.State, item.Note, item.CopyId));
|
||||
Assert.AreEqual("Nel percorso c'è un altro file", ExportText.Note(item.Note));
|
||||
Assert.HasCount(0, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NothingThereGivesNotFoundWithoutConverting()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var counting = new CountingExportFileSystem();
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = counting });
|
||||
var photo = await bed.PostAsync(bed.Marta, "r06", 6);
|
||||
var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"));
|
||||
await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "r07", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")]);
|
||||
var usb = await GeneralInPngAsync(bed, ct);
|
||||
counting.Reads = 0;
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
Assert.HasCount(2, items);
|
||||
Assert.IsTrue(items.All(i => i.State == ExportItemState.Skipped && i.Note == ExportText.Notes.NotFound), string.Join(", ", items.Select(i => $"{i.State} {i.Note}")));
|
||||
Assert.AreEqual(0, counting.Reads, "no file read, hashed or converted when nothing is there");
|
||||
Assert.AreEqual(ExportVariant.Converted, items.Single(i => i.MediaId == photo.Media[0].Id).Variant);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecognitionNeverWritesOrDeletesAFile()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r08", 7, 8, 9);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
var different = PutCopy(bed, bed.Marta, post.Media[1]);
|
||||
await File.WriteAllBytesAsync(different, [9, 9, 9], ct);
|
||||
|
||||
// A frame whose row says «Superato»: its item gets the folder of the row (where a copy job cleans its .part).
|
||||
var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"));
|
||||
var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "r08v", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")])).Media[0];
|
||||
var frame = await FrameAsync(bed, video, TimeSpan.Zero, ct);
|
||||
await bed.Db.Exports.UpdateCopyAsync(frame with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(778), StateChangedAt = bed.Clock.Now }, ct);
|
||||
|
||||
// Temporary files left by someone in the items' folders: a copy job cleans its own, «Riconosci» touches nothing.
|
||||
var strays = new[] { different, Full(bed, frame.RelativePath!) }
|
||||
.Select(f => Path.Combine(Path.GetDirectoryName(f)!, SafeFileWriter.TempPrefix + "stray.part"))
|
||||
.ToList();
|
||||
foreach (var stray in strays)
|
||||
{
|
||||
await File.WriteAllBytesAsync(stray, [1], ct);
|
||||
}
|
||||
|
||||
File.SetLastWriteTimeUtc(different, new DateTime(2021, 3, 4, 5, 6, 7, DateTimeKind.Utc));
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
var times = Times(bed.Usb);
|
||||
var library = Fingerprint.Of(bed.Library.Layout.Root, "febe.db");
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
Assert.AreEqual(ExportItemState.Adopted, items.Single(i => i.Variant == ExportVariant.Frame).State, "the frame revived");
|
||||
var states = items.Where(i => i.Variant != ExportVariant.Frame).Select(i => i.State).Order().ToList();
|
||||
CollectionAssert.AreEqual(new[] { ExportItemState.Adopted, ExportItemState.Skipped, ExportItemState.Skipped, ExportItemState.Skipped }, states);
|
||||
Assert.IsTrue(strays.All(File.Exists));
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the destination");
|
||||
CollectionAssert.AreEqual(times, Times(bed.Usb), "names, lengths and times");
|
||||
Fingerprint.AreEqual(library, Fingerprint.Of(bed.Library.Layout.Root, "febe.db"), "the library");
|
||||
}
|
||||
|
||||
/// <summary>Answer 51: a «Tolto» stays «Tolto» even when its file came back identical; only «Copia di nuovo» copies it.</summary>
|
||||
[TestMethod]
|
||||
public async Task ARemovedCopyWhoseFileCameBackIdenticalStaysRemoved()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r09", 10);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
|
||||
var file = bed.GeneralCopy(bed.Marta, media);
|
||||
File.Move(file, file + ".away");
|
||||
await bed.Service.CheckCopiesAsync(usb.Id, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(copyId, ct))!.State);
|
||||
File.Move(file + ".away", file); // back, byte for byte
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
Assert.HasCount(0, await bed.ItemsAsync(run.Id, ct), "not even looked for");
|
||||
var rows = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
|
||||
Assert.AreEqual((copyId, ExportCopyState.Removed), (rows.Single().Id, rows.Single().State));
|
||||
|
||||
// A Recognize run planned before the «Tolto» (resumed later) leaves it «Tolto» too.
|
||||
var planned = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, Kind = ExportRunKind.Recognize, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
|
||||
await bed.Db.Exports.AddItemsAsync([new ExportItem { RunId = planned.Id, MediaId = media.Id, AccountId = bed.Marta.Id, SourceSha256 = media.Sha256 }], ct);
|
||||
await bed.Service.ResumeAsync([planned.Id], ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
var item = (await bed.ItemsAsync(planned.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Removed, (long?)copyId), (item.State, item.Note, item.CopyId));
|
||||
rows = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
|
||||
Assert.AreEqual((copyId, ExportCopyState.Removed), (rows.Single().Id, rows.Single().State));
|
||||
|
||||
// «Copia di nuovo» still copies it.
|
||||
Assert.AreEqual(1, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id), CopyAgain: true), ct)).Files);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFailedIdentityBecomesCopiedNotDuplicated()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r10", 11);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var failed = await bed.Db.Exports.AddCopyAsync(
|
||||
new ExportCopy
|
||||
{
|
||||
DestinationId = usb.Id,
|
||||
AccountId = bed.Marta.Id,
|
||||
MediaId = media.Id,
|
||||
SourceSha256 = media.Sha256!,
|
||||
Variant = ExportVariant.Whole,
|
||||
State = ExportCopyState.Failed,
|
||||
CopiedAt = bed.Clock.Now,
|
||||
LastError = "Errore di lettura o scrittura",
|
||||
},
|
||||
ct);
|
||||
PutCopy(bed, bed.Marta, media);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)failed.Id), (item.State, item.CopyId));
|
||||
var row = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
|
||||
Assert.AreEqual((failed.Id, ExportCopyState.Copied, ExportCopyOrigin.Adopted, (string?)null), (row.Id, row.State, row.Origin, row.LastError));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnOrphanRowIsRelinked()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.PostAsync(bed.Marta, "r11", 12);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
|
||||
|
||||
// marta.demo is removed (her copy stays without an account); an account with that name but another id comes back
|
||||
// with the same post: the copy does not come back by itself.
|
||||
await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct);
|
||||
Directory.Delete(bed.Library.Layout.AccountFolder(bed.Marta), recursive: true);
|
||||
var again = await bed.Db.Accounts.AddAsync(Make.Account("marta.demo", "999"), ct);
|
||||
await bed.PostAsync(again, "r11", 12);
|
||||
Assert.IsNull((await bed.Db.Exports.GetCopyAsync(copyId, ct))!.AccountId);
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)copyId), (item.State, item.CopyId));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!;
|
||||
Assert.AreEqual((again.Id, ExportCopyState.Copied), (row.AccountId, row.State));
|
||||
Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASupersededRowWithMatchingBytesIsRevived()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r12", 13);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
|
||||
|
||||
// Recorded «Superato» although the library still has (again) these very bytes: «Superato» is not «Tolto».
|
||||
var copy = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!;
|
||||
await bed.Db.Exports.UpdateCopyAsync(copy with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(777), StateChangedAt = bed.Clock.Now }, ct);
|
||||
Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct)).Files, "a copy job leaves it");
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)copyId), (item.State, item.CopyId));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!;
|
||||
Assert.AreEqual((ExportCopyState.Copied, (string?)null, post.Media[0].Id), (row.State, row.SupersededBySha256, row.MediaId));
|
||||
Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFrameWithAFailedRowIsRecognised_RemovedFramesStayRemoved_FramesWithoutRowsAreNotCandidates()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"));
|
||||
var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "r13", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")])).Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var at0 = await FrameAsync(bed, video, TimeSpan.Zero, ct);
|
||||
var at1 = await FrameAsync(bed, video, TimeSpan.FromMilliseconds(100), ct);
|
||||
var at2 = await FrameAsync(bed, video, TimeSpan.FromMilliseconds(200), ct);
|
||||
|
||||
// At 0 s the copy said «Non riuscito» (the file was written all the same, by an earlier Febe or by hand); at 0,1 s
|
||||
// the frame is «Tolto» although its file is there; at 0,2 s the frame was never recorded (its row is gone).
|
||||
await bed.Db.Exports.UpdateCopyAsync(at0 with { State = ExportCopyState.Failed, RelativePath = null, Bytes = null, CopySha256 = null, LastError = "x" }, ct);
|
||||
await bed.Db.Exports.UpdateCopyAsync(at1 with { State = ExportCopyState.Removed, StateChangedAt = bed.Clock.Now }, ct);
|
||||
await DeleteCopyAsync(bed, at2.Id, ct);
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
var frame = items.Single(i => i.Variant == ExportVariant.Frame);
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)at0.Id, at0.FrameAt), (frame.State, frame.CopyId, frame.FrameAt));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(at0.Id, ct))!;
|
||||
Assert.AreEqual((ExportCopyState.Copied, at0.RelativePath, at0.CopySha256), (row.State, row.RelativePath, row.CopySha256));
|
||||
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(at1.Id, ct))!.State, "a «Tolto» frame stays «Tolto»");
|
||||
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotFound), (items.Single(i => i.Variant != ExportVariant.Frame).State, items.Single(i => i.Variant != ExportVariant.Frame).Note), "the video itself");
|
||||
Assert.HasCount(2, items, "no item for the frame never recorded, nor for the «Tolto» one");
|
||||
Assert.HasCount(2, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Where(c => c.State != ExportCopyState.Failed));
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnOrphanFrameIsRelinkedByTheBytesItsRowRecorded()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"));
|
||||
var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "r14", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")])).Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var frame = await FrameAsync(bed, video, TimeSpan.Zero, ct);
|
||||
await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct);
|
||||
Directory.Delete(bed.Library.Layout.AccountFolder(bed.Marta), recursive: true);
|
||||
var again = await bed.Db.Accounts.AddAsync(Make.Account("marta.demo", "999"), ct);
|
||||
await bed.Library.SaveAsync(again, Make.Entry(again.Id, "r14", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")]);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single(i => i.Variant == ExportVariant.Frame);
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)frame.Id), (item.State, item.CopyId));
|
||||
Assert.AreEqual((again.Id, ExportCopyState.Copied), ((await bed.Db.Exports.GetCopyAsync(frame.Id, ct))!.AccountId, (await bed.Db.Exports.GetCopyAsync(frame.Id, ct))!.State));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OneOnlyIsRespected()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
|
||||
var marta = await bed.PostAsync(bed.Marta, "r15", 14);
|
||||
var luca = await bed.PostAsync(bed.Luca, "r15", 14); // the same bytes for another account
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, marta.Media[0]);
|
||||
var lucasCopy = PutCopy(bed, bed.Luca, luca.Media[0]); // an identical file at luca's path too
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
Assert.AreEqual(ExportItemState.Adopted, items.Single(i => i.AccountId == bed.Marta.Id).State);
|
||||
var rows = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
|
||||
Assert.AreEqual(bed.Marta.Id, rows.Single().AccountId, "one copy only: luca's file is not recorded");
|
||||
Assert.IsTrue(File.Exists(lucasCopy));
|
||||
|
||||
// Planned before marta's copy was recognised (two pages, or a resume): the item ends «già copiato per un altro account».
|
||||
var lucasItem = items.SingleOrDefault(i => i.AccountId == bed.Luca.Id);
|
||||
Assert.IsTrue(lucasItem is null || (lucasItem.State == ExportItemState.AlreadyCopied && lucasItem.Note == ExportText.Notes.CopiedForAnotherAccount), $"{lucasItem?.State} {lucasItem?.Note}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnUnreachableRootPausesAndMarksNothing()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r16", 15, 16);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
Directory.Move(bed.Usb, bed.Usb + "-staccata");
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
Assert.AreEqual(ExportRunState.Paused, run.State);
|
||||
Assert.IsTrue((await bed.ItemsAsync(run.Id, ct)).All(i => i.State == ExportItemState.Pending), "nothing marked «Non c'è»");
|
||||
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||
Assert.HasCount(0, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
|
||||
Assert.IsFalse(Directory.Exists(bed.Usb), "the root is never created");
|
||||
|
||||
// Back: «Riprova» resumes it, and it ends.
|
||||
Directory.Move(bed.Usb + "-staccata", bed.Usb);
|
||||
var retry = await bed.Service.RetryDestinationAsync(usb.Id, ct);
|
||||
Assert.AreEqual(run.Id, retry.Resumed.Single().Id);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||
var states = (await bed.ItemsAsync(run.Id, ct)).ToDictionary(i => i.MediaId!.Value, i => (i.State, i.Note));
|
||||
Assert.AreEqual((ExportItemState.Adopted, (string?)null), states[post.Media[0].Id]);
|
||||
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotFound), states[post.Media[1].Id]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARecognizeRunIsResumable()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r17", 17, 18);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
PutCopy(bed, bed.Marta, post.Media[1]);
|
||||
|
||||
// Febe stopped in the middle of a Recognize run: the first file was recognised, the second still waits.
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
var second = items.Single(i => i.MediaId == post.Media[1].Id);
|
||||
var copyId = second.CopyId!.Value;
|
||||
await bed.Db.Exports.UpdateItemsAsync([second with { State = ExportItemState.Pending, CopyId = null, RelativePath = null }], ct);
|
||||
await DeleteCopyAsync(bed, copyId, ct);
|
||||
await bed.Db.Exports.UpdateRunAsync(run with { State = ExportRunState.Running, CompletedAt = null }, ct);
|
||||
|
||||
Assert.AreEqual(1, await bed.Service.RecoverAsync(ct));
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(run.Id, ct)).State);
|
||||
await bed.Service.ResumeAsync(null, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||
Assert.IsTrue((await bed.ItemsAsync(run.Id, ct)).All(i => i.State == ExportItemState.Adopted));
|
||||
Assert.HasCount(2, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Where(c => c.State == ExportCopyState.Copied));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARecognizeRunWritesOnlyItsOwnEvent()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r18", 19, 20);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
|
||||
await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var events = await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct);
|
||||
Assert.IsFalse(events.Any(e => e.Code == "esportazione-completata"));
|
||||
var recognized = events.Single(e => e.Code == ExportText.RecognizeEventCode);
|
||||
Assert.AreEqual(("Riconosciuta 1 copia già presente in Disco USB.", EventSeverity.Success), (recognized.Message, recognized.Severity));
|
||||
|
||||
// Nothing more to recognise: information, not success.
|
||||
await RecognizeAsync(bed, usb, ct);
|
||||
var second = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Where(e => e.Code == ExportText.RecognizeEventCode).OrderBy(e => e.Id).Last();
|
||||
Assert.AreEqual(("Nessuna copia già presente da riconoscere in Disco USB.", EventSeverity.Info), (second.Message, second.Severity));
|
||||
Assert.IsFalse((await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Any(e => e.Code == "esportazione-completata"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecognizeReportCountsNotFoundAndDifferentAndListsOnlyDifferent()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r19", 21, 22, 23, 24);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
await File.WriteAllBytesAsync(PutCopy(bed, bed.Marta, post.Media[1]), [1, 2], ct);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
var report = await bed.Service.Reports.BuildAsync(run.Id, ct);
|
||||
|
||||
Assert.AreEqual((2, 1), (report.NotFound, report.Different));
|
||||
Assert.AreEqual(1, report.ByState[ExportItemState.Adopted]);
|
||||
var problem = report.Problems.Single();
|
||||
Assert.AreEqual(("Nel percorso c'è un altro file", "marta.demo/" + post.Media[1].RelativePath), (problem.Text, problem.RelativePath));
|
||||
|
||||
// In a copy job nothing changes: a skipped file with a note is a problem line, and nothing is counted by note.
|
||||
var copy = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyReport = await bed.Service.Reports.BuildAsync(copy.Runs.Single().Id, ct);
|
||||
Assert.AreEqual((0, 0), (copyReport.NotFound, copyReport.Different));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecognitionPreemptsAnAutomaticJob()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var held = new HeldExportFileSystem(p => p.EndsWith("_2.jpg", StringComparison.Ordinal));
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||
var post = await bed.PostAsync(bed.Luca, "r20", 25, 26, 27);
|
||||
var other = await bed.PostAsync(bed.Marta, "r21", 28);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, other.Media[0]);
|
||||
var spec = new DestinationSpec(usb.Scope, usb.AccountId, usb.RootPath, usb.Label, usb.ContentTypes, usb.NamingScheme, usb.HighlightNamingScheme, usb.ProfileNamingScheme, Automatic: true, OnlyNew: false);
|
||||
var auto = (await bed.Service.Destinations.UpdateAsync(usb.Id, spec, ct)).Destination;
|
||||
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, false, ct);
|
||||
|
||||
var start = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([new ExportSelection.AutomaticScope(auto.Id, auto.AutomaticSince)], [], true), ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
Assert.IsTrue(bed.Service.AutomaticRunning);
|
||||
|
||||
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, true, ct);
|
||||
var run = await bed.Service.RecognizeAsync(usb.Id, ct);
|
||||
Assert.AreEqual((ExportRunState.Interrupted, (string?)null), ((await bed.RunAsync(start.Runs.Single().Id, ct)).State, (await bed.RunAsync(start.Runs.Single().Id, ct)).LastError), "displaced, not failed");
|
||||
Assert.IsFalse(bed.Service.AutomaticRunning);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||
Assert.AreEqual(ExportItemState.Adopted, (await bed.ItemsAsync(run.Id, ct)).Single(i => i.MediaId == other.Media[0].Id).State);
|
||||
held.Release();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecognizeRefusesARetiredOrUnknownDestinationAndWhileAJobRuns()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||
await bed.PostAsync(bed.Marta, "r22", 29);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var own = await bed.OwnAsync(bed.Luca, "luca-own", ct: ct);
|
||||
await bed.Service.Destinations.RetireAsync(own.Id, ct);
|
||||
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => bed.Service.RecognizeAsync(9999, ct));
|
||||
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.RecognizeAsync(own.Id, ct));
|
||||
|
||||
// A «Copia in…» of Alberto's runs: «Riconosci» waits for it, it does not displace it.
|
||||
await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.RecognizeAsync(usb.Id, ct));
|
||||
held.Release();
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.IsFalse((await bed.Db.Exports.ListRunsAsync(ct)).Any(r => r.Kind == ExportRunKind.Recognize), "a refused start records nothing");
|
||||
}
|
||||
|
||||
// Helpers -------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>«Riconosci» and waits for its job.</summary>
|
||||
private static async Task<ExportRun> RecognizeAsync(ExportTestBed bed, ExportDestination destination, CancellationToken ct)
|
||||
{
|
||||
var run = await bed.Service.RecognizeAsync(destination.Id, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
return await bed.RunAsync(run.Id, ct);
|
||||
}
|
||||
|
||||
/// <summary>The general folder at <see cref="ExportTestBed.Usb"/> asking PNG for photos.</summary>
|
||||
private static async Task<ExportDestination> GeneralInPngAsync(ExportTestBed bed, CancellationToken ct) =>
|
||||
(await bed.Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, bed.Usb, "Disco USB", ContentTypes.All, null, null, null, PhotoFormat: ExportFormat.Png), ct)).Destination;
|
||||
|
||||
/// <summary>A byte copy of the library file at the path of the general folder «Come la libreria» (by hand, or an older Febe).</summary>
|
||||
private static string PutCopy(ExportTestBed bed, Account account, Media media)
|
||||
{
|
||||
var path = bed.GeneralCopy(account, media);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.Copy(bed.LibraryFile(account, media), path);
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>A PNG frame of «Questo istante» written by Febe; its copy row.</summary>
|
||||
private static async Task<ExportCopy> FrameAsync(ExportTestBed bed, Media video, TimeSpan at, CancellationToken ct)
|
||||
{
|
||||
var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: new ExportFramesRequest(FrameMode.At, at, null, null, ExportFormat.Png)), ct);
|
||||
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
|
||||
Assert.AreEqual(ExportItemState.Copied, item.State);
|
||||
return (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
|
||||
}
|
||||
|
||||
/// <summary>A copy row gone from the database (its items keep no link to it).</summary>
|
||||
private static Task DeleteCopyAsync(ExportTestBed bed, long copyId, CancellationToken ct) =>
|
||||
bed.Db.WriteAsync(x => x.Command("DELETE FROM export_copy WHERE id = @id").With("@id", copyId).ExecuteNonQuery(), ct);
|
||||
|
||||
private static string Full(ExportTestBed bed, string relativePath) => Path.Combine(bed.Usb, LibraryLayout.ToPlatform(relativePath));
|
||||
|
||||
/// <summary>Every file of a folder tree with its length and last write time.</summary>
|
||||
private static List<string> Times(string folder) =>
|
||||
[.. Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)
|
||||
.Select(f => $"{Path.GetRelativePath(folder, f)}:{new FileInfo(f).Length}:{File.GetLastWriteTimeUtc(f).Ticks}")
|
||||
.Order(StringComparer.Ordinal)];
|
||||
|
||||
/// <summary>The real file system, counting every read of a file (opened, or hashed).</summary>
|
||||
private sealed class CountingExportFileSystem : IExportFileSystem
|
||||
{
|
||||
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
|
||||
private int _reads;
|
||||
|
||||
public int Reads
|
||||
{
|
||||
get => Volatile.Read(ref _reads);
|
||||
set => Volatile.Write(ref _reads, value);
|
||||
}
|
||||
|
||||
public Stream OpenRead(string path)
|
||||
{
|
||||
Interlocked.Increment(ref _reads);
|
||||
return _inner.OpenRead(path);
|
||||
}
|
||||
|
||||
public Stream OpenRandomAccess(string path)
|
||||
{
|
||||
Interlocked.Increment(ref _reads);
|
||||
return _inner.OpenRandomAccess(path);
|
||||
}
|
||||
|
||||
public Task<string> ComputeSha256Async(string path, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _reads);
|
||||
return _inner.ComputeSha256Async(path, ct);
|
||||
}
|
||||
|
||||
public bool FileExists(string path) => _inner.FileExists(path);
|
||||
|
||||
public long? FileLength(string path) => _inner.FileLength(path);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user