App.xaml.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. using MediaBrowser.ClickOnce;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Kernel;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.IsoMounter;
  6. using MediaBrowser.Logging.Nlog;
  7. using MediaBrowser.Model.IO;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.MediaInfo;
  10. using MediaBrowser.Model.Updates;
  11. using MediaBrowser.Server.Uninstall;
  12. using MediaBrowser.ServerApplication.Implementations;
  13. using Microsoft.Win32;
  14. using SimpleInjector;
  15. using System;
  16. using System.Diagnostics;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Net.Cache;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using System.Windows;
  23. using System.Windows.Controls;
  24. using System.Windows.Media;
  25. using System.Windows.Media.Imaging;
  26. namespace MediaBrowser.ServerApplication
  27. {
  28. /// <summary>
  29. /// Interaction logic for App.xaml
  30. /// </summary>
  31. public partial class App : Application, IApplicationHost
  32. {
  33. /// <summary>
  34. /// Defines the entry point of the application.
  35. /// </summary>
  36. [STAThread]
  37. public static void Main()
  38. {
  39. var application = new App(new NLogger("App"));
  40. application.Run();
  41. }
  42. /// <summary>
  43. /// Gets the instance.
  44. /// </summary>
  45. /// <value>The instance.</value>
  46. public static App Instance
  47. {
  48. get
  49. {
  50. return Current as App;
  51. }
  52. }
  53. /// <summary>
  54. /// The single instance mutex
  55. /// </summary>
  56. private Mutex SingleInstanceMutex;
  57. /// <summary>
  58. /// Gets or sets the kernel.
  59. /// </summary>
  60. /// <value>The kernel.</value>
  61. protected IKernel Kernel { get; set; }
  62. /// <summary>
  63. /// Gets or sets the logger.
  64. /// </summary>
  65. /// <value>The logger.</value>
  66. protected ILogger Logger { get; set; }
  67. /// <summary>
  68. /// Gets or sets the log file path.
  69. /// </summary>
  70. /// <value>The log file path.</value>
  71. public string LogFilePath { get; private set; }
  72. /// <summary>
  73. /// The container
  74. /// </summary>
  75. private Container _container = new Container();
  76. /// <summary>
  77. /// Initializes a new instance of the <see cref="App" /> class.
  78. /// </summary>
  79. /// <param name="logger">The logger.</param>
  80. public App(ILogger logger)
  81. {
  82. Logger = logger;
  83. InitializeComponent();
  84. }
  85. /// <summary>
  86. /// Gets the name of the product.
  87. /// </summary>
  88. /// <value>The name of the product.</value>
  89. protected string ProductName
  90. {
  91. get { return Globals.ProductName; }
  92. }
  93. /// <summary>
  94. /// Gets the name of the publisher.
  95. /// </summary>
  96. /// <value>The name of the publisher.</value>
  97. protected string PublisherName
  98. {
  99. get { return Globals.PublisherName; }
  100. }
  101. /// <summary>
  102. /// Gets the name of the suite.
  103. /// </summary>
  104. /// <value>The name of the suite.</value>
  105. protected string SuiteName
  106. {
  107. get { return Globals.SuiteName; }
  108. }
  109. /// <summary>
  110. /// Gets the name of the uninstaller file.
  111. /// </summary>
  112. /// <value>The name of the uninstaller file.</value>
  113. protected string UninstallerFileName
  114. {
  115. get { return "MediaBrowser.Server.Uninstall.exe"; }
  116. }
  117. /// <summary>
  118. /// Gets or sets the iso manager.
  119. /// </summary>
  120. /// <value>The iso manager.</value>
  121. private IIsoManager IsoManager { get; set; }
  122. /// <summary>
  123. /// Gets or sets a value indicating whether [last run at startup value].
  124. /// </summary>
  125. /// <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>
  126. private bool? LastRunAtStartupValue { get; set; }
  127. /// <summary>
  128. /// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
  129. /// </summary>
  130. /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
  131. protected override void OnStartup(StartupEventArgs e)
  132. {
  133. bool createdNew;
  134. SingleInstanceMutex = new Mutex(true, @"Local\" + GetType().Assembly.GetName().Name, out createdNew);
  135. if (!createdNew)
  136. {
  137. SingleInstanceMutex = null;
  138. Shutdown();
  139. return;
  140. }
  141. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  142. LoadKernel();
  143. SystemEvents.SessionEnding += SystemEvents_SessionEnding;
  144. }
  145. /// <summary>
  146. /// Handles the UnhandledException event of the CurrentDomain control.
  147. /// </summary>
  148. /// <param name="sender">The source of the event.</param>
  149. /// <param name="e">The <see cref="UnhandledExceptionEventArgs" /> instance containing the event data.</param>
  150. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  151. {
  152. var exception = (Exception)e.ExceptionObject;
  153. Logger.ErrorException("UnhandledException", exception);
  154. MessageBox.Show("Unhandled exception: " + exception.Message);
  155. }
  156. /// <summary>
  157. /// Handles the SessionEnding event of the SystemEvents control.
  158. /// </summary>
  159. /// <param name="sender">The source of the event.</param>
  160. /// <param name="e">The <see cref="SessionEndingEventArgs" /> instance containing the event data.</param>
  161. void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
  162. {
  163. // Try to shut down gracefully
  164. Shutdown();
  165. }
  166. /// <summary>
  167. /// Loads the kernel.
  168. /// </summary>
  169. protected async void LoadKernel()
  170. {
  171. RegisterResources();
  172. Kernel = new Kernel(this, Logger);
  173. try
  174. {
  175. new MainWindow(Logger).Show();
  176. var now = DateTime.UtcNow;
  177. await Kernel.Init();
  178. var done = (DateTime.UtcNow - now);
  179. Logger.Info("Kernel.Init completed in {0}{1} minutes and {2} seconds.", done.Hours > 0 ? done.Hours + " Hours " : "", done.Minutes, done.Seconds);
  180. await OnKernelLoaded();
  181. }
  182. catch (Exception ex)
  183. {
  184. Logger.ErrorException("Error launching application", ex);
  185. MessageBox.Show("There was an error launching Media Browser: " + ex.Message);
  186. // Shutdown the app with an error code
  187. Shutdown(1);
  188. }
  189. }
  190. /// <summary>
  191. /// Called when [kernel loaded].
  192. /// </summary>
  193. /// <returns>Task.</returns>
  194. protected Task OnKernelLoaded()
  195. {
  196. return Task.Run(() =>
  197. {
  198. Kernel.ConfigurationUpdated += Kernel_ConfigurationUpdated;
  199. ConfigureClickOnceStartup();
  200. });
  201. }
  202. /// <summary>
  203. /// Handles the ConfigurationUpdated event of the Kernel control.
  204. /// </summary>
  205. /// <param name="sender">The source of the event.</param>
  206. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  207. void Kernel_ConfigurationUpdated(object sender, EventArgs e)
  208. {
  209. if (!LastRunAtStartupValue.HasValue || LastRunAtStartupValue.Value != Kernel.Configuration.RunAtStartup)
  210. {
  211. ConfigureClickOnceStartup();
  212. }
  213. }
  214. /// <summary>
  215. /// Configures the click once startup.
  216. /// </summary>
  217. private void ConfigureClickOnceStartup()
  218. {
  219. try
  220. {
  221. ClickOnceHelper.ConfigureClickOnceStartupIfInstalled(PublisherName, ProductName, SuiteName, Kernel.Configuration.RunAtStartup, UninstallerFileName);
  222. LastRunAtStartupValue = Kernel.Configuration.RunAtStartup;
  223. }
  224. catch (Exception ex)
  225. {
  226. Logger.ErrorException("Error configuring ClickOnce", ex);
  227. }
  228. }
  229. /// <summary>
  230. /// Raises the <see cref="E:System.Windows.Application.Exit" /> event.
  231. /// </summary>
  232. /// <param name="e">An <see cref="T:System.Windows.ExitEventArgs" /> that contains the event data.</param>
  233. protected override void OnExit(ExitEventArgs e)
  234. {
  235. ReleaseMutex();
  236. base.OnExit(e);
  237. Kernel.Dispose();
  238. }
  239. /// <summary>
  240. /// Releases the mutex.
  241. /// </summary>
  242. private void ReleaseMutex()
  243. {
  244. if (SingleInstanceMutex == null)
  245. {
  246. return;
  247. }
  248. SingleInstanceMutex.ReleaseMutex();
  249. SingleInstanceMutex.Close();
  250. SingleInstanceMutex.Dispose();
  251. SingleInstanceMutex = null;
  252. }
  253. /// <summary>
  254. /// Opens the dashboard.
  255. /// </summary>
  256. public static void OpenDashboard()
  257. {
  258. OpenDashboardPage("dashboard.html");
  259. }
  260. /// <summary>
  261. /// Opens the dashboard page.
  262. /// </summary>
  263. /// <param name="page">The page.</param>
  264. public static void OpenDashboardPage(string page)
  265. {
  266. var url = "http://localhost:" + Controller.Kernel.Instance.Configuration.HttpServerPortNumber + "/" +
  267. Controller.Kernel.Instance.WebApplicationName + "/dashboard/" + page;
  268. url = AddAutoLoginToDashboardUrl(url);
  269. OpenUrl(url);
  270. }
  271. /// <summary>
  272. /// Adds the auto login to dashboard URL.
  273. /// </summary>
  274. /// <param name="url">The URL.</param>
  275. /// <returns>System.String.</returns>
  276. public static string AddAutoLoginToDashboardUrl(string url)
  277. {
  278. var user = Controller.Kernel.Instance.Users.FirstOrDefault(u => u.Configuration.IsAdministrator);
  279. if (user != null)
  280. {
  281. if (url.IndexOf('?') == -1)
  282. {
  283. url += "?u=" + user.Id;
  284. }
  285. else
  286. {
  287. url += "&u=" + user.Id;
  288. }
  289. }
  290. return url;
  291. }
  292. /// <summary>
  293. /// Opens the URL.
  294. /// </summary>
  295. /// <param name="url">The URL.</param>
  296. public static void OpenUrl(string url)
  297. {
  298. var process = new Process
  299. {
  300. StartInfo = new ProcessStartInfo
  301. {
  302. FileName = url
  303. },
  304. EnableRaisingEvents = true
  305. };
  306. process.Exited += ProcessExited;
  307. process.Start();
  308. }
  309. /// <summary>
  310. /// Processes the exited.
  311. /// </summary>
  312. /// <param name="sender">The sender.</param>
  313. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  314. static void ProcessExited(object sender, EventArgs e)
  315. {
  316. ((Process)sender).Dispose();
  317. }
  318. /// <summary>
  319. /// Restarts this instance.
  320. /// </summary>
  321. /// <exception cref="System.NotImplementedException"></exception>
  322. public void Restart()
  323. {
  324. Dispatcher.Invoke(ReleaseMutex);
  325. Kernel.Dispose();
  326. System.Windows.Forms.Application.Restart();
  327. Dispatcher.Invoke(Shutdown);
  328. }
  329. /// <summary>
  330. /// Reloads the logger.
  331. /// </summary>
  332. /// <exception cref="System.NotImplementedException"></exception>
  333. public void ReloadLogger()
  334. {
  335. LogFilePath = Path.Combine(Kernel.ApplicationPaths.LogDirectoryPath, "Server-" + DateTime.Now.Ticks + ".log");
  336. NlogManager.AddFileTarget(LogFilePath, Kernel.Configuration.EnableDebugLevelLogging);
  337. }
  338. /// <summary>
  339. /// Gets the image.
  340. /// </summary>
  341. /// <param name="uri">The URI.</param>
  342. /// <returns>Image.</returns>
  343. /// <exception cref="System.ArgumentNullException">uri</exception>
  344. public Image GetImage(string uri)
  345. {
  346. if (string.IsNullOrEmpty(uri))
  347. {
  348. throw new ArgumentNullException("uri");
  349. }
  350. return GetImage(new Uri(uri));
  351. }
  352. /// <summary>
  353. /// Gets the image.
  354. /// </summary>
  355. /// <param name="uri">The URI.</param>
  356. /// <returns>Image.</returns>
  357. /// <exception cref="System.ArgumentNullException">uri</exception>
  358. public Image GetImage(Uri uri)
  359. {
  360. if (uri == null)
  361. {
  362. throw new ArgumentNullException("uri");
  363. }
  364. return new Image { Source = GetBitmapImage(uri) };
  365. }
  366. /// <summary>
  367. /// Gets the bitmap image.
  368. /// </summary>
  369. /// <param name="uri">The URI.</param>
  370. /// <returns>BitmapImage.</returns>
  371. /// <exception cref="System.ArgumentNullException">uri</exception>
  372. public BitmapImage GetBitmapImage(string uri)
  373. {
  374. if (string.IsNullOrEmpty(uri))
  375. {
  376. throw new ArgumentNullException("uri");
  377. }
  378. return GetBitmapImage(new Uri(uri));
  379. }
  380. /// <summary>
  381. /// Gets the bitmap image.
  382. /// </summary>
  383. /// <param name="uri">The URI.</param>
  384. /// <returns>BitmapImage.</returns>
  385. /// <exception cref="System.ArgumentNullException">uri</exception>
  386. public BitmapImage GetBitmapImage(Uri uri)
  387. {
  388. if (uri == null)
  389. {
  390. throw new ArgumentNullException("uri");
  391. }
  392. var bitmap = new BitmapImage
  393. {
  394. CreateOptions = BitmapCreateOptions.DelayCreation,
  395. CacheOption = BitmapCacheOption.OnDemand,
  396. UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable)
  397. };
  398. bitmap.BeginInit();
  399. bitmap.UriSource = uri;
  400. bitmap.EndInit();
  401. RenderOptions.SetBitmapScalingMode(bitmap, BitmapScalingMode.Fant);
  402. return bitmap;
  403. }
  404. /// <summary>
  405. /// Gets or sets a value indicating whether this instance can self update.
  406. /// </summary>
  407. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  408. public bool CanSelfUpdate
  409. {
  410. get { return ClickOnceHelper.IsNetworkDeployed; }
  411. }
  412. /// <summary>
  413. /// Checks for update.
  414. /// </summary>
  415. /// <param name="cancellationToken">The cancellation token.</param>
  416. /// <param name="progress">The progress.</param>
  417. /// <returns>Task{CheckForUpdateResult}.</returns>
  418. public Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  419. {
  420. return new ApplicationUpdateCheck().CheckForApplicationUpdate(cancellationToken, progress);
  421. }
  422. /// <summary>
  423. /// Updates the application.
  424. /// </summary>
  425. /// <param name="cancellationToken">The cancellation token.</param>
  426. /// <param name="progress">The progress.</param>
  427. /// <returns>Task.</returns>
  428. public Task UpdateApplication(CancellationToken cancellationToken, IProgress<double> progress)
  429. {
  430. return new ApplicationUpdater().UpdateApplication(cancellationToken, progress);
  431. }
  432. /// <summary>
  433. /// Registers resources that classes will depend on
  434. /// </summary>
  435. private void RegisterResources()
  436. {
  437. Register<IApplicationHost>(this);
  438. Register(Logger);
  439. IsoManager = new PismoIsoManager(Logger);
  440. Register<IIsoManager>(IsoManager);
  441. Register<IBlurayExaminer>(new BdInfoExaminer());
  442. Register<IZipClient>(new DotNetZipClient());
  443. }
  444. /// <summary>
  445. /// Creates an instance of type and resolves all constructor dependancies
  446. /// </summary>
  447. /// <param name="type">The type.</param>
  448. /// <returns>System.Object.</returns>
  449. public object CreateInstance(Type type)
  450. {
  451. try
  452. {
  453. return _container.GetInstance(type);
  454. }
  455. catch
  456. {
  457. Logger.Error("Error creating {0}", type.Name);
  458. throw;
  459. }
  460. }
  461. /// <summary>
  462. /// Registers the specified obj.
  463. /// </summary>
  464. /// <typeparam name="T"></typeparam>
  465. /// <param name="obj">The obj.</param>
  466. public void Register<T>(T obj)
  467. where T : class
  468. {
  469. _container.RegisterSingle(obj);
  470. }
  471. /// <summary>
  472. /// Resolves this instance.
  473. /// </summary>
  474. /// <typeparam name="T"></typeparam>
  475. /// <returns>``0.</returns>
  476. public T Resolve<T>()
  477. {
  478. return (T)_container.GetRegistration(typeof (T), true).GetInstance();
  479. }
  480. /// <summary>
  481. /// Resolves this instance.
  482. /// </summary>
  483. /// <typeparam name="T"></typeparam>
  484. /// <returns>``0.</returns>
  485. public T TryResolve<T>()
  486. {
  487. var result = _container.GetRegistration(typeof (T), false);
  488. if (result == null)
  489. {
  490. return default(T);
  491. }
  492. return (T)result.GetInstance();
  493. }
  494. }
  495. }