SessionManager.cs 51 KB

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