ApplicationHost.cs 37 KB

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