UserManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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.Logging;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Server.Implementations.Library
  16. {
  17. /// <summary>
  18. /// Class UserManager
  19. /// </summary>
  20. public class UserManager : IUserManager
  21. {
  22. /// <summary>
  23. /// The _active connections
  24. /// </summary>
  25. private readonly ConcurrentBag<ClientConnectionInfo> _activeConnections =
  26. new ConcurrentBag<ClientConnectionInfo>();
  27. /// <summary>
  28. /// The _users
  29. /// </summary>
  30. private IEnumerable<User> _users;
  31. /// <summary>
  32. /// The _user lock
  33. /// </summary>
  34. private object _usersSyncLock = new object();
  35. /// <summary>
  36. /// The _users initialized
  37. /// </summary>
  38. private bool _usersInitialized;
  39. /// <summary>
  40. /// Gets the users.
  41. /// </summary>
  42. /// <value>The users.</value>
  43. public IEnumerable<User> Users
  44. {
  45. get
  46. {
  47. // Call ToList to exhaust the stream because we'll be iterating over this multiple times
  48. LazyInitializer.EnsureInitialized(ref _users, ref _usersInitialized, ref _usersSyncLock, LoadUsers);
  49. return _users;
  50. }
  51. internal set
  52. {
  53. _users = value;
  54. if (value == null)
  55. {
  56. _usersInitialized = false;
  57. }
  58. }
  59. }
  60. /// <summary>
  61. /// Gets all connections.
  62. /// </summary>
  63. /// <value>All connections.</value>
  64. private IEnumerable<ClientConnectionInfo> AllConnections
  65. {
  66. get { return _activeConnections.Where(c => GetUserById(c.UserId) != null).OrderByDescending(c => c.LastActivityDate); }
  67. }
  68. /// <summary>
  69. /// Gets the active connections.
  70. /// </summary>
  71. /// <value>The active connections.</value>
  72. public IEnumerable<ClientConnectionInfo> ConnectedUsers
  73. {
  74. get { return AllConnections.Where(c => (DateTime.UtcNow - c.LastActivityDate).TotalMinutes <= 10); }
  75. }
  76. /// <summary>
  77. /// The _logger
  78. /// </summary>
  79. private readonly ILogger _logger;
  80. /// <summary>
  81. /// Gets or sets the kernel.
  82. /// </summary>
  83. /// <value>The kernel.</value>
  84. private Kernel Kernel { get; set; }
  85. /// <summary>
  86. /// Gets or sets the configuration manager.
  87. /// </summary>
  88. /// <value>The configuration manager.</value>
  89. private IServerConfigurationManager ConfigurationManager { get; set; }
  90. /// <summary>
  91. /// Initializes a new instance of the <see cref="UserManager" /> class.
  92. /// </summary>
  93. /// <param name="kernel">The kernel.</param>
  94. /// <param name="logger">The logger.</param>
  95. /// <param name="configurationManager">The configuration manager.</param>
  96. public UserManager(Kernel kernel, ILogger logger, IServerConfigurationManager configurationManager)
  97. {
  98. _logger = logger;
  99. Kernel = kernel;
  100. ConfigurationManager = configurationManager;
  101. }
  102. #region Events
  103. /// <summary>
  104. /// Occurs when [playback start].
  105. /// </summary>
  106. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  107. /// <summary>
  108. /// Occurs when [playback progress].
  109. /// </summary>
  110. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  111. /// <summary>
  112. /// Occurs when [playback stopped].
  113. /// </summary>
  114. public event EventHandler<PlaybackProgressEventArgs> PlaybackStopped;
  115. #endregion
  116. #region UserUpdated Event
  117. /// <summary>
  118. /// Occurs when [user updated].
  119. /// </summary>
  120. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  121. /// <summary>
  122. /// Called when [user updated].
  123. /// </summary>
  124. /// <param name="user">The user.</param>
  125. private void OnUserUpdated(User user)
  126. {
  127. EventHelper.QueueEventIfNotNull(UserUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger);
  128. }
  129. #endregion
  130. #region UserDeleted Event
  131. /// <summary>
  132. /// Occurs when [user deleted].
  133. /// </summary>
  134. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  135. /// <summary>
  136. /// Called when [user deleted].
  137. /// </summary>
  138. /// <param name="user">The user.</param>
  139. private void OnUserDeleted(User user)
  140. {
  141. EventHelper.QueueEventIfNotNull(UserDeleted, this, new GenericEventArgs<User> { Argument = user }, _logger);
  142. }
  143. #endregion
  144. /// <summary>
  145. /// Gets a User by Id
  146. /// </summary>
  147. /// <param name="id">The id.</param>
  148. /// <returns>User.</returns>
  149. /// <exception cref="System.ArgumentNullException"></exception>
  150. public User GetUserById(Guid id)
  151. {
  152. if (id == Guid.Empty)
  153. {
  154. throw new ArgumentNullException();
  155. }
  156. return Users.FirstOrDefault(u => u.Id == id);
  157. }
  158. /// <summary>
  159. /// Authenticates a User and returns a result indicating whether or not it succeeded
  160. /// </summary>
  161. /// <param name="user">The user.</param>
  162. /// <param name="password">The password.</param>
  163. /// <returns>Task{System.Boolean}.</returns>
  164. /// <exception cref="System.ArgumentNullException">user</exception>
  165. public async Task<bool> AuthenticateUser(User user, string password)
  166. {
  167. if (user == null)
  168. {
  169. throw new ArgumentNullException("user");
  170. }
  171. password = password ?? string.Empty;
  172. var existingPassword = string.IsNullOrEmpty(user.Password) ? string.Empty.GetMD5().ToString() : user.Password;
  173. var success = password.GetMD5().ToString().Equals(existingPassword);
  174. // Update LastActivityDate and LastLoginDate, then save
  175. if (success)
  176. {
  177. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  178. await UpdateUser(user).ConfigureAwait(false);
  179. }
  180. _logger.Info("Authentication request for {0} {1}.", user.Name, (success ? "has succeeded" : "has been denied"));
  181. return success;
  182. }
  183. /// <summary>
  184. /// Logs the user activity.
  185. /// </summary>
  186. /// <param name="user">The user.</param>
  187. /// <param name="clientType">Type of the client.</param>
  188. /// <param name="deviceName">Name of the device.</param>
  189. /// <returns>Task.</returns>
  190. /// <exception cref="System.ArgumentNullException">user</exception>
  191. public Task LogUserActivity(User user, ClientType clientType, string deviceName)
  192. {
  193. if (user == null)
  194. {
  195. throw new ArgumentNullException("user");
  196. }
  197. var activityDate = DateTime.UtcNow;
  198. user.LastActivityDate = activityDate;
  199. LogConnection(user.Id, clientType, deviceName, activityDate);
  200. // Save this directly. No need to fire off all the events for this.
  201. return Kernel.UserRepository.SaveUser(user, CancellationToken.None);
  202. }
  203. /// <summary>
  204. /// Updates the now playing item id.
  205. /// </summary>
  206. /// <param name="user">The user.</param>
  207. /// <param name="clientType">Type of the client.</param>
  208. /// <param name="deviceName">Name of the device.</param>
  209. /// <param name="item">The item.</param>
  210. /// <param name="currentPositionTicks">The current position ticks.</param>
  211. private void UpdateNowPlayingItemId(User user, ClientType clientType, string deviceName, BaseItem item, long? currentPositionTicks = null)
  212. {
  213. var conn = GetConnection(user.Id, clientType, deviceName);
  214. conn.NowPlayingPositionTicks = currentPositionTicks;
  215. conn.NowPlayingItem = DtoBuilder.GetBaseItemInfo(item);
  216. }
  217. /// <summary>
  218. /// Removes the now playing item id.
  219. /// </summary>
  220. /// <param name="user">The user.</param>
  221. /// <param name="clientType">Type of the client.</param>
  222. /// <param name="deviceName">Name of the device.</param>
  223. /// <param name="item">The item.</param>
  224. private void RemoveNowPlayingItemId(User user, ClientType clientType, string deviceName, BaseItem item)
  225. {
  226. var conn = GetConnection(user.Id, clientType, deviceName);
  227. if (conn.NowPlayingItem != null && conn.NowPlayingItem.Id.Equals(item.Id.ToString()))
  228. {
  229. conn.NowPlayingItem = null;
  230. conn.NowPlayingPositionTicks = null;
  231. }
  232. }
  233. /// <summary>
  234. /// Logs the connection.
  235. /// </summary>
  236. /// <param name="userId">The user id.</param>
  237. /// <param name="clientType">Type of the client.</param>
  238. /// <param name="deviceName">Name of the device.</param>
  239. /// <param name="lastActivityDate">The last activity date.</param>
  240. private void LogConnection(Guid userId, ClientType clientType, string deviceName, DateTime lastActivityDate)
  241. {
  242. GetConnection(userId, clientType, deviceName).LastActivityDate = lastActivityDate;
  243. }
  244. /// <summary>
  245. /// Gets the connection.
  246. /// </summary>
  247. /// <param name="userId">The user id.</param>
  248. /// <param name="clientType">Type of the client.</param>
  249. /// <param name="deviceName">Name of the device.</param>
  250. /// <returns>ClientConnectionInfo.</returns>
  251. private ClientConnectionInfo GetConnection(Guid userId, ClientType clientType, string deviceName)
  252. {
  253. var conn = _activeConnections.FirstOrDefault(c => c.UserId == userId && c.ClientType == clientType && string.Equals(deviceName, c.DeviceName, StringComparison.OrdinalIgnoreCase));
  254. if (conn == null)
  255. {
  256. conn = new ClientConnectionInfo
  257. {
  258. UserId = userId,
  259. ClientType = clientType,
  260. DeviceName = deviceName
  261. };
  262. _activeConnections.Add(conn);
  263. }
  264. return conn;
  265. }
  266. /// <summary>
  267. /// Loads the users from the repository
  268. /// </summary>
  269. /// <returns>IEnumerable{User}.</returns>
  270. private IEnumerable<User> LoadUsers()
  271. {
  272. var users = Kernel.UserRepository.RetrieveAllUsers().ToList();
  273. // There always has to be at least one user.
  274. if (users.Count == 0)
  275. {
  276. var name = Environment.UserName;
  277. var user = InstantiateNewUser(name);
  278. var task = Kernel.UserRepository.SaveUser(user, CancellationToken.None);
  279. // Hate having to block threads
  280. Task.WaitAll(task);
  281. users.Add(user);
  282. }
  283. return users;
  284. }
  285. /// <summary>
  286. /// Refreshes metadata for each user
  287. /// </summary>
  288. /// <param name="cancellationToken">The cancellation token.</param>
  289. /// <param name="force">if set to <c>true</c> [force].</param>
  290. /// <returns>Task.</returns>
  291. public Task RefreshUsersMetadata(CancellationToken cancellationToken, bool force = false)
  292. {
  293. var tasks = Users.Select(user => user.RefreshMetadata(cancellationToken, forceRefresh: force)).ToList();
  294. return Task.WhenAll(tasks);
  295. }
  296. /// <summary>
  297. /// Renames the user.
  298. /// </summary>
  299. /// <param name="user">The user.</param>
  300. /// <param name="newName">The new name.</param>
  301. /// <returns>Task.</returns>
  302. /// <exception cref="System.ArgumentNullException">user</exception>
  303. /// <exception cref="System.ArgumentException"></exception>
  304. public async Task RenameUser(User user, string newName)
  305. {
  306. if (user == null)
  307. {
  308. throw new ArgumentNullException("user");
  309. }
  310. if (string.IsNullOrEmpty(newName))
  311. {
  312. throw new ArgumentNullException("newName");
  313. }
  314. if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  315. {
  316. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  317. }
  318. if (user.Name.Equals(newName, StringComparison.Ordinal))
  319. {
  320. throw new ArgumentException("The new and old names must be different.");
  321. }
  322. await user.Rename(newName);
  323. OnUserUpdated(user);
  324. }
  325. /// <summary>
  326. /// Updates the user.
  327. /// </summary>
  328. /// <param name="user">The user.</param>
  329. /// <exception cref="System.ArgumentNullException">user</exception>
  330. /// <exception cref="System.ArgumentException"></exception>
  331. public async Task UpdateUser(User user)
  332. {
  333. if (user == null)
  334. {
  335. throw new ArgumentNullException("user");
  336. }
  337. if (user.Id == Guid.Empty || !Users.Any(u => u.Id.Equals(user.Id)))
  338. {
  339. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  340. }
  341. user.DateModified = DateTime.UtcNow;
  342. await Kernel.UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  343. OnUserUpdated(user);
  344. }
  345. /// <summary>
  346. /// Creates the user.
  347. /// </summary>
  348. /// <param name="name">The name.</param>
  349. /// <returns>User.</returns>
  350. /// <exception cref="System.ArgumentNullException">name</exception>
  351. /// <exception cref="System.ArgumentException"></exception>
  352. public async Task<User> CreateUser(string name)
  353. {
  354. if (string.IsNullOrEmpty(name))
  355. {
  356. throw new ArgumentNullException("name");
  357. }
  358. if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  359. {
  360. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  361. }
  362. var user = InstantiateNewUser(name);
  363. var list = Users.ToList();
  364. list.Add(user);
  365. Users = list;
  366. await Kernel.UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  367. return user;
  368. }
  369. /// <summary>
  370. /// Deletes the user.
  371. /// </summary>
  372. /// <param name="user">The user.</param>
  373. /// <returns>Task.</returns>
  374. /// <exception cref="System.ArgumentNullException">user</exception>
  375. /// <exception cref="System.ArgumentException"></exception>
  376. public async Task DeleteUser(User user)
  377. {
  378. if (user == null)
  379. {
  380. throw new ArgumentNullException("user");
  381. }
  382. if (Users.FirstOrDefault(u => u.Id == user.Id) == null)
  383. {
  384. 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));
  385. }
  386. if (Users.Count() == 1)
  387. {
  388. throw new ArgumentException(string.Format("The user '{0}' be deleted because there must be at least one user in the system.", user.Name));
  389. }
  390. await Kernel.UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  391. OnUserDeleted(user);
  392. // Force this to be lazy loaded again
  393. Users = null;
  394. }
  395. /// <summary>
  396. /// Instantiates the new user.
  397. /// </summary>
  398. /// <param name="name">The name.</param>
  399. /// <returns>User.</returns>
  400. private User InstantiateNewUser(string name)
  401. {
  402. return new User
  403. {
  404. Name = name,
  405. Id = ("MBUser" + name).GetMD5(),
  406. DateCreated = DateTime.UtcNow,
  407. DateModified = DateTime.UtcNow
  408. };
  409. }
  410. /// <summary>
  411. /// Used to report that playback has started for an item
  412. /// </summary>
  413. /// <param name="user">The user.</param>
  414. /// <param name="item">The item.</param>
  415. /// <param name="clientType">Type of the client.</param>
  416. /// <param name="deviceName">Name of the device.</param>
  417. /// <exception cref="System.ArgumentNullException"></exception>
  418. public void OnPlaybackStart(User user, BaseItem item, ClientType clientType, string deviceName)
  419. {
  420. if (user == null)
  421. {
  422. throw new ArgumentNullException();
  423. }
  424. if (item == null)
  425. {
  426. throw new ArgumentNullException();
  427. }
  428. UpdateNowPlayingItemId(user, clientType, deviceName, item);
  429. // Nothing to save here
  430. // Fire events to inform plugins
  431. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  432. {
  433. Argument = item,
  434. User = user
  435. }, _logger);
  436. }
  437. /// <summary>
  438. /// Used to report playback progress for an item
  439. /// </summary>
  440. /// <param name="user">The user.</param>
  441. /// <param name="item">The item.</param>
  442. /// <param name="positionTicks">The position ticks.</param>
  443. /// <param name="clientType">Type of the client.</param>
  444. /// <param name="deviceName">Name of the device.</param>
  445. /// <returns>Task.</returns>
  446. /// <exception cref="System.ArgumentNullException"></exception>
  447. public async Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, ClientType clientType, string deviceName)
  448. {
  449. if (user == null)
  450. {
  451. throw new ArgumentNullException();
  452. }
  453. if (item == null)
  454. {
  455. throw new ArgumentNullException();
  456. }
  457. UpdateNowPlayingItemId(user, clientType, deviceName, item, positionTicks);
  458. if (positionTicks.HasValue)
  459. {
  460. var data = item.GetUserData(user, true);
  461. UpdatePlayState(item, data, positionTicks.Value, false);
  462. await SaveUserDataForItem(user, item, data).ConfigureAwait(false);
  463. }
  464. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  465. {
  466. Argument = item,
  467. User = user,
  468. PlaybackPositionTicks = positionTicks
  469. }, _logger);
  470. }
  471. /// <summary>
  472. /// Used to report that playback has ended for an item
  473. /// </summary>
  474. /// <param name="user">The user.</param>
  475. /// <param name="item">The item.</param>
  476. /// <param name="positionTicks">The position ticks.</param>
  477. /// <param name="clientType">Type of the client.</param>
  478. /// <param name="deviceName">Name of the device.</param>
  479. /// <returns>Task.</returns>
  480. /// <exception cref="System.ArgumentNullException"></exception>
  481. public async Task OnPlaybackStopped(User user, BaseItem item, long? positionTicks, ClientType clientType, string deviceName)
  482. {
  483. if (user == null)
  484. {
  485. throw new ArgumentNullException();
  486. }
  487. if (item == null)
  488. {
  489. throw new ArgumentNullException();
  490. }
  491. RemoveNowPlayingItemId(user, clientType, deviceName, item);
  492. var data = item.GetUserData(user, true);
  493. if (positionTicks.HasValue)
  494. {
  495. UpdatePlayState(item, data, positionTicks.Value, true);
  496. }
  497. else
  498. {
  499. // If the client isn't able to report this, then we'll just have to make an assumption
  500. data.PlayCount++;
  501. data.Played = true;
  502. }
  503. await SaveUserDataForItem(user, item, data).ConfigureAwait(false);
  504. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  505. {
  506. Argument = item,
  507. User = user,
  508. PlaybackPositionTicks = positionTicks
  509. }, _logger);
  510. }
  511. /// <summary>
  512. /// Updates playstate position for an item but does not save
  513. /// </summary>
  514. /// <param name="item">The item</param>
  515. /// <param name="data">User data for the item</param>
  516. /// <param name="positionTicks">The current playback position</param>
  517. /// <param name="incrementPlayCount">Whether or not to increment playcount</param>
  518. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks, bool incrementPlayCount)
  519. {
  520. // If a position has been reported, and if we know the duration
  521. if (positionTicks > 0 && item.RunTimeTicks.HasValue && item.RunTimeTicks > 0)
  522. {
  523. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  524. // Don't track in very beginning
  525. if (pctIn < ConfigurationManager.Configuration.MinResumePct)
  526. {
  527. positionTicks = 0;
  528. incrementPlayCount = false;
  529. }
  530. // If we're at the end, assume completed
  531. else if (pctIn > ConfigurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  532. {
  533. positionTicks = 0;
  534. data.Played = true;
  535. }
  536. else
  537. {
  538. // Enforce MinResumeDuration
  539. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  540. if (durationSeconds < ConfigurationManager.Configuration.MinResumeDurationSeconds)
  541. {
  542. positionTicks = 0;
  543. data.Played = true;
  544. }
  545. }
  546. }
  547. data.PlaybackPositionTicks = positionTicks;
  548. if (incrementPlayCount)
  549. {
  550. data.PlayCount++;
  551. data.LastPlayedDate = DateTime.UtcNow;
  552. }
  553. }
  554. /// <summary>
  555. /// Saves user data for an item
  556. /// </summary>
  557. /// <param name="user">The user.</param>
  558. /// <param name="item">The item.</param>
  559. /// <param name="data">The data.</param>
  560. public Task SaveUserDataForItem(User user, BaseItem item, UserItemData data)
  561. {
  562. item.AddOrUpdateUserData(user, data);
  563. return Kernel.UserDataRepository.SaveUserData(item, CancellationToken.None);
  564. }
  565. }
  566. }