UserDataManager.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.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 ILogger _logger;
  27. private readonly IServerConfigurationManager _config;
  28. public UserDataManager(ILogManager logManager, IServerConfigurationManager config)
  29. {
  30. _config = config;
  31. _logger = logManager.GetLogger(GetType().Name);
  32. }
  33. /// <summary>
  34. /// Gets or sets the repository.
  35. /// </summary>
  36. /// <value>The repository.</value>
  37. public IUserDataRepository Repository { get; set; }
  38. public async Task SaveUserData(Guid userId, IHasUserData item, UserItemData userData, UserDataSaveReason reason, CancellationToken cancellationToken)
  39. {
  40. if (userData == null)
  41. {
  42. throw new ArgumentNullException("userData");
  43. }
  44. if (item == null)
  45. {
  46. throw new ArgumentNullException("item");
  47. }
  48. if (userId == Guid.Empty)
  49. {
  50. throw new ArgumentNullException("userId");
  51. }
  52. cancellationToken.ThrowIfCancellationRequested();
  53. var keys = item.GetUserDataKeys();
  54. foreach (var key in keys)
  55. {
  56. try
  57. {
  58. await Repository.SaveUserData(userId, key, userData, cancellationToken).ConfigureAwait(false);
  59. }
  60. catch (Exception ex)
  61. {
  62. _logger.ErrorException("Error saving user data", ex);
  63. throw;
  64. }
  65. }
  66. var cacheKey = GetCacheKey(userId, item.Id);
  67. _userData.AddOrUpdate(cacheKey, userData, (k, v) => userData);
  68. EventHelper.FireEventIfNotNull(UserDataSaved, this, new UserDataSaveEventArgs
  69. {
  70. Keys = keys,
  71. UserData = userData,
  72. SaveReason = reason,
  73. UserId = userId,
  74. Item = item
  75. }, _logger);
  76. }
  77. /// <summary>
  78. /// Save the provided user data for the given user. Batch operation. Does not fire any events or update the cache.
  79. /// </summary>
  80. /// <param name="userId"></param>
  81. /// <param name="userData"></param>
  82. /// <param name="cancellationToken"></param>
  83. /// <returns></returns>
  84. public async Task SaveAllUserData(Guid userId, IEnumerable<UserItemData> userData, CancellationToken cancellationToken)
  85. {
  86. if (userData == null)
  87. {
  88. throw new ArgumentNullException("userData");
  89. }
  90. if (userId == Guid.Empty)
  91. {
  92. throw new ArgumentNullException("userId");
  93. }
  94. cancellationToken.ThrowIfCancellationRequested();
  95. try
  96. {
  97. await Repository.SaveAllUserData(userId, userData, cancellationToken).ConfigureAwait(false);
  98. }
  99. catch (Exception ex)
  100. {
  101. _logger.ErrorException("Error saving user data", ex);
  102. throw;
  103. }
  104. }
  105. /// <summary>
  106. /// Retrieve all user data for the given user
  107. /// </summary>
  108. /// <param name="userId"></param>
  109. /// <returns></returns>
  110. public IEnumerable<UserItemData> GetAllUserData(Guid userId)
  111. {
  112. if (userId == Guid.Empty)
  113. {
  114. throw new ArgumentNullException("userId");
  115. }
  116. return Repository.GetAllUserData(userId);
  117. }
  118. public UserItemData GetUserData(Guid userId, Guid itemId, List<string> keys)
  119. {
  120. if (userId == Guid.Empty)
  121. {
  122. throw new ArgumentNullException("userId");
  123. }
  124. if (keys == null)
  125. {
  126. throw new ArgumentNullException("keys");
  127. }
  128. if (keys.Count == 0)
  129. {
  130. throw new ArgumentException("UserData keys cannot be empty.");
  131. }
  132. var cacheKey = GetCacheKey(userId, itemId);
  133. return _userData.GetOrAdd(cacheKey, k => GetUserDataInternal(userId, keys));
  134. }
  135. private UserItemData GetUserDataInternal(Guid userId, List<string> keys)
  136. {
  137. var userData = Repository.GetUserData(userId, keys);
  138. if (userData != null)
  139. {
  140. return userData;
  141. }
  142. if (keys.Count > 0)
  143. {
  144. return new UserItemData
  145. {
  146. UserId = userId,
  147. Key = keys[0]
  148. };
  149. }
  150. return null;
  151. }
  152. /// <summary>
  153. /// Gets the internal key.
  154. /// </summary>
  155. /// <returns>System.String.</returns>
  156. private string GetCacheKey(Guid userId, Guid itemId)
  157. {
  158. return userId.ToString("N") + itemId.ToString("N");
  159. }
  160. public UserItemData GetUserData(IHasUserData user, IHasUserData item)
  161. {
  162. return GetUserData(user.Id, item);
  163. }
  164. public UserItemData GetUserData(string userId, IHasUserData item)
  165. {
  166. return GetUserData(new Guid(userId), item);
  167. }
  168. public UserItemData GetUserData(Guid userId, IHasUserData item)
  169. {
  170. return GetUserData(userId, item.Id, item.GetUserDataKeys());
  171. }
  172. public UserItemDataDto GetUserDataDto(IHasUserData item, User user)
  173. {
  174. var userData = GetUserData(user.Id, item);
  175. var dto = GetUserItemDataDto(userData);
  176. item.FillUserDataDtoValues(dto, userData, user);
  177. return dto;
  178. }
  179. /// <summary>
  180. /// Converts a UserItemData to a DTOUserItemData
  181. /// </summary>
  182. /// <param name="data">The data.</param>
  183. /// <returns>DtoUserItemData.</returns>
  184. /// <exception cref="System.ArgumentNullException"></exception>
  185. private UserItemDataDto GetUserItemDataDto(UserItemData data)
  186. {
  187. if (data == null)
  188. {
  189. throw new ArgumentNullException("data");
  190. }
  191. return new UserItemDataDto
  192. {
  193. IsFavorite = data.IsFavorite,
  194. Likes = data.Likes,
  195. PlaybackPositionTicks = data.PlaybackPositionTicks,
  196. PlayCount = data.PlayCount,
  197. Rating = data.Rating,
  198. Played = data.Played,
  199. LastPlayedDate = data.LastPlayedDate,
  200. Key = data.Key
  201. };
  202. }
  203. public bool UpdatePlayState(BaseItem item, UserItemData data, long? reportedPositionTicks)
  204. {
  205. var playedToCompletion = false;
  206. var positionTicks = reportedPositionTicks ?? item.RunTimeTicks ?? 0;
  207. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  208. // If a position has been reported, and if we know the duration
  209. if (positionTicks > 0 && hasRuntime)
  210. {
  211. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  212. // Don't track in very beginning
  213. if (pctIn < _config.Configuration.MinResumePct)
  214. {
  215. positionTicks = 0;
  216. }
  217. // If we're at the end, assume completed
  218. else if (pctIn > _config.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  219. {
  220. positionTicks = 0;
  221. data.Played = playedToCompletion = true;
  222. }
  223. else
  224. {
  225. // Enforce MinResumeDuration
  226. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  227. if (durationSeconds < _config.Configuration.MinResumeDurationSeconds)
  228. {
  229. positionTicks = 0;
  230. data.Played = playedToCompletion = true;
  231. }
  232. }
  233. }
  234. else if (!hasRuntime)
  235. {
  236. // If we don't know the runtime we'll just have to assume it was fully played
  237. data.Played = playedToCompletion = true;
  238. positionTicks = 0;
  239. }
  240. if (item is Audio)
  241. {
  242. positionTicks = 0;
  243. }
  244. data.PlaybackPositionTicks = positionTicks;
  245. return playedToCompletion;
  246. }
  247. }
  248. }