UserManager.cs 28 KB

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