Main.cs 6.4 KB

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