ApplicationHost.cs 35 KB

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