SessionManager.cs 31 KB

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