-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.razor
More file actions
766 lines (744 loc) · 39.9 KB
/
Copy pathApp.razor
File metadata and controls
766 lines (744 loc) · 39.9 KB
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
@using System.Reflection;
@using static AvailableProperties;
@using Microsoft.FluentUI.AspNetCore.Components;
@using System.IO.Compression;
@using MetadataChange.Layout;
@using MetadataChange;
@using System.Text.Json.Serialization
@inject IToastService ToastService
@inject IJSRuntime JS;
<FluentDesignSystemProvider Font BaseLayerLuminance="(float) 0.1">
<div
style="max-width: calc(100vw - 30px); max-height: calc(100vh - 30px); width: calc(100vw - 30px); top: 0; left: 0; position: fixed; padding: 15px; overflow: auto;">
<header>
<div class="labelFlex">
<img style="width: 48px; height: 48px" id="logo">
<h1>TagLibSharp-Web</h1>
</div>
<p>Edit all the metadata of an audio or video file using TagLib Sharp</p>
</header><br>
<FluentButton Id="settingsBtn" style="position: absolute; top: 15px; width: fit-content; right: 15px;"
IconStart="@(new Icons.Regular.Size20.Settings())" Appearance="Appearance.Accent"
@onclick='() => {showSettings = true;}'></FluentButton>
<FluentTooltip Anchor="settingsBtn" Position="TooltipPosition.Left">Show settings</FluentTooltip>
<FluentToastProvider MaxToastCount="1" />
@if (files.Count != 0)
{
<FluentCard style="contain: inherit; content-visibility: inherit;">
<h2>Edit metadata:</h2>
@if (showGrid)
{
<p>Choose the fields to show in the table:</p>
<FluentListbox Items=@(AvailableProperties.AvailableMetadata) Multiple="true" Height="20vh"
TOption="AvailableProperties.PropertiesObject" OptionText="@(file => file.DisplayName)"
SelectedOptionsChanged="(file) => {
gridSelected = file.ToList();
StateHasChanged();
}">
</FluentListbox>
<br>
<br>
<FluentCard style="background: var(--neutral-fill-active);" AreaRestricted="false">
<FluentSelect Appearance="Appearance.Outline" TOption="string" @onchange="UpdateMultipleOptions">
<FluentOption Value="-1">Update only this entry</FluentOption>
<FluentOption Value="0">Update all items</FluentOption>
<FluentOption Value="1">Update the files with the same album</FluentOption>
<FluentOption Value="2">Update the files with the same album (only common values)</FluentOption>
</FluentSelect><br><br>
<FluentDataGrid ResizableColumns="true" ResizeType="DataGridResizeType.Discrete"
Items="files.AsQueryable<TagInfoContainer>()" ItemKey="@(file => file.id)">
<TemplateColumn Width="@((100 /(gridSelected.Count + 2)) + "%")" Sortable="false" Title="Actions:">
<div class="flexContainer">
<FluentButton Id="@($"{context.id}customImage")" IconStart="@(new Icons.Regular.Size20.Image())" @onclick='@(() => {
fileEditPosition = int.Parse(@context.id);
showImageDialog = true;
})'>
</FluentButton>
<FluentTooltip Anchor="@($"{context.id}customImage")" Position="TooltipPosition.Bottom">Change album art</FluentTooltip>
<FluentButton Id="@($"{context.id}customMetadata")" IconStart="@(new Icons.Regular.Size20.StarEdit())" @onclick='@(() => {
fileEditPosition = int.Parse(@context.id);
showCustomMetadata = true;
})'></FluentButton>
<FluentTooltip Anchor="@($"{context.id}customMetadata")" Position="TooltipPosition.Bottom">Add custom metadata & advanced metadata view</FluentTooltip>
<FluentButton Id="@($"{context.id}customLyrics")" OnClick='@(() => {
fileEditPosition = int.Parse(@context.id);
showUploadLyricsDialog = true;
})' IconStart="@(new Icons.Regular.Size20.AttachText())"></FluentButton>
<FluentTooltip Anchor="@($"{context.id}customLyrics")" Position="TooltipPosition.Bottom">Fetch lyrics online, or add them from a local file</FluentTooltip>
<FluentButton Id="@($"{context.id}playAudio")" OnClick="@(() => {
fileEditPosition = int.Parse(@context.id);
showPlayDialog = true;
})" IconStart="@(new Icons.Regular.Size20.Play())"></FluentButton>
<FluentTooltip Anchor="@($"{context.id}playAudio")" Position="TooltipPosition.Bottom">Play the audio or video file</FluentTooltip>
</div>
</TemplateColumn>
<TemplateColumn Width="@((100 /(gridSelected.Count + 2)) + "%")"
SortBy="GridSort<TagInfoContainer>.ByAscending(file => file.file)" Title="File name:"
Sortable="true">
<a style="text-decoration: underline; white-space: normal"
@onclick='() => SaveItem(context)'>@context.file</a>
</TemplateColumn>
@foreach (AvailableProperties.PropertiesObject metadata in gridSelected)
{
<TemplateColumn Width="@((100 /(gridSelected.Count + 2)) + "%")" SortBy="gridSort(metadata)"
Title="@metadata.DisplayName" Sortable="true">
@if (metadata.ConvertValue ==
AvailableProperties.PropertiesObject.PropertiesType.STRING_TEXTAREA)
{
<FluentTextArea @onchange="(val) => UpdateValueFromEvent(val, metadata, context)"
value=@(TagValueHandler.GetCurrentValue(metadata.TagLibProperty, context))>
</FluentTextArea>
}
else
{
<FluentTextField @onchange="(val) => UpdateValueFromEvent(val, metadata, context)"
value=@(TagValueHandler.GetCurrentValue(metadata.TagLibProperty, context))
type=@(metadata.ConvertValue == AvailableProperties.PropertiesObject.PropertiesType.UINT ?
"number" : "text")>
</FluentTextField>
}
</TemplateColumn>
}
</FluentDataGrid><br>
<FluentButton @onclick='() => {showUploadDialog = true;}' Appearance="Appearance.Lightweight">Add
files</FluentButton>
</FluentCard>
}
else
{
<div class="labelFlex">
<FluentSelect @onchange="(val) => {fileEditPosition = int.Parse(val.Value.ToString());}" Items="files "
OptionValue="@(file => file.id)" OptionText="@(file => file.file)"></FluentSelect>
<FluentButton Appearance="Appearance.Accent" style="width: fit-content"
@onclick='() => {showUploadDialog = true;}'>+
</FluentButton>
</div>
<p>Choose a property to edit about the metadata</p>
<FluentSelect Items=@(AvailableProperties.AvailableMetadata.Select(file => file.DisplayName))
TOption="string"
@onchange="(val) => {selectedItem = AvailableProperties.AvailableMetadata.Find(item => item.DisplayName == val.Value.ToString());}">
</FluentSelect>
<br>
<br>
<FluentCard style="background: var(--neutral-fill-active);" AreaRestricted="false">
@if (selectedItem.ConvertValue ==
AvailableProperties.PropertiesObject.PropertiesType.STRING_TEXTAREA)
{
<FluentTextArea @onchange="UpdateValueFromEvent"
value=@(TagValueHandler.GetCurrentValue(selectedItem.TagLibProperty, files[fileEditPosition]))>
</FluentTextArea>
}
else
{
<FluentTextField @onchange=" UpdateValueFromEvent"
value=@(TagValueHandler.GetCurrentValue(selectedItem.TagLibProperty, files[fileEditPosition]))
type=@(selectedItem.ConvertValue == AvailableProperties.PropertiesObject.PropertiesType.UINT ?
"number" : "text")>
</FluentTextField>
}
<br><br>
<FluentSelect TOption="string" Appearance="Appearance.Outline" @onchange="UpdateMultipleOptions">
<FluentOption Value="-1">Update only this entry</FluentOption>
<FluentOption Value="0">Update all items</FluentOption>
<FluentOption Value="1">Update the files with the same album</FluentOption>
<FluentOption Value="2">Update the files with the same album (only common values)</FluentOption>
</FluentSelect>
</FluentCard>
}
<br>
<div class="flexContainer">
@if (!showGrid)
{
<FluentMenuButton Text="Edit other metadata" Items="advancedMetadataSettings" ButtonAppearance="Appearance.Accent" OnMenuChanged='@((arg) => {
showImageDialog = arg.Id == "0";
showCustomMetadata = arg.Id == "1";
showUploadLyricsDialog = arg.Id == "2";
showPlayDialog = arg.Id == "3";
})'></FluentMenuButton>
}
<FluentButton Appearance="@(showGrid ? Appearance.Accent : Appearance.Outline)"
@onclick='() => {showCopyMetadata = true;}'>Copy
metadata
</FluentButton>
</div><br>
</FluentCard>
<br>
<FluentCard>
<div class="flexContainer">
@if (!showGrid)
{
<FluentButton Appearance="Appearance.Accent" @onclick="() => SaveItem(files[fileEditPosition])">Download
edited
file
</FluentButton>
}
<FluentButton @onclick="SaveItemsFSApi"
Appearance="@(showGrid ? Appearance.Accent : Appearance.Neutral)">Save everything in your device's
folder</FluentButton>
<FluentButton @onclick="SaveItemsInZip"
Appearance="@(showGrid ? Appearance.Neutral : Appearance.Outline)">Download everything in a ZIP
file
</FluentButton>
</div>
</FluentCard>
<br>
<FluentCard style="contain: inherit; content-visibility: inherit;">
<h2>Redownload files:</h2>
<p>Choose a file to download again, then click on the link. You can also delete the entry (the
downloaded file will remain on the device).</p>
<div class="labelFlex">
<FluentSelect @bind-Value="selectedFileDownload" TOption="DownloadResult"
OptionValue="@(file => file.url)" OptionText="@(file => file.name)" Items="redownloadFiles">
</FluentSelect>
<FluentButton Id="DeleteDownloadFile" style="width: fit-content;" Appearance="Appearance.Accent" @onclick='async () => {
redownloadFiles.Remove(redownloadFiles.Find(file => file.url == selectedFileDownload));
await JS.InvokeVoidAsync("revokeUrl", [selectedFileDownload]);
selectedFileDownload = "";
}' IconStart="@(new Icons.Regular.Size20.Delete())">
</FluentButton>
<FluentTooltip Anchor="DeleteDownloadFile" Position="TooltipPosition.Left">Delete file from RAM (not from your drive)</FluentTooltip>
</div><br>
@if (selectedFileDownload != "" && selectedFileDownload != null)
{
<a style="color: var(--neutral-foreground-rest)" href="@selectedFileDownload"
download="@(redownloadFiles.Find(file => file.url == selectedFileDownload).name)">Download again</a>
}
</FluentCard>
@if (showImageDialog)
{
<MetadataChange.Layout.ImageElement imageTags="@(files[fileEditPosition].tag.Tag.Pictures)"
Callback="@(() => {
showImageDialog = false;
StateHasChanged();
})" files="@files" fileEditPosition="@fileEditPosition" DownloadFile="async (byte[] bytes, string str) => await DownloadFile(bytes, str)">
</MetadataChange.Layout.ImageElement>
}
@if (showCustomMetadata)
{
<CustomMetadata AvailableTags="files" Callback="() => {
showCustomMetadata = false;
StateHasChanged();
}" CurrentFile="fileEditPosition" DownloadFileAction="async (byte[] bytes, string str) => await DownloadFile(bytes, str)">
</CustomMetadata>
}
@if (showCopyMetadata)
{
<MetadataCopy Container="files" CurrentPosition="@fileEditPosition.ToString()" Callback="() => {
showCopyMetadata = false;
StateHasChanged();
}">
</MetadataCopy>
}
@if (showUploadLyricsDialog) {
<UploadLyrics Container="files" CurrentPosition="@fileEditPosition.ToString()" Callback="() => {
showUploadLyricsDialog = false;
StateHasChanged();
}" RerenderState="() => {
if (!showUploadLyricsDialog) StateHasChanged();
}" DownloadFile="DownloadLrcZipFile"></UploadLyrics>
}
@if (showPlayDialog) {
<PlayFile Callback="() => {
showPlayDialog = false;
StateHasChanged();
}" SelectedFile="files[fileEditPosition]"></PlayFile>
}
}
else
{
<FluentCard>
<h2>Choose files:</h2>
<MainFileInput GetFiles="GetFiles"></MainFileInput>
<br>
<p>Don't worry. Everything will be elaborated locally.</p>
</FluentCard>
}
@if (showSettings)
{
<Settings GridUpdate="(val) => {showGrid = val; StateHasChanged();}" fileSystemAvailable="fileSystemAvailable"
showGrid="showGrid" Callback="() => {
showSettings = false;
StateHasChanged();
}"></Settings>
}
@if (showLicenses)
{
<Licenses Callback="() => {
showLicenses = false;
StateHasChanged();
}"></Licenses>
}
@if (showUploadDialog) {
<FluentDialog>
<FluentDialogHeader>
<div>
<h2>Pick files:</h2>
<FluentButton Id="CloseDialogBtn" Appearance="Appearance.Lightweight" @onclick="() => {showUploadDialog = false;}" IconStart="@(new Icons.Regular.Size20.Dismiss())"></FluentButton>
<FluentTooltip Anchor="CloseDialogBtn" Position="TooltipPosition.Left">Close the dialog</FluentTooltip>
</div>
</FluentDialogHeader>
<MainFileInput GetFiles="GetFiles"></MainFileInput>
</FluentDialog>
}
<br>
<FluentCard>
<h2>Credits:</h2>
<p>Website made with <a href="https://github.com/dotnet/aspnetcore" target="_blank">Blazor WebAssembly</a>, the <a target="_blank" href="https://github.com/mono/taglib-sharp">TagLib-Sharp library</a> and the <a href="https://github.com/JamesNK/Newtonsoft.Json" target="_blank">Newtonsoft.Json library</a>. This
project is in no way affiliated with TagLib-Sharp.</p><br>
<a style="margin-right: 10px;" href="https://github.com/dinoosauro/taglibsharp-web" target="_blank">View on
GitHub</a>
<label style="text-decoration: underline;" class="hover" @onclick="() => {showLicenses = true;}">View
licenses</label>
</FluentCard>
</div>
<FluentTooltipProvider />
</FluentDesignSystemProvider>
<script>
/**
The File System Directory Handle for saving multiple files.
If this value isn't nullish, the next files will be saved there.
*/
let directoryHandle;
/**
Get a valid file name for the OS
*/
function getFileName(name) {
return name.trim().replaceAll("/", "⧸").replaceAll("\\", "⧹").replaceAll("?", "ʔ").replaceAll("*", "*").replaceAll(":", "꞉").replaceAll("|", "∣").replaceAll("\"", "'").replaceAll("<", "˂").replaceAll(">", "˃");
}
async function downloadByteArray(byte, name, useDirectoryHandle) {
// The values returned are [The link (or null if the File System API has been used), the file name, "0" if the File System API has been used, or "1" if it hasn't been used]
if (useDirectoryHandle && typeof (window.showDirectoryPicker) !== "undefined") {
if (!directoryHandle) directoryHandle = await window.showDirectoryPicker({ mode: "readwrite", id: "TagLibWeb-Picker" });
// We'll now navigate through all the subdirectories to save that file
let directoryHandleToUse = directoryHandle;
const splitFile = name.split("/");
const outputName = splitFile.pop();
for (const path of splitFile) directoryHandleToUse = await directoryHandleToUse.getDirectoryHandle(path, {create: true});
const handle = await directoryHandleToUse.getFileHandle(getFileName(outputName), { create: true });
const writable = await handle.createWritable();
await writable.write(byte);
await writable.close();
return [null, name, "0"];
} else if (localStorage.getItem("TagLibWeb-UseFS") !== "b" && typeof (window.showSaveFilePicker) !== "undefined") {
try {
const handle = await window.showSaveFilePicker({ id: "TagLibWeb-Picker", suggestedName: name.indexOf("/") !== -1 ? getFileName(name.substring(name.lastIndexOf("/") + 1)) : getFileName(name) });
const writable = await handle.createWritable();
await writable.write(byte);
await writable.close();
return [null, name, "0"];
} catch (ex) {
console.warn("Failed File System API usage", ex);
}
}
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([byte]));
a.download = name.indexOf("/") !== -1 ? getFileName(name.substring(name.lastIndexOf("/") + 1)) : getFileName(name);
a.click();
return [a.href, name, "1"];
}
/**
Remove the previously-selected directory handle
*/
function clearDirectoryHandle() {
directoryHandle = undefined;
}
/**
Open new files from the user's drive
*/
function clickInput(isDirectory) {
if (isDirectory) {
// Since there's no support in Blazor for picking directories, we'll create a new input, update the name to add the directories (the real file name in Blazor memory will still be the temp file created, but the suggested name will be the new one), and finally we'll trigger the onchange event.
const input = document.createElement("input");
input.type = "file";
input.webkitdirectory = true;
input.multiple = true;
input.onchange = () => {
const dataTransfer = new DataTransfer();
Array.from(input.files).forEach(item => dataTransfer.items.add(new File([item], item.webkitRelativePath || item.name, {type: item.type})));
document.getElementById("fileUploader").files = dataTransfer.files;
document.getElementById("fileUploader").dispatchEvent(new Event("change", { bubbles: true }));
};
input.click();
} else document.getElementById("fileUploader").click();
}
/**
Revoke a Blob URL
*/
function revokeUrl(url) {
URL.revokeObjectURL(url);
}
</script>
@code {
private enum MultipleUpdateOptions {
/// <summary>
/// Update only the currently-selected file
/// </summary>
SINGLE_UPDATE = -1,
/// <summary>
/// Update all the uploaded audio files
/// </summary>
UPDATE_EVERYTHING = 0,
/// <summary>
/// Update all the files with the same album name
/// </summary>
UPDATE_ALBUM = 1,
/// <summary>
/// Update all the files with the same album name, only if the selected field isn't track-specific (ex: track title, etc.)
/// </summary>
UPDATE_COMMON_ALBUM = 2
}
/// <summary>
/// What the application should do when an entry is updated
/// </summary>
private MultipleUpdateOptions IntelligentAlbumUpdate = MultipleUpdateOptions.SINGLE_UPDATE;
/// <summary>
/// If the "Lyrics upload" dialog should be shown or not
/// </summary>
public bool showUploadLyricsDialog = false;
/// <summary>
/// If the album art editor should be shown
/// </summary>
public bool showImageDialog = false;
/// <summary>
/// If the "add a custom metadata" dialog should be shown
/// </summary>
public bool showCustomMetadata = false;
/// <summary>
/// If the "copy metadata from a tag to another" should be shown
/// </summary>
public bool showCopyMetadata = false;
/// <summary>
/// If the dialog that plays the uploaded video or audio file should be played
/// </summary>
public bool showPlayDialog = false;
/// <summary>
/// If the settings dialog should be shown
/// </summary>
public bool showSettings = false;
/// <summary>
/// If the licenses dialog should be shown
/// </summary>
public bool showLicenses = false;
/// <summary>
/// Switch to the metadata grid view instead of the cloassic single metadata view
/// </summary>
private bool showGrid = true;
/// <summary>
/// Show the dialog where the user can upload more files
/// </summary>
private bool showUploadDialog = false;
/// <summary>
/// A list that contains all the selected tag options
/// </summary>
private List<AvailableProperties.PropertiesObject> gridSelected = new List<PropertiesObject>();
/// <summary>
/// Information about the currently-selected tag
/// </summary>
private AvailableProperties.PropertiesObject selectedItem = AvailableProperties.AvailableMetadata[0];
/// <summary>
/// All the files that have been selected
/// </summary>
private List<TagInfoContainer> files = new List<TagInfoContainer>();
/// <summary>
/// The position of the file that is being currently edited
/// </summary>
public int fileEditPosition = 0;
/// <summary>
/// If the File System API is supported by the browser
/// </summary>
private bool fileSystemAvailable = false;
/// <summary>
/// A list of the Blob URLs that can be re-downloaded
/// </summary>
private List<DownloadResult> redownloadFiles = new List<DownloadResult>();
/// <summary>
/// The URL of the link to download the currently-selected file (in the "Redownload files" tab)
/// </summary>
private string selectedFileDownload = "";
/// <summary>
/// The Dictionary used in the FluentMenuButton to access custom dialogs in the "Single metadata" view
/// </summary>
private Dictionary<string, string> advancedMetadataSettings = new(){
{"0", "Change album art"},
{"1", "Add custom metadata & advanced metadata view"},
{"2", "Fetch lyrics online, or add them from a local file"},
{"3", "Play the current audio/video file"}
};
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender) // Get the selected theme, and apply it
{
fileSystemAvailable = await JS.InvokeAsync<bool>("getFileSystemAvailability");
showGrid = await JS.InvokeAsync<bool>("getGridUI");
await JS.InvokeVoidAsync("updateColor", [await JS.InvokeAsync<string>("getColor")]);
await JS.InvokeVoidAsync("updateSlider", [(await JS.InvokeAsync<double>("getSliderValue")).ToString()]);
}
}
/// <summary>
/// The callback used by the Lyrics dialog to download the zip file with synced, unsynced lyrics and the LRCLIB's JSON response.
/// </summary>
private async void DownloadLrcZipFile(byte[] bytes) {
string?[] result = await DownloadFile(bytes, $"LRCContent-{DateTime.Now.ToString().Replace("/", "-")}.zip");
if (result != null) {
ToastService.ClearProgressToasts();
ToastService.ShowProgress("Downloaded lyrics zip file", 3000);
}
}
/// <summary>
/// If true, the currently-edited value is not a track-specific value (ex: track title, track position etc.), and can be applied to all the albums.
/// </summary>
private bool EnsureNotCommonValue(AvailableProperties.PropertiesObject item) {
return item.TagLibProperty != "Track" && item.TagLibProperty != "Composers" && item.TagLibProperty != "Performers" && item.TagLibProperty != "Comment" && item.TagLibProperty != "ComposersSort" && item.TagLibProperty != "Conductor" && item.TagLibProperty != "Description" && item.TagLibProperty != "Lyrics" && item.TagLibProperty != "Title" && item.TagLibProperty != "PerformersSort";
}
/// <summary>
/// Update the tag from the user's input in a FluentTextField
/// <param name="val">The ChangeEventArgs triggered</param>
/// <param name="item">The PropertiesObject to change</param>
/// <param name="selectedFile">The TagInfoContainer of the file that needs to be edited</param>
/// </summary>
private void UpdateValueFromEvent(ChangeEventArgs val, AvailableProperties.PropertiesObject item, TagInfoContainer
selectedFile)
{
if (IntelligentAlbumUpdate == MultipleUpdateOptions.UPDATE_EVERYTHING) {
TagValueHandler.SetCurrentValue(val.Value == null ? null : val.Value.ToString(), files,
item);
} else if (selectedFile.tag.Tag.Album != null && selectedFile.tag.Tag.Album.Trim() != "" && (IntelligentAlbumUpdate == MultipleUpdateOptions.UPDATE_ALBUM || (IntelligentAlbumUpdate == MultipleUpdateOptions.UPDATE_COMMON_ALBUM && EnsureNotCommonValue(item)))) {
foreach (TagInfoContainer file in files.Where(item => item.tag.Tag.Album == selectedFile.tag.Tag.Album).ToArray()) { // We need to convert the IEnumerable to an Array since otherwise, if the user changed the album name, not all of the objects would be updated with the new album name. By converting it to an array, we iterate over all the items that currently have that album name, even if we change their album value.
if (IntelligentAlbumUpdate == MultipleUpdateOptions.UPDATE_COMMON_ALBUM && item.TagLibProperty == "TrackCount" && file.tag.Tag.DiscCount > 1 && file.tag.Tag.Disc != selectedFile.tag.Tag.Disc && selectedFile.id != file.id) continue; // Since multiple disks have different track count, we should update this property only if they're on the same disk.
if (IntelligentAlbumUpdate == MultipleUpdateOptions.UPDATE_COMMON_ALBUM && item.TagLibProperty == "Disc" && file.tag.Tag.DiscCount > 1 && file.id != selectedFile.id) continue; // Also, the "Disk" property is no longer a common value if there's more than a disk.
TagValueHandler.SetCurrentValue(val.Value == null ? null : val.Value.ToString(), file.tag.Tag, item);
}
} else TagValueHandler.SetCurrentValue(val.Value == null ? null : val.Value.ToString(), selectedFile.tag.Tag,
item);
}
/// <summary>
/// Update the logic used to update multiple files
/// </summary>
private void UpdateMultipleOptions(ChangeEventArgs val) {
if (int.TryParse(val.Value?.ToString(), out int parsed)) {
IntelligentAlbumUpdate = (MultipleUpdateOptions)parsed;
}
}
/// <summary>
/// Update the tag from the user's input in a FluentTextField. The updated file will be the currently-selected one.
/// <param name="val">The ChangeEventArgs triggered</param>
/// <param name="item">The PropertiesObject to change</param>
/// </summary>
private void UpdateValueFromEvent(ChangeEventArgs val, AvailableProperties.PropertiesObject item)
{
UpdateValueFromEvent(val, item, files[fileEditPosition]);
}
/// <summary>
/// Update the tag from the user's input in a FluentTextField. The updated file will be the currently-selected one. The
/// property update will be the selected one.
/// <param name="val">The ChangeEventArgs triggered</param>
/// <param name="item">The PropertiesObject to change</param>
/// </summary>
private void UpdateValueFromEvent(ChangeEventArgs val)
{
UpdateValueFromEvent(val, selectedItem);
}
/// <summary>
/// Read all the files from an FileEvent, and create a new TagLib.Tag
/// </summary>
/// <param name="e">The FileInput event</param>
private async void GetFiles(IEnumerable<FluentInputFileEventArgs> arr)
{
string ToastId = Guid.NewGuid().ToString();
ProgressToastParams toastParams = new ProgressToastParams(){
Title = "Reading files...",
Max = files.Count(),
Progress = 0
};
ToastService.ShowToast<Layout.ProgressToast, ProgressToastParams>(new ToastParameters<ProgressToastParams>()
{
Id = ToastId,
Intent = ToastIntent.Custom,
Timeout = 0,
Icon = (new Icons.Regular.Size20.DocumentAdd(), Color.Accent),
Content = toastParams
});
foreach (var file in arr)
{
try
{
toastParams.Progress++;
toastParams.Title = $"Reading: {file.Name}";
string name = file.LocalFile?.FullName != null ? $"{file.LocalFile.FullName}{file.Name[file.Name.LastIndexOf(".")..]}" : file.Name; // We need to update the file name with its real outut extension (not .tmp), since it's the one that TagLib uses to get the suggested tag
if (file.LocalFile?.FullName != null) file.LocalFile.MoveTo(name);
files.Add(new TagInfoContainer(TagLib.File.Create(name), file.Name, files.Count.ToString()));
await Task.Yield();
}
catch (Exception ex)
{
file.LocalFile?.Delete(); // Not supported file, let's delete it to save memory.
Console.WriteLine(ex);
}
}
ToastService.CloseToast(ToastId);
StateHasChanged(); // Necessary since otherwise the new items wouldn't be shown.
}
/// <summary>
/// Download a file to the user's device
/// </summary>
/// <param name="container">The TagInfoContainer object of the file to download</param>
private async Task SaveItem(TagInfoContainer container)
{
container.tag.Save();
string?[] result = await DownloadFile(await File.ReadAllBytesAsync(container.tag.FileAbstraction.Name), container.file);
// If true, the file will be downloaded using the File System API
ToastService.ClearProgressToasts();
ToastService.ShowProgress((result[2] == "0" ? "Written on the device: " : "Started file downloading: ") +
container.file,
3000);
}
/// <summary>
/// Save everything in a Zip file
/// </summary>
private async Task SaveItemsInZip()
{
string ToastId = Guid.NewGuid().ToString();
ProgressToastParams toastParams = new ProgressToastParams(){
Title = "Creating zip file...",
Max = files.Count(),
Progress = 0
};
ToastService.ShowToast<Layout.ProgressToast, ProgressToastParams>(new ToastParameters<ProgressToastParams>()
{
Id = ToastId,
Intent = ToastIntent.Custom,
Timeout = 0,
Icon = (new Icons.Regular.Size20.FolderZip(), Color.Accent),
Content = toastParams
});
try {
// Note: without the brackets, the zip file would not be readable in macOS.
using (MemoryStream stream = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
foreach (TagInfoContainer file in files)
{
toastParams.Title = $"Added {file.file} in the zip file";
toastParams.Progress++;
toastParams.UpdateState?.Invoke();
file.tag.Save();
ZipArchiveEntry entry = archive.CreateEntryFromFile(file.tag.FileAbstraction.Name, file.file, CompressionLevel.Fastest);
await Task.Delay(25); // Give 25ms to update the UI
await Task.Yield();
}
};
stream.Position = 0;
string?[] result = await DownloadFile(stream.ToArray(), $"EditedMetadata-{DateTime.Now.ToString().Replace("/", "-")}.zip");
if (result != null) {
toastParams.Title = $"The zip file has been {(result[2] == "0" ? "written on the device!" : "downloaded!")}";
toastParams.UpdateState?.Invoke();
} else {
toastParams.Title = "Failed zip file download.";
}
};
} catch (Exception ex) {
Console.WriteLine(ex);
toastParams.Title = $"Failed zip file creation: {(ex.ToString().Length > 150 ? ex.ToString().Substring(0, 150) : ex.ToString())}";
}
await Task.Delay(5000);
ToastService.CloseToast(ToastId);
}
/// <summary>
/// Download a byte array with the suggested file name.
/// </summary>
private async Task<string?[]> DownloadFile(byte[] bytes, string name, bool? useFSApi = false) {
string?[] result = await JS.InvokeAsync<string?[]>("downloadByteArray", [bytes,
name, useFSApi]);
if (result[0] != null) redownloadFiles.Add(new DownloadResult(result[2] == "0", result[0], result[1]));
return result;
}
/// <summary>
/// Save all the tags directly on the user's drive using the File System API
/// </summary>
private async Task SaveItemsFSApi()
{
string ToastId = Guid.NewGuid().ToString();
ProgressToastParams toastParams = new ProgressToastParams(){
Max = files.Count(),
Title = "Starting file download...",
Progress = 0
};
ToastService.ShowToast<Layout.ProgressToast, ProgressToastParams>(new ToastParameters<ProgressToastParams>()
{
Id = ToastId,
Intent = ToastIntent.Custom,
Timeout = 0,
Icon = (new Icons.Regular.Size20.DocumentAdd(), Color.Accent),
Content = toastParams
});
try {
foreach (TagInfoContainer file in files)
{
toastParams.Title = $"Writing {file.file} on the device's folder";
toastParams.Progress++;
toastParams.UpdateState?.Invoke();
file.tag.Save();
string?[] result = await DownloadFile(await File.ReadAllBytesAsync(file.tag.FileAbstraction.Name), file.file, true);
await Task.Delay(25);
await Task.Yield();
}
await JS.InvokeVoidAsync("clearDirectoryHandle");
toastParams.Title = "All the files have been written to the device's folder";
} catch (Exception ex) {
Console.WriteLine(ex);
toastParams.Title = $"Failed file copy: {(ex.ToString().Length > 150 ? ex.ToString().Substring(0, 150) : ex.ToString())}";
}
await Task.Delay(5000);
ToastService.CloseToast(ToastId);
}
/// <summary>
/// Sort a grid in alphabetical order
/// </summary>
/// <param name="container">The PropertiesObject of the property to sort</param>
private GridSort<TagInfoContainer> gridSort(AvailableProperties.PropertiesObject obj)
{
return GridSort<TagInfoContainer>.ByAscending<object>(file => GetParsedValue(obj, file));
}
/// <summary>
/// Get the correct parsed value for sorting (an int if it's a number, otherwise a string)
/// </summary>
/// <param name="obj">The PropertiesObject of the property to sort</param>
/// <param name="file">The TagInfoContainer of the file</param>
private object GetParsedValue(AvailableProperties.PropertiesObject obj, TagInfoContainer file)
{
var temp = TagValueHandler.GetCurrentValue(obj.TagLibProperty, file);
if (int.TryParse(temp, out int result))
{
return result;
}
return temp;
}
/// <summary>
/// The container of each downloaded file
/// </summary>
private class DownloadResult
{
/// <summary>
/// If the file has been downloaded using the File System API.
/// Currently, this class is used only when this is set to false.
/// </summary>
public bool fs = false;
/// <summary>
/// The Blob URL that can be used to download the file
/// </summary>
public string? url = null;
/// <summary>
/// The file name
/// </summary>
public string name = "";
[JsonConstructor]
public DownloadResult(bool fs, string? url, string name)
{
this.fs = fs;
this.url = url;
this.name = name;
}
}
}