jellyfin/Jellyfin.Api/Middleware/UrlDecodeQueryFeature.cs

84 lines
2.4 KiB
C#
Raw Normal View History

2021-05-12 15:19:08 +00:00
using System;
2021-05-05 21:52:39 +00:00
using System.Collections.Generic;
using System.Linq;
using Jellyfin.Extensions;
2021-05-05 21:52:39 +00:00
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Primitives;
2023-01-31 11:18:10 +00:00
namespace Jellyfin.Api.Middleware;
/// <summary>
/// Defines the <see cref="UrlDecodeQueryFeature"/>.
/// </summary>
public class UrlDecodeQueryFeature : IQueryFeature
2021-05-05 21:52:39 +00:00
{
2023-01-31 11:18:10 +00:00
private IQueryCollection? _store;
2021-05-05 21:52:39 +00:00
/// <summary>
2023-01-31 11:18:10 +00:00
/// Initializes a new instance of the <see cref="UrlDecodeQueryFeature"/> class.
2021-05-05 21:52:39 +00:00
/// </summary>
2023-01-31 11:18:10 +00:00
/// <param name="feature">The <see cref="IQueryFeature"/> instance.</param>
public UrlDecodeQueryFeature(IQueryFeature feature)
2021-05-05 21:52:39 +00:00
{
2023-01-31 11:18:10 +00:00
Query = feature.Query;
}
2021-05-05 21:52:39 +00:00
2023-01-31 11:18:10 +00:00
/// <summary>
/// Gets or sets a value indicating the url decoded <see cref="IQueryCollection"/>.
/// </summary>
public IQueryCollection Query
{
get
2021-05-05 21:52:39 +00:00
{
2023-01-31 11:18:10 +00:00
return _store ?? QueryCollection.Empty;
2021-05-05 21:52:39 +00:00
}
2023-01-31 11:18:10 +00:00
set
2021-05-05 21:52:39 +00:00
{
2023-01-31 11:18:10 +00:00
// Only interested in where the querystring is encoded which shows up as one key with nothing in the value.
if (value.Count != 1)
2021-05-05 21:52:39 +00:00
{
2023-01-31 11:18:10 +00:00
_store = value;
return;
2021-05-05 21:52:39 +00:00
}
2023-01-31 11:18:10 +00:00
// Encoded querystrings have no value, so don't process anything if a value is present.
var (key, stringValues) = value.First();
if (!string.IsNullOrEmpty(stringValues))
2021-05-05 21:52:39 +00:00
{
2023-01-31 11:18:10 +00:00
_store = value;
return;
}
2021-05-05 21:52:39 +00:00
2023-01-31 11:18:10 +00:00
if (!key.Contains('=', StringComparison.Ordinal))
{
_store = value;
return;
}
2021-05-05 21:52:39 +00:00
2023-01-31 11:18:10 +00:00
var pairs = new Dictionary<string, StringValues>();
foreach (var pair in key.SpanSplit('&'))
{
var i = pair.IndexOf('=');
if (i == -1)
2021-09-25 16:15:46 +00:00
{
2023-01-31 11:18:10 +00:00
// encoded is an equals.
// We use TryAdd so duplicate keys get ignored
pairs.TryAdd(pair.ToString(), StringValues.Empty);
continue;
2021-09-25 16:15:46 +00:00
}
2021-05-05 21:52:39 +00:00
2023-01-31 11:18:10 +00:00
var k = pair[..i].ToString();
var v = pair[(i + 1)..].ToString();
if (!pairs.TryAdd(k, new StringValues(v)))
2021-05-05 21:52:39 +00:00
{
2023-01-31 11:18:10 +00:00
pairs[k] = StringValues.Concat(pairs[k], v);
2021-05-05 21:52:39 +00:00
}
}
2023-01-31 11:18:10 +00:00
_store = new QueryCollection(pairs);
2021-05-05 21:52:39 +00:00
}
}
}