Spotify.NET/SpotifyAPI.Web.Examples/Example.ASPBlazor/Pages/Index.razor

62 lines
1.6 KiB
Plaintext
Raw Normal View History

2020-05-22 12:53:58 +01:00
@page "/"
@inject NavigationManager navManager
@using SpotifyAPI.Web
2020-05-22 11:23:25 +01:00
<h1>Hello, world!</h1>
2020-05-22 12:53:58 +01:00
@if (_isAuthed && _me != null)
{
<h2>Welcome @_me.DisplayName!</h2>
<p>
2020-06-04 13:42:16 +01:00
You have a grant total of @_totalPlaylistCount playlists!
2020-05-22 12:53:58 +01:00
</p>
}
else
{
<span>To get started:</span>
<a href="@_authUri">
Login via Spotify
</a>
}
2020-05-22 11:23:25 +01:00
2020-05-22 12:53:58 +01:00
@code {
2020-06-04 13:42:16 +01:00
private Uri _authUri;
2020-05-22 12:53:58 +01:00
2020-06-04 13:42:16 +01:00
private bool _isAuthed;
2020-05-22 12:53:58 +01:00
2020-06-04 13:42:16 +01:00
private PrivateUser _me;
2020-05-22 12:53:58 +01:00
2020-06-04 13:42:16 +01:00
private int _totalPlaylistCount;
2020-05-22 12:53:58 +01:00
2020-06-04 13:42:16 +01:00
protected override void OnInitialized()
{
var clientId = Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_ID");
var baseUri = navManager.ToAbsoluteUri(navManager.BaseUri);
2020-05-22 12:53:58 +01:00
2020-06-04 13:42:16 +01:00
var loginRequest = new LoginRequest(baseUri, clientId, LoginRequest.ResponseType.Token)
2020-05-22 12:53:58 +01:00
{
2020-06-04 13:42:16 +01:00
Scope = new[] { Scopes.PlaylistReadPrivate, Scopes.PlaylistReadCollaborative }
};
_authUri = loginRequest.ToUri();
}
protected override async Task OnInitializedAsync()
{
var uri = new Uri(navManager.Uri);
var maxLen = Math.Min(1, uri.Fragment.Length);
Dictionary<string, string> fragmentParams = uri.Fragment.Substring(maxLen)?
.Split("&", StringSplitOptions.RemoveEmptyEntries)?
.Select(param => param.Split("=", StringSplitOptions.RemoveEmptyEntries))?
.ToDictionary(param => param[0], param => param[1]) ?? new Dictionary<string, string>();
_isAuthed = fragmentParams.ContainsKey("access_token");
if (_isAuthed)
{
var spotify = new SpotifyClient(fragmentParams["access_token"]);
_me = await spotify.UserProfile.Current();
_totalPlaylistCount = (await spotify.Playlists.CurrentUsers()).Total;
2020-05-22 12:53:58 +01:00
}
2020-06-04 13:42:16 +01:00
}
2020-05-22 12:53:58 +01:00
}