返回提交历史
Modified
HaloPixelToolBox/HaloPixelToolBox/Utilities/SpotifyLyricsReader.cs
+51
-71
XFEstudio/HaloPixelToolBox
Update SpotifyLyricsReader.cs
removed debug function leftover from antigravity cli
ded05ba
代码差异
1 个文件
+51
-71
@@ -85,7 +85,6 @@ public class LrclibResponse
85
85
86
86
public class SpotifyLyricsReader
87
87
{
88
private static readonly string LogPath = @"C:\Users\WePro\.gemini\antigravity-cli\spotify_debug.log";
89
88
private static HttpClient? _httpClient;
90
89
private static readonly object HttpLock = new object();
91
90
@@ -123,16 +122,6 @@ public class SpotifyLyricsReader
123
122
public string CurrentTitle => _currentTitle;
124
123
public string CurrentArtist => _currentArtist;
125
124
126
static SpotifyLyricsReader()
127
{
128
try
129
{
130
if (File.Exists(LogPath)) File.Delete(LogPath);
131
File.WriteAllText(LogPath, $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] Log initialized.\n");
132
}
133
catch { }
134
}
135
136
125
private static HttpClient CreateHttpClient()
137
126
{
138
127
var handler = new HttpClientHandler
@@ -166,11 +155,11 @@ public class SpotifyLyricsReader
166
155
167
156
if (proxyConfigured)
168
157
{
169
LogDebug("Auto-configured HttpClient to use local proxy for accelerated connection.");
158
Console.WriteLine("Auto-configured HttpClient to use local proxy for accelerated connection.");
170
159
}
171
160
else
172
161
{
173
LogDebug("No local proxy detected, using direct system default connection.");
162
Console.WriteLine("No local proxy detected, using direct system default connection.");
174
163
}
175
164
176
165
return client;
@@ -191,15 +180,6 @@ public class SpotifyLyricsReader
191
180
return false;
192
181
}
193
182
194
private static void LogDebug(string message)
195
{
196
try
197
{
198
File.AppendAllText(LogPath, $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}\n");
199
}
200
catch { }
201
}
202
203
183
private static async Task<T?> RunWithTimeout<T>(Windows.Foundation.IAsyncOperation<T> asyncOp, int timeoutMs)
204
184
{
205
185
using var cts = new CancellationTokenSource();
@@ -215,19 +195,19 @@ public class SpotifyLyricsReader
215
195
else
216
196
{
217
197
cts.Cancel(); // Cancel the WinRT operation
218
LogDebug("WinRT async operation timed out.");
198
Console.WriteLine("WinRT async operation timed out.");
219
199
}
220
200
}
221
201
catch (Exception ex)
222
202
{
223
LogDebug($"RunWithTimeout failed: {ex.Message}");
203
Console.WriteLine($"RunWithTimeout failed: {ex.Message}");
224
204
}
225
205
return default;
226
206
}
227
207
228
208
public bool Initialize()
229
209
{
230
LogDebug($"Initialize called. isInitialized={_isInitialized}");
210
Console.WriteLine($"Initialize called. isInitialized={_isInitialized}");
231
211
if (_isInitialized)
232
212
{
233
213
UpdateCurrentSession();
@@ -249,14 +229,14 @@ public class SpotifyLyricsReader
249
229
}
250
230
catch (Exception ex)
251
231
{
252
LogDebug($"SpotifyLyricsReader Initialize failed: {ex.Message}");
232
Console.WriteLine($"SpotifyLyricsReader Initialize failed: {ex.Message}");
253
233
return false;
254
234
}
255
235
}
256
236
257
237
private void OnSessionsChanged(GlobalSystemMediaTransportControlsSessionManager sender, SessionsChangedEventArgs args)
258
238
{
259
LogDebug("OnSessionsChanged event fired.");
239
Console.WriteLine("OnSessionsChanged event fired.");
260
240
UpdateCurrentSession();
261
241
}
262
242
@@ -277,7 +257,7 @@ public class SpotifyLyricsReader
277
257
278
258
if (spotifySession != _currentSession)
279
259
{
280
LogDebug($"Active session changed. Old: {_currentSession?.SourceAppUserModelId ?? "null"}, New: {spotifySession?.SourceAppUserModelId ?? "null"}");
260
Console.WriteLine($"Active session changed. Old: {_currentSession?.SourceAppUserModelId ?? "null"}, New: {spotifySession?.SourceAppUserModelId ?? "null"}");
281
261
if (_currentSession != null)
282
262
{
283
263
_currentSession.MediaPropertiesChanged -= OnMediaPropertiesChanged;
@@ -299,19 +279,19 @@ public class SpotifyLyricsReader
299
279
300
280
private void OnMediaPropertiesChanged(GlobalSystemMediaTransportControlsSession sender, MediaPropertiesChangedEventArgs args)
301
281
{
302
LogDebug("OnMediaPropertiesChanged event fired.");
282
Console.WriteLine("OnMediaPropertiesChanged event fired.");
303
283
_ = SyncWithSmtcAsync();
304
284
}
305
285
306
286
private void OnPlaybackInfoChanged(GlobalSystemMediaTransportControlsSession sender, PlaybackInfoChangedEventArgs args)
307
287
{
308
LogDebug("OnPlaybackInfoChanged event fired.");
288
Console.WriteLine("OnPlaybackInfoChanged event fired.");
309
289
_ = SyncWithSmtcAsync();
310
290
}
311
291
312
292
private void OnTimelinePropertiesChanged(GlobalSystemMediaTransportControlsSession sender, TimelinePropertiesChangedEventArgs args)
313
293
{
314
LogDebug("OnTimelinePropertiesChanged event fired.");
294
Console.WriteLine("OnTimelinePropertiesChanged event fired.");
315
295
_ = SyncWithSmtcAsync();
316
296
}
317
297
@@ -331,23 +311,23 @@ public class SpotifyLyricsReader
331
311
var timeline = _currentSession.GetTimelineProperties();
332
312
_currentDuration = timeline?.EndTime.TotalSeconds ?? 0;
333
313
_isSmtcSynced = true;
334
LogDebug($"SMTC Sync Achieved for: {_currentArtist} - {_currentTitle} (Duration: {_currentDuration}s)");
314
Console.WriteLine($"SMTC Sync Achieved for: {_currentArtist} - {_currentTitle} (Duration: {_currentDuration}s)");
335
315
}
336
316
else
337
317
{
338
LogDebug($"SMTC song mismatch. SMTC Title: {media.Title}, Current Title: {_currentTitle}");
318
Console.WriteLine($"SMTC song mismatch. SMTC Title: {media.Title}, Current Title: {_currentTitle}");
339
319
}
340
320
}
341
321
}
342
322
catch (Exception ex)
343
323
{
344
LogDebug($"SyncWithSmtcAsync failed: {ex.Message}");
324
Console.WriteLine($"SyncWithSmtcAsync failed: {ex.Message}");
345
325
}
346
326
}
347
327
348
328
private void StartWindowTitlePolling()
349
329
{
350
LogDebug("Starting window title polling loop.");
330
Console.WriteLine("Starting window title polling loop.");
351
331
Task.Run(async () =>
352
332
{
353
333
while (true)
@@ -360,7 +340,7 @@ public class SpotifyLyricsReader
360
340
{
361
341
if (trackInfo.Artist != _currentArtist || trackInfo.Title != _currentTitle)
362
342
{
363
LogDebug($"Track change detected via polling: {trackInfo.Artist} - {trackInfo.Title}");
343
Console.WriteLine($"Track change detected via polling: {trackInfo.Artist} - {trackInfo.Title}");
364
344
_ = HandleTrackChangeAsync(trackInfo.Artist, trackInfo.Title);
365
345
}
366
346
}
@@ -368,7 +348,7 @@ public class SpotifyLyricsReader
368
348
{
369
349
if (!string.IsNullOrEmpty(_currentTitle))
370
350
{
371
LogDebug("No active track detected, clearing lyrics.");
351
Console.WriteLine("No active track detected, clearing lyrics.");
372
352
_currentTitle = string.Empty;
373
353
_currentArtist = string.Empty;
374
354
_lyricLines.Clear();
@@ -377,7 +357,7 @@ public class SpotifyLyricsReader
377
357
}
378
358
catch (Exception ex)
379
359
{
380
LogDebug($"Track polling loop error: {ex.Message}");
360
Console.WriteLine($"Track polling loop error: {ex.Message}");
381
361
}
382
362
await Task.Delay(250);
383
363
}
@@ -445,7 +425,7 @@ public class SpotifyLyricsReader
445
425
446
426
private async Task HandleTrackChangeAsync(string artist, string track)
447
427
{
448
LogDebug($"HandleTrackChangeAsync started. Target: {artist} - {track}");
428
Console.WriteLine($"HandleTrackChangeAsync started. Target: {artist} - {track}");
449
429
_cts?.Cancel();
450
430
_cts = new CancellationTokenSource();
451
431
var token = _cts.Token;
@@ -462,7 +442,7 @@ public class SpotifyLyricsReader
462
442
// Await SMTC synchronization to get the duration before requesting lyrics
463
443
await SyncWithSmtcAsync();
464
444
465
LogDebug($"Fetching lyrics for: {_currentArtist} - {_currentTitle} (Duration: {_currentDuration}s)");
445
Console.WriteLine($"Fetching lyrics for: {_currentArtist} - {_currentTitle} (Duration: {_currentDuration}s)");
466
446
467
447
// 1. Check local cache first
468
448
string lyricsCacheDir = Path.Combine(AppPathHelper.AppCache, "Lyrics");
@@ -480,13 +460,13 @@ public class SpotifyLyricsReader
480
460
if (!string.IsNullOrEmpty(cachedLrc))
481
461
{
482
462
_lyricLines = LrcParser.Parse(cachedLrc);
483
LogDebug($"Loaded lyrics from local cache file: '{cacheFilePath}'");
463
Console.WriteLine($"Loaded lyrics from local cache file: '{cacheFilePath}'");
484
464
return;
485
465
}
486
466
}
487
467
catch (Exception ex)
488
468
{
489
LogDebug($"Failed to read cached lyrics file: {ex.Message}");
469
Console.WriteLine($"Failed to read cached lyrics file: {ex.Message}");
490
470
}
491
471
}
492
472
@@ -495,42 +475,42 @@ public class SpotifyLyricsReader
495
475
496
476
if (token.IsCancellationRequested)
497
477
{
498
LogDebug($"Lyrics fetch cancelled for: {artist} - {track}");
478
Console.WriteLine($"Lyrics fetch cancelled for: {artist} - {track}");
499
479
return;
500
480
}
501
481
502
482
if (lyricsRes != null && !string.IsNullOrEmpty(lyricsRes.SyncedLyrics))
503
483
{
504
484
_lyricLines = LrcParser.Parse(lyricsRes.SyncedLyrics);
505
LogDebug($"Loaded {_lyricLines.Count} synced lines from LRCLIB.");
485
Console.WriteLine($"Loaded {_lyricLines.Count} synced lines from LRCLIB.");
506
486
507
487
// Save to local cache asynchronously
508
488
try
509
489
{
510
490
await File.WriteAllTextAsync(cacheFilePath, lyricsRes.SyncedLyrics, token);
511
LogDebug($"Saved fetched lyrics to local cache: '{cacheFilePath}'");
491
Console.WriteLine($"Saved fetched lyrics to local cache: '{cacheFilePath}'");
512
492
}
513
493
catch (Exception ex)
514
494
{
515
LogDebug($"Failed to save lyrics to local cache: {ex.Message}");
495
Console.WriteLine($"Failed to save lyrics to local cache: {ex.Message}");
516
496
}
517
497
}
518
498
else if (lyricsRes != null && !string.IsNullOrEmpty(lyricsRes.PlainLyrics))
519
499
{
520
LogDebug("Synced lyrics not found, plain lyrics available.");
500
Console.WriteLine("Synced lyrics not found, plain lyrics available.");
521
501
}
522
502
else
523
503
{
524
LogDebug("No lyrics found.");
504
Console.WriteLine("No lyrics found.");
525
505
}
526
506
}
527
507
catch (OperationCanceledException)
528
508
{
529
LogDebug("Fetch cancelled (OperationCanceledException).");
509
Console.WriteLine("Fetch cancelled (OperationCanceledException).");
530
510
}
531
511
catch (Exception ex)
532
512
{
533
LogDebug($"HandleTrackChangeAsync failed: {ex.Message}");
513
Console.WriteLine($"HandleTrackChangeAsync failed: {ex.Message}");
534
514
}
535
515
}
536
516
@@ -609,7 +589,7 @@ public class SpotifyLyricsReader
609
589
string artistName = result.ArtistName ?? string.Empty;
610
590
611
591
bool match = IsLooseMatch(trackName, artistName, targetTitle, targetArtist);
612
LogDebug($"IsLrcLibMatch: Returned Title: '{trackName}', Artist: '{artistName}' vs Target Title: '{targetTitle}', Artist: '{targetArtist}' => MATCH={match}");
592
Console.WriteLine($"IsLrcLibMatch: Returned Title: '{trackName}', Artist: '{artistName}' vs Target Title: '{targetTitle}', Artist: '{targetArtist}' => MATCH={match}");
613
593
return match;
614
594
}
615
595
@@ -627,7 +607,7 @@ public class SpotifyLyricsReader
627
607
628
608
int durationSeconds = (int)Math.Round(duration);
629
609
string getUrl = $"https://lrclib.net/api/get?track_name={Uri.EscapeDataString(title)}&artist_name={Uri.EscapeDataString(artist)}&duration={durationSeconds}";
630
LogDebug($"LRCLIB /api/get lookup URL: '{getUrl}'");
610
Console.WriteLine($"LRCLIB /api/get lookup URL: '{getUrl}'");
631
611
632
612
try
633
613
{
@@ -637,18 +617,18 @@ public class SpotifyLyricsReader
637
617
var getRes = await getResponse.Content.ReadFromJsonAsync<LrclibResponse>(cancellationToken: getCts.Token);
638
618
if (getRes != null && (!string.IsNullOrEmpty(getRes.SyncedLyrics) || !string.IsNullOrEmpty(getRes.PlainLyrics)))
639
619
{
640
LogDebug("LRCLIB /api/get lyrics retrieved successfully.");
620
Console.WriteLine("LRCLIB /api/get lyrics retrieved successfully.");
641
621
return getRes;
642
622
}
643
623
}
644
624
else
645
625
{
646
LogDebug($"LRCLIB /api/get returned status code: {getResponse.StatusCode}");
626
Console.WriteLine($"LRCLIB /api/get returned status code: {getResponse.StatusCode}");
647
627
}
648
628
}
649
629
catch (Exception ex)
650
630
{
651
LogDebug($"LRCLIB /api/get failed: {ex.Message}");
631
Console.WriteLine($"LRCLIB /api/get failed: {ex.Message}");
652
632
}
653
633
}
654
634
@@ -660,7 +640,7 @@ public class SpotifyLyricsReader
660
640
cachedCts.CancelAfter(TimeSpan.FromSeconds(15));
661
641
662
642
string cachedUrl = $"https://lrclib.net/api/get-cached?track_name={Uri.EscapeDataString(title)}&artist_name={Uri.EscapeDataString(artist)}";
663
LogDebug($"LRCLIB cached lookup URL: '{cachedUrl}'");
643
Console.WriteLine($"LRCLIB cached lookup URL: '{cachedUrl}'");
664
644
665
645
try
666
646
{
@@ -670,18 +650,18 @@ public class SpotifyLyricsReader
670
650
var cachedRes = await response.Content.ReadFromJsonAsync<LrclibResponse>(cancellationToken: cachedCts.Token);
671
651
if (cachedRes != null && (!string.IsNullOrEmpty(cachedRes.SyncedLyrics) || !string.IsNullOrEmpty(cachedRes.PlainLyrics)))
672
652
{
673
LogDebug("LRCLIB cached lyrics retrieved successfully.");
653
Console.WriteLine("LRCLIB cached lyrics retrieved successfully.");
674
654
return cachedRes;
675
655
}
676
656
}
677
657
else
678
658
{
679
LogDebug($"LRCLIB cached API returned status code: {response.StatusCode}");
659
Console.WriteLine($"LRCLIB cached API returned status code: {response.StatusCode}");
680
660
}
681
661
}
682
662
catch (Exception ex)
683
663
{
684
LogDebug($"LRCLIB cached API failed: {ex.Message}");
664
Console.WriteLine($"LRCLIB cached API failed: {ex.Message}");
685
665
}
686
666
}
687
667
@@ -693,7 +673,7 @@ public class SpotifyLyricsReader
693
673
searchCts.CancelAfter(TimeSpan.FromSeconds(15));
694
674
695
675
string searchUrl = $"https://lrclib.net/api/search?track_name={Uri.EscapeDataString(title)}&artist_name={Uri.EscapeDataString(artist)}";
696
LogDebug($"LRCLIB precise search URL: '{searchUrl}'");
676
Console.WriteLine($"LRCLIB precise search URL: '{searchUrl}'");
697
677
698
678
try
699
679
{
@@ -703,12 +683,12 @@ public class SpotifyLyricsReader
703
683
var searchResults = await searchResponse.Content.ReadFromJsonAsync<List<LrclibResponse>>(cancellationToken: searchCts.Token);
704
684
if (searchResults != null && searchResults.Count > 0)
705
685
{
706
LogDebug($"LRCLIB precise search returned {searchResults.Count} results.");
686
Console.WriteLine($"LRCLIB precise search returned {searchResults.Count} results.");
707
687
foreach (var result in searchResults)
708
688
{
709
689
if (!string.IsNullOrEmpty(result.SyncedLyrics) && IsLrcLibMatch(result, artist, title))
710
690
{
711
LogDebug("LRCLIB matched precise search result.");
691
Console.WriteLine("LRCLIB matched precise search result.");
712
692
return result;
713
693
}
714
694
}
@@ -716,12 +696,12 @@ public class SpotifyLyricsReader
716
696
}
717
697
else
718
698
{
719
LogDebug($"LRCLIB precise search returned status code: {searchResponse.StatusCode}");
699
Console.WriteLine($"LRCLIB precise search returned status code: {searchResponse.StatusCode}");
720
700
}
721
701
}
722
702
catch (Exception ex)
723
703
{
724
LogDebug($"LRCLIB precise search failed: {ex.Message}");
704
Console.WriteLine($"LRCLIB precise search failed: {ex.Message}");
725
705
}
726
706
}
727
707
@@ -748,7 +728,7 @@ public class SpotifyLyricsReader
748
728
fallbackCts.CancelAfter(TimeSpan.FromSeconds(15));
749
729
750
730
string fallbackUrl = $"https://lrclib.net/api/search?track_name={Uri.EscapeDataString(cleanTitle)}&artist_name={Uri.EscapeDataString(cleanArtist)}";
751
LogDebug($"LRCLIB clean fallback search URL: '{fallbackUrl}'");
731
Console.WriteLine($"LRCLIB clean fallback search URL: '{fallbackUrl}'");
752
732
753
733
try
754
734
{
@@ -758,12 +738,12 @@ public class SpotifyLyricsReader
758
738
var fallbackResults = await fallbackResponse.Content.ReadFromJsonAsync<List<LrclibResponse>>(cancellationToken: fallbackCts.Token);
759
739
if (fallbackResults != null && fallbackResults.Count > 0)
760
740
{
761
LogDebug($"LRCLIB fallback search returned {fallbackResults.Count} results.");
741
Console.WriteLine($"LRCLIB fallback search returned {fallbackResults.Count} results.");
762
742
foreach (var result in fallbackResults)
763
743
{
764
744
if (!string.IsNullOrEmpty(result.SyncedLyrics) && IsLrcLibMatch(result, artist, title))
765
745
{
766
LogDebug("LRCLIB matched clean fallback search result.");
746
Console.WriteLine("LRCLIB matched clean fallback search result.");
767
747
return result;
768
748
}
769
749
}
@@ -771,18 +751,18 @@ public class SpotifyLyricsReader
771
751
}
772
752
else
773
753
{
774
LogDebug($"LRCLIB fallback search returned status code: {fallbackResponse.StatusCode}");
754
Console.WriteLine($"LRCLIB fallback search returned status code: {fallbackResponse.StatusCode}");
775
755
}
776
756
}
777
757
catch (Exception ex)
778
758
{
779
LogDebug($"LRCLIB fallback search failed: {ex.Message}");
759
Console.WriteLine($"LRCLIB fallback search failed: {ex.Message}");
780
760
}
781
761
}
782
762
}
783
763
catch (Exception ex)
784
764
{
785
LogDebug($"LRCLIB lyric fetch outer error: {ex.Message}");
765
Console.WriteLine($"LRCLIB lyric fetch outer error: {ex.Message}");
786
766
}
787
767
788
768
return null;
@@ -828,7 +808,7 @@ public class SpotifyLyricsReader
828
808
}
829
809
catch (Exception ex)
830
810
{
831
LogDebug($"TryReadLyrics SMTC position error: {ex.Message}");
811
Console.WriteLine($"TryReadLyrics SMTC position error: {ex.Message}");
832
812
}
833
813
}
834
814