2
0

App.xaml.cs 13 KB

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