2
0

App.xaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. using MediaBrowser.ClickOnce;
  2. using MediaBrowser.Common.Kernel;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Server.Uninstall;
  6. using Microsoft.Win32;
  7. using System;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Net.Cache;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. using System.Windows.Controls;
  15. using System.Windows.Media;
  16. using System.Windows.Media.Imaging;
  17. namespace MediaBrowser.ServerApplication
  18. {
  19. /// <summary>
  20. /// Interaction logic for App.xaml
  21. /// </summary>
  22. public partial class App : Application
  23. {
  24. /// <summary>
  25. /// Defines the entry point of the application.
  26. /// </summary>
  27. [STAThread]
  28. public static void Main()
  29. {
  30. var application = new App();
  31. application.Run();
  32. }
  33. /// <summary>
  34. /// Gets the instance.
  35. /// </summary>
  36. /// <value>The instance.</value>
  37. public static App Instance
  38. {
  39. get
  40. {
  41. return Current as App;
  42. }
  43. }
  44. /// <summary>
  45. /// The single instance mutex
  46. /// </summary>
  47. private Mutex SingleInstanceMutex;
  48. /// <summary>
  49. /// Gets or sets the kernel.
  50. /// </summary>
  51. /// <value>The kernel.</value>
  52. protected IKernel Kernel { get; set; }
  53. /// <summary>
  54. /// Gets or sets the logger.
  55. /// </summary>
  56. /// <value>The logger.</value>
  57. protected ILogger Logger { get; set; }
  58. /// <summary>
  59. /// Gets or sets the composition root.
  60. /// </summary>
  61. /// <value>The composition root.</value>
  62. protected ApplicationHost CompositionRoot { get; set; }
  63. /// <summary>
  64. /// Initializes a new instance of the <see cref="App" /> class.
  65. /// </summary>
  66. /// <param name="logger">The logger.</param>
  67. public App()
  68. {
  69. InitializeComponent();
  70. }
  71. /// <summary>
  72. /// Gets the name of the product.
  73. /// </summary>
  74. /// <value>The name of the product.</value>
  75. protected string ProductName
  76. {
  77. get { return Globals.ProductName; }
  78. }
  79. /// <summary>
  80. /// Gets the name of the publisher.
  81. /// </summary>
  82. /// <value>The name of the publisher.</value>
  83. protected string PublisherName
  84. {
  85. get { return Globals.PublisherName; }
  86. }
  87. /// <summary>
  88. /// Gets the name of the suite.
  89. /// </summary>
  90. /// <value>The name of the suite.</value>
  91. protected string SuiteName
  92. {
  93. get { return Globals.SuiteName; }
  94. }
  95. /// <summary>
  96. /// Gets the name of the uninstaller file.
  97. /// </summary>
  98. /// <value>The name of the uninstaller file.</value>
  99. protected string UninstallerFileName
  100. {
  101. get { return "MediaBrowser.Server.Uninstall.exe"; }
  102. }
  103. /// <summary>
  104. /// Gets or sets a value indicating whether [last run at startup value].
  105. /// </summary>
  106. /// <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>
  107. private bool? LastRunAtStartupValue { get; set; }
  108. /// <summary>
  109. /// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
  110. /// </summary>
  111. /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
  112. protected override void OnStartup(StartupEventArgs e)
  113. {
  114. bool createdNew;
  115. SingleInstanceMutex = new Mutex(true, @"Local\" + GetType().Assembly.GetName().Name, out createdNew);
  116. if (!createdNew)
  117. {
  118. SingleInstanceMutex = null;
  119. Shutdown();
  120. return;
  121. }
  122. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  123. LoadKernel();
  124. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  125. }
  126. /// <summary>
  127. /// Handles the UnhandledException event of the CurrentDomain control.
  128. /// </summary>
  129. /// <param name="sender">The source of the event.</param>
  130. /// <param name="e">The <see cref="UnhandledExceptionEventArgs" /> instance containing the event data.</param>
  131. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  132. {
  133. var exception = (Exception)e.ExceptionObject;
  134. Logger.ErrorException("UnhandledException", exception);
  135. MessageBox.Show("Unhandled exception: " + exception.Message);
  136. }
  137. /// <summary>
  138. /// Handles the SessionEnding event of the SystemEvents control.
  139. /// </summary>
  140. /// <param name="sender">The source of the event.</param>
  141. /// <param name="e">The <see cref="SessionEndingEventArgs" /> instance containing the event data.</param>
  142. void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  143. {
  144. // Try to shut down gracefully
  145. Shutdown();
  146. }
  147. /// <summary>
  148. /// Loads the kernel.
  149. /// </summary>
  150. protected async void LoadKernel()
  151. {
  152. CompositionRoot = new ApplicationHost();
  153. Logger = CompositionRoot.Logger;
  154. Kernel = CompositionRoot.Kernel;
  155. try
  156. {
  157. var win = (MainWindow)CompositionRoot.CreateInstance(typeof(MainWindow));
  158. win.Show();
  159. var now = DateTime.UtcNow;
  160. await Kernel.Init();
  161. var done = (DateTime.UtcNow - now);
  162. Logger.Info("Kernel.Init completed in {0}{1} minutes and {2} seconds.", done.Hours > 0 ? done.Hours + " Hours " : "", done.Minutes, done.Seconds);
  163. await OnKernelLoaded();
  164. }
  165. catch (Exception ex)
  166. {
  167. Logger.ErrorException("Error launching application", ex);
  168. MessageBox.Show("There was an error launching Media Browser: " + ex.Message);
  169. // Shutdown the app with an error code
  170. Shutdown(1);
  171. }
  172. }
  173. /// <summary>
  174. /// Called when [kernel loaded].
  175. /// </summary>
  176. /// <returns>Task.</returns>
  177. protected Task OnKernelLoaded()
  178. {
  179. return Task.Run(() =>
  180. {
  181. Kernel.ConfigurationUpdated += Kernel_ConfigurationUpdated;
  182. ConfigureClickOnceStartup();
  183. });
  184. }
  185. /// <summary>
  186. /// Handles the ConfigurationUpdated event of the Kernel control.
  187. /// </summary>
  188. /// <param name="sender">The source of the event.</param>
  189. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  190. void Kernel_ConfigurationUpdated(object sender, EventArgs e)
  191. {
  192. if (!LastRunAtStartupValue.HasValue || LastRunAtStartupValue.Value != Kernel.Configuration.RunAtStartup)
  193. {
  194. ConfigureClickOnceStartup();
  195. }
  196. }
  197. /// <summary>
  198. /// Configures the click once startup.
  199. /// </summary>
  200. private void ConfigureClickOnceStartup()
  201. {
  202. try
  203. {
  204. ClickOnceHelper.ConfigureClickOnceStartupIfInstalled(PublisherName, ProductName, SuiteName, Kernel.Configuration.RunAtStartup, UninstallerFileName);
  205. LastRunAtStartupValue = Kernel.Configuration.RunAtStartup;
  206. }
  207. catch (Exception ex)
  208. {
  209. Logger.ErrorException("Error configuring ClickOnce", ex);
  210. }
  211. }
  212. /// <summary>
  213. /// Raises the <see cref="E:System.Windows.Application.Exit" /> event.
  214. /// </summary>
  215. /// <param name="e">An <see cref="T:System.Windows.ExitEventArgs" /> that contains the event data.</param>
  216. protected override void OnExit(ExitEventArgs e)
  217. {
  218. ReleaseMutex();
  219. base.OnExit(e);
  220. Kernel.Dispose();
  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()
  241. {
  242. OpenDashboardPage("dashboard.html");
  243. }
  244. /// <summary>
  245. /// Opens the dashboard page.
  246. /// </summary>
  247. /// <param name="page">The page.</param>
  248. public static void OpenDashboardPage(string page)
  249. {
  250. var url = "http://localhost:" + Controller.Kernel.Instance.Configuration.HttpServerPortNumber + "/" +
  251. Controller.Kernel.Instance.WebApplicationName + "/dashboard/" + page;
  252. url = AddAutoLoginToDashboardUrl(url);
  253. OpenUrl(url);
  254. }
  255. /// <summary>
  256. /// Adds the auto login to dashboard URL.
  257. /// </summary>
  258. /// <param name="url">The URL.</param>
  259. /// <returns>System.String.</returns>
  260. public static string AddAutoLoginToDashboardUrl(string url)
  261. {
  262. var user = Controller.Kernel.Instance.Users.FirstOrDefault(u => u.Configuration.IsAdministrator);
  263. if (user != null)
  264. {
  265. if (url.IndexOf('?') == -1)
  266. {
  267. url += "?u=" + user.Id;
  268. }
  269. else
  270. {
  271. url += "&u=" + user.Id;
  272. }
  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. Kernel.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. }