jellyfin-server/MediaBrowser.ServerApplication/MainStartup.cs

801 lines
28 KiB
C#
Raw Normal View History

2016-10-29 20:13:23 +00:00
using MediaBrowser.Model.Logging;
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;
2017-05-12 18:09:42 +00:00
using Emby.Drawing;
2016-11-18 21:06:00 +00:00
using Emby.Server.Implementations;
using Emby.Server.Implementations.Browser;
using Emby.Server.Implementations.EnvironmentInfo;
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;
2016-01-04 19:40:59 +00:00
using MediaBrowser.Common.Net;
2017-09-09 18:51:24 +00:00
using MediaBrowser.Controller;
2017-02-20 20:50:58 +00:00
using MediaBrowser.Model.IO;
using SystemEvents = Emby.Server.Implementations.SystemEvents;
namespace MediaBrowser.ServerApplication
{
public class MainStartup
{
2017-09-09 18:51:24 +00:00
private static IServerApplicationPaths _appPaths;
private static ILogManager _logManager;
2013-09-21 01:04:14 +00:00
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;
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;
2017-09-09 18:51:24 +00:00
private static bool _restartOnShutdown;
2017-02-20 20:50:58 +00:00
/// <summary>
2016-11-11 19:55:12 +00:00
/// Defines the entry point of the application.
/// </summary>
2017-06-24 18:30:45 +00:00
[STAThread]
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");
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
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);
2017-09-09 18:51:24 +00:00
_appPaths = appPaths;
2013-09-21 01:04:14 +00:00
2017-09-05 19:49:02 +00:00
using (var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server"))
{
2017-09-09 18:51:24 +00:00
_logManager = logManager;
2017-09-05 19:49:02 +00:00
logManager.ReloadLogger(LogSeverity.Debug);
logManager.AddConsoleOutput();
2013-09-21 01:04:14 +00:00
2017-09-05 19:49:02 +00:00
var logger = _logger = logManager.GetLogger("Main");
2013-09-21 01:04:14 +00:00
2017-09-05 19:49:02 +00:00
ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
2013-09-21 01:04:14 +00:00
2017-09-05 19:49:02 +00:00
// Uninstall directly
if (options.ContainsOption("-uninstallservice"))
{
logger.Info("Performing service uninstallation");
UninstallService(ApplicationPath, logger);
return;
}
2013-09-21 01:04:14 +00:00
2017-09-05 19:49:02 +00:00
// Restart with admin rights, then uninstall
if (options.ContainsOption("-uninstallserviceasadmin"))
{
logger.Info("Performing service uninstallation");
RunServiceUninstallation(ApplicationPath);
return;
}
2013-09-21 01:04:14 +00:00
2017-09-05 19:49:02 +00:00
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
2017-09-05 19:49:02 +00:00
if (IsAlreadyRunning(ApplicationPath, currentProcess))
{
logger.Info("Shutting down because another instance of Emby Server is already running.");
return;
}
2017-09-05 19:49:02 +00:00
if (PerformUpdateIfNeeded(appPaths, logger))
{
logger.Info("Exiting to perform application update.");
return;
}
2017-09-09 18:51:24 +00:00
RunApplication(appPaths, logManager, IsRunningAsService, options);
logger.Info("Shutdown complete");
if (_restartOnShutdown)
2017-09-05 19:49:02 +00:00
{
2017-09-09 18:51:24 +00:00
logger.Info("Starting new server process");
var restartCommandLine = GetRestartCommandLine();
Process.Start(restartCommandLine.Item1, restartCommandLine.Item2);
2017-09-05 19:49:02 +00:00
}
2013-09-27 21:09:21 +00:00
}
}
2017-09-09 18:51:24 +00:00
public static Tuple<string, string> GetRestartCommandLine()
{
var currentProcess = Process.GetCurrentProcess();
var processModulePath = currentProcess.MainModule.FileName;
return new Tuple<string, string>(processModulePath, Environment.CommandLine);
}
2017-09-10 00:24:45 +00:00
private static bool IsServiceInstalled()
{
2017-09-10 01:02:01 +00:00
try
{
var serviceName = BackgroundService.GetExistingServiceName();
var ctl = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == serviceName);
2017-09-10 00:24:45 +00:00
2017-09-10 01:02:01 +00:00
return ctl != null;
}
catch
{
return false;
}
2017-09-10 00:24:45 +00:00
}
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
2017-04-01 19:49:36 +00:00
if (!duplicate.WaitForExit(40000))
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)
{
2017-09-02 19:22:01 +00:00
try
{
var serviceName = BackgroundService.GetExistingServiceName();
2017-09-02 19:22:01 +00:00
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();
2017-09-02 19:22:01 +00:00
foreach (ManagementObject managementObject in managementObjectCollection)
{
2017-09-02 19:22:01 +00:00
var obj = managementObject.GetPropertyValue("PathName");
if (obj == null)
{
continue;
}
var path = obj.ToString();
2017-09-02 19:22:01 +00:00
_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;
}
}
}
2017-09-02 19:22:01 +00:00
catch (COMException)
{
// Catch errors thrown due to WMI not being initialized
}
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-09-10 00:24:45 +00:00
if (runAsService && IsServiceInstalled())
2013-09-21 01:04:14 +00:00
{
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-08-17 20:19:02 +00:00
return new ServerApplicationPaths(programDataPath, appFolderPath, resourcesPath);
2013-09-21 01:04:14 +00:00
}
2017-08-17 20:19:02 +00:00
return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(applicationPath), appFolderPath, resourcesPath);
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
{
2017-09-10 00:24:45 +00:00
return false;
2016-08-28 13:27:22 +00:00
}
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
{
2017-09-10 00:24:45 +00:00
return false;
2016-08-28 13:27:22 +00:00
}
else
{
return true;
}
2013-10-07 14:38:31 +00:00
}
}
private static string UpdatePackageFileName
{
get
{
if (Environment.Is64BitOperatingSystem)
{
return "embyserver-win-x64-{version}.zip";
}
return "embyserver-win-x86-{version}.zip";
}
}
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)
{
2017-03-10 19:51:29 +00:00
var environmentInfo = new EnvironmentInfo();
var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory);
2014-10-06 23:58:46 +00:00
2017-02-20 20:50:58 +00:00
FileSystem = fileSystem;
2017-09-09 18:51:24 +00:00
using (var appHost = new WindowsAppHost(appPaths,
logManager,
options,
fileSystem,
2016-11-09 04:58:58 +00:00
new PowerManagement(),
UpdatePackageFileName,
2017-03-10 19:51:29 +00:00
environmentInfo,
2017-05-12 18:09:42 +00:00
new NullImageEncoder(),
new SystemEvents(logManager.GetLogger("SystemEvents")),
2017-09-09 18:51:24 +00:00
new Networking.NetworkManager(logManager.GetLogger("NetworkManager"))))
2013-09-28 18:07:30 +00:00
{
2017-09-09 18:51:24 +00:00
var initProgress = new Progress<double>();
2017-09-09 18:51:24 +00:00
if (!runService)
{
if (!options.ContainsOption("-nosplash")) ShowSplashScreen(appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash"));
2013-10-07 00:49:33 +00:00
2017-09-09 18:51:24 +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);
}
2016-05-24 18:17:12 +00:00
2017-09-09 18:51:24 +00:00
var task = appHost.Init(initProgress);
2017-05-12 18:09:42 +00:00
Task.WaitAll(task);
2017-09-09 18:51:24 +00:00
if (!runService)
{
task = InstallVcredist2013IfNeeded(appHost.HttpClient, _logger);
Task.WaitAll(task);
2017-05-12 18:09:42 +00:00
2017-09-09 18:51:24 +00:00
// needed by skia
task = InstallVcredist2015IfNeeded(appHost.HttpClient, _logger);
Task.WaitAll(task);
}
2017-05-12 18:09:42 +00:00
2017-09-09 18:51:24 +00:00
// set image encoder here
appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => appHost.HttpClient, appPaths, appHost.LocalizationManager);
2017-09-09 18:51:24 +00:00
task = task.ContinueWith(new Action<Task>(a => appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
2014-07-22 01:31:53 +00:00
2017-09-10 00:24:45 +00:00
if (runService && IsServiceInstalled())
2017-09-09 18:51:24 +00:00
{
StartService(logManager);
}
else
{
Task.WaitAll(task);
2017-09-09 18:51:24 +00:00
HideSplashScreen();
2014-02-15 20:26:21 +00:00
2017-09-09 18:51:24 +00:00
ShowTrayIcon(appHost);
}
2014-02-15 19:48:35 +00:00
}
}
2014-02-15 21:17:36 +00:00
private static ServerNotifyIcon _serverNotifyIcon;
2016-04-28 01:59:38 +00:00
private static TaskScheduler _mainTaskScheduler;
2017-09-09 18:51:24 +00:00
private static void ShowTrayIcon(ApplicationHost appHost)
2014-02-15 20:26:21 +00:00
{
2014-02-15 21:17:36 +00:00
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
2017-09-09 18:51:24 +00:00
_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
}
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"));
ServiceBase.Run(service);
}
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-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-09-09 18:51:24 +00:00
new UnhandledExceptionWriter(_appPaths, _logger, _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()
{
2017-09-10 00:24:45 +00:00
if (IsRunningAsService && IsServiceInstalled())
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
{
2013-09-27 21:09:21 +00:00
ShutdownWindowsApplication();
2013-09-21 21:00:12 +00:00
}
}
public static void Restart()
{
2016-11-13 04:33:51 +00:00
if (IsRunningAsService)
2016-08-28 13:27:22 +00:00
{
}
else
2013-09-21 21:00:12 +00:00
{
2017-09-09 18:51:24 +00:00
_restartOnShutdown = true;
2015-09-22 01:05:33 +00:00
ShutdownWindowsApplication();
}
2013-09-27 21:09:21 +00:00
}
private static void ShutdownWindowsApplication()
{
if (_serverNotifyIcon != null)
{
_serverNotifyIcon.Dispose();
_serverNotifyIcon = null;
}
2017-06-24 18:30:45 +00:00
_logger.Info("Calling Application.Exit");
2017-09-09 18:51:24 +00:00
Application.Exit();
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
2017-09-09 18:51:24 +00:00
private static async Task InstallVcredist2013IfNeeded(IHttpClient httpClient, ILogger logger)
2016-08-28 13:27:22 +00:00
{
2017-05-12 05:02:58 +00:00
// Reference
// http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed
try
2016-08-28 13:27:22 +00:00
{
2017-05-12 05:02:58 +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))
2016-08-28 13:27:22 +00:00
{
2017-05-12 05:02:58 +00: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 13:27:22 +00:00
}
}
2017-05-12 05:02:58 +00:00
catch (Exception ex)
{
logger.ErrorException("Error getting .NET Framework version", ex);
return;
}
try
{
2017-09-09 18:51:24 +00:00
await InstallVcredist(GetVcredist2013Url(), httpClient).ConfigureAwait(false);
2017-05-12 05:02:58 +00:00
}
catch (Exception ex)
{
logger.ErrorException("Error installing Visual Studio C++ runtime", ex);
}
2016-08-28 13:27:22 +00:00
}
2017-05-12 05:02:58 +00: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";
}
2017-09-09 18:51:24 +00:00
private static async Task InstallVcredist2015IfNeeded(IHttpClient httpClient, 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
{
2017-07-02 01:22:06 +00:00
RegistryKey key;
2016-07-19 03:58:13 +00:00
2017-07-02 01:22:06 +00:00
if (Environment.Is64BitProcess)
2016-07-19 03:58:13 +00:00
{
2017-07-02 01:22:06 +00:00
key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
.OpenSubKey("SOFTWARE\\Classes\\Installer\\Dependencies\\{d992c12e-cab2-426f-bde3-fb8c53950b0d}");
if (key == null)
2016-07-19 03:58:13 +00:00
{
2017-07-02 01:22:06 +00:00
key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
.OpenSubKey("SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x64");
}
}
else
{
key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
.OpenSubKey("SOFTWARE\\Classes\\Installer\\Dependencies\\{e2803110-78b3-4664-a479-3611a381656a}");
if (key == null)
{
key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)
.OpenSubKey("SOFTWARE\\Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\x86");
}
}
if (key != null)
{
using (key)
{
var version = key.GetValue("Version");
if (version != null)
2016-07-19 03:58:13 +00:00
{
2017-07-02 01:22:06 +00:00
var installedVersion = ((string)version).TrimStart('v');
if (installedVersion.StartsWith("14", StringComparison.OrdinalIgnoreCase))
{
return;
}
2016-07-19 03:58:13 +00:00
}
}
}
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
{
2017-09-09 18:51:24 +00:00
await InstallVcredist(GetVcredist2015Url(), httpClient).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
}
}
2017-05-12 05:02:58 +00: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";
}
2017-09-09 18:51:24 +00:00
private async static Task InstallVcredist(string url, IHttpClient httpClient)
2016-01-04 19:40:59 +00:00
{
var tmp = await httpClient.GetTempFile(new HttpRequestOptions
{
2017-05-12 05:02:58 +00:00
Url = url,
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();
}
}
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
}
}
}