Main.cs 10 KB

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