/// <summary> /// A client closed the connection. /// </summary> /// <param name="sender"></param> private void NewSocket_DidClose(AsyncSocket sender) { // Remove the client from the client list. lock (connectedSockets) { Logger.Info("WifiRemote: Removing client " + sender.GetRemoteClient().ClientName + " from connected sockets"); connectedSockets.Remove(sender); } }
private void SendAuthenticationResponse(AsyncSocket socket, bool _success) { MessageAuthenticationResponse authResponse = new MessageAuthenticationResponse(_success); if (!_success) { authResponse.ErrorMessage = "Login failed"; } else { Logger.Debug("WifiRemote: Client identified: " + socket.GetRemoteClient().ToString()); string key = GetRandomMD5(); authResponse.AutologinKey = key; _loginTokens.Add(new AutoLoginToken(key, socket.GetRemoteClient())); } SendMessageToClient.Send(authResponse, socket, true); }
public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender) { string action = GetMessageValue <string>(message, "Action"); var client = sender.GetRemoteClient(); if (!string.IsNullOrEmpty(action)) { string search = GetMessageValue <string>(message, "Search"); int count = GetMessageValue <int>(message, "Count", 10); int offset = GetMessageValue <int>(message, "Offset"); string recordingName = GetMessageValue <string>(message, "RecordingName"); string id = GetMessageValue <string>(message, "RecordingId"); int startPos = GetMessageValue <int>(message, "StartPosition"); // Search for recordings if (action.Equals("recordingsearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <RecordingInfo>(client, search, Convert.ToUInt32(count), null, Helper.GetRecordingsByRecordingSearchAsync); SendMessageToClient.Send(new MessageRecordings { Recordings = list }, sender, true); } // Show recording list else if (action.Equals("recordinglist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <RecordingInfo>(client, null, Convert.ToUInt32(offset), Convert.ToUInt32(count), Helper.GetRecordingsByRecordingSearchAsync); SendMessageToClient.Send(new MessageRecordings { Recordings = list }, sender, true); } // Show details for this recording else if (action.Equals("recordingdetails", StringComparison.InvariantCultureIgnoreCase)) { // TODO: implementation possible? } // Play a recording else if (action.Equals("playrecording", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Recording: RecordingName: {0}, RecordingId: {1}, StartPos: {2}", recordingName, id, startPos); var mediaItemGuid = await GetIdFromNameAsync(client, recordingName, id, Helper.GetRecordingByRecordingNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Recording: Couldn't convert RecordingId '{0} to Guid", id); return(false); } await Helper.PlayMediaItemAsync(mediaItemGuid.Value, startPos); } } return(true); }
public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender) { string action = GetMessageValue <string>(message, "Action"); var client = sender.GetRemoteClient(); if (!string.IsNullOrEmpty(action)) { string search = GetMessageValue <string>(message, "Search"); int count = GetMessageValue <int>(message, "Count", 10); int offset = GetMessageValue <int>(message, "Offset"); string imagePath = GetMessageValue <string>(message, "ImagePath"); string id = GetMessageValue <string>(message, "ImageId"); // Search for image if (action.Equals("imagesearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <ImageInfo>(client, search, Convert.ToUInt32(count), null, Helper.GetImagesByImageSearchAsync); SendMessageToClient.Send(new MessageImages { Images = list }, sender, true); } // Show image list else if (action.Equals("imagelist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <ImageInfo>(client, null, Convert.ToUInt32(count), Convert.ToUInt32(offset), Helper.GetImagesByImageSearchAsync); SendMessageToClient.Send(new MessageImages { Images = list }, sender, true); } else // Show image if (action.Equals("playimage", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Image: ImageId: {0}, ImagePath: {1}, ", id, imagePath); var mediaItemGuid = await GetIdFromNameAsync(client, imagePath, id, Helper.GetMediaItemByFileNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Image: Couldn't convert ImageId '{0} to Guid", id); return(false); } await Helper.PlayMediaItemAsync(mediaItemGuid.Value, 0); } } return(true); }
/// <summary> /// Send a message to a specific client /// </summary> /// <param name="message">The message</param> /// <param name="client">A connected client socket</param> /// <param name="ignoreAuth">False if messages should only be sent to authed clients</param> public static void Send(string message, AsyncSocket client, bool ignoreAuth) { if (message == null) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: SendMessageToClient failed: Message string is null"); return; } byte[] data = Encoding.UTF8.GetBytes(message + "\r\n"); if (client.GetRemoteClient().IsAuthenticated || ignoreAuth) { client.Write(data, -1, 0); } else { ServiceRegistration.Get <ILogger>().Info("WifiRemote: SendMessageToClient failed: No Auth: {0}, ignoreAuth: {1}", client.GetRemoteClient().IsAuthenticated, ignoreAuth); } }
public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender) { string action = GetMessageValue <string>(message, "Action"); var client = sender.GetRemoteClient(); if (!string.IsNullOrEmpty(action)) { string search = GetMessageValue <string>(message, "Search"); int count = GetMessageValue <int>(message, "Count", 10); int offset = GetMessageValue <int>(message, "Offset"); int id = GetMessageValue <int>(message, "ScheduleId"); // Search for schedule if (action.Equals("schedulesearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetSchedulesAsync(); SendMessageToClient.Send(new MessageSchedules { Schedules = list.Where(p => p.Name.Contains(search)).OrderBy(p => p.StartTime).Select(p => new ScheduleInfo(p)).ToList() }, sender, true); } // Show schedule list else if (action.Equals("schedulelist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetSchedulesAsync(); SendMessageToClient.Send(new MessageSchedules { Schedules = list.OrderBy(p => p.StartTime).Select(p => new ScheduleInfo(p)).ToList() }, sender, true); } // Show details for this schedule else if (action.Equals("scheduledetails", StringComparison.InvariantCultureIgnoreCase)) { // TODO: implementation possible? } // Delete schedule else if (action.Equals("deleteschedule", StringComparison.InvariantCultureIgnoreCase)) { await RemoveSchedulesAsync(id); } } return(true); }
public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender) { string fileType = GetMessageValue <string>(message, "FileType"); string filePath = GetMessageValue <string>(message, "FilePath"); string id = GetMessageValue <string>(message, "FileId"); int startPos = GetMessageValue <int>(message, "StartPosition"); var client = sender.GetRemoteClient(); ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play File: FileType: {0}, FilePath: {1}, FileId: {2}, StartPos: {3}", fileType, filePath, id, startPos); var mediaItemGuid = await GetIdFromNameAsync(client, filePath, id, Helper.GetMediaItemByFileNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play File: Couldn't convert FileId '{0} to Guid", id); return(false); } await Helper.PlayMediaItemAsync(mediaItemGuid.Value, startPos); return(true); }
public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender, bool isTV) { string action = GetMessageValue <string>(message, "Action"); var client = sender.GetRemoteClient(); if (!string.IsNullOrEmpty(action)) { int channelGroupId = GetMessageValue <int>(message, "ChannelGroupId"); int channelId = GetMessageValue <int>(message, "ChannelId"); string search = GetMessageValue <string>(message, "Search"); int hours = GetMessageValue <int>(message, "Hours", 1); int count = GetMessageValue <int>(message, "Count", 10); int offset = GetMessageValue <int>(message, "Offset"); bool startFullscreen = GetMessageValue <bool>(message, "StartFullscreen", true); // Show channel group list if (action.Equals("grouplist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetChannelGroupsAsync(isTV); SendMessageToClient.Send(new MessageChannelGroups { ChannelGroups = list.Select(g => new ChannelGroupInfo(g)).ToList() }, sender, true); } // Search group EPG else if (action.Equals("groupepgsearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetEpgAsync(channelGroupId, hours, isTV); SendMessageToClient.Send(new MessagePrograms { Programs = list.Where(p => p.Title.Contains(search)).OrderBy(p => p.StartTime).Select(p => new ProgramInfo(p)).ToList() }, sender, true); } // Show group EPG else if (action.Equals("groupepglist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetEpgAsync(channelGroupId, hours, isTV); SendMessageToClient.Send(new MessagePrograms { Programs = list.OrderBy(p => p.StartTime).Select(p => new ProgramInfo(p)).ToList() }, sender, true); } // Search for channel else if (action.Equals("channelsearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetChannelsAsync(channelGroupId, isTV); SendMessageToClient.Send(new MessageChannels { Channels = list.Where(c => c.Name.StartsWith(search)).OrderBy(c => c.Name).Select(c => new ChannelInfo(c)).ToList() }, sender, true); } // Show channel list else if (action.Equals("channellist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetChannelsAsync(channelGroupId, isTV); SendMessageToClient.Send(new MessageChannels { Channels = list.OrderBy(c => c.Name).Skip(offset).Take(count).Select(c => new ChannelInfo(c)).ToList() }, sender, true); } //Search channel EPG else if (action.Equals("channelepgsearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <VideoInfo>(client, search, Convert.ToUInt32(count), null, Helper.GetVideosByVideoSearchAsync); SendMessageToClient.Send(new MessageVideos { Videos = list }, sender, true); } // Show channel EPG else if (action.Equals("channelepglist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetChannelEpgAsync(channelId, hours, isTV); SendMessageToClient.Send(new MessagePrograms { Programs = list.Where(p => p.Title.Contains(search)).OrderBy(p => p.StartTime).Select(p => new ProgramInfo(p)).ToList() }, sender, true); } // Show details for this channel else if (action.Equals("channeldetails", StringComparison.InvariantCultureIgnoreCase)) { // TODO: implementation possible? } // Play a channel else if (action.Equals("playchannel", StringComparison.InvariantCultureIgnoreCase)) { return(await PlayChannelAsync(channelId)); } } return(true); }
public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender) { string action = GetMessageValue <string>(message, "Action"); var client = sender.GetRemoteClient(); if (!string.IsNullOrEmpty(action)) { string search = GetMessageValue <string>(message, "Search"); int offset = GetMessageValue <int>(message, "Offset"); int count = GetMessageValue <int>(message, "Count", 10); string seriesName = GetMessageValue <string>(message, "SeriesName"); int seasonNum = GetMessageValue <int>(message, "SeasonNumber"); string id = GetMessageValue <string>(message, "SeriesId"); int episodeNum = GetMessageValue <int>(message, "EpisodeNumber"); int startPos = GetMessageValue <int>(message, "StartPosition"); bool onlyUnwatched = GetMessageValue <bool>(message, "OnlyUnwatchedEpisodes"); // Search for series if (action.Equals("seriessearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <SeriesShowInfo>(client, search, Convert.ToUInt32(count), null, Helper.GetSeriesBySeriesSearchAsync); SendMessageToClient.Send(new MessageSeries { Series = list }, sender, true); } // Show series list else if (action.Equals("serieslist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <SeriesShowInfo>(client, null, Convert.ToUInt32(count), Convert.ToUInt32(offset), Helper.GetSeriesBySeriesSearchAsync); SendMessageToClient.Send(new MessageSeries { Series = list }, sender, true); } // Show season list for series else if (action.Equals("seasonlist", StringComparison.InvariantCultureIgnoreCase)) { var mediaItemGuid = await GetIdFromNameAsync(client, seriesName, id, Helper.GetSeriesBySeriesNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: List Seasons: Couldn't convert SeriesId '{0} to Guid", id); return(false); } var list = await Helper.GetSeasonsBySeriesIdAsync(client.UserId, mediaItemGuid.Value); SendMessageToClient.Send(new MessageSeasons { Seasons = list.Select(i => new SeriesSeasonInfo(i)).ToList() }, sender, true); } // Show episode list for series season else if (action.Equals("episodelist", StringComparison.InvariantCultureIgnoreCase)) { var mediaItemGuid = await GetIdFromNameAsync(client, seriesName, id, Helper.GetSeriesBySeriesNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: List Episodes: Couldn't convert SeriesId '{0} to Guid", id); return(false); } var list = await Helper.GetEpisodesBySeriesSeasonAsync(client.UserId, mediaItemGuid.Value, seasonNum); SendMessageToClient.Send(new MessageEpisodes { Episodes = list.Select(i => new SeriesEpisodeInfo(i)).ToList() }, sender, true); } // Show movie details for this episode else if (action.Equals("episodetails", StringComparison.InvariantCultureIgnoreCase)) { // TODO: implementation possible? } // Play a episode else if (action.Equals("playepisode", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Episode: SeriesName: {0}, SeriesId: {1}, SeasonNumber: {2}, EpisodeNumber: {3}, StartPos: {4}", seriesName, id, seasonNum, episodeNum, startPos); var mediaItemGuid = await GetIdFromNameAsync(client, seriesName, id, Helper.GetSeriesBySeriesNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Episode: Couldn't convert SeriesId '{0} to Guid", id); return(false); } var episode = await Helper.GetEpisodeBySeriesEpisodeAsync(client.UserId, mediaItemGuid.Value, seasonNum, episodeNum); if (episode == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Episode: Couldn't find episode"); return(false); } await Helper.PlayMediaItemAsync(episode.MediaItemId, startPos); } else if (action.Equals("playunwatchedepisode", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Episode: SeriesName: {0}, SeriesId: {1}", seriesName, id); var mediaItemGuid = await GetIdFromNameAsync(client, seriesName, id, Helper.GetSeriesBySeriesNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Episode: Couldn't convert SeriesId '{0} to Guid", id); return(false); } var episodes = await Helper.GetEpisodesBySeriesIdAsync(client.UserId, mediaItemGuid.Value); if (!(episodes?.Count > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Episode: Couldn't find episodes"); return(false); } var episode = episodes.FirstOrDefault(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") < 100); if (episode == null) { episode = episodes.LastOrDefault(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") == 100); } if (episode == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Episode: Couldn't find episodes"); return(false); } await Helper.PlayMediaItemAsync(episode.MediaItemId, 0); } else if (action.Equals("playrandomepisode", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Episode: SeriesName: {0}, SeriesId: {1}", seriesName, id); var mediaItemGuid = await GetIdFromNameAsync(client, seriesName, id, Helper.GetSeriesBySeriesNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Episode: Couldn't convert SeriesId '{0} to Guid", id); return(false); } var episodes = await Helper.GetEpisodesBySeriesIdAsync(client.UserId, mediaItemGuid.Value); if (!(episodes?.Count > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Episode: Couldn't find episodes"); return(false); } var episodeList = episodes?.ToList(); var episodeIndex = new Random().Next(0, episodeList.Count - 1); await Helper.PlayMediaItemAsync(episodeList[episodeIndex].MediaItemId, 0); } else if (action.Equals("playseason", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Season: SeriesName: {0}, SeriesId: {1}, SeasonNumber: {2}, OnlyUnwatchedEpisodes: {3}", seriesName, id, seasonNum, onlyUnwatched); var mediaItemGuid = await GetIdFromNameAsync(client, seriesName, id, Helper.GetSeriesBySeriesNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Season: Couldn't convert SeriesId '{0} to Guid", id); return(false); } var items = await Helper.GetEpisodesBySeriesSeasonAsync(client.UserId, mediaItemGuid.Value, seasonNum); IEnumerable <MediaItem> episodes = null; if (onlyUnwatched) { episodes = items.Where(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") < 100); } else { episodes = items; } if (!(episodes?.Count() > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Season: Couldn't find any episodes"); return(false); } PlayItemsModel.CheckQueryPlayAction(() => episodes, UI.Presentation.Players.AVType.Video); } else if (action.Equals("playseries", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Series: SeriesName: {0}, SeriesId: {1}, OnlyUnwatchedEpisodes: {2}", seriesName, id, onlyUnwatched); var mediaItemGuid = await GetIdFromNameAsync(client, seriesName, id, Helper.GetSeriesBySeriesNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Series: Couldn't convert SeriesId '{0} to Guid", id); return(false); } var items = await Helper.GetEpisodesBySeriesIdAsync(client.UserId, mediaItemGuid.Value); IEnumerable <MediaItem> episodes = null; if (onlyUnwatched) { episodes = items.Where(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") < 100); } else { episodes = items; } if (!(episodes?.Count() > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Series: Couldn't find any episodes"); return(false); } PlayItemsModel.CheckQueryPlayAction(() => episodes, UI.Presentation.Players.AVType.Video); } } return(true); }
/// <summary> /// Read a message from the client. /// </summary> /// <param name="sender"></param> /// <param name="data"></param> /// <param name="tag"></param> private void NewSocket_DidRead(AsyncSocket sender, byte[] data, long tag) { string msg = null; try { msg = Encoding.UTF8.GetString(data); //comment this out to log all received commands //Logger.Debug("WifiRemote: " + msg); // Get json object JObject message = JObject.Parse(msg); string type = (string)message["Type"]; RemoteClient client = sender.GetRemoteClient(); // Autologin handling // Has to be activated in WifiRemote configuration. string clientKey = (string)message["AutologinKey"]; // Key is set: try to authenticate by AutoLoginKey if (clientKey != null && !client.IsAuthenticated) { if (AutologinTimeout > 0) { AutoLoginToken token = new AutoLoginToken(clientKey, client); // the client token is in the list foreach (AutoLoginToken aToken in _loginTokens) { if (aToken.Key == token.Key) { // Check if the autologin key was issued within the timeout TimeSpan elapsed = DateTime.Now - aToken.Issued; client.IsAuthenticated = (elapsed.Minutes < AutologinTimeout); client = aToken.Client; // Renew the timeout aToken.Issued = DateTime.Now; } } // MediaPortal was rebooted (will wipe all AutoLoginKeys) or // autologin time out period is over (configurable in settings). // // Tell the client to reauthenticate. if (!client.IsAuthenticated) { Logger.Debug("WifiRemote: AutoLoginToken timed out. Client needs to reauthenticate."); TellClientToReAuthenticate(sender); return; } } else { Logger.Debug("WifiRemote: AutoLogin is disabled but client tried to auto-authenticate."); TellClientToReAuthenticate(sender); return; } } // The client is already authentificated or we don't need authentification if (type != null && client.IsAuthenticated && type != "identify") { Func <JObject, SocketServer, AsyncSocket, Task <bool> > function; if (MessageType.TryGetValue(type, out function)) { Logger.Debug("WifiRemote: MessageType: {0} got called", type); function.Invoke(message, this, sender); } else { Logger.Warn("WifiRemote: Couldn't get MessageType: {0}", type); } } else { // user is not yet authenticated if (type == "identify") { // Save client name if supplied if (message["Name"] != null) { client.ClientName = (string)message["Name"]; } // Save client description if supplied if (message["Description"] != null) { client.ClientDescription = (string)message["Description"]; } // Save application name if supplied if (message["Application"] != null) { client.ApplicationName = (string)message["Application"]; } // Save application version if supplied if (message["Version"] != null) { client.ApplicationVersion = (string)message["Version"]; } // Authentication if (AllowedAuth == AuthMethod.None || CheckAuthenticationRequest(client, message["Authenticate"])) { // User successfully authenticated sender.GetRemoteClient().IsAuthenticated = true; SendAuthenticationResponse(sender, true); SendMessageOverviewInformation.Send(sender); } else { // Client sends a message other then authenticate when not yet // authenticated or authenticate failed SendAuthenticationResponse(sender, false); } } else { // Client needs to authenticate first TellClientToReAuthenticate(sender); } } } catch (Exception e) { Logger.Error("WifiRemote: Communication Error", e); } // Continue listening sender.Read(AsyncSocket.CRLFData, -1, 0); }
public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender) { string imagePath = GetMessageValue <string>(message, "ImagePath"); string userTag = GetMessageValue <string>(message, "UserTag"); int maxWidth = GetMessageValue <int>(message, "MaximumWidth"); int maxHeight = GetMessageValue <int>(message, "MaximumHeight"); string id = GetMessageValue <string>(message, "ImageId"); var client = sender.GetRemoteClient(); ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Get Image: UserTag: {0}, ImageId: {1}, ImagePath: {2}, MaximumWidth: {3}, MaximumHeight: {4}", userTag, id, imagePath, maxWidth, maxHeight); if (!string.IsNullOrEmpty(imagePath) && string.IsNullOrEmpty(id)) { var item = await Helper.GetMediaItemByFileNameAsync(client.UserId, imagePath); id = item?.MediaItemId.ToString(); } if (!Guid.TryParse(id, out Guid mediaItemGuid)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Get Image: Couldn't convert ImageId {0} to Guid", id); return(false); } MessageImage msg = new MessageImage(); var mediaItem = await Helper.GetMediaItemByIdAsync(client.UserId, mediaItemGuid); Image image = null; IResourceLocator locator = mediaItem.GetResourceLocator(); using (IResourceAccessor ra = locator.CreateAccessor()) { IFileSystemResourceAccessor fsra = ra as IFileSystemResourceAccessor; if (fsra == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Get Image: Couldn't read image {0}", id); return(false); } using (Stream stream = fsra.OpenRead()) { image = Image.FromStream(stream); } } if ((maxWidth > 0 && image.Width > maxWidth) || (maxHeight > 0 && image.Height > maxHeight)) { int height = image.Height; int width = image.Width; if (maxHeight > 0 && height > maxHeight) { float ratio = (float)height / (float)maxHeight; width = Convert.ToInt32((float)width / ratio); } if (maxWidth > 0 && width > maxWidth) { width = maxWidth; } var newImage = ImageHelper.ResizedImage(image, width); image.Dispose(); image = newImage; } byte[] data = ImageHelper.ImageToByteArray(image, System.Drawing.Imaging.ImageFormat.Jpeg); image?.Dispose(); msg.ImagePath = mediaItem.ToString(); msg.UserTag = userTag; msg.Image = Convert.ToBase64String(data); SendMessageToClient.Send(msg, sender); return(true); }
public static async Task <bool> ParseAsync(JObject message, SocketServer server, AsyncSocket sender) { string action = GetMessageValue <string>(message, "Action"); var client = sender.GetRemoteClient(); if (!string.IsNullOrEmpty(action)) { string search = GetMessageValue <string>(message, "Search"); int count = GetMessageValue <int>(message, "Count", 10); int offset = GetMessageValue <int>(message, "Offset"); string albumName = GetMessageValue <string>(message, "AlbumName"); string id = GetMessageValue <string>(message, "AlbumId"); int discNum = GetMessageValue <int>(message, "DiscNumber"); int trackNum = GetMessageValue <int>(message, "TrackNumber"); int startPos = GetMessageValue <int>(message, "StartPosition"); bool onlyUnwatched = GetMessageValue <bool>(message, "OnlyUnplayedTracks"); // Search for album if (action.Equals("albumsearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <MusicAlbumInfo>(client, search, Convert.ToUInt32(count), null, Helper.GetAlbumsByAlbumSearchAsync); SendMessageToClient.Send(new MessageAlbums { Albums = list }, sender, true); } // Show album list else if (action.Equals("albumlist", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <MusicAlbumInfo>(client, null, Convert.ToUInt32(count), Convert.ToUInt32(offset), Helper.GetAlbumsByAlbumSearchAsync); SendMessageToClient.Send(new MessageAlbums { Albums = list }, sender, true); } // Search for track if (action.Equals("tracksearch", StringComparison.InvariantCultureIgnoreCase)) { var list = await GetItemListAsync <MusicInfo>(client, search, Convert.ToUInt32(count), null, Helper.GetTracksByTrackSearchAsync); SendMessageToClient.Send(new MessageMusic { Music = list }, sender, true); } // Show track list for album else if (action.Equals("tracklist", StringComparison.InvariantCultureIgnoreCase)) { var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: List Tracks: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var list = await Helper.GetTracksByAlbumIdAsync(client.UserId, mediaItemGuid.Value); SendMessageToClient.Send(new MessageMusic { Music = list.Select(i => new MusicInfo(i)).ToList() }, sender, true); } // Show track details for this track else if (action.Equals("tracktails", StringComparison.InvariantCultureIgnoreCase)) { // TODO: implementation possible? } // Play a track else if (action.Equals("playtrack", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Track: AlbumName: {0}, AlbumId: {1}, DiscNumber: {2}, TrackNumber: {3}, StartPos: {4}", albumName, id, discNum, trackNum, startPos); var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var episode = await Helper.GetTrackByAlbumTrackAsync(client.UserId, mediaItemGuid.Value, discNum, trackNum); if (!(episode?.Count > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't find track"); return(false); } await Helper.PlayMediaItemAsync(episode.First().MediaItemId, startPos); } else if (action.Equals("playunplayedtrack", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote Play Track: AlbumName: {0}, AlbumId: {1}", albumName, id); var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var tracks = await Helper.GetTracksByAlbumIdAsync(client.UserId, mediaItemGuid.Value); if (!(tracks?.Count > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't find track"); return(false); } var track = tracks.FirstOrDefault(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") < 100); if (track == null) { track = tracks.LastOrDefault(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") == 100); } if (track == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't find tracks"); return(false); } await Helper.PlayMediaItemAsync(track.MediaItemId, 0); } else if (action.Equals("playrandomtrack", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Track: AlbumName: {0}, AlbumId: {1}", albumName, id); var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var tracks = await Helper.GetTracksByAlbumIdAsync(client.UserId, mediaItemGuid.Value); if (!(tracks?.Count > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Track: Couldn't find tracks"); return(false); } var trackList = tracks?.ToList(); var episodeIndex = new Random().Next(0, trackList.Count - 1); await Helper.PlayMediaItemAsync(trackList[episodeIndex].MediaItemId, 0); } else if (action.Equals("playalbum", StringComparison.InvariantCultureIgnoreCase)) { ServiceRegistration.Get <ILogger>().Debug("WifiRemote: Play Album: AlbumName: {0}, AlbumId: {1}, OnlyUnplayedTracks: {2}", albumName, id, onlyUnwatched); var mediaItemGuid = await GetIdFromNameAsync(client, albumName, id, Helper.GetAlbumByAlbumNameAsync); if (mediaItemGuid == null) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Album: Couldn't convert AlbumId '{0} to Guid", id); return(false); } var items = await Helper.GetTracksByAlbumIdAsync(client.UserId, mediaItemGuid.Value); IEnumerable <MediaItem> tracks = null; if (onlyUnwatched) { tracks = items.Where(e => Convert.ToInt32(e.UserData.FirstOrDefault(d => d.Key == UserDataKeysKnown.KEY_PLAY_PERCENTAGE).Value ?? "0") < 100); } else { tracks = items; } if (!(tracks?.Count() > 0)) { ServiceRegistration.Get <ILogger>().Error("WifiRemote: Play Album: Couldn't find any tracks"); return(false); } PlayItemsModel.CheckQueryPlayAction(() => tracks, UI.Presentation.Players.AVType.Audio); } } return(true); }
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); }