< Summary - Jellyfin

Information
Class: Jellyfin.Api.Controllers.DisplayPreferencesController
Assembly: Jellyfin.Api
File(s): /srv/git/jellyfin/Jellyfin.Api/Controllers/DisplayPreferencesController.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 102
Coverable lines: 102
Total lines: 214
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 44
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
GetDisplayPreferences(...)0%7280%
UpdateDisplayPreferences(...)0%1332360%

File(s)

/srv/git/jellyfin/Jellyfin.Api/Controllers/DisplayPreferencesController.cs

#LineLine coverage
 1using System;
 2using System.ComponentModel.DataAnnotations;
 3using System.Diagnostics.CodeAnalysis;
 4using System.Globalization;
 5using System.Linq;
 6using Jellyfin.Api.Helpers;
 7using Jellyfin.Database.Implementations.Entities;
 8using Jellyfin.Database.Implementations.Enums;
 9using MediaBrowser.Common.Extensions;
 10using MediaBrowser.Controller;
 11using MediaBrowser.Model.Dto;
 12using Microsoft.AspNetCore.Authorization;
 13using Microsoft.AspNetCore.Http;
 14using Microsoft.AspNetCore.Mvc;
 15using Microsoft.Extensions.Logging;
 16
 17namespace Jellyfin.Api.Controllers;
 18
 19/// <summary>
 20/// Display Preferences Controller.
 21/// </summary>
 22[Authorize]
 23public class DisplayPreferencesController : BaseJellyfinApiController
 24{
 25    private readonly IDisplayPreferencesManager _displayPreferencesManager;
 26    private readonly ILogger<DisplayPreferencesController> _logger;
 27
 28    /// <summary>
 29    /// Initializes a new instance of the <see cref="DisplayPreferencesController"/> class.
 30    /// </summary>
 31    /// <param name="displayPreferencesManager">Instance of <see cref="IDisplayPreferencesManager"/> interface.</param>
 32    /// <param name="logger">Instance of <see cref="ILogger{DisplayPreferencesController}"/> interface.</param>
 033    public DisplayPreferencesController(IDisplayPreferencesManager displayPreferencesManager, ILogger<DisplayPreferences
 34    {
 035        _displayPreferencesManager = displayPreferencesManager;
 036        _logger = logger;
 037    }
 38
 39    /// <summary>
 40    /// Get Display Preferences.
 41    /// </summary>
 42    /// <param name="displayPreferencesId">Display preferences id.</param>
 43    /// <param name="userId">User id.</param>
 44    /// <param name="client">Client.</param>
 45    /// <response code="200">Display preferences retrieved.</response>
 46    /// <returns>An <see cref="OkResult"/> containing the display preferences on success, or a <see cref="NotFoundResult
 47    [HttpGet("{displayPreferencesId}")]
 48    [ProducesResponseType(StatusCodes.Status200OK)]
 49    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justi
 50    public ActionResult<DisplayPreferencesDto> GetDisplayPreferences(
 51        [FromRoute, Required] string displayPreferencesId,
 52        [FromQuery] Guid? userId,
 53        [FromQuery, Required] string client)
 54    {
 055        userId = RequestHelpers.GetUserId(User, userId);
 56
 057        if (!Guid.TryParse(displayPreferencesId, out var itemId))
 58        {
 059            itemId = displayPreferencesId.GetMD5();
 60        }
 61
 062        var displayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId.Value, itemId, client);
 063        var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(displayPreferences.UserId, itemId, di
 064        itemPreferences.ItemId = itemId;
 65
 066        var dto = new DisplayPreferencesDto
 067        {
 068            Client = displayPreferences.Client,
 069            Id = displayPreferences.ItemId.ToString(),
 070            SortBy = itemPreferences.SortBy,
 071            SortOrder = itemPreferences.SortOrder,
 072            IndexBy = displayPreferences.IndexBy?.ToString(),
 073            RememberIndexing = itemPreferences.RememberIndexing,
 074            RememberSorting = itemPreferences.RememberSorting,
 075            ScrollDirection = displayPreferences.ScrollDirection,
 076            ShowBackdrop = displayPreferences.ShowBackdrop,
 077            ShowSidebar = displayPreferences.ShowSidebar
 078        };
 79
 080        foreach (var homeSection in displayPreferences.HomeSections)
 81        {
 082            dto.CustomPrefs["homesection" + homeSection.Order] = homeSection.Type.ToString().ToLowerInvariant();
 83        }
 84
 085        dto.CustomPrefs["chromecastVersion"] = displayPreferences.ChromecastVersion.ToString().ToLowerInvariant();
 086        dto.CustomPrefs["skipForwardLength"] = displayPreferences.SkipForwardLength.ToString(CultureInfo.InvariantCultur
 087        dto.CustomPrefs["skipBackLength"] = displayPreferences.SkipBackwardLength.ToString(CultureInfo.InvariantCulture)
 088        dto.CustomPrefs["enableNextVideoInfoOverlay"] = displayPreferences.EnableNextVideoInfoOverlay.ToString(CultureIn
 089        dto.CustomPrefs["tvhome"] = displayPreferences.TvHome;
 090        dto.CustomPrefs["dashboardTheme"] = displayPreferences.DashboardTheme;
 91
 92        // Load all custom display preferences
 093        var customDisplayPreferences = _displayPreferencesManager.ListCustomItemDisplayPreferences(displayPreferences.Us
 094        foreach (var (key, value) in customDisplayPreferences)
 95        {
 096            dto.CustomPrefs.TryAdd(key, value);
 97        }
 98
 099        return dto;
 100    }
 101
 102    /// <summary>
 103    /// Update Display Preferences.
 104    /// </summary>
 105    /// <param name="displayPreferencesId">Display preferences id.</param>
 106    /// <param name="userId">User Id.</param>
 107    /// <param name="client">Client.</param>
 108    /// <param name="displayPreferences">New Display Preferences object.</param>
 109    /// <response code="204">Display preferences updated.</response>
 110    /// <returns>An <see cref="NoContentResult"/> on success.</returns>
 111    [HttpPost("{displayPreferencesId}")]
 112    [ProducesResponseType(StatusCodes.Status204NoContent)]
 113    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justi
 114    public ActionResult UpdateDisplayPreferences(
 115        [FromRoute, Required] string displayPreferencesId,
 116        [FromQuery] Guid? userId,
 117        [FromQuery, Required] string client,
 118        [FromBody, Required] DisplayPreferencesDto displayPreferences)
 119    {
 0120        userId = RequestHelpers.GetUserId(User, userId);
 121
 0122        HomeSectionType[] defaults =
 0123        {
 0124            HomeSectionType.SmallLibraryTiles,
 0125            HomeSectionType.Resume,
 0126            HomeSectionType.ResumeAudio,
 0127            HomeSectionType.ResumeBook,
 0128            HomeSectionType.LiveTv,
 0129            HomeSectionType.NextUp,
 0130            HomeSectionType.LatestMedia,
 0131            HomeSectionType.None,
 0132        };
 133
 0134        if (!Guid.TryParse(displayPreferencesId, out var itemId))
 135        {
 0136            itemId = displayPreferencesId.GetMD5();
 137        }
 138
 0139        var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId.Value, itemId, client);
 0140        existingDisplayPreferences.IndexBy = Enum.TryParse<IndexingKind>(displayPreferences.IndexBy, true, out var index
 0141        existingDisplayPreferences.ShowBackdrop = displayPreferences.ShowBackdrop;
 0142        existingDisplayPreferences.ShowSidebar = displayPreferences.ShowSidebar;
 143
 0144        existingDisplayPreferences.ScrollDirection = displayPreferences.ScrollDirection;
 0145        existingDisplayPreferences.ChromecastVersion = displayPreferences.CustomPrefs.TryGetValue("chromecastVersion", o
 0146                                                       && !string.IsNullOrEmpty(chromecastVersion)
 0147            ? Enum.Parse<ChromecastVersion>(chromecastVersion, true)
 0148            : ChromecastVersion.Stable;
 0149        displayPreferences.CustomPrefs.Remove("chromecastVersion");
 150
 0151        existingDisplayPreferences.EnableNextVideoInfoOverlay = !displayPreferences.CustomPrefs.TryGetValue("enableNextV
 0152                                                                || string.IsNullOrEmpty(enableNextVideoInfoOverlay)
 0153                                                                || bool.Parse(enableNextVideoInfoOverlay);
 0154        displayPreferences.CustomPrefs.Remove("enableNextVideoInfoOverlay");
 155
 0156        existingDisplayPreferences.SkipBackwardLength = displayPreferences.CustomPrefs.TryGetValue("skipBackLength", out
 0157                                                        && !string.IsNullOrEmpty(skipBackLength)
 0158            ? int.Parse(skipBackLength, CultureInfo.InvariantCulture)
 0159            : 10000;
 0160        displayPreferences.CustomPrefs.Remove("skipBackLength");
 161
 0162        existingDisplayPreferences.SkipForwardLength = displayPreferences.CustomPrefs.TryGetValue("skipForwardLength", o
 0163                                                       && !string.IsNullOrEmpty(skipForwardLength)
 0164            ? int.Parse(skipForwardLength, CultureInfo.InvariantCulture)
 0165            : 30000;
 0166        displayPreferences.CustomPrefs.Remove("skipForwardLength");
 167
 0168        existingDisplayPreferences.DashboardTheme = displayPreferences.CustomPrefs.TryGetValue("dashboardTheme", out var
 0169            ? theme
 0170            : string.Empty;
 0171        displayPreferences.CustomPrefs.Remove("dashboardTheme");
 172
 0173        existingDisplayPreferences.TvHome = displayPreferences.CustomPrefs.TryGetValue("tvhome", out var home)
 0174            ? home
 0175            : string.Empty;
 0176        displayPreferences.CustomPrefs.Remove("tvhome");
 177
 0178        existingDisplayPreferences.HomeSections.Clear();
 179
 0180        foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("homesection", StringCompari
 181        {
 0182            var order = int.Parse(key.AsSpan().Slice("homesection".Length), CultureInfo.InvariantCulture);
 0183            if (!Enum.TryParse<HomeSectionType>(displayPreferences.CustomPrefs[key], true, out var type))
 184            {
 0185                type = order < 8 ? defaults[order] : HomeSectionType.None;
 186            }
 187
 0188            displayPreferences.CustomPrefs.Remove(key);
 0189            existingDisplayPreferences.HomeSections.Add(new HomeSection { Order = order, Type = type });
 190        }
 191
 0192        foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison
 193        {
 0194            if (!Enum.TryParse<ViewType>(displayPreferences.CustomPrefs[key], true, out _))
 195            {
 0196                _logger.LogError("Invalid ViewType: {LandingScreenOption}", displayPreferences.CustomPrefs[key]);
 0197                displayPreferences.CustomPrefs.Remove(key);
 198            }
 199        }
 200
 0201        var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, itemId, 
 0202        itemPrefs.SortBy = displayPreferences.SortBy ?? "SortName";
 0203        itemPrefs.SortOrder = displayPreferences.SortOrder;
 0204        itemPrefs.RememberIndexing = displayPreferences.RememberIndexing;
 0205        itemPrefs.RememberSorting = displayPreferences.RememberSorting;
 0206        itemPrefs.ItemId = itemId;
 207
 208        // Set all remaining custom preferences.
 0209        _displayPreferencesManager.SetCustomItemDisplayPreferences(userId.Value, itemId, existingDisplayPreferences.Clie
 0210        _displayPreferencesManager.UpdateItemDisplayPreferences(itemPrefs);
 0211        _displayPreferencesManager.UpdateDisplayPreferences(existingDisplayPreferences);
 0212        return NoContent();
 213    }
 214}