ApplicationHost.cs 36 KB

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