public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender)
        {
            string action       = GetMessageValue <string>(message, "Action");
            string playlistType = GetMessageValue <string>(message, "PlaylistType", "music");
            bool   autoPlay     = GetMessageValue <bool>(message, "AutoPlay");
            int    index        = GetMessageValue <int>(message, "Index");
            var    playList     = ServiceRegistration.Get <IPlayerContextManager>().CurrentPlayerContext.Playlist;
            var    client       = sender.GetRemoteClient();

            if (action.Equals("new", StringComparison.InvariantCultureIgnoreCase) || action.Equals("append", StringComparison.InvariantCultureIgnoreCase))
            {
                //new playlist or append to playlist
                int  insertIndex = GetMessageValue <int>(message, "InsertIndex");
                bool shuffle     = GetMessageValue <bool>(message, "Shuffle");

                // Add items from JSON or SQL
                JArray array = GetMessageValue <JArray>(message, "PlaylistItems");

                if (array != null)
                {
                    if (action.Equals("new", StringComparison.InvariantCultureIgnoreCase))
                    {
                        playList.Clear();
                    }

                    int idx = insertIndex;
                    if (array != null)
                    {
                        playList.StartBatchUpdate();

                        // Add items from JSON
                        foreach (JObject o in array)
                        {
                            string fileName = GetMessageValue <string>(o, "FileName");
                            string id       = GetMessageValue <string>(o, "FileId");

                            var mediaItemGuid = await GetIdFromNameAsync(client, fileName, id, Helper.GetMediaItemByFileNameAsync);

                            if (mediaItemGuid == null)
                            {
                                ServiceRegistration.Get <ILogger>().Error("WifiRemote: Playlist: Couldn't convert FileId '{0} to Guid", id);
                                return(false);
                            }

                            MediaItem item = await Helper.GetMediaItemByIdAsync(client.UserId, mediaItemGuid.Value);

                            if (item == null)
                            {
                                ServiceRegistration.Get <ILogger>().Warn("WifiRemote: Playlist: Not media item found");
                                continue;
                            }

                            playList.Insert(idx, item);

                            idx++;
                        }
                        playList.EndBatchUpdate();

                        playList.PlayMode = PlayMode.Continuous;
                        if (shuffle)
                        {
                            playList.PlayMode = PlayMode.Shuffle;
                        }
                    }

                    if (autoPlay)
                    {
                        playList.ItemListIndex = 0;
                        ServiceRegistration.Get <IPlayerContextManager>().CurrentPlayerContext.Play();
                    }
                }
            }
            else if (action.Equals("load", StringComparison.InvariantCultureIgnoreCase))
            {
                //load a playlist
                string playlistName = GetMessageValue <string>(message, "PlayListName");
                string playlistId   = GetMessageValue <string>(message, "PlaylistId");
                bool   shuffle      = GetMessageValue <bool>(message, "Shuffle");
                if (string.IsNullOrEmpty(playlistId))
                {
                    List <PlaylistInformationData> playLists = ServerPlaylists.GetPlaylists().ToList();
                    playlistId = playLists.FirstOrDefault(p => p.Name == playlistName)?.PlaylistId.ToString();
                }

                if (Guid.TryParse(playlistId, out Guid id))
                {
                    var data = await Helper.LoadPlayListAsync(id);

                    LastLoadedPlayList = data.Name;
                    playList.StartBatchUpdate();
                    playList.Clear();
                    foreach (var item in data.Items)
                    {
                        playList.Add(item);
                    }
                    playList.EndBatchUpdate();

                    if (autoPlay)
                    {
                        playList.ItemListIndex = 0;
                        ServiceRegistration.Get <IPlayerContextManager>().CurrentPlayerContext.Play();
                    }
                }
            }
            else if (action.Equals("get", StringComparison.InvariantCultureIgnoreCase))
            {
                //get all playlist items of the currently active playlist
                IList <MediaItem>      items          = playList.ItemList;
                MessagePlaylistDetails returnPlaylist = new MessagePlaylistDetails
                {
                    PlaylistName   = LastLoadedPlayList ?? "Play list",
                    PlaylistRepeat = playList.RepeatMode != RepeatMode.None,
                    PlaylistItems  = new List <PlaylistEntry>()
                };
                foreach (var mediaItem in playList.ItemList)
                {
                    var ple = new PlaylistEntry
                    {
                        FileId = mediaItem.MediaItemId.ToString(),
                    };

                    if (mediaItem.Aspects.ContainsKey(VideoAspect.ASPECT_ID))
                    {
                        if (returnPlaylist.PlaylistType != "video")
                        {
                            if (returnPlaylist.PlaylistType == null)
                            {
                                returnPlaylist.PlaylistType = "video";
                            }
                            else
                            {
                                continue;
                            }
                        }

                        IList <MultipleMediaItemAspect> videoStreamAspects;
                        MediaItemAspect.TryGetAspects(mediaItem.Aspects, VideoStreamAspect.Metadata, out videoStreamAspects);
                        var mediaAspect   = MediaItemAspect.GetAspect(mediaItem.Aspects, MediaAspect.Metadata);
                        var movieAspect   = MediaItemAspect.GetAspect(mediaItem.Aspects, MovieAspect.Metadata);
                        var episodeAspect = MediaItemAspect.GetAspect(mediaItem.Aspects, EpisodeAspect.Metadata);

                        TimeSpan duration = TimeSpan.FromSeconds(0);
                        int?     setNo    = videoStreamAspects?.FirstOrDefault()?.GetAttributeValue <int>(VideoStreamAspect.ATTR_VIDEO_PART_SET);
                        if (setNo.HasValue)
                        {
                            foreach (var stream in videoStreamAspects.Where(s => s.GetAttributeValue <int>(VideoStreamAspect.ATTR_VIDEO_PART_SET) == setNo.Value))
                            {
                                long?durSecs = stream.GetAttributeValue <long?>(VideoStreamAspect.ATTR_DURATION);
                                if (durSecs.HasValue)
                                {
                                    duration.Add(TimeSpan.FromSeconds(durSecs.Value));
                                }
                            }
                        }

                        ple.MpMediaType  = (int)MpMediaTypes.Movie;
                        ple.MpProviderId = (int)MpProviders.MPVideo;
                        ple.MediaType    = returnPlaylist.PlaylistType;
                        ple.Name         = movieAspect?.GetAttributeValue <string>(MovieAspect.ATTR_MOVIE_NAME) ?? episodeAspect?.GetAttributeValue <string>(EpisodeAspect.ATTR_EPISODE_NAME) ?? mediaAspect.GetAttributeValue <string>(MediaAspect.ATTR_TITLE);
                        ple.Name2        = episodeAspect?.GetAttributeValue <string>(EpisodeAspect.ATTR_SERIES_NAME);
                        ple.Duration     = Convert.ToInt32(duration.TotalSeconds);
                        ple.Played       = Convert.ToInt32(mediaItem.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") == 100;
                        returnPlaylist.PlaylistItems.Add(ple);
                    }
                    else if (mediaItem.Aspects.ContainsKey(AudioAspect.ASPECT_ID))
                    {
                        if (returnPlaylist.PlaylistType != "music")
                        {
                            if (returnPlaylist.PlaylistType == null)
                            {
                                returnPlaylist.PlaylistType = "music";
                            }
                            else
                            {
                                continue;
                            }
                        }

                        var mediaAspect = MediaItemAspect.GetAspect(mediaItem.Aspects, MediaAspect.Metadata);
                        var audioAspect = MediaItemAspect.GetAspect(mediaItem.Aspects, AudioAspect.Metadata);

                        ple.MpMediaType  = (int)MpMediaTypes.MusicTrack;
                        ple.MpProviderId = (int)MpProviders.MPMusic;
                        ple.MediaType    = returnPlaylist.PlaylistType;
                        ple.Name         = audioAspect.GetAttributeValue <string>(AudioAspect.ATTR_TRACKNAME);
                        ple.Name2        = audioAspect.GetAttributeValue <string>(AudioAspect.ATTR_ALBUM);
                        var albumArtists = audioAspect.GetCollectionAttribute <string>(AudioAspect.ATTR_ALBUMARTISTS);
                        if (albumArtists?.Count() > 0)
                        {
                            ple.AlbumArtist = string.Join(", ", albumArtists);
                        }
                        ple.Duration = Convert.ToInt32(audioAspect.GetAttributeValue <long>(AudioAspect.ATTR_DURATION));
                        ple.Played   = Convert.ToInt32(mediaItem.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") == 100;
                        returnPlaylist.PlaylistItems.Add(ple);
                    }
                }
                SendMessageToClient.Send(returnPlaylist, sender, true);
            }
            else if (action.Equals("remove", StringComparison.InvariantCultureIgnoreCase))
            {
                //remove an item from the playlist
                playList.RemoveAt(index);
            }
            else if (action.Equals("move", StringComparison.InvariantCultureIgnoreCase))
            {
                //move a playlist item to a new index
                int oldIndex  = GetMessageValue <int>(message, "OldIndex");
                int newIndex  = GetMessageValue <int>(message, "NewIndex");
                var mediaItem = playList.ItemList[oldIndex];
                playList.RemoveAt(oldIndex);
                playList.Insert(newIndex, mediaItem);
            }
            else if (action.Equals("play", StringComparison.InvariantCultureIgnoreCase))
            {
                //start playback of a playlist item
                playList.ItemListIndex = index;
                ServiceRegistration.Get <IPlayerContextManager>().CurrentPlayerContext.Play();
            }
            else if (action.Equals("clear", StringComparison.InvariantCultureIgnoreCase))
            {
                //clear the playlist
                playList.Clear();
            }
            else if (action.Equals("list", StringComparison.InvariantCultureIgnoreCase))
            {
                //get a list of all available playlists
                List <PlaylistInformationData> playLists = ServerPlaylists.GetPlaylists().ToList();
                MessagePlaylists returnList = new MessagePlaylists {
                    PlayLists = playLists.Select(x => x.Name).ToList()
                };
                SendMessageToAllClients.Send(returnList, ref SocketServer.Instance.connectedSockets);
            }
            else if (action.Equals("save", StringComparison.InvariantCultureIgnoreCase))
            {
                //save the current playlist to file
                string name = GetMessageValue <string>(message, "PlayListName");
                if (name != null)
                {
                    await Helper.SavePlayListAsync(Guid.NewGuid(), name, playlistType, playList.ItemList.Select(i => i.MediaItemId));
                }
                else
                {
                    Logger.Warn("WifiRemote: Playlist: Must specify a name to save a playlist");
                }
            }
            else if (action.Equals("shuffle", StringComparison.InvariantCultureIgnoreCase))
            {
                var playMode = playList.PlayMode == PlayMode.Shuffle ? PlayMode.Continuous : PlayMode.Shuffle;
                playList.PlayMode = playMode;
            }
            else if (action.Equals("repeat", StringComparison.InvariantCultureIgnoreCase))
            {
                Logger.Debug("WifiRemote: Playlist action repeat");
                bool       repeat = GetMessageValue <bool>(message, "Repeat");
                RepeatMode repeatMode;
                if (repeat)
                {
                    repeatMode = RepeatMode.All;
                }
                else
                {
                    repeatMode = RepeatMode.None;
                }
                playList.RepeatMode = repeatMode;
            }

            return(true);
        }
Beispiel #2
0
        /// <summary>
        /// Handle an Playlist message received from a client
        /// </summary>
        /// <param name="message">Message</param>
        /// <param name="socketServer">Socket server</param>
        /// <param name="sender">Sender</param>
        internal static void HandlePlaylistMessage(Newtonsoft.Json.Linq.JObject message, SocketServer socketServer, Deusty.Net.AsyncSocket sender)
        {
            String action       = (string)message["PlaylistAction"];
            String playlistType = (message["PlaylistType"] != null) ? (string)message["PlaylistType"] : "music";
            bool   shuffle      = (message["Shuffle"] != null) ? (bool)message["Shuffle"] : false;
            bool   autoPlay     = (message["AutoPlay"] != null) ? (bool)message["AutoPlay"] : false;
            bool   showPlaylist = (message["ShowPlaylist"] != null) ? (bool)message["ShowPlaylist"] : true;

            if (action.Equals("new") || action.Equals("append"))
            {
                //new playlist or append to playlist
                int insertIndex = 0;
                if (message["InsertIndex"] != null)
                {
                    insertIndex = (int)message["InsertIndex"];
                }

                // Add items from JSON or SQL
                JArray  array = (message["PlaylistItems"] != null) ? (JArray)message["PlaylistItems"] : null;
                JObject sql   = (message["PlayListSQL"] != null) ? (JObject)message["PlayListSQL"] : null;
                if (array != null || sql != null)
                {
                    if (action.Equals("new"))
                    {
                        PlaylistHelper.ClearPlaylist(playlistType, false);
                    }

                    int index = insertIndex;

                    if (array != null)
                    {
                        // Add items from JSON
                        foreach (JObject o in array)
                        {
                            PlaylistEntry entry = new PlaylistEntry();
                            entry.FileName = (o["FileName"] != null) ? (string)o["FileName"] : null;
                            entry.Name     = (o["Name"] != null) ? (string)o["Name"] : null;
                            entry.Duration = (o["Duration"] != null) ? (int)o["Duration"] : 0;
                            PlaylistHelper.AddItemToPlaylist(playlistType, entry, index, false);
                            index++;
                        }
                        PlaylistHelper.RefreshPlaylistIfVisible();

                        if (shuffle)
                        {
                            PlaylistHelper.Shuffle(playlistType);
                        }
                    }
                    else
                    {
                        // Add items with SQL
                        string where = (sql["Where"] != null) ? (string)sql["Where"] : String.Empty;
                        int limit = (sql["Limit"] != null) ? (int)sql["Limit"] : 0;

                        PlaylistHelper.AddSongsToPlaylistWithSQL(playlistType, where, limit, shuffle, insertIndex);
                    }

                    if (autoPlay)
                    {
                        if (message["StartPosition"] != null)
                        {
                            int startPos = (int)message["StartPosition"];
                            insertIndex += startPos;
                        }
                        PlaylistHelper.StartPlayingPlaylist(playlistType, insertIndex, showPlaylist);
                    }
                }
            }
            else if (action.Equals("load"))
            {
                //load a playlist
                string playlistName = (string)message["PlayListName"];
                string playlistPath = (string)message["PlaylistPath"];

                if (!string.IsNullOrEmpty(playlistName) || !string.IsNullOrEmpty(playlistPath))
                {
                    PlaylistHelper.LoadPlaylist(playlistType, (!string.IsNullOrEmpty(playlistName)) ? playlistName : playlistPath, shuffle);
                    if (autoPlay)
                    {
                        PlaylistHelper.StartPlayingPlaylist(playlistType, 0, showPlaylist);
                    }
                }
            }
            else if (action.Equals("get"))
            {
                //get all playlist items of the currently active playlist
                List <PlaylistEntry> items = PlaylistHelper.GetPlaylistItems(playlistType);

                MessagePlaylistDetails returnPlaylist = new MessagePlaylistDetails();
                returnPlaylist.PlaylistType   = playlistType;
                returnPlaylist.PlaylistName   = PlaylistHelper.GetPlaylistName(playlistType);
                returnPlaylist.PlaylistRepeat = PlaylistHelper.GetPlaylistRepeat(playlistType);
                returnPlaylist.PlaylistItems  = items;

                socketServer.SendMessageToClient(returnPlaylist, sender);
            }
            else if (action.Equals("remove"))
            {
                //remove an item from the playlist
                int indexToRemove = (message["Index"] != null) ? (int)message["Index"] : 0;

                PlaylistHelper.RemoveItemFromPlaylist(playlistType, indexToRemove);
            }
            else if (action.Equals("move"))
            {
                //move a playlist item to a new index
                int oldIndex = (message["OldIndex"] != null) ? (int)message["OldIndex"] : 0;
                int newIndex = (message["NewIndex"] != null) ? (int)message["NewIndex"] : 0;
                PlaylistHelper.ChangePlaylistItemPosition(playlistType, oldIndex, newIndex);
            }
            else if (action.Equals("play"))
            {
                //start playback of a playlist item
                int index = (message["Index"] != null) ? (int)message["Index"] : 0;
                PlaylistHelper.StartPlayingPlaylist(playlistType, index, showPlaylist);
            }
            else if (action.Equals("clear"))
            {
                //clear the playlist
                PlaylistHelper.ClearPlaylist(playlistType, true);
            }
            else if (action.Equals("list"))
            {
                //get a list of all available playlists
                MessagePlaylists returnList = new MessagePlaylists();
                returnList.PlayLists = PlaylistHelper.GetPlaylists();
                socketServer.SendMessageToClient(returnList, sender);
            }
            else if (action.Equals("save"))
            {
                //save the current playlist to file
                String name = (message["Name"] != null) ? (String)message["Name"] : null;
                if (name != null)
                {
                    PlaylistHelper.SaveCurrentPlaylist(name);
                }
                else
                {
                    WifiRemote.LogMessage("Must specify a name to save a playlist", WifiRemote.LogType.Warn);
                }
            }
            else if (action.Equals("shuffle"))
            {
                PlaylistHelper.Shuffle(playlistType);
            }
            else if (action.Equals("repeat"))
            {
                WifiRemote.LogMessage("Playlist action repeat", WifiRemote.LogType.Debug);
                if (message["Repeat"] != null)
                {
                    bool repeat = (bool)message["Repeat"];
                    PlaylistHelper.Repeat(playlistType, repeat);
                }
                else
                {
                    WifiRemote.LogMessage("Must specify repeat to change playlist repeat mode", WifiRemote.LogType.Warn);
                }
            }
        }