SessionManager.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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. info.Item = GetItemInfo(libraryItem, runtimeTicks, libraryItem, info.MediaSourceId);
  243. }
  244. session.NowPlayingItem = info.Item;
  245. session.LastActivityDate = DateTime.UtcNow;
  246. session.PlayState.IsPaused = info.IsPaused;
  247. session.PlayState.PositionTicks = info.PositionTicks;
  248. session.PlayState.MediaSourceId = info.MediaSourceId;
  249. session.PlayState.CanSeek = info.CanSeek;
  250. session.PlayState.IsMuted = info.IsMuted;
  251. session.PlayState.VolumeLevel = info.VolumeLevel;
  252. session.PlayState.AudioStreamIndex = info.AudioStreamIndex;
  253. session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex;
  254. session.PlayState.PlayMethod = info.PlayMethod;
  255. }
  256. /// <summary>
  257. /// Removes the now playing item id.
  258. /// </summary>
  259. /// <param name="session">The session.</param>
  260. /// <exception cref="System.ArgumentNullException">item</exception>
  261. private void RemoveNowPlayingItem(SessionInfo session)
  262. {
  263. session.NowPlayingItem = null;
  264. session.PlayState = new PlayerStateInfo();
  265. }
  266. private string GetSessionKey(string clientType, string appVersion, string deviceId)
  267. {
  268. return clientType + deviceId + appVersion;
  269. }
  270. /// <summary>
  271. /// Gets the connection.
  272. /// </summary>
  273. /// <param name="clientType">Type of the client.</param>
  274. /// <param name="appVersion">The app version.</param>
  275. /// <param name="deviceId">The device id.</param>
  276. /// <param name="deviceName">Name of the device.</param>
  277. /// <param name="remoteEndPoint">The remote end point.</param>
  278. /// <param name="userId">The user identifier.</param>
  279. /// <param name="username">The username.</param>
  280. /// <returns>SessionInfo.</returns>
  281. private async Task<SessionInfo> GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username)
  282. {
  283. var key = GetSessionKey(clientType, appVersion, deviceId);
  284. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  285. try
  286. {
  287. var connection = _activeConnections.GetOrAdd(key, keyName =>
  288. {
  289. var sessionInfo = new SessionInfo
  290. {
  291. Client = clientType,
  292. DeviceId = deviceId,
  293. ApplicationVersion = appVersion,
  294. Id = Guid.NewGuid().ToString("N")
  295. };
  296. OnSessionStarted(sessionInfo);
  297. return sessionInfo;
  298. });
  299. connection.DeviceName = deviceName;
  300. connection.UserId = userId;
  301. connection.UserName = username;
  302. connection.RemoteEndPoint = remoteEndPoint;
  303. if (!userId.HasValue)
  304. {
  305. connection.AdditionalUsers.Clear();
  306. }
  307. if (connection.SessionController == null)
  308. {
  309. connection.SessionController = _sessionFactories
  310. .Select(i => i.GetSessionController(connection))
  311. .FirstOrDefault(i => i != null);
  312. }
  313. return connection;
  314. }
  315. finally
  316. {
  317. _sessionLock.Release();
  318. }
  319. }
  320. private List<User> GetUsers(SessionInfo session)
  321. {
  322. var users = new List<User>();
  323. if (session.UserId.HasValue)
  324. {
  325. var user = _userManager.GetUserById(session.UserId.Value);
  326. if (user == null)
  327. {
  328. throw new InvalidOperationException("User not found");
  329. }
  330. users.Add(user);
  331. var additionalUsers = session.AdditionalUsers
  332. .Select(i => _userManager.GetUserById(new Guid(i.UserId)))
  333. .Where(i => i != null);
  334. users.AddRange(additionalUsers);
  335. }
  336. return users;
  337. }
  338. /// <summary>
  339. /// Used to report that playback has started for an item
  340. /// </summary>
  341. /// <param name="info">The info.</param>
  342. /// <returns>Task.</returns>
  343. /// <exception cref="System.ArgumentNullException">info</exception>
  344. public async Task OnPlaybackStart(PlaybackStartInfo info)
  345. {
  346. if (info == null)
  347. {
  348. throw new ArgumentNullException("info");
  349. }
  350. var session = GetSession(info.SessionId);
  351. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  352. ? null
  353. : _libraryManager.GetItemById(new Guid(info.ItemId));
  354. UpdateNowPlayingItem(session, info, libraryItem);
  355. session.QueueableMediaTypes = info.QueueableMediaTypes;
  356. var users = GetUsers(session);
  357. if (libraryItem != null)
  358. {
  359. var key = libraryItem.GetUserDataKey();
  360. foreach (var user in users)
  361. {
  362. await OnPlaybackStart(user.Id, key, libraryItem).ConfigureAwait(false);
  363. }
  364. }
  365. // Nothing to save here
  366. // Fire events to inform plugins
  367. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  368. {
  369. Item = libraryItem,
  370. Users = users,
  371. MediaSourceId = info.MediaSourceId,
  372. MediaInfo = info.Item,
  373. DeviceName = session.DeviceName,
  374. ClientName = session.Client
  375. }, _logger);
  376. await SendPlaybackStartNotification(session, CancellationToken.None).ConfigureAwait(false);
  377. }
  378. /// <summary>
  379. /// Called when [playback start].
  380. /// </summary>
  381. /// <param name="userId">The user identifier.</param>
  382. /// <param name="userDataKey">The user data key.</param>
  383. /// <param name="item">The item.</param>
  384. /// <returns>Task.</returns>
  385. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  386. {
  387. var data = _userDataRepository.GetUserData(userId, userDataKey);
  388. data.PlayCount++;
  389. data.LastPlayedDate = DateTime.UtcNow;
  390. if (!(item is Video))
  391. {
  392. data.Played = true;
  393. }
  394. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  395. }
  396. /// <summary>
  397. /// Used to report playback progress for an item
  398. /// </summary>
  399. /// <param name="info">The info.</param>
  400. /// <returns>Task.</returns>
  401. /// <exception cref="System.ArgumentNullException"></exception>
  402. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  403. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  404. {
  405. if (info == null)
  406. {
  407. throw new ArgumentNullException("info");
  408. }
  409. var session = GetSession(info.SessionId);
  410. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  411. ? null
  412. : _libraryManager.GetItemById(new Guid(info.ItemId));
  413. UpdateNowPlayingItem(session, info, libraryItem);
  414. var users = GetUsers(session);
  415. if (libraryItem != null)
  416. {
  417. var key = libraryItem.GetUserDataKey();
  418. foreach (var user in users)
  419. {
  420. await OnPlaybackProgress(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  421. }
  422. }
  423. EventHelper.QueueEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  424. {
  425. Item = libraryItem,
  426. Users = users,
  427. PlaybackPositionTicks = session.PlayState.PositionTicks,
  428. MediaSourceId = session.PlayState.MediaSourceId,
  429. MediaInfo = info.Item,
  430. DeviceName = session.DeviceName,
  431. ClientName = session.Client
  432. }, _logger);
  433. }
  434. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  435. {
  436. var data = _userDataRepository.GetUserData(userId, userDataKey);
  437. if (positionTicks.HasValue)
  438. {
  439. UpdatePlayState(item, data, positionTicks.Value);
  440. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  441. }
  442. }
  443. /// <summary>
  444. /// Used to report that playback has ended for an item
  445. /// </summary>
  446. /// <param name="info">The info.</param>
  447. /// <returns>Task.</returns>
  448. /// <exception cref="System.ArgumentNullException">info</exception>
  449. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  450. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  451. {
  452. if (info == null)
  453. {
  454. throw new ArgumentNullException("info");
  455. }
  456. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  457. {
  458. throw new ArgumentOutOfRangeException("positionTicks");
  459. }
  460. var session = GetSession(info.SessionId);
  461. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  462. ? null
  463. : _libraryManager.GetItemById(new Guid(info.ItemId));
  464. // Normalize
  465. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  466. {
  467. info.MediaSourceId = info.ItemId;
  468. }
  469. RemoveNowPlayingItem(session);
  470. var users = GetUsers(session);
  471. var playedToCompletion = false;
  472. if (libraryItem != null)
  473. {
  474. var key = libraryItem.GetUserDataKey();
  475. foreach (var user in users)
  476. {
  477. playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  478. }
  479. }
  480. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  481. {
  482. Item = libraryItem,
  483. Users = users,
  484. PlaybackPositionTicks = info.PositionTicks,
  485. PlayedToCompletion = playedToCompletion,
  486. MediaSourceId = info.MediaSourceId,
  487. MediaInfo = info.Item,
  488. DeviceName = session.DeviceName,
  489. ClientName = session.Client
  490. }, _logger);
  491. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  492. }
  493. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  494. {
  495. var data = _userDataRepository.GetUserData(userId, userDataKey);
  496. bool playedToCompletion;
  497. if (positionTicks.HasValue)
  498. {
  499. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  500. }
  501. else
  502. {
  503. // If the client isn't able to report this, then we'll just have to make an assumption
  504. data.PlayCount++;
  505. data.Played = true;
  506. data.PlaybackPositionTicks = 0;
  507. playedToCompletion = true;
  508. }
  509. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  510. return playedToCompletion;
  511. }
  512. /// <summary>
  513. /// Updates playstate position for an item but does not save
  514. /// </summary>
  515. /// <param name="item">The item</param>
  516. /// <param name="data">User data for the item</param>
  517. /// <param name="positionTicks">The current playback position</param>
  518. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  519. {
  520. var playedToCompletion = false;
  521. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  522. // If a position has been reported, and if we know the duration
  523. if (positionTicks > 0 && hasRuntime)
  524. {
  525. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  526. // Don't track in very beginning
  527. if (pctIn < _configurationManager.Configuration.MinResumePct)
  528. {
  529. positionTicks = 0;
  530. }
  531. // If we're at the end, assume completed
  532. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  533. {
  534. positionTicks = 0;
  535. data.Played = playedToCompletion = true;
  536. }
  537. else
  538. {
  539. // Enforce MinResumeDuration
  540. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  541. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  542. {
  543. positionTicks = 0;
  544. data.Played = playedToCompletion = true;
  545. }
  546. }
  547. }
  548. else if (!hasRuntime)
  549. {
  550. // If we don't know the runtime we'll just have to assume it was fully played
  551. data.Played = playedToCompletion = true;
  552. positionTicks = 0;
  553. }
  554. if (item is Audio)
  555. {
  556. positionTicks = 0;
  557. }
  558. data.PlaybackPositionTicks = positionTicks;
  559. return playedToCompletion;
  560. }
  561. /// <summary>
  562. /// Gets the session.
  563. /// </summary>
  564. /// <param name="sessionId">The session identifier.</param>
  565. /// <returns>SessionInfo.</returns>
  566. /// <exception cref="ResourceNotFoundException"></exception>
  567. private SessionInfo GetSession(string sessionId)
  568. {
  569. var session = Sessions.First(i => string.Equals(i.Id, sessionId));
  570. if (session == null)
  571. {
  572. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  573. }
  574. return session;
  575. }
  576. /// <summary>
  577. /// Gets the session for remote control.
  578. /// </summary>
  579. /// <param name="sessionId">The session id.</param>
  580. /// <returns>SessionInfo.</returns>
  581. /// <exception cref="ResourceNotFoundException"></exception>
  582. private SessionInfo GetSessionForRemoteControl(string sessionId)
  583. {
  584. var session = GetSession(sessionId);
  585. if (!session.SupportsRemoteControl)
  586. {
  587. throw new ArgumentException(string.Format("Session {0} does not support remote control.", session.Id));
  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 = GetSessionForRemoteControl(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 = GetSessionForRemoteControl(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 = GetSessionForRemoteControl(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. }
  935. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  936. {
  937. var dto = new SessionInfoDto
  938. {
  939. Client = session.Client,
  940. DeviceId = session.DeviceId,
  941. DeviceName = session.DeviceName,
  942. Id = session.Id,
  943. LastActivityDate = session.LastActivityDate,
  944. NowPlayingPositionTicks = session.PlayState.PositionTicks,
  945. SupportsRemoteControl = session.SupportsRemoteControl,
  946. IsPaused = session.PlayState.IsPaused,
  947. IsMuted = session.PlayState.IsMuted,
  948. NowViewingItem = session.NowViewingItem,
  949. ApplicationVersion = session.ApplicationVersion,
  950. CanSeek = session.PlayState.CanSeek,
  951. QueueableMediaTypes = session.QueueableMediaTypes,
  952. PlayableMediaTypes = session.PlayableMediaTypes,
  953. RemoteEndPoint = session.RemoteEndPoint,
  954. AdditionalUsers = session.AdditionalUsers,
  955. SupportedCommands = session.SupportedCommands,
  956. UserName = session.UserName,
  957. NowPlayingItem = session.NowPlayingItem,
  958. PlayState = session.PlayState
  959. };
  960. if (session.UserId.HasValue)
  961. {
  962. dto.UserId = session.UserId.Value.ToString("N");
  963. var user = _userManager.GetUserById(session.UserId.Value);
  964. if (user != null)
  965. {
  966. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  967. }
  968. }
  969. return dto;
  970. }
  971. /// <summary>
  972. /// Converts a BaseItem to a BaseItemInfo
  973. /// </summary>
  974. /// <param name="item">The item.</param>
  975. /// <param name="runtimeTicks">The now playing runtime ticks.</param>
  976. /// <param name="chapterOwner">The chapter owner.</param>
  977. /// <param name="mediaSourceId">The media source identifier.</param>
  978. /// <returns>BaseItemInfo.</returns>
  979. /// <exception cref="System.ArgumentNullException">item</exception>
  980. private BaseItemInfo GetItemInfo(BaseItem item, long? runtimeTicks, BaseItem chapterOwner, string mediaSourceId)
  981. {
  982. if (item == null)
  983. {
  984. throw new ArgumentNullException("item");
  985. }
  986. var info = new BaseItemInfo
  987. {
  988. Id = GetDtoId(item),
  989. Name = item.Name,
  990. MediaType = item.MediaType,
  991. Type = item.GetClientTypeName(),
  992. RunTimeTicks = runtimeTicks,
  993. IndexNumber = item.IndexNumber,
  994. ParentIndexNumber = item.ParentIndexNumber,
  995. PremiereDate = item.PremiereDate,
  996. ProductionYear = item.ProductionYear
  997. };
  998. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  999. if (info.PrimaryImageTag != null)
  1000. {
  1001. info.PrimaryImageItemId = GetDtoId(item);
  1002. }
  1003. var episode = item as Episode;
  1004. if (episode != null)
  1005. {
  1006. info.IndexNumberEnd = episode.IndexNumberEnd;
  1007. }
  1008. var hasSeries = item as IHasSeries;
  1009. if (hasSeries != null)
  1010. {
  1011. info.SeriesName = hasSeries.SeriesName;
  1012. }
  1013. var recording = item as ILiveTvRecording;
  1014. if (recording != null && recording.RecordingInfo != null)
  1015. {
  1016. if (recording.RecordingInfo.IsSeries)
  1017. {
  1018. info.Name = recording.RecordingInfo.EpisodeTitle;
  1019. info.SeriesName = recording.RecordingInfo.Name;
  1020. if (string.IsNullOrWhiteSpace(info.Name))
  1021. {
  1022. info.Name = recording.RecordingInfo.Name;
  1023. }
  1024. }
  1025. }
  1026. var audio = item as Audio;
  1027. if (audio != null)
  1028. {
  1029. info.Album = audio.Album;
  1030. info.Artists = audio.Artists;
  1031. if (info.PrimaryImageTag == null)
  1032. {
  1033. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1034. if (album != null && album.HasImage(ImageType.Primary))
  1035. {
  1036. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1037. if (info.PrimaryImageTag != null)
  1038. {
  1039. info.PrimaryImageItemId = GetDtoId(album);
  1040. }
  1041. }
  1042. }
  1043. }
  1044. var musicVideo = item as MusicVideo;
  1045. if (musicVideo != null)
  1046. {
  1047. info.Album = musicVideo.Album;
  1048. if (!string.IsNullOrWhiteSpace(musicVideo.Artist))
  1049. {
  1050. info.Artists.Add(musicVideo.Artist);
  1051. }
  1052. }
  1053. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1054. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1055. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1056. if (thumbItem == null)
  1057. {
  1058. if (episode != null)
  1059. {
  1060. var series = episode.Series;
  1061. if (series != null && series.HasImage(ImageType.Thumb))
  1062. {
  1063. thumbItem = series;
  1064. }
  1065. }
  1066. }
  1067. if (backropItem == null)
  1068. {
  1069. if (episode != null)
  1070. {
  1071. var series = episode.Series;
  1072. if (series != null && series.HasImage(ImageType.Backdrop))
  1073. {
  1074. backropItem = series;
  1075. }
  1076. }
  1077. }
  1078. if (backropItem == null)
  1079. {
  1080. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1081. }
  1082. if (thumbItem == null)
  1083. {
  1084. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1085. }
  1086. if (logoItem == null)
  1087. {
  1088. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1089. }
  1090. if (thumbItem != null)
  1091. {
  1092. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1093. info.ThumbItemId = GetDtoId(thumbItem);
  1094. }
  1095. if (backropItem != null)
  1096. {
  1097. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1098. info.BackdropItemId = GetDtoId(backropItem);
  1099. }
  1100. if (logoItem != null)
  1101. {
  1102. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1103. info.LogoItemId = GetDtoId(logoItem);
  1104. }
  1105. if (chapterOwner != null)
  1106. {
  1107. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1108. info.Chapters = _itemRepo.GetChapters(chapterOwner.Id).Select(i => _dtoService.GetChapterInfoDto(i, chapterOwner)).ToList();
  1109. }
  1110. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  1111. {
  1112. info.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  1113. {
  1114. ItemId = new Guid(mediaSourceId)
  1115. }).ToList();
  1116. }
  1117. return info;
  1118. }
  1119. private string GetImageCacheTag(BaseItem item, ImageType type)
  1120. {
  1121. try
  1122. {
  1123. return _imageProcessor.GetImageCacheTag(item, type);
  1124. }
  1125. catch (Exception ex)
  1126. {
  1127. _logger.ErrorException("Error getting {0} image info", ex, type);
  1128. return null;
  1129. }
  1130. }
  1131. private string GetDtoId(BaseItem item)
  1132. {
  1133. return _dtoService.GetDtoId(item);
  1134. }
  1135. public void ReportNowViewingItem(string sessionId, string itemId)
  1136. {
  1137. var item = _libraryManager.GetItemById(new Guid(itemId));
  1138. var info = GetItemInfo(item, item.RunTimeTicks, null, null);
  1139. ReportNowViewingItem(sessionId, info);
  1140. }
  1141. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1142. {
  1143. var session = GetSession(sessionId);
  1144. session.NowViewingItem = item;
  1145. }
  1146. }
  1147. }