UserDataManager.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Persistence;
  7. using MediaBrowser.Model.Dto;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  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 UserItemData GetUserData(IHasUserData user, IHasUserData item)
  148. {
  149. return GetUserData(user.Id, item.GetUserDataKey());
  150. }
  151. public UserItemData GetUserData(string userId, IHasUserData item)
  152. {
  153. return GetUserData(userId, item.GetUserDataKey());
  154. }
  155. public UserItemData GetUserData(Guid userId, IHasUserData item)
  156. {
  157. return GetUserData(userId, item.GetUserDataKey());
  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. public bool UpdatePlayState(BaseItem item, UserItemData data, long? reportedPositionTicks)
  191. {
  192. var playedToCompletion = false;
  193. var positionTicks = reportedPositionTicks ?? item.RunTimeTicks ?? 0;
  194. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  195. // If a position has been reported, and if we know the duration
  196. if (positionTicks > 0 && hasRuntime)
  197. {
  198. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  199. // Don't track in very beginning
  200. if (pctIn < _config.Configuration.MinResumePct)
  201. {
  202. positionTicks = 0;
  203. }
  204. // If we're at the end, assume completed
  205. else if (pctIn > _config.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  206. {
  207. positionTicks = 0;
  208. data.Played = playedToCompletion = true;
  209. }
  210. else
  211. {
  212. // Enforce MinResumeDuration
  213. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  214. if (durationSeconds < _config.Configuration.MinResumeDurationSeconds)
  215. {
  216. positionTicks = 0;
  217. data.Played = playedToCompletion = true;
  218. }
  219. }
  220. }
  221. else if (!hasRuntime)
  222. {
  223. // If we don't know the runtime we'll just have to assume it was fully played
  224. data.Played = playedToCompletion = true;
  225. positionTicks = 0;
  226. }
  227. if (item is Audio)
  228. {
  229. positionTicks = 0;
  230. }
  231. data.PlaybackPositionTicks = positionTicks;
  232. return playedToCompletion;
  233. }
  234. public UserItemData GetUserData(string userId, string key)
  235. {
  236. return GetUserData(new Guid(userId), key);
  237. }
  238. }
  239. }