ApplicationHost.cs 48 KB

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