SessionManager.cs 50 KB

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