Main.cs 11 KB

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