UserDataManager.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. using System.Collections.Generic;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Persistence;
  6. using MediaBrowser.Model.Dto;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Server.Implementations.Library
  14. {
  15. /// <summary>
  16. /// Class UserDataManager
  17. /// </summary>
  18. public class UserDataManager : IUserDataManager
  19. {
  20. public event EventHandler<UserDataSaveEventArgs> UserDataSaved;
  21. private readonly ConcurrentDictionary<string, UserItemData> _userData = new ConcurrentDictionary<string, UserItemData>();
  22. private readonly ILogger _logger;
  23. public UserDataManager(ILogManager logManager)
  24. {
  25. _logger = logManager.GetLogger(GetType().Name);
  26. }
  27. /// <summary>
  28. /// Gets or sets the repository.
  29. /// </summary>
  30. /// <value>The repository.</value>
  31. public IUserDataRepository Repository { get; set; }
  32. /// <summary>
  33. /// Saves the user data.
  34. /// </summary>
  35. /// <param name="userId">The user id.</param>
  36. /// <param name="item">The item.</param>
  37. /// <param name="userData">The user data.</param>
  38. /// <param name="reason">The reason.</param>
  39. /// <param name="cancellationToken">The cancellation token.</param>
  40. /// <returns>Task.</returns>
  41. /// <exception cref="System.ArgumentNullException">userData
  42. /// or
  43. /// cancellationToken
  44. /// or
  45. /// userId
  46. /// or
  47. /// key</exception>
  48. public async Task SaveUserData(Guid userId, IHasUserData item, UserItemData userData, UserDataSaveReason reason, CancellationToken cancellationToken)
  49. {
  50. if (userData == null)
  51. {
  52. throw new ArgumentNullException("userData");
  53. }
  54. if (item == null)
  55. {
  56. throw new ArgumentNullException("item");
  57. }
  58. if (userId == Guid.Empty)
  59. {
  60. throw new ArgumentNullException("userId");
  61. }
  62. cancellationToken.ThrowIfCancellationRequested();
  63. var key = item.GetUserDataKey();
  64. try
  65. {
  66. await Repository.SaveUserData(userId, key, userData, cancellationToken).ConfigureAwait(false);
  67. var newValue = userData;
  68. // Once it succeeds, put it into the dictionary to make it available to everyone else
  69. _userData.AddOrUpdate(GetCacheKey(userId, key), newValue, delegate { return newValue; });
  70. }
  71. catch (Exception ex)
  72. {
  73. _logger.ErrorException("Error saving user data", ex);
  74. throw;
  75. }
  76. EventHelper.FireEventIfNotNull(UserDataSaved, this, new UserDataSaveEventArgs
  77. {
  78. Key = key,
  79. UserData = userData,
  80. SaveReason = reason,
  81. UserId = userId,
  82. Item = item
  83. }, _logger);
  84. }
  85. /// <summary>
  86. /// Save the provided user data for the given user. Batch operation. Does not fire any events or update the cache.
  87. /// </summary>
  88. /// <param name="userId"></param>
  89. /// <param name="userData"></param>
  90. /// <param name="cancellationToken"></param>
  91. /// <returns></returns>
  92. public async Task SaveAllUserData(Guid userId, IEnumerable<UserItemData> userData, CancellationToken cancellationToken)
  93. {
  94. if (userData == null)
  95. {
  96. throw new ArgumentNullException("userData");
  97. }
  98. if (userId == Guid.Empty)
  99. {
  100. throw new ArgumentNullException("userId");
  101. }
  102. cancellationToken.ThrowIfCancellationRequested();
  103. try
  104. {
  105. await Repository.SaveAllUserData(userId, userData, cancellationToken).ConfigureAwait(false);
  106. }
  107. catch (Exception ex)
  108. {
  109. _logger.ErrorException("Error saving user data", ex);
  110. throw;
  111. }
  112. }
  113. /// <summary>
  114. /// Retrieve all user data for the given user
  115. /// </summary>
  116. /// <param name="userId"></param>
  117. /// <returns></returns>
  118. public IEnumerable<UserItemData> GetAllUserData(Guid userId)
  119. {
  120. if (userId == Guid.Empty)
  121. {
  122. throw new ArgumentNullException("userId");
  123. }
  124. return Repository.GetAllUserData(userId);
  125. }
  126. /// <summary>
  127. /// Gets the user data.
  128. /// </summary>
  129. /// <param name="userId">The user id.</param>
  130. /// <param name="key">The key.</param>
  131. /// <returns>Task{UserItemData}.</returns>
  132. public UserItemData GetUserData(Guid userId, string key)
  133. {
  134. if (userId == Guid.Empty)
  135. {
  136. throw new ArgumentNullException("userId");
  137. }
  138. if (string.IsNullOrEmpty(key))
  139. {
  140. throw new ArgumentNullException("key");
  141. }
  142. return _userData.GetOrAdd(GetCacheKey(userId, key), keyName => GetUserDataFromRepository(userId, key));
  143. }
  144. public UserItemData GetUserDataFromRepository(Guid userId, string key)
  145. {
  146. var data = Repository.GetUserData(userId, key);
  147. return data;
  148. }
  149. /// <summary>
  150. /// Gets the internal key.
  151. /// </summary>
  152. /// <param name="userId">The user id.</param>
  153. /// <param name="key">The key.</param>
  154. /// <returns>System.String.</returns>
  155. private string GetCacheKey(Guid userId, string key)
  156. {
  157. return userId + key;
  158. }
  159. public UserItemDataDto GetUserDataDto(IHasUserData item, User user)
  160. {
  161. var userData = GetUserData(user.Id, item.GetUserDataKey());
  162. var dto = GetUserItemDataDto(userData);
  163. item.FillUserDataDtoValues(dto, userData, user);
  164. return dto;
  165. }
  166. /// <summary>
  167. /// Converts a UserItemData to a DTOUserItemData
  168. /// </summary>
  169. /// <param name="data">The data.</param>
  170. /// <returns>DtoUserItemData.</returns>
  171. /// <exception cref="System.ArgumentNullException"></exception>
  172. private UserItemDataDto GetUserItemDataDto(UserItemData data)
  173. {
  174. if (data == null)
  175. {
  176. throw new ArgumentNullException("data");
  177. }
  178. return new UserItemDataDto
  179. {
  180. IsFavorite = data.IsFavorite,
  181. Likes = data.Likes,
  182. PlaybackPositionTicks = data.PlaybackPositionTicks,
  183. PlayCount = data.PlayCount,
  184. Rating = data.Rating,
  185. Played = data.Played,
  186. LastPlayedDate = data.LastPlayedDate,
  187. Key = data.Key
  188. };
  189. }
  190. }
  191. }