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