FileResponseFilter.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Linq;
  3. using Jellyfin.Api.Attributes;
  4. using Microsoft.OpenApi.Models;
  5. using Swashbuckle.AspNetCore.SwaggerGen;
  6. namespace Jellyfin.Server.Filters
  7. {
  8. /// <inheritdoc />
  9. public class FileResponseFilter : IOperationFilter
  10. {
  11. private const string SuccessCode = "200";
  12. private static readonly OpenApiMediaType _openApiMediaType = new OpenApiMediaType
  13. {
  14. Schema = new OpenApiSchema
  15. {
  16. Type = "string",
  17. Format = "binary"
  18. }
  19. };
  20. /// <inheritdoc />
  21. public void Apply(OpenApiOperation operation, OperationFilterContext context)
  22. {
  23. foreach (var attribute in context.ApiDescription.ActionDescriptor.EndpointMetadata)
  24. {
  25. if (attribute is ProducesFileAttribute producesFileAttribute)
  26. {
  27. // Get operation response values.
  28. var response = operation.Responses
  29. .FirstOrDefault(o => o.Key.Equals(SuccessCode, StringComparison.Ordinal));
  30. // Operation doesn't have a response.
  31. if (response.Value is null)
  32. {
  33. continue;
  34. }
  35. // Clear existing responses.
  36. response.Value.Content.Clear();
  37. // Add all content-types as file.
  38. foreach (var contentType in producesFileAttribute.ContentTypes)
  39. {
  40. response.Value.Content.Add(contentType, _openApiMediaType);
  41. }
  42. break;
  43. }
  44. }
  45. }
  46. }
  47. }