SessionManager.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  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, false);
  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. /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
  593. /// <returns>SessionInfo.</returns>
  594. /// <exception cref="ResourceNotFoundException"></exception>
  595. private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
  596. {
  597. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  598. if (session == null && throwOnMissing)
  599. {
  600. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  601. }
  602. return session;
  603. }
  604. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  605. {
  606. var generalCommand = new GeneralCommand
  607. {
  608. Name = GeneralCommandType.DisplayMessage.ToString()
  609. };
  610. generalCommand.Arguments["Header"] = command.Header;
  611. generalCommand.Arguments["Text"] = command.Text;
  612. if (command.TimeoutMs.HasValue)
  613. {
  614. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  615. }
  616. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  617. }
  618. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  619. {
  620. var session = GetSession(sessionId);
  621. var controllingSession = GetSession(controllingSessionId);
  622. AssertCanControl(session, controllingSession);
  623. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  624. }
  625. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  626. {
  627. var session = GetSession(sessionId);
  628. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  629. List<BaseItem> items;
  630. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  631. {
  632. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  633. .Where(i => i.LocationType != LocationType.Virtual)
  634. .ToList();
  635. command.PlayCommand = PlayCommand.PlayNow;
  636. }
  637. else
  638. {
  639. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  640. .Where(i => i.LocationType != LocationType.Virtual)
  641. .ToList();
  642. }
  643. if (command.PlayCommand == PlayCommand.PlayShuffle)
  644. {
  645. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  646. command.PlayCommand = PlayCommand.PlayNow;
  647. }
  648. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  649. if (user != null)
  650. {
  651. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  652. {
  653. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  654. }
  655. }
  656. if (command.PlayCommand != PlayCommand.PlayNow)
  657. {
  658. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  659. {
  660. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  661. }
  662. }
  663. else
  664. {
  665. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  666. {
  667. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  668. }
  669. }
  670. var controllingSession = GetSession(controllingSessionId);
  671. AssertCanControl(session, controllingSession);
  672. if (controllingSession.UserId.HasValue)
  673. {
  674. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  675. }
  676. return session.SessionController.SendPlayCommand(command, cancellationToken);
  677. }
  678. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  679. {
  680. var item = _libraryManager.GetItemById(new Guid(id));
  681. if (item.IsFolder)
  682. {
  683. var folder = (Folder)item;
  684. var items = user == null ? folder.RecursiveChildren :
  685. folder.GetRecursiveChildren(user);
  686. items = items.Where(i => !i.IsFolder);
  687. items = items.OrderBy(i => i.SortName);
  688. return items;
  689. }
  690. return new[] { item };
  691. }
  692. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  693. {
  694. var item = _libraryManager.GetItemById(new Guid(id));
  695. var audio = item as Audio;
  696. if (audio != null)
  697. {
  698. return _musicManager.GetInstantMixFromSong(audio, user);
  699. }
  700. var artist = item as MusicArtist;
  701. if (artist != null)
  702. {
  703. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  704. }
  705. var album = item as MusicAlbum;
  706. if (album != null)
  707. {
  708. return _musicManager.GetInstantMixFromAlbum(album, user);
  709. }
  710. var genre = item as MusicGenre;
  711. if (genre != null)
  712. {
  713. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  714. }
  715. return new BaseItem[] { };
  716. }
  717. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  718. {
  719. var generalCommand = new GeneralCommand
  720. {
  721. Name = GeneralCommandType.DisplayContent.ToString()
  722. };
  723. generalCommand.Arguments["ItemId"] = command.ItemId;
  724. generalCommand.Arguments["ItemName"] = command.ItemName;
  725. generalCommand.Arguments["ItemType"] = command.ItemType;
  726. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  727. }
  728. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  729. {
  730. var session = GetSession(sessionId);
  731. var controllingSession = GetSession(controllingSessionId);
  732. AssertCanControl(session, controllingSession);
  733. if (controllingSession.UserId.HasValue)
  734. {
  735. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  736. }
  737. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  738. }
  739. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  740. {
  741. if (session == null)
  742. {
  743. throw new ArgumentNullException("session");
  744. }
  745. if (controllingSession == null)
  746. {
  747. throw new ArgumentNullException("controllingSession");
  748. }
  749. }
  750. /// <summary>
  751. /// Sends the restart required message.
  752. /// </summary>
  753. /// <param name="cancellationToken">The cancellation token.</param>
  754. /// <returns>Task.</returns>
  755. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  756. {
  757. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  758. var info = _appHost.GetSystemInfo();
  759. var tasks = sessions.Select(session => Task.Run(async () =>
  760. {
  761. try
  762. {
  763. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  764. }
  765. catch (Exception ex)
  766. {
  767. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  768. }
  769. }, cancellationToken));
  770. return Task.WhenAll(tasks);
  771. }
  772. /// <summary>
  773. /// Sends the server shutdown notification.
  774. /// </summary>
  775. /// <param name="cancellationToken">The cancellation token.</param>
  776. /// <returns>Task.</returns>
  777. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  778. {
  779. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  780. var tasks = sessions.Select(session => Task.Run(async () =>
  781. {
  782. try
  783. {
  784. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  785. }
  786. catch (Exception ex)
  787. {
  788. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  789. }
  790. }, cancellationToken));
  791. return Task.WhenAll(tasks);
  792. }
  793. /// <summary>
  794. /// Sends the server restart notification.
  795. /// </summary>
  796. /// <param name="cancellationToken">The cancellation token.</param>
  797. /// <returns>Task.</returns>
  798. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  799. {
  800. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  801. var tasks = sessions.Select(session => Task.Run(async () =>
  802. {
  803. try
  804. {
  805. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  806. }
  807. catch (Exception ex)
  808. {
  809. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  810. }
  811. }, cancellationToken));
  812. return Task.WhenAll(tasks);
  813. }
  814. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  815. {
  816. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  817. var dto = GetSessionInfoDto(sessionInfo);
  818. var tasks = sessions.Select(session => Task.Run(async () =>
  819. {
  820. try
  821. {
  822. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  823. }
  824. catch (Exception ex)
  825. {
  826. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  827. }
  828. }, cancellationToken));
  829. return Task.WhenAll(tasks);
  830. }
  831. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  832. {
  833. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  834. var dto = GetSessionInfoDto(sessionInfo);
  835. var tasks = sessions.Select(session => Task.Run(async () =>
  836. {
  837. try
  838. {
  839. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  840. }
  841. catch (Exception ex)
  842. {
  843. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  844. }
  845. }, cancellationToken));
  846. return Task.WhenAll(tasks);
  847. }
  848. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  849. {
  850. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  851. var dto = GetSessionInfoDto(sessionInfo);
  852. var tasks = sessions.Select(session => Task.Run(async () =>
  853. {
  854. try
  855. {
  856. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  857. }
  858. catch (Exception ex)
  859. {
  860. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  861. }
  862. }, cancellationToken));
  863. return Task.WhenAll(tasks);
  864. }
  865. /// <summary>
  866. /// Adds the additional user.
  867. /// </summary>
  868. /// <param name="sessionId">The session identifier.</param>
  869. /// <param name="userId">The user identifier.</param>
  870. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  871. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  872. public void AddAdditionalUser(string sessionId, Guid userId)
  873. {
  874. var session = GetSession(sessionId);
  875. if (!session.UserId.HasValue)
  876. {
  877. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  878. }
  879. if (session.UserId.Value == userId)
  880. {
  881. throw new ArgumentException("The requested user is already the primary user of the session.");
  882. }
  883. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  884. {
  885. var user = _userManager.GetUserById(userId);
  886. session.AdditionalUsers.Add(new SessionUserInfo
  887. {
  888. UserId = userId.ToString("N"),
  889. UserName = user.Name
  890. });
  891. }
  892. }
  893. /// <summary>
  894. /// Removes the additional user.
  895. /// </summary>
  896. /// <param name="sessionId">The session identifier.</param>
  897. /// <param name="userId">The user identifier.</param>
  898. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  899. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  900. public void RemoveAdditionalUser(string sessionId, Guid userId)
  901. {
  902. var session = GetSession(sessionId);
  903. if (!session.UserId.HasValue)
  904. {
  905. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  906. }
  907. if (session.UserId.Value == userId)
  908. {
  909. throw new ArgumentException("The requested user is already the primary user of the session.");
  910. }
  911. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  912. if (user != null)
  913. {
  914. session.AdditionalUsers.Remove(user);
  915. }
  916. }
  917. /// <summary>
  918. /// Authenticates the new session.
  919. /// </summary>
  920. /// <param name="user">The user.</param>
  921. /// <param name="password">The password.</param>
  922. /// <param name="clientType">Type of the client.</param>
  923. /// <param name="appVersion">The application version.</param>
  924. /// <param name="deviceId">The device identifier.</param>
  925. /// <param name="deviceName">Name of the device.</param>
  926. /// <param name="remoteEndPoint">The remote end point.</param>
  927. /// <returns>Task{SessionInfo}.</returns>
  928. /// <exception cref="UnauthorizedAccessException"></exception>
  929. public async Task<SessionInfo> AuthenticateNewSession(User user, string password, string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint)
  930. {
  931. var result = await _userManager.AuthenticateUser(user, password).ConfigureAwait(false);
  932. if (!result)
  933. {
  934. throw new UnauthorizedAccessException("Invalid user or password entered.");
  935. }
  936. return await LogSessionActivity(clientType, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
  937. }
  938. /// <summary>
  939. /// Reports the capabilities.
  940. /// </summary>
  941. /// <param name="sessionId">The session identifier.</param>
  942. /// <param name="capabilities">The capabilities.</param>
  943. public void ReportCapabilities(string sessionId, SessionCapabilities capabilities)
  944. {
  945. var session = GetSession(sessionId);
  946. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  947. session.SupportedCommands = capabilities.SupportedCommands;
  948. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  949. {
  950. var postUrl = string.Format("http://{0}{1}", session.RemoteEndPoint, capabilities.MessageCallbackUrl);
  951. var controller = session.SessionController as HttpSessionController;
  952. if (controller == null)
  953. {
  954. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, postUrl, this);
  955. }
  956. }
  957. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  958. {
  959. SessionInfo = session
  960. }, _logger);
  961. }
  962. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  963. {
  964. var dto = new SessionInfoDto
  965. {
  966. Client = session.Client,
  967. DeviceId = session.DeviceId,
  968. DeviceName = session.DeviceName,
  969. Id = session.Id,
  970. LastActivityDate = session.LastActivityDate,
  971. NowPlayingPositionTicks = session.PlayState.PositionTicks,
  972. IsPaused = session.PlayState.IsPaused,
  973. IsMuted = session.PlayState.IsMuted,
  974. NowViewingItem = session.NowViewingItem,
  975. ApplicationVersion = session.ApplicationVersion,
  976. CanSeek = session.PlayState.CanSeek,
  977. QueueableMediaTypes = session.QueueableMediaTypes,
  978. PlayableMediaTypes = session.PlayableMediaTypes,
  979. RemoteEndPoint = session.RemoteEndPoint,
  980. AdditionalUsers = session.AdditionalUsers,
  981. SupportedCommands = session.SupportedCommands,
  982. UserName = session.UserName,
  983. NowPlayingItem = session.NowPlayingItem,
  984. SupportsRemoteControl = session.SupportsMediaControl,
  985. PlayState = session.PlayState
  986. };
  987. if (session.UserId.HasValue)
  988. {
  989. dto.UserId = session.UserId.Value.ToString("N");
  990. var user = _userManager.GetUserById(session.UserId.Value);
  991. if (user != null)
  992. {
  993. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  994. }
  995. }
  996. return dto;
  997. }
  998. /// <summary>
  999. /// Converts a BaseItem to a BaseItemInfo
  1000. /// </summary>
  1001. /// <param name="item">The item.</param>
  1002. /// <param name="chapterOwner">The chapter owner.</param>
  1003. /// <param name="mediaSourceId">The media source identifier.</param>
  1004. /// <returns>BaseItemInfo.</returns>
  1005. /// <exception cref="System.ArgumentNullException">item</exception>
  1006. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, string mediaSourceId)
  1007. {
  1008. if (item == null)
  1009. {
  1010. throw new ArgumentNullException("item");
  1011. }
  1012. var info = new BaseItemInfo
  1013. {
  1014. Id = GetDtoId(item),
  1015. Name = item.Name,
  1016. MediaType = item.MediaType,
  1017. Type = item.GetClientTypeName(),
  1018. RunTimeTicks = item.RunTimeTicks,
  1019. IndexNumber = item.IndexNumber,
  1020. ParentIndexNumber = item.ParentIndexNumber,
  1021. PremiereDate = item.PremiereDate,
  1022. ProductionYear = item.ProductionYear
  1023. };
  1024. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1025. if (info.PrimaryImageTag != null)
  1026. {
  1027. info.PrimaryImageItemId = GetDtoId(item);
  1028. }
  1029. var episode = item as Episode;
  1030. if (episode != null)
  1031. {
  1032. info.IndexNumberEnd = episode.IndexNumberEnd;
  1033. }
  1034. var hasSeries = item as IHasSeries;
  1035. if (hasSeries != null)
  1036. {
  1037. info.SeriesName = hasSeries.SeriesName;
  1038. }
  1039. var recording = item as ILiveTvRecording;
  1040. if (recording != null && recording.RecordingInfo != null)
  1041. {
  1042. if (recording.RecordingInfo.IsSeries)
  1043. {
  1044. info.Name = recording.RecordingInfo.EpisodeTitle;
  1045. info.SeriesName = recording.RecordingInfo.Name;
  1046. if (string.IsNullOrWhiteSpace(info.Name))
  1047. {
  1048. info.Name = recording.RecordingInfo.Name;
  1049. }
  1050. }
  1051. }
  1052. var audio = item as Audio;
  1053. if (audio != null)
  1054. {
  1055. info.Album = audio.Album;
  1056. info.Artists = audio.Artists;
  1057. if (info.PrimaryImageTag == null)
  1058. {
  1059. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1060. if (album != null && album.HasImage(ImageType.Primary))
  1061. {
  1062. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1063. if (info.PrimaryImageTag != null)
  1064. {
  1065. info.PrimaryImageItemId = GetDtoId(album);
  1066. }
  1067. }
  1068. }
  1069. }
  1070. var musicVideo = item as MusicVideo;
  1071. if (musicVideo != null)
  1072. {
  1073. info.Album = musicVideo.Album;
  1074. if (!string.IsNullOrWhiteSpace(musicVideo.Artist))
  1075. {
  1076. info.Artists.Add(musicVideo.Artist);
  1077. }
  1078. }
  1079. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1080. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1081. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1082. if (thumbItem == null)
  1083. {
  1084. if (episode != null)
  1085. {
  1086. var series = episode.Series;
  1087. if (series != null && series.HasImage(ImageType.Thumb))
  1088. {
  1089. thumbItem = series;
  1090. }
  1091. }
  1092. }
  1093. if (backropItem == null)
  1094. {
  1095. if (episode != null)
  1096. {
  1097. var series = episode.Series;
  1098. if (series != null && series.HasImage(ImageType.Backdrop))
  1099. {
  1100. backropItem = series;
  1101. }
  1102. }
  1103. }
  1104. if (backropItem == null)
  1105. {
  1106. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1107. }
  1108. if (thumbItem == null)
  1109. {
  1110. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1111. }
  1112. if (logoItem == null)
  1113. {
  1114. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1115. }
  1116. if (thumbItem != null)
  1117. {
  1118. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1119. info.ThumbItemId = GetDtoId(thumbItem);
  1120. }
  1121. if (backropItem != null)
  1122. {
  1123. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1124. info.BackdropItemId = GetDtoId(backropItem);
  1125. }
  1126. if (logoItem != null)
  1127. {
  1128. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1129. info.LogoItemId = GetDtoId(logoItem);
  1130. }
  1131. if (chapterOwner != null)
  1132. {
  1133. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1134. info.Chapters = _itemRepo.GetChapters(chapterOwner.Id).Select(i => _dtoService.GetChapterInfoDto(i, chapterOwner)).ToList();
  1135. }
  1136. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  1137. {
  1138. info.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  1139. {
  1140. ItemId = new Guid(mediaSourceId)
  1141. }).ToList();
  1142. }
  1143. return info;
  1144. }
  1145. private string GetImageCacheTag(BaseItem item, ImageType type)
  1146. {
  1147. try
  1148. {
  1149. return _imageProcessor.GetImageCacheTag(item, type);
  1150. }
  1151. catch (Exception ex)
  1152. {
  1153. _logger.ErrorException("Error getting {0} image info", ex, type);
  1154. return null;
  1155. }
  1156. }
  1157. private string GetDtoId(BaseItem item)
  1158. {
  1159. return _dtoService.GetDtoId(item);
  1160. }
  1161. public void ReportNowViewingItem(string sessionId, string itemId)
  1162. {
  1163. var item = _libraryManager.GetItemById(new Guid(itemId));
  1164. var info = GetItemInfo(item, null, null);
  1165. ReportNowViewingItem(sessionId, info);
  1166. }
  1167. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1168. {
  1169. var session = GetSession(sessionId);
  1170. session.NowViewingItem = item;
  1171. }
  1172. }
  1173. }