2020-10-01 17:56:59 +00:00
|
|
|
using System;
|
|
|
|
using System.ComponentModel;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
|
|
|
|
|
|
|
namespace Jellyfin.Api.ModelBinders
|
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// Comma delimited array model binder.
|
|
|
|
/// Returns an empty array of specified type if there is no query parameter.
|
|
|
|
/// </summary>
|
|
|
|
public class CommaDelimitedArrayModelBinder : IModelBinder
|
|
|
|
{
|
|
|
|
/// <inheritdoc/>
|
|
|
|
public Task BindModelAsync(ModelBindingContext bindingContext)
|
|
|
|
{
|
|
|
|
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
|
|
|
|
var elementType = bindingContext.ModelType.GetElementType();
|
2020-10-01 20:04:53 +00:00
|
|
|
var converter = TypeDescriptor.GetConverter(elementType);
|
2020-10-01 17:56:59 +00:00
|
|
|
|
2020-10-01 20:04:53 +00:00
|
|
|
if (valueProviderResult.Length > 1)
|
2020-10-01 17:56:59 +00:00
|
|
|
{
|
2020-10-01 20:04:53 +00:00
|
|
|
var result = Array.CreateInstance(elementType, valueProviderResult.Length);
|
2020-10-01 17:56:59 +00:00
|
|
|
|
2020-10-01 20:04:53 +00:00
|
|
|
for (int i = 0; i < valueProviderResult.Length; i++)
|
|
|
|
{
|
|
|
|
var value = converter.ConvertFromString(valueProviderResult.Values[i].Trim());
|
2020-10-01 17:56:59 +00:00
|
|
|
|
2020-10-01 20:04:53 +00:00
|
|
|
result.SetValue(value, i);
|
|
|
|
}
|
|
|
|
|
|
|
|
bindingContext.Result = ModelBindingResult.Success(result);
|
2020-10-01 17:56:59 +00:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2020-10-01 20:04:53 +00:00
|
|
|
var value = valueProviderResult.FirstValue;
|
|
|
|
|
|
|
|
if (value != null)
|
|
|
|
{
|
|
|
|
var values = Array.ConvertAll(
|
|
|
|
value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries),
|
|
|
|
x => { return converter.ConvertFromString(x != null ? x.Trim() : x); });
|
|
|
|
|
|
|
|
var typedValues = Array.CreateInstance(elementType, values.Length);
|
|
|
|
values.CopyTo(typedValues, 0);
|
|
|
|
|
|
|
|
bindingContext.Result = ModelBindingResult.Success(typedValues);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
var emptyResult = Array.CreateInstance(elementType, 0);
|
|
|
|
bindingContext.Result = ModelBindingResult.Success(emptyResult);
|
|
|
|
}
|
2020-10-01 17:56:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|