ApplicationHost.cs 48 KB

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