SessionManager.cs 60 KB

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