/// <summary> /// Play episode async /// </summary> /// <param name="episode">Episode to play</param> /// <param name="startPosition">Postion from where playback should be started (only valid if resum=false)</param> /// <param name="resume">Resume from last stop?</param> private static void DoPlayEpisode(DBEpisode episode, bool resume, int startPosition) { if (GUIGraphicsContext.form.InvokeRequired) { PlayEpisodeAsyncDelegate d = new PlayEpisodeAsyncDelegate(DoPlayEpisode); GUIGraphicsContext.form.Invoke(d, new object[] { episode, resume, startPosition }); return; } WifiRemote.LogMessage("Play episode (resume: " + resume + ", pos: " + startPosition, WifiRemote.LogType.Debug); if (player == null) { player = new VideoHandler(); } // Reset stopTime if resume is false if (!resume) { episode[DBEpisode.cStopTime] = 0; } player.ResumeOrPlay((DBEpisode)episode); if (!resume && startPosition > 0) { g_Player.SeekAbsolute(startPosition); } }
/// <summary> /// Get a movie object by movie name /// </summary> /// <param name="movieName">Name of a movie</param> /// <returns>Returns a movie object or null if no movie was found.</returns> private static DBMovieInfo GetMovieByName(string movieName) { ICriteria titleFilter = new BaseCriteria(DBField.GetField(typeof(DBMovieInfo), "Title"), "like", "%" + movieName + "%"); List <DBMovieInfo> foundMovies = MovingPicturesCore.DatabaseManager.Get <DBMovieInfo>(titleFilter); // If there are more than one result return the movie with an exact title // match or first movie if no exact match was found if (foundMovies.Count > 1) { foreach (DBMovieInfo movie in foundMovies) { if (movie.Title.ToLower().Equals(movieName.ToLower())) { return(movie); } } return(foundMovies[0]); } else { // Return the first and only movie or null if there was no result if (foundMovies.Count == 1) { return(foundMovies[0]); } else { WifiRemote.LogMessage("Could not find MovingPictures movie " + movieName, WifiRemote.LogType.Info); return(null); } } }
/// <summary> /// Playback the first unwatched episode for a series using TVSeries internal Video Handler /// If no Unwatched episodes exists, play the Most Recently Aired /// /// Taken from Trakt-for-MediaPortal: /// https://github.com/Technicolour/Trakt-for-Mediaportal/blob/master/TraktPlugin/TraktHandlers/TVSeries.cs /// </summary> /// <param name="seriesid">series id of episode</param> /// <param name="resume">Resume from last stop?</param> public static void PlayFirstUnwatchedEpisode(int seriesid, bool resume) { var episodes = DBEpisode.Get(seriesid); if (episodes == null || episodes.Count == 0) { return; } // filter out anything we can't play episodes.RemoveAll(e => string.IsNullOrEmpty(e[DBEpisode.cFilename])); if (episodes.Count == 0) { return; } // sort episodes using DBEpisode sort comparer // this takes into consideration Aired/DVD order and Specials in-line sorting episodes.Sort(); // get first episode unwatched, otherwise get most recently aired var episode = episodes.Where(e => e[DBOnlineEpisode.cWatched] == 0).FirstOrDefault(); if (episode == null) { WifiRemote.LogMessage("No Unwatched episodes found, Playing most recent episode", WifiRemote.LogType.Info); episode = episodes.LastOrDefault(); } if (episode != null) { PlayEpisode(episode, resume); } }
/// <summary> /// System power mode has changed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e) { // Resume from standby if (e.Mode == Microsoft.Win32.PowerModes.Resume) { WifiRemote.LogMessage("Resuming WifiRemote, starting server", LogType.Debug); // Restart the socket server InitAndStartSocket(); // Restart bonjour service if (!disableBonjour) { WifiRemote.LogMessage("Restarting bonjour service", LogType.Debug); PublishBonjourService(); } } // Going to standby else if (e.Mode == Microsoft.Win32.PowerModes.Suspend) { WifiRemote.LogMessage("Suspending WifiRemote, stopping server", LogType.Debug); // Stop bonjour service if (!disableBonjour) { publishService.Stop(); } // Stop socket server if (socketServer != null) { socketServer.Stop(); } } }
/// <summary> /// Constructor. /// </summary> public MessageNowPlaying() { // Check for "hookable" plugins isMovingPicturesAvailable = WifiRemote.IsAssemblyAvailable("MovingPictures", new Version(1, 0, 6, 1116)); isTVSeriesAvailable = WifiRemote.IsAssemblyAvailable("MP-TVSeries", new Version(2, 6, 3, 1242)); isFanartHandlerAvailable = WifiRemote.IsAssemblyAvailable("FanartHandler", new Version(2, 2, 1, 19191)); }
protected void screenshotReadyCheck(object sender, System.Timers.ElapsedEventArgs e) { ((System.Timers.Timer)sender).Stop(); if (IsScreenshotReady(screenshotPath)) { // MediaPortal completed writing the screenshot to disk // We can now grab and delete it processScreenshot(); screenshotOpenTries = 0; } else { if (screenshotOpenTries < maximumScreenshotOpenTries) { // Continue checking if the file is locked WifiRemote.LogMessage("Waiting for screenshot to be written ...", WifiRemote.LogType.Debug); screenshotOpenTries++; ((System.Timers.Timer)sender).Start(); } else { WifiRemote.LogMessage("Maximum number of screenshot open tries reached, aborting.", WifiRemote.LogType.Debug); OnScreenshotFailed(new ImageHelperError(ImageHelperError.ImageHelperErrorType.Timeout)); screenshotOpenTries = 0; } } }
/// <summary> /// Network status has changed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) { if (e.IsAvailable) { WifiRemote.LogMessage("Network connected, starting server", LogType.Debug); // Restart the socket server InitAndStartSocket(); // Restart bonjour service if (!disableBonjour) { WifiRemote.LogMessage("Restarting bonjour service", LogType.Debug); PublishBonjourService(); } } else { WifiRemote.LogMessage("Network lost, stopping server", LogType.Debug); // Stop bonjour service if (!disableBonjour) { publishService.Stop(); } // Stop socket server if (socketServer != null) { socketServer.Stop(); } } }
/// <summary> /// Constructor. /// </summary> /// <param name="filename">Filename of the currently played media file</param> public NowPlayingMovingPictures(string filename) { try { DBLocalMedia possibleMatches = DBLocalMedia.Get(filename); if (possibleMatches.AttachedMovies.Count > 0) { movieFound = true; DBMovieInfo match = possibleMatches.AttachedMovies[0]; ItemId = (int)match.ID; Title = match.Title; AlternateTitles = match.AlternateTitles.ToString(); Directors = match.Directors.ToString(); Writers = match.Writers.ToString(); Actors = match.Actors.ToString(); Year = match.Year; Genres = match.Genres.ToString(); Certification = match.Certification; Tagline = match.Tagline; Summary = match.Summary; Rating = match.Score.ToString(); DetailsUrl = match.DetailsURL; ImageName = match.CoverFullPath; } } catch (Exception e) { WifiRemote.LogMessage("Error getting now playing moving pictures: " + e.Message, WifiRemote.LogType.Error); } }
/// <summary> /// Start playing a movie on a seperate thread /// </summary> /// <param name="movie">Movie to play</param> /// <param name="resume">Ask user to resume?</param> private static void DoPlayMovie(DBMovieInfo movie, bool resume, int startPosition) { if (GUIGraphicsContext.form.InvokeRequired) { PlayMovieAsyncDelegate d = new PlayMovieAsyncDelegate(DoPlayMovie); GUIGraphicsContext.form.Invoke(d, new object[] { movie, resume, startPosition }); return; } WifiRemote.LogMessage("Play movie (resume: " + resume + ", pos: " + startPosition, WifiRemote.LogType.Debug); // Clear resume if (!resume && movie.UserSettings != null && movie.UserSettings.Count > 0) { DBUserMovieSettings userSetting = movie.ActiveUserSettings; userSetting.ResumePart = 0; userSetting.ResumeTime = 0; userSetting.ResumeData = null; userSetting.Commit(); } if (player == null) { player = new MoviePlayer(new MovingPicturesGUI()); } player.Play(movie); if (!resume && startPosition > 0) { g_Player.SeekAbsolute(startPosition); } }
/// <summary> /// Sends the dialog to all connected socket with a delay so we can /// read the list items /// </summary> /// <param name="_control"></param> private void SendDelayed(object _control) { MessageDialog msg = (MessageDialog)_control; WifiRemote.LogMessage("Sending delayed list dialog", LogType.Debug); MpDialogMenu dialog = msg.Dialog as MpDialogMenu; //get the items from the dialog dialog.RetrieveListItems(); socketServer.SendMessageToAllClients(msg); }
/// <summary> /// Play a movie with MovingPictures by ID. /// </summary> /// <param name="movieId">A MovingPictures movie id.</param> /// <param name="resume">Ask to resume movie?</param> /// <param name="startPosition">Position from which the video should start in seconds (e.g. StartPosition=180 will start the episode 3 minutes into the video). Will be ignored if AskToResume is true.</param> public static void PlayMovie(int movieId, bool resume, int startPosition = 0) { DBMovieInfo movie = DBMovieInfo.Get(movieId); if (movie == null) { WifiRemote.LogMessage("Could not find MovingPictures movie with id " + movieId.ToString(), WifiRemote.LogType.Info); } else { PlayMovie(movie, resume, startPosition); } }
/// <summary> /// Generate a QR Barcode with the server information /// </summary> private void GenerateBarcode() { try { ServerDescription desc = new ServerDescription(); desc.Port = Int32.Parse(textBoxPort.Text); desc.Name = textBoxName.Text; desc.HardwareAddresses = WifiRemote.GetHardwareAddresses(); desc.Hostname = WifiRemote.GetServiceName(); IPHostEntry host; String localIP = "?"; StringBuilder localIPs = new StringBuilder(); host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork || ip.AddressFamily == AddressFamily.InterNetworkV6) { // Single address field localIP = ip.ToString(); // Multiple addresses field if (localIPs.Length > 0) { localIPs.Append(";"); } localIPs.Append(ip.ToString()); } } desc.Address = localIP; desc.Addresses = (localIPs.Length > 0) ? localIPs.ToString() : "?"; desc.AuthOptions = cbAuthMethod.SelectedIndex; if (checkBoxIncludeAuth.Checked) { desc.User = txtUsername.Text; desc.Password = txtPassword.Text; desc.Passcode = txtPasscode.Text; } Bitmap bm = QRCodeGenerator.Generate(JsonConvert.SerializeObject(desc)); pbQrCode.Image = bm; } catch (Exception ex) { Log.Error("[WifiRemote Setup] Error generating barcode: {0}", ex.Message); } }
/// <summary> /// Save changed vars to mediaportal settings file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SetupForm_FormClosing(object sender, FormClosingEventArgs e) { try { UInt16 portCheck = UInt16.Parse(textBoxPort.Text); if (portCheck == 0) { resetPort(); } } catch (Exception) { resetPort(); } using (MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) { xmlwriter.SetValue(WifiRemote.PLUGIN_NAME, "port", textBoxPort.Text); xmlwriter.SetValueAsBool(WifiRemote.PLUGIN_NAME, "disableBonjour", checkBoxDisableBonjour.Checked); xmlwriter.SetValue(WifiRemote.PLUGIN_NAME, "serviceName", textBoxName.Text); xmlwriter.SetValue(WifiRemote.PLUGIN_NAME, "username", WifiRemote.EncryptString(txtUsername.Text)); xmlwriter.SetValue(WifiRemote.PLUGIN_NAME, "password", WifiRemote.EncryptString(txtPassword.Text)); xmlwriter.SetValue(WifiRemote.PLUGIN_NAME, "passcode", WifiRemote.EncryptString(txtPasscode.Text)); xmlwriter.SetValue(WifiRemote.PLUGIN_NAME, "auth", cbAuthMethod.SelectedIndex); xmlwriter.SetValue(WifiRemote.PLUGIN_NAME, "autologinTimeout", numericUpDownAutologin.Value); xmlwriter.SetValueAsBool(WifiRemote.PLUGIN_NAME, "showNotifications", checkBoxShowConnectionMessage.Checked); // Save plugins order, custom names and if they should be displayed List <string> pluginIdsToSave = new List <String>(); foreach (WindowPlugin plugin in pluginsDataSource) { pluginIdsToSave.Add(plugin.WindowId.ToString()); pluginIdsToSave.Add(plugin.Name); // Don't display plugin if (!plugin.DisplayPlugin && !ignoredPluginsList.Contains(plugin.WindowId)) { // Plugin disabled, add to ignored plugins list ignoredPluginsList.Add(plugin.WindowId); } else if (plugin.DisplayPlugin && ignoredPluginsList.Contains(plugin.WindowId)) { // Plugin not disabled but on disabled list. Remove it. ignoredPluginsList.Remove(plugin.WindowId); } } xmlwriter.SetValue(WifiRemote.PLUGIN_NAME, "savedPlugins", String.Join("|", pluginIdsToSave.ToArray())); xmlwriter.SetValue(WifiRemote.PLUGIN_NAME, "ignoredPlugins", String.Join("|", ignoredPluginsList.ConvertAll <string>(x => x.ToString()).ToArray())); } }
/// <summary> /// Constructor. /// </summary> /// <param name="filename">Filename of the currently played episode</param> public NowPlayingSeries(string filename) { try { SQLCondition query = new SQLCondition(new DBEpisode(), DBEpisode.cFilename, filename, SQLConditionType.Equal); List <DBEpisode> episodes = DBEpisode.Get(query); if (episodes.Count > 0) { episodeFound = true; SeriesId = episodes[0].onlineEpisode[DBOnlineEpisode.cSeriesID]; SeasonId = episodes[0].onlineEpisode[DBOnlineEpisode.cSeasonID]; EpisodeId = episodes[0].onlineEpisode[DBOnlineEpisode.cID]; CompositeId = episodes[0].fullItem[DBEpisode.cCompositeID]; Episode = episodes[0].onlineEpisode[DBOnlineEpisode.cEpisodeIndex]; Season = episodes[0].onlineEpisode[DBOnlineEpisode.cSeasonIndex]; Plot = episodes[0].onlineEpisode[DBOnlineEpisode.cEpisodeSummary]; Title = episodes[0].onlineEpisode[DBOnlineEpisode.cEpisodeName]; Director = episodes[0].onlineEpisode[DBOnlineEpisode.cDirector]; Writer = episodes[0].onlineEpisode[DBOnlineEpisode.cWriter]; Rating = episodes[0].onlineEpisode[DBOnlineEpisode.cRating]; MyRating = episodes[0].onlineEpisode[DBOnlineEpisode.cMyRating]; RatingCount = episodes[0].onlineEpisode[DBOnlineEpisode.cRatingCount]; AirDate = episodes[0].onlineEpisode[DBOnlineEpisode.cFirstAired]; DBSeries s = Helper.getCorrespondingSeries(episodes[0].onlineEpisode[DBOnlineEpisode.cSeriesID]); Series = s[DBOnlineSeries.cPrettyName]; Status = s[DBOnlineSeries.cStatus]; Genre = s[DBOnlineSeries.cGenre]; // Get season poster path DBSeason season = DBSeason.getRaw(SeriesId, episodes[0].onlineEpisode[DBOnlineEpisode.cSeasonIndex]); ImageName = ImageAllocator.GetSeasonBannerAsFilename(season); // Fall back to series poster if no season poster is available if (String.IsNullOrEmpty(ImageName)) { ImageName = ImageAllocator.GetSeriesPosterAsFilename(s); } } } catch (Exception e) { WifiRemote.LogMessage("Error getting now playing tvseries: " + e.Message, WifiRemote.LogType.Error); } }
/// <summary> /// Plays the local audio file on the MediaPortal client /// </summary> /// <param name="audio">Path to the audio file</param> /// <param name="position">Position with in the file (in ms)</param> internal void PlayAudioFile(string audio, double position) { if (audio != null && File.Exists(audio)) { WifiRemote.LogMessage("Play audio file: " + audio + ", pos: " + position, WifiRemote.LogType.Debug); if (PlayListPlayer.SingletonPlayer.g_Player != null) { PlayListPlayer.SingletonPlayer.g_Player.Stop(); } g_Player.Play(audio, g_Player.MediaType.Music); if (position != 0) { g_Player.SeekAbsolute(position); } } }
/// <summary> /// Encrypt a setting string /// </summary> /// <param name="decrypted">An unencrypted string</param> /// <returns>The string encrypted</returns> internal static string EncryptString(string decrypted) { EncryptDecrypt Crypto = new EncryptDecrypt(); string encrypted = String.Empty; try { encrypted = Crypto.Encrypt(decrypted); } catch (Exception) { WifiRemote.LogMessage("Could not encrypt setting string!", LogType.Error); encrypted = null; } return(encrypted); }
/// <summary> /// Decrypt an encrypted setting string /// </summary> /// <param name="encrypted">The string to decrypt</param> /// <returns>The decrypted string or an empty string if something went wrong</returns> internal static string DecryptString(string encrypted) { string decrypted = String.Empty; EncryptDecrypt Crypto = new EncryptDecrypt(); try { decrypted = Crypto.Decrypt(encrypted); } catch (Exception) { WifiRemote.LogMessage("Could not decrypt config string!", LogType.Error); decrypted = null; } return(decrypted); }
/// <summary> /// Create a PlayListItem from a given movie id /// </summary> /// <param name="movieId">id of movie</param> /// <returns>PlayListItem object from movie id</returns> internal static MediaPortal.Playlists.PlayListItem CreatePlaylistItem(int movieId) { DBMovieInfo movie = DBMovieInfo.Get(movieId); if (movie == null) { WifiRemote.LogMessage("Could not find MovingPictures movie with id " + movieId.ToString(), WifiRemote.LogType.Info); } else { PlayListItem item = new PlayListItem(); item.FileName = movie.LocalMedia[0].FullPath; item.Description = movie.Title; item.Duration = movie.LocalMedia[0].Duration / 1000; return(item); } return(null); }
/// <summary> /// Initialise the socket server if necessary /// </summary> internal void InitAndStartSocket() { if (socketServer == null) { WifiRemote.LogMessage("Setting up socket server", LogType.Debug); String userName = null; String password = null; String passcode = null; AuthMethod auth = AuthMethod.None; int autologinTimeout = 0; bool showNotification = false; // Load port from config using (MediaPortal.Profile.Settings reader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) { port = (UInt16)reader.GetValueAsInt(PLUGIN_NAME, "port", DEFAULT_PORT); disableBonjour = reader.GetValueAsBool(PLUGIN_NAME, "disableBonjour", false); serviceName = reader.GetValueAsString(PLUGIN_NAME, "serviceName", ""); userName = reader.GetValueAsString(PLUGIN_NAME, "username", ""); userName = WifiRemote.DecryptString(userName); password = reader.GetValueAsString(PLUGIN_NAME, "password", ""); password = WifiRemote.DecryptString(password); passcode = reader.GetValueAsString(PLUGIN_NAME, "passcode", ""); passcode = WifiRemote.DecryptString(passcode); auth = (AuthMethod)reader.GetValueAsInt(PLUGIN_NAME, "auth", 0); autologinTimeout = reader.GetValueAsInt(PLUGIN_NAME, "autologinTimeout", 0); showNotification = reader.GetValueAsBool(PLUGIN_NAME, "showNotifications", false); } // Start listening for client connections socketServer = new SocketServer(port); socketServer.UserName = userName; socketServer.Password = password; socketServer.PassCode = passcode; socketServer.AllowedAuth = auth; socketServer.AutologinTimeout = autologinTimeout; socketServer.ShowNotifications = showNotification; } socketServer.Start(); }
/// <summary> /// Make MediaPortal take a screenshot, take that and delete it /// from disk. First we need to check if the screenshot folder already exists. /// See https://github.com/MediaPortal/MediaPortal-1/blob/cae80bd6dd2241bd7182c39418373bee545bf464/mediaportal/MediaPortal.Application/MediaPortal.cs#L3611 /// </summary> public void TakeScreenshot() { // Only take one screenshot at a time, all requests // will be served from that screenshot. if (takingScreenshot) { return; } takingScreenshot = true; // MediaPortal doesn't output events for new screenshots so we 'manually' // watch the screenshot folder setupFileSystemWatcher(); if (watcher == null) { // Something went wrong creating the filesystem watcher takingScreenshot = false; OnScreenshotFailed(new ImageHelperError(ImageHelperError.ImageHelperErrorType.WatcherCreate)); return; } if (!watcher.EnableRaisingEvents) { try { watcher.EnableRaisingEvents = true; } catch (Exception e) { WifiRemote.LogMessage(String.Format("Could not watch the screenshots folder: {0}", e.Message), WifiRemote.LogType.Error); watcher = null; takingScreenshot = false; OnScreenshotFailed(new ImageHelperError(ImageHelperError.ImageHelperErrorType.WatcherEnable)); return; } } // Take the screenshot MediaPortal.GUI.Library.Action action = new MediaPortal.GUI.Library.Action(MediaPortal.GUI.Library.Action.ActionType.ACTION_TAKE_SCREENSHOT, 0, 0); GUIGraphicsContext.OnAction(action); }
/// <summary> /// Plays the local file on the MediaPortal client /// </summary> /// <param name="video">Path to the video</param> /// <param name="position">Start position</param> internal void PlayVideoFile(string video, int position, string fileHandler) { if (video != null && File.Exists(video)) { WifiRemote.LogMessage("Play video file: " + video + ", pos: " + position, WifiRemote.LogType.Debug); // from MP-TvSeries code: // sometimes it takes up to 30+ secs to go to fullscreen even though the video is already playing // lets force fullscreen here // note: MP might still be unresponsive during this time, but at least we are in fullscreen and can see video should this happen // I haven't actually found out why it happens, but I strongly believe it has something to do with the video database and the player doing something in the background // (why does it do anything with the video database.....i just want it to play a file and do NOTHING else!) GUIGraphicsContext.IsFullScreenVideo = true; GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO); // Play File MediaPortal.Player.g_Player.MediaType handler; switch (fileHandler) { case "recording": handler = g_Player.MediaType.Recording; break; case "tv": handler = g_Player.MediaType.TV; break; case "video": default: handler = g_Player.MediaType.Video; break; } g_Player.Play(video, handler); if (position != 0) { g_Player.SeekAbsolute(position); } g_Player.ShowFullScreenWindowVideo(); } }
protected void processScreenshot() { try { using (FileStream stream = new FileStream(screenshotPath, FileMode.Open, FileAccess.Read)) { Screenshot = Image.FromStream(stream); } } catch (Exception ex) { WifiRemote.LogMessage(String.Format("Could not open screenshot file {0}: {1}", screenshotPath, ex.Message), WifiRemote.LogType.Error); takingScreenshot = false; OnScreenshotFailed(new ImageHelperError(ImageHelperError.ImageHelperErrorType.ScreenshotRead)); return; } // Delete the screenshot from disk try { File.Delete(screenshotPath); if (Directory.GetFiles(Path.GetDirectoryName(screenshotPath), "*.png").Length == 0) { // No screenshots in the screenshot folder, delete that as well Directory.Delete(Path.GetDirectoryName(screenshotPath)); } } catch (Exception ex) { WifiRemote.LogMessage(String.Format("Could not delete screenshot or screenshot folder {0}: {1}", screenshotPath, ex.Message), WifiRemote.LogType.Info); } // Stop listening for new files watcher.EnableRaisingEvents = false; // Inform observers that the screenshot is now ready OnScreenshotReady(); takingScreenshot = false; }
/// <summary> /// Publish the service via Bonjour protocol to the network /// </summary> private void PublishBonjourService() { if (servicePublishing) { WifiRemote.LogMessage("Already in the process of publishing the Bonjour service. Aborting publish ...", LogType.Debug); return; } // Test if Bonjour is installed try { //float bonjourVersion = NetService.GetVersion(); Version bonjourVersion = NetService.DaemonVersion; LogMessage(String.Format("Bonjour version {0} found.", bonjourVersion.ToString()), LogType.Info); } catch { LogMessage("Bonjour enabled but not installed! Get it at http://support.apple.com/downloads/Bonjour_for_Windows", LogType.Error); LogMessage("Disabling Bonjour for this session.", LogType.Info); disableBonjour = true; return; } servicePublishing = true; publishService = new NetService(domain, serviceType, serviceName, port); // Get the MAC addresses and set it as bonjour txt record // Needed by the clients to implement wake on lan Hashtable dict = new Hashtable(); dict.Add("hwAddr", GetHardwareAddresses()); publishService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict); publishService.DidPublishService += new NetService.ServicePublished(publishService_DidPublishService); publishService.DidNotPublishService += new NetService.ServiceNotPublished(publishService_DidNotPublishService); publishService.Publish(); }
protected void setupFileSystemWatcher() { String directory = String.Format("{0}\\MediaPortal Screenshots\\{1:0000}-{2:00}-{3:00}", Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); if (!Directory.Exists(directory)) { WifiRemote.LogMessage(String.Format("Creating screenshot directory: {0}", directory), WifiRemote.LogType.Info); try { Directory.CreateDirectory(directory); } catch (Exception e) { WifiRemote.LogMessage(String.Format("Could not create screenshot directory {0}: {1}", directory, e.Message), WifiRemote.LogType.Error); watcher = null; takingScreenshot = false; OnScreenshotFailed(new ImageHelperError(ImageHelperError.ImageHelperErrorType.DirectoryCreate)); return; } } if (watcher == null) { // Add a filesystem watcher to be informed when MediaPortal creates the screenshot watcher = new FileSystemWatcher(directory, "*.png"); watcher.Created += new FileSystemEventHandler(watcherCreated); } else if (!watcher.Path.Equals(directory)) { // Date changed, update path watcher.Path = directory; } }
/// <summary> /// Get all active window plugins and the corresponding window IDs. /// This can be used in the client to jump to a specific plugin. /// /// We are also sending the plugin icon as byte array if it exists. /// </summary> internal static ArrayList GetActiveWindowPluginsAndIDs(bool sendIcons) { // Return cached data if (WifiRemote.savedAndSortedPlugins != null) { return(WifiRemote.savedAndSortedPlugins); } // Init cache savedAndSortedPlugins = new ArrayList(); // No cache yet, build plugin list ArrayList plugins = new ArrayList(); ArrayList sortedPlugins = new ArrayList(); Dictionary <int, String> savedPlugins; List <int> ignoredPluginsList; using (MediaPortal.Profile.Settings reader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) { // Read plugin ids and convert them to int String[] savedPluginStrings = reader.GetValueAsString(WifiRemote.PLUGIN_NAME, "savedPlugins", "").Split('|'); savedPlugins = new Dictionary <int, string>(); for (int j = 0; j + 1 < savedPluginStrings.Length; j = j + 2) { // Add plugin id and name int i; if (int.TryParse(savedPluginStrings[j], out i)) { savedPlugins.Add(i, savedPluginStrings[j + 1]); } } // Read ignored plugins // Ignored by default: // -1: // 0: home // 3005: GUITopbar // 730716: fanart handler String[] ignoredPluginsString = reader.GetValueAsString(WifiRemote.PLUGIN_NAME, "ignoredPlugins", "-1|0|3005|730716").Split('|'); ignoredPluginsList = new List <int>(); foreach (String pluginId in ignoredPluginsString) { int i; if (int.TryParse(pluginId, out i)) { ignoredPluginsList.Add(i); } } } // Fetch all active plugins foreach (ISetupForm plugin in PluginManager.SetupForms) { // Plugin not hidden if (!ignoredPluginsList.Contains(plugin.GetWindowId())) { if (sendIcons) { byte[] iconBytes = new byte[0]; // Load plugin icon Type pluginType = plugin.GetType(); PluginIconsAttribute[] icons = (PluginIconsAttribute[])pluginType.GetCustomAttributes(typeof(PluginIconsAttribute), false); if (icons.Length > 0) { string resourceName = icons[0].ActivatedResourceName; if (!string.IsNullOrEmpty(resourceName)) { System.Drawing.Image icon = null; try { icon = System.Drawing.Image.FromStream(pluginType.Assembly.GetManifestResourceStream(resourceName)); } catch (Exception e) { WifiRemote.LogMessage("Could not load plugin icon: " + e.Message, WifiRemote.LogType.Error); } if (icon != null) { iconBytes = ImageHelper.imageToByteArray(icon, System.Drawing.Imaging.ImageFormat.Png); } } } plugins.Add(new WindowPlugin(plugin.PluginName(), plugin.GetWindowId(), iconBytes)); } else { plugins.Add(new WindowPlugin(plugin.PluginName(), plugin.GetWindowId(), null)); } } } // Add sorted plugins foreach (var aSavedPlugin in savedPlugins) { // Find saved plugin with this window id var query = from WindowPlugin p in plugins where p.WindowId == aSavedPlugin.Key select p; // Add the first found plugin to the list foreach (WindowPlugin plugin in query) { WifiRemote.savedAndSortedPlugins.Add(new WindowPlugin(aSavedPlugin.Value, aSavedPlugin.Key, plugin.Icon)); break; } } // Add rest of plugins foreach (WindowPlugin plugin in plugins) { if (!savedPlugins.ContainsKey(plugin.WindowId)) { WifiRemote.savedAndSortedPlugins.Add(plugin); } } return(WifiRemote.savedAndSortedPlugins); }
/// <summary> /// Contructor. /// </summary> public MessagePlugins(bool sendIcons) { plugins = WifiRemote.GetActiveWindowPluginsAndIDs(sendIcons); }
/// <summary> /// Event handler when a GUI property was changed /// </summary> /// <param name="tag"></param> /// <param name="tagValue"></param> void GUIPropertyManager_OnPropertyChanged(string tag, string tagValue) { if (tag.Equals("#currentmodule")) { if (tagValue != null && tagValue.Equals(localizedKeyboard)) { MessageOnscreenKeyboard keyboardMessage = new MessageOnscreenKeyboard(true); string keyboard = Newtonsoft.Json.JsonConvert.SerializeObject(keyboardMessage); socketServer.SendMessageToAllClients(keyboard); keyboardIsActive = true; } else if (keyboardIsActive) { MessageOnscreenKeyboard keyboardMessage = new MessageOnscreenKeyboard(false); string keyboard = Newtonsoft.Json.JsonConvert.SerializeObject(keyboardMessage); socketServer.SendMessageToAllClients(keyboard); keyboardIsActive = false; } IRenderLayer layer = GUILayerManager.GetLayer(GUILayerManager.LayerType.Dialog); if (layer != null && layer.GetType().IsSubclassOf(typeof(GUIDialogWindow))) { WifiRemote.LogMessage("Sending dialog open to clients", LogType.Debug); MpDialogsHelper.CurrentDialog = layer as GUIDialogWindow; MessageDialog msg = MpDialogsHelper.GetDialogMessage(MpDialogsHelper.CurrentDialog); if (msg != null && msg.Dialog != null && msg.Dialog.GetType() == typeof(MpDialogMenu)) { //TODO: this is a hack to retrieve the list items of a dialog because they are //set after initialisation of the dialog and there is no event fired up after //that. We might run into situations where the list hasn't been updated when //we try to read it Thread t = new Thread(new ParameterizedThreadStart(SendDelayed)); t.Start(msg); } else if (msg != null && msg.Dialog != null && msg.Dialog.GetType() == typeof(MpDialogProgress)) { Thread t = new Thread(new ParameterizedThreadStart(SendProgressUpdates)); t.Start(msg); } else { socketServer.SendMessageToAllClients(msg); } MpDialogsHelper.IsDialogShown = true; } else if (MpDialogsHelper.IsDialogShown) { WifiRemote.LogMessage("Sending dialog close to clients", LogType.Debug); MessageDialog message = new MessageDialog(); message.DialogShown = false; socketServer.SendMessageToAllClients(message); MpDialogsHelper.IsDialogShown = false; } } if (tag.Equals("#selecteditem") || tag.Equals("#selecteditem2") || tag.Equals("#highlightedbutton") || tag.Equals("#currentmodule")) { SendStatus(); } else if (tag.StartsWith("#Play.") || tag.StartsWith("#TV.")) { socketServer.SendPropertyToClient(tag, tagValue); } if (tag.Equals("#selectedindex") || tag.Equals("#highlightedbutton")) { socketServer.SendListViewStatusToAllClientsIfChanged(); } }
public SetupForm() { InitializeComponent(); labelDefaultPort.Text = String.Format("(Default: {0})", WifiRemote.DEFAULT_PORT); // load port from settings using (MediaPortal.Profile.Settings reader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) { originalPort = reader.GetValue(WifiRemote.PLUGIN_NAME, "port"); checkBoxDisableBonjour.Checked = reader.GetValueAsBool(WifiRemote.PLUGIN_NAME, "disableBonjour", false); textBoxName.Text = reader.GetValueAsString(WifiRemote.PLUGIN_NAME, "serviceName", WifiRemote.GetServiceName()); checkBoxShowConnectionMessage.Checked = reader.GetValueAsBool(WifiRemote.PLUGIN_NAME, "showNotifications", false); txtUsername.Text = WifiRemote.DecryptString(reader.GetValueAsString(WifiRemote.PLUGIN_NAME, "username", "")); txtPassword.Text = WifiRemote.DecryptString(reader.GetValueAsString(WifiRemote.PLUGIN_NAME, "password", "")); txtPasscode.Text = WifiRemote.DecryptString(reader.GetValueAsString(WifiRemote.PLUGIN_NAME, "passcode", "")); cbAuthMethod.SelectedIndex = reader.GetValueAsInt(WifiRemote.PLUGIN_NAME, "auth", 0); numericUpDownAutologin.Value = reader.GetValueAsInt(WifiRemote.PLUGIN_NAME, "autologinTimeout", 0); resetPort(); // Read plugin ids and convert them to int String[] savedPluginStrings = reader.GetValueAsString(WifiRemote.PLUGIN_NAME, "savedPlugins", "").Split('|'); savedPlugins = new Dictionary <int, string>(); for (int j = 0; j + 1 < savedPluginStrings.Length; j = j + 2) { // Add plugin id and name int i; if (int.TryParse(savedPluginStrings[j], out i)) { try { savedPlugins.Add(i, savedPluginStrings[j + 1]); } catch (Exception e) { WifiRemote.LogMessage("Adding saved plugin from config failed: " + e.Message, WifiRemote.LogType.Debug); } } } // Read ignored plugins // Ignored by default: // -1: // 0: home // 3005: GUITopbar // 730716: fanart handler String[] ignoredPluginsString = reader.GetValueAsString(WifiRemote.PLUGIN_NAME, "ignoredPlugins", "-1|0|3005|730716").Split('|'); ignoredPluginsList = new List <int>(); foreach (String pluginId in ignoredPluginsString) { int i; if (int.TryParse(pluginId, out i)) { try { ignoredPluginsList.Add(i); } catch (Exception e) { WifiRemote.LogMessage("Adding ignored plugin from config failed: " + e.Message, WifiRemote.LogType.Debug); } } } } // Test if Bonjour is installed try { Version bonjourVersion = ZeroconfService.NetService.DaemonVersion; buttonDownloadBonjour.Enabled = false; checkBoxDisableBonjour.Enabled = false; buttonDownloadBonjour.Text = "Bonjour already installed"; } catch { if (Is64Bit() || Is32BitProcessOn64BitProcessor()) { // 64 bit windows is64bit = true; buttonDownloadBonjour.Enabled = true; checkBoxDisableBonjour.Enabled = true; buttonDownloadBonjour.Text = "Download and install Bonjour (64 bit)"; } else { // 32 bit windows is64bit = false; buttonDownloadBonjour.Enabled = true; checkBoxDisableBonjour.Enabled = true; buttonDownloadBonjour.Text = "Download and install Bonjour (32 bit)"; } } // Setup plugins list availablePlugins = new ArrayList(); plugins = new ArrayList(); pluginIcons = new ImageList(); pluginIcons.ImageSize = new Size(20, 20); EnumerateWindowPlugins(); LoadPlugins(); LoadSettings(); // Add saved plugins to list for ordering foreach (var aSavedPlugin in savedPlugins) { // Find saved plugin with this window id var query = from ItemTag p in plugins where p.WindowId == aSavedPlugin.Key select p; // Add the first found plugin to the list foreach (ItemTag plugin in query) { if (plugin.IsEnabled) { pluginsDataSource.Add(new WindowPlugin(aSavedPlugin.Value, aSavedPlugin.Key, (plugin.ActiveImage != null) ? ImageHelper.imageToByteArray(plugin.ActiveImage, System.Drawing.Imaging.ImageFormat.Png) : ImageHelper.imageToByteArray(Properties.Resources.NoPluginImage, System.Drawing.Imaging.ImageFormat.Png), !ignoredPluginsList.Contains(aSavedPlugin.Key))); } break; } } // Add rest of the plugins to the list foreach (ItemTag plugin in plugins) { if (!savedPlugins.ContainsKey(plugin.WindowId)) { addPluginToList(plugin); } } dataGridViewPluginList.AutoGenerateColumns = false; dataGridViewPluginList.AutoSize = true; dataGridViewPluginList.DataSource = pluginsDataSource; dataGridViewPluginList.CurrentCellDirtyStateChanged += new EventHandler(dataGridViewPluginList_CurrentCellDirtyStateChanged); DataGridViewCheckBoxColumn displayColumn = new DataGridViewCheckBoxColumn(); displayColumn.ReadOnly = false; displayColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCellsExceptHeader; displayColumn.DataPropertyName = "DisplayPlugin"; displayColumn.Name = ""; dataGridViewPluginList.Columns.Add(displayColumn); DataGridViewImageColumn iconColumn = new DataGridViewImageColumn(false); iconColumn.ReadOnly = true; iconColumn.ImageLayout = DataGridViewImageCellLayout.Zoom; iconColumn.Width = 20; iconColumn.DataPropertyName = "Icon"; iconColumn.Name = ""; dataGridViewPluginList.Columns.Add(iconColumn); DataGridViewColumn nameColumn = new DataGridViewTextBoxColumn(); nameColumn.ReadOnly = false; nameColumn.MinimumWidth = 200; nameColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; nameColumn.DataPropertyName = "Name"; nameColumn.Name = "Plugin"; dataGridViewPluginList.Columns.Add(nameColumn); }