DisplayPreferencesController.cs 11 KB

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