SessionManager.cs 15 KB

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