SessionManager.cs 15 KB

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