App.xaml.cs 17 KB

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