예제 #1
0
        public ActionResult Me()
        {
            var returnURL = "/Profiles/Me";
            var ah        = new AuthHelper();
            var result    = ah.DoAuth(returnURL, this);

            if (result != null)
            {
                return(Redirect(result));
            }

            var access_token = Session["AccessToken"].ToString();
            var url2         = "https://api.spotify.com/v1/me";
            var sh           = new SpotifyHelper();
            var result2      = sh.CallSpotifyAPIPassingToken(access_token, url2);

            var meReponse = JsonConvert.DeserializeObject <MeResponse>(result2);

            // Holder UserId in session so can turn menu on and off for login
            //Session["UserId"] = meReponse.id;

            meReponse.access_token = access_token;
            //return View(meReponse);
            // Redirect to PlaylistShuffler page
            return(Redirect("/Users/Playlists/" + meReponse.id));
        }
예제 #2
0
        public ActionResult SpotifyCallback(string code)
        {
            bool   keepTrying    = true;
            string resultContent = "";

            while (keepTrying)
            {
                // Have now got authorization code (which can be exchanged for an access token)
                var client_id     = "0fd1718f5ef14cb291ef114a13382d15";
                var client_secret = "964e8a4a50de4dfd8247d061a8517920";

                var url = "https://accounts.spotify.com/api/token";

                // Request access and refresh tokens
                var postData = new Dictionary <string, string> {
                    { "grant_type", "authorization_code" },
                    { "code", code },
                    { "redirect_uri", GetRedirectUriWithServerName() },
                    { "client_id", client_id },
                    { "client_secret", client_secret }
                };

                HttpContent content = new FormUrlEncodedContent(postData.ToArray());

                var client       = new HttpClient();
                var httpResponse = client.PostAsync(url, content);
                var result       = httpResponse.Result;
                resultContent = result.Content.ReadAsStringAsync().Result;

                // Catching gateway timeouts or strange stuff from Spotify
                if (result.IsSuccessStatusCode)
                {
                    keepTrying = false;
                }
            }

            var obj = JsonConvert.DeserializeObject <AccessToken>(resultContent, new JsonSerializerSettings {
                TypeNameHandling       = TypeNameHandling.All,
                TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
            });
            var access_token = obj.access_token;

            // Set access token in session
            Session["AccessToken"] = access_token;

            // do a quick call to get the username of the currently logged in user so I can use it to hide or display if it is davemateer (admin)
            var url2    = "https://api.spotify.com/v1/me";
            var sh      = new SpotifyHelper();
            var result2 = sh.CallSpotifyAPIPassingToken(access_token, url2);

            var meReponse = JsonConvert.DeserializeObject <MeResponse>(result2);

            Session["SpotifyUserID"] = meReponse.id;

            // Get return URL from session state
            var returnURL = Session["ReturnURL"].ToString();

            return(Redirect(returnURL));
        }
예제 #3
0
        private List <TopTracksVM> GetTopTracks()
        {
            var vm = new List <TopTracksVM>();

            using (var db = DBHelper.GetOpenConnection())
            {
                vm = db.GetList <TopTracksVM>("ORDER BY AlbumDate Desc").ToList();
            }

            // If logged in
            if (Session["AccessToken"] != null)
            {
                ViewBag.access_token = Session["AccessToken"].ToString();

                var access_token = Session["AccessToken"].ToString();

                // User clicks via LoginRedirect to come back here
                // If this is the first time back to this page after logging in, need to get the UserID
                if (Session["UserID"] == null)
                {
                    var    url = "https://api.spotify.com/v1/me";
                    string json;
                    using (mp.CustomTiming("http", url))
                    {
                        var sh = new SpotifyHelper();
                        json = sh.CallSpotifyAPIPassingToken(access_token, url);
                    }

                    var meReponse = JsonConvert.DeserializeObject <MeResponse>(json);
                    meReponse.access_token = access_token;

                    Session["UserID"] = meReponse.id;
                }
                // Grab the userID as we'll use that in our database to remember what a user has selected
                ViewBag.user_id = Session["UserID"];

                // Find out what the user has already added to their playlist
                List <string> listTracksAlreadyAdded;
                var           userID = Session["UserID"];
                using (IDbConnection db = DBHelper.GetOpenConnection())
                {
                    listTracksAlreadyAdded =
                        db.Query <string>("SELECT TrackID FROM UserPlaylists WHERE UserID = @UserID", new { @UserID = userID })
                        .ToList();
                }

                foreach (var track in vm)
                {
                    if (listTracksAlreadyAdded.Contains(track.TrackID))
                    {
                        track.AddedInUserPlaylist = true;
                    }
                }
            }
            return(vm);
        }
예제 #4
0
        public ActionResult Details(string id, string userId)
        {
            var returnURL = "/Playlists/Details/" + id + "/" + userId;
            var ah        = new AuthHelper();
            var result    = ah.DoAuth(returnURL, this);

            if (result != null)
            {
                return(Redirect(result));
            }

            var access_token = Session["AccessToken"].ToString();
            var url2         = String.Format("https://api.spotify.com/v1/users/{0}/playlists/{1}", userId, id);
            var sh           = new SpotifyHelper();
            var result2      = sh.CallSpotifyAPIPassingToken(access_token, url2);

            var meReponse = JsonConvert.DeserializeObject <PlaylistDetails>(result2);

            meReponse.access_token = access_token;
            return(View(meReponse));
        }
예제 #5
0
        ///v1/users/{user_id}
        public ActionResult User(string id)
        {
            var returnURL = "/Profiles/User";
            var ah        = new AuthHelper();
            var result    = ah.DoAuth(returnURL, this);

            if (result != null)
            {
                return(Redirect(result));
            }

            var access_token = Session["AccessToken"].ToString();
            var url2         = String.Format("https://api.spotify.com/v1/users/{0}", id);
            var sh           = new SpotifyHelper();
            var result2      = sh.CallSpotifyAPIPassingToken(access_token, url2);

            var response = JsonConvert.DeserializeObject <UserDetails>(result2);

            response.access_token = access_token;
            return(View(response));
        }
예제 #6
0
        // Browse/NewReleases
        public ActionResult NewReleases()
        {
            var returnURL = "/Browse/NewReleases";
            var ah        = new AuthHelper();
            var result    = ah.DoAuth(returnURL, this);

            if (result != null)
            {
                return(Redirect(result));
            }

            var access_token = Session["AccessToken"].ToString();
            var url2         = "https://api.spotify.com/v1/browse/new-releases?country=GB";
            var sh           = new SpotifyHelper();
            var result2      = sh.CallSpotifyAPIPassingToken(access_token, url2);

            var meReponse = JsonConvert.DeserializeObject <NewReleaseDetails>(result2);

            meReponse.access_token = access_token;
            return(View(meReponse));
        }
예제 #7
0
        public ActionResult FeaturedPlaylists()
        {
            var returnURL    = "/Browse/FeaturedPlaylists";
            var helper       = new AuthHelper();
            var helperResult = helper.DoAuth(returnURL, this);

            if (helperResult != null)
            {
                return(Redirect(helperResult));
            }

            var access_token = Session["AccessToken"].ToString();
            var url          = "https://api.spotify.com/v1/browse/featured-playlists?country=GB";
            var sh           = new SpotifyHelper();
            var result       = sh.CallSpotifyAPIPassingToken(access_token, url);

            var meReponse = JsonConvert.DeserializeObject <FeaturedPlaylists>(result);

            meReponse.access_token = access_token;
            return(View(meReponse));
        }
예제 #8
0
        //eg /v1/users/davemateer/playlists
        public ActionResult Create()
        {
            var returnURL = "/Playlists/Create";

            var ah     = new AuthHelper();
            var result = ah.DoAuth(returnURL, this);

            if (result != null)
            {
                return(Redirect(result));
            }

            var sh           = new SpotifyHelper();
            var access_token = Session["AccessToken"].ToString();

            // Get the current users id eg davemateer
            var url7    = "https://api.spotify.com/v1/me";
            var result7 = sh.CallSpotifyAPIPassingToken(access_token, url7);

            var    meReponse7 = JsonConvert.DeserializeObject <MeResponse>(result7);
            string userId     = meReponse7.id;

            // Does the playlist exist already for this user?
            var url4              = String.Format("https://api.spotify.com/v1/users/{0}/playlists", userId);
            var result4           = sh.CallSpotifyAPIPassingToken(access_token, url4);
            var meReponse         = JsonConvert.DeserializeObject <PlaylistSummaryViewModel>(result4);
            var currentPlaylistID = "";

            foreach (var thing in meReponse.items)
            {
                if (thing.name == "DTM - Playlist")
                {
                    currentPlaylistID = thing.id;
                }
            }

            // If not playlist create one
            if (currentPlaylistID == "")
            {
                var url2           = String.Format("https://api.spotify.com/v1/users/{0}/playlists", userId);
                var result2        = sh.CallSpotifyCreatePlaylistPostAPIPassingToken(access_token, url2);
                var playlistReturn = JsonConvert.DeserializeObject <CreatePlaylistReturn>(result2);
                currentPlaylistID = playlistReturn.id;
            }

            // Get trackID's from database to add to Spotify (the app saves the trackID's to the db before we send to spotify)
            var listOfTrackIDs = new List <String>();

            using (var connection = new SqlConnection(connectionString))
                using (var command = new SqlCommand(null, connection)) {
                    connection.Open();
                    command.CommandText = String.Format("SELECT TrackID FROM UserPlaylists WHERE UserID = @UserID");
                    command.Parameters.AddWithValue("@UserID", userId);
                    command.CommandType = System.Data.CommandType.Text;
                    using (var reader = command.ExecuteReader()) {
                        while (reader.Read())
                        {
                            var trackID = reader.GetString(reader.GetOrdinal("TrackID"));
                            listOfTrackIDs.Add(trackID);
                        }
                    }
                }

            if (listOfTrackIDs.Count > 100)
            {
                string csvOfUris = "";

                // Get first 100 tracks and put into a csv string
                var first100 = listOfTrackIDs.Take(100);
                foreach (var trackID in first100)
                {
                    csvOfUris += "spotify:track:" + trackID + ",";
                }
                csvOfUris = csvOfUris.TrimEnd(',');

                var url3 = String.Format("https://api.spotify.com/v1/users/{0}/playlists/{1}/tracks?uris={2}", userId, currentPlaylistID, csvOfUris);

                // this will replace
                var result3 = sh.CallSpotifyPutAPIPassingToken(access_token, url3);

                var recordsPerPage      = 100;
                var records             = listOfTrackIDs.Count;
                int numberOfTimesToLoop = (records + recordsPerPage - 1) / recordsPerPage;

                // 1 as we've already done the first loop (0 based)
                for (int i = 1; i < numberOfTimesToLoop; i++)
                {
                    var stuff = listOfTrackIDs.Skip(100 * i).Take(100);
                    csvOfUris = "";
                    foreach (var trackID in stuff)
                    {
                        csvOfUris += "spotify:track:" + trackID + ",";
                    }
                    csvOfUris = csvOfUris.TrimEnd(',');

                    // this will add
                    url3 = String.Format("https://api.spotify.com/v1/users/{0}/playlists/{1}/tracks?uris={2}", userId, currentPlaylistID, csvOfUris);
                    var result5 = sh.CallSpotifyPostAPIPassingToken(access_token, url3);
                }
            }
            else
            {
                string csvOfUris = "";

                var first100 = listOfTrackIDs;
                foreach (var trackID in first100)
                {
                    csvOfUris += "spotify:track:" + trackID + ",";
                }
                csvOfUris = csvOfUris.TrimEnd(',');

                var url3 = String.Format("https://api.spotify.com/v1/users/{0}/playlists/{1}/tracks?uris={2}", userId,
                                         currentPlaylistID, csvOfUris);

                // this will replace
                var result3 = sh.CallSpotifyPutAPIPassingToken(access_token, url3);
            }

            return(Redirect("/"));
        }
예제 #9
0
        public async Task <ActionResult> Playlists(PlaylistSummaryViewModel vm, string id)
        {
            ServicePointManager.DefaultConnectionLimit = 5;

            var userId       = id;
            var access_token = Session["AccessToken"].ToString();
            var sh           = new SpotifyHelper();

            // Create/Update playlist in Spotify
            // like /Playlists/Follow

            // Does the playlist exist already for this user?
            var    url4 = String.Format("https://api.spotify.com/v1/users/{0}/playlists", userId);
            string result4;

            using (mp.Step("POST - Does the DTM Shuffler playlist exist already for this user")) {
                result4 = sh.CallSpotifyAPIPassingToken(access_token, url4);
            }
            var meReponse         = JsonConvert.DeserializeObject <PlaylistSummaryViewModel>(result4);
            var currentPlaylistID = "";
            var shuffler          = meReponse.items.FirstOrDefault(x => x.name == "DTM - Shuffler");

            if (shuffler != null)
            {
                currentPlaylistID = shuffler.id;
            }

            // If not playlist create one
            if (currentPlaylistID == "")
            {
                var    url2 = String.Format("https://api.spotify.com/v1/users/{0}/playlists", userId);
                string result2;
                using (mp.Step("POST - Creating DTM - Shuffler playlist")) {
                    result2 = sh.CallSpotifyCreatePlaylistPostAPIPassingToken(access_token, url2, "DTM - Shuffler");
                }
                var playlistReturn = JsonConvert.DeserializeObject <CreatePlaylistReturn>(result2);
                currentPlaylistID = playlistReturn.id;
            }

            // Go through each Checked playlist and add to Shuffler list
            var listOfTrackIDs = new List <String>();

            foreach (var playlist in vm.items)
            {
                var ownerId    = playlist.owner.id;
                var playlistId = playlist.id;
                if (playlist.Checked)
                {
                    // Get the details of the playlist ie the tracks
                    PlaylistTracks result22;
                    using (mp.Step("POST - Async.. Get details of the playlist ie the tracks.. 50 at a time")) {
                        result22 = await sh.CallSpotifyAPIPassingTokenPlaylistsAsync(access_token, ownerId, playlistId);
                    }
                    // add tracks to list
                    foreach (var item in result22.items)
                    {
                        // catching a track in a playlist with no id
                        if (item.track != null)
                        {
                            listOfTrackIDs.Add(item.track.id);
                        }
                    }
                }
            }

            var result3 = await sh.CallSpotifyPutAPIPassingTokenSendTracksAsync(access_token, userId, currentPlaylistID, listOfTrackIDs);

            // Get data again as not saved, including Checked status
            var vm2 = await GetPlaylistDetailsViewModel(id);

            return(View(vm2));
        }
예제 #10
0
        private async Task <PlaylistSummaryViewModel> GetPlaylistDetailsViewModel(string id, bool doAsync = true)
        {
            ServicePointManager.DefaultConnectionLimit = 5;
            var access_token = Session["AccessToken"].ToString();

            var    url = String.Format("https://api.spotify.com/v1/users/{0}/playlists?limit=50", id);
            string json;

            using (mp.Step("Get Users Playlists first 50")) {
                json = sh.CallSpotifyAPIPassingToken(access_token, url);
            }
            var vm = JsonConvert.DeserializeObject <PlaylistSummaryViewModel>(json);

            var recordsPerPage = 50;

            if (vm.total > recordsPerPage)
            {
                var totalRecords        = vm.total;
                int numberOfTimesToLoop = (totalRecords + recordsPerPage - 1) / recordsPerPage;

                // we've already done the first query to get the total, do skip that
                numberOfTimesToLoop -= 1;
                if (doAsync)
                {
                    using (mp.Step("Async " + numberOfTimesToLoop + " queries"))
                        using (mp.CustomTiming("http", "overall")) {
                            var tasks  = new Task <string> [numberOfTimesToLoop];
                            int offset = 0;
                            for (int i = 0; i < numberOfTimesToLoop; i++)
                            {
                                // start offset at 50
                                offset += recordsPerPage;
                                url     = String.Format("https://api.spotify.com/v1/users/{0}/playlists?limit={2}&offset={1}", id,
                                                        offset, recordsPerPage);
                                tasks[i] = sh.CallSpotifyAPIPassingTokenAsync(access_token, url);
                            }
                            // at this point all tasks will be running at the same time
                            await Task.WhenAll(tasks);
                        }

                    for (int i = 0; i < numberOfTimesToLoop - 1; i++)
                    {
                        var vm2 = JsonConvert.DeserializeObject <PlaylistSummaryViewModel>(json);
                        // merge with vm
                        vm.items = vm.items.Union(vm2.items).ToList();
                    }
                }
                else
                {
                    for (int i = 1; i < numberOfTimesToLoop; i++)
                    {
                        int offset = i * recordsPerPage;
                        url = String.Format("https://api.spotify.com/v1/users/{0}/playlists?limit={2}&offset={1}", id, offset, recordsPerPage);
                        using (mp.Step("Get Users Playlists - " + i)) {
                            json = sh.CallSpotifyAPIPassingToken(access_token, url);
                        }

                        var vm2 = JsonConvert.DeserializeObject <PlaylistSummaryViewModel>(json);
                        // merge with vm
                        vm.items = vm.items.Union(vm2.items).ToList();
                    }
                }
            }
            vm.access_token = access_token;
            return(vm);
        }