SessionManager.cs 49 KB

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