Spotify.NET/SpotifyAPI.Web.Examples/Example.CLI.PersistentConfig/Program.cs

110 lines
3.4 KiB
C#
Raw Normal View History

2020-05-15 19:06:24 +01:00
using System;
using System.Collections.Generic;
2022-11-27 12:29:35 +00:00
using System.IO;
using System.Threading.Tasks;
2020-05-15 19:06:24 +01:00
using Newtonsoft.Json;
2022-11-27 12:29:35 +00:00
using SpotifyAPI.Web;
using SpotifyAPI.Web.Auth;
using static SpotifyAPI.Web.Scopes;
2020-05-15 19:06:24 +01:00
2020-05-16 21:31:44 +01:00
namespace Example.CLI.PersistentConfig
2020-05-15 19:06:24 +01:00
{
/// <summary>
/// This is a basic example how to get user access using the Auth package and a CLI Program
/// Your spotify app needs to have http://localhost:5543 as redirect uri whitelisted
2020-05-15 19:06:24 +01:00
/// </summary>
public class Program
{
private const string CredentialsPath = "credentials.json";
2020-05-25 17:00:38 +01:00
private static readonly string? clientId = Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_ID");
private static readonly EmbedIOAuthServer _server = new(new Uri("http://localhost:5543/callback"), 5543);
private static void Exiting()
{
Console.CursorVisible = true;
}
2020-05-15 19:06:24 +01:00
public static async Task<int> Main()
{
// This is a bug in the SWAN Logging library, need this hack to bring back the cursor
AppDomain.CurrentDomain.ProcessExit += (sender, e) => Exiting();
if (string.IsNullOrEmpty(clientId))
2020-05-25 17:00:38 +01:00
{
throw new NullReferenceException(
"Please set SPOTIFY_CLIENT_ID via environment variables before starting the program"
2020-05-25 17:00:38 +01:00
);
}
2020-05-15 19:06:24 +01:00
if (File.Exists(CredentialsPath))
{
await Start();
}
else
{
await StartAuthentication();
}
_ = Console.ReadKey();
2020-05-15 19:06:24 +01:00
return 0;
}
private static async Task Start()
{
var json = await File.ReadAllTextAsync(CredentialsPath);
var token = JsonConvert.DeserializeObject<PKCETokenResponse>(json);
2020-05-15 19:06:24 +01:00
var authenticator = new PKCEAuthenticator(clientId!, token!);
2020-05-15 19:06:24 +01:00
authenticator.TokenRefreshed += (sender, token) => File.WriteAllText(CredentialsPath, JsonConvert.SerializeObject(token));
var config = SpotifyClientConfig.CreateDefault()
.WithAuthenticator(authenticator);
var spotify = new SpotifyClient(config);
var me = await spotify.UserProfile.Current();
2020-09-07 08:02:57 +01:00
Console.WriteLine($"Welcome {me.DisplayName} ({me.Id}), you're authenticated!");
2020-05-15 19:06:24 +01:00
var playlists = await spotify.PaginateAll(await spotify.Playlists.CurrentUsers().ConfigureAwait(false));
2020-05-15 19:06:24 +01:00
Console.WriteLine($"Total Playlists in your Account: {playlists.Count}");
_server.Dispose();
2020-05-15 19:06:24 +01:00
Environment.Exit(0);
}
private static async Task StartAuthentication()
{
var (verifier, challenge) = PKCEUtil.GenerateCodes();
2020-05-15 19:06:24 +01:00
await _server.Start();
_server.AuthorizationCodeReceived += async (sender, response) =>
{
await _server.Stop();
var token = await new OAuthClient().RequestToken(
new PKCETokenRequest(clientId!, response.Code, _server.BaseUri, verifier)
);
await File.WriteAllTextAsync(CredentialsPath, JsonConvert.SerializeObject(token));
await Start();
};
2020-05-15 19:06:24 +01:00
2020-05-25 17:00:38 +01:00
var request = new LoginRequest(_server.BaseUri, clientId!, LoginRequest.ResponseType.Code)
2020-05-15 19:06:24 +01:00
{
CodeChallenge = challenge,
CodeChallengeMethod = "S256",
Scope = new List<string> { UserReadEmail, UserReadPrivate, PlaylistReadPrivate, PlaylistReadCollaborative }
2020-05-15 19:06:24 +01:00
};
var uri = request.ToUri();
2020-05-15 19:06:24 +01:00
try
{
BrowserUtil.Open(uri);
2020-05-15 19:06:24 +01:00
}
catch (Exception)
{
Console.WriteLine("Unable to open URL, manually open: {0}", uri);
2020-05-15 19:06:24 +01:00
}
}
}
}