UserManager.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. var lastActivityDate = user.LastActivityDate;
  268. user.LastActivityDate = activityDate;
  269. LogConnection(user.Id, clientType, deviceId, deviceName, activityDate);
  270. // Don't log in the db anymore frequently than 10 seconds
  271. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  272. {
  273. return Task.FromResult(true);
  274. }
  275. // Save this directly. No need to fire off all the events for this.
  276. return Kernel.UserRepository.SaveUser(user, CancellationToken.None);
  277. }
  278. /// <summary>
  279. /// Updates the now playing item id.
  280. /// </summary>
  281. /// <param name="user">The user.</param>
  282. /// <param name="clientType">Type of the client.</param>
  283. /// <param name="deviceId">The device id.</param>
  284. /// <param name="deviceName">Name of the device.</param>
  285. /// <param name="item">The item.</param>
  286. /// <param name="currentPositionTicks">The current position ticks.</param>
  287. private void UpdateNowPlayingItemId(User user, string clientType, string deviceId, string deviceName, BaseItem item, long? currentPositionTicks = null)
  288. {
  289. var conn = GetConnection(user.Id, clientType, deviceId, deviceName);
  290. conn.NowPlayingPositionTicks = currentPositionTicks;
  291. conn.NowPlayingItem = DtoBuilder.GetBaseItemInfo(item);
  292. conn.LastActivityDate = DateTime.UtcNow;
  293. }
  294. /// <summary>
  295. /// Removes the now playing item id.
  296. /// </summary>
  297. /// <param name="user">The user.</param>
  298. /// <param name="clientType">Type of the client.</param>
  299. /// <param name="deviceId">The device id.</param>
  300. /// <param name="deviceName">Name of the device.</param>
  301. /// <param name="item">The item.</param>
  302. private void RemoveNowPlayingItemId(User user, string clientType, string deviceId, string deviceName, BaseItem item)
  303. {
  304. var conn = GetConnection(user.Id, clientType, deviceId, deviceName);
  305. if (conn.NowPlayingItem != null && conn.NowPlayingItem.Id.Equals(item.Id.ToString()))
  306. {
  307. conn.NowPlayingItem = null;
  308. conn.NowPlayingPositionTicks = null;
  309. }
  310. }
  311. /// <summary>
  312. /// Logs the connection.
  313. /// </summary>
  314. /// <param name="userId">The user id.</param>
  315. /// <param name="clientType">Type of the client.</param>
  316. /// <param name="deviceId">The device id.</param>
  317. /// <param name="deviceName">Name of the device.</param>
  318. /// <param name="lastActivityDate">The last activity date.</param>
  319. private void LogConnection(Guid userId, string clientType, string deviceId, string deviceName, DateTime lastActivityDate)
  320. {
  321. GetConnection(userId, clientType, deviceId, deviceName).LastActivityDate = lastActivityDate;
  322. }
  323. /// <summary>
  324. /// Gets the connection.
  325. /// </summary>
  326. /// <param name="userId">The user id.</param>
  327. /// <param name="clientType">Type of the client.</param>
  328. /// <param name="deviceId">The device id.</param>
  329. /// <param name="deviceName">Name of the device.</param>
  330. /// <returns>ClientConnectionInfo.</returns>
  331. private ClientConnectionInfo GetConnection(Guid userId, string clientType, string deviceId, string deviceName)
  332. {
  333. lock (_activeConnections)
  334. {
  335. var conn = _activeConnections.FirstOrDefault(c => string.Equals(c.Client, clientType, StringComparison.OrdinalIgnoreCase) && string.Equals(deviceId, c.DeviceId));
  336. if (conn == null)
  337. {
  338. conn = new ClientConnectionInfo
  339. {
  340. UserId = userId,
  341. Client = clientType,
  342. DeviceName = deviceName,
  343. DeviceId = deviceId
  344. };
  345. _activeConnections.Add(conn);
  346. }
  347. else
  348. {
  349. conn.UserId = userId;
  350. }
  351. return conn;
  352. }
  353. }
  354. /// <summary>
  355. /// Loads the users from the repository
  356. /// </summary>
  357. /// <returns>IEnumerable{User}.</returns>
  358. private IEnumerable<User> LoadUsers()
  359. {
  360. var users = Kernel.UserRepository.RetrieveAllUsers().ToList();
  361. // There always has to be at least one user.
  362. if (users.Count == 0)
  363. {
  364. var name = Environment.UserName;
  365. var user = InstantiateNewUser(name);
  366. var task = Kernel.UserRepository.SaveUser(user, CancellationToken.None);
  367. // Hate having to block threads
  368. Task.WaitAll(task);
  369. users.Add(user);
  370. }
  371. return users;
  372. }
  373. /// <summary>
  374. /// Refreshes metadata for each user
  375. /// </summary>
  376. /// <param name="cancellationToken">The cancellation token.</param>
  377. /// <param name="force">if set to <c>true</c> [force].</param>
  378. /// <returns>Task.</returns>
  379. public Task RefreshUsersMetadata(CancellationToken cancellationToken, bool force = false)
  380. {
  381. var tasks = Users.Select(user => user.RefreshMetadata(cancellationToken, forceRefresh: force)).ToList();
  382. return Task.WhenAll(tasks);
  383. }
  384. /// <summary>
  385. /// Renames the user.
  386. /// </summary>
  387. /// <param name="user">The user.</param>
  388. /// <param name="newName">The new name.</param>
  389. /// <returns>Task.</returns>
  390. /// <exception cref="System.ArgumentNullException">user</exception>
  391. /// <exception cref="System.ArgumentException"></exception>
  392. public async Task RenameUser(User user, string newName)
  393. {
  394. if (user == null)
  395. {
  396. throw new ArgumentNullException("user");
  397. }
  398. if (string.IsNullOrEmpty(newName))
  399. {
  400. throw new ArgumentNullException("newName");
  401. }
  402. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  403. {
  404. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  405. }
  406. if (user.Name.Equals(newName, StringComparison.Ordinal))
  407. {
  408. throw new ArgumentException("The new and old names must be different.");
  409. }
  410. await user.Rename(newName);
  411. OnUserUpdated(user);
  412. }
  413. /// <summary>
  414. /// Updates the user.
  415. /// </summary>
  416. /// <param name="user">The user.</param>
  417. /// <exception cref="System.ArgumentNullException">user</exception>
  418. /// <exception cref="System.ArgumentException"></exception>
  419. public async Task UpdateUser(User user)
  420. {
  421. if (user == null)
  422. {
  423. throw new ArgumentNullException("user");
  424. }
  425. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  426. {
  427. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  428. }
  429. user.DateModified = DateTime.UtcNow;
  430. await Kernel.UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  431. OnUserUpdated(user);
  432. }
  433. /// <summary>
  434. /// Creates the user.
  435. /// </summary>
  436. /// <param name="name">The name.</param>
  437. /// <returns>User.</returns>
  438. /// <exception cref="System.ArgumentNullException">name</exception>
  439. /// <exception cref="System.ArgumentException"></exception>
  440. public async Task<User> CreateUser(string name)
  441. {
  442. if (string.IsNullOrEmpty(name))
  443. {
  444. throw new ArgumentNullException("name");
  445. }
  446. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  447. {
  448. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  449. }
  450. var user = InstantiateNewUser(name);
  451. var list = Users.ToList();
  452. list.Add(user);
  453. Users = list;
  454. await Kernel.UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  455. return user;
  456. }
  457. /// <summary>
  458. /// Deletes the user.
  459. /// </summary>
  460. /// <param name="user">The user.</param>
  461. /// <returns>Task.</returns>
  462. /// <exception cref="System.ArgumentNullException">user</exception>
  463. /// <exception cref="System.ArgumentException"></exception>
  464. public async Task DeleteUser(User user)
  465. {
  466. if (user == null)
  467. {
  468. throw new ArgumentNullException("user");
  469. }
  470. if (Users.FirstOrDefault(u => u.Id == user.Id) == null)
  471. {
  472. 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));
  473. }
  474. if (Users.Count() == 1)
  475. {
  476. throw new ArgumentException(string.Format("The user '{0}' be deleted because there must be at least one user in the system.", user.Name));
  477. }
  478. await Kernel.UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  479. OnUserDeleted(user);
  480. // Force this to be lazy loaded again
  481. Users = null;
  482. }
  483. /// <summary>
  484. /// Resets the password by clearing it.
  485. /// </summary>
  486. /// <returns>Task.</returns>
  487. public Task ResetPassword(User user)
  488. {
  489. return ChangePassword(user, string.Empty);
  490. }
  491. /// <summary>
  492. /// Changes the password.
  493. /// </summary>
  494. /// <param name="user">The user.</param>
  495. /// <param name="newPassword">The new password.</param>
  496. /// <returns>Task.</returns>
  497. public Task ChangePassword(User user, string newPassword)
  498. {
  499. if (user == null)
  500. {
  501. throw new ArgumentNullException("user");
  502. }
  503. user.Password = string.IsNullOrEmpty(newPassword) ? string.Empty : GetSha1String(newPassword);
  504. return UpdateUser(user);
  505. }
  506. /// <summary>
  507. /// Instantiates the new user.
  508. /// </summary>
  509. /// <param name="name">The name.</param>
  510. /// <returns>User.</returns>
  511. private User InstantiateNewUser(string name)
  512. {
  513. return new User
  514. {
  515. Name = name,
  516. Id = ("MBUser" + name).GetMD5(),
  517. DateCreated = DateTime.UtcNow,
  518. DateModified = DateTime.UtcNow
  519. };
  520. }
  521. /// <summary>
  522. /// Used to report that playback has started for an item
  523. /// </summary>
  524. /// <param name="user">The user.</param>
  525. /// <param name="item">The item.</param>
  526. /// <param name="clientType">Type of the client.</param>
  527. /// <param name="deviceId">The device id.</param>
  528. /// <param name="deviceName">Name of the device.</param>
  529. /// <exception cref="System.ArgumentNullException"></exception>
  530. public void OnPlaybackStart(User user, BaseItem item, string clientType, string deviceId, string deviceName)
  531. {
  532. if (user == null)
  533. {
  534. throw new ArgumentNullException();
  535. }
  536. if (item == null)
  537. {
  538. throw new ArgumentNullException();
  539. }
  540. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  541. // Nothing to save here
  542. // Fire events to inform plugins
  543. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  544. {
  545. Item = item,
  546. User = user
  547. }, _logger);
  548. }
  549. /// <summary>
  550. /// Used to report playback progress for an item
  551. /// </summary>
  552. /// <param name="user">The user.</param>
  553. /// <param name="item">The item.</param>
  554. /// <param name="positionTicks">The position ticks.</param>
  555. /// <param name="clientType">Type of the client.</param>
  556. /// <param name="deviceId">The device id.</param>
  557. /// <param name="deviceName">Name of the device.</param>
  558. /// <returns>Task.</returns>
  559. /// <exception cref="System.ArgumentNullException"></exception>
  560. public async Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  561. {
  562. if (user == null)
  563. {
  564. throw new ArgumentNullException();
  565. }
  566. if (item == null)
  567. {
  568. throw new ArgumentNullException();
  569. }
  570. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item, positionTicks);
  571. if (positionTicks.HasValue)
  572. {
  573. var data = await GetUserData(user.Id, item.UserDataId).ConfigureAwait(false);
  574. UpdatePlayState(item, data, positionTicks.Value, false);
  575. await SaveUserData(user.Id, item.UserDataId, data, CancellationToken.None).ConfigureAwait(false);
  576. }
  577. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  578. {
  579. Item = item,
  580. User = user,
  581. PlaybackPositionTicks = positionTicks
  582. }, _logger);
  583. }
  584. /// <summary>
  585. /// Used to report that playback has ended for an item
  586. /// </summary>
  587. /// <param name="user">The user.</param>
  588. /// <param name="item">The item.</param>
  589. /// <param name="positionTicks">The position ticks.</param>
  590. /// <param name="clientType">Type of the client.</param>
  591. /// <param name="deviceId">The device id.</param>
  592. /// <param name="deviceName">Name of the device.</param>
  593. /// <returns>Task.</returns>
  594. /// <exception cref="System.ArgumentNullException"></exception>
  595. public async Task OnPlaybackStopped(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  596. {
  597. if (user == null)
  598. {
  599. throw new ArgumentNullException();
  600. }
  601. if (item == null)
  602. {
  603. throw new ArgumentNullException();
  604. }
  605. RemoveNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  606. var data = await GetUserData(user.Id, item.UserDataId).ConfigureAwait(false);
  607. if (positionTicks.HasValue)
  608. {
  609. UpdatePlayState(item, data, positionTicks.Value, true);
  610. }
  611. else
  612. {
  613. // If the client isn't able to report this, then we'll just have to make an assumption
  614. data.PlayCount++;
  615. data.Played = true;
  616. }
  617. await SaveUserData(user.Id, item.UserDataId, data, CancellationToken.None).ConfigureAwait(false);
  618. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  619. {
  620. Item = item,
  621. User = user,
  622. PlaybackPositionTicks = positionTicks
  623. }, _logger);
  624. }
  625. /// <summary>
  626. /// Updates playstate position for an item but does not save
  627. /// </summary>
  628. /// <param name="item">The item</param>
  629. /// <param name="data">User data for the item</param>
  630. /// <param name="positionTicks">The current playback position</param>
  631. /// <param name="incrementPlayCount">Whether or not to increment playcount</param>
  632. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks, bool incrementPlayCount)
  633. {
  634. // If a position has been reported, and if we know the duration
  635. if (positionTicks > 0 && item.RunTimeTicks.HasValue && item.RunTimeTicks > 0)
  636. {
  637. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  638. // Don't track in very beginning
  639. if (pctIn < ConfigurationManager.Configuration.MinResumePct)
  640. {
  641. positionTicks = 0;
  642. incrementPlayCount = false;
  643. }
  644. // If we're at the end, assume completed
  645. else if (pctIn > ConfigurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  646. {
  647. positionTicks = 0;
  648. data.Played = true;
  649. }
  650. else
  651. {
  652. // Enforce MinResumeDuration
  653. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  654. if (durationSeconds < ConfigurationManager.Configuration.MinResumeDurationSeconds)
  655. {
  656. positionTicks = 0;
  657. data.Played = true;
  658. }
  659. }
  660. }
  661. data.PlaybackPositionTicks = positionTicks;
  662. if (incrementPlayCount)
  663. {
  664. data.PlayCount++;
  665. data.LastPlayedDate = DateTime.UtcNow;
  666. }
  667. }
  668. /// <summary>
  669. /// Saves display preferences for an item
  670. /// </summary>
  671. /// <param name="userId">The user id.</param>
  672. /// <param name="userDataId">The user data id.</param>
  673. /// <param name="userData">The user data.</param>
  674. /// <param name="cancellationToken">The cancellation token.</param>
  675. /// <returns>Task.</returns>
  676. public async Task SaveUserData(Guid userId, Guid userDataId, UserItemData userData, CancellationToken cancellationToken)
  677. {
  678. var key = userId + userDataId.ToString();
  679. try
  680. {
  681. await Kernel.Instance.UserDataRepository.SaveUserData(userId, userDataId, userData, cancellationToken).ConfigureAwait(false);
  682. var newValue = Task.FromResult(userData);
  683. // Once it succeeds, put it into the dictionary to make it available to everyone else
  684. _userData.AddOrUpdate(key, newValue, delegate { return newValue; });
  685. }
  686. catch (Exception ex)
  687. {
  688. _logger.ErrorException("Error saving user data", ex);
  689. throw;
  690. }
  691. }
  692. /// <summary>
  693. /// Gets the display preferences.
  694. /// </summary>
  695. /// <param name="userId">The user id.</param>
  696. /// <param name="userDataId">The user data id.</param>
  697. /// <returns>Task{DisplayPreferences}.</returns>
  698. public Task<UserItemData> GetUserData(Guid userId, Guid userDataId)
  699. {
  700. var key = userId + userDataId.ToString();
  701. return _userData.GetOrAdd(key, keyName => RetrieveUserData(userId, userDataId));
  702. }
  703. /// <summary>
  704. /// Retrieves the display preferences.
  705. /// </summary>
  706. /// <param name="userId">The user id.</param>
  707. /// <param name="userDataId">The user data id.</param>
  708. /// <returns>DisplayPreferences.</returns>
  709. private async Task<UserItemData> RetrieveUserData(Guid userId, Guid userDataId)
  710. {
  711. var userdata = await Kernel.Instance.UserDataRepository.GetUserData(userId, userDataId).ConfigureAwait(false);
  712. return userdata ?? new UserItemData();
  713. }
  714. }
  715. }