Main.cs 11 KB

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