Some more refactoring.

This commit is contained in:
Johnny Dellinger @PC 2015-10-28 17:05:09 +01:00
parent cd74868a8d
commit 96bcb7bd36
9 changed files with 76 additions and 87 deletions

View File

@ -33,26 +33,26 @@ namespace SpotifyAPI.Example
{ {
if (!SpotifyLocalAPI.IsSpotifyRunning()) if (!SpotifyLocalAPI.IsSpotifyRunning())
{ {
MessageBox.Show("Spotify isn't running!"); MessageBox.Show(@"Spotify isn't running!");
return; return;
} }
if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning()) if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning())
{ {
MessageBox.Show("SpotifyWebHelper isn't running!"); MessageBox.Show(@"SpotifyWebHelper isn't running!");
return; return;
} }
bool successful = _spotify.Connect(); bool successful = _spotify.Connect();
if (successful) if (successful)
{ {
connectBtn.Text = "Connection to Spotify successful"; connectBtn.Text = @"Connection to Spotify successful";
connectBtn.Enabled = false; connectBtn.Enabled = false;
UpdateInfos(); UpdateInfos();
_spotify.ListenForEvents = true; _spotify.ListenForEvents = true;
} }
else else
{ {
DialogResult res = MessageBox.Show("Couldn't connect to the spotify client. Retry?", "Spotify", MessageBoxButtons.YesNo); DialogResult res = MessageBox.Show(@"Couldn't connect to the spotify client. Retry?", @"Spotify", MessageBoxButtons.YesNo);
if (res == DialogResult.Yes) if (res == DialogResult.Yes)
Connect(); Connect();
} }
@ -109,7 +109,7 @@ namespace SpotifyAPI.Example
private void _spotify_OnTrackTimeChange(TrackTimeChangeEventArgs e) private void _spotify_OnTrackTimeChange(TrackTimeChangeEventArgs e)
{ {
timeLabel.Text = FormatTime(e.TrackTime) + "/" + FormatTime(_currentTrack.Length); timeLabel.Text = $"{FormatTime(e.TrackTime)}/{FormatTime(_currentTrack.Length)}";
timeProgressBar.Value = (int)e.TrackTime; timeProgressBar.Value = (int)e.TrackTime;
} }

View File

@ -42,12 +42,12 @@ namespace SpotifyAPI.Example
if (state != "XSS") if (state != "XSS")
{ {
MessageBox.Show("Wrong state received.", "SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(@"Wrong state received.", @"SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
if (token.Error != null) if (token.Error != null)
{ {
MessageBox.Show("Error: " + token.Error, "SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Error: {token.Error}", @"SpotifyWeb API Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }

View File

@ -35,7 +35,7 @@ namespace SpotifyAPI.Local
internal async void SendPlayRequest(String url, String context = "") internal async void SendPlayRequest(String url, String context = "")
{ {
// TODO: instead of having an empty context, one way to fix the bug with the playback time beyond the length of a song would be to provide a 1-song context, and it would be fixed. // TODO: instead of having an empty context, one way to fix the bug with the playback time beyond the length of a song would be to provide a 1-song context, and it would be fixed.
await QueryAsync(string.Format("remote/play.json?uri={0}&context={1}", url, context), true, true, -1); await QueryAsync($"remote/play.json?uri={url}&context={context}", true, true, -1);
} }
internal async void SendQueueRequest(String url) internal async void SendQueueRequest(String url)

View File

@ -2,7 +2,6 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO; using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Timers; using System.Timers;
@ -216,7 +215,7 @@ namespace SpotifyAPI.Local
if (Environment.OSVersion.Version.Minor == 0) if (Environment.OSVersion.Version.Minor == 0)
throw new NotSupportedException("This feature is only available on Windows 7 or newer"); throw new NotSupportedException("This feature is only available on Windows 7 or newer");
if (volume < 0 || volume > 100) if (volume < 0 || volume > 100)
throw new ArgumentOutOfRangeException("Volume parameter has to be a value between 0 and 100"); throw new ArgumentOutOfRangeException(nameof(volume));
VolumeMixerControl.SetSpotifyVolume(volume); VolumeMixerControl.SetSpotifyVolume(volume);
} }

View File

@ -6,11 +6,11 @@ namespace SpotifyAPI.Local
{ {
internal class VolumeMixerControl internal class VolumeMixerControl
{ {
private const String SPOTIFY_PROCESS_NAME = "spotify"; private const String SpotifyProcessName = "spotify";
internal static float GetSpotifyVolume() internal static float GetSpotifyVolume()
{ {
Process[] p = Process.GetProcessesByName(SPOTIFY_PROCESS_NAME); Process[] p = Process.GetProcessesByName(SpotifyProcessName);
if (p.Length == 0) if (p.Length == 0)
throw new Exception("Spotify process is not running or was not found!"); throw new Exception("Spotify process is not running or was not found!");
@ -19,7 +19,6 @@ namespace SpotifyAPI.Local
ISimpleAudioVolume volume = GetVolumeObject(pid); ISimpleAudioVolume volume = GetVolumeObject(pid);
if (volume == null) if (volume == null)
{ {
Marshal.ReleaseComObject(volume);
throw new COMException("Volume object creation failed"); throw new COMException("Volume object creation failed");
} }
@ -31,7 +30,7 @@ namespace SpotifyAPI.Local
internal static bool IsSpotifyMuted() internal static bool IsSpotifyMuted()
{ {
Process[] p = Process.GetProcessesByName(SPOTIFY_PROCESS_NAME); Process[] p = Process.GetProcessesByName(SpotifyProcessName);
if (p.Length == 0) if (p.Length == 0)
throw new Exception("Spotify process is not running or was not found!"); throw new Exception("Spotify process is not running or was not found!");
@ -40,7 +39,6 @@ namespace SpotifyAPI.Local
ISimpleAudioVolume volume = GetVolumeObject(pid); ISimpleAudioVolume volume = GetVolumeObject(pid);
if (volume == null) if (volume == null)
{ {
Marshal.ReleaseComObject(volume);
throw new COMException("Volume object creation failed"); throw new COMException("Volume object creation failed");
} }
@ -52,7 +50,7 @@ namespace SpotifyAPI.Local
internal static void SetSpotifyVolume(float level) internal static void SetSpotifyVolume(float level)
{ {
Process[] p = Process.GetProcessesByName(SPOTIFY_PROCESS_NAME); Process[] p = Process.GetProcessesByName(SpotifyProcessName);
if (p.Length == 0) if (p.Length == 0)
throw new Exception("Spotify process is not running or was not found!"); throw new Exception("Spotify process is not running or was not found!");
@ -61,7 +59,6 @@ namespace SpotifyAPI.Local
ISimpleAudioVolume volume = GetVolumeObject(pid); ISimpleAudioVolume volume = GetVolumeObject(pid);
if (volume == null) if (volume == null)
{ {
Marshal.ReleaseComObject(volume);
throw new COMException("Volume object creation failed"); throw new COMException("Volume object creation failed");
} }
@ -72,7 +69,7 @@ namespace SpotifyAPI.Local
internal static void MuteSpotify(bool mute) internal static void MuteSpotify(bool mute)
{ {
Process[] p = Process.GetProcessesByName(SPOTIFY_PROCESS_NAME); Process[] p = Process.GetProcessesByName(SpotifyProcessName);
if (p.Length == 0) if (p.Length == 0)
throw new Exception("Spotify process is not running or was not found!"); throw new Exception("Spotify process is not running or was not found!");
@ -81,7 +78,6 @@ namespace SpotifyAPI.Local
ISimpleAudioVolume volume = GetVolumeObject(pid); ISimpleAudioVolume volume = GetVolumeObject(pid);
if (volume == null) if (volume == null)
{ {
Marshal.ReleaseComObject(volume);
throw new COMException("Volume object creation failed"); throw new COMException("Volume object creation failed");
} }
@ -93,14 +89,14 @@ namespace SpotifyAPI.Local
private static ISimpleAudioVolume GetVolumeObject(int pid) private static ISimpleAudioVolume GetVolumeObject(int pid)
{ {
// get the speakers (1st render + multimedia) device // get the speakers (1st render + multimedia) device
IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); IMmDeviceEnumerator deviceEnumerator = (IMmDeviceEnumerator)(new MMDeviceEnumerator());
IMMDevice speakers; IMmDevice speakers;
deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out speakers); deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.ERender, ERole.EMultimedia, out speakers);
// activate the session manager. we need the enumerator // activate the session manager. we need the enumerator
Guid IID_IAudioSessionManager2 = typeof(IAudioSessionManager2).GUID; Guid iidIAudioSessionManager2 = typeof(IAudioSessionManager2).GUID;
object o; object o;
speakers.Activate(ref IID_IAudioSessionManager2, 0, IntPtr.Zero, out o); speakers.Activate(ref iidIAudioSessionManager2, 0, IntPtr.Zero, out o);
IAudioSessionManager2 mgr = (IAudioSessionManager2)o; IAudioSessionManager2 mgr = (IAudioSessionManager2)o;
// enumerate sessions for on this device // enumerate sessions for on this device
@ -121,7 +117,7 @@ namespace SpotifyAPI.Local
if (cpid == pid) if (cpid == pid)
{ {
volumeControl = ctl as ISimpleAudioVolume; volumeControl = (ISimpleAudioVolume) ctl;
break; break;
} }
Marshal.ReleaseComObject(ctl); Marshal.ReleaseComObject(ctl);
@ -142,31 +138,31 @@ namespace SpotifyAPI.Local
private enum EDataFlow private enum EDataFlow
{ {
eRender, ERender,
eCapture, ECapture,
eAll, EAll,
EDataFlow_enum_count EDataFlowEnumCount
} }
private enum ERole private enum ERole
{ {
eConsole, EConsole,
eMultimedia, EMultimedia,
eCommunications, ECommunications,
ERole_enum_count ERoleEnumCount
} }
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDeviceEnumerator private interface IMmDeviceEnumerator
{ {
int NotImpl1(); int NotImpl1();
[PreserveSig] [PreserveSig]
int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppDevice); int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMmDevice ppDevice);
} }
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDevice private interface IMmDevice
{ {
[PreserveSig] [PreserveSig]
int Activate(ref Guid iid, int dwClsCtx, IntPtr pActivationParams, [MarshalAs(UnmanagedType.IUnknown)] out object ppInterface); int Activate(ref Guid iid, int dwClsCtx, IntPtr pActivationParams, [MarshalAs(UnmanagedType.IUnknown)] out object ppInterface);
@ -180,30 +176,30 @@ namespace SpotifyAPI.Local
int NotImpl2(); int NotImpl2();
[PreserveSig] [PreserveSig]
int GetSessionEnumerator(out IAudioSessionEnumerator SessionEnum); int GetSessionEnumerator(out IAudioSessionEnumerator sessionEnum);
} }
[Guid("E2F5BB11-0570-40CA-ACDD-3AA01277DEE8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("E2F5BB11-0570-40CA-ACDD-3AA01277DEE8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAudioSessionEnumerator private interface IAudioSessionEnumerator
{ {
[PreserveSig] [PreserveSig]
int GetCount(out int SessionCount); int GetCount(out int sessionCount);
[PreserveSig] [PreserveSig]
int GetSession(int SessionCount, out IAudioSessionControl2 Session); int GetSession(int sessionCount, out IAudioSessionControl2 session);
} }
[Guid("87CE5498-68D6-44E5-9215-6DA47EF883D8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("87CE5498-68D6-44E5-9215-6DA47EF883D8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface ISimpleAudioVolume private interface ISimpleAudioVolume
{ {
[PreserveSig] [PreserveSig]
int SetMasterVolume(float fLevel, ref Guid EventContext); int SetMasterVolume(float fLevel, ref Guid eventContext);
[PreserveSig] [PreserveSig]
int GetMasterVolume(out float pfLevel); int GetMasterVolume(out float pfLevel);
[PreserveSig] [PreserveSig]
int SetMute(bool bMute, ref Guid EventContext); int SetMute(bool bMute, ref Guid eventContext);
[PreserveSig] [PreserveSig]
int GetMute(out bool pbMute); int GetMute(out bool pbMute);
@ -219,19 +215,19 @@ namespace SpotifyAPI.Local
int GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal); int GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig] [PreserveSig]
int SetDisplayName([MarshalAs(UnmanagedType.LPWStr)]string Value, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext); int SetDisplayName([MarshalAs(UnmanagedType.LPWStr)]string value, [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);
[PreserveSig] [PreserveSig]
int GetIconPath([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal); int GetIconPath([MarshalAs(UnmanagedType.LPWStr)] out string pRetVal);
[PreserveSig] [PreserveSig]
int SetIconPath([MarshalAs(UnmanagedType.LPWStr)] string Value, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext); int SetIconPath([MarshalAs(UnmanagedType.LPWStr)] string value, [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);
[PreserveSig] [PreserveSig]
int GetGroupingParam(out Guid pRetVal); int GetGroupingParam(out Guid pRetVal);
[PreserveSig] [PreserveSig]
int SetGroupingParam([MarshalAs(UnmanagedType.LPStruct)] Guid Override, [MarshalAs(UnmanagedType.LPStruct)] Guid EventContext); int SetGroupingParam([MarshalAs(UnmanagedType.LPStruct)] Guid Override, [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext);
[PreserveSig] [PreserveSig]
int NotImpl1(); int NotImpl1();

View File

@ -98,13 +98,12 @@ namespace SpotifyAPI.Web.Auth
private void HttpServerOnOnAuth(AuthEventArgs e) private void HttpServerOnOnAuth(AuthEventArgs e)
{ {
if (OnResponseReceivedEvent != null) OnResponseReceivedEvent?.Invoke(new AutorizationCodeAuthResponse()
OnResponseReceivedEvent(new AutorizationCodeAuthResponse() {
{ Code = e.Code,
Code = e.Code, State = e.State,
State = e.State, Error = e.Error
Error = e.Error });
});
} }
/// <summary> /// <summary>

View File

@ -56,14 +56,13 @@ namespace SpotifyAPI.Web.Auth
private void HttpServerOnOnAuth(AuthEventArgs e) private void HttpServerOnOnAuth(AuthEventArgs e)
{ {
if (OnResponseReceivedEvent != null) OnResponseReceivedEvent?.Invoke(new Token
OnResponseReceivedEvent(new Token {
{ AccessToken = e.Code,
AccessToken = e.Code, TokenType = e.TokenType,
TokenType = e.TokenType, ExpiresIn = e.ExpiresIn,
ExpiresIn = e.ExpiresIn, Error = e.Error
Error = e.Error }, e.State);
}, e.State);
} }
/// <summary> /// <summary>

View File

@ -147,7 +147,7 @@ namespace SpotifyAPI.Web
var contentLen = Convert.ToInt32(HttpHeaders["Content-Length"]); var contentLen = Convert.ToInt32(HttpHeaders["Content-Length"]);
if (contentLen > MaxPostSize) if (contentLen > MaxPostSize)
{ {
throw new Exception(String.Format("POST Content-Length({0}) too big for this simple server", contentLen)); throw new Exception($"POST Content-Length({contentLen}) too big for this simple server");
} }
byte[] buf = new byte[BufSize]; byte[] buf = new byte[BufSize];
int toRead = contentLen; int toRead = contentLen;
@ -274,12 +274,11 @@ namespace SpotifyAPI.Web
p.OutputStream.WriteLine("<html><body><h1>Spotify Auth canceled!</h1></body></html>"); p.OutputStream.WriteLine("<html><body><h1>Spotify Auth canceled!</h1></body></html>");
t = new Thread(o => t = new Thread(o =>
{ {
if (OnAuth != null) OnAuth?.Invoke(new AuthEventArgs()
OnAuth(new AuthEventArgs() {
{ State = col.Get(1),
State = col.Get(1), Error = col.Get(0),
Error = col.Get(0), });
});
}); });
} }
else else
@ -287,12 +286,11 @@ namespace SpotifyAPI.Web
p.OutputStream.WriteLine("<html><body><h1>Spotify Auth successful!</h1><script>window.close();</script></body></html>"); p.OutputStream.WriteLine("<html><body><h1>Spotify Auth successful!</h1><script>window.close();</script></body></html>");
t = new Thread(o => t = new Thread(o =>
{ {
if (OnAuth != null) OnAuth?.Invoke(new AuthEventArgs()
OnAuth(new AuthEventArgs() {
{ Code = col.Get(0),
Code = col.Get(0), State = col.Get(1)
State = col.Get(1) });
});
}); });
} }
} }
@ -318,12 +316,11 @@ namespace SpotifyAPI.Web
p.OutputStream.WriteLine("<html><body><h1>Spotify Auth canceled!</h1></body></html>"); p.OutputStream.WriteLine("<html><body><h1>Spotify Auth canceled!</h1></body></html>");
t = new Thread(o => t = new Thread(o =>
{ {
if (OnAuth != null) OnAuth?.Invoke(new AuthEventArgs()
OnAuth(new AuthEventArgs() {
{ Error = col.Get(0),
Error = col.Get(0), State = col.Get(1)
State = col.Get(1) });
});
}); });
} }
else else
@ -331,14 +328,13 @@ namespace SpotifyAPI.Web
p.OutputStream.WriteLine("<html><body><h1>Spotify Auth successful!</h1><script>window.close();</script></body></html>"); p.OutputStream.WriteLine("<html><body><h1>Spotify Auth successful!</h1><script>window.close();</script></body></html>");
t = new Thread(o => t = new Thread(o =>
{ {
if (OnAuth != null) OnAuth?.Invoke(new AuthEventArgs()
OnAuth(new AuthEventArgs() {
{ Code = col.Get(0),
Code = col.Get(0), TokenType = col.Get(1),
TokenType = col.Get(1), ExpiresIn = Convert.ToInt32(col.Get(2)),
ExpiresIn = Convert.ToInt32(col.Get(2)), State = col.Get(3)
State = col.Get(3) });
});
}); });
} }
} }

View File

@ -35,7 +35,7 @@ namespace SpotifyAPI.Web
public void Dispose() public void Dispose()
{ {
WebClient.Dispose(); WebClient.Dispose();
GC.SuppressFinalize(this); GC.SuppressFinalize(this); //TODO
} }
#region Search #region Search