Merge branch 'master' of github.com:JohnnyCrazy/SpotifyAPI-NET

This commit is contained in:
Jonas Dellinger 2018-09-21 14:45:22 +02:00
commit 70a57579cf
5 changed files with 135 additions and 92 deletions

View File

@ -5,26 +5,26 @@ SpotifyAPI-NET
[![Nuget](https://badge.fury.io/nu/SpotifyAPI-NET.svg)](https://www.nuget.org/packages/SpotifyAPI-NET/) [![Nuget](https://badge.fury.io/nu/SpotifyAPI-NET.svg)](https://www.nuget.org/packages/SpotifyAPI-NET/)
[![Gitter](https://img.shields.io/gitter/room/SpotifyAPI-NET/Lobby.svg)](https://gitter.im/SpotifyAPI-NET/Lobby) [![Gitter](https://img.shields.io/gitter/room/SpotifyAPI-NET/Lobby.svg)](https://gitter.im/SpotifyAPI-NET/Lobby)
An API for the Spotify-Client and Spotify's Web API, written in .NET A Wrapper for Spotify's Web API, written in .NET
**Spotify's Web API** ([link](https://developer.spotify.com/web-api/)) **Spotify's Web API** ([link](https://developer.spotify.com/web-api/))
> Based on simple REST principles, our Web API endpoints return metadata in JSON format about artists, albums, and tracks directly from the Spotify catalogue. > Based on simple REST principles, our Web API endpoints return metadata in JSON format about artists, albums, and tracks directly from the Spotify catalogue.
> The API also provides access to user-related data such as playlists and music saved in a “Your Music” library, subject to users authorization. > The API also provides access to user-related data such as playlists and music saved in a “Your Music” library, subject to users authorization.
**Spotify's *unofficial* Local API**
> Do you ever wanted to control your local Spotify Client with some sort of API? Now you can! This API gives you full control over your spotify client.
> You can get infos about the currently playing song, get its Album-Art, skip/pause and much more. It also features multiple Event-Interfaces.
### Docs and Usage ### Docs and Usage
More Information, Installation-Instructions, Examples and API-Reference can be found at [github.io/SpotifyAPI-Net/](http://johnnycrazy.github.io/SpotifyAPI-NET/) More Information, Installation-Instructions, Examples and API-Reference can be found at [github.io/SpotifyAPI-Net/](http://johnnycrazy.github.io/SpotifyAPI-NET/)
### NuGet ### NuGet
You can add the API to your project via [nuget-package](https://www.nuget.org/packages/SpotifyAPI-NET/): You can add the API to your project via [nuget-package](https://www.nuget.org/packages/SpotifyAPI.Web/):
``` ```
Install-Package SpotifyAPI-NET Install-Package SpotifyAPI.Web
Install-Package SpotifyAPI.Web.Auth
//or //or
Install-Package SpotifyAPI-Net -pre
Install-Package SpotifyAPI.Web -pre
Install-Package SpotifyAPI.Web.Auth -pre
``` ```
### Example ### Example

View File

@ -1,4 +1,5 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using SpotifyAPI.Web.Enums;
using System; using System;
using System.Net; using System.Net;

View File

@ -1,4 +1,5 @@
using System.Net; using SpotifyAPI.Web.Enums;
using System.Net;
namespace SpotifyAPI.Web.Models namespace SpotifyAPI.Web.Models
{ {

View File

@ -1,4 +1,4 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using SpotifyAPI.Web.Enums; using SpotifyAPI.Web.Enums;
using SpotifyAPI.Web.Models; using SpotifyAPI.Web.Models;
@ -23,15 +23,14 @@ namespace SpotifyAPI.Web
{ {
_builder = new SpotifyWebBuilder(); _builder = new SpotifyWebBuilder();
UseAuth = true; UseAuth = true;
WebClient = new SpotifyWebClient WebClient = new SpotifyWebClient(proxyConfig)
{ {
JsonSettings = JsonSettings =
new JsonSerializerSettings new JsonSerializerSettings
{ {
NullValueHandling = NullValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore,
TypeNameHandling = TypeNameHandling.All TypeNameHandling = TypeNameHandling.All
}, }
ProxyConfig = proxyConfig
}; };
} }
@ -79,6 +78,11 @@ namespace SpotifyAPI.Web
/// </summary> /// </summary>
public int RetryTimes { get; set; } = 10; public int RetryTimes { get; set; } = 10;
/// <summary>
/// Whether a failure of type "Too Many Requests" should use up one of the allocated retry attempts.
/// </summary>
public bool TooManyRequestsConsumesARetry { get; set; } = false;
/// <summary> /// <summary>
/// Error codes that will trigger auto-retry if <see cref="UseAutoRetry"/> is enabled. /// Error codes that will trigger auto-retry if <see cref="UseAutoRetry"/> is enabled.
/// </summary> /// </summary>
@ -2002,10 +2006,11 @@ namespace SpotifyAPI.Web
/// <param name="contextUri">Spotify URI of the context to play.</param> /// <param name="contextUri">Spotify URI of the context to play.</param>
/// <param name="uris">A JSON array of the Spotify track URIs to play.</param> /// <param name="uris">A JSON array of the Spotify track URIs to play.</param>
/// <param name="offset">Indicates from where in the context playback should start. /// <param name="offset">Indicates from where in the context playback should start.
/// <param name="positionMs">The starting time to seek the track to</param>
/// Only available when context_uri corresponds to an album or playlist object, or when the uris parameter is used.</param> /// Only available when context_uri corresponds to an album or playlist object, or when the uris parameter is used.</param>
/// <returns></returns> /// <returns></returns>
public ErrorResponse ResumePlayback(string deviceId = "", string contextUri = "", List<string> uris = null, public ErrorResponse ResumePlayback(string deviceId = "", string contextUri = "", List<string> uris = null,
int? offset = null) int? offset = null, int positionMs = 0)
{ {
JObject ob = new JObject(); JObject ob = new JObject();
if(!string.IsNullOrEmpty(contextUri)) if(!string.IsNullOrEmpty(contextUri))
@ -2014,6 +2019,8 @@ namespace SpotifyAPI.Web
ob.Add("uris", new JArray(uris)); ob.Add("uris", new JArray(uris));
if(offset != null) if(offset != null)
ob.Add("offset", new JObject { { "position", offset } }); ob.Add("offset", new JObject { { "position", offset } });
if (positionMs > 0)
ob.Add("position_ms", positionMs);
return UploadData<ErrorResponse>(_builder.ResumePlayback(deviceId), ob.ToString(Formatting.None), "PUT"); return UploadData<ErrorResponse>(_builder.ResumePlayback(deviceId), ob.ToString(Formatting.None), "PUT");
} }
@ -2024,10 +2031,11 @@ namespace SpotifyAPI.Web
/// <param name="contextUri">Spotify URI of the context to play.</param> /// <param name="contextUri">Spotify URI of the context to play.</param>
/// <param name="uris">A JSON array of the Spotify track URIs to play.</param> /// <param name="uris">A JSON array of the Spotify track URIs to play.</param>
/// <param name="offset">Indicates from where in the context playback should start. /// <param name="offset">Indicates from where in the context playback should start.
/// <param name="positionMs">The starting time to seek the track to</param>
/// Only available when context_uri corresponds to an album or playlist object, or when the uris parameter is used.</param> /// Only available when context_uri corresponds to an album or playlist object, or when the uris parameter is used.</param>
/// <returns></returns> /// <returns></returns>
public Task<ErrorResponse> ResumePlaybackAsync(string deviceId = "", string contextUri = "", List<string> uris = null, public Task<ErrorResponse> ResumePlaybackAsync(string deviceId = "", string contextUri = "", List<string> uris = null,
int? offset = null) int? offset = null, int positionMs = 0)
{ {
JObject ob = new JObject(); JObject ob = new JObject();
if (!string.IsNullOrEmpty(contextUri)) if (!string.IsNullOrEmpty(contextUri))
@ -2036,6 +2044,8 @@ namespace SpotifyAPI.Web
ob.Add("uris", new JArray(uris)); ob.Add("uris", new JArray(uris));
if (offset != null) if (offset != null)
ob.Add("offset", new JObject { { "position", offset } }); ob.Add("offset", new JObject { { "position", offset } });
if (positionMs > 0)
ob.Add("position_ms", positionMs);
return UploadDataAsync<ErrorResponse>(_builder.ResumePlayback(deviceId), ob.ToString(Formatting.None), "PUT"); return UploadDataAsync<ErrorResponse>(_builder.ResumePlayback(deviceId), ob.ToString(Formatting.None), "PUT");
} }
@ -2046,10 +2056,11 @@ namespace SpotifyAPI.Web
/// <param name="contextUri">Spotify URI of the context to play.</param> /// <param name="contextUri">Spotify URI of the context to play.</param>
/// <param name="uris">A JSON array of the Spotify track URIs to play.</param> /// <param name="uris">A JSON array of the Spotify track URIs to play.</param>
/// <param name="offset">Indicates from where in the context playback should start. /// <param name="offset">Indicates from where in the context playback should start.
/// <param name="positionMs">The starting time to seek the track to</param>
/// Only available when context_uri corresponds to an album or playlist object, or when the uris parameter is used.</param> /// Only available when context_uri corresponds to an album or playlist object, or when the uris parameter is used.</param>
/// <returns></returns> /// <returns></returns>
public ErrorResponse ResumePlayback(string deviceId = "", string contextUri = "", List<string> uris = null, public ErrorResponse ResumePlayback(string deviceId = "", string contextUri = "", List<string> uris = null,
string offset = "") string offset = "", int positionMs = 0)
{ {
JObject ob = new JObject(); JObject ob = new JObject();
if (!string.IsNullOrEmpty(contextUri)) if (!string.IsNullOrEmpty(contextUri))
@ -2058,6 +2069,8 @@ namespace SpotifyAPI.Web
ob.Add("uris", new JArray(uris)); ob.Add("uris", new JArray(uris));
if (!string.IsNullOrEmpty(offset)) if (!string.IsNullOrEmpty(offset))
ob.Add("offset", new JObject {{"uri", offset}}); ob.Add("offset", new JObject {{"uri", offset}});
if (positionMs > 0)
ob.Add("position_ms", positionMs);
return UploadData<ErrorResponse>(_builder.ResumePlayback(deviceId), ob.ToString(Formatting.None), "PUT"); return UploadData<ErrorResponse>(_builder.ResumePlayback(deviceId), ob.ToString(Formatting.None), "PUT");
} }
@ -2068,10 +2081,11 @@ namespace SpotifyAPI.Web
/// <param name="contextUri">Spotify URI of the context to play.</param> /// <param name="contextUri">Spotify URI of the context to play.</param>
/// <param name="uris">A JSON array of the Spotify track URIs to play.</param> /// <param name="uris">A JSON array of the Spotify track URIs to play.</param>
/// <param name="offset">Indicates from where in the context playback should start. /// <param name="offset">Indicates from where in the context playback should start.
/// <param name="positionMs">The starting time to seek the track to</param>
/// Only available when context_uri corresponds to an album or playlist object, or when the uris parameter is used.</param> /// Only available when context_uri corresponds to an album or playlist object, or when the uris parameter is used.</param>
/// <returns></returns> /// <returns></returns>
public Task<ErrorResponse> ResumePlaybackAsync(string deviceId = "", string contextUri = "", List<string> uris = null, public Task<ErrorResponse> ResumePlaybackAsync(string deviceId = "", string contextUri = "", List<string> uris = null,
string offset = "") string offset = "", int positionMs = 0)
{ {
JObject ob = new JObject(); JObject ob = new JObject();
if (!string.IsNullOrEmpty(contextUri)) if (!string.IsNullOrEmpty(contextUri))
@ -2080,6 +2094,8 @@ namespace SpotifyAPI.Web
ob.Add("uris", new JArray(uris)); ob.Add("uris", new JArray(uris));
if (!string.IsNullOrEmpty(offset)) if (!string.IsNullOrEmpty(offset))
ob.Add("offset", new JObject { { "uri", offset } }); ob.Add("offset", new JObject { { "uri", offset } });
if (positionMs > 0)
ob.Add("position_ms", positionMs);
return UploadDataAsync<ErrorResponse>(_builder.ResumePlayback(deviceId), ob.ToString(Formatting.None), "PUT"); return UploadDataAsync<ErrorResponse>(_builder.ResumePlayback(deviceId), ob.ToString(Formatting.None), "PUT");
} }
@ -2434,6 +2450,26 @@ namespace SpotifyAPI.Web
return response.Item2; return response.Item2;
} }
/// <summary>
/// Retrieves whether request had a "TooManyRequests" error, and get the amount Spotify recommends waiting before another request.
/// </summary>
/// <param name="info">Info object to analyze.</param>
/// <returns>Seconds to wait before making another request. -1 if no error.</returns>
/// <remarks>AUTH NEEDED</remarks>
private int GetTooManyRequests(ResponseInfo info)
{
// 429 is "TooManyRequests" value specified in Spotify API
if (429 != (int)info.StatusCode)
{
return -1;
}
if (!int.TryParse(info.Headers.Get("Retry-After"), out var secondsToWait))
{
return -1;
}
return secondsToWait;
}
public async Task<T> DownloadDataAsync<T>(string url) where T : BasicModel public async Task<T> DownloadDataAsync<T>(string url) where T : BasicModel
{ {
int triesLeft = RetryTimes + 1; int triesLeft = RetryTimes + 1;
@ -2442,15 +2478,30 @@ namespace SpotifyAPI.Web
Tuple<ResponseInfo, T> response = null; Tuple<ResponseInfo, T> response = null;
do do
{ {
if (response != null) { await Task.Delay(RetryAfter).ConfigureAwait(false); } if (response != null)
{
int msToWait = RetryAfter;
var secondsToWait = GetTooManyRequests(response.Item1);
if (secondsToWait > 0)
{
msToWait = secondsToWait * 1000;
}
await Task.Delay(msToWait).ConfigureAwait(false);
}
response = await DownloadDataAltAsync<T>(url).ConfigureAwait(false); response = await DownloadDataAltAsync<T>(url).ConfigureAwait(false);
response.Item2.AddResponseInfo(response.Item1); response.Item2.AddResponseInfo(response.Item1);
lastError = response.Item2.Error; lastError = response.Item2.Error;
triesLeft -= 1; if (TooManyRequestsConsumesARetry || GetTooManyRequests(response.Item1) == -1)
{
triesLeft -= 1;
}
} while (UseAutoRetry && triesLeft > 0 && lastError != null && RetryErrorCodes.Contains(lastError.Status)); } while (UseAutoRetry
&& triesLeft > 0
&& (GetTooManyRequests(response.Item1) != -1
|| (lastError != null && RetryErrorCodes.Contains(lastError.Status))));
return response.Item2; return response.Item2;

View File

@ -1,4 +1,4 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
@ -7,16 +7,21 @@ using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using SpotifyAPI.Web.Models; using SpotifyAPI.Web.Models;
using SpotifyAPI.Web.Enums;
namespace SpotifyAPI.Web namespace SpotifyAPI.Web
{ {
internal class SpotifyWebClient : IClient internal class SpotifyWebClient : IClient
{ {
public JsonSerializerSettings JsonSettings { get; set; } public JsonSerializerSettings JsonSettings { get; set; }
public ProxyConfig ProxyConfig { get; set; }
private readonly Encoding _encoding = Encoding.UTF8; private readonly Encoding _encoding = Encoding.UTF8;
private readonly HttpClient _client;
public SpotifyWebClient(ProxyConfig proxyConfig = null)
{
HttpClientHandler clientHandler = CreateClientHandler(proxyConfig);
_client = new HttpClient(clientHandler);
}
public Tuple<ResponseInfo, string> Download(string url, Dictionary<string, string> headers = null) public Tuple<ResponseInfo, string> Download(string url, Dictionary<string, string> headers = null)
{ {
@ -32,47 +37,39 @@ namespace SpotifyAPI.Web
public Tuple<ResponseInfo, byte[]> DownloadRaw(string url, Dictionary<string, string> headers = null) public Tuple<ResponseInfo, byte[]> DownloadRaw(string url, Dictionary<string, string> headers = null)
{ {
HttpClientHandler clientHandler = CreateClientHandler(ProxyConfig); if (headers != null)
using (HttpClient client = new HttpClient(clientHandler))
{ {
if (headers != null) foreach (KeyValuePair<string, string> headerPair in headers)
{ {
foreach (KeyValuePair<string, string> headerPair in headers) _client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
{
client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
}
} }
using (HttpResponseMessage response = Task.Run(() => client.GetAsync(url)).Result) }
using (HttpResponseMessage response = Task.Run(() => _client.GetAsync(url)).Result)
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo
{ {
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo StatusCode = response.StatusCode,
{ Headers = ConvertHeaders(response.Headers)
StatusCode = response.StatusCode, }, Task.Run(() => response.Content.ReadAsByteArrayAsync()).Result);
Headers = ConvertHeaders(response.Headers)
}, Task.Run(() => response.Content.ReadAsByteArrayAsync()).Result);
}
} }
} }
public async Task<Tuple<ResponseInfo, byte[]>> DownloadRawAsync(string url, Dictionary<string, string> headers = null) public async Task<Tuple<ResponseInfo, byte[]>> DownloadRawAsync(string url, Dictionary<string, string> headers = null)
{ {
HttpClientHandler clientHandler = CreateClientHandler(ProxyConfig); if (headers != null)
using (HttpClient client = new HttpClient(clientHandler))
{ {
if (headers != null) foreach (KeyValuePair<string, string> headerPair in headers)
{ {
foreach (KeyValuePair<string, string> headerPair in headers) _client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
{
client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
}
} }
using (HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false)) }
using (HttpResponseMessage response = await _client.GetAsync(url).ConfigureAwait(false))
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo
{ {
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo StatusCode = response.StatusCode,
{ Headers = ConvertHeaders(response.Headers)
StatusCode = response.StatusCode, }, await response.Content.ReadAsByteArrayAsync());
Headers = ConvertHeaders(response.Headers)
}, await response.Content.ReadAsByteArrayAsync());
}
} }
} }
@ -102,57 +99,49 @@ namespace SpotifyAPI.Web
public Tuple<ResponseInfo, byte[]> UploadRaw(string url, string body, string method, Dictionary<string, string> headers = null) public Tuple<ResponseInfo, byte[]> UploadRaw(string url, string body, string method, Dictionary<string, string> headers = null)
{ {
HttpClientHandler clientHandler = CreateClientHandler(ProxyConfig); if (headers != null)
using (HttpClient client = new HttpClient(clientHandler))
{ {
if (headers != null) foreach (KeyValuePair<string, string> headerPair in headers)
{ {
foreach (KeyValuePair<string, string> headerPair in headers) _client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
{
client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
}
} }
}
HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(method), url) HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(method), url)
{
Content = new StringContent(body, _encoding)
};
using (HttpResponseMessage response = Task.Run(() => _client.SendAsync(message)).Result)
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo
{ {
Content = new StringContent(body, _encoding) StatusCode = response.StatusCode,
}; Headers = ConvertHeaders(response.Headers)
using (HttpResponseMessage response = Task.Run(() => client.SendAsync(message)).Result) }, Task.Run(() => response.Content.ReadAsByteArrayAsync()).Result);
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo
{
StatusCode = response.StatusCode,
Headers = ConvertHeaders(response.Headers)
}, Task.Run(() => response.Content.ReadAsByteArrayAsync()).Result);
}
} }
} }
public async Task<Tuple<ResponseInfo, byte[]>> UploadRawAsync(string url, string body, string method, Dictionary<string, string> headers = null) public async Task<Tuple<ResponseInfo, byte[]>> UploadRawAsync(string url, string body, string method, Dictionary<string, string> headers = null)
{ {
HttpClientHandler clientHandler = CreateClientHandler(ProxyConfig); if (headers != null)
using (HttpClient client = new HttpClient(clientHandler))
{ {
if (headers != null) foreach (KeyValuePair<string, string> headerPair in headers)
{ {
foreach (KeyValuePair<string, string> headerPair in headers) _client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
{
client.DefaultRequestHeaders.TryAddWithoutValidation(headerPair.Key, headerPair.Value);
}
} }
}
HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(method), url) HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(method), url)
{
Content = new StringContent(body, _encoding)
};
using (HttpResponseMessage response = await _client.SendAsync(message))
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo
{ {
Content = new StringContent(body, _encoding) StatusCode = response.StatusCode,
}; Headers = ConvertHeaders(response.Headers)
using (HttpResponseMessage response = await client.SendAsync(message)) }, await response.Content.ReadAsByteArrayAsync());
{
return new Tuple<ResponseInfo, byte[]>(new ResponseInfo
{
StatusCode = response.StatusCode,
Headers = ConvertHeaders(response.Headers)
}, await response.Content.ReadAsByteArrayAsync());
}
} }
} }
@ -170,6 +159,7 @@ namespace SpotifyAPI.Web
public void Dispose() public void Dispose()
{ {
_client.Dispose();
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }