Main.cs 10 KB

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