SessionManager.cs 15 KB

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