App.xaml.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Constants;
  3. using MediaBrowser.Common.Implementations.Updates;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Server.Implementations;
  9. using MediaBrowser.ServerApplication.Splash;
  10. using Microsoft.Win32;
  11. using System;
  12. using System.Diagnostics;
  13. using System.IO;
  14. using System.Net.Cache;
  15. using System.Threading;
  16. using System.Windows;
  17. using System.Windows.Controls;
  18. using System.Windows.Media;
  19. using System.Windows.Media.Imaging;
  20. namespace MediaBrowser.ServerApplication
  21. {
  22. /// <summary>
  23. /// Interaction logic for App.xaml
  24. /// </summary>
  25. public partial class App : Application
  26. {
  27. /// <summary>
  28. /// The single instance mutex
  29. /// </summary>
  30. private static Mutex _singleInstanceMutex;
  31. /// <summary>
  32. /// Defines the entry point of the application.
  33. /// </summary>
  34. [STAThread]
  35. public static void Main()
  36. {
  37. bool createdNew;
  38. _singleInstanceMutex = new Mutex(true, @"Local\" + typeof(App).Assembly.GetName().Name, out createdNew);
  39. if (!createdNew)
  40. {
  41. _singleInstanceMutex = null;
  42. return;
  43. }
  44. // Look for the existence of an update archive
  45. var appPaths = new ServerApplicationPaths();
  46. var updateArchive = Path.Combine(appPaths.TempUpdatePath, Constants.MbServerPkgName + ".zip");
  47. if (File.Exists(updateArchive))
  48. {
  49. // Update is there - execute update
  50. try
  51. {
  52. new ApplicationUpdater().UpdateApplication(MBApplication.MBServer, appPaths, updateArchive);
  53. // And just let the app exit so it can update
  54. return;
  55. }
  56. catch (Exception e)
  57. {
  58. MessageBox.Show(string.Format("Error attempting to update application.\n\n{0}\n\n{1}", e.GetType().Name, e.Message));
  59. }
  60. }
  61. var application = new App();
  62. application.Run();
  63. }
  64. /// <summary>
  65. /// Gets the instance.
  66. /// </summary>
  67. /// <value>The instance.</value>
  68. public static App Instance
  69. {
  70. get
  71. {
  72. return Current as App;
  73. }
  74. }
  75. /// <summary>
  76. /// Gets or sets the logger.
  77. /// </summary>
  78. /// <value>The logger.</value>
  79. protected ILogger Logger { get; set; }
  80. /// <summary>
  81. /// Gets or sets the composition root.
  82. /// </summary>
  83. /// <value>The composition root.</value>
  84. protected ApplicationHost CompositionRoot { get; set; }
  85. /// <summary>
  86. /// Initializes a new instance of the <see cref="App" /> class.
  87. /// </summary>
  88. /// <param name="logger">The logger.</param>
  89. public App()
  90. {
  91. InitializeComponent();
  92. }
  93. /// <summary>
  94. /// Gets the name of the uninstaller file.
  95. /// </summary>
  96. /// <value>The name of the uninstaller file.</value>
  97. protected string UninstallerFileName
  98. {
  99. get { return "MediaBrowser.Server.Uninstall.exe"; }
  100. }
  101. /// <summary>
  102. /// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
  103. /// </summary>
  104. /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
  105. protected override void OnStartup(StartupEventArgs e)
  106. {
  107. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  108. LoadKernel();
  109. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  110. }
  111. /// <summary>
  112. /// Handles the UnhandledException event of the CurrentDomain control.
  113. /// </summary>
  114. /// <param name="sender">The source of the event.</param>
  115. /// <param name="e">The <see cref="UnhandledExceptionEventArgs" /> instance containing the event data.</param>
  116. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  117. {
  118. var exception = (Exception)e.ExceptionObject;
  119. Logger.ErrorException("UnhandledException", exception);
  120. MessageBox.Show("Unhandled exception: " + exception.Message);
  121. if (!Debugger.IsAttached)
  122. {
  123. Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(exception));
  124. }
  125. }
  126. /// <summary>
  127. /// Handles the SessionEnding event of the SystemEvents control.
  128. /// </summary>
  129. /// <param name="sender">The source of the event.</param>
  130. /// <param name="e">The <see cref="SessionEndingEventArgs" /> instance containing the event data.</param>
  131. void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  132. {
  133. // Try to shut down gracefully
  134. Shutdown();
  135. }
  136. /// <summary>
  137. /// Loads the kernel.
  138. /// </summary>
  139. protected async void LoadKernel()
  140. {
  141. try
  142. {
  143. CompositionRoot = new ApplicationHost();
  144. Logger = CompositionRoot.LogManager.GetLogger("App");
  145. var splash = new SplashWindow(CompositionRoot.ApplicationVersion);
  146. splash.Show();
  147. await CompositionRoot.Init();
  148. splash.Hide();
  149. var task = CompositionRoot.RunStartupTasks();
  150. new MainWindow(CompositionRoot.LogManager, CompositionRoot, CompositionRoot.ServerConfigurationManager, CompositionRoot.UserManager, CompositionRoot.LibraryManager, CompositionRoot.JsonSerializer, CompositionRoot.DisplayPreferencesRepository).Show();
  151. await task.ConfigureAwait(false);
  152. }
  153. catch (Exception ex)
  154. {
  155. Logger.ErrorException("Error launching application", ex);
  156. MessageBox.Show("There was an error launching Media Browser: " + ex.Message);
  157. // Shutdown the app with an error code
  158. Shutdown(1);
  159. }
  160. }
  161. /// <summary>
  162. /// Raises the <see cref="E:System.Windows.Application.Exit" /> event.
  163. /// </summary>
  164. /// <param name="e">An <see cref="T:System.Windows.ExitEventArgs" /> that contains the event data.</param>
  165. protected override void OnExit(ExitEventArgs e)
  166. {
  167. ReleaseMutex();
  168. base.OnExit(e);
  169. if (CompositionRoot != null)
  170. {
  171. CompositionRoot.Dispose();
  172. }
  173. }
  174. /// <summary>
  175. /// Releases the mutex.
  176. /// </summary>
  177. private void ReleaseMutex()
  178. {
  179. if (_singleInstanceMutex == null)
  180. {
  181. return;
  182. }
  183. _singleInstanceMutex.ReleaseMutex();
  184. _singleInstanceMutex.Close();
  185. _singleInstanceMutex.Dispose();
  186. _singleInstanceMutex = null;
  187. }
  188. /// <summary>
  189. /// Opens the dashboard page.
  190. /// </summary>
  191. /// <param name="page">The page.</param>
  192. /// <param name="loggedInUser">The logged in user.</param>
  193. /// <param name="configurationManager">The configuration manager.</param>
  194. /// <param name="appHost">The app host.</param>
  195. public static void OpenDashboardPage(string page, User loggedInUser, IServerConfigurationManager configurationManager, IServerApplicationHost appHost)
  196. {
  197. var url = "http://localhost:" + configurationManager.Configuration.HttpServerPortNumber + "/" +
  198. appHost.WebApplicationName + "/dashboard/" + page;
  199. OpenUrl(url);
  200. }
  201. /// <summary>
  202. /// Opens the URL.
  203. /// </summary>
  204. /// <param name="url">The URL.</param>
  205. public static void OpenUrl(string url)
  206. {
  207. var process = new Process
  208. {
  209. StartInfo = new ProcessStartInfo
  210. {
  211. FileName = url
  212. },
  213. EnableRaisingEvents = true
  214. };
  215. process.Exited += ProcessExited;
  216. process.Start();
  217. }
  218. /// <summary>
  219. /// Processes the exited.
  220. /// </summary>
  221. /// <param name="sender">The sender.</param>
  222. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  223. static void ProcessExited(object sender, EventArgs e)
  224. {
  225. ((Process)sender).Dispose();
  226. }
  227. /// <summary>
  228. /// Restarts this instance.
  229. /// </summary>
  230. /// <exception cref="System.NotImplementedException"></exception>
  231. public void Restart()
  232. {
  233. Dispatcher.Invoke(ReleaseMutex);
  234. CompositionRoot.Dispose();
  235. System.Windows.Forms.Application.Restart();
  236. Dispatcher.Invoke(Shutdown);
  237. }
  238. /// <summary>
  239. /// Gets the image.
  240. /// </summary>
  241. /// <param name="uri">The URI.</param>
  242. /// <returns>Image.</returns>
  243. /// <exception cref="System.ArgumentNullException">uri</exception>
  244. public Image GetImage(string uri)
  245. {
  246. if (string.IsNullOrEmpty(uri))
  247. {
  248. throw new ArgumentNullException("uri");
  249. }
  250. return GetImage(new Uri(uri));
  251. }
  252. /// <summary>
  253. /// Gets the image.
  254. /// </summary>
  255. /// <param name="uri">The URI.</param>
  256. /// <returns>Image.</returns>
  257. /// <exception cref="System.ArgumentNullException">uri</exception>
  258. public Image GetImage(Uri uri)
  259. {
  260. if (uri == null)
  261. {
  262. throw new ArgumentNullException("uri");
  263. }
  264. return new Image { Source = GetBitmapImage(uri) };
  265. }
  266. /// <summary>
  267. /// Gets the bitmap image.
  268. /// </summary>
  269. /// <param name="uri">The URI.</param>
  270. /// <returns>BitmapImage.</returns>
  271. /// <exception cref="System.ArgumentNullException">uri</exception>
  272. public BitmapImage GetBitmapImage(string uri)
  273. {
  274. if (string.IsNullOrEmpty(uri))
  275. {
  276. throw new ArgumentNullException("uri");
  277. }
  278. return GetBitmapImage(new Uri(uri));
  279. }
  280. /// <summary>
  281. /// Gets the bitmap image.
  282. /// </summary>
  283. /// <param name="uri">The URI.</param>
  284. /// <returns>BitmapImage.</returns>
  285. /// <exception cref="System.ArgumentNullException">uri</exception>
  286. public BitmapImage GetBitmapImage(Uri uri)
  287. {
  288. if (uri == null)
  289. {
  290. throw new ArgumentNullException("uri");
  291. }
  292. var bitmap = new BitmapImage
  293. {
  294. CreateOptions = BitmapCreateOptions.DelayCreation,
  295. CacheOption = BitmapCacheOption.OnDemand,
  296. UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable)
  297. };
  298. bitmap.BeginInit();
  299. bitmap.UriSource = uri;
  300. bitmap.EndInit();
  301. RenderOptions.SetBitmapScalingMode(bitmap, BitmapScalingMode.Fant);
  302. return bitmap;
  303. }
  304. }
  305. }