SessionManager.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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. /// <summary>
  519. /// Sends the system command.
  520. /// </summary>
  521. /// <param name="sessionId">The session id.</param>
  522. /// <param name="command">The command.</param>
  523. /// <param name="cancellationToken">The cancellation token.</param>
  524. /// <returns>Task.</returns>
  525. public Task SendSystemCommand(Guid sessionId, SystemCommand command, CancellationToken cancellationToken)
  526. {
  527. var session = GetSessionForRemoteControl(sessionId);
  528. return session.SessionController.SendSystemCommand(command, cancellationToken);
  529. }
  530. /// <summary>
  531. /// Sends the message command.
  532. /// </summary>
  533. /// <param name="sessionId">The session id.</param>
  534. /// <param name="command">The command.</param>
  535. /// <param name="cancellationToken">The cancellation token.</param>
  536. /// <returns>Task.</returns>
  537. public Task SendMessageCommand(Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  538. {
  539. var session = GetSessionForRemoteControl(sessionId);
  540. return session.SessionController.SendMessageCommand(command, cancellationToken);
  541. }
  542. /// <summary>
  543. /// Sends the play command.
  544. /// </summary>
  545. /// <param name="sessionId">The session id.</param>
  546. /// <param name="command">The command.</param>
  547. /// <param name="cancellationToken">The cancellation token.</param>
  548. /// <returns>Task.</returns>
  549. public Task SendPlayCommand(Guid sessionId, PlayRequest command, CancellationToken cancellationToken)
  550. {
  551. var session = GetSessionForRemoteControl(sessionId);
  552. var items = command.ItemIds.Select(i => _libraryManager.GetItemById(new Guid(i)))
  553. .Where(i => i.LocationType != LocationType.Virtual)
  554. .ToList();
  555. if (session.UserId.HasValue)
  556. {
  557. var user = _userManager.GetUserById(session.UserId.Value);
  558. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  559. {
  560. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  561. }
  562. }
  563. if (command.PlayCommand != PlayCommand.PlayNow)
  564. {
  565. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  566. {
  567. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  568. }
  569. }
  570. else
  571. {
  572. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  573. {
  574. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  575. }
  576. }
  577. return session.SessionController.SendPlayCommand(command, cancellationToken);
  578. }
  579. /// <summary>
  580. /// Sends the browse command.
  581. /// </summary>
  582. /// <param name="sessionId">The session id.</param>
  583. /// <param name="command">The command.</param>
  584. /// <param name="cancellationToken">The cancellation token.</param>
  585. /// <returns>Task.</returns>
  586. public Task SendBrowseCommand(Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  587. {
  588. var session = GetSessionForRemoteControl(sessionId);
  589. return session.SessionController.SendBrowseCommand(command, cancellationToken);
  590. }
  591. /// <summary>
  592. /// Sends the playstate command.
  593. /// </summary>
  594. /// <param name="sessionId">The session id.</param>
  595. /// <param name="command">The command.</param>
  596. /// <param name="cancellationToken">The cancellation token.</param>
  597. /// <returns>Task.</returns>
  598. public Task SendPlaystateCommand(Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  599. {
  600. var session = GetSessionForRemoteControl(sessionId);
  601. if (command.Command == PlaystateCommand.Seek && !session.CanSeek)
  602. {
  603. throw new ArgumentException(string.Format("Session {0} is unable to seek.", session.Id));
  604. }
  605. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  606. }
  607. /// <summary>
  608. /// Sends the restart required message.
  609. /// </summary>
  610. /// <param name="cancellationToken">The cancellation token.</param>
  611. /// <returns>Task.</returns>
  612. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  613. {
  614. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  615. var tasks = sessions.Select(session => Task.Run(async () =>
  616. {
  617. try
  618. {
  619. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  620. }
  621. catch (Exception ex)
  622. {
  623. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  624. }
  625. }, cancellationToken));
  626. return Task.WhenAll(tasks);
  627. }
  628. /// <summary>
  629. /// Sends the server shutdown notification.
  630. /// </summary>
  631. /// <param name="cancellationToken">The cancellation token.</param>
  632. /// <returns>Task.</returns>
  633. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  634. {
  635. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  636. var tasks = sessions.Select(session => Task.Run(async () =>
  637. {
  638. try
  639. {
  640. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  641. }
  642. catch (Exception ex)
  643. {
  644. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  645. }
  646. }, cancellationToken));
  647. return Task.WhenAll(tasks);
  648. }
  649. /// <summary>
  650. /// Sends the server restart notification.
  651. /// </summary>
  652. /// <param name="cancellationToken">The cancellation token.</param>
  653. /// <returns>Task.</returns>
  654. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  655. {
  656. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  657. var tasks = sessions.Select(session => Task.Run(async () =>
  658. {
  659. try
  660. {
  661. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  662. }
  663. catch (Exception ex)
  664. {
  665. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  666. }
  667. }, cancellationToken));
  668. return Task.WhenAll(tasks);
  669. }
  670. /// <summary>
  671. /// Adds the additional user.
  672. /// </summary>
  673. /// <param name="sessionId">The session identifier.</param>
  674. /// <param name="userId">The user identifier.</param>
  675. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  676. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  677. public void AddAdditionalUser(Guid sessionId, Guid userId)
  678. {
  679. var session = GetSession(sessionId);
  680. if (!session.UserId.HasValue)
  681. {
  682. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  683. }
  684. if (session.UserId.Value == userId)
  685. {
  686. throw new ArgumentException("The requested user is already the primary user of the session.");
  687. }
  688. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  689. {
  690. var user = _userManager.GetUserById(userId);
  691. session.AdditionalUsers.Add(new SessionUserInfo
  692. {
  693. UserId = userId.ToString("N"),
  694. UserName = user.Name
  695. });
  696. }
  697. }
  698. /// <summary>
  699. /// Removes the additional user.
  700. /// </summary>
  701. /// <param name="sessionId">The session identifier.</param>
  702. /// <param name="userId">The user identifier.</param>
  703. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  704. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  705. public void RemoveAdditionalUser(Guid sessionId, Guid userId)
  706. {
  707. var session = GetSession(sessionId);
  708. if (!session.UserId.HasValue)
  709. {
  710. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  711. }
  712. if (session.UserId.Value == userId)
  713. {
  714. throw new ArgumentException("The requested user is already the primary user of the session.");
  715. }
  716. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  717. if (user != null)
  718. {
  719. session.AdditionalUsers.Remove(user);
  720. }
  721. }
  722. /// <summary>
  723. /// Authenticates the new session.
  724. /// </summary>
  725. /// <param name="user">The user.</param>
  726. /// <param name="password">The password.</param>
  727. /// <param name="clientType">Type of the client.</param>
  728. /// <param name="appVersion">The application version.</param>
  729. /// <param name="deviceId">The device identifier.</param>
  730. /// <param name="deviceName">Name of the device.</param>
  731. /// <param name="remoteEndPoint">The remote end point.</param>
  732. /// <returns>Task{SessionInfo}.</returns>
  733. /// <exception cref="UnauthorizedAccessException"></exception>
  734. public async Task<SessionInfo> AuthenticateNewSession(User user, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  735. {
  736. var result = await _userManager.AuthenticateUser(user, password).ConfigureAwait(false);
  737. if (!result)
  738. {
  739. throw new UnauthorizedAccessException("Invalid user or password entered.");
  740. }
  741. return await LogSessionActivity(clientType, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
  742. }
  743. }
  744. }