ApplicationHost.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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);
  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);
  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. }
  692. /// <summary>
  693. /// Finds the parts.
  694. /// </summary>
  695. protected override void FindParts()
  696. {
  697. if (IsFirstRun)
  698. {
  699. RegisterServerWithAdministratorAccess();
  700. }
  701. base.FindParts();
  702. HttpServer.Init(GetExports<IRestfulService>(false));
  703. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  704. StartServer(true);
  705. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  706. GetExports<IVirtualFolderCreator>(),
  707. GetExports<IItemResolver>(),
  708. GetExports<IIntroProvider>(),
  709. GetExports<IBaseItemComparer>(),
  710. GetExports<ILibraryPostScanTask>());
  711. ProviderManager.AddParts(GetExports<IImageProvider>(),
  712. GetExports<IMetadataService>(),
  713. GetExports<IItemIdentityProvider>(),
  714. GetExports<IItemIdentityConverter>(),
  715. GetExports<IMetadataProvider>(),
  716. GetExports<IMetadataSaver>(),
  717. GetExports<IImageSaver>(),
  718. GetExports<IExternalId>());
  719. SeriesOrderManager.AddParts(GetExports<ISeriesOrderProvider>());
  720. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  721. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  722. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  723. ChapterManager.AddParts(GetExports<IChapterProvider>());
  724. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  725. ChannelManager.AddParts(GetExports<IChannel>(), GetExports<IChannelFactory>());
  726. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  727. SyncManager.AddParts(GetExports<ISyncProvider>());
  728. }
  729. /// <summary>
  730. /// Starts the server.
  731. /// </summary>
  732. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  733. private void StartServer(bool retryOnFailure)
  734. {
  735. try
  736. {
  737. ServerManager.Start(HttpServerUrlPrefixes);
  738. }
  739. catch (Exception ex)
  740. {
  741. Logger.ErrorException("Error starting http server", ex);
  742. if (retryOnFailure)
  743. {
  744. RegisterServerWithAdministratorAccess();
  745. StartServer(false);
  746. }
  747. else
  748. {
  749. throw;
  750. }
  751. }
  752. }
  753. /// <summary>
  754. /// Called when [configuration updated].
  755. /// </summary>
  756. /// <param name="sender">The sender.</param>
  757. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  758. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  759. {
  760. base.OnConfigurationUpdated(sender, e);
  761. if (!HttpServer.UrlPrefixes.SequenceEqual(HttpServerUrlPrefixes, StringComparer.OrdinalIgnoreCase))
  762. {
  763. NotifyPendingRestart();
  764. }
  765. }
  766. /// <summary>
  767. /// Restarts this instance.
  768. /// </summary>
  769. public override async Task Restart()
  770. {
  771. if (!CanSelfRestart)
  772. {
  773. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  774. }
  775. try
  776. {
  777. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  778. }
  779. catch (Exception ex)
  780. {
  781. Logger.ErrorException("Error sending server restart notification", ex);
  782. }
  783. Logger.Debug("Calling NativeApp.Restart");
  784. NativeApp.Restart();
  785. }
  786. /// <summary>
  787. /// Gets or sets a value indicating whether this instance can self update.
  788. /// </summary>
  789. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  790. public override bool CanSelfUpdate
  791. {
  792. get
  793. {
  794. #if DEBUG
  795. return false;
  796. #endif
  797. #pragma warning disable 162
  798. return NativeApp.CanSelfUpdate;
  799. #pragma warning restore 162
  800. }
  801. }
  802. /// <summary>
  803. /// Gets the composable part assemblies.
  804. /// </summary>
  805. /// <returns>IEnumerable{Assembly}.</returns>
  806. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  807. {
  808. var list = GetPluginAssemblies()
  809. .ToList();
  810. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  811. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  812. // Include composable parts in the Api assembly
  813. list.Add(typeof(ApiEntryPoint).Assembly);
  814. // Include composable parts in the Dashboard assembly
  815. list.Add(typeof(DashboardService).Assembly);
  816. // Include composable parts in the Model assembly
  817. list.Add(typeof(SystemInfo).Assembly);
  818. // Include composable parts in the Common assembly
  819. list.Add(typeof(IApplicationHost).Assembly);
  820. // Include composable parts in the Controller assembly
  821. list.Add(typeof(IServerApplicationHost).Assembly);
  822. // Include composable parts in the Providers assembly
  823. list.Add(typeof(ProviderUtils).Assembly);
  824. // Common implementations
  825. list.Add(typeof(TaskManager).Assembly);
  826. // Server implementations
  827. list.Add(typeof(ServerApplicationPaths).Assembly);
  828. // MediaEncoding
  829. list.Add(typeof(MediaEncoder).Assembly);
  830. // Dlna
  831. list.Add(typeof(DlnaEntryPoint).Assembly);
  832. // Local metadata
  833. list.Add(typeof(AlbumXmlProvider).Assembly);
  834. // Xbmc
  835. list.Add(typeof(ArtistNfoProvider).Assembly);
  836. list.AddRange(Assemblies.GetAssembliesWithParts());
  837. // Include composable parts in the running assembly
  838. list.Add(GetType().Assembly);
  839. return list;
  840. }
  841. /// <summary>
  842. /// Gets the plugin assemblies.
  843. /// </summary>
  844. /// <returns>IEnumerable{Assembly}.</returns>
  845. private IEnumerable<Assembly> GetPluginAssemblies()
  846. {
  847. try
  848. {
  849. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  850. .Select(LoadAssembly)
  851. .Where(a => a != null)
  852. .ToList();
  853. }
  854. catch (DirectoryNotFoundException)
  855. {
  856. return new List<Assembly>();
  857. }
  858. }
  859. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  860. public string ServerId
  861. {
  862. get { return _systemId; }
  863. }
  864. /// <summary>
  865. /// Gets the system status.
  866. /// </summary>
  867. /// <returns>SystemInfo.</returns>
  868. public virtual SystemInfo GetSystemInfo()
  869. {
  870. return new SystemInfo
  871. {
  872. HasPendingRestart = HasPendingRestart,
  873. Version = ApplicationVersion.ToString(),
  874. IsNetworkDeployed = CanSelfUpdate,
  875. WebSocketPortNumber = HttpServerPort,
  876. SupportsNativeWebSocket = true,
  877. FailedPluginAssemblies = FailedAssemblies.ToList(),
  878. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  879. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  880. Id = ServerId,
  881. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  882. LogPath = ApplicationPaths.LogDirectoryPath,
  883. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  884. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  885. CachePath = ApplicationPaths.CachePath,
  886. MacAddress = GetMacAddress(),
  887. HttpServerPortNumber = HttpServerPort,
  888. OperatingSystem = Environment.OSVersion.ToString(),
  889. CanSelfRestart = CanSelfRestart,
  890. CanSelfUpdate = CanSelfUpdate,
  891. WanAddress = GetWanAddress(),
  892. HasUpdateAvailable = HasUpdateAvailable,
  893. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  894. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  895. IsRunningAsService = IsRunningAsService,
  896. ServerName = FriendlyName
  897. };
  898. }
  899. public string FriendlyName
  900. {
  901. get
  902. {
  903. return string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName)
  904. ? Environment.MachineName
  905. : ServerConfigurationManager.Configuration.ServerName;
  906. }
  907. }
  908. public int HttpServerPort
  909. {
  910. get { return ServerConfigurationManager.Configuration.HttpServerPortNumber; }
  911. }
  912. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  913. private string GetWanAddress()
  914. {
  915. var ip = ServerConfigurationManager.Configuration.WanDdns;
  916. if (string.IsNullOrWhiteSpace(ip))
  917. {
  918. ip = WanAddressEntryPoint.WanAddress;
  919. }
  920. if (!string.IsNullOrEmpty(ip))
  921. {
  922. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  923. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  924. {
  925. ip = "http://" + ip;
  926. }
  927. return ip + ":" + ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(_usCulture);
  928. }
  929. return null;
  930. }
  931. /// <summary>
  932. /// Gets the mac address.
  933. /// </summary>
  934. /// <returns>System.String.</returns>
  935. private string GetMacAddress()
  936. {
  937. try
  938. {
  939. return NetworkManager.GetMacAddress();
  940. }
  941. catch (Exception ex)
  942. {
  943. Logger.ErrorException("Error getting mac address", ex);
  944. return null;
  945. }
  946. }
  947. /// <summary>
  948. /// Shuts down.
  949. /// </summary>
  950. public override async Task Shutdown()
  951. {
  952. try
  953. {
  954. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  955. }
  956. catch (Exception ex)
  957. {
  958. Logger.ErrorException("Error sending server shutdown notification", ex);
  959. }
  960. NativeApp.Shutdown();
  961. }
  962. /// <summary>
  963. /// Registers the server with administrator access.
  964. /// </summary>
  965. private void RegisterServerWithAdministratorAccess()
  966. {
  967. Logger.Info("Requesting administrative access to authorize http server");
  968. try
  969. {
  970. ServerAuthorization.AuthorizeServer(
  971. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  972. HttpServerUrlPrefixes.First(),
  973. UdpServerEntryPoint.PortNumber,
  974. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  975. }
  976. catch (Exception ex)
  977. {
  978. Logger.ErrorException("Error authorizing server", ex);
  979. }
  980. }
  981. public event EventHandler HasUpdateAvailableChanged;
  982. private bool _hasUpdateAvailable;
  983. public bool HasUpdateAvailable
  984. {
  985. get { return _hasUpdateAvailable; }
  986. set
  987. {
  988. var fireEvent = value && !_hasUpdateAvailable;
  989. _hasUpdateAvailable = value;
  990. if (fireEvent)
  991. {
  992. EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
  993. }
  994. }
  995. }
  996. /// <summary>
  997. /// Checks for update.
  998. /// </summary>
  999. /// <param name="cancellationToken">The cancellation token.</param>
  1000. /// <param name="progress">The progress.</param>
  1001. /// <returns>Task{CheckForUpdateResult}.</returns>
  1002. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  1003. {
  1004. var result = await NativeApp.CheckForApplicationUpdate(ApplicationVersion,
  1005. ConfigurationManager.CommonConfiguration.SystemUpdateLevel, InstallationManager,
  1006. cancellationToken, progress).ConfigureAwait(false);
  1007. HasUpdateAvailable = result.IsUpdateAvailable;
  1008. if (result.IsUpdateAvailable)
  1009. {
  1010. Logger.Info("New application version is available: {0}", result.AvailableVersion);
  1011. }
  1012. return result;
  1013. }
  1014. /// <summary>
  1015. /// Updates the application.
  1016. /// </summary>
  1017. /// <param name="package">The package that contains the update</param>
  1018. /// <param name="cancellationToken">The cancellation token.</param>
  1019. /// <param name="progress">The progress.</param>
  1020. /// <returns>Task.</returns>
  1021. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  1022. {
  1023. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  1024. HasUpdateAvailable = false;
  1025. OnApplicationUpdated(package);
  1026. }
  1027. /// <summary>
  1028. /// Configures the automatic run at startup.
  1029. /// </summary>
  1030. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  1031. protected override void ConfigureAutoRunAtStartup(bool autorun)
  1032. {
  1033. if (SupportsAutoRunAtStartup)
  1034. {
  1035. Autorun.Configure(autorun);
  1036. }
  1037. }
  1038. }
  1039. }