SessionManager.cs 23 KB

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