SessionManager.cs 58 KB

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