UserDataManager.cs 9.3 KB

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