SessionManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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="info">The info.</param>
  231. /// <returns>Task.</returns>
  232. /// <exception cref="System.ArgumentNullException"></exception>
  233. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  234. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  235. {
  236. if (info == null)
  237. {
  238. throw new ArgumentNullException("info");
  239. }
  240. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  241. {
  242. throw new ArgumentOutOfRangeException("positionTicks");
  243. }
  244. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  245. UpdateNowPlayingItem(session, info.Item, info.IsPaused, info.IsMuted, info.PositionTicks);
  246. var key = info.Item.GetUserDataKey();
  247. var user = session.User;
  248. if (info.PositionTicks.HasValue)
  249. {
  250. var data = _userDataRepository.GetUserData(user.Id, key);
  251. UpdatePlayState(info.Item, data, info.PositionTicks.Value);
  252. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  253. }
  254. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  255. {
  256. Item = info.Item,
  257. User = user,
  258. PlaybackPositionTicks = info.PositionTicks
  259. }, _logger);
  260. }
  261. /// <summary>
  262. /// Used to report that playback has ended for an item
  263. /// </summary>
  264. /// <param name="info">The info.</param>
  265. /// <returns>Task.</returns>
  266. /// <exception cref="System.ArgumentNullException">info</exception>
  267. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  268. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  269. {
  270. if (info == null)
  271. {
  272. throw new ArgumentNullException("info");
  273. }
  274. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  275. {
  276. throw new ArgumentOutOfRangeException("positionTicks");
  277. }
  278. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  279. RemoveNowPlayingItem(session, info.Item);
  280. var key = info.Item.GetUserDataKey();
  281. var user = session.User;
  282. var data = _userDataRepository.GetUserData(user.Id, key);
  283. if (info.PositionTicks.HasValue)
  284. {
  285. UpdatePlayState(info.Item, data, info.PositionTicks.Value);
  286. }
  287. else
  288. {
  289. // If the client isn't able to report this, then we'll just have to make an assumption
  290. data.PlayCount++;
  291. data.Played = true;
  292. data.PlaybackPositionTicks = 0;
  293. }
  294. await _userDataRepository.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  295. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  296. {
  297. Item = info.Item,
  298. User = user,
  299. PlaybackPositionTicks = info.PositionTicks
  300. }, _logger);
  301. }
  302. /// <summary>
  303. /// Updates playstate position for an item but does not save
  304. /// </summary>
  305. /// <param name="item">The item</param>
  306. /// <param name="data">User data for the item</param>
  307. /// <param name="positionTicks">The current playback position</param>
  308. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  309. {
  310. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  311. // If a position has been reported, and if we know the duration
  312. if (positionTicks > 0 && hasRuntime)
  313. {
  314. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  315. // Don't track in very beginning
  316. if (pctIn < _configurationManager.Configuration.MinResumePct)
  317. {
  318. positionTicks = 0;
  319. }
  320. // If we're at the end, assume completed
  321. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  322. {
  323. positionTicks = 0;
  324. data.Played = true;
  325. }
  326. else
  327. {
  328. // Enforce MinResumeDuration
  329. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  330. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  331. {
  332. positionTicks = 0;
  333. data.Played = true;
  334. }
  335. }
  336. }
  337. else if (!hasRuntime)
  338. {
  339. // If we don't know the runtime we'll just have to assume it was fully played
  340. data.Played = true;
  341. positionTicks = 0;
  342. }
  343. if (item is Audio)
  344. {
  345. positionTicks = 0;
  346. }
  347. data.PlaybackPositionTicks = positionTicks;
  348. }
  349. /// <summary>
  350. /// Gets the session for remote control.
  351. /// </summary>
  352. /// <param name="sessionId">The session id.</param>
  353. /// <returns>SessionInfo.</returns>
  354. /// <exception cref="ResourceNotFoundException"></exception>
  355. private SessionInfo GetSessionForRemoteControl(Guid sessionId)
  356. {
  357. var session = Sessions.First(i => i.Id.Equals(sessionId));
  358. if (session == null)
  359. {
  360. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  361. }
  362. if (!session.SupportsRemoteControl)
  363. {
  364. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  365. }
  366. return session;
  367. }
  368. /// <summary>
  369. /// Gets the controllers.
  370. /// </summary>
  371. /// <param name="session">The session.</param>
  372. /// <returns>IEnumerable{ISessionRemoteController}.</returns>
  373. private IEnumerable<ISessionRemoteController> GetControllers(SessionInfo session)
  374. {
  375. return _remoteControllers.Where(i => i.Supports(session));
  376. }
  377. /// <summary>
  378. /// Sends the system command.
  379. /// </summary>
  380. /// <param name="sessionId">The session id.</param>
  381. /// <param name="command">The command.</param>
  382. /// <param name="cancellationToken">The cancellation token.</param>
  383. /// <returns>Task.</returns>
  384. public Task SendSystemCommand(Guid sessionId, SystemCommand command, CancellationToken cancellationToken)
  385. {
  386. var session = GetSessionForRemoteControl(sessionId);
  387. var tasks = GetControllers(session).Select(i => i.SendSystemCommand(session, command, cancellationToken));
  388. return Task.WhenAll(tasks);
  389. }
  390. /// <summary>
  391. /// Sends the message command.
  392. /// </summary>
  393. /// <param name="sessionId">The session id.</param>
  394. /// <param name="command">The command.</param>
  395. /// <param name="cancellationToken">The cancellation token.</param>
  396. /// <returns>Task.</returns>
  397. public Task SendMessageCommand(Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  398. {
  399. var session = GetSessionForRemoteControl(sessionId);
  400. var tasks = GetControllers(session).Select(i => i.SendMessageCommand(session, command, cancellationToken));
  401. return Task.WhenAll(tasks);
  402. }
  403. /// <summary>
  404. /// Sends the play command.
  405. /// </summary>
  406. /// <param name="sessionId">The session id.</param>
  407. /// <param name="command">The command.</param>
  408. /// <param name="cancellationToken">The cancellation token.</param>
  409. /// <returns>Task.</returns>
  410. public Task SendPlayCommand(Guid sessionId, PlayRequest command, CancellationToken cancellationToken)
  411. {
  412. var session = GetSessionForRemoteControl(sessionId);
  413. var tasks = GetControllers(session).Select(i => i.SendPlayCommand(session, command, cancellationToken));
  414. return Task.WhenAll(tasks);
  415. }
  416. /// <summary>
  417. /// Sends the browse command.
  418. /// </summary>
  419. /// <param name="sessionId">The session id.</param>
  420. /// <param name="command">The command.</param>
  421. /// <param name="cancellationToken">The cancellation token.</param>
  422. /// <returns>Task.</returns>
  423. public Task SendBrowseCommand(Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  424. {
  425. var session = GetSessionForRemoteControl(sessionId);
  426. var tasks = GetControllers(session).Select(i => i.SendBrowseCommand(session, command, cancellationToken));
  427. return Task.WhenAll(tasks);
  428. }
  429. /// <summary>
  430. /// Sends the playstate command.
  431. /// </summary>
  432. /// <param name="sessionId">The session id.</param>
  433. /// <param name="command">The command.</param>
  434. /// <param name="cancellationToken">The cancellation token.</param>
  435. /// <returns>Task.</returns>
  436. public Task SendPlaystateCommand(Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  437. {
  438. var session = GetSessionForRemoteControl(sessionId);
  439. var tasks = GetControllers(session).Select(i => i.SendPlaystateCommand(session, command, cancellationToken));
  440. return Task.WhenAll(tasks);
  441. }
  442. }
  443. }