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())
{
MessageBox.Show("Spotify isn't running!");
MessageBox.Show(@"Spotify isn't running!");
return;
}
if (!SpotifyLocalAPI.IsSpotifyWebHelperRunning())
{
MessageBox.Show("SpotifyWebHelper isn't running!");
MessageBox.Show(@"SpotifyWebHelper isn't running!");
return;
}
bool successful = _spotify.Connect();
if (successful)
{
connectBtn.Text = "Connection to Spotify successful";
connectBtn.Text = @"Connection to Spotify successful";
connectBtn.Enabled = false;
UpdateInfos();
_spotify.ListenForEvents = true;
}
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)
Connect();
}
@ -109,7 +109,7 @@ namespace SpotifyAPI.Example
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;
}

View File

@ -42,12 +42,12 @@ namespace SpotifyAPI.Example
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;
}
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;
}

View File

@ -35,7 +35,7 @@ namespace SpotifyAPI.Local
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.
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)

View File

@ -2,7 +2,6 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
using System.Timers;
@ -216,7 +215,7 @@ namespace SpotifyAPI.Local
if (Environment.OSVersion.Version.Minor == 0)
throw new NotSupportedException("This feature is only available on Windows 7 or newer");
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);
}

View File

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

View File

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

View File

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

View File

@ -147,7 +147,7 @@ namespace SpotifyAPI.Web
var contentLen = Convert.ToInt32(HttpHeaders["Content-Length"]);
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];
int toRead = contentLen;
@ -274,12 +274,11 @@ namespace SpotifyAPI.Web
p.OutputStream.WriteLine("<html><body><h1>Spotify Auth canceled!</h1></body></html>");
t = new Thread(o =>
{
if (OnAuth != null)
OnAuth(new AuthEventArgs()
{
State = col.Get(1),
Error = col.Get(0),
});
OnAuth?.Invoke(new AuthEventArgs()
{
State = col.Get(1),
Error = col.Get(0),
});
});
}
else
@ -287,12 +286,11 @@ namespace SpotifyAPI.Web
p.OutputStream.WriteLine("<html><body><h1>Spotify Auth successful!</h1><script>window.close();</script></body></html>");
t = new Thread(o =>
{
if (OnAuth != null)
OnAuth(new AuthEventArgs()
{
Code = col.Get(0),
State = col.Get(1)
});
OnAuth?.Invoke(new AuthEventArgs()
{
Code = col.Get(0),
State = col.Get(1)
});
});
}
}
@ -318,12 +316,11 @@ namespace SpotifyAPI.Web
p.OutputStream.WriteLine("<html><body><h1>Spotify Auth canceled!</h1></body></html>");
t = new Thread(o =>
{
if (OnAuth != null)
OnAuth(new AuthEventArgs()
{
Error = col.Get(0),
State = col.Get(1)
});
OnAuth?.Invoke(new AuthEventArgs()
{
Error = col.Get(0),
State = col.Get(1)
});
});
}
else
@ -331,14 +328,13 @@ namespace SpotifyAPI.Web
p.OutputStream.WriteLine("<html><body><h1>Spotify Auth successful!</h1><script>window.close();</script></body></html>");
t = new Thread(o =>
{
if (OnAuth != null)
OnAuth(new AuthEventArgs()
{
Code = col.Get(0),
TokenType = col.Get(1),
ExpiresIn = Convert.ToInt32(col.Get(2)),
State = col.Get(3)
});
OnAuth?.Invoke(new AuthEventArgs()
{
Code = col.Get(0),
TokenType = col.Get(1),
ExpiresIn = Convert.ToInt32(col.Get(2)),
State = col.Get(3)
});
});
}
}

View File

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