Main.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 fileSystem = new MonoFileSystem(logManager.GetLogger("FileSystem"), false, false, appPaths.TempDirectory);
  89. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  90. _fileSystem = fileSystem;
  91. var environmentInfo = GetEnvironmentInfo();
  92. var imageEncoder = ImageEncoderHelper.GetImageEncoder(_logger,
  93. logManager,
  94. fileSystem,
  95. options,
  96. () => AppHost.HttpClient,
  97. appPaths);
  98. AppHost = new MacAppHost(appPaths,
  99. logManager,
  100. options,
  101. fileSystem,
  102. new PowerManagement(),
  103. "Emby.Server.Mac.pkg",
  104. environmentInfo,
  105. imageEncoder,
  106. new Startup.Common.SystemEvents(logManager.GetLogger("SystemEvents")),
  107. new MemoryStreamProvider(),
  108. new NetworkManager(logManager.GetLogger("NetworkManager")),
  109. GenerateCertificate,
  110. () => Environment.UserName);
  111. if (options.ContainsOption("-v")) {
  112. Console.WriteLine (AppHost.ApplicationVersion.ToString());
  113. return;
  114. }
  115. Console.WriteLine ("appHost.Init");
  116. Task.Run (() => StartServer(CancellationToken.None));
  117. }
  118. private static void GenerateCertificate(string certPath, string certHost)
  119. {
  120. CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, _logger);
  121. }
  122. private static EnvironmentInfo GetEnvironmentInfo()
  123. {
  124. var info = new EnvironmentInfo()
  125. {
  126. CustomOperatingSystem = MediaBrowser.Model.System.OperatingSystem.OSX
  127. };
  128. var uname = GetUnixName();
  129. var sysName = uname.sysname ?? string.Empty;
  130. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  131. {
  132. //info.OperatingSystem = Startup.Common.OperatingSystem.Osx;
  133. }
  134. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  135. {
  136. //info.OperatingSystem = Startup.Common.OperatingSystem.Linux;
  137. }
  138. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  139. {
  140. //info.OperatingSystem = Startup.Common.OperatingSystem.Bsd;
  141. //info.IsBsd = true;
  142. }
  143. var archX86 = new Regex("(i|I)[3-6]86");
  144. if (archX86.IsMatch(uname.machine))
  145. {
  146. info.CustomArchitecture = Architecture.X86;
  147. }
  148. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  149. {
  150. info.CustomArchitecture = Architecture.X64;
  151. }
  152. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  153. {
  154. info.CustomArchitecture = Architecture.Arm;
  155. }
  156. else if (System.Environment.Is64BitOperatingSystem)
  157. {
  158. info.CustomArchitecture = Architecture.X64;
  159. }
  160. else
  161. {
  162. info.CustomArchitecture = Architecture.X86;
  163. }
  164. return info;
  165. }
  166. private static Uname _unixName;
  167. private static Uname GetUnixName()
  168. {
  169. if (_unixName == null)
  170. {
  171. var uname = new Uname();
  172. try
  173. {
  174. Utsname utsname;
  175. var callResult = Syscall.uname(out utsname);
  176. if (callResult == 0)
  177. {
  178. uname.sysname = utsname.sysname ?? string.Empty;
  179. uname.machine = utsname.machine ?? string.Empty;
  180. }
  181. }
  182. catch (Exception ex)
  183. {
  184. _logger.ErrorException("Error getting unix name", ex);
  185. }
  186. _unixName = uname;
  187. }
  188. return _unixName;
  189. }
  190. public class Uname
  191. {
  192. public string sysname = string.Empty;
  193. public string machine = string.Empty;
  194. }
  195. private static async void StartServer(CancellationToken cancellationToken)
  196. {
  197. var initProgress = new Progress<double>();
  198. await AppHost.Init (initProgress).ConfigureAwait (false);
  199. await AppHost.RunStartupTasks ().ConfigureAwait (false);
  200. if (MenuBarIcon.Instance != null)
  201. {
  202. MenuBarIcon.Instance.Localize ();
  203. }
  204. }
  205. public static void Shutdown()
  206. {
  207. ShutdownApp();
  208. }
  209. private static void ShutdownApp()
  210. {
  211. _logger.Info ("Calling ApplicationHost.Dispose");
  212. AppHost.Dispose ();
  213. _logger.Info("AppController.Terminate");
  214. MenuBarIcon.Instance.Terminate ();
  215. }
  216. public static void Restart()
  217. {
  218. _logger.Info("Disposing app host");
  219. AppHost.Dispose();
  220. _logger.Info("Starting new instance");
  221. var args = Environment.GetCommandLineArgs()
  222. .Skip(1)
  223. .Select(NormalizeCommandLineArgument);
  224. var commandLineArgsString = string.Join(" ", args.ToArray());
  225. var module = Environment.GetCommandLineArgs().First();
  226. _logger.Info ("Executable: {0}", module);
  227. _logger.Info ("Arguments: {0}", commandLineArgsString);
  228. Process.Start(module, commandLineArgsString);
  229. _logger.Info("AppController.Terminate");
  230. MenuBarIcon.Instance.Terminate();
  231. }
  232. private static string NormalizeCommandLineArgument(string arg)
  233. {
  234. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  235. {
  236. return arg;
  237. }
  238. return "\"" + arg + "\"";
  239. }
  240. /// <summary>
  241. /// Handles the UnhandledException event of the CurrentDomain control.
  242. /// </summary>
  243. /// <param name="sender">The source of the event.</param>
  244. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  245. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  246. {
  247. var exception = (Exception)e.ExceptionObject;
  248. var consoleLogger = new ConsoleLogger();
  249. new UnhandledExceptionWriter(AppHost.ServerConfigurationManager.ApplicationPaths, _logger, AppHost.LogManager, _fileSystem, consoleLogger).Log(exception);
  250. if (!Debugger.IsAttached)
  251. {
  252. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  253. }
  254. }
  255. }
  256. class NoCheckCertificatePolicy : ICertificatePolicy
  257. {
  258. public bool CheckValidationResult (ServicePoint srvPoint,
  259. System.Security.Cryptography.X509Certificates.X509Certificate certificate,
  260. WebRequest request,
  261. int certificateProblem)
  262. {
  263. return true;
  264. }
  265. }
  266. }