diff --git a/src/CCVTAC.Main/CCVTAC.Main.fsproj b/src/CCVTAC.Main/CCVTAC.Main.fsproj index 00f1f1c0..96a1ab8a 100644 --- a/src/CCVTAC.Main/CCVTAC.Main.fsproj +++ b/src/CCVTAC.Main/CCVTAC.Main.fsproj @@ -40,7 +40,7 @@ - + diff --git a/src/CCVTAC.Main/Downloading/Downloader.fs b/src/CCVTAC.Main/Downloading/Downloader.fs index 78c112ae..aec2d488 100644 --- a/src/CCVTAC.Main/Downloading/Downloader.fs +++ b/src/CCVTAC.Main/Downloading/Downloader.fs @@ -8,51 +8,64 @@ open CCVTAC.Main.Downloading.Downloading open CCVTAC.Main.ExternalTools open CCVTAC.Main.Settings.Settings open CCFSharpUtils +open CCFSharpUtils.Text open FSharpPlus -open System module Downloader = let maximumFormatPasses = 3 - let generateDownloadArgs audioFormat userSettings (mediaType: MediaType option) additionalArgs : string = + /// Builds the downloader's argument list. Each element is a single argv entry, + /// so flags and their values are kept as separate elements. + let generateDownloadArgs audioFormat userSettings (mediaType: MediaType option) additionalArgs : string list = let writeJsonArg = "--write-info-json" - let trimFileNamesArg = "--trim-filenames 250" - let formatArg = + let formatArgs = match audioFormat with | None | Some "best" -> [] - | Some format -> [$"-f {format}"] + | Some format -> [ "-f"; format ] let args = match mediaType with | None -> - [ "--flat-playlist"; writeJsonArg; trimFileNamesArg ] + [ "--flat-playlist"; writeJsonArg; "--trim-filenames"; "250" ] | Some _ -> - [ "--extract-audio" ] @ formatArg - @ [ $"--audio-quality {userSettings.AudioQuality}" + [ "--extract-audio" ] + @ formatArgs + @ [ "--audio-quality"; string userSettings.AudioQuality "--write-thumbnail" - "--convert-thumbnails jpg" + "--convert-thumbnails"; "jpg" writeJsonArg - trimFileNamesArg - "--retries 3" ] - - let args' = - args - @ (if userSettings.QuietMode then [ "--quiet"; "--no-warnings" ] else []) - @ Option.toList userSettings.DownloaderAdditionalOptions - @ (match mediaType with - | None -> [] - | Some mt -> - [ if userSettings.SplitChapters then "--split-chapters" - if isMultiVideo mt then - $"--sleep-interval {userSettings.SleepSecondsBetweenDownloads}" - if isMultiVideo mt && mt.IsStandardPlaylist then - """-o "%(uploader).80B - %(playlist).80B - %(playlist_autonumber)s - %(title).150B [%(id)s].%(ext)s" --playlist-reverse""" ]) - @ defaultArg additionalArgs [] - - String.Join(" ", args') + "--trim-filenames"; "250" + "--retries"; "3" ] + + let quietArgs = + if userSettings.QuietMode then [ "--quiet"; "--no-warnings" ] else [] + + let additionalOptionArgs = + option String.splitOnSpaces [] userSettings.DownloaderAdditionalOptions + + let mediaSpecificArgs = + match mediaType with + | None -> [] + | Some mt -> + (if userSettings.SplitChapters then [ "--split-chapters" ] else []) + @ (if isMultiVideo mt then + [ "--sleep-interval"; string userSettings.SleepSecondsBetweenDownloads ] + else []) + @ (if isMultiVideo mt && mt.IsStandardPlaylist then + [ "-o" + "%(uploader).80B - %(playlist).80B - %(playlist_autonumber)s - %(title).150B [%(id)s].%(ext)s" + "--playlist-reverse" ] + else []) + + args @ quietArgs @ additionalOptionArgs @ mediaSpecificArgs @ defaultArg additionalArgs [] + + /// Creates the tool settings for the configured downloader and runs it. + let private runDownloader (printer: Printer) userSettings args : Result = + ToolSettings.create userSettings.DownloaderCommand args userSettings.WorkingDirectory + >>= fun settings -> runTool printer settings [ 1 ] let wrapUrlInMediaType url : Result = mediaTypeWithIds url @@ -67,11 +80,8 @@ module Downloader = err :: Option.toList maybeSndErr let attemptAudioFormat format previousErrors = - let args = generateDownloadArgs (Some format) userSettings (Some mediaType) (Some [url]) - let commandWithArgs = $"{userSettings.DownloaderCommand} {args}" - let downloadSettings = ToolSettings.create commandWithArgs userSettings.WorkingDirectory - - let downloadResult = runTool printer downloadSettings [1] + let args = generateDownloadArgs (Some format) userSettings (Some mediaType) (Some [ url ]) + let downloadResult = runDownloader printer userSettings args let anyFilesDownloaded = Num.isPos <| audioFileCount Files.audioFileExts userSettings.WorkingDirectory match downloadResult, anyFilesDownloaded with @@ -79,7 +89,7 @@ module Downloader = Ok <| $"Successfully downloaded the \"{format}\" format." :: match result.Error with - | Some err -> [$"However, a minor issue was reported: {err}"] + | Some err -> [ $"However, a minor issue was reported: {err}" ] | None -> [] | Ok result, false -> let msg = $"While the downloader finished successfully, no audio files were downloaded in the \"{format}\" format." @@ -89,13 +99,13 @@ module Downloader = Error (previousErrors @ buildErrMsg msg (Some err)) | Error err, false -> let msg = $"A download error was reported for the \"{format}\" format, and no audio files were downloaded. {err}" - Error (previousErrors @ [msg]) + Error (previousErrors @ [ msg ]) let rec retryLoop errors passesRemaining formatsRemaining = if Num.isZero passesRemaining then Error <| errors - @ [$"Gave up after {maximumFormatPasses} passes through the configured audio formats."] + @ [ $"Gave up after {maximumFormatPasses} passes through the configured audio formats." ] else match formatsRemaining with | [] -> @@ -103,27 +113,24 @@ module Downloader = retryLoop errors (passesRemaining - 1) userSettings.AudioFormats | format :: remainingFormats -> match attemptAudioFormat format errors with - | Ok msgs -> Ok msgs - | Error errs -> retryLoop errs passesRemaining remainingFormats + | Ok messages -> Ok messages + | Error errors -> retryLoop errors passesRemaining remainingFormats match userSettings.AudioFormats with - | [] -> Error ["No audio formats are configured."] + | [] -> Error [ "No audio formats are configured." ] | formats -> retryLoop [] maximumFormatPasses formats let downloadMetadata (printer: Printer) userSettings (SupplementaryUrl url) : Result = match url with | None -> Ok "No supplementary metadata link found." | Some url' -> - let args = generateDownloadArgs None userSettings None (Some [url']) - let commandWithArgs = $"{userSettings.DownloaderCommand} {args}" - let downloadSettings = ToolSettings.create commandWithArgs userSettings.WorkingDirectory - let metadataDownloadResult = runTool printer downloadSettings [1] + let args = generateDownloadArgs None userSettings None (Some [ url' ]) - match metadataDownloadResult with - | Ok _ -> Ok "Supplementary metadata download completed OK." - | Error err -> Error [$"Supplementary metadata download failed: {err}"] + match runDownloader printer userSettings args with + | Ok _ -> Ok "Supplementary metadata download completed OK." + | Error err -> Error [ $"Supplementary metadata download failed: {err}" ] - let run (printer: Printer) (mediaType: MediaType) userSettings : Result = + let run (printer: Printer) mediaType userSettings : Result = monad { let rawUrls = generateDownloadUrl mediaType let urls = diff --git a/src/CCVTAC.Main/Downloading/Updater.fs b/src/CCVTAC.Main/Downloading/Updater.fs index 0759ae41..f9f60341 100644 --- a/src/CCVTAC.Main/Downloading/Updater.fs +++ b/src/CCVTAC.Main/Downloading/Updater.fs @@ -4,6 +4,8 @@ open CCVTAC.Main open CCVTAC.Main.ExternalTools open CCVTAC.Main.Settings.Settings open CCFSharpUtils.Text +open FSharpPlus +open System module Updater = @@ -13,15 +15,20 @@ module Updater = if String.hasNoText userSettings.DownloaderUpdateCommand then printer.Info "No downloader update command provided, so will skip updating." else - let toolSettings = ToolSettings.create userSettings.DownloaderUpdateCommand - userSettings.WorkingDirectory + let outcome = + match String.splitOnSpaces userSettings.DownloaderUpdateCommand with + | tool :: args -> + ToolSettings.create tool args userSettings.WorkingDirectory + >>= fun settings -> Runner.runTool printer settings [] + | [] -> + Error "No downloader update command could be parsed." - match Runner.runTool printer toolSettings [] with + match outcome with | Ok details -> if details.ExitCode <> successExitCode then printer.Warning <| match details.Error with - | Some errMsg -> $"Update completed with minor issues: {errMsg}" - | None -> "Update completed with minor unspecified issues." - | Error msg -> - printer.Error $"Update failure: {msg}" + | Some message -> $"Update completed with minor issues: {message}" + | None -> "Update completed with unspecified minor issues." + | Error message -> + printer.Error $"Update failure: {message}" diff --git a/src/CCVTAC.Main/ExternalTools/Runner.fs b/src/CCVTAC.Main/ExternalTools/Runner.fs index 435837fe..863a6cbc 100644 --- a/src/CCVTAC.Main/ExternalTools/Runner.fs +++ b/src/CCVTAC.Main/ExternalTools/Runner.fs @@ -1,57 +1,67 @@ namespace CCVTAC.Main.ExternalTools +open System.IO +open System.ComponentModel +open System.Diagnostics open CCVTAC.Main -open CCFSharpUtils.Collections open CCFSharpUtils.Text open Startwatch.Library -open System -open System.Diagnostics +open FSharpPlus module Runner = type ToolResult = { ExitCode: int; Error: string option } - [] - let private authenticSuccessExitCode = 0 + let private isSuccessExitCode customSuccessCodes actualCode = + let normalSuccessCode = 0 + let allSuccessCodes = normalSuccessCode :: customSuccessCodes + allSuccessCodes |> List.contains actualCode + + let private buildStartInfo (toolSettings: ToolSettings) = + let psi = ProcessStartInfo(ToolSettings.tool toolSettings) + + for arg in ToolSettings.args toolSettings do + psi.ArgumentList.Add arg - let private isSuccessExitCode (otherSuccessExitCodes: int list) (exitCode: int) = - List.contains exitCode (authenticSuccessExitCode :: otherSuccessExitCodes) + psi.WorkingDirectory <- ToolSettings.workingDir toolSettings + psi.UseShellExecute <- false + psi.RedirectStandardOutput <- false + psi.RedirectStandardError <- true + psi.CreateNoWindow <- true + psi - /// Calls an external application. - /// Tool settings for execution - /// Additional exit codes, other than 0, that can be treated as non-failures - /// - let runTool (printer: Printer) toolSettings otherSuccessExitCodes : Result = + let private tryStart (psi: ProcessStartInfo) : Result = + try + match Process.Start psi with + | Null -> Error $"Could not start {psi.FileName}." + | NonNull proc -> Ok proc + with + | :? Win32Exception as ex -> + Error $"Could not locate or start {psi.FileName}: {ex.Message}" + | :? DirectoryNotFoundException as ex -> + Error $"Working directory for {psi.FileName} does not exist: {ex.Message}" + + let runTool (printer: Printer) toolSettings customSuccessCodes : Result = let watch = Watch() - printer.Info $"Running {toolSettings.CommandWithArgs}..." - - let command = - toolSettings.CommandWithArgs.Split([|' '|], 2) - |> fun arr -> {| Tool = arr[0] - Args = if Array.hasMultiple arr then arr[1] else String.Empty |} - - let processStartInfo = ProcessStartInfo command.Tool - processStartInfo.Arguments <- command.Args - processStartInfo.RedirectStandardOutput <- false - processStartInfo.RedirectStandardError <- true - processStartInfo.CreateNoWindow <- true - processStartInfo.WorkingDirectory <- toolSettings.WorkingDirectory - - match Process.Start processStartInfo with - | Null -> - Error $"Could not locate or start {command.Tool}." - | NonNull proc -> - let error = proc.StandardError.ReadToEnd() + + let toolName = ToolSettings.toolName toolSettings + printer.Info <| ToolSettings.runSummary toolSettings + + buildStartInfo toolSettings + |> tryStart + >>= fun proc -> + use _ = proc + let rawError = proc.StandardError.ReadToEnd() proc.WaitForExit() - printer.Info $"{command.Tool} finished in {watch.ElapsedFriendly}." + printer.Info $"{toolName} finished in {watch.ElapsedFriendly}." - let maybeError = String.toOption error + let maybeError = String.toOption rawError - if isSuccessExitCode otherSuccessExitCodes proc.ExitCode then + if isSuccessExitCode customSuccessCodes proc.ExitCode then Ok { ExitCode = proc.ExitCode Error = maybeError } else match maybeError with - | Some err -> Error $"%s{command.Tool} exited with code %d{proc.ExitCode}: %s{err}." - | None -> Error $"%s{command.Tool} exited with code %d{proc.ExitCode}." + | Some err -> Error $"%s{toolName} exited with code %d{proc.ExitCode}: %s{err}." + | None -> Error $"%s{toolName} exited with code %d{proc.ExitCode}." diff --git a/src/CCVTAC.Main/ExternalTools/ToolSettings.fs b/src/CCVTAC.Main/ExternalTools/ToolSettings.fs index 208c5f3c..9026a22f 100644 --- a/src/CCVTAC.Main/ExternalTools/ToolSettings.fs +++ b/src/CCVTAC.Main/ExternalTools/ToolSettings.fs @@ -1,13 +1,28 @@ namespace CCVTAC.Main.ExternalTools +open CCFSharpUtils.Text + /// Settings to govern the behavior of an external program. -type ToolSettings = private { - CommandWithArgs: string - WorkingDirectory: string -} +type ToolSettings = + private + { Tool: string + Args: string list + WorkingDir: string } module ToolSettings = - let create commandWithArgs workingDirectory = - { CommandWithArgs = commandWithArgs - WorkingDirectory = workingDirectory } + open System.IO + + let tool t = t.Tool + let toolName t = t.Tool |> Path.GetFileName + let args t = t.Args + let argText t = t.Args |> String.concat " " + let workingDir t = t.WorkingDir + let runSummary t = $"Running %s{toolName t} using `%s{tool t} %s{argText t}`." + let create tool args workingDir : Result = + if String.hasNoText tool then + Error "Tool name must not be empty." + else + Ok { Tool = tool + Args = args + WorkingDir = workingDir } diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 7c3be5de..fe510bad 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -89,7 +89,10 @@ module Orchestrator = | Error errMsg -> Error (Recoverable $"URL parse error: %s{errMsg}") | Ok mediaType -> - printer.Info $"%s{typeName mediaType} URL '%s{url}' detected." + printer.Info( + $"%s{typeName mediaType} URL '%s{url}' detected.", + PrintOptions.DefaultWithLineBefore) + history.Append(url, urlInputTime, printer) let downloadResult = Downloader.run printer mediaType settings @@ -145,7 +148,9 @@ module Orchestrator = let processCommand printer command settings (history: History) : Result = let checkCommand = List.containsIgnoreCase command - let toggle = toggleSpecs printer |> List.tryFind (fun spec -> checkCommand spec.Triggers) + + let toggle = toggleSpecs printer + |> List.tryFind (fun spec -> checkCommand spec.Triggers) match toggle with | Some spec -> @@ -232,7 +237,7 @@ module Orchestrator = let sleptMsg = sleep (fun remainingSeconds -> $"Sleeping for {secondsMsg remainingSeconds}...") - (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") + (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") seconds let options = PrintOptions.DefaultWithLineBefore printer.Info(sleptMsg, options) diff --git a/src/CCVTAC.Main/PostProcessing/ImageProcessor.fs b/src/CCVTAC.Main/PostProcessing/ImageProcessor.fs index d8a901f1..7455e4bf 100644 --- a/src/CCVTAC.Main/PostProcessing/ImageProcessor.fs +++ b/src/CCVTAC.Main/PostProcessing/ImageProcessor.fs @@ -1,11 +1,29 @@ namespace CCVTAC.Main.PostProcessing +open CCVTAC.Main open CCVTAC.Main.ExternalTools +open System.IO module ImageProcessor = let private programName = "mogrify" - let run printer workingDirectory : unit = - let toolSettings = workingDirectory |> ToolSettings.create $"{programName} -trim -fuzz 10%% *.jpg" - Runner.runTool printer toolSettings [] |> ignore + let run (printer: Printer) workingDirectory : unit = + if not (Directory.Exists workingDirectory) then + printer.Error $"Working directory does not exist: {workingDirectory}" + else + let jpgFiles = + Directory.GetFiles(workingDirectory, "*.jpg") + |> Array.map Path.GetFileName + |> List.ofArray + +#nowarn FS3261 // For IDEs only, which emit a null warning in createValidated, though compilation itself is fine. + if List.isEmpty jpgFiles then + printer.Error $"No JPG files found in {workingDirectory}." + else + let args = [ "-trim"; "-fuzz"; "10%" ] @ jpgFiles + + match ToolSettings.create programName args workingDirectory with + | Ok settings -> Runner.runTool printer settings |> ignore + | Error msg -> printer.Error msg +#warnon FS3261 diff --git a/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs b/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs index 3e82d836..ede8239b 100644 --- a/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs +++ b/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs @@ -27,7 +27,7 @@ module TaggingSet = t.AudioFiles @ [t.JsonFile; t.ImageFile] // Regex group 0 is the full filename, and group 1 contains the video ID. - let hasVideoIdRgx = + let videoIdRgx = Regex(@".+\[([\w\-]{11})\](?:.*)?\.(\w+)", RegexOptions.Compiled) let private create v a j i = @@ -41,15 +41,16 @@ module TaggingSet = #nowarn FS3261 // For IDEs only, which emit a null warning in createValidated, though compilation itself is fine. let hasSupportedAudioExt (fileName: string) = match Path.GetExtension fileName with - | ext when String.hasText ext -> Files.audioFileExts |> List.containsIgnoreCase ext - | _ -> false + | ext when String.hasText ext -> + Files.audioFileExts |> List.containsIgnoreCase ext + | _ -> + false #warnon FS3261 let audioFiles = fileNames |> List.filter hasSupportedAudioExt let jsonFiles = fileNames |> Files.filterByExt Files.jsonFileExt - let imageFiles = - Files.imageFileExts - |> List.collect (fun ext -> fileNames |> Files.filterByExt ext) + let imageFiles = Files.imageFileExts + |> List.collect (fun ext -> fileNames |> Files.filterByExt ext) applicative { let! a = List.ensureNotEmptyV audioFiles @@ -67,14 +68,13 @@ module TaggingSet = /// Irrelevant files are ignored. Validation errors are accumulated and returned in an Error. let createSets filePaths : Result = if Seq.isEmpty filePaths then - Error ["No file paths to create a tagging set were provided."] + Error [ "No file paths to create a tagging set were provided." ] else let relevantFileInfo fileName = fileName - |> Rgx.trySuccessMatch hasVideoIdRgx - |> Option.map (fun m -> - {| FileName = m.Groups[0].Value - VideoId = m.Groups[1].Value |} ) + |> Rgx.tryMatch videoIdRgx + |> Option.map (fun m -> {| FileName = m.Groups[0].Value + VideoId = m.Groups[1].Value |} ) let results = filePaths @@ -88,10 +88,9 @@ module TaggingSet = results |> List.collect (function | Failure errs -> NonEmptyList.toList errs - | Success _ -> []) + | Success _ -> []) if List.isEmpty errors then Ok (results |> List.choose (function Success ts -> Some ts | Failure _ -> None)) else Error errors - diff --git a/src/CCVTAC.Main/Shared.fs b/src/CCVTAC.Main/Shared.fs index b8a3e6c8..a36539f5 100644 --- a/src/CCVTAC.Main/Shared.fs +++ b/src/CCVTAC.Main/Shared.fs @@ -28,4 +28,3 @@ module Shared = |> loop seconds) doneMsgFn seconds - diff --git a/src/CCVTAC.Tests/CCVTAC.Tests.fsproj b/src/CCVTAC.Tests/CCVTAC.Tests.fsproj index 6cd6b896..a04ee3b3 100644 --- a/src/CCVTAC.Tests/CCVTAC.Tests.fsproj +++ b/src/CCVTAC.Tests/CCVTAC.Tests.fsproj @@ -14,7 +14,7 @@ - +