UserManager.cs 28 KB

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