UserDataManager.cs 11 KB

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