LegacyDateTimeModelBinder.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. {
  9. /// <summary>
  10. /// DateTime model binder.
  11. /// </summary>
  12. public class LegacyDateTimeModelBinder : IModelBinder
  13. {
  14. // Borrowed from the DateTimeModelBinderProvider
  15. private const DateTimeStyles SupportedStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces;
  16. private readonly DateTimeModelBinder _defaultModelBinder;
  17. /// <summary>
  18. /// Initializes a new instance of the <see cref="LegacyDateTimeModelBinder"/> class.
  19. /// </summary>
  20. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  21. public LegacyDateTimeModelBinder(ILoggerFactory loggerFactory)
  22. {
  23. _defaultModelBinder = new DateTimeModelBinder(SupportedStyles, loggerFactory);
  24. }
  25. /// <inheritdoc />
  26. public Task BindModelAsync(ModelBindingContext bindingContext)
  27. {
  28. var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  29. if (valueProviderResult.Values.Count == 1)
  30. {
  31. var dateTimeString = valueProviderResult.FirstValue;
  32. // Mark Played Item.
  33. if (DateTime.TryParseExact(dateTimeString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var dateTime))
  34. {
  35. bindingContext.Result = ModelBindingResult.Success(dateTime);
  36. }
  37. else
  38. {
  39. return _defaultModelBinder.BindModelAsync(bindingContext);
  40. }
  41. }
  42. return Task.CompletedTask;
  43. }
  44. }
  45. }