SessionManager.cs 23 KB

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