UserManager.cs 30 KB

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