-
Notifications
You must be signed in to change notification settings - Fork 0
/
RootCommand.cs
349 lines (301 loc) · 12.1 KB
/
RootCommand.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using dis.Features.Common;
using dis.Features.Conversion;
using dis.Features.Conversion.Models;
using dis.Features.Download.Models;
using dis.Features.Download.Models.Interfaces;
using dis.Features.TrimSlider;
using Microsoft.AspNetCore.StaticFiles;
using Serilog;
using Spectre.Console;
using Spectre.Console.Cli;
using Xabe.FFmpeg;
namespace dis;
public sealed class RootCommand(
FileExtensionContentTypeProvider type,
ILogger logger,
Globals globals,
VideoCodecs videoCodecs,
ValidResolutions validResolutions,
IDownloader downloader,
Converter converter)
: AsyncCommand<Settings>
{
private static readonly string[] VersionArgs = ["-v", "--version"];
private void ValidateInputs(IEnumerable<string> inputs)
{
if (VersionArgs.Any(Environment.GetCommandLineArgs().Contains))
return;
foreach (var input in inputs)
{
var isPath = File.Exists(input);
var isUrl = Uri.IsWellFormedUriString(input, UriKind.RelativeOrAbsolute);
switch (isPath)
{
case false when isUrl is false:
{
ValidationResult.Error($"Invalid input file or link: {input}");
return;
}
case true:
{
if (type.TryGetContentType(input, out var contentType) is false) return;
if (contentType.Contains("video") || contentType.Contains("audio")) return;
break;
}
}
}
}
private static void ValidateOutput(string? output)
{
if (string.IsNullOrEmpty(output)) output = Environment.CurrentDirectory;
if (Directory.Exists(output) is false)
ValidationResult.Error("Output directory does not exist");
}
private static void ValidateCrf(int crf)
{
const int min = 6;
const int minRecommended = 22;
const int max = 63;
const int maxRecommended = 38;
var settingsType = typeof(Settings);
// Use reflection to get the Crf property in the Settings class.
var crfProperty = settingsType.GetProperty(nameof(Settings.Crf));
// Get the DefaultValueAttribute assigned to the Crf property.
var defaultValueAttribute = crfProperty?
.GetCustomAttributes(typeof(DefaultValueAttribute), false)
.FirstOrDefault() as DefaultValueAttribute;
// Get the value from the DefaultValueAttribute.
var defaultValue = (int)defaultValueAttribute?.Value!;
/*
* Use pattern matching with a switch expression to check if the 'crf' value is valid.
* If 'crf' is less than 0 or greater than the maximum, it is invalid, so 'validCrf' will be set to false.
* If 'crf' is between the minimum and maximum, inclusive, 'crf' is valid, and 'validCrf' will be set to true.
*/
var validCrf = crf switch
{
< 0 => false,
>= min and <= max => true,
_ => false
};
if (validCrf is false)
ValidationResult.Error($"CRF value must be between {min} and {max} (Avoid values below {defaultValue})");
else switch (crf)
{
case < minRecommended:
AnsiConsole.MarkupLine($"[yellow]CRF values below {minRecommended} are not recommended[/]");
break;
case > maxRecommended:
AnsiConsole.MarkupLine($"[yellow]CRF values above {maxRecommended} are not recommended[/]");
break;
}
}
private static void ValidateAudioBitrate(int? audioBitrate)
{
if (audioBitrate is null) return;
var audioBitrateRange = audioBitrate switch
{
< 128 => false,
> 192 => false,
_ => true
};
if (audioBitrateRange is false)
AnsiConsole.MarkupLine("[yellow]Audio bitrate values below 128 or above 192 are not recommended[/]");
if (audioBitrate % 2 != 0)
ValidationResult.Error("Audio bitrate must be a multiple of 2");
}
private void ValidateResolution(string? resolution)
{
var hasResolution = resolution is not null;
if (hasResolution is false) return;
var validResolution = validResolutions.Resolutions
.Any(res => res.ToString().Equals($"{resolution}p", StringComparison.InvariantCultureIgnoreCase));
if (validResolution is false)
ValidationResult.Error("Invalid resolution");
}
private void ValidateVideoCodec(string? videoCodec)
{
var hasVideoCodec = videoCodec is not null;
if (!hasVideoCodec) return;
var validVideoCodec = videoCodecs.Codecs
.Any(codec => codec.ToString()
.Equals(videoCodec,
StringComparison.InvariantCultureIgnoreCase));
if (validVideoCodec is false)
ValidationResult.Error("Invalid video codec");
}
public override ValidationResult Validate(CommandContext context, Settings settings)
{
ValidateInputs(settings.Input);
ValidateOutput(settings.Output);
ValidateCrf(settings.Crf);
ValidateAudioBitrate(settings.AudioBitrate);
ValidateResolution(settings.Resolution);
ValidateVideoCodec(settings.VideoCodec);
ValidationResult.Success();
return base.Validate(context, settings);
}
public override async Task<int> ExecuteAsync(CommandContext context, Settings settings)
{
// This is a hacky way to check for the version, but the library doesn't really have a better way. So, we have to do what we have to do.
if (VersionArgs.Any(Environment.GetCommandLineArgs().Contains))
{
AnsiConsole.MarkupLine(typeof(RootCommand).Assembly.GetName().Version!.ToString(3));
return 0;
}
// Patch up output directory to current dir if it's empty
if (string.IsNullOrEmpty(settings.Output)) settings.Output = Environment.CurrentDirectory;
var links = settings.Input
.Where(video =>
Uri.IsWellFormedUriString(video, UriKind.RelativeOrAbsolute) &&
File.Exists(video) is false)
.Select(video => new Uri(video));
var files = settings.Input
.Where(File.Exists);
var paths = new Dictionary<string, DateTime?>();
TrimSettings? downloadTrimSettings = null;
TrimSettings? ffmpegTrimSettings = null;
if (await CheckForFFmpegAndYtDlp() is false)
return 1;
// Get trim settings once if trimming is enabled for URLs
var linksList = links.ToList();
if (settings.Trim && linksList.Count != 0)
{
var duration = await GetVideoDuration(linksList.First(), settings);
if (duration.HasValue)
{
var slider = new TrimmingSlider(duration.Value);
var trimResult = slider.ShowSlider();
if (string.IsNullOrEmpty(trimResult)) // If cancelled, exit immediately
return 0;
var parts = trimResult.Split('-');
if (parts.Length == 2 &&
double.TryParse(parts[0], out var start) &&
double.TryParse(parts[1], out var end))
{
downloadTrimSettings = new TrimSettings(start, end - start);
}
}
}
await Download(linksList, paths, settings, downloadTrimSettings);
// Get trim settings for local files if trimming is enabled
var filesList = files.ToList();
if (settings.Trim && filesList.Count != 0)
{
var mediaInfo = await FFmpeg.GetMediaInfo(filesList.First());
if (mediaInfo.Streams.FirstOrDefault(s => s is IVideoStream) is IVideoStream videoStream)
{
var slider = new TrimmingSlider(videoStream.Duration);
var trimResult = slider.ShowSlider();
if (string.IsNullOrEmpty(trimResult)) // If cancelled, exit immediately
return 0;
var parts = trimResult.Split('-');
if (parts.Length == 2 &&
double.TryParse(parts[0], out var start) &&
double.TryParse(parts[1], out var end))
{
ffmpegTrimSettings = new TrimSettings(start, end - start);
}
}
}
foreach (var file in filesList)
paths.TryAdd(file, null);
await Convert(paths, settings, ffmpegTrimSettings);
return 0;
}
private static async Task<bool> CheckForFFmpegAndYtDlp()
{
try
{
var cmd = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "where" : "which";
var ffmpegPath = await GetCommandPath(cmd, "ffmpeg");
var ytDlpPath = await GetCommandPath(cmd, "yt-dlp");
if (string.IsNullOrWhiteSpace(ffmpegPath))
{
AnsiConsole.WriteLine("FFmpeg not found in PATH. Please install FFmpeg and add it to PATH.");
return false;
}
if (string.IsNullOrWhiteSpace(ytDlpPath))
{
AnsiConsole.WriteLine("yt-dlp not found in PATH. Please install yt-dlp and add it to PATH.");
return false;
}
return true;
}
catch (Exception ex)
{
AnsiConsole.WriteLine($"An error occurred: {ex.Message}");
return false;
}
}
private static async Task<string> GetCommandPath(string cmd, string commandName)
{
ProcessStartInfo processInfo = new(cmd, commandName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = Process.Start(processInfo);
var commandPath = await process?.StandardOutput.ReadToEndAsync()!;
await process.WaitForExitAsync();
return commandPath;
}
private async Task Download(IEnumerable<Uri> links, Dictionary<string, DateTime?> videos, Settings options, TrimSettings? trimSettings)
{
var list = links.ToList();
if (list.Count is 0)
return;
foreach (var link in list)
{
var downloadOptions = new DownloadOptions(link, options, trimSettings);
var (path, date) = await downloader.DownloadTask(downloadOptions);
if (path is null)
logger.Error("There was an error downloading the video");
else
{
var added = videos.TryAdd(path, date);
if (added is false)
logger.Error("Failed to add video to list: {Path}", path);
}
}
foreach (var path in videos.Keys) AnsiConsole.MarkupLine($"Downloaded video to: [green]{path}[/]");
}
private async Task<TimeSpan?> GetVideoDuration(Uri uri, Settings options)
{
try
{
var downloadOptions = new DownloadOptions(uri, options);
return await downloader.GetDuration(downloadOptions);
}
catch (Exception ex)
{
logger.Error(ex, "Failed to get video duration");
return null;
}
}
private async Task Convert(IEnumerable<KeyValuePair<string, DateTime?>> videos, Settings options, TrimSettings? trimSettings)
{
foreach (var (path, date) in videos)
{
try
{
await converter.ConvertVideo(path, date, options, trimSettings);
}
catch (Exception ex)
{
logger.Error(ex, "Failed to convert video: {Path}", path);
}
}
var hasAny = globals.TempDir.Count is not 0;
if (hasAny is false)
return;
globals.TempDir.ForEach(d =>
{
Directory.Delete(d, true);
AnsiConsole.MarkupLine($"Deleted temp dir: [red]{d}[/]");
});
}
}