SessionManager.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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="mediaSourceId">The media version identifier.</param>
  190. /// <param name="isPaused">if set to <c>true</c> [is paused].</param>
  191. /// <param name="isMuted">if set to <c>true</c> [is muted].</param>
  192. /// <param name="currentPositionTicks">The current position ticks.</param>
  193. private void UpdateNowPlayingItem(SessionInfo session, BaseItem item, string mediaSourceId, bool isPaused, bool isMuted, long? currentPositionTicks = null)
  194. {
  195. session.IsMuted = isMuted;
  196. session.IsPaused = isPaused;
  197. session.NowPlayingPositionTicks = currentPositionTicks;
  198. session.NowPlayingItem = item;
  199. session.LastActivityDate = DateTime.UtcNow;
  200. session.NowPlayingMediaSourceId = mediaSourceId;
  201. if (string.IsNullOrWhiteSpace(mediaSourceId))
  202. {
  203. session.NowPlayingRunTimeTicks = item.RunTimeTicks;
  204. }
  205. else
  206. {
  207. var version = _libraryManager.GetItemById(new Guid(mediaSourceId));
  208. session.NowPlayingRunTimeTicks = version.RunTimeTicks;
  209. }
  210. }
  211. /// <summary>
  212. /// Removes the now playing item id.
  213. /// </summary>
  214. /// <param name="session">The session.</param>
  215. /// <param name="item">The item.</param>
  216. private void RemoveNowPlayingItem(SessionInfo session, BaseItem item)
  217. {
  218. if (item == null)
  219. {
  220. throw new ArgumentNullException("item");
  221. }
  222. if (session.NowPlayingItem != null && session.NowPlayingItem.Id == item.Id)
  223. {
  224. session.NowPlayingItem = null;
  225. session.NowPlayingPositionTicks = null;
  226. session.IsPaused = false;
  227. session.NowPlayingRunTimeTicks = null;
  228. session.NowPlayingMediaSourceId = null;
  229. }
  230. }
  231. private string GetSessionKey(string clientType, string appVersion, string deviceId)
  232. {
  233. return clientType + deviceId + appVersion;
  234. }
  235. /// <summary>
  236. /// Gets the connection.
  237. /// </summary>
  238. /// <param name="clientType">Type of the client.</param>
  239. /// <param name="appVersion">The app version.</param>
  240. /// <param name="deviceId">The device id.</param>
  241. /// <param name="deviceName">Name of the device.</param>
  242. /// <param name="remoteEndPoint">The remote end point.</param>
  243. /// <param name="userId">The user identifier.</param>
  244. /// <param name="username">The username.</param>
  245. /// <returns>SessionInfo.</returns>
  246. private async Task<SessionInfo> GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username)
  247. {
  248. var key = GetSessionKey(clientType, appVersion, deviceId);
  249. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  250. try
  251. {
  252. var connection = _activeConnections.GetOrAdd(key, keyName => new SessionInfo
  253. {
  254. Client = clientType,
  255. DeviceId = deviceId,
  256. ApplicationVersion = appVersion,
  257. Id = Guid.NewGuid()
  258. });
  259. connection.DeviceName = deviceName;
  260. connection.UserId = userId;
  261. connection.UserName = username;
  262. connection.RemoteEndPoint = remoteEndPoint;
  263. if (!userId.HasValue)
  264. {
  265. connection.AdditionalUsers.Clear();
  266. }
  267. if (connection.SessionController == null)
  268. {
  269. connection.SessionController = _sessionFactories
  270. .Select(i => i.GetSessionController(connection))
  271. .FirstOrDefault(i => i != null);
  272. }
  273. return connection;
  274. }
  275. finally
  276. {
  277. _sessionLock.Release();
  278. }
  279. }
  280. private List<User> GetUsers(SessionInfo session)
  281. {
  282. var users = new List<User>();
  283. if (session.UserId.HasValue)
  284. {
  285. var user = _userManager.GetUserById(session.UserId.Value);
  286. if (user == null)
  287. {
  288. throw new InvalidOperationException("User not found");
  289. }
  290. users.Add(user);
  291. var additionalUsers = session.AdditionalUsers
  292. .Select(i => _userManager.GetUserById(new Guid(i.UserId)))
  293. .Where(i => i != null);
  294. users.AddRange(additionalUsers);
  295. }
  296. return users;
  297. }
  298. /// <summary>
  299. /// Used to report that playback has started for an item
  300. /// </summary>
  301. /// <param name="info">The info.</param>
  302. /// <returns>Task.</returns>
  303. /// <exception cref="System.ArgumentNullException">info</exception>
  304. public async Task OnPlaybackStart(PlaybackInfo info)
  305. {
  306. if (info == null)
  307. {
  308. throw new ArgumentNullException("info");
  309. }
  310. if (info.SessionId == Guid.Empty)
  311. {
  312. throw new ArgumentNullException("info");
  313. }
  314. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  315. var item = info.Item;
  316. var mediaSourceId = GetMediaSourceId(item, info.MediaSourceId);
  317. UpdateNowPlayingItem(session, item, mediaSourceId, false, false);
  318. session.CanSeek = info.CanSeek;
  319. session.QueueableMediaTypes = info.QueueableMediaTypes;
  320. var key = item.GetUserDataKey();
  321. var users = GetUsers(session);
  322. foreach (var user in users)
  323. {
  324. await OnPlaybackStart(user.Id, key, item).ConfigureAwait(false);
  325. }
  326. // Nothing to save here
  327. // Fire events to inform plugins
  328. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  329. {
  330. Item = item,
  331. Users = users,
  332. MediaSourceId = info.MediaSourceId
  333. }, _logger);
  334. }
  335. /// <summary>
  336. /// Called when [playback start].
  337. /// </summary>
  338. /// <param name="userId">The user identifier.</param>
  339. /// <param name="userDataKey">The user data key.</param>
  340. /// <param name="item">The item.</param>
  341. /// <returns>Task.</returns>
  342. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  343. {
  344. var data = _userDataRepository.GetUserData(userId, userDataKey);
  345. data.PlayCount++;
  346. data.LastPlayedDate = DateTime.UtcNow;
  347. if (!(item is Video))
  348. {
  349. data.Played = true;
  350. }
  351. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  352. }
  353. /// <summary>
  354. /// Used to report playback progress for an item
  355. /// </summary>
  356. /// <param name="info">The info.</param>
  357. /// <returns>Task.</returns>
  358. /// <exception cref="System.ArgumentNullException"></exception>
  359. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  360. public async Task OnPlaybackProgress(Controller.Session.PlaybackProgressInfo info)
  361. {
  362. if (info == null)
  363. {
  364. throw new ArgumentNullException("info");
  365. }
  366. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  367. {
  368. throw new ArgumentOutOfRangeException("positionTicks");
  369. }
  370. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  371. var mediaSourceId = GetMediaSourceId(info.Item, info.MediaSourceId);
  372. UpdateNowPlayingItem(session, info.Item, mediaSourceId, info.IsPaused, info.IsMuted, info.PositionTicks);
  373. var key = info.Item.GetUserDataKey();
  374. var users = GetUsers(session);
  375. foreach (var user in users)
  376. {
  377. await OnPlaybackProgress(user.Id, key, info.Item, info.PositionTicks).ConfigureAwait(false);
  378. }
  379. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  380. {
  381. Item = info.Item,
  382. Users = users,
  383. PlaybackPositionTicks = info.PositionTicks,
  384. MediaSourceId = mediaSourceId
  385. }, _logger);
  386. }
  387. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  388. {
  389. var data = _userDataRepository.GetUserData(userId, userDataKey);
  390. if (positionTicks.HasValue)
  391. {
  392. UpdatePlayState(item, data, positionTicks.Value);
  393. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  394. }
  395. }
  396. /// <summary>
  397. /// Used to report that playback has ended for an item
  398. /// </summary>
  399. /// <param name="info">The info.</param>
  400. /// <returns>Task.</returns>
  401. /// <exception cref="System.ArgumentNullException">info</exception>
  402. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  403. public async Task OnPlaybackStopped(Controller.Session.PlaybackStopInfo info)
  404. {
  405. if (info == null)
  406. {
  407. throw new ArgumentNullException("info");
  408. }
  409. if (info.Item == null)
  410. {
  411. throw new ArgumentException("PlaybackStopInfo.Item cannot be null");
  412. }
  413. if (info.SessionId == Guid.Empty)
  414. {
  415. throw new ArgumentException("PlaybackStopInfo.SessionId cannot be Guid.Empty");
  416. }
  417. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  418. {
  419. throw new ArgumentOutOfRangeException("positionTicks");
  420. }
  421. var session = Sessions.First(i => i.Id.Equals(info.SessionId));
  422. RemoveNowPlayingItem(session, info.Item);
  423. var key = info.Item.GetUserDataKey();
  424. var users = GetUsers(session);
  425. var playedToCompletion = false;
  426. foreach (var user in users)
  427. {
  428. playedToCompletion = await OnPlaybackStopped(user.Id, key, info.Item, info.PositionTicks).ConfigureAwait(false);
  429. }
  430. var mediaSourceId = GetMediaSourceId(info.Item, info.MediaSourceId);
  431. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  432. {
  433. Item = info.Item,
  434. Users = users,
  435. PlaybackPositionTicks = info.PositionTicks,
  436. PlayedToCompletion = playedToCompletion,
  437. MediaSourceId = mediaSourceId
  438. }, _logger);
  439. }
  440. private string GetMediaSourceId(BaseItem item, string reportedMediaSourceId)
  441. {
  442. if (string.IsNullOrWhiteSpace(reportedMediaSourceId))
  443. {
  444. if (item is Video || item is Audio)
  445. {
  446. reportedMediaSourceId = item.Id.ToString("N");
  447. }
  448. }
  449. return reportedMediaSourceId;
  450. }
  451. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  452. {
  453. var data = _userDataRepository.GetUserData(userId, userDataKey);
  454. bool playedToCompletion;
  455. if (positionTicks.HasValue)
  456. {
  457. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  458. }
  459. else
  460. {
  461. // If the client isn't able to report this, then we'll just have to make an assumption
  462. data.PlayCount++;
  463. data.Played = true;
  464. data.PlaybackPositionTicks = 0;
  465. playedToCompletion = true;
  466. }
  467. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  468. return playedToCompletion;
  469. }
  470. /// <summary>
  471. /// Updates playstate position for an item but does not save
  472. /// </summary>
  473. /// <param name="item">The item</param>
  474. /// <param name="data">User data for the item</param>
  475. /// <param name="positionTicks">The current playback position</param>
  476. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  477. {
  478. var playedToCompletion = false;
  479. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  480. // If a position has been reported, and if we know the duration
  481. if (positionTicks > 0 && hasRuntime)
  482. {
  483. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  484. // Don't track in very beginning
  485. if (pctIn < _configurationManager.Configuration.MinResumePct)
  486. {
  487. positionTicks = 0;
  488. }
  489. // If we're at the end, assume completed
  490. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  491. {
  492. positionTicks = 0;
  493. data.Played = playedToCompletion = true;
  494. }
  495. else
  496. {
  497. // Enforce MinResumeDuration
  498. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  499. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  500. {
  501. positionTicks = 0;
  502. data.Played = playedToCompletion = true;
  503. }
  504. }
  505. }
  506. else if (!hasRuntime)
  507. {
  508. // If we don't know the runtime we'll just have to assume it was fully played
  509. data.Played = playedToCompletion = true;
  510. positionTicks = 0;
  511. }
  512. if (item is Audio)
  513. {
  514. positionTicks = 0;
  515. }
  516. data.PlaybackPositionTicks = positionTicks;
  517. return playedToCompletion;
  518. }
  519. /// <summary>
  520. /// Gets the session.
  521. /// </summary>
  522. /// <param name="sessionId">The session identifier.</param>
  523. /// <returns>SessionInfo.</returns>
  524. /// <exception cref="ResourceNotFoundException"></exception>
  525. private SessionInfo GetSession(Guid sessionId)
  526. {
  527. var session = Sessions.First(i => i.Id.Equals(sessionId));
  528. if (session == null)
  529. {
  530. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  531. }
  532. return session;
  533. }
  534. /// <summary>
  535. /// Gets the session for remote control.
  536. /// </summary>
  537. /// <param name="sessionId">The session id.</param>
  538. /// <returns>SessionInfo.</returns>
  539. /// <exception cref="ResourceNotFoundException"></exception>
  540. private SessionInfo GetSessionForRemoteControl(Guid sessionId)
  541. {
  542. var session = GetSession(sessionId);
  543. if (!session.SupportsRemoteControl)
  544. {
  545. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  546. }
  547. return session;
  548. }
  549. public Task SendSystemCommand(Guid controllingSessionId, Guid sessionId, SystemCommand command, CancellationToken cancellationToken)
  550. {
  551. var session = GetSessionForRemoteControl(sessionId);
  552. var controllingSession = GetSession(controllingSessionId);
  553. AssertCanControl(session, controllingSession);
  554. return session.SessionController.SendSystemCommand(command, cancellationToken);
  555. }
  556. public Task SendMessageCommand(Guid controllingSessionId, Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  557. {
  558. var session = GetSessionForRemoteControl(sessionId);
  559. var controllingSession = GetSession(controllingSessionId);
  560. AssertCanControl(session, controllingSession);
  561. return session.SessionController.SendMessageCommand(command, cancellationToken);
  562. }
  563. public Task SendPlayCommand(Guid controllingSessionId, Guid sessionId, PlayRequest command, CancellationToken cancellationToken)
  564. {
  565. var session = GetSessionForRemoteControl(sessionId);
  566. var items = command.ItemIds.Select(i => _libraryManager.GetItemById(new Guid(i)))
  567. .Where(i => i.LocationType != LocationType.Virtual)
  568. .ToList();
  569. if (session.UserId.HasValue)
  570. {
  571. var user = _userManager.GetUserById(session.UserId.Value);
  572. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  573. {
  574. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  575. }
  576. }
  577. if (command.PlayCommand != PlayCommand.PlayNow)
  578. {
  579. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  580. {
  581. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  582. }
  583. }
  584. else
  585. {
  586. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  587. {
  588. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  589. }
  590. }
  591. var controllingSession = GetSession(controllingSessionId);
  592. AssertCanControl(session, controllingSession);
  593. if (controllingSession.UserId.HasValue)
  594. {
  595. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  596. }
  597. return session.SessionController.SendPlayCommand(command, cancellationToken);
  598. }
  599. public Task SendBrowseCommand(Guid controllingSessionId, Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  600. {
  601. var session = GetSessionForRemoteControl(sessionId);
  602. var controllingSession = GetSession(controllingSessionId);
  603. AssertCanControl(session, controllingSession);
  604. return session.SessionController.SendBrowseCommand(command, cancellationToken);
  605. }
  606. public Task SendPlaystateCommand(Guid controllingSessionId, Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  607. {
  608. var session = GetSessionForRemoteControl(sessionId);
  609. if (command.Command == PlaystateCommand.Seek && !session.CanSeek)
  610. {
  611. throw new ArgumentException(string.Format("Session {0} is unable to seek.", session.Id));
  612. }
  613. var controllingSession = GetSession(controllingSessionId);
  614. AssertCanControl(session, controllingSession);
  615. if (controllingSession.UserId.HasValue)
  616. {
  617. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  618. }
  619. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  620. }
  621. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  622. {
  623. if (session == null)
  624. {
  625. throw new ArgumentNullException("session");
  626. }
  627. if (controllingSession == null)
  628. {
  629. throw new ArgumentNullException("controllingSession");
  630. }
  631. }
  632. /// <summary>
  633. /// Sends the restart required message.
  634. /// </summary>
  635. /// <param name="cancellationToken">The cancellation token.</param>
  636. /// <returns>Task.</returns>
  637. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  638. {
  639. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  640. var tasks = sessions.Select(session => Task.Run(async () =>
  641. {
  642. try
  643. {
  644. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  645. }
  646. catch (Exception ex)
  647. {
  648. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  649. }
  650. }, cancellationToken));
  651. return Task.WhenAll(tasks);
  652. }
  653. /// <summary>
  654. /// Sends the server shutdown notification.
  655. /// </summary>
  656. /// <param name="cancellationToken">The cancellation token.</param>
  657. /// <returns>Task.</returns>
  658. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  659. {
  660. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  661. var tasks = sessions.Select(session => Task.Run(async () =>
  662. {
  663. try
  664. {
  665. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  666. }
  667. catch (Exception ex)
  668. {
  669. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  670. }
  671. }, cancellationToken));
  672. return Task.WhenAll(tasks);
  673. }
  674. /// <summary>
  675. /// Sends the server restart notification.
  676. /// </summary>
  677. /// <param name="cancellationToken">The cancellation token.</param>
  678. /// <returns>Task.</returns>
  679. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  680. {
  681. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  682. var tasks = sessions.Select(session => Task.Run(async () =>
  683. {
  684. try
  685. {
  686. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  687. }
  688. catch (Exception ex)
  689. {
  690. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  691. }
  692. }, cancellationToken));
  693. return Task.WhenAll(tasks);
  694. }
  695. /// <summary>
  696. /// Adds the additional user.
  697. /// </summary>
  698. /// <param name="sessionId">The session identifier.</param>
  699. /// <param name="userId">The user identifier.</param>
  700. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  701. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  702. public void AddAdditionalUser(Guid sessionId, Guid userId)
  703. {
  704. var session = GetSession(sessionId);
  705. if (!session.UserId.HasValue)
  706. {
  707. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  708. }
  709. if (session.UserId.Value == userId)
  710. {
  711. throw new ArgumentException("The requested user is already the primary user of the session.");
  712. }
  713. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  714. {
  715. var user = _userManager.GetUserById(userId);
  716. session.AdditionalUsers.Add(new SessionUserInfo
  717. {
  718. UserId = userId.ToString("N"),
  719. UserName = user.Name
  720. });
  721. }
  722. }
  723. /// <summary>
  724. /// Removes the additional user.
  725. /// </summary>
  726. /// <param name="sessionId">The session identifier.</param>
  727. /// <param name="userId">The user identifier.</param>
  728. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  729. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  730. public void RemoveAdditionalUser(Guid sessionId, Guid userId)
  731. {
  732. var session = GetSession(sessionId);
  733. if (!session.UserId.HasValue)
  734. {
  735. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  736. }
  737. if (session.UserId.Value == userId)
  738. {
  739. throw new ArgumentException("The requested user is already the primary user of the session.");
  740. }
  741. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  742. if (user != null)
  743. {
  744. session.AdditionalUsers.Remove(user);
  745. }
  746. }
  747. /// <summary>
  748. /// Authenticates the new session.
  749. /// </summary>
  750. /// <param name="user">The user.</param>
  751. /// <param name="password">The password.</param>
  752. /// <param name="clientType">Type of the client.</param>
  753. /// <param name="appVersion">The application version.</param>
  754. /// <param name="deviceId">The device identifier.</param>
  755. /// <param name="deviceName">Name of the device.</param>
  756. /// <param name="remoteEndPoint">The remote end point.</param>
  757. /// <returns>Task{SessionInfo}.</returns>
  758. /// <exception cref="UnauthorizedAccessException"></exception>
  759. public async Task<SessionInfo> AuthenticateNewSession(User user, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  760. {
  761. var result = await _userManager.AuthenticateUser(user, password).ConfigureAwait(false);
  762. if (!result)
  763. {
  764. throw new UnauthorizedAccessException("Invalid user or password entered.");
  765. }
  766. return await LogSessionActivity(clientType, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
  767. }
  768. /// <summary>
  769. /// Reports the capabilities.
  770. /// </summary>
  771. /// <param name="sessionId">The session identifier.</param>
  772. /// <param name="capabilities">The capabilities.</param>
  773. public void ReportCapabilities(Guid sessionId, SessionCapabilities capabilities)
  774. {
  775. var session = GetSession(sessionId);
  776. session.PlayableMediaTypes = capabilities.PlayableMediaTypes.ToList();
  777. session.SupportsFullscreenToggle = capabilities.SupportsFullscreenToggle;
  778. session.SupportsOsdToggle = capabilities.SupportsOsdToggle;
  779. session.SupportsNavigationControl = capabilities.SupportsNavigationControl;
  780. }
  781. }
  782. }