SessionManager.cs 51 KB

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