Main.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using System;
  2. using System.Diagnostics;
  3. using System.Drawing;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Security;
  8. using System.Reflection;
  9. using System.Runtime.InteropServices;
  10. using System.Security.Cryptography.X509Certificates;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using MediaBrowser.Common.Configuration;
  14. using MediaBrowser.Common.Implementations.IO;
  15. using MediaBrowser.Common.Implementations.Logging;
  16. using MediaBrowser.Model.Logging;
  17. using MediaBrowser.Server.Implementations;
  18. using MediaBrowser.Server.Startup.Common;
  19. using MediaBrowser.Server.Startup.Common.Browser;
  20. using Microsoft.Win32;
  21. using MonoMac.AppKit;
  22. using MonoMac.Foundation;
  23. using MonoMac.ObjCRuntime;
  24. namespace MediaBrowser.Server.Mac
  25. {
  26. class MainClass
  27. {
  28. internal static ApplicationHost AppHost;
  29. private static ILogger _logger;
  30. static void Main (string[] args)
  31. {
  32. var applicationPath = Assembly.GetEntryAssembly().Location;
  33. var options = new StartupOptions();
  34. // Allow this to be specified on the command line.
  35. var customProgramDataPath = options.GetOption("-programdata");
  36. var appPaths = CreateApplicationPaths(applicationPath, customProgramDataPath);
  37. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  38. logManager.ReloadLogger(LogSeverity.Info);
  39. logManager.AddConsoleOutput();
  40. var logger = _logger = logManager.GetLogger("Main");
  41. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  42. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  43. StartApplication(appPaths, logManager, options);
  44. NSApplication.Init ();
  45. NSApplication.Main (args);
  46. }
  47. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  48. {
  49. if (string.IsNullOrEmpty(programDataPath))
  50. {
  51. // TODO: Use CommonApplicationData? Will we always have write access?
  52. programDataPath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "mediabrowser-server");
  53. if (!Directory.Exists (programDataPath)) {
  54. programDataPath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "emby-server");
  55. }
  56. }
  57. // Within the mac bundle, go uo two levels then down into Resources folder
  58. var resourcesPath = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName (applicationPath)), "Resources");
  59. return new ServerApplicationPaths(programDataPath, applicationPath, resourcesPath);
  60. }
  61. /// <summary>
  62. /// Runs the application.
  63. /// </summary>
  64. /// <param name="appPaths">The app paths.</param>
  65. /// <param name="logManager">The log manager.</param>
  66. /// <param name="options">The options.</param>
  67. private static void StartApplication(ServerApplicationPaths appPaths,
  68. ILogManager logManager,
  69. StartupOptions options)
  70. {
  71. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  72. // Allow all https requests
  73. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  74. var fileSystem = new CommonFileSystem(logManager.GetLogger("FileSystem"), false, true);
  75. var nativeApp = new NativeApp();
  76. AppHost = new ApplicationHost(appPaths, logManager, options, fileSystem, "MBServer.Mono", nativeApp);
  77. if (options.ContainsOption("-v")) {
  78. Console.WriteLine (AppHost.ApplicationVersion.ToString());
  79. return;
  80. }
  81. Console.WriteLine ("appHost.Init");
  82. Task.Run (() => StartServer(CancellationToken.None));
  83. }
  84. private static async void StartServer(CancellationToken cancellationToken)
  85. {
  86. var initProgress = new Progress<double>();
  87. await AppHost.Init (initProgress).ConfigureAwait (false);
  88. await AppHost.RunStartupTasks ().ConfigureAwait (false);
  89. if (MenuBarIcon.Instance != null)
  90. {
  91. MenuBarIcon.Instance.Localize ();
  92. }
  93. }
  94. /// <summary>
  95. /// Handles the SessionEnding event of the SystemEvents control.
  96. /// </summary>
  97. /// <param name="sender">The source of the event.</param>
  98. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  99. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  100. {
  101. if (e.Reason == SessionEndReasons.SystemShutdown)
  102. {
  103. Shutdown();
  104. }
  105. }
  106. public static void Shutdown()
  107. {
  108. ShutdownApp();
  109. }
  110. private static void ShutdownApp()
  111. {
  112. _logger.Info ("Calling ApplicationHost.Dispose");
  113. AppHost.Dispose ();
  114. _logger.Info("AppController.Terminate");
  115. MenuBarIcon.Instance.Terminate ();
  116. }
  117. public static void Restart()
  118. {
  119. _logger.Info("Disposing app host");
  120. AppHost.Dispose();
  121. _logger.Info("Starting new instance");
  122. var args = Environment.GetCommandLineArgs()
  123. .Skip(1)
  124. .Select(NormalizeCommandLineArgument);
  125. var commandLineArgsString = string.Join(" ", args.ToArray());
  126. var module = Environment.GetCommandLineArgs().First();
  127. _logger.Info ("Executable: {0}", module);
  128. _logger.Info ("Arguments: {0}", commandLineArgsString);
  129. Process.Start(module, commandLineArgsString);
  130. _logger.Info("AppController.Terminate");
  131. MenuBarIcon.Instance.Terminate();
  132. }
  133. private static string NormalizeCommandLineArgument(string arg)
  134. {
  135. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  136. {
  137. return arg;
  138. }
  139. return "\"" + arg + "\"";
  140. }
  141. /// <summary>
  142. /// Handles the UnhandledException event of the CurrentDomain control.
  143. /// </summary>
  144. /// <param name="sender">The source of the event.</param>
  145. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  146. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  147. {
  148. var exception = (Exception)e.ExceptionObject;
  149. new UnhandledExceptionWriter(AppHost.ServerConfigurationManager.ApplicationPaths, _logger, AppHost.LogManager).Log(exception);
  150. if (!Debugger.IsAttached)
  151. {
  152. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  153. }
  154. }
  155. }
  156. class NoCheckCertificatePolicy : ICertificatePolicy
  157. {
  158. public bool CheckValidationResult (ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  159. {
  160. return true;
  161. }
  162. }
  163. }