-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.axaml.cs
237 lines (205 loc) · 8.13 KB
/
MainWindow.axaml.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
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media;
using System.Threading.Tasks;
using YoutubeDownloader.Entities;
// Technically, the external download tool handles far more than just YouTube.
// I might add wider support at some point, but I have no need right now.
namespace YoutubeDownloader
{
public partial class MainWindow : Window
{
// TODO: Get binding working.
// public string LogText { get; set; } = string.Empty;
// public string SaveFolder { get; set; } = string.Empty;
public MainWindow()
{
InitializeComponent();
// this.DataContext = this;
// Auto-populate the save (output) directory, if available.
const string fileContainingSavePath = "default-output-folder.txt";
if (File.Exists(fileContainingSavePath))
{
var pathData = File.ReadAllText(fileContainingSavePath).Trim();
if (Directory.Exists(pathData))
{
var saveFolderTextBox = SaveFolder;
saveFolderTextBox.Text = pathData;
}
}
}
private async void OnDownloadButton_Click(object sender, RoutedEventArgs e)
{
var urlPartTextBox = Url;
var log = Log;
log.Text = string.Empty;
var saveFolderTextBox = SaveFolder;
if (string.IsNullOrWhiteSpace(saveFolderTextBox.Text))
{
log.Text += "ERROR: An output directory must be entered\n";
return;
}
var urlPart = urlPartTextBox.Text;
if (urlPart is null)
{
log.Text += "ERROR: A URL or media ID must be entered\n";
return;
}
var playlistControl = DownloadPlaylist;
Download downloadInfo = playlistControl!.IsChecked == true
? new PlaylistDownload(urlPart)
: new VideoDownload(urlPart);
if (!downloadInfo.ParsedData.ParsedSuccessfully)
{
log.Text += $"ERROR: {downloadInfo.Name} media ID could not be parsed from \"{urlPart}\"\n";
return;
}
log.Text += $"{downloadInfo.Name} media ID parsed OK: " + downloadInfo.ParsedData.Id + "\n";
var downloadExitCodeOrNull = await DownloadMediaAsync(downloadInfo);
if (downloadExitCodeOrNull is null)
{
log.Text += "ERROR: An unexpected error occurred.";
return;
}
if (downloadExitCodeOrNull == 0) // Success
{
log.Text += "Saved OK!\n";
urlPartTextBox.Text = string.Empty;
}
else
{
log.Text += $"ERROR: Could not download the video (error code {downloadExitCodeOrNull.ToString() ?? "unknown"}).\n\n";
return;
}
// Rename, if requested.
var newFileName = FileName;
if (string.IsNullOrWhiteSpace(newFileName?.Text))
return;
RenameFile(downloadInfo.ParsedData.Id!, saveFolderTextBox.Text, newFileName.Text);
newFileName.Text = string.Empty;
}
/// <summary>
/// Arranges download settings, then calls the external program
/// to download media data locally.
/// </summary>
/// <returns>A return code from the external program.</returns>
private async Task<int?> DownloadMediaAsync(Download downloadData)
{
var log = Log;
var args = "--extract-audio --audio-format mp3 --audio-quality 0";
var splitChapters = SplitChapters;
if (splitChapters!.IsChecked == true)
{
args += " --split-chapters";
log.Text += "Split Chapters is ON\n";
}
var playlist = DownloadPlaylist;
if (playlist!.IsChecked == true)
{
args += " --yes-playlist";
log.Text += "Download Playlist is ON\n";
}
string directory;
var saveFolderTextBox = SaveFolder;
if (string.IsNullOrWhiteSpace(saveFolderTextBox.Text))
{
log.Text += "ERROR: You must enter a folder path.\n";
return null;
}
directory = saveFolderTextBox.Text.Trim();
if (!Directory.Exists(directory))
{
log.Text += $"ERROR: Could not find directory \"{saveFolderTextBox.Text.Trim()}\"\n";
return null;
}
log.Text += $"Will save to directory \"{directory}\"\n";
var stopwatch = new Stopwatch();
stopwatch.Start();
const string processFileName = "yt-dlp";
log.Text += $"Running command: {processFileName} {args} {downloadData.FullUrl}\n";
var processInfo = new ProcessStartInfo()
{
FileName = processFileName,
Arguments = $"{args} {downloadData.FullUrl}",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
WorkingDirectory = directory
};
var process = await Task.Run(() => Process.Start(processInfo));
if (process is null)
{
log.Text += $"ERROR: Could not start process {processFileName} -- is it installed?\n\n";
return null;
}
process.WaitForExit();
log.Text += $"Done in {stopwatch.ElapsedMilliseconds:#,##0}ms\n";
return process.ExitCode;
}
/// <summary>
/// Renames a single download file as specified.
/// Does nothing (yet) if there are multiple matching files.
/// </summary>
/// <param name="mediaId"></param>
/// <param name="directory"></param>
/// <param name="newFileName"></param>
private void RenameFile(string mediaId, string directory, string newFileName)
{
GuardClauses();
var log = Log;
log.Text += $"Renaming file with video ID \"{mediaId}\" to \"{newFileName}\"...\n";
var foundFiles = Directory.EnumerateFiles(directory, $"*{mediaId}*").ToList();
if (foundFiles.Count == 0)
{
log.Text += $"No file to rename was found in \"{directory}\"\n";
return;
}
if (foundFiles.Count > 1)
{
log.Text += "ERROR: Cannot rename multiple files (yet).\n";
log.Text += $"{foundFiles.Count} files containing \"{mediaId}\" in their names were found:\n";
foundFiles.ForEach(f => log.Text += "- " + f + "\n");
return;
}
try
{
File.Move(foundFiles[0],
Path.Combine(directory, newFileName) + Path.GetExtension(foundFiles[0]),
overwrite: false);
}
catch (Exception ex)
{
log.Text += $"RENAMING ERROR: {ex.Message}\n";
return;
}
log.Text += "Rename OK!\n";
void GuardClauses()
{
if (string.IsNullOrWhiteSpace(mediaId))
{
throw new InvalidOperationException(
"A media ID must be provided."
);
}
if (string.IsNullOrWhiteSpace(directory))
{
throw new InvalidOperationException(
"A directory must be provided."
);
}
if (string.IsNullOrWhiteSpace(newFileName))
{
throw new InvalidOperationException(
"A new file name must be provided."
);
}
}
}
}
}