SessionManager.cs 34 KB

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