SessionManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 async Task 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. var key = item.GetUserDataKey();
  189. var data = await _userDataRepository.GetUserData(user.Id, key).ConfigureAwait(false);
  190. data.PlayCount++;
  191. data.LastPlayedDate = DateTime.UtcNow;
  192. if (!(item is Video))
  193. {
  194. data.Played = true;
  195. }
  196. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  197. // Nothing to save here
  198. // Fire events to inform plugins
  199. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  200. {
  201. Item = item,
  202. User = user
  203. }, _logger);
  204. }
  205. /// <summary>
  206. /// Used to report playback progress for an item
  207. /// </summary>
  208. /// <param name="user">The user.</param>
  209. /// <param name="item">The item.</param>
  210. /// <param name="positionTicks">The position ticks.</param>
  211. /// <param name="isPaused">if set to <c>true</c> [is paused].</param>
  212. /// <param name="clientType">Type of the client.</param>
  213. /// <param name="deviceId">The device id.</param>
  214. /// <param name="deviceName">Name of the device.</param>
  215. /// <returns>Task.</returns>
  216. /// <exception cref="System.ArgumentNullException">
  217. /// </exception>
  218. public async Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, bool isPaused, string clientType, string deviceId, string deviceName)
  219. {
  220. if (user == null)
  221. {
  222. throw new ArgumentNullException();
  223. }
  224. if (item == null)
  225. {
  226. throw new ArgumentNullException();
  227. }
  228. UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item, isPaused, positionTicks);
  229. var key = item.GetUserDataKey();
  230. if (positionTicks.HasValue)
  231. {
  232. var data = await _userDataRepository.GetUserData(user.Id, key).ConfigureAwait(false);
  233. UpdatePlayState(item, data, positionTicks.Value);
  234. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  235. }
  236. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  237. {
  238. Item = item,
  239. User = user,
  240. PlaybackPositionTicks = positionTicks
  241. }, _logger);
  242. }
  243. /// <summary>
  244. /// Used to report that playback has ended for an item
  245. /// </summary>
  246. /// <param name="user">The user.</param>
  247. /// <param name="item">The item.</param>
  248. /// <param name="positionTicks">The position ticks.</param>
  249. /// <param name="clientType">Type of the client.</param>
  250. /// <param name="deviceId">The device id.</param>
  251. /// <param name="deviceName">Name of the device.</param>
  252. /// <returns>Task.</returns>
  253. /// <exception cref="System.ArgumentNullException">
  254. /// </exception>
  255. public async Task OnPlaybackStopped(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
  256. {
  257. if (user == null)
  258. {
  259. throw new ArgumentNullException();
  260. }
  261. if (item == null)
  262. {
  263. throw new ArgumentNullException();
  264. }
  265. RemoveNowPlayingItemId(user, clientType, deviceId, deviceName, item);
  266. var key = item.GetUserDataKey();
  267. var data = await _userDataRepository.GetUserData(user.Id, key).ConfigureAwait(false);
  268. if (positionTicks.HasValue)
  269. {
  270. UpdatePlayState(item, data, positionTicks.Value);
  271. }
  272. else
  273. {
  274. // If the client isn't able to report this, then we'll just have to make an assumption
  275. data.PlayCount++;
  276. data.Played = true;
  277. }
  278. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  279. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  280. {
  281. Item = item,
  282. User = user,
  283. PlaybackPositionTicks = positionTicks
  284. }, _logger);
  285. }
  286. /// <summary>
  287. /// Updates playstate position for an item but does not save
  288. /// </summary>
  289. /// <param name="item">The item</param>
  290. /// <param name="data">User data for the item</param>
  291. /// <param name="positionTicks">The current playback position</param>
  292. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  293. {
  294. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  295. // If a position has been reported, and if we know the duration
  296. if (positionTicks > 0 && hasRuntime)
  297. {
  298. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  299. // Don't track in very beginning
  300. if (pctIn < _configurationManager.Configuration.MinResumePct)
  301. {
  302. positionTicks = 0;
  303. }
  304. // If we're at the end, assume completed
  305. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  306. {
  307. positionTicks = 0;
  308. data.Played = true;
  309. }
  310. else
  311. {
  312. // Enforce MinResumeDuration
  313. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  314. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  315. {
  316. positionTicks = 0;
  317. data.Played = true;
  318. }
  319. }
  320. }
  321. else if (!hasRuntime)
  322. {
  323. // If we don't know the runtime we'll just have to assume it was fully played
  324. data.Played = true;
  325. positionTicks = 0;
  326. }
  327. if (item is Audio)
  328. {
  329. positionTicks = 0;
  330. }
  331. data.PlaybackPositionTicks = positionTicks;
  332. }
  333. }
  334. }