jellyfin/MediaBrowser.ServerApplication/MainStartup.cs

925 lines
32 KiB
C#
Raw Normal View History

2016-10-29 13:13:23 -07:00
using MediaBrowser.Model.Logging;
using MediaBrowser.Server.Implementations;
using MediaBrowser.Server.Startup.Common;
2013-09-28 11:07:30 -07:00
using MediaBrowser.ServerApplication.Native;
2014-02-15 12:48:35 -07:00
using MediaBrowser.ServerApplication.Splash;
using MediaBrowser.ServerApplication.Updates;
2013-09-20 18:04:14 -07:00
using Microsoft.Win32;
using System;
2013-09-20 18:04:14 -07:00
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;
2013-09-20 18:04:14 -07:00
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
2013-09-20 18:04:14 -07:00
using System.ServiceProcess;
2016-09-12 11:10:09 -07:00
using System.Text;
2014-02-15 13:26:21 -07:00
using System.Threading;
using System.Threading.Tasks;
2014-02-15 12:48:35 -07:00
using System.Windows.Forms;
2016-11-11 01:13:11 -07:00
using Emby.Common.Implementations.EnvironmentInfo;
2016-10-29 13:02:21 -07:00
using Emby.Common.Implementations.IO;
2016-10-29 13:13:23 -07:00
using Emby.Common.Implementations.Logging;
2016-11-11 12:55:12 -07:00
using Emby.Common.Implementations.Networking;
using Emby.Common.Implementations.Security;
2017-05-12 11:09:42 -07:00
using Emby.Drawing;
2016-11-10 22:23:15 -07:00
using Emby.Server.Core;
2017-02-20 13:50:58 -07:00
using Emby.Server.Core.Logging;
2016-11-18 14:06:00 -07:00
using Emby.Server.Implementations;
using Emby.Server.Implementations.Browser;
2016-11-11 00:24:36 -07:00
using Emby.Server.Implementations.IO;
2017-02-20 13:50:58 -07:00
using Emby.Server.Implementations.Logging;
2015-12-06 21:57:04 -07:00
using ImageMagickSharp;
2016-01-04 12:40:59 -07:00
using MediaBrowser.Common.Net;
2017-02-20 13:50:58 -07:00
using MediaBrowser.Model.IO;
2016-11-11 12:55:12 -07:00
using MediaBrowser.Server.Startup.Common.IO;
namespace MediaBrowser.ServerApplication
{
public class MainStartup
{
2013-09-20 18:04:14 -07:00
private static ApplicationHost _appHost;
2013-09-21 14:00:12 -07:00
private static ILogger _logger;
2016-11-12 21:33:51 -07:00
public static bool IsRunningAsService = false;
2016-08-28 06:27:22 -07:00
private static bool _canRestartService = false;
2015-10-27 07:02:30 -07:00
private static bool _appHostDisposed;
2013-09-27 14:09:21 -07:00
2015-12-01 11:55:35 -07:00
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);
2016-11-13 14:04:21 -07:00
public static string ApplicationPath;
2017-02-20 13:50:58 -07:00
private static IFileSystem FileSystem;
2016-09-12 11:10:09 -07:00
public static bool TryGetLocalFromUncDirectory(string local, out string unc)
{
if ((local == null) || (local == ""))
{
unc = "";
throw new ArgumentNullException("local");
}
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_share WHERE path ='" + local.Replace("\\", "\\\\") + "'");
ManagementObjectCollection coll = searcher.Get();
if (coll.Count == 1)
{
foreach (ManagementObject share in searcher.Get())
{
unc = share["Name"] as String;
unc = "\\\\" + SystemInformation.ComputerName + "\\" + unc;
return true;
}
}
unc = "";
return false;
}
/// <summary>
2016-11-11 12:55:12 -07:00
/// Defines the entry point of the application.
/// </summary>
public static void Main()
{
2016-11-18 14:06:00 -07:00
var options = new StartupOptions(Environment.GetCommandLineArgs());
2016-11-12 21:33:51 -07:00
IsRunningAsService = options.ContainsOption("-service");
2016-11-12 21:33:51 -07:00
if (IsRunningAsService)
{
2016-10-18 11:30:50 -07:00
//_canRestartService = CanRestartWindowsService();
}
2013-09-20 18:04:14 -07:00
var currentProcess = Process.GetCurrentProcess();
2016-11-13 14:04:21 -07:00
ApplicationPath = currentProcess.MainModule.FileName;
var architecturePath = Path.Combine(Path.GetDirectoryName(ApplicationPath), Environment.Is64BitProcess ? "x64" : "x86");
2015-12-01 11:55:35 -07:00
2015-12-06 21:57:04 -07:00
Wand.SetMagickCoderModulePath(architecturePath);
2015-12-01 11:55:35 -07:00
var success = SetDllDirectory(architecturePath);
2013-12-12 21:06:38 -07:00
2016-11-18 01:39:20 -07:00
SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
2016-11-13 14:04:21 -07:00
var appPaths = CreateApplicationPaths(ApplicationPath, IsRunningAsService);
2013-09-20 18:04:14 -07:00
var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
2013-12-07 08:52:38 -07:00
logManager.ReloadLogger(LogSeverity.Debug);
2014-01-08 21:44:51 -07:00
logManager.AddConsoleOutput();
2013-09-20 18:04:14 -07:00
2013-09-21 14:00:12 -07:00
var logger = _logger = logManager.GetLogger("Main");
2013-09-20 18:04:14 -07:00
2014-11-23 16:10:41 -07:00
ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
2013-09-20 18:04:14 -07:00
// Install directly
2014-09-14 08:26:33 -07:00
if (options.ContainsOption("-installservice"))
2013-09-20 18:04:14 -07:00
{
logger.Info("Performing service installation");
2016-11-13 14:04:21 -07:00
InstallService(ApplicationPath, logger);
2013-09-20 18:04:14 -07:00
return;
}
// Restart with admin rights, then install
2014-09-14 08:26:33 -07:00
if (options.ContainsOption("-installserviceasadmin"))
2013-09-20 18:04:14 -07:00
{
logger.Info("Performing service installation");
2016-11-13 14:04:21 -07:00
RunServiceInstallation(ApplicationPath);
2013-09-20 18:04:14 -07:00
return;
}
// Uninstall directly
2014-09-14 08:26:33 -07:00
if (options.ContainsOption("-uninstallservice"))
2013-09-20 18:04:14 -07:00
{
logger.Info("Performing service uninstallation");
2016-11-13 14:04:21 -07:00
UninstallService(ApplicationPath, logger);
2013-09-20 18:04:14 -07:00
return;
}
// Restart with admin rights, then uninstall
2014-09-14 08:26:33 -07:00
if (options.ContainsOption("-uninstallserviceasadmin"))
2013-09-20 18:04:14 -07:00
{
logger.Info("Performing service uninstallation");
2016-11-13 14:04:21 -07:00
RunServiceUninstallation(ApplicationPath);
2013-09-20 18:04:14 -07:00
return;
}
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
2016-11-13 14:04:21 -07:00
RunServiceInstallationIfNeeded(ApplicationPath);
2016-11-13 14:04:21 -07:00
if (IsAlreadyRunning(ApplicationPath, currentProcess))
{
logger.Info("Shutting down because another instance of Emby Server is already running.");
return;
}
2013-09-20 18:04:14 -07:00
if (PerformUpdateIfNeeded(appPaths, logger))
{
2013-09-20 18:04:14 -07:00
logger.Info("Exiting to perform application update.");
return;
}
2013-09-20 18:04:14 -07:00
try
{
2016-11-12 21:33:51 -07:00
RunApplication(appPaths, logManager, IsRunningAsService, options);
}
2013-09-20 18:04:14 -07:00
finally
{
2013-09-27 14:09:21 -07:00
OnServiceShutdown();
}
}
2013-09-27 14:09:21 -07:00
/// <summary>
/// Determines whether [is already running] [the specified current process].
/// </summary>
2014-05-07 13:16:57 -07:00
/// <param name="applicationPath">The application path.</param>
2013-09-27 14:09:21 -07:00
/// <param name="currentProcess">The current process.</param>
/// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
2013-12-12 21:06:38 -07:00
private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
2013-09-27 14:09:21 -07:00
{
var duplicate = Process.GetProcesses().FirstOrDefault(i =>
2013-12-12 21:06:38 -07:00
{
try
2013-09-27 14:09:21 -07:00
{
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;
2013-12-12 21:06:38 -07:00
}
catch (Exception)
{
return false;
}
});
2013-09-27 14:09:21 -07:00
if (duplicate != null)
{
_logger.Info("Found a duplicate process. Giving it time to exit.");
2013-10-06 17:49:33 -07:00
2017-04-01 12:49:36 -07:00
if (!duplicate.WaitForExit(40000))
2013-09-27 14:09:21 -07:00
{
_logger.Info("The duplicate process did not exit.");
2015-11-18 19:35:08 -07:00
return true;
2013-09-27 14:09:21 -07:00
}
2013-09-20 18:04:14 -07:00
}
2013-09-27 14:09:21 -07:00
2016-11-12 21:33:51 -07:00
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");
2016-07-13 20:36:23 -07:00
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;
}
}
2013-09-27 14:09:21 -07:00
return false;
}
2013-09-20 18:04:14 -07:00
/// <summary>
/// Creates the application paths.
/// </summary>
2014-11-25 21:12:29 -07:00
/// <param name="applicationPath">The application path.</param>
2013-09-20 18:04:14 -07:00
/// <param name="runAsService">if set to <c>true</c> [run as service].</param>
/// <returns>ServerApplicationPaths.</returns>
2013-12-12 21:06:38 -07:00
private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService)
2013-09-20 18:04:14 -07:00
{
2016-11-13 14:04:21 -07:00
var appFolderPath = Path.GetDirectoryName(applicationPath);
var resourcesPath = Path.GetDirectoryName(applicationPath);
2017-02-20 13:50:58 -07:00
Action<string> createDirectoryFn = s => Directory.CreateDirectory(s);
2013-09-20 18:04:14 -07:00
if (runAsService)
{
2013-12-12 21:06:38 -07:00
var systemPath = Path.GetDirectoryName(applicationPath);
2013-09-20 18:04:14 -07:00
var programDataPath = Path.GetDirectoryName(systemPath);
2017-02-20 13:50:58 -07:00
return new ServerApplicationPaths(programDataPath, appFolderPath, resourcesPath, createDirectoryFn);
2013-09-20 18:04:14 -07:00
}
2017-02-20 13:50:58 -07:00
return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), appFolderPath, resourcesPath, createDirectoryFn);
2013-09-20 18:04:14 -07:00
}
2013-10-07 07:38:31 -07:00
/// <summary>
/// Gets a value indicating whether this instance can self restart.
/// </summary>
/// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
public static bool CanSelfRestart
{
get
{
2016-11-12 21:33:51 -07:00
if (IsRunningAsService)
2016-08-28 06:27:22 -07:00
{
return _canRestartService;
}
else
{
return true;
}
}
}
/// <summary>
/// Gets a value indicating whether this instance can self update.
/// </summary>
/// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
public static bool CanSelfUpdate
{
get
{
2016-11-12 01:02:46 -07:00
#if DEBUG
return false;
#endif
2016-11-12 21:33:51 -07:00
if (IsRunningAsService)
2016-08-28 06:27:22 -07:00
{
return _canRestartService;
}
else
{
return true;
}
2013-10-07 07:38:31 -07:00
}
}
2014-02-15 12:48:35 -07:00
private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
2013-09-20 18:04:14 -07:00
/// <summary>
/// Runs the application.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="logManager">The log manager.</param>
/// <param name="runService">if set to <c>true</c> [run service].</param>
2014-09-14 08:26:33 -07:00
/// <param name="options">The options.</param>
private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
{
2017-03-10 12:51:29 -07:00
var environmentInfo = new EnvironmentInfo();
var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory);
2014-10-06 16:58:46 -07:00
2017-02-20 13:50:58 -07:00
FileSystem = fileSystem;
2016-11-12 21:33:51 -07:00
_appHost = new WindowsAppHost(appPaths,
logManager,
options,
fileSystem,
2016-11-08 21:58:58 -07:00
new PowerManagement(),
2016-11-11 01:13:11 -07:00
"emby.windows.zip",
2017-03-10 12:51:29 -07:00
environmentInfo,
2017-05-12 11:09:42 -07:00
new NullImageEncoder(),
2016-11-11 12:55:12 -07:00
new Server.Startup.Common.SystemEvents(logManager.GetLogger("SystemEvents")),
new RecyclableMemoryStreamProvider(),
2016-11-26 19:33:42 -07:00
new Networking.NetworkManager(logManager.GetLogger("NetworkManager")),
2016-11-11 12:55:12 -07:00
GenerateCertificate,
() => Environment.UserDomainName);
2015-09-29 21:13:48 -07:00
2014-02-15 12:48:35 -07:00
var initProgress = new Progress<double>();
2013-09-20 18:04:14 -07:00
if (!runService)
2013-09-28 11:07:30 -07:00
{
if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
2013-09-28 11:07:30 -07:00
// Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
}
2013-10-06 17:49:33 -07:00
2014-02-15 12:48:35 -07:00
var task = _appHost.Init(initProgress);
2016-05-24 11:17:12 -07:00
Task.WaitAll(task);
2017-05-12 11:09:42 -07:00
if (!runService)
{
task = InstallVcredist2013IfNeeded(_appHost, _logger);
Task.WaitAll(task);
// needed by skia
task = InstallVcredist2015IfNeeded(_appHost, _logger);
Task.WaitAll(task);
}
// set image encoder here
_appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => _appHost.HttpClient, appPaths);
2016-05-24 11:17:12 -07:00
task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
if (runService)
{
StartService(logManager);
}
else
2014-02-15 12:48:35 -07:00
{
2014-07-21 18:31:53 -07:00
Task.WaitAll(task);
2016-10-28 22:40:15 -07:00
Microsoft.Win32.SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
2014-02-15 12:48:35 -07:00
HideSplashScreen();
2014-02-15 13:26:21 -07:00
2014-02-15 14:17:36 -07:00
ShowTrayIcon();
task = ApplicationTaskCompletionSource.Task;
Task.WaitAll(task);
2014-02-15 12:48:35 -07:00
}
}
2017-04-30 19:22:13 -07:00
private static void GenerateCertificate(string certPath, string certHost, string certPassword)
2016-11-11 12:55:12 -07:00
{
2017-04-30 19:22:13 -07:00
CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, certPassword, _logger);
2016-11-11 12:55:12 -07:00
}
2014-02-15 14:17:36 -07:00
private static ServerNotifyIcon _serverNotifyIcon;
2016-04-27 18:59:38 -07:00
private static TaskScheduler _mainTaskScheduler;
2014-02-15 14:17:36 -07:00
private static void ShowTrayIcon()
2014-02-15 13:26:21 -07:00
{
2014-02-15 14:17:36 -07:00
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
_serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
2016-04-27 18:59:38 -07:00
_mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
2014-02-15 14:17:36 -07:00
Application.Run();
2014-02-15 13:26:21 -07:00
}
2016-09-07 23:41:49 -07:00
internal static SplashForm _splash;
2014-02-15 12:48:35 -07:00
private static Thread _splashThread;
private static void ShowSplashScreen(Version appVersion, Progress<double> progress, ILogger logger)
{
var thread = new Thread(() =>
{
_splash = new SplashForm(appVersion, progress);
_splash.ShowDialog();
});
2014-02-15 12:48:35 -07:00
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
_splashThread = thread;
}
private static void HideSplashScreen()
{
if (_splash != null)
{
2014-02-15 13:26:21 -07:00
Action act = () =>
{
_splash.Close();
_splashThread = null;
};
_splash.Invoke(act);
2014-02-15 12:48:35 -07:00
}
2013-09-20 18:04:14 -07:00
}
2013-09-28 11:07:30 -07:00
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLogon)
{
2016-04-23 20:03:49 -07:00
BrowserLauncher.OpenDashboard(_appHost);
2013-09-28 11:07:30 -07:00
}
}
2016-04-23 11:38:36 -07:00
public static void Invoke(Action action)
{
2016-11-12 21:33:51 -07:00
if (IsRunningAsService)
2016-04-27 18:59:38 -07:00
{
action();
}
else
{
Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _mainTaskScheduler ?? TaskScheduler.Current);
}
2016-04-23 11:38:36 -07:00
}
2013-09-20 18:04:14 -07:00
/// <summary>
/// Starts the service.
/// </summary>
private static void StartService(ILogManager logManager)
{
var service = new BackgroundService(logManager.GetLogger("Service"));
service.Disposed += service_Disposed;
ServiceBase.Run(service);
}
2013-09-20 18:04:14 -07:00
/// <summary>
/// Handles the Disposed event of the service control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
2013-09-27 14:09:21 -07:00
static void service_Disposed(object sender, EventArgs e)
{
2014-02-15 12:48:35 -07:00
ApplicationTaskCompletionSource.SetResult(true);
2013-09-27 14:09:21 -07:00
OnServiceShutdown();
}
private static void OnServiceShutdown()
{
2013-09-27 14:09:21 -07:00
_logger.Info("Shutting down");
2015-10-27 07:02:30 -07:00
DisposeAppHost();
2013-09-20 18:04:14 -07:00
}
/// <summary>
/// Installs the service.
/// </summary>
2013-12-12 21:06:38 -07:00
private static void InstallService(string applicationPath, ILogger logger)
2013-09-20 18:04:14 -07:00
{
try
{
2013-12-12 21:06:38 -07:00
ManagedInstallerClass.InstallHelper(new[] { applicationPath });
2013-09-20 18:04:14 -07:00
logger.Info("Service installation succeeded");
}
catch (Exception ex)
{
logger.ErrorException("Uninstall failed", ex);
}
}
2013-09-20 18:04:14 -07:00
/// <summary>
/// Uninstalls the service.
/// </summary>
2013-12-12 21:06:38 -07:00
private static void UninstallService(string applicationPath, ILogger logger)
{
2013-09-20 18:04:14 -07:00
try
{
2013-12-12 21:06:38 -07:00
ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
2013-09-20 18:04:14 -07:00
logger.Info("Service uninstallation succeeded");
}
catch (Exception ex)
{
logger.ErrorException("Uninstall failed", ex);
}
}
2013-12-12 21:06:38 -07:00
private static void RunServiceInstallationIfNeeded(string applicationPath)
2013-09-27 14:09:21 -07:00
{
2015-05-23 13:44:15 -07:00
var serviceName = BackgroundService.GetExistingServiceName();
var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
2013-09-27 14:09:21 -07:00
if (ctl == null)
{
2013-12-12 21:06:38 -07:00
RunServiceInstallation(applicationPath);
2013-09-27 14:09:21 -07:00
}
}
2013-09-20 18:04:14 -07:00
/// <summary>
/// Runs the service installation.
/// </summary>
2013-12-12 21:06:38 -07:00
private static void RunServiceInstallation(string applicationPath)
{
2013-09-20 18:04:14 -07:00
var startInfo = new ProcessStartInfo
{
2013-12-12 21:06:38 -07:00
FileName = applicationPath,
2013-09-20 18:04:14 -07:00
Arguments = "-installservice",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
ErrorDialog = false
};
2013-09-20 18:04:14 -07:00
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
}
}
2013-09-20 18:04:14 -07:00
/// <summary>
/// Runs the service uninstallation.
/// </summary>
2013-12-12 21:06:38 -07:00
private static void RunServiceUninstallation(string applicationPath)
{
2013-09-20 18:04:14 -07:00
var startInfo = new ProcessStartInfo
{
2013-12-12 21:06:38 -07:00
FileName = applicationPath,
2013-09-20 18:04:14 -07:00
Arguments = "-uninstallservice",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
ErrorDialog = false
};
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
}
2013-09-20 18:04:14 -07:00
}
/// <summary>
/// Handles the UnhandledException event of the CurrentDomain control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = (Exception)e.ExceptionObject;
2017-02-20 13:50:58 -07:00
new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager, FileSystem, new ConsoleLogger()).Log(exception);
2016-11-12 21:33:51 -07:00
if (!IsRunningAsService)
2013-09-21 14:00:12 -07:00
{
2014-02-15 12:48:35 -07:00
MessageBox.Show("Unhandled exception: " + exception.Message);
2013-09-21 14:00:12 -07:00
}
if (!Debugger.IsAttached)
{
Environment.Exit(Marshal.GetHRForException(exception));
}
}
2013-09-20 18:04:14 -07:00
/// <summary>
/// Performs the update if needed.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="logger">The logger.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
{
2017-01-08 23:25:09 -07:00
// Not supported
if (IsRunningAsService)
{
return false;
}
2013-09-20 18:04:14 -07:00
// Look for the existence of an update archive
2014-05-12 11:04:25 -07:00
var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
2013-09-20 18:04:14 -07:00
if (File.Exists(updateArchive))
{
logger.Info("An update is available from {0}", updateArchive);
// Update is there - execute update
try
{
2016-11-12 21:33:51 -07:00
var serviceName = IsRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
2013-09-20 18:04:14 -07:00
// And just let the app exit so it can update
return true;
}
catch (Exception e)
{
logger.ErrorException("Error starting updater.", e);
2013-09-20 18:04:14 -07:00
MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
}
}
return false;
}
2013-09-21 14:00:12 -07:00
public static void Shutdown()
{
2016-11-12 21:33:51 -07:00
if (IsRunningAsService)
2013-09-21 14:00:12 -07:00
{
2013-09-27 14:09:21 -07:00
ShutdownWindowsService();
2013-09-21 14:00:12 -07:00
}
else
{
2015-10-27 07:02:30 -07:00
DisposeAppHost();
2013-09-27 14:09:21 -07:00
ShutdownWindowsApplication();
2013-09-21 14:00:12 -07:00
}
}
public static void Restart()
{
2015-10-27 07:02:30 -07:00
DisposeAppHost();
2013-09-21 14:00:12 -07:00
2016-11-12 21:33:51 -07:00
if (IsRunningAsService)
2016-08-28 06:27:22 -07:00
{
RestartWindowsService();
}
else
2013-09-21 14:00:12 -07:00
{
2015-09-21 18:05:33 -07:00
//_logger.Info("Hiding server notify icon");
//_serverNotifyIcon.Visible = false;
2013-09-27 14:09:21 -07:00
2015-05-23 15:01:13 -07:00
_logger.Info("Starting new instance");
2014-06-19 21:50:30 -07:00
//Application.Restart();
2016-11-13 14:04:21 -07:00
Process.Start(ApplicationPath);
2014-06-19 21:50:30 -07:00
2015-09-21 18:05:33 -07:00
ShutdownWindowsApplication();
}
2013-09-27 14:09:21 -07:00
}
2015-10-27 07:02:30 -07:00
private static void DisposeAppHost()
{
if (!_appHostDisposed)
{
_logger.Info("Disposing app host");
_appHostDisposed = true;
_appHost.Dispose();
2017-02-16 00:13:32 -07:00
_logger.Info("App host dispose complete");
2015-10-27 07:02:30 -07:00
}
}
2013-09-27 14:09:21 -07:00
private static void ShutdownWindowsApplication()
{
if (_serverNotifyIcon != null)
{
_serverNotifyIcon.Dispose();
_serverNotifyIcon = null;
}
2016-04-22 09:12:20 -07:00
//_logger.Info("Calling Application.Exit");
//Application.Exit();
2014-06-19 21:50:30 -07:00
2016-04-22 09:12:20 -07:00
_logger.Info("Calling Environment.Exit");
2015-10-27 07:02:30 -07:00
Environment.Exit(0);
2014-06-19 21:50:30 -07:00
_logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
2014-02-15 12:48:35 -07:00
ApplicationTaskCompletionSource.SetResult(true);
2013-09-27 14:09:21 -07:00
}
private static void ShutdownWindowsService()
{
_logger.Info("Stopping background service");
2015-05-23 13:44:15 -07:00
var service = new ServiceController(BackgroundService.GetExistingServiceName());
2013-09-27 14:09:21 -07:00
service.Refresh();
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
2013-09-21 14:00:12 -07:00
}
}
2013-09-28 11:07:30 -07:00
2016-08-28 06:27:22 -07:00
private static void RestartWindowsService()
{
_logger.Info("Restarting background service");
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
ErrorDialog = false,
2016-10-10 21:18:32 -07:00
Arguments = String.Format("/c sc stop {0} & sc start {0} & sc start {0}", BackgroundService.GetExistingServiceName())
2016-08-28 06:27:22 -07:00
};
Process.Start(startInfo);
}
2017-05-11 22:02:58 -07:00
private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger)
2016-08-28 06:27:22 -07:00
{
2017-05-11 22:02:58 -07:00
// Reference
// http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
try
2016-08-28 06:27:22 -07:00
{
2017-05-11 22:02:58 -07:00
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))
2016-08-28 06:27:22 -07:00
{
2017-05-11 22:02:58 -07:00
if (ndpKey != null && ndpKey.GetValue("Version") != null)
{
var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v');
if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase))
{
return;
}
}
2016-08-28 06:27:22 -07:00
}
}
2017-05-11 22:02:58 -07:00
catch (Exception ex)
{
logger.ErrorException("Error getting .NET Framework version", ex);
return;
}
2017-05-11 22:07:01 -07:00
MessageBox.Show("The Visual C++ 2013 Runtime will now be installed.", "Install Visual C++ Runtime", MessageBoxButtons.OK, MessageBoxIcon.Information);
2017-05-11 22:02:58 -07:00
try
{
await InstallVcredist(GetVcredist2013Url()).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
}
2016-08-28 06:27:22 -07:00
}
2017-05-11 22:02:58 -07:00
private static string GetVcredist2013Url()
{
if (Environment.Is64BitProcess)
{
return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x64.exe";
}
// TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_arm.exe
return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2013/vcredist_x86.exe";
}
private static async Task InstallVcredist2015IfNeeded(ApplicationHost appHost, ILogger logger)
2016-01-04 12:40:59 -07:00
{
2016-07-18 20:58:13 -07:00
// Reference
// http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
2016-01-04 12:40:59 -07:00
try
{
2016-07-18 20:58:13 -07:00
var subkey = Environment.Is64BitProcess
2017-05-11 22:02:58 -07:00
? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x64"
: "SOFTWARE\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x86";
2016-07-18 20:58:13 -07:00
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');
2017-05-11 22:02:58 -07:00
if (installedVersion.StartsWith("14", StringComparison.OrdinalIgnoreCase))
2016-07-18 20:58:13 -07:00
{
return;
}
}
}
2016-01-04 12:40:59 -07:00
}
catch (Exception ex)
{
2016-07-18 20:58:13 -07:00
logger.ErrorException("Error getting .NET Framework version", ex);
return;
2016-01-04 12:40:59 -07:00
}
2017-05-11 22:07:01 -07:00
MessageBox.Show("The Visual C++ 2015 Runtime will now be installed.", "Install Visual C++ Runtime", MessageBoxButtons.OK, MessageBoxIcon.Information);
2017-05-11 22:02:58 -07:00
2016-01-04 12:40:59 -07:00
try
{
2017-05-11 22:02:58 -07:00
await InstallVcredist(GetVcredist2015Url()).ConfigureAwait(false);
2016-01-04 12:40:59 -07:00
}
catch (Exception ex)
{
2016-01-13 13:58:45 -07:00
logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
2016-01-04 12:40:59 -07:00
}
}
2017-05-11 22:02:58 -07:00
private static string GetVcredist2015Url()
{
if (Environment.Is64BitProcess)
{
return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vc_redist.x64.exe";
}
// TODO: ARM url - https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vcredist_arm.exe
return "https://github.com/MediaBrowser/Emby.Resources/raw/master/vcredist2015/vc_redist.x86.exe";
}
private async static Task InstallVcredist(string url)
2016-01-04 12:40:59 -07:00
{
var httpClient = _appHost.HttpClient;
var tmp = await httpClient.GetTempFile(new HttpRequestOptions
{
2017-05-11 22:02:58 -07:00
Url = url,
2016-01-04 12:40:59 -07:00
Progress = new Progress<double>()
}).ConfigureAwait(false);
var exePath = Path.ChangeExtension(tmp, ".exe");
File.Copy(tmp, exePath);
var startInfo = new ProcessStartInfo
{
FileName = exePath,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
ErrorDialog = false
};
2016-01-13 13:58:45 -07:00
_logger.Info("Running {0}", startInfo.FileName);
2016-01-04 12:40:59 -07:00
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
}
}
2013-09-28 11:07:30 -07:00
/// <summary>
/// Sets the error mode.
/// </summary>
/// <param name="uMode">The u mode.</param>
/// <returns>ErrorModes.</returns>
[DllImport("kernel32.dll")]
static extern ErrorModes SetErrorMode(ErrorModes uMode);
/// <summary>
/// Enum ErrorModes
/// </summary>
[Flags]
public enum ErrorModes : uint
{
/// <summary>
/// The SYSTE m_ DEFAULT
/// </summary>
SYSTEM_DEFAULT = 0x0,
/// <summary>
/// The SE m_ FAILCRITICALERRORS
/// </summary>
SEM_FAILCRITICALERRORS = 0x0001,
/// <summary>
/// The SE m_ NOALIGNMENTFAULTEXCEPT
/// </summary>
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
/// <summary>
/// The SE m_ NOGPFAULTERRORBOX
/// </summary>
SEM_NOGPFAULTERRORBOX = 0x0002,
/// <summary>
/// The SE m_ NOOPENFILEERRORBOX
/// </summary>
SEM_NOOPENFILEERRORBOX = 0x8000
}
}
}