ApplicationHost.cs 47 KB

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