UserManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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.DeviceName = deviceName;
  290. connection.UserId = userId.ToString();
  291. return connection;
  292. }
  293. /// <summary>
  294. /// Loads the users from the repository
  295. /// </summary>
  296. /// <returns>IEnumerable{User}.</returns>
  297. private IEnumerable<User> LoadUsers()
  298. {
  299. var users = UserRepository.RetrieveAllUsers().ToList();
  300. // There always has to be at least one user.
  301. if (users.Count == 0)
  302. {
  303. var name = Environment.UserName;
  304. var user = InstantiateNewUser(name);
  305. var task = UserRepository.SaveUser(user, CancellationToken.None);
  306. // Hate having to block threads
  307. Task.WaitAll(task);
  308. users.Add(user);
  309. }
  310. return users;
  311. }
  312. /// <summary>
  313. /// Refreshes metadata for each user
  314. /// </summary>
  315. /// <param name="cancellationToken">The cancellation token.</param>
  316. /// <param name="force">if set to <c>true</c> [force].</param>
  317. /// <returns>Task.</returns>
  318. public Task RefreshUsersMetadata(CancellationToken cancellationToken, bool force = false)
  319. {
  320. var tasks = Users.Select(user => user.RefreshMetadata(cancellationToken, forceRefresh: force)).ToList();
  321. return Task.WhenAll(tasks);
  322. }
  323. /// <summary>
  324. /// Renames the user.
  325. /// </summary>
  326. /// <param name="user">The user.</param>
  327. /// <param name="newName">The new name.</param>
  328. /// <returns>Task.</returns>
  329. /// <exception cref="System.ArgumentNullException">user</exception>
  330. /// <exception cref="System.ArgumentException"></exception>
  331. public async Task RenameUser(User user, string newName)
  332. {
  333. if (user == null)
  334. {
  335. throw new ArgumentNullException("user");
  336. }
  337. if (string.IsNullOrEmpty(newName))
  338. {
  339. throw new ArgumentNullException("newName");
  340. }
  341. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  342. {
  343. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  344. }
  345. if (user.Name.Equals(newName, StringComparison.Ordinal))
  346. {
  347. throw new ArgumentException("The new and old names must be different.");
  348. }
  349. await user.Rename(newName);
  350. OnUserUpdated(user);
  351. }
  352. /// <summary>
  353. /// Updates the user.
  354. /// </summary>
  355. /// <param name="user">The user.</param>
  356. /// <exception cref="System.ArgumentNullException">user</exception>
  357. /// <exception cref="System.ArgumentException"></exception>
  358. public async Task UpdateUser(User user)
  359. {
  360. if (user == null)
  361. {
  362. throw new ArgumentNullException("user");
  363. }
  364. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  365. {
  366. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  367. }
  368. user.DateModified = DateTime.UtcNow;
  369. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  370. OnUserUpdated(user);
  371. }
  372. /// <summary>
  373. /// Creates the user.
  374. /// </summary>
  375. /// <param name="name">The name.</param>
  376. /// <returns>User.</returns>
  377. /// <exception cref="System.ArgumentNullException">name</exception>
  378. /// <exception cref="System.ArgumentException"></exception>
  379. public async Task<User> CreateUser(string name)
  380. {
  381. if (string.IsNullOrEmpty(name))
  382. {
  383. throw new ArgumentNullException("name");
  384. }
  385. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  386. {
  387. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  388. }
  389. var user = InstantiateNewUser(name);
  390. var list = Users.ToList();
  391. list.Add(user);
  392. Users = list;
  393. await UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  394. return user;
  395. }
  396. /// <summary>
  397. /// Deletes the user.
  398. /// </summary>
  399. /// <param name="user">The user.</param>
  400. /// <returns>Task.</returns>
  401. /// <exception cref="System.ArgumentNullException">user</exception>
  402. /// <exception cref="System.ArgumentException"></exception>
  403. public async Task DeleteUser(User user)
  404. {
  405. if (user == null)
  406. {
  407. throw new ArgumentNullException("user");
  408. }
  409. if (Users.FirstOrDefault(u => u.Id == user.Id) == null)
  410. {
  411. 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));
  412. }
  413. if (Users.Count() == 1)
  414. {
  415. throw new ArgumentException(string.Format("The user '{0}' be deleted because there must be at least one user in the system.", user.Name));
  416. }
  417. await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  418. OnUserDeleted(user);
  419. // Force this to be lazy loaded again
  420. Users = null;
  421. }
  422. /// <summary>
  423. /// Resets the password by clearing it.
  424. /// </summary>
  425. /// <returns>Task.</returns>
  426. public Task ResetPassword(User user)
  427. {
  428. return ChangePassword(user, string.Empty);
  429. }
  430. /// <summary>
  431. /// Changes the password.
  432. /// </summary>
  433. /// <param name="user">The user.</param>
  434. /// <param name="newPassword">The new password.</param>
  435. /// <returns>Task.</returns>
  436. public Task ChangePassword(User user, string newPassword)
  437. {
  438. if (user == null)
  439. {
  440. throw new ArgumentNullException("user");
  441. }
  442. user.Password = string.IsNullOrEmpty(newPassword) ? string.Empty : GetSha1String(newPassword);
  443. return UpdateUser(user);
  444. }
  445. /// <summary>
  446. /// Instantiates the new user.
  447. /// </summary>
  448. /// <param name="name">The name.</param>
  449. /// <returns>User.</returns>
  450. private User InstantiateNewUser(string name)
  451. {
  452. return new User
  453. {
  454. Name = name,
  455. Id = ("MBUser" + name).GetMD5(),
  456. DateCreated = DateTime.UtcNow,
  457. DateModified = DateTime.UtcNow
  458. };
  459. }
  460. /// <summary>
  461. /// Used to report that playback has started for an item
  462. /// </summary>
  463. /// <param name="user">The user.</param>
  464. /// <param name="item">The item.</param>
  465. /// <param name="clientType">Type of the client.</param>
  466. /// <param name="deviceId">The device id.</param>
  467. /// <param name="deviceName">Name of the device.</param>
  468. /// <exception cref="System.ArgumentNullException"></exception>
  469. public void OnPlaybackStart(User user, BaseItem item, string clientType, string deviceId, string deviceName)
  470. {
  471. if (user == null)
  472. {
  473. throw new ArgumentNullException();
  474. }
  475. if (item == null)
  476. {
  477. throw new ArgumentNullException();
  478. }
  479. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  480. // Nothing to save here
  481. // Fire events to inform plugins
  482. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  483. {
  484. Item = item,
  485. User = user
  486. }, _logger);
  487. }
  488. /// <summary>
  489. /// Used to report playback progress for an item
  490. /// </summary>
  491. /// <param name="user">The user.</param>
  492. /// <param name="item">The item.</param>
  493. /// <param name="positionTicks">The position ticks.</param>
  494. /// <param name="clientType">Type of the client.</param>
  495. /// <param name="deviceId">The device id.</param>
  496. /// <param name="deviceName">Name of the device.</param>
  497. /// <returns>Task.</returns>
  498. /// <exception cref="System.ArgumentNullException"></exception>
  499. public async Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  500. {
  501. if (user == null)
  502. {
  503. throw new ArgumentNullException();
  504. }
  505. if (item == null)
  506. {
  507. throw new ArgumentNullException();
  508. }
  509. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item, positionTicks);
  510. var key = item.GetUserDataKey();
  511. if (positionTicks.HasValue)
  512. {
  513. var data = await _userDataRepository.GetUserData(user.Id, key).ConfigureAwait(false);
  514. UpdatePlayState(item, data, positionTicks.Value, false);
  515. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  516. }
  517. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  518. {
  519. Item = 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, string 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 key = item.GetUserDataKey();
  547. var data = await _userDataRepository.GetUserData(user.Id, key).ConfigureAwait(false);
  548. if (positionTicks.HasValue)
  549. {
  550. UpdatePlayState(item, data, positionTicks.Value, true);
  551. }
  552. else
  553. {
  554. // If the client isn't able to report this, then we'll just have to make an assumption
  555. data.PlayCount++;
  556. data.Played = true;
  557. }
  558. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  559. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  560. {
  561. Item = item,
  562. User = user,
  563. PlaybackPositionTicks = positionTicks
  564. }, _logger);
  565. }
  566. /// <summary>
  567. /// Updates playstate position for an item but does not save
  568. /// </summary>
  569. /// <param name="item">The item</param>
  570. /// <param name="data">User data for the item</param>
  571. /// <param name="positionTicks">The current playback position</param>
  572. /// <param name="incrementPlayCount">Whether or not to increment playcount</param>
  573. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks, bool incrementPlayCount)
  574. {
  575. // If a position has been reported, and if we know the duration
  576. if (positionTicks > 0 && item.RunTimeTicks.HasValue && item.RunTimeTicks > 0)
  577. {
  578. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  579. // Don't track in very beginning
  580. if (pctIn < ConfigurationManager.Configuration.MinResumePct)
  581. {
  582. positionTicks = 0;
  583. incrementPlayCount = false;
  584. }
  585. // If we're at the end, assume completed
  586. else if (pctIn > ConfigurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  587. {
  588. positionTicks = 0;
  589. data.Played = true;
  590. }
  591. else
  592. {
  593. // Enforce MinResumeDuration
  594. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  595. if (durationSeconds < ConfigurationManager.Configuration.MinResumeDurationSeconds)
  596. {
  597. positionTicks = 0;
  598. data.Played = true;
  599. }
  600. }
  601. }
  602. data.PlaybackPositionTicks = positionTicks;
  603. if (incrementPlayCount)
  604. {
  605. data.PlayCount++;
  606. data.LastPlayedDate = DateTime.UtcNow;
  607. }
  608. }
  609. }
  610. }