UserDataManager.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using System.Collections.Generic;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Audio;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Model.Dto;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Server.Implementations.Library
  16. {
  17. /// <summary>
  18. /// Class UserDataManager
  19. /// </summary>
  20. public class UserDataManager : IUserDataManager
  21. {
  22. public event EventHandler<UserDataSaveEventArgs> UserDataSaved;
  23. private readonly ConcurrentDictionary<string, UserItemData> _userData = new ConcurrentDictionary<string, UserItemData>();
  24. private readonly ILogger _logger;
  25. private readonly IServerConfigurationManager _config;
  26. public UserDataManager(ILogManager logManager, IServerConfigurationManager config)
  27. {
  28. _config = config;
  29. _logger = logManager.GetLogger(GetType().Name);
  30. }
  31. /// <summary>
  32. /// Gets or sets the repository.
  33. /// </summary>
  34. /// <value>The repository.</value>
  35. public IUserDataRepository Repository { get; set; }
  36. public async Task SaveUserData(Guid userId, IHasUserData item, UserItemData userData, UserDataSaveReason reason, CancellationToken cancellationToken)
  37. {
  38. if (userData == null)
  39. {
  40. throw new ArgumentNullException("userData");
  41. }
  42. if (item == null)
  43. {
  44. throw new ArgumentNullException("item");
  45. }
  46. if (userId == Guid.Empty)
  47. {
  48. throw new ArgumentNullException("userId");
  49. }
  50. cancellationToken.ThrowIfCancellationRequested();
  51. var key = item.GetUserDataKey();
  52. try
  53. {
  54. await Repository.SaveUserData(userId, key, userData, cancellationToken).ConfigureAwait(false);
  55. var newValue = userData;
  56. // Once it succeeds, put it into the dictionary to make it available to everyone else
  57. _userData.AddOrUpdate(GetCacheKey(userId, key), newValue, delegate { return newValue; });
  58. }
  59. catch (Exception ex)
  60. {
  61. _logger.ErrorException("Error saving user data", ex);
  62. throw;
  63. }
  64. EventHelper.FireEventIfNotNull(UserDataSaved, this, new UserDataSaveEventArgs
  65. {
  66. Key = key,
  67. UserData = userData,
  68. SaveReason = reason,
  69. UserId = userId,
  70. Item = item
  71. }, _logger);
  72. }
  73. /// <summary>
  74. /// Save the provided user data for the given user. Batch operation. Does not fire any events or update the cache.
  75. /// </summary>
  76. /// <param name="userId"></param>
  77. /// <param name="userData"></param>
  78. /// <param name="cancellationToken"></param>
  79. /// <returns></returns>
  80. public async Task SaveAllUserData(Guid userId, IEnumerable<UserItemData> userData, CancellationToken cancellationToken)
  81. {
  82. if (userData == null)
  83. {
  84. throw new ArgumentNullException("userData");
  85. }
  86. if (userId == Guid.Empty)
  87. {
  88. throw new ArgumentNullException("userId");
  89. }
  90. cancellationToken.ThrowIfCancellationRequested();
  91. try
  92. {
  93. await Repository.SaveAllUserData(userId, userData, cancellationToken).ConfigureAwait(false);
  94. }
  95. catch (Exception ex)
  96. {
  97. _logger.ErrorException("Error saving user data", ex);
  98. throw;
  99. }
  100. }
  101. /// <summary>
  102. /// Retrieve all user data for the given user
  103. /// </summary>
  104. /// <param name="userId"></param>
  105. /// <returns></returns>
  106. public IEnumerable<UserItemData> GetAllUserData(Guid userId)
  107. {
  108. if (userId == Guid.Empty)
  109. {
  110. throw new ArgumentNullException("userId");
  111. }
  112. return Repository.GetAllUserData(userId);
  113. }
  114. /// <summary>
  115. /// Gets the user data.
  116. /// </summary>
  117. /// <param name="userId">The user id.</param>
  118. /// <param name="key">The key.</param>
  119. /// <returns>Task{UserItemData}.</returns>
  120. public UserItemData GetUserData(Guid userId, string key)
  121. {
  122. if (userId == Guid.Empty)
  123. {
  124. throw new ArgumentNullException("userId");
  125. }
  126. if (string.IsNullOrEmpty(key))
  127. {
  128. throw new ArgumentNullException("key");
  129. }
  130. return _userData.GetOrAdd(GetCacheKey(userId, key), keyName => GetUserDataFromRepository(userId, key));
  131. }
  132. public UserItemData GetUserDataFromRepository(Guid userId, string key)
  133. {
  134. var data = Repository.GetUserData(userId, key);
  135. return data;
  136. }
  137. /// <summary>
  138. /// Gets the internal key.
  139. /// </summary>
  140. /// <param name="userId">The user id.</param>
  141. /// <param name="key">The key.</param>
  142. /// <returns>System.String.</returns>
  143. private string GetCacheKey(Guid userId, string key)
  144. {
  145. return userId + key;
  146. }
  147. public UserItemDataDto GetUserDataDto(IHasUserData item, User user)
  148. {
  149. var userData = GetUserData(user.Id, item.GetUserDataKey());
  150. var dto = GetUserItemDataDto(userData);
  151. item.FillUserDataDtoValues(dto, userData, user);
  152. return dto;
  153. }
  154. /// <summary>
  155. /// Converts a UserItemData to a DTOUserItemData
  156. /// </summary>
  157. /// <param name="data">The data.</param>
  158. /// <returns>DtoUserItemData.</returns>
  159. /// <exception cref="System.ArgumentNullException"></exception>
  160. private UserItemDataDto GetUserItemDataDto(UserItemData data)
  161. {
  162. if (data == null)
  163. {
  164. throw new ArgumentNullException("data");
  165. }
  166. return new UserItemDataDto
  167. {
  168. IsFavorite = data.IsFavorite,
  169. Likes = data.Likes,
  170. PlaybackPositionTicks = data.PlaybackPositionTicks,
  171. PlayCount = data.PlayCount,
  172. Rating = data.Rating,
  173. Played = data.Played,
  174. LastPlayedDate = data.LastPlayedDate,
  175. Key = data.Key
  176. };
  177. }
  178. public bool UpdatePlayState(BaseItem item, UserItemData data, long? reportedPositionTicks)
  179. {
  180. var playedToCompletion = false;
  181. var positionTicks = reportedPositionTicks ?? item.RunTimeTicks ?? 0;
  182. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  183. // If a position has been reported, and if we know the duration
  184. if (positionTicks > 0 && hasRuntime)
  185. {
  186. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  187. // Don't track in very beginning
  188. if (pctIn < _config.Configuration.MinResumePct)
  189. {
  190. positionTicks = 0;
  191. }
  192. // If we're at the end, assume completed
  193. else if (pctIn > _config.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  194. {
  195. positionTicks = 0;
  196. data.Played = playedToCompletion = true;
  197. }
  198. else
  199. {
  200. // Enforce MinResumeDuration
  201. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  202. if (durationSeconds < _config.Configuration.MinResumeDurationSeconds)
  203. {
  204. positionTicks = 0;
  205. data.Played = playedToCompletion = true;
  206. }
  207. }
  208. }
  209. else if (!hasRuntime)
  210. {
  211. // If we don't know the runtime we'll just have to assume it was fully played
  212. data.Played = playedToCompletion = true;
  213. positionTicks = 0;
  214. }
  215. if (item is Audio)
  216. {
  217. positionTicks = 0;
  218. }
  219. data.PlaybackPositionTicks = positionTicks;
  220. return playedToCompletion;
  221. }
  222. }
  223. }