2
0

UrlDecodeQueryFeature.cs 2.7 KB

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