< 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: 217
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.Data.Entities;
 8using Jellyfin.Data.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
 99        // This will essentially be a noop if no changes have been made, but new prefs must be saved at least.
 0100        _displayPreferencesManager.SaveChanges();
 101
 0102        return dto;
 103    }
 104
 105    /// <summary>
 106    /// Update Display Preferences.
 107    /// </summary>
 108    /// <param name="displayPreferencesId">Display preferences id.</param>
 109    /// <param name="userId">User Id.</param>
 110    /// <param name="client">Client.</param>
 111    /// <param name="displayPreferences">New Display Preferences object.</param>
 112    /// <response code="204">Display preferences updated.</response>
 113    /// <returns>An <see cref="NoContentResult"/> on success.</returns>
 114    [HttpPost("{displayPreferencesId}")]
 115    [ProducesResponseType(StatusCodes.Status204NoContent)]
 116    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justi
 117    public ActionResult UpdateDisplayPreferences(
 118        [FromRoute, Required] string displayPreferencesId,
 119        [FromQuery] Guid? userId,
 120        [FromQuery, Required] string client,
 121        [FromBody, Required] DisplayPreferencesDto displayPreferences)
 122    {
 0123        userId = RequestHelpers.GetUserId(User, userId);
 124
 0125        HomeSectionType[] defaults =
 0126        {
 0127            HomeSectionType.SmallLibraryTiles,
 0128            HomeSectionType.Resume,
 0129            HomeSectionType.ResumeAudio,
 0130            HomeSectionType.ResumeBook,
 0131            HomeSectionType.LiveTv,
 0132            HomeSectionType.NextUp,
 0133            HomeSectionType.LatestMedia,
 0134            HomeSectionType.None,
 0135        };
 136
 0137        if (!Guid.TryParse(displayPreferencesId, out var itemId))
 138        {
 0139            itemId = displayPreferencesId.GetMD5();
 140        }
 141
 0142        var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId.Value, itemId, client);
 0143        existingDisplayPreferences.IndexBy = Enum.TryParse<IndexingKind>(displayPreferences.IndexBy, true, out var index
 0144        existingDisplayPreferences.ShowBackdrop = displayPreferences.ShowBackdrop;
 0145        existingDisplayPreferences.ShowSidebar = displayPreferences.ShowSidebar;
 146
 0147        existingDisplayPreferences.ScrollDirection = displayPreferences.ScrollDirection;
 0148        existingDisplayPreferences.ChromecastVersion = displayPreferences.CustomPrefs.TryGetValue("chromecastVersion", o
 0149                                                       && !string.IsNullOrEmpty(chromecastVersion)
 0150            ? Enum.Parse<ChromecastVersion>(chromecastVersion, true)
 0151            : ChromecastVersion.Stable;
 0152        displayPreferences.CustomPrefs.Remove("chromecastVersion");
 153
 0154        existingDisplayPreferences.EnableNextVideoInfoOverlay = !displayPreferences.CustomPrefs.TryGetValue("enableNextV
 0155                                                                || string.IsNullOrEmpty(enableNextVideoInfoOverlay)
 0156                                                                || bool.Parse(enableNextVideoInfoOverlay);
 0157        displayPreferences.CustomPrefs.Remove("enableNextVideoInfoOverlay");
 158
 0159        existingDisplayPreferences.SkipBackwardLength = displayPreferences.CustomPrefs.TryGetValue("skipBackLength", out
 0160                                                        && !string.IsNullOrEmpty(skipBackLength)
 0161            ? int.Parse(skipBackLength, CultureInfo.InvariantCulture)
 0162            : 10000;
 0163        displayPreferences.CustomPrefs.Remove("skipBackLength");
 164
 0165        existingDisplayPreferences.SkipForwardLength = displayPreferences.CustomPrefs.TryGetValue("skipForwardLength", o
 0166                                                       && !string.IsNullOrEmpty(skipForwardLength)
 0167            ? int.Parse(skipForwardLength, CultureInfo.InvariantCulture)
 0168            : 30000;
 0169        displayPreferences.CustomPrefs.Remove("skipForwardLength");
 170
 0171        existingDisplayPreferences.DashboardTheme = displayPreferences.CustomPrefs.TryGetValue("dashboardTheme", out var
 0172            ? theme
 0173            : string.Empty;
 0174        displayPreferences.CustomPrefs.Remove("dashboardTheme");
 175
 0176        existingDisplayPreferences.TvHome = displayPreferences.CustomPrefs.TryGetValue("tvhome", out var home)
 0177            ? home
 0178            : string.Empty;
 0179        displayPreferences.CustomPrefs.Remove("tvhome");
 180
 0181        existingDisplayPreferences.HomeSections.Clear();
 182
 0183        foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("homesection", StringCompari
 184        {
 0185            var order = int.Parse(key.AsSpan().Slice("homesection".Length), CultureInfo.InvariantCulture);
 0186            if (!Enum.TryParse<HomeSectionType>(displayPreferences.CustomPrefs[key], true, out var type))
 187            {
 0188                type = order < 8 ? defaults[order] : HomeSectionType.None;
 189            }
 190
 0191            displayPreferences.CustomPrefs.Remove(key);
 0192            existingDisplayPreferences.HomeSections.Add(new HomeSection { Order = order, Type = type });
 193        }
 194
 0195        foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison
 196        {
 0197            if (!Enum.TryParse<ViewType>(displayPreferences.CustomPrefs[key], true, out _))
 198            {
 0199                _logger.LogError("Invalid ViewType: {LandingScreenOption}", displayPreferences.CustomPrefs[key]);
 0200                displayPreferences.CustomPrefs.Remove(key);
 201            }
 202        }
 203
 0204        var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, itemId, 
 0205        itemPrefs.SortBy = displayPreferences.SortBy ?? "SortName";
 0206        itemPrefs.SortOrder = displayPreferences.SortOrder;
 0207        itemPrefs.RememberIndexing = displayPreferences.RememberIndexing;
 0208        itemPrefs.RememberSorting = displayPreferences.RememberSorting;
 0209        itemPrefs.ItemId = itemId;
 210
 211        // Set all remaining custom preferences.
 0212        _displayPreferencesManager.SetCustomItemDisplayPreferences(userId.Value, itemId, existingDisplayPreferences.Clie
 0213        _displayPreferencesManager.SaveChanges();
 214
 0215        return NoContent();
 216    }
 217}