aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server/Filters/FileResponseFilter.cs
blob: 8ea35c2818a075f70d170751c916d0c7053d2eb9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Linq;
using Jellyfin.Api.Attributes;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Jellyfin.Server.Filters
{
    /// <inheritdoc />
    public class FileResponseFilter : IOperationFilter
    {
        private const string SuccessCode = "200";
        private static readonly OpenApiMediaType _openApiMediaType = new OpenApiMediaType
        {
            Schema = new OpenApiSchema
            {
                Type = "file"
            }
        };

        /// <inheritdoc />
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            foreach (var attribute in context.ApiDescription.ActionDescriptor.EndpointMetadata)
            {
                if (attribute is ProducesFileAttribute producesFileAttribute)
                {
                    // Get operation response values.
                    var (_, value) = operation.Responses
                        .FirstOrDefault(o => o.Key.Equals(SuccessCode, StringComparison.Ordinal));

                    // Operation doesn't have a response.
                    if (value == null)
                    {
                        continue;
                    }

                    // Clear existing responses.
                    value.Content.Clear();

                    // Add all content-types as file.
                    foreach (var contentType in producesFileAttribute.GetContentTypes())
                    {
                        value.Content.Add(contentType, _openApiMediaType);
                    }

                    break;
                }
            }
        }
    }
}