SessionManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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<PlaybackProgressEventArgs> 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. }, _logger);
  247. }
  248. /// <summary>
  249. /// Used to report playback progress for an item
  250. /// </summary>
  251. /// <param name="info">The info.</param>
  252. /// <returns>Task.</returns>
  253. /// <exception cref="System.ArgumentNullException"></exception>
  254. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  255. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  256. {
  257. if (info == null)
  258. {
  259. throw new ArgumentNullException("info");
  260. }
  261. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  262. {
  263. throw new ArgumentOutOfRangeException("positionTicks");
  264. }
  265. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  266. UpdateNowPlayingItem(session, info.Item, info.IsPaused, info.IsMuted, info.PositionTicks);
  267. var key = info.Item.GetUserDataKey();
  268. var user = session.User;
  269. if (info.PositionTicks.HasValue)
  270. {
  271. var data = _userDataRepository.GetUserData(user.Id, key);
  272. UpdatePlayState(info.Item, data, info.PositionTicks.Value);
  273. await _userDataRepository.SaveUserData(user.Id, info.Item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  274. }
  275. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  276. {
  277. Item = info.Item,
  278. User = user,
  279. PlaybackPositionTicks = info.PositionTicks
  280. }, _logger);
  281. }
  282. /// <summary>
  283. /// Used to report that playback has ended for an item
  284. /// </summary>
  285. /// <param name="info">The info.</param>
  286. /// <returns>Task.</returns>
  287. /// <exception cref="System.ArgumentNullException">info</exception>
  288. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  289. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  290. {
  291. if (info == null)
  292. {
  293. throw new ArgumentNullException("info");
  294. }
  295. if (info.Item == null)
  296. {
  297. throw new ArgumentException("PlaybackStopInfo.Item cannot be null");
  298. }
  299. if (info.SessionId == Guid.Empty)
  300. {
  301. throw new ArgumentException("PlaybackStopInfo.SessionId cannot be Guid.Empty");
  302. }
  303. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  304. {
  305. throw new ArgumentOutOfRangeException("positionTicks");
  306. }
  307. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  308. RemoveNowPlayingItem(session, info.Item);
  309. var key = info.Item.GetUserDataKey();
  310. var user = session.User;
  311. var data = _userDataRepository.GetUserData(user.Id, key);
  312. if (info.PositionTicks.HasValue)
  313. {
  314. UpdatePlayState(info.Item, data, info.PositionTicks.Value);
  315. }
  316. else
  317. {
  318. // If the client isn't able to report this, then we'll just have to make an assumption
  319. data.PlayCount++;
  320. data.Played = true;
  321. data.PlaybackPositionTicks = 0;
  322. }
  323. await _userDataRepository.SaveUserData(user.Id, info.Item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  324. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  325. {
  326. Item = info.Item,
  327. User = user,
  328. PlaybackPositionTicks = info.PositionTicks
  329. }, _logger);
  330. }
  331. /// <summary>
  332. /// Updates playstate position for an item but does not save
  333. /// </summary>
  334. /// <param name="item">The item</param>
  335. /// <param name="data">User data for the item</param>
  336. /// <param name="positionTicks">The current playback position</param>
  337. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  338. {
  339. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  340. // If a position has been reported, and if we know the duration
  341. if (positionTicks > 0 && hasRuntime)
  342. {
  343. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  344. // Don't track in very beginning
  345. if (pctIn < _configurationManager.Configuration.MinResumePct)
  346. {
  347. positionTicks = 0;
  348. }
  349. // If we're at the end, assume completed
  350. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  351. {
  352. positionTicks = 0;
  353. data.Played = true;
  354. }
  355. else
  356. {
  357. // Enforce MinResumeDuration
  358. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  359. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  360. {
  361. positionTicks = 0;
  362. data.Played = true;
  363. }
  364. }
  365. }
  366. else if (!hasRuntime)
  367. {
  368. // If we don't know the runtime we'll just have to assume it was fully played
  369. data.Played = true;
  370. positionTicks = 0;
  371. }
  372. if (item is Audio)
  373. {
  374. positionTicks = 0;
  375. }
  376. data.PlaybackPositionTicks = positionTicks;
  377. }
  378. /// <summary>
  379. /// Gets the session for remote control.
  380. /// </summary>
  381. /// <param name="sessionId">The session id.</param>
  382. /// <returns>SessionInfo.</returns>
  383. /// <exception cref="ResourceNotFoundException"></exception>
  384. private SessionInfo GetSessionForRemoteControl(Guid sessionId)
  385. {
  386. var session = Sessions.First(i => i.Id.Equals(sessionId));
  387. if (session == null)
  388. {
  389. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  390. }
  391. if (!session.SupportsRemoteControl)
  392. {
  393. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  394. }
  395. return session;
  396. }
  397. /// <summary>
  398. /// Sends the system command.
  399. /// </summary>
  400. /// <param name="sessionId">The session id.</param>
  401. /// <param name="command">The command.</param>
  402. /// <param name="cancellationToken">The cancellation token.</param>
  403. /// <returns>Task.</returns>
  404. public Task SendSystemCommand(Guid sessionId, SystemCommand command, CancellationToken cancellationToken)
  405. {
  406. var session = GetSessionForRemoteControl(sessionId);
  407. return session.SessionController.SendSystemCommand(command, cancellationToken);
  408. }
  409. /// <summary>
  410. /// Sends the message command.
  411. /// </summary>
  412. /// <param name="sessionId">The session id.</param>
  413. /// <param name="command">The command.</param>
  414. /// <param name="cancellationToken">The cancellation token.</param>
  415. /// <returns>Task.</returns>
  416. public Task SendMessageCommand(Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  417. {
  418. var session = GetSessionForRemoteControl(sessionId);
  419. return session.SessionController.SendMessageCommand(command, cancellationToken);
  420. }
  421. /// <summary>
  422. /// Sends the play command.
  423. /// </summary>
  424. /// <param name="sessionId">The session id.</param>
  425. /// <param name="command">The command.</param>
  426. /// <param name="cancellationToken">The cancellation token.</param>
  427. /// <returns>Task.</returns>
  428. public Task SendPlayCommand(Guid sessionId, PlayRequest command, CancellationToken cancellationToken)
  429. {
  430. var session = GetSessionForRemoteControl(sessionId);
  431. var items = command.ItemIds.Select(i => _libraryManager.GetItemById(new Guid(i)))
  432. .ToList();
  433. if (items.Any(i => i.LocationType == LocationType.Virtual))
  434. {
  435. throw new ArgumentException("Virtual items are not playable.");
  436. }
  437. if (command.PlayCommand != PlayCommand.PlayNow)
  438. {
  439. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  440. {
  441. throw new ArgumentException(string.Format("Session {0} is unable to queue the requested media type.", session.Id));
  442. }
  443. }
  444. return session.SessionController.SendPlayCommand(command, cancellationToken);
  445. }
  446. /// <summary>
  447. /// Sends the browse command.
  448. /// </summary>
  449. /// <param name="sessionId">The session id.</param>
  450. /// <param name="command">The command.</param>
  451. /// <param name="cancellationToken">The cancellation token.</param>
  452. /// <returns>Task.</returns>
  453. public Task SendBrowseCommand(Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  454. {
  455. var session = GetSessionForRemoteControl(sessionId);
  456. return session.SessionController.SendBrowseCommand(command, cancellationToken);
  457. }
  458. /// <summary>
  459. /// Sends the playstate command.
  460. /// </summary>
  461. /// <param name="sessionId">The session id.</param>
  462. /// <param name="command">The command.</param>
  463. /// <param name="cancellationToken">The cancellation token.</param>
  464. /// <returns>Task.</returns>
  465. public Task SendPlaystateCommand(Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  466. {
  467. var session = GetSessionForRemoteControl(sessionId);
  468. if (command.Command == PlaystateCommand.Seek && !session.CanSeek)
  469. {
  470. throw new ArgumentException(string.Format("Session {0} is unable to seek.", session.Id));
  471. }
  472. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  473. }
  474. /// <summary>
  475. /// Sends the restart required message.
  476. /// </summary>
  477. /// <param name="cancellationToken">The cancellation token.</param>
  478. /// <returns>Task.</returns>
  479. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  480. {
  481. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  482. var tasks = sessions.Select(session => Task.Run(async () =>
  483. {
  484. try
  485. {
  486. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  487. }
  488. catch (Exception ex)
  489. {
  490. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  491. }
  492. }));
  493. return Task.WhenAll(tasks);
  494. }
  495. /// <summary>
  496. /// Sends the server shutdown notification.
  497. /// </summary>
  498. /// <param name="cancellationToken">The cancellation token.</param>
  499. /// <returns>Task.</returns>
  500. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  501. {
  502. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  503. var tasks = sessions.Select(session => Task.Run(async () =>
  504. {
  505. try
  506. {
  507. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  508. }
  509. catch (Exception ex)
  510. {
  511. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  512. }
  513. }));
  514. return Task.WhenAll(tasks);
  515. }
  516. /// <summary>
  517. /// Sends the server restart notification.
  518. /// </summary>
  519. /// <param name="cancellationToken">The cancellation token.</param>
  520. /// <returns>Task.</returns>
  521. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  522. {
  523. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  524. var tasks = sessions.Select(session => Task.Run(async () =>
  525. {
  526. try
  527. {
  528. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  529. }
  530. catch (Exception ex)
  531. {
  532. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  533. }
  534. }));
  535. return Task.WhenAll(tasks);
  536. }
  537. }
  538. }