Added Docs/Fixxed Spelling URI --> URL

This commit is contained in:
Johnny @PC 2014-02-13 14:23:52 +01:00
parent 03a18e0bdf
commit 69e69f9cf5
11 changed files with 186 additions and 32 deletions

Binary file not shown.

View File

@ -5,6 +5,9 @@ using System.Text;
namespace SpotifyAPIv1 namespace SpotifyAPIv1
{ {
/// <summary>
/// JSON Response, used internaly
/// </summary>
class CFID class CFID
{ {
public Error error { get; set; } public Error error { get; set; }
@ -13,6 +16,9 @@ namespace SpotifyAPIv1
public String client_version { get; set; } public String client_version { get; set; }
public Boolean running { get; set; } public Boolean running { get; set; }
} }
/// <summary>
/// JSON Response, used internaly
/// </summary>
class Error class Error
{ {
public String type { get; set; } public String type { get; set; }

View File

@ -3,12 +3,18 @@ using System.Text;
namespace SpotifyAPIv1 namespace SpotifyAPIv1
{ {
/// <summary>
/// Enum for the AlbumArt
/// </summary>
public enum AlbumArtSize public enum AlbumArtSize
{ {
SIZE_160, SIZE_160,
SIZE_320, SIZE_320,
SIZE_640 SIZE_640
} }
/// <summary>
/// Not implemented yet
/// </summary>
public enum CFIDResponse public enum CFIDResponse
{ {
SUCCESS, SUCCESS,

View File

@ -3,20 +3,32 @@ using System.Text;
namespace SpotifyAPIv1 namespace SpotifyAPIv1
{ {
/// <summary>
/// Event gets triggered, when the Track is changed
/// </summary>
public class TrackChangeEventArgs public class TrackChangeEventArgs
{ {
public Track old_track { get; set; } public Track old_track { get; set; }
public Track new_track { get; set; } public Track new_track { get; set; }
} }
/// <summary>
/// Event gets triggered, when the Playin-state is changed (e.g Play --> Pause)
/// </summary>
public class PlayStateEventArgs public class PlayStateEventArgs
{ {
public Boolean playing { get; set; } public Boolean playing { get; set; }
} }
/// <summary>
/// Event gets triggered, when the volume changes
/// </summary>
public class VolumeChangeEventArgs public class VolumeChangeEventArgs
{ {
public double old_volume { get; set; } public double old_volume { get; set; }
public double new_volume { get; set; } public double new_volume { get; set; }
} }
/// <summary>
/// Event gets triggered, when the tracktime changes
/// </summary>
public class TrackTimeChangeEventArgs public class TrackTimeChangeEventArgs
{ {
public double track_time { get; set; } public double track_time { get; set; }

View File

@ -53,7 +53,7 @@ namespace SpotifyAPIv1
String response = query("remote/status.json", true, true, -1); String response = query("remote/status.json", true, true, -1);
if(response == "") if(response == "")
{ {
return Update(); return null;
} }
response = response.Replace("\\n", ""); response = response.Replace("\\n", "");
byte[] bytes = Encoding.Default.GetBytes(response); byte[] bytes = Encoding.Default.GetBytes(response);
@ -61,7 +61,7 @@ namespace SpotifyAPIv1
List<StatusResponse> raw = (List<StatusResponse>)JsonConvert.DeserializeObject(response,typeof(List<StatusResponse>)); List<StatusResponse> raw = (List<StatusResponse>)JsonConvert.DeserializeObject(response,typeof(List<StatusResponse>));
return raw[0]; return raw[0];
} }
private String GetOAuthKey() internal String GetOAuthKey()
{ {
String raw = ""; String raw = "";
using(WebClient wc = new WebClient()) using(WebClient wc = new WebClient())
@ -73,7 +73,7 @@ namespace SpotifyAPIv1
return (String)lol["t"]; return (String)lol["t"];
} }
private String GetCFID() internal String GetCFID()
{ {
string a = query("simplecsrf/token.json", false, false, -1); string a = query("simplecsrf/token.json", false, false, -1);
a = a.Replace(@"\", ""); a = a.Replace(@"\", "");
@ -84,7 +84,7 @@ namespace SpotifyAPIv1
throw new Exception("SpotifyWebHelper Error: " + d[0].error.message); throw new Exception("SpotifyWebHelper Error: " + d[0].error.message);
return d[0].token; return d[0].token;
} }
private string query(string request, bool oauth, bool cfid, int wait) internal string query(string request, bool oauth, bool cfid, int wait)
{ {
string parameters = "?&ref=&cors=&_=" + GetTimestamp(); string parameters = "?&ref=&cors=&_=" + GetTimestamp();
if (request.Contains("?")) if (request.Contains("?"))
@ -108,19 +108,18 @@ namespace SpotifyAPIv1
} }
string a = "http://" + host + ":4380/" + request + parameters; string a = "http://" + host + ":4380/" + request + parameters;
string derp = ""; string response = "";
try try
{ {
derp = wc.DownloadString(a); response = "[ " + wc.DownloadString(a) + " ]";
derp = "[ " + derp + " ]";
} }
catch (Exception z) catch (Exception z)
{ {
throw;
} }
return derp; return response;
} }
private int GetTimestamp() internal int GetTimestamp()
{ {
return Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds); return Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds);
} }

View File

@ -18,48 +18,81 @@ namespace SpotifyAPIv1
eh = new SpotifyEventHandler(this, mh); eh = new SpotifyEventHandler(this, mh);
} }
/// <summary>
/// Connects with Spotify. Needs to be called before all other SpotifyAPI functions
/// </summary>
public void Connect() public void Connect()
{ {
rh.Init(); rh.Init();
} }
/// <summary>
/// Returns the MusicHandler
/// </summary>
/// <returns>Returns the MusicHandler</returns>
public SpotifyMusicHandler GetMusicHandler() public SpotifyMusicHandler GetMusicHandler()
{ {
return mh; return mh;
} }
/// <summary>
/// Returns the EventHanlder
/// </summary>
/// <returns>Returns the EventHanlder</returns>
public SpotifyEventHandler GetEventHandler() public SpotifyEventHandler GetEventHandler()
{ {
return eh; return eh;
} }
/// <summary>
/// Checks if Spotify is running
/// </summary>
/// <returns>True, if it's running, false if not</returns>
public static Boolean IsSpotifyRunning() public static Boolean IsSpotifyRunning()
{ {
if (Process.GetProcessesByName("spotify").Length < 1) if (Process.GetProcessesByName("spotify").Length < 1)
return false; return false;
return true; return true;
} }
/// <summary>
/// Checks if Spotify's WebHelper is running (Needed for API Calls)
/// </summary>
/// <returns>True, if it's running, false if not</returns>
public static Boolean IsSpotifyWebHelperRunning() public static Boolean IsSpotifyWebHelperRunning()
{ {
if (Process.GetProcessesByName("SpotifyWebHelper").Length < 1) if (Process.GetProcessesByName("SpotifyWebHelper").Length < 1)
return false; return false;
return true; return true;
} }
/// <summary>
/// Runs Spotify
/// </summary>
public void RunSpotify() public void RunSpotify()
{ {
if(!IsSpotifyRunning()) if(!IsSpotifyRunning())
Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Spotify\\spotify.exe"); Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Spotify\\spotify.exe");
} }
/// <summary>
/// Runs Spotify's WebHelper
/// </summary>
public void RunSpotifyWebHelper() public void RunSpotifyWebHelper()
{ {
if (!IsSpotifyWebHelperRunning()) if (!IsSpotifyWebHelperRunning())
Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Spotify\\Data\\SpotifyWebHelper.exe"); Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Spotify\\Data\\SpotifyWebHelper.exe");
} }
public static Boolean IsValidSpotifyURL(String url) /// <summary>
/// Checks for a valid SpotifyURL (Still not finished)
/// </summary>
/// <param name="url">The Spotify URI starting with "spotify:"</param>
/// <returns>True if the URI is valid, false if not</returns>
public static Boolean IsValidSpotifyURI(String uri)
{ {
String[] types = new String[] { "track","album","local","artist"}; String[] types = new String[] { "track","album","local","artist"};
String[] split = url.Split(':'); String[] split = uri.Split(':');
if (split.Length < 3) if (split.Length < 3)
return false; return false;
return split[0] == "spotify" && Array.IndexOf(types, split[1]) > -1 && split[2].Length == 22; return split[0] == "spotify" && Array.IndexOf(types, split[1]) > -1 && split[2].Length == 22;
} }
/// <summary>
/// Updates and Fetches all current information about the current track etc.
/// </summary>
public void Update() public void Update()
{ {
if (!SpotifyAPI.IsSpotifyWebHelperRunning()) if (!SpotifyAPI.IsSpotifyWebHelperRunning())

View File

@ -30,28 +30,31 @@ namespace SpotifyAPIv1
timer.Interval = 50; timer.Interval = 50;
timer.Elapsed += tick; timer.Elapsed += tick;
timer.AutoReset = false; timer.AutoReset = false;
timer.Enabled = true; timer.Enabled = false;
timer.Start();
this.api = api; this.api = api;
this.mh = mh; this.mh = mh;
} }
/// <summary>
/// If Events should be triggered
/// </summary>
/// <param name="listen">True if you want to listen for events, false if not</param>
public void ListenForEvents(Boolean listen) public void ListenForEvents(Boolean listen)
{ {
this.listen = listen; timer.Enabled = listen;
if (listen)
timer.Start();
} }
/// <summary>
/// Sets a synchronizing object, so you don't need to Invoke
/// </summary>
/// <param name="obj">The SynchronizingObject e.g a Form</param>
public void SetSynchronizingObject(System.ComponentModel.ISynchronizeInvoke obj) public void SetSynchronizingObject(System.ComponentModel.ISynchronizeInvoke obj)
{ {
timer.SynchronizingObject = obj; timer.SynchronizingObject = obj;
} }
private void tick(object sender, EventArgs e) internal void tick(object sender, EventArgs e)
{ {
if (!listen)
{
timer.Start();
return;
}
api.Update(); api.Update();
if (response == null) if (response == null)
{ {

View File

@ -11,13 +11,14 @@ namespace SpotifyAPIv1
public class SpotifyMusicHandler public class SpotifyMusicHandler
{ {
[DllImport("user32.dll")] [DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo); private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
[DllImport("nircmd.dll")] [DllImport("nircmd.dll")]
public static extern bool DoNirCmd(String NirCmdStr); private static extern bool DoNirCmd(String NirCmdStr);
RemoteHandler rh; RemoteHandler rh;
StatusResponse sr; StatusResponse sr;
//Constants for the Keyboard Event (NextTrack + PreviousTrack)
const byte VK_MEDIA_NEXT_TRACK = 0xb0; const byte VK_MEDIA_NEXT_TRACK = 0xb0;
const byte VK_MEDIA_PREV_TRACK = 0xb1; const byte VK_MEDIA_PREV_TRACK = 0xb1;
const int KEYEVENTF_EXTENDEDKEY = 0x1; const int KEYEVENTF_EXTENDEDKEY = 0x1;
@ -27,66 +28,116 @@ namespace SpotifyAPIv1
{ {
rh = RemoteHandler.GetInstance(); rh = RemoteHandler.GetInstance();
} }
/// <summary>
/// Simulates a KeyPress
/// </summary>
/// <param name="keyCode">The keycode for the represented Key</param>
void PressKey(byte keyCode) void PressKey(byte keyCode)
{ {
keybd_event(keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0); keybd_event(keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); keybd_event(keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
} }
/// <summary>
/// Checks if a song is playing
/// </summary>
/// <returns>True if a song is playing, false if not</returns>
public Boolean IsPlaying() public Boolean IsPlaying()
{ {
return sr.playing; return sr.playing;
} }
/// <summary>
/// Returns the current Volume
/// </summary>
/// <returns>A value between 0 and 1</returns>
public double GetVolume() public double GetVolume()
{ {
return sr.volume; return sr.volume;
} }
public void PlayURL(String url) /// <summary>
/// Plays a Spotify URI
/// </summary>
/// <param name="uri">The Spotify URI. Can be checked with <seealso cref="SpotifyAPI.IsValidSpotifyURI"/></param>
public void PlayURL(String uri)
{ {
rh.SendPlayRequest(url); rh.SendPlayRequest(uri);
} }
/// <summary>
/// Checks if the current "Track" is an Advert
/// </summary>
/// <returns>True if it's an Advert, false if not</returns>
public Boolean IsAdRunning() public Boolean IsAdRunning()
{ {
return !sr.next_enabled && !sr.prev_enabled; return !sr.next_enabled && !sr.prev_enabled;
} }
/// <summary>
/// Returns the current Track object
/// </summary>
/// <returns>Returns the current track object</returns>
public Track GetCurrentTrack() public Track GetCurrentTrack()
{ {
return sr.track; return sr.track;
} }
/// <summary>
/// Skips the current song (Using keypress simulation)
/// </summary>
public void Skip() public void Skip()
{ {
PressKey(VK_MEDIA_NEXT_TRACK); PressKey(VK_MEDIA_NEXT_TRACK);
} }
/// <summary>
/// Emulates the "Previous" Key (Using keypress simulation)
/// </summary>
public void Previous()
{
PressKey(VK_MEDIA_PREV_TRACK);
}
/// <summary>
/// Returns the current track postion
/// </summary>
/// <returns>A double between 0 and ∞</returns>
public double GetTrackPosition() public double GetTrackPosition()
{ {
return sr.playing_position; return sr.playing_position;
} }
/// <summary>
/// Mutes Spotify (Requires nircmd.dll)
/// </summary>
public void Mute() public void Mute()
{ {
if(File.Exists("nircmd.dll")) if(File.Exists("nircmd.dll"))
DoNirCmd("muteappvolume spotify.exe 1"); DoNirCmd("muteappvolume spotify.exe 1");
} }
/// <summary>
/// Unmutes Spotify (Requires nircmd.dll)
/// </summary>
public void UnMute() public void UnMute()
{ {
if (File.Exists("nircmd.dll")) if (File.Exists("nircmd.dll"))
DoNirCmd("muteappvolume spotify.exe 0"); DoNirCmd("muteappvolume spotify.exe 0");
} }
public void Previous() /// <summary>
{ /// Pause function
PressKey(VK_MEDIA_PREV_TRACK); /// </summary>
}
public void Pause() public void Pause()
{ {
rh.SendPauseRequest(); rh.SendPauseRequest();
} }
/// <summary>
/// Play function
/// </summary>
public void Play() public void Play()
{ {
rh.SendPlayRequest(); rh.SendPlayRequest();
} }
/// <summary>
/// Returns all Informations gathered by the JSON Request
/// </summary>
/// <returns>A StatusResponse object</returns>
public StatusResponse GetStatusResponse() public StatusResponse GetStatusResponse()
{ {
return sr; return sr;
} }
//Used internaly
internal void Update(StatusResponse sr) internal void Update(StatusResponse sr)
{ {
this.sr = sr; this.sr = sr;

View File

@ -7,6 +7,7 @@ namespace SpotifyAPIv1
{ {
public class StatusResponse public class StatusResponse
{ {
//All information got from the JSON Response
public int version { get; set; } public int version { get; set; }
public string client_version { get; set; } public string client_version { get; set; }
public bool playing { get; set; } public bool playing { get; set; }

View File

@ -16,34 +16,67 @@ namespace SpotifyAPIv1
public int length { get; set; } public int length { get; set; }
public string track_type { get; set; } public string track_type { get; set; }
/// <summary>
/// Returns the track name
/// </summary>
/// <returns>A String. which is the track name</returns>
public String GetTrackName() public String GetTrackName()
{ {
return track_resource.name; return track_resource.name;
} }
/// <summary>
/// Returns the track lenght
/// </summary>
/// <returns>A integer, which is the track length</returns>
public int GetLength() public int GetLength()
{ {
return length; return length;
} }
/// <summary>
/// Returns the URI for the album
/// </summary>
/// <returns>A String, which is the album URI</returns>
public String GetAlbumURI() public String GetAlbumURI()
{ {
return album_resource.uri; return album_resource.uri;
} }
/// <summary>
/// Returns the URI for the track
/// </summary>
/// <returns>A String, which is the track URI</returns>
public String GetTrackURI() public String GetTrackURI()
{ {
return track_resource.uri; return track_resource.uri;
} }
/// <summary>
/// Returns the URI for the artist
/// </summary>
/// <returns>A String, which is the artist URI</returns>
public String GetArtistURI() public String GetArtistURI()
{ {
return artist_resource.uri; return artist_resource.uri;
} }
/// <summary>
/// Returns the albume name
/// </summary>
/// <returns>A String, which is the album name</returns>
public String GetAlbumName() public String GetAlbumName()
{ {
return album_resource.name; return album_resource.name;
} }
/// <summary>
/// Returns the artist name
/// </summary>
/// <returns>A String, which is the artist name</returns>
public String GetArtistName() public String GetArtistName()
{ {
return artist_resource.name; return artist_resource.name;
} }
/// <summary>
/// Returns a URL to the album cover in the provided size
/// </summary>
/// <param name="size">AlbumArtSize (160,320,640)</param>
/// <returns>A String, which is the URL to the Albumart</returns>
public String GetAlbumArtURL(AlbumArtSize size) public String GetAlbumArtURL(AlbumArtSize size)
{ {
if (album_resource.uri.Contains("local")) if (album_resource.uri.Contains("local"))
@ -79,6 +112,11 @@ namespace SpotifyAPIv1
} }
return ""; return "";
} }
/// <summary>
/// Returns a Bitmap of the album cover in the provided size asynchronous
/// </summary>
/// <param name="size">AlbumArtSize (160,320,640)</param>
/// <returns>A Bitmap, which is the albumart</returns>
public async Task<Bitmap> GetAlbumArtAsync(AlbumArtSize size) public async Task<Bitmap> GetAlbumArtAsync(AlbumArtSize size)
{ {
using (WebClient wc = new WebClient()) using (WebClient wc = new WebClient())
@ -102,6 +140,11 @@ namespace SpotifyAPIv1
} }
} }
} }
/// <summary>
/// Returns a Bitmap of the album cover in the provided size
/// </summary>
/// <param name="size">AlbumArtSize (160,320,640)</param>
/// <returns>A Bitmap, which is the albumart</returns>
public Bitmap GetAlbumArt(AlbumArtSize size) public Bitmap GetAlbumArt(AlbumArtSize size)
{ {
using(WebClient wc = new WebClient()) using(WebClient wc = new WebClient())

View File

@ -106,7 +106,7 @@ namespace SpotifyAPI_Example
private void button5_Click(object sender, EventArgs e) private void button5_Click(object sender, EventArgs e)
{ {
if (SpotifyAPI.IsValidSpotifyURL(textBox1.Text)) if (SpotifyAPI.IsValidSpotifyURI(textBox1.Text))
mh.PlayURL(textBox1.Text); mh.PlayURL(textBox1.Text);
} }