ApiApplicationBuilderExtensions.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Collections.Generic;
  2. using MediaBrowser.Controller.Configuration;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.OpenApi.Models;
  5. namespace Jellyfin.Server.Extensions
  6. {
  7. /// <summary>
  8. /// Extensions for adding API specific functionality to the application pipeline.
  9. /// </summary>
  10. public static class ApiApplicationBuilderExtensions
  11. {
  12. /// <summary>
  13. /// Adds swagger and swagger UI to the application pipeline.
  14. /// </summary>
  15. /// <param name="applicationBuilder">The application builder.</param>
  16. /// <param name="serverConfigurationManager">The server configuration.</param>
  17. /// <returns>The updated application builder.</returns>
  18. public static IApplicationBuilder UseJellyfinApiSwagger(
  19. this IApplicationBuilder applicationBuilder,
  20. IServerConfigurationManager serverConfigurationManager)
  21. {
  22. // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
  23. // specifying the Swagger JSON endpoint.
  24. var baseUrl = serverConfigurationManager.Configuration.BaseUrl.Trim('/');
  25. var apiDocBaseUrl = serverConfigurationManager.Configuration.BaseUrl;
  26. if (!string.IsNullOrEmpty(baseUrl))
  27. {
  28. baseUrl += '/';
  29. }
  30. return applicationBuilder
  31. .UseSwagger(c =>
  32. {
  33. // Custom path requires {documentName}, SwaggerDoc documentName is 'api-docs'
  34. c.RouteTemplate = $"/{baseUrl}{{documentName}}/openapi.json";
  35. c.PreSerializeFilters.Add((swagger, httpReq) =>
  36. {
  37. swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{apiDocBaseUrl}" } };
  38. // BaseUrl is empty, ignore
  39. if (apiDocBaseUrl.Length != 0)
  40. {
  41. // Update all relative paths to remove baseUrl.
  42. var updatedPaths = new OpenApiPaths();
  43. foreach (var (key, value) in swagger.Paths)
  44. {
  45. var relativePath = key;
  46. relativePath = relativePath.Remove(0, apiDocBaseUrl.Length);
  47. updatedPaths.Add(relativePath, value);
  48. }
  49. swagger.Paths = updatedPaths;
  50. }
  51. });
  52. })
  53. .UseSwaggerUI(c =>
  54. {
  55. c.DocumentTitle = "Jellyfin API";
  56. c.SwaggerEndpoint($"/{baseUrl}api-docs/openapi.json", "Jellyfin API");
  57. c.RoutePrefix = $"{baseUrl}api-docs/swagger";
  58. })
  59. .UseReDoc(c =>
  60. {
  61. c.DocumentTitle = "Jellyfin API";
  62. c.SpecUrl($"/{baseUrl}api-docs/openapi.json");
  63. c.RoutePrefix = $"{baseUrl}api-docs/redoc";
  64. });
  65. }
  66. }
  67. }