-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
471 lines (457 loc) · 16 KB
/
Program.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
namespace ytdl;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using Mono.Options;
using YoutubeExplode;
using YoutubeExplode.Common;
using YoutubeExplode.Converter;
using YoutubeExplode.Exceptions;
using YoutubeExplode.Playlists;
using YoutubeExplode.Videos;
using YoutubeExplode.Videos.Streams;
class Program
{
static int CurrentRow, CurrentCollumn;
static int LastPercent = -1;
static List<string> URLs = new();
static bool AudioOnly = false;
static bool GetCaptions = false;
static string CaptionLang = "EN";
static bool NoDASH = false;
static bool PlaylistFolder = false;
static bool ChannelFolder = false;
static bool SaveThumbnails = false;
static bool DontCombine = false;
static bool Redownload = false;
static string OutputDir = "";
static YoutubeClient? Client;
static HttpClient? httpClient = null;
static readonly CancellationTokenSource Source = new();
static readonly CancellationToken Token = Source.Token;
static async Task<int> Main(string[] args)
{
ParseCommandOptions(args);
OutputDir = Directory.GetCurrentDirectory();
Client = new();
if (SaveThumbnails) httpClient = new();
Console.CancelKeyPress += new(CleanupDuringCancel);
Stopwatch sw = Stopwatch.StartNew();
foreach (string url in URLs)
{
Console.WriteLine($"Downloading {url}");
if (url.Contains("/watch?"))
{
Video video;
try { video = await Client.Videos.GetAsync(url); }
catch (Exception ex) { Console.WriteLine($"Can't get video. {ex.Message}"); continue; }
if (SaveThumbnails)
{
Console.WriteLine($"Downloading thumbnail for video {video.Title}");
Stream stream = await httpClient.GetStreamAsync(video.Thumbnails.GetWithHighestResolution().Url);
FileStream outstream = File.OpenWrite(RemoveInvalidChars(video.Title) + ".webp");
await stream.CopyToAsync(outstream);
}
var manifest = await Client.Videos.Streams.GetManifestAsync(video.Url);
await DownloadFunc(manifest, video.Title, url);
continue;
}
else if (url.Contains("playlist"))
{
Playlist playlist;
try { playlist = await Client.Playlists.GetAsync(url); }
catch (Exception ex) { Console.WriteLine($"Can't get playlist. {ex.Message}"); continue; }
Console.WriteLine($"Downloading playlist \"{playlist.Title}\"");
if (PlaylistFolder)
{
Directory.CreateDirectory(RemoveInvalidPathChars(playlist.Title));
Directory.SetCurrentDirectory(RemoveInvalidPathChars(playlist.Title));
}
await foreach (PlaylistVideo video in Client.Playlists.GetVideosAsync(url))
{
if (SaveThumbnails)
{
Console.WriteLine($"Downloading thumbnail for video {video.Title}");
Stream stream = await httpClient.GetStreamAsync(video.Thumbnails.GetWithHighestResolution().Url);
FileStream outstream = File.OpenWrite(RemoveInvalidChars(video.Title) + ".webp");
await stream.CopyToAsync(outstream);
}
var manifest = await Client.Videos.Streams.GetManifestAsync(video.Url);
await DownloadFunc(manifest, video.Title, video.Url);
}
if (PlaylistFolder) Directory.SetCurrentDirectory(OutputDir);
}
else if (url.Contains("/@") || url.Contains("/c/") || url.Contains("/channel/"))
{
YoutubeExplode.Channels.Channel channel;
try { channel = await Client.Channels.GetByHandleAsync(url); }
catch (Exception ex) { Console.WriteLine($"Can't get channel. {ex.Message}"); continue; }
Console.WriteLine($"Downloading all uploads from channel \"{channel.Title}\"");
if (ChannelFolder)
{
Directory.CreateDirectory(RemoveInvalidPathChars(channel.Title));
Directory.SetCurrentDirectory(RemoveInvalidPathChars(channel.Title));
}
await foreach (PlaylistVideo video in Client.Channels.GetUploadsAsync(channel.Id))
{
try
{
if (SaveThumbnails)
{
Console.WriteLine($"Downloading thumbnail for video {video.Title}");
Stream stream = await httpClient.GetStreamAsync(video.Thumbnails.GetWithHighestResolution().Url);
FileStream outstream = File.OpenWrite(RemoveInvalidChars(video.Title) + ".webp");
await stream.CopyToAsync(outstream);
}
var manifest = await Client.Videos.Streams.GetManifestAsync(video.Url);
await DownloadFunc(manifest, video.Title, video.Url);
}
catch (Exception e)
{
Console.WriteLine($"An exception occured trying to download video \"{video.Title}\": {e.Message}");
continue;
}
}
if (ChannelFolder) Directory.SetCurrentDirectory(OutputDir);
}
}
Console.WriteLine($"Done in {FormatTimespan(sw.Elapsed)}.");
return 0;
}
static async Task DownloadFunc(StreamManifest? manifest, string videoTitle, string url)
{
ArgumentNullException.ThrowIfNull(manifest);
ArgumentNullException.ThrowIfNull(Client);
try
{
if (AudioOnly)
{
var audiosstream = manifest.GetAudioOnlyStreams().GetWithHighestBitrate();
await DownloadAudio(audiosstream, videoTitle);
return;
}
if (GetCaptions)
{
try
{
var captions = await Client.Videos.ClosedCaptions.GetManifestAsync(url);
var lang = captions.GetByLanguage(CaptionLang);
Console.Write($"Captions for {videoTitle} ({CaptionLang}) ");
CurrentRow = Console.GetCursorPosition().Top;
CurrentCollumn = Console.GetCursorPosition().Left;
await Client.Videos.ClosedCaptions.DownloadAsync(lang, $"{RemoveInvalidChars(videoTitle)}-{CaptionLang}.srt", default, Token);
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.WriteLine("Completed.");
}
catch (Exception e)
{
Console.WriteLine($"Couldn't get captions. {e.Message}");
}
}
if (NoDASH)
{
var stream = manifest.GetMuxedStreams().GetWithHighestVideoQuality();
string filename1 = $"{RemoveInvalidChars(videoTitle)}.{stream.Container.Name}";
if (Path.Exists(filename1) && new FileInfo(filename1).Length != 0 && !Redownload)
{
Console.WriteLine($"Skipping {videoTitle} beacuse it's already downloaded.");
return;
}
Console.Write($"{videoTitle} - ");
CurrentRow = Console.GetCursorPosition().Top;
CurrentCollumn = Console.GetCursorPosition().Left;
await Client.Videos.Streams.DownloadAsync(stream, filename1,
new Progress<double>(percent =>
{
int CurrentPercent = (int)(percent * 100);
if (CurrentPercent != LastPercent)
{
LastPercent = CurrentPercent;
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.Write($"{CurrentPercent}%");
}
}), Token);
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.WriteLine("Completed.");
return;
}
if (DontCombine)
{
var video = manifest.GetVideoStreams().GetWithHighestVideoQuality();
var audio = manifest.GetAudioStreams().GetWithHighestBitrate();
Console.Write($"Downloading video for {videoTitle} - ");
CurrentRow = Console.GetCursorPosition().Top;
CurrentCollumn = Console.GetCursorPosition().Left;
await Client.Videos.Streams.DownloadAsync(video, $"{RemoveInvalidChars(videoTitle)} - Video.{video.Container.Name}",
new Progress<double>(percent =>
{
int CurrentPercent = (int)(percent * 100);
if (CurrentPercent != LastPercent)
{
LastPercent = CurrentPercent;
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.Write($"{CurrentPercent}%");
}
}), Token);
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.WriteLine("Completed.");
Console.Write($"Downloading audio for {videoTitle} - ");
CurrentRow = Console.GetCursorPosition().Top;
CurrentCollumn = Console.GetCursorPosition().Left;
await Client.Videos.Streams.DownloadAsync(audio, $"{RemoveInvalidChars(videoTitle)} - Audio.{audio.Container.Name}",
new Progress<double>(percent =>
{
int CurrentPercent = (int)(percent * 100);
if (CurrentPercent != LastPercent)
{
LastPercent = CurrentPercent;
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.Write($"{CurrentPercent}%");
}
}), Token);
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.WriteLine("Completed.");
return;
}
var audiostream = manifest.GetAudioOnlyStreams().GetWithHighestBitrate();
var videostream = manifest.GetVideoOnlyStreams().GetWithHighestVideoQuality();
string filename = $"{RemoveInvalidChars(videoTitle)}.{videostream.Container.Name}";
if (Path.Exists(filename) && new FileInfo(filename).Length != 0 && !Redownload)
{
Console.WriteLine($"Skipping {videoTitle} beacuse it's already downloaded.");
return;
}
await DownloadVideo([audiostream, videostream], videoTitle, videostream.Container.Name);
return;
}
catch (Exception e)
{
Console.WriteLine($"An exception occured trying to download {url}: {e.GetType()} {e.Message}");
}
}
static async Task DownloadAudio(IStreamInfo stream, string title)
{
if (Client is null)
return;
string filename = $"{RemoveInvalidChars(title)}.{stream.Container.Name}";
if (Path.Exists(filename) && new FileInfo(filename).Length != 0 && !Redownload)
{
Console.WriteLine($"Skipping {title} beacuse it's already downloaded.");
return;
}
Console.Write($"{title} - ");
CurrentRow = Console.GetCursorPosition().Top;
CurrentCollumn = Console.GetCursorPosition().Left;
try
{
await Client.Videos.Streams.DownloadAsync(stream, filename, new Progress<double>(percent =>
{
int CurrentPercent = (int)(percent * 100);
if (CurrentPercent != LastPercent)
{
LastPercent = CurrentPercent;
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.Write($"{CurrentPercent}%");
}
}), Token);
}
catch (IOException e)
{
Console.WriteLine("Failed to write the video's streams: " + e.Message);
Exit(1);
}
catch (HttpRequestException e)
{
Console.WriteLine($"An HTTP error occured: {e.Message}");
Console.WriteLine("403 errors usually happen on age restricted videos.");
return;
}
catch (Win32Exception)
{
Console.WriteLine("Downloading DASH streams requires having ffmpeg installed and available from your system's PATH.");
Console.WriteLine("Download it here: https://www.ffmpeg.org/");
Exit(1);
}
catch (TaskCanceledException)
{
return;
}
catch (Exception e)
{
Console.WriteLine($"An exception occured: {e.GetType()} {e.Message}");
#if DEBUG
Console.WriteLine(e.StackTrace);
#endif
return;
}
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.WriteLine("Completed.");
}
static async Task DownloadVideo(IReadOnlyList<IStreamInfo> streams, string title, string container)
{
if (Client is null)
return;
Console.Write($"{title} - ");
CurrentRow = Console.GetCursorPosition().Top;
CurrentCollumn = Console.GetCursorPosition().Left;
try
{
await Client.Videos.DownloadAsync(streams, new ConversionRequestBuilder($"{RemoveInvalidChars(title)}.{container}").Build(),
new Progress<double>(percent =>
{
int CurrentPercent = (int)(percent * 100);
if (CurrentPercent != LastPercent)
{
LastPercent = CurrentPercent;
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.Write($"{CurrentPercent}%");
}
}), Token);
}
catch (IOException e)
{
Console.WriteLine("Failed to write the video's streams: " + e.Message);
Exit(1);
}
catch (HttpRequestException e)
{
Console.WriteLine($"An HTTP error occured: {e.Message}");
Console.WriteLine("403 errors usually happen on age restricted videos.");
return;
}
catch (Win32Exception)
{
Console.WriteLine("Downloading DASH streams requires having ffmpeg installed and available from your system's PATH.");
Console.WriteLine("Download it here: https://www.ffmpeg.org/");
Exit(1);
}
catch (TaskCanceledException)
{
return;
}
catch (Exception e)
{
Console.WriteLine($"An exception occured: {e.GetType()} {e.Message}");
#if DEBUG
Console.WriteLine(e.StackTrace);
#endif
return;
}
Console.SetCursorPosition(CurrentCollumn, CurrentRow);
Console.WriteLine("Completed.");
}
static void ParseCommandOptions(string[] args)
{
string outpath = "";
bool help = false;
OptionSet options = new OptionSet {
{ "o|outpath=", "A path to download videos and their streams to.", o => outpath = o },
{ "a|audio-only", "Download only the audio streams from the given URLs", a => AudioOnly = a != null },
{ "cc|closed-captions", "Download Closed-Captions if they're available. Uses English by default",
cc => GetCaptions = cc != null },
{ "D|no-dash", "Don't download DASH streams. This skips the requirement of ffmpeg, but limits video quality to " +
"below 720p.", nd => NoDASH = nd != null },
{ "cl|caption-lang=", "Caption language to download, if it's available. Must be the 2 letter ISO 3166 language code.",
cl => CaptionLang = cl },
{ "pf|playlist-folders", "Download playlists to a folder with the name of the playlist.", pf => PlaylistFolder = pf != null },
{ "cf|channel-folders", "Download channels to a folder with the channel's name.", cf => ChannelFolder = cf != null },
{ "uf|use-folders", "Download playlists and channels to folders with their names. Equivalent to setting --channel-folders " +
"and --playlist-folders.", uf => { if (uf != null) { ChannelFolder = true; PlaylistFolder = true; } }},
{ "st|save-thumbnails", "Download the video's thumbnails.", sf => SaveThumbnails = sf != null },
{ "dc|dont-combine", "Use DASH streams, but don't automatically combine the audio/video streams, save them separately instead.",
dc => DontCombine = dc != null },
{ "h|help", "Show help message and exit.", h => help = h != null }
};
try { URLs = options.Parse(args); }
catch (OptionException e)
{
Console.WriteLine($"ytdl: {e.Message}");
Console.WriteLine("Try --help to see all switches/usages.");
Exit(1);
}
if (help)
{
Console.WriteLine("ytdl: Download YouTube channels, videos, and playlists.");
Console.WriteLine("Usage: [-o Outpath] URL(s)");
Console.WriteLine("Options:");
options.WriteOptionDescriptions(Console.Out);
Exit(1);
}
if (URLs.Count == 0)
{
Console.WriteLine("No URLs provided.");
Console.WriteLine("Usage: [-o Outpath] URL(s)");
Console.WriteLine("Try --help to see all switches/usages.");
Exit(1);
}
if (outpath != "")
{
if (!Path.Exists(outpath))
{
Console.WriteLine("Provided output directory doesn't exist.");
Exit(1);
}
Directory.SetCurrentDirectory(outpath);
Console.WriteLine($"Saving videos to {outpath}");
}
if (AudioOnly) Console.WriteLine("Downloading videos as audio only.");
}
protected static void CleanupDuringCancel(object? sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("Canceling downloads...");
Source.Cancel();
Console.WriteLine("Deleting temporary files...");
CleanupTempFiles();
Exit(1);
}
static void CleanupTempFiles()
{
Regex regex = new(".*[.]stream-.?[.]tmp");
foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
if (regex.IsMatch(file))
File.Delete(file);
}
}
[DoesNotReturn]
static void Exit(int code)
{
Environment.Exit(code);
}
static string FormatTimespan(TimeSpan span)
{
string outstr;
if (span.Hours == 0)
{
outstr = span.ToString("mm\\:ss\\.ff");
return outstr;
}
outstr = span.ToString("hh\\:mm\\:ss\\.ff");
return outstr;
}
static string RemoveInvalidChars(string filepath)
{
char[] invalid = Path.GetInvalidFileNameChars();
string outpath = "";
foreach (char c in filepath)
{
if (invalid.Contains(c) || ((c == '&' || c == ':' || c == '$' || c == '"' || c == '?' || c == '*') && !NoDASH))
continue;
outpath += c;
}
return outpath;
}
static string RemoveInvalidPathChars(string path)
{
char[] invalid = Path.GetInvalidPathChars();
string outpath = "";
foreach (char c in path)
{
if (invalid.Contains(c))
continue;
outpath += c;
}
return outpath;
}
}