Main.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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.Model.Logging;
  14. using MediaBrowser.Server.Implementations;
  15. using MediaBrowser.Server.Startup.Common;
  16. using Microsoft.Win32;
  17. using MonoMac.AppKit;
  18. using MonoMac.Foundation;
  19. using MonoMac.ObjCRuntime;
  20. using Emby.Server.Core;
  21. using Emby.Common.Implementations.Logging;
  22. using Emby.Server.Mac.Native;
  23. namespace MediaBrowser.Server.Mac
  24. {
  25. class MainClass
  26. {
  27. internal static MacAppHost AppHost;
  28. private static ILogger _logger;
  29. static void Main (string[] args)
  30. {
  31. var applicationPath = Assembly.GetEntryAssembly().Location;
  32. var options = new StartupOptions();
  33. // Allow this to be specified on the command line.
  34. var customProgramDataPath = options.GetOption("-programdata");
  35. var appFolderPath = Path.GetDirectoryName(applicationPath);
  36. var appPaths = CreateApplicationPaths(appFolderPath, 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 appFolderPath, 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(appFolderPath), "Resources");
  59. return new ServerApplicationPaths(programDataPath, appFolderPath, 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 MonoFileSystem(logManager.GetLogger("FileSystem"), false, false);
  75. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  76. AppHost = new MacAppHost(appPaths,
  77. logManager,
  78. options,
  79. fileSystem,
  80. new PowerManagement(),
  81. "Emby.Server.Mac.pkg",
  82. nativeApp);
  83. if (options.ContainsOption("-v")) {
  84. Console.WriteLine (AppHost.ApplicationVersion.ToString());
  85. return;
  86. }
  87. Console.WriteLine ("appHost.Init");
  88. Task.Run (() => StartServer(CancellationToken.None));
  89. }
  90. private static async void StartServer(CancellationToken cancellationToken)
  91. {
  92. var initProgress = new Progress<double>();
  93. await AppHost.Init (initProgress).ConfigureAwait (false);
  94. await AppHost.RunStartupTasks ().ConfigureAwait (false);
  95. if (MenuBarIcon.Instance != null)
  96. {
  97. MenuBarIcon.Instance.Localize ();
  98. }
  99. }
  100. /// <summary>
  101. /// Handles the SessionEnding event of the SystemEvents control.
  102. /// </summary>
  103. /// <param name="sender">The source of the event.</param>
  104. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  105. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  106. {
  107. if (e.Reason == SessionEndReasons.SystemShutdown)
  108. {
  109. Shutdown();
  110. }
  111. }
  112. public static void Shutdown()
  113. {
  114. ShutdownApp();
  115. }
  116. private static void ShutdownApp()
  117. {
  118. _logger.Info ("Calling ApplicationHost.Dispose");
  119. AppHost.Dispose ();
  120. _logger.Info("AppController.Terminate");
  121. MenuBarIcon.Instance.Terminate ();
  122. }
  123. public static void Restart()
  124. {
  125. _logger.Info("Disposing app host");
  126. AppHost.Dispose();
  127. _logger.Info("Starting new instance");
  128. var args = Environment.GetCommandLineArgs()
  129. .Skip(1)
  130. .Select(NormalizeCommandLineArgument);
  131. var commandLineArgsString = string.Join(" ", args.ToArray());
  132. var module = Environment.GetCommandLineArgs().First();
  133. _logger.Info ("Executable: {0}", module);
  134. _logger.Info ("Arguments: {0}", commandLineArgsString);
  135. Process.Start(module, commandLineArgsString);
  136. _logger.Info("AppController.Terminate");
  137. MenuBarIcon.Instance.Terminate();
  138. }
  139. private static string NormalizeCommandLineArgument(string arg)
  140. {
  141. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  142. {
  143. return arg;
  144. }
  145. return "\"" + arg + "\"";
  146. }
  147. /// <summary>
  148. /// Handles the UnhandledException event of the CurrentDomain control.
  149. /// </summary>
  150. /// <param name="sender">The source of the event.</param>
  151. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  152. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  153. {
  154. var exception = (Exception)e.ExceptionObject;
  155. new UnhandledExceptionWriter(AppHost.ServerConfigurationManager.ApplicationPaths, _logger, AppHost.LogManager).Log(exception);
  156. if (!Debugger.IsAttached)
  157. {
  158. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  159. }
  160. }
  161. }
  162. class NoCheckCertificatePolicy : ICertificatePolicy
  163. {
  164. public bool CheckValidationResult (ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  165. {
  166. return true;
  167. }
  168. }
  169. }