SessionManager.cs 19 KB

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