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