diff options
Diffstat (limited to 'MediaBrowser.ServerApplication/MainStartup.cs')
| -rw-r--r-- | MediaBrowser.ServerApplication/MainStartup.cs | 121 |
1 files changed, 104 insertions, 17 deletions
diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 87acd652e..bdfd7d1bb 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -12,6 +12,7 @@ using System.Configuration.Install; using System.Diagnostics; using System.IO; using System.Linq; +using System.Management; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Threading; @@ -102,7 +103,7 @@ namespace MediaBrowser.ServerApplication if (IsAlreadyRunning(applicationPath, currentProcess)) { - logger.Info("Shutting down because another instance of Media Browser Server is already running."); + logger.Info("Shutting down because another instance of Emby Server is already running."); return; } @@ -130,13 +131,28 @@ namespace MediaBrowser.ServerApplication /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns> private static bool IsAlreadyRunning(string applicationPath, Process currentProcess) { - var filename = Path.GetFileName(applicationPath); - var duplicate = Process.GetProcesses().FirstOrDefault(i => { try { - return string.Equals(filename, Path.GetFileName(i.MainModule.FileName)) && currentProcess.Id != i.Id; + if (currentProcess.Id == i.Id) + { + return false; + } + } + catch (Exception) + { + return false; + } + + try + { + //_logger.Info("Module: {0}", i.MainModule.FileName); + if (string.Equals(applicationPath, i.MainModule.FileName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + return false; } catch (Exception) { @@ -155,6 +171,41 @@ namespace MediaBrowser.ServerApplication } } + if (!_isRunningAsService) + { + return IsAlreadyRunningAsService(applicationPath); + } + + return false; + } + + private static bool IsAlreadyRunningAsService(string applicationPath) + { + var serviceName = BackgroundService.GetExistingServiceName(); + + WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE State = 'Running' AND Name = '{0}'", serviceName)); + ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery); + ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get(); + + foreach (ManagementObject managementObject in managementObjectCollection) + { + var obj = managementObject.GetPropertyValue("PathName"); + if (obj == null) + { + continue; + } + var path = obj.ToString(); + + _logger.Info("Service path: {0}", path); + // Need to use indexOf instead of equality because the path will have the full service command line + if (path.IndexOf(applicationPath, StringComparison.OrdinalIgnoreCase) != -1) + { + _logger.Info("The windows service is already running"); + MessageBox.Show("Emby Server is already running as a Windows Service. Only one instance is allowed at a time. To run as a tray icon, shut down the Windows Service."); + return true; + } + } + return false; } @@ -217,6 +268,7 @@ namespace MediaBrowser.ServerApplication { var fileSystem = new WindowsFileSystem(new PatternsLogger(logManager.GetLogger("FileSystem"))); fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); + //fileSystem.AddShortcutHandler(new LnkShortcutHandler(fileSystem)); var nativeApp = new WindowsApp(fileSystem, _logger) { @@ -243,7 +295,9 @@ namespace MediaBrowser.ServerApplication var task = _appHost.Init(initProgress); - task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks())); + Task.WaitAll(task); + + task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent); if (runService) { @@ -253,7 +307,7 @@ namespace MediaBrowser.ServerApplication { Task.WaitAll(task); - task = InstallVcredistIfNeeded(_appHost, _logger); + task = InstallVcredist2013IfNeeded(_appHost, _logger); Task.WaitAll(task); SystemEvents.SessionEnding += SystemEvents_SessionEnding; @@ -269,11 +323,13 @@ namespace MediaBrowser.ServerApplication } private static ServerNotifyIcon _serverNotifyIcon; + private static TaskScheduler _mainTaskScheduler; private static void ShowTrayIcon() { //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager); + _mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); Application.Run(); } @@ -313,7 +369,19 @@ namespace MediaBrowser.ServerApplication { if (e.Reason == SessionSwitchReason.SessionLogon) { - BrowserLauncher.OpenDashboard(_appHost, _logger); + BrowserLauncher.OpenDashboard(_appHost); + } + } + + public static void Invoke(Action action) + { + if (_isRunningAsService) + { + action(); + } + else + { + Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _mainTaskScheduler ?? TaskScheduler.Current); } } @@ -551,9 +619,10 @@ namespace MediaBrowser.ServerApplication private static void ShutdownWindowsApplication() { - _logger.Info("Calling Application.Exit"); - Application.Exit(); + //_logger.Info("Calling Application.Exit"); + //Application.Exit(); + _logger.Info("Calling Environment.Exit"); Environment.Exit(0); _logger.Info("Calling ApplicationTaskCompletionSource.SetResult"); @@ -573,21 +642,39 @@ namespace MediaBrowser.ServerApplication } } - private static async Task InstallVcredistIfNeeded(ApplicationHost appHost, ILogger logger) + private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger) { + // Reference + // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed + try { - var version = ImageMagickEncoder.GetVersion(); - return; + var subkey = Environment.Is64BitProcess + ? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x64" + : "SOFTWARE\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x86"; + + using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default) + .OpenSubKey(subkey)) + { + if (ndpKey != null && ndpKey.GetValue("Version") != null) + { + var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v'); + if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase)) + { + return; + } + } + } } catch (Exception ex) { - logger.ErrorException("Error loading ImageMagick", ex); + logger.ErrorException("Error getting .NET Framework version", ex); + return; } try { - await InstallVcredist().ConfigureAwait(false); + await InstallVcredist2013().ConfigureAwait(false); } catch (Exception ex) { @@ -595,13 +682,13 @@ namespace MediaBrowser.ServerApplication } } - private async static Task InstallVcredist() + private async static Task InstallVcredist2013() { var httpClient = _appHost.HttpClient; var tmp = await httpClient.GetTempFile(new HttpRequestOptions { - Url = GetVcredistUrl(), + Url = GetVcredist2013Url(), Progress = new Progress<double>() }).ConfigureAwait(false); @@ -627,7 +714,7 @@ namespace MediaBrowser.ServerApplication } } - private static string GetVcredistUrl() + private static string GetVcredist2013Url() { if (Environment.Is64BitProcess) { |
