SessionManager.cs 15 KB

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