/// <summary> /// Updates the song and its progress /// </summary> /// <param name="song">The new song to update</param> private void SongChanged(CurrentlyPlaying song) { CurrentlyPlayingSong = song; IsPlaying = CurrentlyPlayingSong.is_playing; Progress.Progress_Ms = CurrentlyPlayingSong.progress_ms; Progress.Duration_Ms = CurrentlyPlayingSong.item.duration_ms; }
private void Shuffle() { Random r = new Random(); CurrentlyPlaying = CurrentlyPlaying.OrderBy(x => (r.Next())).ToList(); CurrentlyPlayingIndex = 0; }
// Host and Client Function. Sends currently playing info to host/other clients. private void BroadcastCurrentlyPlaying() { string Playing = "CURRENTLYPLAYING "; Playing += CurrentlyPlaying.ToString(); if (CurrentlyPlaying >= 0) { string sCurrentTime = YoutubeVideo_CallFlash("getCurrentTime()"); if (sCurrentTime != "") { sCurrentTime = sCurrentTime.Remove(sCurrentTime.Length - 9).Remove(0, 8); Playing += " " + sCurrentTime; } } if (Hosting) { Broadcast(Playing, "", false); } else { ClientBroadcast("CURRENTLYPLAYING$" + Encrypt(CurrentlyPlaying.ToString()) + "$"); } }
/// <summary> /// Plays the newly selected track /// </summary> private async void PlayTrack(object obj) { int indexOfTrack = Tracks.items.IndexOf(SelectedTrack); CurrentlyPlaying newSong = await _spotifyApi.PlaySongAsync(SelectedPlaylist.uri, indexOfTrack); await _signalRService.SendSongChangedAsync(newSong); }
/// <summary> /// Goes to the previous song /// </summary> private async void PreviousSong(object obj) { IsPlaying = true; CurrentlyPlaying newSong = await _spotifyApi.PreviousSongAsync(); await _signalRService.SendSongChangedAsync(newSong); }
public CurrentlyPlaying GetCurrentlyPlayingSong() { var webClient = new WebClient(); JObject jObject = JObject.Parse(storage.AuthorizationCodeFlowAuthTokenResponse); string AuthToken = (string)jObject.SelectToken("access_token"); webClient.Headers.Add(HttpRequestHeader.Accept, "application/json"); webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json"); webClient.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + AuthToken); var GetResponse = SendAuthorizationCodeRequest(webClient, "https://api.spotify.com/v1/me/player/currently-playing?market=DK"); var jsonTrack = JObject.Parse(GetResponse); var trackId = jsonTrack["item"]["id"].ToString(); var songName = jsonTrack["item"]["name"].ToString(); var artistName = jsonTrack["item"]["artists"][0]["name"].ToString(); var image_small_url = jsonTrack["item"]["album"]["images"][2]["url"].ToString(); var image_medium_url = jsonTrack["item"]["album"]["images"][1]["url"].ToString(); var image_large_url = jsonTrack["item"]["album"]["images"][0]["url"].ToString(); var webplayerLink = jsonTrack["item"]["external_urls"]["spotify"].ToString(); int duration = Int32.Parse(jsonTrack["item"]["duration_ms"].ToString()); int progress = Int32.Parse(jsonTrack["progress_ms"].ToString()); CurrentlyPlaying track = new CurrentlyPlaying(new Track(trackId, songName, artistName, image_small_url, image_medium_url, image_large_url, webplayerLink), duration, progress); return(track); //return GetResponse; }
public void changeBGM(CurrentlyPlaying state) { if (state != nextPlaying) { fading = true; nextPlaying = state; } }
public async Task <ActionResult <CurrentlyPlaying> > Previous() { HttpStatusCode status = await _httpCaller.Post("me/player/previous?device_id=" + _spotifyAPISettings.DeviceID, _spotifyAPISettings.AccessToken); CurrentlyPlaying currentlyPlaying = await _httpCaller.Get <CurrentlyPlaying>("me/player", _spotifyAPISettings.AccessToken); return(Ok(currentlyPlaying)); }
public void UpdateStatus() { var update = Task.Run(async() => { while (true) { await Task.Delay(1000); if (Ready()) { PlayerCurrentlyPlayingRequest request = new PlayerCurrentlyPlayingRequest(PlayerCurrentlyPlayingRequest.AdditionalTypes.All); CurrentlyPlaying playing = await SClient.Player.GetCurrentlyPlaying(request); if (playing != null) { if (playing.IsPlaying) { await bot.SetStatusAsync(UserStatus.Online); string song = ""; switch (playing.Item.Type) { case ItemType.Track: song = (playing.Item as FullTrack).Name; break; case ItemType.Episode: song = (playing.Item as FullEpisode).Name; break; } await bot.SetGameAsync(song, type: ActivityType.Listening); if (Queue[0].SongName == song) { Queue.RemoveAt(0); } } else { await bot.SetStatusAsync(UserStatus.DoNotDisturb); } } else { await bot.SetGameAsync($"Spotify", type: ActivityType.Listening); } } else { await bot.SetStatusAsync(UserStatus.DoNotDisturb); } } }); }
public void SkipBackward() { if (CurrentlyPlayingIndex == 0) { CurrentlyPlayingIndex = CurrentlyPlaying.Count() - 1; } else { CurrentlyPlayingIndex -= 1; } }
public void SkipForward() { if (CurrentlyPlayingIndex == CurrentlyPlaying.Count() - 1) { CurrentlyPlayingIndex = 0; } else { CurrentlyPlayingIndex += 1; } }
/// <summary> /// Update selected song whenever a new song comes on /// </summary> /// <param name="newSong">The song which is the new one</param> private void SongChanged(CurrentlyPlaying newSong) { // If newSong is null do nothing if (newSong == null || Tracks?.items == null) { return; } // Finds new track in playlist TrackItem newTrack = Tracks.items.Find(t => t.track.uri == newSong.item.uri); // Sets the new track as the SelectedTrack SelectedTrack = newTrack; }
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 void UpdateCurrentlyPlayingSong(List <Song> songs, bool isShuffled) { CurrentlyPlaying.Clear(); foreach (Song song in songs) { CurrentlyPlaying.Add(song); } if (isShuffled) { Shuffle(); } CurrentlyPlayingIndex = 0; }
public static PlayingItem?GetPlayingItem(CurrentlyPlaying currentlyPlaying) { if (currentlyPlaying is null) { return(null); } if (currentlyPlaying.Item is FullTrack track) { return(new Track(track)); } else if (currentlyPlaying.Item is FullEpisode episode) { return(new Episode(episode)); } return(null); }
public static async Task <string> GetCurrentlyPlaying(string username) { if (new OkayegTeaTimeContext().Spotify.Any(s => s.Username == username)) { Database.Models.Spotify user = DataBase.GetSpotifyUser(username); if (user.Time + new Hour().ToMilliseconds() <= TimeHelper.Now() + new Second(5).ToMilliseconds()) { await GetNewAccessToken(username); user = DataBase.GetSpotifyUser(username); } CurrentlyPlaying response = await new SpotifyClient(user.AccessToken).Player.GetCurrentlyPlaying(new PlayerCurrentlyPlayingRequest()); return(response.GetItem() != null?response.GetItem().Message : "nothing playing"); } else { return("the user is not registered"); } }
public async Task UpdateSession() { DataLoader dataLoader = DataLoader.GetInstance(); _playbackState = await dataLoader.GetCurrentlyPlaying(); if (_playbackState != null && _playbackState.Is_Playing && CurrentTrack != null && _playbackState.Item.Id != CurrentTrack.Id && _playbackState.Item.Id != NextTrackPeek.Id) { long playBackStarted = _playbackState.Timestamp - _playbackState.Progress_ms; _playedSongs.Add(new SessionHistoryItem() { Track = _playbackState.Item, TimeStamp = new DateTime(playBackStarted), Context = SessionContext.Unknown }); } SessionStateChanged?.Invoke(this, EventArgs.Empty); }
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 async Task <ActionResult <CurrentlyPlaying> > Play(string contextUri, int offset) { var playContent = new { context_uri = contextUri, offset = new { position = offset } }; // Serialize anonymous object into HttpContent HttpContent content = new StringContent(JsonConvert.SerializeObject(playContent)); HttpStatusCode status = await _httpCaller.Put("me/player/play?device_id=" + _spotifyAPISettings.DeviceID, _spotifyAPISettings.AccessToken, content); CurrentlyPlaying currentlyPlaying = await _httpCaller.Get <CurrentlyPlaying>("me/player/currently-playing", _spotifyAPISettings.AccessToken); return(Ok(currentlyPlaying)); }
public async Task <CurrentlyPlaying> GetCurrentlyPlaying(bool retryOnLimit = false, int retryAfterLimitms = 5000) { try { Stopwatch watch = Stopwatch.StartNew(); long unixtimestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds(); CurrentlyPlaying result = await ExecuteWebrequest <CurrentlyPlaying>(GET_CURRENTLY_PLAYING, retryOnLimit, retryAfterLimitms); watch.Stop(); if (result != null) { result.Timestamp = unixtimestamp; } return(result); } catch (Exception) { return(null); } }
public async Task SongChanged(CurrentlyPlaying song) { await Clients.All.SendAsync("SongChanged", song); }
/// <summary> /// Stops playback of audio that is currently playing /// </summary> public void StopPlayback() { CurrentlyPlaying.Abort(); IsPlayingAudio = false; NotifyOfPropertyChange(() => CurrentlyPlaying); }
private async void RunInternal() { await Task.Run(async() => { _playbackState = await DataLoader.GetInstance().GetCurrentlyPlaying(true, (int)SESSION_NEXT_SONG_BEVOR_END_MS - 50); long lastUpadte = _unixTimestamp; string lastDeviceId = null; long tickStart = 0; SessionStateChanged?.Invoke(this, EventArgs.Empty); while (IsRunning) { tickStart = Environment.TickCount; if (AMOUNT_ITEMS_LEFT_TO_REPOPULATED_BACKLOG >= CurrentBacklogQueue.Count()) { await RepopulateBacklog(); } if (_unixTimestamp >= lastUpadte + SESSION_UPDATE_SLEEP_PAUSE_MS || //update when "updatetimer" tiggers _possibleMSLeftInTrack < SESSION_NEXT_SONG_BEVOR_END_MS) //update befor a PlayTrack to check whether playback is paused { await UpdateSession(); lastUpadte = _unixTimestamp; } //if (CurrentTrack == null || (_playbackState.Is_Playing && _possibleMSLeftInTrack < SESSION_NEXT_SONG_BEVOR_END_MS)) if (CurrentTrack == null || (_playbackState != null && CurrentTrack.Id == _playbackState.Item.Id && !_playbackState.Is_Playing && _playbackState.Progress_ms == 0)) { Tuple <Track, SessionContext> nextTrackContext = PullNextTrack(); if (await PlayTrack(nextTrackContext)) { Thread.Sleep(10); await UpdateSession(); } else { CurrentManualQueue.Push(nextTrackContext.Item1); } } if (DeviceId != null && DeviceId != lastDeviceId) { await Controller.GetInstance().TransferPlayback(DeviceId, true); } lastDeviceId = DeviceId; int sleepTime = (int)(SESSION_TICK_SLEEP_PAUSE_MS - (Environment.TickCount - tickStart)); if (sleepTime > 0) { Thread.Sleep(sleepTime); } } }); }
public async Task <ActionResult <CurrentlyPlaying> > Get() { CurrentlyPlaying currentlyPlaying = await _httpCaller.Get <CurrentlyPlaying>("me/player", _spotifyAPISettings.AccessToken); return(Ok(currentlyPlaying)); }
public static CurrentlyPlayingResponse Map(this IMapper mapper, CurrentlyPlaying currentlyPlaying) => mapper.Map <CurrentlyPlayingResponse>(currentlyPlaying);
/// <summary> /// Triggers the SongChanged event /// </summary> /// <param name="song">The song which should be sent to all subscribers</param> public async Task SendSongChangedAsync(CurrentlyPlaying song) { await connection.InvokeAsync("SongChanged", song); }
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}"); }