ApplicationHost.cs 37 KB

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