Beispiel #1
0
        public async Task <SpotifyUser> GetUser(string token)
        {
            SpotifyUser user = await GetAsync <SpotifyUser>("https://api.spotify.com/v1/me", token);


            return(user);
        }
Beispiel #2
0
        public JsonResult GetUser(string AccessToken, string TokenType, string ExpiresIn, string State)
        {
            SpotifyUser user = APICalls.GetCurrentSpotifyUser(AccessToken);

            return(Json(new { Username = user.display_name, Id = user.id, Email = user.email, Images = user.images, Url = user.external_urls.spotify,
                              Birthday = user.birthdate, Country = user.country, Followers = user.followers }));
        }
Beispiel #3
0
        private static SpotifyWebAPI GetWebClient(SpotifyUser oSpotifyUser)
        {
            AutorizationCodeAuth oAuth = new AutorizationCodeAuth()
            {
                ClientId    = _ClientPublic,
                RedirectUri = _RedirectUrl,
                Scope       = Scope.UserReadPrivate | Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.UserFollowRead
            };

            //oAuth.StartHttpServer();//Not sure if this is needed or not but what the hell why not!

            if (oSpotifyUser.AccessToken.AccessExpired)//The user has authorized us and was tokenized but the temp access token has expired
            {
                Token oToken = oAuth.RefreshToken(oSpotifyUser.RefreshToken.Code, _ClientPrivate);
                if (oToken.Error == null)
                {
                    oSpotifyUser.UpdateUserWithToken(oToken);
                }
            }



            //oAuth.StopHttpServer();
            SpotifyWebAPI oWebClient = new SpotifyWebAPI()
            {
                AccessToken = oSpotifyUser.AccessToken.Code,
                TokenType   = oSpotifyUser.AccessToken.TokenType,
                UseAuth     = true
            };

            return(oWebClient);
        }
Beispiel #4
0
        public SpotifyUser GetUserProfile()
        {
            string      url         = "https://api.spotify.com/v1/me";
            SpotifyUser spotifyUser = _spotifyApi.GetSpotifyType <SpotifyUser>(url);

            return(spotifyUser);
        }
Beispiel #5
0
        public static IEnumerable <SpotifyPlaylist> GetUsersFollowedPlaylists(SpotifyUser oSpotifyUser)
        {
            List <SpotifyPlaylist> Playlists = new List <SpotifyPlaylist>();

            using (SpotifyWebAPI oWebCLient = GetWebClient(oSpotifyUser))
            {
                Paging <SimplePlaylist> oPaging = oWebCLient.GetUserPlaylists(oSpotifyUser.Name);

                foreach (SimplePlaylist oSimplePlaylist in oPaging.Items)
                {
                    if (!oSimplePlaylist.Owner.Id.Equals(oSpotifyUser.Name))
                    {
                        Dictionary <int, SpotifyTrack> oTracks = GetTracksForPlaylist(oWebCLient, oSimplePlaylist, oSpotifyUser);
                        Playlists.Add(new SpotifyPlaylist(oSimplePlaylist, oTracks));
                    }
                }
                while (oPaging.Next != null)
                {
                    oPaging = oWebCLient.DownloadData <Paging <SimplePlaylist> >(oPaging.Next);
                    foreach (SimplePlaylist oSimplePlaylist in oPaging.Items)
                    {
                        if (!oSimplePlaylist.Owner.Id.Equals(oSpotifyUser.Name))
                        {
                            Dictionary <int, SpotifyTrack> oTracks = GetTracksForPlaylist(oWebCLient, oSimplePlaylist, oSpotifyUser);
                            Playlists.Add(new SpotifyPlaylist(oSimplePlaylist, oTracks));
                        }
                    }
                }
            }
            return(Playlists);
        }
        public async Task <string> GetUsersSpotifyUserName()
        {
            SpotifyUser user   = new SpotifyUser();
            string      token  = Request.Cookies["spot_toke"].Value.ToString();
            HttpClient  client = new HttpClient();

            client.BaseAddress = new Uri("https://api.spotify.com/v1/me");
            string phantomPram = "";

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            HttpResponseMessage response = client.GetAsync(phantomPram).Result;

            if (response.IsSuccessStatusCode)
            {
                var     result      = response.Content.ReadAsStringAsync().Result;
                string  replacement = System.Text.RegularExpressions.Regex.Replace(result, @"\t|\n|\r|\\\\", "");
                JObject s           = JObject.Parse(replacement);

                user = s.ToObject <SpotifyUser>();

                using (RelayDJDevEntities db = new RelayDJDevEntities())
                {
                    string userId = User.Identity.GetUserId();
                    Dj     item   = db.Djs.Where(x => x.DjUserId == userId).FirstOrDefault();
                    item.SpotifyUserName = user.id;
                    db.SaveChanges();
                }
            }
            return(user.id);
        }
Beispiel #7
0
        public SpotifyUser GetUserProfile(string token)
        {
            string      url         = "https://api.spotify.com/v1/me";
            SpotifyUser spotifyUser = GetFromSpotify <SpotifyUser>(url, token);

            return(spotifyUser);
        }
        public JsonResult getPlayList()
        {
            //Se não houver sessão ativa, redireciona para o login
            if ((string)Session["Token"] == null)
            {
                return(Json(false, JsonRequestBehavior.AllowGet));
            }
            else
            {
                try {
                    _spotifyApi.Token = (string)Session["Token"];
                    SpotifyService spotifyService = new SpotifyService(_spotifyApi);

                    //Get user_id and user displayName
                    SpotifyUser spotifyUser = spotifyService.GetUserProfile();
                    ViewBag.UserName = spotifyUser.DisplayName;

                    //Get user playlists ids
                    Playlists playlists = spotifyService.GetPlaylists(spotifyUser.UserId);

                    //Get all tracks from user
                    List <string> tracks = spotifyService.GetTracksAndArtistsFromPlaylists(playlists);

                    //Generate the new playlist
                    List <string> newPlayList = spotifyService.GenerateNewPlaylist(spotifyUser.DisplayName, tracks);

                    return(Json(newPlayList, JsonRequestBehavior.AllowGet));
                } catch (Exception ex) {
                    return(Json(false, JsonRequestBehavior.AllowGet));
                }
            }
        }
Beispiel #9
0
        public async Task <SkillResponse> Run(SkillRequest skillRequest, ILambdaContext context)
        {
            var userId = skillRequest.Context.System.User.UserId;

            if (skillRequest.GetRequestType() == typeof(LaunchRequest))
            {
                const string msg = "Hey. What can I do for you?";
                return(ResponseBuilder.Ask(msg, new Reprompt("Sorry. I don't know what you mean.")));
            }

            if (skillRequest.GetRequestType() == typeof(SessionEndedRequest))
            {
                const string msg = "See you later";
                return(ResponseBuilder.Tell(msg));
            }

            if (skillRequest.GetRequestType() == typeof(SkillEventRequest))
            {
                // todo: check enable / disable
                var eventRequest = (SkillEventRequest)skillRequest.Request;
                if (eventRequest.Type == "AlexaSkillEvent.SkillDisabled")
                {
                }
            }

            var actualIntentRequest = (IntentRequest)skillRequest.Request;
            var handler             = _handlers.FirstOrDefault(x => x.Name == actualIntentRequest.Intent.Name);

            if (handler == null)
            {
                return(TellWithoutEnding("Sorry. I don't know what you mean."));
            }

            var user = await _userStorageService.GetAsync(userId);

            if (user == null)
            {
                user = new SpotifyUser(userId);
                await _userStorageService.SaveAsync(user);
            }

            try
            {
                await handler.VerifySession(skillRequest);

                await handler.BuildSpotifySession(skillRequest);

                return(await handler.HandleIntent(skillRequest, actualIntentRequest, context));
            }
            catch (Exception ex)
            {
                if (ex is AccessTokenMissingException)
                {
                    return(ResponseBuilder.Tell("AccessToken is missing. Please link your account"));
                }

                return(ResponseBuilder.Tell(ex.Message));
            }
        }
        public async Task <IActionResult> GetSpotifyUser(FromBodyAttribute authCode, string code)
        {
            var authToken = GetAuthToken(code);

            var userResponse = await SpotifyUser.GetCurrentUserProfile(authToken);

            return(Ok(userResponse));
        }
Beispiel #11
0
        public string SaveAccountDeatils(OAuthTokens tokens, string userId, string Email)
        {
            try
            {
                //AccessDetails accessToken = new AccessDetails() { AccessToken = tokens.access_token };
                SpotifyUser profile = GetUserprofile(new AccessDetails {
                    AccessToken = tokens.access_token
                });
                var profilePic    = string.Empty;
                var returnMessage = string.Empty;
                //if (profile.images != null) { profilePic = profile.images[0].url; }
                //else { profilePic = null; }
                var checkAccountIsAvail = _socialMediaRepo.Get().Include(x => x.AccessDetails).Where(x => x.SMId == profile.id.ToString() && x.IsDeleted == false).FirstOrDefault();
                if (checkAccountIsAvail == null)
                {
                    SocialMedia socialDetails = new SocialMedia()
                    {
                        UserId        = userId,
                        Provider      = SocialMediaProviders.Spotify.ToString(),
                        AccessDetails = new AccessDetails {
                            AccessToken = tokens.access_token, Refresh_token = tokens.refresh_token, Expires_in = DateTime.UtcNow.AddMinutes(58)
                        },

                        SMId   = profile.id.ToString(),
                        Status = true,

                        //ProfilepicUrl = profilePic,
                        Followers   = profile.followers.total,
                        UserName    = profile.email,
                        AccSettings = new AccSettings()
                    };
                    socialDetails.AccSettings.UserManagement.Add(new UserManagement {
                        Email = Email, userId = userId, Role = "Owner"
                    });
                    _socialMediaRepo.Add(socialDetails);
                }
                else if (checkAccountIsAvail.UserId == userId)
                {
                    checkAccountIsAvail.AccessDetails.AccessToken = tokens.access_token;
                    checkAccountIsAvail.IsInvalid = false;
                    checkAccountIsAvail.Status    = true;
                    returnMessage = "Already added.";
                }
                else
                {
                    checkAccountIsAvail.AccessDetails.AccessToken = tokens.access_token;
                    checkAccountIsAvail.IsInvalid = false;
                    checkAccountIsAvail.Status    = true;
                    returnMessage = "Cannot add this account, as already added by other user.";
                }
                _unitOfWork.Commit();
                return(returnMessage);
            }
            catch (Exception)
            {
                return("Something went wrong.");
            }
        }
Beispiel #12
0
        /// <summary>
        /// Get detailed profile information about the current user (including the current user’s username).
        /// </summary>
        /// <param name="userId"></param>
        public async static Task <User> GetCurrentUserProfile(AuthenticationToken token)
        {
            string json = await HttpHelper.Get("https://api.spotify.com/v1/me", token);

            CheckForExpiredToken(json);
            SpotifyUser toReturn = JsonConvert.DeserializeObject <SpotifyUser>(json, new JsonSerializerSettings());

            return(toReturn.ToPOCO());
        }
Beispiel #13
0
 public static UserData CreateUserData(SpotifyUser inUser)
 {
     return(new UserData
     {
         Uri = inUser.Uri,
         Id = inUser.Id,
         Type = inUser.Type,
         Href = inUser.Href
     });
 }
        public async Task <IActionResult> GetSpotifyUser(FromBodyAttribute authCode, string code)
        {
            var authToken = HttpHelper.Post("https://accounts.spotify.com/api/token", code);

            var userResponse = await SpotifyUser.GetCurrentUserProfile(authToken);

            await _dashboardHub.Clients.All.InvokeAsync("TestSend", "Hello From The Hub Server!!");

            return(Ok(userResponse));
        }
        public async Task <IActionResult> GetPlayer(string code)
        {
            var authToken = HttpHelper.Post("https://accounts.spotify.com/api/token", code);

            var userResponse = await SpotifyUser.GetCurrentUserProfile(authToken);

            var playingNow = await userResponse.GetPlayer(authToken);

            return(Ok(playingNow));
        }
        public async Task <IActionResult> GetPlayer(string code)
        {
            var authToken = GetAuthToken(code);

            var userResponse = await SpotifyUser.GetCurrentUserProfile(authToken);

            var playingNow = await userResponse.GetPlayer(authToken);

            return(Ok(playingNow));
        }
Beispiel #17
0
        public static string GetUsersEmail(SpotifyUser oSpotifyUser)
        {
            string sEmail;

            using (SpotifyWebAPI oWebCLient = GetWebClient(oSpotifyUser))
            {
                PrivateProfile oPrivateProfile = oWebCLient.GetPrivateProfile();
                sEmail = oPrivateProfile.Email;
            }
            return(sEmail);
        }
        public async void startSpotify()
        {
            _spotifyClient = new SpotifyClient();
            _spotifyUser   = new SpotifyUser();

            // Authenticating Client
            await Task.Run(() => _spotifyClient.post_authenticateClient());

            // Authenticating User
            await Task.Run(() => _spotifyUser.get_authenticateUser(this));
        }
        private void SetTracks(SpotifyUser user, SpotifyPlaylist createdPlaylist, Tracklist tracklist)
        {
            var request = new HttpRequestMessage(HttpMethod.Put, $"/v1/users/{user.Id}/playlists/{createdPlaylist.Id}/tracks")
            {
                Content = new StringContent(JsonConvert.SerializeObject(tracklist),
                                            Encoding.UTF8,
                                            "application/json")
            };

            var response = _client.SendAsync(request).Result;
        }
        public static void SaveUserAndAuthToDatabase(SpotifyUser oSpotifyUser)
        {
            DataSet ds = RelationalDatabase.ExecuteStoredProcedure("AddSpotifyUser",
                                                                   new SqlParameter("iUserID", oSpotifyUser.ID),
                                                                   new SqlParameter("sUserName", oSpotifyUser.Name),
                                                                   new SqlParameter("sAuthCode", oSpotifyUser.UserAuth.Code),
                                                                   new SqlParameter("dtAuth", oSpotifyUser.UserAuth.AuthDate)
                                                                   );

            oSpotifyUser.SessionGuid = ds.Tables[0].Rows[0]["SessionGuid"].ToString();
        }
Beispiel #21
0
        public void LogSpotify(SpotifyUser user, PlaylistResult playlistResult, TokenResponse token)
        {
            var combinedLog = new CombinedLog {
                User = user, Playlist = playlistResult, Token = token
            };

            var client   = new AmazonDynamoDBClient(_config.Value.AccessKey, _config.Value.AccessKeySecret, RegionEndpoint.USEast1);
            var table    = Table.LoadTable(client, "ReadySetGoSpotify");
            var jsonText = JsonConvert.SerializeObject(combinedLog);
            var item     = Document.FromJson(jsonText);

            var result = table.PutItemAsync(item).Result;
        }
        public static IEnumerable <SpotifyUser> GetSpotifyUsersAndTokens()
        {
            List <SpotifyUser> oUsers = new List <SpotifyUser>();
            DataSet            ds     = RelationalDatabase.ExecuteStoredProcedure("GetSpotifyUsersAndSpotifyTokens");

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                SpotifyUser oUser = new SpotifyUser(dr);
                oUsers.Add(oUser);
                oUser = null;
            }
            return(oUsers);
        }
        public static SpotifyUser GetSpotifyUserForGuid(string sUserGuid)
        {
            SpotifyUser oSpotifyUser = null;
            DataSet     ds           = RelationalDatabase.ExecuteStoredProcedure("GetSpotifyUsersAndSpotifyTokens");

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (dr["UserGuid"].ToString().ToUpper().Equals(sUserGuid.ToUpper()))
                {
                    oSpotifyUser = new SpotifyUser(dr);
                }
            }
            return(oSpotifyUser);
        }
 public SpotifyUserController
     (SpotifyUser userRepo,
     IMapper mapper,
     SpotifyPlayer playerRepo,
     ICookieManager cookiesManager,
     PublicUserViewModel userModel,
     UserProfileViewModel model)
 {
     _model          = model;
     _userModel      = userModel;
     _userRepo       = userRepo;
     _mapper         = mapper;
     _playerRepo     = playerRepo;
     _cookiesManager = cookiesManager;
 }
        private SpotifyPlaylist CreateNew(SpotifyUser user, string artistName)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, $"/v1/users/{user.Id}/playlists")
            {
                Content = new StringContent($"{{\"name\":\"{artistName} - ReadySetGo\", \"public\":false}}",
                                            Encoding.UTF8,
                                            "application/json")
            };

            var response = _client.SendAsync(request).Result;

            var createdPlaylist = JsonConvert.DeserializeObject <SpotifyPlaylist>(response.Content.ReadAsStringAsync().Result);

            return(createdPlaylist);
        }
        public static SpotifyUser GetSpotifyUser(string AccessToken, string UserId)
        {
            var client  = new RestClient("https://api.spotify.com/v1");
            var request = new RestRequest("users/{userid}", Method.GET);

            request.AddUrlSegment("userid", UserId);
            //client.Authenticator = new RestSharp.Authenticators.OAuth2UriQueryParameterAuthenticator(AccessToken);
            request.AddHeader("Authorization", string.Format("Bearer {0}", AccessToken));
            //request.AddHeader()

            // execute api call and deserialize the results into the object
            IRestResponse response = client.Execute(request);
            SpotifyUser   user     = new SpotifyUser();

            user = JsonConvert.DeserializeObject <SpotifyUser>(response.Content);

            return(user);
        }
        public ActionResult Spotify(string access_token, string error, string searchString)
        {
            if (error != null || error == "access_denied")
            {
                return(View("Error"));
            }

            if (string.IsNullOrEmpty(access_token))
            {
                return(View());
            }

            try
            {
                _spotifyApi.Token = access_token;
                SpotifyService spotifyService = new SpotifyService(_spotifyApi);
                //Get user_id and user displayName
                SpotifyUser spotifyUser = spotifyService.GetUserProfile();
                ViewBag.UserName = spotifyUser.DisplayName;


                _spotify = new SpotifyWebAPI()
                {
                    //TODO Get token from session
                    AccessToken = access_token,
                    TokenType   = "Bearer"
                };
                PlaybackContext context = _spotify.GetPlayingTrack();
                if (context.Item != null)
                {
                    ViewBag.song = context.Item.Artists[0].Name + " - " + context.Item.Name;
                }

                return(View());
            }
            catch (Exception)
            {
                return(View("Error"));
            }
        }
Beispiel #28
0
        public bool Read()
        {
            if (_iCurrentIndex > this._Users.Length - 1)
            {
                this._iCurrentIndex = 0; //All users returned reset this before we return
                return(false);
            }
            SpotifyUser oSpotifyUser = this._Users[this._iCurrentIndex];

            this._iCurrentIndex++;


            this._ID           = oSpotifyUser.ID;
            this._SpotifyID    = oSpotifyUser.SpotifyID;
            this._Name         = oSpotifyUser.Name;
            this._UserAuth     = oSpotifyUser.UserAuth;
            this._RefreshToken = oSpotifyUser.RefreshToken;
            this._AccessToken  = oSpotifyUser.AccessToken;
            this._Playlists    = oSpotifyUser.Playlist;


            return(true);
        }
        public ActionResult Index(string access_token, string error)
        {
            if (error != null || error == "access_denied")
            {
                return(View("Error"));
            }

            if (string.IsNullOrEmpty(access_token))
            {
                return(View());
            }

            try
            {
                _spotifyApi.Token = access_token;
                SpotifyService spotifyService = new SpotifyService(_spotifyApi);
                //Get user_id and user displayName
                SpotifyUser spotifyUser = spotifyService.GetUserProfile();
                ViewBag.UserName = spotifyUser.DisplayName;

                //Get user playlists ids
                Playlists playlists = spotifyService.GetPlaylists(spotifyUser.UserId);

                //Get all tracks from user
                List <string> tracks = spotifyService.GetTracksAndArtistsFromPlaylists(playlists);

                //Generate the new playlist
                List <string> newPlayList = spotifyService.GenerateNewPlaylist(spotifyUser.DisplayName, tracks);

                return(RedirectToAction("Index", "Home", new { token = access_token }));
            }
            catch (Exception)
            {
                return(View("Error"));
            }
        }
        public RedirectResult Authorized(string code, string error, string state)
        {
            if (error != null)
            {
                throw new Exception(error);
            }
            AutorizationCodeAuth oAutorizationCodeAuth = new AutorizationCodeAuth()
            {
                //Your client Id
                ClientId = this._oSCCManager.SCC_PUBLIC_ID,
                //Set this to localhost if you want to use the built-in HTTP Server
                RedirectUri = this._oSCCManager.RedirectUrl,
                //How many permissions we need?
                Scope = Scope.UserReadPrivate | Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.UserFollowRead
            };


            Token oToken;

            oToken = oAutorizationCodeAuth.ExchangeAuthCode(code, this._oSCCManager.SCC_PRIVATE_ID);
            //oToken = oAutorizationCodeAuth.RefreshToken(response.Code, SCC_PRIVATE_ID);


            SpotifyWebAPI oSpotifyWebApi = new SpotifyWebAPI()
            {
                AccessToken = oToken.AccessToken,
                TokenType   = oToken.TokenType,
                UseAuth     = true
            };


            PrivateProfile oPrivateProfile = oSpotifyWebApi.GetPrivateProfile();



            SpotifyUser oSpotifyUser = this._oSCCManager.AddSpotifyUser(oPrivateProfile, code, oToken);

            // ViewBag.RedirectUrl = string.Format("/SpotifyChangeControl/Change/Index?UserGuid={0}&SessionGuid={1}", oSpotifyUser.UserGuid, oSpotifyUser.SessionGuid);

            if (!this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("UserGuid"))
            {
                HttpCookie hcUserGuid = new HttpCookie("UserGuid");
                hcUserGuid.Value = oSpotifyUser.UserGuid;
                this.ControllerContext.HttpContext.Response.Cookies.Add(hcUserGuid);
                this.ControllerContext.HttpContext.Response.Cookies.Add(hcUserGuid);
            }
            else
            {
                this.ControllerContext.HttpContext.Request.Cookies.Get("UserGuid").Value = oSpotifyUser.UserGuid;
            }

            if (!this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("SessionGuid"))
            {
                HttpCookie hcSessionGuid = new HttpCookie("SessionGuid");
                hcSessionGuid.Value = oSpotifyUser.SessionGuid;
                this.ControllerContext.HttpContext.Response.Cookies.Add(hcSessionGuid);
            }
            else
            {
                this.ControllerContext.HttpContext.Request.Cookies.Get("SessionGuid").Value = oSpotifyUser.SessionGuid;
            }


            return(new RedirectResult(string.Format("/SpotifyChangeControl/Change/Index", oSpotifyUser.UserGuid, oSpotifyUser.SessionGuid)));
        }