App.xaml.cs 15 KB

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