2
0

SessionManager.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Drawing;
  5. using MediaBrowser.Controller.Dto;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Audio;
  8. using MediaBrowser.Controller.Entities.TV;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.LiveTv;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Session;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.Library;
  15. using MediaBrowser.Model.Logging;
  16. using MediaBrowser.Model.Session;
  17. using System;
  18. using System.Collections.Concurrent;
  19. using System.Collections.Generic;
  20. using System.Linq;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. namespace MediaBrowser.Server.Implementations.Session
  24. {
  25. /// <summary>
  26. /// Class SessionManager
  27. /// </summary>
  28. public class SessionManager : ISessionManager
  29. {
  30. /// <summary>
  31. /// The _user data repository
  32. /// </summary>
  33. private readonly IUserDataManager _userDataRepository;
  34. /// <summary>
  35. /// The _user repository
  36. /// </summary>
  37. private readonly IUserRepository _userRepository;
  38. /// <summary>
  39. /// The _logger
  40. /// </summary>
  41. private readonly ILogger _logger;
  42. private readonly ILibraryManager _libraryManager;
  43. private readonly IUserManager _userManager;
  44. private readonly IMusicManager _musicManager;
  45. private readonly IDtoService _dtoService;
  46. private readonly IImageProcessor _imageProcessor;
  47. /// <summary>
  48. /// Gets or sets the configuration manager.
  49. /// </summary>
  50. /// <value>The configuration manager.</value>
  51. private readonly IServerConfigurationManager _configurationManager;
  52. /// <summary>
  53. /// The _active connections
  54. /// </summary>
  55. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  56. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  57. /// <summary>
  58. /// Occurs when [playback start].
  59. /// </summary>
  60. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  61. /// <summary>
  62. /// Occurs when [playback progress].
  63. /// </summary>
  64. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  65. /// <summary>
  66. /// Occurs when [playback stopped].
  67. /// </summary>
  68. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  69. public event EventHandler<SessionEventArgs> SessionStarted;
  70. public event EventHandler<SessionEventArgs> SessionEnded;
  71. private IEnumerable<ISessionControllerFactory> _sessionFactories = new List<ISessionControllerFactory>();
  72. private readonly SemaphoreSlim _sessionLock = new SemaphoreSlim(1, 1);
  73. /// <summary>
  74. /// Initializes a new instance of the <see cref="SessionManager" /> class.
  75. /// </summary>
  76. /// <param name="userDataRepository">The user data repository.</param>
  77. /// <param name="configurationManager">The configuration manager.</param>
  78. /// <param name="logger">The logger.</param>
  79. /// <param name="userRepository">The user repository.</param>
  80. /// <param name="libraryManager">The library manager.</param>
  81. public SessionManager(IUserDataManager userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository, ILibraryManager libraryManager, IUserManager userManager, IMusicManager musicManager, IDtoService dtoService, IImageProcessor imageProcessor)
  82. {
  83. _userDataRepository = userDataRepository;
  84. _configurationManager = configurationManager;
  85. _logger = logger;
  86. _userRepository = userRepository;
  87. _libraryManager = libraryManager;
  88. _userManager = userManager;
  89. _musicManager = musicManager;
  90. _dtoService = dtoService;
  91. _imageProcessor = imageProcessor;
  92. }
  93. /// <summary>
  94. /// Adds the parts.
  95. /// </summary>
  96. /// <param name="sessionFactories">The session factories.</param>
  97. public void AddParts(IEnumerable<ISessionControllerFactory> sessionFactories)
  98. {
  99. _sessionFactories = sessionFactories.ToList();
  100. }
  101. /// <summary>
  102. /// Gets all connections.
  103. /// </summary>
  104. /// <value>All connections.</value>
  105. public IEnumerable<SessionInfo> Sessions
  106. {
  107. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList(); }
  108. }
  109. private void OnSessionStarted(SessionInfo info)
  110. {
  111. EventHelper.QueueEventIfNotNull(SessionStarted, this, new SessionEventArgs
  112. {
  113. SessionInfo = info
  114. }, _logger);
  115. }
  116. private async void OnSessionEnded(SessionInfo info)
  117. {
  118. try
  119. {
  120. await SendSessionEndedNotification(info, CancellationToken.None).ConfigureAwait(false);
  121. }
  122. catch (Exception ex)
  123. {
  124. _logger.ErrorException("Error in SendSessionEndedNotification", ex);
  125. }
  126. EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
  127. {
  128. SessionInfo = info
  129. }, _logger);
  130. var disposable = info.SessionController as IDisposable;
  131. if (disposable != null)
  132. {
  133. try
  134. {
  135. disposable.Dispose();
  136. }
  137. catch (Exception ex)
  138. {
  139. _logger.ErrorException("Error disposing session controller", ex);
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// Logs the user activity.
  145. /// </summary>
  146. /// <param name="clientType">Type of the client.</param>
  147. /// <param name="appVersion">The app version.</param>
  148. /// <param name="deviceId">The device id.</param>
  149. /// <param name="deviceName">Name of the device.</param>
  150. /// <param name="remoteEndPoint">The remote end point.</param>
  151. /// <param name="user">The user.</param>
  152. /// <returns>Task.</returns>
  153. /// <exception cref="System.ArgumentNullException">user</exception>
  154. /// <exception cref="System.UnauthorizedAccessException"></exception>
  155. public async Task<SessionInfo> LogSessionActivity(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
  156. {
  157. if (string.IsNullOrEmpty(clientType))
  158. {
  159. throw new ArgumentNullException("clientType");
  160. }
  161. if (string.IsNullOrEmpty(appVersion))
  162. {
  163. throw new ArgumentNullException("appVersion");
  164. }
  165. if (string.IsNullOrEmpty(deviceId))
  166. {
  167. throw new ArgumentNullException("deviceId");
  168. }
  169. if (string.IsNullOrEmpty(deviceName))
  170. {
  171. throw new ArgumentNullException("deviceName");
  172. }
  173. if (user != null && user.Configuration.IsDisabled)
  174. {
  175. throw new UnauthorizedAccessException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  176. }
  177. var activityDate = DateTime.UtcNow;
  178. var userId = user == null ? (Guid?)null : user.Id;
  179. var username = user == null ? null : user.Name;
  180. var session = await GetSessionInfo(clientType, appVersion, deviceId, deviceName, remoteEndPoint, userId, username).ConfigureAwait(false);
  181. session.LastActivityDate = activityDate;
  182. if (user == null)
  183. {
  184. return session;
  185. }
  186. var lastActivityDate = user.LastActivityDate;
  187. user.LastActivityDate = activityDate;
  188. // Don't log in the db anymore frequently than 10 seconds
  189. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  190. {
  191. return session;
  192. }
  193. // Save this directly. No need to fire off all the events for this.
  194. await _userRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  195. return session;
  196. }
  197. public async Task ReportSessionEnded(string sessionId)
  198. {
  199. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  200. try
  201. {
  202. var session = GetSession(sessionId);
  203. if (session == null)
  204. {
  205. throw new ArgumentException("Session not found");
  206. }
  207. var key = GetSessionKey(session.Client, session.ApplicationVersion, session.DeviceId);
  208. SessionInfo removed;
  209. if (_activeConnections.TryRemove(key, out removed))
  210. {
  211. OnSessionEnded(removed);
  212. }
  213. }
  214. finally
  215. {
  216. _sessionLock.Release();
  217. }
  218. }
  219. /// <summary>
  220. /// Updates the now playing item id.
  221. /// </summary>
  222. /// <param name="session">The session.</param>
  223. /// <param name="info">The information.</param>
  224. /// <param name="libraryItem">The library item.</param>
  225. private void UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem)
  226. {
  227. var runtimeTicks = libraryItem.RunTimeTicks;
  228. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  229. {
  230. info.MediaSourceId = info.ItemId;
  231. }
  232. if (!string.Equals(info.ItemId, info.MediaSourceId) &&
  233. !string.IsNullOrWhiteSpace(info.MediaSourceId))
  234. {
  235. runtimeTicks = _libraryManager.GetItemById(new Guid(info.MediaSourceId)).RunTimeTicks;
  236. }
  237. if (!string.IsNullOrWhiteSpace(info.ItemId))
  238. {
  239. info.Item = GetItemInfo(libraryItem, runtimeTicks);
  240. }
  241. session.NowPlayingItem = info.Item;
  242. session.LastActivityDate = DateTime.UtcNow;
  243. session.PlayState.IsPaused = info.IsPaused;
  244. session.PlayState.PositionTicks = info.PositionTicks;
  245. session.PlayState.MediaSourceId = info.MediaSourceId;
  246. session.PlayState.CanSeek = info.CanSeek;
  247. session.PlayState.IsMuted = info.IsMuted;
  248. session.PlayState.VolumeLevel = info.VolumeLevel;
  249. session.PlayState.AudioStreamIndex = info.AudioStreamIndex;
  250. session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex;
  251. session.PlayState.PlayMethod = info.PlayMethod;
  252. }
  253. /// <summary>
  254. /// Removes the now playing item id.
  255. /// </summary>
  256. /// <param name="session">The session.</param>
  257. /// <exception cref="System.ArgumentNullException">item</exception>
  258. private void RemoveNowPlayingItem(SessionInfo session)
  259. {
  260. session.NowPlayingItem = null;
  261. session.PlayState = new PlayerStateInfo();
  262. }
  263. private string GetSessionKey(string clientType, string appVersion, string deviceId)
  264. {
  265. return clientType + deviceId + appVersion;
  266. }
  267. /// <summary>
  268. /// Gets the connection.
  269. /// </summary>
  270. /// <param name="clientType">Type of the client.</param>
  271. /// <param name="appVersion">The app version.</param>
  272. /// <param name="deviceId">The device id.</param>
  273. /// <param name="deviceName">Name of the device.</param>
  274. /// <param name="remoteEndPoint">The remote end point.</param>
  275. /// <param name="userId">The user identifier.</param>
  276. /// <param name="username">The username.</param>
  277. /// <returns>SessionInfo.</returns>
  278. private async Task<SessionInfo> GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username)
  279. {
  280. var key = GetSessionKey(clientType, appVersion, deviceId);
  281. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  282. try
  283. {
  284. var connection = _activeConnections.GetOrAdd(key, keyName =>
  285. {
  286. var sessionInfo = new SessionInfo
  287. {
  288. Client = clientType,
  289. DeviceId = deviceId,
  290. ApplicationVersion = appVersion,
  291. Id = Guid.NewGuid().ToString("N")
  292. };
  293. OnSessionStarted(sessionInfo);
  294. return sessionInfo;
  295. });
  296. connection.DeviceName = deviceName;
  297. connection.UserId = userId;
  298. connection.UserName = username;
  299. connection.RemoteEndPoint = remoteEndPoint;
  300. if (!userId.HasValue)
  301. {
  302. connection.AdditionalUsers.Clear();
  303. }
  304. if (connection.SessionController == null)
  305. {
  306. connection.SessionController = _sessionFactories
  307. .Select(i => i.GetSessionController(connection))
  308. .FirstOrDefault(i => i != null);
  309. }
  310. return connection;
  311. }
  312. finally
  313. {
  314. _sessionLock.Release();
  315. }
  316. }
  317. private List<User> GetUsers(SessionInfo session)
  318. {
  319. var users = new List<User>();
  320. if (session.UserId.HasValue)
  321. {
  322. var user = _userManager.GetUserById(session.UserId.Value);
  323. if (user == null)
  324. {
  325. throw new InvalidOperationException("User not found");
  326. }
  327. users.Add(user);
  328. var additionalUsers = session.AdditionalUsers
  329. .Select(i => _userManager.GetUserById(new Guid(i.UserId)))
  330. .Where(i => i != null);
  331. users.AddRange(additionalUsers);
  332. }
  333. return users;
  334. }
  335. /// <summary>
  336. /// Used to report that playback has started for an item
  337. /// </summary>
  338. /// <param name="info">The info.</param>
  339. /// <returns>Task.</returns>
  340. /// <exception cref="System.ArgumentNullException">info</exception>
  341. public async Task OnPlaybackStart(PlaybackStartInfo info)
  342. {
  343. if (info == null)
  344. {
  345. throw new ArgumentNullException("info");
  346. }
  347. var session = GetSession(info.SessionId);
  348. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  349. ? null
  350. : _libraryManager.GetItemById(new Guid(info.ItemId));
  351. UpdateNowPlayingItem(session, info, libraryItem);
  352. session.QueueableMediaTypes = info.QueueableMediaTypes;
  353. var users = GetUsers(session);
  354. if (libraryItem != null)
  355. {
  356. var key = libraryItem.GetUserDataKey();
  357. foreach (var user in users)
  358. {
  359. await OnPlaybackStart(user.Id, key, libraryItem).ConfigureAwait(false);
  360. }
  361. }
  362. // Nothing to save here
  363. // Fire events to inform plugins
  364. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  365. {
  366. Item = libraryItem,
  367. Users = users,
  368. MediaSourceId = info.MediaSourceId,
  369. MediaInfo = info.Item
  370. }, _logger);
  371. await SendPlaybackStartNotification(session, CancellationToken.None).ConfigureAwait(false);
  372. }
  373. /// <summary>
  374. /// Called when [playback start].
  375. /// </summary>
  376. /// <param name="userId">The user identifier.</param>
  377. /// <param name="userDataKey">The user data key.</param>
  378. /// <param name="item">The item.</param>
  379. /// <returns>Task.</returns>
  380. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  381. {
  382. var data = _userDataRepository.GetUserData(userId, userDataKey);
  383. data.PlayCount++;
  384. data.LastPlayedDate = DateTime.UtcNow;
  385. if (!(item is Video))
  386. {
  387. data.Played = true;
  388. }
  389. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  390. }
  391. /// <summary>
  392. /// Used to report playback progress for an item
  393. /// </summary>
  394. /// <param name="info">The info.</param>
  395. /// <returns>Task.</returns>
  396. /// <exception cref="System.ArgumentNullException"></exception>
  397. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  398. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  399. {
  400. if (info == null)
  401. {
  402. throw new ArgumentNullException("info");
  403. }
  404. var session = GetSession(info.SessionId);
  405. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  406. ? null
  407. : _libraryManager.GetItemById(new Guid(info.ItemId));
  408. UpdateNowPlayingItem(session, info, libraryItem);
  409. var users = GetUsers(session);
  410. if (libraryItem != null)
  411. {
  412. var key = libraryItem.GetUserDataKey();
  413. foreach (var user in users)
  414. {
  415. await OnPlaybackProgress(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  416. }
  417. }
  418. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  419. {
  420. Item = libraryItem,
  421. Users = users,
  422. PlaybackPositionTicks = session.PlayState.PositionTicks,
  423. MediaSourceId = session.PlayState.MediaSourceId,
  424. MediaInfo = info.Item
  425. }, _logger);
  426. }
  427. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  428. {
  429. var data = _userDataRepository.GetUserData(userId, userDataKey);
  430. if (positionTicks.HasValue)
  431. {
  432. UpdatePlayState(item, data, positionTicks.Value);
  433. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  434. }
  435. }
  436. /// <summary>
  437. /// Used to report that playback has ended for an item
  438. /// </summary>
  439. /// <param name="info">The info.</param>
  440. /// <returns>Task.</returns>
  441. /// <exception cref="System.ArgumentNullException">info</exception>
  442. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  443. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  444. {
  445. if (info == null)
  446. {
  447. throw new ArgumentNullException("info");
  448. }
  449. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  450. {
  451. throw new ArgumentOutOfRangeException("positionTicks");
  452. }
  453. var session = GetSession(info.SessionId);
  454. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  455. ? null
  456. : _libraryManager.GetItemById(new Guid(info.ItemId));
  457. // Normalize
  458. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  459. {
  460. info.MediaSourceId = info.ItemId;
  461. }
  462. RemoveNowPlayingItem(session);
  463. var users = GetUsers(session);
  464. var playedToCompletion = false;
  465. if (libraryItem != null)
  466. {
  467. var key = libraryItem.GetUserDataKey();
  468. foreach (var user in users)
  469. {
  470. playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  471. }
  472. }
  473. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  474. {
  475. Item = libraryItem,
  476. Users = users,
  477. PlaybackPositionTicks = info.PositionTicks,
  478. PlayedToCompletion = playedToCompletion,
  479. MediaSourceId = info.MediaSourceId,
  480. MediaInfo = info.Item
  481. }, _logger);
  482. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  483. }
  484. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  485. {
  486. var data = _userDataRepository.GetUserData(userId, userDataKey);
  487. bool playedToCompletion;
  488. if (positionTicks.HasValue)
  489. {
  490. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  491. }
  492. else
  493. {
  494. // If the client isn't able to report this, then we'll just have to make an assumption
  495. data.PlayCount++;
  496. data.Played = true;
  497. data.PlaybackPositionTicks = 0;
  498. playedToCompletion = true;
  499. }
  500. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  501. return playedToCompletion;
  502. }
  503. /// <summary>
  504. /// Updates playstate position for an item but does not save
  505. /// </summary>
  506. /// <param name="item">The item</param>
  507. /// <param name="data">User data for the item</param>
  508. /// <param name="positionTicks">The current playback position</param>
  509. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  510. {
  511. var playedToCompletion = false;
  512. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  513. // If a position has been reported, and if we know the duration
  514. if (positionTicks > 0 && hasRuntime)
  515. {
  516. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  517. // Don't track in very beginning
  518. if (pctIn < _configurationManager.Configuration.MinResumePct)
  519. {
  520. positionTicks = 0;
  521. }
  522. // If we're at the end, assume completed
  523. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  524. {
  525. positionTicks = 0;
  526. data.Played = playedToCompletion = true;
  527. }
  528. else
  529. {
  530. // Enforce MinResumeDuration
  531. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  532. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  533. {
  534. positionTicks = 0;
  535. data.Played = playedToCompletion = true;
  536. }
  537. }
  538. }
  539. else if (!hasRuntime)
  540. {
  541. // If we don't know the runtime we'll just have to assume it was fully played
  542. data.Played = playedToCompletion = true;
  543. positionTicks = 0;
  544. }
  545. if (item is Audio)
  546. {
  547. positionTicks = 0;
  548. }
  549. data.PlaybackPositionTicks = positionTicks;
  550. return playedToCompletion;
  551. }
  552. /// <summary>
  553. /// Gets the session.
  554. /// </summary>
  555. /// <param name="sessionId">The session identifier.</param>
  556. /// <returns>SessionInfo.</returns>
  557. /// <exception cref="ResourceNotFoundException"></exception>
  558. private SessionInfo GetSession(string sessionId)
  559. {
  560. var session = Sessions.First(i => string.Equals(i.Id, sessionId));
  561. if (session == null)
  562. {
  563. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  564. }
  565. return session;
  566. }
  567. /// <summary>
  568. /// Gets the session for remote control.
  569. /// </summary>
  570. /// <param name="sessionId">The session id.</param>
  571. /// <returns>SessionInfo.</returns>
  572. /// <exception cref="ResourceNotFoundException"></exception>
  573. private SessionInfo GetSessionForRemoteControl(string sessionId)
  574. {
  575. var session = GetSession(sessionId);
  576. if (!session.SupportsRemoteControl)
  577. {
  578. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  579. }
  580. return session;
  581. }
  582. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  583. {
  584. var session = GetSessionForRemoteControl(sessionId);
  585. var controllingSession = GetSession(controllingSessionId);
  586. AssertCanControl(session, controllingSession);
  587. return session.SessionController.SendMessageCommand(command, cancellationToken);
  588. }
  589. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  590. {
  591. var session = GetSessionForRemoteControl(sessionId);
  592. var controllingSession = GetSession(controllingSessionId);
  593. AssertCanControl(session, controllingSession);
  594. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  595. }
  596. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  597. {
  598. var session = GetSessionForRemoteControl(sessionId);
  599. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  600. List<BaseItem> items;
  601. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  602. {
  603. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  604. .Where(i => i.LocationType != LocationType.Virtual)
  605. .ToList();
  606. command.PlayCommand = PlayCommand.PlayNow;
  607. }
  608. else
  609. {
  610. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  611. .Where(i => i.LocationType != LocationType.Virtual)
  612. .ToList();
  613. }
  614. if (command.PlayCommand == PlayCommand.PlayShuffle)
  615. {
  616. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  617. command.PlayCommand = PlayCommand.PlayNow;
  618. }
  619. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  620. if (user != null)
  621. {
  622. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  623. {
  624. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  625. }
  626. }
  627. if (command.PlayCommand != PlayCommand.PlayNow)
  628. {
  629. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  630. {
  631. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  632. }
  633. }
  634. else
  635. {
  636. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  637. {
  638. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  639. }
  640. }
  641. var controllingSession = GetSession(controllingSessionId);
  642. AssertCanControl(session, controllingSession);
  643. if (controllingSession.UserId.HasValue)
  644. {
  645. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  646. }
  647. return session.SessionController.SendPlayCommand(command, cancellationToken);
  648. }
  649. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  650. {
  651. var item = _libraryManager.GetItemById(new Guid(id));
  652. if (item.IsFolder)
  653. {
  654. var folder = (Folder)item;
  655. var items = user == null ? folder.RecursiveChildren :
  656. folder.GetRecursiveChildren(user);
  657. items = items.Where(i => !i.IsFolder);
  658. items = items.OrderBy(i => i.SortName);
  659. return items;
  660. }
  661. return new[] { item };
  662. }
  663. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  664. {
  665. var item = _libraryManager.GetItemById(new Guid(id));
  666. var audio = item as Audio;
  667. if (audio != null)
  668. {
  669. return _musicManager.GetInstantMixFromSong(audio, user);
  670. }
  671. var artist = item as MusicArtist;
  672. if (artist != null)
  673. {
  674. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  675. }
  676. var album = item as MusicAlbum;
  677. if (album != null)
  678. {
  679. return _musicManager.GetInstantMixFromAlbum(album, user);
  680. }
  681. var genre = item as MusicGenre;
  682. if (genre != null)
  683. {
  684. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  685. }
  686. return new BaseItem[] { };
  687. }
  688. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  689. {
  690. var generalCommand = new GeneralCommand
  691. {
  692. Name = GeneralCommandType.DisplayContent.ToString()
  693. };
  694. generalCommand.Arguments["Context"] = command.Context;
  695. generalCommand.Arguments["ItemId"] = command.ItemId;
  696. generalCommand.Arguments["ItemName"] = command.ItemName;
  697. generalCommand.Arguments["ItemType"] = command.ItemType;
  698. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  699. }
  700. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  701. {
  702. var session = GetSessionForRemoteControl(sessionId);
  703. var controllingSession = GetSession(controllingSessionId);
  704. AssertCanControl(session, controllingSession);
  705. if (controllingSession.UserId.HasValue)
  706. {
  707. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  708. }
  709. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  710. }
  711. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  712. {
  713. if (session == null)
  714. {
  715. throw new ArgumentNullException("session");
  716. }
  717. if (controllingSession == null)
  718. {
  719. throw new ArgumentNullException("controllingSession");
  720. }
  721. }
  722. /// <summary>
  723. /// Sends the restart required message.
  724. /// </summary>
  725. /// <param name="cancellationToken">The cancellation token.</param>
  726. /// <returns>Task.</returns>
  727. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  728. {
  729. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  730. var tasks = sessions.Select(session => Task.Run(async () =>
  731. {
  732. try
  733. {
  734. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  735. }
  736. catch (Exception ex)
  737. {
  738. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  739. }
  740. }, cancellationToken));
  741. return Task.WhenAll(tasks);
  742. }
  743. /// <summary>
  744. /// Sends the server shutdown notification.
  745. /// </summary>
  746. /// <param name="cancellationToken">The cancellation token.</param>
  747. /// <returns>Task.</returns>
  748. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  749. {
  750. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  751. var tasks = sessions.Select(session => Task.Run(async () =>
  752. {
  753. try
  754. {
  755. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  756. }
  757. catch (Exception ex)
  758. {
  759. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  760. }
  761. }, cancellationToken));
  762. return Task.WhenAll(tasks);
  763. }
  764. /// <summary>
  765. /// Sends the server restart notification.
  766. /// </summary>
  767. /// <param name="cancellationToken">The cancellation token.</param>
  768. /// <returns>Task.</returns>
  769. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  770. {
  771. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  772. var tasks = sessions.Select(session => Task.Run(async () =>
  773. {
  774. try
  775. {
  776. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  777. }
  778. catch (Exception ex)
  779. {
  780. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  781. }
  782. }, cancellationToken));
  783. return Task.WhenAll(tasks);
  784. }
  785. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  786. {
  787. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  788. var dto = GetSessionInfoDto(sessionInfo);
  789. var tasks = sessions.Select(session => Task.Run(async () =>
  790. {
  791. try
  792. {
  793. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  794. }
  795. catch (Exception ex)
  796. {
  797. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  798. }
  799. }, cancellationToken));
  800. return Task.WhenAll(tasks);
  801. }
  802. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  803. {
  804. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  805. var dto = GetSessionInfoDto(sessionInfo);
  806. var tasks = sessions.Select(session => Task.Run(async () =>
  807. {
  808. try
  809. {
  810. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  811. }
  812. catch (Exception ex)
  813. {
  814. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  815. }
  816. }, cancellationToken));
  817. return Task.WhenAll(tasks);
  818. }
  819. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  820. {
  821. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  822. var dto = GetSessionInfoDto(sessionInfo);
  823. var tasks = sessions.Select(session => Task.Run(async () =>
  824. {
  825. try
  826. {
  827. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  828. }
  829. catch (Exception ex)
  830. {
  831. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  832. }
  833. }, cancellationToken));
  834. return Task.WhenAll(tasks);
  835. }
  836. /// <summary>
  837. /// Adds the additional user.
  838. /// </summary>
  839. /// <param name="sessionId">The session identifier.</param>
  840. /// <param name="userId">The user identifier.</param>
  841. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  842. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  843. public void AddAdditionalUser(string sessionId, Guid userId)
  844. {
  845. var session = GetSession(sessionId);
  846. if (!session.UserId.HasValue)
  847. {
  848. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  849. }
  850. if (session.UserId.Value == userId)
  851. {
  852. throw new ArgumentException("The requested user is already the primary user of the session.");
  853. }
  854. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  855. {
  856. var user = _userManager.GetUserById(userId);
  857. session.AdditionalUsers.Add(new SessionUserInfo
  858. {
  859. UserId = userId.ToString("N"),
  860. UserName = user.Name
  861. });
  862. }
  863. }
  864. /// <summary>
  865. /// Removes the additional user.
  866. /// </summary>
  867. /// <param name="sessionId">The session identifier.</param>
  868. /// <param name="userId">The user identifier.</param>
  869. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  870. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  871. public void RemoveAdditionalUser(string sessionId, Guid userId)
  872. {
  873. var session = GetSession(sessionId);
  874. if (!session.UserId.HasValue)
  875. {
  876. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  877. }
  878. if (session.UserId.Value == userId)
  879. {
  880. throw new ArgumentException("The requested user is already the primary user of the session.");
  881. }
  882. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  883. if (user != null)
  884. {
  885. session.AdditionalUsers.Remove(user);
  886. }
  887. }
  888. /// <summary>
  889. /// Authenticates the new session.
  890. /// </summary>
  891. /// <param name="user">The user.</param>
  892. /// <param name="password">The password.</param>
  893. /// <param name="clientType">Type of the client.</param>
  894. /// <param name="appVersion">The application version.</param>
  895. /// <param name="deviceId">The device identifier.</param>
  896. /// <param name="deviceName">Name of the device.</param>
  897. /// <param name="remoteEndPoint">The remote end point.</param>
  898. /// <returns>Task{SessionInfo}.</returns>
  899. /// <exception cref="UnauthorizedAccessException"></exception>
  900. public async Task<SessionInfo> AuthenticateNewSession(User user, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  901. {
  902. var result = await _userManager.AuthenticateUser(user, password).ConfigureAwait(false);
  903. if (!result)
  904. {
  905. throw new UnauthorizedAccessException("Invalid user or password entered.");
  906. }
  907. return await LogSessionActivity(clientType, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
  908. }
  909. /// <summary>
  910. /// Reports the capabilities.
  911. /// </summary>
  912. /// <param name="sessionId">The session identifier.</param>
  913. /// <param name="capabilities">The capabilities.</param>
  914. public void ReportCapabilities(string sessionId, SessionCapabilities capabilities)
  915. {
  916. var session = GetSession(sessionId);
  917. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  918. session.SupportedCommands = capabilities.SupportedCommands;
  919. }
  920. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  921. {
  922. var dto = new SessionInfoDto
  923. {
  924. Client = session.Client,
  925. DeviceId = session.DeviceId,
  926. DeviceName = session.DeviceName,
  927. Id = session.Id,
  928. LastActivityDate = session.LastActivityDate,
  929. NowPlayingPositionTicks = session.PlayState.PositionTicks,
  930. SupportsRemoteControl = session.SupportsRemoteControl,
  931. IsPaused = session.PlayState.IsPaused,
  932. IsMuted = session.PlayState.IsMuted,
  933. NowViewingContext = session.NowViewingContext,
  934. NowViewingItem = session.NowViewingItem,
  935. ApplicationVersion = session.ApplicationVersion,
  936. CanSeek = session.PlayState.CanSeek,
  937. QueueableMediaTypes = session.QueueableMediaTypes,
  938. PlayableMediaTypes = session.PlayableMediaTypes,
  939. RemoteEndPoint = session.RemoteEndPoint,
  940. AdditionalUsers = session.AdditionalUsers,
  941. SupportedCommands = session.SupportedCommands,
  942. UserName = session.UserName,
  943. NowPlayingItem = session.NowPlayingItem,
  944. PlayState = session.PlayState
  945. };
  946. if (session.UserId.HasValue)
  947. {
  948. dto.UserId = session.UserId.Value.ToString("N");
  949. var user = _userManager.GetUserById(session.UserId.Value);
  950. if (user != null)
  951. {
  952. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  953. }
  954. }
  955. return dto;
  956. }
  957. /// <summary>
  958. /// Converts a BaseItem to a BaseItemInfo
  959. /// </summary>
  960. /// <param name="item">The item.</param>
  961. /// <param name="runtimeTicks">The now playing runtime ticks.</param>
  962. /// <returns>BaseItemInfo.</returns>
  963. /// <exception cref="System.ArgumentNullException">item</exception>
  964. private BaseItemInfo GetItemInfo(BaseItem item, long? runtimeTicks)
  965. {
  966. if (item == null)
  967. {
  968. throw new ArgumentNullException("item");
  969. }
  970. var info = new BaseItemInfo
  971. {
  972. Id = GetDtoId(item),
  973. Name = item.Name,
  974. MediaType = item.MediaType,
  975. Type = item.GetClientTypeName(),
  976. RunTimeTicks = runtimeTicks,
  977. IndexNumber = item.IndexNumber,
  978. ParentIndexNumber = item.ParentIndexNumber,
  979. PremiereDate = item.PremiereDate,
  980. ProductionYear = item.ProductionYear
  981. };
  982. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  983. if (info.PrimaryImageTag.HasValue)
  984. {
  985. info.PrimaryImageItemId = GetDtoId(item);
  986. }
  987. var episode = item as Episode;
  988. if (episode != null)
  989. {
  990. info.IndexNumberEnd = episode.IndexNumberEnd;
  991. }
  992. var hasSeries = item as IHasSeries;
  993. if (hasSeries != null)
  994. {
  995. info.SeriesName = hasSeries.SeriesName;
  996. }
  997. var recording = item as ILiveTvRecording;
  998. if (recording != null && recording.RecordingInfo != null)
  999. {
  1000. if (recording.RecordingInfo.IsSeries)
  1001. {
  1002. info.Name = recording.RecordingInfo.EpisodeTitle;
  1003. info.SeriesName = recording.RecordingInfo.Name;
  1004. if (string.IsNullOrWhiteSpace(info.Name))
  1005. {
  1006. info.Name = recording.RecordingInfo.Name;
  1007. }
  1008. }
  1009. }
  1010. var audio = item as Audio;
  1011. if (audio != null)
  1012. {
  1013. info.Album = audio.Album;
  1014. info.Artists = audio.Artists;
  1015. if (!info.PrimaryImageTag.HasValue)
  1016. {
  1017. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1018. if (album != null && album.HasImage(ImageType.Primary))
  1019. {
  1020. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1021. if (info.PrimaryImageTag.HasValue)
  1022. {
  1023. info.PrimaryImageItemId = GetDtoId(album);
  1024. }
  1025. }
  1026. }
  1027. }
  1028. var musicVideo = item as MusicVideo;
  1029. if (musicVideo != null)
  1030. {
  1031. info.Album = musicVideo.Album;
  1032. if (!string.IsNullOrWhiteSpace(musicVideo.Artist))
  1033. {
  1034. info.Artists.Add(musicVideo.Artist);
  1035. }
  1036. }
  1037. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1038. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1039. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1040. if (thumbItem == null)
  1041. {
  1042. if (episode != null)
  1043. {
  1044. var series = episode.Series;
  1045. if (series != null && series.HasImage(ImageType.Thumb))
  1046. {
  1047. thumbItem = series;
  1048. }
  1049. }
  1050. }
  1051. if (backropItem == null)
  1052. {
  1053. if (episode != null)
  1054. {
  1055. var series = episode.Series;
  1056. if (series != null && series.HasImage(ImageType.Backdrop))
  1057. {
  1058. backropItem = series;
  1059. }
  1060. }
  1061. }
  1062. if (backropItem == null)
  1063. {
  1064. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1065. }
  1066. if (thumbItem == null)
  1067. {
  1068. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1069. }
  1070. if (logoItem == null)
  1071. {
  1072. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1073. }
  1074. if (thumbItem != null)
  1075. {
  1076. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1077. info.ThumbItemId = GetDtoId(thumbItem);
  1078. }
  1079. if (backropItem != null)
  1080. {
  1081. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1082. info.BackdropItemId = GetDtoId(backropItem);
  1083. }
  1084. if (logoItem != null)
  1085. {
  1086. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1087. info.LogoItemId = GetDtoId(logoItem);
  1088. }
  1089. return info;
  1090. }
  1091. private Guid? GetImageCacheTag(BaseItem item, ImageType type)
  1092. {
  1093. try
  1094. {
  1095. return _imageProcessor.GetImageCacheTag(item, type);
  1096. }
  1097. catch (Exception ex)
  1098. {
  1099. _logger.ErrorException("Error getting {0} image info", ex, type);
  1100. return null;
  1101. }
  1102. }
  1103. private string GetDtoId(BaseItem item)
  1104. {
  1105. return _dtoService.GetDtoId(item);
  1106. }
  1107. public void ReportNowViewingItem(string sessionId, string itemId, string context)
  1108. {
  1109. var item = _libraryManager.GetItemById(new Guid(itemId));
  1110. var info = GetItemInfo(item, item.RunTimeTicks);
  1111. ReportNowViewingItem(sessionId, info, context);
  1112. }
  1113. public void ReportNowViewingItem(string sessionId, BaseItemInfo item, string context)
  1114. {
  1115. var session = GetSession(sessionId);
  1116. session.NowViewingItem = item;
  1117. session.NowViewingContext = context;
  1118. }
  1119. }
  1120. }