Main.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. {
  120. CustomOperatingSystem = MediaBrowser.Model.System.OperatingSystem.OSX
  121. };
  122. var uname = GetUnixName();
  123. var sysName = uname.sysname ?? string.Empty;
  124. if (string.Equals(sysName, "Darwin", StringComparison.OrdinalIgnoreCase))
  125. {
  126. //info.OperatingSystem = Startup.Common.OperatingSystem.Osx;
  127. }
  128. else if (string.Equals(sysName, "Linux", StringComparison.OrdinalIgnoreCase))
  129. {
  130. //info.OperatingSystem = Startup.Common.OperatingSystem.Linux;
  131. }
  132. else if (string.Equals(sysName, "BSD", StringComparison.OrdinalIgnoreCase))
  133. {
  134. //info.OperatingSystem = Startup.Common.OperatingSystem.Bsd;
  135. //info.IsBsd = true;
  136. }
  137. var archX86 = new Regex("(i|I)[3-6]86");
  138. if (archX86.IsMatch(uname.machine))
  139. {
  140. info.CustomArchitecture = Architecture.X86;
  141. }
  142. else if (string.Equals(uname.machine, "x86_64", StringComparison.OrdinalIgnoreCase))
  143. {
  144. info.CustomArchitecture = Architecture.X64;
  145. }
  146. else if (uname.machine.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
  147. {
  148. info.CustomArchitecture = Architecture.Arm;
  149. }
  150. else if (System.Environment.Is64BitOperatingSystem)
  151. {
  152. info.CustomArchitecture = Architecture.X64;
  153. }
  154. else
  155. {
  156. info.CustomArchitecture = Architecture.X86;
  157. }
  158. return info;
  159. }
  160. private static Uname _unixName;
  161. private static Uname GetUnixName()
  162. {
  163. if (_unixName == null)
  164. {
  165. var uname = new Uname();
  166. try
  167. {
  168. Utsname utsname;
  169. var callResult = Syscall.uname(out utsname);
  170. if (callResult == 0)
  171. {
  172. uname.sysname = utsname.sysname ?? string.Empty;
  173. uname.machine = utsname.machine ?? string.Empty;
  174. }
  175. }
  176. catch (Exception ex)
  177. {
  178. _logger.ErrorException("Error getting unix name", ex);
  179. }
  180. _unixName = uname;
  181. }
  182. return _unixName;
  183. }
  184. public class Uname
  185. {
  186. public string sysname = string.Empty;
  187. public string machine = string.Empty;
  188. }
  189. private static async void StartServer(CancellationToken cancellationToken)
  190. {
  191. var initProgress = new Progress<double>();
  192. await AppHost.Init (initProgress).ConfigureAwait (false);
  193. await AppHost.RunStartupTasks ().ConfigureAwait (false);
  194. if (MenuBarIcon.Instance != null)
  195. {
  196. MenuBarIcon.Instance.Localize ();
  197. }
  198. }
  199. public static void Shutdown()
  200. {
  201. ShutdownApp();
  202. }
  203. private static void ShutdownApp()
  204. {
  205. _logger.Info ("Calling ApplicationHost.Dispose");
  206. AppHost.Dispose ();
  207. _logger.Info("AppController.Terminate");
  208. MenuBarIcon.Instance.Terminate ();
  209. }
  210. public static void Restart()
  211. {
  212. _logger.Info("Disposing app host");
  213. AppHost.Dispose();
  214. _logger.Info("Starting new instance");
  215. var args = Environment.GetCommandLineArgs()
  216. .Skip(1)
  217. .Select(NormalizeCommandLineArgument);
  218. var commandLineArgsString = string.Join(" ", args.ToArray());
  219. var module = Environment.GetCommandLineArgs().First();
  220. _logger.Info ("Executable: {0}", module);
  221. _logger.Info ("Arguments: {0}", commandLineArgsString);
  222. Process.Start(module, commandLineArgsString);
  223. _logger.Info("AppController.Terminate");
  224. MenuBarIcon.Instance.Terminate();
  225. }
  226. private static string NormalizeCommandLineArgument(string arg)
  227. {
  228. if (arg.IndexOf(" ", StringComparison.OrdinalIgnoreCase) == -1)
  229. {
  230. return arg;
  231. }
  232. return "\"" + arg + "\"";
  233. }
  234. /// <summary>
  235. /// Handles the UnhandledException event of the CurrentDomain control.
  236. /// </summary>
  237. /// <param name="sender">The source of the event.</param>
  238. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  239. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  240. {
  241. var exception = (Exception)e.ExceptionObject;
  242. new UnhandledExceptionWriter(AppHost.ServerConfigurationManager.ApplicationPaths, _logger, AppHost.LogManager).Log(exception);
  243. if (!Debugger.IsAttached)
  244. {
  245. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  246. }
  247. }
  248. }
  249. class NoCheckCertificatePolicy : ICertificatePolicy
  250. {
  251. public bool CheckValidationResult (ServicePoint srvPoint,
  252. System.Security.Cryptography.X509Certificates.X509Certificate certificate,
  253. WebRequest request,
  254. int certificateProblem)
  255. {
  256. return true;
  257. }
  258. }
  259. }