UserDataManager.cs 9.8 KB

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