Main.cs 10 KB

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