DisplayPreferencesController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Globalization;
  5. using System.Linq;
  6. using Jellyfin.Api.Helpers;
  7. using Jellyfin.Database.Implementations.Entities;
  8. using Jellyfin.Database.Implementations.Enums;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Controller;
  11. using MediaBrowser.Model.Dto;
  12. using Microsoft.AspNetCore.Authorization;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.AspNetCore.Mvc;
  15. using Microsoft.Extensions.Logging;
  16. namespace Jellyfin.Api.Controllers;
  17. /// <summary>
  18. /// Display Preferences Controller.
  19. /// </summary>
  20. [Authorize]
  21. public class DisplayPreferencesController : BaseJellyfinApiController
  22. {
  23. private readonly IDisplayPreferencesManager _displayPreferencesManager;
  24. private readonly ILogger<DisplayPreferencesController> _logger;
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="DisplayPreferencesController"/> class.
  27. /// </summary>
  28. /// <param name="displayPreferencesManager">Instance of <see cref="IDisplayPreferencesManager"/> interface.</param>
  29. /// <param name="logger">Instance of <see cref="ILogger{DisplayPreferencesController}"/> interface.</param>
  30. public DisplayPreferencesController(IDisplayPreferencesManager displayPreferencesManager, ILogger<DisplayPreferencesController> logger)
  31. {
  32. _displayPreferencesManager = displayPreferencesManager;
  33. _logger = logger;
  34. }
  35. /// <summary>
  36. /// Get Display Preferences.
  37. /// </summary>
  38. /// <param name="displayPreferencesId">Display preferences id.</param>
  39. /// <param name="userId">User id.</param>
  40. /// <param name="client">Client.</param>
  41. /// <response code="200">Display preferences retrieved.</response>
  42. /// <returns>An <see cref="OkResult"/> containing the display preferences on success, or a <see cref="NotFoundResult"/> if the display preferences could not be found.</returns>
  43. [HttpGet("{displayPreferencesId}")]
  44. [ProducesResponseType(StatusCodes.Status200OK)]
  45. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justification = "Imported from ServiceStack")]
  46. public ActionResult<DisplayPreferencesDto> GetDisplayPreferences(
  47. [FromRoute, Required] string displayPreferencesId,
  48. [FromQuery] Guid? userId,
  49. [FromQuery, Required] string client)
  50. {
  51. userId = RequestHelpers.GetUserId(User, userId);
  52. if (!Guid.TryParse(displayPreferencesId, out var itemId))
  53. {
  54. itemId = displayPreferencesId.GetMD5();
  55. }
  56. var displayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId.Value, itemId, client);
  57. var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client);
  58. itemPreferences.ItemId = itemId;
  59. var dto = new DisplayPreferencesDto
  60. {
  61. Client = displayPreferences.Client,
  62. Id = displayPreferences.ItemId.ToString(),
  63. SortBy = itemPreferences.SortBy,
  64. SortOrder = itemPreferences.SortOrder,
  65. IndexBy = displayPreferences.IndexBy?.ToString(),
  66. RememberIndexing = itemPreferences.RememberIndexing,
  67. RememberSorting = itemPreferences.RememberSorting,
  68. ScrollDirection = displayPreferences.ScrollDirection,
  69. ShowBackdrop = displayPreferences.ShowBackdrop,
  70. ShowSidebar = displayPreferences.ShowSidebar
  71. };
  72. foreach (var homeSection in displayPreferences.HomeSections)
  73. {
  74. dto.CustomPrefs["homesection" + homeSection.Order] = homeSection.Type.ToString().ToLowerInvariant();
  75. }
  76. dto.CustomPrefs["chromecastVersion"] = displayPreferences.ChromecastVersion.ToString().ToLowerInvariant();
  77. dto.CustomPrefs["skipForwardLength"] = displayPreferences.SkipForwardLength.ToString(CultureInfo.InvariantCulture);
  78. dto.CustomPrefs["skipBackLength"] = displayPreferences.SkipBackwardLength.ToString(CultureInfo.InvariantCulture);
  79. dto.CustomPrefs["enableNextVideoInfoOverlay"] = displayPreferences.EnableNextVideoInfoOverlay.ToString(CultureInfo.InvariantCulture);
  80. dto.CustomPrefs["tvhome"] = displayPreferences.TvHome;
  81. dto.CustomPrefs["dashboardTheme"] = displayPreferences.DashboardTheme;
  82. // Load all custom display preferences
  83. var customDisplayPreferences = _displayPreferencesManager.ListCustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client);
  84. foreach (var (key, value) in customDisplayPreferences)
  85. {
  86. dto.CustomPrefs.TryAdd(key, value);
  87. }
  88. // This will essentially be a noop if no changes have been made, but new prefs must be saved at least.
  89. _displayPreferencesManager.SaveChanges();
  90. return dto;
  91. }
  92. /// <summary>
  93. /// Update Display Preferences.
  94. /// </summary>
  95. /// <param name="displayPreferencesId">Display preferences id.</param>
  96. /// <param name="userId">User Id.</param>
  97. /// <param name="client">Client.</param>
  98. /// <param name="displayPreferences">New Display Preferences object.</param>
  99. /// <response code="204">Display preferences updated.</response>
  100. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  101. [HttpPost("{displayPreferencesId}")]
  102. [ProducesResponseType(StatusCodes.Status204NoContent)]
  103. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justification = "Imported from ServiceStack")]
  104. public ActionResult UpdateDisplayPreferences(
  105. [FromRoute, Required] string displayPreferencesId,
  106. [FromQuery] Guid? userId,
  107. [FromQuery, Required] string client,
  108. [FromBody, Required] DisplayPreferencesDto displayPreferences)
  109. {
  110. userId = RequestHelpers.GetUserId(User, userId);
  111. HomeSectionType[] defaults =
  112. {
  113. HomeSectionType.SmallLibraryTiles,
  114. HomeSectionType.Resume,
  115. HomeSectionType.ResumeAudio,
  116. HomeSectionType.ResumeBook,
  117. HomeSectionType.LiveTv,
  118. HomeSectionType.NextUp,
  119. HomeSectionType.LatestMedia,
  120. HomeSectionType.None,
  121. };
  122. if (!Guid.TryParse(displayPreferencesId, out var itemId))
  123. {
  124. itemId = displayPreferencesId.GetMD5();
  125. }
  126. var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId.Value, itemId, client);
  127. existingDisplayPreferences.IndexBy = Enum.TryParse<IndexingKind>(displayPreferences.IndexBy, true, out var indexBy) ? indexBy : null;
  128. existingDisplayPreferences.ShowBackdrop = displayPreferences.ShowBackdrop;
  129. existingDisplayPreferences.ShowSidebar = displayPreferences.ShowSidebar;
  130. existingDisplayPreferences.ScrollDirection = displayPreferences.ScrollDirection;
  131. existingDisplayPreferences.ChromecastVersion = displayPreferences.CustomPrefs.TryGetValue("chromecastVersion", out var chromecastVersion)
  132. && !string.IsNullOrEmpty(chromecastVersion)
  133. ? Enum.Parse<ChromecastVersion>(chromecastVersion, true)
  134. : ChromecastVersion.Stable;
  135. displayPreferences.CustomPrefs.Remove("chromecastVersion");
  136. existingDisplayPreferences.EnableNextVideoInfoOverlay = !displayPreferences.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enableNextVideoInfoOverlay)
  137. || string.IsNullOrEmpty(enableNextVideoInfoOverlay)
  138. || bool.Parse(enableNextVideoInfoOverlay);
  139. displayPreferences.CustomPrefs.Remove("enableNextVideoInfoOverlay");
  140. existingDisplayPreferences.SkipBackwardLength = displayPreferences.CustomPrefs.TryGetValue("skipBackLength", out var skipBackLength)
  141. && !string.IsNullOrEmpty(skipBackLength)
  142. ? int.Parse(skipBackLength, CultureInfo.InvariantCulture)
  143. : 10000;
  144. displayPreferences.CustomPrefs.Remove("skipBackLength");
  145. existingDisplayPreferences.SkipForwardLength = displayPreferences.CustomPrefs.TryGetValue("skipForwardLength", out var skipForwardLength)
  146. && !string.IsNullOrEmpty(skipForwardLength)
  147. ? int.Parse(skipForwardLength, CultureInfo.InvariantCulture)
  148. : 30000;
  149. displayPreferences.CustomPrefs.Remove("skipForwardLength");
  150. existingDisplayPreferences.DashboardTheme = displayPreferences.CustomPrefs.TryGetValue("dashboardTheme", out var theme)
  151. ? theme
  152. : string.Empty;
  153. displayPreferences.CustomPrefs.Remove("dashboardTheme");
  154. existingDisplayPreferences.TvHome = displayPreferences.CustomPrefs.TryGetValue("tvhome", out var home)
  155. ? home
  156. : string.Empty;
  157. displayPreferences.CustomPrefs.Remove("tvhome");
  158. existingDisplayPreferences.HomeSections.Clear();
  159. foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("homesection", StringComparison.OrdinalIgnoreCase)))
  160. {
  161. var order = int.Parse(key.AsSpan().Slice("homesection".Length), CultureInfo.InvariantCulture);
  162. if (!Enum.TryParse<HomeSectionType>(displayPreferences.CustomPrefs[key], true, out var type))
  163. {
  164. type = order < 8 ? defaults[order] : HomeSectionType.None;
  165. }
  166. displayPreferences.CustomPrefs.Remove(key);
  167. existingDisplayPreferences.HomeSections.Add(new HomeSection { Order = order, Type = type });
  168. }
  169. foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.OrdinalIgnoreCase)))
  170. {
  171. if (!Enum.TryParse<ViewType>(displayPreferences.CustomPrefs[key], true, out _))
  172. {
  173. _logger.LogError("Invalid ViewType: {LandingScreenOption}", displayPreferences.CustomPrefs[key]);
  174. displayPreferences.CustomPrefs.Remove(key);
  175. }
  176. }
  177. var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, itemId, existingDisplayPreferences.Client);
  178. itemPrefs.SortBy = displayPreferences.SortBy ?? "SortName";
  179. itemPrefs.SortOrder = displayPreferences.SortOrder;
  180. itemPrefs.RememberIndexing = displayPreferences.RememberIndexing;
  181. itemPrefs.RememberSorting = displayPreferences.RememberSorting;
  182. itemPrefs.ItemId = itemId;
  183. // Set all remaining custom preferences.
  184. _displayPreferencesManager.SetCustomItemDisplayPreferences(userId.Value, itemId, existingDisplayPreferences.Client, displayPreferences.CustomPrefs);
  185. _displayPreferencesManager.SaveChanges();
  186. return NoContent();
  187. }
  188. }