SessionManager.cs 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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.PlayState.IsPaused = info.IsPaused;
  242. session.PlayState.PositionTicks = info.PositionTicks;
  243. session.NowPlayingItem = info.Item;
  244. session.LastActivityDate = DateTime.UtcNow;
  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. }, _logger);
  370. await SendPlaybackStartNotification(session, CancellationToken.None).ConfigureAwait(false);
  371. }
  372. /// <summary>
  373. /// Called when [playback start].
  374. /// </summary>
  375. /// <param name="userId">The user identifier.</param>
  376. /// <param name="userDataKey">The user data key.</param>
  377. /// <param name="item">The item.</param>
  378. /// <returns>Task.</returns>
  379. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  380. {
  381. var data = _userDataRepository.GetUserData(userId, userDataKey);
  382. data.PlayCount++;
  383. data.LastPlayedDate = DateTime.UtcNow;
  384. if (!(item is Video))
  385. {
  386. data.Played = true;
  387. }
  388. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  389. }
  390. /// <summary>
  391. /// Used to report playback progress for an item
  392. /// </summary>
  393. /// <param name="info">The info.</param>
  394. /// <returns>Task.</returns>
  395. /// <exception cref="System.ArgumentNullException"></exception>
  396. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  397. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  398. {
  399. if (info == null)
  400. {
  401. throw new ArgumentNullException("info");
  402. }
  403. var session = GetSession(info.SessionId);
  404. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  405. ? null
  406. : _libraryManager.GetItemById(new Guid(info.ItemId));
  407. UpdateNowPlayingItem(session, info, libraryItem);
  408. var users = GetUsers(session);
  409. if (libraryItem != null)
  410. {
  411. var key = libraryItem.GetUserDataKey();
  412. foreach (var user in users)
  413. {
  414. await OnPlaybackProgress(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  415. }
  416. }
  417. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  418. {
  419. Item = libraryItem,
  420. Users = users,
  421. PlaybackPositionTicks = session.PlayState.PositionTicks,
  422. MediaSourceId = session.PlayState.MediaSourceId
  423. }, _logger);
  424. }
  425. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  426. {
  427. var data = _userDataRepository.GetUserData(userId, userDataKey);
  428. if (positionTicks.HasValue)
  429. {
  430. UpdatePlayState(item, data, positionTicks.Value);
  431. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  432. }
  433. }
  434. /// <summary>
  435. /// Used to report that playback has ended for an item
  436. /// </summary>
  437. /// <param name="info">The info.</param>
  438. /// <returns>Task.</returns>
  439. /// <exception cref="System.ArgumentNullException">info</exception>
  440. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  441. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  442. {
  443. if (info == null)
  444. {
  445. throw new ArgumentNullException("info");
  446. }
  447. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  448. {
  449. throw new ArgumentOutOfRangeException("positionTicks");
  450. }
  451. var session = GetSession(info.SessionId);
  452. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  453. ? null
  454. : _libraryManager.GetItemById(new Guid(info.ItemId));
  455. // Normalize
  456. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  457. {
  458. info.MediaSourceId = info.ItemId;
  459. }
  460. RemoveNowPlayingItem(session);
  461. var users = GetUsers(session);
  462. var playedToCompletion = false;
  463. if (libraryItem != null)
  464. {
  465. var key = libraryItem.GetUserDataKey();
  466. foreach (var user in users)
  467. {
  468. playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  469. }
  470. }
  471. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  472. {
  473. Item = libraryItem,
  474. Users = users,
  475. PlaybackPositionTicks = info.PositionTicks,
  476. PlayedToCompletion = playedToCompletion,
  477. MediaSourceId = info.MediaSourceId
  478. }, _logger);
  479. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  480. }
  481. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  482. {
  483. var data = _userDataRepository.GetUserData(userId, userDataKey);
  484. bool playedToCompletion;
  485. if (positionTicks.HasValue)
  486. {
  487. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  488. }
  489. else
  490. {
  491. // If the client isn't able to report this, then we'll just have to make an assumption
  492. data.PlayCount++;
  493. data.Played = true;
  494. data.PlaybackPositionTicks = 0;
  495. playedToCompletion = true;
  496. }
  497. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  498. return playedToCompletion;
  499. }
  500. /// <summary>
  501. /// Updates playstate position for an item but does not save
  502. /// </summary>
  503. /// <param name="item">The item</param>
  504. /// <param name="data">User data for the item</param>
  505. /// <param name="positionTicks">The current playback position</param>
  506. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  507. {
  508. var playedToCompletion = false;
  509. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  510. // If a position has been reported, and if we know the duration
  511. if (positionTicks > 0 && hasRuntime)
  512. {
  513. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  514. // Don't track in very beginning
  515. if (pctIn < _configurationManager.Configuration.MinResumePct)
  516. {
  517. positionTicks = 0;
  518. }
  519. // If we're at the end, assume completed
  520. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  521. {
  522. positionTicks = 0;
  523. data.Played = playedToCompletion = true;
  524. }
  525. else
  526. {
  527. // Enforce MinResumeDuration
  528. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  529. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  530. {
  531. positionTicks = 0;
  532. data.Played = playedToCompletion = true;
  533. }
  534. }
  535. }
  536. else if (!hasRuntime)
  537. {
  538. // If we don't know the runtime we'll just have to assume it was fully played
  539. data.Played = playedToCompletion = true;
  540. positionTicks = 0;
  541. }
  542. if (item is Audio)
  543. {
  544. positionTicks = 0;
  545. }
  546. data.PlaybackPositionTicks = positionTicks;
  547. return playedToCompletion;
  548. }
  549. /// <summary>
  550. /// Gets the session.
  551. /// </summary>
  552. /// <param name="sessionId">The session identifier.</param>
  553. /// <returns>SessionInfo.</returns>
  554. /// <exception cref="ResourceNotFoundException"></exception>
  555. private SessionInfo GetSession(string sessionId)
  556. {
  557. var session = Sessions.First(i => string.Equals(i.Id, sessionId));
  558. if (session == null)
  559. {
  560. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  561. }
  562. return session;
  563. }
  564. /// <summary>
  565. /// Gets the session for remote control.
  566. /// </summary>
  567. /// <param name="sessionId">The session id.</param>
  568. /// <returns>SessionInfo.</returns>
  569. /// <exception cref="ResourceNotFoundException"></exception>
  570. private SessionInfo GetSessionForRemoteControl(string sessionId)
  571. {
  572. var session = GetSession(sessionId);
  573. if (!session.SupportsRemoteControl)
  574. {
  575. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  576. }
  577. return session;
  578. }
  579. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  580. {
  581. var session = GetSessionForRemoteControl(sessionId);
  582. var controllingSession = GetSession(controllingSessionId);
  583. AssertCanControl(session, controllingSession);
  584. return session.SessionController.SendMessageCommand(command, cancellationToken);
  585. }
  586. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  587. {
  588. var session = GetSessionForRemoteControl(sessionId);
  589. var controllingSession = GetSession(controllingSessionId);
  590. AssertCanControl(session, controllingSession);
  591. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  592. }
  593. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  594. {
  595. var session = GetSessionForRemoteControl(sessionId);
  596. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  597. List<BaseItem> items;
  598. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  599. {
  600. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  601. .Where(i => i.LocationType != LocationType.Virtual)
  602. .ToList();
  603. command.PlayCommand = PlayCommand.PlayNow;
  604. }
  605. else
  606. {
  607. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  608. .Where(i => i.LocationType != LocationType.Virtual)
  609. .ToList();
  610. }
  611. if (command.PlayCommand == PlayCommand.PlayShuffle)
  612. {
  613. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  614. command.PlayCommand = PlayCommand.PlayNow;
  615. }
  616. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  617. if (user != null)
  618. {
  619. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  620. {
  621. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  622. }
  623. }
  624. if (command.PlayCommand != PlayCommand.PlayNow)
  625. {
  626. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  627. {
  628. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  629. }
  630. }
  631. else
  632. {
  633. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  634. {
  635. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  636. }
  637. }
  638. var controllingSession = GetSession(controllingSessionId);
  639. AssertCanControl(session, controllingSession);
  640. if (controllingSession.UserId.HasValue)
  641. {
  642. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  643. }
  644. return session.SessionController.SendPlayCommand(command, cancellationToken);
  645. }
  646. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  647. {
  648. var item = _libraryManager.GetItemById(new Guid(id));
  649. if (item.IsFolder)
  650. {
  651. var folder = (Folder)item;
  652. var items = user == null ? folder.RecursiveChildren :
  653. folder.GetRecursiveChildren(user);
  654. items = items.Where(i => !i.IsFolder);
  655. items = items.OrderBy(i => i.SortName);
  656. return items;
  657. }
  658. return new[] { item };
  659. }
  660. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  661. {
  662. var item = _libraryManager.GetItemById(new Guid(id));
  663. var audio = item as Audio;
  664. if (audio != null)
  665. {
  666. return _musicManager.GetInstantMixFromSong(audio, user);
  667. }
  668. var artist = item as MusicArtist;
  669. if (artist != null)
  670. {
  671. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  672. }
  673. var album = item as MusicAlbum;
  674. if (album != null)
  675. {
  676. return _musicManager.GetInstantMixFromAlbum(album, user);
  677. }
  678. var genre = item as MusicGenre;
  679. if (genre != null)
  680. {
  681. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  682. }
  683. return new BaseItem[] { };
  684. }
  685. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  686. {
  687. var generalCommand = new GeneralCommand
  688. {
  689. Name = GeneralCommandType.DisplayContent.ToString()
  690. };
  691. generalCommand.Arguments["Context"] = command.Context;
  692. generalCommand.Arguments["ItemId"] = command.ItemId;
  693. generalCommand.Arguments["ItemName"] = command.ItemName;
  694. generalCommand.Arguments["ItemType"] = command.ItemType;
  695. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  696. }
  697. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  698. {
  699. var session = GetSessionForRemoteControl(sessionId);
  700. var controllingSession = GetSession(controllingSessionId);
  701. AssertCanControl(session, controllingSession);
  702. if (controllingSession.UserId.HasValue)
  703. {
  704. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  705. }
  706. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  707. }
  708. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  709. {
  710. if (session == null)
  711. {
  712. throw new ArgumentNullException("session");
  713. }
  714. if (controllingSession == null)
  715. {
  716. throw new ArgumentNullException("controllingSession");
  717. }
  718. }
  719. /// <summary>
  720. /// Sends the restart required message.
  721. /// </summary>
  722. /// <param name="cancellationToken">The cancellation token.</param>
  723. /// <returns>Task.</returns>
  724. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  725. {
  726. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  727. var tasks = sessions.Select(session => Task.Run(async () =>
  728. {
  729. try
  730. {
  731. await session.SessionController.SendRestartRequiredNotification(cancellationToken).ConfigureAwait(false);
  732. }
  733. catch (Exception ex)
  734. {
  735. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  736. }
  737. }, cancellationToken));
  738. return Task.WhenAll(tasks);
  739. }
  740. /// <summary>
  741. /// Sends the server shutdown notification.
  742. /// </summary>
  743. /// <param name="cancellationToken">The cancellation token.</param>
  744. /// <returns>Task.</returns>
  745. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  746. {
  747. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  748. var tasks = sessions.Select(session => Task.Run(async () =>
  749. {
  750. try
  751. {
  752. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  753. }
  754. catch (Exception ex)
  755. {
  756. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  757. }
  758. }, cancellationToken));
  759. return Task.WhenAll(tasks);
  760. }
  761. /// <summary>
  762. /// Sends the server restart notification.
  763. /// </summary>
  764. /// <param name="cancellationToken">The cancellation token.</param>
  765. /// <returns>Task.</returns>
  766. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  767. {
  768. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  769. var tasks = sessions.Select(session => Task.Run(async () =>
  770. {
  771. try
  772. {
  773. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  774. }
  775. catch (Exception ex)
  776. {
  777. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  778. }
  779. }, cancellationToken));
  780. return Task.WhenAll(tasks);
  781. }
  782. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  783. {
  784. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  785. var dto = GetSessionInfoDto(sessionInfo);
  786. var tasks = sessions.Select(session => Task.Run(async () =>
  787. {
  788. try
  789. {
  790. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  791. }
  792. catch (Exception ex)
  793. {
  794. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  795. }
  796. }, cancellationToken));
  797. return Task.WhenAll(tasks);
  798. }
  799. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  800. {
  801. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  802. var dto = GetSessionInfoDto(sessionInfo);
  803. var tasks = sessions.Select(session => Task.Run(async () =>
  804. {
  805. try
  806. {
  807. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  808. }
  809. catch (Exception ex)
  810. {
  811. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  812. }
  813. }, cancellationToken));
  814. return Task.WhenAll(tasks);
  815. }
  816. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  817. {
  818. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  819. var dto = GetSessionInfoDto(sessionInfo);
  820. var tasks = sessions.Select(session => Task.Run(async () =>
  821. {
  822. try
  823. {
  824. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  825. }
  826. catch (Exception ex)
  827. {
  828. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  829. }
  830. }, cancellationToken));
  831. return Task.WhenAll(tasks);
  832. }
  833. /// <summary>
  834. /// Adds the additional user.
  835. /// </summary>
  836. /// <param name="sessionId">The session identifier.</param>
  837. /// <param name="userId">The user identifier.</param>
  838. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  839. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  840. public void AddAdditionalUser(string sessionId, Guid userId)
  841. {
  842. var session = GetSession(sessionId);
  843. if (!session.UserId.HasValue)
  844. {
  845. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  846. }
  847. if (session.UserId.Value == userId)
  848. {
  849. throw new ArgumentException("The requested user is already the primary user of the session.");
  850. }
  851. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  852. {
  853. var user = _userManager.GetUserById(userId);
  854. session.AdditionalUsers.Add(new SessionUserInfo
  855. {
  856. UserId = userId.ToString("N"),
  857. UserName = user.Name
  858. });
  859. }
  860. }
  861. /// <summary>
  862. /// Removes the additional user.
  863. /// </summary>
  864. /// <param name="sessionId">The session identifier.</param>
  865. /// <param name="userId">The user identifier.</param>
  866. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  867. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  868. public void RemoveAdditionalUser(string sessionId, Guid userId)
  869. {
  870. var session = GetSession(sessionId);
  871. if (!session.UserId.HasValue)
  872. {
  873. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  874. }
  875. if (session.UserId.Value == userId)
  876. {
  877. throw new ArgumentException("The requested user is already the primary user of the session.");
  878. }
  879. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  880. if (user != null)
  881. {
  882. session.AdditionalUsers.Remove(user);
  883. }
  884. }
  885. /// <summary>
  886. /// Authenticates the new session.
  887. /// </summary>
  888. /// <param name="user">The user.</param>
  889. /// <param name="password">The password.</param>
  890. /// <param name="clientType">Type of the client.</param>
  891. /// <param name="appVersion">The application version.</param>
  892. /// <param name="deviceId">The device identifier.</param>
  893. /// <param name="deviceName">Name of the device.</param>
  894. /// <param name="remoteEndPoint">The remote end point.</param>
  895. /// <returns>Task{SessionInfo}.</returns>
  896. /// <exception cref="UnauthorizedAccessException"></exception>
  897. public async Task<SessionInfo> AuthenticateNewSession(User user, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  898. {
  899. var result = await _userManager.AuthenticateUser(user, password).ConfigureAwait(false);
  900. if (!result)
  901. {
  902. throw new UnauthorizedAccessException("Invalid user or password entered.");
  903. }
  904. return await LogSessionActivity(clientType, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
  905. }
  906. /// <summary>
  907. /// Reports the capabilities.
  908. /// </summary>
  909. /// <param name="sessionId">The session identifier.</param>
  910. /// <param name="capabilities">The capabilities.</param>
  911. public void ReportCapabilities(string sessionId, SessionCapabilities capabilities)
  912. {
  913. var session = GetSession(sessionId);
  914. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  915. session.SupportedCommands = capabilities.SupportedCommands;
  916. }
  917. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  918. {
  919. var dto = new SessionInfoDto
  920. {
  921. Client = session.Client,
  922. DeviceId = session.DeviceId,
  923. DeviceName = session.DeviceName,
  924. Id = session.Id,
  925. LastActivityDate = session.LastActivityDate,
  926. NowPlayingPositionTicks = session.PlayState.PositionTicks,
  927. SupportsRemoteControl = session.SupportsRemoteControl,
  928. IsPaused = session.PlayState.IsPaused,
  929. IsMuted = session.PlayState.IsMuted,
  930. NowViewingContext = session.NowViewingContext,
  931. NowViewingItem = session.NowViewingItem,
  932. ApplicationVersion = session.ApplicationVersion,
  933. CanSeek = session.PlayState.CanSeek,
  934. QueueableMediaTypes = session.QueueableMediaTypes,
  935. PlayableMediaTypes = session.PlayableMediaTypes,
  936. RemoteEndPoint = session.RemoteEndPoint,
  937. AdditionalUsers = session.AdditionalUsers,
  938. SupportedCommands = session.SupportedCommands,
  939. UserName = session.UserName,
  940. NowPlayingItem = session.NowPlayingItem,
  941. PlayState = session.PlayState
  942. };
  943. if (session.UserId.HasValue)
  944. {
  945. dto.UserId = session.UserId.Value.ToString("N");
  946. var user = _userManager.GetUserById(session.UserId.Value);
  947. if (user != null)
  948. {
  949. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  950. }
  951. }
  952. return dto;
  953. }
  954. /// <summary>
  955. /// Converts a BaseItem to a BaseItemInfo
  956. /// </summary>
  957. /// <param name="item">The item.</param>
  958. /// <param name="runtimeTicks">The now playing runtime ticks.</param>
  959. /// <returns>BaseItemInfo.</returns>
  960. /// <exception cref="System.ArgumentNullException">item</exception>
  961. private BaseItemInfo GetItemInfo(BaseItem item, long? runtimeTicks)
  962. {
  963. if (item == null)
  964. {
  965. throw new ArgumentNullException("item");
  966. }
  967. var info = new BaseItemInfo
  968. {
  969. Id = GetDtoId(item),
  970. Name = item.Name,
  971. MediaType = item.MediaType,
  972. Type = item.GetClientTypeName(),
  973. RunTimeTicks = runtimeTicks,
  974. IndexNumber = item.IndexNumber,
  975. ParentIndexNumber = item.ParentIndexNumber,
  976. PremiereDate = item.PremiereDate,
  977. ProductionYear = item.ProductionYear
  978. };
  979. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  980. if (info.PrimaryImageTag.HasValue)
  981. {
  982. info.PrimaryImageItemId = GetDtoId(item);
  983. }
  984. var episode = item as Episode;
  985. if (episode != null)
  986. {
  987. info.IndexNumberEnd = episode.IndexNumberEnd;
  988. }
  989. var hasSeries = item as IHasSeries;
  990. if (hasSeries != null)
  991. {
  992. info.SeriesName = hasSeries.SeriesName;
  993. }
  994. var recording = item as ILiveTvRecording;
  995. if (recording != null && recording.RecordingInfo != null)
  996. {
  997. if (recording.RecordingInfo.IsSeries)
  998. {
  999. info.Name = recording.RecordingInfo.EpisodeTitle;
  1000. info.SeriesName = recording.RecordingInfo.Name;
  1001. if (string.IsNullOrWhiteSpace(info.Name))
  1002. {
  1003. info.Name = recording.RecordingInfo.Name;
  1004. }
  1005. }
  1006. }
  1007. var audio = item as Audio;
  1008. if (audio != null)
  1009. {
  1010. info.Album = audio.Album;
  1011. info.Artists = audio.Artists;
  1012. if (!info.PrimaryImageTag.HasValue)
  1013. {
  1014. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1015. if (album != null && album.HasImage(ImageType.Primary))
  1016. {
  1017. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1018. if (info.PrimaryImageTag.HasValue)
  1019. {
  1020. info.PrimaryImageItemId = GetDtoId(album);
  1021. }
  1022. }
  1023. }
  1024. }
  1025. var musicVideo = item as MusicVideo;
  1026. if (musicVideo != null)
  1027. {
  1028. info.Album = musicVideo.Album;
  1029. if (!string.IsNullOrWhiteSpace(musicVideo.Artist))
  1030. {
  1031. info.Artists.Add(musicVideo.Artist);
  1032. }
  1033. }
  1034. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1035. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1036. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1037. if (thumbItem == null)
  1038. {
  1039. if (episode != null)
  1040. {
  1041. var series = episode.Series;
  1042. if (series != null && series.HasImage(ImageType.Thumb))
  1043. {
  1044. thumbItem = series;
  1045. }
  1046. }
  1047. }
  1048. if (backropItem == null)
  1049. {
  1050. if (episode != null)
  1051. {
  1052. var series = episode.Series;
  1053. if (series != null && series.HasImage(ImageType.Backdrop))
  1054. {
  1055. backropItem = series;
  1056. }
  1057. }
  1058. }
  1059. if (backropItem == null)
  1060. {
  1061. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1062. }
  1063. if (thumbItem == null)
  1064. {
  1065. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1066. }
  1067. if (logoItem == null)
  1068. {
  1069. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1070. }
  1071. if (thumbItem != null)
  1072. {
  1073. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1074. info.ThumbItemId = GetDtoId(thumbItem);
  1075. }
  1076. if (backropItem != null)
  1077. {
  1078. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1079. info.BackdropItemId = GetDtoId(backropItem);
  1080. }
  1081. if (logoItem != null)
  1082. {
  1083. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1084. info.LogoItemId = GetDtoId(logoItem);
  1085. }
  1086. return info;
  1087. }
  1088. private Guid? GetImageCacheTag(BaseItem item, ImageType type)
  1089. {
  1090. try
  1091. {
  1092. return _imageProcessor.GetImageCacheTag(item, type);
  1093. }
  1094. catch (Exception ex)
  1095. {
  1096. _logger.ErrorException("Error getting {0} image info", ex, type);
  1097. return null;
  1098. }
  1099. }
  1100. private string GetDtoId(BaseItem item)
  1101. {
  1102. return _dtoService.GetDtoId(item);
  1103. }
  1104. public void ReportNowViewingItem(string sessionId, string itemId, string context)
  1105. {
  1106. var item = _libraryManager.GetItemById(new Guid(itemId));
  1107. var info = GetItemInfo(item, item.RunTimeTicks);
  1108. ReportNowViewingItem(sessionId, info, context);
  1109. }
  1110. public void ReportNowViewingItem(string sessionId, BaseItemInfo item, string context)
  1111. {
  1112. var session = GetSession(sessionId);
  1113. session.NowViewingItem = item;
  1114. session.NowViewingContext = context;
  1115. }
  1116. }
  1117. }