/
AddDownloadDialog.cs
589 lines (573 loc) · 22.7 KB
/
AddDownloadDialog.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
using Nickvision.Aura;
using NickvisionTubeConverter.GNOME.Controls;
using NickvisionTubeConverter.GNOME.Helpers;
using NickvisionTubeConverter.Shared.Controllers;
using NickvisionTubeConverter.Shared.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using static Nickvision.Aura.Localization.Gettext;
namespace NickvisionTubeConverter.GNOME.Views;
/// <summary>
/// The AddDownloadDialog for the application
/// </summary>
public partial class AddDownloadDialog : Adw.Window
{
private const uint GTK_INVALID_LIST_POSITION = 4294967295;
private readonly Gtk.Window _parent;
private readonly AddDownloadDialogController _controller;
private readonly List<MediaRow> _mediaRows;
private readonly string[] _audioQualities;
private string _saveFolderString;
[Gtk.Connect] private readonly Gtk.Label _titleLabel;
[Gtk.Connect] private readonly Adw.ToastOverlay _toastOverlay;
[Gtk.Connect] private readonly Adw.ViewStack _viewStack;
[Gtk.Connect] private readonly Adw.EntryRow _urlRow;
[Gtk.Connect] private readonly Adw.ExpanderRow _authRow;
[Gtk.Connect] private readonly Adw.ComboRow _keyringRow;
[Gtk.Connect] private readonly Adw.EntryRow _usernameRow;
[Gtk.Connect] private readonly Adw.PasswordEntryRow _passwordRow;
[Gtk.Connect] private readonly Gtk.Button _validateUrlButton;
[Gtk.Connect] private readonly Gtk.Button _addDownloadButton;
[Gtk.Connect] private readonly Gtk.Box _downloadPage;
[Gtk.Connect] private readonly Gtk.Button _backButton;
[Gtk.Connect] private readonly Adw.ComboRow _fileTypeRow;
[Gtk.Connect] private readonly Adw.ComboRow _qualityRow;
[Gtk.Connect] private readonly Adw.ComboRow _audioLanguageRow;
[Gtk.Connect] private readonly Adw.SwitchRow _subtitleRow;
[Gtk.Connect] private readonly Adw.EntryRow _saveFolderRow;
[Gtk.Connect] private readonly Gtk.Button _selectSaveFolderButton;
[Gtk.Connect] private readonly Adw.ActionRow _openAdvancedRow;
[Gtk.Connect] private readonly Adw.PreferencesGroup _mediaGroup;
[Gtk.Connect] private readonly Adw.PreferencesGroup _openPlaylistGroup;
[Gtk.Connect] private readonly Adw.ActionRow _openPlaylistRow;
[Gtk.Connect] private readonly Adw.SwitchRow _numberTitlesRow;
[Gtk.Connect] private readonly Gtk.Button _selectAllButton;
[Gtk.Connect] private readonly Gtk.Button _deselectAllButton;
[Gtk.Connect] private readonly Adw.PreferencesGroup _playlistGroup;
[Gtk.Connect] private readonly Adw.SwitchRow _speedLimitRow;
[Gtk.Connect] private readonly Adw.SwitchRow _preferAV1Row;
[Gtk.Connect] private readonly Adw.SwitchRow _splitChaptersRow;
[Gtk.Connect] private readonly Adw.SwitchRow _cropThumbnailRow;
[Gtk.Connect] private readonly Adw.ExpanderRow _downloadTimeframeRow;
[Gtk.Connect] private readonly Adw.EntryRow _timeframeStartRow;
[Gtk.Connect] private readonly Adw.EntryRow _timeframeEndRow;
private Gtk.Spinner? _urlSpinner;
public event EventHandler? OnDownload;
/// <summary>
/// Constructs an AddDownloadDialog
/// </summary>
/// <param name="builder">Gtk.Builder</param>
/// <param name="controller">AddDownloadDialogController</param>
/// <param name="parent">Gtk.Window</param>
private AddDownloadDialog(Gtk.Builder builder, AddDownloadDialogController controller, Gtk.Window parent) : base(builder.GetPointer("_root"), false)
{
_parent = parent;
_controller = controller;
_mediaRows = new List<MediaRow>();
_audioQualities = new string[] { _("Best"), _("Worst") };
//Dialog Settings
SetTransientFor(parent);
SetIconName(_controller.AppInfo.ID);
//Build UI
builder.Connect(this);
_validateUrlButton.OnClicked += async (sender, e) => await SearchUrlAsync(_urlRow.GetText());
_viewStack.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "visible-child")
{
_backButton.SetVisible(_viewStack.GetVisibleChildName() == "pagePlaylist" || _viewStack.GetVisibleChildName() == "pageAdvanced");
_titleLabel.SetLabel(_viewStack.GetVisibleChildName() switch
{
"pagePlaylist" => _("Playlist"),
"pageAdvanced" => _("Advanced Options"),
_ => _("Add Download")
});
}
};
_backButton.OnClicked += (sender, e) => _viewStack.SetVisibleChildName("pageDownload");
_urlRow.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "text")
{
if (!string.IsNullOrEmpty(_urlRow.GetText()))
{
var result = Uri.TryCreate(_urlRow.GetText(), UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
_validateUrlButton.SetSensitive(result);
}
}
};
_authRow.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "enable-expansion")
{
_usernameRow.SetText("");
_passwordRow.SetText("");
}
};
_keyringRow.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "selected")
{
if (_keyringRow.GetSelected() == 0)
{
_usernameRow.SetVisible(true);
_passwordRow.SetVisible(true);
}
else
{
_usernameRow.SetVisible(false);
_passwordRow.SetVisible(false);
}
}
};
_fileTypeRow.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "selected-item")
{
OnFileTypeChanged();
}
};
_selectSaveFolderButton.OnClicked += async (sender, e) => await SelectSaveFolderAsync();
_cropThumbnailRow.SetVisible(_controller.EmbedMetadata);
_speedLimitRow.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "active")
{
if (_speedLimitRow.GetActive())
{
_downloadTimeframeRow.SetExpanded(false);
}
_downloadTimeframeRow.SetSensitive(!_speedLimitRow.GetActive());
}
};
_downloadTimeframeRow.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "expanded")
{
if (_downloadTimeframeRow.GetExpanded())
{
_speedLimitRow.SetActive(false);
_timeframeStartRow.SetText(TimeSpan.FromSeconds(0).ToString(@"hh\:mm\:ss"));
_timeframeEndRow.SetText(TimeSpan.FromSeconds(_controller.MediaList[0].Duration).ToString(@"hh\:mm\:ss"));
}
_speedLimitRow.SetSensitive(!_downloadTimeframeRow.GetExpanded());
ValidateOptions();
}
};
_timeframeStartRow.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "text")
{
ValidateOptions();
}
};
_timeframeEndRow.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "text")
{
ValidateOptions();
}
};
_openAdvancedRow.OnActivated += (sender, e) => _viewStack.SetVisibleChildName("pageAdvanced");
_openPlaylistRow.OnActivated += (sender, e) => _viewStack.SetVisibleChildName("pagePlaylist");
_numberTitlesRow.OnNotify += (sender, e) =>
{
if (e.Pspec.GetName() == "active")
{
ToggleNumberTitles();
}
};
_selectAllButton.OnClicked += (sender, e) =>
{
foreach (var row in _mediaRows)
{
row.Active = true;
}
};
_deselectAllButton.OnClicked += (sender, e) =>
{
foreach (var row in _mediaRows)
{
row.Active = false;
}
};
//Add Download Button
_addDownloadButton.OnClicked += AddDownload;
_addDownloadButton.SetSensitive(false);
//Load
_viewStack.SetVisibleChildName("pageUrl");
SetDefaultWidget(_validateUrlButton);
if (Directory.Exists(_controller.PreviousSaveFolder))
{
_saveFolderString = _controller.PreviousSaveFolder;
}
else
{
_saveFolderString = UserDirectories.Downloads;
}
_saveFolderRow.SetText(Path.GetFileName(_saveFolderString) ?? "");
_subtitleRow.SetActive(_controller.PreviousSubtitleState);
_preferAV1Row.SetActive(_controller.PreviousPreferAV1State);
_speedLimitRow.SetSubtitle($"{_("{0:f1} KiB/s", _controller.CurrentSpeedLimit)} {_("(Configurable in preferences)")}");
}
/// <summary>
/// Constructs an AddDownloadDialog
/// </summary>
/// <param name="controller">AddDownloadDialogController</param>
/// <param name="parent">Gtk.Window</param>
public AddDownloadDialog(AddDownloadDialogController controller, Gtk.Window parent) : this(Builder.FromFile("add_download_dialog.ui"), controller, parent)
{
}
/// <summary>
/// The MediaFileType object representing the selected file type
/// </summary>
private MediaFileType SelectedMediaFileType
{
get
{
MediaFileType fileType;
if (_controller.DisallowConversions)
{
fileType = (_fileTypeRow.GetSelected() == 0 && _controller.HasVideoResolutions) ? MediaFileType.Video : MediaFileType.Audio;
}
else
{
fileType = (MediaFileType)_fileTypeRow.GetSelected();
if (!_controller.HasVideoResolutions)
{
fileType += 2;
}
}
return fileType;
}
}
/// <summary>
/// Presents the dialog
/// </summary>
/// <param name="url">A url to validate at startup</param>
public async Task PresentAsync(string? url = null)
{
Present();
//Validated from startup
if (!string.IsNullOrEmpty(url))
{
_urlRow.SetText(url);
await SearchUrlAsync(url);
}
else
{
//Validate Clipboard
var clipboard = Gdk.Display.GetDefault()!.GetClipboard();
try
{
var clipboardText = await clipboard.ReadTextAsync();
if (!string.IsNullOrEmpty(clipboardText))
{
var result = Uri.TryCreate(clipboardText, UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
if (result)
{
_urlRow.SetText(clipboardText);
_urlRow.SelectRegion(0, -1);
}
}
}
catch { }
}
//Keyring
var names = await _controller.GetKeyringCredentialNamesAsync();
if (names.Count > 0)
{
_keyringRow.SetModel(Gtk.StringList.New(names.ToArray()));
_keyringRow.SetSelected(names.Count > 1 ? 1u : 0u);
}
else
{
_keyringRow.SetVisible(false);
_usernameRow.SetVisible(true);
_passwordRow.SetVisible(true);
}
}
/// <summary>
/// Searches for information about a URL in the dialog
/// </summary>
/// <param name="url">The URL to search</param>
private async Task SearchUrlAsync(string url)
{
_urlSpinner = Gtk.Spinner.New();
_validateUrlButton.SetSensitive(false);
_validateUrlButton.SetChild(_urlSpinner);
_urlSpinner.Start();
await Task.Run(async () =>
{
try
{
if (_keyringRow.GetSelected() == 0 || _keyringRow.GetSelected() == GTK_INVALID_LIST_POSITION || !_authRow.GetEnableExpansion())
{
await _controller.SearchUrlAsync(url, _usernameRow.GetText(), _passwordRow.GetText());
}
else
{
await _controller.SearchUrlAsync(url, ((int)_keyringRow.GetSelected()) - 1);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
});
_urlSpinner.Stop();
_urlRow.RemoveCssClass("error");
_urlRow.SetTitle(_("Media URL"));
_validateUrlButton.SetSensitive(true);
_validateUrlButton.SetChild(null);
_validateUrlButton.SetLabel(_("Validate"));
if (!_controller.HasMediaInfo)
{
_urlRow.AddCssClass("error");
_urlRow.SetTitle(_("Media URL (Invalid)"));
if (_authRow.GetEnableExpansion())
{
_toastOverlay.AddToast(Adw.Toast.New(_("Ensure credentials are correct.")));
}
}
else
{
if (!_controller.HasVideoResolutions)
{
if (_controller.DisallowConversions)
{
_fileTypeRow.SetModel(Gtk.StringList.New(new string[] { _("Audio") }));
_fileTypeRow.SetSelected(0);
}
else
{
_fileTypeRow.SetModel(Gtk.StringList.New(new string[] { "MP3", "M4A", "OPUS", "FLAC", "WAV" }));
_fileTypeRow.SetSelected((uint)Math.Max((int)_controller.PreviousMediaFileType - 2, 0));
}
}
else
{
if (_controller.DisallowConversions)
{
_fileTypeRow.SetModel(Gtk.StringList.New(new string[] { _("Video"), _("Audio") }));
_fileTypeRow.SetSelected(_controller.PreviousGenericMediaFileType switch
{
MediaFileType.Audio => 1,
_ => 0
});
}
else
{
_fileTypeRow.SetSelected((uint)_controller.PreviousMediaFileType);
}
}
if (_controller.AudioLanguages.Count > 1)
{
_audioLanguageRow.SetVisible(true);
_audioLanguageRow.SetModel(Gtk.StringList.New(_controller.AudioLanguages.ToArray()));
if(_controller.AudioLanguages.Contains(CultureInfo.CurrentCulture.TwoLetterISOLanguageName))
{
_audioLanguageRow.SetSelected((uint)_controller.AudioLanguages.IndexOf(CultureInfo.CurrentCulture.TwoLetterISOLanguageName));
}
}
OnFileTypeChanged(); // in case _fileTypeRow.SetSelected didn't invoke OnNotify
_downloadPage.SetVisible(true);
_viewStack.SetVisibleChildName("pageDownload");
SetDefaultWidget(_addDownloadButton);
_addDownloadButton.SetSensitive(Directory.Exists(_saveFolderString));
_numberTitlesRow.SetVisible(_controller.MediaList.Count > 1 ? true : false);
if (_controller.MediaList.Count > 1)
{
foreach (var mediaInfo in _controller.MediaList)
{
var row = new MediaRow(mediaInfo, _controller.LimitCharacters);
_mediaRows.Add(row);
row.OnSelectionChanged += PlaylistChanged;
_playlistGroup.Add(row);
}
_downloadTimeframeRow.SetVisible(false);
_openPlaylistGroup.SetVisible(true);
_openPlaylistRow.SetTitle(_n("{0} of {1} items", "{0} of {1} items", _controller.MediaList.Count, _controller.MediaList.Count, _controller.MediaList.Count));
_qualityRow.SetTitle(_("Maximum Quality"));
if (_controller.NumberTitles)
{
_numberTitlesRow.SetActive(true);
}
}
else
{
_downloadTimeframeRow.SetVisible(_controller.MediaList[0].Duration > 0);
var row = new MediaRow(_controller.MediaList[0], _controller.LimitCharacters);
row.SetActivatesDefault(true);
_mediaRows.Add(row);
_mediaGroup.SetVisible(true);
_mediaGroup.Add(row);
}
ValidateOptions();
}
}
/// <summary>
/// Validate download options
/// </summary>
private void ValidateOptions()
{
_saveFolderRow.RemoveCssClass("error");
_saveFolderRow.SetTitle(_("Save Folder"));
_timeframeStartRow.RemoveCssClass("error");
_timeframeStartRow.SetTitle(_("Start Time"));
_timeframeEndRow.RemoveCssClass("error");
_timeframeEndRow.SetTitle(_("End Time"));
_addDownloadButton.SetSensitive(false);
var status = _controller.ValidateDownloadOptions(_saveFolderString, _downloadTimeframeRow.GetExpanded(), _timeframeStartRow.GetText(), _timeframeEndRow.GetText(), _controller.MediaList[0].Duration);
if (status == DownloadOptionsCheckStatus.Valid)
{
_addDownloadButton.SetSensitive(true);
return;
}
if (status.HasFlag(DownloadOptionsCheckStatus.InvalidSaveFolder))
{
_saveFolderRow.SetTitle(_("Save Folder (Invalid)"));
_saveFolderRow.AddCssClass("error");
}
if (status.HasFlag(DownloadOptionsCheckStatus.InvalidTimeframeStart))
{
_timeframeStartRow.SetTitle(_("Start Time (Invalid)"));
_timeframeStartRow.AddCssClass("error");
}
if (status.HasFlag(DownloadOptionsCheckStatus.InvalidTimeframeEnd))
{
_timeframeEndRow.SetTitle(_("End Time (Invalid)"));
_timeframeEndRow.AddCssClass("error");
}
}
/// <summary>
/// Occurs when the file type was changed
/// </summary>
private void OnFileTypeChanged()
{
if (SelectedMediaFileType.GetIsVideo())
{
_qualityRow.SetModel(Gtk.StringList.New(_controller.VideoResolutions.ToArray()));
var findPrevious = _controller.PreviousVideoResolutionIndex;
if (findPrevious != -1)
{
_qualityRow.SetSelected((uint)findPrevious);
}
_subtitleRow.SetVisible(true);
_preferAV1Row.SetVisible(true);
}
else
{
_qualityRow.SetModel(Gtk.StringList.New(_audioQualities));
_subtitleRow.SetVisible(false);
_preferAV1Row.SetVisible(false);
}
if (_controller.CropAudioThumbnails)
{
_cropThumbnailRow.SetActive(SelectedMediaFileType.GetIsAudio());
}
}
/// <summary>
/// Occurs when the select save folder button is clicked
/// </summary>
private async Task SelectSaveFolderAsync()
{
var folderDialog = Gtk.FileDialog.New();
folderDialog.SetTitle(_("Select Save Folder"));
if (Directory.Exists(_saveFolderString) && _saveFolderString != "/" && string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SNAP")))
{
var folder = Gio.FileHelper.NewForPath(_saveFolderString);
folderDialog.SetInitialFolder(folder);
}
try
{
var file = await folderDialog.SelectFolderAsync(this);
_saveFolderString = file.GetPath();
_saveFolderRow.SetText(Path.GetFileName(_saveFolderString));
_saveFolderRow.RemoveCssClass("error");
}
catch { }
ValidateOptions();
}
/// <summary>
/// Occurs when the number of items selected to download has changed
/// </summary>
/// <param name="sender">object?</param>
/// <param name="e">EventArgs</param>
private void PlaylistChanged(object? sender, EventArgs e)
{
var downloadsCount = _controller.MediaList.FindAll(x => x.ToDownload).Count;
_openPlaylistRow.SetTitle(_n("{0} of {1} items", "{0} of {1} items", _controller.MediaList.Count, downloadsCount, _controller.MediaList.Count));
_addDownloadButton.SetSensitive(downloadsCount > 0);
}
/// <summary>
/// Occurs when the number titles toggle button is clicked
/// </summary>
private void ToggleNumberTitles()
{
if (_controller.ToggleNumberTitles(_numberTitlesRow.GetActive()))
{
foreach (var row in _mediaRows)
{
row.UpdateTitle(_numberTitlesRow.GetActive());
}
}
}
/// <summary>
/// Occurs when the add download button is clicked
/// </summary>
/// <param name="sender">Gtk.Button</param>
/// <param name="e">EventArgs</param>
private async void AddDownload(Gtk.Button sender, EventArgs e)
{
Quality quality;
int? resolutionIndex;
if (SelectedMediaFileType.GetIsAudio())
{
quality = (Quality)_qualityRow.GetSelected();
resolutionIndex = null;
}
else
{
quality = Quality.Resolution;
resolutionIndex = (int)_qualityRow.GetSelected();
}
string? audioLanguage = null;
if (_controller.AudioLanguages.Count > 1)
{
audioLanguage = _controller.AudioLanguages[(int)_audioLanguageRow.GetSelected()];
}
Timeframe? timeframe = null;
if (_downloadTimeframeRow.GetExpanded())
{
try
{
timeframe = Timeframe.Parse(_timeframeStartRow.GetText(), _timeframeEndRow.GetText(), _controller.MediaList[0].Duration);
}
catch { }
}
var options = new AdvancedDownloadOptions()
{
LimitSpeed = _speedLimitRow.GetActive(),
PreferAV1 = _preferAV1Row.GetActive(),
SplitChapters = _splitChaptersRow.GetActive(),
CropThumbnail = _cropThumbnailRow.GetActive(),
Timeframe = timeframe
};
if (_keyringRow.GetSelected() == 0 || _keyringRow.GetSelected() == GTK_INVALID_LIST_POSITION || !_authRow.GetEnableExpansion())
{
options.Username = _usernameRow.GetText();
options.Password = _passwordRow.GetText();
_controller.PopulateDownloads(SelectedMediaFileType, quality, resolutionIndex, audioLanguage, _subtitleRow.GetActive(), _saveFolderString, options);
}
else
{
await _controller.PopulateDownloadsAsync(SelectedMediaFileType, quality, resolutionIndex, audioLanguage, _subtitleRow.GetActive(), _saveFolderString, options, ((int)_keyringRow.GetSelected()) - 1);
}
OnDownload?.Invoke(this, EventArgs.Empty);
}
}