SessionManager.cs 36 KB

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