ApplicationHost.cs 60 KB

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