UserManager.cs 25 KB

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