SessionManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Audio;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Controller.Session;
  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.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Server.Implementations.Session
  17. {
  18. /// <summary>
  19. /// Class SessionManager
  20. /// </summary>
  21. public class SessionManager : ISessionManager
  22. {
  23. /// <summary>
  24. /// The _user data repository
  25. /// </summary>
  26. private readonly IUserDataRepository _userDataRepository;
  27. /// <summary>
  28. /// The _user repository
  29. /// </summary>
  30. private readonly IUserRepository _userRepository;
  31. /// <summary>
  32. /// The _logger
  33. /// </summary>
  34. private readonly ILogger _logger;
  35. /// <summary>
  36. /// Gets or sets the configuration manager.
  37. /// </summary>
  38. /// <value>The configuration manager.</value>
  39. private readonly IServerConfigurationManager _configurationManager;
  40. /// <summary>
  41. /// The _active connections
  42. /// </summary>
  43. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  44. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  45. /// <summary>
  46. /// Occurs when [playback start].
  47. /// </summary>
  48. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  49. /// <summary>
  50. /// Occurs when [playback progress].
  51. /// </summary>
  52. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  53. /// <summary>
  54. /// Occurs when [playback stopped].
  55. /// </summary>
  56. public event EventHandler<PlaybackProgressEventArgs> PlaybackStopped;
  57. /// <summary>
  58. /// Initializes a new instance of the <see cref="SessionManager"/> class.
  59. /// </summary>
  60. /// <param name="userDataRepository">The user data repository.</param>
  61. /// <param name="configurationManager">The configuration manager.</param>
  62. /// <param name="logger">The logger.</param>
  63. /// <param name="userRepository">The user repository.</param>
  64. public SessionManager(IUserDataRepository userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository)
  65. {
  66. _userDataRepository = userDataRepository;
  67. _configurationManager = configurationManager;
  68. _logger = logger;
  69. _userRepository = userRepository;
  70. }
  71. /// <summary>
  72. /// Gets all connections.
  73. /// </summary>
  74. /// <value>All connections.</value>
  75. public IEnumerable<SessionInfo> Sessions
  76. {
  77. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList(); }
  78. }
  79. /// <summary>
  80. /// The _true task result
  81. /// </summary>
  82. private readonly Task _trueTaskResult = Task.FromResult(true);
  83. /// <summary>
  84. /// Logs the user activity.
  85. /// </summary>
  86. /// <param name="clientType">Type of the client.</param>
  87. /// <param name="appVersion">The app version.</param>
  88. /// <param name="deviceId">The device id.</param>
  89. /// <param name="deviceName">Name of the device.</param>
  90. /// <param name="user">The user.</param>
  91. /// <returns>Task.</returns>
  92. /// <exception cref="System.UnauthorizedAccessException"></exception>
  93. /// <exception cref="System.ArgumentNullException">user</exception>
  94. public async Task<SessionInfo> LogConnectionActivity(string clientType, string appVersion, string deviceId, string deviceName, User user)
  95. {
  96. if (string.IsNullOrEmpty(clientType))
  97. {
  98. throw new ArgumentNullException("clientType");
  99. }
  100. if (string.IsNullOrEmpty(appVersion))
  101. {
  102. throw new ArgumentNullException("appVersion");
  103. }
  104. if (string.IsNullOrEmpty(deviceId))
  105. {
  106. throw new ArgumentNullException("deviceId");
  107. }
  108. if (string.IsNullOrEmpty(deviceName))
  109. {
  110. throw new ArgumentNullException("deviceName");
  111. }
  112. if (user != null && user.Configuration.IsDisabled)
  113. {
  114. throw new UnauthorizedAccessException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  115. }
  116. var activityDate = DateTime.UtcNow;
  117. var session = GetSessionInfo(clientType, appVersion, deviceId, deviceName, user);
  118. session.LastActivityDate = activityDate;
  119. if (user == null)
  120. {
  121. return session;
  122. }
  123. var lastActivityDate = user.LastActivityDate;
  124. user.LastActivityDate = activityDate;
  125. // Don't log in the db anymore frequently than 10 seconds
  126. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  127. {
  128. return session;
  129. }
  130. // Save this directly. No need to fire off all the events for this.
  131. await _userRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  132. return session;
  133. }
  134. /// <summary>
  135. /// Updates the now playing item id.
  136. /// </summary>
  137. /// <param name="session">The session.</param>
  138. /// <param name="item">The item.</param>
  139. /// <param name="isPaused">if set to <c>true</c> [is paused].</param>
  140. /// <param name="currentPositionTicks">The current position ticks.</param>
  141. private void UpdateNowPlayingItem(SessionInfo session, BaseItem item, bool isPaused, long? currentPositionTicks = null)
  142. {
  143. session.IsPaused = isPaused;
  144. session.NowPlayingPositionTicks = currentPositionTicks;
  145. session.NowPlayingItem = item;
  146. session.LastActivityDate = DateTime.UtcNow;
  147. }
  148. /// <summary>
  149. /// Removes the now playing item id.
  150. /// </summary>
  151. /// <param name="session">The session.</param>
  152. /// <param name="item">The item.</param>
  153. private void RemoveNowPlayingItem(SessionInfo session, BaseItem item)
  154. {
  155. if (session.NowPlayingItem != null && session.NowPlayingItem.Id == item.Id)
  156. {
  157. session.NowPlayingItem = null;
  158. session.NowPlayingPositionTicks = null;
  159. session.IsPaused = null;
  160. }
  161. }
  162. /// <summary>
  163. /// Gets the connection.
  164. /// </summary>
  165. /// <param name="clientType">Type of the client.</param>
  166. /// <param name="appVersion">The app version.</param>
  167. /// <param name="deviceId">The device id.</param>
  168. /// <param name="deviceName">Name of the device.</param>
  169. /// <param name="user">The user.</param>
  170. /// <returns>SessionInfo.</returns>
  171. private SessionInfo GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, User user)
  172. {
  173. var key = clientType + deviceId + appVersion;
  174. var connection = _activeConnections.GetOrAdd(key, keyName => new SessionInfo
  175. {
  176. Client = clientType,
  177. DeviceId = deviceId,
  178. ApplicationVersion = appVersion,
  179. Id = Guid.NewGuid()
  180. });
  181. connection.DeviceName = deviceName;
  182. connection.User = user;
  183. return connection;
  184. }
  185. /// <summary>
  186. /// Used to report that playback has started for an item
  187. /// </summary>
  188. /// <param name="item">The item.</param>
  189. /// <param name="sessionId">The session id.</param>
  190. /// <returns>Task.</returns>
  191. /// <exception cref="System.ArgumentNullException"></exception>
  192. public async Task OnPlaybackStart(BaseItem item, Guid sessionId)
  193. {
  194. if (item == null)
  195. {
  196. throw new ArgumentNullException();
  197. }
  198. var session = Sessions.First(i => i.Id.Equals(sessionId));
  199. UpdateNowPlayingItem(session, item, false);
  200. var key = item.GetUserDataKey();
  201. var user = session.User;
  202. var data = _userDataRepository.GetUserData(user.Id, key);
  203. data.PlayCount++;
  204. data.LastPlayedDate = DateTime.UtcNow;
  205. if (!(item is Video))
  206. {
  207. data.Played = true;
  208. }
  209. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  210. // Nothing to save here
  211. // Fire events to inform plugins
  212. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  213. {
  214. Item = item,
  215. User = user
  216. }, _logger);
  217. }
  218. /// <summary>
  219. /// Used to report playback progress for an item
  220. /// </summary>
  221. /// <param name="item">The item.</param>
  222. /// <param name="positionTicks">The position ticks.</param>
  223. /// <param name="isPaused">if set to <c>true</c> [is paused].</param>
  224. /// <param name="sessionId">The session id.</param>
  225. /// <returns>Task.</returns>
  226. /// <exception cref="System.ArgumentNullException"></exception>
  227. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  228. public async Task OnPlaybackProgress(BaseItem item, long? positionTicks, bool isPaused, Guid sessionId)
  229. {
  230. if (item == null)
  231. {
  232. throw new ArgumentNullException();
  233. }
  234. if (positionTicks.HasValue && positionTicks.Value < 0)
  235. {
  236. throw new ArgumentOutOfRangeException("positionTicks");
  237. }
  238. var session = Sessions.First(i => i.Id.Equals(sessionId));
  239. UpdateNowPlayingItem(session, item, isPaused, positionTicks);
  240. var key = item.GetUserDataKey();
  241. var user = session.User;
  242. if (positionTicks.HasValue)
  243. {
  244. var data = _userDataRepository.GetUserData(user.Id, key);
  245. UpdatePlayState(item, data, positionTicks.Value);
  246. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  247. }
  248. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  249. {
  250. Item = item,
  251. User = user,
  252. PlaybackPositionTicks = positionTicks
  253. }, _logger);
  254. }
  255. /// <summary>
  256. /// Used to report that playback has ended for an item
  257. /// </summary>
  258. /// <param name="item">The item.</param>
  259. /// <param name="positionTicks">The position ticks.</param>
  260. /// <param name="sessionId">The session id.</param>
  261. /// <returns>Task.</returns>
  262. /// <exception cref="System.ArgumentNullException"></exception>
  263. public async Task OnPlaybackStopped(BaseItem item, long? positionTicks, Guid sessionId)
  264. {
  265. if (item == null)
  266. {
  267. throw new ArgumentNullException();
  268. }
  269. if (positionTicks.HasValue && positionTicks.Value < 0)
  270. {
  271. throw new ArgumentOutOfRangeException("positionTicks");
  272. }
  273. var session = Sessions.First(i => i.Id.Equals(sessionId));
  274. RemoveNowPlayingItem(session, item);
  275. var key = item.GetUserDataKey();
  276. var user = session.User;
  277. var data = _userDataRepository.GetUserData(user.Id, key);
  278. if (positionTicks.HasValue)
  279. {
  280. UpdatePlayState(item, data, positionTicks.Value);
  281. }
  282. else
  283. {
  284. // If the client isn't able to report this, then we'll just have to make an assumption
  285. data.PlayCount++;
  286. data.Played = true;
  287. }
  288. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  289. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  290. {
  291. Item = item,
  292. User = user,
  293. PlaybackPositionTicks = positionTicks
  294. }, _logger);
  295. }
  296. /// <summary>
  297. /// Updates playstate position for an item but does not save
  298. /// </summary>
  299. /// <param name="item">The item</param>
  300. /// <param name="data">User data for the item</param>
  301. /// <param name="positionTicks">The current playback position</param>
  302. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  303. {
  304. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  305. // If a position has been reported, and if we know the duration
  306. if (positionTicks > 0 && hasRuntime)
  307. {
  308. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  309. // Don't track in very beginning
  310. if (pctIn < _configurationManager.Configuration.MinResumePct)
  311. {
  312. positionTicks = 0;
  313. }
  314. // If we're at the end, assume completed
  315. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  316. {
  317. positionTicks = 0;
  318. data.Played = true;
  319. }
  320. else
  321. {
  322. // Enforce MinResumeDuration
  323. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  324. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  325. {
  326. positionTicks = 0;
  327. data.Played = true;
  328. }
  329. }
  330. }
  331. else if (!hasRuntime)
  332. {
  333. // If we don't know the runtime we'll just have to assume it was fully played
  334. data.Played = true;
  335. positionTicks = 0;
  336. }
  337. if (item is Audio)
  338. {
  339. positionTicks = 0;
  340. }
  341. data.PlaybackPositionTicks = positionTicks;
  342. }
  343. }
  344. }