Main.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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.Implementations;
  20. using Emby.Server.Implementations.Logging;
  21. using Emby.Server.Mac.Native;
  22. using Emby.Server.Implementations.IO;
  23. using Mono.Unix.Native;
  24. using MediaBrowser.Model.System;
  25. using MediaBrowser.Model.IO;
  26. using Emby.Drawing;
  27. using Emby.Drawing.Skia;
  28. using MediaBrowser.Controller.Drawing;
  29. using MediaBrowser.Model.Drawing;
  30. using Emby.Server.Implementations.EnvironmentInfo;
  31. using Emby.Server.Implementations.Networking;
  32. namespace MediaBrowser.Server.Mac
  33. {
  34. class MainClass
  35. {
  36. internal static MacAppHost AppHost;
  37. private static ILogger _logger;
  38. private static IFileSystem _fileSystem;
  39. static void Main (string[] args)
  40. {
  41. SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  42. var applicationPath = Assembly.GetEntryAssembly().Location;
  43. var options = new StartupOptions(Environment.GetCommandLineArgs());
  44. // Allow this to be specified on the command line.
  45. var customProgramDataPath = options.GetOption("-programdata");
  46. var appFolderPath = Path.GetDirectoryName(applicationPath);
  47. var appPaths = CreateApplicationPaths(appFolderPath, customProgramDataPath);
  48. using (var logManager = new SimpleLogManager(appPaths.LogDirectoryPath, "server"))
  49. {
  50. logManager.ReloadLogger(LogSeverity.Info);
  51. logManager.AddConsoleOutput();
  52. var logger = _logger = logManager.GetLogger("Main");
  53. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  54. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  55. StartApplication(appPaths, logManager, options);
  56. NSApplication.Init();
  57. NSApplication.Main(args);
  58. }
  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 NetworkManager(logManager.GetLogger("NetworkManager")));
  100. if (options.ContainsOption("-v")) {
  101. Console.WriteLine (AppHost.ApplicationVersion.ToString());
  102. return;
  103. }
  104. Console.WriteLine ("appHost.Init");
  105. Task.Run (() => StartServer(CancellationToken.None));
  106. }
  107. private static IImageEncoder GetImageEncoder(ServerApplicationPaths appPaths, IFileSystem fileSystem, ILogManager logManager)
  108. {
  109. try
  110. {
  111. return new SkiaEncoder(logManager.GetLogger("Skia"), appPaths, () => AppHost.HttpClient, fileSystem);
  112. }
  113. catch (Exception ex)
  114. {
  115. return new NullImageEncoder();
  116. }
  117. }
  118. private static EnvironmentInfo GetEnvironmentInfo()
  119. {
  120. var info = new EnvironmentInfo()
  121. {
  122. OperatingSystem = MediaBrowser.Model.System.OperatingSystem.OSX
  123. };
  124. var uname = GetUnixName();
  125. var sysName = uname.sysname ?? string.Empty;
  126. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  127. {
  128. //info.OperatingSystem = Startup.Common.OperatingSystem.Osx;
  129. }
  130. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  131. {
  132. //info.OperatingSystem = Startup.Common.OperatingSystem.Linux;
  133. }
  134. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  135. {
  136. //info.OperatingSystem = Startup.Common.OperatingSystem.Bsd;
  137. //info.IsBsd = true;
  138. }
  139. var archX86 = new Regex("(i|I)[3-6]86");
  140. if (archX86.IsMatch(uname.machine))
  141. {
  142. info.SystemArchitecture = Architecture.X86;
  143. }
  144. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  145. {
  146. info.SystemArchitecture = Architecture.X64;
  147. }
  148. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  149. {
  150. info.SystemArchitecture = Architecture.Arm;
  151. }
  152. else if (System.Environment.Is64BitOperatingSystem)
  153. {
  154. info.SystemArchitecture = Architecture.X64;
  155. }
  156. else
  157. {
  158. info.SystemArchitecture = Architecture.X86;
  159. }
  160. return info;
  161. }
  162. private static Uname _unixName;
  163. private static Uname GetUnixName()
  164. {
  165. if (_unixName == null)
  166. {
  167. var uname = new Uname();
  168. try
  169. {
  170. Utsname utsname;
  171. var callResult = Syscall.uname(out utsname);
  172. if (callResult == 0)
  173. {
  174. uname.sysname = utsname.sysname ?? string.Empty;
  175. uname.machine = utsname.machine ?? string.Empty;
  176. }
  177. }
  178. catch (Exception ex)
  179. {
  180. _logger.ErrorException("Error getting unix name", ex);
  181. }
  182. _unixName = uname;
  183. }
  184. return _unixName;
  185. }
  186. public class Uname
  187. {
  188. public string sysname = string.Empty;
  189. public string machine = string.Empty;
  190. }
  191. private static async void StartServer(CancellationToken cancellationToken)
  192. {
  193. var initProgress = new Progress<double>();
  194. await AppHost.Init (initProgress).ConfigureAwait (false);
  195. await AppHost.RunStartupTasks ().ConfigureAwait (false);
  196. if (MenuBarIcon.Instance != null)
  197. {
  198. MenuBarIcon.Instance.Localize ();
  199. }
  200. }
  201. public static void Shutdown()
  202. {
  203. ShutdownApp();
  204. }
  205. private static void ShutdownApp()
  206. {
  207. _logger.Info ("Calling ApplicationHost.Dispose");
  208. AppHost.Dispose ();
  209. _logger.Info("AppController.Terminate");
  210. MenuBarIcon.Instance.Terminate ();
  211. }
  212. public static void Restart()
  213. {
  214. _logger.Info("Disposing app host");
  215. AppHost.Dispose();
  216. _logger.Info("Starting new instance");
  217. var args = Environment.GetCommandLineArgs()
  218. .Skip(1)
  219. .Select(NormalizeCommandLineArgument);
  220. var commandLineArgsString = string.Join(" ", args.ToArray());
  221. var module = Environment.GetCommandLineArgs().First();
  222. _logger.Info ("Executable: {0}", module);
  223. _logger.Info ("Arguments: {0}", commandLineArgsString);
  224. Process.Start(module, commandLineArgsString);
  225. _logger.Info("AppController.Terminate");
  226. MenuBarIcon.Instance.Terminate();
  227. }
  228. private static string NormalizeCommandLineArgument(string arg)
  229. {
  230. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  231. {
  232. return arg;
  233. }
  234. return "\"" + arg + "\"";
  235. }
  236. /// <summary>
  237. /// Handles the UnhandledException event of the CurrentDomain control.
  238. /// </summary>
  239. /// <param name="sender">The source of the event.</param>
  240. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  241. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  242. {
  243. var exception = (Exception)e.ExceptionObject;
  244. var consoleLogger = new ConsoleLogger();
  245. new UnhandledExceptionWriter(AppHost.ServerConfigurationManager.ApplicationPaths, _logger, AppHost.LogManager, _fileSystem, consoleLogger).Log(exception);
  246. if (!Debugger.IsAttached)
  247. {
  248. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  249. }
  250. }
  251. }
  252. class NoCheckCertificatePolicy : ICertificatePolicy
  253. {
  254. public bool CheckValidationResult (ServicePoint srvPoint,
  255. System.Security.Cryptography.X509Certificates.X509Certificate certificate,
  256. WebRequest request,
  257. int certificateProblem)
  258. {
  259. return true;
  260. }
  261. }
  262. }