DisplayPreferencesController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. {
  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. 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, Required] Guid userId,
  107. [FromQuery, Required] string client,
  108. [FromBody, Required] DisplayPreferencesDto displayPreferences)
  109. {
  110. HomeSectionType[] defaults =
  111. {
  112. HomeSectionType.SmallLibraryTiles,
  113. HomeSectionType.Resume,
  114. HomeSectionType.ResumeAudio,
  115. HomeSectionType.ResumeBook,
  116. HomeSectionType.LiveTv,
  117. HomeSectionType.NextUp,
  118. HomeSectionType.LatestMedia,
  119. HomeSectionType.None,
  120. };
  121. if (!Guid.TryParse(displayPreferencesId, out var itemId))
  122. {
  123. itemId = displayPreferencesId.GetMD5();
  124. }
  125. var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, itemId, client);
  126. existingDisplayPreferences.IndexBy = Enum.TryParse<IndexingKind>(displayPreferences.IndexBy, true, out var indexBy) ? indexBy : null;
  127. existingDisplayPreferences.ShowBackdrop = displayPreferences.ShowBackdrop;
  128. existingDisplayPreferences.ShowSidebar = displayPreferences.ShowSidebar;
  129. existingDisplayPreferences.ScrollDirection = displayPreferences.ScrollDirection;
  130. existingDisplayPreferences.ChromecastVersion = displayPreferences.CustomPrefs.TryGetValue("chromecastVersion", out var chromecastVersion)
  131. && !string.IsNullOrEmpty(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. || string.IsNullOrEmpty(enableNextVideoInfoOverlay)
  137. || bool.Parse(enableNextVideoInfoOverlay);
  138. displayPreferences.CustomPrefs.Remove("enableNextVideoInfoOverlay");
  139. existingDisplayPreferences.SkipBackwardLength = displayPreferences.CustomPrefs.TryGetValue("skipBackLength", out var skipBackLength)
  140. && !string.IsNullOrEmpty(skipBackLength)
  141. ? int.Parse(skipBackLength, CultureInfo.InvariantCulture)
  142. : 10000;
  143. displayPreferences.CustomPrefs.Remove("skipBackLength");
  144. existingDisplayPreferences.SkipForwardLength = displayPreferences.CustomPrefs.TryGetValue("skipForwardLength", out var skipForwardLength)
  145. && !string.IsNullOrEmpty(skipForwardLength)
  146. ? int.Parse(skipForwardLength, CultureInfo.InvariantCulture)
  147. : 30000;
  148. displayPreferences.CustomPrefs.Remove("skipForwardLength");
  149. existingDisplayPreferences.DashboardTheme = displayPreferences.CustomPrefs.TryGetValue("dashboardTheme", out var theme)
  150. ? theme
  151. : string.Empty;
  152. displayPreferences.CustomPrefs.Remove("dashboardTheme");
  153. existingDisplayPreferences.TvHome = displayPreferences.CustomPrefs.TryGetValue("tvhome", out var home)
  154. ? home
  155. : string.Empty;
  156. displayPreferences.CustomPrefs.Remove("tvhome");
  157. existingDisplayPreferences.HomeSections.Clear();
  158. foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("homesection", StringComparison.OrdinalIgnoreCase)))
  159. {
  160. var order = int.Parse(key.AsSpan().Slice("homesection".Length));
  161. if (!Enum.TryParse<HomeSectionType>(displayPreferences.CustomPrefs[key], true, out var type))
  162. {
  163. type = order < 8 ? defaults[order] : HomeSectionType.None;
  164. }
  165. displayPreferences.CustomPrefs.Remove(key);
  166. existingDisplayPreferences.HomeSections.Add(new HomeSection { Order = order, Type = type });
  167. }
  168. foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.OrdinalIgnoreCase)))
  169. {
  170. if (!Enum.TryParse<ViewType>(displayPreferences.CustomPrefs[key], true, out var type))
  171. {
  172. _logger.LogError("Invalid ViewType: {LandingScreenOption}", displayPreferences.CustomPrefs[key]);
  173. displayPreferences.CustomPrefs.Remove(key);
  174. }
  175. }
  176. var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, itemId, existingDisplayPreferences.Client);
  177. itemPrefs.SortBy = displayPreferences.SortBy ?? "SortName";
  178. itemPrefs.SortOrder = displayPreferences.SortOrder;
  179. itemPrefs.RememberIndexing = displayPreferences.RememberIndexing;
  180. itemPrefs.RememberSorting = displayPreferences.RememberSorting;
  181. itemPrefs.ItemId = itemId;
  182. // Set all remaining custom preferences.
  183. _displayPreferencesManager.SetCustomItemDisplayPreferences(userId, itemId, existingDisplayPreferences.Client, displayPreferences.CustomPrefs);
  184. _displayPreferencesManager.SaveChanges();
  185. return NoContent();
  186. }
  187. }
  188. }