SessionManager.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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. private readonly IMusicManager _musicManager;
  41. /// <summary>
  42. /// Gets or sets the configuration manager.
  43. /// </summary>
  44. /// <value>The configuration manager.</value>
  45. private readonly IServerConfigurationManager _configurationManager;
  46. /// <summary>
  47. /// The _active connections
  48. /// </summary>
  49. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  50. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  51. /// <summary>
  52. /// Occurs when [playback start].
  53. /// </summary>
  54. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  55. /// <summary>
  56. /// Occurs when [playback progress].
  57. /// </summary>
  58. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  59. /// <summary>
  60. /// Occurs when [playback stopped].
  61. /// </summary>
  62. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  63. private IEnumerable<ISessionControllerFactory> _sessionFactories = new List<ISessionControllerFactory>();
  64. private readonly SemaphoreSlim _sessionLock = new SemaphoreSlim(1, 1);
  65. /// <summary>
  66. /// Initializes a new instance of the <see cref="SessionManager" /> class.
  67. /// </summary>
  68. /// <param name="userDataRepository">The user data repository.</param>
  69. /// <param name="configurationManager">The configuration manager.</param>
  70. /// <param name="logger">The logger.</param>
  71. /// <param name="userRepository">The user repository.</param>
  72. /// <param name="libraryManager">The library manager.</param>
  73. public SessionManager(IUserDataManager userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository, ILibraryManager libraryManager, IUserManager userManager, IMusicManager musicManager)
  74. {
  75. _userDataRepository = userDataRepository;
  76. _configurationManager = configurationManager;
  77. _logger = logger;
  78. _userRepository = userRepository;
  79. _libraryManager = libraryManager;
  80. _userManager = userManager;
  81. _musicManager = musicManager;
  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 SendMessageCommand(Guid controllingSessionId, Guid sessionId, MessageCommand command, CancellationToken cancellationToken)
  552. {
  553. var session = GetSessionForRemoteControl(sessionId);
  554. var controllingSession = GetSession(controllingSessionId);
  555. AssertCanControl(session, controllingSession);
  556. return session.SessionController.SendMessageCommand(command, cancellationToken);
  557. }
  558. public Task SendGeneralCommand(Guid controllingSessionId, Guid sessionId, GeneralCommand command, CancellationToken cancellationToken)
  559. {
  560. var session = GetSessionForRemoteControl(sessionId);
  561. var controllingSession = GetSession(controllingSessionId);
  562. AssertCanControl(session, controllingSession);
  563. return session.SessionController.SendGeneralCommand(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. List<BaseItem> items;
  570. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  571. {
  572. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  573. .Where(i => i.LocationType != LocationType.Virtual)
  574. .ToList();
  575. command.PlayCommand = PlayCommand.PlayNow;
  576. }
  577. else
  578. {
  579. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  580. .Where(i => i.LocationType != LocationType.Virtual)
  581. .ToList();
  582. }
  583. if (command.PlayCommand == PlayCommand.PlayShuffle)
  584. {
  585. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  586. command.PlayCommand = PlayCommand.PlayNow;
  587. }
  588. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  589. if (user != null)
  590. {
  591. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  592. {
  593. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  594. }
  595. }
  596. if (command.PlayCommand != PlayCommand.PlayNow)
  597. {
  598. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  599. {
  600. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  601. }
  602. }
  603. else
  604. {
  605. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  606. {
  607. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  608. }
  609. }
  610. var controllingSession = GetSession(controllingSessionId);
  611. AssertCanControl(session, controllingSession);
  612. if (controllingSession.UserId.HasValue)
  613. {
  614. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  615. }
  616. return session.SessionController.SendPlayCommand(command, cancellationToken);
  617. }
  618. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  619. {
  620. var item = _libraryManager.GetItemById(new Guid(id));
  621. if (item.IsFolder)
  622. {
  623. var folder = (Folder)item;
  624. var items = user == null ? folder.RecursiveChildren :
  625. folder.GetRecursiveChildren(user);
  626. items = items.Where(i => !i.IsFolder);
  627. items = items.OrderBy(i => i.SortName);
  628. return items;
  629. }
  630. return new[] { item };
  631. }
  632. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  633. {
  634. var item = _libraryManager.GetItemById(new Guid(id));
  635. var audio = item as Audio;
  636. if (audio != null)
  637. {
  638. return _musicManager.GetInstantMixFromSong(audio, user);
  639. }
  640. var artist = item as MusicArtist;
  641. if (artist != null)
  642. {
  643. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  644. }
  645. var album = item as MusicAlbum;
  646. if (album != null)
  647. {
  648. return _musicManager.GetInstantMixFromAlbum(album, user);
  649. }
  650. var genre = item as MusicGenre;
  651. if (genre != null)
  652. {
  653. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  654. }
  655. return new BaseItem[] { };
  656. }
  657. public Task SendBrowseCommand(Guid controllingSessionId, Guid sessionId, BrowseRequest command, CancellationToken cancellationToken)
  658. {
  659. var session = GetSessionForRemoteControl(sessionId);
  660. var controllingSession = GetSession(controllingSessionId);
  661. AssertCanControl(session, controllingSession);
  662. return session.SessionController.SendBrowseCommand(command, cancellationToken);
  663. }
  664. public Task SendPlaystateCommand(Guid controllingSessionId, Guid sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  665. {
  666. var session = GetSessionForRemoteControl(sessionId);
  667. if (command.Command == PlaystateCommand.Seek && !session.CanSeek)
  668. {
  669. throw new ArgumentException(string.Format("Session {0} is unable to seek.", session.Id));
  670. }
  671. var controllingSession = GetSession(controllingSessionId);
  672. AssertCanControl(session, controllingSession);
  673. if (controllingSession.UserId.HasValue)
  674. {
  675. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  676. }
  677. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  678. }
  679. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  680. {
  681. if (session == null)
  682. {
  683. throw new ArgumentNullException("session");
  684. }
  685. if (controllingSession == null)
  686. {
  687. throw new ArgumentNullException("controllingSession");
  688. }
  689. }
  690. /// <summary>
  691. /// Sends the restart required message.
  692. /// </summary>
  693. /// <param name="cancellationToken">The cancellation token.</param>
  694. /// <returns>Task.</returns>
  695. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  696. {
  697. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  698. var tasks = sessions.Select(session => Task.Run(async () =>
  699. {
  700. try
  701. {
  702. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  703. }
  704. catch (Exception ex)
  705. {
  706. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  707. }
  708. }, cancellationToken));
  709. return Task.WhenAll(tasks);
  710. }
  711. /// <summary>
  712. /// Sends the server shutdown notification.
  713. /// </summary>
  714. /// <param name="cancellationToken">The cancellation token.</param>
  715. /// <returns>Task.</returns>
  716. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  717. {
  718. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  719. var tasks = sessions.Select(session => Task.Run(async () =>
  720. {
  721. try
  722. {
  723. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  724. }
  725. catch (Exception ex)
  726. {
  727. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  728. }
  729. }, cancellationToken));
  730. return Task.WhenAll(tasks);
  731. }
  732. /// <summary>
  733. /// Sends the server restart notification.
  734. /// </summary>
  735. /// <param name="cancellationToken">The cancellation token.</param>
  736. /// <returns>Task.</returns>
  737. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  738. {
  739. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  740. var tasks = sessions.Select(session => Task.Run(async () =>
  741. {
  742. try
  743. {
  744. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  745. }
  746. catch (Exception ex)
  747. {
  748. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  749. }
  750. }, cancellationToken));
  751. return Task.WhenAll(tasks);
  752. }
  753. /// <summary>
  754. /// Adds the additional user.
  755. /// </summary>
  756. /// <param name="sessionId">The session identifier.</param>
  757. /// <param name="userId">The user identifier.</param>
  758. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  759. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  760. public void AddAdditionalUser(Guid sessionId, Guid userId)
  761. {
  762. var session = GetSession(sessionId);
  763. if (!session.UserId.HasValue)
  764. {
  765. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  766. }
  767. if (session.UserId.Value == userId)
  768. {
  769. throw new ArgumentException("The requested user is already the primary user of the session.");
  770. }
  771. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  772. {
  773. var user = _userManager.GetUserById(userId);
  774. session.AdditionalUsers.Add(new SessionUserInfo
  775. {
  776. UserId = userId.ToString("N"),
  777. UserName = user.Name
  778. });
  779. }
  780. }
  781. /// <summary>
  782. /// Removes the additional user.
  783. /// </summary>
  784. /// <param name="sessionId">The session identifier.</param>
  785. /// <param name="userId">The user identifier.</param>
  786. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  787. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  788. public void RemoveAdditionalUser(Guid sessionId, Guid userId)
  789. {
  790. var session = GetSession(sessionId);
  791. if (!session.UserId.HasValue)
  792. {
  793. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  794. }
  795. if (session.UserId.Value == userId)
  796. {
  797. throw new ArgumentException("The requested user is already the primary user of the session.");
  798. }
  799. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  800. if (user != null)
  801. {
  802. session.AdditionalUsers.Remove(user);
  803. }
  804. }
  805. /// <summary>
  806. /// Authenticates the new session.
  807. /// </summary>
  808. /// <param name="user">The user.</param>
  809. /// <param name="password">The password.</param>
  810. /// <param name="clientType">Type of the client.</param>
  811. /// <param name="appVersion">The application version.</param>
  812. /// <param name="deviceId">The device identifier.</param>
  813. /// <param name="deviceName">Name of the device.</param>
  814. /// <param name="remoteEndPoint">The remote end point.</param>
  815. /// <returns>Task{SessionInfo}.</returns>
  816. /// <exception cref="UnauthorizedAccessException"></exception>
  817. public async Task<SessionInfo> AuthenticateNewSession(User user, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  818. {
  819. var result = await _userManager.AuthenticateUser(user, password).ConfigureAwait(false);
  820. if (!result)
  821. {
  822. throw new UnauthorizedAccessException("Invalid user or password entered.");
  823. }
  824. return await LogSessionActivity(clientType, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
  825. }
  826. /// <summary>
  827. /// Reports the capabilities.
  828. /// </summary>
  829. /// <param name="sessionId">The session identifier.</param>
  830. /// <param name="capabilities">The capabilities.</param>
  831. public void ReportCapabilities(Guid sessionId, SessionCapabilities capabilities)
  832. {
  833. var session = GetSession(sessionId);
  834. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  835. session.SupportedCommands = capabilities.SupportedCommands;
  836. }
  837. }
  838. }