App.xaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. await CompositionRoot.Init();
  149. Logger = CompositionRoot.Logger;
  150. Kernel = CompositionRoot.Kernel;
  151. try
  152. {
  153. var win = (MainWindow)CompositionRoot.CreateInstance(typeof(MainWindow));
  154. win.Show();
  155. var now = DateTime.UtcNow;
  156. Kernel.Init();
  157. var done = (DateTime.UtcNow - now);
  158. Logger.Info("Kernel.Init completed in {0}{1} minutes and {2} seconds.", done.Hours > 0 ? done.Hours + " Hours " : "", done.Minutes, done.Seconds);
  159. await OnKernelLoaded();
  160. }
  161. catch (Exception ex)
  162. {
  163. Logger.ErrorException("Error launching application", ex);
  164. MessageBox.Show("There was an error launching Media Browser: " + ex.Message);
  165. // Shutdown the app with an error code
  166. Shutdown(1);
  167. }
  168. }
  169. /// <summary>
  170. /// Called when [kernel loaded].
  171. /// </summary>
  172. /// <returns>Task.</returns>
  173. protected Task OnKernelLoaded()
  174. {
  175. return Task.Run(() =>
  176. {
  177. Kernel.ConfigurationUpdated += Kernel_ConfigurationUpdated;
  178. ConfigureAutoRun();
  179. });
  180. }
  181. /// <summary>
  182. /// Handles the ConfigurationUpdated event of the Kernel control.
  183. /// </summary>
  184. /// <param name="sender">The source of the event.</param>
  185. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  186. void Kernel_ConfigurationUpdated(object sender, EventArgs e)
  187. {
  188. if (!LastRunAtStartupValue.HasValue || LastRunAtStartupValue.Value != Kernel.Configuration.RunAtStartup)
  189. {
  190. ConfigureAutoRun();
  191. }
  192. }
  193. /// <summary>
  194. /// Configures the click once startup.
  195. /// </summary>
  196. private void ConfigureAutoRun()
  197. {
  198. CompositionRoot.ConfigureAutoRunAtStartup(Kernel.Configuration.RunAtStartup);
  199. }
  200. /// <summary>
  201. /// Raises the <see cref="E:System.Windows.Application.Exit" /> event.
  202. /// </summary>
  203. /// <param name="e">An <see cref="T:System.Windows.ExitEventArgs" /> that contains the event data.</param>
  204. protected override void OnExit(ExitEventArgs e)
  205. {
  206. ReleaseMutex();
  207. base.OnExit(e);
  208. CompositionRoot.Dispose();
  209. }
  210. /// <summary>
  211. /// Releases the mutex.
  212. /// </summary>
  213. private void ReleaseMutex()
  214. {
  215. if (SingleInstanceMutex == null)
  216. {
  217. return;
  218. }
  219. SingleInstanceMutex.ReleaseMutex();
  220. SingleInstanceMutex.Close();
  221. SingleInstanceMutex.Dispose();
  222. SingleInstanceMutex = null;
  223. }
  224. /// <summary>
  225. /// Opens the dashboard.
  226. /// </summary>
  227. public static void OpenDashboard(User loggedInUser)
  228. {
  229. OpenDashboardPage("dashboard.html", loggedInUser);
  230. }
  231. /// <summary>
  232. /// Opens the dashboard page.
  233. /// </summary>
  234. /// <param name="page">The page.</param>
  235. public static void OpenDashboardPage(string page, User loggedInUser)
  236. {
  237. var url = "http://localhost:" + Controller.Kernel.Instance.Configuration.HttpServerPortNumber + "/" +
  238. Controller.Kernel.Instance.WebApplicationName + "/dashboard/" + page;
  239. if (loggedInUser != null)
  240. {
  241. url = AddAutoLoginToDashboardUrl(url, loggedInUser);
  242. }
  243. OpenUrl(url);
  244. }
  245. /// <summary>
  246. /// Adds the auto login to dashboard URL.
  247. /// </summary>
  248. /// <param name="url">The URL.</param>
  249. /// <param name="user">The user.</param>
  250. /// <returns>System.String.</returns>
  251. public static string AddAutoLoginToDashboardUrl(string url, User user)
  252. {
  253. if (url.IndexOf('?') == -1)
  254. {
  255. url += "?u=" + user.Id;
  256. }
  257. else
  258. {
  259. url += "&u=" + user.Id;
  260. }
  261. return url;
  262. }
  263. /// <summary>
  264. /// Opens the URL.
  265. /// </summary>
  266. /// <param name="url">The URL.</param>
  267. public static void OpenUrl(string url)
  268. {
  269. var process = new Process
  270. {
  271. StartInfo = new ProcessStartInfo
  272. {
  273. FileName = url
  274. },
  275. EnableRaisingEvents = true
  276. };
  277. process.Exited += ProcessExited;
  278. process.Start();
  279. }
  280. /// <summary>
  281. /// Processes the exited.
  282. /// </summary>
  283. /// <param name="sender">The sender.</param>
  284. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  285. static void ProcessExited(object sender, EventArgs e)
  286. {
  287. ((Process)sender).Dispose();
  288. }
  289. /// <summary>
  290. /// Restarts this instance.
  291. /// </summary>
  292. /// <exception cref="System.NotImplementedException"></exception>
  293. public void Restart()
  294. {
  295. Dispatcher.Invoke(ReleaseMutex);
  296. CompositionRoot.Dispose();
  297. System.Windows.Forms.Application.Restart();
  298. Dispatcher.Invoke(Shutdown);
  299. }
  300. /// <summary>
  301. /// Gets the image.
  302. /// </summary>
  303. /// <param name="uri">The URI.</param>
  304. /// <returns>Image.</returns>
  305. /// <exception cref="System.ArgumentNullException">uri</exception>
  306. public Image GetImage(string uri)
  307. {
  308. if (string.IsNullOrEmpty(uri))
  309. {
  310. throw new ArgumentNullException("uri");
  311. }
  312. return GetImage(new Uri(uri));
  313. }
  314. /// <summary>
  315. /// Gets the image.
  316. /// </summary>
  317. /// <param name="uri">The URI.</param>
  318. /// <returns>Image.</returns>
  319. /// <exception cref="System.ArgumentNullException">uri</exception>
  320. public Image GetImage(Uri uri)
  321. {
  322. if (uri == null)
  323. {
  324. throw new ArgumentNullException("uri");
  325. }
  326. return new Image { Source = GetBitmapImage(uri) };
  327. }
  328. /// <summary>
  329. /// Gets the bitmap image.
  330. /// </summary>
  331. /// <param name="uri">The URI.</param>
  332. /// <returns>BitmapImage.</returns>
  333. /// <exception cref="System.ArgumentNullException">uri</exception>
  334. public BitmapImage GetBitmapImage(string uri)
  335. {
  336. if (string.IsNullOrEmpty(uri))
  337. {
  338. throw new ArgumentNullException("uri");
  339. }
  340. return GetBitmapImage(new Uri(uri));
  341. }
  342. /// <summary>
  343. /// Gets the bitmap image.
  344. /// </summary>
  345. /// <param name="uri">The URI.</param>
  346. /// <returns>BitmapImage.</returns>
  347. /// <exception cref="System.ArgumentNullException">uri</exception>
  348. public BitmapImage GetBitmapImage(Uri uri)
  349. {
  350. if (uri == null)
  351. {
  352. throw new ArgumentNullException("uri");
  353. }
  354. var bitmap = new BitmapImage
  355. {
  356. CreateOptions = BitmapCreateOptions.DelayCreation,
  357. CacheOption = BitmapCacheOption.OnDemand,
  358. UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable)
  359. };
  360. bitmap.BeginInit();
  361. bitmap.UriSource = uri;
  362. bitmap.EndInit();
  363. RenderOptions.SetBitmapScalingMode(bitmap, BitmapScalingMode.Fant);
  364. return bitmap;
  365. }
  366. }
  367. }