Main.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  78. var nativeApp = new NativeApp();
  79. AppHost = new ApplicationHost(appPaths, logManager, options, fileSystem, "MBServer.Mono", nativeApp);
  80. if (options.ContainsOption("-v")) {
  81. Console.WriteLine (AppHost.ApplicationVersion.ToString());
  82. return;
  83. }
  84. Console.WriteLine ("appHost.Init");
  85. Task.Run (() => StartServer(CancellationToken.None));
  86. }
  87. private static async void StartServer(CancellationToken cancellationToken)
  88. {
  89. var initProgress = new Progress<double>();
  90. await AppHost.Init (initProgress).ConfigureAwait (false);
  91. await AppHost.RunStartupTasks ().ConfigureAwait (false);
  92. if (MenuBarIcon.Instance != null)
  93. {
  94. MenuBarIcon.Instance.Localize ();
  95. }
  96. }
  97. /// <summary>
  98. /// Handles the SessionEnding event of the SystemEvents control.
  99. /// </summary>
  100. /// <param name="sender">The source of the event.</param>
  101. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  102. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  103. {
  104. if (e.Reason == SessionEndReasons.SystemShutdown)
  105. {
  106. Shutdown();
  107. }
  108. }
  109. public static void Shutdown()
  110. {
  111. ShutdownApp();
  112. }
  113. private static void ShutdownApp()
  114. {
  115. _logger.Info ("Calling ApplicationHost.Dispose");
  116. AppHost.Dispose ();
  117. _logger.Info("AppController.Terminate");
  118. MenuBarIcon.Instance.Terminate ();
  119. }
  120. public static void Restart()
  121. {
  122. _logger.Info("Disposing app host");
  123. AppHost.Dispose();
  124. _logger.Info("Starting new instance");
  125. var args = Environment.GetCommandLineArgs()
  126. .Skip(1)
  127. .Select(NormalizeCommandLineArgument);
  128. var commandLineArgsString = string.Join(" ", args.ToArray());
  129. var module = Environment.GetCommandLineArgs().First();
  130. _logger.Info ("Executable: {0}", module);
  131. _logger.Info ("Arguments: {0}", commandLineArgsString);
  132. Process.Start(module, commandLineArgsString);
  133. _logger.Info("AppController.Terminate");
  134. MenuBarIcon.Instance.Terminate();
  135. }
  136. private static string NormalizeCommandLineArgument(string arg)
  137. {
  138. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  139. {
  140. return arg;
  141. }
  142. return "\"" + arg + "\"";
  143. }
  144. /// <summary>
  145. /// Handles the UnhandledException event of the CurrentDomain control.
  146. /// </summary>
  147. /// <param name="sender">The source of the event.</param>
  148. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  149. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  150. {
  151. var exception = (Exception)e.ExceptionObject;
  152. new UnhandledExceptionWriter(AppHost.ServerConfigurationManager.ApplicationPaths, _logger, AppHost.LogManager).Log(exception);
  153. if (!Debugger.IsAttached)
  154. {
  155. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  156. }
  157. }
  158. }
  159. class NoCheckCertificatePolicy : ICertificatePolicy
  160. {
  161. public bool CheckValidationResult (ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  162. {
  163. return true;
  164. }
  165. }
  166. }