-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainViewModel.cs
More file actions
738 lines (662 loc) · 30.1 KB
/
Copy pathMainViewModel.cs
File metadata and controls
738 lines (662 loc) · 30.1 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
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Windows;
using System.Windows.Threading;
using DeadDailyDose.Models;
namespace DeadDailyDose;
/// <summary>Playlist repeat behavior.</summary>
public enum RepeatMode
{
None,
RepeatAll,
RepeatOne
}
/// <summary>
/// ViewModel for the main window: show-of-the-day selection, setlist, tracks, and playback state.
/// </summary>
public class MainViewModel : INotifyPropertyChanged
{
private static readonly HttpClient IaClient = new() { Timeout = TimeSpan.FromSeconds(30) };
/// <summary>Available artists for the daily dose (Grateful Dead, JGB, Dead & Company).</summary>
public static IReadOnlyList<Artist> Artists { get; } = new List<Artist>
{
new() { Name = "Grateful Dead", Collection = "GratefulDead", Mbid = "6faa7ca7-0d99-4a5e-bfa6-1fd5037520c6" },
new() { Name = "Jerry Garcia Band", Collection = "JerryGarcia", Mbid = "6b5c16a5-9a3b-40e0-9fdb-789ab5a30f5a", CollectionFilterKeyword = "jgb" },
new() { Name = "Dead & Company", Collection = "DeadAndCompany", Mbid = "94f8947c-2d9c-4519-bcf9-6d11a24ad006" }
};
private static HttpClient CreateSetlistClient()
{
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
client.DefaultRequestHeaders.Add("Accept", "application/json");
var key = AppSettings.SetlistFmApiKey;
if (!string.IsNullOrWhiteSpace(key))
client.DefaultRequestHeaders.Add("x-api-key", key);
return client;
}
private Show? _currentShow;
private Artist? _artistForCurrentShow;
private Artist? _selectedArtist;
private bool _randomizeArtistOnRefresh;
private string _setlistText = string.Empty;
private string _status = "Ready.";
private bool _isLoading;
private bool _isPlaying;
private int _selectedTrackIndex = -1;
private double _positionSeconds;
private double _durationSeconds;
private string _playPauseButtonText = "Play";
private string _manualDateInput = string.Empty;
private string _showOfTheDayLabel = "Show of the Day: —";
private bool _suppressArtistChangeLoad;
/// <summary>Current show from Internet Archive.</summary>
public Show? CurrentShow
{
get => _currentShow;
set { _currentShow = value; OnPropertyChanged(); UpdateShowLabel(); }
}
/// <summary>Artist used for the currently loaded show (for label and setlist).</summary>
private Artist? ArtistForCurrentShow
{
get => _artistForCurrentShow;
set { _artistForCurrentShow = value; OnPropertyChanged(); UpdateShowLabel(); }
}
/// <summary>Currently selected artist in the ComboBox; changing this loads shows for that artist.</summary>
public Artist? SelectedArtist
{
get => _selectedArtist;
set
{
if (_selectedArtist == value) return;
_selectedArtist = value;
OnPropertyChanged();
if (!_suppressArtistChangeLoad && value != null)
_ = LoadShowAsync(null);
}
}
/// <summary>When true, refresh picks a random artist before loading.</summary>
public bool RandomizeArtistOnRefresh
{
get => _randomizeArtistOnRefresh;
set { _randomizeArtistOnRefresh = value; OnPropertyChanged(); }
}
/// <summary>Formatted setlist text for display (sets and songs).</summary>
public string SetlistText
{
get => _setlistText;
set { _setlistText = value; OnPropertyChanged(); }
}
/// <summary>Status line (e.g. "Playing: Bertha - 01:23 / 05:45").</summary>
public string Status
{
get => _status;
set { _status = value; OnPropertyChanged(); }
}
/// <summary>True while API calls are in progress.</summary>
public bool IsLoading
{
get => _isLoading;
set { _isLoading = value; OnPropertyChanged(); }
}
/// <summary>True when media is playing.</summary>
public bool IsPlaying
{
get => _isPlaying;
set { _isPlaying = value; PlayPauseButtonText = value ? "Pause" : "Play"; OnPropertyChanged(); }
}
/// <summary>Index of the selected/current track in Tracks.</summary>
public int SelectedTrackIndex
{
get => _selectedTrackIndex;
set { _selectedTrackIndex = value; OnPropertyChanged(); }
}
/// <summary>Current playback position in seconds (for seek slider).</summary>
public double PositionSeconds
{
get => _positionSeconds;
set { _positionSeconds = value; OnPropertyChanged(); }
}
/// <summary>Total duration of current track in seconds.</summary>
public double DurationSeconds
{
get => _durationSeconds;
set { _durationSeconds = value; OnPropertyChanged(); }
}
/// <summary>Play/Pause button content.</summary>
public string PlayPauseButtonText
{
get => _playPauseButtonText;
set { _playPauseButtonText = value; OnPropertyChanged(); }
}
/// <summary>Manual date input (MM-DD or MM-DD-YY) for "search by date" feature.</summary>
public string ManualDateInput
{
get => _manualDateInput;
set { _manualDateInput = value; OnPropertyChanged(); }
}
/// <summary>Label for show of the day (e.g. "Show of the Day: 1977-05-08 - Barton Hall").</summary>
public string ShowOfTheDayLabel
{
get => _showOfTheDayLabel;
set { _showOfTheDayLabel = value; OnPropertyChanged(); }
}
/// <summary>True when setlist.fm API key is set; setlist UI is visible only then.</summary>
public bool IsSetlistVisible
{
get => _isSetlistVisible;
set { _isSetlistVisible = value; OnPropertyChanged(); }
}
private bool _isSetlistVisible;
private RepeatMode _repeatMode = RepeatMode.None;
/// <summary>Repeat mode: None (stop at end), RepeatAll, or RepeatOne.</summary>
public RepeatMode RepeatMode
{
get => _repeatMode;
set { _repeatMode = value; OnPropertyChanged(); }
}
/// <summary>All repeat modes for the repeat dropdown.</summary>
public RepeatMode[] RepeatModeOptions => (RepeatMode[])Enum.GetValues(typeof(RepeatMode));
/// <summary>List of artists for the ComboBox (same as static Artists).</summary>
public IReadOnlyList<Artist> ArtistsList => Artists;
/// <summary>List of tracks for the current show (bound to ListBox).</summary>
public ObservableCollection<Track> Tracks { get; } = new();
/// <summary>Refresh show (re-run selection and setlist).</summary>
public RelayCommand RefreshCommand { get; }
/// <summary>Open dialog to set setlist.fm API key.</summary>
public RelayCommand SetApiKeyCommand { get; }
/// <summary>Toggle play/pause (view syncs MediaElement).</summary>
public RelayCommand PlayPauseCommand { get; }
/// <summary>Stop playback.</summary>
public RelayCommand StopCommand { get; }
/// <summary>Select and play next track.</summary>
public RelayCommand NextTrackCommand { get; }
/// <summary>Select and play previous track.</summary>
public RelayCommand PreviousTrackCommand { get; }
/// <summary>Search by manual MM-DD and load that show.</summary>
public RelayCommand SearchByDateCommand { get; }
public MainViewModel()
{
_suppressArtistChangeLoad = true;
try
{
var defaultArtist = Artists.First(a => a.Name == "Grateful Dead");
var savedName = AppSettings.LastArtistName;
_selectedArtist = string.IsNullOrEmpty(savedName)
? defaultArtist
: Artists.FirstOrDefault(a => a.Name == savedName) ?? defaultArtist;
}
finally
{
_suppressArtistChangeLoad = false;
}
RefreshCommand = new RelayCommand(_ => _ = LoadShowAsync(null));
SetApiKeyCommand = new RelayCommand(_ => RequestSetApiKey?.Invoke());
PlayPauseCommand = new RelayCommand(_ => IsPlaying = !IsPlaying);
StopCommand = new RelayCommand(_ => RequestStop?.Invoke());
NextTrackCommand = new RelayCommand(_ => RequestNextTrack?.Invoke());
PreviousTrackCommand = new RelayCommand(_ => RequestPreviousTrack?.Invoke());
SearchByDateCommand = new RelayCommand(_ =>
{
var mmdd = (ManualDateInput ?? "").Trim();
if (mmdd.Length > 0) _ = LoadShowAsync(mmdd);
}, _ => !string.IsNullOrWhiteSpace(ManualDateInput));
}
/// <summary>Raised when the view should open the API key dialog.</summary>
public event Action? RequestSetApiKey;
/// <summary>Raised when the view should stop playback.</summary>
public event Action? RequestStop;
/// <summary>Raised when the view should play next track.</summary>
public event Action? RequestNextTrack;
/// <summary>Raised when the view should play previous track.</summary>
public event Action? RequestPreviousTrack;
/// <summary>Raised when a new track should be played (identifier + track index).</summary>
public event Action<Track>? RequestPlayTrack;
private void UpdateShowLabel()
{
var artistName = ArtistForCurrentShow?.Name ?? "Show";
if (CurrentShow == null)
ShowOfTheDayLabel = $"{artistName}: —";
else
ShowOfTheDayLabel = (CurrentShow.IsRandom ? $"{artistName} Random Show: " : $"{artistName} Show of the Day: ") +
$"{CurrentShow.Date} - {CurrentShow.Title}";
}
/// <summary>
/// Load show of the day (or by manual date), then metadata and setlist.
/// </summary>
/// <param name="manualMmDd">Optional date override: MM-DD (e.g. "02-20") or MM-DD-YY / MM/DD/YY (e.g. "08-27-72"). If null, uses current date.</param>
public async Task LoadShowAsync(string? manualMmDd = null)
{
if (SelectedArtist == null)
{
Status = "Select an artist.";
return;
}
if (RandomizeArtistOnRefresh)
{
_suppressArtistChangeLoad = true;
try
{
_selectedArtist = Artists[Random.Shared.Next(Artists.Count)];
OnPropertyChanged(nameof(SelectedArtist));
}
finally
{
_suppressArtistChangeLoad = false;
}
}
var artist = SelectedArtist;
IsLoading = true;
SetlistText = string.Empty;
RunOnUi(() => { Tracks.Clear(); SelectedTrackIndex = -1; });
Status = "Loading…";
try
{
var mmdd = manualMmDd ?? DateTime.Now.ToString("MM-dd");
var show = await SelectShowAsync(artist, mmdd).ConfigureAwait(true);
if (show == null)
{
// No show for this artist today and random fallback returned nothing — try a random artist.
var originalArtistName = artist.Name;
var otherArtists = Artists.Where(a => a != artist).ToList();
if (otherArtists.Count > 0)
{
var randomArtist = otherArtists[Random.Shared.Next(otherArtists.Count)];
show = await SelectShowAsync(randomArtist, mmdd).ConfigureAwait(true);
if (show != null)
{
_suppressArtistChangeLoad = true;
try
{
_selectedArtist = randomArtist;
OnPropertyChanged(nameof(SelectedArtist));
}
finally { _suppressArtistChangeLoad = false; }
artist = randomArtist;
Status = $"No {originalArtistName} show on this date; loaded random {randomArtist.Name} show. Press Play.";
}
}
if (show == null)
{
Status = $"No shows found for {artist.Name}.";
CurrentShow = null;
ArtistForCurrentShow = null;
RequestStop?.Invoke();
return;
}
}
CurrentShow = show;
ArtistForCurrentShow = artist;
AppSettings.LastShowIdentifier = show.Identifier;
AppSettings.LastArtistName = artist.Name;
await LoadTracksAsync(show).ConfigureAwait(true);
var hasSetlistKey = !string.IsNullOrWhiteSpace(AppSettings.SetlistFmApiKey);
IsSetlistVisible = hasSetlistKey;
if (hasSetlistKey)
await LoadSetlistAsync(show, artist).ConfigureAwait(true);
if (Tracks.Count == 0)
Status = "No playable tracks found.";
else
{
SelectedTrackIndex = 0;
Status = show.IsRandom ? $"No {artist.Name} show on this date; loaded random. Press Play." : "Ready. Press Play.";
}
}
catch (HttpRequestException ex)
{
Status = "Network error.";
System.Windows.MessageBox.Show($"Error: {ex.Message}", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
}
catch (JsonException ex)
{
Status = "Data error.";
System.Windows.MessageBox.Show($"Error: {ex.Message}", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
}
catch (Exception ex)
{
Status = "Error.";
System.Windows.MessageBox.Show($"Error: {ex.Message}", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
}
finally
{
IsLoading = false;
}
}
/// <summary>Select a show: first by date match for the artist's collection, then fallback to random.</summary>
private async Task<Show?> SelectShowAsync(Artist artist, string dateInput)
{
var collection = artist.Collection;
// Normalize separator and detect if a 2-digit year was provided (MM-DD-YY or MM/DD/YY)
var normalized = dateInput.Replace('/', '-');
var parts = normalized.Split('-');
var hasYear = parts.Length == 3;
string mmdd;
string? fullDate = null;
string? yyStr = null;
if (hasYear && int.TryParse(parts[2], out var yy))
{
var mm = parts[0];
var dd = parts[1];
// Century pivot: 70-99 → 1970-1999, 00-69 → 2000-2069 (inputs are always zero-padded 2-digit)
var year = yy >= 70 ? 1900 + yy : 2000 + yy;
mmdd = $"{mm}-{dd}";
fullDate = $"{year:D4}-{mm}-{dd}";
yyStr = parts[2];
}
else
{
mmdd = normalized;
}
List<ShowDoc> list;
if (hasYear && fullDate != null)
{
// Try 1: exact date field (date:YYYY-MM-DD)
list = await SearchShowsAsync(artist, $"collection:{collection}+AND+date:{fullDate}", 50).ConfigureAwait(false);
if (list.Count == 0)
{
// Try 2: identifier contains full 4-digit-year date (e.g. *1972-08-27*)
var fullDateEsc = Uri.EscapeDataString(fullDate);
list = await SearchShowsAsync(artist, $"collection:{collection}+AND+identifier:*{fullDateEsc}*", 100).ConfigureAwait(false);
}
if (list.Count == 0 && yyStr != null)
{
// Try 3: identifier contains 2-digit-year date (e.g. *72-08-27*)
var shortDateEsc = Uri.EscapeDataString($"{yyStr}-{mmdd}");
list = await SearchShowsAsync(artist, $"collection:{collection}+AND+identifier:*{shortDateEsc}*", 100).ConfigureAwait(false);
}
// Try 4: for JGB etc., search by identifier keyword + full date across archive
if (list.Count == 0 && !string.IsNullOrEmpty(artist.CollectionFilterKeyword))
{
var keyword = Uri.EscapeDataString(artist.CollectionFilterKeyword);
var fullDateEsc = Uri.EscapeDataString(fullDate);
list = await SearchShowsAsync(artist, $"identifier:*{fullDateEsc}*+AND+identifier:*{keyword}*", 100).ConfigureAwait(false);
}
}
else
{
// Try 1: date field (e.g. date:*-02-20). IA may index as YYYY-MM-DD; wildcard can be unreliable.
list = await SearchShowsAsync(artist, $"collection:{collection}+AND+date:*-{mmdd}", 50).ConfigureAwait(false);
if (list.Count == 0)
{
// Try 2: identifier often contains the date (e.g. gd1982-02-20.xxx, jg87-02-20.jgb...). Search for month-day in identifier.
var mmddInId = Uri.EscapeDataString(mmdd);
list = await SearchShowsAsync(artist, $"collection:{collection}+AND+identifier:*{mmddInId}*", 100).ConfigureAwait(false);
}
// Try 3: for JGB etc., some shows live in other collections (e.g. Taper's Section). Search by identifier containing date + artist keyword.
if (list.Count == 0 && !string.IsNullOrEmpty(artist.CollectionFilterKeyword))
{
var keyword = Uri.EscapeDataString(artist.CollectionFilterKeyword);
var mmddEsc = Uri.EscapeDataString(mmdd);
list = await SearchShowsAsync(artist, $"identifier:*{mmddEsc}*+AND+identifier:*{keyword}*", 100).ConfigureAwait(false);
}
}
if (list.Count > 0)
{
list.Sort((a, b) => string.CompareOrdinal(b.Date, a.Date));
var first = list[0];
return new Show
{
Identifier = first.Identifier,
Title = first.Title,
Date = first.Date,
IsRandom = false
};
}
// Fallback: random show from collection (retry with more rows if first attempt returns no docs)
for (var rows = 1000; rows <= 5000; rows += 2000)
{
var showResult = await TryRandomShowFromCollectionAsync(artist, collection, rows).ConfigureAwait(false);
if (showResult != null) return showResult;
}
// For JGB etc., collection may not hold all shows — try random by identifier keyword across archive.
if (!string.IsNullOrEmpty(artist.CollectionFilterKeyword))
{
var showResult = await TryRandomShowByIdentifierKeywordAsync(artist, artist.CollectionFilterKeyword).ConfigureAwait(false);
if (showResult != null) return showResult;
}
return null;
}
private async Task<Show?> TryRandomShowByIdentifierKeywordAsync(Artist artist, string keyword)
{
var keywordEsc = Uri.EscapeDataString(keyword);
var url = $"https://archive.org/advancedsearch.php?q=identifier:*{keywordEsc}*&fl[]=identifier&fl[]=title&fl[]=date&sort[]=date+desc&rows=500&output=json";
using var response = await IaClient.GetAsync(url).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (!TryGetDocsArray(doc.RootElement, out var docs))
return null;
var list = new List<ShowDoc>();
foreach (var item in docs.EnumerateArray())
list.Add(ShowDoc.FromElement(item));
var filtered = FilterShowsByArtist(list, artist);
if (filtered.Count == 0) return null;
var idx = Random.Shared.Next(filtered.Count);
var d = filtered[idx];
return new Show { Identifier = d.Identifier, Title = d.Title, Date = d.Date, IsRandom = true };
}
private async Task<Show?> TryRandomShowFromCollectionAsync(Artist artist, string collection, int rows)
{
var url = $"https://archive.org/advancedsearch.php?q=collection:{collection}&fl[]=identifier&fl[]=title&fl[]=date&sort[]=date+desc&rows={rows}&output=json";
using var fallback = await IaClient.GetAsync(url).ConfigureAwait(false);
fallback.EnsureSuccessStatusCode();
var json = await fallback.Content.ReadAsStringAsync().ConfigureAwait(false);
using var doc2 = JsonDocument.Parse(json);
if (!TryGetDocsArray(doc2.RootElement, out var docs2))
return null;
var allList = new List<ShowDoc>();
foreach (var item in docs2.EnumerateArray())
allList.Add(ShowDoc.FromElement(item));
var filtered = FilterShowsByArtist(allList, artist);
if (filtered.Count == 0)
return null;
var idx = Random.Shared.Next(filtered.Count);
var doc = filtered[idx];
return new Show
{
Identifier = doc.Identifier,
Title = doc.Title,
Date = doc.Date,
IsRandom = true
};
}
/// <summary>Get the "docs" array from IA advanced search response (case-insensitive for response/docs).</summary>
private static bool TryGetDocsArray(JsonElement root, out JsonElement docs)
{
docs = default;
if (!TryGetChild(root, "response", out var resp)) return false;
return TryGetChild(resp, "docs", out docs);
}
private static bool TryGetChild(JsonElement parent, string name, out JsonElement child)
{
child = default;
foreach (var prop in parent.EnumerateObject())
if (prop.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{ child = prop.Value; return true; }
return false;
}
/// <summary>Run advanced search and return filtered list of show docs (empty if no results or missing structure).</summary>
private async Task<List<ShowDoc>> SearchShowsAsync(Artist artist, string query, int rows)
{
var url = $"https://archive.org/advancedsearch.php?q={query}&fl[]=identifier&fl[]=title&fl[]=date&sort[]=date+desc&rows={rows}&output=json";
using var response = await IaClient.GetAsync(url).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (!TryGetDocsArray(root, out var docs))
return new List<ShowDoc>();
var list = new List<ShowDoc>();
foreach (var item in docs.EnumerateArray())
list.Add(ShowDoc.FromElement(item));
return FilterShowsByArtist(list, artist);
}
/// <summary>Filter docs for Jerry Garcia Solo vs JGB when sharing the same collection.</summary>
private static List<ShowDoc> FilterShowsByArtist(List<ShowDoc> list, Artist artist)
{
if (list.Count == 0) return list;
var includeKeyword = artist.CollectionFilterKeyword;
var excludeKeyword = artist.ExcludeKeyword;
if (string.IsNullOrEmpty(includeKeyword) && string.IsNullOrEmpty(excludeKeyword))
return list;
var result = new List<ShowDoc>();
foreach (var doc in list)
{
var combined = $"{doc.Identifier} {doc.Title}".ToLowerInvariant();
if (!string.IsNullOrEmpty(excludeKeyword) && combined.Contains(excludeKeyword.ToLowerInvariant()))
continue;
if (!string.IsNullOrEmpty(includeKeyword) && !combined.Contains(includeKeyword.ToLowerInvariant()))
continue;
result.Add(doc);
}
return result.Count > 0 ? result : list;
}
/// <summary>DTO for a show search hit; holds copied values so we don't keep references to a disposed JsonDocument.</summary>
private sealed record ShowDoc(string Identifier, string Title, string Date)
{
public static ShowDoc FromElement(JsonElement el)
{
var id = el.TryGetProperty("identifier", out var idVal) ? idVal.GetString() ?? "" : "";
var title = el.TryGetProperty("title", out var tVal) ? tVal.GetString() ?? "" : "";
var date = el.TryGetProperty("date", out var dVal) ? dVal.GetString() ?? "" : "";
return new ShowDoc(id, title, date);
}
}
/// <summary>Fetch show metadata from IA and populate Tracks (VBR MP3, 64Kb MP3, Ogg Vorbis).</summary>
private async Task LoadTracksAsync(Show show)
{
var url = $"https://archive.org/metadata/{show.Identifier}";
using var response = await IaClient.GetAsync(url).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("files", out var files))
return;
var preferred = new[] { "VBR MP3", "64Kb MP3", "Ogg Vorbis" };
var candidates = new List<(string name, string format, string title)>();
foreach (var f in files.EnumerateArray())
{
var format = f.TryGetProperty("format", out var fmt) ? fmt.GetString() ?? "" : "";
if (!preferred.Contains(format)) continue;
var name = f.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
if (string.IsNullOrEmpty(name)) continue;
var title = f.TryGetProperty("title", out var t) ? t.GetString() ?? "" : "";
candidates.Add((name, format, title ?? ""));
}
var mp3First = candidates.OrderBy(c => c.format == "Ogg Vorbis" ? 1 : 0).ThenBy(c => c.name).ToList();
var baseUrl = $"https://archive.org/download/{show.Identifier}/";
var toAdd = mp3First.Select(t => new Track
{
Name = t.name,
Title = t.title,
Url = baseUrl + Uri.EscapeDataString(t.name)
}).ToList();
RunOnUi(() => { foreach (var t in toAdd) Tracks.Add(t); });
}
/// <summary>Run an action on the UI (Dispatcher) thread so ObservableCollection updates are valid.</summary>
private static void RunOnUi(Action action)
{
var d = Application.Current?.Dispatcher;
if (d == null || d.CheckAccess())
action();
else
d.Invoke(action);
}
/// <summary>Fetch setlist from setlist.fm and set SetlistText. Only called when API key is set.</summary>
private async Task LoadSetlistAsync(Show show, Artist artist)
{
if (string.IsNullOrWhiteSpace(AppSettings.SetlistFmApiKey))
return;
var dateStr = show.Date;
if (string.IsNullOrEmpty(dateStr) || dateStr.Length < 10)
{
SetlistText = "No setlist available for this show.";
return;
}
if (dateStr.Length == 10 && dateStr[4] == '-' && dateStr[7] == '-')
{
var parts = dateStr.Split('-');
if (parts.Length == 3)
dateStr = $"{parts[2]}-{parts[1]}-{parts[0]}";
}
using var client = CreateSetlistClient();
var url = $"https://api.setlist.fm/rest/1.0/search/setlists?artistMbid={artist.Mbid}&date={dateStr}";
using var response = await client.GetAsync(url).ConfigureAwait(false);
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
SetlistText = "Setlist.fm API key invalid. Use 'Set API Key' from the menu.";
return;
}
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("setlist", out var setlistArr) || setlistArr.GetArrayLength() == 0)
{
SetlistText = "No setlist available for this show.";
return;
}
var firstSetlist = setlistArr[0];
if (!firstSetlist.TryGetProperty("sets", out var setsObj))
{
SetlistText = "No setlist available for this show.";
return;
}
var sb = new System.Text.StringBuilder();
if (setsObj.TryGetProperty("set", out var setArr))
{
foreach (var setEl in setArr.EnumerateArray())
{
var setName = setEl.TryGetProperty("name", out var sn) ? sn.GetString() ?? "Set" : "Set";
sb.AppendLine();
sb.AppendLine(setName + ":");
if (setEl.TryGetProperty("song", out var songArr))
{
foreach (var song in songArr.EnumerateArray())
{
var songName = song.TryGetProperty("name", out var sname) ? sname.GetString() ?? "" : "";
if (!string.IsNullOrEmpty(songName)) sb.AppendLine("• " + songName);
}
}
}
}
SetlistText = sb.Length > 0 ? sb.ToString().Trim() : "No setlist available for this show.";
}
/// <summary>Called by the view when user selects a track to play.</summary>
public void OnTrackSelected(Track? track)
{
if (track == null) return;
RequestPlayTrack?.Invoke(track);
}
/// <summary>Called by the view when playback position/duration change.</summary>
public void UpdatePlaybackState(double positionSeconds, double durationSeconds, string trackTitle)
{
PositionSeconds = positionSeconds;
DurationSeconds = durationSeconds;
var pos = TimeSpan.FromSeconds(positionSeconds);
var dur = TimeSpan.FromSeconds(durationSeconds);
Status = $"Playing: {trackTitle} - {pos:mm\\:ss} / {dur:mm\\:ss}";
}
/// <summary>Re-fetch setlist for current show (e.g. after user sets API key).</summary>
public async Task RefreshSetlistAsync()
{
if (CurrentShow == null || _artistForCurrentShow == null) return;
IsLoading = true;
try { await LoadSetlistAsync(CurrentShow, _artistForCurrentShow).ConfigureAwait(true); }
finally { IsLoading = false; }
}
/// <summary>Shows the setlist UI (e.g. after user enters API key via menu).</summary>
public void ShowSetlistSection()
{
IsSetlistVisible = !string.IsNullOrWhiteSpace(AppSettings.SetlistFmApiKey);
}
/// <summary>Called when playback is stopped.</summary>
public void OnPlaybackStopped()
{
IsPlaying = false;
Status = "Stopped.";
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}