UserDataManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. public UserItemData GetUserData(Guid userId, List<string> keys)
  121. {
  122. if (userId == Guid.Empty)
  123. {
  124. throw new ArgumentNullException("userId");
  125. }
  126. if (keys == null)
  127. {
  128. throw new ArgumentNullException("keys");
  129. }
  130. lock (_userData)
  131. {
  132. foreach (var key in keys)
  133. {
  134. var cacheKey = GetCacheKey(userId, key);
  135. UserItemData value;
  136. if (_userData.TryGetValue(cacheKey, out value))
  137. {
  138. return value;
  139. }
  140. value = Repository.GetUserData(userId, key);
  141. if (value != null)
  142. {
  143. _userData[cacheKey] = value;
  144. return value;
  145. }
  146. }
  147. }
  148. if (keys.Count > 0)
  149. {
  150. return new UserItemData
  151. {
  152. UserId = userId,
  153. Key = keys[0]
  154. };
  155. }
  156. return null;
  157. }
  158. /// <summary>
  159. /// Gets the user data.
  160. /// </summary>
  161. /// <param name="userId">The user id.</param>
  162. /// <param name="key">The key.</param>
  163. /// <returns>Task{UserItemData}.</returns>
  164. public UserItemData GetUserData(Guid userId, string key)
  165. {
  166. if (userId == Guid.Empty)
  167. {
  168. throw new ArgumentNullException("userId");
  169. }
  170. if (string.IsNullOrEmpty(key))
  171. {
  172. throw new ArgumentNullException("key");
  173. }
  174. lock (_userData)
  175. {
  176. var cacheKey = GetCacheKey(userId, key);
  177. UserItemData value;
  178. if (_userData.TryGetValue(cacheKey, out value))
  179. {
  180. return value;
  181. }
  182. value = Repository.GetUserData(userId, key);
  183. if (value == null)
  184. {
  185. value = new UserItemData
  186. {
  187. UserId = userId,
  188. Key = key
  189. };
  190. }
  191. _userData[cacheKey] = value;
  192. return value;
  193. }
  194. }
  195. /// <summary>
  196. /// Gets the internal key.
  197. /// </summary>
  198. /// <param name="userId">The user id.</param>
  199. /// <param name="key">The key.</param>
  200. /// <returns>System.String.</returns>
  201. private string GetCacheKey(Guid userId, string key)
  202. {
  203. return userId + key;
  204. }
  205. public UserItemData GetUserData(IHasUserData user, IHasUserData item)
  206. {
  207. return GetUserData(user.Id, item);
  208. }
  209. public UserItemData GetUserData(string userId, IHasUserData item)
  210. {
  211. return GetUserData(new Guid(userId), item);
  212. }
  213. public UserItemData GetUserData(Guid userId, IHasUserData item)
  214. {
  215. return GetUserData(userId, item.GetUserDataKeys());
  216. }
  217. public UserItemDataDto GetUserDataDto(IHasUserData item, User user)
  218. {
  219. var userData = GetUserData(user.Id, item);
  220. var dto = GetUserItemDataDto(userData);
  221. item.FillUserDataDtoValues(dto, userData, user);
  222. return dto;
  223. }
  224. /// <summary>
  225. /// Converts a UserItemData to a DTOUserItemData
  226. /// </summary>
  227. /// <param name="data">The data.</param>
  228. /// <returns>DtoUserItemData.</returns>
  229. /// <exception cref="System.ArgumentNullException"></exception>
  230. private UserItemDataDto GetUserItemDataDto(UserItemData data)
  231. {
  232. if (data == null)
  233. {
  234. throw new ArgumentNullException("data");
  235. }
  236. return new UserItemDataDto
  237. {
  238. IsFavorite = data.IsFavorite,
  239. Likes = data.Likes,
  240. PlaybackPositionTicks = data.PlaybackPositionTicks,
  241. PlayCount = data.PlayCount,
  242. Rating = data.Rating,
  243. Played = data.Played,
  244. LastPlayedDate = data.LastPlayedDate,
  245. Key = data.Key
  246. };
  247. }
  248. public bool UpdatePlayState(BaseItem item, UserItemData data, long? reportedPositionTicks)
  249. {
  250. var playedToCompletion = false;
  251. var positionTicks = reportedPositionTicks ?? item.RunTimeTicks ?? 0;
  252. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  253. // If a position has been reported, and if we know the duration
  254. if (positionTicks > 0 && hasRuntime)
  255. {
  256. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  257. // Don't track in very beginning
  258. if (pctIn < _config.Configuration.MinResumePct)
  259. {
  260. positionTicks = 0;
  261. }
  262. // If we're at the end, assume completed
  263. else if (pctIn > _config.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  264. {
  265. positionTicks = 0;
  266. data.Played = playedToCompletion = true;
  267. }
  268. else
  269. {
  270. // Enforce MinResumeDuration
  271. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  272. if (durationSeconds < _config.Configuration.MinResumeDurationSeconds)
  273. {
  274. positionTicks = 0;
  275. data.Played = playedToCompletion = true;
  276. }
  277. }
  278. }
  279. else if (!hasRuntime)
  280. {
  281. // If we don't know the runtime we'll just have to assume it was fully played
  282. data.Played = playedToCompletion = true;
  283. positionTicks = 0;
  284. }
  285. if (item is Audio)
  286. {
  287. positionTicks = 0;
  288. }
  289. data.PlaybackPositionTicks = positionTicks;
  290. return playedToCompletion;
  291. }
  292. }
  293. }