SessionManager.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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. private readonly IUserManager _userManager;
  39. /// <summary>
  40. /// Gets or sets the configuration manager.
  41. /// </summary>
  42. /// <value>The configuration manager.</value>
  43. private readonly IServerConfigurationManager _configurationManager;
  44. /// <summary>
  45. /// The _active connections
  46. /// </summary>
  47. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  48. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  49. /// <summary>
  50. /// Occurs when [playback start].
  51. /// </summary>
  52. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  53. /// <summary>
  54. /// Occurs when [playback progress].
  55. /// </summary>
  56. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  57. /// <summary>
  58. /// Occurs when [playback stopped].
  59. /// </summary>
  60. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  61. private IEnumerable<ISessionControllerFactory> _sessionFactories = new List<ISessionControllerFactory>();
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="SessionManager" /> class.
  64. /// </summary>
  65. /// <param name="userDataRepository">The user data repository.</param>
  66. /// <param name="configurationManager">The configuration manager.</param>
  67. /// <param name="logger">The logger.</param>
  68. /// <param name="userRepository">The user repository.</param>
  69. /// <param name="libraryManager">The library manager.</param>
  70. public SessionManager(IUserDataManager userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository, ILibraryManager libraryManager, IUserManager userManager)
  71. {
  72. _userDataRepository = userDataRepository;
  73. _configurationManager = configurationManager;
  74. _logger = logger;
  75. _userRepository = userRepository;
  76. _libraryManager = libraryManager;
  77. _userManager = userManager;
  78. }
  79. /// <summary>
  80. /// Adds the parts.
  81. /// </summary>
  82. /// <param name="sessionFactories">The session factories.</param>
  83. public void AddParts(IEnumerable<ISessionControllerFactory> sessionFactories)
  84. {
  85. _sessionFactories = sessionFactories.ToList();
  86. }
  87. /// <summary>
  88. /// Gets all connections.
  89. /// </summary>
  90. /// <value>All connections.</value>
  91. public IEnumerable<SessionInfo> Sessions
  92. {
  93. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList(); }
  94. }
  95. /// <summary>
  96. /// Logs the user activity.
  97. /// </summary>
  98. /// <param name="clientType">Type of the client.</param>
  99. /// <param name="appVersion">The app version.</param>
  100. /// <param name="deviceId">The device id.</param>
  101. /// <param name="deviceName">Name of the device.</param>
  102. /// <param name="remoteEndPoint">The remote end point.</param>
  103. /// <param name="user">The user.</param>
  104. /// <returns>Task.</returns>
  105. /// <exception cref="System.ArgumentNullException">user</exception>
  106. /// <exception cref="System.UnauthorizedAccessException"></exception>
  107. public async Task<SessionInfo> LogSessionActivity(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
  108. {
  109. if (string.IsNullOrEmpty(clientType))
  110. {
  111. throw new ArgumentNullException("clientType");
  112. }
  113. if (string.IsNullOrEmpty(appVersion))
  114. {
  115. throw new ArgumentNullException("appVersion");
  116. }
  117. if (string.IsNullOrEmpty(deviceId))
  118. {
  119. throw new ArgumentNullException("deviceId");
  120. }
  121. if (string.IsNullOrEmpty(deviceName))
  122. {
  123. throw new ArgumentNullException("deviceName");
  124. }
  125. if (user != null && user.Configuration.IsDisabled)
  126. {
  127. throw new UnauthorizedAccessException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  128. }
  129. var activityDate = DateTime.UtcNow;
  130. var userId = user == null ? (Guid?)null : user.Id;
  131. var username = user == null ? null : user.Name;
  132. var session = GetSessionInfo(clientType, appVersion, deviceId, deviceName, remoteEndPoint, userId, username);
  133. session.LastActivityDate = activityDate;
  134. if (user == null)
  135. {
  136. return session;
  137. }
  138. var lastActivityDate = user.LastActivityDate;
  139. user.LastActivityDate = activityDate;
  140. // Don't log in the db anymore frequently than 10 seconds
  141. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  142. {
  143. return session;
  144. }
  145. // Save this directly. No need to fire off all the events for this.
  146. await _userRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  147. return session;
  148. }
  149. /// <summary>
  150. /// Updates the now playing item id.
  151. /// </summary>
  152. /// <param name="session">The session.</param>
  153. /// <param name="item">The item.</param>
  154. /// <param name="isPaused">if set to <c>true</c> [is paused].</param>
  155. /// <param name="currentPositionTicks">The current position ticks.</param>
  156. private void UpdateNowPlayingItem(SessionInfo session, BaseItem item, bool isPaused, bool isMuted, long? currentPositionTicks = null)
  157. {
  158. session.IsMuted = isMuted;
  159. session.IsPaused = isPaused;
  160. session.NowPlayingPositionTicks = currentPositionTicks;
  161. session.NowPlayingItem = item;
  162. session.LastActivityDate = DateTime.UtcNow;
  163. }
  164. /// <summary>
  165. /// Removes the now playing item id.
  166. /// </summary>
  167. /// <param name="session">The session.</param>
  168. /// <param name="item">The item.</param>
  169. private void RemoveNowPlayingItem(SessionInfo session, BaseItem item)
  170. {
  171. if (item == null)
  172. {
  173. throw new ArgumentNullException("item");
  174. }
  175. if (session.NowPlayingItem != null && session.NowPlayingItem.Id == item.Id)
  176. {
  177. session.NowPlayingItem = null;
  178. session.NowPlayingPositionTicks = null;
  179. session.IsPaused = false;
  180. }
  181. }
  182. /// <summary>
  183. /// Gets the connection.
  184. /// </summary>
  185. /// <param name="clientType">Type of the client.</param>
  186. /// <param name="appVersion">The app version.</param>
  187. /// <param name="deviceId">The device id.</param>
  188. /// <param name="deviceName">Name of the device.</param>
  189. /// <param name="remoteEndPoint">The remote end point.</param>
  190. /// <param name="userId">The user identifier.</param>
  191. /// <param name="username">The username.</param>
  192. /// <returns>SessionInfo.</returns>
  193. private SessionInfo GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username)
  194. {
  195. var key = clientType + deviceId + appVersion;
  196. var connection = _activeConnections.GetOrAdd(key, keyName => new SessionInfo
  197. {
  198. Client = clientType,
  199. DeviceId = deviceId,
  200. ApplicationVersion = appVersion,
  201. Id = Guid.NewGuid()
  202. });
  203. connection.DeviceName = deviceName;
  204. connection.UserId = userId;
  205. connection.UserName = username;
  206. connection.RemoteEndPoint = remoteEndPoint;
  207. if (!userId.HasValue)
  208. {
  209. connection.AdditionalUsers.Clear();
  210. }
  211. if (connection.SessionController == null)
  212. {
  213. connection.SessionController = _sessionFactories
  214. .Select(i => i.GetSessionController(connection))
  215. .FirstOrDefault(i => i != null);
  216. }
  217. return connection;
  218. }
  219. private List<User> GetUsers(SessionInfo session)
  220. {
  221. var users = new List<User>();
  222. if (session.UserId.HasValue)
  223. {
  224. var user = _userManager.GetUserById(session.UserId.Value);
  225. if (user == null)
  226. {
  227. throw new InvalidOperationException("User not found");
  228. }
  229. users.Add(user);
  230. var additionalUsers = session.AdditionalUsers
  231. .Select(i => _userManager.GetUserById(new Guid(i.UserId)))
  232. .Where(i => i != null);
  233. users.AddRange(additionalUsers);
  234. }
  235. return users;
  236. }
  237. /// <summary>
  238. /// Used to report that playback has started for an item
  239. /// </summary>
  240. /// <param name="info">The info.</param>
  241. /// <returns>Task.</returns>
  242. /// <exception cref="System.ArgumentNullException">info</exception>
  243. public async Task OnPlaybackStart(PlaybackInfo info)
  244. {
  245. if (info == null)
  246. {
  247. throw new ArgumentNullException("info");
  248. }
  249. if (info.SessionId == Guid.Empty)
  250. {
  251. throw new ArgumentNullException("info");
  252. }
  253. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  254. var item = info.Item;
  255. UpdateNowPlayingItem(session, item, false, false);
  256. session.CanSeek = info.CanSeek;
  257. session.QueueableMediaTypes = info.QueueableMediaTypes;
  258. var key = item.GetUserDataKey();
  259. var users = GetUsers(session);
  260. foreach (var user in users)
  261. {
  262. await OnPlaybackStart(user.Id, key, item).ConfigureAwait(false);
  263. }
  264. // Nothing to save here
  265. // Fire events to inform plugins
  266. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  267. {
  268. Item = item,
  269. Users = users
  270. }, _logger);
  271. }
  272. /// <summary>
  273. /// Called when [playback start].
  274. /// </summary>
  275. /// <param name="userId">The user identifier.</param>
  276. /// <param name="userDataKey">The user data key.</param>
  277. /// <param name="item">The item.</param>
  278. /// <returns>Task.</returns>
  279. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  280. {
  281. var data = _userDataRepository.GetUserData(userId, userDataKey);
  282. data.PlayCount++;
  283. data.LastPlayedDate = DateTime.UtcNow;
  284. if (!(item is Video))
  285. {
  286. data.Played = true;
  287. }
  288. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  289. }
  290. /// <summary>
  291. /// Used to report playback progress for an item
  292. /// </summary>
  293. /// <param name="info">The info.</param>
  294. /// <returns>Task.</returns>
  295. /// <exception cref="System.ArgumentNullException"></exception>
  296. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  297. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  298. {
  299. if (info == null)
  300. {
  301. throw new ArgumentNullException("info");
  302. }
  303. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  304. {
  305. throw new ArgumentOutOfRangeException("positionTicks");
  306. }
  307. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  308. UpdateNowPlayingItem(session, info.Item, info.IsPaused, info.IsMuted, info.PositionTicks);
  309. var key = info.Item.GetUserDataKey();
  310. var users = GetUsers(session);
  311. foreach (var user in users)
  312. {
  313. await OnPlaybackProgress(user.Id, key, info.Item, info.PositionTicks).ConfigureAwait(false);
  314. }
  315. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  316. {
  317. Item = info.Item,
  318. Users = users,
  319. PlaybackPositionTicks = info.PositionTicks
  320. }, _logger);
  321. }
  322. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  323. {
  324. var data = _userDataRepository.GetUserData(userId, userDataKey);
  325. if (positionTicks.HasValue)
  326. {
  327. UpdatePlayState(item, data, positionTicks.Value);
  328. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  329. }
  330. }
  331. /// <summary>
  332. /// Used to report that playback has ended for an item
  333. /// </summary>
  334. /// <param name="info">The info.</param>
  335. /// <returns>Task.</returns>
  336. /// <exception cref="System.ArgumentNullException">info</exception>
  337. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  338. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  339. {
  340. if (info == null)
  341. {
  342. throw new ArgumentNullException("info");
  343. }
  344. if (info.Item == null)
  345. {
  346. throw new ArgumentException("PlaybackStopInfo.Item cannot be null");
  347. }
  348. if (info.SessionId == Guid.Empty)
  349. {
  350. throw new ArgumentException("PlaybackStopInfo.SessionId cannot be Guid.Empty");
  351. }
  352. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  353. {
  354. throw new ArgumentOutOfRangeException("positionTicks");
  355. }
  356. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  357. RemoveNowPlayingItem(session, info.Item);
  358. var key = info.Item.GetUserDataKey();
  359. var users = GetUsers(session);
  360. var playedToCompletion = false;
  361. foreach (var user in users)
  362. {
  363. playedToCompletion = await OnPlaybackStopped(user.Id, key, info.Item, info.PositionTicks).ConfigureAwait(false);
  364. }
  365. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  366. {
  367. Item = info.Item,
  368. Users = users,
  369. PlaybackPositionTicks = info.PositionTicks,
  370. PlayedToCompletion = playedToCompletion
  371. }, _logger);
  372. }
  373. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  374. {
  375. var data = _userDataRepository.GetUserData(userId, userDataKey);
  376. bool playedToCompletion;
  377. if (positionTicks.HasValue)
  378. {
  379. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  380. }
  381. else
  382. {
  383. // If the client isn't able to report this, then we'll just have to make an assumption
  384. data.PlayCount++;
  385. data.Played = true;
  386. data.PlaybackPositionTicks = 0;
  387. playedToCompletion = true;
  388. }
  389. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  390. return playedToCompletion;
  391. }
  392. /// <summary>
  393. /// Updates playstate position for an item but does not save
  394. /// </summary>
  395. /// <param name="item">The item</param>
  396. /// <param name="data">User data for the item</param>
  397. /// <param name="positionTicks">The current playback position</param>
  398. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  399. {
  400. var playedToCompletion = false;
  401. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  402. // If a position has been reported, and if we know the duration
  403. if (positionTicks > 0 && hasRuntime)
  404. {
  405. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  406. // Don't track in very beginning
  407. if (pctIn < _configurationManager.Configuration.MinResumePct)
  408. {
  409. positionTicks = 0;
  410. }
  411. // If we're at the end, assume completed
  412. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  413. {
  414. positionTicks = 0;
  415. data.Played = playedToCompletion = true;
  416. }
  417. else
  418. {
  419. // Enforce MinResumeDuration
  420. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  421. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  422. {
  423. positionTicks = 0;
  424. data.Played = playedToCompletion = true;
  425. }
  426. }
  427. }
  428. else if (!hasRuntime)
  429. {
  430. // If we don't know the runtime we'll just have to assume it was fully played
  431. data.Played = playedToCompletion = true;
  432. positionTicks = 0;
  433. }
  434. if (item is Audio)
  435. {
  436. positionTicks = 0;
  437. }
  438. data.PlaybackPositionTicks = positionTicks;
  439. return playedToCompletion;
  440. }
  441. /// <summary>
  442. /// Gets the session.
  443. /// </summary>
  444. /// <param name="sessionId">The session identifier.</param>
  445. /// <returns>SessionInfo.</returns>
  446. /// <exception cref="ResourceNotFoundException"></exception>
  447. private SessionInfo GetSession(Guid sessionId)
  448. {
  449. var session = Sessions.First(i => i.Id.Equals(sessionId));
  450. if (session == null)
  451. {
  452. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  453. }
  454. return session;
  455. }
  456. /// <summary>
  457. /// Gets the session for remote control.
  458. /// </summary>
  459. /// <param name="sessionId">The session id.</param>
  460. /// <returns>SessionInfo.</returns>
  461. /// <exception cref="ResourceNotFoundException"></exception>
  462. private SessionInfo GetSessionForRemoteControl(Guid sessionId)
  463. {
  464. var session = GetSession(sessionId);
  465. if (!session.SupportsRemoteControl)
  466. {
  467. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  468. }
  469. return session;
  470. }
  471. /// <summary>
  472. /// Sends the system command.
  473. /// </summary>
  474. /// <param name="sessionId">The session id.</param>
  475. /// <param name="command">The command.</param>
  476. /// <param name="cancellationToken">The cancellation token.</param>
  477. /// <returns>Task.</returns>
  478. public Task SendSystemCommand(Guid sessionId, SystemCommand command, CancellationToken cancellationToken)
  479. {
  480. var session = GetSessionForRemoteControl(sessionId);
  481. return session.SessionController.SendSystemCommand(command, cancellationToken);
  482. }
  483. /// <summary>
  484. /// Sends the message command.
  485. /// </summary>
  486. /// <param name="sessionId">The session id.</param>
  487. /// <param name="command">The command.</param>
  488. /// <param name="cancellationToken">The cancellation token.</param>
  489. /// <returns>Task.</returns>
  490. public Task SendMessageCommand(Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  491. {
  492. var session = GetSessionForRemoteControl(sessionId);
  493. return session.SessionController.SendMessageCommand(command, cancellationToken);
  494. }
  495. /// <summary>
  496. /// Sends the play command.
  497. /// </summary>
  498. /// <param name="sessionId">The session id.</param>
  499. /// <param name="command">The command.</param>
  500. /// <param name="cancellationToken">The cancellation token.</param>
  501. /// <returns>Task.</returns>
  502. public Task SendPlayCommand(Guid sessionId, PlayRequest command, CancellationToken cancellationToken)
  503. {
  504. var session = GetSessionForRemoteControl(sessionId);
  505. var items = command.ItemIds.Select(i => _libraryManager.GetItemById(new Guid(i)))
  506. .ToList();
  507. if (items.Any(i => i.LocationType == LocationType.Virtual))
  508. {
  509. throw new ArgumentException("Virtual items are not playable.");
  510. }
  511. if (command.PlayCommand != PlayCommand.PlayNow)
  512. {
  513. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  514. {
  515. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  516. }
  517. }
  518. else
  519. {
  520. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  521. {
  522. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  523. }
  524. }
  525. return session.SessionController.SendPlayCommand(command, cancellationToken);
  526. }
  527. /// <summary>
  528. /// Sends the browse command.
  529. /// </summary>
  530. /// <param name="sessionId">The session id.</param>
  531. /// <param name="command">The command.</param>
  532. /// <param name="cancellationToken">The cancellation token.</param>
  533. /// <returns>Task.</returns>
  534. public Task SendBrowseCommand(Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  535. {
  536. var session = GetSessionForRemoteControl(sessionId);
  537. return session.SessionController.SendBrowseCommand(command, cancellationToken);
  538. }
  539. /// <summary>
  540. /// Sends the playstate command.
  541. /// </summary>
  542. /// <param name="sessionId">The session id.</param>
  543. /// <param name="command">The command.</param>
  544. /// <param name="cancellationToken">The cancellation token.</param>
  545. /// <returns>Task.</returns>
  546. public Task SendPlaystateCommand(Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  547. {
  548. var session = GetSessionForRemoteControl(sessionId);
  549. if (command.Command == PlaystateCommand.Seek && !session.CanSeek)
  550. {
  551. throw new ArgumentException(string.Format("Session {0} is unable to seek.", session.Id));
  552. }
  553. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  554. }
  555. /// <summary>
  556. /// Sends the restart required message.
  557. /// </summary>
  558. /// <param name="cancellationToken">The cancellation token.</param>
  559. /// <returns>Task.</returns>
  560. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  561. {
  562. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  563. var tasks = sessions.Select(session => Task.Run(async () =>
  564. {
  565. try
  566. {
  567. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  568. }
  569. catch (Exception ex)
  570. {
  571. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  572. }
  573. }, cancellationToken));
  574. return Task.WhenAll(tasks);
  575. }
  576. /// <summary>
  577. /// Sends the server shutdown notification.
  578. /// </summary>
  579. /// <param name="cancellationToken">The cancellation token.</param>
  580. /// <returns>Task.</returns>
  581. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  582. {
  583. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  584. var tasks = sessions.Select(session => Task.Run(async () =>
  585. {
  586. try
  587. {
  588. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  589. }
  590. catch (Exception ex)
  591. {
  592. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  593. }
  594. }, cancellationToken));
  595. return Task.WhenAll(tasks);
  596. }
  597. /// <summary>
  598. /// Sends the server restart notification.
  599. /// </summary>
  600. /// <param name="cancellationToken">The cancellation token.</param>
  601. /// <returns>Task.</returns>
  602. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  603. {
  604. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  605. var tasks = sessions.Select(session => Task.Run(async () =>
  606. {
  607. try
  608. {
  609. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  610. }
  611. catch (Exception ex)
  612. {
  613. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  614. }
  615. }, cancellationToken));
  616. return Task.WhenAll(tasks);
  617. }
  618. /// <summary>
  619. /// Adds the additional user.
  620. /// </summary>
  621. /// <param name="sessionId">The session identifier.</param>
  622. /// <param name="userId">The user identifier.</param>
  623. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  624. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  625. public void AddAdditionalUser(Guid sessionId, Guid userId)
  626. {
  627. var session = GetSession(sessionId);
  628. if (!session.UserId.HasValue)
  629. {
  630. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  631. }
  632. if (session.UserId.Value == userId)
  633. {
  634. throw new ArgumentException("The requested user is already the primary user of the session.");
  635. }
  636. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  637. {
  638. var user = _userManager.GetUserById(userId);
  639. session.AdditionalUsers.Add(new SessionUserInfo
  640. {
  641. UserId = userId.ToString("N"),
  642. UserName = user.Name
  643. });
  644. }
  645. }
  646. /// <summary>
  647. /// Removes the additional user.
  648. /// </summary>
  649. /// <param name="sessionId">The session identifier.</param>
  650. /// <param name="userId">The user identifier.</param>
  651. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  652. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  653. public void RemoveAdditionalUser(Guid sessionId, Guid userId)
  654. {
  655. var session = GetSession(sessionId);
  656. if (!session.UserId.HasValue)
  657. {
  658. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  659. }
  660. if (session.UserId.Value == userId)
  661. {
  662. throw new ArgumentException("The requested user is already the primary user of the session.");
  663. }
  664. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  665. if (user != null)
  666. {
  667. session.AdditionalUsers.Remove(user);
  668. }
  669. }
  670. }
  671. }