Example #1
0
        public MonitorTaskForm(MCEBuddyConf mceOptions, string SourceName)
        {
            InitializeComponent();

            _mceOptions = mceOptions;
            _mjo        = mceOptions.GetMonitorTaskByName(SourceName);
        }
Example #2
0
        private bool _newTask = false; // Are we creating a new task

        public ConversionTaskForm(MCEBuddyConf mceOptions, string taskName)
        {
            InitializeComponent();

            maxWidthBar.Maximum = _resolutions.Length - 1;
            _advGrpSize         = advancedSettings.Size; // Store the value
            _mceOptions         = mceOptions;
            _cjo = _mceOptions.GetConversionTaskByName(taskName);

            // First get the new scale
            using (Graphics g = this.CreateGraphics())
            {
                float _scale = g.DpiX / 96; // Get the system DPI (font scaling)

                _advancedBoxCollapsedSize = (int)(_advancedBoxCollapsedSize * _scale);
            }
        }
Example #3
0
        MCEBuddyConf _mceOptions; // Config options

        public SettingsForm(ICore pipeProxy, MCEBuddyConf mceOptions)
        {
            InitializeComponent();

            advGrpSize  = advancedSettings.Size; // Store the value
            _pipeProxy  = pipeProxy;             // Store for use by other forms
            _mceOptions = mceOptions;            // We will use this mcebuddy config object everywhere, not work directly on the GlobalMCEbuddyConf object

            // First get the new scale
            using (Graphics g = this.CreateGraphics())
            {
                float _scale = g.DpiX / 96; // Get the system DPI (font scaling)

                // Rescale the columns - for some reason Windows does not rescale the columns in high DPI mode
                this.monitorName.Width = (int)(this.monitorName.Width * _scale);
                this.monitorPath.Width = (int)(this.monitorPath.Width * _scale);
                this.taskName.Width    = (int)(this.taskName.Width * _scale);
                this.taskPath.Width    = (int)(this.taskPath.Width * _scale);

                _advancedBoxCollapsedSize = (int)(_advancedBoxCollapsedSize * _scale);
            }
        }
        private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            //MessageBox.Show("Called AfterInstall");

            // Restore the history file from the %HOMEPATH% if it exists
            string installPath = Context.Parameters["TARGETDIR"].Replace(@"\\", @"\").Trim();

            try
            {
                // Copy the backup files back to the MCEBuddy installation directory with .old extensions (except history)
                // Convert History file to unicode while copying it back
                if (File.Exists(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "history")))
                {
                    string sourceHistory      = Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "history");
                    string destinationHistory = Path.Combine(installPath, @"config\history");

                    // First check if the file is a UTF16LE file (required for INI files)
                    if (Encodings.GetFileEncoding(sourceHistory) != Encoding.Unicode)
                    {
                        using (StreamReader sourceRead = new StreamReader(sourceHistory))                                                   // Open the source file for reading
                        {
                            FileIO.TryFileDelete(destinationHistory);                                                                       // Try to delete the destination file first
                            using (FileStream destinationFile = File.Create(destinationHistory))                                            // Create the destination file
                            {
                                using (StreamWriter destinationWrite = new StreamWriter(destinationFile, new UnicodeEncoding(false, true))) // UTF16, LE with BOM for INI files
                                {
                                    // Read everything from the file
                                    string line;
                                    while ((line = sourceRead.ReadLine()) != null)
                                    {
                                        destinationWrite.WriteLine(line); // Write to the new file
                                    }
                                    destinationWrite.Close();
                                }
                                destinationFile.Close();
                            }
                            sourceRead.Close();
                        }
                    }
                    else // We are good, just copy the file
                    {
                        File.Copy(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "history"), Path.Combine(installPath, @"config\history"), true);
                    }
                }
                if (File.Exists(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "mcebuddy.conf")))
                {
                    File.Copy(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "mcebuddy.conf"), Path.Combine(installPath, @"config\mcebuddy.conf.old"), true);
                }
                if (File.Exists(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "profiles.conf")))
                {
                    File.Copy(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "profiles.conf"), Path.Combine(installPath, @"config\profiles.conf.old"), true);
                }
                if (File.Exists(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "comskip.ini")))
                {
                    File.Copy(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "comskip.ini"), Path.Combine(installPath, @"comskip\comskip.ini.old"), true);
                }

                // Copy the settings from the last config file (retain user settings) (this will also take care of UTF16LE conversion for ini)
                if (File.Exists(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "mcebuddy.conf")))
                {
                    MCEBuddyConf mceConf = new MCEBuddyConf(Path.Combine(Environment.GetEnvironmentVariable("HOMEPATH"), "mcebuddy.conf")); // Read the old config file
                    mceConf.WriteSettings(Path.Combine(installPath, @"config\mcebuddy.conf"));                                              // Write to the new installation file
                }
            }
            catch (Exception exp)
            {
                Log.WriteSystemEventLog("Failed to restore config files. Error:" + exp.ToString(), EventLogEntryType.Error);
            }

            try
            {
                // Install extras (such as filters etc)
                // Check if Haali Media Splitter is installed, else install it
                string haaliKey = "";

                if (Environment.Is64BitOperatingSystem)
                {
                    haaliKey = @"Software\Wow6432Node\HaaliMkx";
                }
                else
                {
                    haaliKey = @"Software\HaaliMkx";
                }

                if (Registry.LocalMachine.OpenSubKey(haaliKey) == null)
                {
                    if (MessageBox.Show("MCEBuddy suggests installing Haali Media Splitter for MKV playback support.\nPress OK to Install.", "MKV Playback Support Not Found", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
                    {
                        RunCustomApp(Path.Combine(installPath, "extras", "MatroskaSplitter"), "/S", true); // Install Haali Media Splitter (required for MKV playback)
                    }
                }

                // WTV Playback: Uninstall Windows Update KB2670838 if the resulting file does not play in MCE/WMP - nothing to do with ffdshow
                // Check if FFDSHOW is installed, else install FFDSHOW for MPEG2/AVI support else NoRecode profiles does not work
                bool   modifyReg  = true;
                string ffdshowKey = "";

                if (Environment.Is64BitOperatingSystem)
                {
                    ffdshowKey = @"Software\GNU\ffdshow64";
                }
                else
                {
                    ffdshowKey = @"Software\GNU\ffdshow";
                }

                if (Registry.LocalMachine.OpenSubKey(ffdshowKey) == null) // if the key doesn't exist i.e. not installed, it returns null
                {
                    if (MessageBox.Show("MCEBuddy suggests installing FFDShow for MPEG2/AVI playback support.\nPress OK to install.", "FFDShow Not Found", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
                    {
                        if (RunCustomAppWithMediumPrivilege(Path.Combine(installPath, "extras", "ffdshow.exe"), " /silent", true) == true) // FFDShow needs to be installed with Medium Privileges else the installation does not work
                        {
                            Registry.LocalMachine.DeleteSubKeyTree(@"Software\GNU");                                                       // Delete all the keys under GNU (we will only create those required later) - TODO: Can we find a clean way to do a custom install for FFDSHOw, default Silent install enables many filters not required
                        }
                        else
                        {
                            MessageBox.Show("FFDShow installation error, please install it manually from the Extra's folder in the MCEBuddy Installation directory.\nEnsure you select MPEG2 during installation", "Error installing FFDSHOW");
                            modifyReg = false;
                        }
                    }
                    else
                    {
                        modifyReg = false;
                    }
                }

                // FFDSHOW, enable the MPEG-2 splitter in the registry (whenever it's installed)
                if (modifyReg)
                {
                    Registry.LocalMachine.CreateSubKey(ffdshowKey); // Create the key if required (since the silent installation does not create one)
                    Registry.LocalMachine.OpenSubKey(ffdshowKey, true).SetValue("mpegAVI", 1, RegistryValueKind.DWord);
                    Registry.LocalMachine.OpenSubKey(ffdshowKey, true).SetValue("mpg2", 1, RegistryValueKind.DWord);
                    Registry.LocalMachine.OpenSubKey(ffdshowKey, true).SetValue("mpg1", 1, RegistryValueKind.DWord);
                }

                // Install ShowAnalyzer - last one, delayed start to avoid MSI install conflict (only 1 at a time)
                if (!Scanner.ShowAnalyzerInstalled()) // only if not installed
                {
                    if (MessageBox.Show("MCEBuddy comes with Comskip commercial detection software built in. However some countries have better commercial detection with ShowAnalyzer.\nPress OK if you would like to install ShowAnalyzer.", "Commercial detection options", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                    {
                        RunCustomApp(Path.Combine(installPath, "extras", "InstallShowAnalyzerDelayed.bat"), "", false);
                    }
                }
            }
            catch (Exception exp)
            {
                Log.WriteSystemEventLog("Failed to install custom apps. Error:" + exp.ToString(), EventLogEntryType.Error);
            }

            try
            {
                //Set the restart properties for the service
                ServiceControlManager scm = new ServiceControlManager();
                scm.SetRestartOnFailure(engineName);
            }
            catch (Exception exp)
            {
                Log.WriteSystemEventLog("Failed to set MCEBuddy service restart parameters. Error:" + exp.ToString(), EventLogEntryType.Error);
            }

            /*string installPath = Context.Parameters["TARGETDIR"].Replace(@"\\", @"\").Trim();
             * CreateExposedDirectory(Path.Combine(installPath, "config"));
             * CreateExposedDirectory(Path.Combine(installPath, "log"));
             * CreateExposedDirectory(Path.Combine(installPath, "working"));*///Dont' create directories here since it create Canonical issues, create within application at runtime

            WindowsService.StartService(engineName);
        }
Example #5
0
        protected override void OnStart(string[] args)
        {
            Log.WriteSystemEventLog("MCEBuddy service OnStart called", EventLogEntryType.Information);

            try
            {
                RequestAdditionalTime(10000);                                           // Ask for 10 second to complete initial operations and not mark service as unresponsive

                MCEBuddyConf.GlobalMCEConfig = new MCEBuddyConf(GlobalDefs.ConfigFile); // Read the settings for global objects

                MCEBuddyConf.CheckDefaultJobPaths();                                    // Update paths before we start the engine to it is read

                _host = new ServiceHost(typeof(Core));
                TimeSpan timeoutPeriod = GlobalDefs.PIPE_TIMEOUT;

                // Create a binding for network SOAP WEB SERVICES
                string serverString = GlobalDefs.MCEBUDDY_WEB_SOAP_PIPE;
                serverString = serverString.Replace(GlobalDefs.MCEBUDDY_SERVER_PORT, MCEBuddyConf.GlobalMCEConfig.GeneralOptions.localServerPort.ToString(System.Globalization.CultureInfo.InvariantCulture)); // Update the Server Port with that from the config file
                BasicHttpBinding ntb = new BasicHttpBinding(GlobalDefs.MCEBUDDY_PIPE_SECURITY);
                ntb.OpenTimeout            = ntb.CloseTimeout = ntb.SendTimeout = ntb.ReceiveTimeout = timeoutPeriod;
                ntb.TransferMode           = TransferMode.Buffered;
                ntb.MaxReceivedMessageSize = ntb.MaxBufferPoolSize = ntb.MaxBufferSize = Int32.MaxValue;
                ntb.ReaderQuotas           = XmlDictionaryReaderQuotas.Max;
                ServiceEndpoint soapEndpoint = _host.AddServiceEndpoint(typeof(ICore), ntb, serverString);
                // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue
                foreach (OperationDescription operation in soapEndpoint.Contract.Operations)
                {
                    DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                    }
                }

                // Create a binding for local NAMED PIPES
                NetNamedPipeBinding npb = new NetNamedPipeBinding();
                npb.OpenTimeout            = npb.CloseTimeout = npb.SendTimeout = npb.ReceiveTimeout = timeoutPeriod;
                npb.TransferMode           = TransferMode.Buffered;
                npb.MaxReceivedMessageSize = npb.MaxBufferPoolSize = npb.MaxBufferSize = Int32.MaxValue;
                npb.ReaderQuotas           = XmlDictionaryReaderQuotas.Max;
                ServiceEndpoint namedPipeEndpoint = _host.AddServiceEndpoint(typeof(ICore), npb, GlobalDefs.MCEBUDDY_LOCAL_NAMED_PIPE);
                // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue
                foreach (OperationDescription operation in namedPipeEndpoint.Contract.Operations)
                {
                    DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                    }
                }

                _host.CloseTimeout = GlobalDefs.PIPE_TIMEOUT;
                _host.Open();

                Log.WriteSystemEventLog("MCEBuddy service started on port " + MCEBuddyConf.GlobalMCEConfig.GeneralOptions.localServerPort.ToString(System.Globalization.CultureInfo.InvariantCulture), EventLogEntryType.Information);

                _pipeProxy = MCEBuddyEngineConnect.ConnectToLocalEngine();
                if (MCEBuddyConf.GlobalMCEConfig.GeneralOptions.engineRunning) // Check for last saved state by user
                {
                    _pipeProxy.Start();
                    Log.WriteSystemEventLog(Localise.GetPhrase("Last user saved state: MCEBuddy engine started"), EventLogEntryType.Information);
                }
                else
                {
                    Log.WriteSystemEventLog(Localise.GetPhrase("Last user saved state: MCEBuddy engine NOT started"), EventLogEntryType.Information);
                }
            }
            catch (Exception e)
            {
                Log.WriteSystemEventLog(Localise.GetPhrase("MCEBuddy service failed to start. Error:") + e.ToString(), EventLogEntryType.Error);
            }
        }
Example #6
0
        static int Main(string[] args)
        {
            if (_pipeProxy != null)
            {
                Log.WriteSystemEventLog("MCEBuddy engine app already running, cannot start another instance.", EventLogEntryType.Error);
                return(-1); // We can't start engine's
            }

            if (!AppProcess.HaveAdministrativeRights())
            {
                Log.WriteSystemEventLog("Start MCEBuddy engine app with Administrative rights.", EventLogEntryType.Information);
                AppProcess.StartAppWithAdministrativeRights(Application.ExecutablePath); // Engine needs Admin rights for firewall and binding
                return(-2);                                                              // Exit, the process will restart with admin rights
            }

            // Capture the Window close event if the user manually closes it
            _controlHandler = new HandlerRoutine(ConsoleCloseCheck); // Setup a static object otherwise on some systems it crashes with null pointer exception due to garbage collection
            SetConsoleCtrlHandler(_controlHandler, true);

            // Now that we are running, first Stop the the Windows Service otherwise we don't be able to start (stop before starting the GUI to prevent closure)
            Log.WriteSystemEventLog("Trying to stop MCEBuddy engine service.", EventLogEntryType.Information);
            WindowsService.StopService(GlobalDefs.MCEBUDDY_SERVICE_NAME, 10000);

            //Start MCEBuddy GUI with Normal user rights (just incase this is running admin rights
            try
            {
                if (AppProcess.HaveAdministrativeRights())
                {
                    AppProcess.StartAppWithMediumPrivilegeFromUISession(Path.Combine(GlobalDefs.AppPath, "MCEBuddy.GUI.exe"), "", false);
                }
                else // Normal user
                {
                    Process Proc = new Process();
                    Proc.StartInfo.FileName       = Path.Combine(GlobalDefs.AppPath, "MCEBuddy.GUI.exe");
                    Proc.StartInfo.CreateNoWindow = false;
                    Proc.StartInfo.WindowStyle    = ProcessWindowStyle.Normal;
                    Proc.Start();
                }
            }
            catch (Exception e)
            {
                // Sometimes the DLL does not work or is missing or running on wrong windows version, catch it and log it
                Log.WriteSystemEventLog("MCEBuddy engine app: Unable to start MCEBuddy GUI. Error ->\r\n" + e.ToString(), EventLogEntryType.Warning);
            }

            Log.WriteSystemEventLog("Starting MCEBuddy engine app.", EventLogEntryType.Information);
            MCEBuddyConf.GlobalMCEConfig = new MCEBuddyConf(GlobalDefs.ConfigFile); // Read the settings for global objects

            MCEBuddyConf.CheckDefaultJobPaths();                                    // Update paths before we start the engine to it is read

            _host = new ServiceHost(typeof(Core));
            TimeSpan timeoutPeriod = GlobalDefs.PIPE_TIMEOUT;

            // Create a binding for network SOAP WEB SERVICES
            string serverString = GlobalDefs.MCEBUDDY_WEB_SOAP_PIPE;

            serverString = serverString.Replace(GlobalDefs.MCEBUDDY_SERVER_PORT, MCEBuddyConf.GlobalMCEConfig.GeneralOptions.localServerPort.ToString()); // Update the Server Port with that from the config file
            BasicHttpBinding ntb = new BasicHttpBinding(GlobalDefs.MCEBUDDY_PIPE_SECURITY);

            ntb.OpenTimeout            = ntb.CloseTimeout = ntb.SendTimeout = ntb.ReceiveTimeout = timeoutPeriod;
            ntb.TransferMode           = TransferMode.Buffered;
            ntb.MaxReceivedMessageSize = ntb.MaxBufferPoolSize = ntb.MaxBufferSize = Int32.MaxValue;
            ntb.ReaderQuotas           = XmlDictionaryReaderQuotas.Max;
            ServiceEndpoint soapEndpoint = _host.AddServiceEndpoint(typeof(ICore), ntb, serverString);

            // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue
            foreach (OperationDescription operation in soapEndpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                }
            }

            // Create a binding for local NAMED PIPES
            NetNamedPipeBinding npb = new NetNamedPipeBinding();

            npb.OpenTimeout            = npb.CloseTimeout = npb.SendTimeout = npb.ReceiveTimeout = timeoutPeriod;
            npb.TransferMode           = TransferMode.Buffered;
            npb.MaxReceivedMessageSize = npb.MaxBufferPoolSize = npb.MaxBufferSize = Int32.MaxValue;
            npb.ReaderQuotas           = XmlDictionaryReaderQuotas.Max;
            ServiceEndpoint namedPipeEndpoint = _host.AddServiceEndpoint(typeof(ICore), npb, GlobalDefs.MCEBUDDY_LOCAL_NAMED_PIPE);

            // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue
            foreach (OperationDescription operation in namedPipeEndpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                }
            }

            _host.CloseTimeout = GlobalDefs.PIPE_TIMEOUT;
            _host.Open();

            _pipeProxy = MCEBuddyEngineConnect.ConnectToLocalEngine();
            if (MCEBuddyConf.GlobalMCEConfig.GeneralOptions.engineRunning)
            {
                _pipeProxy.Start();
            }

            // Now that we are up and running
            SystemEvents.PowerModeChanged += OnPowerChange; // Register for power event changes

            ConsoleKeyInfo cki;

            Console.Title        = "MCEBuddy 2.x Service Started, Press ESC to stop";
            Console.WindowHeight = 15;
            Console.WindowWidth  = 80;
            int  lastNumJobs = 0;
            bool Shutdown    = false;

            while (!Shutdown)
            {
                if (_forceClosed)
                {
                    return(1); // Someone forced the closure, the handler will clean up. Exit now
                }
                if (Console.KeyAvailable)
                {
                    cki = Console.ReadKey(true);
                    if (cki.Key == ConsoleKey.Escape)
                    {
                        Log.WriteSystemEventLog("MCEBuddy engine app received user shutdown request.", EventLogEntryType.Information);
                        Shutdown = true;
                    }
                }

                try
                {
                    for (int i = 0, numJobs = _pipeProxy.NumConversionJobs(); i < numJobs; i++)
                    {
                        if (lastNumJobs != numJobs) // The number of conversion jobs has changed
                        {
                            Console.Clear();        // Clear the screen
                        }
                        string outputStr = "";
                        outputStr = "Job" + i.ToString();
                        JobStatus status = _pipeProxy.GetJobStatus(i);
                        if (status != null)
                        {
                            outputStr += " " + status.CurrentAction;
                            if (status.PercentageComplete > 0)
                            {
                                outputStr += " " + status.PercentageComplete.ToString("#0.0", CultureInfo.InvariantCulture) + "%";
                            }
                            else if (-1 == status.PercentageComplete)
                            {
                                outputStr += " Working..."; //some processes like ReMuxSupp don't update perc
                            }
                            if (!String.IsNullOrEmpty(status.ETA))
                            {
                                outputStr += " ETA=" + status.ETA;
                            }

                            if (!String.IsNullOrEmpty(status.SourceFile))
                            {
                                outputStr += " " + Path.GetFileName(status.SourceFile);
                            }
                        }
                        else
                        {
                            outputStr += " Idle";
                        }
                        if (outputStr.Length > 78)
                        {
                            outputStr = outputStr.Substring(0, 78);
                        }
                        Console.SetCursorPosition(0, i);
                        Console.Write(outputStr.PadRight(78));
                        lastNumJobs = _pipeProxy.NumConversionJobs();
                    }
                }
                catch (Exception) //while debugging catch Proxy Faulted state and reset it
                {
                    if (_forceClosed)
                    {
                        return(1);
                    }

                    if (Shutdown)
                    {
                        break; // we are done here
                    }
                    _pipeProxy = MCEBuddyEngineConnect.ConnectToLocalEngine();
                }

                System.Threading.Thread.Sleep(GlobalDefs.LOCAL_ENGINE_POLL_PERIOD);
            }

            ConsoleCloseCheck(ControlSignalType.CTRL_CLOSE_EVENT); // Gracefully shutdown the engine and restart the windows service

            return(0);                                             // All good
        }