ApplicationHost.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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. if (ServerConfigurationManager.Configuration.EnableHttps)
  638. {
  639. NetworkManager.GenerateSelfSignedSslCertificate(
  640. ServerConfigurationManager.Configuration.CertificatePath,
  641. GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns));
  642. }
  643. ServerManager.Start(GetUrlPrefixes(), ServerConfigurationManager.Configuration.CertificatePath);
  644. }
  645. catch (Exception ex)
  646. {
  647. Logger.ErrorException("Error starting http server", ex);
  648. throw;
  649. }
  650. }
  651. /// <summary>
  652. /// Called when [configuration updated].
  653. /// </summary>
  654. /// <param name="sender">The sender.</param>
  655. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  656. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  657. {
  658. base.OnConfigurationUpdated(sender, e);
  659. var requiresRestart = false;
  660. // Don't do anything if these haven't been set yet
  661. if (HttpPort != 0 && HttpsPort != 0)
  662. {
  663. // Need to restart if ports have changed
  664. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  665. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  666. {
  667. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  668. ServerConfigurationManager.SaveConfiguration();
  669. requiresRestart = true;
  670. }
  671. }
  672. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  673. {
  674. requiresRestart = true;
  675. }
  676. if (requiresRestart)
  677. {
  678. NotifyPendingRestart();
  679. }
  680. }
  681. /// <summary>
  682. /// Restarts this instance.
  683. /// </summary>
  684. public override async Task Restart()
  685. {
  686. if (!CanSelfRestart)
  687. {
  688. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  689. }
  690. try
  691. {
  692. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  693. }
  694. catch (Exception ex)
  695. {
  696. Logger.ErrorException("Error sending server restart notification", ex);
  697. }
  698. Logger.Debug("Calling NativeApp.Restart");
  699. NativeApp.Restart();
  700. }
  701. /// <summary>
  702. /// Gets or sets a value indicating whether this instance can self update.
  703. /// </summary>
  704. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  705. public override bool CanSelfUpdate
  706. {
  707. get
  708. {
  709. #if DEBUG
  710. return false;
  711. #endif
  712. #pragma warning disable 162
  713. return NativeApp.CanSelfUpdate;
  714. #pragma warning restore 162
  715. }
  716. }
  717. /// <summary>
  718. /// Gets the composable part assemblies.
  719. /// </summary>
  720. /// <returns>IEnumerable{Assembly}.</returns>
  721. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  722. {
  723. var list = GetPluginAssemblies()
  724. .ToList();
  725. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  726. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  727. // Include composable parts in the Api assembly
  728. list.Add(typeof(ApiEntryPoint).Assembly);
  729. // Include composable parts in the Dashboard assembly
  730. list.Add(typeof(DashboardService).Assembly);
  731. // Include composable parts in the Model assembly
  732. list.Add(typeof(SystemInfo).Assembly);
  733. // Include composable parts in the Common assembly
  734. list.Add(typeof(IApplicationHost).Assembly);
  735. // Include composable parts in the Controller assembly
  736. list.Add(typeof(IServerApplicationHost).Assembly);
  737. // Include composable parts in the Providers assembly
  738. list.Add(typeof(ProviderUtils).Assembly);
  739. // Common implementations
  740. list.Add(typeof(TaskManager).Assembly);
  741. // Server implementations
  742. list.Add(typeof(ServerApplicationPaths).Assembly);
  743. // MediaEncoding
  744. list.Add(typeof(MediaEncoder).Assembly);
  745. // Dlna
  746. list.Add(typeof(DlnaEntryPoint).Assembly);
  747. // Local metadata
  748. list.Add(typeof(AlbumXmlProvider).Assembly);
  749. // Xbmc
  750. list.Add(typeof(ArtistNfoProvider).Assembly);
  751. list.AddRange(NativeApp.GetAssembliesWithParts());
  752. // Include composable parts in the running assembly
  753. list.Add(GetType().Assembly);
  754. return list;
  755. }
  756. /// <summary>
  757. /// Gets the plugin assemblies.
  758. /// </summary>
  759. /// <returns>IEnumerable{Assembly}.</returns>
  760. private IEnumerable<Assembly> GetPluginAssemblies()
  761. {
  762. try
  763. {
  764. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  765. .Select(LoadAssembly)
  766. .Where(a => a != null)
  767. .ToList();
  768. }
  769. catch (DirectoryNotFoundException)
  770. {
  771. return new List<Assembly>();
  772. }
  773. }
  774. /// <summary>
  775. /// Gets the system status.
  776. /// </summary>
  777. /// <returns>SystemInfo.</returns>
  778. public virtual SystemInfo GetSystemInfo()
  779. {
  780. return new SystemInfo
  781. {
  782. HasPendingRestart = HasPendingRestart,
  783. Version = ApplicationVersion.ToString(),
  784. IsNetworkDeployed = CanSelfUpdate,
  785. WebSocketPortNumber = HttpPort,
  786. FailedPluginAssemblies = FailedAssemblies.ToList(),
  787. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  788. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  789. Id = SystemId,
  790. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  791. LogPath = ApplicationPaths.LogDirectoryPath,
  792. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  793. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  794. CachePath = ApplicationPaths.CachePath,
  795. MacAddress = GetMacAddress(),
  796. HttpServerPortNumber = HttpPort,
  797. EnableHttps = EnableHttps,
  798. HttpsPortNumber = HttpsPort,
  799. OperatingSystem = OperatingSystemDisplayName,
  800. CanSelfRestart = CanSelfRestart,
  801. CanSelfUpdate = CanSelfUpdate,
  802. WanAddress = ConnectManager.WanApiAddress,
  803. HasUpdateAvailable = HasUpdateAvailable,
  804. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  805. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  806. IsRunningAsService = IsRunningAsService,
  807. SupportsRunningAsService = SupportsRunningAsService,
  808. ServerName = FriendlyName,
  809. LocalAddress = GetLocalIpAddress()
  810. };
  811. }
  812. public bool EnableHttps
  813. {
  814. get
  815. {
  816. return SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  817. }
  818. }
  819. public bool SupportsHttps
  820. {
  821. get { return !string.IsNullOrWhiteSpace(HttpServer.CertificatePath); }
  822. }
  823. /// <summary>
  824. /// Gets the local ip address.
  825. /// </summary>
  826. /// <returns>System.String.</returns>
  827. private string GetLocalIpAddress()
  828. {
  829. // Return the first matched address, if found, or the first known local address
  830. var address = HttpServerIpAddresses.FirstOrDefault();
  831. if (!string.IsNullOrWhiteSpace(address))
  832. {
  833. address = string.Format("http://{0}:{1}",
  834. address,
  835. HttpPort.ToString(CultureInfo.InvariantCulture));
  836. }
  837. return address;
  838. }
  839. public IEnumerable<string> HttpServerIpAddresses
  840. {
  841. get
  842. {
  843. var localAddresses = NetworkManager.GetLocalIpAddresses()
  844. .ToList();
  845. var httpServerAddresses = HttpServer.LocalEndPoints
  846. .Select(i => i.Split(':').FirstOrDefault())
  847. .Where(i => !string.IsNullOrEmpty(i))
  848. .ToList();
  849. // Cross-check the local ip addresses with addresses that have been received on with the http server
  850. var matchedAddresses = httpServerAddresses
  851. .Where(i => localAddresses.Contains(i, StringComparer.OrdinalIgnoreCase))
  852. .ToList();
  853. if (matchedAddresses.Count == 0)
  854. {
  855. return localAddresses;
  856. }
  857. return matchedAddresses;
  858. }
  859. }
  860. public string FriendlyName
  861. {
  862. get
  863. {
  864. return string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.ServerName)
  865. ? Environment.MachineName
  866. : ServerConfigurationManager.Configuration.ServerName;
  867. }
  868. }
  869. public int HttpPort { get; private set; }
  870. public int HttpsPort { get; private set; }
  871. /// <summary>
  872. /// Gets the mac address.
  873. /// </summary>
  874. /// <returns>System.String.</returns>
  875. private string GetMacAddress()
  876. {
  877. try
  878. {
  879. return NetworkManager.GetMacAddress();
  880. }
  881. catch (Exception ex)
  882. {
  883. Logger.ErrorException("Error getting mac address", ex);
  884. return null;
  885. }
  886. }
  887. /// <summary>
  888. /// Shuts down.
  889. /// </summary>
  890. public override async Task Shutdown()
  891. {
  892. try
  893. {
  894. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  895. }
  896. catch (Exception ex)
  897. {
  898. Logger.ErrorException("Error sending server shutdown notification", ex);
  899. }
  900. NativeApp.Shutdown();
  901. }
  902. /// <summary>
  903. /// Registers the server with administrator access.
  904. /// </summary>
  905. private void RegisterServerWithAdministratorAccess()
  906. {
  907. Logger.Info("Requesting administrative access to authorize http server");
  908. try
  909. {
  910. NativeApp.AuthorizeServer(
  911. UdpServerEntryPoint.PortNumber,
  912. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  913. ServerConfigurationManager.Configuration.HttpsPortNumber,
  914. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  915. }
  916. catch (Exception ex)
  917. {
  918. Logger.ErrorException("Error authorizing server", ex);
  919. }
  920. }
  921. public event EventHandler HasUpdateAvailableChanged;
  922. private bool _hasUpdateAvailable;
  923. public bool HasUpdateAvailable
  924. {
  925. get { return _hasUpdateAvailable; }
  926. set
  927. {
  928. var fireEvent = value && !_hasUpdateAvailable;
  929. _hasUpdateAvailable = value;
  930. if (fireEvent)
  931. {
  932. EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
  933. }
  934. }
  935. }
  936. /// <summary>
  937. /// Checks for update.
  938. /// </summary>
  939. /// <param name="cancellationToken">The cancellation token.</param>
  940. /// <param name="progress">The progress.</param>
  941. /// <returns>Task{CheckForUpdateResult}.</returns>
  942. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  943. {
  944. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  945. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, _remotePackageName, null, ApplicationVersion, ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  946. var versionObject = version == null || string.IsNullOrWhiteSpace(version.versionStr) ? null : new Version(version.versionStr);
  947. var isUpdateAvailable = versionObject != null && versionObject > ApplicationVersion;
  948. var result = versionObject != null ?
  949. new CheckForUpdateResult { AvailableVersion = versionObject.ToString(), IsUpdateAvailable = isUpdateAvailable, Package = version } :
  950. new CheckForUpdateResult { AvailableVersion = ApplicationVersion.ToString(), IsUpdateAvailable = false };
  951. HasUpdateAvailable = result.IsUpdateAvailable;
  952. if (result.IsUpdateAvailable)
  953. {
  954. Logger.Info("New application version is available: {0}", result.AvailableVersion);
  955. }
  956. return result;
  957. }
  958. /// <summary>
  959. /// Updates the application.
  960. /// </summary>
  961. /// <param name="package">The package that contains the update</param>
  962. /// <param name="cancellationToken">The cancellation token.</param>
  963. /// <param name="progress">The progress.</param>
  964. /// <returns>Task.</returns>
  965. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  966. {
  967. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  968. HasUpdateAvailable = false;
  969. OnApplicationUpdated(package);
  970. }
  971. /// <summary>
  972. /// Configures the automatic run at startup.
  973. /// </summary>
  974. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  975. protected override void ConfigureAutoRunAtStartup(bool autorun)
  976. {
  977. if (SupportsAutoRunAtStartup)
  978. {
  979. NativeApp.ConfigureAutoRun(autorun);
  980. }
  981. }
  982. /// <summary>
  983. /// This returns localhost in the case of no external dns, and the hostname if the
  984. /// dns is prefixed with a valid Uri prefix.
  985. /// </summary>
  986. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  987. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  988. private static string GetHostnameFromExternalDns(string externalDns)
  989. {
  990. if (string.IsNullOrWhiteSpace(externalDns))
  991. {
  992. return "localhost";
  993. }
  994. try
  995. {
  996. Uri uri = new Uri(externalDns);
  997. return uri.Host;
  998. }
  999. catch (Exception e)
  1000. {
  1001. return externalDns;
  1002. }
  1003. }
  1004. }
  1005. }