Main.cs 10 KB

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