2
0

UserManager.cs 25 KB

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