UserDataManager.cs 9.8 KB

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