UserManager.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Dto;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Model.Connectivity;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Security.Cryptography;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.Library
  19. {
  20. /// <summary>
  21. /// Class UserManager
  22. /// </summary>
  23. public class UserManager : IUserManager
  24. {
  25. /// <summary>
  26. /// The _active connections
  27. /// </summary>
  28. private readonly ConcurrentDictionary<string, ClientConnectionInfo> _activeConnections =
  29. new ConcurrentDictionary<string, ClientConnectionInfo>(StringComparer.OrdinalIgnoreCase);
  30. /// <summary>
  31. /// The _users
  32. /// </summary>
  33. private IEnumerable<User> _users;
  34. /// <summary>
  35. /// The _user lock
  36. /// </summary>
  37. private object _usersSyncLock = new object();
  38. /// <summary>
  39. /// The _users initialized
  40. /// </summary>
  41. private bool _usersInitialized;
  42. /// <summary>
  43. /// Gets the users.
  44. /// </summary>
  45. /// <value>The users.</value>
  46. public IEnumerable<User> Users
  47. {
  48. get
  49. {
  50. // Call ToList to exhaust the stream because we'll be iterating over this multiple times
  51. LazyInitializer.EnsureInitialized(ref _users, ref _usersInitialized, ref _usersSyncLock, LoadUsers);
  52. return _users;
  53. }
  54. internal set
  55. {
  56. _users = value;
  57. if (value == null)
  58. {
  59. _usersInitialized = false;
  60. }
  61. }
  62. }
  63. /// <summary>
  64. /// Gets all connections.
  65. /// </summary>
  66. /// <value>All connections.</value>
  67. public IEnumerable<ClientConnectionInfo> AllConnections
  68. {
  69. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate); }
  70. }
  71. /// <summary>
  72. /// Gets the active connections.
  73. /// </summary>
  74. /// <value>The active connections.</value>
  75. public IEnumerable<ClientConnectionInfo> RecentConnections
  76. {
  77. get { return AllConnections.Where(c => (DateTime.UtcNow - c.LastActivityDate).TotalMinutes <= 5); }
  78. }
  79. /// <summary>
  80. /// The _logger
  81. /// </summary>
  82. private readonly ILogger _logger;
  83. private readonly IUserDataRepository _userDataRepository;
  84. /// <summary>
  85. /// Gets or sets the configuration manager.
  86. /// </summary>
  87. /// <value>The configuration manager.</value>
  88. private IServerConfigurationManager ConfigurationManager { get; set; }
  89. /// <summary>
  90. /// Gets the active user repository
  91. /// </summary>
  92. /// <value>The user repository.</value>
  93. public IUserRepository UserRepository { get; set; }
  94. /// <summary>
  95. /// Initializes a new instance of the <see cref="UserManager" /> class.
  96. /// </summary>
  97. /// <param name="logger">The logger.</param>
  98. /// <param name="configurationManager">The configuration manager.</param>
  99. public UserManager(ILogger logger, IServerConfigurationManager configurationManager)
  100. {
  101. _logger = logger;
  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("id");
  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, string clientType, string deviceId, string deviceName)
  207. {
  208. if (user == null)
  209. {
  210. throw new ArgumentNullException("user");
  211. }
  212. var activityDate = DateTime.UtcNow;
  213. var lastActivityDate = user.LastActivityDate;
  214. user.LastActivityDate = activityDate;
  215. LogConnection(user.Id, clientType, deviceId, deviceName, activityDate);
  216. // Don't log in the db anymore frequently than 10 seconds
  217. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  218. {
  219. return Task.FromResult(true);
  220. }
  221. // Save this directly. No need to fire off all the events for this.
  222. return UserRepository.SaveUser(user, CancellationToken.None);
  223. }
  224. /// <summary>
  225. /// Updates the now playing item id.
  226. /// </summary>
  227. /// <param name="user">The user.</param>
  228. /// <param name="clientType">Type of the client.</param>
  229. /// <param name="deviceId">The device id.</param>
  230. /// <param name="deviceName">Name of the device.</param>
  231. /// <param name="item">The item.</param>
  232. /// <param name="currentPositionTicks">The current position ticks.</param>
  233. private void UpdateNowPlayingItemId(User user, string clientType, string deviceId, string deviceName, BaseItem item, long? currentPositionTicks = null)
  234. {
  235. var conn = GetConnection(user.Id, clientType, deviceId, deviceName);
  236. conn.NowPlayingPositionTicks = currentPositionTicks;
  237. conn.NowPlayingItem = DtoBuilder.GetBaseItemInfo(item);
  238. conn.LastActivityDate = DateTime.UtcNow;
  239. }
  240. /// <summary>
  241. /// Removes the now playing item id.
  242. /// </summary>
  243. /// <param name="user">The user.</param>
  244. /// <param name="clientType">Type of the client.</param>
  245. /// <param name="deviceId">The device id.</param>
  246. /// <param name="deviceName">Name of the device.</param>
  247. /// <param name="item">The item.</param>
  248. private void RemoveNowPlayingItemId(User user, string clientType, string deviceId, string deviceName, BaseItem item)
  249. {
  250. var conn = GetConnection(user.Id, clientType, deviceId, deviceName);
  251. if (conn.NowPlayingItem != null && conn.NowPlayingItem.Id.Equals(item.Id.ToString()))
  252. {
  253. conn.NowPlayingItem = null;
  254. conn.NowPlayingPositionTicks = null;
  255. }
  256. }
  257. /// <summary>
  258. /// Logs the connection.
  259. /// </summary>
  260. /// <param name="userId">The user id.</param>
  261. /// <param name="clientType">Type of the client.</param>
  262. /// <param name="deviceId">The device id.</param>
  263. /// <param name="deviceName">Name of the device.</param>
  264. /// <param name="lastActivityDate">The last activity date.</param>
  265. private void LogConnection(Guid userId, string clientType, string deviceId, string deviceName, DateTime lastActivityDate)
  266. {
  267. GetConnection(userId, clientType, deviceId, deviceName).LastActivityDate = lastActivityDate;
  268. }
  269. /// <summary>
  270. /// Gets the connection.
  271. /// </summary>
  272. /// <param name="userId">The user id.</param>
  273. /// <param name="clientType">Type of the client.</param>
  274. /// <param name="deviceId">The device id.</param>
  275. /// <param name="deviceName">Name of the device.</param>
  276. /// <returns>ClientConnectionInfo.</returns>
  277. private ClientConnectionInfo GetConnection(Guid userId, string clientType, string deviceId, string deviceName)
  278. {
  279. var key = clientType + deviceId;
  280. var connection = _activeConnections.GetOrAdd(key, keyName => new ClientConnectionInfo
  281. {
  282. UserId = userId.ToString(),
  283. Client = clientType,
  284. DeviceName = deviceName,
  285. DeviceId = deviceId
  286. });
  287. connection.UserId = userId.ToString();
  288. return connection;
  289. }
  290. /// <summary>
  291. /// Loads the users from the repository
  292. /// </summary>
  293. /// <returns>IEnumerable{User}.</returns>
  294. private IEnumerable<User> LoadUsers()
  295. {
  296. var users = UserRepository.RetrieveAllUsers().ToList();
  297. // There always has to be at least one user.
  298. if (users.Count == 0)
  299. {
  300. var name = Environment.UserName;
  301. var user = InstantiateNewUser(name);
  302. var task = UserRepository.SaveUser(user, CancellationToken.None);
  303. // Hate having to block threads
  304. Task.WaitAll(task);
  305. users.Add(user);
  306. }
  307. return users;
  308. }
  309. /// <summary>
  310. /// Refreshes metadata for each user
  311. /// </summary>
  312. /// <param name="cancellationToken">The cancellation token.</param>
  313. /// <param name="force">if set to <c>true</c> [force].</param>
  314. /// <returns>Task.</returns>
  315. public Task RefreshUsersMetadata(CancellationToken cancellationToken, bool force = false)
  316. {
  317. var tasks = Users.Select(user => user.RefreshMetadata(cancellationToken, forceRefresh: force)).ToList();
  318. return Task.WhenAll(tasks);
  319. }
  320. /// <summary>
  321. /// Renames the user.
  322. /// </summary>
  323. /// <param name="user">The user.</param>
  324. /// <param name="newName">The new name.</param>
  325. /// <returns>Task.</returns>
  326. /// <exception cref="System.ArgumentNullException">user</exception>
  327. /// <exception cref="System.ArgumentException"></exception>
  328. public async Task RenameUser(User user, string newName)
  329. {
  330. if (user == null)
  331. {
  332. throw new ArgumentNullException("user");
  333. }
  334. if (string.IsNullOrEmpty(newName))
  335. {
  336. throw new ArgumentNullException("newName");
  337. }
  338. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  339. {
  340. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  341. }
  342. if (user.Name.Equals(newName, StringComparison.Ordinal))
  343. {
  344. throw new ArgumentException("The new and old names must be different.");
  345. }
  346. await user.Rename(newName);
  347. OnUserUpdated(user);
  348. }
  349. /// <summary>
  350. /// Updates the user.
  351. /// </summary>
  352. /// <param name="user">The user.</param>
  353. /// <exception cref="System.ArgumentNullException">user</exception>
  354. /// <exception cref="System.ArgumentException"></exception>
  355. public async Task UpdateUser(User user)
  356. {
  357. if (user == null)
  358. {
  359. throw new ArgumentNullException("user");
  360. }
  361. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  362. {
  363. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  364. }
  365. user.DateModified = DateTime.UtcNow;
  366. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  367. OnUserUpdated(user);
  368. }
  369. /// <summary>
  370. /// Creates the user.
  371. /// </summary>
  372. /// <param name="name">The name.</param>
  373. /// <returns>User.</returns>
  374. /// <exception cref="System.ArgumentNullException">name</exception>
  375. /// <exception cref="System.ArgumentException"></exception>
  376. public async Task<User> CreateUser(string name)
  377. {
  378. if (string.IsNullOrEmpty(name))
  379. {
  380. throw new ArgumentNullException("name");
  381. }
  382. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  383. {
  384. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  385. }
  386. var user = InstantiateNewUser(name);
  387. var list = Users.ToList();
  388. list.Add(user);
  389. Users = list;
  390. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  391. return user;
  392. }
  393. /// <summary>
  394. /// Deletes the user.
  395. /// </summary>
  396. /// <param name="user">The user.</param>
  397. /// <returns>Task.</returns>
  398. /// <exception cref="System.ArgumentNullException">user</exception>
  399. /// <exception cref="System.ArgumentException"></exception>
  400. public async Task DeleteUser(User user)
  401. {
  402. if (user == null)
  403. {
  404. throw new ArgumentNullException("user");
  405. }
  406. if (Users.FirstOrDefault(u => u.Id == user.Id) == null)
  407. {
  408. 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));
  409. }
  410. if (Users.Count() == 1)
  411. {
  412. throw new ArgumentException(string.Format("The user '{0}' be deleted because there must be at least one user in the system.", user.Name));
  413. }
  414. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  415. OnUserDeleted(user);
  416. // Force this to be lazy loaded again
  417. Users = null;
  418. }
  419. /// <summary>
  420. /// Resets the password by clearing it.
  421. /// </summary>
  422. /// <returns>Task.</returns>
  423. public Task ResetPassword(User user)
  424. {
  425. return ChangePassword(user, string.Empty);
  426. }
  427. /// <summary>
  428. /// Changes the password.
  429. /// </summary>
  430. /// <param name="user">The user.</param>
  431. /// <param name="newPassword">The new password.</param>
  432. /// <returns>Task.</returns>
  433. public Task ChangePassword(User user, string newPassword)
  434. {
  435. if (user == null)
  436. {
  437. throw new ArgumentNullException("user");
  438. }
  439. user.Password = string.IsNullOrEmpty(newPassword) ? string.Empty : GetSha1String(newPassword);
  440. return UpdateUser(user);
  441. }
  442. /// <summary>
  443. /// Instantiates the new user.
  444. /// </summary>
  445. /// <param name="name">The name.</param>
  446. /// <returns>User.</returns>
  447. private User InstantiateNewUser(string name)
  448. {
  449. return new User
  450. {
  451. Name = name,
  452. Id = ("MBUser" + name).GetMD5(),
  453. DateCreated = DateTime.UtcNow,
  454. DateModified = DateTime.UtcNow
  455. };
  456. }
  457. /// <summary>
  458. /// Used to report that playback has started for an item
  459. /// </summary>
  460. /// <param name="user">The user.</param>
  461. /// <param name="item">The item.</param>
  462. /// <param name="clientType">Type of the client.</param>
  463. /// <param name="deviceId">The device id.</param>
  464. /// <param name="deviceName">Name of the device.</param>
  465. /// <exception cref="System.ArgumentNullException"></exception>
  466. public void OnPlaybackStart(User user, BaseItem item, string clientType, string deviceId, string deviceName)
  467. {
  468. if (user == null)
  469. {
  470. throw new ArgumentNullException();
  471. }
  472. if (item == null)
  473. {
  474. throw new ArgumentNullException();
  475. }
  476. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  477. // Nothing to save here
  478. // Fire events to inform plugins
  479. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  480. {
  481. Item = item,
  482. User = user
  483. }, _logger);
  484. }
  485. /// <summary>
  486. /// Used to report playback progress for an item
  487. /// </summary>
  488. /// <param name="user">The user.</param>
  489. /// <param name="item">The item.</param>
  490. /// <param name="positionTicks">The position ticks.</param>
  491. /// <param name="clientType">Type of the client.</param>
  492. /// <param name="deviceId">The device id.</param>
  493. /// <param name="deviceName">Name of the device.</param>
  494. /// <returns>Task.</returns>
  495. /// <exception cref="System.ArgumentNullException"></exception>
  496. public async Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  497. {
  498. if (user == null)
  499. {
  500. throw new ArgumentNullException();
  501. }
  502. if (item == null)
  503. {
  504. throw new ArgumentNullException();
  505. }
  506. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item, positionTicks);
  507. var key = item.GetUserDataKey();
  508. if (positionTicks.HasValue)
  509. {
  510. var data = await _userDataRepository.GetUserData(user.Id, key).ConfigureAwait(false);
  511. UpdatePlayState(item, data, positionTicks.Value, false);
  512. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  513. }
  514. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  515. {
  516. Item = item,
  517. User = user,
  518. PlaybackPositionTicks = positionTicks
  519. }, _logger);
  520. }
  521. /// <summary>
  522. /// Used to report that playback has ended for an item
  523. /// </summary>
  524. /// <param name="user">The user.</param>
  525. /// <param name="item">The item.</param>
  526. /// <param name="positionTicks">The position ticks.</param>
  527. /// <param name="clientType">Type of the client.</param>
  528. /// <param name="deviceId">The device id.</param>
  529. /// <param name="deviceName">Name of the device.</param>
  530. /// <returns>Task.</returns>
  531. /// <exception cref="System.ArgumentNullException"></exception>
  532. public async Task OnPlaybackStopped(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  533. {
  534. if (user == null)
  535. {
  536. throw new ArgumentNullException();
  537. }
  538. if (item == null)
  539. {
  540. throw new ArgumentNullException();
  541. }
  542. RemoveNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  543. var key = item.GetUserDataKey();
  544. var data = await _userDataRepository.GetUserData(user.Id, key).ConfigureAwait(false);
  545. if (positionTicks.HasValue)
  546. {
  547. UpdatePlayState(item, data, positionTicks.Value, true);
  548. }
  549. else
  550. {
  551. // If the client isn't able to report this, then we'll just have to make an assumption
  552. data.PlayCount++;
  553. data.Played = true;
  554. }
  555. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  556. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  557. {
  558. Item = item,
  559. User = user,
  560. PlaybackPositionTicks = positionTicks
  561. }, _logger);
  562. }
  563. /// <summary>
  564. /// Updates playstate position for an item but does not save
  565. /// </summary>
  566. /// <param name="item">The item</param>
  567. /// <param name="data">User data for the item</param>
  568. /// <param name="positionTicks">The current playback position</param>
  569. /// <param name="incrementPlayCount">Whether or not to increment playcount</param>
  570. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks, bool incrementPlayCount)
  571. {
  572. // If a position has been reported, and if we know the duration
  573. if (positionTicks > 0 && item.RunTimeTicks.HasValue && item.RunTimeTicks > 0)
  574. {
  575. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  576. // Don't track in very beginning
  577. if (pctIn < ConfigurationManager.Configuration.MinResumePct)
  578. {
  579. positionTicks = 0;
  580. incrementPlayCount = false;
  581. }
  582. // If we're at the end, assume completed
  583. else if (pctIn > ConfigurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  584. {
  585. positionTicks = 0;
  586. data.Played = true;
  587. }
  588. else
  589. {
  590. // Enforce MinResumeDuration
  591. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  592. if (durationSeconds < ConfigurationManager.Configuration.MinResumeDurationSeconds)
  593. {
  594. positionTicks = 0;
  595. data.Played = true;
  596. }
  597. }
  598. }
  599. data.PlaybackPositionTicks = positionTicks;
  600. if (incrementPlayCount)
  601. {
  602. data.PlayCount++;
  603. data.LastPlayedDate = DateTime.UtcNow;
  604. }
  605. }
  606. }
  607. }