ApplicationHost.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. using MediaBrowser.Api;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Configuration;
  4. using MediaBrowser.Common.Events;
  5. using MediaBrowser.Common.Extensions;
  6. using MediaBrowser.Common.Implementations;
  7. using MediaBrowser.Common.Implementations.ScheduledTasks;
  8. using MediaBrowser.Common.IO;
  9. using MediaBrowser.Common.Net;
  10. using MediaBrowser.Common.Progress;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Activity;
  13. using MediaBrowser.Controller.Channels;
  14. using MediaBrowser.Controller.Chapters;
  15. using MediaBrowser.Controller.Collections;
  16. using MediaBrowser.Controller.Configuration;
  17. using MediaBrowser.Controller.Dlna;
  18. using MediaBrowser.Controller.Drawing;
  19. using MediaBrowser.Controller.Dto;
  20. using MediaBrowser.Controller.Entities;
  21. using MediaBrowser.Controller.FileOrganization;
  22. using MediaBrowser.Controller.Library;
  23. using MediaBrowser.Controller.LiveTv;
  24. using MediaBrowser.Controller.Localization;
  25. using MediaBrowser.Controller.MediaEncoding;
  26. using MediaBrowser.Controller.Net;
  27. using MediaBrowser.Controller.News;
  28. using MediaBrowser.Controller.Notifications;
  29. using MediaBrowser.Controller.Persistence;
  30. using MediaBrowser.Controller.Playlists;
  31. using MediaBrowser.Controller.Plugins;
  32. using MediaBrowser.Controller.Providers;
  33. using MediaBrowser.Controller.Resolvers;
  34. using MediaBrowser.Controller.Security;
  35. using MediaBrowser.Controller.Session;
  36. using MediaBrowser.Controller.Sorting;
  37. using MediaBrowser.Controller.Subtitles;
  38. using MediaBrowser.Controller.Sync;
  39. using MediaBrowser.Controller.Themes;
  40. using MediaBrowser.Dlna;
  41. using MediaBrowser.Dlna.ConnectionManager;
  42. using MediaBrowser.Dlna.ContentDirectory;
  43. using MediaBrowser.Dlna.Main;
  44. using MediaBrowser.LocalMetadata.Providers;
  45. using MediaBrowser.MediaEncoding.BdInfo;
  46. using MediaBrowser.MediaEncoding.Encoder;
  47. using MediaBrowser.MediaEncoding.Subtitles;
  48. using MediaBrowser.Model.FileOrganization;
  49. using MediaBrowser.Model.Logging;
  50. using MediaBrowser.Model.MediaInfo;
  51. using MediaBrowser.Model.System;
  52. using MediaBrowser.Model.Updates;
  53. using MediaBrowser.Providers.Chapters;
  54. using MediaBrowser.Providers.Manager;
  55. using MediaBrowser.Providers.Subtitles;
  56. using MediaBrowser.Server.Implementations;
  57. using MediaBrowser.Server.Implementations.Activity;
  58. using MediaBrowser.Server.Implementations.Channels;
  59. using MediaBrowser.Server.Implementations.Collections;
  60. using MediaBrowser.Server.Implementations.Configuration;
  61. using MediaBrowser.Server.Implementations.Drawing;
  62. using MediaBrowser.Server.Implementations.Dto;
  63. using MediaBrowser.Server.Implementations.EntryPoints;
  64. using MediaBrowser.Server.Implementations.FileOrganization;
  65. using MediaBrowser.Server.Implementations.HttpServer;
  66. using MediaBrowser.Server.Implementations.HttpServer.Security;
  67. using MediaBrowser.Server.Implementations.IO;
  68. using MediaBrowser.Server.Implementations.Library;
  69. using MediaBrowser.Server.Implementations.LiveTv;
  70. using MediaBrowser.Server.Implementations.Localization;
  71. using MediaBrowser.Server.Implementations.MediaEncoder;
  72. using MediaBrowser.Server.Implementations.Notifications;
  73. using MediaBrowser.Server.Implementations.Persistence;
  74. using MediaBrowser.Server.Implementations.Playlists;
  75. using MediaBrowser.Server.Implementations.Security;
  76. using MediaBrowser.Server.Implementations.ServerManager;
  77. using MediaBrowser.Server.Implementations.Session;
  78. using MediaBrowser.Server.Implementations.Sync;
  79. using MediaBrowser.Server.Implementations.Themes;
  80. using MediaBrowser.ServerApplication.EntryPoints;
  81. using MediaBrowser.ServerApplication.FFMpeg;
  82. using MediaBrowser.ServerApplication.IO;
  83. using MediaBrowser.ServerApplication.Native;
  84. using MediaBrowser.ServerApplication.Networking;
  85. using MediaBrowser.WebDashboard.Api;
  86. using MediaBrowser.XbmcMetadata.Providers;
  87. using System;
  88. using System.Collections.Generic;
  89. using System.Globalization;
  90. using System.IO;
  91. using System.Linq;
  92. using System.Reflection;
  93. using System.Threading;
  94. using System.Threading.Tasks;
  95. namespace MediaBrowser.ServerApplication
  96. {
  97. /// <summary>
  98. /// Class CompositionRoot
  99. /// </summary>
  100. public class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost
  101. {
  102. /// <summary>
  103. /// Gets the server configuration manager.
  104. /// </summary>
  105. /// <value>The server configuration manager.</value>
  106. public IServerConfigurationManager ServerConfigurationManager
  107. {
  108. get { return (IServerConfigurationManager)ConfigurationManager; }
  109. }
  110. /// <summary>
  111. /// Gets the name of the web application that can be used for url building.
  112. /// All api urls will be of the form {protocol}://{host}:{port}/{appname}/...
  113. /// </summary>
  114. /// <value>The name of the web application.</value>
  115. public string WebApplicationName
  116. {
  117. get { return "mediabrowser"; }
  118. }
  119. /// <summary>
  120. /// Gets the HTTP server URL prefix.
  121. /// </summary>
  122. /// <value>The HTTP server URL prefix.</value>
  123. private IEnumerable<string> HttpServerUrlPrefixes
  124. {
  125. get
  126. {
  127. var list = new List<string>
  128. {
  129. "http://+:" + ServerConfigurationManager.Configuration.HttpServerPortNumber + "/" + WebApplicationName + "/"
  130. };
  131. return list;
  132. }
  133. }
  134. /// <summary>
  135. /// Gets the configuration manager.
  136. /// </summary>
  137. /// <returns>IConfigurationManager.</returns>
  138. protected override IConfigurationManager GetConfigurationManager()
  139. {
  140. return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer);
  141. }
  142. /// <summary>
  143. /// Gets or sets the server manager.
  144. /// </summary>
  145. /// <value>The server manager.</value>
  146. private IServerManager ServerManager { get; set; }
  147. /// <summary>
  148. /// Gets or sets the user manager.
  149. /// </summary>
  150. /// <value>The user manager.</value>
  151. public IUserManager UserManager { get; set; }
  152. /// <summary>
  153. /// Gets or sets the library manager.
  154. /// </summary>
  155. /// <value>The library manager.</value>
  156. internal ILibraryManager LibraryManager { get; set; }
  157. /// <summary>
  158. /// Gets or sets the directory watchers.
  159. /// </summary>
  160. /// <value>The directory watchers.</value>
  161. private ILibraryMonitor LibraryMonitor { get; set; }
  162. /// <summary>
  163. /// Gets or sets the provider manager.
  164. /// </summary>
  165. /// <value>The provider manager.</value>
  166. private IProviderManager ProviderManager { get; set; }
  167. /// <summary>
  168. /// Gets or sets the HTTP server.
  169. /// </summary>
  170. /// <value>The HTTP server.</value>
  171. private IHttpServer HttpServer { get; set; }
  172. private IDtoService DtoService { get; set; }
  173. private IImageProcessor ImageProcessor { get; set; }
  174. private ISeriesOrderManager SeriesOrderManager { get; set; }
  175. /// <summary>
  176. /// Gets or sets the media encoder.
  177. /// </summary>
  178. /// <value>The media encoder.</value>
  179. private IMediaEncoder MediaEncoder { get; set; }
  180. private ISessionManager SessionManager { get; set; }
  181. private ILiveTvManager LiveTvManager { get; set; }
  182. internal ILocalizationManager LocalizationManager { get; set; }
  183. private IEncodingManager EncodingManager { get; set; }
  184. private IChannelManager ChannelManager { get; set; }
  185. private ISyncManager SyncManager { get; set; }
  186. /// <summary>
  187. /// Gets or sets the user data repository.
  188. /// </summary>
  189. /// <value>The user data repository.</value>
  190. private IUserDataManager UserDataManager { get; set; }
  191. private IUserRepository UserRepository { get; set; }
  192. internal IDisplayPreferencesRepository DisplayPreferencesRepository { get; set; }
  193. internal IItemRepository ItemRepository { get; set; }
  194. private INotificationsRepository NotificationsRepository { get; set; }
  195. private IFileOrganizationRepository FileOrganizationRepository { get; set; }
  196. private IProviderRepository ProviderRepository { get; set; }
  197. private INotificationManager NotificationManager { get; set; }
  198. private ISubtitleManager SubtitleManager { get; set; }
  199. private IChapterManager ChapterManager { get; set; }
  200. private IUserViewManager UserViewManager { get; set; }
  201. private IAuthenticationRepository AuthenticationRepository { get; set; }
  202. private ISyncRepository SyncRepository { get; set; }
  203. /// <summary>
  204. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  205. /// </summary>
  206. /// <param name="applicationPaths">The application paths.</param>
  207. /// <param name="logManager">The log manager.</param>
  208. /// <param name="isRunningAsService">if set to <c>true</c> [is running as service].</param>
  209. public ApplicationHost(ServerApplicationPaths applicationPaths, ILogManager logManager, bool isRunningAsService)
  210. : base(applicationPaths, logManager)
  211. {
  212. _isRunningAsService = isRunningAsService;
  213. }
  214. private readonly bool _isRunningAsService;
  215. public override bool IsRunningAsService
  216. {
  217. get { return _isRunningAsService; }
  218. }
  219. /// <summary>
  220. /// Gets the name.
  221. /// </summary>
  222. /// <value>The name.</value>
  223. public override string Name
  224. {
  225. get
  226. {
  227. return "Media Browser Server";
  228. }
  229. }
  230. /// <summary>
  231. /// Gets a value indicating whether this instance can self restart.
  232. /// </summary>
  233. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  234. public override bool CanSelfRestart
  235. {
  236. get { return NativeApp.CanSelfRestart; }
  237. }
  238. public bool SupportsAutoRunAtStartup
  239. {
  240. get { return NativeApp.SupportsAutoRunAtStartup; }
  241. }
  242. /// <summary>
  243. /// Runs the startup tasks.
  244. /// </summary>
  245. /// <returns>Task.</returns>
  246. public override async Task RunStartupTasks()
  247. {
  248. await base.RunStartupTasks().ConfigureAwait(false);
  249. Logger.Info("Core startup complete");
  250. Parallel.ForEach(GetExports<IServerEntryPoint>(), entryPoint =>
  251. {
  252. try
  253. {
  254. entryPoint.Run();
  255. }
  256. catch (Exception ex)
  257. {
  258. Logger.ErrorException("Error in {0}", ex, entryPoint.GetType().Name);
  259. }
  260. });
  261. LogManager.RemoveConsoleOutput();
  262. }
  263. public override async Task Init(IProgress<double> progress)
  264. {
  265. PerformVersionMigration();
  266. await base.Init(progress).ConfigureAwait(false);
  267. MigrateModularConfigurations();
  268. }
  269. private void PerformVersionMigration()
  270. {
  271. DeleteDeprecatedModules();
  272. }
  273. private void MigrateModularConfigurations()
  274. {
  275. var saveConfig = false;
  276. if (ServerConfigurationManager.Configuration.DlnaOptions != null)
  277. {
  278. ServerConfigurationManager.SaveConfiguration("dlna", ServerConfigurationManager.Configuration.DlnaOptions);
  279. ServerConfigurationManager.Configuration.DlnaOptions = null;
  280. saveConfig = true;
  281. }
  282. if (ServerConfigurationManager.Configuration.ChapterOptions != null)
  283. {
  284. ServerConfigurationManager.SaveConfiguration("chapters", ServerConfigurationManager.Configuration.ChapterOptions);
  285. ServerConfigurationManager.Configuration.ChapterOptions = null;
  286. saveConfig = true;
  287. }
  288. if (ServerConfigurationManager.Configuration.ChannelOptions != null)
  289. {
  290. ServerConfigurationManager.SaveConfiguration("channels", ServerConfigurationManager.Configuration.ChannelOptions);
  291. ServerConfigurationManager.Configuration.ChannelOptions = null;
  292. saveConfig = true;
  293. }
  294. if (ServerConfigurationManager.Configuration.NotificationOptions != null)
  295. {
  296. ServerConfigurationManager.SaveConfiguration("notifications", ServerConfigurationManager.Configuration.NotificationOptions);
  297. ServerConfigurationManager.Configuration.NotificationOptions = null;
  298. saveConfig = true;
  299. }
  300. if (ServerConfigurationManager.Configuration.LiveTvOptions != null)
  301. {
  302. ServerConfigurationManager.SaveConfiguration("livetv", ServerConfigurationManager.Configuration.LiveTvOptions);
  303. ServerConfigurationManager.Configuration.LiveTvOptions = null;
  304. saveConfig = true;
  305. }
  306. if (ServerConfigurationManager.Configuration.TvFileOrganizationOptions != null)
  307. {
  308. ServerConfigurationManager.SaveConfiguration("autoorganize", new AutoOrganizeOptions { TvOptions = ServerConfigurationManager.Configuration.TvFileOrganizationOptions });
  309. ServerConfigurationManager.Configuration.TvFileOrganizationOptions = null;
  310. saveConfig = true;
  311. }
  312. if (ServerConfigurationManager.Configuration.SubtitleOptions != null)
  313. {
  314. ServerConfigurationManager.SaveConfiguration("subtitles", ServerConfigurationManager.Configuration.SubtitleOptions);
  315. ServerConfigurationManager.Configuration.SubtitleOptions = null;
  316. saveConfig = true;
  317. }
  318. if (saveConfig)
  319. {
  320. ServerConfigurationManager.SaveConfiguration();
  321. }
  322. }
  323. private void DeleteDeprecatedModules()
  324. {
  325. try
  326. {
  327. MigrateUserFolders();
  328. }
  329. catch (IOException)
  330. {
  331. }
  332. try
  333. {
  334. File.Delete(Path.Combine(ApplicationPaths.PluginsPath, "MBPhoto.dll"));
  335. }
  336. catch (IOException)
  337. {
  338. // Not there, no big deal
  339. }
  340. try
  341. {
  342. File.Delete(Path.Combine(ApplicationPaths.PluginsPath, "MediaBrowser.Plugins.XbmcMetadata.dll"));
  343. }
  344. catch (IOException)
  345. {
  346. // Not there, no big deal
  347. }
  348. Task.Run(() =>
  349. {
  350. try
  351. {
  352. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "remote-images"), true);
  353. }
  354. catch (IOException)
  355. {
  356. // Not there, no big deal
  357. }
  358. try
  359. {
  360. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "chapter-images"), true);
  361. }
  362. catch (IOException)
  363. {
  364. // Not there, no big deal
  365. }
  366. try
  367. {
  368. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "extracted-video-images"), true);
  369. }
  370. catch (IOException)
  371. {
  372. // Not there, no big deal
  373. }
  374. try
  375. {
  376. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "extracted-audio-images"), true);
  377. }
  378. catch (IOException)
  379. {
  380. // Not there, no big deal
  381. }
  382. try
  383. {
  384. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "tmdb-tv"), true);
  385. }
  386. catch (IOException)
  387. {
  388. // Not there, no big deal
  389. }
  390. try
  391. {
  392. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "tmdb-collections"), true);
  393. }
  394. catch (IOException)
  395. {
  396. // Not there, no big deal
  397. }
  398. try
  399. {
  400. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "tmdb-movies"), true);
  401. }
  402. catch (IOException)
  403. {
  404. // Not there, no big deal
  405. }
  406. try
  407. {
  408. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "fanart-movies"), true);
  409. }
  410. catch (IOException)
  411. {
  412. // Not there, no big deal
  413. }
  414. try
  415. {
  416. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "fanart-music"), true);
  417. }
  418. catch (IOException)
  419. {
  420. // Not there, no big deal
  421. }
  422. try
  423. {
  424. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "fanart-tv"), true);
  425. }
  426. catch (IOException)
  427. {
  428. // Not there, no big deal
  429. }
  430. try
  431. {
  432. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "tmdb-people"), true);
  433. }
  434. catch (IOException)
  435. {
  436. // Not there, no big deal
  437. }
  438. try
  439. {
  440. Directory.Delete(Path.Combine(ApplicationPaths.DataPath, "tvdb-v3"), true);
  441. }
  442. catch (IOException)
  443. {
  444. // Not there, no big deal
  445. }
  446. });
  447. }
  448. private void MigrateUserFolders()
  449. {
  450. var rootPath = ApplicationPaths.RootFolderPath;
  451. var folders = new DirectoryInfo(rootPath).EnumerateDirectories("*", SearchOption.TopDirectoryOnly).Where(i => !string.Equals(i.Name, "default", StringComparison.OrdinalIgnoreCase))
  452. .ToList();
  453. foreach (var folder in folders)
  454. {
  455. Directory.Delete(folder.FullName, true);
  456. }
  457. }
  458. /// <summary>
  459. /// Registers resources that classes will depend on
  460. /// </summary>
  461. /// <returns>Task.</returns>
  462. protected override async Task RegisterResources(IProgress<double> progress)
  463. {
  464. await base.RegisterResources(progress).ConfigureAwait(false);
  465. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer));
  466. RegisterSingleInstance<IServerApplicationHost>(this);
  467. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  468. RegisterSingleInstance(ServerConfigurationManager);
  469. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager, JsonSerializer);
  470. RegisterSingleInstance(LocalizationManager);
  471. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  472. UserDataManager = new UserDataManager(LogManager);
  473. RegisterSingleInstance(UserDataManager);
  474. UserRepository = await GetUserRepository().ConfigureAwait(false);
  475. RegisterSingleInstance(UserRepository);
  476. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  477. RegisterSingleInstance(DisplayPreferencesRepository);
  478. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  479. RegisterSingleInstance(ItemRepository);
  480. ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager);
  481. RegisterSingleInstance(ProviderRepository);
  482. FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false);
  483. RegisterSingleInstance(FileOrganizationRepository);
  484. AuthenticationRepository = await GetAuthenticationRepository().ConfigureAwait(false);
  485. RegisterSingleInstance(AuthenticationRepository);
  486. //SyncRepository = await GetSyncRepository().ConfigureAwait(false);
  487. //RegisterSingleInstance(SyncRepository);
  488. UserManager = new UserManager(LogManager.GetLogger("UserManager"), ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService);
  489. RegisterSingleInstance(UserManager);
  490. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager);
  491. RegisterSingleInstance(LibraryManager);
  492. var musicManager = new MusicManager(LibraryManager);
  493. RegisterSingleInstance<IMusicManager>(new MusicManager(LibraryManager));
  494. LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
  495. RegisterSingleInstance(LibraryMonitor);
  496. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager);
  497. RegisterSingleInstance(ProviderManager);
  498. SeriesOrderManager = new SeriesOrderManager();
  499. RegisterSingleInstance(SeriesOrderManager);
  500. RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));
  501. HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", WebApplicationName, "dashboard/index.html");
  502. RegisterSingleInstance(HttpServer, false);
  503. progress.Report(10);
  504. ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager);
  505. RegisterSingleInstance(ServerManager);
  506. var innerProgress = new ActionableProgress<double>();
  507. innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));
  508. await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);
  509. progress.Report(90);
  510. ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder);
  511. RegisterSingleInstance(ImageProcessor);
  512. SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"));
  513. RegisterSingleInstance(SyncManager);
  514. DtoService = new DtoService(Logger, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager);
  515. RegisterSingleInstance(DtoService);
  516. SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, ItemRepository, JsonSerializer, this, HttpClient, AuthenticationRepository);
  517. RegisterSingleInstance(SessionManager);
  518. var newsService = new Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
  519. RegisterSingleInstance<INewsService>(newsService);
  520. var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);
  521. RegisterSingleInstance<IFileOrganizationService>(fileOrganizationService);
  522. progress.Report(15);
  523. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager);
  524. RegisterSingleInstance(ChannelManager);
  525. var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger);
  526. RegisterSingleInstance<IAppThemeManager>(appThemeManager);
  527. var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer);
  528. RegisterSingleInstance<IDlnaManager>(dlnaManager);
  529. var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient);
  530. RegisterSingleInstance<IConnectionManager>(connectionManager);
  531. var collectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"));
  532. RegisterSingleInstance<ICollectionManager>(collectionManager);
  533. var playlistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager);
  534. RegisterSingleInstance<IPlaylistManager>(playlistManager);
  535. LiveTvManager = new LiveTvManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer);
  536. RegisterSingleInstance(LiveTvManager);
  537. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, FileSystemManager, UserManager, ChannelManager, LiveTvManager, ApplicationPaths, playlistManager);
  538. RegisterSingleInstance(UserViewManager);
  539. var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, UserViewManager, ChannelManager);
  540. RegisterSingleInstance<IContentDirectory>(contentDirectory);
  541. NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
  542. RegisterSingleInstance(NotificationManager);
  543. RegisterSingleInstance<IEncryptionManager>(new EncryptionManager());
  544. SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, ItemRepository);
  545. RegisterSingleInstance(SubtitleManager);
  546. ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
  547. RegisterSingleInstance(ChapterManager);
  548. EncodingManager = new EncodingManager(ServerConfigurationManager, FileSystemManager, Logger,
  549. MediaEncoder, ChapterManager);
  550. RegisterSingleInstance(EncodingManager);
  551. var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false);
  552. RegisterSingleInstance(activityLogRepo);
  553. RegisterSingleInstance<IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo));
  554. var authContext = new AuthorizationContext();
  555. RegisterSingleInstance<IAuthorizationContext>(authContext);
  556. RegisterSingleInstance<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  557. RegisterSingleInstance<IAuthService>(new AuthService(UserManager, SessionManager, authContext, ServerConfigurationManager));
  558. RegisterSingleInstance<ISubtitleEncoder>(new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder));
  559. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  560. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  561. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  562. await ConfigureNotificationsRepository().ConfigureAwait(false);
  563. progress.Report(92);
  564. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  565. progress.Report(100);
  566. SetStaticProperties();
  567. await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
  568. SetKernelProperties();
  569. }
  570. protected override INetworkManager CreateNetworkManager()
  571. {
  572. return new NetworkManager();
  573. }
  574. protected override IFileSystem CreateFileSystemManager()
  575. {
  576. return FileSystemFactory.CreateFileSystemManager(LogManager);
  577. }
  578. /// <summary>
  579. /// Registers the media encoder.
  580. /// </summary>
  581. /// <returns>Task.</returns>
  582. private async Task RegisterMediaEncoder(IProgress<double> progress)
  583. {
  584. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager).GetFFMpegInfo(progress).ConfigureAwait(false);
  585. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), JsonSerializer, info.EncoderPath, info.ProbePath, info.Version);
  586. RegisterSingleInstance(MediaEncoder);
  587. }
  588. /// <summary>
  589. /// Sets the kernel properties.
  590. /// </summary>
  591. private void SetKernelProperties()
  592. {
  593. LocalizedStrings.StringFiles = GetExports<LocalizedStringData>();
  594. }
  595. /// <summary>
  596. /// Gets the user repository.
  597. /// </summary>
  598. /// <returns>Task{IUserRepository}.</returns>
  599. private async Task<IUserRepository> GetUserRepository()
  600. {
  601. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  602. await repo.Initialize().ConfigureAwait(false);
  603. return repo;
  604. }
  605. /// <summary>
  606. /// Gets the file organization repository.
  607. /// </summary>
  608. /// <returns>Task{IUserRepository}.</returns>
  609. private async Task<IFileOrganizationRepository> GetFileOrganizationRepository()
  610. {
  611. var repo = new SqliteFileOrganizationRepository(LogManager, ServerConfigurationManager.ApplicationPaths);
  612. await repo.Initialize().ConfigureAwait(false);
  613. return repo;
  614. }
  615. private async Task<IAuthenticationRepository> GetAuthenticationRepository()
  616. {
  617. var repo = new AuthenticationRepository(LogManager.GetLogger("AuthenticationRepository"), ServerConfigurationManager.ApplicationPaths);
  618. await repo.Initialize().ConfigureAwait(false);
  619. return repo;
  620. }
  621. private async Task<IActivityRepository> GetActivityLogRepository()
  622. {
  623. var repo = new ActivityRepository(LogManager.GetLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths);
  624. await repo.Initialize().ConfigureAwait(false);
  625. return repo;
  626. }
  627. private async Task<ISyncRepository> GetSyncRepository()
  628. {
  629. var repo = new SyncRepository(LogManager.GetLogger("SyncRepository"), ServerConfigurationManager.ApplicationPaths);
  630. await repo.Initialize().ConfigureAwait(false);
  631. return repo;
  632. }
  633. /// <summary>
  634. /// Configures the repositories.
  635. /// </summary>
  636. /// <returns>Task.</returns>
  637. private async Task ConfigureNotificationsRepository()
  638. {
  639. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  640. await repo.Initialize().ConfigureAwait(false);
  641. NotificationsRepository = repo;
  642. RegisterSingleInstance(NotificationsRepository);
  643. }
  644. /// <summary>
  645. /// Configures the repositories.
  646. /// </summary>
  647. /// <returns>Task.</returns>
  648. private async Task ConfigureDisplayPreferencesRepositories()
  649. {
  650. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  651. }
  652. /// <summary>
  653. /// Configures the item repositories.
  654. /// </summary>
  655. /// <returns>Task.</returns>
  656. private async Task ConfigureItemRepositories()
  657. {
  658. await ItemRepository.Initialize().ConfigureAwait(false);
  659. await ProviderRepository.Initialize().ConfigureAwait(false);
  660. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  661. }
  662. /// <summary>
  663. /// Configures the user data repositories.
  664. /// </summary>
  665. /// <returns>Task.</returns>
  666. private async Task ConfigureUserDataRepositories()
  667. {
  668. var repo = new SqliteUserDataRepository(ApplicationPaths, LogManager);
  669. await repo.Initialize().ConfigureAwait(false);
  670. ((UserDataManager)UserDataManager).Repository = repo;
  671. }
  672. /// <summary>
  673. /// Dirty hacks
  674. /// </summary>
  675. private void SetStaticProperties()
  676. {
  677. // For now there's no real way to inject these properly
  678. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  679. BaseItem.ConfigurationManager = ServerConfigurationManager;
  680. BaseItem.LibraryManager = LibraryManager;
  681. BaseItem.ProviderManager = ProviderManager;
  682. BaseItem.LocalizationManager = LocalizationManager;
  683. BaseItem.ItemRepository = ItemRepository;
  684. User.XmlSerializer = XmlSerializer;
  685. User.UserManager = UserManager;
  686. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  687. Folder.UserManager = UserManager;
  688. BaseItem.FileSystem = FileSystemManager;
  689. BaseItem.UserDataManager = UserDataManager;
  690. ChannelVideoItem.ChannelManager = ChannelManager;
  691. BaseItem.LiveTvManager = LiveTvManager;
  692. UserView.UserViewManager = UserViewManager;
  693. }
  694. /// <summary>
  695. /// Finds the parts.
  696. /// </summary>
  697. protected override void FindParts()
  698. {
  699. if (IsFirstRun)
  700. {
  701. RegisterServerWithAdministratorAccess();
  702. }
  703. base.FindParts();
  704. HttpServer.Init(GetExports<IRestfulService>(false));
  705. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  706. StartServer(true);
  707. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  708. GetExports<IVirtualFolderCreator>(),
  709. GetExports<IItemResolver>(),
  710. GetExports<IIntroProvider>(),
  711. GetExports<IBaseItemComparer>(),
  712. GetExports<ILibraryPostScanTask>());
  713. ProviderManager.AddParts(GetExports<IImageProvider>(),
  714. GetExports<IMetadataService>(),
  715. GetExports<IItemIdentityProvider>(),
  716. GetExports<IItemIdentityConverter>(),
  717. GetExports<IMetadataProvider>(),
  718. GetExports<IMetadataSaver>(),
  719. GetExports<IImageSaver>(),
  720. GetExports<IExternalId>());
  721. SeriesOrderManager.AddParts(GetExports<ISeriesOrderProvider>());
  722. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  723. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  724. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  725. ChapterManager.AddParts(GetExports<IChapterProvider>());
  726. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  727. ChannelManager.AddParts(GetExports<IChannel>(), GetExports<IChannelFactory>());
  728. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  729. SyncManager.AddParts(GetExports<ISyncProvider>());
  730. }
  731. /// <summary>
  732. /// Starts the server.
  733. /// </summary>
  734. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  735. private void StartServer(bool retryOnFailure)
  736. {
  737. try
  738. {
  739. ServerManager.Start(HttpServerUrlPrefixes);
  740. }
  741. catch (Exception ex)
  742. {
  743. Logger.ErrorException("Error starting http server", ex);
  744. if (retryOnFailure)
  745. {
  746. RegisterServerWithAdministratorAccess();
  747. StartServer(false);
  748. }
  749. else
  750. {
  751. throw;
  752. }
  753. }
  754. }
  755. /// <summary>
  756. /// Called when [configuration updated].
  757. /// </summary>
  758. /// <param name="sender">The sender.</param>
  759. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  760. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  761. {
  762. base.OnConfigurationUpdated(sender, e);
  763. if (!HttpServer.UrlPrefixes.SequenceEqual(HttpServerUrlPrefixes, StringComparer.OrdinalIgnoreCase))
  764. {
  765. NotifyPendingRestart();
  766. }
  767. }
  768. /// <summary>
  769. /// Restarts this instance.
  770. /// </summary>
  771. public override async Task Restart()
  772. {
  773. if (!CanSelfRestart)
  774. {
  775. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  776. }
  777. try
  778. {
  779. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  780. }
  781. catch (Exception ex)
  782. {
  783. Logger.ErrorException("Error sending server restart notification", ex);
  784. }
  785. Logger.Debug("Calling NativeApp.Restart");
  786. NativeApp.Restart();
  787. }
  788. /// <summary>
  789. /// Gets or sets a value indicating whether this instance can self update.
  790. /// </summary>
  791. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  792. public override bool CanSelfUpdate
  793. {
  794. get
  795. {
  796. #if DEBUG
  797. return false;
  798. #endif
  799. #pragma warning disable 162
  800. return NativeApp.CanSelfUpdate;
  801. #pragma warning restore 162
  802. }
  803. }
  804. /// <summary>
  805. /// Gets the composable part assemblies.
  806. /// </summary>
  807. /// <returns>IEnumerable{Assembly}.</returns>
  808. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  809. {
  810. var list = GetPluginAssemblies()
  811. .ToList();
  812. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  813. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  814. // Include composable parts in the Api assembly
  815. list.Add(typeof(ApiEntryPoint).Assembly);
  816. // Include composable parts in the Dashboard assembly
  817. list.Add(typeof(DashboardService).Assembly);
  818. // Include composable parts in the Model assembly
  819. list.Add(typeof(SystemInfo).Assembly);
  820. // Include composable parts in the Common assembly
  821. list.Add(typeof(IApplicationHost).Assembly);
  822. // Include composable parts in the Controller assembly
  823. list.Add(typeof(IServerApplicationHost).Assembly);
  824. // Include composable parts in the Providers assembly
  825. list.Add(typeof(ProviderUtils).Assembly);
  826. // Common implementations
  827. list.Add(typeof(TaskManager).Assembly);
  828. // Server implementations
  829. list.Add(typeof(ServerApplicationPaths).Assembly);
  830. // MediaEncoding
  831. list.Add(typeof(MediaEncoder).Assembly);
  832. // Dlna
  833. list.Add(typeof(DlnaEntryPoint).Assembly);
  834. // Local metadata
  835. list.Add(typeof(AlbumXmlProvider).Assembly);
  836. // Xbmc
  837. list.Add(typeof(ArtistNfoProvider).Assembly);
  838. list.AddRange(Assemblies.GetAssembliesWithParts());
  839. // Include composable parts in the running assembly
  840. list.Add(GetType().Assembly);
  841. return list;
  842. }
  843. /// <summary>
  844. /// Gets the plugin assemblies.
  845. /// </summary>
  846. /// <returns>IEnumerable{Assembly}.</returns>
  847. private IEnumerable<Assembly> GetPluginAssemblies()
  848. {
  849. try
  850. {
  851. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  852. .Select(LoadAssembly)
  853. .Where(a => a != null)
  854. .ToList();
  855. }
  856. catch (DirectoryNotFoundException)
  857. {
  858. return new List<Assembly>();
  859. }
  860. }
  861. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  862. public string ServerId
  863. {
  864. get { return _systemId; }
  865. }
  866. /// <summary>
  867. /// Gets the system status.
  868. /// </summary>
  869. /// <returns>SystemInfo.</returns>
  870. public virtual SystemInfo GetSystemInfo()
  871. {
  872. return new SystemInfo
  873. {
  874. HasPendingRestart = HasPendingRestart,
  875. Version = ApplicationVersion.ToString(),
  876. IsNetworkDeployed = CanSelfUpdate,
  877. WebSocketPortNumber = HttpServerPort,
  878. SupportsNativeWebSocket = true,
  879. FailedPluginAssemblies = FailedAssemblies.ToList(),
  880. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  881. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  882. Id = ServerId,
  883. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  884. LogPath = ApplicationPaths.LogDirectoryPath,
  885. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  886. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  887. CachePath = ApplicationPaths.CachePath,
  888. MacAddress = GetMacAddress(),
  889. HttpServerPortNumber = HttpServerPort,
  890. OperatingSystem = Environment.OSVersion.ToString(),
  891. CanSelfRestart = CanSelfRestart,
  892. CanSelfUpdate = CanSelfUpdate,
  893. WanAddress = GetWanAddress(),
  894. HasUpdateAvailable = HasUpdateAvailable,
  895. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  896. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  897. IsRunningAsService = IsRunningAsService,
  898. ServerName = FriendlyName
  899. };
  900. }
  901. public string FriendlyName
  902. {
  903. get
  904. {
  905. return string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName)
  906. ? Environment.MachineName
  907. : ServerConfigurationManager.Configuration.ServerName;
  908. }
  909. }
  910. public int HttpServerPort
  911. {
  912. get { return ServerConfigurationManager.Configuration.HttpServerPortNumber; }
  913. }
  914. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  915. private string GetWanAddress()
  916. {
  917. var ip = ServerConfigurationManager.Configuration.WanDdns;
  918. if (string.IsNullOrWhiteSpace(ip))
  919. {
  920. ip = WanAddressEntryPoint.WanAddress;
  921. }
  922. if (!string.IsNullOrEmpty(ip))
  923. {
  924. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  925. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  926. {
  927. ip = "http://" + ip;
  928. }
  929. return ip + ":" + ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(_usCulture);
  930. }
  931. return null;
  932. }
  933. /// <summary>
  934. /// Gets the mac address.
  935. /// </summary>
  936. /// <returns>System.String.</returns>
  937. private string GetMacAddress()
  938. {
  939. try
  940. {
  941. return NetworkManager.GetMacAddress();
  942. }
  943. catch (Exception ex)
  944. {
  945. Logger.ErrorException("Error getting mac address", ex);
  946. return null;
  947. }
  948. }
  949. /// <summary>
  950. /// Shuts down.
  951. /// </summary>
  952. public override async Task Shutdown()
  953. {
  954. try
  955. {
  956. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  957. }
  958. catch (Exception ex)
  959. {
  960. Logger.ErrorException("Error sending server shutdown notification", ex);
  961. }
  962. NativeApp.Shutdown();
  963. }
  964. /// <summary>
  965. /// Registers the server with administrator access.
  966. /// </summary>
  967. private void RegisterServerWithAdministratorAccess()
  968. {
  969. Logger.Info("Requesting administrative access to authorize http server");
  970. try
  971. {
  972. ServerAuthorization.AuthorizeServer(
  973. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  974. HttpServerUrlPrefixes.First(),
  975. UdpServerEntryPoint.PortNumber,
  976. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  977. }
  978. catch (Exception ex)
  979. {
  980. Logger.ErrorException("Error authorizing server", ex);
  981. }
  982. }
  983. public event EventHandler HasUpdateAvailableChanged;
  984. private bool _hasUpdateAvailable;
  985. public bool HasUpdateAvailable
  986. {
  987. get { return _hasUpdateAvailable; }
  988. set
  989. {
  990. var fireEvent = value && !_hasUpdateAvailable;
  991. _hasUpdateAvailable = value;
  992. if (fireEvent)
  993. {
  994. EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
  995. }
  996. }
  997. }
  998. /// <summary>
  999. /// Checks for update.
  1000. /// </summary>
  1001. /// <param name="cancellationToken">The cancellation token.</param>
  1002. /// <param name="progress">The progress.</param>
  1003. /// <returns>Task{CheckForUpdateResult}.</returns>
  1004. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  1005. {
  1006. var result = await NativeApp.CheckForApplicationUpdate(ApplicationVersion,
  1007. ConfigurationManager.CommonConfiguration.SystemUpdateLevel, InstallationManager,
  1008. cancellationToken, progress).ConfigureAwait(false);
  1009. HasUpdateAvailable = result.IsUpdateAvailable;
  1010. if (result.IsUpdateAvailable)
  1011. {
  1012. Logger.Info("New application version is available: {0}", result.AvailableVersion);
  1013. }
  1014. return result;
  1015. }
  1016. /// <summary>
  1017. /// Updates the application.
  1018. /// </summary>
  1019. /// <param name="package">The package that contains the update</param>
  1020. /// <param name="cancellationToken">The cancellation token.</param>
  1021. /// <param name="progress">The progress.</param>
  1022. /// <returns>Task.</returns>
  1023. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  1024. {
  1025. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  1026. HasUpdateAvailable = false;
  1027. OnApplicationUpdated(package);
  1028. }
  1029. /// <summary>
  1030. /// Configures the automatic run at startup.
  1031. /// </summary>
  1032. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  1033. protected override void ConfigureAutoRunAtStartup(bool autorun)
  1034. {
  1035. if (SupportsAutoRunAtStartup)
  1036. {
  1037. Autorun.Configure(autorun);
  1038. }
  1039. }
  1040. }
  1041. }