ApplicationHost.cs 48 KB

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