Main.cs 10 KB

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