ApplicationHost.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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 + "/"
  131. };
  132. if (ServerConfigurationManager.Configuration.UseHttps)
  133. {
  134. list.Add("https://+:" + ServerConfigurationManager.Configuration.HttpsPortNumber + "/");
  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. HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", "web/index.html");
  399. RegisterSingleInstance(HttpServer, false);
  400. progress.Report(10);
  401. ServerManager = new ServerManager(this, JsonSerializer, LogManager.GetLogger("ServerManager"), ServerConfigurationManager);
  402. RegisterSingleInstance(ServerManager);
  403. var innerProgress = new ActionableProgress<double>();
  404. innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));
  405. ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder);
  406. RegisterSingleInstance(ImageProcessor);
  407. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager);
  408. RegisterSingleInstance(TVSeriesManager);
  409. SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"), UserManager, () => DtoService, this, TVSeriesManager, () => MediaEncoder, FileSystemManager, () => SubtitleEncoder, ServerConfigurationManager);
  410. RegisterSingleInstance(SyncManager);
  411. DtoService = new DtoService(Logger, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager, () => ChannelManager, SyncManager, this);
  412. RegisterSingleInstance(DtoService);
  413. var encryptionManager = new EncryptionManager();
  414. RegisterSingleInstance<IEncryptionManager>(encryptionManager);
  415. ConnectManager = new ConnectManager(LogManager.GetLogger("Connect"), ApplicationPaths, JsonSerializer, encryptionManager, HttpClient, this, ServerConfigurationManager, UserManager, ProviderManager);
  416. RegisterSingleInstance(ConnectManager);
  417. DeviceManager = new DeviceManager(new DeviceRepository(ApplicationPaths, JsonSerializer, Logger, FileSystemManager), UserManager, FileSystemManager, LibraryMonitor, ConfigurationManager, LogManager.GetLogger("DeviceManager"));
  418. RegisterSingleInstance(DeviceManager);
  419. SessionManager = new SessionManager(UserDataManager, Logger, UserRepository, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, ItemRepository, JsonSerializer, this, HttpClient, AuthenticationRepository, DeviceManager);
  420. RegisterSingleInstance(SessionManager);
  421. var newsService = new Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
  422. RegisterSingleInstance<INewsService>(newsService);
  423. var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, LogManager.GetLogger("FileOrganizationService"), LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);
  424. RegisterSingleInstance<IFileOrganizationService>(fileOrganizationService);
  425. progress.Report(15);
  426. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, Logger, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, LocalizationManager, HttpClient);
  427. RegisterSingleInstance(ChannelManager);
  428. var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger);
  429. RegisterSingleInstance<IAppThemeManager>(appThemeManager);
  430. var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("Dlna"), JsonSerializer);
  431. RegisterSingleInstance<IDlnaManager>(dlnaManager);
  432. var connectionManager = new ConnectionManager(dlnaManager, ServerConfigurationManager, LogManager.GetLogger("UpnpConnectionManager"), HttpClient);
  433. RegisterSingleInstance<IConnectionManager>(connectionManager);
  434. CollectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("CollectionManager"));
  435. RegisterSingleInstance(CollectionManager);
  436. var playlistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LogManager.GetLogger("PlaylistManager"), UserManager);
  437. RegisterSingleInstance<IPlaylistManager>(playlistManager);
  438. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer);
  439. RegisterSingleInstance(LiveTvManager);
  440. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, FileSystemManager, UserManager, ChannelManager, LiveTvManager, ApplicationPaths, playlistManager);
  441. RegisterSingleInstance(UserViewManager);
  442. var contentDirectory = new ContentDirectory(dlnaManager, UserDataManager, ImageProcessor, LibraryManager, ServerConfigurationManager, UserManager, LogManager.GetLogger("UpnpContentDirectory"), HttpClient, LocalizationManager, ChannelManager);
  443. RegisterSingleInstance<IContentDirectory>(contentDirectory);
  444. NotificationManager = new NotificationManager(LogManager, UserManager, ServerConfigurationManager);
  445. RegisterSingleInstance(NotificationManager);
  446. SubtitleManager = new SubtitleManager(LogManager.GetLogger("SubtitleManager"), FileSystemManager, LibraryMonitor, LibraryManager, ItemRepository);
  447. RegisterSingleInstance(SubtitleManager);
  448. ChapterManager = new ChapterManager(LibraryManager, LogManager.GetLogger("ChapterManager"), ServerConfigurationManager, ItemRepository);
  449. RegisterSingleInstance(ChapterManager);
  450. await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);
  451. progress.Report(90);
  452. EncodingManager = new EncodingManager(FileSystemManager, Logger,
  453. MediaEncoder, ChapterManager);
  454. RegisterSingleInstance(EncodingManager);
  455. var activityLogRepo = await GetActivityLogRepository().ConfigureAwait(false);
  456. RegisterSingleInstance(activityLogRepo);
  457. RegisterSingleInstance<IActivityManager>(new ActivityManager(LogManager.GetLogger("ActivityManager"), activityLogRepo, UserManager));
  458. var authContext = new AuthorizationContext(AuthenticationRepository);
  459. RegisterSingleInstance<IAuthorizationContext>(authContext);
  460. RegisterSingleInstance<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  461. RegisterSingleInstance<IAuthService>(new AuthService(UserManager, authContext, ServerConfigurationManager, ConnectManager, SessionManager, DeviceManager));
  462. SubtitleEncoder = new SubtitleEncoder(LibraryManager, LogManager.GetLogger("SubtitleEncoder"), ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer);
  463. RegisterSingleInstance(SubtitleEncoder);
  464. await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false);
  465. await ConfigureItemRepositories().ConfigureAwait(false);
  466. await ConfigureUserDataRepositories().ConfigureAwait(false);
  467. await ConfigureNotificationsRepository().ConfigureAwait(false);
  468. progress.Report(100);
  469. SetStaticProperties();
  470. await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
  471. SetKernelProperties();
  472. }
  473. protected override INetworkManager CreateNetworkManager(ILogger logger)
  474. {
  475. return NativeApp.CreateNetworkManager(logger);
  476. }
  477. /// <summary>
  478. /// Registers the media encoder.
  479. /// </summary>
  480. /// <returns>Task.</returns>
  481. private async Task RegisterMediaEncoder(IProgress<double> progress)
  482. {
  483. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager, NativeApp.Environment)
  484. .GetFFMpegInfo(NativeApp.Environment, _startupOptions, progress).ConfigureAwait(false);
  485. new FFmpegValidator(Logger, ApplicationPaths).Validate(info);
  486. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"),
  487. JsonSerializer,
  488. info.EncoderPath,
  489. info.ProbePath,
  490. info.Version,
  491. ServerConfigurationManager,
  492. FileSystemManager,
  493. LiveTvManager,
  494. IsoManager,
  495. LibraryManager,
  496. ChannelManager,
  497. SessionManager,
  498. () => SubtitleEncoder);
  499. RegisterSingleInstance(MediaEncoder);
  500. }
  501. /// <summary>
  502. /// Sets the kernel properties.
  503. /// </summary>
  504. private void SetKernelProperties()
  505. {
  506. LocalizedStrings.StringFiles = GetExports<LocalizedStringData>();
  507. }
  508. /// <summary>
  509. /// Gets the user repository.
  510. /// </summary>
  511. /// <returns>Task{IUserRepository}.</returns>
  512. private async Task<IUserRepository> GetUserRepository()
  513. {
  514. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  515. await repo.Initialize().ConfigureAwait(false);
  516. return repo;
  517. }
  518. /// <summary>
  519. /// Gets the file organization repository.
  520. /// </summary>
  521. /// <returns>Task{IUserRepository}.</returns>
  522. private async Task<IFileOrganizationRepository> GetFileOrganizationRepository()
  523. {
  524. var repo = new SqliteFileOrganizationRepository(LogManager, ServerConfigurationManager.ApplicationPaths);
  525. await repo.Initialize().ConfigureAwait(false);
  526. return repo;
  527. }
  528. private async Task<IAuthenticationRepository> GetAuthenticationRepository()
  529. {
  530. var repo = new AuthenticationRepository(LogManager.GetLogger("AuthenticationRepository"), ServerConfigurationManager.ApplicationPaths);
  531. await repo.Initialize().ConfigureAwait(false);
  532. return repo;
  533. }
  534. private async Task<IActivityRepository> GetActivityLogRepository()
  535. {
  536. var repo = new ActivityRepository(LogManager.GetLogger("ActivityRepository"), ServerConfigurationManager.ApplicationPaths);
  537. await repo.Initialize().ConfigureAwait(false);
  538. return repo;
  539. }
  540. private async Task<ISyncRepository> GetSyncRepository()
  541. {
  542. var repo = new SyncRepository(LogManager.GetLogger("SyncRepository"), ServerConfigurationManager.ApplicationPaths, JsonSerializer);
  543. await repo.Initialize().ConfigureAwait(false);
  544. return repo;
  545. }
  546. /// <summary>
  547. /// Configures the repositories.
  548. /// </summary>
  549. /// <returns>Task.</returns>
  550. private async Task ConfigureNotificationsRepository()
  551. {
  552. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  553. await repo.Initialize().ConfigureAwait(false);
  554. NotificationsRepository = repo;
  555. RegisterSingleInstance(NotificationsRepository);
  556. }
  557. /// <summary>
  558. /// Configures the repositories.
  559. /// </summary>
  560. /// <returns>Task.</returns>
  561. private async Task ConfigureDisplayPreferencesRepositories()
  562. {
  563. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  564. }
  565. /// <summary>
  566. /// Configures the item repositories.
  567. /// </summary>
  568. /// <returns>Task.</returns>
  569. private async Task ConfigureItemRepositories()
  570. {
  571. await ItemRepository.Initialize().ConfigureAwait(false);
  572. await ProviderRepository.Initialize().ConfigureAwait(false);
  573. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  574. }
  575. /// <summary>
  576. /// Configures the user data repositories.
  577. /// </summary>
  578. /// <returns>Task.</returns>
  579. private async Task ConfigureUserDataRepositories()
  580. {
  581. var repo = new SqliteUserDataRepository(ApplicationPaths, LogManager);
  582. await repo.Initialize().ConfigureAwait(false);
  583. ((UserDataManager)UserDataManager).Repository = repo;
  584. }
  585. /// <summary>
  586. /// Dirty hacks
  587. /// </summary>
  588. private void SetStaticProperties()
  589. {
  590. // For now there's no real way to inject these properly
  591. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  592. BaseItem.ConfigurationManager = ServerConfigurationManager;
  593. BaseItem.LibraryManager = LibraryManager;
  594. BaseItem.ProviderManager = ProviderManager;
  595. BaseItem.LocalizationManager = LocalizationManager;
  596. BaseItem.ItemRepository = ItemRepository;
  597. User.XmlSerializer = XmlSerializer;
  598. User.UserManager = UserManager;
  599. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  600. Folder.UserManager = UserManager;
  601. BaseItem.FileSystem = FileSystemManager;
  602. BaseItem.UserDataManager = UserDataManager;
  603. BaseItem.ChannelManager = ChannelManager;
  604. BaseItem.LiveTvManager = LiveTvManager;
  605. Folder.UserViewManager = UserViewManager;
  606. UserView.TVSeriesManager = TVSeriesManager;
  607. BaseItem.CollectionManager = CollectionManager;
  608. }
  609. /// <summary>
  610. /// Finds the parts.
  611. /// </summary>
  612. protected override void FindParts()
  613. {
  614. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  615. {
  616. RegisterServerWithAdministratorAccess();
  617. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  618. ConfigurationManager.SaveConfiguration();
  619. }
  620. base.FindParts();
  621. HttpServer.Init(GetExports<IRestfulService>(false));
  622. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  623. StartServer();
  624. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  625. GetExports<IVirtualFolderCreator>(),
  626. GetExports<IItemResolver>(),
  627. GetExports<IIntroProvider>(),
  628. GetExports<IBaseItemComparer>(),
  629. GetExports<ILibraryPostScanTask>());
  630. ProviderManager.AddParts(GetExports<IImageProvider>(),
  631. GetExports<IMetadataService>(),
  632. GetExports<IItemIdentityProvider>(),
  633. GetExports<IItemIdentityConverter>(),
  634. GetExports<IMetadataProvider>(),
  635. GetExports<IMetadataSaver>(),
  636. GetExports<IImageSaver>(),
  637. GetExports<IExternalId>());
  638. SeriesOrderManager.AddParts(GetExports<ISeriesOrderProvider>());
  639. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  640. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  641. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  642. ChapterManager.AddParts(GetExports<IChapterProvider>());
  643. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  644. ChannelManager.AddParts(GetExports<IChannel>(), GetExports<IChannelFactory>());
  645. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  646. SyncManager.AddParts(GetExports<ISyncProvider>());
  647. }
  648. /// <summary>
  649. /// Starts the server.
  650. /// </summary>
  651. private void StartServer()
  652. {
  653. try
  654. {
  655. ServerManager.Start(HttpServerUrlPrefixes, ServerConfigurationManager.Configuration.CertificatePath);
  656. }
  657. catch (Exception ex)
  658. {
  659. Logger.ErrorException("Error starting http server", ex);
  660. throw;
  661. }
  662. }
  663. /// <summary>
  664. /// Called when [configuration updated].
  665. /// </summary>
  666. /// <param name="sender">The sender.</param>
  667. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  668. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  669. {
  670. base.OnConfigurationUpdated(sender, e);
  671. if (!HttpServer.UrlPrefixes.SequenceEqual(HttpServerUrlPrefixes, StringComparer.OrdinalIgnoreCase))
  672. {
  673. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  674. ServerConfigurationManager.SaveConfiguration();
  675. NotifyPendingRestart();
  676. }
  677. }
  678. /// <summary>
  679. /// Restarts this instance.
  680. /// </summary>
  681. public override async Task Restart()
  682. {
  683. if (!CanSelfRestart)
  684. {
  685. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  686. }
  687. try
  688. {
  689. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  690. }
  691. catch (Exception ex)
  692. {
  693. Logger.ErrorException("Error sending server restart notification", ex);
  694. }
  695. Logger.Debug("Calling NativeApp.Restart");
  696. NativeApp.Restart();
  697. }
  698. /// <summary>
  699. /// Gets or sets a value indicating whether this instance can self update.
  700. /// </summary>
  701. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  702. public override bool CanSelfUpdate
  703. {
  704. get
  705. {
  706. #if DEBUG
  707. return false;
  708. #endif
  709. #pragma warning disable 162
  710. return NativeApp.CanSelfUpdate;
  711. #pragma warning restore 162
  712. }
  713. }
  714. /// <summary>
  715. /// Gets the composable part assemblies.
  716. /// </summary>
  717. /// <returns>IEnumerable{Assembly}.</returns>
  718. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  719. {
  720. var list = GetPluginAssemblies()
  721. .ToList();
  722. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  723. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  724. // Include composable parts in the Api assembly
  725. list.Add(typeof(ApiEntryPoint).Assembly);
  726. // Include composable parts in the Dashboard assembly
  727. list.Add(typeof(DashboardService).Assembly);
  728. // Include composable parts in the Model assembly
  729. list.Add(typeof(SystemInfo).Assembly);
  730. // Include composable parts in the Common assembly
  731. list.Add(typeof(IApplicationHost).Assembly);
  732. // Include composable parts in the Controller assembly
  733. list.Add(typeof(IServerApplicationHost).Assembly);
  734. // Include composable parts in the Providers assembly
  735. list.Add(typeof(ProviderUtils).Assembly);
  736. // Common implementations
  737. list.Add(typeof(TaskManager).Assembly);
  738. // Server implementations
  739. list.Add(typeof(ServerApplicationPaths).Assembly);
  740. // MediaEncoding
  741. list.Add(typeof(MediaEncoder).Assembly);
  742. // Dlna
  743. list.Add(typeof(DlnaEntryPoint).Assembly);
  744. // Local metadata
  745. list.Add(typeof(AlbumXmlProvider).Assembly);
  746. // Xbmc
  747. list.Add(typeof(ArtistNfoProvider).Assembly);
  748. list.AddRange(NativeApp.GetAssembliesWithParts());
  749. // Include composable parts in the running assembly
  750. list.Add(GetType().Assembly);
  751. return list;
  752. }
  753. /// <summary>
  754. /// Gets the plugin assemblies.
  755. /// </summary>
  756. /// <returns>IEnumerable{Assembly}.</returns>
  757. private IEnumerable<Assembly> GetPluginAssemblies()
  758. {
  759. try
  760. {
  761. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  762. .Select(LoadAssembly)
  763. .Where(a => a != null)
  764. .ToList();
  765. }
  766. catch (DirectoryNotFoundException)
  767. {
  768. return new List<Assembly>();
  769. }
  770. }
  771. /// <summary>
  772. /// Gets the system status.
  773. /// </summary>
  774. /// <returns>SystemInfo.</returns>
  775. public virtual SystemInfo GetSystemInfo()
  776. {
  777. return new SystemInfo
  778. {
  779. HasPendingRestart = HasPendingRestart,
  780. Version = ApplicationVersion.ToString(),
  781. IsNetworkDeployed = CanSelfUpdate,
  782. WebSocketPortNumber = HttpServerPort,
  783. FailedPluginAssemblies = FailedAssemblies.ToList(),
  784. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  785. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  786. Id = SystemId,
  787. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  788. LogPath = ApplicationPaths.LogDirectoryPath,
  789. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  790. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  791. CachePath = ApplicationPaths.CachePath,
  792. MacAddress = GetMacAddress(),
  793. HttpServerPortNumber = HttpServerPort,
  794. UseHttps = this.ServerConfigurationManager.Configuration.UseHttps,
  795. HttpsPortNumber = HttpsServerPort,
  796. OperatingSystem = OperatingSystemDisplayName,
  797. CanSelfRestart = CanSelfRestart,
  798. CanSelfUpdate = CanSelfUpdate,
  799. WanAddress = ConnectManager.WanApiAddress,
  800. HasUpdateAvailable = HasUpdateAvailable,
  801. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  802. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  803. IsRunningAsService = IsRunningAsService,
  804. SupportsRunningAsService = SupportsRunningAsService,
  805. ServerName = FriendlyName,
  806. LocalAddress = GetLocalIpAddress()
  807. };
  808. }
  809. /// <summary>
  810. /// Gets the local ip address.
  811. /// </summary>
  812. /// <returns>System.String.</returns>
  813. private string GetLocalIpAddress()
  814. {
  815. // Return the first matched address, if found, or the first known local address
  816. var address = HttpServerIpAddresses.FirstOrDefault();
  817. if (!string.IsNullOrWhiteSpace(address))
  818. {
  819. address = string.Format("http://{0}:{1}",
  820. address,
  821. ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(CultureInfo.InvariantCulture));
  822. }
  823. return address;
  824. }
  825. public IEnumerable<string> HttpServerIpAddresses
  826. {
  827. get
  828. {
  829. var localAddresses = NetworkManager.GetLocalIpAddresses()
  830. .ToList();
  831. var httpServerAddresses = HttpServer.LocalEndPoints
  832. .Select(i => i.Split(':').FirstOrDefault())
  833. .Where(i => !string.IsNullOrEmpty(i))
  834. .ToList();
  835. // Cross-check the local ip addresses with addresses that have been received on with the http server
  836. var matchedAddresses = httpServerAddresses
  837. .Where(i => localAddresses.Contains(i, StringComparer.OrdinalIgnoreCase))
  838. .ToList();
  839. if (matchedAddresses.Count == 0)
  840. {
  841. return localAddresses;
  842. }
  843. return matchedAddresses;
  844. }
  845. }
  846. public string FriendlyName
  847. {
  848. get
  849. {
  850. return string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName)
  851. ? Environment.MachineName
  852. : ServerConfigurationManager.Configuration.ServerName;
  853. }
  854. }
  855. public int HttpServerPort
  856. {
  857. get { return ServerConfigurationManager.Configuration.HttpServerPortNumber; }
  858. }
  859. public int HttpsServerPort
  860. {
  861. get { return ServerConfigurationManager.Configuration.HttpsPortNumber; }
  862. }
  863. /// <summary>
  864. /// Gets the mac address.
  865. /// </summary>
  866. /// <returns>System.String.</returns>
  867. private string GetMacAddress()
  868. {
  869. try
  870. {
  871. return NetworkManager.GetMacAddress();
  872. }
  873. catch (Exception ex)
  874. {
  875. Logger.ErrorException("Error getting mac address", ex);
  876. return null;
  877. }
  878. }
  879. /// <summary>
  880. /// Shuts down.
  881. /// </summary>
  882. public override async Task Shutdown()
  883. {
  884. try
  885. {
  886. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  887. }
  888. catch (Exception ex)
  889. {
  890. Logger.ErrorException("Error sending server shutdown notification", ex);
  891. }
  892. NativeApp.Shutdown();
  893. }
  894. /// <summary>
  895. /// Registers the server with administrator access.
  896. /// </summary>
  897. private void RegisterServerWithAdministratorAccess()
  898. {
  899. Logger.Info("Requesting administrative access to authorize http server");
  900. try
  901. {
  902. NativeApp.AuthorizeServer(
  903. UdpServerEntryPoint.PortNumber,
  904. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  905. ServerConfigurationManager.Configuration.HttpsPortNumber,
  906. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  907. }
  908. catch (Exception ex)
  909. {
  910. Logger.ErrorException("Error authorizing server", ex);
  911. }
  912. }
  913. public event EventHandler HasUpdateAvailableChanged;
  914. private bool _hasUpdateAvailable;
  915. public bool HasUpdateAvailable
  916. {
  917. get { return _hasUpdateAvailable; }
  918. set
  919. {
  920. var fireEvent = value && !_hasUpdateAvailable;
  921. _hasUpdateAvailable = value;
  922. if (fireEvent)
  923. {
  924. EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
  925. }
  926. }
  927. }
  928. /// <summary>
  929. /// Checks for update.
  930. /// </summary>
  931. /// <param name="cancellationToken">The cancellation token.</param>
  932. /// <param name="progress">The progress.</param>
  933. /// <returns>Task{CheckForUpdateResult}.</returns>
  934. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  935. {
  936. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  937. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, _remotePackageName, null, ApplicationVersion, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  938. var versionObject = version == null || string.IsNullOrWhiteSpace(version.versionStr) ? null : new Version(version.versionStr);
  939. var isUpdateAvailable = versionObject != null && versionObject > ApplicationVersion;
  940. var result = versionObject != null ?
  941. new CheckForUpdateResult { AvailableVersion = versionObject.ToString(), IsUpdateAvailable = isUpdateAvailable, Package = version } :
  942. new CheckForUpdateResult { AvailableVersion = ApplicationVersion.ToString(), IsUpdateAvailable = false };
  943. HasUpdateAvailable = result.IsUpdateAvailable;
  944. if (result.IsUpdateAvailable)
  945. {
  946. Logger.Info("New application version is available: {0}", result.AvailableVersion);
  947. }
  948. return result;
  949. }
  950. /// <summary>
  951. /// Updates the application.
  952. /// </summary>
  953. /// <param name="package">The package that contains the update</param>
  954. /// <param name="cancellationToken">The cancellation token.</param>
  955. /// <param name="progress">The progress.</param>
  956. /// <returns>Task.</returns>
  957. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  958. {
  959. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  960. HasUpdateAvailable = false;
  961. OnApplicationUpdated(package);
  962. }
  963. /// <summary>
  964. /// Configures the automatic run at startup.
  965. /// </summary>
  966. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  967. protected override void ConfigureAutoRunAtStartup(bool autorun)
  968. {
  969. if (SupportsAutoRunAtStartup)
  970. {
  971. NativeApp.ConfigureAutoRun(autorun);
  972. }
  973. }
  974. }
  975. }