forked from JohnnyCrazy/SpotifyAPI-NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpotifyAuthServer.cs
More file actions
88 lines (72 loc) · 2.61 KB
/
SpotifyAuthServer.cs
File metadata and controls
88 lines (72 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using EmbedIO;
using EmbedIO.WebApi;
using SpotifyAPI.Web.Enums;
using Swan.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web;
namespace SpotifyAPI.Web.Auth;
public abstract class SpotifyAuthServer<T> : Auth
{
private readonly string _folder;
private readonly string _type;
private WebServer _server;
private CancellationTokenSource _serverSource;
#pragma warning disable IDE1006 // Naming Styles
internal static readonly Dictionary<string, SpotifyAuthServer<T>> Instances = [];
#pragma warning restore IDE1006 // Naming Styles
private protected SpotifyAuthServer(string type, string folder, string redirectUri, string serverUri, Scope scope = Scope.None, string state = "")
{
_type = type;
_folder = folder;
ServerUri = serverUri;
RedirectUri = redirectUri;
Scope = scope;
State = string.IsNullOrEmpty(state) ? string.Join("", Guid.NewGuid().ToString("n").Take(8)) : state;
}
public override void Start()
{
Logger.NoLogging();
Instances.Add(State, this);
_serverSource = new CancellationTokenSource();
_server = new WebServer(ServerUri);
var webApiModule = new WebApiModule("/");
_server.WithModule(webApiModule);
AdaptModule(webApiModule);
_server.WithEmbeddedResources("/", Assembly.GetExecutingAssembly(), $"SpotifyAPI.Web.Auth.Resources.{_folder}");
_ = _server.RunAsync(_serverSource.Token);
}
public virtual string GetUri()
{
var queryValues = HttpUtility.ParseQueryString(string.Empty);
queryValues.Add("client_id", ClientId);
queryValues.Add("response_type", _type);
queryValues.Add("redirect_uri", RedirectUri);
queryValues.Add("state", State);
queryValues.Add("scope", Scope.GetStringAttribute(" "));
queryValues.Add("show_dialog", ShowDialog.ToString());
return "https://accounts.spotify.com/authorize/?" + queryValues;
}
public override void Stop(int delay = 2000)
{
if (_serverSource == null)
return;
_serverSource.CancelAfter(delay);
_serverSource.Dispose();
_server.Dispose();
Instances.Remove(State);
}
public override void OpenBrowser()
{
var uri = GetUri();
AuthUtil.OpenBrowser(uri);
}
internal static SpotifyAuthServer<T> GetByState(string state)
{
return Instances.TryGetValue(state, out var auth) ? auth : null;
}
protected abstract void AdaptModule(WebApiModule webApiModule);
}