public static async Task <List <ListenerTrack> > Run( [ActivityTrigger] List <string> listenerIds, ILogger log ) { return(await SpotifyHelper.GetListenerTracks(listenerIds, log)); }
public async Task <ActionResult> DisplayArtists() // grab three artists from a genre. { SearchItem ArtistSearch = await SpotifyHelper.GrabArtists("Imagine"); List <FullArtist> searchedArtists = ArtistSearch.Artists.Items; // this list acts like an array? TempData["ArtistList"] = searchedArtists[0].Name + " " + searchedArtists[1].Name + " " + searchedArtists[2].Name; return(RedirectToAction("Spotify")); }
public static void Search(string query) { App._searchResult = new SearchResult(); SpotifyHelper spotify = new SpotifyHelper("test"); //App._searchResult.AddArtists(spotify.SearchArtists(query).Artists); spotify.SearchArtistsAsync(query, App.SearchArtistsCallback); spotify.SearchAlbumsAsync(query, App.SearchAlbumsCallback); spotify.SearchTracksAsync(query, App.SearchTracksCallback); var page = new View.GroupedCollectionPage(); page.Groups = App._searchResult.SearchResultGroups; Window.Current.Content = page; }
public static async Task <PlayingItem?> GetCurrentlyPlayingTrack(string username) { SpotifyUser?user = await GetSpotifyUser(username); if (user is null) { return(null); } CurrentlyPlaying response = await new SpotifyClient(user.AccessToken).Player.GetCurrentlyPlaying(new()); PlayingItem? item = SpotifyHelper.GetPlayingItem(response); return(item); }
public async Task <string> GetToken(string code) { var request = new RestRequest("/api/token", Method.POST); var base64 = SpotifyHelper.Base64Encode($"{AppSettings.ClientId}:{AppSettings.ClientSecret}"); request.AddParameter("code", code); request.AddParameter("redirect_uri", "https://localhost:44320/callback"); request.AddParameter("grant_type", "authorization_code"); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddHeader("Authorization", $"Basic {base64}"); IRestResponse response = await Client.ExecutePostTaskAsync <AccessTokenResponse>(request); return(JsonConvert.DeserializeObject <AccessTokenResponse>(response?.Content)?.AccessToken); }
public static async Task <string> AddToQueue(string channel, string song, bool channelEqualsTarget = true) { string?uri = SpotifyHelper.GetSpotifyUri(song); if (uri is null) { return("this isn't a valid track link"); } SpotifyUser?user = await GetSpotifyUser(channel); if (user is null) { return($"can't add the song to the queue of {channel}, they have to register first"); } if (user.SongRequestEnabled == true) { try { SpotifyClient client = new(user.AccessToken); await client.Player.AddToQueue(new(uri)); FullTrack item = await client.Tracks.Get(uri.Remove("spotify:track:")); string[] artists = item.Artists.GetArtistNames(); string response = $"{item.Name} by {string.Join(", ", artists)} has been added to the queue"; if (!channelEqualsTarget) { response = string.Concat(response, $" of {channel}"); } return(response); } catch (APIException ex) { Logger.Log(ex); return($"no music playing on any device, {channel} has to start their playback first"); } catch (Exception ex) { Logger.Log(ex); return($"an unknown error occurred. It might not be possible to request songs for this user"); } } else { return($"song requests are currently not open, {channel} or a mod has to enable song requests first"); } }
public async Task <ActionResult> DisplayRandomGenre() // name needs to be changed to RandomGenre { string Genre = await SpotifyHelper.GetGenre(); if (Genre != null) { TempData["Genre"] = Genre; } else { TempData["Genre"] = "Whoops!"; } return(RedirectToAction("Spotify")); }
public async Task <bool> Login() { if (Sessao.spotify == null || !Sessao.spotify.logged) { var spotify = new SpotifyHelper(); var estaLogado = await spotify.Login(); if (estaLogado) { Sessao.spotify = spotify; } return(estaLogado); } return(true); }
public static async Task <string> GetCurrentlyPlaying(string username) { SpotifyUser?user = await GetSpotifyUser(username); if (user is null) { return($"can't request the current playing song, user {username} has to register first"); } CurrentlyPlaying response = await new SpotifyClient(user.AccessToken).Player.GetCurrentlyPlaying(new()); PlayingItem? item = SpotifyHelper.GetPlayingItem(response); if (item is not null) { return(item.Message); } else { return("nothing playing"); } }
public static async Task <string> Search(string query) { SpotifyUser?user = await GetSpotifyUser("strbhlfe"); if (user is null) { return("can't search for a track at the moment"); } SearchResponse response = await new SpotifyClient(user.AccessToken).Search.Item(new(SearchRequest.Types.Track, query)); FullTrack? track = SpotifyHelper.GetExcactTrackFromSearch(response.Tracks.Items, query.Split().ToList()); if (track is not null) { string[] artists = track.Artists.GetArtistNames(); return($"{track.Name} by {string.Join(", ", artists)} || {track.Uri}"); } else { return("no tracks found to match the search query"); } }
public static async Task <List <ListenerTrack> > Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "listeners")] HttpRequest req, [Table( TableConstants.UserTable, Connection = Constants.StorageConnection )] CloudTable userTable, ILogger log) { log.LogInformation("Retrieving non-hidden users"); await userTable.CreateIfNotExistsAsync(); var repo = new UserRepository(userTable); var entities = await repo.GetUsersAsync(); var nonHiddenUserIds = entities .Where(e => e.Active) .Select(e => e.RowKey) .ToList(); log.LogInformation("Found these users: {Users}", string.Join(", ", nonHiddenUserIds)); return(await SpotifyHelper.GetListenerTracks(nonHiddenUserIds, log)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "recent/{userId}")] HttpRequest req, [Table( TableConstants.UserTable, Connection = Constants.StorageConnection )] CloudTable userTable, string userId, ILogger log) { await userTable.CreateIfNotExistsAsync(); var repo = new UserRepository(userTable); var entity = await repo.GetUserAsync(userId); if (entity != null && entity.Active) { var playHistory = await SpotifyHelper.GetRecentlyPlayedTracksAsync(userId); return(new JsonResult(playHistory)); } return(new NotFoundResult()); }
public async Task <ActionResult> SpotifyArtistSearch(string Keyword, string Genre) { string ArtistString = ""; if (ModelState.IsValid) { SearchItem ArtistSearch = await SpotifyHelper.GrabArtists(Keyword); List <FullArtist> searchedArtists = ArtistSearch.Artists.Items; // this list acts like an array? int arraySize = searchedArtists.Count(); string[] ArtistArray = new string[arraySize]; for (int i = 0; i <= arraySize - 1; i++) { if (Genre == "") //leave genre blank to grab 50 artists { ArtistArray[i] = searchedArtists[i].Name; } else if (searchedArtists[i].Genres.Contains(Genre)) { ArtistString += searchedArtists[i].Name + ", "; ArtistArray[i] = searchedArtists[i].Name; } } TempData["ArtistsByGenre"] = ArtistArray; } else { TempData["ArtistsByGenre"] = "Whoops something went wrong!"; } return(View()); }
public void SelectPlaylist(string id) { var val = Task.Run(() => Spotify.getPlayListById(id)); SpotifyHelper.SelectItemByValue(comboBox1, val.Result); }
public async Task <IMusicServiceStatus> GetStatusAsync() => await Task.Run(() => SpotifyHelper.GetStatus());
static void Main(string[] args) { // string accessToken = KeyVaultHelper.GetSecret(bearerTokenIdentifier); // var storageAccount = AzureStorageHelper.CreateStorageAccountFromConnectionString(connectionString); CloudTable table = AzureStorageHelper.GetOrCreateTableAsync("partyCodes").Result; // AzureStorageHelper.DeleteParty("WXYZ", table); // AzureStorageHelper.InsertOrMergeParty(new Party("IYEY"), table); // AzureStorageHelper.InsertAccessTokenToParty("WXYZ", table, accessTokenA); var accessTokens = AzureStorageHelper.GetParty("WXYZ", table).GetAccessTokens(); var topArtists = new List <IEnumerable <Artist> >(); foreach (var token in accessTokens) { topArtists.Add(SpotifyHelper.GetTopArtistsAsync(token).Result); } var commonArtists = Matchmaker.FindCommonArtists(topArtists.ElementAt(0), topArtists.ElementAt(1)); var commonGenres = Matchmaker.FindCommonGenres(topArtists.ElementAt(0), topArtists.ElementAt(1)); var difference = topArtists.ElementAt(0).Except(commonArtists); ; // var topArtistsA = SpotifyHelper.GetTopArtistsAsync(accessTokenA, "short_term").Result; // var topArtistsB = SpotifyHelper.GetTopArtistsAsync(accessTokenB, "short_term").Result; // ; // // var userA = SpotifyHelper.GetUserAsync(accessTokenA).Result; // // var userB = SpotifyHelper.GetUserAsync(accessTokenB).Result; // // SpotifyHelper.CreatePlaylistAsync(accessToken, user.Id).Wait(); // var commonArtists = SpotifyHelper.FindCommonArtists(topArtistsA, topArtistsB); // var commonGenres = SpotifyHelper.FindCommonGenres(topArtistsA, topArtistsB); // var commonArtistsString = String.Join(", ", commonArtists); // var commonGenresString = string.Join(", ", commonGenres); // Console.WriteLine($"You have these artists in common: {commonArtistsString}"); // Console.WriteLine($"You have these genres in common: {commonGenresString}"); // var suggestedArtists = SpotifyHelper.SuggestArtists(topArtistsA, topArtistsB); // var suggestedArtistsString = String.Join(", ", suggestedArtists); // Console.WriteLine($"We suggest listening to these artists: {suggestedArtistsString}"); // var artistIDs = SpotifyHelper.SuggestArtistIDs(topArtistsA, topArtistsB).ToList(); var playListId = SpotifyHelper.CreatePlaylistAsync(accessTokens[0], "Spotify Matchmaker Playlist").Result; foreach (var artist in commonArtists) { var tracks = SpotifyHelper.GetArtistsTopTracksAsync(accessTokens[0], artist).Result; SpotifyHelper.AddSongsToPlaylistAsync(accessTokens[0], playListId, tracks); } ; }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "slack")] HttpRequest req, [Table( TableConstants.UserTable, Connection = Constants.StorageConnection )] CloudTable userTable, ILogger log) { await userTable.CreateIfNotExistsAsync(); var bodyString = await req.ReadAsStringAsync(); var slackPayload = HttpUtility.ParseQueryString(bodyString); var token = slackPayload["token"]; if (!string.Equals(token, Config.SlackToken)) { throw new System.Exception("Not allowed"); } var args = slackPayload["text"]?.Trim(); if (string.Equals("list", args)) { var repo = new UserRepository(userTable); var entities = await repo.GetUsersAsync(); var nonHiddenUserIds = entities .Where(e => e.Active) .Select(e => e.RowKey) .ToList(); log.LogInformation("Found these users: {Users}", string.Join(", ", nonHiddenUserIds)); var listenerTracks = await SpotifyHelper.GetListenerTracks(nonHiddenUserIds, log); return(new JsonResult(new { blocks = new { type = "section", block_id = "listeners", fields = listenerTracks.Select(lt => new { type = "mrkdwn", text = $"- {lt.userId}: {lt.currentTrack}" }).ToArray <object>() } })); } return(new JsonResult(new { blocks = new object[] { new { type = "section", block_id = "help_text_commands", fields = new [] { new { type = "mrkdwn", text = "*Hey! Welcome to now playing* \n Press the button below to go to the website, or register with Now Playing:" } } }, new { type = "actions", elements = new object[] { new { type = "button", action_id = "dashboard_nowplaying", url = Config.HostUrl, text = new { type = "plain_text", text = "Dashboard website", } }, new { type = "button", action_id = "register_nowplaying", url = $"{Config.HostUrl}api/authorize", text = new { type = "plain_text", text = "Register with Now Playing", } } } } } })); }
public async Task <float> GetVolumeAsync() => await Task.Run(() => SpotifyHelper.GetVolume());
public async Task <bool> NextAsync(string url) { await Task.Run(() => SpotifyHelper.Next(url)); return(true); }
public async Task <bool> PauseAsync() { await Task.Run(() => SpotifyHelper.Pause()); return(true); }
public async Task <bool> PlayAsync() => await Task.Run(() => SpotifyHelper.Play());
public async Task <bool> PlayAsync(string url) => await Task.Run(() => SpotifyHelper.Play(url));
public static async Task <string> ListenTo(string username, string target) { SpotifyUser?user = await GetSpotifyUser(username); if (user is null) { return($"can't listen to other's songs, you have to register first"); } if (username == target) { return($"you can't listen to your own song"); } SpotifyUser?targetUser = await GetSpotifyUser(target); if (targetUser is null) { return($"can't listen to {target}'s songs, they have to register first"); } SpotifyClient targetClient = new(targetUser.AccessToken); CurrentlyPlaying targetCurrentlyPlaying = await targetClient.Player.GetCurrentlyPlaying(new()); PlayingItem?playingItem = SpotifyHelper.GetPlayingItem(targetCurrentlyPlaying); if (playingItem is null) { return($"{target} is currently not listening to a song"); } if (playingItem.IsLocal) { return($"can't listen to {target}'s local file"); } SpotifyClient userClient = new(user.AccessToken); try { await userClient.Player.AddToQueue(new(playingItem.Uri)); } catch (APIException ex) { Logger.Log(ex); return($"no music playing on any device, you have to start your playback first"); } catch (Exception ex) { Logger.Log(ex); return($"an unknown error occurred. It might not be possible to listen to songs"); } try { await userClient.Player.SkipNext(new()); } catch (Exception ex) { Logger.Log(ex); return($"an error occurred while trying to play the song"); } return($"now playing {playingItem.Title} by {string.Join(", ", playingItem.Artists)} || {playingItem.Uri}"); }
public async Task <IList <ISearchResult> > SearchAsync(string keyword) => await Task.Run(() => SpotifyHelper.Search(keyword));
public async Task SetVolumeAsync(float volume) => await Task.Run(() => SpotifyHelper.SetVolume(volume));