Program.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. using MediaBrowser.Common.Constants;
  2. using MediaBrowser.Common.Implementations.Logging;
  3. using MediaBrowser.Common.Implementations.Updates;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Server.Implementations;
  6. using MediaBrowser.ServerApplication;
  7. using MediaBrowser.ServerApplication.Native;
  8. using Microsoft.Win32;
  9. using System;
  10. using System.Diagnostics;
  11. using System.IO;
  12. using System.Threading;
  13. using System.Windows;
  14. using System.Net;
  15. using System.Net.Security;
  16. using System.Security.Cryptography.X509Certificates;
  17. using Gtk;
  18. using Gdk;
  19. using System.Threading.Tasks;
  20. using System.Reflection;
  21. namespace MediaBrowser.Server.Mono
  22. {
  23. public class MainClass
  24. {
  25. private static ApplicationHost _appHost;
  26. private static ILogger _logger;
  27. private static MainWindow _mainWindow;
  28. // The tray Icon
  29. private static StatusIcon trayIcon;
  30. public static void Main (string[] args)
  31. {
  32. Application.Init ();
  33. var appPaths = CreateApplicationPaths();
  34. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  35. logManager.ReloadLogger(LogSeverity.Info);
  36. var logger = _logger = logManager.GetLogger("Main");
  37. BeginLog(logger);
  38. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  39. if (PerformUpdateIfNeeded(appPaths, logger))
  40. {
  41. logger.Info("Exiting to perform application update.");
  42. return;
  43. }
  44. try
  45. {
  46. RunApplication(appPaths, logManager);
  47. }
  48. finally
  49. {
  50. logger.Info("Shutting down");
  51. _appHost.Dispose();
  52. }
  53. }
  54. private static ServerApplicationPaths CreateApplicationPaths()
  55. {
  56. return new ServerApplicationPaths();
  57. }
  58. /// <summary>
  59. /// Determines whether this instance [can self restart].
  60. /// </summary>
  61. /// <returns><c>true</c> if this instance [can self restart]; otherwise, <c>false</c>.</returns>
  62. public static bool CanSelfRestart
  63. {
  64. get
  65. {
  66. return false;
  67. }
  68. }
  69. /// <summary>
  70. /// Gets a value indicating whether this instance can self update.
  71. /// </summary>
  72. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  73. public static bool CanSelfUpdate
  74. {
  75. get
  76. {
  77. return false;
  78. }
  79. }
  80. private static RemoteCertificateValidationCallback _ignoreCertificates = new RemoteCertificateValidationCallback(delegate { return true; });
  81. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager)
  82. {
  83. // TODO: Show splash here
  84. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  85. // Allow all https requests
  86. ServicePointManager.ServerCertificateValidationCallback = _ignoreCertificates;
  87. _appHost = new ApplicationHost(appPaths, logManager);
  88. var task = _appHost.Init();
  89. Task.WaitAll (task);
  90. task = _appHost.RunStartupTasks();
  91. Task.WaitAll (task);
  92. // TODO: Hide splash here
  93. _mainWindow = new MainWindow ();
  94. // Creation of the Icon
  95. // Creation of the Icon
  96. trayIcon = new StatusIcon(new Pixbuf ("tray.png"));
  97. trayIcon.Visible = true;
  98. // When the TrayIcon has been clicked.
  99. trayIcon.Activate += delegate { };
  100. // Show a pop up menu when the icon has been right clicked.
  101. trayIcon.PopupMenu += OnTrayIconPopup;
  102. // A Tooltip for the Icon
  103. trayIcon.Tooltip = "Media Browser Server";
  104. _mainWindow.ShowAll ();
  105. _mainWindow.Visible = false;
  106. Application.Run ();
  107. }
  108. // Create the popup menu, on right click.
  109. static void OnTrayIconPopup (object o, EventArgs args) {
  110. Menu popupMenu = new Menu();
  111. var menuItemBrowse = new ImageMenuItem ("Browse Library");
  112. menuItemBrowse.Image = new Gtk.Image(Stock.MediaPlay, IconSize.Menu);
  113. popupMenu.Add(menuItemBrowse);
  114. menuItemBrowse.Activated += delegate {
  115. BrowserLauncher.OpenWebClient(_appHost.UserManager, _appHost.ServerConfigurationManager, _appHost, _logger);
  116. };
  117. var menuItemConfigure = new ImageMenuItem ("Configure Media Browser");
  118. menuItemConfigure.Image = new Gtk.Image(Stock.Edit, IconSize.Menu);
  119. popupMenu.Add(menuItemConfigure);
  120. menuItemConfigure.Activated += delegate {
  121. BrowserLauncher.OpenDashboard(_appHost.UserManager, _appHost.ServerConfigurationManager, _appHost, _logger);
  122. };
  123. var menuItemApi = new ImageMenuItem ("View Api Docs");
  124. menuItemApi.Image = new Gtk.Image(Stock.Network, IconSize.Menu);
  125. popupMenu.Add(menuItemApi);
  126. menuItemApi.Activated += delegate {
  127. BrowserLauncher.OpenSwagger(_appHost.ServerConfigurationManager, _appHost, _logger);
  128. };
  129. var menuItemCommunity = new ImageMenuItem ("Visit Community");
  130. menuItemCommunity.Image = new Gtk.Image(Stock.Help, IconSize.Menu);
  131. popupMenu.Add(menuItemCommunity);
  132. menuItemCommunity.Activated += delegate { BrowserLauncher.OpenCommunity(_logger); };
  133. var menuItemGithub = new ImageMenuItem ("Visit Github");
  134. menuItemGithub.Image = new Gtk.Image(Stock.Network, IconSize.Menu);
  135. popupMenu.Add(menuItemGithub);
  136. menuItemGithub.Activated += delegate { BrowserLauncher.OpenGithub(_logger); };
  137. var menuItemQuit = new ImageMenuItem ("Exit");
  138. menuItemQuit.Image = new Gtk.Image(Stock.Quit, IconSize.Menu);
  139. popupMenu.Add(menuItemQuit);
  140. menuItemQuit.Activated += delegate { Shutdown(); };
  141. popupMenu.ShowAll();
  142. popupMenu.Popup();
  143. }
  144. /// <summary>
  145. /// Handles the SessionEnding event of the SystemEvents control.
  146. /// </summary>
  147. /// <param name="sender">The source of the event.</param>
  148. /// <param name="e">The <see cref="SessionEndingEventArgs"/> instance containing the event data.</param>
  149. static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  150. {
  151. if (e.Reason == SessionEndReasons.SystemShutdown)
  152. {
  153. Shutdown();
  154. }
  155. }
  156. /// <summary>
  157. /// Begins the log.
  158. /// </summary>
  159. /// <param name="logger">The logger.</param>
  160. private static void BeginLog(ILogger logger)
  161. {
  162. logger.Info("Media Browser Server started");
  163. logger.Info("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs()));
  164. logger.Info("Server: {0}", Environment.MachineName);
  165. logger.Info("Operating system: {0}", Environment.OSVersion.ToString());
  166. MonoBug11817WorkAround.Apply ();
  167. }
  168. /// <summary>
  169. /// Handles the UnhandledException event of the CurrentDomain control.
  170. /// </summary>
  171. /// <param name="sender">The source of the event.</param>
  172. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  173. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  174. {
  175. var exception = (Exception)e.ExceptionObject;
  176. LogUnhandledException(exception);
  177. if (!Debugger.IsAttached)
  178. {
  179. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  180. }
  181. }
  182. private static void LogUnhandledException(Exception ex)
  183. {
  184. _logger.ErrorException("UnhandledException", ex);
  185. _appHost.LogManager.Flush ();
  186. var path = Path.Combine(_appHost.ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "crash_" + Guid.NewGuid() + ".txt");
  187. var builder = LogHelper.GetLogMessage(ex);
  188. File.WriteAllText(path, builder.ToString());
  189. }
  190. /// <summary>
  191. /// Performs the update if needed.
  192. /// </summary>
  193. /// <param name="appPaths">The app paths.</param>
  194. /// <param name="logger">The logger.</param>
  195. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  196. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  197. {
  198. return false;
  199. }
  200. public static void Shutdown()
  201. {
  202. if (trayIcon != null) {
  203. trayIcon.Visible = false;
  204. trayIcon.Dispose ();
  205. trayIcon = null;
  206. }
  207. if (_mainWindow != null) {
  208. _mainWindow.HideAll ();
  209. _mainWindow.Dispose ();
  210. _mainWindow = null;
  211. }
  212. Application.Quit ();
  213. }
  214. public static void Restart()
  215. {
  216. // Second instance will start first, so dispose so that the http ports will be available to the new instance
  217. _appHost.Dispose();
  218. // Right now this method will just shutdown, but not restart
  219. Shutdown ();
  220. }
  221. }
  222. class NoCheckCertificatePolicy : ICertificatePolicy
  223. {
  224. public bool CheckValidationResult (ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  225. {
  226. return true;
  227. }
  228. }
  229. public class MonoBug11817WorkAround
  230. {
  231. public static void Apply()
  232. {
  233. var property = typeof(TimeZoneInfo).GetProperty("TimeZoneDirectory", BindingFlags.Static | BindingFlags.NonPublic);
  234. if (property == null) return;
  235. var zoneInfo = FindZoneInfoFolder();
  236. property.SetValue(null, zoneInfo, new object[0]);
  237. }
  238. public static string FindZoneInfoFolder()
  239. {
  240. var current = new DirectoryInfo(Directory.GetCurrentDirectory());
  241. while(current != null)
  242. {
  243. var zoneinfoTestPath = Path.Combine(current.FullName, "zoneinfo");
  244. if (Directory.Exists(zoneinfoTestPath))
  245. return zoneinfoTestPath;
  246. current = current.Parent;
  247. }
  248. return null;
  249. }
  250. }
  251. }