using System; using System.CommandLine; using System.CommandLine.Invocation; using System.Threading.Tasks; using BililiveRecorder.ToolBox.Commands; using Newtonsoft.Json; namespace BililiveRecorder.ToolBox { public class ToolCommand : Command { public ToolCommand() : base("tool", "Run Tools") { this.RegisterCommand("analyze", null, c => { c.Add(new Argument("input", "example: input.flv")); }); this.RegisterCommand("fix", null, c => { c.Add(new Argument("input", "example: input.flv")); c.Add(new Argument("output-base", "example: output.flv")); }); this.RegisterCommand("export", null, c => { c.Add(new Argument("input", "example: input.flv")); c.Add(new Argument("output", "example: output.brec.xml.gz")); }); } private void RegisterCommand(string name, string? description, Action configure) where THandler : ICommandHandler where TRequest : ICommandRequest where TResponse : class { var cmd = new Command(name, description) { new Option("--json", "print result as json string"), new Option("--json-indented", "print result as indented json string") }; cmd.Handler = CommandHandler.Create((TRequest r, bool json, bool jsonIndented) => RunSubCommand(r, json, jsonIndented)); configure(cmd); this.Add(cmd); } private static async Task RunSubCommand(TRequest request, bool json, bool jsonIndented) where THandler : ICommandHandler where TRequest : ICommandRequest where TResponse : class { var handler = Activator.CreateInstance(); var response = await handler.Handle(request).ConfigureAwait(false); if (json || jsonIndented) { var json_str = JsonConvert.SerializeObject(response, jsonIndented ? Formatting.Indented : Formatting.None); Console.WriteLine(json_str); } else { if (response.Status == ResponseStatus.OK) { handler.PrintResponse(response.Result!); } else { Console.Write("Error: "); Console.WriteLine(response.Status); Console.WriteLine(response.ErrorMessage); } } return 0; } } }