-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpotifyController.cs
More file actions
64 lines (58 loc) · 2.58 KB
/
SpotifyController.cs
File metadata and controls
64 lines (58 loc) · 2.58 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
using System.Diagnostics;
using System.Net;
using SpotifyAPI.Web;
namespace SpotifyCSG;
public class SpotifyController
{
private SpotifyClient? _spotifyClient;
private readonly string _clientId = "10e5c1cbbad546e39ef558e1aa4c03f4";
private readonly Uri _redirectUri = new Uri("http://127.0.0.1:5543/");
public async Task TrySetVolume(int vol)
{
try
{
await _spotifyClient?.Player.SetVolume(new PlayerVolumeRequest(vol))!;
}
catch (Exception ignored)
{
Console.WriteLine(ignored.Message);
}
}
public async Task CreateSpotify()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add(_redirectUri.ToString());
listener.Start();
var (verifier, challenge) = PKCEUtil.GenerateCodes(120);
var loginRequest = new LoginRequest(_redirectUri, _clientId, LoginRequest.ResponseType.Code)
{
CodeChallengeMethod = "S256", CodeChallenge = challenge, Scope = [Scopes.UserModifyPlaybackState]
};
Console.WriteLine($"Authorization for Spotify needed! If your browser doesn't open, manually open this link to sign in.\n{loginRequest.ToUri().ToString()}");
Process.Start(new ProcessStartInfo { FileName = loginRequest.ToUri().ToString(), UseShellExecute = true });
while (true)
{
var context = await listener.GetContextAsync();
var request = context.Request;
var response = context.Response;
if (request.HttpMethod == "GET" && request.QueryString["code"] != null)
{
var code = request.QueryString["code"]!;
var initialResponse = await new OAuthClient().RequestToken(
new PKCETokenRequest(_clientId, code, _redirectUri, verifier));
var authenticator = new PKCEAuthenticator(_clientId, initialResponse);
var config = SpotifyClientConfig.CreateDefault().WithAuthenticator(authenticator);
_spotifyClient = new SpotifyClient(config);
Console.WriteLine($"Hello {_spotifyClient.UserProfile.Current().Result.DisplayName}.");
// Send a response back to the browser
var buffer = "Authentication successful! You can close this window."u8.ToArray();
response.ContentLength64 = buffer.Length;
await response.OutputStream.WriteAsync(buffer);
listener.Close();
break;
}
response.StatusCode = 400; // Bad Request
response.Close();
}
}
}