aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server/Filters/AdditionalModelFilter.cs
blob: 58d37db5a59df199929326567b5b17e25a348116 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Jellyfin.Extensions;
using Jellyfin.Server.Migrations;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Net.WebSocketMessages;
using MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.SyncPlay;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Jellyfin.Server.Filters
{
    /// <summary>
    /// Add models not directly used by the API, but used for discovery and websockets.
    /// </summary>
    public class AdditionalModelFilter : IDocumentFilter
    {
        // Array of options that should not be visible in the api spec.
        private static readonly Type[] _ignoredConfigurations = { typeof(MigrationOptions), typeof(MediaBrowser.Model.Branding.BrandingOptions) };
        private readonly IServerConfigurationManager _serverConfigurationManager;

        /// <summary>
        /// Initializes a new instance of the <see cref="AdditionalModelFilter"/> class.
        /// </summary>
        /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
        public AdditionalModelFilter(IServerConfigurationManager serverConfigurationManager)
        {
            _serverConfigurationManager = serverConfigurationManager;
        }

        /// <inheritdoc />
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            context.SchemaGenerator.GenerateSchema(typeof(IPlugin), context.SchemaRepository);

            var webSocketTypes = typeof(WebSocketMessage).Assembly.GetTypes()
                .Where(t => t.IsSubclassOf(typeof(WebSocketMessage))
                            && !t.IsGenericType
                            && t != typeof(WebSocketMessageInfo))
                .ToList();

            var inboundWebSocketSchemas = new List<OpenApiSchema>();
            var inboundWebSocketDiscriminators = new Dictionary<string, string>();
            foreach (var type in webSocketTypes.Where(t => typeof(IInboundWebSocketMessage).IsAssignableFrom(t)))
            {
                var messageType = (SessionMessageType?)type.GetProperty(nameof(WebSocketMessage.MessageType))?.GetCustomAttribute<DefaultValueAttribute>()?.Value;
                if (messageType is null)
                {
                    continue;
                }

                var schema = context.SchemaGenerator.GenerateSchema(type, context.SchemaRepository);
                inboundWebSocketSchemas.Add(schema);
                inboundWebSocketDiscriminators[messageType.ToString()!] = schema.Reference.ReferenceV3;
            }

            var inboundWebSocketMessageSchema = new OpenApiSchema
            {
                Type = "object",
                Description = "Represents the list of possible inbound websocket types",
                Reference = new OpenApiReference
                {
                    Id = nameof(InboundWebSocketMessage),
                    Type = ReferenceType.Schema
                },
                OneOf = inboundWebSocketSchemas,
                Discriminator = new OpenApiDiscriminator
                {
                    PropertyName = nameof(WebSocketMessage.MessageType),
                    Mapping = inboundWebSocketDiscriminators
                }
            };

            context.SchemaRepository.AddDefinition(nameof(InboundWebSocketMessage), inboundWebSocketMessageSchema);

            var outboundWebSocketSchemas = new List<OpenApiSchema>();
            var outboundWebSocketDiscriminators = new Dictionary<string, string>();
            foreach (var type in webSocketTypes.Where(t => typeof(IOutboundWebSocketMessage).IsAssignableFrom(t)))
            {
                var messageType = (SessionMessageType?)type.GetProperty(nameof(WebSocketMessage.MessageType))?.GetCustomAttribute<DefaultValueAttribute>()?.Value;
                if (messageType is null)
                {
                    continue;
                }

                var schema = context.SchemaGenerator.GenerateSchema(type, context.SchemaRepository);
                outboundWebSocketSchemas.Add(schema);
                outboundWebSocketDiscriminators.Add(messageType.ToString()!, schema.Reference.ReferenceV3);
            }

            // Add custom "SyncPlayGroupUpdateMessage" schema because Swashbuckle cannot generate it for us
            var syncPlayGroupUpdateMessageSchema = new OpenApiSchema
            {
                Type = "object",
                Description = "Untyped sync play command.",
                Properties = new Dictionary<string, OpenApiSchema>
                {
                    {
                        "Data", new OpenApiSchema
                        {
                            AllOf =
                            [
                                new OpenApiSchema { Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = nameof(GroupUpdate<object>) } }
                            ],
                            Description = "Group update data",
                            Nullable = false,
                        }
                    },
                    { "MessageId", new OpenApiSchema { Type = "string", Format = "uuid", Description = "Gets or sets the message id." } },
                    {
                        "MessageType", new OpenApiSchema
                        {
                            Enum = Enum.GetValues<SessionMessageType>().Select(type => new OpenApiString(type.ToString())).ToList<IOpenApiAny>(),
                            AllOf =
                            [
                                new OpenApiSchema { Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = nameof(SessionMessageType) } }
                            ],
                            Description = "The different kinds of messages that are used in the WebSocket api.",
                            Default = new OpenApiString(nameof(SessionMessageType.SyncPlayGroupUpdate)),
                            ReadOnly = true
                        }
                    },
                },
                AdditionalPropertiesAllowed = false,
                Reference = new OpenApiReference { Type = ReferenceType.Schema, Id = "SyncPlayGroupUpdateMessage" }
            };
            context.SchemaRepository.AddDefinition("SyncPlayGroupUpdateMessage", syncPlayGroupUpdateMessageSchema);
            outboundWebSocketSchemas.Add(syncPlayGroupUpdateMessageSchema);
            outboundWebSocketDiscriminators[nameof(SessionMessageType.SyncPlayGroupUpdate)] = syncPlayGroupUpdateMessageSchema.Reference.ReferenceV3;

            var outboundWebSocketMessageSchema = new OpenApiSchema
            {
                Type = "object",
                Description = "Represents the list of possible outbound websocket types",
                Reference = new OpenApiReference
                {
                    Id = nameof(OutboundWebSocketMessage),
                    Type = ReferenceType.Schema
                },
                OneOf = outboundWebSocketSchemas,
                Discriminator = new OpenApiDiscriminator
                {
                    PropertyName = nameof(WebSocketMessage.MessageType),
                    Mapping = outboundWebSocketDiscriminators
                }
            };

            context.SchemaRepository.AddDefinition(nameof(OutboundWebSocketMessage), outboundWebSocketMessageSchema);
            context.SchemaRepository.AddDefinition(
                nameof(WebSocketMessage),
                new OpenApiSchema
                {
                    Type = "object",
                    Description = "Represents the possible websocket types",
                    Reference = new OpenApiReference
                    {
                        Id = nameof(WebSocketMessage),
                        Type = ReferenceType.Schema
                    },
                    OneOf = new[]
                    {
                        inboundWebSocketMessageSchema,
                        outboundWebSocketMessageSchema
                    }
                });

            // Manually generate sync play GroupUpdate messages.
            var groupUpdateTypes = typeof(GroupUpdate<>).Assembly.GetTypes()
                .Where(t => t.BaseType is not null
                            && t.BaseType.IsGenericType
                            && t.BaseType.GetGenericTypeDefinition() == typeof(GroupUpdate<>))
                .ToList();

            var groupUpdateSchemas = new List<OpenApiSchema>();
            var groupUpdateDiscriminators = new Dictionary<string, string>();
            foreach (var type in groupUpdateTypes)
            {
                var groupUpdateType = (GroupUpdateType?)type.GetProperty(nameof(GroupUpdate<object>.Type))?.GetCustomAttribute<DefaultValueAttribute>()?.Value;
                if (groupUpdateType is null)
                {
                    continue;
                }

                var schema = context.SchemaGenerator.GenerateSchema(type, context.SchemaRepository);
                groupUpdateSchemas.Add(schema);
                groupUpdateDiscriminators[groupUpdateType.ToString()!] = schema.Reference.ReferenceV3;
            }

            var groupUpdateSchema = new OpenApiSchema
            {
                Type = "object",
                Description = "Represents the list of possible group update types",
                Reference = new OpenApiReference
                {
                    Id = nameof(GroupUpdate<object>),
                    Type = ReferenceType.Schema
                },
                OneOf = groupUpdateSchemas,
                Discriminator = new OpenApiDiscriminator
                {
                    PropertyName = nameof(GroupUpdate<object>.Type),
                    Mapping = groupUpdateDiscriminators
                }
            };

            context.SchemaRepository.Schemas[nameof(GroupUpdate<object>)] = groupUpdateSchema;

            context.SchemaGenerator.GenerateSchema(typeof(ServerDiscoveryInfo), context.SchemaRepository);

            foreach (var configuration in _serverConfigurationManager.GetConfigurationStores())
            {
                if (_ignoredConfigurations.IndexOf(configuration.ConfigurationType) != -1)
                {
                    continue;
                }

                context.SchemaGenerator.GenerateSchema(configuration.ConfigurationType, context.SchemaRepository);
            }

            context.SchemaRepository.AddDefinition(nameof(TranscodeReason), new OpenApiSchema
            {
                Type = "string",
                Enum = Enum.GetNames<TranscodeReason>()
                    .Select(e => new OpenApiString(e))
                    .Cast<IOpenApiAny>()
                    .ToArray()
            });
        }
    }
}