SessionManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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 (session.NowPlayingItem != null && session.NowPlayingItem.Id == item.Id)
  156. {
  157. session.NowPlayingItem = null;
  158. session.NowPlayingPositionTicks = null;
  159. session.IsPaused = false;
  160. }
  161. }
  162. /// <summary>
  163. /// Gets the connection.
  164. /// </summary>
  165. /// <param name="clientType">Type of the client.</param>
  166. /// <param name="appVersion">The app version.</param>
  167. /// <param name="deviceId">The device id.</param>
  168. /// <param name="deviceName">Name of the device.</param>
  169. /// <param name="user">The user.</param>
  170. /// <returns>SessionInfo.</returns>
  171. private SessionInfo GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, User user)
  172. {
  173. var key = clientType + deviceId + appVersion;
  174. var connection = _activeConnections.GetOrAdd(key, keyName => new SessionInfo
  175. {
  176. Client = clientType,
  177. DeviceId = deviceId,
  178. ApplicationVersion = appVersion,
  179. Id = Guid.NewGuid()
  180. });
  181. connection.DeviceName = deviceName;
  182. connection.User = user;
  183. return connection;
  184. }
  185. /// <summary>
  186. /// Used to report that playback has started for an item
  187. /// </summary>
  188. /// <param name="info">The info.</param>
  189. /// <returns>Task.</returns>
  190. /// <exception cref="System.ArgumentNullException">info</exception>
  191. public async Task OnPlaybackStart(PlaybackInfo info)
  192. {
  193. if (info == null)
  194. {
  195. throw new ArgumentNullException("info");
  196. }
  197. if (info.SessionId == Guid.Empty)
  198. {
  199. throw new ArgumentNullException("info");
  200. }
  201. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  202. var item = info.Item;
  203. UpdateNowPlayingItem(session, item, false, false);
  204. session.CanSeek = info.CanSeek;
  205. session.QueueableMediaTypes = info.QueueableMediaTypes;
  206. var key = item.GetUserDataKey();
  207. var user = session.User;
  208. var data = _userDataRepository.GetUserData(user.Id, key);
  209. data.PlayCount++;
  210. data.LastPlayedDate = DateTime.UtcNow;
  211. if (!(item is Video))
  212. {
  213. data.Played = true;
  214. }
  215. await _userDataRepository.SaveUserData(user.Id, key, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  216. // Nothing to save here
  217. // Fire events to inform plugins
  218. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  219. {
  220. Item = item,
  221. User = user
  222. }, _logger);
  223. }
  224. /// <summary>
  225. /// Used to report playback progress for an item
  226. /// </summary>
  227. /// <param name="info">The info.</param>
  228. /// <returns>Task.</returns>
  229. /// <exception cref="System.ArgumentNullException"></exception>
  230. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  231. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  232. {
  233. if (info == null)
  234. {
  235. throw new ArgumentNullException("info");
  236. }
  237. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  238. {
  239. throw new ArgumentOutOfRangeException("positionTicks");
  240. }
  241. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  242. UpdateNowPlayingItem(session, info.Item, info.IsPaused, info.IsMuted, info.PositionTicks);
  243. var key = info.Item.GetUserDataKey();
  244. var user = session.User;
  245. if (info.PositionTicks.HasValue)
  246. {
  247. var data = _userDataRepository.GetUserData(user.Id, key);
  248. UpdatePlayState(info.Item, data, info.PositionTicks.Value);
  249. await _userDataRepository.SaveUserData(user.Id, key, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  250. }
  251. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  252. {
  253. Item = info.Item,
  254. User = user,
  255. PlaybackPositionTicks = info.PositionTicks
  256. }, _logger);
  257. }
  258. /// <summary>
  259. /// Used to report that playback has ended for an item
  260. /// </summary>
  261. /// <param name="info">The info.</param>
  262. /// <returns>Task.</returns>
  263. /// <exception cref="System.ArgumentNullException">info</exception>
  264. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  265. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  266. {
  267. if (info == null)
  268. {
  269. throw new ArgumentNullException("info");
  270. }
  271. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  272. {
  273. throw new ArgumentOutOfRangeException("positionTicks");
  274. }
  275. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  276. RemoveNowPlayingItem(session, info.Item);
  277. var key = info.Item.GetUserDataKey();
  278. var user = session.User;
  279. var data = _userDataRepository.GetUserData(user.Id, key);
  280. if (info.PositionTicks.HasValue)
  281. {
  282. UpdatePlayState(info.Item, data, info.PositionTicks.Value);
  283. }
  284. else
  285. {
  286. // If the client isn't able to report this, then we'll just have to make an assumption
  287. data.PlayCount++;
  288. data.Played = true;
  289. data.PlaybackPositionTicks = 0;
  290. }
  291. await _userDataRepository.SaveUserData(user.Id, key, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  292. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  293. {
  294. Item = info.Item,
  295. User = user,
  296. PlaybackPositionTicks = info.PositionTicks
  297. }, _logger);
  298. }
  299. /// <summary>
  300. /// Updates playstate position for an item but does not save
  301. /// </summary>
  302. /// <param name="item">The item</param>
  303. /// <param name="data">User data for the item</param>
  304. /// <param name="positionTicks">The current playback position</param>
  305. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  306. {
  307. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  308. // If a position has been reported, and if we know the duration
  309. if (positionTicks > 0 && hasRuntime)
  310. {
  311. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  312. // Don't track in very beginning
  313. if (pctIn < _configurationManager.Configuration.MinResumePct)
  314. {
  315. positionTicks = 0;
  316. }
  317. // If we're at the end, assume completed
  318. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  319. {
  320. positionTicks = 0;
  321. data.Played = true;
  322. }
  323. else
  324. {
  325. // Enforce MinResumeDuration
  326. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  327. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  328. {
  329. positionTicks = 0;
  330. data.Played = true;
  331. }
  332. }
  333. }
  334. else if (!hasRuntime)
  335. {
  336. // If we don't know the runtime we'll just have to assume it was fully played
  337. data.Played = true;
  338. positionTicks = 0;
  339. }
  340. if (item is Audio)
  341. {
  342. positionTicks = 0;
  343. }
  344. data.PlaybackPositionTicks = positionTicks;
  345. }
  346. /// <summary>
  347. /// Gets the session for remote control.
  348. /// </summary>
  349. /// <param name="sessionId">The session id.</param>
  350. /// <returns>SessionInfo.</returns>
  351. /// <exception cref="ResourceNotFoundException"></exception>
  352. private SessionInfo GetSessionForRemoteControl(Guid sessionId)
  353. {
  354. var session = Sessions.First(i => i.Id.Equals(sessionId));
  355. if (session == null)
  356. {
  357. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  358. }
  359. if (!session.SupportsRemoteControl)
  360. {
  361. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  362. }
  363. return session;
  364. }
  365. /// <summary>
  366. /// Sends the system command.
  367. /// </summary>
  368. /// <param name="sessionId">The session id.</param>
  369. /// <param name="command">The command.</param>
  370. /// <param name="cancellationToken">The cancellation token.</param>
  371. /// <returns>Task.</returns>
  372. public Task SendSystemCommand(Guid sessionId, SystemCommand command, CancellationToken cancellationToken)
  373. {
  374. var session = GetSessionForRemoteControl(sessionId);
  375. return session.SessionController.SendSystemCommand(command, cancellationToken);
  376. }
  377. /// <summary>
  378. /// Sends the message 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 SendMessageCommand(Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  385. {
  386. var session = GetSessionForRemoteControl(sessionId);
  387. return session.SessionController.SendMessageCommand(command, cancellationToken);
  388. }
  389. /// <summary>
  390. /// Sends the play 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 SendPlayCommand(Guid sessionId, PlayRequest command, CancellationToken cancellationToken)
  397. {
  398. var session = GetSessionForRemoteControl(sessionId);
  399. if (command.PlayCommand != PlayCommand.PlayNow)
  400. {
  401. if (command.ItemIds.Any(i =>
  402. {
  403. var item = _libraryManager.GetItemById(new Guid(i));
  404. return !session.QueueableMediaTypes.Contains(item.MediaType, StringComparer.OrdinalIgnoreCase);
  405. }))
  406. {
  407. throw new ArgumentException(string.Format("Session {0} is unable to queue the requested media type.", session.Id));
  408. }
  409. }
  410. return session.SessionController.SendPlayCommand(command, cancellationToken);
  411. }
  412. /// <summary>
  413. /// Sends the browse command.
  414. /// </summary>
  415. /// <param name="sessionId">The session id.</param>
  416. /// <param name="command">The command.</param>
  417. /// <param name="cancellationToken">The cancellation token.</param>
  418. /// <returns>Task.</returns>
  419. public Task SendBrowseCommand(Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  420. {
  421. var session = GetSessionForRemoteControl(sessionId);
  422. return session.SessionController.SendBrowseCommand(command, cancellationToken);
  423. }
  424. /// <summary>
  425. /// Sends the playstate command.
  426. /// </summary>
  427. /// <param name="sessionId">The session id.</param>
  428. /// <param name="command">The command.</param>
  429. /// <param name="cancellationToken">The cancellation token.</param>
  430. /// <returns>Task.</returns>
  431. public Task SendPlaystateCommand(Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  432. {
  433. var session = GetSessionForRemoteControl(sessionId);
  434. if (command.Command == PlaystateCommand.Seek && !session.CanSeek)
  435. {
  436. throw new ArgumentException(string.Format("Session {0} is unable to seek.", session.Id));
  437. }
  438. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  439. }
  440. /// <summary>
  441. /// Sends the restart required message.
  442. /// </summary>
  443. /// <param name="cancellationToken">The cancellation token.</param>
  444. /// <returns>Task.</returns>
  445. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  446. {
  447. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  448. var tasks = sessions.Select(session => Task.Run(async () =>
  449. {
  450. try
  451. {
  452. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  453. }
  454. catch (Exception ex)
  455. {
  456. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  457. }
  458. }));
  459. return Task.WhenAll(tasks);
  460. }
  461. /// <summary>
  462. /// Sends the server shutdown notification.
  463. /// </summary>
  464. /// <param name="cancellationToken">The cancellation token.</param>
  465. /// <returns>Task.</returns>
  466. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  467. {
  468. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  469. var tasks = sessions.Select(session => Task.Run(async () =>
  470. {
  471. try
  472. {
  473. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  474. }
  475. catch (Exception ex)
  476. {
  477. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  478. }
  479. }));
  480. return Task.WhenAll(tasks);
  481. }
  482. /// <summary>
  483. /// Sends the server restart notification.
  484. /// </summary>
  485. /// <param name="cancellationToken">The cancellation token.</param>
  486. /// <returns>Task.</returns>
  487. public Task SendServerRestartNotification(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.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  495. }
  496. catch (Exception ex)
  497. {
  498. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  499. }
  500. }));
  501. return Task.WhenAll(tasks);
  502. }
  503. }
  504. }