2021-11-17 08:36:23 -05:00
|
|
|
// Copyright Epic Games, Inc. All Rights Reserved.
|
|
|
|
|
|
|
|
|
|
using System;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Net.Mime;
|
2022-11-23 14:14:33 -05:00
|
|
|
using EpicGames.AspNet;
|
2021-11-17 08:36:23 -05:00
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
|
using Microsoft.Extensions.Primitives;
|
|
|
|
|
|
2022-10-12 06:36:30 -04:00
|
|
|
namespace Jupiter.Controllers
|
2021-11-17 08:36:23 -05:00
|
|
|
{
|
2023-07-27 11:20:47 -04:00
|
|
|
public class FormatResolver
|
|
|
|
|
{
|
|
|
|
|
private readonly IOptionsMonitor<MvcOptions> _mvcOptions;
|
2021-11-17 08:36:23 -05:00
|
|
|
|
2023-07-27 11:20:47 -04:00
|
|
|
private readonly string[] _validContentTypes = {
|
|
|
|
|
MediaTypeNames.Application.Octet,
|
|
|
|
|
MediaTypeNames.Application.Json,
|
|
|
|
|
CustomMediaTypeNames.UnrealCompactBinary,
|
|
|
|
|
CustomMediaTypeNames.JupiterInlinedPayload,
|
|
|
|
|
CustomMediaTypeNames.UnrealCompactBinaryPackage
|
|
|
|
|
};
|
2021-11-17 08:36:23 -05:00
|
|
|
|
2023-07-27 11:20:47 -04:00
|
|
|
public FormatResolver(IOptionsMonitor<MvcOptions> mvcOptions)
|
|
|
|
|
{
|
|
|
|
|
_mvcOptions = mvcOptions;
|
|
|
|
|
}
|
2021-11-17 08:36:23 -05:00
|
|
|
|
2023-07-27 11:20:47 -04:00
|
|
|
public string GetResponseType(HttpRequest request, string? format, string defaultContentType)
|
|
|
|
|
{
|
|
|
|
|
// if format specifier is used it takes precedence over the accept header
|
|
|
|
|
if (format != null)
|
|
|
|
|
{
|
|
|
|
|
string? typeMapping = _mvcOptions.CurrentValue.FormatterMappings.GetMediaTypeMappingForFormat(format);
|
|
|
|
|
if (typeMapping == null)
|
|
|
|
|
{
|
|
|
|
|
throw new Exception($"No mapping defined from format {format} to mime type");
|
|
|
|
|
}
|
2022-05-09 04:21:10 -04:00
|
|
|
|
2023-07-27 11:20:47 -04:00
|
|
|
return typeMapping;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
StringValues acceptHeader = request.Headers["Accept"];
|
2021-11-17 08:36:23 -05:00
|
|
|
|
2023-07-27 11:20:47 -04:00
|
|
|
if (acceptHeader.Count == 0)
|
|
|
|
|
{
|
|
|
|
|
// no accept header specified, return default type
|
|
|
|
|
return defaultContentType;
|
|
|
|
|
}
|
2021-11-17 08:36:23 -05:00
|
|
|
|
2023-07-27 11:20:47 -04:00
|
|
|
// */* means to accept anything, so we use the default content type
|
|
|
|
|
if (acceptHeader == "*/*")
|
|
|
|
|
{
|
|
|
|
|
return defaultContentType;
|
|
|
|
|
}
|
2022-03-17 05:30:32 -04:00
|
|
|
|
2023-07-27 11:20:47 -04:00
|
|
|
foreach (string header in acceptHeader)
|
|
|
|
|
{
|
|
|
|
|
if (_validContentTypes.Contains(header, StringComparer.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
return header;
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-11-17 08:36:23 -05:00
|
|
|
|
2023-07-27 11:20:47 -04:00
|
|
|
throw new Exception($"Unable to determine response type for header: {acceptHeader}");
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-11-17 08:36:23 -05:00
|
|
|
}
|