ApplicationHost.cs 37 KB

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