SessionManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. /// <summary>
  38. /// Gets or sets the configuration manager.
  39. /// </summary>
  40. /// <value>The configuration manager.</value>
  41. private readonly IServerConfigurationManager _configurationManager;
  42. private object _sessionLock = new object();
  43. /// <summary>
  44. /// The _active connections
  45. /// </summary>
  46. private readonly Dictionary<string, SessionInfo> _activeConnections =
  47. new Dictionary<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.ToList().OrderByDescending(c => c.LastActivityDate); }
  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. lock (_sessionLock)
  175. {
  176. SessionInfo connection;
  177. if (!_activeConnections.TryGetValue(key, out connection))
  178. {
  179. connection = new SessionInfo
  180. {
  181. Client = clientType,
  182. DeviceId = deviceId,
  183. ApplicationVersion = appVersion,
  184. Id = Guid.NewGuid()
  185. };
  186. _activeConnections[key] = connection;
  187. }
  188. connection.DeviceName = deviceName;
  189. connection.User = user;
  190. return connection;
  191. }
  192. }
  193. /// <summary>
  194. /// Used to report that playback has started for an item
  195. /// </summary>
  196. /// <param name="info">The info.</param>
  197. /// <returns>Task.</returns>
  198. /// <exception cref="System.ArgumentNullException">info</exception>
  199. public async Task OnPlaybackStart(PlaybackInfo info)
  200. {
  201. if (info == null)
  202. {
  203. throw new ArgumentNullException("info");
  204. }
  205. if (info.SessionId == Guid.Empty)
  206. {
  207. throw new ArgumentNullException("info");
  208. }
  209. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  210. var item = info.Item;
  211. UpdateNowPlayingItem(session, item, false, false);
  212. session.CanSeek = info.CanSeek;
  213. session.QueueableMediaTypes = info.QueueableMediaTypes;
  214. var key = item.GetUserDataKey();
  215. var user = session.User;
  216. var data = _userDataRepository.GetUserData(user.Id, key);
  217. data.PlayCount++;
  218. data.LastPlayedDate = DateTime.UtcNow;
  219. if (!(item is Video))
  220. {
  221. data.Played = true;
  222. }
  223. await _userDataRepository.SaveUserData(user.Id, key, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  224. // Nothing to save here
  225. // Fire events to inform plugins
  226. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  227. {
  228. Item = item,
  229. User = user
  230. }, _logger);
  231. }
  232. /// <summary>
  233. /// Used to report playback progress for an item
  234. /// </summary>
  235. /// <param name="info">The info.</param>
  236. /// <returns>Task.</returns>
  237. /// <exception cref="System.ArgumentNullException"></exception>
  238. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  239. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  240. {
  241. if (info == null)
  242. {
  243. throw new ArgumentNullException("info");
  244. }
  245. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  246. {
  247. throw new ArgumentOutOfRangeException("positionTicks");
  248. }
  249. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  250. UpdateNowPlayingItem(session, info.Item, info.IsPaused, info.IsMuted, info.PositionTicks);
  251. var key = info.Item.GetUserDataKey();
  252. var user = session.User;
  253. if (info.PositionTicks.HasValue)
  254. {
  255. var data = _userDataRepository.GetUserData(user.Id, key);
  256. UpdatePlayState(info.Item, data, info.PositionTicks.Value);
  257. await _userDataRepository.SaveUserData(user.Id, key, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  258. }
  259. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  260. {
  261. Item = info.Item,
  262. User = user,
  263. PlaybackPositionTicks = info.PositionTicks
  264. }, _logger);
  265. }
  266. /// <summary>
  267. /// Used to report that playback has ended for an item
  268. /// </summary>
  269. /// <param name="info">The info.</param>
  270. /// <returns>Task.</returns>
  271. /// <exception cref="System.ArgumentNullException">info</exception>
  272. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  273. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  274. {
  275. if (info == null)
  276. {
  277. throw new ArgumentNullException("info");
  278. }
  279. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  280. {
  281. throw new ArgumentOutOfRangeException("positionTicks");
  282. }
  283. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  284. RemoveNowPlayingItem(session, info.Item);
  285. var key = info.Item.GetUserDataKey();
  286. var user = session.User;
  287. var data = _userDataRepository.GetUserData(user.Id, key);
  288. if (info.PositionTicks.HasValue)
  289. {
  290. UpdatePlayState(info.Item, data, info.PositionTicks.Value);
  291. }
  292. else
  293. {
  294. // If the client isn't able to report this, then we'll just have to make an assumption
  295. data.PlayCount++;
  296. data.Played = true;
  297. data.PlaybackPositionTicks = 0;
  298. }
  299. await _userDataRepository.SaveUserData(user.Id, key, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  300. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackProgressEventArgs
  301. {
  302. Item = info.Item,
  303. User = user,
  304. PlaybackPositionTicks = info.PositionTicks
  305. }, _logger);
  306. }
  307. /// <summary>
  308. /// Updates playstate position for an item but does not save
  309. /// </summary>
  310. /// <param name="item">The item</param>
  311. /// <param name="data">User data for the item</param>
  312. /// <param name="positionTicks">The current playback position</param>
  313. private void UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  314. {
  315. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  316. // If a position has been reported, and if we know the duration
  317. if (positionTicks > 0 && hasRuntime)
  318. {
  319. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  320. // Don't track in very beginning
  321. if (pctIn < _configurationManager.Configuration.MinResumePct)
  322. {
  323. positionTicks = 0;
  324. }
  325. // If we're at the end, assume completed
  326. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  327. {
  328. positionTicks = 0;
  329. data.Played = true;
  330. }
  331. else
  332. {
  333. // Enforce MinResumeDuration
  334. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  335. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  336. {
  337. positionTicks = 0;
  338. data.Played = true;
  339. }
  340. }
  341. }
  342. else if (!hasRuntime)
  343. {
  344. // If we don't know the runtime we'll just have to assume it was fully played
  345. data.Played = true;
  346. positionTicks = 0;
  347. }
  348. if (item is Audio)
  349. {
  350. positionTicks = 0;
  351. }
  352. data.PlaybackPositionTicks = positionTicks;
  353. }
  354. /// <summary>
  355. /// Gets the session for remote control.
  356. /// </summary>
  357. /// <param name="sessionId">The session id.</param>
  358. /// <returns>SessionInfo.</returns>
  359. /// <exception cref="ResourceNotFoundException"></exception>
  360. private SessionInfo GetSessionForRemoteControl(Guid sessionId)
  361. {
  362. var session = Sessions.First(i => i.Id.Equals(sessionId));
  363. if (session == null)
  364. {
  365. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  366. }
  367. if (!session.SupportsRemoteControl)
  368. {
  369. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  370. }
  371. return session;
  372. }
  373. /// <summary>
  374. /// Sends the system command.
  375. /// </summary>
  376. /// <param name="sessionId">The session id.</param>
  377. /// <param name="command">The command.</param>
  378. /// <param name="cancellationToken">The cancellation token.</param>
  379. /// <returns>Task.</returns>
  380. public Task SendSystemCommand(Guid sessionId, SystemCommand command, CancellationToken cancellationToken)
  381. {
  382. var session = GetSessionForRemoteControl(sessionId);
  383. return session.SessionController.SendSystemCommand(command, cancellationToken);
  384. }
  385. /// <summary>
  386. /// Sends the message command.
  387. /// </summary>
  388. /// <param name="sessionId">The session id.</param>
  389. /// <param name="command">The command.</param>
  390. /// <param name="cancellationToken">The cancellation token.</param>
  391. /// <returns>Task.</returns>
  392. public Task SendMessageCommand(Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  393. {
  394. var session = GetSessionForRemoteControl(sessionId);
  395. return session.SessionController.SendMessageCommand(command, cancellationToken);
  396. }
  397. /// <summary>
  398. /// Sends the play 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 SendPlayCommand(Guid sessionId, PlayRequest command, CancellationToken cancellationToken)
  405. {
  406. var session = GetSessionForRemoteControl(sessionId);
  407. return session.SessionController.SendPlayCommand(command, cancellationToken);
  408. }
  409. /// <summary>
  410. /// Sends the browse 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 SendBrowseCommand(Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  417. {
  418. var session = GetSessionForRemoteControl(sessionId);
  419. return session.SessionController.SendBrowseCommand(command, cancellationToken);
  420. }
  421. /// <summary>
  422. /// Sends the playstate 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 SendPlaystateCommand(Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  429. {
  430. var session = GetSessionForRemoteControl(sessionId);
  431. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  432. }
  433. /// <summary>
  434. /// Sends the restart required message.
  435. /// </summary>
  436. /// <param name="cancellationToken">The cancellation token.</param>
  437. /// <returns>Task.</returns>
  438. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  439. {
  440. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  441. var tasks = sessions.Select(session => Task.Run(async () =>
  442. {
  443. try
  444. {
  445. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  446. }
  447. catch (Exception ex)
  448. {
  449. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  450. }
  451. }));
  452. return Task.WhenAll(tasks);
  453. }
  454. /// <summary>
  455. /// Sends the server shutdown notification.
  456. /// </summary>
  457. /// <param name="cancellationToken">The cancellation token.</param>
  458. /// <returns>Task.</returns>
  459. public Task SendServerShutdownNotification(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.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  467. }
  468. catch (Exception ex)
  469. {
  470. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  471. }
  472. }));
  473. return Task.WhenAll(tasks);
  474. }
  475. /// <summary>
  476. /// Sends the server restart notification.
  477. /// </summary>
  478. /// <param name="cancellationToken">The cancellation token.</param>
  479. /// <returns>Task.</returns>
  480. public Task SendServerRestartNotification(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.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  488. }
  489. catch (Exception ex)
  490. {
  491. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  492. }
  493. }));
  494. return Task.WhenAll(tasks);
  495. }
  496. }
  497. }