LegacyDateTimeModelBinder.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Globalization;
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Mvc.ModelBinding;
  5. using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
  6. using Microsoft.Extensions.Logging;
  7. namespace Jellyfin.Api.ModelBinders;
  8. /// <summary>
  9. /// DateTime model binder.
  10. /// </summary>
  11. public class LegacyDateTimeModelBinder : IModelBinder
  12. {
  13. // Borrowed from the DateTimeModelBinderProvider
  14. private const DateTimeStyles SupportedStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces;
  15. private readonly DateTimeModelBinder _defaultModelBinder;
  16. /// <summary>
  17. /// Initializes a new instance of the <see cref="LegacyDateTimeModelBinder"/> class.
  18. /// </summary>
  19. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  20. public LegacyDateTimeModelBinder(ILoggerFactory loggerFactory)
  21. {
  22. _defaultModelBinder = new DateTimeModelBinder(SupportedStyles, loggerFactory);
  23. }
  24. /// <inheritdoc />
  25. public Task BindModelAsync(ModelBindingContext bindingContext)
  26. {
  27. var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  28. if (valueProviderResult.Values.Count == 1)
  29. {
  30. var dateTimeString = valueProviderResult.FirstValue;
  31. // Mark Played Item.
  32. if (DateTime.TryParseExact(dateTimeString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var dateTime))
  33. {
  34. bindingContext.Result = ModelBindingResult.Success(dateTime);
  35. }
  36. else
  37. {
  38. return _defaultModelBinder.BindModelAsync(bindingContext);
  39. }
  40. }
  41. return Task.CompletedTask;
  42. }
  43. }