SessionManager.cs 50 KB

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