SessionManager.cs 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  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="appName">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 appName,
  186. string appVersion,
  187. string deviceId,
  188. string deviceName,
  189. string remoteEndPoint,
  190. User user)
  191. {
  192. if (string.IsNullOrEmpty(appName))
  193. {
  194. throw new ArgumentNullException("appName");
  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 session = await GetSessionInfo(appName, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false);
  210. session.LastActivityDate = activityDate;
  211. if (user == null)
  212. {
  213. return session;
  214. }
  215. var lastActivityDate = user.LastActivityDate;
  216. user.LastActivityDate = activityDate;
  217. // Don't log in the db anymore frequently than 10 seconds
  218. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  219. {
  220. return session;
  221. }
  222. // Save this directly. No need to fire off all the events for this.
  223. await _userRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  224. EventHelper.FireEventIfNotNull(SessionActivity, this, new SessionEventArgs
  225. {
  226. SessionInfo = session
  227. }, _logger);
  228. return session;
  229. }
  230. public async void ReportSessionEnded(string sessionId)
  231. {
  232. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  233. try
  234. {
  235. var session = GetSession(sessionId, false);
  236. if (session != null)
  237. {
  238. var key = GetSessionKey(session.Client, session.DeviceId);
  239. SessionInfo removed;
  240. if (_activeConnections.TryRemove(key, out removed))
  241. {
  242. OnSessionEnded(removed);
  243. }
  244. }
  245. }
  246. finally
  247. {
  248. _sessionLock.Release();
  249. }
  250. }
  251. /// <summary>
  252. /// Updates the now playing item id.
  253. /// </summary>
  254. /// <param name="session">The session.</param>
  255. /// <param name="info">The information.</param>
  256. /// <param name="libraryItem">The library item.</param>
  257. private void UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem)
  258. {
  259. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  260. {
  261. info.MediaSourceId = info.ItemId;
  262. }
  263. if (!string.IsNullOrWhiteSpace(info.ItemId) && info.Item == null && libraryItem != null)
  264. {
  265. var runtimeTicks = libraryItem.RunTimeTicks;
  266. if (!string.Equals(info.ItemId, info.MediaSourceId) &&
  267. !string.IsNullOrWhiteSpace(info.MediaSourceId))
  268. {
  269. var runtimeItem = _libraryManager.GetItemById(new Guid(info.MediaSourceId)) ??
  270. _libraryManager.GetItemById(info.ItemId);
  271. runtimeTicks = runtimeItem.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 appName, string deviceId)
  312. {
  313. return appName + deviceId;
  314. }
  315. /// <summary>
  316. /// Gets the connection.
  317. /// </summary>
  318. /// <param name="appName">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="user">The user.</param>
  324. /// <returns>SessionInfo.</returns>
  325. private async Task<SessionInfo> GetSessionInfo(string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
  326. {
  327. var key = GetSessionKey(appName, deviceId);
  328. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  329. var userId = user == null ? (Guid?)null : user.Id;
  330. var username = user == null ? null : user.Name;
  331. try
  332. {
  333. SessionInfo sessionInfo;
  334. DeviceInfo device = null;
  335. if (!_activeConnections.TryGetValue(key, out sessionInfo))
  336. {
  337. sessionInfo = new SessionInfo
  338. {
  339. Client = appName,
  340. DeviceId = deviceId,
  341. ApplicationVersion = appVersion,
  342. Id = key.GetMD5().ToString("N")
  343. };
  344. sessionInfo.DeviceName = deviceName;
  345. sessionInfo.UserId = userId;
  346. sessionInfo.UserName = username;
  347. sessionInfo.RemoteEndPoint = remoteEndPoint;
  348. OnSessionStarted(sessionInfo);
  349. _activeConnections.TryAdd(key, sessionInfo);
  350. if (!string.IsNullOrEmpty(deviceId))
  351. {
  352. var userIdString = userId.HasValue ? userId.Value.ToString("N") : null;
  353. device = await _deviceManager.RegisterDevice(deviceId, deviceName, appName, appVersion, userIdString).ConfigureAwait(false);
  354. }
  355. }
  356. device = device ?? _deviceManager.GetDevice(deviceId);
  357. if (!string.IsNullOrEmpty(device.CustomName))
  358. {
  359. deviceName = device.CustomName;
  360. }
  361. sessionInfo.DeviceName = deviceName;
  362. sessionInfo.UserId = userId;
  363. sessionInfo.UserName = username;
  364. sessionInfo.RemoteEndPoint = remoteEndPoint;
  365. sessionInfo.ApplicationVersion = appVersion;
  366. if (!userId.HasValue)
  367. {
  368. sessionInfo.AdditionalUsers.Clear();
  369. }
  370. if (sessionInfo.SessionController == null)
  371. {
  372. sessionInfo.SessionController = _sessionFactories
  373. .Select(i => i.GetSessionController(sessionInfo))
  374. .FirstOrDefault(i => i != null);
  375. }
  376. return sessionInfo;
  377. }
  378. finally
  379. {
  380. _sessionLock.Release();
  381. }
  382. }
  383. private List<User> GetUsers(SessionInfo session)
  384. {
  385. var users = new List<User>();
  386. if (session.UserId.HasValue)
  387. {
  388. var user = _userManager.GetUserById(session.UserId.Value);
  389. if (user == null)
  390. {
  391. throw new InvalidOperationException("User not found");
  392. }
  393. users.Add(user);
  394. var additionalUsers = session.AdditionalUsers
  395. .Select(i => _userManager.GetUserById(i.UserId))
  396. .Where(i => i != null);
  397. users.AddRange(additionalUsers);
  398. }
  399. return users;
  400. }
  401. private Timer _idleTimer;
  402. private void StartIdleCheckTimer()
  403. {
  404. if (_idleTimer == null)
  405. {
  406. _idleTimer = new Timer(CheckForIdlePlayback, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
  407. }
  408. }
  409. private void StopIdleCheckTimer()
  410. {
  411. if (_idleTimer != null)
  412. {
  413. _idleTimer.Dispose();
  414. _idleTimer = null;
  415. }
  416. }
  417. private async void CheckForIdlePlayback(object state)
  418. {
  419. var playingSessions = Sessions.Where(i => i.NowPlayingItem != null)
  420. .ToList();
  421. if (playingSessions.Count > 0)
  422. {
  423. var idle = playingSessions
  424. .Where(i => (DateTime.UtcNow - i.LastPlaybackCheckIn).TotalMinutes > 5)
  425. .ToList();
  426. foreach (var session in idle)
  427. {
  428. _logger.Debug("Session {0} has gone idle while playing", session.Id);
  429. try
  430. {
  431. await OnPlaybackStopped(new PlaybackStopInfo
  432. {
  433. Item = session.NowPlayingItem,
  434. ItemId = (session.NowPlayingItem == null ? null : session.NowPlayingItem.Id),
  435. SessionId = session.Id,
  436. MediaSourceId = (session.PlayState == null ? null : session.PlayState.MediaSourceId),
  437. PositionTicks = session.PlayState == null ? null : session.PlayState.PositionTicks
  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) && info.Item == null && 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. private SessionInfo GetSessionToRemoteControl(string sessionId)
  665. {
  666. // Accept either device id or session id
  667. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  668. if (session == null)
  669. {
  670. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  671. }
  672. return session;
  673. }
  674. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  675. {
  676. var generalCommand = new GeneralCommand
  677. {
  678. Name = GeneralCommandType.DisplayMessage.ToString()
  679. };
  680. generalCommand.Arguments["Header"] = command.Header;
  681. generalCommand.Arguments["Text"] = command.Text;
  682. if (command.TimeoutMs.HasValue)
  683. {
  684. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  685. }
  686. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  687. }
  688. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  689. {
  690. var session = GetSessionToRemoteControl(sessionId);
  691. var controllingSession = GetSession(controllingSessionId);
  692. AssertCanControl(session, controllingSession);
  693. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  694. }
  695. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  696. {
  697. var session = GetSessionToRemoteControl(sessionId);
  698. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  699. List<BaseItem> items;
  700. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  701. {
  702. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  703. .Where(i => i.LocationType != LocationType.Virtual)
  704. .ToList();
  705. command.PlayCommand = PlayCommand.PlayNow;
  706. }
  707. else
  708. {
  709. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  710. .Where(i => i.LocationType != LocationType.Virtual)
  711. .ToList();
  712. }
  713. if (command.PlayCommand == PlayCommand.PlayShuffle)
  714. {
  715. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  716. command.PlayCommand = PlayCommand.PlayNow;
  717. }
  718. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  719. if (user != null)
  720. {
  721. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  722. {
  723. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  724. }
  725. }
  726. if (command.PlayCommand != PlayCommand.PlayNow)
  727. {
  728. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  729. {
  730. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id));
  731. }
  732. }
  733. else
  734. {
  735. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  736. {
  737. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id));
  738. }
  739. }
  740. var controllingSession = GetSession(controllingSessionId);
  741. AssertCanControl(session, controllingSession);
  742. if (controllingSession.UserId.HasValue)
  743. {
  744. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  745. }
  746. return session.SessionController.SendPlayCommand(command, cancellationToken);
  747. }
  748. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  749. {
  750. var item = _libraryManager.GetItemById(new Guid(id));
  751. var byName = item as IItemByName;
  752. if (byName != null)
  753. {
  754. var itemFilter = byName.GetItemFilter();
  755. var items = user == null ?
  756. _libraryManager.RootFolder.GetRecursiveChildren(i => !i.IsFolder && itemFilter(i)) :
  757. user.RootFolder.GetRecursiveChildren(user, i => !i.IsFolder && itemFilter(i));
  758. return FilterToSingleMediaType(items)
  759. .OrderBy(i => i.SortName);
  760. }
  761. if (item.IsFolder)
  762. {
  763. var folder = (Folder)item;
  764. var items = user == null ?
  765. folder.GetRecursiveChildren(i => !i.IsFolder) :
  766. folder.GetRecursiveChildren(user, i => !i.IsFolder);
  767. return FilterToSingleMediaType(items)
  768. .OrderBy(i => i.SortName);
  769. }
  770. return new[] { item };
  771. }
  772. private IEnumerable<BaseItem> FilterToSingleMediaType(IEnumerable<BaseItem> items)
  773. {
  774. return items
  775. .Where(i => !string.IsNullOrWhiteSpace(i.MediaType))
  776. .ToLookup(i => i.MediaType, StringComparer.OrdinalIgnoreCase)
  777. .OrderByDescending(i => i.Count())
  778. .FirstOrDefault();
  779. }
  780. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  781. {
  782. var item = _libraryManager.GetItemById(id);
  783. return _musicManager.GetInstantMixFromItem(item, user);
  784. }
  785. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  786. {
  787. var generalCommand = new GeneralCommand
  788. {
  789. Name = GeneralCommandType.DisplayContent.ToString()
  790. };
  791. generalCommand.Arguments["ItemId"] = command.ItemId;
  792. generalCommand.Arguments["ItemName"] = command.ItemName;
  793. generalCommand.Arguments["ItemType"] = command.ItemType;
  794. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  795. }
  796. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  797. {
  798. var session = GetSessionToRemoteControl(sessionId);
  799. var controllingSession = GetSession(controllingSessionId);
  800. AssertCanControl(session, controllingSession);
  801. if (controllingSession.UserId.HasValue)
  802. {
  803. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  804. }
  805. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  806. }
  807. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  808. {
  809. if (session == null)
  810. {
  811. throw new ArgumentNullException("session");
  812. }
  813. if (controllingSession == null)
  814. {
  815. throw new ArgumentNullException("controllingSession");
  816. }
  817. }
  818. /// <summary>
  819. /// Sends the restart required message.
  820. /// </summary>
  821. /// <param name="cancellationToken">The cancellation token.</param>
  822. /// <returns>Task.</returns>
  823. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  824. {
  825. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  826. var info = _appHost.GetSystemInfo();
  827. var tasks = sessions.Select(session => Task.Run(async () =>
  828. {
  829. try
  830. {
  831. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  832. }
  833. catch (Exception ex)
  834. {
  835. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  836. }
  837. }, cancellationToken));
  838. return Task.WhenAll(tasks);
  839. }
  840. /// <summary>
  841. /// Sends the server shutdown notification.
  842. /// </summary>
  843. /// <param name="cancellationToken">The cancellation token.</param>
  844. /// <returns>Task.</returns>
  845. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  846. {
  847. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  848. var tasks = sessions.Select(session => Task.Run(async () =>
  849. {
  850. try
  851. {
  852. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  853. }
  854. catch (Exception ex)
  855. {
  856. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  857. }
  858. }, cancellationToken));
  859. return Task.WhenAll(tasks);
  860. }
  861. /// <summary>
  862. /// Sends the server restart notification.
  863. /// </summary>
  864. /// <param name="cancellationToken">The cancellation token.</param>
  865. /// <returns>Task.</returns>
  866. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  867. {
  868. _logger.Debug("Beginning SendServerRestartNotification");
  869. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  870. var tasks = sessions.Select(session => Task.Run(async () =>
  871. {
  872. try
  873. {
  874. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  875. }
  876. catch (Exception ex)
  877. {
  878. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  879. }
  880. }, cancellationToken));
  881. return Task.WhenAll(tasks);
  882. }
  883. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  884. {
  885. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  886. var dto = GetSessionInfoDto(sessionInfo);
  887. var tasks = sessions.Select(session => Task.Run(async () =>
  888. {
  889. try
  890. {
  891. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  892. }
  893. catch (Exception ex)
  894. {
  895. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  896. }
  897. }, cancellationToken));
  898. return Task.WhenAll(tasks);
  899. }
  900. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  901. {
  902. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  903. var dto = GetSessionInfoDto(sessionInfo);
  904. var tasks = sessions.Select(session => Task.Run(async () =>
  905. {
  906. try
  907. {
  908. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  909. }
  910. catch (Exception ex)
  911. {
  912. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  913. }
  914. }, cancellationToken));
  915. return Task.WhenAll(tasks);
  916. }
  917. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  918. {
  919. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  920. var dto = GetSessionInfoDto(sessionInfo);
  921. var tasks = sessions.Select(session => Task.Run(async () =>
  922. {
  923. try
  924. {
  925. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  926. }
  927. catch (Exception ex)
  928. {
  929. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  930. }
  931. }, cancellationToken));
  932. return Task.WhenAll(tasks);
  933. }
  934. /// <summary>
  935. /// Adds the additional user.
  936. /// </summary>
  937. /// <param name="sessionId">The session identifier.</param>
  938. /// <param name="userId">The user identifier.</param>
  939. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  940. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  941. public void AddAdditionalUser(string sessionId, Guid userId)
  942. {
  943. var session = GetSession(sessionId);
  944. if (session.UserId.HasValue && session.UserId.Value == userId)
  945. {
  946. throw new ArgumentException("The requested user is already the primary user of the session.");
  947. }
  948. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  949. {
  950. var user = _userManager.GetUserById(userId);
  951. session.AdditionalUsers.Add(new SessionUserInfo
  952. {
  953. UserId = userId.ToString("N"),
  954. UserName = user.Name
  955. });
  956. }
  957. }
  958. /// <summary>
  959. /// Removes the additional user.
  960. /// </summary>
  961. /// <param name="sessionId">The session identifier.</param>
  962. /// <param name="userId">The user identifier.</param>
  963. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  964. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  965. public void RemoveAdditionalUser(string sessionId, Guid userId)
  966. {
  967. var session = GetSession(sessionId);
  968. if (session.UserId.HasValue && session.UserId.Value == userId)
  969. {
  970. throw new ArgumentException("The requested user is already the primary user of the session.");
  971. }
  972. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  973. if (user != null)
  974. {
  975. session.AdditionalUsers.Remove(user);
  976. }
  977. }
  978. /// <summary>
  979. /// Authenticates the new session.
  980. /// </summary>
  981. /// <param name="request">The request.</param>
  982. /// <returns>Task{SessionInfo}.</returns>
  983. public async Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  984. {
  985. var user = _userManager.Users
  986. .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
  987. if (user != null && !string.IsNullOrWhiteSpace(request.DeviceId))
  988. {
  989. if (!_deviceManager.CanAccessDevice(user.Id.ToString("N"), request.DeviceId))
  990. {
  991. throw new UnauthorizedAccessException("User is not allowed access from this device.");
  992. }
  993. }
  994. var result = await _userManager.AuthenticateUser(request.Username, request.PasswordSha1, request.PasswordMd5, request.RemoteEndPoint).ConfigureAwait(false);
  995. if (!result)
  996. {
  997. EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  998. throw new UnauthorizedAccessException("Invalid user or password entered.");
  999. }
  1000. var token = await GetAuthorizationToken(user.Id.ToString("N"), request.DeviceId, request.App, request.DeviceName).ConfigureAwait(false);
  1001. EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1002. var session = await LogSessionActivity(request.App,
  1003. request.AppVersion,
  1004. request.DeviceId,
  1005. request.DeviceName,
  1006. request.RemoteEndPoint,
  1007. user)
  1008. .ConfigureAwait(false);
  1009. return new AuthenticationResult
  1010. {
  1011. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1012. SessionInfo = GetSessionInfoDto(session),
  1013. AccessToken = token,
  1014. ServerId = _appHost.SystemId
  1015. };
  1016. }
  1017. private async Task<string> GetAuthorizationToken(string userId, string deviceId, string app, string deviceName)
  1018. {
  1019. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1020. {
  1021. DeviceId = deviceId,
  1022. IsActive = true,
  1023. UserId = userId,
  1024. Limit = 1
  1025. });
  1026. if (existing.Items.Length > 0)
  1027. {
  1028. _logger.Debug("Reissuing access token");
  1029. return existing.Items[0].AccessToken;
  1030. }
  1031. var newToken = new AuthenticationInfo
  1032. {
  1033. AppName = app,
  1034. DateCreated = DateTime.UtcNow,
  1035. DeviceId = deviceId,
  1036. DeviceName = deviceName,
  1037. UserId = userId,
  1038. IsActive = true,
  1039. AccessToken = Guid.NewGuid().ToString("N")
  1040. };
  1041. _logger.Debug("Creating new access token for user {0}", userId);
  1042. await _authRepo.Create(newToken, CancellationToken.None).ConfigureAwait(false);
  1043. return newToken.AccessToken;
  1044. }
  1045. public async Task Logout(string accessToken)
  1046. {
  1047. if (string.IsNullOrWhiteSpace(accessToken))
  1048. {
  1049. throw new ArgumentNullException("accessToken");
  1050. }
  1051. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1052. {
  1053. Limit = 1,
  1054. AccessToken = accessToken
  1055. }).Items.FirstOrDefault();
  1056. if (existing != null)
  1057. {
  1058. existing.IsActive = false;
  1059. await _authRepo.Update(existing, CancellationToken.None).ConfigureAwait(false);
  1060. var sessions = Sessions
  1061. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1062. .ToList();
  1063. foreach (var session in sessions)
  1064. {
  1065. try
  1066. {
  1067. ReportSessionEnded(session.Id);
  1068. }
  1069. catch (Exception ex)
  1070. {
  1071. _logger.ErrorException("Error reporting session ended", ex);
  1072. }
  1073. }
  1074. }
  1075. }
  1076. public async Task RevokeUserTokens(string userId)
  1077. {
  1078. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1079. {
  1080. IsActive = true,
  1081. UserId = userId
  1082. });
  1083. foreach (var info in existing.Items)
  1084. {
  1085. await Logout(info.AccessToken).ConfigureAwait(false);
  1086. }
  1087. }
  1088. public Task RevokeToken(string token)
  1089. {
  1090. return Logout(token);
  1091. }
  1092. /// <summary>
  1093. /// Reports the capabilities.
  1094. /// </summary>
  1095. /// <param name="sessionId">The session identifier.</param>
  1096. /// <param name="capabilities">The capabilities.</param>
  1097. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1098. {
  1099. var session = GetSession(sessionId);
  1100. ReportCapabilities(session, capabilities, true);
  1101. }
  1102. private async void ReportCapabilities(SessionInfo session,
  1103. ClientCapabilities capabilities,
  1104. bool saveCapabilities)
  1105. {
  1106. session.Capabilities = capabilities;
  1107. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1108. {
  1109. var controller = session.SessionController as HttpSessionController;
  1110. if (controller == null)
  1111. {
  1112. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1113. }
  1114. }
  1115. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1116. {
  1117. SessionInfo = session
  1118. }, _logger);
  1119. if (saveCapabilities)
  1120. {
  1121. try
  1122. {
  1123. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1124. }
  1125. catch (Exception ex)
  1126. {
  1127. _logger.ErrorException("Error saving device capabilities", ex);
  1128. }
  1129. }
  1130. }
  1131. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1132. {
  1133. return _deviceManager.GetCapabilities(deviceId);
  1134. }
  1135. private Task SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1136. {
  1137. return _deviceManager.SaveCapabilities(deviceId, capabilities);
  1138. }
  1139. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1140. {
  1141. var dto = new SessionInfoDto
  1142. {
  1143. Client = session.Client,
  1144. DeviceId = session.DeviceId,
  1145. DeviceName = session.DeviceName,
  1146. Id = session.Id,
  1147. LastActivityDate = session.LastActivityDate,
  1148. NowViewingItem = session.NowViewingItem,
  1149. ApplicationVersion = session.ApplicationVersion,
  1150. QueueableMediaTypes = session.QueueableMediaTypes,
  1151. PlayableMediaTypes = session.PlayableMediaTypes,
  1152. AdditionalUsers = session.AdditionalUsers,
  1153. SupportedCommands = session.SupportedCommands,
  1154. UserName = session.UserName,
  1155. NowPlayingItem = session.NowPlayingItem,
  1156. SupportsRemoteControl = session.SupportsMediaControl,
  1157. PlayState = session.PlayState,
  1158. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1159. };
  1160. if (session.UserId.HasValue)
  1161. {
  1162. dto.UserId = session.UserId.Value.ToString("N");
  1163. var user = _userManager.GetUserById(session.UserId.Value);
  1164. if (user != null)
  1165. {
  1166. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1167. }
  1168. }
  1169. return dto;
  1170. }
  1171. /// <summary>
  1172. /// Converts a BaseItem to a BaseItemInfo
  1173. /// </summary>
  1174. /// <param name="item">The item.</param>
  1175. /// <param name="chapterOwner">The chapter owner.</param>
  1176. /// <param name="mediaSourceId">The media source identifier.</param>
  1177. /// <returns>BaseItemInfo.</returns>
  1178. /// <exception cref="System.ArgumentNullException">item</exception>
  1179. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, string mediaSourceId)
  1180. {
  1181. if (item == null)
  1182. {
  1183. throw new ArgumentNullException("item");
  1184. }
  1185. var info = new BaseItemInfo
  1186. {
  1187. Id = GetDtoId(item),
  1188. Name = item.Name,
  1189. MediaType = item.MediaType,
  1190. Type = item.GetClientTypeName(),
  1191. RunTimeTicks = item.RunTimeTicks,
  1192. IndexNumber = item.IndexNumber,
  1193. ParentIndexNumber = item.ParentIndexNumber,
  1194. PremiereDate = item.PremiereDate,
  1195. ProductionYear = item.ProductionYear
  1196. };
  1197. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1198. if (info.PrimaryImageTag != null)
  1199. {
  1200. info.PrimaryImageItemId = GetDtoId(item);
  1201. }
  1202. var episode = item as Episode;
  1203. if (episode != null)
  1204. {
  1205. info.IndexNumberEnd = episode.IndexNumberEnd;
  1206. }
  1207. var hasSeries = item as IHasSeries;
  1208. if (hasSeries != null)
  1209. {
  1210. info.SeriesName = hasSeries.SeriesName;
  1211. }
  1212. var recording = item as ILiveTvRecording;
  1213. if (recording != null && recording.RecordingInfo != null)
  1214. {
  1215. if (recording.RecordingInfo.IsSeries)
  1216. {
  1217. info.Name = recording.RecordingInfo.EpisodeTitle;
  1218. info.SeriesName = recording.RecordingInfo.Name;
  1219. if (string.IsNullOrWhiteSpace(info.Name))
  1220. {
  1221. info.Name = recording.RecordingInfo.Name;
  1222. }
  1223. }
  1224. }
  1225. var audio = item as Audio;
  1226. if (audio != null)
  1227. {
  1228. info.Album = audio.Album;
  1229. info.Artists = audio.Artists;
  1230. if (info.PrimaryImageTag == null)
  1231. {
  1232. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1233. if (album != null && album.HasImage(ImageType.Primary))
  1234. {
  1235. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1236. if (info.PrimaryImageTag != null)
  1237. {
  1238. info.PrimaryImageItemId = GetDtoId(album);
  1239. }
  1240. }
  1241. }
  1242. }
  1243. var musicVideo = item as MusicVideo;
  1244. if (musicVideo != null)
  1245. {
  1246. info.Album = musicVideo.Album;
  1247. info.Artists = musicVideo.Artists.ToList();
  1248. }
  1249. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1250. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1251. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1252. if (thumbItem == null)
  1253. {
  1254. if (episode != null)
  1255. {
  1256. var series = episode.Series;
  1257. if (series != null && series.HasImage(ImageType.Thumb))
  1258. {
  1259. thumbItem = series;
  1260. }
  1261. }
  1262. }
  1263. if (backropItem == null)
  1264. {
  1265. if (episode != null)
  1266. {
  1267. var series = episode.Series;
  1268. if (series != null && series.HasImage(ImageType.Backdrop))
  1269. {
  1270. backropItem = series;
  1271. }
  1272. }
  1273. }
  1274. if (backropItem == null)
  1275. {
  1276. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1277. }
  1278. if (thumbItem == null)
  1279. {
  1280. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1281. }
  1282. if (logoItem == null)
  1283. {
  1284. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1285. }
  1286. if (thumbItem != null)
  1287. {
  1288. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1289. info.ThumbItemId = GetDtoId(thumbItem);
  1290. }
  1291. if (backropItem != null)
  1292. {
  1293. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1294. info.BackdropItemId = GetDtoId(backropItem);
  1295. }
  1296. if (logoItem != null)
  1297. {
  1298. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1299. info.LogoItemId = GetDtoId(logoItem);
  1300. }
  1301. if (chapterOwner != null)
  1302. {
  1303. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1304. info.Chapters = _dtoService.GetChapterInfoDtos(chapterOwner).ToList();
  1305. }
  1306. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  1307. {
  1308. info.MediaStreams = _mediaSourceManager.GetMediaStreams(mediaSourceId).ToList();
  1309. }
  1310. return info;
  1311. }
  1312. private string GetImageCacheTag(BaseItem item, ImageType type)
  1313. {
  1314. try
  1315. {
  1316. return _imageProcessor.GetImageCacheTag(item, type);
  1317. }
  1318. catch (Exception ex)
  1319. {
  1320. _logger.ErrorException("Error getting {0} image info", ex, type);
  1321. return null;
  1322. }
  1323. }
  1324. private string GetDtoId(BaseItem item)
  1325. {
  1326. return _dtoService.GetDtoId(item);
  1327. }
  1328. public void ReportNowViewingItem(string sessionId, string itemId)
  1329. {
  1330. var item = _libraryManager.GetItemById(new Guid(itemId));
  1331. var info = GetItemInfo(item, null, null);
  1332. ReportNowViewingItem(sessionId, info);
  1333. }
  1334. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1335. {
  1336. var session = GetSession(sessionId);
  1337. session.NowViewingItem = item;
  1338. }
  1339. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1340. {
  1341. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1342. if (session != null)
  1343. {
  1344. session.TranscodingInfo = info;
  1345. }
  1346. }
  1347. public void ClearTranscodingInfo(string deviceId)
  1348. {
  1349. ReportTranscodingInfo(deviceId, null);
  1350. }
  1351. public SessionInfo GetSession(string deviceId, string client, string version)
  1352. {
  1353. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1354. string.Equals(i.Client, client));
  1355. }
  1356. public Task<SessionInfo> GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1357. {
  1358. if (info == null)
  1359. {
  1360. throw new ArgumentNullException("info");
  1361. }
  1362. var user = string.IsNullOrWhiteSpace(info.UserId)
  1363. ? null
  1364. : _userManager.GetUserById(info.UserId);
  1365. appVersion = string.IsNullOrWhiteSpace(appVersion)
  1366. ? info.AppVersion
  1367. : appVersion;
  1368. var deviceName = info.DeviceName;
  1369. var appName = info.AppName;
  1370. if (!string.IsNullOrWhiteSpace(deviceId))
  1371. {
  1372. // Replace the info from the token with more recent info
  1373. var device = _deviceManager.GetDevice(deviceId);
  1374. if (device != null)
  1375. {
  1376. deviceName = device.Name;
  1377. appName = device.AppName;
  1378. if (!string.IsNullOrWhiteSpace(device.AppVersion))
  1379. {
  1380. appVersion = device.AppVersion;
  1381. }
  1382. }
  1383. }
  1384. else
  1385. {
  1386. deviceId = info.DeviceId;
  1387. }
  1388. return GetSessionInfo(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1389. }
  1390. public Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1391. {
  1392. var result = _authRepo.Get(new AuthenticationInfoQuery
  1393. {
  1394. AccessToken = token
  1395. });
  1396. var info = result.Items.FirstOrDefault();
  1397. if (info == null)
  1398. {
  1399. return Task.FromResult<SessionInfo>(null);
  1400. }
  1401. return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
  1402. }
  1403. public Task SendMessageToUserSessions<T>(string userId, string name, T data,
  1404. CancellationToken cancellationToken)
  1405. {
  1406. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && i.ContainsUser(userId)).ToList();
  1407. var tasks = sessions.Select(session => Task.Run(async () =>
  1408. {
  1409. try
  1410. {
  1411. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1412. }
  1413. catch (Exception ex)
  1414. {
  1415. _logger.ErrorException("Error sending message", ex);
  1416. }
  1417. }, cancellationToken));
  1418. return Task.WhenAll(tasks);
  1419. }
  1420. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data,
  1421. CancellationToken cancellationToken)
  1422. {
  1423. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
  1424. var tasks = sessions.Select(session => Task.Run(async () =>
  1425. {
  1426. try
  1427. {
  1428. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1429. }
  1430. catch (Exception ex)
  1431. {
  1432. _logger.ErrorException("Error sending message", ex);
  1433. }
  1434. }, cancellationToken));
  1435. return Task.WhenAll(tasks);
  1436. }
  1437. }
  1438. }