Startup.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. using System;
  2. using System.Globalization;
  3. using System.Net;
  4. using System.Net.Http;
  5. using System.Net.Http.Headers;
  6. using System.Net.Mime;
  7. using System.Text;
  8. using Jellyfin.Api.Middleware;
  9. using Jellyfin.MediaEncoding.Hls.Extensions;
  10. using Jellyfin.Networking.Configuration;
  11. using Jellyfin.Networking.HappyEyeballs;
  12. using Jellyfin.Server.Extensions;
  13. using Jellyfin.Server.HealthChecks;
  14. using Jellyfin.Server.Implementations;
  15. using Jellyfin.Server.Implementations.Extensions;
  16. using Jellyfin.Server.Infrastructure;
  17. using MediaBrowser.Common.Net;
  18. using MediaBrowser.Controller;
  19. using MediaBrowser.Controller.Configuration;
  20. using MediaBrowser.Controller.Extensions;
  21. using Microsoft.AspNetCore.Builder;
  22. using Microsoft.AspNetCore.Hosting;
  23. using Microsoft.AspNetCore.Mvc;
  24. using Microsoft.AspNetCore.Mvc.Infrastructure;
  25. using Microsoft.AspNetCore.StaticFiles;
  26. using Microsoft.Extensions.Configuration;
  27. using Microsoft.Extensions.DependencyInjection;
  28. using Microsoft.Extensions.FileProviders;
  29. using Microsoft.Extensions.Hosting;
  30. using Microsoft.VisualBasic;
  31. using Prometheus;
  32. namespace Jellyfin.Server
  33. {
  34. /// <summary>
  35. /// Startup configuration for the Kestrel webhost.
  36. /// </summary>
  37. public class Startup
  38. {
  39. private readonly IServerApplicationHost _serverApplicationHost;
  40. private readonly IServerConfigurationManager _serverConfigurationManager;
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="Startup" /> class.
  43. /// </summary>
  44. /// <param name="appHost">The server application host.</param>
  45. public Startup(CoreAppHost appHost)
  46. {
  47. _serverApplicationHost = appHost;
  48. _serverConfigurationManager = appHost.ConfigurationManager;
  49. }
  50. /// <summary>
  51. /// Configures the service collection for the webhost.
  52. /// </summary>
  53. /// <param name="services">The service collection.</param>
  54. public void ConfigureServices(IServiceCollection services)
  55. {
  56. services.AddResponseCompression();
  57. services.AddHttpContextAccessor();
  58. services.AddHttpsRedirection(options =>
  59. {
  60. options.HttpsPort = _serverApplicationHost.HttpsPort;
  61. });
  62. // TODO remove once this is fixed upstream https://github.com/dotnet/aspnetcore/issues/34371
  63. services.AddSingleton<IActionResultExecutor<PhysicalFileResult>, SymlinkFollowingPhysicalFileResultExecutor>();
  64. services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration());
  65. services.AddJellyfinDbContext();
  66. services.AddJellyfinApiSwagger();
  67. // configure custom legacy authentication
  68. services.AddCustomAuthentication();
  69. services.AddJellyfinApiAuthorization();
  70. var productHeader = new ProductInfoHeaderValue(
  71. _serverApplicationHost.Name.Replace(' ', '-'),
  72. _serverApplicationHost.ApplicationVersionString);
  73. var acceptJsonHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json, 1.0);
  74. var acceptXmlHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Xml, 0.9);
  75. var acceptAnyHeader = new MediaTypeWithQualityHeaderValue("*/*", 0.8);
  76. Func<IServiceProvider, HttpMessageHandler> eyeballsHttpClientHandlerDelegate = (_) => new SocketsHttpHandler()
  77. {
  78. AutomaticDecompression = DecompressionMethods.All,
  79. RequestHeaderEncodingSelector = (_, _) => Encoding.UTF8,
  80. ConnectCallback = HttpClientExtension.OnConnect
  81. };
  82. Func<IServiceProvider, HttpMessageHandler> defaultHttpClientHandlerDelegate = (_) => new SocketsHttpHandler()
  83. {
  84. AutomaticDecompression = DecompressionMethods.All,
  85. RequestHeaderEncodingSelector = (_, _) => Encoding.UTF8
  86. };
  87. services.AddHttpClient(NamedClient.Default, c =>
  88. {
  89. c.DefaultRequestHeaders.UserAgent.Add(productHeader);
  90. c.DefaultRequestHeaders.Accept.Add(acceptJsonHeader);
  91. c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader);
  92. c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader);
  93. })
  94. .ConfigurePrimaryHttpMessageHandler(eyeballsHttpClientHandlerDelegate);
  95. services.AddHttpClient(NamedClient.MusicBrainz, c =>
  96. {
  97. c.DefaultRequestHeaders.UserAgent.Add(productHeader);
  98. c.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue($"({_serverApplicationHost.ApplicationUserAgentAddress})"));
  99. c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader);
  100. c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader);
  101. })
  102. .ConfigurePrimaryHttpMessageHandler(eyeballsHttpClientHandlerDelegate);
  103. services.AddHttpClient(NamedClient.DirectIp, c =>
  104. {
  105. c.DefaultRequestHeaders.UserAgent.Add(productHeader);
  106. c.DefaultRequestHeaders.Accept.Add(acceptJsonHeader);
  107. c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader);
  108. c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader);
  109. })
  110. .ConfigurePrimaryHttpMessageHandler(defaultHttpClientHandlerDelegate);
  111. services.AddHttpClient(NamedClient.Dlna, c =>
  112. {
  113. c.DefaultRequestHeaders.UserAgent.ParseAdd(
  114. string.Format(
  115. CultureInfo.InvariantCulture,
  116. "{0}/{1} UPnP/1.0 {2}/{3}",
  117. Environment.OSVersion.Platform,
  118. Environment.OSVersion,
  119. _serverApplicationHost.Name,
  120. _serverApplicationHost.ApplicationVersionString));
  121. c.DefaultRequestHeaders.Add("CPFN.UPNP.ORG", _serverApplicationHost.FriendlyName); // Required for UPnP DeviceArchitecture v2.0
  122. c.DefaultRequestHeaders.Add("FriendlyName.DLNA.ORG", _serverApplicationHost.FriendlyName); // REVIEW: where does this come from?
  123. })
  124. .ConfigurePrimaryHttpMessageHandler(defaultHttpClientHandlerDelegate);
  125. services.AddHealthChecks()
  126. .AddCheck<DbContextFactoryHealthCheck<JellyfinDbContext>>(nameof(JellyfinDbContext));
  127. services.AddHlsPlaylistGenerator();
  128. }
  129. /// <summary>
  130. /// Configures the app builder for the webhost.
  131. /// </summary>
  132. /// <param name="app">The application builder.</param>
  133. /// <param name="env">The webhost environment.</param>
  134. /// <param name="appConfig">The application config.</param>
  135. public void Configure(
  136. IApplicationBuilder app,
  137. IWebHostEnvironment env,
  138. IConfiguration appConfig)
  139. {
  140. app.UseBaseUrlRedirection();
  141. // Wrap rest of configuration so everything only listens on BaseUrl.
  142. var config = _serverConfigurationManager.GetNetworkConfiguration();
  143. app.Map(config.BaseUrl, mainApp =>
  144. {
  145. if (env.IsDevelopment())
  146. {
  147. mainApp.UseDeveloperExceptionPage();
  148. }
  149. mainApp.UseForwardedHeaders();
  150. mainApp.UseMiddleware<ExceptionMiddleware>();
  151. mainApp.UseMiddleware<ResponseTimeMiddleware>();
  152. mainApp.UseWebSockets();
  153. mainApp.UseResponseCompression();
  154. mainApp.UseCors();
  155. if (config.RequireHttps && _serverApplicationHost.ListenWithHttps)
  156. {
  157. mainApp.UseHttpsRedirection();
  158. }
  159. // This must be injected before any path related middleware.
  160. mainApp.UsePathTrim();
  161. mainApp.UseStaticFiles();
  162. if (appConfig.HostWebClient())
  163. {
  164. var extensionProvider = new FileExtensionContentTypeProvider();
  165. // subtitles octopus requires .data, .mem files.
  166. extensionProvider.Mappings.Add(".data", MediaTypeNames.Application.Octet);
  167. extensionProvider.Mappings.Add(".mem", MediaTypeNames.Application.Octet);
  168. mainApp.UseStaticFiles(new StaticFileOptions
  169. {
  170. FileProvider = new PhysicalFileProvider(_serverConfigurationManager.ApplicationPaths.WebPath),
  171. RequestPath = "/web",
  172. ContentTypeProvider = extensionProvider
  173. });
  174. mainApp.UseRobotsRedirection();
  175. }
  176. mainApp.UseAuthentication();
  177. mainApp.UseJellyfinApiSwagger(_serverConfigurationManager);
  178. mainApp.UseQueryStringDecoding();
  179. mainApp.UseRouting();
  180. mainApp.UseAuthorization();
  181. mainApp.UseLanFiltering();
  182. mainApp.UseIPBasedAccessValidation();
  183. mainApp.UseWebSocketHandler();
  184. mainApp.UseServerStartupMessage();
  185. if (_serverConfigurationManager.Configuration.EnableMetrics)
  186. {
  187. // Must be registered after any middleware that could change HTTP response codes or the data will be bad
  188. mainApp.UseHttpMetrics();
  189. }
  190. mainApp.UseEndpoints(endpoints =>
  191. {
  192. endpoints.MapControllers();
  193. if (_serverConfigurationManager.Configuration.EnableMetrics)
  194. {
  195. endpoints.MapMetrics();
  196. }
  197. endpoints.MapHealthChecks("/health");
  198. });
  199. });
  200. }
  201. }
  202. }