UserManager.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Model.Connectivity;
  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.Security.Cryptography;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.Library
  19. {
  20. /// <summary>
  21. /// Class UserManager
  22. /// </summary>
  23. public class UserManager : IUserManager
  24. {
  25. /// <summary>
  26. /// The _active connections
  27. /// </summary>
  28. private readonly ConcurrentDictionary<string, ClientConnectionInfo> _activeConnections =
  29. new ConcurrentDictionary<string, ClientConnectionInfo>(StringComparer.OrdinalIgnoreCase);
  30. /// <summary>
  31. /// The _users
  32. /// </summary>
  33. private IEnumerable<User> _users;
  34. /// <summary>
  35. /// The _user lock
  36. /// </summary>
  37. private object _usersSyncLock = new object();
  38. /// <summary>
  39. /// The _users initialized
  40. /// </summary>
  41. private bool _usersInitialized;
  42. /// <summary>
  43. /// Gets the users.
  44. /// </summary>
  45. /// <value>The users.</value>
  46. public IEnumerable<User> Users
  47. {
  48. get
  49. {
  50. // Call ToList to exhaust the stream because we'll be iterating over this multiple times
  51. LazyInitializer.EnsureInitialized(ref _users, ref _usersInitialized, ref _usersSyncLock, LoadUsers);
  52. return _users;
  53. }
  54. internal set
  55. {
  56. _users = value;
  57. if (value == null)
  58. {
  59. _usersInitialized = false;
  60. }
  61. }
  62. }
  63. /// <summary>
  64. /// Gets all connections.
  65. /// </summary>
  66. /// <value>All connections.</value>
  67. public IEnumerable<ClientConnectionInfo> AllConnections
  68. {
  69. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate); }
  70. }
  71. /// <summary>
  72. /// Gets the active connections.
  73. /// </summary>
  74. /// <value>The active connections.</value>
  75. public IEnumerable<ClientConnectionInfo> RecentConnections
  76. {
  77. get { return AllConnections.Where(c => (DateTime.UtcNow - c.LastActivityDate).TotalMinutes <= 5); }
  78. }
  79. /// <summary>
  80. /// The _logger
  81. /// </summary>
  82. private readonly ILogger _logger;
  83. /// <summary>
  84. /// Gets or sets the configuration manager.
  85. /// </summary>
  86. /// <value>The configuration manager.</value>
  87. private IServerConfigurationManager ConfigurationManager { get; set; }
  88. private readonly ConcurrentDictionary<string, Task<UserItemData>> _userData = new ConcurrentDictionary<string, Task<UserItemData>>();
  89. /// <summary>
  90. /// Gets the active user data repository
  91. /// </summary>
  92. /// <value>The user data repository.</value>
  93. public IUserDataRepository UserDataRepository { get; set; }
  94. /// <summary>
  95. /// Gets the active user repository
  96. /// </summary>
  97. /// <value>The user repository.</value>
  98. public IUserRepository UserRepository { get; set; }
  99. /// <summary>
  100. /// Initializes a new instance of the <see cref="UserManager" /> class.
  101. /// </summary>
  102. /// <param name="logger">The logger.</param>
  103. /// <param name="configurationManager">The configuration manager.</param>
  104. public UserManager(ILogger logger, IServerConfigurationManager configurationManager)
  105. {
  106. _logger = logger;
  107. ConfigurationManager = configurationManager;
  108. }
  109. #region Events
  110. /// <summary>
  111. /// Occurs when [playback start].
  112. /// </summary>
  113. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  114. /// <summary>
  115. /// Occurs when [playback progress].
  116. /// </summary>
  117. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  118. /// <summary>
  119. /// Occurs when [playback stopped].
  120. /// </summary>
  121. public event EventHandler<PlaybackProgressEventArgs> PlaybackStopped;
  122. #endregion
  123. #region UserUpdated Event
  124. /// <summary>
  125. /// Occurs when [user updated].
  126. /// </summary>
  127. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  128. /// <summary>
  129. /// Called when [user updated].
  130. /// </summary>
  131. /// <param name="user">The user.</param>
  132. private void OnUserUpdated(User user)
  133. {
  134. EventHelper.QueueEventIfNotNull(UserUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  135. }
  136. #endregion
  137. #region UserDeleted Event
  138. /// <summary>
  139. /// Occurs when [user deleted].
  140. /// </summary>
  141. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  142. /// <summary>
  143. /// Called when [user deleted].
  144. /// </summary>
  145. /// <param name="user">The user.</param>
  146. private void OnUserDeleted(User user)
  147. {
  148. EventHelper.QueueEventIfNotNull(UserDeleted, this, new GenericEventArgs<User> { Argument = user }, _logger);
  149. }
  150. #endregion
  151. /// <summary>
  152. /// Gets a User by Id
  153. /// </summary>
  154. /// <param name="id">The id.</param>
  155. /// <returns>User.</returns>
  156. /// <exception cref="System.ArgumentNullException"></exception>
  157. public User GetUserById(Guid id)
  158. {
  159. if (id == Guid.Empty)
  160. {
  161. throw new ArgumentNullException("id");
  162. }
  163. return Users.FirstOrDefault(u => u.Id == id);
  164. }
  165. /// <summary>
  166. /// Authenticates a User and returns a result indicating whether or not it succeeded
  167. /// </summary>
  168. /// <param name="user">The user.</param>
  169. /// <param name="password">The password.</param>
  170. /// <returns>Task{System.Boolean}.</returns>
  171. /// <exception cref="System.ArgumentNullException">user</exception>
  172. public async Task<bool> AuthenticateUser(User user, string password)
  173. {
  174. if (user == null)
  175. {
  176. throw new ArgumentNullException("user");
  177. }
  178. var existingPasswordString = string.IsNullOrEmpty(user.Password) ? GetSha1String(string.Empty) : user.Password;
  179. var success = string.Equals(existingPasswordString, password.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
  180. // Update LastActivityDate and LastLoginDate, then save
  181. if (success)
  182. {
  183. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  184. await UpdateUser(user).ConfigureAwait(false);
  185. }
  186. _logger.Info("Authentication request for {0} {1}.", user.Name, (success ? "has succeeded" : "has been denied"));
  187. return success;
  188. }
  189. /// <summary>
  190. /// Gets the sha1 string.
  191. /// </summary>
  192. /// <param name="str">The STR.</param>
  193. /// <returns>System.String.</returns>
  194. private static string GetSha1String(string str)
  195. {
  196. using (var provider = SHA1.Create())
  197. {
  198. var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(str));
  199. return BitConverter.ToString(hash).Replace("-", string.Empty);
  200. }
  201. }
  202. /// <summary>
  203. /// Logs the user activity.
  204. /// </summary>
  205. /// <param name="user">The user.</param>
  206. /// <param name="clientType">Type of the client.</param>
  207. /// <param name="deviceId">The device id.</param>
  208. /// <param name="deviceName">Name of the device.</param>
  209. /// <returns>Task.</returns>
  210. /// <exception cref="System.ArgumentNullException">user</exception>
  211. public Task LogUserActivity(User user, string clientType, string deviceId, string deviceName)
  212. {
  213. if (user == null)
  214. {
  215. throw new ArgumentNullException("user");
  216. }
  217. var activityDate = DateTime.UtcNow;
  218. var lastActivityDate = user.LastActivityDate;
  219. user.LastActivityDate = activityDate;
  220. LogConnection(user.Id, clientType, deviceId, deviceName, activityDate);
  221. // Don't log in the db anymore frequently than 10 seconds
  222. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  223. {
  224. return Task.FromResult(true);
  225. }
  226. // Save this directly. No need to fire off all the events for this.
  227. return UserRepository.SaveUser(user, CancellationToken.None);
  228. }
  229. /// <summary>
  230. /// Updates the now playing item id.
  231. /// </summary>
  232. /// <param name="user">The user.</param>
  233. /// <param name="clientType">Type of the client.</param>
  234. /// <param name="deviceId">The device id.</param>
  235. /// <param name="deviceName">Name of the device.</param>
  236. /// <param name="item">The item.</param>
  237. /// <param name="currentPositionTicks">The current position ticks.</param>
  238. private void UpdateNowPlayingItemId(User user, string clientType, string deviceId, string deviceName, BaseItem item, long? currentPositionTicks = null)
  239. {
  240. var conn = GetConnection(user.Id, clientType, deviceId, deviceName);
  241. conn.NowPlayingPositionTicks = currentPositionTicks;
  242. conn.NowPlayingItem = DtoBuilder.GetBaseItemInfo(item);
  243. conn.LastActivityDate = DateTime.UtcNow;
  244. }
  245. /// <summary>
  246. /// Removes the now playing item id.
  247. /// </summary>
  248. /// <param name="user">The user.</param>
  249. /// <param name="clientType">Type of the client.</param>
  250. /// <param name="deviceId">The device id.</param>
  251. /// <param name="deviceName">Name of the device.</param>
  252. /// <param name="item">The item.</param>
  253. private void RemoveNowPlayingItemId(User user, string clientType, string deviceId, string deviceName, BaseItem item)
  254. {
  255. var conn = GetConnection(user.Id, clientType, deviceId, deviceName);
  256. if (conn.NowPlayingItem != null && conn.NowPlayingItem.Id.Equals(item.Id.ToString()))
  257. {
  258. conn.NowPlayingItem = null;
  259. conn.NowPlayingPositionTicks = null;
  260. }
  261. }
  262. /// <summary>
  263. /// Logs the connection.
  264. /// </summary>
  265. /// <param name="userId">The user id.</param>
  266. /// <param name="clientType">Type of the client.</param>
  267. /// <param name="deviceId">The device id.</param>
  268. /// <param name="deviceName">Name of the device.</param>
  269. /// <param name="lastActivityDate">The last activity date.</param>
  270. private void LogConnection(Guid userId, string clientType, string deviceId, string deviceName, DateTime lastActivityDate)
  271. {
  272. GetConnection(userId, clientType, deviceId, deviceName).LastActivityDate = lastActivityDate;
  273. }
  274. /// <summary>
  275. /// Gets the connection.
  276. /// </summary>
  277. /// <param name="userId">The user id.</param>
  278. /// <param name="clientType">Type of the client.</param>
  279. /// <param name="deviceId">The device id.</param>
  280. /// <param name="deviceName">Name of the device.</param>
  281. /// <returns>ClientConnectionInfo.</returns>
  282. private ClientConnectionInfo GetConnection(Guid userId, string clientType, string deviceId, string deviceName)
  283. {
  284. var key = clientType + deviceId;
  285. var connection = _activeConnections.GetOrAdd(key, keyName => new ClientConnectionInfo
  286. {
  287. UserId = userId,
  288. Client = clientType,
  289. DeviceName = deviceName,
  290. DeviceId = deviceId
  291. });
  292. connection.UserId = userId;
  293. return connection;
  294. }
  295. /// <summary>
  296. /// Loads the users from the repository
  297. /// </summary>
  298. /// <returns>IEnumerable{User}.</returns>
  299. private IEnumerable<User> LoadUsers()
  300. {
  301. var users = UserRepository.RetrieveAllUsers().ToList();
  302. // There always has to be at least one user.
  303. if (users.Count == 0)
  304. {
  305. var name = Environment.UserName;
  306. var user = InstantiateNewUser(name);
  307. var task = UserRepository.SaveUser(user, CancellationToken.None);
  308. // Hate having to block threads
  309. Task.WaitAll(task);
  310. users.Add(user);
  311. }
  312. return users;
  313. }
  314. /// <summary>
  315. /// Refreshes metadata for each user
  316. /// </summary>
  317. /// <param name="cancellationToken">The cancellation token.</param>
  318. /// <param name="force">if set to <c>true</c> [force].</param>
  319. /// <returns>Task.</returns>
  320. public Task RefreshUsersMetadata(CancellationToken cancellationToken, bool force = false)
  321. {
  322. var tasks = Users.Select(user => user.RefreshMetadata(cancellationToken, forceRefresh: force)).ToList();
  323. return Task.WhenAll(tasks);
  324. }
  325. /// <summary>
  326. /// Renames the user.
  327. /// </summary>
  328. /// <param name="user">The user.</param>
  329. /// <param name="newName">The new name.</param>
  330. /// <returns>Task.</returns>
  331. /// <exception cref="System.ArgumentNullException">user</exception>
  332. /// <exception cref="System.ArgumentException"></exception>
  333. public async Task RenameUser(User user, string newName)
  334. {
  335. if (user == null)
  336. {
  337. throw new ArgumentNullException("user");
  338. }
  339. if (string.IsNullOrEmpty(newName))
  340. {
  341. throw new ArgumentNullException("newName");
  342. }
  343. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  344. {
  345. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  346. }
  347. if (user.Name.Equals(newName, StringComparison.Ordinal))
  348. {
  349. throw new ArgumentException("The new and old names must be different.");
  350. }
  351. await user.Rename(newName);
  352. OnUserUpdated(user);
  353. }
  354. /// <summary>
  355. /// Updates the user.
  356. /// </summary>
  357. /// <param name="user">The user.</param>
  358. /// <exception cref="System.ArgumentNullException">user</exception>
  359. /// <exception cref="System.ArgumentException"></exception>
  360. public async Task UpdateUser(User user)
  361. {
  362. if (user == null)
  363. {
  364. throw new ArgumentNullException("user");
  365. }
  366. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  367. {
  368. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  369. }
  370. user.DateModified = DateTime.UtcNow;
  371. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  372. OnUserUpdated(user);
  373. }
  374. /// <summary>
  375. /// Creates the user.
  376. /// </summary>
  377. /// <param name="name">The name.</param>
  378. /// <returns>User.</returns>
  379. /// <exception cref="System.ArgumentNullException">name</exception>
  380. /// <exception cref="System.ArgumentException"></exception>
  381. public async Task<User> CreateUser(string name)
  382. {
  383. if (string.IsNullOrEmpty(name))
  384. {
  385. throw new ArgumentNullException("name");
  386. }
  387. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  388. {
  389. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  390. }
  391. var user = InstantiateNewUser(name);
  392. var list = Users.ToList();
  393. list.Add(user);
  394. Users = list;
  395. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  396. return user;
  397. }
  398. /// <summary>
  399. /// Deletes the user.
  400. /// </summary>
  401. /// <param name="user">The user.</param>
  402. /// <returns>Task.</returns>
  403. /// <exception cref="System.ArgumentNullException">user</exception>
  404. /// <exception cref="System.ArgumentException"></exception>
  405. public async Task DeleteUser(User user)
  406. {
  407. if (user == null)
  408. {
  409. throw new ArgumentNullException("user");
  410. }
  411. if (Users.FirstOrDefault(u => u.Id == user.Id) == null)
  412. {
  413. throw new ArgumentException(string.Format("The user cannot be deleted because there is no user with the Name {0} and Id {1}.", user.Name, user.Id));
  414. }
  415. if (Users.Count() == 1)
  416. {
  417. throw new ArgumentException(string.Format("The user '{0}' be deleted because there must be at least one user in the system.", user.Name));
  418. }
  419. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  420. OnUserDeleted(user);
  421. // Force this to be lazy loaded again
  422. Users = null;
  423. }
  424. /// <summary>
  425. /// Resets the password by clearing it.
  426. /// </summary>
  427. /// <returns>Task.</returns>
  428. public Task ResetPassword(User user)
  429. {
  430. return ChangePassword(user, string.Empty);
  431. }
  432. /// <summary>
  433. /// Changes the password.
  434. /// </summary>
  435. /// <param name="user">The user.</param>
  436. /// <param name="newPassword">The new password.</param>
  437. /// <returns>Task.</returns>
  438. public Task ChangePassword(User user, string newPassword)
  439. {
  440. if (user == null)
  441. {
  442. throw new ArgumentNullException("user");
  443. }
  444. user.Password = string.IsNullOrEmpty(newPassword) ? string.Empty : GetSha1String(newPassword);
  445. return UpdateUser(user);
  446. }
  447. /// <summary>
  448. /// Instantiates the new user.
  449. /// </summary>
  450. /// <param name="name">The name.</param>
  451. /// <returns>User.</returns>
  452. private User InstantiateNewUser(string name)
  453. {
  454. return new User
  455. {
  456. Name = name,
  457. Id = ("MBUser" + name).GetMD5(),
  458. DateCreated = DateTime.UtcNow,
  459. DateModified = DateTime.UtcNow
  460. };
  461. }
  462. /// <summary>
  463. /// Used to report that playback has started for an item
  464. /// </summary>
  465. /// <param name="user">The user.</param>
  466. /// <param name="item">The item.</param>
  467. /// <param name="clientType">Type of the client.</param>
  468. /// <param name="deviceId">The device id.</param>
  469. /// <param name="deviceName">Name of the device.</param>
  470. /// <exception cref="System.ArgumentNullException"></exception>
  471. public void OnPlaybackStart(User user, BaseItem item, string clientType, string deviceId, string deviceName)
  472. {
  473. if (user == null)
  474. {
  475. throw new ArgumentNullException();
  476. }
  477. if (item == null)
  478. {
  479. throw new ArgumentNullException();
  480. }
  481. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  482. // Nothing to save here
  483. // Fire events to inform plugins
  484. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  485. {
  486. Item = item,
  487. User = user
  488. }, _logger);
  489. }
  490. /// <summary>
  491. /// Used to report playback progress for an item
  492. /// </summary>
  493. /// <param name="user">The user.</param>
  494. /// <param name="item">The item.</param>
  495. /// <param name="positionTicks">The position ticks.</param>
  496. /// <param name="clientType">Type of the client.</param>
  497. /// <param name="deviceId">The device id.</param>
  498. /// <param name="deviceName">Name of the device.</param>
  499. /// <returns>Task.</returns>
  500. /// <exception cref="System.ArgumentNullException"></exception>
  501. public async Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  502. {
  503. if (user == null)
  504. {
  505. throw new ArgumentNullException();
  506. }
  507. if (item == null)
  508. {
  509. throw new ArgumentNullException();
  510. }
  511. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item, positionTicks);
  512. if (positionTicks.HasValue)
  513. {
  514. var data = await GetUserData(user.Id, item.UserDataId).ConfigureAwait(false);
  515. UpdatePlayState(item, data, positionTicks.Value, false);
  516. await SaveUserData(user.Id, item.UserDataId, data, CancellationToken.None).ConfigureAwait(false);
  517. }
  518. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  519. {
  520. Item = item,
  521. User = user,
  522. PlaybackPositionTicks = positionTicks
  523. }, _logger);
  524. }
  525. /// <summary>
  526. /// Used to report that playback has ended for an item
  527. /// </summary>
  528. /// <param name="user">The user.</param>
  529. /// <param name="item">The item.</param>
  530. /// <param name="positionTicks">The position ticks.</param>
  531. /// <param name="clientType">Type of the client.</param>
  532. /// <param name="deviceId">The device id.</param>
  533. /// <param name="deviceName">Name of the device.</param>
  534. /// <returns>Task.</returns>
  535. /// <exception cref="System.ArgumentNullException"></exception>
  536. public async Task OnPlaybackStopped(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  537. {
  538. if (user == null)
  539. {
  540. throw new ArgumentNullException();
  541. }
  542. if (item == null)
  543. {
  544. throw new ArgumentNullException();
  545. }
  546. RemoveNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  547. var data = await GetUserData(user.Id, item.UserDataId).ConfigureAwait(false);
  548. if (positionTicks.HasValue)
  549. {
  550. UpdatePlayState(item, data, positionTicks.Value, true);
  551. }
  552. else
  553. {
  554. // If the client isn't able to report this, then we'll just have to make an assumption
  555. data.PlayCount++;
  556. data.Played = true;
  557. }
  558. await SaveUserData(user.Id, item.UserDataId, data, CancellationToken.None).ConfigureAwait(false);
  559. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  560. {
  561. Item = item,
  562. User = user,
  563. PlaybackPositionTicks = positionTicks
  564. }, _logger);
  565. }
  566. /// <summary>
  567. /// Updates playstate position for an item but does not save
  568. /// </summary>
  569. /// <param name="item">The item</param>
  570. /// <param name="data">User data for the item</param>
  571. /// <param name="positionTicks">The current playback position</param>
  572. /// <param name="incrementPlayCount">Whether or not to increment playcount</param>
  573. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks, bool incrementPlayCount)
  574. {
  575. // If a position has been reported, and if we know the duration
  576. if (positionTicks > 0 && item.RunTimeTicks.HasValue && item.RunTimeTicks > 0)
  577. {
  578. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  579. // Don't track in very beginning
  580. if (pctIn < ConfigurationManager.Configuration.MinResumePct)
  581. {
  582. positionTicks = 0;
  583. incrementPlayCount = false;
  584. }
  585. // If we're at the end, assume completed
  586. else if (pctIn > ConfigurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  587. {
  588. positionTicks = 0;
  589. data.Played = true;
  590. }
  591. else
  592. {
  593. // Enforce MinResumeDuration
  594. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  595. if (durationSeconds < ConfigurationManager.Configuration.MinResumeDurationSeconds)
  596. {
  597. positionTicks = 0;
  598. data.Played = true;
  599. }
  600. }
  601. }
  602. data.PlaybackPositionTicks = positionTicks;
  603. if (incrementPlayCount)
  604. {
  605. data.PlayCount++;
  606. data.LastPlayedDate = DateTime.UtcNow;
  607. }
  608. }
  609. /// <summary>
  610. /// Saves display preferences for an item
  611. /// </summary>
  612. /// <param name="userId">The user id.</param>
  613. /// <param name="userDataId">The user data id.</param>
  614. /// <param name="userData">The user data.</param>
  615. /// <param name="cancellationToken">The cancellation token.</param>
  616. /// <returns>Task.</returns>
  617. public async Task SaveUserData(Guid userId, Guid userDataId, UserItemData userData, CancellationToken cancellationToken)
  618. {
  619. var key = userId + userDataId.ToString();
  620. try
  621. {
  622. await UserDataRepository.SaveUserData(userId, userDataId, userData, cancellationToken).ConfigureAwait(false);
  623. var newValue = Task.FromResult(userData);
  624. // Once it succeeds, put it into the dictionary to make it available to everyone else
  625. _userData.AddOrUpdate(key, newValue, delegate { return newValue; });
  626. }
  627. catch (Exception ex)
  628. {
  629. _logger.ErrorException("Error saving user data", ex);
  630. throw;
  631. }
  632. }
  633. /// <summary>
  634. /// Gets the user data.
  635. /// </summary>
  636. /// <param name="userId">The user id.</param>
  637. /// <param name="userDataId">The user data id.</param>
  638. /// <returns>Task{UserItemData}.</returns>
  639. public Task<UserItemData> GetUserData(Guid userId, Guid userDataId)
  640. {
  641. var key = userId + userDataId.ToString();
  642. return _userData.GetOrAdd(key, keyName => RetrieveUserData(userId, userDataId));
  643. }
  644. /// <summary>
  645. /// Retrieves the user data.
  646. /// </summary>
  647. /// <param name="userId">The user id.</param>
  648. /// <param name="userDataId">The user data id.</param>
  649. /// <returns>Task{UserItemData}.</returns>
  650. private async Task<UserItemData> RetrieveUserData(Guid userId, Guid userDataId)
  651. {
  652. var userdata = await UserDataRepository.GetUserData(userId, userDataId).ConfigureAwait(false);
  653. return userdata ?? new UserItemData();
  654. }
  655. }
  656. }