SessionManager.cs 49 KB

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