RequestHelpers.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Claims;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Api.Constants;
  7. using Jellyfin.Api.Extensions;
  8. using Jellyfin.Data.Entities;
  9. using Jellyfin.Data.Enums;
  10. using Jellyfin.Extensions;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Controller.Dto;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Net;
  16. using MediaBrowser.Controller.Session;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Querying;
  19. using Microsoft.AspNetCore.Http;
  20. namespace Jellyfin.Api.Helpers;
  21. /// <summary>
  22. /// Request Extensions.
  23. /// </summary>
  24. public static class RequestHelpers
  25. {
  26. /// <summary>
  27. /// Get Order By.
  28. /// </summary>
  29. /// <param name="sortBy">Sort By. Comma delimited string.</param>
  30. /// <param name="requestedSortOrder">Sort Order. Comma delimited string.</param>
  31. /// <returns>Order By.</returns>
  32. public static (ItemSortBy, SortOrder)[] GetOrderBy(IReadOnlyList<ItemSortBy> sortBy, IReadOnlyList<SortOrder> requestedSortOrder)
  33. {
  34. if (sortBy.Count == 0)
  35. {
  36. return Array.Empty<(ItemSortBy, SortOrder)>();
  37. }
  38. var result = new (ItemSortBy, SortOrder)[sortBy.Count];
  39. var i = 0;
  40. // Add elements which have a SortOrder specified
  41. for (; i < requestedSortOrder.Count; i++)
  42. {
  43. result[i] = (sortBy[i], requestedSortOrder[i]);
  44. }
  45. // Add remaining elements with the first specified SortOrder
  46. // or the default one if no SortOrders are specified
  47. var order = requestedSortOrder.Count > 0 ? requestedSortOrder[0] : SortOrder.Ascending;
  48. for (; i < sortBy.Count; i++)
  49. {
  50. result[i] = (sortBy[i], order);
  51. }
  52. return result;
  53. }
  54. /// <summary>
  55. /// Checks if the user can access a user.
  56. /// </summary>
  57. /// <param name="claimsPrincipal">The <see cref="ClaimsPrincipal"/> for the current request.</param>
  58. /// <param name="userId">The user id.</param>
  59. /// <returns>A <see cref="bool"/> whether the user can access the user.</returns>
  60. internal static Guid GetUserId(ClaimsPrincipal claimsPrincipal, Guid? userId)
  61. {
  62. var authenticatedUserId = claimsPrincipal.GetUserId();
  63. // UserId not provided, fall back to authenticated user id.
  64. if (userId.IsNullOrEmpty())
  65. {
  66. return authenticatedUserId;
  67. }
  68. // User must be administrator to access another user.
  69. var isAdministrator = claimsPrincipal.IsInRole(UserRoles.Administrator);
  70. if (!userId.Value.Equals(authenticatedUserId) && !isAdministrator)
  71. {
  72. throw new SecurityException("Forbidden");
  73. }
  74. return userId.Value;
  75. }
  76. /// <summary>
  77. /// Checks if the user can update an entry.
  78. /// </summary>
  79. /// <param name="userManager">An instance of the <see cref="IUserManager"/> interface.</param>
  80. /// <param name="claimsPrincipal">The <see cref="ClaimsPrincipal"/> for the current request.</param>
  81. /// <param name="userId">The user id.</param>
  82. /// <param name="restrictUserPreferences">Whether to restrict the user preferences.</param>
  83. /// <returns>A <see cref="bool"/> whether the user can update the entry.</returns>
  84. internal static bool AssertCanUpdateUser(IUserManager userManager, ClaimsPrincipal claimsPrincipal, Guid userId, bool restrictUserPreferences)
  85. {
  86. var authenticatedUserId = claimsPrincipal.GetUserId();
  87. var isAdministrator = claimsPrincipal.IsInRole(UserRoles.Administrator);
  88. // If they're going to update the record of another user, they must be an administrator
  89. if (!userId.Equals(authenticatedUserId) && !isAdministrator)
  90. {
  91. return false;
  92. }
  93. // TODO the EnableUserPreferenceAccess policy does not seem to be used elsewhere
  94. if (!restrictUserPreferences || isAdministrator)
  95. {
  96. return true;
  97. }
  98. var user = userManager.GetUserById(userId);
  99. if (user is null)
  100. {
  101. throw new ResourceNotFoundException();
  102. }
  103. return user.EnableUserPreferenceAccess;
  104. }
  105. internal static async Task<SessionInfo> GetSession(ISessionManager sessionManager, IUserManager userManager, HttpContext httpContext)
  106. {
  107. var userId = httpContext.User.GetUserId();
  108. var user = userManager.GetUserById(userId);
  109. var session = await sessionManager.LogSessionActivity(
  110. httpContext.User.GetClient(),
  111. httpContext.User.GetVersion(),
  112. httpContext.User.GetDeviceId(),
  113. httpContext.User.GetDevice(),
  114. httpContext.GetNormalizedRemoteIP().ToString(),
  115. user).ConfigureAwait(false);
  116. if (session is null)
  117. {
  118. throw new ResourceNotFoundException("Session not found.");
  119. }
  120. return session;
  121. }
  122. internal static async Task<string> GetSessionId(ISessionManager sessionManager, IUserManager userManager, HttpContext httpContext)
  123. {
  124. var session = await GetSession(sessionManager, userManager, httpContext).ConfigureAwait(false);
  125. return session.Id;
  126. }
  127. internal static QueryResult<BaseItemDto> CreateQueryResult(
  128. QueryResult<(BaseItem Item, ItemCounts ItemCounts)> result,
  129. DtoOptions dtoOptions,
  130. IDtoService dtoService,
  131. bool includeItemTypes,
  132. User? user)
  133. {
  134. var dtos = result.Items.Select(i =>
  135. {
  136. var (baseItem, counts) = i;
  137. var dto = dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
  138. if (includeItemTypes)
  139. {
  140. dto.ChildCount = counts.ItemCount;
  141. dto.ProgramCount = counts.ProgramCount;
  142. dto.SeriesCount = counts.SeriesCount;
  143. dto.EpisodeCount = counts.EpisodeCount;
  144. dto.MovieCount = counts.MovieCount;
  145. dto.TrailerCount = counts.TrailerCount;
  146. dto.AlbumCount = counts.AlbumCount;
  147. dto.SongCount = counts.SongCount;
  148. dto.ArtistCount = counts.ArtistCount;
  149. }
  150. return dto;
  151. });
  152. return new QueryResult<BaseItemDto>(
  153. result.StartIndex,
  154. result.TotalRecordCount,
  155. dtos.ToArray());
  156. }
  157. }