App.xaml.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. using MediaBrowser.ClickOnce;
  2. using MediaBrowser.Common.Kernel;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Model.Logging;
  6. using Microsoft.Win32;
  7. using System;
  8. using System.Diagnostics;
  9. using System.Net.Cache;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Windows;
  13. using System.Windows.Controls;
  14. using System.Windows.Media;
  15. using System.Windows.Media.Imaging;
  16. namespace MediaBrowser.ServerApplication
  17. {
  18. /// <summary>
  19. /// Interaction logic for App.xaml
  20. /// </summary>
  21. public partial class App : Application
  22. {
  23. /// <summary>
  24. /// Defines the entry point of the application.
  25. /// </summary>
  26. [STAThread]
  27. public static void Main()
  28. {
  29. var application = new App();
  30. application.Run();
  31. }
  32. /// <summary>
  33. /// Gets the instance.
  34. /// </summary>
  35. /// <value>The instance.</value>
  36. public static App Instance
  37. {
  38. get
  39. {
  40. return Current as App;
  41. }
  42. }
  43. /// <summary>
  44. /// The single instance mutex
  45. /// </summary>
  46. private Mutex SingleInstanceMutex;
  47. /// <summary>
  48. /// Gets or sets the kernel.
  49. /// </summary>
  50. /// <value>The kernel.</value>
  51. protected IKernel Kernel { get; set; }
  52. /// <summary>
  53. /// Gets or sets the logger.
  54. /// </summary>
  55. /// <value>The logger.</value>
  56. protected ILogger Logger { get; set; }
  57. /// <summary>
  58. /// Gets or sets the composition root.
  59. /// </summary>
  60. /// <value>The composition root.</value>
  61. protected ApplicationHost CompositionRoot { get; set; }
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="App" /> class.
  64. /// </summary>
  65. /// <param name="logger">The logger.</param>
  66. public App()
  67. {
  68. InitializeComponent();
  69. }
  70. /// <summary>
  71. /// Gets the name of the uninstaller file.
  72. /// </summary>
  73. /// <value>The name of the uninstaller file.</value>
  74. protected string UninstallerFileName
  75. {
  76. get { return "MediaBrowser.Server.Uninstall.exe"; }
  77. }
  78. /// <summary>
  79. /// Gets or sets a value indicating whether [last run at startup value].
  80. /// </summary>
  81. /// <value><c>null</c> if [last run at startup value] contains no value, <c>true</c> if [last run at startup value]; otherwise, <c>false</c>.</value>
  82. private bool? LastRunAtStartupValue { get; set; }
  83. /// <summary>
  84. /// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
  85. /// </summary>
  86. /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
  87. protected override void OnStartup(StartupEventArgs e)
  88. {
  89. bool createdNew;
  90. SingleInstanceMutex = new Mutex(true, @"Local\" + GetType().Assembly.GetName().Name, out createdNew);
  91. if (!createdNew)
  92. {
  93. SingleInstanceMutex = null;
  94. Shutdown();
  95. return;
  96. }
  97. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  98. LoadKernel();
  99. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  100. }
  101. /// <summary>
  102. /// Handles the UnhandledException event of the CurrentDomain control.
  103. /// </summary>
  104. /// <param name="sender">The source of the event.</param>
  105. /// <param name="e">The <see cref="UnhandledExceptionEventArgs" /> instance containing the event data.</param>
  106. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  107. {
  108. var exception = (Exception)e.ExceptionObject;
  109. Logger.ErrorException("UnhandledException", exception);
  110. MessageBox.Show("Unhandled exception: " + exception.Message);
  111. }
  112. /// <summary>
  113. /// Handles the SessionEnding event of the SystemEvents control.
  114. /// </summary>
  115. /// <param name="sender">The source of the event.</param>
  116. /// <param name="e">The <see cref="SessionEndingEventArgs" /> instance containing the event data.</param>
  117. void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  118. {
  119. // Try to shut down gracefully
  120. Shutdown();
  121. }
  122. /// <summary>
  123. /// Loads the kernel.
  124. /// </summary>
  125. protected async void LoadKernel()
  126. {
  127. CompositionRoot = new ApplicationHost();
  128. Logger = CompositionRoot.Logger;
  129. Kernel = CompositionRoot.Kernel;
  130. try
  131. {
  132. var win = (MainWindow)CompositionRoot.CreateInstance(typeof(MainWindow));
  133. win.Show();
  134. var now = DateTime.UtcNow;
  135. await Kernel.Init();
  136. var done = (DateTime.UtcNow - now);
  137. Logger.Info("Kernel.Init completed in {0}{1} minutes and {2} seconds.", done.Hours > 0 ? done.Hours + " Hours " : "", done.Minutes, done.Seconds);
  138. await OnKernelLoaded();
  139. }
  140. catch (Exception ex)
  141. {
  142. Logger.ErrorException("Error launching application", ex);
  143. MessageBox.Show("There was an error launching Media Browser: " + ex.Message);
  144. // Shutdown the app with an error code
  145. Shutdown(1);
  146. }
  147. }
  148. /// <summary>
  149. /// Called when [kernel loaded].
  150. /// </summary>
  151. /// <returns>Task.</returns>
  152. protected Task OnKernelLoaded()
  153. {
  154. return Task.Run(() =>
  155. {
  156. Kernel.ConfigurationUpdated += Kernel_ConfigurationUpdated;
  157. ConfigureAutoRun();
  158. });
  159. }
  160. /// <summary>
  161. /// Handles the ConfigurationUpdated event of the Kernel control.
  162. /// </summary>
  163. /// <param name="sender">The source of the event.</param>
  164. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  165. void Kernel_ConfigurationUpdated(object sender, EventArgs e)
  166. {
  167. if (!LastRunAtStartupValue.HasValue || LastRunAtStartupValue.Value != Kernel.Configuration.RunAtStartup)
  168. {
  169. ConfigureAutoRun();
  170. }
  171. }
  172. /// <summary>
  173. /// Configures the click once startup.
  174. /// </summary>
  175. private void ConfigureAutoRun()
  176. {
  177. CompositionRoot.ConfigureAutoRunAtStartup(Kernel.Configuration.RunAtStartup);
  178. }
  179. /// <summary>
  180. /// Raises the <see cref="E:System.Windows.Application.Exit" /> event.
  181. /// </summary>
  182. /// <param name="e">An <see cref="T:System.Windows.ExitEventArgs" /> that contains the event data.</param>
  183. protected override void OnExit(ExitEventArgs e)
  184. {
  185. ReleaseMutex();
  186. base.OnExit(e);
  187. CompositionRoot.Dispose();
  188. }
  189. /// <summary>
  190. /// Releases the mutex.
  191. /// </summary>
  192. private void ReleaseMutex()
  193. {
  194. if (SingleInstanceMutex == null)
  195. {
  196. return;
  197. }
  198. SingleInstanceMutex.ReleaseMutex();
  199. SingleInstanceMutex.Close();
  200. SingleInstanceMutex.Dispose();
  201. SingleInstanceMutex = null;
  202. }
  203. /// <summary>
  204. /// Opens the dashboard.
  205. /// </summary>
  206. public static void OpenDashboard(User loggedInUser)
  207. {
  208. OpenDashboardPage("dashboard.html", loggedInUser);
  209. }
  210. /// <summary>
  211. /// Opens the dashboard page.
  212. /// </summary>
  213. /// <param name="page">The page.</param>
  214. public static void OpenDashboardPage(string page, User loggedInUser)
  215. {
  216. var url = "http://localhost:" + Controller.Kernel.Instance.Configuration.HttpServerPortNumber + "/" +
  217. Controller.Kernel.Instance.WebApplicationName + "/dashboard/" + page;
  218. if (loggedInUser != null)
  219. {
  220. url = AddAutoLoginToDashboardUrl(url, loggedInUser);
  221. }
  222. OpenUrl(url);
  223. }
  224. /// <summary>
  225. /// Adds the auto login to dashboard URL.
  226. /// </summary>
  227. /// <param name="url">The URL.</param>
  228. /// <param name="user">The user.</param>
  229. /// <returns>System.String.</returns>
  230. public static string AddAutoLoginToDashboardUrl(string url, User user)
  231. {
  232. if (url.IndexOf('?') == -1)
  233. {
  234. url += "?u=" + user.Id;
  235. }
  236. else
  237. {
  238. url += "&u=" + user.Id;
  239. }
  240. return url;
  241. }
  242. /// <summary>
  243. /// Opens the URL.
  244. /// </summary>
  245. /// <param name="url">The URL.</param>
  246. public static void OpenUrl(string url)
  247. {
  248. var process = new Process
  249. {
  250. StartInfo = new ProcessStartInfo
  251. {
  252. FileName = url
  253. },
  254. EnableRaisingEvents = true
  255. };
  256. process.Exited += ProcessExited;
  257. process.Start();
  258. }
  259. /// <summary>
  260. /// Processes the exited.
  261. /// </summary>
  262. /// <param name="sender">The sender.</param>
  263. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  264. static void ProcessExited(object sender, EventArgs e)
  265. {
  266. ((Process)sender).Dispose();
  267. }
  268. /// <summary>
  269. /// Restarts this instance.
  270. /// </summary>
  271. /// <exception cref="System.NotImplementedException"></exception>
  272. public void Restart()
  273. {
  274. Dispatcher.Invoke(ReleaseMutex);
  275. CompositionRoot.Dispose();
  276. System.Windows.Forms.Application.Restart();
  277. Dispatcher.Invoke(Shutdown);
  278. }
  279. /// <summary>
  280. /// Gets the image.
  281. /// </summary>
  282. /// <param name="uri">The URI.</param>
  283. /// <returns>Image.</returns>
  284. /// <exception cref="System.ArgumentNullException">uri</exception>
  285. public Image GetImage(string uri)
  286. {
  287. if (string.IsNullOrEmpty(uri))
  288. {
  289. throw new ArgumentNullException("uri");
  290. }
  291. return GetImage(new Uri(uri));
  292. }
  293. /// <summary>
  294. /// Gets the image.
  295. /// </summary>
  296. /// <param name="uri">The URI.</param>
  297. /// <returns>Image.</returns>
  298. /// <exception cref="System.ArgumentNullException">uri</exception>
  299. public Image GetImage(Uri uri)
  300. {
  301. if (uri == null)
  302. {
  303. throw new ArgumentNullException("uri");
  304. }
  305. return new Image { Source = GetBitmapImage(uri) };
  306. }
  307. /// <summary>
  308. /// Gets the bitmap image.
  309. /// </summary>
  310. /// <param name="uri">The URI.</param>
  311. /// <returns>BitmapImage.</returns>
  312. /// <exception cref="System.ArgumentNullException">uri</exception>
  313. public BitmapImage GetBitmapImage(string uri)
  314. {
  315. if (string.IsNullOrEmpty(uri))
  316. {
  317. throw new ArgumentNullException("uri");
  318. }
  319. return GetBitmapImage(new Uri(uri));
  320. }
  321. /// <summary>
  322. /// Gets the bitmap image.
  323. /// </summary>
  324. /// <param name="uri">The URI.</param>
  325. /// <returns>BitmapImage.</returns>
  326. /// <exception cref="System.ArgumentNullException">uri</exception>
  327. public BitmapImage GetBitmapImage(Uri uri)
  328. {
  329. if (uri == null)
  330. {
  331. throw new ArgumentNullException("uri");
  332. }
  333. var bitmap = new BitmapImage
  334. {
  335. CreateOptions = BitmapCreateOptions.DelayCreation,
  336. CacheOption = BitmapCacheOption.OnDemand,
  337. UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable)
  338. };
  339. bitmap.BeginInit();
  340. bitmap.UriSource = uri;
  341. bitmap.EndInit();
  342. RenderOptions.SetBitmapScalingMode(bitmap, BitmapScalingMode.Fant);
  343. return bitmap;
  344. }
  345. }
  346. }