SessionManager.cs 55 KB

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