ApplicationHost.cs 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Net.Sockets;
  11. using System.Reflection;
  12. using System.Runtime.InteropServices;
  13. using System.Security.Cryptography.X509Certificates;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using Emby.Dlna;
  18. using Emby.Dlna.Main;
  19. using Emby.Dlna.Ssdp;
  20. using Emby.Drawing;
  21. using Emby.Notifications;
  22. using Emby.Photos;
  23. using Emby.Server.Implementations.Activity;
  24. using Emby.Server.Implementations.Archiving;
  25. using Emby.Server.Implementations.Channels;
  26. using Emby.Server.Implementations.Collections;
  27. using Emby.Server.Implementations.Configuration;
  28. using Emby.Server.Implementations.Cryptography;
  29. using Emby.Server.Implementations.Data;
  30. using Emby.Server.Implementations.Devices;
  31. using Emby.Server.Implementations.Diagnostics;
  32. using Emby.Server.Implementations.Dto;
  33. using Emby.Server.Implementations.HttpServer;
  34. using Emby.Server.Implementations.HttpServer.Security;
  35. using Emby.Server.Implementations.IO;
  36. using Emby.Server.Implementations.Library;
  37. using Emby.Server.Implementations.LiveTv;
  38. using Emby.Server.Implementations.Localization;
  39. using Emby.Server.Implementations.Net;
  40. using Emby.Server.Implementations.Playlists;
  41. using Emby.Server.Implementations.ScheduledTasks;
  42. using Emby.Server.Implementations.Security;
  43. using Emby.Server.Implementations.Serialization;
  44. using Emby.Server.Implementations.Session;
  45. using Emby.Server.Implementations.SocketSharp;
  46. using Emby.Server.Implementations.TV;
  47. using Emby.Server.Implementations.Updates;
  48. using MediaBrowser.Api;
  49. using MediaBrowser.Common;
  50. using MediaBrowser.Common.Configuration;
  51. using MediaBrowser.Common.Events;
  52. using MediaBrowser.Common.Extensions;
  53. using MediaBrowser.Common.Net;
  54. using MediaBrowser.Common.Plugins;
  55. using MediaBrowser.Common.Updates;
  56. using MediaBrowser.Controller;
  57. using MediaBrowser.Controller.Authentication;
  58. using MediaBrowser.Controller.Channels;
  59. using MediaBrowser.Controller.Chapters;
  60. using MediaBrowser.Controller.Collections;
  61. using MediaBrowser.Controller.Configuration;
  62. using MediaBrowser.Controller.Devices;
  63. using MediaBrowser.Controller.Dlna;
  64. using MediaBrowser.Controller.Drawing;
  65. using MediaBrowser.Controller.Dto;
  66. using MediaBrowser.Controller.Entities;
  67. using MediaBrowser.Controller.Library;
  68. using MediaBrowser.Controller.LiveTv;
  69. using MediaBrowser.Controller.MediaEncoding;
  70. using MediaBrowser.Controller.Net;
  71. using MediaBrowser.Controller.Notifications;
  72. using MediaBrowser.Controller.Persistence;
  73. using MediaBrowser.Controller.Playlists;
  74. using MediaBrowser.Controller.Plugins;
  75. using MediaBrowser.Controller.Providers;
  76. using MediaBrowser.Controller.Resolvers;
  77. using MediaBrowser.Controller.Security;
  78. using MediaBrowser.Controller.Session;
  79. using MediaBrowser.Controller.Sorting;
  80. using MediaBrowser.Controller.Subtitles;
  81. using MediaBrowser.Controller.TV;
  82. using MediaBrowser.LocalMetadata.Savers;
  83. using MediaBrowser.MediaEncoding.BdInfo;
  84. using MediaBrowser.Model.Activity;
  85. using MediaBrowser.Model.Configuration;
  86. using MediaBrowser.Model.Cryptography;
  87. using MediaBrowser.Model.Diagnostics;
  88. using MediaBrowser.Model.Dlna;
  89. using MediaBrowser.Model.Events;
  90. using MediaBrowser.Model.Extensions;
  91. using MediaBrowser.Model.Globalization;
  92. using MediaBrowser.Model.IO;
  93. using MediaBrowser.Model.MediaInfo;
  94. using MediaBrowser.Model.Net;
  95. using MediaBrowser.Model.Serialization;
  96. using MediaBrowser.Model.Services;
  97. using MediaBrowser.Model.System;
  98. using MediaBrowser.Model.Tasks;
  99. using MediaBrowser.Model.Updates;
  100. using MediaBrowser.Providers.Chapters;
  101. using MediaBrowser.Providers.Manager;
  102. using MediaBrowser.Providers.Subtitles;
  103. using MediaBrowser.Providers.TV.TheTVDB;
  104. using MediaBrowser.WebDashboard.Api;
  105. using MediaBrowser.XbmcMetadata.Providers;
  106. using Microsoft.AspNetCore.Builder;
  107. using Microsoft.AspNetCore.Hosting;
  108. using Microsoft.AspNetCore.Http;
  109. using Microsoft.AspNetCore.Http.Extensions;
  110. using Microsoft.Extensions.Configuration;
  111. using Microsoft.Extensions.DependencyInjection;
  112. using Microsoft.Extensions.DependencyInjection.Extensions;
  113. using Microsoft.Extensions.Logging;
  114. using ServiceStack;
  115. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  116. namespace Emby.Server.Implementations
  117. {
  118. /// <summary>
  119. /// Class CompositionRoot
  120. /// </summary>
  121. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  122. {
  123. private SqliteUserRepository _userRepository;
  124. private SqliteDisplayPreferencesRepository _displayPreferencesRepository;
  125. /// <summary>
  126. /// Gets a value indicating whether this instance can self restart.
  127. /// </summary>
  128. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  129. public abstract bool CanSelfRestart { get; }
  130. public virtual bool CanLaunchWebBrowser
  131. {
  132. get
  133. {
  134. if (!Environment.UserInteractive)
  135. {
  136. return false;
  137. }
  138. if (StartupOptions.IsService)
  139. {
  140. return false;
  141. }
  142. if (OperatingSystem.Id == OperatingSystemId.Windows
  143. || OperatingSystem.Id == OperatingSystemId.Darwin)
  144. {
  145. return true;
  146. }
  147. return false;
  148. }
  149. }
  150. /// <summary>
  151. /// Occurs when [has pending restart changed].
  152. /// </summary>
  153. public event EventHandler HasPendingRestartChanged;
  154. /// <summary>
  155. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  156. /// </summary>
  157. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  158. public bool HasPendingRestart { get; private set; }
  159. public bool IsShuttingDown { get; private set; }
  160. /// <summary>
  161. /// Gets or sets the logger.
  162. /// </summary>
  163. /// <value>The logger.</value>
  164. protected ILogger Logger { get; set; }
  165. private IPlugin[] _plugins;
  166. /// <summary>
  167. /// Gets the plugins.
  168. /// </summary>
  169. /// <value>The plugins.</value>
  170. public IPlugin[] Plugins
  171. {
  172. get => _plugins;
  173. protected set => _plugins = value;
  174. }
  175. /// <summary>
  176. /// Gets or sets the logger factory.
  177. /// </summary>
  178. /// <value>The logger factory.</value>
  179. public ILoggerFactory LoggerFactory { get; protected set; }
  180. /// <summary>
  181. /// Gets or sets the application paths.
  182. /// </summary>
  183. /// <value>The application paths.</value>
  184. protected ServerApplicationPaths ApplicationPaths { get; set; }
  185. /// <summary>
  186. /// Gets or sets all concrete types.
  187. /// </summary>
  188. /// <value>All concrete types.</value>
  189. private Type[] _allConcreteTypes;
  190. /// <summary>
  191. /// The disposable parts.
  192. /// </summary>
  193. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  194. /// <summary>
  195. /// Gets the configuration manager.
  196. /// </summary>
  197. /// <value>The configuration manager.</value>
  198. protected IConfigurationManager ConfigurationManager { get; set; }
  199. public IFileSystem FileSystemManager { get; set; }
  200. public PackageVersionClass SystemUpdateLevel
  201. {
  202. get
  203. {
  204. #if BETA
  205. return PackageVersionClass.Beta;
  206. #else
  207. return PackageVersionClass.Release;
  208. #endif
  209. }
  210. }
  211. protected IServiceProvider _serviceProvider;
  212. /// <summary>
  213. /// Gets the server configuration manager.
  214. /// </summary>
  215. /// <value>The server configuration manager.</value>
  216. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  217. /// <summary>
  218. /// Gets or sets the user manager.
  219. /// </summary>
  220. /// <value>The user manager.</value>
  221. public IUserManager UserManager { get; set; }
  222. /// <summary>
  223. /// Gets or sets the library manager.
  224. /// </summary>
  225. /// <value>The library manager.</value>
  226. internal ILibraryManager LibraryManager { get; set; }
  227. /// <summary>
  228. /// Gets or sets the directory watchers.
  229. /// </summary>
  230. /// <value>The directory watchers.</value>
  231. private ILibraryMonitor LibraryMonitor { get; set; }
  232. /// <summary>
  233. /// Gets or sets the provider manager.
  234. /// </summary>
  235. /// <value>The provider manager.</value>
  236. private IProviderManager ProviderManager { get; set; }
  237. /// <summary>
  238. /// Gets or sets the HTTP server.
  239. /// </summary>
  240. /// <value>The HTTP server.</value>
  241. private IHttpServer HttpServer { get; set; }
  242. private IDtoService DtoService { get; set; }
  243. public IImageProcessor ImageProcessor { get; set; }
  244. /// <summary>
  245. /// Gets or sets the media encoder.
  246. /// </summary>
  247. /// <value>The media encoder.</value>
  248. private IMediaEncoder MediaEncoder { get; set; }
  249. private ISubtitleEncoder SubtitleEncoder { get; set; }
  250. private ISessionManager SessionManager { get; set; }
  251. private ILiveTvManager LiveTvManager { get; set; }
  252. public LocalizationManager LocalizationManager { get; set; }
  253. private IEncodingManager EncodingManager { get; set; }
  254. private IChannelManager ChannelManager { get; set; }
  255. /// <summary>
  256. /// Gets or sets the user data repository.
  257. /// </summary>
  258. /// <value>The user data repository.</value>
  259. private IUserDataManager UserDataManager { get; set; }
  260. internal SqliteItemRepository ItemRepository { get; set; }
  261. private INotificationManager NotificationManager { get; set; }
  262. private ISubtitleManager SubtitleManager { get; set; }
  263. private IChapterManager ChapterManager { get; set; }
  264. private IDeviceManager DeviceManager { get; set; }
  265. internal IUserViewManager UserViewManager { get; set; }
  266. private IAuthenticationRepository AuthenticationRepository { get; set; }
  267. private ITVSeriesManager TVSeriesManager { get; set; }
  268. private ICollectionManager CollectionManager { get; set; }
  269. private IMediaSourceManager MediaSourceManager { get; set; }
  270. private readonly IConfiguration _configuration;
  271. /// <summary>
  272. /// Gets or sets the installation manager.
  273. /// </summary>
  274. /// <value>The installation manager.</value>
  275. protected IInstallationManager InstallationManager { get; private set; }
  276. protected IAuthService AuthService { get; private set; }
  277. public IStartupOptions StartupOptions { get; }
  278. internal IImageEncoder ImageEncoder { get; private set; }
  279. protected IProcessFactory ProcessFactory { get; private set; }
  280. protected readonly IXmlSerializer XmlSerializer;
  281. protected ISocketFactory SocketFactory { get; private set; }
  282. protected ITaskManager TaskManager { get; private set; }
  283. public IHttpClient HttpClient { get; private set; }
  284. protected INetworkManager NetworkManager { get; set; }
  285. public IJsonSerializer JsonSerializer { get; private set; }
  286. protected IIsoManager IsoManager { get; private set; }
  287. /// <summary>
  288. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  289. /// </summary>
  290. public ApplicationHost(
  291. ServerApplicationPaths applicationPaths,
  292. ILoggerFactory loggerFactory,
  293. IStartupOptions options,
  294. IFileSystem fileSystem,
  295. IImageEncoder imageEncoder,
  296. INetworkManager networkManager,
  297. IConfiguration configuration)
  298. {
  299. _configuration = configuration;
  300. XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory);
  301. NetworkManager = networkManager;
  302. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  303. ApplicationPaths = applicationPaths;
  304. LoggerFactory = loggerFactory;
  305. FileSystemManager = fileSystem;
  306. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
  307. Logger = LoggerFactory.CreateLogger("App");
  308. StartupOptions = options;
  309. ImageEncoder = imageEncoder;
  310. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  311. NetworkManager.NetworkChanged += OnNetworkChanged;
  312. }
  313. public string ExpandVirtualPath(string path)
  314. {
  315. var appPaths = ApplicationPaths;
  316. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  317. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  318. }
  319. public string ReverseVirtualPath(string path)
  320. {
  321. var appPaths = ApplicationPaths;
  322. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  323. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  324. }
  325. private string[] GetConfiguredLocalSubnets()
  326. {
  327. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  328. }
  329. private void OnNetworkChanged(object sender, EventArgs e)
  330. {
  331. _validAddressResults.Clear();
  332. }
  333. public string ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  334. /// <summary>
  335. /// Gets the current application user agent.
  336. /// </summary>
  337. /// <value>The application user agent.</value>
  338. public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersion;
  339. /// <summary>
  340. /// Gets the email address for use within a comment section of a user agent field.
  341. /// Presently used to provide contact information to MusicBrainz service.
  342. /// </summary>
  343. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  344. /// <summary>
  345. /// Gets the current application name.
  346. /// </summary>
  347. /// <value>The application name.</value>
  348. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  349. private DeviceId _deviceId;
  350. public string SystemId
  351. {
  352. get
  353. {
  354. if (_deviceId == null)
  355. {
  356. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  357. }
  358. return _deviceId.Value;
  359. }
  360. }
  361. /// <summary>
  362. /// Gets the name.
  363. /// </summary>
  364. /// <value>The name.</value>
  365. public string Name => ApplicationProductName;
  366. /// <summary>
  367. /// Creates an instance of type and resolves all constructor dependencies
  368. /// </summary>
  369. /// <param name="type">The type.</param>
  370. /// <returns>System.Object.</returns>
  371. public object CreateInstance(Type type)
  372. => ActivatorUtilities.CreateInstance(_serviceProvider, type);
  373. /// <summary>
  374. /// Creates an instance of type and resolves all constructor dependencies
  375. /// </summary>
  376. /// /// <typeparam name="T">The type.</typeparam>
  377. /// <returns>T.</returns>
  378. public T CreateInstance<T>()
  379. => ActivatorUtilities.CreateInstance<T>(_serviceProvider);
  380. /// <summary>
  381. /// Creates the instance safe.
  382. /// </summary>
  383. /// <param name="type">The type.</param>
  384. /// <returns>System.Object.</returns>
  385. protected object CreateInstanceSafe(Type type)
  386. {
  387. try
  388. {
  389. Logger.LogDebug("Creating instance of {Type}", type);
  390. return ActivatorUtilities.CreateInstance(_serviceProvider, type);
  391. }
  392. catch (Exception ex)
  393. {
  394. Logger.LogError(ex, "Error creating {Type}", type);
  395. return null;
  396. }
  397. }
  398. /// <summary>
  399. /// Resolves this instance.
  400. /// </summary>
  401. /// <typeparam name="T">The type</typeparam>
  402. /// <returns>``0.</returns>
  403. public T Resolve<T>() => _serviceProvider.GetService<T>();
  404. /// <summary>
  405. /// Gets the export types.
  406. /// </summary>
  407. /// <typeparam name="T">The type</typeparam>
  408. /// <returns>IEnumerable{Type}.</returns>
  409. public IEnumerable<Type> GetExportTypes<T>()
  410. {
  411. var currentType = typeof(T);
  412. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  413. }
  414. /// <inheritdoc />
  415. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  416. {
  417. var parts = GetExportTypes<T>()
  418. .Select(CreateInstanceSafe)
  419. .Where(i => i != null)
  420. .Cast<T>()
  421. .ToList(); // Convert to list so this isn't executed for each iteration
  422. if (manageLifetime)
  423. {
  424. lock (_disposableParts)
  425. {
  426. _disposableParts.AddRange(parts.OfType<IDisposable>());
  427. }
  428. }
  429. return parts;
  430. }
  431. /// <summary>
  432. /// Runs the startup tasks.
  433. /// </summary>
  434. /// <returns><see cref="Task" />.</returns>
  435. public async Task RunStartupTasksAsync()
  436. {
  437. Logger.LogInformation("Running startup tasks");
  438. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  439. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  440. MediaEncoder.SetFFmpegPath();
  441. Logger.LogInformation("ServerId: {0}", SystemId);
  442. var entryPoints = GetExports<IServerEntryPoint>();
  443. var stopWatch = new Stopwatch();
  444. stopWatch.Start();
  445. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  446. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  447. Logger.LogInformation("Core startup complete");
  448. HttpServer.GlobalResponse = null;
  449. stopWatch.Restart();
  450. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  451. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  452. stopWatch.Stop();
  453. }
  454. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  455. {
  456. foreach (var entryPoint in entryPoints)
  457. {
  458. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  459. {
  460. continue;
  461. }
  462. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  463. yield return entryPoint.RunAsync();
  464. }
  465. }
  466. public async Task InitAsync(IServiceCollection serviceCollection)
  467. {
  468. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  469. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  470. // Safeguard against invalid configuration
  471. if (HttpPort == HttpsPort)
  472. {
  473. HttpPort = ServerConfiguration.DefaultHttpPort;
  474. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  475. }
  476. JsonSerializer = new JsonSerializer(FileSystemManager);
  477. if (Plugins != null)
  478. {
  479. var pluginBuilder = new StringBuilder();
  480. foreach (var plugin in Plugins)
  481. {
  482. pluginBuilder.AppendLine(
  483. string.Format(
  484. CultureInfo.InvariantCulture,
  485. "{0} {1}",
  486. plugin.Name,
  487. plugin.Version));
  488. }
  489. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  490. }
  491. DiscoverTypes();
  492. await RegisterResources(serviceCollection).ConfigureAwait(false);
  493. FindParts();
  494. string contentRoot = ServerConfigurationManager.Configuration.DashboardSourcePath;
  495. if (string.IsNullOrEmpty(contentRoot))
  496. {
  497. contentRoot = ServerConfigurationManager.ApplicationPaths.WebPath;
  498. }
  499. var host = new WebHostBuilder()
  500. .UseKestrel(options =>
  501. {
  502. var addresses = ServerConfigurationManager
  503. .Configuration
  504. .LocalNetworkAddresses
  505. .Select(NormalizeConfiguredLocalAddress)
  506. .Where(i => i != null)
  507. .ToList();
  508. if (addresses.Any())
  509. {
  510. foreach (var address in addresses)
  511. {
  512. Logger.LogInformation("Kestrel listening on {ipaddr}", address);
  513. options.Listen(address, HttpPort);
  514. if (EnableHttps && Certificate != null)
  515. {
  516. options.Listen(address, HttpsPort, listenOptions => listenOptions.UseHttps(Certificate));
  517. }
  518. }
  519. }
  520. else
  521. {
  522. Logger.LogInformation("Kestrel listening on all interfaces");
  523. options.ListenAnyIP(HttpPort);
  524. if (EnableHttps && Certificate != null)
  525. {
  526. options.ListenAnyIP(HttpsPort, listenOptions => listenOptions.UseHttps(Certificate));
  527. }
  528. }
  529. })
  530. .UseContentRoot(contentRoot)
  531. .ConfigureServices(services =>
  532. {
  533. services.AddResponseCompression();
  534. services.AddHttpContextAccessor();
  535. })
  536. .Configure(app =>
  537. {
  538. app.UseWebSockets();
  539. app.UseResponseCompression();
  540. // TODO app.UseMiddleware<WebSocketMiddleware>();
  541. app.Use(ExecuteWebsocketHandlerAsync);
  542. app.Use(ExecuteHttpHandlerAsync);
  543. })
  544. .Build();
  545. try
  546. {
  547. await host.StartAsync().ConfigureAwait(false);
  548. }
  549. catch
  550. {
  551. Logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in system.xml and try again.");
  552. throw;
  553. }
  554. }
  555. private async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  556. {
  557. if (!context.WebSockets.IsWebSocketRequest)
  558. {
  559. await next().ConfigureAwait(false);
  560. return;
  561. }
  562. await HttpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  563. }
  564. private async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  565. {
  566. if (context.WebSockets.IsWebSocketRequest)
  567. {
  568. await next().ConfigureAwait(false);
  569. return;
  570. }
  571. var request = context.Request;
  572. var response = context.Response;
  573. var localPath = context.Request.Path.ToString();
  574. var req = new WebSocketSharpRequest(request, response, request.Path, Logger);
  575. await HttpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted).ConfigureAwait(false);
  576. }
  577. /// <summary>
  578. /// Registers resources that classes will depend on
  579. /// </summary>
  580. protected async Task RegisterResources(IServiceCollection serviceCollection)
  581. {
  582. serviceCollection.AddMemoryCache();
  583. serviceCollection.AddSingleton(ConfigurationManager);
  584. serviceCollection.AddSingleton<IApplicationHost>(this);
  585. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  586. serviceCollection.AddSingleton<IConfiguration>(_configuration);
  587. serviceCollection.AddSingleton(JsonSerializer);
  588. serviceCollection.AddSingleton(LoggerFactory);
  589. serviceCollection.AddLogging();
  590. serviceCollection.AddSingleton(Logger);
  591. serviceCollection.AddSingleton(FileSystemManager);
  592. serviceCollection.AddSingleton<TvDbClientManager>();
  593. HttpClient = new HttpClientManager.HttpClientManager(
  594. ApplicationPaths,
  595. LoggerFactory.CreateLogger<HttpClientManager.HttpClientManager>(),
  596. FileSystemManager,
  597. () => ApplicationUserAgent);
  598. serviceCollection.AddSingleton(HttpClient);
  599. serviceCollection.AddSingleton(NetworkManager);
  600. IsoManager = new IsoManager();
  601. serviceCollection.AddSingleton(IsoManager);
  602. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager);
  603. serviceCollection.AddSingleton(TaskManager);
  604. serviceCollection.AddSingleton(XmlSerializer);
  605. ProcessFactory = new ProcessFactory();
  606. serviceCollection.AddSingleton(ProcessFactory);
  607. serviceCollection.AddSingleton(typeof(IStreamHelper), typeof(StreamHelper));
  608. serviceCollection.AddSingleton(typeof(ICryptoProvider), typeof(CryptographyProvider));
  609. SocketFactory = new SocketFactory();
  610. serviceCollection.AddSingleton(SocketFactory);
  611. serviceCollection.AddSingleton(typeof(IInstallationManager), typeof(InstallationManager));
  612. serviceCollection.AddSingleton(typeof(IZipClient), typeof(ZipClient));
  613. serviceCollection.AddSingleton(typeof(IHttpResultFactory), typeof(HttpResultFactory));
  614. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  615. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  616. serviceCollection.AddSingleton(ServerConfigurationManager);
  617. LocalizationManager = new LocalizationManager(ServerConfigurationManager, JsonSerializer, LoggerFactory.CreateLogger<LocalizationManager>());
  618. await LocalizationManager.LoadAll().ConfigureAwait(false);
  619. serviceCollection.AddSingleton<ILocalizationManager>(LocalizationManager);
  620. serviceCollection.AddSingleton<IBlurayExaminer>(new BdInfoExaminer(FileSystemManager));
  621. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  622. serviceCollection.AddSingleton(UserDataManager);
  623. _displayPreferencesRepository = new SqliteDisplayPreferencesRepository(
  624. LoggerFactory.CreateLogger<SqliteDisplayPreferencesRepository>(),
  625. JsonSerializer,
  626. ApplicationPaths,
  627. FileSystemManager);
  628. serviceCollection.AddSingleton<IDisplayPreferencesRepository>(_displayPreferencesRepository);
  629. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory, LocalizationManager);
  630. serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
  631. AuthenticationRepository = GetAuthenticationRepository();
  632. serviceCollection.AddSingleton(AuthenticationRepository);
  633. _userRepository = GetUserRepository();
  634. UserManager = new UserManager(LoggerFactory.CreateLogger<UserManager>(), _userRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager);
  635. serviceCollection.AddSingleton(UserManager);
  636. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
  637. serviceCollection.AddSingleton(LibraryManager);
  638. // TODO wtaylor: investigate use of second music manager
  639. var musicManager = new MusicManager(LibraryManager);
  640. serviceCollection.AddSingleton<IMusicManager>(new MusicManager(LibraryManager));
  641. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager);
  642. serviceCollection.AddSingleton(LibraryMonitor);
  643. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  644. CertificateInfo = GetCertificateInfo(true);
  645. Certificate = GetCertificate(CertificateInfo);
  646. HttpServer = new HttpListenerHost(
  647. this,
  648. LoggerFactory.CreateLogger<HttpListenerHost>(),
  649. ServerConfigurationManager,
  650. _configuration,
  651. NetworkManager,
  652. JsonSerializer,
  653. XmlSerializer,
  654. CreateHttpListener())
  655. {
  656. GlobalResponse = LocalizationManager.GetLocalizedString("StartupEmbyServerIsLoading")
  657. };
  658. serviceCollection.AddSingleton(HttpServer);
  659. ImageProcessor = new ImageProcessor(LoggerFactory.CreateLogger<ImageProcessor>(), ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  660. serviceCollection.AddSingleton(ImageProcessor);
  661. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  662. serviceCollection.AddSingleton(TVSeriesManager);
  663. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  664. serviceCollection.AddSingleton(DeviceManager);
  665. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  666. serviceCollection.AddSingleton(MediaSourceManager);
  667. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  668. serviceCollection.AddSingleton(SubtitleManager);
  669. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  670. serviceCollection.AddSingleton(ProviderManager);
  671. DtoService = new DtoService(LoggerFactory, LibraryManager, UserDataManager, ItemRepository, ImageProcessor, ProviderManager, this, () => MediaSourceManager, () => LiveTvManager);
  672. serviceCollection.AddSingleton(DtoService);
  673. ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, ProviderManager);
  674. serviceCollection.AddSingleton(ChannelManager);
  675. SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, this, AuthenticationRepository, DeviceManager, MediaSourceManager);
  676. serviceCollection.AddSingleton(SessionManager);
  677. serviceCollection.AddSingleton<IDlnaManager>(
  678. new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LoggerFactory, JsonSerializer, this));
  679. CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
  680. serviceCollection.AddSingleton(CollectionManager);
  681. serviceCollection.AddSingleton(typeof(IPlaylistManager), typeof(PlaylistManager));
  682. LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
  683. serviceCollection.AddSingleton(LiveTvManager);
  684. UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager);
  685. serviceCollection.AddSingleton(UserViewManager);
  686. NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager);
  687. serviceCollection.AddSingleton(NotificationManager);
  688. serviceCollection.AddSingleton<IDeviceDiscovery>(
  689. new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory));
  690. ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository);
  691. serviceCollection.AddSingleton(ChapterManager);
  692. MediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  693. LoggerFactory,
  694. JsonSerializer,
  695. StartupOptions.FFmpegPath,
  696. ServerConfigurationManager,
  697. FileSystemManager,
  698. () => SubtitleEncoder,
  699. () => MediaSourceManager,
  700. ProcessFactory,
  701. 5000,
  702. LocalizationManager);
  703. serviceCollection.AddSingleton(MediaEncoder);
  704. EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager);
  705. serviceCollection.AddSingleton(EncodingManager);
  706. var activityLogRepo = GetActivityLogRepository();
  707. serviceCollection.AddSingleton(activityLogRepo);
  708. serviceCollection.AddSingleton<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager));
  709. var authContext = new AuthorizationContext(AuthenticationRepository, UserManager);
  710. serviceCollection.AddSingleton<IAuthorizationContext>(authContext);
  711. serviceCollection.AddSingleton<ISessionContext>(new SessionContext(UserManager, authContext, SessionManager));
  712. AuthService = new AuthService(authContext, ServerConfigurationManager, SessionManager, NetworkManager);
  713. serviceCollection.AddSingleton(AuthService);
  714. SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
  715. serviceCollection.AddSingleton(SubtitleEncoder);
  716. serviceCollection.AddSingleton(typeof(IResourceFileManager), typeof(ResourceFileManager));
  717. _displayPreferencesRepository.Initialize();
  718. var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths);
  719. SetStaticProperties();
  720. ((UserManager)UserManager).Initialize();
  721. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  722. ItemRepository.Initialize(userDataRepo, UserManager);
  723. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  724. _serviceProvider = serviceCollection.BuildServiceProvider();
  725. }
  726. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  727. {
  728. // Distinct these to prevent users from reporting problems that aren't actually problems
  729. var commandLineArgs = Environment
  730. .GetCommandLineArgs()
  731. .Distinct();
  732. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  733. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  734. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  735. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  736. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  737. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  738. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  739. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  740. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  741. }
  742. private X509Certificate2 GetCertificate(CertificateInfo info)
  743. {
  744. var certificateLocation = info?.Path;
  745. if (string.IsNullOrWhiteSpace(certificateLocation))
  746. {
  747. return null;
  748. }
  749. try
  750. {
  751. if (!File.Exists(certificateLocation))
  752. {
  753. return null;
  754. }
  755. // Don't use an empty string password
  756. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  757. var localCert = new X509Certificate2(certificateLocation, password);
  758. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  759. if (!localCert.HasPrivateKey)
  760. {
  761. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  762. return null;
  763. }
  764. return localCert;
  765. }
  766. catch (Exception ex)
  767. {
  768. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  769. return null;
  770. }
  771. }
  772. /// <summary>
  773. /// Gets the user repository.
  774. /// </summary>
  775. /// <returns><see cref="Task{SqliteUserRepository}" />.</returns>
  776. private SqliteUserRepository GetUserRepository()
  777. {
  778. var repo = new SqliteUserRepository(
  779. LoggerFactory.CreateLogger<SqliteUserRepository>(),
  780. ApplicationPaths,
  781. JsonSerializer);
  782. repo.Initialize();
  783. return repo;
  784. }
  785. private IAuthenticationRepository GetAuthenticationRepository()
  786. {
  787. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  788. repo.Initialize();
  789. return repo;
  790. }
  791. private IActivityRepository GetActivityLogRepository()
  792. {
  793. var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager);
  794. repo.Initialize();
  795. return repo;
  796. }
  797. /// <summary>
  798. /// Dirty hacks
  799. /// </summary>
  800. private void SetStaticProperties()
  801. {
  802. ItemRepository.ImageProcessor = ImageProcessor;
  803. // For now there's no real way to inject these properly
  804. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  805. BaseItem.ConfigurationManager = ServerConfigurationManager;
  806. BaseItem.LibraryManager = LibraryManager;
  807. BaseItem.ProviderManager = ProviderManager;
  808. BaseItem.LocalizationManager = LocalizationManager;
  809. BaseItem.ItemRepository = ItemRepository;
  810. User.UserManager = UserManager;
  811. BaseItem.FileSystem = FileSystemManager;
  812. BaseItem.UserDataManager = UserDataManager;
  813. BaseItem.ChannelManager = ChannelManager;
  814. Video.LiveTvManager = LiveTvManager;
  815. Folder.UserViewManager = UserViewManager;
  816. UserView.TVSeriesManager = TVSeriesManager;
  817. UserView.CollectionManager = CollectionManager;
  818. BaseItem.MediaSourceManager = MediaSourceManager;
  819. CollectionFolder.XmlSerializer = XmlSerializer;
  820. CollectionFolder.JsonSerializer = JsonSerializer;
  821. CollectionFolder.ApplicationHost = this;
  822. AuthenticatedAttribute.AuthService = AuthService;
  823. }
  824. private async void PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> args)
  825. {
  826. string dir = Path.Combine(ApplicationPaths.PluginsPath, args.Argument.name);
  827. var types = Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
  828. .Select(x => Assembly.LoadFrom(x))
  829. .SelectMany(x => x.ExportedTypes)
  830. .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
  831. .ToArray();
  832. int oldLen = _allConcreteTypes.Length;
  833. Array.Resize(ref _allConcreteTypes, oldLen + types.Length);
  834. types.CopyTo(_allConcreteTypes, oldLen);
  835. var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
  836. .Select(CreateInstanceSafe)
  837. .Where(x => x != null)
  838. .Cast<IPlugin>()
  839. .Select(LoadPlugin)
  840. .Where(x => x != null)
  841. .ToArray();
  842. oldLen = _plugins.Length;
  843. Array.Resize(ref _plugins, oldLen + plugins.Length);
  844. plugins.CopyTo(_plugins, oldLen);
  845. var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
  846. .Select(CreateInstanceSafe)
  847. .Where(x => x != null)
  848. .Cast<IServerEntryPoint>()
  849. .ToList();
  850. await Task.WhenAll(StartEntryPoints(entries, true)).ConfigureAwait(false);
  851. await Task.WhenAll(StartEntryPoints(entries, false)).ConfigureAwait(false);
  852. }
  853. /// <summary>
  854. /// Finds the parts.
  855. /// </summary>
  856. protected void FindParts()
  857. {
  858. InstallationManager = _serviceProvider.GetService<IInstallationManager>();
  859. InstallationManager.PluginInstalled += PluginInstalled;
  860. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  861. {
  862. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  863. ConfigurationManager.SaveConfiguration();
  864. }
  865. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  866. Plugins = GetExports<IPlugin>()
  867. .Select(LoadPlugin)
  868. .Where(i => i != null)
  869. .ToArray();
  870. HttpServer.Init(GetExports<IService>(false), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  871. LibraryManager.AddParts(
  872. GetExports<IResolverIgnoreRule>(),
  873. GetExports<IItemResolver>(),
  874. GetExports<IIntroProvider>(),
  875. GetExports<IBaseItemComparer>(),
  876. GetExports<ILibraryPostScanTask>());
  877. ProviderManager.AddParts(
  878. GetExports<IImageProvider>(),
  879. GetExports<IMetadataService>(),
  880. GetExports<IMetadataProvider>(),
  881. GetExports<IMetadataSaver>(),
  882. GetExports<IExternalId>());
  883. ImageProcessor.ImageEnhancers = GetExports<IImageEnhancer>();
  884. LiveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  885. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  886. ChannelManager.AddParts(GetExports<IChannel>());
  887. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  888. NotificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  889. UserManager.AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  890. IsoManager.AddParts(GetExports<IIsoMounter>());
  891. }
  892. private IPlugin LoadPlugin(IPlugin plugin)
  893. {
  894. try
  895. {
  896. if (plugin is IPluginAssembly assemblyPlugin)
  897. {
  898. var assembly = plugin.GetType().Assembly;
  899. var assemblyName = assembly.GetName();
  900. var assemblyFilePath = assembly.Location;
  901. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  902. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  903. try
  904. {
  905. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  906. if (idAttributes.Length > 0)
  907. {
  908. var attribute = (GuidAttribute)idAttributes[0];
  909. var assemblyId = new Guid(attribute.Value);
  910. assemblyPlugin.SetId(assemblyId);
  911. }
  912. }
  913. catch (Exception ex)
  914. {
  915. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  916. }
  917. }
  918. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  919. {
  920. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  921. }
  922. }
  923. catch (Exception ex)
  924. {
  925. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  926. return null;
  927. }
  928. return plugin;
  929. }
  930. /// <summary>
  931. /// Discovers the types.
  932. /// </summary>
  933. protected void DiscoverTypes()
  934. {
  935. Logger.LogInformation("Loading assemblies");
  936. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  937. }
  938. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  939. {
  940. foreach (var ass in assemblies)
  941. {
  942. Type[] exportedTypes;
  943. try
  944. {
  945. exportedTypes = ass.GetExportedTypes();
  946. }
  947. catch (TypeLoadException ex)
  948. {
  949. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  950. continue;
  951. }
  952. foreach (Type type in exportedTypes)
  953. {
  954. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  955. {
  956. yield return type;
  957. }
  958. }
  959. }
  960. }
  961. private CertificateInfo CertificateInfo { get; set; }
  962. protected X509Certificate2 Certificate { get; private set; }
  963. private IEnumerable<string> GetUrlPrefixes()
  964. {
  965. var hosts = new[] { "+" };
  966. return hosts.SelectMany(i =>
  967. {
  968. var prefixes = new List<string>
  969. {
  970. "http://" + i + ":" + HttpPort + "/"
  971. };
  972. if (CertificateInfo != null)
  973. {
  974. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  975. }
  976. return prefixes;
  977. });
  978. }
  979. protected IHttpListener CreateHttpListener() => new WebSocketSharpListener(Logger);
  980. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  981. {
  982. // Custom cert
  983. return new CertificateInfo
  984. {
  985. Path = ServerConfigurationManager.Configuration.CertificatePath,
  986. Password = ServerConfigurationManager.Configuration.CertificatePassword
  987. };
  988. }
  989. /// <summary>
  990. /// Called when [configuration updated].
  991. /// </summary>
  992. /// <param name="sender">The sender.</param>
  993. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  994. protected void OnConfigurationUpdated(object sender, EventArgs e)
  995. {
  996. var requiresRestart = false;
  997. // Don't do anything if these haven't been set yet
  998. if (HttpPort != 0 && HttpsPort != 0)
  999. {
  1000. // Need to restart if ports have changed
  1001. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  1002. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  1003. {
  1004. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  1005. {
  1006. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  1007. ServerConfigurationManager.SaveConfiguration();
  1008. requiresRestart = true;
  1009. }
  1010. }
  1011. }
  1012. if (!HttpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  1013. {
  1014. requiresRestart = true;
  1015. }
  1016. var currentCertPath = CertificateInfo?.Path;
  1017. var newCertInfo = GetCertificateInfo(false);
  1018. var newCertPath = newCertInfo?.Path;
  1019. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  1020. {
  1021. requiresRestart = true;
  1022. }
  1023. if (requiresRestart)
  1024. {
  1025. Logger.LogInformation("App needs to be restarted due to configuration change.");
  1026. NotifyPendingRestart();
  1027. }
  1028. }
  1029. /// <summary>
  1030. /// Notifies that the kernel that a change has been made that requires a restart
  1031. /// </summary>
  1032. public void NotifyPendingRestart()
  1033. {
  1034. Logger.LogInformation("App needs to be restarted.");
  1035. var changed = !HasPendingRestart;
  1036. HasPendingRestart = true;
  1037. if (changed)
  1038. {
  1039. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  1040. }
  1041. }
  1042. /// <summary>
  1043. /// Restarts this instance.
  1044. /// </summary>
  1045. public void Restart()
  1046. {
  1047. if (!CanSelfRestart)
  1048. {
  1049. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  1050. }
  1051. if (IsShuttingDown)
  1052. {
  1053. return;
  1054. }
  1055. IsShuttingDown = true;
  1056. Task.Run(async () =>
  1057. {
  1058. try
  1059. {
  1060. await SessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  1061. }
  1062. catch (Exception ex)
  1063. {
  1064. Logger.LogError(ex, "Error sending server restart notification");
  1065. }
  1066. Logger.LogInformation("Calling RestartInternal");
  1067. RestartInternal();
  1068. });
  1069. }
  1070. protected abstract void RestartInternal();
  1071. /// <summary>
  1072. /// Gets the composable part assemblies.
  1073. /// </summary>
  1074. /// <returns>IEnumerable{Assembly}.</returns>
  1075. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  1076. {
  1077. if (Directory.Exists(ApplicationPaths.PluginsPath))
  1078. {
  1079. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  1080. {
  1081. Assembly plugAss;
  1082. try
  1083. {
  1084. plugAss = Assembly.LoadFrom(file);
  1085. }
  1086. catch (FileLoadException ex)
  1087. {
  1088. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  1089. continue;
  1090. }
  1091. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  1092. yield return plugAss;
  1093. }
  1094. }
  1095. // Include composable parts in the Api assembly
  1096. yield return typeof(ApiEntryPoint).Assembly;
  1097. // Include composable parts in the Dashboard assembly
  1098. yield return typeof(DashboardService).Assembly;
  1099. // Include composable parts in the Model assembly
  1100. yield return typeof(SystemInfo).Assembly;
  1101. // Include composable parts in the Common assembly
  1102. yield return typeof(IApplicationHost).Assembly;
  1103. // Include composable parts in the Controller assembly
  1104. yield return typeof(IServerApplicationHost).Assembly;
  1105. // Include composable parts in the Providers assembly
  1106. yield return typeof(ProviderUtils).Assembly;
  1107. // Include composable parts in the Photos assembly
  1108. yield return typeof(PhotoProvider).Assembly;
  1109. // Emby.Server implementations
  1110. yield return typeof(InstallationManager).Assembly;
  1111. // MediaEncoding
  1112. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  1113. // Dlna
  1114. yield return typeof(DlnaEntryPoint).Assembly;
  1115. // Local metadata
  1116. yield return typeof(BoxSetXmlSaver).Assembly;
  1117. // Notifications
  1118. yield return typeof(NotificationManager).Assembly;
  1119. // Xbmc
  1120. yield return typeof(ArtistNfoProvider).Assembly;
  1121. foreach (var i in GetAssembliesWithPartsInternal())
  1122. {
  1123. yield return i;
  1124. }
  1125. }
  1126. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1127. /// <summary>
  1128. /// Gets the system status.
  1129. /// </summary>
  1130. /// <param name="cancellationToken">The cancellation token</param>
  1131. /// <returns>SystemInfo.</returns>
  1132. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1133. {
  1134. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1135. return new SystemInfo
  1136. {
  1137. HasPendingRestart = HasPendingRestart,
  1138. IsShuttingDown = IsShuttingDown,
  1139. Version = ApplicationVersion,
  1140. WebSocketPortNumber = HttpPort,
  1141. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1142. Id = SystemId,
  1143. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1144. WebPath = ApplicationPaths.WebPath,
  1145. LogPath = ApplicationPaths.LogDirectoryPath,
  1146. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1147. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1148. CachePath = ApplicationPaths.CachePath,
  1149. HttpServerPortNumber = HttpPort,
  1150. SupportsHttps = SupportsHttps,
  1151. HttpsPortNumber = HttpsPort,
  1152. OperatingSystem = OperatingSystem.Id.ToString(),
  1153. OperatingSystemDisplayName = OperatingSystem.Name,
  1154. CanSelfRestart = CanSelfRestart,
  1155. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1156. HasUpdateAvailable = HasUpdateAvailable,
  1157. TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
  1158. ServerName = FriendlyName,
  1159. LocalAddress = localAddress,
  1160. SupportsLibraryMonitor = true,
  1161. EncoderLocation = MediaEncoder.EncoderLocation,
  1162. SystemArchitecture = RuntimeInformation.OSArchitecture,
  1163. SystemUpdateLevel = SystemUpdateLevel,
  1164. PackageName = StartupOptions.PackageName
  1165. };
  1166. }
  1167. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1168. => NetworkManager.GetMacAddresses()
  1169. .Select(i => new WakeOnLanInfo(i))
  1170. .ToList();
  1171. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1172. {
  1173. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1174. return new PublicSystemInfo
  1175. {
  1176. Version = ApplicationVersion,
  1177. ProductName = ApplicationProductName,
  1178. Id = SystemId,
  1179. OperatingSystem = OperatingSystem.Id.ToString(),
  1180. ServerName = FriendlyName,
  1181. LocalAddress = localAddress
  1182. };
  1183. }
  1184. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1185. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1186. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1187. {
  1188. try
  1189. {
  1190. // Return the first matched address, if found, or the first known local address
  1191. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1192. foreach (var address in addresses)
  1193. {
  1194. return GetLocalApiUrl(address);
  1195. }
  1196. return null;
  1197. }
  1198. catch (Exception ex)
  1199. {
  1200. Logger.LogError(ex, "Error getting local Ip address information");
  1201. }
  1202. return null;
  1203. }
  1204. /// <summary>
  1205. /// Removes the scope id from IPv6 addresses.
  1206. /// </summary>
  1207. /// <param name="address">The IPv6 address.</param>
  1208. /// <returns>The IPv6 address without the scope id.</returns>
  1209. private string RemoveScopeId(string address)
  1210. {
  1211. var index = address.IndexOf('%');
  1212. if (index == -1)
  1213. {
  1214. return address;
  1215. }
  1216. return address.Substring(0, index);
  1217. }
  1218. public string GetLocalApiUrl(IPAddress ipAddress)
  1219. {
  1220. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1221. {
  1222. var str = RemoveScopeId(ipAddress.ToString());
  1223. return GetLocalApiUrl("[" + str + "]");
  1224. }
  1225. return GetLocalApiUrl(ipAddress.ToString());
  1226. }
  1227. public string GetLocalApiUrl(string host)
  1228. {
  1229. if (EnableHttps)
  1230. {
  1231. return string.Format("https://{0}:{1}",
  1232. host,
  1233. HttpsPort.ToString(CultureInfo.InvariantCulture));
  1234. }
  1235. return string.Format("http://{0}:{1}",
  1236. host,
  1237. HttpPort.ToString(CultureInfo.InvariantCulture));
  1238. }
  1239. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1240. {
  1241. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1242. }
  1243. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1244. {
  1245. var addresses = ServerConfigurationManager
  1246. .Configuration
  1247. .LocalNetworkAddresses
  1248. .Select(NormalizeConfiguredLocalAddress)
  1249. .Where(i => i != null)
  1250. .ToList();
  1251. if (addresses.Count == 0)
  1252. {
  1253. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1254. }
  1255. var resultList = new List<IPAddress>();
  1256. foreach (var address in addresses)
  1257. {
  1258. if (!allowLoopback)
  1259. {
  1260. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1261. {
  1262. continue;
  1263. }
  1264. }
  1265. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1266. if (valid)
  1267. {
  1268. resultList.Add(address);
  1269. if (limit > 0 && resultList.Count >= limit)
  1270. {
  1271. return resultList;
  1272. }
  1273. }
  1274. }
  1275. return resultList;
  1276. }
  1277. private IPAddress NormalizeConfiguredLocalAddress(string address)
  1278. {
  1279. var index = address.Trim('/').IndexOf('/');
  1280. if (index != -1)
  1281. {
  1282. address = address.Substring(index + 1);
  1283. }
  1284. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1285. {
  1286. return result;
  1287. }
  1288. return null;
  1289. }
  1290. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1291. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1292. {
  1293. if (address.Equals(IPAddress.Loopback)
  1294. || address.Equals(IPAddress.IPv6Loopback))
  1295. {
  1296. return true;
  1297. }
  1298. var apiUrl = GetLocalApiUrl(address);
  1299. apiUrl += "/system/ping";
  1300. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1301. {
  1302. return cachedResult;
  1303. }
  1304. try
  1305. {
  1306. using (var response = await HttpClient.SendAsync(
  1307. new HttpRequestOptions
  1308. {
  1309. Url = apiUrl,
  1310. LogErrorResponseBody = false,
  1311. BufferContent = false,
  1312. CancellationToken = cancellationToken
  1313. }, HttpMethod.Post).ConfigureAwait(false))
  1314. {
  1315. using (var reader = new StreamReader(response.Content))
  1316. {
  1317. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1318. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1319. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1320. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1321. return valid;
  1322. }
  1323. }
  1324. }
  1325. catch (OperationCanceledException)
  1326. {
  1327. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1328. throw;
  1329. }
  1330. catch (Exception ex)
  1331. {
  1332. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1333. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1334. return false;
  1335. }
  1336. }
  1337. public string FriendlyName =>
  1338. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1339. ? Environment.MachineName
  1340. : ServerConfigurationManager.Configuration.ServerName;
  1341. public int HttpPort { get; private set; }
  1342. public int HttpsPort { get; private set; }
  1343. /// <summary>
  1344. /// Shuts down.
  1345. /// </summary>
  1346. public async Task Shutdown()
  1347. {
  1348. if (IsShuttingDown)
  1349. {
  1350. return;
  1351. }
  1352. IsShuttingDown = true;
  1353. try
  1354. {
  1355. await SessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1356. }
  1357. catch (Exception ex)
  1358. {
  1359. Logger.LogError(ex, "Error sending server shutdown notification");
  1360. }
  1361. ShutdownInternal();
  1362. }
  1363. protected abstract void ShutdownInternal();
  1364. public event EventHandler HasUpdateAvailableChanged;
  1365. private bool _hasUpdateAvailable;
  1366. public bool HasUpdateAvailable
  1367. {
  1368. get => _hasUpdateAvailable;
  1369. set
  1370. {
  1371. var fireEvent = value && !_hasUpdateAvailable;
  1372. _hasUpdateAvailable = value;
  1373. if (fireEvent)
  1374. {
  1375. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1376. }
  1377. }
  1378. }
  1379. /// <summary>
  1380. /// Removes the plugin.
  1381. /// </summary>
  1382. /// <param name="plugin">The plugin.</param>
  1383. public void RemovePlugin(IPlugin plugin)
  1384. {
  1385. var list = Plugins.ToList();
  1386. list.Remove(plugin);
  1387. Plugins = list.ToArray();
  1388. }
  1389. /// <summary>
  1390. /// This returns localhost in the case of no external dns, and the hostname if the
  1391. /// dns is prefixed with a valid Uri prefix.
  1392. /// </summary>
  1393. /// <param name="externalDns">The external dns prefix to get the hostname of.</param>
  1394. /// <returns>The hostname in <paramref name="externalDns"/></returns>
  1395. private static string GetHostnameFromExternalDns(string externalDns)
  1396. {
  1397. if (string.IsNullOrEmpty(externalDns))
  1398. {
  1399. return "localhost";
  1400. }
  1401. try
  1402. {
  1403. return new Uri(externalDns).Host;
  1404. }
  1405. catch
  1406. {
  1407. return externalDns;
  1408. }
  1409. }
  1410. public virtual void LaunchUrl(string url)
  1411. {
  1412. if (!CanLaunchWebBrowser)
  1413. {
  1414. throw new NotSupportedException();
  1415. }
  1416. var process = ProcessFactory.Create(new ProcessOptions
  1417. {
  1418. FileName = url,
  1419. EnableRaisingEvents = true,
  1420. UseShellExecute = true,
  1421. ErrorDialog = false
  1422. });
  1423. process.Exited += ProcessExited;
  1424. try
  1425. {
  1426. process.Start();
  1427. }
  1428. catch (Exception ex)
  1429. {
  1430. Logger.LogError(ex, "Error launching url: {url}", url);
  1431. throw;
  1432. }
  1433. }
  1434. private static void ProcessExited(object sender, EventArgs e)
  1435. {
  1436. ((IProcess)sender).Dispose();
  1437. }
  1438. public virtual void EnableLoopback(string appName)
  1439. {
  1440. }
  1441. private bool _disposed = false;
  1442. /// <summary>
  1443. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1444. /// </summary>
  1445. public void Dispose()
  1446. {
  1447. Dispose(true);
  1448. GC.SuppressFinalize(this);
  1449. }
  1450. /// <summary>
  1451. /// Releases unmanaged and - optionally - managed resources.
  1452. /// </summary>
  1453. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1454. protected virtual void Dispose(bool dispose)
  1455. {
  1456. if (_disposed)
  1457. {
  1458. return;
  1459. }
  1460. if (dispose)
  1461. {
  1462. var type = GetType();
  1463. Logger.LogInformation("Disposing {Type}", type.Name);
  1464. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1465. _disposableParts.Clear();
  1466. foreach (var part in parts)
  1467. {
  1468. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1469. try
  1470. {
  1471. part.Dispose();
  1472. }
  1473. catch (Exception ex)
  1474. {
  1475. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1476. }
  1477. }
  1478. _userRepository?.Dispose();
  1479. _displayPreferencesRepository.Dispose();
  1480. }
  1481. _userRepository = null;
  1482. _displayPreferencesRepository = null;
  1483. _disposed = true;
  1484. }
  1485. }
  1486. internal class CertificateInfo
  1487. {
  1488. public string Path { get; set; }
  1489. public string Password { get; set; }
  1490. }
  1491. }