jellyfin-server/MediaBrowser.ServerApplication/MainStartup.cs

885 lines
30 KiB
C#
Raw Normal View History

2016-10-29 20:13:23 +00:00
using MediaBrowser.Model.Logging;
using MediaBrowser.Server.Implementations;
using MediaBrowser.Server.Startup.Common;
2013-09-28 18:07:30 +00:00
using MediaBrowser.ServerApplication.Native;
2014-02-15 19:48:35 +00:00
using MediaBrowser.ServerApplication.Splash;
using MediaBrowser.ServerApplication.Updates;
2013-09-21 01:04:14 +00:00
using Microsoft.Win32;
using System;
2013-09-21 01:04:14 +00:00
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;
2013-09-21 01:04:14 +00:00
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
2013-09-21 01:04:14 +00:00
using System.ServiceProcess;
2016-09-12 18:10:09 +00:00
using System.Text;
2014-02-15 20:26:21 +00:00
using System.Threading;
using System.Threading.Tasks;
2014-02-15 19:48:35 +00:00
using System.Windows.Forms;
2016-11-11 08:13:11 +00:00
using Emby.Common.Implementations.EnvironmentInfo;
2016-10-29 20:02:21 +00:00
using Emby.Common.Implementations.IO;
2016-10-29 20:13:23 +00:00
using Emby.Common.Implementations.Logging;
2016-11-11 19:55:12 +00:00
using Emby.Common.Implementations.Networking;
using Emby.Common.Implementations.Security;
2016-11-11 05:23:15 +00:00
using Emby.Server.Core;
2017-02-20 20:50:58 +00:00
using Emby.Server.Core.Logging;
2016-11-18 21:06:00 +00:00
using Emby.Server.Implementations;
using Emby.Server.Implementations.Browser;
2016-11-11 07:24:36 +00:00
using Emby.Server.Implementations.IO;
2017-02-20 20:50:58 +00:00
using Emby.Server.Implementations.Logging;
2015-12-07 04:57:04 +00:00
using ImageMagickSharp;
2016-01-04 19:40:59 +00:00
using MediaBrowser.Common.Net;
2017-02-20 20:50:58 +00:00
using MediaBrowser.Model.IO;
2016-11-11 19:55:12 +00:00
using MediaBrowser.Server.Startup.Common.IO;
namespace MediaBrowser.ServerApplication
{
public class MainStartup
{
2013-09-21 01:04:14 +00:00
private static ApplicationHost _appHost;
2013-09-21 21:00:12 +00:00
private static ILogger _logger;
2016-11-13 04:33:51 +00:00
public static bool IsRunningAsService = false;
2016-08-28 13:27:22 +00:00
private static bool _canRestartService = false;
2015-10-27 14:02:30 +00:00
private static bool _appHostDisposed;
2013-09-27 21:09:21 +00:00
2015-12-01 18:55:35 +00:00
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);
2016-11-13 21:04:21 +00:00
public static string ApplicationPath;
2017-02-20 20:50:58 +00:00
private static IFileSystem FileSystem;
2016-09-12 18:10:09 +00: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 19:55:12 +00:00
/// Defines the entry point of the application.
/// </summary>
public static void Main()
{
2016-11-18 21:06:00 +00:00
var options = new StartupOptions(Environment.GetCommandLineArgs());
2016-11-13 04:33:51 +00:00
IsRunningAsService = options.ContainsOption("-service");
2016-11-13 04:33:51 +00:00
if (IsRunningAsService)
{
2016-10-18 18:30:50 +00:00
//_canRestartService = CanRestartWindowsService();
}
2013-09-21 01:04:14 +00:00
var currentProcess = Process.GetCurrentProcess();
2016-11-13 21:04:21 +00:00
ApplicationPath = currentProcess.MainModule.FileName;
var architecturePath = Path.Combine(Path.GetDirectoryName(ApplicationPath), Environment.Is64BitProcess ? "x64" : "x86");
2015-12-01 18:55:35 +00:00
2015-12-07 04:57:04 +00:00
Wand.SetMagickCoderModulePath(architecturePath);
2015-12-01 18:55:35 +00:00
var success = SetDllDirectory(architecturePath);
2013-12-13 04:06:38 +00:00
2016-11-18 08:39:20 +00:00
SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
2016-11-13 21:04:21 +00:00
var appPaths = CreateApplicationPaths(ApplicationPath, IsRunningAsService);
2013-09-21 01:04:14 +00:00
var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
2013-12-07 15:52:38 +00:00
logManager.ReloadLogger(LogSeverity.Debug);
2014-01-09 04:44:51 +00:00
logManager.AddConsoleOutput();
2013-09-21 01:04:14 +00:00
2013-09-21 21:00:12 +00:00
var logger = _logger = logManager.GetLogger("Main");
2013-09-21 01:04:14 +00:00
2014-11-23 23:10:41 +00:00
ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
2013-09-21 01:04:14 +00:00
// Install directly
2014-09-14 15:26:33 +00:00
if (options.ContainsOption("-installservice"))
2013-09-21 01:04:14 +00:00
{
logger.Info("Performing service installation");
2016-11-13 21:04:21 +00:00
InstallService(ApplicationPath, logger);
2013-09-21 01:04:14 +00:00
return;
}
// Restart with admin rights, then install
2014-09-14 15:26:33 +00:00
if (options.ContainsOption("-installserviceasadmin"))
2013-09-21 01:04:14 +00:00
{
logger.Info("Performing service installation");
2016-11-13 21:04:21 +00:00
RunServiceInstallation(ApplicationPath);
2013-09-21 01:04:14 +00:00
return;
}
// Uninstall directly
2014-09-14 15:26:33 +00:00
if (options.ContainsOption("-uninstallservice"))
2013-09-21 01:04:14 +00:00
{
logger.Info("Performing service uninstallation");
2016-11-13 21:04:21 +00:00
UninstallService(ApplicationPath, logger);
2013-09-21 01:04:14 +00:00
return;
}
// Restart with admin rights, then uninstall
2014-09-14 15:26:33 +00:00
if (options.ContainsOption("-uninstallserviceasadmin"))
2013-09-21 01:04:14 +00:00
{
logger.Info("Performing service uninstallation");
2016-11-13 21:04:21 +00:00
RunServiceUninstallation(ApplicationPath);
2013-09-21 01:04:14 +00:00
return;
}
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
2016-11-13 21:04:21 +00:00
RunServiceInstallationIfNeeded(ApplicationPath);
2016-11-13 21:04:21 +00:00
if (IsAlreadyRunning(ApplicationPath, currentProcess))
{
logger.Info("Shutting down because another instance of Emby Server is already running.");
return;
}
2013-09-21 01:04:14 +00:00
if (PerformUpdateIfNeeded(appPaths, logger))
{
2013-09-21 01:04:14 +00:00
logger.Info("Exiting to perform application update.");
return;
}
2013-09-21 01:04:14 +00:00
try
{
2016-11-13 04:33:51 +00:00
RunApplication(appPaths, logManager, IsRunningAsService, options);
}
2013-09-21 01:04:14 +00:00
finally
{
2013-09-27 21:09:21 +00:00
OnServiceShutdown();
}
}
2013-09-27 21:09:21 +00:00
/// <summary>
/// Determines whether [is already running] [the specified current process].
/// </summary>
2014-05-07 20:16:57 +00:00
/// <param name="applicationPath">The application path.</param>
2013-09-27 21:09:21 +00: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-13 04:06:38 +00:00
private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
2013-09-27 21:09:21 +00:00
{
var duplicate = Process.GetProcesses().FirstOrDefault(i =>
2013-12-13 04:06:38 +00:00
{
try
2013-09-27 21:09:21 +00: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-13 04:06:38 +00:00
}
catch (Exception)
{
return false;
}
});
2013-09-27 21:09:21 +00:00
if (duplicate != null)
{
_logger.Info("Found a duplicate process. Giving it time to exit.");
2013-10-07 00:49:33 +00:00
2016-10-23 19:48:51 +00:00
if (!duplicate.WaitForExit(30000))
2013-09-27 21:09:21 +00:00
{
_logger.Info("The duplicate process did not exit.");
2015-11-19 02:35:08 +00:00
return true;
2013-09-27 21:09:21 +00:00
}
2013-09-21 01:04:14 +00:00
}
2013-09-27 21:09:21 +00:00
2016-11-13 04:33:51 +00: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-14 03:36:23 +00: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 21:09:21 +00:00
return false;
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Creates the application paths.
/// </summary>
2014-11-26 04:12:29 +00:00
/// <param name="applicationPath">The application path.</param>
2013-09-21 01:04:14 +00:00
/// <param name="runAsService">if set to <c>true</c> [run as service].</param>
/// <returns>ServerApplicationPaths.</returns>
2013-12-13 04:06:38 +00:00
private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, bool runAsService)
2013-09-21 01:04:14 +00:00
{
2016-11-13 21:04:21 +00:00
var appFolderPath = Path.GetDirectoryName(applicationPath);
var resourcesPath = Path.GetDirectoryName(applicationPath);
2017-02-20 20:50:58 +00:00
Action<string> createDirectoryFn = s => Directory.CreateDirectory(s);
2013-09-21 01:04:14 +00:00
if (runAsService)
{
2013-12-13 04:06:38 +00:00
var systemPath = Path.GetDirectoryName(applicationPath);
2013-09-21 01:04:14 +00:00
var programDataPath = Path.GetDirectoryName(systemPath);
2017-02-20 20:50:58 +00:00
return new ServerApplicationPaths(programDataPath, appFolderPath, resourcesPath, createDirectoryFn);
2013-09-21 01:04:14 +00:00
}
2017-02-20 20:50:58 +00:00
return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), appFolderPath, resourcesPath, createDirectoryFn);
2013-09-21 01:04:14 +00:00
}
2013-10-07 14:38:31 +00: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-13 04:33:51 +00:00
if (IsRunningAsService)
2016-08-28 13:27:22 +00: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 08:02:46 +00:00
#if DEBUG
return false;
#endif
2016-11-13 04:33:51 +00:00
if (IsRunningAsService)
2016-08-28 13:27:22 +00:00
{
return _canRestartService;
}
else
{
return true;
}
2013-10-07 14:38:31 +00:00
}
}
2014-02-15 19:48:35 +00:00
private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
2013-09-21 01:04:14 +00: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 15:26:33 +00:00
/// <param name="options">The options.</param>
private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options)
{
var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), true, true, false, appPaths.TempDirectory);
2016-10-29 04:10:11 +00:00
fileSystem.AddShortcutHandler(new LnkShortcutHandler());
2015-10-04 04:23:11 +00:00
fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
2014-10-06 23:58:46 +00:00
2016-11-11 19:55:12 +00:00
var imageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => _appHost.HttpClient, appPaths);
2017-02-20 20:50:58 +00:00
FileSystem = fileSystem;
2016-11-13 04:33:51 +00:00
_appHost = new WindowsAppHost(appPaths,
logManager,
options,
fileSystem,
2016-11-09 04:58:58 +00:00
new PowerManagement(),
2016-11-11 08:13:11 +00:00
"emby.windows.zip",
2016-11-11 19:55:12 +00:00
new EnvironmentInfo(),
imageEncoder,
new Server.Startup.Common.SystemEvents(logManager.GetLogger("SystemEvents")),
new RecyclableMemoryStreamProvider(),
2016-11-27 02:33:42 +00:00
new Networking.NetworkManager(logManager.GetLogger("NetworkManager")),
2016-11-11 19:55:12 +00:00
GenerateCertificate,
() => Environment.UserDomainName);
2015-09-30 04:13:48 +00:00
2014-02-15 19:48:35 +00:00
var initProgress = new Progress<double>();
2013-09-21 01:04:14 +00:00
if (!runService)
2013-09-28 18:07:30 +00:00
{
if (!options.ContainsOption("-nosplash")) ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
2013-09-28 18:07:30 +00: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-07 00:49:33 +00:00
2014-02-15 19:48:35 +00:00
var task = _appHost.Init(initProgress);
2016-05-24 18:17:12 +00:00
Task.WaitAll(task);
task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
if (runService)
{
StartService(logManager);
}
else
2014-02-15 19:48:35 +00:00
{
2014-07-22 01:31:53 +00:00
Task.WaitAll(task);
2016-05-24 03:06:51 +00:00
task = InstallVcredist2013IfNeeded(_appHost, _logger);
2016-01-04 19:40:59 +00:00
Task.WaitAll(task);
2016-10-29 05:40:15 +00:00
Microsoft.Win32.SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
2014-02-15 19:48:35 +00:00
HideSplashScreen();
2014-02-15 20:26:21 +00:00
2014-02-15 21:17:36 +00:00
ShowTrayIcon();
task = ApplicationTaskCompletionSource.Task;
Task.WaitAll(task);
2014-02-15 19:48:35 +00:00
}
}
2016-11-11 19:55:12 +00:00
private static void GenerateCertificate(string certPath, string certHost)
{
CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, _logger);
}
2014-02-15 21:17:36 +00:00
private static ServerNotifyIcon _serverNotifyIcon;
2016-04-28 01:59:38 +00:00
private static TaskScheduler _mainTaskScheduler;
2014-02-15 21:17:36 +00:00
private static void ShowTrayIcon()
2014-02-15 20:26:21 +00:00
{
2014-02-15 21:17:36 +00:00
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
_serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager);
2016-04-28 01:59:38 +00:00
_mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
2014-02-15 21:17:36 +00:00
Application.Run();
2014-02-15 20:26:21 +00:00
}
2016-09-08 06:41:49 +00:00
internal static SplashForm _splash;
2014-02-15 19:48:35 +00: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 19:48:35 +00:00
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
_splashThread = thread;
}
private static void HideSplashScreen()
{
if (_splash != null)
{
2014-02-15 20:26:21 +00:00
Action act = () =>
{
_splash.Close();
_splashThread = null;
};
_splash.Invoke(act);
2014-02-15 19:48:35 +00:00
}
2013-09-21 01:04:14 +00:00
}
2013-09-28 18:07:30 +00:00
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLogon)
{
2016-04-24 03:03:49 +00:00
BrowserLauncher.OpenDashboard(_appHost);
2013-09-28 18:07:30 +00:00
}
}
2016-04-23 18:38:36 +00:00
public static void Invoke(Action action)
{
2016-11-13 04:33:51 +00:00
if (IsRunningAsService)
2016-04-28 01:59:38 +00:00
{
action();
}
else
{
Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _mainTaskScheduler ?? TaskScheduler.Current);
}
2016-04-23 18:38:36 +00:00
}
2013-09-21 01:04:14 +00: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-21 01:04:14 +00: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 21:09:21 +00:00
static void service_Disposed(object sender, EventArgs e)
{
2014-02-15 19:48:35 +00:00
ApplicationTaskCompletionSource.SetResult(true);
2013-09-27 21:09:21 +00:00
OnServiceShutdown();
}
private static void OnServiceShutdown()
{
2013-09-27 21:09:21 +00:00
_logger.Info("Shutting down");
2015-10-27 14:02:30 +00:00
DisposeAppHost();
2013-09-21 01:04:14 +00:00
}
/// <summary>
/// Installs the service.
/// </summary>
2013-12-13 04:06:38 +00:00
private static void InstallService(string applicationPath, ILogger logger)
2013-09-21 01:04:14 +00:00
{
try
{
2013-12-13 04:06:38 +00:00
ManagedInstallerClass.InstallHelper(new[] { applicationPath });
2013-09-21 01:04:14 +00:00
logger.Info("Service installation succeeded");
}
catch (Exception ex)
{
logger.ErrorException("Uninstall failed", ex);
}
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Uninstalls the service.
/// </summary>
2013-12-13 04:06:38 +00:00
private static void UninstallService(string applicationPath, ILogger logger)
{
2013-09-21 01:04:14 +00:00
try
{
2013-12-13 04:06:38 +00:00
ManagedInstallerClass.InstallHelper(new[] { "/u", applicationPath });
2013-09-21 01:04:14 +00:00
logger.Info("Service uninstallation succeeded");
}
catch (Exception ex)
{
logger.ErrorException("Uninstall failed", ex);
}
}
2013-12-13 04:06:38 +00:00
private static void RunServiceInstallationIfNeeded(string applicationPath)
2013-09-27 21:09:21 +00:00
{
2015-05-23 20:44:15 +00:00
var serviceName = BackgroundService.GetExistingServiceName();
var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
2013-09-27 21:09:21 +00:00
if (ctl == null)
{
2013-12-13 04:06:38 +00:00
RunServiceInstallation(applicationPath);
2013-09-27 21:09:21 +00:00
}
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Runs the service installation.
/// </summary>
2013-12-13 04:06:38 +00:00
private static void RunServiceInstallation(string applicationPath)
{
2013-09-21 01:04:14 +00:00
var startInfo = new ProcessStartInfo
{
2013-12-13 04:06:38 +00:00
FileName = applicationPath,
2013-09-21 01:04:14 +00:00
Arguments = "-installservice",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
ErrorDialog = false
};
2013-09-21 01:04:14 +00:00
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
}
}
2013-09-21 01:04:14 +00:00
/// <summary>
/// Runs the service uninstallation.
/// </summary>
2013-12-13 04:06:38 +00:00
private static void RunServiceUninstallation(string applicationPath)
{
2013-09-21 01:04:14 +00:00
var startInfo = new ProcessStartInfo
{
2013-12-13 04:06:38 +00:00
FileName = applicationPath,
2013-09-21 01:04:14 +00:00
Arguments = "-uninstallservice",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
ErrorDialog = false
};
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
}
2013-09-21 01:04:14 +00: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 20:50:58 +00:00
new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager, FileSystem, new ConsoleLogger()).Log(exception);
2016-11-13 04:33:51 +00:00
if (!IsRunningAsService)
2013-09-21 21:00:12 +00:00
{
2014-02-15 19:48:35 +00:00
MessageBox.Show("Unhandled exception: " + exception.Message);
2013-09-21 21:00:12 +00:00
}
if (!Debugger.IsAttached)
{
Environment.Exit(Marshal.GetHRForException(exception));
}
}
2013-09-21 01:04:14 +00: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-09 06:25:09 +00:00
// Not supported
if (IsRunningAsService)
{
return false;
}
2013-09-21 01:04:14 +00:00
// Look for the existence of an update archive
2014-05-12 18:04:25 +00:00
var updateArchive = Path.Combine(appPaths.TempUpdatePath, "MBServer" + ".zip");
2013-09-21 01:04:14 +00:00
if (File.Exists(updateArchive))
{
logger.Info("An update is available from {0}", updateArchive);
// Update is there - execute update
try
{
2016-11-13 04:33:51 +00:00
var serviceName = IsRunningAsService ? BackgroundService.GetExistingServiceName() : string.Empty;
new ApplicationUpdater().UpdateApplication(appPaths, updateArchive, logger, serviceName);
2013-09-21 01:04:14 +00:00
// And just let the app exit so it can update
return true;
}
catch (Exception e)
{
logger.ErrorException("Error starting updater.", e);
2013-09-21 01:04:14 +00: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 21:00:12 +00:00
public static void Shutdown()
{
2016-11-13 04:33:51 +00:00
if (IsRunningAsService)
2013-09-21 21:00:12 +00:00
{
2013-09-27 21:09:21 +00:00
ShutdownWindowsService();
2013-09-21 21:00:12 +00:00
}
else
{
2015-10-27 14:02:30 +00:00
DisposeAppHost();
2013-09-27 21:09:21 +00:00
ShutdownWindowsApplication();
2013-09-21 21:00:12 +00:00
}
}
public static void Restart()
{
2015-10-27 14:02:30 +00:00
DisposeAppHost();
2013-09-21 21:00:12 +00:00
2016-11-13 04:33:51 +00:00
if (IsRunningAsService)
2016-08-28 13:27:22 +00:00
{
RestartWindowsService();
}
else
2013-09-21 21:00:12 +00:00
{
2015-09-22 01:05:33 +00:00
//_logger.Info("Hiding server notify icon");
//_serverNotifyIcon.Visible = false;
2013-09-27 21:09:21 +00:00
2015-05-23 22:01:13 +00:00
_logger.Info("Starting new instance");
2014-06-20 04:50:30 +00:00
//Application.Restart();
2016-11-13 21:04:21 +00:00
Process.Start(ApplicationPath);
2014-06-20 04:50:30 +00:00
2015-09-22 01:05:33 +00:00
ShutdownWindowsApplication();
}
2013-09-27 21:09:21 +00:00
}
2015-10-27 14:02:30 +00:00
private static void DisposeAppHost()
{
if (!_appHostDisposed)
{
_logger.Info("Disposing app host");
_appHostDisposed = true;
_appHost.Dispose();
2017-02-16 07:13:32 +00:00
_logger.Info("App host dispose complete");
2015-10-27 14:02:30 +00:00
}
}
2013-09-27 21:09:21 +00:00
private static void ShutdownWindowsApplication()
{
if (_serverNotifyIcon != null)
{
_serverNotifyIcon.Dispose();
_serverNotifyIcon = null;
}
2016-04-22 16:12:20 +00:00
//_logger.Info("Calling Application.Exit");
//Application.Exit();
2014-06-20 04:50:30 +00:00
2016-04-22 16:12:20 +00:00
_logger.Info("Calling Environment.Exit");
2015-10-27 14:02:30 +00:00
Environment.Exit(0);
2014-06-20 04:50:30 +00:00
_logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
2014-02-15 19:48:35 +00:00
ApplicationTaskCompletionSource.SetResult(true);
2013-09-27 21:09:21 +00:00
}
private static void ShutdownWindowsService()
{
_logger.Info("Stopping background service");
2015-05-23 20:44:15 +00:00
var service = new ServiceController(BackgroundService.GetExistingServiceName());
2013-09-27 21:09:21 +00:00
service.Refresh();
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
2013-09-21 21:00:12 +00:00
}
}
2013-09-28 18:07:30 +00:00
2016-08-28 13:27:22 +00: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-11 04:18:32 +00:00
Arguments = String.Format("/c sc stop {0} & sc start {0} & sc start {0}", BackgroundService.GetExistingServiceName())
2016-08-28 13:27:22 +00:00
};
Process.Start(startInfo);
}
private static bool CanRestartWindowsService()
{
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
ErrorDialog = false,
Arguments = String.Format("/c sc query {0}", BackgroundService.GetExistingServiceName())
};
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
if (process.ExitCode == 0)
{
return true;
}
else
{
return false;
}
}
}
2016-05-24 03:06:51 +00:00
private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger)
2016-01-04 19:40:59 +00:00
{
2016-07-19 03:58:13 +00:00
// Reference
// http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
2016-01-04 19:40:59 +00:00
try
{
2016-07-19 03:58:13 +00: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))
{
if (ndpKey != null && ndpKey.GetValue("Version") != null)
{
var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v');
if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase))
{
return;
}
}
}
2016-01-04 19:40:59 +00:00
}
catch (Exception ex)
{
2016-07-19 03:58:13 +00:00
logger.ErrorException("Error getting .NET Framework version", ex);
return;
2016-01-04 19:40:59 +00:00
}
try
{
2016-05-24 03:06:51 +00:00
await InstallVcredist2013().ConfigureAwait(false);
2016-01-04 19:40:59 +00:00
}
catch (Exception ex)
{
2016-01-13 20:58:45 +00:00
logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
2016-01-04 19:40:59 +00:00
}
}
2016-05-24 03:06:51 +00:00
private async static Task InstallVcredist2013()
2016-01-04 19:40:59 +00:00
{
var httpClient = _appHost.HttpClient;
var tmp = await httpClient.GetTempFile(new HttpRequestOptions
{
2016-05-24 03:06:51 +00:00
Url = GetVcredist2013Url(),
2016-01-04 19:40:59 +00: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 20:58:45 +00:00
_logger.Info("Running {0}", startInfo.FileName);
2016-01-04 19:40:59 +00:00
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
}
}
2016-05-24 03:06:51 +00:00
private static string GetVcredist2013Url()
2016-01-04 19:40:59 +00:00
{
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";
}
2013-09-28 18:07:30 +00: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
}
}
}