ApplicationHost.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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. });
  308. }
  309. private void MigrateUserFolders()
  310. {
  311. var rootPath = ApplicationPaths.RootFolderPath;
  312. var folders = new DirectoryInfo(rootPath).EnumerateDirectories("*", SearchOption.TopDirectoryOnly).Where(i => !string.Equals(i.Name, "default", StringComparison.OrdinalIgnoreCase))
  313. .ToList();
  314. foreach (var folder in folders)
  315. {
  316. Directory.Delete(folder.FullName, true);
  317. }
  318. }
  319. /// <summary>
  320. /// Registers resources that classes will depend on
  321. /// </summary>
  322. /// <returns>Task.</returns>
  323. protected override async Task RegisterResources(IProgress<double> progress)
  324. {
  325. await base.RegisterResources(progress).ConfigureAwait(false);
  326. RegisterSingleInstance<IHttpResultFactory>(new HttpResultFactory(LogManager, FileSystemManager, JsonSerializer));
  327. RegisterSingleInstance<IServerApplicationHost>(this);
  328. RegisterSingleInstance<IServerApplicationPaths>(ApplicationPaths);
  329. RegisterSingleInstance(ServerConfigurationManager);
  330. RegisterSingleInstance<IWebSocketServer>(() => new AlchemyServer(Logger));
  331. RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer());
  332. UserDataManager = new UserDataManager(LogManager);
  333. RegisterSingleInstance(UserDataManager);
  334. UserRepository = await GetUserRepository().ConfigureAwait(false);
  335. RegisterSingleInstance(UserRepository);
  336. DisplayPreferencesRepository = new SqliteDisplayPreferencesRepository(ApplicationPaths, JsonSerializer, LogManager);
  337. RegisterSingleInstance(DisplayPreferencesRepository);
  338. ItemRepository = new SqliteItemRepository(ApplicationPaths, JsonSerializer, LogManager);
  339. RegisterSingleInstance(ItemRepository);
  340. ProviderRepository = new SqliteProviderInfoRepository(ApplicationPaths, LogManager);
  341. RegisterSingleInstance(ProviderRepository);
  342. FileOrganizationRepository = await GetFileOrganizationRepository().ConfigureAwait(false);
  343. RegisterSingleInstance(FileOrganizationRepository);
  344. UserManager = new UserManager(Logger, ServerConfigurationManager, UserRepository);
  345. RegisterSingleInstance(UserManager);
  346. LibraryManager = new LibraryManager(Logger, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager);
  347. RegisterSingleInstance(LibraryManager);
  348. LibraryMonitor = new LibraryMonitor(LogManager, TaskManager, LibraryManager, ServerConfigurationManager, FileSystemManager);
  349. RegisterSingleInstance(LibraryMonitor);
  350. ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager);
  351. RegisterSingleInstance(ProviderManager);
  352. RegisterSingleInstance<ISearchEngine>(() => new SearchEngine(LogManager, LibraryManager, UserManager));
  353. SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager);
  354. RegisterSingleInstance(SessionManager);
  355. HttpServer = ServerFactory.CreateServer(this, LogManager, "Media Browser", "mediabrowser", "dashboard/index.html");
  356. RegisterSingleInstance(HttpServer, false);
  357. progress.Report(10);
  358. ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
  359. RegisterSingleInstance(ServerManager);
  360. LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager);
  361. RegisterSingleInstance(LocalizationManager);
  362. ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer);
  363. RegisterSingleInstance(ImageProcessor);
  364. DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager);
  365. RegisterSingleInstance(DtoService);
  366. var newsService = new Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
  367. RegisterSingleInstance<INewsService>(newsService);
  368. var fileOrganizationService = new FileOrganizationService(TaskManager, FileOrganizationRepository, Logger, LibraryMonitor, LibraryManager, ServerConfigurationManager, FileSystemManager, ProviderManager);
  369. RegisterSingleInstance<IFileOrganizationService>(fileOrganizationService);
  370. progress.Report(15);
  371. var innerProgress = new ActionableProgress<double>();
  372. innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15));
  373. await RegisterMediaEncoder(innerProgress).ConfigureAwait(false);
  374. progress.Report(90);
  375. EncodingManager = new EncodingManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository,
  376. MediaEncoder);
  377. RegisterSingleInstance(EncodingManager);
  378. var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger);
  379. RegisterSingleInstance<IAppThemeManager>(appThemeManager);
  380. LiveTvManager = new LiveTvManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager);
  381. RegisterSingleInstance(LiveTvManager);
  382. var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
  383. var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
  384. var userdataTask = Task.Run(async () => await ConfigureUserDataRepositories().ConfigureAwait(false));
  385. await ConfigureNotificationsRepository().ConfigureAwait(false);
  386. progress.Report(92);
  387. await Task.WhenAll(itemsTask, displayPreferencesTask, userdataTask).ConfigureAwait(false);
  388. progress.Report(100);
  389. SetStaticProperties();
  390. await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
  391. SetKernelProperties();
  392. }
  393. protected override INetworkManager CreateNetworkManager()
  394. {
  395. return new NetworkManager();
  396. }
  397. protected override IFileSystem CreateFileSystemManager()
  398. {
  399. return FileSystemFactory.CreateFileSystemManager(LogManager);
  400. }
  401. /// <summary>
  402. /// Registers the media encoder.
  403. /// </summary>
  404. /// <returns>Task.</returns>
  405. private async Task RegisterMediaEncoder(IProgress<double> progress)
  406. {
  407. var info = await new FFMpegDownloader(Logger, ApplicationPaths, HttpClient, ZipClient, FileSystemManager).GetFFMpegInfo(progress).ConfigureAwait(false);
  408. MediaEncoder = new MediaEncoder(LogManager.GetLogger("MediaEncoder"), ApplicationPaths, JsonSerializer, info.Path, info.ProbePath, info.Version, FileSystemManager);
  409. RegisterSingleInstance(MediaEncoder);
  410. }
  411. /// <summary>
  412. /// Sets the kernel properties.
  413. /// </summary>
  414. private void SetKernelProperties()
  415. {
  416. LocalizedStrings.StringFiles = GetExports<LocalizedStringData>();
  417. }
  418. /// <summary>
  419. /// Gets the user repository.
  420. /// </summary>
  421. /// <returns>Task{IUserRepository}.</returns>
  422. private async Task<IUserRepository> GetUserRepository()
  423. {
  424. var repo = new SqliteUserRepository(JsonSerializer, LogManager, ApplicationPaths);
  425. await repo.Initialize().ConfigureAwait(false);
  426. return repo;
  427. }
  428. /// <summary>
  429. /// Gets the file organization repository.
  430. /// </summary>
  431. /// <returns>Task{IUserRepository}.</returns>
  432. private async Task<IFileOrganizationRepository> GetFileOrganizationRepository()
  433. {
  434. var repo = new SqliteFileOrganizationRepository(LogManager, ServerConfigurationManager.ApplicationPaths);
  435. await repo.Initialize().ConfigureAwait(false);
  436. return repo;
  437. }
  438. /// <summary>
  439. /// Configures the repositories.
  440. /// </summary>
  441. /// <returns>Task.</returns>
  442. private async Task ConfigureNotificationsRepository()
  443. {
  444. var repo = new SqliteNotificationsRepository(LogManager, ApplicationPaths);
  445. await repo.Initialize().ConfigureAwait(false);
  446. NotificationsRepository = repo;
  447. RegisterSingleInstance(NotificationsRepository);
  448. }
  449. /// <summary>
  450. /// Configures the repositories.
  451. /// </summary>
  452. /// <returns>Task.</returns>
  453. private async Task ConfigureDisplayPreferencesRepositories()
  454. {
  455. await DisplayPreferencesRepository.Initialize().ConfigureAwait(false);
  456. }
  457. /// <summary>
  458. /// Configures the item repositories.
  459. /// </summary>
  460. /// <returns>Task.</returns>
  461. private async Task ConfigureItemRepositories()
  462. {
  463. await ItemRepository.Initialize().ConfigureAwait(false);
  464. await ProviderRepository.Initialize().ConfigureAwait(false);
  465. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  466. }
  467. /// <summary>
  468. /// Configures the user data repositories.
  469. /// </summary>
  470. /// <returns>Task.</returns>
  471. private async Task ConfigureUserDataRepositories()
  472. {
  473. var repo = new SqliteUserDataRepository(ApplicationPaths, LogManager);
  474. await repo.Initialize().ConfigureAwait(false);
  475. ((UserDataManager)UserDataManager).Repository = repo;
  476. }
  477. /// <summary>
  478. /// Dirty hacks
  479. /// </summary>
  480. private void SetStaticProperties()
  481. {
  482. // For now there's no real way to inject these properly
  483. BaseItem.Logger = LogManager.GetLogger("BaseItem");
  484. BaseItem.ConfigurationManager = ServerConfigurationManager;
  485. BaseItem.LibraryManager = LibraryManager;
  486. BaseItem.ProviderManager = ProviderManager;
  487. BaseItem.LocalizationManager = LocalizationManager;
  488. BaseItem.ItemRepository = ItemRepository;
  489. User.XmlSerializer = XmlSerializer;
  490. User.UserManager = UserManager;
  491. LocalizedStrings.ApplicationPaths = ApplicationPaths;
  492. Folder.UserManager = UserManager;
  493. BaseItem.FileSystem = FileSystemManager;
  494. BaseItem.UserDataManager = UserDataManager;
  495. }
  496. /// <summary>
  497. /// Finds the parts.
  498. /// </summary>
  499. protected override void FindParts()
  500. {
  501. if (IsFirstRun)
  502. {
  503. RegisterServerWithAdministratorAccess();
  504. }
  505. base.FindParts();
  506. HttpServer.Init(GetExports<IRestfulService>(false));
  507. ServerManager.AddWebSocketListeners(GetExports<IWebSocketListener>(false));
  508. StartServer(true);
  509. LibraryManager.AddParts(GetExports<IResolverIgnoreRule>(),
  510. GetExports<IVirtualFolderCreator>(),
  511. GetExports<IItemResolver>(),
  512. GetExports<IIntroProvider>(),
  513. GetExports<IBaseItemComparer>(),
  514. GetExports<ILibraryPostScanTask>());
  515. ProviderManager.AddParts(GetExports<IImageProvider>(), GetExports<IMetadataService>(), GetExports<IMetadataProvider>(),
  516. GetExports<IMetadataSaver>(),
  517. GetExports<IImageSaver>(),
  518. GetExports<IExternalId>());
  519. ImageProcessor.AddParts(GetExports<IImageEnhancer>());
  520. LiveTvManager.AddParts(GetExports<ILiveTvService>());
  521. SessionManager.AddParts(GetExports<ISessionControllerFactory>());
  522. }
  523. /// <summary>
  524. /// Starts the server.
  525. /// </summary>
  526. /// <param name="retryOnFailure">if set to <c>true</c> [retry on failure].</param>
  527. private void StartServer(bool retryOnFailure)
  528. {
  529. try
  530. {
  531. ServerManager.Start(HttpServerUrlPrefixes, ServerConfigurationManager.Configuration.EnableHttpLevelLogging);
  532. }
  533. catch (Exception ex)
  534. {
  535. Logger.ErrorException("Error starting http server", ex);
  536. if (retryOnFailure)
  537. {
  538. RegisterServerWithAdministratorAccess();
  539. StartServer(false);
  540. }
  541. else
  542. {
  543. throw;
  544. }
  545. }
  546. ServerManager.StartWebSocketServer();
  547. }
  548. /// <summary>
  549. /// Called when [configuration updated].
  550. /// </summary>
  551. /// <param name="sender">The sender.</param>
  552. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  553. protected override void OnConfigurationUpdated(object sender, EventArgs e)
  554. {
  555. base.OnConfigurationUpdated(sender, e);
  556. HttpServer.EnableHttpRequestLogging = ServerConfigurationManager.Configuration.EnableHttpLevelLogging;
  557. if (!HttpServer.UrlPrefixes.SequenceEqual(HttpServerUrlPrefixes, StringComparer.OrdinalIgnoreCase))
  558. {
  559. NotifyPendingRestart();
  560. }
  561. else if (!ServerManager.SupportsNativeWebSocket && ServerManager.WebSocketPortNumber != ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber)
  562. {
  563. NotifyPendingRestart();
  564. }
  565. }
  566. /// <summary>
  567. /// Restarts this instance.
  568. /// </summary>
  569. public override async Task Restart()
  570. {
  571. if (!CanSelfRestart)
  572. {
  573. throw new InvalidOperationException("The server is unable to self-restart. Please restart manually.");
  574. }
  575. try
  576. {
  577. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  578. }
  579. catch (Exception ex)
  580. {
  581. Logger.ErrorException("Error sending server restart notification", ex);
  582. }
  583. NativeApp.Restart();
  584. }
  585. /// <summary>
  586. /// Gets or sets a value indicating whether this instance can self update.
  587. /// </summary>
  588. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  589. public override bool CanSelfUpdate
  590. {
  591. get
  592. {
  593. #if DEBUG
  594. return false;
  595. #endif
  596. return NativeApp.CanSelfUpdate;
  597. }
  598. }
  599. /// <summary>
  600. /// Gets the composable part assemblies.
  601. /// </summary>
  602. /// <returns>IEnumerable{Assembly}.</returns>
  603. protected override IEnumerable<Assembly> GetComposablePartAssemblies()
  604. {
  605. var list = GetPluginAssemblies()
  606. .ToList();
  607. // Gets all plugin assemblies by first reading all bytes of the .dll and calling Assembly.Load against that
  608. // This will prevent the .dll file from getting locked, and allow us to replace it when needed
  609. // Include composable parts in the Api assembly
  610. list.Add(typeof(ApiEntryPoint).Assembly);
  611. // Include composable parts in the Dashboard assembly
  612. list.Add(typeof(DashboardInfo).Assembly);
  613. // Include composable parts in the Model assembly
  614. list.Add(typeof(SystemInfo).Assembly);
  615. // Include composable parts in the Common assembly
  616. list.Add(typeof(IApplicationHost).Assembly);
  617. // Include composable parts in the Controller assembly
  618. list.Add(typeof(IServerApplicationHost).Assembly);
  619. // Include composable parts in the Providers assembly
  620. list.Add(typeof(ProviderUtils).Assembly);
  621. // Common implementations
  622. list.Add(typeof(TaskManager).Assembly);
  623. // Server implementations
  624. list.Add(typeof(ServerApplicationPaths).Assembly);
  625. // Dlna implementations
  626. list.Add(typeof(PlayToServerEntryPoint).Assembly);
  627. list.AddRange(Assemblies.GetAssembliesWithParts());
  628. // Include composable parts in the running assembly
  629. list.Add(GetType().Assembly);
  630. return list;
  631. }
  632. /// <summary>
  633. /// Gets the plugin assemblies.
  634. /// </summary>
  635. /// <returns>IEnumerable{Assembly}.</returns>
  636. private IEnumerable<Assembly> GetPluginAssemblies()
  637. {
  638. try
  639. {
  640. return Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.TopDirectoryOnly)
  641. .Select(LoadAssembly)
  642. .Where(a => a != null)
  643. .ToList();
  644. }
  645. catch (DirectoryNotFoundException)
  646. {
  647. return new List<Assembly>();
  648. }
  649. }
  650. private readonly string _systemId = Environment.MachineName.GetMD5().ToString();
  651. /// <summary>
  652. /// Gets the system status.
  653. /// </summary>
  654. /// <returns>SystemInfo.</returns>
  655. public virtual SystemInfo GetSystemInfo()
  656. {
  657. return new SystemInfo
  658. {
  659. HasPendingRestart = HasPendingRestart,
  660. Version = ApplicationVersion.ToString(),
  661. IsNetworkDeployed = CanSelfUpdate,
  662. WebSocketPortNumber = ServerManager.WebSocketPortNumber,
  663. SupportsNativeWebSocket = ServerManager.SupportsNativeWebSocket,
  664. FailedPluginAssemblies = FailedAssemblies.ToList(),
  665. InProgressInstallations = InstallationManager.CurrentInstallations.Select(i => i.Item1).ToList(),
  666. CompletedInstallations = InstallationManager.CompletedInstallations.ToList(),
  667. Id = _systemId,
  668. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  669. LogPath = ApplicationPaths.LogDirectoryPath,
  670. ItemsByNamePath = ApplicationPaths.ItemsByNamePath,
  671. CachePath = ApplicationPaths.CachePath,
  672. MacAddress = GetMacAddress(),
  673. HttpServerPortNumber = ServerConfigurationManager.Configuration.HttpServerPortNumber,
  674. OperatingSystem = Environment.OSVersion.ToString(),
  675. CanSelfRestart = CanSelfRestart,
  676. CanSelfUpdate = CanSelfUpdate,
  677. WanAddress = GetWanAddress(),
  678. HasUpdateAvailable = _hasUpdateAvailable,
  679. SupportsAutoRunAtStartup = SupportsAutoRunAtStartup,
  680. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  681. IsRunningAsService = IsRunningAsService
  682. };
  683. }
  684. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  685. private string GetWanAddress()
  686. {
  687. var ip = WanAddressEntryPoint.WanAddress;
  688. if (!string.IsNullOrEmpty(ip))
  689. {
  690. return "http://" + ip + ":" + ServerConfigurationManager.Configuration.HttpServerPortNumber.ToString(_usCulture);
  691. }
  692. return null;
  693. }
  694. /// <summary>
  695. /// Gets the mac address.
  696. /// </summary>
  697. /// <returns>System.String.</returns>
  698. private string GetMacAddress()
  699. {
  700. try
  701. {
  702. return NetworkManager.GetMacAddress();
  703. }
  704. catch (Exception ex)
  705. {
  706. Logger.ErrorException("Error getting mac address", ex);
  707. return null;
  708. }
  709. }
  710. /// <summary>
  711. /// Shuts down.
  712. /// </summary>
  713. public override async Task Shutdown()
  714. {
  715. try
  716. {
  717. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  718. }
  719. catch (Exception ex)
  720. {
  721. Logger.ErrorException("Error sending server shutdown notification", ex);
  722. }
  723. NativeApp.Shutdown();
  724. }
  725. /// <summary>
  726. /// Registers the server with administrator access.
  727. /// </summary>
  728. private void RegisterServerWithAdministratorAccess()
  729. {
  730. Logger.Info("Requesting administrative access to authorize http server");
  731. try
  732. {
  733. ServerAuthorization.AuthorizeServer(
  734. ServerConfigurationManager.Configuration.HttpServerPortNumber,
  735. HttpServerUrlPrefixes.First(),
  736. ServerConfigurationManager.Configuration.LegacyWebSocketPortNumber,
  737. UdpServerEntryPoint.PortNumber,
  738. ConfigurationManager.CommonApplicationPaths.TempDirectory);
  739. }
  740. catch (Exception ex)
  741. {
  742. Logger.ErrorException("Error authorizing server", ex);
  743. }
  744. }
  745. private bool _hasUpdateAvailable;
  746. /// <summary>
  747. /// Checks for update.
  748. /// </summary>
  749. /// <param name="cancellationToken">The cancellation token.</param>
  750. /// <param name="progress">The progress.</param>
  751. /// <returns>Task{CheckForUpdateResult}.</returns>
  752. public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
  753. {
  754. var availablePackages = await InstallationManager.GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);
  755. var version = InstallationManager.GetLatestCompatibleVersion(availablePackages, Constants.MbServerPkgName, null, ApplicationVersion,
  756. ConfigurationManager.CommonConfiguration.SystemUpdateLevel);
  757. _hasUpdateAvailable = version != null;
  758. return version != null ? new CheckForUpdateResult { AvailableVersion = version.version, IsUpdateAvailable = version.version > ApplicationVersion, Package = version } :
  759. new CheckForUpdateResult { AvailableVersion = ApplicationVersion, IsUpdateAvailable = false };
  760. }
  761. /// <summary>
  762. /// Updates the application.
  763. /// </summary>
  764. /// <param name="package">The package that contains the update</param>
  765. /// <param name="cancellationToken">The cancellation token.</param>
  766. /// <param name="progress">The progress.</param>
  767. /// <returns>Task.</returns>
  768. public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
  769. {
  770. await InstallationManager.InstallPackage(package, progress, cancellationToken).ConfigureAwait(false);
  771. _hasUpdateAvailable = false;
  772. OnApplicationUpdated(package.version);
  773. }
  774. /// <summary>
  775. /// Configures the automatic run at startup.
  776. /// </summary>
  777. /// <param name="autorun">if set to <c>true</c> [autorun].</param>
  778. protected override void ConfigureAutoRunAtStartup(bool autorun)
  779. {
  780. if (SupportsAutoRunAtStartup)
  781. {
  782. Autorun.Configure(autorun);
  783. }
  784. }
  785. }
  786. }