SessionManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  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 MediaBrowser.Model.Session;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Server.Implementations.Session
  18. {
  19. /// <summary>
  20. /// Class SessionManager
  21. /// </summary>
  22. public class SessionManager : ISessionManager
  23. {
  24. /// <summary>
  25. /// The _user data repository
  26. /// </summary>
  27. private readonly IUserDataRepository _userDataRepository;
  28. /// <summary>
  29. /// The _user repository
  30. /// </summary>
  31. private readonly IUserRepository _userRepository;
  32. /// <summary>
  33. /// The _logger
  34. /// </summary>
  35. private readonly ILogger _logger;
  36. /// <summary>
  37. /// Gets or sets the configuration manager.
  38. /// </summary>
  39. /// <value>The configuration manager.</value>
  40. private readonly IServerConfigurationManager _configurationManager;
  41. /// <summary>
  42. /// The _active connections
  43. /// </summary>
  44. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  45. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  46. /// <summary>
  47. /// Occurs when [playback start].
  48. /// </summary>
  49. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  50. /// <summary>
  51. /// Occurs when [playback progress].
  52. /// </summary>
  53. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  54. /// <summary>
  55. /// Occurs when [playback stopped].
  56. /// </summary>
  57. public event EventHandler<PlaybackProgressEventArgs> PlaybackStopped;
  58. /// <summary>
  59. /// Initializes a new instance of the <see cref="SessionManager"/> class.
  60. /// </summary>
  61. /// <param name="userDataRepository">The user data repository.</param>
  62. /// <param name="configurationManager">The configuration manager.</param>
  63. /// <param name="logger">The logger.</param>
  64. /// <param name="userRepository">The user repository.</param>
  65. public SessionManager(IUserDataRepository userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository)
  66. {
  67. _userDataRepository = userDataRepository;
  68. _configurationManager = configurationManager;
  69. _logger = logger;
  70. _userRepository = userRepository;
  71. }
  72. private List<ISessionRemoteController> _remoteControllers;
  73. public void AddParts(IEnumerable<ISessionRemoteController> remoteControllers)
  74. {
  75. _remoteControllers = remoteControllers.ToList();
  76. }
  77. /// <summary>
  78. /// Gets all connections.
  79. /// </summary>
  80. /// <value>All connections.</value>
  81. public IEnumerable<SessionInfo> Sessions
  82. {
  83. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList(); }
  84. }
  85. /// <summary>
  86. /// Logs the user activity.
  87. /// </summary>
  88. /// <param name="clientType">Type of the client.</param>
  89. /// <param name="appVersion">The app version.</param>
  90. /// <param name="deviceId">The device id.</param>
  91. /// <param name="deviceName">Name of the device.</param>
  92. /// <param name="user">The user.</param>
  93. /// <returns>Task.</returns>
  94. /// <exception cref="System.UnauthorizedAccessException"></exception>
  95. /// <exception cref="System.ArgumentNullException">user</exception>
  96. public async Task<SessionInfo> LogConnectionActivity(string clientType, string appVersion, string deviceId, string deviceName, User user)
  97. {
  98. if (string.IsNullOrEmpty(clientType))
  99. {
  100. throw new ArgumentNullException("clientType");
  101. }
  102. if (string.IsNullOrEmpty(appVersion))
  103. {
  104. throw new ArgumentNullException("appVersion");
  105. }
  106. if (string.IsNullOrEmpty(deviceId))
  107. {
  108. throw new ArgumentNullException("deviceId");
  109. }
  110. if (string.IsNullOrEmpty(deviceName))
  111. {
  112. throw new ArgumentNullException("deviceName");
  113. }
  114. if (user != null && user.Configuration.IsDisabled)
  115. {
  116. throw new UnauthorizedAccessException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  117. }
  118. var activityDate = DateTime.UtcNow;
  119. var session = GetSessionInfo(clientType, appVersion, deviceId, deviceName, user);
  120. session.LastActivityDate = activityDate;
  121. if (user == null)
  122. {
  123. return session;
  124. }
  125. var lastActivityDate = user.LastActivityDate;
  126. user.LastActivityDate = activityDate;
  127. // Don't log in the db anymore frequently than 10 seconds
  128. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  129. {
  130. return session;
  131. }
  132. // Save this directly. No need to fire off all the events for this.
  133. await _userRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  134. return session;
  135. }
  136. /// <summary>
  137. /// Updates the now playing item id.
  138. /// </summary>
  139. /// <param name="session">The session.</param>
  140. /// <param name="item">The item.</param>
  141. /// <param name="isPaused">if set to <c>true</c> [is paused].</param>
  142. /// <param name="currentPositionTicks">The current position ticks.</param>
  143. private void UpdateNowPlayingItem(SessionInfo session, BaseItem item, bool isPaused, bool isMuted, long? currentPositionTicks = null)
  144. {
  145. session.IsMuted = isMuted;
  146. session.IsPaused = isPaused;
  147. session.NowPlayingPositionTicks = currentPositionTicks;
  148. session.NowPlayingItem = item;
  149. session.LastActivityDate = DateTime.UtcNow;
  150. }
  151. /// <summary>
  152. /// Removes the now playing item id.
  153. /// </summary>
  154. /// <param name="session">The session.</param>
  155. /// <param name="item">The item.</param>
  156. private void RemoveNowPlayingItem(SessionInfo session, BaseItem item)
  157. {
  158. if (session.NowPlayingItem != null && session.NowPlayingItem.Id == item.Id)
  159. {
  160. session.NowPlayingItem = null;
  161. session.NowPlayingPositionTicks = null;
  162. session.IsPaused = false;
  163. }
  164. }
  165. /// <summary>
  166. /// Gets the connection.
  167. /// </summary>
  168. /// <param name="clientType">Type of the client.</param>
  169. /// <param name="appVersion">The app version.</param>
  170. /// <param name="deviceId">The device id.</param>
  171. /// <param name="deviceName">Name of the device.</param>
  172. /// <param name="user">The user.</param>
  173. /// <returns>SessionInfo.</returns>
  174. private SessionInfo GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, User user)
  175. {
  176. var key = clientType + deviceId + appVersion;
  177. var connection = _activeConnections.GetOrAdd(key, keyName => new SessionInfo
  178. {
  179. Client = clientType,
  180. DeviceId = deviceId,
  181. ApplicationVersion = appVersion,
  182. Id = Guid.NewGuid()
  183. });
  184. connection.DeviceName = deviceName;
  185. connection.User = user;
  186. return connection;
  187. }
  188. /// <summary>
  189. /// Used to report that playback has started for an item
  190. /// </summary>
  191. /// <param name="info">The info.</param>
  192. /// <returns>Task.</returns>
  193. /// <exception cref="System.ArgumentNullException">info</exception>
  194. public async Task OnPlaybackStart(PlaybackInfo info)
  195. {
  196. if (info == null)
  197. {
  198. throw new ArgumentNullException("info");
  199. }
  200. if (info.SessionId == Guid.Empty)
  201. {
  202. throw new ArgumentNullException("info");
  203. }
  204. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  205. var item = info.Item;
  206. UpdateNowPlayingItem(session, item, false, false);
  207. session.CanSeek = info.CanSeek;
  208. session.QueueableMediaTypes = info.QueueableMediaTypes;
  209. var key = item.GetUserDataKey();
  210. var user = session.User;
  211. var data = _userDataRepository.GetUserData(user.Id, key);
  212. data.PlayCount++;
  213. data.LastPlayedDate = DateTime.UtcNow;
  214. if (!(item is Video))
  215. {
  216. data.Played = true;
  217. }
  218. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  219. // Nothing to save here
  220. // Fire events to inform plugins
  221. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  222. {
  223. Item = item,
  224. User = user
  225. }, _logger);
  226. }
  227. /// <summary>
  228. /// Used to report playback progress for an item
  229. /// </summary>
  230. /// <param name="item">The item.</param>
  231. /// <param name="positionTicks">The position ticks.</param>
  232. /// <param name="isPaused">if set to <c>true</c> [is paused].</param>
  233. /// <param name="sessionId">The session id.</param>
  234. /// <returns>Task.</returns>
  235. /// <exception cref="System.ArgumentNullException"></exception>
  236. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  237. public async Task OnPlaybackProgress(BaseItem item, long? positionTicks, bool isPaused, bool isMuted, Guid sessionId)
  238. {
  239. if (item == null)
  240. {
  241. throw new ArgumentNullException();
  242. }
  243. if (positionTicks.HasValue && positionTicks.Value < 0)
  244. {
  245. throw new ArgumentOutOfRangeException("positionTicks");
  246. }
  247. var session = Sessions.First(i => i.Id.Equals(sessionId));
  248. UpdateNowPlayingItem(session, item, isPaused, isMuted, positionTicks);
  249. var key = item.GetUserDataKey();
  250. var user = session.User;
  251. if (positionTicks.HasValue)
  252. {
  253. var data = _userDataRepository.GetUserData(user.Id, key);
  254. UpdatePlayState(item, data, positionTicks.Value);
  255. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  256. }
  257. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  258. {
  259. Item = item,
  260. User = user,
  261. PlaybackPositionTicks = positionTicks
  262. }, _logger);
  263. }
  264. /// <summary>
  265. /// Used to report that playback has ended for an item
  266. /// </summary>
  267. /// <param name="item">The item.</param>
  268. /// <param name="positionTicks">The position ticks.</param>
  269. /// <param name="sessionId">The session id.</param>
  270. /// <returns>Task.</returns>
  271. /// <exception cref="System.ArgumentNullException"></exception>
  272. public async Task OnPlaybackStopped(BaseItem item, long? positionTicks, Guid sessionId)
  273. {
  274. if (item == null)
  275. {
  276. throw new ArgumentNullException();
  277. }
  278. if (positionTicks.HasValue && positionTicks.Value < 0)
  279. {
  280. throw new ArgumentOutOfRangeException("positionTicks");
  281. }
  282. var session = Sessions.First(i => i.Id.Equals(sessionId));
  283. RemoveNowPlayingItem(session, item);
  284. var key = item.GetUserDataKey();
  285. var user = session.User;
  286. var data = _userDataRepository.GetUserData(user.Id, key);
  287. if (positionTicks.HasValue)
  288. {
  289. UpdatePlayState(item, data, positionTicks.Value);
  290. }
  291. else
  292. {
  293. // If the client isn't able to report this, then we'll just have to make an assumption
  294. data.PlayCount++;
  295. data.Played = true;
  296. data.PlaybackPositionTicks = 0;
  297. }
  298. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  299. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  300. {
  301. Item = item,
  302. User = user,
  303. PlaybackPositionTicks = positionTicks
  304. }, _logger);
  305. }
  306. /// <summary>
  307. /// Updates playstate position for an item but does not save
  308. /// </summary>
  309. /// <param name="item">The item</param>
  310. /// <param name="data">User data for the item</param>
  311. /// <param name="positionTicks">The current playback position</param>
  312. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  313. {
  314. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  315. // If a position has been reported, and if we know the duration
  316. if (positionTicks > 0 && hasRuntime)
  317. {
  318. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  319. // Don't track in very beginning
  320. if (pctIn < _configurationManager.Configuration.MinResumePct)
  321. {
  322. positionTicks = 0;
  323. }
  324. // If we're at the end, assume completed
  325. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  326. {
  327. positionTicks = 0;
  328. data.Played = true;
  329. }
  330. else
  331. {
  332. // Enforce MinResumeDuration
  333. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  334. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  335. {
  336. positionTicks = 0;
  337. data.Played = true;
  338. }
  339. }
  340. }
  341. else if (!hasRuntime)
  342. {
  343. // If we don't know the runtime we'll just have to assume it was fully played
  344. data.Played = true;
  345. positionTicks = 0;
  346. }
  347. if (item is Audio)
  348. {
  349. positionTicks = 0;
  350. }
  351. data.PlaybackPositionTicks = positionTicks;
  352. }
  353. /// <summary>
  354. /// Gets the session for remote control.
  355. /// </summary>
  356. /// <param name="sessionId">The session id.</param>
  357. /// <returns>SessionInfo.</returns>
  358. /// <exception cref="ResourceNotFoundException"></exception>
  359. private SessionInfo GetSessionForRemoteControl(Guid sessionId)
  360. {
  361. var session = Sessions.First(i => i.Id.Equals(sessionId));
  362. if (session == null)
  363. {
  364. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  365. }
  366. if (!session.SupportsRemoteControl)
  367. {
  368. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  369. }
  370. return session;
  371. }
  372. /// <summary>
  373. /// Gets the controllers.
  374. /// </summary>
  375. /// <param name="session">The session.</param>
  376. /// <returns>IEnumerable{ISessionRemoteController}.</returns>
  377. private IEnumerable<ISessionRemoteController> GetControllers(SessionInfo session)
  378. {
  379. return _remoteControllers.Where(i => i.Supports(session));
  380. }
  381. /// <summary>
  382. /// Sends the system command.
  383. /// </summary>
  384. /// <param name="sessionId">The session id.</param>
  385. /// <param name="command">The command.</param>
  386. /// <param name="cancellationToken">The cancellation token.</param>
  387. /// <returns>Task.</returns>
  388. public Task SendSystemCommand(Guid sessionId, SystemCommand command, CancellationToken cancellationToken)
  389. {
  390. var session = GetSessionForRemoteControl(sessionId);
  391. var tasks = GetControllers(session).Select(i => i.SendSystemCommand(session, command, cancellationToken));
  392. return Task.WhenAll(tasks);
  393. }
  394. /// <summary>
  395. /// Sends the message command.
  396. /// </summary>
  397. /// <param name="sessionId">The session id.</param>
  398. /// <param name="command">The command.</param>
  399. /// <param name="cancellationToken">The cancellation token.</param>
  400. /// <returns>Task.</returns>
  401. public Task SendMessageCommand(Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  402. {
  403. var session = GetSessionForRemoteControl(sessionId);
  404. var tasks = GetControllers(session).Select(i => i.SendMessageCommand(session, command, cancellationToken));
  405. return Task.WhenAll(tasks);
  406. }
  407. /// <summary>
  408. /// Sends the play command.
  409. /// </summary>
  410. /// <param name="sessionId">The session id.</param>
  411. /// <param name="command">The command.</param>
  412. /// <param name="cancellationToken">The cancellation token.</param>
  413. /// <returns>Task.</returns>
  414. public Task SendPlayCommand(Guid sessionId, PlayRequest command, CancellationToken cancellationToken)
  415. {
  416. var session = GetSessionForRemoteControl(sessionId);
  417. var tasks = GetControllers(session).Select(i => i.SendPlayCommand(session, command, cancellationToken));
  418. return Task.WhenAll(tasks);
  419. }
  420. /// <summary>
  421. /// Sends the browse command.
  422. /// </summary>
  423. /// <param name="sessionId">The session id.</param>
  424. /// <param name="command">The command.</param>
  425. /// <param name="cancellationToken">The cancellation token.</param>
  426. /// <returns>Task.</returns>
  427. public Task SendBrowseCommand(Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  428. {
  429. var session = GetSessionForRemoteControl(sessionId);
  430. var tasks = GetControllers(session).Select(i => i.SendBrowseCommand(session, command, cancellationToken));
  431. return Task.WhenAll(tasks);
  432. }
  433. /// <summary>
  434. /// Sends the playstate command.
  435. /// </summary>
  436. /// <param name="sessionId">The session id.</param>
  437. /// <param name="command">The command.</param>
  438. /// <param name="cancellationToken">The cancellation token.</param>
  439. /// <returns>Task.</returns>
  440. public Task SendPlaystateCommand(Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  441. {
  442. var session = GetSessionForRemoteControl(sessionId);
  443. var tasks = GetControllers(session).Select(i => i.SendPlaystateCommand(session, command, cancellationToken));
  444. return Task.WhenAll(tasks);
  445. }
  446. }
  447. }