SessionManager.cs 38 KB

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