UserDataManager.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Threading;
  7. using Jellyfin.Data.Entities;
  8. using MediaBrowser.Controller.Configuration;
  9. using MediaBrowser.Controller.Dto;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Persistence;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.Entities;
  15. using Book = MediaBrowser.Controller.Entities.Book;
  16. namespace Emby.Server.Implementations.Library
  17. {
  18. /// <summary>
  19. /// Class UserDataManager.
  20. /// </summary>
  21. public class UserDataManager : IUserDataManager
  22. {
  23. public event EventHandler<UserDataSaveEventArgs> UserDataSaved;
  24. private readonly ConcurrentDictionary<string, UserItemData> _userData =
  25. new ConcurrentDictionary<string, UserItemData>(StringComparer.OrdinalIgnoreCase);
  26. private readonly IServerConfigurationManager _config;
  27. private readonly IUserManager _userManager;
  28. private readonly IUserDataRepository _repository;
  29. public UserDataManager(
  30. IServerConfigurationManager config,
  31. IUserManager userManager,
  32. IUserDataRepository repository)
  33. {
  34. _config = config;
  35. _userManager = userManager;
  36. _repository = repository;
  37. }
  38. public void SaveUserData(Guid userId, BaseItem item, UserItemData userData, UserDataSaveReason reason, CancellationToken cancellationToken)
  39. {
  40. var user = _userManager.GetUserById(userId);
  41. SaveUserData(user, item, userData, reason, cancellationToken);
  42. }
  43. public void SaveUserData(User user, BaseItem item, UserItemData userData, UserDataSaveReason reason, CancellationToken cancellationToken)
  44. {
  45. if (userData == null)
  46. {
  47. throw new ArgumentNullException(nameof(userData));
  48. }
  49. if (item == null)
  50. {
  51. throw new ArgumentNullException(nameof(item));
  52. }
  53. cancellationToken.ThrowIfCancellationRequested();
  54. var keys = item.GetUserDataKeys();
  55. var userId = user.InternalId;
  56. foreach (var key in keys)
  57. {
  58. _repository.SaveUserData(userId, key, userData, cancellationToken);
  59. }
  60. var cacheKey = GetCacheKey(userId, item.Id);
  61. _userData.AddOrUpdate(cacheKey, userData, (k, v) => userData);
  62. UserDataSaved?.Invoke(this, new UserDataSaveEventArgs
  63. {
  64. Keys = keys,
  65. UserData = userData,
  66. SaveReason = reason,
  67. UserId = user.Id,
  68. Item = item
  69. });
  70. }
  71. /// <summary>
  72. /// Save the provided user data for the given user. Batch operation. Does not fire any events or update the cache.
  73. /// </summary>
  74. /// <param name="userId"></param>
  75. /// <param name="userData"></param>
  76. /// <param name="cancellationToken"></param>
  77. /// <returns></returns>
  78. public void SaveAllUserData(Guid userId, UserItemData[] userData, CancellationToken cancellationToken)
  79. {
  80. var user = _userManager.GetUserById(userId);
  81. _repository.SaveAllUserData(user.InternalId, userData, cancellationToken);
  82. }
  83. /// <summary>
  84. /// Retrieve all user data for the given user.
  85. /// </summary>
  86. /// <param name="userId"></param>
  87. /// <returns></returns>
  88. public List<UserItemData> GetAllUserData(Guid userId)
  89. {
  90. var user = _userManager.GetUserById(userId);
  91. return _repository.GetAllUserData(user.InternalId);
  92. }
  93. public UserItemData GetUserData(Guid userId, Guid itemId, List<string> keys)
  94. {
  95. var user = _userManager.GetUserById(userId);
  96. return GetUserData(user, itemId, keys);
  97. }
  98. public UserItemData GetUserData(User user, Guid itemId, List<string> keys)
  99. {
  100. var userId = user.InternalId;
  101. var cacheKey = GetCacheKey(userId, itemId);
  102. return _userData.GetOrAdd(cacheKey, k => GetUserDataInternal(userId, keys));
  103. }
  104. private UserItemData GetUserDataInternal(long internalUserId, List<string> keys)
  105. {
  106. var userData = _repository.GetUserData(internalUserId, keys);
  107. if (userData != null)
  108. {
  109. return userData;
  110. }
  111. if (keys.Count > 0)
  112. {
  113. return new UserItemData
  114. {
  115. Key = keys[0]
  116. };
  117. }
  118. return null;
  119. }
  120. /// <summary>
  121. /// Gets the internal key.
  122. /// </summary>
  123. /// <returns>System.String.</returns>
  124. private static string GetCacheKey(long internalUserId, Guid itemId)
  125. {
  126. return internalUserId.ToString(CultureInfo.InvariantCulture) + "-" + itemId.ToString("N", CultureInfo.InvariantCulture);
  127. }
  128. public UserItemData GetUserData(User user, BaseItem item)
  129. {
  130. return GetUserData(user, item.Id, item.GetUserDataKeys());
  131. }
  132. public UserItemData GetUserData(Guid userId, BaseItem item)
  133. {
  134. return GetUserData(userId, item.Id, item.GetUserDataKeys());
  135. }
  136. public UserItemDataDto GetUserDataDto(BaseItem item, User user)
  137. {
  138. var userData = GetUserData(user, item);
  139. var dto = GetUserItemDataDto(userData);
  140. item.FillUserDataDtoValues(dto, userData, null, user, new DtoOptions());
  141. return dto;
  142. }
  143. public UserItemDataDto GetUserDataDto(BaseItem item, BaseItemDto itemDto, User user, DtoOptions options)
  144. {
  145. var userData = GetUserData(user, item);
  146. var dto = GetUserItemDataDto(userData);
  147. item.FillUserDataDtoValues(dto, userData, itemDto, user, options);
  148. return dto;
  149. }
  150. /// <summary>
  151. /// Converts a UserItemData to a DTOUserItemData.
  152. /// </summary>
  153. /// <param name="data">The data.</param>
  154. /// <returns>DtoUserItemData.</returns>
  155. /// <exception cref="ArgumentNullException"></exception>
  156. private UserItemDataDto GetUserItemDataDto(UserItemData data)
  157. {
  158. if (data == null)
  159. {
  160. throw new ArgumentNullException(nameof(data));
  161. }
  162. return new UserItemDataDto
  163. {
  164. IsFavorite = data.IsFavorite,
  165. Likes = data.Likes,
  166. PlaybackPositionTicks = data.PlaybackPositionTicks,
  167. PlayCount = data.PlayCount,
  168. Rating = data.Rating,
  169. Played = data.Played,
  170. LastPlayedDate = data.LastPlayedDate,
  171. Key = data.Key
  172. };
  173. }
  174. public bool UpdatePlayState(BaseItem item, UserItemData data, long? reportedPositionTicks)
  175. {
  176. var playedToCompletion = false;
  177. var runtimeTicks = item.GetRunTimeTicksForPlayState();
  178. var positionTicks = reportedPositionTicks ?? runtimeTicks;
  179. var hasRuntime = runtimeTicks > 0;
  180. // If a position has been reported, and if we know the duration
  181. if (positionTicks > 0 && hasRuntime)
  182. {
  183. var pctIn = decimal.Divide(positionTicks, runtimeTicks) * 100;
  184. if (pctIn < _config.Configuration.MinResumePct)
  185. {
  186. // ignore progress during the beginning
  187. positionTicks = 0;
  188. }
  189. else if (pctIn > _config.Configuration.MaxResumePct || positionTicks >= runtimeTicks)
  190. {
  191. // mark as completed close to the end
  192. positionTicks = 0;
  193. data.Played = playedToCompletion = true;
  194. }
  195. else
  196. {
  197. // Enforce MinResumeDuration
  198. var durationSeconds = TimeSpan.FromTicks(runtimeTicks).TotalSeconds;
  199. if (durationSeconds < _config.Configuration.MinResumeDurationSeconds && !(item is Book))
  200. {
  201. positionTicks = 0;
  202. data.Played = playedToCompletion = true;
  203. }
  204. }
  205. }
  206. else if (!hasRuntime)
  207. {
  208. // If we don't know the runtime we'll just have to assume it was fully played
  209. data.Played = playedToCompletion = true;
  210. positionTicks = 0;
  211. }
  212. if (!item.SupportsPlayedStatus)
  213. {
  214. positionTicks = 0;
  215. data.Played = false;
  216. }
  217. if (!item.SupportsPositionTicksResume)
  218. {
  219. positionTicks = 0;
  220. }
  221. data.PlaybackPositionTicks = positionTicks;
  222. return playedToCompletion;
  223. }
  224. }
  225. }