Main.cs 9.9 KB

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