2
0

UserManager.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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 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 <= 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. lock (_activeConnections)
  274. {
  275. var conn = _activeConnections.FirstOrDefault(c => c.ClientType == clientType && string.Equals(deviceId, c.DeviceId));
  276. if (conn == null)
  277. {
  278. conn = new ClientConnectionInfo
  279. {
  280. UserId = userId,
  281. ClientType = clientType,
  282. DeviceName = deviceName,
  283. DeviceId = deviceId
  284. };
  285. _activeConnections.Add(conn);
  286. }
  287. else
  288. {
  289. conn.UserId = userId;
  290. }
  291. return conn;
  292. }
  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 = Kernel.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 = Kernel.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 Kernel.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 Kernel.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 Kernel.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, ClientType 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. Argument = 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, ClientType 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 = item.GetUserData(user, true);
  514. UpdatePlayState(item, data, positionTicks.Value, false);
  515. await SaveUserDataForItem(user, item, data).ConfigureAwait(false);
  516. }
  517. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  518. {
  519. Argument = 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, ClientType 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 = item.GetUserData(user, true);
  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 SaveUserDataForItem(user, item, data).ConfigureAwait(false);
  558. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  559. {
  560. Argument = 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 user data for an item
  610. /// </summary>
  611. /// <param name="user">The user.</param>
  612. /// <param name="item">The item.</param>
  613. /// <param name="data">The data.</param>
  614. public Task SaveUserDataForItem(User user, BaseItem item, UserItemData data)
  615. {
  616. item.AddOrUpdateUserData(user, data);
  617. return Kernel.UserDataRepository.SaveUserData(item, CancellationToken.None);
  618. }
  619. }
  620. }