DisplayPreferencesController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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.Constants;
  7. using Jellyfin.Data.Entities;
  8. using Jellyfin.Data.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(Policy = Policies.DefaultAuthorization)]
  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, Required] Guid userId,
  49. [FromQuery, Required] string client)
  50. {
  51. if (!Guid.TryParse(displayPreferencesId, out var itemId))
  52. {
  53. itemId = displayPreferencesId.GetMD5();
  54. }
  55. var displayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, itemId, client);
  56. var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client);
  57. itemPreferences.ItemId = itemId;
  58. var dto = new DisplayPreferencesDto
  59. {
  60. Client = displayPreferences.Client,
  61. Id = displayPreferences.ItemId.ToString(),
  62. SortBy = itemPreferences.SortBy,
  63. SortOrder = itemPreferences.SortOrder,
  64. IndexBy = displayPreferences.IndexBy?.ToString(),
  65. RememberIndexing = itemPreferences.RememberIndexing,
  66. RememberSorting = itemPreferences.RememberSorting,
  67. ScrollDirection = displayPreferences.ScrollDirection,
  68. ShowBackdrop = displayPreferences.ShowBackdrop,
  69. ShowSidebar = displayPreferences.ShowSidebar
  70. };
  71. foreach (var homeSection in displayPreferences.HomeSections)
  72. {
  73. dto.CustomPrefs["homesection" + homeSection.Order] = homeSection.Type.ToString().ToLowerInvariant();
  74. }
  75. dto.CustomPrefs["chromecastVersion"] = displayPreferences.ChromecastVersion.ToString().ToLowerInvariant();
  76. dto.CustomPrefs["skipForwardLength"] = displayPreferences.SkipForwardLength.ToString(CultureInfo.InvariantCulture);
  77. dto.CustomPrefs["skipBackLength"] = displayPreferences.SkipBackwardLength.ToString(CultureInfo.InvariantCulture);
  78. dto.CustomPrefs["enableNextVideoInfoOverlay"] = displayPreferences.EnableNextVideoInfoOverlay.ToString(CultureInfo.InvariantCulture);
  79. dto.CustomPrefs["tvhome"] = displayPreferences.TvHome;
  80. dto.CustomPrefs["dashboardTheme"] = displayPreferences.DashboardTheme;
  81. // Load all custom display preferences
  82. var customDisplayPreferences = _displayPreferencesManager.ListCustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client);
  83. foreach (var (key, value) in customDisplayPreferences)
  84. {
  85. dto.CustomPrefs.TryAdd(key, value);
  86. }
  87. // This will essentially be a noop if no changes have been made, but new prefs must be saved at least.
  88. _displayPreferencesManager.SaveChanges();
  89. return dto;
  90. }
  91. /// <summary>
  92. /// Update Display Preferences.
  93. /// </summary>
  94. /// <param name="displayPreferencesId">Display preferences id.</param>
  95. /// <param name="userId">User Id.</param>
  96. /// <param name="client">Client.</param>
  97. /// <param name="displayPreferences">New Display Preferences object.</param>
  98. /// <response code="204">Display preferences updated.</response>
  99. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  100. [HttpPost("{displayPreferencesId}")]
  101. [ProducesResponseType(StatusCodes.Status204NoContent)]
  102. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justification = "Imported from ServiceStack")]
  103. public ActionResult UpdateDisplayPreferences(
  104. [FromRoute, Required] string displayPreferencesId,
  105. [FromQuery, Required] Guid userId,
  106. [FromQuery, Required] string client,
  107. [FromBody, Required] DisplayPreferencesDto displayPreferences)
  108. {
  109. HomeSectionType[] defaults =
  110. {
  111. HomeSectionType.SmallLibraryTiles,
  112. HomeSectionType.Resume,
  113. HomeSectionType.ResumeAudio,
  114. HomeSectionType.ResumeBook,
  115. HomeSectionType.LiveTv,
  116. HomeSectionType.NextUp,
  117. HomeSectionType.LatestMedia,
  118. HomeSectionType.None,
  119. };
  120. if (!Guid.TryParse(displayPreferencesId, out var itemId))
  121. {
  122. itemId = displayPreferencesId.GetMD5();
  123. }
  124. var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, itemId, client);
  125. existingDisplayPreferences.IndexBy = Enum.TryParse<IndexingKind>(displayPreferences.IndexBy, true, out var indexBy) ? indexBy : null;
  126. existingDisplayPreferences.ShowBackdrop = displayPreferences.ShowBackdrop;
  127. existingDisplayPreferences.ShowSidebar = displayPreferences.ShowSidebar;
  128. existingDisplayPreferences.ScrollDirection = displayPreferences.ScrollDirection;
  129. existingDisplayPreferences.ChromecastVersion = displayPreferences.CustomPrefs.TryGetValue("chromecastVersion", out var chromecastVersion)
  130. && !string.IsNullOrEmpty(chromecastVersion)
  131. ? Enum.Parse<ChromecastVersion>(chromecastVersion, true)
  132. : ChromecastVersion.Stable;
  133. displayPreferences.CustomPrefs.Remove("chromecastVersion");
  134. existingDisplayPreferences.EnableNextVideoInfoOverlay = !displayPreferences.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enableNextVideoInfoOverlay)
  135. || string.IsNullOrEmpty(enableNextVideoInfoOverlay)
  136. || bool.Parse(enableNextVideoInfoOverlay);
  137. displayPreferences.CustomPrefs.Remove("enableNextVideoInfoOverlay");
  138. existingDisplayPreferences.SkipBackwardLength = displayPreferences.CustomPrefs.TryGetValue("skipBackLength", out var skipBackLength)
  139. && !string.IsNullOrEmpty(skipBackLength)
  140. ? int.Parse(skipBackLength, CultureInfo.InvariantCulture)
  141. : 10000;
  142. displayPreferences.CustomPrefs.Remove("skipBackLength");
  143. existingDisplayPreferences.SkipForwardLength = displayPreferences.CustomPrefs.TryGetValue("skipForwardLength", out var skipForwardLength)
  144. && !string.IsNullOrEmpty(skipForwardLength)
  145. ? int.Parse(skipForwardLength, CultureInfo.InvariantCulture)
  146. : 30000;
  147. displayPreferences.CustomPrefs.Remove("skipForwardLength");
  148. existingDisplayPreferences.DashboardTheme = displayPreferences.CustomPrefs.TryGetValue("dashboardTheme", out var theme)
  149. ? theme
  150. : string.Empty;
  151. displayPreferences.CustomPrefs.Remove("dashboardTheme");
  152. existingDisplayPreferences.TvHome = displayPreferences.CustomPrefs.TryGetValue("tvhome", out var home)
  153. ? home
  154. : string.Empty;
  155. displayPreferences.CustomPrefs.Remove("tvhome");
  156. existingDisplayPreferences.HomeSections.Clear();
  157. foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("homesection", StringComparison.OrdinalIgnoreCase)))
  158. {
  159. var order = int.Parse(key.AsSpan().Slice("homesection".Length), CultureInfo.InvariantCulture);
  160. if (!Enum.TryParse<HomeSectionType>(displayPreferences.CustomPrefs[key], true, out var type))
  161. {
  162. type = order < 8 ? defaults[order] : HomeSectionType.None;
  163. }
  164. displayPreferences.CustomPrefs.Remove(key);
  165. existingDisplayPreferences.HomeSections.Add(new HomeSection { Order = order, Type = type });
  166. }
  167. foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.OrdinalIgnoreCase)))
  168. {
  169. if (!Enum.TryParse<ViewType>(displayPreferences.CustomPrefs[key], true, out var type))
  170. {
  171. _logger.LogError("Invalid ViewType: {LandingScreenOption}", displayPreferences.CustomPrefs[key]);
  172. displayPreferences.CustomPrefs.Remove(key);
  173. }
  174. }
  175. var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, itemId, existingDisplayPreferences.Client);
  176. itemPrefs.SortBy = displayPreferences.SortBy ?? "SortName";
  177. itemPrefs.SortOrder = displayPreferences.SortOrder;
  178. itemPrefs.RememberIndexing = displayPreferences.RememberIndexing;
  179. itemPrefs.RememberSorting = displayPreferences.RememberSorting;
  180. itemPrefs.ItemId = itemId;
  181. // Set all remaining custom preferences.
  182. _displayPreferencesManager.SetCustomItemDisplayPreferences(userId, itemId, existingDisplayPreferences.Client, displayPreferences.CustomPrefs);
  183. _displayPreferencesManager.SaveChanges();
  184. return NoContent();
  185. }
  186. }