SessionManager.cs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  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. DeviceId = session.DeviceId
  400. }, _logger);
  401. await SendPlaybackStartNotification(session, CancellationToken.None).ConfigureAwait(false);
  402. }
  403. /// <summary>
  404. /// Called when [playback start].
  405. /// </summary>
  406. /// <param name="userId">The user identifier.</param>
  407. /// <param name="userDataKey">The user data key.</param>
  408. /// <param name="item">The item.</param>
  409. /// <returns>Task.</returns>
  410. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  411. {
  412. var data = _userDataRepository.GetUserData(userId, userDataKey);
  413. data.PlayCount++;
  414. data.LastPlayedDate = DateTime.UtcNow;
  415. if (!(item is Video))
  416. {
  417. data.Played = true;
  418. }
  419. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  420. }
  421. /// <summary>
  422. /// Used to report playback progress for an item
  423. /// </summary>
  424. /// <param name="info">The info.</param>
  425. /// <returns>Task.</returns>
  426. /// <exception cref="System.ArgumentNullException"></exception>
  427. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  428. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  429. {
  430. if (info == null)
  431. {
  432. throw new ArgumentNullException("info");
  433. }
  434. var session = GetSession(info.SessionId);
  435. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  436. ? null
  437. : _libraryManager.GetItemById(new Guid(info.ItemId));
  438. UpdateNowPlayingItem(session, info, libraryItem);
  439. var users = GetUsers(session);
  440. if (libraryItem != null)
  441. {
  442. var key = libraryItem.GetUserDataKey();
  443. foreach (var user in users)
  444. {
  445. await OnPlaybackProgress(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  446. }
  447. }
  448. EventHelper.FireEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  449. {
  450. Item = libraryItem,
  451. Users = users,
  452. PlaybackPositionTicks = session.PlayState.PositionTicks,
  453. MediaSourceId = session.PlayState.MediaSourceId,
  454. MediaInfo = info.Item,
  455. DeviceName = session.DeviceName,
  456. ClientName = session.Client,
  457. DeviceId = session.DeviceId
  458. }, _logger);
  459. }
  460. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  461. {
  462. var data = _userDataRepository.GetUserData(userId, userDataKey);
  463. if (positionTicks.HasValue)
  464. {
  465. UpdatePlayState(item, data, positionTicks.Value);
  466. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  467. }
  468. }
  469. /// <summary>
  470. /// Used to report that playback has ended for an item
  471. /// </summary>
  472. /// <param name="info">The info.</param>
  473. /// <returns>Task.</returns>
  474. /// <exception cref="System.ArgumentNullException">info</exception>
  475. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  476. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  477. {
  478. if (info == null)
  479. {
  480. throw new ArgumentNullException("info");
  481. }
  482. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  483. {
  484. throw new ArgumentOutOfRangeException("positionTicks");
  485. }
  486. var session = GetSession(info.SessionId);
  487. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  488. ? null
  489. : _libraryManager.GetItemById(new Guid(info.ItemId));
  490. // Normalize
  491. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  492. {
  493. info.MediaSourceId = info.ItemId;
  494. }
  495. RemoveNowPlayingItem(session);
  496. var users = GetUsers(session);
  497. var playedToCompletion = false;
  498. if (libraryItem != null)
  499. {
  500. var key = libraryItem.GetUserDataKey();
  501. foreach (var user in users)
  502. {
  503. playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  504. }
  505. }
  506. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  507. {
  508. Item = libraryItem,
  509. Users = users,
  510. PlaybackPositionTicks = info.PositionTicks,
  511. PlayedToCompletion = playedToCompletion,
  512. MediaSourceId = info.MediaSourceId,
  513. MediaInfo = info.Item,
  514. DeviceName = session.DeviceName,
  515. ClientName = session.Client,
  516. DeviceId = session.DeviceId
  517. }, _logger);
  518. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  519. }
  520. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  521. {
  522. var data = _userDataRepository.GetUserData(userId, userDataKey);
  523. bool playedToCompletion;
  524. if (positionTicks.HasValue)
  525. {
  526. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  527. }
  528. else
  529. {
  530. // If the client isn't able to report this, then we'll just have to make an assumption
  531. data.PlayCount++;
  532. data.Played = true;
  533. data.PlaybackPositionTicks = 0;
  534. playedToCompletion = true;
  535. }
  536. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  537. return playedToCompletion;
  538. }
  539. /// <summary>
  540. /// Updates playstate position for an item but does not save
  541. /// </summary>
  542. /// <param name="item">The item</param>
  543. /// <param name="data">User data for the item</param>
  544. /// <param name="positionTicks">The current playback position</param>
  545. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  546. {
  547. var playedToCompletion = false;
  548. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  549. // If a position has been reported, and if we know the duration
  550. if (positionTicks > 0 && hasRuntime)
  551. {
  552. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  553. // Don't track in very beginning
  554. if (pctIn < _configurationManager.Configuration.MinResumePct)
  555. {
  556. positionTicks = 0;
  557. }
  558. // If we're at the end, assume completed
  559. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  560. {
  561. positionTicks = 0;
  562. data.Played = playedToCompletion = true;
  563. }
  564. else
  565. {
  566. // Enforce MinResumeDuration
  567. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  568. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  569. {
  570. positionTicks = 0;
  571. data.Played = playedToCompletion = true;
  572. }
  573. }
  574. }
  575. else if (!hasRuntime)
  576. {
  577. // If we don't know the runtime we'll just have to assume it was fully played
  578. data.Played = playedToCompletion = true;
  579. positionTicks = 0;
  580. }
  581. if (item is Audio)
  582. {
  583. positionTicks = 0;
  584. }
  585. data.PlaybackPositionTicks = positionTicks;
  586. return playedToCompletion;
  587. }
  588. /// <summary>
  589. /// Gets the session.
  590. /// </summary>
  591. /// <param name="sessionId">The session identifier.</param>
  592. /// <returns>SessionInfo.</returns>
  593. /// <exception cref="ResourceNotFoundException"></exception>
  594. private SessionInfo GetSession(string sessionId)
  595. {
  596. var session = Sessions.First(i => string.Equals(i.Id, sessionId));
  597. if (session == null)
  598. {
  599. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  600. }
  601. return session;
  602. }
  603. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  604. {
  605. var generalCommand = new GeneralCommand
  606. {
  607. Name = GeneralCommandType.DisplayMessage.ToString()
  608. };
  609. generalCommand.Arguments["Header"] = command.Header;
  610. generalCommand.Arguments["Text"] = command.Text;
  611. if (command.TimeoutMs.HasValue)
  612. {
  613. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  614. }
  615. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  616. }
  617. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  618. {
  619. var session = GetSession(sessionId);
  620. var controllingSession = GetSession(controllingSessionId);
  621. AssertCanControl(session, controllingSession);
  622. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  623. }
  624. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  625. {
  626. var session = GetSession(sessionId);
  627. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  628. List<BaseItem> items;
  629. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  630. {
  631. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  632. .Where(i => i.LocationType != LocationType.Virtual)
  633. .ToList();
  634. command.PlayCommand = PlayCommand.PlayNow;
  635. }
  636. else
  637. {
  638. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  639. .Where(i => i.LocationType != LocationType.Virtual)
  640. .ToList();
  641. }
  642. if (command.PlayCommand == PlayCommand.PlayShuffle)
  643. {
  644. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  645. command.PlayCommand = PlayCommand.PlayNow;
  646. }
  647. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  648. if (user != null)
  649. {
  650. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  651. {
  652. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  653. }
  654. }
  655. if (command.PlayCommand != PlayCommand.PlayNow)
  656. {
  657. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  658. {
  659. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  660. }
  661. }
  662. else
  663. {
  664. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  665. {
  666. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  667. }
  668. }
  669. var controllingSession = GetSession(controllingSessionId);
  670. AssertCanControl(session, controllingSession);
  671. if (controllingSession.UserId.HasValue)
  672. {
  673. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  674. }
  675. return session.SessionController.SendPlayCommand(command, cancellationToken);
  676. }
  677. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  678. {
  679. var item = _libraryManager.GetItemById(new Guid(id));
  680. if (item.IsFolder)
  681. {
  682. var folder = (Folder)item;
  683. var items = user == null ? folder.RecursiveChildren :
  684. folder.GetRecursiveChildren(user);
  685. items = items.Where(i => !i.IsFolder);
  686. items = items.OrderBy(i => i.SortName);
  687. return items;
  688. }
  689. return new[] { item };
  690. }
  691. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  692. {
  693. var item = _libraryManager.GetItemById(new Guid(id));
  694. var audio = item as Audio;
  695. if (audio != null)
  696. {
  697. return _musicManager.GetInstantMixFromSong(audio, user);
  698. }
  699. var artist = item as MusicArtist;
  700. if (artist != null)
  701. {
  702. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  703. }
  704. var album = item as MusicAlbum;
  705. if (album != null)
  706. {
  707. return _musicManager.GetInstantMixFromAlbum(album, user);
  708. }
  709. var genre = item as MusicGenre;
  710. if (genre != null)
  711. {
  712. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  713. }
  714. return new BaseItem[] { };
  715. }
  716. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  717. {
  718. var generalCommand = new GeneralCommand
  719. {
  720. Name = GeneralCommandType.DisplayContent.ToString()
  721. };
  722. generalCommand.Arguments["ItemId"] = command.ItemId;
  723. generalCommand.Arguments["ItemName"] = command.ItemName;
  724. generalCommand.Arguments["ItemType"] = command.ItemType;
  725. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  726. }
  727. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  728. {
  729. var session = GetSession(sessionId);
  730. var controllingSession = GetSession(controllingSessionId);
  731. AssertCanControl(session, controllingSession);
  732. if (controllingSession.UserId.HasValue)
  733. {
  734. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  735. }
  736. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  737. }
  738. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  739. {
  740. if (session == null)
  741. {
  742. throw new ArgumentNullException("session");
  743. }
  744. if (controllingSession == null)
  745. {
  746. throw new ArgumentNullException("controllingSession");
  747. }
  748. }
  749. /// <summary>
  750. /// Sends the restart required message.
  751. /// </summary>
  752. /// <param name="cancellationToken">The cancellation token.</param>
  753. /// <returns>Task.</returns>
  754. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  755. {
  756. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  757. var info = _appHost.GetSystemInfo();
  758. var tasks = sessions.Select(session => Task.Run(async () =>
  759. {
  760. try
  761. {
  762. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  763. }
  764. catch (Exception ex)
  765. {
  766. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  767. }
  768. }, cancellationToken));
  769. return Task.WhenAll(tasks);
  770. }
  771. /// <summary>
  772. /// Sends the server shutdown notification.
  773. /// </summary>
  774. /// <param name="cancellationToken">The cancellation token.</param>
  775. /// <returns>Task.</returns>
  776. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  777. {
  778. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  779. var tasks = sessions.Select(session => Task.Run(async () =>
  780. {
  781. try
  782. {
  783. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  784. }
  785. catch (Exception ex)
  786. {
  787. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  788. }
  789. }, cancellationToken));
  790. return Task.WhenAll(tasks);
  791. }
  792. /// <summary>
  793. /// Sends the server restart notification.
  794. /// </summary>
  795. /// <param name="cancellationToken">The cancellation token.</param>
  796. /// <returns>Task.</returns>
  797. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  798. {
  799. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  800. var tasks = sessions.Select(session => Task.Run(async () =>
  801. {
  802. try
  803. {
  804. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  805. }
  806. catch (Exception ex)
  807. {
  808. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  809. }
  810. }, cancellationToken));
  811. return Task.WhenAll(tasks);
  812. }
  813. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  814. {
  815. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  816. var dto = GetSessionInfoDto(sessionInfo);
  817. var tasks = sessions.Select(session => Task.Run(async () =>
  818. {
  819. try
  820. {
  821. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  822. }
  823. catch (Exception ex)
  824. {
  825. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  826. }
  827. }, cancellationToken));
  828. return Task.WhenAll(tasks);
  829. }
  830. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  831. {
  832. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  833. var dto = GetSessionInfoDto(sessionInfo);
  834. var tasks = sessions.Select(session => Task.Run(async () =>
  835. {
  836. try
  837. {
  838. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  839. }
  840. catch (Exception ex)
  841. {
  842. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  843. }
  844. }, cancellationToken));
  845. return Task.WhenAll(tasks);
  846. }
  847. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  848. {
  849. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  850. var dto = GetSessionInfoDto(sessionInfo);
  851. var tasks = sessions.Select(session => Task.Run(async () =>
  852. {
  853. try
  854. {
  855. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  856. }
  857. catch (Exception ex)
  858. {
  859. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  860. }
  861. }, cancellationToken));
  862. return Task.WhenAll(tasks);
  863. }
  864. /// <summary>
  865. /// Adds the additional user.
  866. /// </summary>
  867. /// <param name="sessionId">The session identifier.</param>
  868. /// <param name="userId">The user identifier.</param>
  869. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  870. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  871. public void AddAdditionalUser(string sessionId, Guid userId)
  872. {
  873. var session = GetSession(sessionId);
  874. if (!session.UserId.HasValue)
  875. {
  876. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  877. }
  878. if (session.UserId.Value == userId)
  879. {
  880. throw new ArgumentException("The requested user is already the primary user of the session.");
  881. }
  882. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  883. {
  884. var user = _userManager.GetUserById(userId);
  885. session.AdditionalUsers.Add(new SessionUserInfo
  886. {
  887. UserId = userId.ToString("N"),
  888. UserName = user.Name
  889. });
  890. }
  891. }
  892. /// <summary>
  893. /// Removes the additional user.
  894. /// </summary>
  895. /// <param name="sessionId">The session identifier.</param>
  896. /// <param name="userId">The user identifier.</param>
  897. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  898. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  899. public void RemoveAdditionalUser(string sessionId, Guid userId)
  900. {
  901. var session = GetSession(sessionId);
  902. if (!session.UserId.HasValue)
  903. {
  904. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  905. }
  906. if (session.UserId.Value == userId)
  907. {
  908. throw new ArgumentException("The requested user is already the primary user of the session.");
  909. }
  910. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  911. if (user != null)
  912. {
  913. session.AdditionalUsers.Remove(user);
  914. }
  915. }
  916. /// <summary>
  917. /// Authenticates the new session.
  918. /// </summary>
  919. /// <param name="user">The user.</param>
  920. /// <param name="password">The password.</param>
  921. /// <param name="clientType">Type of the client.</param>
  922. /// <param name="appVersion">The application version.</param>
  923. /// <param name="deviceId">The device identifier.</param>
  924. /// <param name="deviceName">Name of the device.</param>
  925. /// <param name="remoteEndPoint">The remote end point.</param>
  926. /// <returns>Task{SessionInfo}.</returns>
  927. /// <exception cref="UnauthorizedAccessException"></exception>
  928. public async Task<SessionInfo> AuthenticateNewSession(User user, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  929. {
  930. var result = await _userManager.AuthenticateUser(user, password).ConfigureAwait(false);
  931. if (!result)
  932. {
  933. throw new UnauthorizedAccessException("Invalid user or password entered.");
  934. }
  935. return await LogSessionActivity(clientType, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
  936. }
  937. /// <summary>
  938. /// Reports the capabilities.
  939. /// </summary>
  940. /// <param name="sessionId">The session identifier.</param>
  941. /// <param name="capabilities">The capabilities.</param>
  942. public void ReportCapabilities(string sessionId, SessionCapabilities capabilities)
  943. {
  944. var session = GetSession(sessionId);
  945. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  946. session.SupportedCommands = capabilities.SupportedCommands;
  947. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  948. {
  949. var postUrl = string.Format("http://{0}{1}", session.RemoteEndPoint, capabilities.MessageCallbackUrl);
  950. var controller = session.SessionController as HttpSessionController;
  951. if (controller == null)
  952. {
  953. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, postUrl, this);
  954. }
  955. }
  956. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  957. {
  958. SessionInfo = session
  959. }, _logger);
  960. }
  961. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  962. {
  963. var dto = new SessionInfoDto
  964. {
  965. Client = session.Client,
  966. DeviceId = session.DeviceId,
  967. DeviceName = session.DeviceName,
  968. Id = session.Id,
  969. LastActivityDate = session.LastActivityDate,
  970. NowPlayingPositionTicks = session.PlayState.PositionTicks,
  971. IsPaused = session.PlayState.IsPaused,
  972. IsMuted = session.PlayState.IsMuted,
  973. NowViewingItem = session.NowViewingItem,
  974. ApplicationVersion = session.ApplicationVersion,
  975. CanSeek = session.PlayState.CanSeek,
  976. QueueableMediaTypes = session.QueueableMediaTypes,
  977. PlayableMediaTypes = session.PlayableMediaTypes,
  978. RemoteEndPoint = session.RemoteEndPoint,
  979. AdditionalUsers = session.AdditionalUsers,
  980. SupportedCommands = session.SupportedCommands,
  981. UserName = session.UserName,
  982. NowPlayingItem = session.NowPlayingItem,
  983. SupportsRemoteControl = session.SupportsMediaControl,
  984. PlayState = session.PlayState
  985. };
  986. if (session.UserId.HasValue)
  987. {
  988. dto.UserId = session.UserId.Value.ToString("N");
  989. var user = _userManager.GetUserById(session.UserId.Value);
  990. if (user != null)
  991. {
  992. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  993. }
  994. }
  995. return dto;
  996. }
  997. /// <summary>
  998. /// Converts a BaseItem to a BaseItemInfo
  999. /// </summary>
  1000. /// <param name="item">The item.</param>
  1001. /// <param name="chapterOwner">The chapter owner.</param>
  1002. /// <param name="mediaSourceId">The media source identifier.</param>
  1003. /// <returns>BaseItemInfo.</returns>
  1004. /// <exception cref="System.ArgumentNullException">item</exception>
  1005. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, string mediaSourceId)
  1006. {
  1007. if (item == null)
  1008. {
  1009. throw new ArgumentNullException("item");
  1010. }
  1011. var info = new BaseItemInfo
  1012. {
  1013. Id = GetDtoId(item),
  1014. Name = item.Name,
  1015. MediaType = item.MediaType,
  1016. Type = item.GetClientTypeName(),
  1017. RunTimeTicks = item.RunTimeTicks,
  1018. IndexNumber = item.IndexNumber,
  1019. ParentIndexNumber = item.ParentIndexNumber,
  1020. PremiereDate = item.PremiereDate,
  1021. ProductionYear = item.ProductionYear
  1022. };
  1023. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1024. if (info.PrimaryImageTag != null)
  1025. {
  1026. info.PrimaryImageItemId = GetDtoId(item);
  1027. }
  1028. var episode = item as Episode;
  1029. if (episode != null)
  1030. {
  1031. info.IndexNumberEnd = episode.IndexNumberEnd;
  1032. }
  1033. var hasSeries = item as IHasSeries;
  1034. if (hasSeries != null)
  1035. {
  1036. info.SeriesName = hasSeries.SeriesName;
  1037. }
  1038. var recording = item as ILiveTvRecording;
  1039. if (recording != null && recording.RecordingInfo != null)
  1040. {
  1041. if (recording.RecordingInfo.IsSeries)
  1042. {
  1043. info.Name = recording.RecordingInfo.EpisodeTitle;
  1044. info.SeriesName = recording.RecordingInfo.Name;
  1045. if (string.IsNullOrWhiteSpace(info.Name))
  1046. {
  1047. info.Name = recording.RecordingInfo.Name;
  1048. }
  1049. }
  1050. }
  1051. var audio = item as Audio;
  1052. if (audio != null)
  1053. {
  1054. info.Album = audio.Album;
  1055. info.Artists = audio.Artists;
  1056. if (info.PrimaryImageTag == null)
  1057. {
  1058. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1059. if (album != null && album.HasImage(ImageType.Primary))
  1060. {
  1061. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1062. if (info.PrimaryImageTag != null)
  1063. {
  1064. info.PrimaryImageItemId = GetDtoId(album);
  1065. }
  1066. }
  1067. }
  1068. }
  1069. var musicVideo = item as MusicVideo;
  1070. if (musicVideo != null)
  1071. {
  1072. info.Album = musicVideo.Album;
  1073. if (!string.IsNullOrWhiteSpace(musicVideo.Artist))
  1074. {
  1075. info.Artists.Add(musicVideo.Artist);
  1076. }
  1077. }
  1078. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1079. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1080. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1081. if (thumbItem == null)
  1082. {
  1083. if (episode != null)
  1084. {
  1085. var series = episode.Series;
  1086. if (series != null && series.HasImage(ImageType.Thumb))
  1087. {
  1088. thumbItem = series;
  1089. }
  1090. }
  1091. }
  1092. if (backropItem == null)
  1093. {
  1094. if (episode != null)
  1095. {
  1096. var series = episode.Series;
  1097. if (series != null && series.HasImage(ImageType.Backdrop))
  1098. {
  1099. backropItem = series;
  1100. }
  1101. }
  1102. }
  1103. if (backropItem == null)
  1104. {
  1105. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1106. }
  1107. if (thumbItem == null)
  1108. {
  1109. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1110. }
  1111. if (logoItem == null)
  1112. {
  1113. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1114. }
  1115. if (thumbItem != null)
  1116. {
  1117. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1118. info.ThumbItemId = GetDtoId(thumbItem);
  1119. }
  1120. if (backropItem != null)
  1121. {
  1122. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1123. info.BackdropItemId = GetDtoId(backropItem);
  1124. }
  1125. if (logoItem != null)
  1126. {
  1127. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1128. info.LogoItemId = GetDtoId(logoItem);
  1129. }
  1130. if (chapterOwner != null)
  1131. {
  1132. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1133. info.Chapters = _itemRepo.GetChapters(chapterOwner.Id).Select(i => _dtoService.GetChapterInfoDto(i, chapterOwner)).ToList();
  1134. }
  1135. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  1136. {
  1137. info.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  1138. {
  1139. ItemId = new Guid(mediaSourceId)
  1140. }).ToList();
  1141. }
  1142. return info;
  1143. }
  1144. private string GetImageCacheTag(BaseItem item, ImageType type)
  1145. {
  1146. try
  1147. {
  1148. return _imageProcessor.GetImageCacheTag(item, type);
  1149. }
  1150. catch (Exception ex)
  1151. {
  1152. _logger.ErrorException("Error getting {0} image info", ex, type);
  1153. return null;
  1154. }
  1155. }
  1156. private string GetDtoId(BaseItem item)
  1157. {
  1158. return _dtoService.GetDtoId(item);
  1159. }
  1160. public void ReportNowViewingItem(string sessionId, string itemId)
  1161. {
  1162. var item = _libraryManager.GetItemById(new Guid(itemId));
  1163. var info = GetItemInfo(item, null, null);
  1164. ReportNowViewingItem(sessionId, info);
  1165. }
  1166. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1167. {
  1168. var session = GetSession(sessionId);
  1169. session.NowViewingItem = item;
  1170. }
  1171. }
  1172. }