UserManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. using System.IO;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Dto;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Audio;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Persistence;
  10. using MediaBrowser.Model.Connectivity;
  11. using MediaBrowser.Model.Logging;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Collections.Generic;
  15. using System.Linq;
  16. using System.Security.Cryptography;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Server.Implementations.Library
  21. {
  22. /// <summary>
  23. /// Class UserManager
  24. /// </summary>
  25. public class UserManager : IUserManager
  26. {
  27. /// <summary>
  28. /// The _active connections
  29. /// </summary>
  30. private readonly ConcurrentDictionary<string, ClientConnectionInfo> _activeConnections =
  31. new ConcurrentDictionary<string, ClientConnectionInfo>(StringComparer.OrdinalIgnoreCase);
  32. /// <summary>
  33. /// The _users
  34. /// </summary>
  35. private IEnumerable<User> _users;
  36. /// <summary>
  37. /// The _user lock
  38. /// </summary>
  39. private object _usersSyncLock = new object();
  40. /// <summary>
  41. /// The _users initialized
  42. /// </summary>
  43. private bool _usersInitialized;
  44. /// <summary>
  45. /// Gets the users.
  46. /// </summary>
  47. /// <value>The users.</value>
  48. public IEnumerable<User> Users
  49. {
  50. get
  51. {
  52. // Call ToList to exhaust the stream because we'll be iterating over this multiple times
  53. LazyInitializer.EnsureInitialized(ref _users, ref _usersInitialized, ref _usersSyncLock, LoadUsers);
  54. return _users;
  55. }
  56. internal set
  57. {
  58. _users = value;
  59. if (value == null)
  60. {
  61. _usersInitialized = false;
  62. }
  63. }
  64. }
  65. /// <summary>
  66. /// Gets all connections.
  67. /// </summary>
  68. /// <value>All connections.</value>
  69. public IEnumerable<ClientConnectionInfo> AllConnections
  70. {
  71. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate); }
  72. }
  73. /// <summary>
  74. /// Gets the active connections.
  75. /// </summary>
  76. /// <value>The active connections.</value>
  77. public IEnumerable<ClientConnectionInfo> RecentConnections
  78. {
  79. get { return AllConnections.Where(c => (DateTime.UtcNow - c.LastActivityDate).TotalMinutes <= 5); }
  80. }
  81. /// <summary>
  82. /// The _logger
  83. /// </summary>
  84. private readonly ILogger _logger;
  85. private readonly IUserDataRepository _userDataRepository;
  86. /// <summary>
  87. /// Gets or sets the configuration manager.
  88. /// </summary>
  89. /// <value>The configuration manager.</value>
  90. private IServerConfigurationManager ConfigurationManager { get; set; }
  91. /// <summary>
  92. /// Gets the active user repository
  93. /// </summary>
  94. /// <value>The user repository.</value>
  95. public IUserRepository UserRepository { get; set; }
  96. /// <summary>
  97. /// Initializes a new instance of the <see cref="UserManager" /> class.
  98. /// </summary>
  99. /// <param name="logger">The logger.</param>
  100. /// <param name="configurationManager">The configuration manager.</param>
  101. /// <param name="userDataRepository">The user data repository.</param>
  102. public UserManager(ILogger logger, IServerConfigurationManager configurationManager, IUserDataRepository userDataRepository)
  103. {
  104. _logger = logger;
  105. ConfigurationManager = configurationManager;
  106. _userDataRepository = userDataRepository;
  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.ToString(),
  287. Client = clientType,
  288. DeviceName = deviceName,
  289. DeviceId = deviceId
  290. });
  291. connection.DeviceName = deviceName;
  292. connection.UserId = userId.ToString();
  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. if (user.Configuration.UseCustomLibrary)
  421. {
  422. var path = user.RootFolderPath;
  423. try
  424. {
  425. Directory.Delete(path, true);
  426. }
  427. catch (IOException ex)
  428. {
  429. _logger.ErrorException("Error deleting directory {0}", ex, path);
  430. }
  431. path = user.ConfigurationFilePath;
  432. try
  433. {
  434. File.Delete(path);
  435. }
  436. catch (IOException ex)
  437. {
  438. _logger.ErrorException("Error deleting file {0}", ex, path);
  439. }
  440. }
  441. OnUserDeleted(user);
  442. // Force this to be lazy loaded again
  443. Users = null;
  444. }
  445. /// <summary>
  446. /// Resets the password by clearing it.
  447. /// </summary>
  448. /// <returns>Task.</returns>
  449. public Task ResetPassword(User user)
  450. {
  451. return ChangePassword(user, string.Empty);
  452. }
  453. /// <summary>
  454. /// Changes the password.
  455. /// </summary>
  456. /// <param name="user">The user.</param>
  457. /// <param name="newPassword">The new password.</param>
  458. /// <returns>Task.</returns>
  459. public Task ChangePassword(User user, string newPassword)
  460. {
  461. if (user == null)
  462. {
  463. throw new ArgumentNullException("user");
  464. }
  465. user.Password = string.IsNullOrEmpty(newPassword) ? string.Empty : GetSha1String(newPassword);
  466. return UpdateUser(user);
  467. }
  468. /// <summary>
  469. /// Instantiates the new user.
  470. /// </summary>
  471. /// <param name="name">The name.</param>
  472. /// <returns>User.</returns>
  473. private User InstantiateNewUser(string name)
  474. {
  475. return new User
  476. {
  477. Name = name,
  478. Id = ("MBUser" + name).GetMD5(),
  479. DateCreated = DateTime.UtcNow,
  480. DateModified = DateTime.UtcNow
  481. };
  482. }
  483. /// <summary>
  484. /// Used to report that playback has started for an item
  485. /// </summary>
  486. /// <param name="user">The user.</param>
  487. /// <param name="item">The item.</param>
  488. /// <param name="clientType">Type of the client.</param>
  489. /// <param name="deviceId">The device id.</param>
  490. /// <param name="deviceName">Name of the device.</param>
  491. /// <exception cref="System.ArgumentNullException"></exception>
  492. public void OnPlaybackStart(User user, BaseItem item, string clientType, string deviceId, string deviceName)
  493. {
  494. if (user == null)
  495. {
  496. throw new ArgumentNullException();
  497. }
  498. if (item == null)
  499. {
  500. throw new ArgumentNullException();
  501. }
  502. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  503. // Nothing to save here
  504. // Fire events to inform plugins
  505. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  506. {
  507. Item = item,
  508. User = user
  509. }, _logger);
  510. }
  511. /// <summary>
  512. /// Used to report playback progress for an item
  513. /// </summary>
  514. /// <param name="user">The user.</param>
  515. /// <param name="item">The item.</param>
  516. /// <param name="positionTicks">The position ticks.</param>
  517. /// <param name="clientType">Type of the client.</param>
  518. /// <param name="deviceId">The device id.</param>
  519. /// <param name="deviceName">Name of the device.</param>
  520. /// <returns>Task.</returns>
  521. /// <exception cref="System.ArgumentNullException"></exception>
  522. public async Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  523. {
  524. if (user == null)
  525. {
  526. throw new ArgumentNullException();
  527. }
  528. if (item == null)
  529. {
  530. throw new ArgumentNullException();
  531. }
  532. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item, positionTicks);
  533. var key = item.GetUserDataKey();
  534. if (positionTicks.HasValue)
  535. {
  536. var data = await _userDataRepository.GetUserData(user.Id, key).ConfigureAwait(false);
  537. UpdatePlayState(item, data, positionTicks.Value, false);
  538. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  539. }
  540. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  541. {
  542. Item = item,
  543. User = user,
  544. PlaybackPositionTicks = positionTicks
  545. }, _logger);
  546. }
  547. /// <summary>
  548. /// Used to report that playback has ended for an item
  549. /// </summary>
  550. /// <param name="user">The user.</param>
  551. /// <param name="item">The item.</param>
  552. /// <param name="positionTicks">The position ticks.</param>
  553. /// <param name="clientType">Type of the client.</param>
  554. /// <param name="deviceId">The device id.</param>
  555. /// <param name="deviceName">Name of the device.</param>
  556. /// <returns>Task.</returns>
  557. /// <exception cref="System.ArgumentNullException"></exception>
  558. public async Task OnPlaybackStopped(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  559. {
  560. if (user == null)
  561. {
  562. throw new ArgumentNullException();
  563. }
  564. if (item == null)
  565. {
  566. throw new ArgumentNullException();
  567. }
  568. RemoveNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  569. var key = item.GetUserDataKey();
  570. var data = await _userDataRepository.GetUserData(user.Id, key).ConfigureAwait(false);
  571. if (positionTicks.HasValue)
  572. {
  573. UpdatePlayState(item, data, positionTicks.Value, true);
  574. }
  575. else
  576. {
  577. // If the client isn't able to report this, then we'll just have to make an assumption
  578. data.PlayCount++;
  579. data.Played = true;
  580. }
  581. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  582. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  583. {
  584. Item = item,
  585. User = user,
  586. PlaybackPositionTicks = positionTicks
  587. }, _logger);
  588. }
  589. /// <summary>
  590. /// Updates playstate position for an item but does not save
  591. /// </summary>
  592. /// <param name="item">The item</param>
  593. /// <param name="data">User data for the item</param>
  594. /// <param name="positionTicks">The current playback position</param>
  595. /// <param name="incrementPlayCount">Whether or not to increment playcount</param>
  596. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks, bool incrementPlayCount)
  597. {
  598. // If a position has been reported, and if we know the duration
  599. if (positionTicks > 0 && item.RunTimeTicks.HasValue && item.RunTimeTicks > 0)
  600. {
  601. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  602. // Don't track in very beginning
  603. if (pctIn < ConfigurationManager.Configuration.MinResumePct)
  604. {
  605. positionTicks = 0;
  606. incrementPlayCount = false;
  607. }
  608. // If we're at the end, assume completed
  609. else if (pctIn > ConfigurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  610. {
  611. positionTicks = 0;
  612. data.Played = true;
  613. }
  614. else
  615. {
  616. // Enforce MinResumeDuration
  617. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  618. if (durationSeconds < ConfigurationManager.Configuration.MinResumeDurationSeconds)
  619. {
  620. positionTicks = 0;
  621. data.Played = true;
  622. }
  623. }
  624. }
  625. if (item is Audio)
  626. {
  627. data.PlaybackPositionTicks = 0;
  628. }
  629. data.PlaybackPositionTicks = positionTicks;
  630. if (incrementPlayCount)
  631. {
  632. data.PlayCount++;
  633. data.LastPlayedDate = DateTime.UtcNow;
  634. }
  635. }
  636. }
  637. }