Main.cs 11 KB

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