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

75 lines
1.9 KiB
Plaintext

@page "/"
@using SpotifyAPI.Web
@using System
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
@inject NavigationManager navManager
<h1>Hello, world!</h1>
<p>SPOTIFY_CLIENT_ID: @(Configuration["SPOTIFY_CLIENT_ID"] ?? "Not set, example won't work")</p>
<p>
</p>
@if (_isAuthed && _me != null)
{
<h2>Welcome @_me.DisplayName!</h2>
<p>
You have a grant total of @_totalPlaylistCount playlists!
</p>
}
else
{
<span>To get started:</span>
<a href="@_authUri">
Login via Spotify
</a>
}
@code {
private bool _isAuthed = false;
private PrivateUser _me;
private int? _totalPlaylistCount;
private Uri _authUri;
protected override void OnInitialized()
{
if (!string.IsNullOrEmpty(Configuration["SPOTIFY_CLIENT_ID"]))
{
var baseUri = navManager.ToAbsoluteUri(navManager.BaseUri);
var loginRequest = new LoginRequest(baseUri, Configuration["SPOTIFY_CLIENT_ID"], LoginRequest.ResponseType.Token)
{
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>();
Console.WriteLine(fragmentParams);
_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;
}
}
}