-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
792 lines (670 loc) · 31 KB
/
MainWindow.xaml.cs
File metadata and controls
792 lines (670 loc) · 31 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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Windows.ApplicationModel.Background;
using Windows.Media.Control;
using Windows.Storage.FileProperties;
using System.Windows.Media;
using Windows.Phone.Notification.Management;
using System.Windows.Media.Animation;
using System.Runtime.InteropServices.ComTypes;
using System.Windows.Media.Effects;
using Windows.Devices.Radios;
using Windows.UI.ViewManagement;
using Windows.Media.Devices;
using System.Diagnostics;
using CoreAudio;
using System.Windows.Controls.Primitives;
using System.Net.Http;
using Newtonsoft.Json;
using System.Reflection.Emit;
using Windows.Web.Syndication;
using System.Net;
using System.ComponentModel;
using System.Threading;
using Wpf.Ui.Controls;
using System.Timers;
using System.Runtime.Remoting.Channels;
using System.Globalization;
using Windows.Foundation.Collections;
using static System.Net.Mime.MediaTypeNames;
using static Now_Playing.Lyrics;
using Windows.UI.Text;
namespace Now_Playing
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private GlobalSystemMediaTransportControlsSession session;
private GlobalSystemMediaTransportControlsSessionManager sessionManager;
private MMDevice device;
private Song currentSong;
public MainWindow()
{
InitializeComponent();
this.Closed += async (object sender, EventArgs e) =>
{
Properties.Settings.Default.Save();
if (Settings.PauseWhenAppClosedEnabled && session != null)
await session.TryPauseAsync();
};
lyricsView.Loaded += (object sender, RoutedEventArgs e) => this.Dispatcher.Invoke(() =>
{
if (Settings.AutoShowLyricsEnabled)
{
if (Settings.LyricsViewViewable && lyrics.Text != "No lyrics available")
lyricsView.Visibility = Visibility.Visible;
else
lyricsView.Visibility = Visibility.Collapsed;
}
else
lyricsView.Visibility = Settings.LyricsViewViewable ? Visibility.Visible : Visibility.Collapsed;
});
this.Dispatcher.Invoke(() => toggleLyricsButton.IsChecked = Settings.LyricsViewViewable);
MakeManager();
MakeAudioManager();
Wpf.Ui.Appearance.SystemThemeWatcher.Watch(this, WindowBackdropType.None, true);
}
private void TimerEnd(object sender, ElapsedEventArgs e)
{
lyricTimer.Stop();
Grid sp = null;
this.Dispatcher.Invoke(() => sp = lyricsGrid.Children[currentLyric] as Grid);
ScrollToLyric(sp);
var alreadyPlayed = currentSong.ParsedLyrics.lyricLines[currentLyric].Timestamp.TotalMilliseconds;
++currentLyric;
var interval = currentSong.ParsedLyrics.lyricLines[currentLyric].Timestamp.TotalMilliseconds - alreadyPlayed;
lyricTimer = new System.Timers.Timer(interval);
lyricTimer.Elapsed += TimerEnd;
lyricTimer.Start();
//var timestamp = TimeSpan.FromMilliseconds(alreadyPlayed);
//string lyricsToDisplay = currentSong.ParsedLyrics.GetTextForTimestamp(timestamp);
//this.Dispatcher.Invoke(() =>
//{
// lyrics.Text = lyricsTint.Text = lyricsToDisplay;
//});
}
private void ScrollToLyric(Grid lyricToScrollTo)
{
var math = (lyricsView.ActualHeight + (lyricToScrollTo.ActualHeight + 10)) / 2;
this.Dispatcher.Invoke(() => lyricToScrollTo.BringIntoView(new Rect(new Point(), new Size(lyricToScrollTo.ActualWidth, math))));
this.Dispatcher.Invoke(() =>
{
foreach (Grid grid in lyricsGrid.Children)
{
var tint = grid.Children[1] as System.Windows.Controls.TextBlock;
if (tint.Opacity != 0.5)
tint.Opacity = 0.5;
}
});
this.Dispatcher.Invoke(() => (lyricToScrollTo.Children[1] as System.Windows.Controls.TextBlock).Opacity = 1);
}
private System.Timers.Timer lyricTimer;
private int currentLyric = 1;
private void SetSongLyrics(Song song)
{
if (song.syncedLyrics != null)
{
try
{
this.Dispatcher.Invoke(() => lyricsGrid.Children.Clear());
Lyrics parsedLyrics = Lyrics.ParseSyncedLyrics(song.syncedLyrics);
song.ParsedLyrics = parsedLyrics;
this.currentSong = song;
foreach (LyricsLine lyricLine in currentSong.ParsedLyrics.lyricLines)
{
if (currentSong.ParsedLyrics.lyricLines[0] != lyricLine)
{
this.Dispatcher.Invoke(() =>
{
var grid = new Grid() { Tag = lyricLine.Timestamp.TotalMilliseconds, Margin = new Thickness(0, 10, 0, 0) };
string text = lyricLine.Text;
if (string.IsNullOrWhiteSpace(text))
text = "loading placeholder";
var textBlock = new System.Windows.Controls.TextBlock() { Text = text, TextWrapping = TextWrapping.Wrap, FontWeight = System.Windows.FontWeights.Bold, FontSize = 40, Foreground = new SolidColorBrush(accentColor) };
var textBlockTint = new System.Windows.Controls.TextBlock() { Text = text, TextWrapping = TextWrapping.Wrap, FontWeight = System.Windows.FontWeights.Bold, FontSize = 40, Foreground = Brushes.White, Opacity = 0.5 };
grid.Children.Add(textBlock);
grid.Children.Add(textBlockTint);
lyricsGrid.Children.Add(grid);
});
}
else
{
this.Dispatcher.Invoke(() =>
{
var grid = new Grid() { Tag = lyricLine.Timestamp.TotalMilliseconds, Height = 0, Margin = new Thickness(0, 0, 0, -10) };
var textBlock = new System.Windows.Controls.TextBlock() { TextWrapping = TextWrapping.Wrap, FontWeight = System.Windows.FontWeights.Bold, FontSize = 40, Foreground = new SolidColorBrush(accentColor) };
var textBlockTint = new System.Windows.Controls.TextBlock() { TextWrapping = TextWrapping.Wrap, FontWeight = System.Windows.FontWeights.Bold, FontSize = 40, Foreground = Brushes.White, Opacity = 0.5 };
grid.Children.Add(textBlock);
grid.Children.Add(textBlockTint);
lyricsGrid.Children.Add(grid);
});
}
}
currentLyric = 1;
lyricTimer = new System.Timers.Timer(currentSong.ParsedLyrics.lyricLines[currentLyric].Timestamp.TotalMilliseconds);
lyricTimer.Start();
lyricTimer.Elapsed += TimerEnd;
//this.Dispatcher.Invoke(() =>
//{
// lyrics.Text = lyricsTint.Text = "";
// if (Settings.AutoShowLyricsEnabled && Settings.LyricsViewViewable)
// lyricsView.Visibility = Visibility.Visible;
//});
}
catch (Exception)
{
this.Dispatcher.Invoke(() =>
{
lyrics.Text = lyricsTint.Text = song.syncedLyrics;
if (Settings.AutoShowLyricsEnabled && Settings.LyricsViewViewable)
lyricsView.Visibility = Visibility.Visible;
});
}
}
else if (song.plainLyrics != null)
{
this.Dispatcher.Invoke(() =>
{
lyrics.Text = lyricsTint.Text = song.plainLyrics;
if (Settings.AutoShowLyricsEnabled && Settings.LyricsViewViewable)
lyricsView.Visibility = Visibility.Visible;
});
}
else
{
this.Dispatcher.Invoke(() =>
{
lyrics.Text = lyricsTint.Text = "No lyrics available";
if (Settings.AutoShowLyricsEnabled)
lyricsView.Visibility = Visibility.Collapsed;
});
}
}
private void MakeAudioManager()
{
MMDeviceEnumerator devEnum = new MMDeviceEnumerator(Guid.NewGuid());
device = devEnum.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
device.AudioEndpointVolume.OnVolumeNotification += (AudioVolumeNotificationData data) => this.Dispatcher.Invoke(() => volume.Value = (int)(data.MasterVolume * 100));
int currentVolume = (int)(device.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
volume.Value = currentVolume;
ToolTipService.SetToolTip(volume, currentVolume);
volume.ValueChanged += (object sender, RoutedPropertyChangedEventArgs<double> e) => ToolTipService.SetToolTip(volume, e.NewValue);
}
private async void MakeManager()
{
sessionManager = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync();
sessionManager.CurrentSessionChanged += CurrentSessionChanged;
MakeSession();
}
private void MakeSession()
{
session = sessionManager.GetCurrentSession();
if (session != null)
{
session.MediaPropertiesChanged += MediaPropertiesChanged;
session.PlaybackInfoChanged += PlaybackInfoChanged;
session.TimelinePropertiesChanged += TimelinePropertiesChanged;
SetNowPlayingDetails();
}
}
private void Window_Close(object sender, RoutedEventArgs e) => this.Close();
private void CurrentSessionChanged(GlobalSystemMediaTransportControlsSessionManager sender, CurrentSessionChangedEventArgs args) => MakeSession();
private void PlaybackInfoChanged(GlobalSystemMediaTransportControlsSession sender, PlaybackInfoChangedEventArgs args) => UpdatePlaybackStatus();
private void MediaPropertiesChanged(GlobalSystemMediaTransportControlsSession sender, MediaPropertiesChangedEventArgs args) => SetNowPlayingDetails();
private void Adjust_Volume(object sender, DragDeltaEventArgs e) => device.AudioEndpointVolume.MasterVolumeLevelScalar = ((float)volume.Value / 100.0f);
private void VolumeUp_Executed(object sender, ExecutedRoutedEventArgs e) => device.AudioEndpointVolume.MasterVolumeLevelScalar = device.AudioEndpointVolume.MasterVolumeLevelScalar + (float)0.01;
private void VolumeDown_Executed(object sender, ExecutedRoutedEventArgs e) => device.AudioEndpointVolume.MasterVolumeLevelScalar = device.AudioEndpointVolume.MasterVolumeLevelScalar - (float)0.01;
private void TimelinePropertiesChanged(GlobalSystemMediaTransportControlsSession sender, TimelinePropertiesChangedEventArgs args)
{
this.Dispatcher.Invoke(() =>
{
var timelineProperties = sender.GetTimelineProperties();
timeline.Maximum = timelineProperties.EndTime.TotalSeconds;
timeline.Minimum = timelineProperties.StartTime.TotalSeconds;
timeline.Value = timelineProperties.Position.TotalSeconds;
//if (currentSong != null && currentSong.ParsedLyrics != null)
//{
// lyrics.Text = currentSong.ParsedLyrics.GetTextForTimestamp(timelineProperties.Position);
// lyricsTint.Text = lyrics.Text;
//}
});
}
Color accentColor = Colors.Black;
private async void SetNowPlayingDetails()
{
UpdatePlaybackStatus();
if (session != null)
{
GlobalSystemMediaTransportControlsSessionMediaProperties mediaProperties = null;
try
{
mediaProperties = await session.TryGetMediaPropertiesAsync();
}
catch (FileNotFoundException)
{
SetNowPlayingDetails();
return;
}
var thumbnail = mediaProperties.Thumbnail;
if (thumbnail != null)
{
var openedThumbnail = await thumbnail.OpenReadAsync();
BitmapFrame albumArtwork = null;
using (var stream = openedThumbnail.AsStream())
{
if (stream != null && stream.Length > 0)
{
stream.Seek(0, SeekOrigin.Current);
//var policy = new System.Net.Cache.RequestCachePolicy();
//BitmapFrame.Create()
albumArtwork = BitmapFrame.Create(stream, BitmapCreateOptions.None, (BitmapCacheOption)Settings.BitmapCacheMode);
accentColor = AverageColor(stream);
this.Dispatcher.Invoke(() =>
{
var backgroundImage = new System.Windows.Controls.Image() { Source = albumArtwork, Effect = new BlurEffect() { Radius = 20 }, Opacity = 0.5 };
var grid = new Grid();
grid.Children.Add(new Rectangle() { Fill = Brushes.Black });
grid.Children.Add(backgroundImage);
this.Background = new VisualBrush(grid) { Stretch = Stretch.UniformToFill };
this.Background.Transform = new ScaleTransform() { ScaleX = 2, ScaleY = 2, CenterX = 200 };
});
}
}
this.Dispatcher.Invoke(() =>
{
imageSource.Source = albumArtwork;
Album.Foreground = Artist.Foreground = title.Foreground = lyrics.Foreground = new SolidColorBrush(accentColor);
if (!string.IsNullOrEmpty(mediaProperties.Title))
{
titleGrid.Visibility = Visibility.Visible;
title.Text = mediaProperties.Title;
titleTint.Text = mediaProperties.Title;
}
else
titleGrid.Visibility = Visibility.Collapsed;
if (!string.IsNullOrEmpty(mediaProperties.AlbumTitle))
{
albumGrid.Visibility = Visibility.Visible;
Album.Text = mediaProperties.AlbumTitle;
albumTint.Text = mediaProperties.AlbumTitle;
}
else
albumGrid.Visibility = Visibility.Collapsed;
if (!string.IsNullOrEmpty(mediaProperties.Artist))
{
artistGrid.Visibility = Visibility.Visible;
Artist.Text = mediaProperties.Artist;
artistTint.Text = mediaProperties.Artist;
}
else if (!string.IsNullOrEmpty(mediaProperties.AlbumArtist))
{
artistGrid.Visibility = Visibility.Visible;
Artist.Text = mediaProperties.AlbumArtist;
artistTint.Text= mediaProperties.AlbumArtist;
}
else
artistGrid.Visibility = Visibility.Collapsed;
});
string artist = string.Empty;
if (!string.IsNullOrEmpty(mediaProperties.Artist))
artist = mediaProperties.Artist;
else if (!string.IsNullOrEmpty(mediaProperties.AlbumArtist))
artist = mediaProperties.AlbumArtist;
double duration = session.GetTimelineProperties().EndTime.TotalSeconds;
var songs = Song.FromSearch(mediaProperties.Title, artist);
if (songs.Count > 0)
SetSongLyrics(songs[0]);
else
{
songs = Song.FromSearch(mediaProperties.Title);
if (songs.Count > 0)
SetSongLyrics(songs[0]);
else
{
this.Dispatcher.Invoke(() =>
{
lyrics.Text = lyricsTint.Text = "No lyrics available";
if (Settings.AutoShowLyricsEnabled)
lyricsView.Visibility = Visibility.Collapsed;
});
}
}
}
}
else
{
this.Dispatcher.Invoke(() =>
{
imageSource.Source = new BitmapImage(new Uri("pack://application:,,,/Now Playing;component/Assets/Placeholder.png"));
this.Background = null;
lyrics.Text = lyricsTint.Text = "No lyrics available";
if (Settings.AutoShowLyricsEnabled)
lyricsView.Visibility = Visibility.Collapsed;
Artist.Text = artistTint.Text = "Artist";
artistGrid.Visibility = Visibility.Collapsed;
title.Text = titleTint.Text = "Title";
titleGrid.Visibility = Visibility.Collapsed;
Album.Text = albumTint.Text = "Album";
albumGrid.Visibility = Visibility.Collapsed;
togglePlayback.Content = new FontIcon() { FontFamily = (FontFamily)this.Resources["SymbolThemeFontFamily"], Glyph = "\uEA3A" };
timeline.Value = 0;
Album.Foreground = Artist.Foreground = title.Foreground = lyrics.Foreground = new SolidColorBrush(Colors.Black);
});
}
}
static Color AverageColor(Stream stream)
{
long threshold;
try
{
threshold = long.Parse(Settings.ImageResolutionThreshold);
}
catch (Exception)
{
threshold = 1000000;
}
if (stream.Length < threshold)
{
using (var bmp = new System.Drawing.Bitmap(stream))
{
int width = bmp.Width;
int height = bmp.Height;
int red = 0;
int green = 0;
int blue = 0;
int alpha = 0;
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
{
var pixel = bmp.GetPixel(x, y);
red += pixel.R;
green += pixel.G;
blue += pixel.B;
alpha += pixel.A;
}
Func<int, int> avg = c => c / (width * height);
red = avg(red);
green = avg(green);
blue = avg(blue);
alpha = avg(alpha);
var color = Color.FromArgb((byte)alpha, (byte)red, (byte)green, (byte)blue);
return color;
}
}
else return Colors.Black;
}
private void UpdatePlaybackStatus()
{
if (session != null)
{
var playbackInfo = session.GetPlaybackInfo().PlaybackStatus;
this.Dispatcher.Invoke(() =>
{
switch (playbackInfo)
{
case GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing:
togglePlayback.Content = new FontIcon() { FontFamily = (FontFamily)this.Resources["SymbolThemeFontFamily"], Glyph = "\uE769" };
if (lyricTimer != null)
lyricTimer.Start();
break;
case GlobalSystemMediaTransportControlsSessionPlaybackStatus.Paused:
togglePlayback.Content = new FontIcon() { FontFamily = (FontFamily)this.Resources["SymbolThemeFontFamily"], Glyph = "\uE768" };
if (lyricTimer != null)
lyricTimer.Stop();
break;
}
});
}
}
private void togglePlayback_Click(object sender, RoutedEventArgs e) => TogglePlayback();
private void PlayPause_Executed(object sender, ExecutedRoutedEventArgs e) => TogglePlayback();
private void forwardtrack_Click(object sender, RoutedEventArgs e) => SkipNext();
private void Next_Executed(object sender, ExecutedRoutedEventArgs e) => SkipNext();
private void backtrack_Click(object sender, RoutedEventArgs e) => SkipPrevious();
private void Previous_Executed(object sender, ExecutedRoutedEventArgs e) => SkipPrevious();
private async void TogglePlayback()
{
if (session != null)
{
await session.TryTogglePlayPauseAsync();
}
}
private async void SkipPrevious()
{
if (session != null)
{
await session.TrySkipPreviousAsync();
}
}
private async void SkipNext()
{
if (session != null)
{
await session.TrySkipNextAsync();
}
}
private async void Adjust_Position(object sender, DragDeltaEventArgs e)
{
if (session != null)
{
await session.TryChangePlaybackPositionAsync((long)(sender as Slider).Value);
}
}
private async void OpenSettings_Executed(object sender, ExecutedRoutedEventArgs e)
{
var contentDialog = new ContentDialog(dialogPresenter);
contentDialog.SetCurrentValue(ContentDialog.TitleProperty, "Settings");
contentDialog.SetCurrentValue(ContentProperty, (StackPanel)this.Resources["SettingsContent"]);
contentDialog.SetCurrentValue(ContentDialog.CloseButtonTextProperty, "Done");
await contentDialog.ShowAsync();
}
private void ToggleLyricsButton_Click(object sender, RoutedEventArgs e)
{
bool valueToSet = (sender as ToggleButton).IsChecked == true;
Settings.LyricsViewViewable = valueToSet;
this.Dispatcher.Invoke(() =>
{
if (Settings.AutoShowLyricsEnabled)
{
if (valueToSet && lyrics.Text != "No lyrics available")
lyricsView.Visibility = Visibility.Visible;
else
lyricsView.Visibility = Visibility.Collapsed;
}
else
lyricsView.Visibility = valueToSet ? Visibility.Visible : Visibility.Collapsed;
});
}
}
public class HttpClientFactory
{
private string webServiceUrl = "https://lrclib.net/api/";
public HttpClient CreateClient()
{
var client = new HttpClient();
SetupClientDefaults(client);
return client;
}
protected virtual void SetupClientDefaults(HttpClient client)
{
//This is global for all REST web service calls
client.Timeout = TimeSpan.FromSeconds(60);
client.BaseAddress = new Uri(webServiceUrl);
}
}
public class Lyrics
{
public class LyricsLine
{
internal TimeSpan Timestamp { get; set; }
internal string Text { get; set; }
}
public LyricsLine[] lyricLines;
private const int TimestampLength = 9;
public string GetTextForTimestamp(TimeSpan timestamp)
{
for (int i = 1; i < lyricLines.Length; ++i)
{
if (timestamp < lyricLines[i].Timestamp)
{
return lyricLines[i - 1].Text; // + " [" + timestamp.ToString() + "]";
}
}
return lyricLines[lyricLines.Length - 1].Text;
}
public static Lyrics ParseSyncedLyrics(string syncedLyrics)
{
if (string.IsNullOrWhiteSpace(syncedLyrics))
{
throw new ArgumentNullException();
}
string[] lines = syncedLyrics.Split('\n');
Lyrics result = new Lyrics();
result.lyricLines = new LyricsLine[lines.Length + 1];
// Empty entry for start of the song
result.lyricLines[0] = new LyricsLine
{
Timestamp = TimeSpan.Zero,
Text = String.Empty
};
int lineIndex = 1;
foreach (string line in lines)
{
string timestampString = line.Substring(1, TimestampLength - 1);
string text = String.Empty;
if (line.Length > TimestampLength + 1)
{
text = line.Substring(TimestampLength + 2);
}
TimeSpan timestamp = TimeSpan.Parse("00:" + timestampString);
// Round the timestamp down to avoid text showing up too late
// (it can still show up too early)
//timestamp = TimeSpan.FromSeconds(Math.Floor(timestamp.TotalSeconds));
result.lyricLines[lineIndex] = new LyricsLine
{
Timestamp = timestamp,
Text = text
};
++lineIndex;
}
return result;
}
};
public class Song
{
public string id { get; set; }
public string name { get; set; }
public string trackName { get; set; }
public string artistName { get; set; }
public string albumName { get; set; }
public string duration { get; set; }
public string instrumental { get; set; }
public string plainLyrics { get; set; }
public string syncedLyrics { get; set; }
public Lyrics ParsedLyrics { get; set; }
public enum GetMode
{
get = 1,
getcached = 2
}
public static Song FromSongID(string songID)
{
Song apiresponse = new Song();
string result = string.Empty;
HttpClientFactory clientFactory = new HttpClientFactory();
var client = clientFactory.CreateClient();
HttpResponseMessage response = client.GetAsync("/api/get/" + songID).Result;
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
apiresponse = JsonConvert.DeserializeObject<Song>(result);
}
else
{
throw new Exception(response.ReasonPhrase);
}
return apiresponse;
}
public static Song FromTrackSignature(string trackSignature, GetMode getMode)
{
string apiGetMode = "get?";
if (getMode == GetMode.get)
{
apiGetMode = "get?";
}
else
{
apiGetMode = "get-cached?";
}
Song apiresponse = new Song();
string result = string.Empty;
HttpClientFactory clientFactory = new HttpClientFactory();
var client = clientFactory.CreateClient();
HttpResponseMessage response = client.GetAsync("/api/" + apiGetMode + trackSignature).Result;
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
apiresponse = JsonConvert.DeserializeObject<Song>(result);
}
else
{
throw new Exception(response.ReasonPhrase);
}
return apiresponse;
}
public static List<Song> FromSearch(string trackName)
{
List<Song> apiresponse = new List<Song>();
string result = string.Empty;
HttpClientFactory clientFactory = new HttpClientFactory();
var client = clientFactory.CreateClient();
var updatedTrackName = WebUtility.UrlEncode(trackName).ToLower();
HttpResponseMessage response = client.GetAsync("/api/search?track_name=" + updatedTrackName).Result;
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
apiresponse = JsonConvert.DeserializeObject<List<Song>>(result);
}
else
{
throw new Exception(response.ReasonPhrase);
}
return apiresponse;
}
public static List<Song> FromSearch(string trackName, string artistName)
{
List<Song> apiresponse = new List<Song>();
string result = string.Empty;
HttpClientFactory clientFactory = new HttpClientFactory();
var client = clientFactory.CreateClient();
var updatedTrackName = WebUtility.UrlEncode(trackName).ToLower();
var updatedArtistName = WebUtility.UrlEncode(artistName).ToLower();
HttpResponseMessage response = client.GetAsync("/api/search?track_name=" + updatedTrackName + "&artist_name=" + updatedArtistName).Result;
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
apiresponse = JsonConvert.DeserializeObject<List<Song>>(result);
}
else
{
throw new Exception(response.ReasonPhrase);
}
return apiresponse;
}
}
}