ApplicationHost.cs 35 KB

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