| | | 1 | | using System; |
| | | 2 | | using Microsoft.OpenApi.Models; |
| | | 3 | | using Swashbuckle.AspNetCore.SwaggerGen; |
| | | 4 | | |
| | | 5 | | namespace Jellyfin.Server.Filters; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Schema filter to ensure flags enums are represented correctly in OpenAPI. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <remarks> |
| | | 11 | | /// For flags enums: |
| | | 12 | | /// - The enum schema definition is set to type "string" (not integer). |
| | | 13 | | /// - Properties using flags enums are transformed to arrays referencing the enum schema. |
| | | 14 | | /// </remarks> |
| | | 15 | | public class FlagsEnumSchemaFilter : ISchemaFilter |
| | | 16 | | { |
| | | 17 | | /// <inheritdoc /> |
| | | 18 | | public void Apply(OpenApiSchema schema, SchemaFilterContext context) |
| | | 19 | | { |
| | 5097 | 20 | | var type = context.Type.IsEnum ? context.Type : Nullable.GetUnderlyingType(context.Type); |
| | 5097 | 21 | | if (type is null || !type.IsEnum) |
| | | 22 | | { |
| | 4743 | 23 | | return; |
| | | 24 | | } |
| | | 25 | | |
| | | 26 | | // Check if enum has [Flags] attribute |
| | 354 | 27 | | if (!type.IsDefined(typeof(FlagsAttribute), false)) |
| | | 28 | | { |
| | 352 | 29 | | return; |
| | | 30 | | } |
| | | 31 | | |
| | 2 | 32 | | if (context.MemberInfo is null) |
| | | 33 | | { |
| | | 34 | | // Processing the enum definition itself - ensure it's type "string" not "integer" |
| | 1 | 35 | | schema.Type = "string"; |
| | 1 | 36 | | schema.Format = null; |
| | | 37 | | } |
| | | 38 | | else |
| | | 39 | | { |
| | | 40 | | // Processing a property that uses the flags enum - transform to array |
| | | 41 | | // Generate the enum schema to ensure it exists in the repository |
| | 1 | 42 | | var enumSchema = context.SchemaGenerator.GenerateSchema(type, context.SchemaRepository); |
| | | 43 | | |
| | | 44 | | // Flags enums should be represented as arrays referencing the enum schema |
| | | 45 | | // since multiple values can be combined |
| | 1 | 46 | | schema.Type = "array"; |
| | 1 | 47 | | schema.Format = null; |
| | 1 | 48 | | schema.Enum = null; |
| | 1 | 49 | | schema.AllOf = null; |
| | 1 | 50 | | schema.Items = enumSchema; |
| | | 51 | | } |
| | 1 | 52 | | } |
| | | 53 | | } |