Main.cs 10 KB

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