SessionManager.cs 24 KB

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