App.xaml.cs 12 KB

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