App.xaml.cs 13 KB

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