SessionManager.cs 14 KB

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