diff --git a/src/CCVTAC.Main/CCVTAC.Main.fsproj b/src/CCVTAC.Main/CCVTAC.Main.fsproj index 864d6480..06eab378 100644 --- a/src/CCVTAC.Main/CCVTAC.Main.fsproj +++ b/src/CCVTAC.Main/CCVTAC.Main.fsproj @@ -40,12 +40,12 @@ - + - + diff --git a/src/CCVTAC.Main/Downloading/Updater.fs b/src/CCVTAC.Main/Downloading/Updater.fs index 3b212432..0759ae41 100644 --- a/src/CCVTAC.Main/Downloading/Updater.fs +++ b/src/CCVTAC.Main/Downloading/Updater.fs @@ -11,21 +11,17 @@ module Updater = let run (printer: Printer) userSettings : unit = if String.hasNoText userSettings.DownloaderUpdateCommand then - printer.Info "No downloader update command provided, so will skip." + printer.Info "No downloader update command provided, so will skip updating." else let toolSettings = ToolSettings.create userSettings.DownloaderUpdateCommand userSettings.WorkingDirectory - let executionResult = Runner.runTool printer toolSettings [] - - match executionResult with + match Runner.runTool printer toolSettings [] with | Ok details -> if details.ExitCode <> successExitCode then - match details.Error with - | Some errMsg -> $"Update completed with minor issues: {errMsg}" - | None -> "Update completed with minor unspecified issues." - |> printer.Warning - printer.EmptyLine() + printer.Warning <| + match details.Error with + | Some errMsg -> $"Update completed with minor issues: {errMsg}" + | None -> "Update completed with minor unspecified issues." | Error msg -> - let printOptions = { PrintOptions.Default with AppendLines = 1uy } - printer.Error($"Failure updating: {msg}", printOptions) + printer.Error $"Update failure: {msg}" diff --git a/src/CCVTAC.Main/History.fs b/src/CCVTAC.Main/History.fs index d16c6cf0..c3c04bad 100644 --- a/src/CCVTAC.Main/History.fs +++ b/src/CCVTAC.Main/History.fs @@ -6,6 +6,7 @@ open CCFSharpUtils.Text open System open System.IO open System.Text.Json +open FSharpPlus open Spectre.Console type History(filePath: string, displayCount: int) = @@ -39,9 +40,9 @@ type History(filePath: string, displayCount: int) = |> Seq.choose (fun line -> match line.Split separator with | [| dateText; url |] -> - match DateTime.TryParse dateText with - | true, date -> Some (date, url) - | _ -> None + DateTime.TryParse dateText + |> Option.ofPair + |> Option.map (fun date -> (date, url)) | _ -> None) |> Seq.groupBy fst |> Seq.map (fun (dt, pairs) -> dt, pairs |> Seq.map snd |> Seq.toList) diff --git a/src/CCVTAC.Main/IoUtilities/Directories.fs b/src/CCVTAC.Main/IoUtilities/Directories.fs index b077743b..40a7d903 100644 --- a/src/CCVTAC.Main/IoUtilities/Directories.fs +++ b/src/CCVTAC.Main/IoUtilities/Directories.fs @@ -11,6 +11,9 @@ module Directories = [] let private allFilesSearchPattern = "*" + [] + let maxFilesToShow = 10 + /// Counts the number of audio files in a directory. let audioFileCount dirName includedExtensions = DirectoryInfo(dirName).EnumerateFiles() @@ -46,10 +49,9 @@ module Directories = |> Result.map delete /// Ask the user to confirm the deletion of files in the specified directory. - let askToDeleteAllFiles (printer: Printer) dirName = - if printer.AskToBool("Delete all temporary files?", "Yes", "No") - then deleteAllFiles dirName - else Error "Will not delete the files." + let confirmDeleteFiles (printer: Printer) : ConfirmationAnswer = + let answer = printer.AskToBool("Delete all temporary files?", "Yes", "No") + if answer then Proceed else Decline "Temporary file deletion was declined." let printDeletionResults (printer: Printer) (results: ResultMessages) : unit = printer.Info $"Deleted %s{String.fileLabel results.Successes.Length}." @@ -66,12 +68,12 @@ module Directories = if Array.isEmpty fileNames then Ok () else - SB($"Unexpectedly found {String.fileLabel fileNames.Length} in working directory \"{dirName}\":{String.nl}") + SB($"""Found {String.plur' "leftover file" S fileNames.Length} in working directory "{dirName}":{String.nl}""") .AppendLine (fileNames |> Array.truncate showMax |> Array.map (sprintf "• %s") - |> String.concat String.nl) + |> String.concatNL) |> fun sb -> if fileNames.Length > showMax then sb.AppendLine $"... plus {fileNames.Length - showMax} more." diff --git a/src/CCVTAC.Main/IoUtilities/Files.fs b/src/CCVTAC.Main/IoUtilities/Files.fs index 442dea51..1d25e6a2 100644 --- a/src/CCVTAC.Main/IoUtilities/Files.fs +++ b/src/CCVTAC.Main/IoUtilities/Files.fs @@ -14,7 +14,7 @@ module Files = let imageFileExts = [".jpg"; ".jpeg"] - let filterByExt ext fs = fs |> List.filter (String.endsWithIgnoreCase ext) + let filterByExt ext fs = fs |> List.filter (String.endsWith' ext) let readAllText (filePath: string) : Result = ofTry (fun _ -> File.ReadAllText filePath) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 4b5f59e4..7883c352 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -4,23 +4,44 @@ open CCVTAC.Main.Downloading open CCVTAC.Main.InputHelper open CCVTAC.Main.IoUtilities open CCVTAC.Main.PostProcessing -open CCVTAC.Main.Settings open CCVTAC.Main.Settings.Settings open CCVTAC.Main.Settings.Settings.LiveUpdating open CCFSharpUtils.Collections open CCFSharpUtils.Text +open FSharpPlus open Startwatch.Library open System open System.Globalization module Orchestrator = - type NextAction = Continue | QuitAtUserRequest | QuitDueToErrors + type NextAction = + | Continue + | QuitAtUserRequest + | QuitDueToErrors type BatchResults = { NextAction: NextAction UpdatedSettings: UserSettings option } + /// Distinguishes input-level failures (skip and continue) from failures + /// that should halt the batch. + type ProcessError = + | Recoverable of string + | Fatal of string + + type ToggleSpec = + { Triggers: string list + Label: string + Toggle: UserSettings -> UserSettings + Read: UserSettings -> bool + AfterToggle: UserSettings -> unit } + + let private errorText error : string = + match error with + | Recoverable msg + | Fatal msg -> msg + let summarizeInput (printer: Printer) (inputs: CategorizedInput list) @@ -28,7 +49,7 @@ module Orchestrator = : unit = if List.hasMultiple inputs then - let urlSummary = String.plur' "URL" S counts[Url] + let urlSummary = String.plur' "URL" S counts[Url] let cmdSummary = String.plur' "command" S counts[Command] printer.Info <| @@ -41,47 +62,43 @@ module Orchestrator = for input in inputs do printer.Info $" • %s{input.Text}" - printer.EmptyLine() - let processUrl (printer: Printer) (url: string) (settings: UserSettings) - (resultTracker: ResultTracker) (history: History) (urlInputTime: DateTime) (batchSize: int) (urlIndex: int) - : Result = + : Result = - match Directories.warnIfAnyFiles 10 settings.WorkingDirectory with + match Directories.warnIfAnyFiles Directories.maxFilesToShow settings.WorkingDirectory with | Error err -> - printer.Error err - Ok { NextAction = QuitDueToErrors; UpdatedSettings = None } + Error (Fatal err) | Ok () -> if batchSize > 1 then - printer.Info $"Processing item %d{urlIndex} of %d{batchSize}..." + let options = PrintOptions.DefaultWithLineBefore + let message = $"Processing URL %d{urlIndex} of %d{batchSize}..." + printer.Info(message, options) let jobWatch = Watch() match Downloading.mediaTypeWithIds url with - | Error e -> - let errorMsg = $"URL parse error: %s{e}" - printer.Error errorMsg - Error errorMsg + | Error errMsg -> + Error (Recoverable $"URL parse error: %s{errMsg}") | Ok mediaType -> printer.Info $"%s{mediaType.GetType().Name} URL '%s{url}' detected." history.Append(url, urlInputTime, printer) let downloadResult = Downloader.run printer mediaType settings - resultTracker.RegisterResult(url, downloadResult) match downloadResult with | Error errs -> - errs - |> List.map (sprintf "Media download error: %s") - |> String.concat String.nl - |> Error + let groupedErrs = + errs + |> List.map (sprintf "Media download error: %s") + |> String.concatNL + Error (Recoverable groupedErrs) | Ok message -> printer.Debug "Download successful." if String.hasText message then printer.Info message @@ -95,253 +112,258 @@ module Orchestrator = printer.Info $"Processed '%s{url}'%s{groupClause} in %s{jobWatch.ElapsedFriendly}." Ok { NextAction = Continue; UpdatedSettings = None } - let summarizeToggle settingName setting = - sprintf "%s toggled to %s for this session." settingName (if setting then "ON" else "OFF") + let summarizeToggle settingName setting : string = + let state = if setting then "ON" else "OFF" + $"%s{settingName} toggled to %s{state} for this session." - let summarizeUpdate settingName setting = - sprintf "%s updated to \"%s\" for this session." settingName setting + let summarizeUpdate settingName setting : string = + $"%s{settingName} updated to \"%s{setting}\" for this session." - let private extractValue (prefix: string) (command: string) : string = + let private extractCommandValue (prefix: string) (command: string) : string = command.Substring(prefix.Length).Trim() - let processCommand - (printer: Printer) - (command: string) - (settings: UserSettings) - (history: History) - : Result = - + let private toggleSpecs (printer: Printer) : ToggleSpec list = + [ { Triggers = Commands.splitChapterToggles + Label = "Split Chapters" + Toggle = toggleSplitChapters + Read = _.SplitChapters + AfterToggle = ignore } + + { Triggers = Commands.embedImagesToggles + Label = "Embed Images" + Toggle = toggleEmbedImages + Read = _.EmbedImages + AfterToggle = ignore } + + { Triggers = Commands.quietModeToggles + Label = "Quiet Mode" + Toggle = toggleQuietMode + Read = _.QuietMode + AfterToggle = fun s -> printer.ShowDebug(not s.QuietMode) } ] + + let processCommand printer command settings (history: History) : Result = let checkCommand = List.containsIgnoreCase command + let toggle = toggleSpecs printer |> List.tryFind (fun spec -> checkCommand spec.Triggers) - // Help - if String.equalIgnoreCase Commands.helpCommand command then - for kvp in Commands.summary do - printer.Info kvp.Key - printer.Info $" %s{kvp.Value}" - Ok { NextAction = Continue; UpdatedSettings = None } - - // Quit - elif checkCommand Commands.quitCommands then - Ok { NextAction = QuitAtUserRequest; UpdatedSettings = None } - - // History - elif checkCommand Commands.history then - history.ShowRecent printer - Ok { NextAction = Continue; UpdatedSettings = None } - - // Update media downloader - elif checkCommand Commands.updateDownloader then - Updater.run printer settings - Ok { NextAction = Continue; UpdatedSettings = None } - - // Settings summary - elif checkCommand Commands.settingsSummary then - Settings.toTable settings |> printer.PrintTable - Ok { NextAction = Continue; UpdatedSettings = None } - - // Toggle split chapters - elif checkCommand Commands.splitChapterToggles then - let newSettings = toggleSplitChapters settings - printer.Info(summarizeToggle "Split Chapters" newSettings.SplitChapters) - Ok { NextAction = Continue; UpdatedSettings = Some newSettings } + match toggle with + | Some spec -> + let newSettings = spec.Toggle settings - // Toggle embed images - elif checkCommand Commands.embedImagesToggles then - let newSettings = toggleEmbedImages settings - printer.Info(summarizeToggle "Embed Images" newSettings.EmbedImages) - Ok { NextAction = Continue; UpdatedSettings = Some newSettings } + let message = summarizeToggle spec.Label (spec.Read newSettings) + let options = PrintOptions.DefaultWithLineBefore + printer.Info(message, options) + + spec.AfterToggle newSettings - // Toggle quiet mode - elif checkCommand Commands.quietModeToggles then - let newSettings = toggleQuietMode settings - printer.Info(summarizeToggle "Quiet Mode" newSettings.QuietMode) - printer.ShowDebug(not newSettings.QuietMode) Ok { NextAction = Continue; UpdatedSettings = Some newSettings } - // Update audio formats - elif command |> String.startsWithIgnoreCase Commands.updateAudioFormatPrefix then - let format = - command - |> extractValue Commands.updateAudioFormatPrefix - |> _.ToLowerInvariant() + | None -> + if String.equalIgnoreCase Commands.helpCommand command then + for pair in Commands.summary do + printer.Info pair.Key + printer.Info $" %s{pair.Value}" + Ok { NextAction = Continue; UpdatedSettings = None } - if String.hasNoText format then - Error "You must append one or more supported audio formats separated by commas (e.g., \"m4a,opus,best\")." - else - let updateResult = updateAudioFormat settings format - match updateResult with - | Error err -> - Error err - | Ok newSettings -> - let audioFormats = String.Join(", ", newSettings.AudioFormats) - printer.Info <| summarizeUpdate "Audio Formats" audioFormats - Ok { NextAction = Continue; UpdatedSettings = Some newSettings } - - // Update audio quality - elif command |> String.startsWithIgnoreCase Commands.updateAudioQualityPrefix then - let inputQuality = extractValue Commands.updateAudioQualityPrefix command - let rangeRule = "Audio quality must be between 10 (lowest) and 0 (highest)." - - if String.hasNoText inputQuality then - Error rangeRule - else - match Byte.TryParse(inputQuality, NumberStyles.None, CultureInfo.InvariantCulture) with - | true, quality when quality <= 10uy -> - match updateAudioQuality settings quality with - | Error err -> - Error err - | Ok updatedSettings -> - let updatedQuality = updatedSettings.AudioQuality.ToString() - printer.Info <| summarizeUpdate "Audio Quality" updatedQuality - Ok { NextAction = Continue - UpdatedSettings = Some updatedSettings } - | true, _ -> - Error rangeRule - | _ -> - Error $"\"%s{inputQuality}\" is an invalid quality value. %s{rangeRule}" + elif checkCommand Commands.quitCommands then + Ok { NextAction = QuitAtUserRequest; UpdatedSettings = None } + + elif checkCommand Commands.history then + history.ShowRecent printer + Ok { NextAction = Continue; UpdatedSettings = None } - // Unknown command - else - Error <| - sprintf "\"%s\" is not a valid command. Enter \"%s\" to see a list of commands." + elif checkCommand Commands.updateDownloader then + Updater.run printer settings + Ok { NextAction = Continue; UpdatedSettings = None } + + elif checkCommand Commands.settingsSummary then + printer.PrintTable (toTable settings) + Ok { NextAction = Continue; UpdatedSettings = None } + + elif command |> String.startsWith' Commands.updateAudioFormatPrefix then + let format = command - $"""{(string Commands.prefix)}help""" + |> extractCommandValue Commands.updateAudioFormatPrefix + |> _.ToLowerInvariant() + + if String.hasNoText format then + Error "Append one or more supported audio formats separated by commas (e.g., \"m4a,opus,best\")." + else + monad { + let! newSettings = updateAudioFormat settings format + let audioFormats = String.Join(", ", newSettings.AudioFormats) + printer.Info <| summarizeUpdate "Audio Formats" audioFormats + { NextAction = Continue; UpdatedSettings = Some newSettings } + } + + elif command |> String.startsWith' Commands.updateAudioQualityPrefix then + let inputQuality = extractCommandValue Commands.updateAudioQualityPrefix command + let limit = 10uy + let rangeMsg = $"Audio quality must be a number between %d{limit} (lowest) and 0 (highest)." + match Byte.TryParse(inputQuality, NumberStyles.None, CultureInfo.InvariantCulture) with + | true, quality when quality <= limit -> + monad { + let! newSettings = updateAudioQuality settings quality + printer.Info <| summarizeUpdate "Audio Quality" (newSettings.AudioQuality.ToString()) + { NextAction = Continue; UpdatedSettings = Some newSettings } + } + | _ -> Error rangeMsg + else + Error $"\"%s{command}\" is not a valid command. Enter \"%c{Commands.prefix}help\" to see a list of commands." /// Processes a single user request, from input to downloading and file post-processing. - /// Returns the next action the application should take (e.g., continue or quit). let processBatch (printer: Printer) (inputs: CategorizedInput list) (categoryCounts: CategoryCounts) (settings: UserSettings) - (resultTracker: ResultTracker) + (resultTracker: ResultTracker) (history: History) : BatchResults = let inputTime = DateTime.Now let batchWatch = Watch() - let batchResults = ResultTracker printer - - let printSleep (category: InputCategory) = - if category.IsUrl then - let seconds = settings.SleepSecondsBetweenURLs - let secondsMsg secs = String.plur' "second" S secs - let sleptMsg = - sleep - (fun remainingSeconds -> $"Sleeping for {secondsMsg remainingSeconds}...") - (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") - seconds - printer.Info $"{String.nl}{sleptMsg}" - printer.EmptyLine() - - let processInput category text index : Result = - match category with - | Command -> processCommand printer text settings history - | Url -> processUrl printer text settings resultTracker history inputTime inputs.Length index - - let deleteLeftoverFiles dirName : Result = - match Directories.warnIfAnyFiles 10 dirName with + + let printSleepCountdown currentSettings = + let seconds = currentSettings.SleepSecondsBetweenURLs + let secondsMsg secs = String.plur' "second" S secs + let sleptMsg = + sleep + (fun remainingSeconds -> $"Sleeping for {secondsMsg remainingSeconds}...") + (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") + seconds + let options = PrintOptions.DefaultWithLineBefore + printer.Info(sleptMsg, options) + + let processInput settings inputCategory text urlPosition : Result = + match inputCategory with + | Command -> + processCommand printer text settings history + |> Result.mapError Recoverable + | Url -> + processUrl printer text settings history inputTime categoryCounts[Url] urlPosition + + let deleteLeftoverFiles dirName : Result = + match Directories.warnIfAnyFiles Directories.maxFilesToShow dirName with | Ok () -> Ok None - | Error filesFoundErr -> - printer.Error filesFoundErr // Might not need this. - Directories.deleteAllFiles dirName |> function - | Ok results -> + | Error msg -> + printer.Warning msg + Directories.deleteAllFiles dirName + |> Result.map (fun results -> Directories.printDeletionResults printer results - Ok (Some "Files deleted successfully.") - | Error deletionError -> - Error $"Error deleting leftover files after download: {deletionError}" + Some "Files deleted successfully.") + |> Result.mapError (sprintf "Error deleting leftover files after download: %s") - let rec loop inputs settings' nextAction' index : NextAction * UserSettings * int = + let rec loop inputs settings nextAction' index urlPosition : NextAction * UserSettings * int = match inputs with - | [] -> - (nextAction', settings', index) | input :: remainingInputs when nextAction' = Continue -> - let processResult = processInput input.Category input.Text index + let processResult = processInput settings input.Category input.Text urlPosition - batchResults.RegisterResult(input.Text, processResult) + resultTracker.RegisterResult( + input.Text, + processResult |> Result.mapError (errorText >> List.singleton)) - // Deleting the files here might make debugging issues a bit tougher. - match deleteLeftoverFiles settings.WorkingDirectory with - | Error errMsg -> - printer.Error errMsg - (QuitDueToErrors, settings', index) - | Ok message -> - message |> Option.iter printer.Debug - match processResult with - | Error err -> - printer.Error err - if List.isNotEmpty remainingInputs then printSleep input.Category - loop remainingInputs settings' nextAction' (index + 1) - | Ok processResult -> - if List.isNotEmpty remainingInputs then printSleep input.Category - let newSettings = defaultArg processResult.UpdatedSettings settings' - let newNextAction = processResult.NextAction - loop remainingInputs newSettings newNextAction (index + 1) + processResult |> Result.iterError (errorText >> printer.Error) + + match processResult with + | Error (Fatal _) -> + (QuitDueToErrors, settings, index) + | _ -> + let cleanupResult = + if input.Category.IsUrl + then deleteLeftoverFiles settings.WorkingDirectory + else Ok None + + match cleanupResult with + | Error errMsg -> + printer.Error errMsg + (QuitDueToErrors, settings, index + 1) + | Ok message -> + message |> Option.iter printer.Debug + + let isNextUrl = remainingInputs |> tryHead |> exists _.Category.IsUrl + if input.Category.IsUrl && isNextUrl then + printSleepCountdown settings + + let updatedSettings, nextAction = + match processResult with + | Ok result -> defaultArg result.UpdatedSettings settings, result.NextAction + | Error _ -> settings, nextAction' + + // Advance the URL position only when the input was a URL. + let nextUrlPosition = + if input.Category.IsUrl then urlPosition + 1 else urlPosition + + loop remainingInputs updatedSettings nextAction (index + 1) nextUrlPosition | _ -> - (nextAction', settings', index) + (nextAction', settings, index) - let (finalNextAction, finalSettings, processedCount) = - loop inputs settings Continue 1 + let finalNextAction, finalSettings, processedCount = + loop inputs settings Continue 1 1 if categoryCounts[Url] > 1 then - printer.Info( - sprintf "%sFinished with batch of %d URLs in %s." - String.nl + let batchDoneMsg = + sprintf "Finished with batch of %d URLs in %s." categoryCounts[Url] batchWatch.ElapsedFriendly - ) - batchResults.PrintBatchFailures() + let options = PrintOptions.DefaultWithLineBefore + printer.Info(batchDoneMsg, options) + resultTracker.PrintBatchFailures() if processedCount <= inputs.Length then let unprocessedInputs = inputs[processedCount-1..] |> List.map (fun x -> $"• {x.Text}") - |> String.concat String.nl + |> String.concatNL printer.Warning $"Some inputs were not yet processed: {String.nl}{unprocessedInputs}" { NextAction = finalNextAction UpdatedSettings = Some finalSettings } - let private isWorkingDirectoryReady (printer: Printer) dirName : bool = - match Directories.warnIfAnyFiles 10 dirName with - | Ok () -> - true + let private isWorkingDirReady (printer: Printer) dirName : Result = + let emptyDirAndReport dirName = + Directories.deleteAllFiles dirName + |> Result.map (fun msgs -> + Directories.printDeletionResults printer msgs + printer.Debug "Files deleted.") + + match Directories.warnIfAnyFiles Directories.maxFilesToShow dirName with + | Ok () -> Ok () + | Error err -> + printer.Error err + match Directories.confirmDeleteFiles printer with + | Proceed -> emptyDirAndReport dirName + | Decline reason -> Error reason + + let start printer settings : NextAction = + match isWorkingDirReady printer settings.WorkingDirectory with | Error err -> printer.Error err - match Directories.askToDeleteAllFiles printer dirName with - | Ok results -> - Directories.printDeletionResults printer results - true - | Error deletionError -> - printer.Error deletionError - printer.Info "Aborting..." - false - - let start (printer: Printer) (settings: UserSettings) : unit = - if isWorkingDirectoryReady printer settings.WorkingDirectory then - let results = ResultTracker printer + printer.Error "Cannot continue until the working directory is emptied. Quitting..." + QuitDueToErrors // TODO: Modify QuitDueToErrors type to include optional errors? + | Ok () -> + let results = ResultTracker printer let history = History(settings.HistoryFile, settings.HistoryDisplayCount) - let mutable nextAction = Continue - let mutable currentSettings = settings - while nextAction = Continue do + let rec repl (settings: UserSettings) : NextAction = let input = printer.GetInput prompt - let splitInputs = splitInputText input - - match splitInputs with + match splitInputText input with | [] -> printer.Error $"Invalid input. Enter only URLs or commands beginning with \"%c{Commands.prefix}\"." - | _ -> + repl settings + | splitInputs -> let categorizedInputs = categorizeInputs splitInputs let categoryCounts = countCategories categorizedInputs summarizeInput printer categorizedInputs categoryCounts - let batchResult = processBatch printer categorizedInputs categoryCounts currentSettings results history - nextAction <- batchResult.NextAction + let batchResult = processBatch printer categorizedInputs categoryCounts settings results history + + let nextSettings = defaultArg batchResult.UpdatedSettings settings - match batchResult.UpdatedSettings with - | Some newSettings -> currentSettings <- newSettings - | None -> () + match batchResult.NextAction with + | Continue -> repl nextSettings + | action -> + results.PrintSessionSummary() + action - results.PrintSessionSummary() + repl settings diff --git a/src/CCVTAC.Main/PostProcessing/PostProcessing.fs b/src/CCVTAC.Main/PostProcessing/PostProcessing.fs index 2f041e4d..09457dfd 100644 --- a/src/CCVTAC.Main/PostProcessing/PostProcessing.fs +++ b/src/CCVTAC.Main/PostProcessing/PostProcessing.fs @@ -46,9 +46,9 @@ module PostProcessor = let taggingSets = createSets <| Directory.GetFiles dir match taggingSets with | Ok ts -> Ok ts - | Error msgs -> - $"Error(s) creating tagging sets in working directory \"%s{dir}\"" :: msgs - |> String.concat String.nl + | Error errMsgs -> + $"Error(s) creating tagging sets in working directory \"%s{dir}\"" :: errMsgs + |> String.concatNL |> Error with exn -> Error $"Error reading working files in \"{dir}\" for tagging set creation: %s{exn.Message}" diff --git a/src/CCVTAC.Main/PostProcessing/Tagging/Tagger.fs b/src/CCVTAC.Main/PostProcessing/Tagging/Tagger.fs index e1dba8dc..57b462d3 100644 --- a/src/CCVTAC.Main/PostProcessing/Tagging/Tagger.fs +++ b/src/CCVTAC.Main/PostProcessing/Tagging/Tagger.fs @@ -7,6 +7,7 @@ open CCVTAC.Main.PostProcessing.Tagging open CCVTAC.Main.Downloading.Downloading open CCFSharpUtils.Collections open CCFSharpUtils.Text +open FSharpPlus open Startwatch.Library open MetadataUtilities open System @@ -66,9 +67,8 @@ module Tagger = elif videoMetadata.UploadDate.Length <> 4 then None else - match UInt32.TryParse(videoMetadata.UploadDate.Substring(0, 4)) with - | true, parsed -> Some parsed - | _ -> None + UInt32.TryParse(videoMetadata.UploadDate.Substring(0, 4)) + |> Option.ofPair let private tagSingleFile (printer: Printer) diff --git a/src/CCVTAC.Main/Printer.fs b/src/CCVTAC.Main/Printer.fs index f0ec2cd4..338f0106 100644 --- a/src/CCVTAC.Main/Printer.fs +++ b/src/CCVTAC.Main/Printer.fs @@ -21,16 +21,17 @@ type private Colors = type PrintOptions = { AppendLineBreak: bool - PrependLines: byte - AppendLines: byte + LinesBefore: byte ProcessMarkup: bool } static member Default = { AppendLineBreak = true - PrependLines = 0uy - AppendLines = 0uy + LinesBefore = 0uy ProcessMarkup = true } + static member DefaultWithLineBefore = + { PrintOptions.Default with LinesBefore = 1uy } + type Printer(showDebug: bool) = let colorMap: Map = @@ -87,7 +88,7 @@ type Printer(showDebug: bool) = if String.hasNoText message then raise (ArgumentException(nameof(message), "Message cannot be empty.")) - printEmptyLines printOptions.PrependLines + printEmptyLines printOptions.LinesBefore let escapedMessage = escapeText message @@ -100,11 +101,9 @@ type Printer(showDebug: bool) = if printOptions.AppendLineBreak then AnsiConsole.WriteLine() - printEmptyLines printOptions.AppendLines - /// Toggle showing or hiding debug messages. member this.ShowDebug(shouldEnable) = - minimumLogLevel <- (if shouldEnable then Level.Debug else Level.Info) + minimumLogLevel <- if shouldEnable then Level.Debug else Level.Info member this.PrintTable(table: Table) = AnsiConsole.Write table @@ -115,23 +114,28 @@ type Printer(showDebug: bool) = member this.Error(message) = print Level.Error message None - member this.Error(message, printOptions) = - print Level.Error message (Some printOptions) + member this.Error(message, options) = + print Level.Error message (Some options) member this.Warning(message) = print Level.Warning message None + member this.Warning(message, options) = + print Level.Warning message (Some options) + member this.Info(message) = print Level.Info message None + member this.Info(message, options) = + print Level.Info message (Some options) + member this.Debug(message) = print Level.Debug message None - member this.EmptyLine() = printEmptyLines 1uy - member this.GetInput(prompt) : string = printEmptyLines 1uy AnsiConsole.Ask($"[skyblue1]{prompt}[/]") member this.AskToBool(question, yesAnswer, noAnswer) : bool = (ask question [ yesAnswer; noAnswer ]) = yesAnswer + diff --git a/src/CCVTAC.Main/Program.fs b/src/CCVTAC.Main/Program.fs index 4bd4db16..b146e70b 100644 --- a/src/CCVTAC.Main/Program.fs +++ b/src/CCVTAC.Main/Program.fs @@ -1,6 +1,7 @@ namespace CCVTAC.Main open CCVTAC.Main.IoUtilities +open CCVTAC.Main.Orchestrator open CCVTAC.Main.Settings open CCVTAC.Main.Settings.Settings open Settings.IO @@ -34,47 +35,44 @@ module Program = | _ -> ShowHelp - let private registerCancelHandler (printer: Printer) workingDirectory = + let private registerCancelHandler (printer: Printer) : unit = + // Exits with error code 130, meaning termination by SIGINT (Ctrl‑C). Console.CancelKeyPress.Add(fun _ -> - printer.Warning $"{String.nl}Quitting at user's request." - - match Directories.warnIfAnyFiles 10 workingDirectory with - | Ok () -> () - | Error warnResult -> - printer.Error warnResult - match Directories.askToDeleteAllFiles printer workingDirectory with - | Error err -> printer.Error err - | Ok results -> Directories.printDeletionResults printer results) + printer.Warning("Quitting by request.", PrintOptions.DefaultWithLineBefore)) let private run (printer: Printer) (settingsFile: FileInfo) : int = if not settingsFile.Exists then match writeDefaultFile settingsFile with | Ok msg -> printer.Info msg - int ExitCodes.Success + ExitCodes.Success | Error err -> printer.Error err - int ExitCodes.OperationError + ExitCodes.OperationError else match read settingsFile with | Error err -> printer.Error err - int ExitCodes.ArgError + ExitCodes.ArgError | Ok settings -> printer.Info "Settings loaded OK." printer.PrintTable (toTable settings) printer.ShowDebug(not settings.QuietMode) - registerCancelHandler printer settings.WorkingDirectory + registerCancelHandler printer try - Orchestrator.start printer settings - int ExitCodes.Success + match Orchestrator.start printer settings with + | QuitDueToErrors -> ExitCodes.OperationError + | _ -> ExitCodes.Success with exn -> printer.Critical $"Fatal error: {exn.Message}" AnsiConsole.WriteException exn - printer.Info "Please help improve this tool by reporting this error and any relevant data (URLs, etc.) at https://github.com/codeconscious/ccvtac/issues." - int ExitCodes.OperationError + printer.Info "Please help improve this tool by reporting this error \ + with any relevant data (URLs, settings, etc.) at \ + https://github.com/codeconscious/ccvtac/issues." + ExitCodes.OperationError + |> int [] let main args : int = diff --git a/src/CCVTAC.Main/ResultTracker.fs b/src/CCVTAC.Main/ResultTracker.fs index 10de2b54..66b71f9f 100644 --- a/src/CCVTAC.Main/ResultTracker.fs +++ b/src/CCVTAC.Main/ResultTracker.fs @@ -5,23 +5,14 @@ open CCFSharpUtils.Text open System open System.Collections.Generic -type ResultTracker<'a>(printer: Printer) = +type ResultTracker(printer: Printer) = let mutable successCount : uint64 = 0UL - let failures = Dictionary() + let failures = Dictionary() /// Logs the result for a specific corresponding input. - member _.RegisterResult(input: string, result: Result<'a, string>) : unit = - match result with - | Ok _ -> - successCount <- successCount + 1UL - | Error e -> - if not (failures.TryAdd(input, e)) then - failures[input] <- e - - /// Logs the result for a specific corresponding input. - member _.RegisterResult(input: string, result: Result<'a, string list>) : unit = + member _.RegisterResult<'T>(input: string, result: Result<'T, string list>) : unit = match result with | Ok _ -> successCount <- successCount + 1UL @@ -30,6 +21,7 @@ type ResultTracker<'a>(printer: Printer) = if not (failures.TryAdd(input, msg)) then failures[input] <- msg + /// Prints any failures for the current batch. member _.PrintBatchFailures() : unit = if Num.isZero failures.Count then @@ -45,7 +37,8 @@ type ResultTracker<'a>(printer: Printer) = let successSummary = String.plur' "success" Es successCount let failureSummary = String.plur' "failure" S failures.Count - printer.Info $"Quitting with %s{successSummary} and %s{failureSummary}." + let options = PrintOptions.DefaultWithLineBefore + printer.Info($"Quitting with %s{successSummary} and %s{failureSummary}.", options) for pair in failures do printer.Warning $"- %s{pair.Key}: %s{pair.Value}" diff --git a/src/CCVTAC.Main/Settings/Settings.fs b/src/CCVTAC.Main/Settings/Settings.fs index 9a71d56a..9f0ac448 100644 --- a/src/CCVTAC.Main/Settings/Settings.fs +++ b/src/CCVTAC.Main/Settings/Settings.fs @@ -157,7 +157,7 @@ module Settings = | { AudioFormats = fmt } when not (fmt |> List.forall validAudioFormat) -> let formats = String.Join(", ", fmt) let approved = supportedAudioFormats |> String.concat ", " - Error $"Audio formats (\"%s{formats}\") include an unsupported audio format.{String.nl}Only the following supported formats: {approved}." + Error $"Unsupported audio format(s) (\"%s{formats}\") found. Supported formats: {approved}." | _ -> Ok settings diff --git a/src/CCVTAC.Main/Shared.fs b/src/CCVTAC.Main/Shared.fs index 5a26f1a8..7a777ed5 100644 --- a/src/CCVTAC.Main/Shared.fs +++ b/src/CCVTAC.Main/Shared.fs @@ -6,7 +6,13 @@ open Spectre.Console [] module Shared = - type ResultMessages = { Successes: string list; Failures: string list } + type ResultMessages = + { Successes: string list + Failures: string list } + + type ConfirmationAnswer = + | Proceed + | Decline of Reason: string let sleep workingMsgFn doneMsgFn seconds : string = let rec loop remaining (ctx: StatusContext) = @@ -23,3 +29,4 @@ module Shared = |> loop seconds) doneMsgFn seconds + diff --git a/src/CCVTAC.Tests/CCVTAC.Tests.fsproj b/src/CCVTAC.Tests/CCVTAC.Tests.fsproj index c0b0cd20..42de9407 100644 --- a/src/CCVTAC.Tests/CCVTAC.Tests.fsproj +++ b/src/CCVTAC.Tests/CCVTAC.Tests.fsproj @@ -14,8 +14,8 @@ - - + + runtime; build; native; contentfiles; analyzers; buildtransitive @@ -25,7 +25,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - +