Main.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. using MediaBrowser.Model.Logging;
  2. using MediaBrowser.Server.Mono.Native;
  3. using MediaBrowser.Server.Startup.Common;
  4. using MediaBrowser.Server.Startup.Common.IO;
  5. using MediaBrowser.Server.Implementations;
  6. using System;
  7. using System.Diagnostics;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Net.Security;
  13. using System.Reflection;
  14. using System.Text.RegularExpressions;
  15. using System.Threading.Tasks;
  16. using System.Drawing;
  17. using System.Runtime.InteropServices;
  18. using System.Security.Cryptography.X509Certificates;
  19. using System.Threading;
  20. using MonoMac.AppKit;
  21. using MonoMac.Foundation;
  22. using MonoMac.ObjCRuntime;
  23. using Emby.Server.Core;
  24. using Emby.Common.Implementations.Logging;
  25. using Emby.Server.Mac.Native;
  26. using Emby.Server.Implementations.IO;
  27. using Emby.Common.Implementations.Networking;
  28. using Emby.Common.Implementations.Security;
  29. using Mono.Unix.Native;
  30. namespace MediaBrowser.Server.Mac
  31. {
  32. class MainClass
  33. {
  34. internal static MacAppHost AppHost;
  35. private static ILogger _logger;
  36. static void Main (string[] args)
  37. {
  38. var applicationPath = Assembly.GetEntryAssembly().Location;
  39. var options = new StartupOptions();
  40. // Allow this to be specified on the command line.
  41. var customProgramDataPath = options.GetOption("-programdata");
  42. var appFolderPath = Path.GetDirectoryName(applicationPath);
  43. var appPaths = CreateApplicationPaths(appFolderPath, customProgramDataPath);
  44. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  45. logManager.ReloadLogger(LogSeverity.Info);
  46. logManager.AddConsoleOutput();
  47. var logger = _logger = logManager.GetLogger("Main");
  48. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  49. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  50. StartApplication(appPaths, logManager, options);
  51. NSApplication.Init ();
  52. NSApplication.Main (args);
  53. }
  54. private static ServerApplicationPaths CreateApplicationPaths(string appFolderPath, string programDataPath)
  55. {
  56. if (string.IsNullOrEmpty(programDataPath))
  57. {
  58. // TODO: Use CommonApplicationData? Will we always have write access?
  59. programDataPath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "mediabrowser-server");
  60. if (!Directory.Exists (programDataPath)) {
  61. programDataPath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "emby-server");
  62. }
  63. }
  64. // Within the mac bundle, go uo two levels then down into Resources folder
  65. var resourcesPath = Path.Combine(Path.GetDirectoryName(appFolderPath), "Resources");
  66. return new ServerApplicationPaths(programDataPath, appFolderPath, resourcesPath);
  67. }
  68. /// <summary>
  69. /// Runs the application.
  70. /// </summary>
  71. /// <param name="appPaths">The app paths.</param>
  72. /// <param name="logManager">The log manager.</param>
  73. /// <param name="options">The options.</param>
  74. private static void StartApplication(ServerApplicationPaths appPaths,
  75. ILogManager logManager,
  76. StartupOptions options)
  77. {
  78. // Allow all https requests
  79. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  80. var fileSystem = new MonoFileSystem(logManager.GetLogger("FileSystem"), false, false);
  81. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  82. var environmentInfo = GetEnvironmentInfo();
  83. var imageEncoder = ImageEncoderHelper.GetImageEncoder(_logger,
  84. logManager,
  85. fileSystem,
  86. options,
  87. () => AppHost.HttpClient,
  88. appPaths);
  89. AppHost = new MacAppHost(appPaths,
  90. logManager,
  91. options,
  92. fileSystem,
  93. new PowerManagement(),
  94. "Emby.Server.Mac.pkg",
  95. environmentInfo,
  96. imageEncoder,
  97. new Startup.Common.SystemEvents(logManager.GetLogger("SystemEvents")),
  98. new MemoryStreamProvider(),
  99. new NetworkManager(logManager.GetLogger("NetworkManager")),
  100. GenerateCertificate,
  101. () => Environment.UserName);
  102. if (options.ContainsOption("-v")) {
  103. Console.WriteLine (AppHost.ApplicationVersion.ToString());
  104. return;
  105. }
  106. Console.WriteLine ("appHost.Init");
  107. Task.Run (() => StartServer(CancellationToken.None));
  108. }
  109. private static void GenerateCertificate(string certPath, string certHost)
  110. {
  111. CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, _logger);
  112. }
  113. private static MonoEnvironmentInfo GetEnvironmentInfo()
  114. {
  115. var info = new MonoEnvironmentInfo();
  116. var uname = GetUnixName();
  117. var sysName = uname.sysname ?? string.Empty;
  118. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  119. {
  120. //info.OperatingSystem = Startup.Common.OperatingSystem.Osx;
  121. }
  122. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  123. {
  124. //info.OperatingSystem = Startup.Common.OperatingSystem.Linux;
  125. }
  126. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  127. {
  128. //info.OperatingSystem = Startup.Common.OperatingSystem.Bsd;
  129. info.IsBsd = true;
  130. }
  131. var archX86 = new Regex("(i|I)[3-6]86");
  132. if (archX86.IsMatch(uname.machine))
  133. {
  134. info.CustomArchitecture = Architecture.X86;
  135. }
  136. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  137. {
  138. info.CustomArchitecture = Architecture.X64;
  139. }
  140. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  141. {
  142. info.CustomArchitecture = Architecture.Arm;
  143. }
  144. else if (System.Environment.Is64BitOperatingSystem)
  145. {
  146. info.CustomArchitecture = Architecture.X64;
  147. }
  148. else
  149. {
  150. info.CustomArchitecture = Architecture.X86;
  151. }
  152. return info;
  153. }
  154. private static Uname _unixName;
  155. private static Uname GetUnixName()
  156. {
  157. if (_unixName == null)
  158. {
  159. var uname = new Uname();
  160. try
  161. {
  162. Utsname utsname;
  163. var callResult = Syscall.uname(out utsname);
  164. if (callResult == 0)
  165. {
  166. uname.sysname = utsname.sysname ?? string.Empty;
  167. uname.machine = utsname.machine ?? string.Empty;
  168. }
  169. }
  170. catch (Exception ex)
  171. {
  172. _logger.ErrorException("Error getting unix name", ex);
  173. }
  174. _unixName = uname;
  175. }
  176. return _unixName;
  177. }
  178. public class Uname
  179. {
  180. public string sysname = string.Empty;
  181. public string machine = string.Empty;
  182. }
  183. private static async void StartServer(CancellationToken cancellationToken)
  184. {
  185. var initProgress = new Progress<double>();
  186. await AppHost.Init (initProgress).ConfigureAwait (false);
  187. await AppHost.RunStartupTasks ().ConfigureAwait (false);
  188. if (MenuBarIcon.Instance != null)
  189. {
  190. MenuBarIcon.Instance.Localize ();
  191. }
  192. }
  193. public static void Shutdown()
  194. {
  195. ShutdownApp();
  196. }
  197. private static void ShutdownApp()
  198. {
  199. _logger.Info ("Calling ApplicationHost.Dispose");
  200. AppHost.Dispose ();
  201. _logger.Info("AppController.Terminate");
  202. MenuBarIcon.Instance.Terminate ();
  203. }
  204. public static void Restart()
  205. {
  206. _logger.Info("Disposing app host");
  207. AppHost.Dispose();
  208. _logger.Info("Starting new instance");
  209. var args = Environment.GetCommandLineArgs()
  210. .Skip(1)
  211. .Select(NormalizeCommandLineArgument);
  212. var commandLineArgsString = string.Join(" ", args.ToArray());
  213. var module = Environment.GetCommandLineArgs().First();
  214. _logger.Info ("Executable: {0}", module);
  215. _logger.Info ("Arguments: {0}", commandLineArgsString);
  216. Process.Start(module, commandLineArgsString);
  217. _logger.Info("AppController.Terminate");
  218. MenuBarIcon.Instance.Terminate();
  219. }
  220. private static string NormalizeCommandLineArgument(string arg)
  221. {
  222. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  223. {
  224. return arg;
  225. }
  226. return "\"" + arg + "\"";
  227. }
  228. /// <summary>
  229. /// Handles the UnhandledException event of the CurrentDomain control.
  230. /// </summary>
  231. /// <param name="sender">The source of the event.</param>
  232. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  233. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  234. {
  235. var exception = (Exception)e.ExceptionObject;
  236. new UnhandledExceptionWriter(AppHost.ServerConfigurationManager.ApplicationPaths, _logger, AppHost.LogManager).Log(exception);
  237. if (!Debugger.IsAttached)
  238. {
  239. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  240. }
  241. }
  242. }
  243. class NoCheckCertificatePolicy : ICertificatePolicy
  244. {
  245. public bool CheckValidationResult (ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  246. {
  247. return true;
  248. }
  249. }
  250. }