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.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.Entities;
  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. {
  18. /// <summary>
  19. /// Display Preferences Controller.
  20. /// </summary>
  21. [Authorize(Policy = Policies.DefaultAuthorization)]
  22. public class DisplayPreferencesController : BaseJellyfinApiController
  23. {
  24. private readonly IDisplayPreferencesManager _displayPreferencesManager;
  25. private readonly ILogger<DisplayPreferencesController> _logger;
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="DisplayPreferencesController"/> class.
  28. /// </summary>
  29. /// <param name="displayPreferencesManager">Instance of <see cref="IDisplayPreferencesManager"/> interface.</param>
  30. /// <param name="logger">Instance of <see cref="ILogger{DisplayPreferencesController}"/> interface.</param>
  31. public DisplayPreferencesController(IDisplayPreferencesManager displayPreferencesManager, ILogger<DisplayPreferencesController> logger)
  32. {
  33. _displayPreferencesManager = displayPreferencesManager;
  34. _logger = logger;
  35. }
  36. /// <summary>
  37. /// Get Display Preferences.
  38. /// </summary>
  39. /// <param name="displayPreferencesId">Display preferences id.</param>
  40. /// <param name="userId">User id.</param>
  41. /// <param name="client">Client.</param>
  42. /// <response code="200">Display preferences retrieved.</response>
  43. /// <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>
  44. [HttpGet("{displayPreferencesId}")]
  45. [ProducesResponseType(StatusCodes.Status200OK)]
  46. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justification = "Imported from ServiceStack")]
  47. public ActionResult<DisplayPreferencesDto> GetDisplayPreferences(
  48. [FromRoute, Required] string displayPreferencesId,
  49. [FromQuery, Required] Guid userId,
  50. [FromQuery, Required] string client)
  51. {
  52. if (!Guid.TryParse(displayPreferencesId, out var itemId))
  53. {
  54. itemId = displayPreferencesId.GetMD5();
  55. }
  56. var displayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, 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. if (customDisplayPreferences != null)
  85. {
  86. foreach (var (key, value) in customDisplayPreferences)
  87. {
  88. dto.CustomPrefs.TryAdd(key, value);
  89. }
  90. }
  91. // This will essentially be a noop if no changes have been made, but new prefs must be saved at least.
  92. _displayPreferencesManager.SaveChanges();
  93. return dto;
  94. }
  95. /// <summary>
  96. /// Update Display Preferences.
  97. /// </summary>
  98. /// <param name="displayPreferencesId">Display preferences id.</param>
  99. /// <param name="userId">User Id.</param>
  100. /// <param name="client">Client.</param>
  101. /// <param name="displayPreferences">New Display Preferences object.</param>
  102. /// <response code="204">Display preferences updated.</response>
  103. /// <returns>An <see cref="NoContentResult"/> on success.</returns>
  104. [HttpPost("{displayPreferencesId}")]
  105. [ProducesResponseType(StatusCodes.Status204NoContent)]
  106. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "displayPreferencesId", Justification = "Imported from ServiceStack")]
  107. public ActionResult UpdateDisplayPreferences(
  108. [FromRoute, Required] string displayPreferencesId,
  109. [FromQuery, Required] Guid userId,
  110. [FromQuery, Required] string client,
  111. [FromBody, Required] DisplayPreferencesDto displayPreferences)
  112. {
  113. HomeSectionType[] defaults =
  114. {
  115. HomeSectionType.SmallLibraryTiles,
  116. HomeSectionType.Resume,
  117. HomeSectionType.ResumeAudio,
  118. HomeSectionType.LiveTv,
  119. HomeSectionType.NextUp,
  120. HomeSectionType.LatestMedia, HomeSectionType.None,
  121. };
  122. if (!Guid.TryParse(displayPreferencesId, out var itemId))
  123. {
  124. itemId = displayPreferencesId.GetMD5();
  125. }
  126. var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, 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. ? Enum.Parse<ChromecastVersion>(chromecastVersion, true)
  133. : ChromecastVersion.Stable;
  134. displayPreferences.CustomPrefs.Remove("chromecastVersion");
  135. existingDisplayPreferences.EnableNextVideoInfoOverlay = displayPreferences.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enableNextVideoInfoOverlay)
  136. ? bool.Parse(enableNextVideoInfoOverlay)
  137. : true;
  138. displayPreferences.CustomPrefs.Remove("enableNextVideoInfoOverlay");
  139. existingDisplayPreferences.SkipBackwardLength = displayPreferences.CustomPrefs.TryGetValue("skipBackLength", out var 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. ? 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));
  159. if (!Enum.TryParse<HomeSectionType>(displayPreferences.CustomPrefs[key], true, out var type))
  160. {
  161. type = order < 7 ? 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;
  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. }
  186. }