UserManager.cs 28 KB

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