public ActionResult EditPrivUser(PrivateUser user) { user.UserName = user.Email; db.Users.AddOrUpdate(user); db.SaveChanges(); return(RedirectToAction("Index")); }
public async void Start() { try { _authenticator = new PKCEAuthenticator(_clientId !, TokenResponse); var config = SpotifyClientConfig.CreateDefault() .WithAuthenticator(_authenticator); _spotifyClient = new SpotifyClient(config); var user = await _spotifyClient.UserProfile.Current(); //var playlists = await _spotifyClient.Playlists.GetUsers(user.Id); _user = user; //UserPlaylists = playlists; if (user.Product == "premium") { IsPremiumUser = true; } OnLoggedIn?.Invoke(_user, TokenResponse); _stateThread = new Thread(StateUpdateTimer); _stateThread.Start(); } catch (Exception e) { //We will just ignore for now, this should be handled better though } }
public async void Start() { _loadParent.gameObject.SetActive(true); _headerParent.gameObject.SetActive(false); _songsParent.gameObject.SetActive(false); SpotifyClient client = SpotifyService.Instance.GetSpotifyClient(); if (client != null) { Paging <SavedTrack> paging = await client.Library.GetTracks(); // Load all saved tracks _allSavedTracks = await S4UUtility.GetAllOfPagingAsync(client, paging, MaximumLength) as List <SavedTrack>; // Only show cwer if (_allSavedTracks.Count > MaximumLength) { _allSavedTracks.RemoveRange(MaximumLength, (_allSavedTracks.Count - 1) - MaximumLength); } // Load current user to display creator PrivateUser profile = await SpotifyService.Instance.GetSpotifyClient().UserProfile.Current(); _creator = profile.DisplayName; _dispatcher.Add(() => { UpdateUI(); }); } }
private void Start() { Log.Instance.PrintMessage("Trying to connect to Spotify...", MessageType.Info, "Spotify.Start()"); User = null; Stopwatch crono = Stopwatch.StartNew(); Kernel.InternetAvaliable(false); try { SpotifyConfig = SpotifyClientConfig.CreateDefault().WithAuthenticator(new ClientCredentialsAuthenticator(PublicKey, PrivateKey)); SpotifyClient = new SpotifyClient(SpotifyConfig); crono.Stop(); if (SpotifyConfig is not null) //?? { Kernel.InternetAvaliable(true); Log.Instance.PrintMessage("Connected!", MessageType.Correct, crono, TimeType.Milliseconds); } else //yo creoque esto nunca se ejecuta... { Kernel.InternetAvaliable(false); Log.Instance.PrintMessage("Token is null", MessageType.Error, crono, TimeType.Milliseconds); } } catch (APIException ex) { Kernel.InternetAvaliable(false); Log.Instance.PrintMessage(ex.Message, MessageType.Error); MessageBox.Show(Kernel.LocalTexts.GetString("error_internet")); } }
protected override async void OnSpotifyConnectionChanged(SpotifyClient client) { base.OnSpotifyConnectionChanged(client); if (client != null) { // Check if we are authorized to read private profile information if (string.IsNullOrEmpty(UserId)) { if (SpotifyService.Instance.AreScopesAuthorized(Scopes.UserReadPrivate)) { _privateUserInfo = await client.UserProfile.Current(); } else { Debug.LogError($"Not authorized to access '{Scopes.UserReadPrivate}'"); } } else { _publicUserInfo = await client.UserProfile.Get(UserId); } } else { _privateUserInfo = null; _publicUserInfo = null; } UpdateUI(); }
private async Task LoginToSpotify(TaskCompletionSource <bool> tcs) { Server = new EmbedIOAuthServer(new Uri("http://localhost:5000/callback"), 5000); await Server.Start(); Server.ImplictGrantReceived += async(object sender, ImplictGrantResponse response) => { await Server.Stop(); if (response.AccessToken != null) { Spotify = new SpotifyClient(response.AccessToken); Profile = await Spotify.UserProfile.Current(); tcs.SetResult(Spotify != null); } else { Log("Error when attempting to log in"); tcs.SetResult(false); } }; var request = new LoginRequest(Server.BaseUri, SpotifySecrets.CLIENT_ID, LoginRequest.ResponseType.Token) { Scope = new List <string> { Scopes.UserLibraryRead, Scopes.PlaylistModifyPublic } }; BrowserUtil.Open(request.ToUri()); }
public async Task <PrivateUser> CurrentUser() { if (currentUser != null) { return(currentUser); } var user = await Api().User.Current(); currentUser = user; return(currentUser); }
/// <summary> /// Checks if the current user has premium /// </summary> /// <returns>true if the user has premium, false otherwise</returns> private async Task <bool> HasPremium() { bool result = false; if (client != null && IsAuthenticated) { PrivateUser currentUser = await client.UserProfile.Current(); result = (currentUser.Product == "premium"); } return(result); }
/// <summary> /// Checks if the current user who provided authorization has Spotify Premium, allowing use to the Spotify API. /// You still need to check the authorization scopes to see if you can access other areas of the API. /// </summary> /// <param name="client">The current client</param> /// <returns>True if the user has premium, if the user's product property is "premium"</returns> public static async Task <bool> IsUserPremium(SpotifyClient client) { if (client != null) { PrivateUser user = await client.UserProfile.Current(); if (user != null) { return(user.Product == "premium"); } } return(false); }
public async Task <ActionResult> RegisterPrivate(RegisterPrivateViewModel model) { if (ModelState.IsValid) { var user = new PrivateUser { UserName = model.Email, Email = model.Email, Address = model.Address, City = model.City, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, PostNr = model.PostNr, LastActivityDate = DateTime.Now }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SendConfirmationEmail(user); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
private async Task StartLoginSpotify(Stopwatch crono) { Log.Instance.PrintMessage("Logging to Spotify", MessageType.Info); var json = await File.ReadAllTextAsync(AuthPath); var token = JsonConvert.DeserializeObject <PKCETokenResponse>(json); var auth = new PKCEAuthenticator(PublicKey, token); auth.TokenRefreshed += (sender, token) => File.WriteAllText(AuthPath, JsonConvert.SerializeObject(token)); SpotifyConfig = SpotifyClientConfig.CreateDefault().WithAuthenticator(auth); SpotifyClient = new SpotifyClient(SpotifyConfig); AccountReady = true; User = SpotifyClient.UserProfile.Current().Result; Log.Instance.PrintMessage("Connected as " + User.Email, MessageType.Correct, crono, TimeType.Seconds); Config.LinkedWithSpotify = true; AccountLinked = true; Kernel.ActivarReproduccionSpotify(); Kernel.InternetAvaliable(true); Kernel.BringMainFormFront(); crono.Stop(); }
protected PrivateUser SetupAuthorizationFlow(Uri callBackUrl = null, string authorizationKey = "test authorization key", string accessToken = "test access token") { var callbackUrl = callBackUrl == null ? new Uri("http://localhost/callback") : callBackUrl; const string csfrToken = "csfr"; const string authorizationCode = "test authorization code"; const string userId = "testuser"; var user = new PrivateUser { Id = userId }; this.MockAuthorizationCallbackUrl(callbackUrl); this.MockCsfrTokenProvider(csfrToken); this.MockAuthorizationInteractionService(callbackUrl).Returns(Task.FromResult(new AuthorizationResponse <string>(authorizationCode, csfrToken))); this.MockGetAuthorizationTokens(authorizationCode).Returns(Task.FromResult(new ProxyAuthorizationTokens { AuthorizationKey = authorizationKey, AccessToken = new ProxyAccessToken { Token = accessToken, ExpiresIn = 2345 } })); this.MockGetUserInformation(accessToken).Returns(Task.FromResult(user)); return(user); }
private void OnLoggedIn(PrivateUser privateUser, PKCETokenResponse tokenResponse) { var playerStateStruct = PlayerState; playerStateStruct.IsLoggedIn = true; PlayerState = playerStateStruct; _plugin.Configuration.SpotifySettings.TokenResponse = tokenResponse; if (_spotifyState.IsPremiumUser) { _plugin.Configuration.SpotifySettings.LimitedAccess = false; } if (!_spotifyState.IsPremiumUser) { if (!_plugin.Configuration.SpotifySettings.LimitedAccess ) //Do a check to not spam the user, I don't want to force it down their throats. (f**k marketing) { _plugin.PluginInterface.Framework.Gui.Chat.PrintError( "Uh-oh, it looks like you're not premium on Spotify. Some features in Fantasy Player have been disabled."); } _plugin.Configuration.SpotifySettings.LimitedAccess = true; //Change configs if (_plugin.Configuration.PlayerSettings.CompactPlayer) { _plugin.Configuration.PlayerSettings.CompactPlayer = false; } if (!_plugin.Configuration.PlayerSettings.NoButtons) { _plugin.Configuration.PlayerSettings.NoButtons = true; } } _plugin.Configuration.Save(); }
public async Task <IActionResult> Index(string error_pass) { int userId = Int32.Parse(HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value); User user = await _repo.findById(userId); PrivateUser u1 = new PrivateUser(); u1.Id = user.Id; u1.Email = user.Email; u1.Surname = user.Surname; u1.Name = user.Name; u1.Cnp = user.Cnp; u1.License = user.License; u1.Insurance = user.Insurance; ViewBag.CurrentUser = u1; ViewBag.UserName = u1.Name + " " + u1.Surname; if (!string.IsNullOrEmpty(error_pass)) { ViewBag.Error = "Password Incorect!!"; } return(View()); }
private async void SetUser() { PrivateUser u = await spotify.UserProfile.Current(); this.SpotifyId = u.Id; }
public async Task OnGet() { var spotify = await _spotifyClientBuilder.BuildClient(); Me = await spotify.UserProfile.Current(); }
// POST: Users/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. public async Task <IActionResult> Build() { var spotify = await _spotifyClientBuilder.CreateClient(); if (spotify == null) { return(RedirectToAction("Index", "Home")); } PrivateUser me = await spotify.UserProfile.Current(); _user.UserId = me.Id; _user.UserName = me.DisplayName; if (me.Images.Any()) { _user.UserProfilePicture = me.Images[0].Url; } else { _user.UserProfilePicture = ""; } var user = await _context.Users .FirstOrDefaultAsync(m => m.UserId == me.Id); var userNum = _context.Users.Count() + 1; _user.UserCode = GenerateUserCode(me.Id) + userNum.ToString(); if (user == null) { PersonalizationTopRequest request = new PersonalizationTopRequest(); request.Limit = 50; var tracks = await spotify.Personalization.GetTopTracks(request); List <FullTrack> .Enumerator tracksEnumerator = tracks.Items.GetEnumerator(); var trackNumbers = tracks.Items.Count; for (int i = 0; i < trackNumbers; i++) { tracksEnumerator.MoveNext(); if (tracksEnumerator.Current != null) { //creating a new track and userTracks to map tracks and users Track newTrack = new Track(); UserTrack userTracks = new UserTrack(); //initializing tracks one bu one newTrack.TrackId = tracksEnumerator.Current.Id; newTrack.TrackName = tracksEnumerator.Current.Name; if (tracksEnumerator.Current.Album.Images.Any()) { newTrack.TrackAlbumPicture = tracksEnumerator.Current.Album.Images[0].Url; } else { newTrack.TrackAlbumPicture = ""; } newTrack.TrackAlbumPicture = tracksEnumerator.Current.Album.Images[0].Url; //adding track and user to UserTracks model initializing userTracks userTracks.Track = newTrack; userTracks.User = _user; //adding userTracks to User model _user.UsersTracks.Add(userTracks); //adding userTracks to Track model newTrack.UsersTracks.Add(userTracks); //check if artist exists in db var trackExists = _context.Tracks.Count(a => a.TrackId == newTrack.TrackId); if (trackExists == 0) { await _context.Tracks.AddAsync(newTrack); } else { _context.Tracks.Update(newTrack); } } } //now put top artist to database var artists = await spotify.Personalization.GetTopArtists(request); List <FullArtist> .Enumerator artistsEnumerator = artists.Items.GetEnumerator(); var artistCount = artists.Items.Count; for (int i = 0; i < artistCount; i++) { artistsEnumerator.MoveNext(); if (artistsEnumerator.Current != null) { //creating a new track and userTracks to map tracks and users Artist newArtist = new Artist(); UserArtist userArtist = new UserArtist(); //initializing tracks one bu one newArtist.ArtistId = artistsEnumerator.Current.Id; newArtist.ArtistName = artistsEnumerator.Current.Name; if (artistsEnumerator.Current.Images.Any()) { newArtist.ArtistPicture = artistsEnumerator.Current.Images[0].Url; } else { newArtist.ArtistPicture = ""; } //adding track and user to UserTracks model initializing userTracks userArtist.Artist = newArtist; userArtist.User = _user; //adding userTracks to User model _user.UsersArtists.Add(userArtist); //adding userTracks to Track model newArtist.UsersArtists.Add(userArtist); //check if artist exists in db var artistExists = _context.Artists.Count(a => a.ArtistId == newArtist.ArtistId); if (artistExists == 0) { await _context.Artists.AddAsync(newArtist); } else { _context.Artists.Update(newArtist); } } } await _context.Users.AddAsync(_user); await _context.SaveChangesAsync(); return(RedirectToAction(actionName: "Home", "Users", new { id = _user.UserId })); } return(RedirectToAction(actionName: "Home", "Users", new { id = _user.UserId })); }
private static async Task <string> GetPlaylistId(string playlistName, SimplePaginatorWithDelay paginator, SpotifyClient spotifyClient, PrivateUser profile) { var playlists = await spotifyClient.PaginateAll(await spotifyClient.Playlists.GetUsers(profile.Id).ConfigureAwait(false), paginator); var playlist = playlists.FirstOrDefault(pl => pl.Name == playlistName); FullPlaylist createdPlaylist = null; if (playlist == null) { createdPlaylist = await spotifyClient.Playlists.Create(profile.Id, new PlaylistCreateRequest(playlistName)); } string playlistId = playlist?.Id ?? createdPlaylist?.Id; return(playlistId); }
private void UpdateViewModel(bool isLoggedIn, PrivateUser user) { this.IsLoggedIn = isLoggedIn; this.User = isLoggedIn ? new UserViewModel(user) : null; }
public static string GetUsername(this PrivateUser profile) => string.IsNullOrEmpty(profile.DisplayName) ? profile.Id : profile.DisplayName;
public static CurrentUserResponse Map(this IMapper mapper, PrivateUser privateUser) => mapper.Map <CurrentUserResponse>(privateUser);
/// <summary> /// Initializes a new instance of the <see cref="AuthenticationTicket"/> class. /// </summary> /// <param name="authorizationKey">The authorization key.</param> /// <param name="accessToken">The access token.</param> /// <param name="user">The user.</param> public AuthenticationTicket(string authorizationKey, AccessToken accessToken, PrivateUser user) { this.AuthorizationKey = authorizationKey; this.AccessToken = accessToken; this.User = user; }
public UserViewModel(PrivateUser privateUser) { this.privateUser = privateUser; }