aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/ModelBinders/LegacyDateTimeModelBinder.cs
blob: e1cb725f3e529e78f8665ab6fb36397a7e78abb9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Api.ModelBinders
{
    /// <summary>
    /// DateTime model binder.
    /// </summary>
    public class LegacyDateTimeModelBinder : IModelBinder
    {
        // Borrowed from the DateTimeModelBinderProvider
        private const DateTimeStyles SupportedStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces;
        private readonly DateTimeModelBinder _defaultModelBinder;

        /// <summary>
        /// Initializes a new instance of the <see cref="LegacyDateTimeModelBinder"/> class.
        /// </summary>
        /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
        public LegacyDateTimeModelBinder(ILoggerFactory loggerFactory)
        {
            _defaultModelBinder = new DateTimeModelBinder(SupportedStyles, loggerFactory);
        }

        /// <inheritdoc />
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (valueProviderResult.Values.Count == 1)
            {
                var dateTimeString = valueProviderResult.FirstValue;
                // Mark Played Item.
                if (DateTime.TryParseExact(dateTimeString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var dateTime))
                {
                    bindingContext.Result = ModelBindingResult.Success(dateTime);
                }
                else
                {
                    return _defaultModelBinder.BindModelAsync(bindingContext);
                }
            }

            return Task.CompletedTask;
        }
    }
}