UserManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Kernel;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Model.Connectivity;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Controller.Library
  13. {
  14. /// <summary>
  15. /// Class UserManager
  16. /// </summary>
  17. public class UserManager : BaseManager<Kernel>
  18. {
  19. /// <summary>
  20. /// The _active connections
  21. /// </summary>
  22. private readonly ConcurrentBag<ClientConnectionInfo> _activeConnections =
  23. new ConcurrentBag<ClientConnectionInfo>();
  24. /// <summary>
  25. /// Gets all connections.
  26. /// </summary>
  27. /// <value>All connections.</value>
  28. public IEnumerable<ClientConnectionInfo> AllConnections
  29. {
  30. get { return _activeConnections.Where(c => Kernel.GetUserById(c.UserId) != null).OrderByDescending(c => c.LastActivityDate); }
  31. }
  32. /// <summary>
  33. /// Gets the active connections.
  34. /// </summary>
  35. /// <value>The active connections.</value>
  36. public IEnumerable<ClientConnectionInfo> ActiveConnections
  37. {
  38. get { return AllConnections.Where(c => (DateTime.UtcNow - c.LastActivityDate).TotalMinutes <= 10); }
  39. }
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="UserManager" /> class.
  42. /// </summary>
  43. /// <param name="kernel">The kernel.</param>
  44. public UserManager(Kernel kernel)
  45. : base(kernel)
  46. {
  47. }
  48. #region UserUpdated Event
  49. /// <summary>
  50. /// Occurs when [user updated].
  51. /// </summary>
  52. public event EventHandler<GenericEventArgs<User>> UserUpdated;
  53. /// <summary>
  54. /// Called when [user updated].
  55. /// </summary>
  56. /// <param name="user">The user.</param>
  57. internal void OnUserUpdated(User user)
  58. {
  59. EventHelper.QueueEventIfNotNull(UserUpdated, this, new GenericEventArgs<User> { Argument = user });
  60. // Notify connected ui's
  61. Kernel.TcpManager.SendWebSocketMessage("UserUpdated", DtoBuilder.GetDtoUser(user));
  62. }
  63. #endregion
  64. #region UserDeleted Event
  65. /// <summary>
  66. /// Occurs when [user deleted].
  67. /// </summary>
  68. public event EventHandler<GenericEventArgs<User>> UserDeleted;
  69. /// <summary>
  70. /// Called when [user deleted].
  71. /// </summary>
  72. /// <param name="user">The user.</param>
  73. internal void OnUserDeleted(User user)
  74. {
  75. EventHelper.QueueEventIfNotNull(UserDeleted, this, new GenericEventArgs<User> { Argument = user });
  76. // Notify connected ui's
  77. Kernel.TcpManager.SendWebSocketMessage("UserDeleted", user.Id.ToString());
  78. }
  79. #endregion
  80. /// <summary>
  81. /// Authenticates a User and returns a result indicating whether or not it succeeded
  82. /// </summary>
  83. /// <param name="user">The user.</param>
  84. /// <param name="password">The password.</param>
  85. /// <returns>Task{System.Boolean}.</returns>
  86. /// <exception cref="System.ArgumentNullException">user</exception>
  87. public async Task<bool> AuthenticateUser(User user, string password)
  88. {
  89. if (user == null)
  90. {
  91. throw new ArgumentNullException("user");
  92. }
  93. password = password ?? string.Empty;
  94. var existingPassword = string.IsNullOrEmpty(user.Password) ? string.Empty.GetMD5().ToString() : user.Password;
  95. var success = password.GetMD5().ToString().Equals(existingPassword);
  96. // Update LastActivityDate and LastLoginDate, then save
  97. if (success)
  98. {
  99. user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
  100. await UpdateUser(user).ConfigureAwait(false);
  101. }
  102. Logger.Info("Authentication request for {0} {1}.", user.Name, (success ? "has succeeded" : "has been denied"));
  103. return success;
  104. }
  105. /// <summary>
  106. /// Logs the user activity.
  107. /// </summary>
  108. /// <param name="user">The user.</param>
  109. /// <param name="clientType">Type of the client.</param>
  110. /// <param name="deviceName">Name of the device.</param>
  111. /// <returns>Task.</returns>
  112. /// <exception cref="System.ArgumentNullException">user</exception>
  113. public Task LogUserActivity(User user, ClientType clientType, string deviceName)
  114. {
  115. if (user == null)
  116. {
  117. throw new ArgumentNullException("user");
  118. }
  119. var activityDate = DateTime.UtcNow;
  120. user.LastActivityDate = activityDate;
  121. LogConnection(user.Id, clientType, deviceName, activityDate);
  122. // Save this directly. No need to fire off all the events for this.
  123. return Kernel.UserRepository.SaveUser(user, CancellationToken.None);
  124. }
  125. /// <summary>
  126. /// Updates the now playing item id.
  127. /// </summary>
  128. /// <param name="user">The user.</param>
  129. /// <param name="clientType">Type of the client.</param>
  130. /// <param name="deviceName">Name of the device.</param>
  131. /// <param name="item">The item.</param>
  132. /// <param name="currentPositionTicks">The current position ticks.</param>
  133. public void UpdateNowPlayingItemId(User user, ClientType clientType, string deviceName, BaseItem item, long? currentPositionTicks = null)
  134. {
  135. var conn = GetConnection(user.Id, clientType, deviceName);
  136. conn.NowPlayingPositionTicks = currentPositionTicks;
  137. conn.NowPlayingItem = DtoBuilder.GetBaseItemInfo(item);
  138. }
  139. /// <summary>
  140. /// Removes the now playing item id.
  141. /// </summary>
  142. /// <param name="user">The user.</param>
  143. /// <param name="clientType">Type of the client.</param>
  144. /// <param name="deviceName">Name of the device.</param>
  145. /// <param name="item">The item.</param>
  146. public void RemoveNowPlayingItemId(User user, ClientType clientType, string deviceName, BaseItem item)
  147. {
  148. var conn = GetConnection(user.Id, clientType, deviceName);
  149. if (conn.NowPlayingItem != null && conn.NowPlayingItem.Id.Equals(item.Id.ToString()))
  150. {
  151. conn.NowPlayingItem = null;
  152. conn.NowPlayingPositionTicks = null;
  153. }
  154. }
  155. /// <summary>
  156. /// Logs the connection.
  157. /// </summary>
  158. /// <param name="userId">The user id.</param>
  159. /// <param name="clientType">Type of the client.</param>
  160. /// <param name="deviceName">Name of the device.</param>
  161. /// <param name="lastActivityDate">The last activity date.</param>
  162. private void LogConnection(Guid userId, ClientType clientType, string deviceName, DateTime lastActivityDate)
  163. {
  164. GetConnection(userId, clientType, deviceName).LastActivityDate = lastActivityDate;
  165. }
  166. /// <summary>
  167. /// Gets the connection.
  168. /// </summary>
  169. /// <param name="userId">The user id.</param>
  170. /// <param name="clientType">Type of the client.</param>
  171. /// <param name="deviceName">Name of the device.</param>
  172. /// <returns>ClientConnectionInfo.</returns>
  173. private ClientConnectionInfo GetConnection(Guid userId, ClientType clientType, string deviceName)
  174. {
  175. var conn = _activeConnections.FirstOrDefault(c => c.UserId == userId && c.ClientType == clientType && string.Equals(deviceName, c.DeviceName, StringComparison.OrdinalIgnoreCase));
  176. if (conn == null)
  177. {
  178. conn = new ClientConnectionInfo
  179. {
  180. UserId = userId,
  181. ClientType = clientType,
  182. DeviceName = deviceName
  183. };
  184. _activeConnections.Add(conn);
  185. }
  186. return conn;
  187. }
  188. /// <summary>
  189. /// Loads the users from the repository
  190. /// </summary>
  191. /// <returns>IEnumerable{User}.</returns>
  192. internal IEnumerable<User> LoadUsers()
  193. {
  194. var users = Kernel.UserRepository.RetrieveAllUsers().ToList();
  195. // There always has to be at least one user.
  196. if (users.Count == 0)
  197. {
  198. var name = Environment.UserName;
  199. var user = InstantiateNewUser(name);
  200. var task = Kernel.UserRepository.SaveUser(user, CancellationToken.None);
  201. // Hate having to block threads
  202. Task.WaitAll(task);
  203. users.Add(user);
  204. }
  205. return users;
  206. }
  207. /// <summary>
  208. /// Refreshes metadata for each user
  209. /// </summary>
  210. /// <param name="cancellationToken">The cancellation token.</param>
  211. /// <param name="force">if set to <c>true</c> [force].</param>
  212. /// <returns>Task.</returns>
  213. public Task RefreshUsersMetadata(CancellationToken cancellationToken, bool force = false)
  214. {
  215. var tasks = Kernel.Users.Select(user => user.RefreshMetadata(cancellationToken, forceRefresh: force)).ToList();
  216. return Task.WhenAll(tasks);
  217. }
  218. /// <summary>
  219. /// Renames the user.
  220. /// </summary>
  221. /// <param name="user">The user.</param>
  222. /// <param name="newName">The new name.</param>
  223. /// <returns>Task.</returns>
  224. /// <exception cref="System.ArgumentNullException">user</exception>
  225. /// <exception cref="System.ArgumentException"></exception>
  226. public async Task RenameUser(User user, string newName)
  227. {
  228. if (user == null)
  229. {
  230. throw new ArgumentNullException("user");
  231. }
  232. if (string.IsNullOrEmpty(newName))
  233. {
  234. throw new ArgumentNullException("newName");
  235. }
  236. if (Kernel.Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
  237. {
  238. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
  239. }
  240. if (user.Name.Equals(newName, StringComparison.Ordinal))
  241. {
  242. throw new ArgumentException("The new and old names must be different.");
  243. }
  244. await user.Rename(newName);
  245. OnUserUpdated(user);
  246. }
  247. /// <summary>
  248. /// Updates the user.
  249. /// </summary>
  250. /// <param name="user">The user.</param>
  251. /// <exception cref="System.ArgumentNullException">user</exception>
  252. /// <exception cref="System.ArgumentException"></exception>
  253. public async Task UpdateUser(User user)
  254. {
  255. if (user == null)
  256. {
  257. throw new ArgumentNullException("user");
  258. }
  259. if (user.Id == Guid.Empty || !Kernel.Users.Any(u => u.Id.Equals(user.Id)))
  260. {
  261. throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
  262. }
  263. user.DateModified = DateTime.UtcNow;
  264. await Kernel.UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  265. OnUserUpdated(user);
  266. }
  267. /// <summary>
  268. /// Creates the user.
  269. /// </summary>
  270. /// <param name="name">The name.</param>
  271. /// <returns>User.</returns>
  272. /// <exception cref="System.ArgumentNullException">name</exception>
  273. /// <exception cref="System.ArgumentException"></exception>
  274. public async Task<User> CreateUser(string name)
  275. {
  276. if (string.IsNullOrEmpty(name))
  277. {
  278. throw new ArgumentNullException("name");
  279. }
  280. if (Kernel.Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
  281. {
  282. throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
  283. }
  284. var user = InstantiateNewUser(name);
  285. var list = Kernel.Users.ToList();
  286. list.Add(user);
  287. Kernel.Users = list;
  288. await Kernel.UserRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  289. return user;
  290. }
  291. /// <summary>
  292. /// Deletes the user.
  293. /// </summary>
  294. /// <param name="user">The user.</param>
  295. /// <returns>Task.</returns>
  296. /// <exception cref="System.ArgumentNullException">user</exception>
  297. /// <exception cref="System.ArgumentException"></exception>
  298. public async Task DeleteUser(User user)
  299. {
  300. if (user == null)
  301. {
  302. throw new ArgumentNullException("user");
  303. }
  304. if (Kernel.Users.FirstOrDefault(u => u.Id == user.Id) == null)
  305. {
  306. 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));
  307. }
  308. if (Kernel.Users.Count() == 1)
  309. {
  310. throw new ArgumentException(string.Format("The user '{0}' be deleted because there must be at least one user in the system.", user.Name));
  311. }
  312. await Kernel.UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false);
  313. OnUserDeleted(user);
  314. // Force this to be lazy loaded again
  315. Kernel.Users = null;
  316. }
  317. /// <summary>
  318. /// Instantiates the new user.
  319. /// </summary>
  320. /// <param name="name">The name.</param>
  321. /// <returns>User.</returns>
  322. private User InstantiateNewUser(string name)
  323. {
  324. return new User
  325. {
  326. Name = name,
  327. Id = ("MBUser" + name).GetMD5(),
  328. DateCreated = DateTime.UtcNow,
  329. DateModified = DateTime.UtcNow
  330. };
  331. }
  332. }
  333. }