ApplicationHost.cs 37 KB

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