Skip to content

Commit 9a9f6df

Browse files
author
theweavr
committed
fix #203, fixed musixmatch lyrics fetch
1 parent afab809 commit 9a9f6df

File tree

10 files changed

+94
-50
lines changed

10 files changed

+94
-50
lines changed

BreadPlayer.Core/Engines/BASSEngine/BASSPlayerEngine.cs

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -105,40 +105,51 @@ await Task.Run(() =>
105105
public async Task ChangeDevice(string deviceName = null)
106106
{
107107
if (deviceName != null)
108-
await InitializeSwitch.NotificationManager.ShowMessageAsync($"Transitioning to {deviceName}.", 5);
108+
await InitializeSwitch.NotificationManager.ShowStatusBarMessageAsync($"Transitioning to {deviceName}.");
109109

110-
await Task.Run(() =>
110+
await Task.Run(async () =>
111111
{
112-
var count = Bass.DeviceCount;
113-
for (var i = 0; i < count; i++)
112+
try
114113
{
115-
var deviceInfo = Bass.GetDeviceInfo(i);
116-
if (deviceInfo.IsDefault && deviceInfo.IsEnabled)
114+
var count = Bass.DeviceCount;
115+
for (var i = 0; i < count; i++)
117116
{
118-
var isPlaying = PlayerState == PlayerState.Playing;
119-
if (isPlaying)
117+
var deviceInfo = Bass.GetDeviceInfo(i);
118+
if (deviceInfo.IsDefault && deviceInfo.IsEnabled)
120119
{
121-
Bass.ChannelPause(_handle);
122-
PlayerState = PlayerState.Paused;
123-
}
120+
var isPlaying = PlayerState == PlayerState.Playing;
121+
if (isPlaying)
122+
{
123+
Bass.ChannelPause(_handle);
124+
PlayerState = PlayerState.Paused;
125+
}
124126

125-
if (InitializeSwitch.IsMobile)
126-
NativeMethods.BASS_SetConfig(NativeMethods.BassConfigDevBuffer, (int)DeviceBufferSize);
127+
if (InitializeSwitch.IsMobile)
128+
NativeMethods.BASS_SetConfig(NativeMethods.BassConfigDevBuffer, (int)DeviceBufferSize);
127129

128-
Bass.Init();
129-
Bass.ChannelSetDevice(_handle, i);
130-
if (isPlaying)
131-
{
132-
Bass.ChannelPlay(_handle);
133-
PlayerState = PlayerState.Playing;
130+
Bass.Init();
131+
Bass.ChannelSetDevice(_handle, i);
132+
if (isPlaying)
133+
{
134+
Bass.ChannelPlay(_handle);
135+
PlayerState = PlayerState.Playing;
136+
}
137+
return;
134138
}
135-
return;
136139
}
137140
}
141+
catch(Exception ex)
142+
{
143+
BLogger.E($"Transition failed.", ex);
144+
await InitializeSwitch.NotificationManager.ShowStatusBarMessageAsync($"Failed to transtion. Reason: {Bass.LastError}");
145+
}
146+
finally
147+
{
148+
if (deviceName != null)
149+
await InitializeSwitch.NotificationManager.ShowStatusBarMessageAsync($"Transition to {deviceName} complete.");
150+
}
138151
});
139152

140-
if (deviceName != null)
141-
await InitializeSwitch.NotificationManager.ShowMessageAsync($"Transition to {deviceName} complete.", 5);
142153
}
143154
public async Task<bool> LoadURLAsync(Mediafile mediafile, string uri)
144155
{

BreadPlayer.Core/Engines/BASSEngine/BassEqualizer.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using ManagedBass;
66
using ManagedBass.Fx;
77
using System;
8+
using System.Collections.Generic;
89
using System.Collections.ObjectModel;
910
using System.Linq;
1011

@@ -23,7 +24,7 @@ public BassEqualizer(int coreHandle)
2324
IsPreampAvailable = true;
2425

2526
Bands = new ObservableCollection<IEqualizerBand>();
26-
Presets = new ObservableCollection<IEqualizerSettings>(new ConfigSaver().GetSettings());
27+
Presets = new ObservableCollection<EqualizerSettings>((IEnumerable<EqualizerSettings>)new ConfigSaver().GetSettings());
2728
EqualizerSettings = InitializeSwitch.EqualizerSettingsHelper.LoadEqualizerSettings("CustomEq").settings;
2829
Name = EqualizerSettings.Name;
2930
SelectedPreset = Presets.IndexOf(Presets.FirstOrDefault(t => t.Name == EqualizerSettings.Name));

BreadPlayer.Core/Engines/Interfaces/IEqualizer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public abstract class Equalizer : ObservableObject
2323
new[] {16000f, 1f, 0f }
2424
};
2525
public IEqualizerSettings EqualizerSettings { get; set; }
26-
public ObservableCollection<IEqualizerSettings> Presets { get; set; }
26+
public ObservableCollection<EqualizerSettings> Presets { get; set; }
2727
private int _selectedPreset = -1;
2828

2929
public int SelectedPreset

BreadPlayer.Interfaces/INotificationManager.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public interface INotificationManager
88
Task ShowMessageBoxAsync(string message, string title);
99

1010
Task ShowMessageAsync(string message, int duration = 10);
11-
11+
Task ShowStatusBarMessageAsync(string message);
1212
void SendUpcomingSongNotification(IMediafile mediaFile);
1313
}
1414
}

BreadPlayer.Views.UWP/Common/NotificationManager.cs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@
99
using System.Threading.Tasks;
1010
using Windows.ApplicationModel.Core;
1111
using Windows.Data.Xml.Dom;
12+
using Windows.Foundation.Metadata;
1213
using Windows.UI.Core;
1314
using Windows.UI.Notifications;
1415
using Windows.UI.Popups;
16+
using Windows.UI.ViewManagement;
1517
using Windows.UI.Xaml;
1618

1719
namespace BreadPlayer.NotificationManager
@@ -22,7 +24,7 @@ public class BreadNotificationManager : ObservableObject, INotificationManager
2224
private ICommand _closeCommand;
2325
private DispatcherTimer _hideTimer;
2426
private string _status = string.Empty;
25-
27+
private StatusBar statusBar;
2628
public ICommand CloseCommand
2729
{
2830
get => _closeCommand ?? (_closeCommand = new DelegateCommand(HideStaticMessage));
@@ -120,5 +122,23 @@ await BreadDispatcher.InvokeAsync(() =>
120122
await ShowMessageAsync(NotificationQueue.Dequeue()).ConfigureAwait(false);
121123
}
122124
}
125+
126+
public async Task ShowStatusBarMessageAsync(string message)
127+
{
128+
if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1))
129+
{
130+
await BreadDispatcher.InvokeAsync(async () =>
131+
{
132+
if(statusBar == null)
133+
statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
134+
await statusBar.ShowAsync();
135+
statusBar.ProgressIndicator.Text = message;
136+
await statusBar.ProgressIndicator.ShowAsync();
137+
await Task.Delay(3000);
138+
await statusBar.ProgressIndicator.HideAsync();
139+
await statusBar.HideAsync();
140+
});
141+
}
142+
}
123143
}
124144
}

BreadPlayer.Views.UWP/Helpers/SettingsHelper.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public static T GetLocalSetting<T>(string key, object def)
3232
public (IEqualizerSettings settings, float PreAMP) LoadEqualizerSettings(string eqConfigName)
3333
{
3434
var eqJson = GetRoamingSetting<string>(eqConfigName, "{}");
35-
var settings = JsonConvert.DeserializeObject<IEqualizerSettings>(eqJson);
35+
var settings = JsonConvert.DeserializeObject<EqualizerSettings>(eqJson);
3636
return (settings, GetRoamingSetting<float>("PreAMP", 1.0f));
3737
}
3838

@@ -51,7 +51,7 @@ public void SaveEqualizerPresets(IEnumerable<IEqualizerSettings> presets)
5151

5252
public IEnumerable<IEqualizerSettings> LoadEqualizerPresets()
5353
{
54-
var presets = JsonConvert.DeserializeObject<IEnumerable<IEqualizerSettings>>(GetLocalSetting<string>("Presets", "[]"));
54+
var presets = JsonConvert.DeserializeObject<IEnumerable<EqualizerSettings>>(GetLocalSetting<string>("Presets", "[]"));
5555
return presets;
5656
}
5757
}

BreadPlayer.Views.UWP/ViewModels/ShellViewModel.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ public ShellViewModel()
103103
PropertyChanged += ShellViewModel_PropertyChanged;
104104
SharedLogic.Instance.Player.MediaAboutToEnd += Player_MediaAboutToEnd;
105105
SharedLogic.Instance.Player.MediaChanging += OnMediaChanging;
106+
106107
//these events are for detecting when the default audio
107108
//device is changed in PC and Mobile.
108109
if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1))
@@ -647,7 +648,10 @@ private Mediafile GetNextOrPrevSongInGroup(bool prev = false)
647648

648649
//get next/prev group index
649650
int nextGroupIndex = prev ? TracksCollection.IndexOf(currentGroup) - 1 : TracksCollection.IndexOf(currentGroup) + 1;
650-
651+
if (nextGroupIndex >= TracksCollection.Count - 1)
652+
{
653+
nextGroupIndex = 0;
654+
}
651655
//get next/prev group.
652656
Grouping<IGroupKey, Mediafile> nextGroup = nextGroupCondition ? TracksCollection.ElementAt(nextGroupIndex) : currentGroup;
653657

@@ -760,16 +764,15 @@ private async void Open(object para)
760764
#region Events
761765

762766
private int eventCount = 0; //used in AudioEndpointChangedEvent
763-
764-
private void OnAudioEndpointChanged(AudioRoutingManager sender, object args)
767+
private async void OnAudioEndpointChanged(AudioRoutingManager sender, object args)
765768
{
766769
var currentEndpoint = sender.GetAudioEndpoint();
767770
//when this event is initialized, it is invoked 2 times.
768771
//to avoid changing the device at that time, we use this statement.
769772
if (eventCount > 1)
770773
{
771774
BLogger.I($"Switching audio render device to [{currentEndpoint.ToString()}].");
772-
SharedLogic.Instance.Player.ChangeDevice(currentEndpoint.ToString());
775+
await SharedLogic.Instance.Player.ChangeDevice(currentEndpoint.ToString());
773776
}
774777
//increase the event count
775778
eventCount += 1;

BreadPlayer.Web/Musixmatch/HttpHelper.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public static HttpClient MusixmatchHttpClient
1616
{
1717
if (musixmatchHttpClient == null)
1818
{
19-
musixmatchHttpClient = new HttpClient();
19+
musixmatchHttpClient = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = false});
2020
musixmatchHttpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Musixmatch/0.19.4 Chrome/56.0.2924.87 Electron/1.6.10 Safari/537.36");
2121
musixmatchHttpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
2222
}

BreadPlayer.Web/Musixmatch/MusixmatchClient.cs

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,31 +9,38 @@
99
using System.IO.Compression;
1010
using Newtonsoft.Json;
1111
using BreadPlayer.Web.Musixmatch.Models;
12+
using RestSharp.Portable.HttpClient;
13+
using RestSharp.Portable;
1214

1315
namespace BreadPlayer.Web.Musixmatch
1416
{
1517
public class MusixmatchClient : ILyricAPI
1618
{
1719
public async Task<string> FetchLyrics(Mediafile mediaFile)
18-
{
19-
HttpHelper.MusixmatchHttpClient.CancelPendingRequests();
20-
string requestURI = string.Format(@"http://apic-desktop.musixmatch.com/ws/1.1/macro.subtitles.get?format=json&q_track={0}&q_artist={1}&q_album={2}&user_language=en&f_subtitle_length=0&f_subtitle_length_max_deviation=0&subtitle_format=lrc&app_id=web-desktop-app-v1.0&usertoken=1710149d15ba9db2a5a545aadd4f93928e90c783ab83565d105693", mediaFile.Title, mediaFile.LeadArtist, mediaFile.Album);
20+
{
21+
string requestURI = string.Format(@"https://apic-desktop.musixmatch.com/ws/1.1/macro.subtitles.get?format=json&q_track={0}&q_artist={1}&q_album={2}&user_language=en&f_subtitle_length=0&f_subtitle_length_max_deviation=0&subtitle_format=lrc&app_id=web-desktop-app-v1.0&guid=e08e6c63-edd1-4207-86dc-d350cdf7f4bc&usertoken=1710144894f79b194e5a5866d9e084d48f227d257dcd8438261277", mediaFile.Title, mediaFile.LeadArtist, mediaFile.Album);
2122

22-
//Send to the server
23-
var result = await HttpHelper.MusixmatchHttpClient.GetAsync(requestURI);
24-
if (!result.IsSuccessStatusCode)
25-
return null;
26-
//Read the content of the result response from the server
27-
using (Stream stream = await result.Content.ReadAsStreamAsync())
28-
using (Stream decompressed = new GZipStream(stream, CompressionMode.Decompress))
29-
using (StreamReader reader = new StreamReader(decompressed))
23+
using (var client = new RestClient(requestURI))
3024
{
25+
var request = new RestRequest(Method.GET);
26+
request.AddHeader("connection", "keep-alive");
27+
request.AddHeader("cookie", "x-mxm-user-id=; x-mxm-token-guid=e08e6c63-edd1-4207-86dc-d350cdf7f4bc; mxm-encrypted-token=; AWSELB=55578B011601B1EF8BC274C33F9043CA947F99DCFF6AB1B746DBF1E96A6F2B997493EE03F2DD5F516C3BC8E8DE7FE9C81FF414E8E76CF57330A3F26A0D86825F74794F3C94");
28+
request.AddHeader("cache-control", "no-cache");
29+
request.AddHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
30+
request.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36");
31+
request.AddHeader("upgrade-insecure-requests", "1");
32+
request.AddHeader("accept-language", "en-US,en;q=0.8");
33+
request.AddHeader("accept-encoding", "gzip, deflate");
34+
request.AddHeader("dnt", "1");
35+
IRestResponse response = await client.Execute(request);
3136
try
3237
{
33-
var json = await reader.ReadToEndAsync().ConfigureAwait(false);
34-
JsonSerializerSettings settings = new JsonSerializerSettings();
35-
settings.NullValueHandling = NullValueHandling.Ignore;
36-
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
38+
var json = response.Content;
39+
JsonSerializerSettings settings = new JsonSerializerSettings
40+
{
41+
NullValueHandling = NullValueHandling.Ignore,
42+
MissingMemberHandling = MissingMemberHandling.Ignore
43+
};
3744
var lyrics = JsonConvert.DeserializeObject<Lyrics>(json, settings).Message?.Body?.MacroCalls?.Subtitles?.Message?.Body?.SubtitleList;
3845
if (lyrics?.Any() == true)
3946
{
@@ -42,11 +49,11 @@ public async Task<string> FetchLyrics(Mediafile mediaFile)
4249
else
4350
return null;
4451
}
45-
catch(JsonSerializationException)
52+
catch (JsonSerializationException)
4653
{
4754
return null;
4855
}
49-
}
56+
}
5057
}
5158
}
5259
}

BreadPlayer.Web/project.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
"supports": {},
33
"dependencies": {
44
"AngleSharp": "0.9.9",
5+
"FubarCoder.RestSharp.Portable": "3.3.0",
6+
"FubarCoder.RestSharp.Portable.HttpClient": "4.0.8",
57
"Inflatable.Lastfm": "1.0.1.307",
68
"LiteDB": "4.0.0",
79
"Microsoft.NETCore.Portable.Compatibility": "1.0.1",

0 commit comments

Comments
 (0)