RequestHelpers.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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="claimsPrincipal">The <see cref="ClaimsPrincipal"/> for the current request.</param>
  80. /// <param name="user">The user id.</param>
  81. /// <param name="restrictUserPreferences">Whether to restrict the user preferences.</param>
  82. /// <returns>A <see cref="bool"/> whether the user can update the entry.</returns>
  83. internal static bool AssertCanUpdateUser(ClaimsPrincipal claimsPrincipal, User user, bool restrictUserPreferences)
  84. {
  85. var authenticatedUserId = claimsPrincipal.GetUserId();
  86. var isAdministrator = claimsPrincipal.IsInRole(UserRoles.Administrator);
  87. // If they're going to update the record of another user, they must be an administrator
  88. if (!user.Id.Equals(authenticatedUserId) && !isAdministrator)
  89. {
  90. return false;
  91. }
  92. // TODO the EnableUserPreferenceAccess policy does not seem to be used elsewhere
  93. if (!restrictUserPreferences || isAdministrator)
  94. {
  95. return true;
  96. }
  97. return user.EnableUserPreferenceAccess;
  98. }
  99. internal static async Task<SessionInfo> GetSession(ISessionManager sessionManager, IUserManager userManager, HttpContext httpContext, Guid? userId = null)
  100. {
  101. userId ??= httpContext.User.GetUserId();
  102. User? user = null;
  103. if (!userId.IsNullOrEmpty())
  104. {
  105. user = userManager.GetUserById(userId.Value);
  106. }
  107. var session = await sessionManager.LogSessionActivity(
  108. httpContext.User.GetClient(),
  109. httpContext.User.GetVersion(),
  110. httpContext.User.GetDeviceId(),
  111. httpContext.User.GetDevice(),
  112. httpContext.GetNormalizedRemoteIP().ToString(),
  113. user).ConfigureAwait(false);
  114. if (session is null)
  115. {
  116. throw new ResourceNotFoundException("Session not found.");
  117. }
  118. return session;
  119. }
  120. internal static async Task<string> GetSessionId(ISessionManager sessionManager, IUserManager userManager, HttpContext httpContext)
  121. {
  122. var session = await GetSession(sessionManager, userManager, httpContext).ConfigureAwait(false);
  123. return session.Id;
  124. }
  125. internal static QueryResult<BaseItemDto> CreateQueryResult(
  126. QueryResult<(BaseItem Item, ItemCounts ItemCounts)> result,
  127. DtoOptions dtoOptions,
  128. IDtoService dtoService,
  129. bool includeItemTypes,
  130. User? user)
  131. {
  132. var dtos = result.Items.Select(i =>
  133. {
  134. var (baseItem, counts) = i;
  135. var dto = dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
  136. if (includeItemTypes)
  137. {
  138. dto.ChildCount = counts.ItemCount;
  139. dto.ProgramCount = counts.ProgramCount;
  140. dto.SeriesCount = counts.SeriesCount;
  141. dto.EpisodeCount = counts.EpisodeCount;
  142. dto.MovieCount = counts.MovieCount;
  143. dto.TrailerCount = counts.TrailerCount;
  144. dto.AlbumCount = counts.AlbumCount;
  145. dto.SongCount = counts.SongCount;
  146. dto.ArtistCount = counts.ArtistCount;
  147. }
  148. return dto;
  149. });
  150. return new QueryResult<BaseItemDto>(
  151. result.StartIndex,
  152. result.TotalRecordCount,
  153. dtos.ToArray());
  154. }
  155. }