2
0

UrlDecodeQueryFeature.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Jellyfin.Extensions;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Http.Features;
  7. using Microsoft.Extensions.Primitives;
  8. namespace Jellyfin.Api.Middleware;
  9. /// <summary>
  10. /// Defines the <see cref="UrlDecodeQueryFeature"/>.
  11. /// </summary>
  12. public class UrlDecodeQueryFeature : IQueryFeature
  13. {
  14. private IQueryCollection? _store;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="UrlDecodeQueryFeature"/> class.
  17. /// </summary>
  18. /// <param name="feature">The <see cref="IQueryFeature"/> instance.</param>
  19. public UrlDecodeQueryFeature(IQueryFeature feature)
  20. {
  21. Query = feature.Query;
  22. }
  23. /// <summary>
  24. /// Gets or sets a value indicating the url decoded <see cref="IQueryCollection"/>.
  25. /// </summary>
  26. public IQueryCollection Query
  27. {
  28. get
  29. {
  30. return _store ?? QueryCollection.Empty;
  31. }
  32. set
  33. {
  34. // Only interested in where the querystring is encoded which shows up as one key with nothing in the value.
  35. if (value.Count != 1)
  36. {
  37. _store = value;
  38. return;
  39. }
  40. // Encoded querystrings have no value, so don't process anything if a value is present.
  41. var (key, stringValues) = value.First();
  42. if (!string.IsNullOrEmpty(stringValues))
  43. {
  44. _store = value;
  45. return;
  46. }
  47. if (!key.Contains('=', StringComparison.Ordinal))
  48. {
  49. _store = value;
  50. return;
  51. }
  52. var pairs = new Dictionary<string, StringValues>();
  53. foreach (var pair in key.SpanSplit('&'))
  54. {
  55. var i = pair.IndexOf('=');
  56. if (i == -1)
  57. {
  58. // encoded is an equals.
  59. // We use TryAdd so duplicate keys get ignored
  60. pairs.TryAdd(pair.ToString(), StringValues.Empty);
  61. continue;
  62. }
  63. var k = pair[..i].ToString();
  64. var v = pair[(i + 1)..].ToString();
  65. if (!pairs.TryAdd(k, new StringValues(v)))
  66. {
  67. pairs[k] = StringValues.Concat(pairs[k], v);
  68. }
  69. }
  70. _store = new QueryCollection(pairs);
  71. }
  72. }
  73. }