SessionManager.cs 54 KB

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