SessionManager.cs 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Events;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Controller;
  11. using MediaBrowser.Controller.Authentication;
  12. using MediaBrowser.Controller.Devices;
  13. using MediaBrowser.Controller.Drawing;
  14. using MediaBrowser.Controller.Dto;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.Entities.TV;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.Net;
  19. using MediaBrowser.Controller.Security;
  20. using MediaBrowser.Controller.Session;
  21. using MediaBrowser.Model.Devices;
  22. using MediaBrowser.Model.Dto;
  23. using MediaBrowser.Model.Entities;
  24. using MediaBrowser.Model.Events;
  25. using MediaBrowser.Model.Library;
  26. using MediaBrowser.Model.Querying;
  27. using MediaBrowser.Model.Session;
  28. using Microsoft.Extensions.Logging;
  29. namespace Emby.Server.Implementations.Session
  30. {
  31. /// <summary>
  32. /// Class SessionManager.
  33. /// </summary>
  34. public class SessionManager : ISessionManager, IDisposable
  35. {
  36. /// <summary>
  37. /// The user data repository.
  38. /// </summary>
  39. private readonly IUserDataManager _userDataManager;
  40. /// <summary>
  41. /// The logger.
  42. /// </summary>
  43. private readonly ILogger _logger;
  44. private readonly ILibraryManager _libraryManager;
  45. private readonly IUserManager _userManager;
  46. private readonly IMusicManager _musicManager;
  47. private readonly IDtoService _dtoService;
  48. private readonly IImageProcessor _imageProcessor;
  49. private readonly IMediaSourceManager _mediaSourceManager;
  50. private readonly IServerApplicationHost _appHost;
  51. private readonly IAuthenticationRepository _authRepo;
  52. private readonly IDeviceManager _deviceManager;
  53. /// <summary>
  54. /// The active connections.
  55. /// </summary>
  56. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  57. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  58. private Timer _idleTimer;
  59. private DtoOptions _itemInfoDtoOptions;
  60. private bool _disposed = false;
  61. public SessionManager(
  62. ILogger<SessionManager> logger,
  63. IUserDataManager userDataManager,
  64. ILibraryManager libraryManager,
  65. IUserManager userManager,
  66. IMusicManager musicManager,
  67. IDtoService dtoService,
  68. IImageProcessor imageProcessor,
  69. IServerApplicationHost appHost,
  70. IAuthenticationRepository authRepo,
  71. IDeviceManager deviceManager,
  72. IMediaSourceManager mediaSourceManager)
  73. {
  74. _logger = logger;
  75. _userDataManager = userDataManager;
  76. _libraryManager = libraryManager;
  77. _userManager = userManager;
  78. _musicManager = musicManager;
  79. _dtoService = dtoService;
  80. _imageProcessor = imageProcessor;
  81. _appHost = appHost;
  82. _authRepo = authRepo;
  83. _deviceManager = deviceManager;
  84. _mediaSourceManager = mediaSourceManager;
  85. _deviceManager.DeviceOptionsUpdated += OnDeviceManagerDeviceOptionsUpdated;
  86. }
  87. /// <inheritdoc />
  88. public event EventHandler<GenericEventArgs<AuthenticationRequest>> AuthenticationFailed;
  89. /// <inheritdoc />
  90. public event EventHandler<GenericEventArgs<AuthenticationResult>> AuthenticationSucceeded;
  91. /// <summary>
  92. /// Occurs when playback has started.
  93. /// </summary>
  94. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  95. /// <summary>
  96. /// Occurs when playback has progressed.
  97. /// </summary>
  98. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  99. /// <summary>
  100. /// Occurs when playback has stopped.
  101. /// </summary>
  102. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  103. /// <inheritdoc />
  104. public event EventHandler<SessionEventArgs> SessionStarted;
  105. /// <inheritdoc />
  106. public event EventHandler<SessionEventArgs> CapabilitiesChanged;
  107. /// <inheritdoc />
  108. public event EventHandler<SessionEventArgs> SessionEnded;
  109. /// <inheritdoc />
  110. public event EventHandler<SessionEventArgs> SessionActivity;
  111. /// <summary>
  112. /// Gets all connections.
  113. /// </summary>
  114. /// <value>All connections.</value>
  115. public IEnumerable<SessionInfo> Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate);
  116. private void OnDeviceManagerDeviceOptionsUpdated(object sender, GenericEventArgs<Tuple<string, DeviceOptions>> e)
  117. {
  118. foreach (var session in Sessions)
  119. {
  120. if (string.Equals(session.DeviceId, e.Argument.Item1, StringComparison.Ordinal))
  121. {
  122. if (!string.IsNullOrWhiteSpace(e.Argument.Item2.CustomName))
  123. {
  124. session.HasCustomDeviceName = true;
  125. session.DeviceName = e.Argument.Item2.CustomName;
  126. }
  127. else
  128. {
  129. session.HasCustomDeviceName = false;
  130. }
  131. }
  132. }
  133. }
  134. /// <inheritdoc />
  135. public void Dispose()
  136. {
  137. Dispose(true);
  138. GC.SuppressFinalize(this);
  139. }
  140. /// <summary>
  141. /// Releases unmanaged and optionally managed resources.
  142. /// </summary>
  143. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  144. protected virtual void Dispose(bool disposing)
  145. {
  146. if (_disposed)
  147. {
  148. return;
  149. }
  150. if (disposing)
  151. {
  152. _idleTimer?.Dispose();
  153. }
  154. _idleTimer = null;
  155. _deviceManager.DeviceOptionsUpdated -= OnDeviceManagerDeviceOptionsUpdated;
  156. _disposed = true;
  157. }
  158. private void CheckDisposed()
  159. {
  160. if (_disposed)
  161. {
  162. throw new ObjectDisposedException(GetType().Name);
  163. }
  164. }
  165. private void OnSessionStarted(SessionInfo info)
  166. {
  167. if (!string.IsNullOrEmpty(info.DeviceId))
  168. {
  169. var capabilities = GetSavedCapabilities(info.DeviceId);
  170. if (capabilities != null)
  171. {
  172. ReportCapabilities(info, capabilities, false);
  173. }
  174. }
  175. EventHelper.QueueEventIfNotNull(
  176. SessionStarted,
  177. this,
  178. new SessionEventArgs
  179. {
  180. SessionInfo = info
  181. },
  182. _logger);
  183. }
  184. private void OnSessionEnded(SessionInfo info)
  185. {
  186. EventHelper.QueueEventIfNotNull(
  187. SessionEnded,
  188. this,
  189. new SessionEventArgs
  190. {
  191. SessionInfo = info
  192. },
  193. _logger);
  194. info.Dispose();
  195. }
  196. /// <inheritdoc />
  197. public void UpdateDeviceName(string sessionId, string deviceName)
  198. {
  199. var session = GetSession(sessionId);
  200. if (session != null)
  201. {
  202. session.DeviceName = deviceName;
  203. }
  204. }
  205. /// <summary>
  206. /// Logs the user activity.
  207. /// </summary>
  208. /// <param name="appName">Type of the client.</param>
  209. /// <param name="appVersion">The app version.</param>
  210. /// <param name="deviceId">The device id.</param>
  211. /// <param name="deviceName">Name of the device.</param>
  212. /// <param name="remoteEndPoint">The remote end point.</param>
  213. /// <param name="user">The user.</param>
  214. /// <returns>SessionInfo.</returns>
  215. public SessionInfo LogSessionActivity(
  216. string appName,
  217. string appVersion,
  218. string deviceId,
  219. string deviceName,
  220. string remoteEndPoint,
  221. User user)
  222. {
  223. CheckDisposed();
  224. if (string.IsNullOrEmpty(appName))
  225. {
  226. throw new ArgumentNullException(nameof(appName));
  227. }
  228. if (string.IsNullOrEmpty(appVersion))
  229. {
  230. throw new ArgumentNullException(nameof(appVersion));
  231. }
  232. if (string.IsNullOrEmpty(deviceId))
  233. {
  234. throw new ArgumentNullException(nameof(deviceId));
  235. }
  236. var activityDate = DateTime.UtcNow;
  237. var session = GetSessionInfo(appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
  238. var lastActivityDate = session.LastActivityDate;
  239. session.LastActivityDate = activityDate;
  240. if (user != null)
  241. {
  242. var userLastActivityDate = user.LastActivityDate ?? DateTime.MinValue;
  243. user.LastActivityDate = activityDate;
  244. if ((activityDate - userLastActivityDate).TotalSeconds > 60)
  245. {
  246. _userManager.UpdateUser(user);
  247. }
  248. }
  249. if ((activityDate - lastActivityDate).TotalSeconds > 10)
  250. {
  251. SessionActivity?.Invoke(
  252. this,
  253. new SessionEventArgs
  254. {
  255. SessionInfo = session
  256. });
  257. }
  258. return session;
  259. }
  260. /// <inheritdoc />
  261. public void CloseIfNeeded(SessionInfo session)
  262. {
  263. if (!session.SessionControllers.Any(i => i.IsSessionActive))
  264. {
  265. var key = GetSessionKey(session.Client, session.DeviceId);
  266. _activeConnections.TryRemove(key, out _);
  267. OnSessionEnded(session);
  268. }
  269. }
  270. /// <inheritdoc />
  271. public void ReportSessionEnded(string sessionId)
  272. {
  273. CheckDisposed();
  274. var session = GetSession(sessionId, false);
  275. if (session != null)
  276. {
  277. var key = GetSessionKey(session.Client, session.DeviceId);
  278. _activeConnections.TryRemove(key, out _);
  279. OnSessionEnded(session);
  280. }
  281. }
  282. private Task<MediaSourceInfo> GetMediaSource(BaseItem item, string mediaSourceId, string liveStreamId)
  283. {
  284. return _mediaSourceManager.GetMediaSource(item, mediaSourceId, liveStreamId, false, CancellationToken.None);
  285. }
  286. /// <summary>
  287. /// Updates the now playing item id.
  288. /// </summary>
  289. /// <returns>Task.</returns>
  290. private async Task UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem, bool updateLastCheckInTime)
  291. {
  292. if (string.IsNullOrEmpty(info.MediaSourceId))
  293. {
  294. info.MediaSourceId = info.ItemId.ToString("N", CultureInfo.InvariantCulture);
  295. }
  296. if (!info.ItemId.Equals(Guid.Empty) && info.Item == null && libraryItem != null)
  297. {
  298. var current = session.NowPlayingItem;
  299. if (current == null || !info.ItemId.Equals(current.Id))
  300. {
  301. var runtimeTicks = libraryItem.RunTimeTicks;
  302. MediaSourceInfo mediaSource = null;
  303. if (libraryItem is IHasMediaSources)
  304. {
  305. mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
  306. if (mediaSource != null)
  307. {
  308. runtimeTicks = mediaSource.RunTimeTicks;
  309. }
  310. }
  311. info.Item = GetItemInfo(libraryItem, mediaSource);
  312. info.Item.RunTimeTicks = runtimeTicks;
  313. }
  314. else
  315. {
  316. info.Item = current;
  317. }
  318. }
  319. session.NowPlayingItem = info.Item;
  320. session.LastActivityDate = DateTime.UtcNow;
  321. if (updateLastCheckInTime)
  322. {
  323. session.LastPlaybackCheckIn = DateTime.UtcNow;
  324. }
  325. session.PlayState.IsPaused = info.IsPaused;
  326. session.PlayState.PositionTicks = info.PositionTicks;
  327. session.PlayState.MediaSourceId = info.MediaSourceId;
  328. session.PlayState.CanSeek = info.CanSeek;
  329. session.PlayState.IsMuted = info.IsMuted;
  330. session.PlayState.VolumeLevel = info.VolumeLevel;
  331. session.PlayState.AudioStreamIndex = info.AudioStreamIndex;
  332. session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex;
  333. session.PlayState.PlayMethod = info.PlayMethod;
  334. session.PlayState.RepeatMode = info.RepeatMode;
  335. session.PlaylistItemId = info.PlaylistItemId;
  336. var nowPlayingQueue = info.NowPlayingQueue;
  337. if (nowPlayingQueue != null)
  338. {
  339. session.NowPlayingQueue = nowPlayingQueue;
  340. }
  341. }
  342. /// <summary>
  343. /// Removes the now playing item id.
  344. /// </summary>
  345. /// <param name="session">The session.</param>
  346. private void RemoveNowPlayingItem(SessionInfo session)
  347. {
  348. session.NowPlayingItem = null;
  349. session.PlayState = new PlayerStateInfo();
  350. if (!string.IsNullOrEmpty(session.DeviceId))
  351. {
  352. ClearTranscodingInfo(session.DeviceId);
  353. }
  354. }
  355. private static string GetSessionKey(string appName, string deviceId)
  356. => appName + deviceId;
  357. /// <summary>
  358. /// Gets the connection.
  359. /// </summary>
  360. /// <param name="appName">Type of the client.</param>
  361. /// <param name="appVersion">The app version.</param>
  362. /// <param name="deviceId">The device id.</param>
  363. /// <param name="deviceName">Name of the device.</param>
  364. /// <param name="remoteEndPoint">The remote end point.</param>
  365. /// <param name="user">The user.</param>
  366. /// <returns>SessionInfo.</returns>
  367. private SessionInfo GetSessionInfo(string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
  368. {
  369. CheckDisposed();
  370. if (string.IsNullOrEmpty(deviceId))
  371. {
  372. throw new ArgumentNullException(nameof(deviceId));
  373. }
  374. var key = GetSessionKey(appName, deviceId);
  375. CheckDisposed();
  376. var sessionInfo = _activeConnections.GetOrAdd(key, k =>
  377. {
  378. return CreateSession(k, appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
  379. });
  380. sessionInfo.UserId = user == null ? Guid.Empty : user.Id;
  381. sessionInfo.UserName = user?.Name;
  382. sessionInfo.UserPrimaryImageTag = user == null ? null : GetImageCacheTag(user, ImageType.Primary);
  383. sessionInfo.RemoteEndPoint = remoteEndPoint;
  384. sessionInfo.Client = appName;
  385. if (!sessionInfo.HasCustomDeviceName || string.IsNullOrEmpty(sessionInfo.DeviceName))
  386. {
  387. sessionInfo.DeviceName = deviceName;
  388. }
  389. sessionInfo.ApplicationVersion = appVersion;
  390. if (user == null)
  391. {
  392. sessionInfo.AdditionalUsers = Array.Empty<SessionUserInfo>();
  393. }
  394. return sessionInfo;
  395. }
  396. private SessionInfo CreateSession(string key, string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
  397. {
  398. var sessionInfo = new SessionInfo(this, _logger)
  399. {
  400. Client = appName,
  401. DeviceId = deviceId,
  402. ApplicationVersion = appVersion,
  403. Id = key.GetMD5().ToString("N", CultureInfo.InvariantCulture)
  404. };
  405. var username = user?.Name;
  406. sessionInfo.UserId = user?.Id ?? Guid.Empty;
  407. sessionInfo.UserName = username;
  408. sessionInfo.UserPrimaryImageTag = user == null ? null : GetImageCacheTag(user, ImageType.Primary);
  409. sessionInfo.RemoteEndPoint = remoteEndPoint;
  410. if (string.IsNullOrEmpty(deviceName))
  411. {
  412. deviceName = "Network Device";
  413. }
  414. var deviceOptions = _deviceManager.GetDeviceOptions(deviceId);
  415. if (string.IsNullOrEmpty(deviceOptions.CustomName))
  416. {
  417. sessionInfo.DeviceName = deviceName;
  418. }
  419. else
  420. {
  421. sessionInfo.DeviceName = deviceOptions.CustomName;
  422. sessionInfo.HasCustomDeviceName = true;
  423. }
  424. OnSessionStarted(sessionInfo);
  425. return sessionInfo;
  426. }
  427. private List<User> GetUsers(SessionInfo session)
  428. {
  429. var users = new List<User>();
  430. if (session.UserId != Guid.Empty)
  431. {
  432. var user = _userManager.GetUserById(session.UserId);
  433. if (user == null)
  434. {
  435. throw new InvalidOperationException("User not found");
  436. }
  437. users.Add(user);
  438. users.AddRange(session.AdditionalUsers
  439. .Select(i => _userManager.GetUserById(i.UserId))
  440. .Where(i => i != null));
  441. }
  442. return users;
  443. }
  444. private void StartIdleCheckTimer()
  445. {
  446. if (_idleTimer == null)
  447. {
  448. _idleTimer = new Timer(CheckForIdlePlayback, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
  449. }
  450. }
  451. private void StopIdleCheckTimer()
  452. {
  453. if (_idleTimer != null)
  454. {
  455. _idleTimer.Dispose();
  456. _idleTimer = null;
  457. }
  458. }
  459. private async void CheckForIdlePlayback(object state)
  460. {
  461. var playingSessions = Sessions.Where(i => i.NowPlayingItem != null)
  462. .ToList();
  463. if (playingSessions.Count > 0)
  464. {
  465. var idle = playingSessions
  466. .Where(i => (DateTime.UtcNow - i.LastPlaybackCheckIn).TotalMinutes > 5)
  467. .ToList();
  468. foreach (var session in idle)
  469. {
  470. _logger.LogDebug("Session {0} has gone idle while playing", session.Id);
  471. try
  472. {
  473. await OnPlaybackStopped(new PlaybackStopInfo
  474. {
  475. Item = session.NowPlayingItem,
  476. ItemId = session.NowPlayingItem == null ? Guid.Empty : session.NowPlayingItem.Id,
  477. SessionId = session.Id,
  478. MediaSourceId = session.PlayState?.MediaSourceId,
  479. PositionTicks = session.PlayState?.PositionTicks
  480. }).ConfigureAwait(false);
  481. }
  482. catch (Exception ex)
  483. {
  484. _logger.LogDebug("Error calling OnPlaybackStopped", ex);
  485. }
  486. }
  487. playingSessions = Sessions.Where(i => i.NowPlayingItem != null)
  488. .ToList();
  489. }
  490. if (playingSessions.Count == 0)
  491. {
  492. StopIdleCheckTimer();
  493. }
  494. }
  495. private BaseItem GetNowPlayingItem(SessionInfo session, Guid itemId)
  496. {
  497. var item = session.FullNowPlayingItem;
  498. if (item != null && item.Id.Equals(itemId))
  499. {
  500. return item;
  501. }
  502. item = _libraryManager.GetItemById(itemId);
  503. session.FullNowPlayingItem = item;
  504. return item;
  505. }
  506. /// <summary>
  507. /// Used to report that playback has started for an item.
  508. /// </summary>
  509. /// <param name="info">The info.</param>
  510. /// <returns>Task.</returns>
  511. /// <exception cref="ArgumentNullException"><c>info</c> is <c>null</c>.</exception>
  512. public async Task OnPlaybackStart(PlaybackStartInfo info)
  513. {
  514. CheckDisposed();
  515. if (info == null)
  516. {
  517. throw new ArgumentNullException(nameof(info));
  518. }
  519. var session = GetSession(info.SessionId);
  520. var libraryItem = info.ItemId == Guid.Empty
  521. ? null
  522. : GetNowPlayingItem(session, info.ItemId);
  523. await UpdateNowPlayingItem(session, info, libraryItem, true).ConfigureAwait(false);
  524. if (!string.IsNullOrEmpty(session.DeviceId) && info.PlayMethod != PlayMethod.Transcode)
  525. {
  526. ClearTranscodingInfo(session.DeviceId);
  527. }
  528. session.StartAutomaticProgress(info);
  529. var users = GetUsers(session);
  530. if (libraryItem != null)
  531. {
  532. foreach (var user in users)
  533. {
  534. OnPlaybackStart(user, libraryItem);
  535. }
  536. }
  537. // Nothing to save here
  538. // Fire events to inform plugins
  539. EventHelper.QueueEventIfNotNull(
  540. PlaybackStart,
  541. this,
  542. new PlaybackProgressEventArgs
  543. {
  544. Item = libraryItem,
  545. Users = users,
  546. MediaSourceId = info.MediaSourceId,
  547. MediaInfo = info.Item,
  548. DeviceName = session.DeviceName,
  549. ClientName = session.Client,
  550. DeviceId = session.DeviceId,
  551. Session = session
  552. },
  553. _logger);
  554. StartIdleCheckTimer();
  555. }
  556. /// <summary>
  557. /// Called when [playback start].
  558. /// </summary>
  559. /// <param name="user">The user object.</param>
  560. /// <param name="item">The item.</param>
  561. private void OnPlaybackStart(User user, BaseItem item)
  562. {
  563. var data = _userDataManager.GetUserData(user, item);
  564. data.PlayCount++;
  565. data.LastPlayedDate = DateTime.UtcNow;
  566. if (item.SupportsPlayedStatus && !item.SupportsPositionTicksResume)
  567. {
  568. data.Played = true;
  569. }
  570. else
  571. {
  572. data.Played = false;
  573. }
  574. _userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None);
  575. }
  576. /// <inheritdoc />
  577. public Task OnPlaybackProgress(PlaybackProgressInfo info)
  578. {
  579. return OnPlaybackProgress(info, false);
  580. }
  581. /// <summary>
  582. /// Used to report playback progress for an item.
  583. /// </summary>
  584. /// <returns>Task.</returns>
  585. public async Task OnPlaybackProgress(PlaybackProgressInfo info, bool isAutomated)
  586. {
  587. CheckDisposed();
  588. if (info == null)
  589. {
  590. throw new ArgumentNullException(nameof(info));
  591. }
  592. var session = GetSession(info.SessionId);
  593. var libraryItem = info.ItemId.Equals(Guid.Empty)
  594. ? null
  595. : GetNowPlayingItem(session, info.ItemId);
  596. await UpdateNowPlayingItem(session, info, libraryItem, !isAutomated).ConfigureAwait(false);
  597. var users = GetUsers(session);
  598. // only update saved user data on actual check-ins, not automated ones
  599. if (libraryItem != null && !isAutomated)
  600. {
  601. foreach (var user in users)
  602. {
  603. OnPlaybackProgress(user, libraryItem, info);
  604. }
  605. }
  606. PlaybackProgress?.Invoke(
  607. this,
  608. new PlaybackProgressEventArgs
  609. {
  610. Item = libraryItem,
  611. Users = users,
  612. PlaybackPositionTicks = session.PlayState.PositionTicks,
  613. MediaSourceId = session.PlayState.MediaSourceId,
  614. MediaInfo = info.Item,
  615. DeviceName = session.DeviceName,
  616. ClientName = session.Client,
  617. DeviceId = session.DeviceId,
  618. IsPaused = info.IsPaused,
  619. PlaySessionId = info.PlaySessionId,
  620. IsAutomated = isAutomated,
  621. Session = session
  622. });
  623. if (!isAutomated)
  624. {
  625. session.StartAutomaticProgress(info);
  626. }
  627. StartIdleCheckTimer();
  628. }
  629. private void OnPlaybackProgress(User user, BaseItem item, PlaybackProgressInfo info)
  630. {
  631. var data = _userDataManager.GetUserData(user, item);
  632. var positionTicks = info.PositionTicks;
  633. var changed = false;
  634. if (positionTicks.HasValue)
  635. {
  636. _userDataManager.UpdatePlayState(item, data, positionTicks.Value);
  637. changed = true;
  638. }
  639. var tracksChanged = UpdatePlaybackSettings(user, info, data);
  640. if (!tracksChanged)
  641. {
  642. changed = true;
  643. }
  644. if (changed)
  645. {
  646. _userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None);
  647. }
  648. }
  649. private static bool UpdatePlaybackSettings(User user, PlaybackProgressInfo info, UserItemData data)
  650. {
  651. var changed = false;
  652. if (user.Configuration.RememberAudioSelections)
  653. {
  654. if (data.AudioStreamIndex != info.AudioStreamIndex)
  655. {
  656. data.AudioStreamIndex = info.AudioStreamIndex;
  657. changed = true;
  658. }
  659. }
  660. else
  661. {
  662. if (data.AudioStreamIndex.HasValue)
  663. {
  664. data.AudioStreamIndex = null;
  665. changed = true;
  666. }
  667. }
  668. if (user.Configuration.RememberSubtitleSelections)
  669. {
  670. if (data.SubtitleStreamIndex != info.SubtitleStreamIndex)
  671. {
  672. data.SubtitleStreamIndex = info.SubtitleStreamIndex;
  673. changed = true;
  674. }
  675. }
  676. else
  677. {
  678. if (data.SubtitleStreamIndex.HasValue)
  679. {
  680. data.SubtitleStreamIndex = null;
  681. changed = true;
  682. }
  683. }
  684. return changed;
  685. }
  686. /// <summary>
  687. /// Used to report that playback has ended for an item
  688. /// </summary>
  689. /// <param name="info">The info.</param>
  690. /// <returns>Task.</returns>
  691. /// <exception cref="ArgumentNullException">info</exception>
  692. /// <exception cref="ArgumentOutOfRangeException">positionTicks</exception>
  693. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  694. {
  695. CheckDisposed();
  696. if (info == null)
  697. {
  698. throw new ArgumentNullException(nameof(info));
  699. }
  700. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  701. {
  702. throw new ArgumentOutOfRangeException(nameof(info), "The PlaybackStopInfo's PositionTicks was negative.");
  703. }
  704. var session = GetSession(info.SessionId);
  705. session.StopAutomaticProgress();
  706. var libraryItem = info.ItemId.Equals(Guid.Empty)
  707. ? null
  708. : GetNowPlayingItem(session, info.ItemId);
  709. // Normalize
  710. if (string.IsNullOrEmpty(info.MediaSourceId))
  711. {
  712. info.MediaSourceId = info.ItemId.ToString("N", CultureInfo.InvariantCulture);
  713. }
  714. if (!info.ItemId.Equals(Guid.Empty) && info.Item == null && libraryItem != null)
  715. {
  716. var current = session.NowPlayingItem;
  717. if (current == null || !info.ItemId.Equals(current.Id))
  718. {
  719. MediaSourceInfo mediaSource = null;
  720. if (libraryItem is IHasMediaSources)
  721. {
  722. mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
  723. }
  724. info.Item = GetItemInfo(libraryItem, mediaSource);
  725. }
  726. else
  727. {
  728. info.Item = current;
  729. }
  730. }
  731. if (info.Item != null)
  732. {
  733. var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.InvariantCulture) : "unknown";
  734. _logger.LogInformation(
  735. "Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
  736. session.Client,
  737. session.ApplicationVersion,
  738. info.Item.Name,
  739. msString);
  740. }
  741. if (info.NowPlayingQueue != null)
  742. {
  743. session.NowPlayingQueue = info.NowPlayingQueue;
  744. }
  745. session.PlaylistItemId = info.PlaylistItemId;
  746. RemoveNowPlayingItem(session);
  747. var users = GetUsers(session);
  748. var playedToCompletion = false;
  749. if (libraryItem != null)
  750. {
  751. foreach (var user in users)
  752. {
  753. playedToCompletion = OnPlaybackStopped(user, libraryItem, info.PositionTicks, info.Failed);
  754. }
  755. }
  756. if (!string.IsNullOrEmpty(info.LiveStreamId))
  757. {
  758. try
  759. {
  760. await _mediaSourceManager.CloseLiveStream(info.LiveStreamId).ConfigureAwait(false);
  761. }
  762. catch (Exception ex)
  763. {
  764. _logger.LogError("Error closing live stream", ex);
  765. }
  766. }
  767. EventHelper.QueueEventIfNotNull(
  768. PlaybackStopped,
  769. this,
  770. new PlaybackStopEventArgs
  771. {
  772. Item = libraryItem,
  773. Users = users,
  774. PlaybackPositionTicks = info.PositionTicks,
  775. PlayedToCompletion = playedToCompletion,
  776. MediaSourceId = info.MediaSourceId,
  777. MediaInfo = info.Item,
  778. DeviceName = session.DeviceName,
  779. ClientName = session.Client,
  780. DeviceId = session.DeviceId,
  781. Session = session
  782. },
  783. _logger);
  784. }
  785. private bool OnPlaybackStopped(User user, BaseItem item, long? positionTicks, bool playbackFailed)
  786. {
  787. bool playedToCompletion = false;
  788. if (!playbackFailed)
  789. {
  790. var data = _userDataManager.GetUserData(user, item);
  791. if (positionTicks.HasValue)
  792. {
  793. playedToCompletion = _userDataManager.UpdatePlayState(item, data, positionTicks.Value);
  794. }
  795. else
  796. {
  797. // If the client isn't able to report this, then we'll just have to make an assumption
  798. data.PlayCount++;
  799. data.Played = item.SupportsPlayedStatus;
  800. data.PlaybackPositionTicks = 0;
  801. playedToCompletion = true;
  802. }
  803. _userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None);
  804. }
  805. return playedToCompletion;
  806. }
  807. /// <summary>
  808. /// Gets the session.
  809. /// </summary>
  810. /// <param name="sessionId">The session identifier.</param>
  811. /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
  812. /// <returns>SessionInfo.</returns>
  813. /// <exception cref="ResourceNotFoundException">
  814. /// No session with an Id equal to <c>sessionId</c> was found
  815. /// and <c>throwOnMissing</c> is <c>true</c>.
  816. /// </exception>
  817. private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
  818. {
  819. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal));
  820. if (session == null && throwOnMissing)
  821. {
  822. throw new ResourceNotFoundException(
  823. string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId));
  824. }
  825. return session;
  826. }
  827. private SessionInfo GetSessionToRemoteControl(string sessionId)
  828. {
  829. // Accept either device id or session id
  830. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal));
  831. if (session == null)
  832. {
  833. throw new ResourceNotFoundException(
  834. string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId));
  835. }
  836. return session;
  837. }
  838. /// <inheritdoc />
  839. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  840. {
  841. CheckDisposed();
  842. var generalCommand = new GeneralCommand
  843. {
  844. Name = GeneralCommandType.DisplayMessage.ToString()
  845. };
  846. generalCommand.Arguments["Header"] = command.Header;
  847. generalCommand.Arguments["Text"] = command.Text;
  848. if (command.TimeoutMs.HasValue)
  849. {
  850. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  851. }
  852. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  853. }
  854. /// <inheritdoc />
  855. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  856. {
  857. CheckDisposed();
  858. var session = GetSessionToRemoteControl(sessionId);
  859. if (!string.IsNullOrEmpty(controllingSessionId))
  860. {
  861. var controllingSession = GetSession(controllingSessionId);
  862. AssertCanControl(session, controllingSession);
  863. }
  864. return SendMessageToSession(session, "GeneralCommand", command, cancellationToken);
  865. }
  866. private static async Task SendMessageToSession<T>(SessionInfo session, string name, T data, CancellationToken cancellationToken)
  867. {
  868. var controllers = session.SessionControllers;
  869. var messageId = Guid.NewGuid();
  870. foreach (var controller in controllers)
  871. {
  872. await controller.SendMessage(name, messageId, data, cancellationToken).ConfigureAwait(false);
  873. }
  874. }
  875. private static Task SendMessageToSessions<T>(IEnumerable<SessionInfo> sessions, string name, T data, CancellationToken cancellationToken)
  876. {
  877. IEnumerable<Task> GetTasks()
  878. {
  879. var messageId = Guid.NewGuid();
  880. foreach (var session in sessions)
  881. {
  882. var controllers = session.SessionControllers;
  883. foreach (var controller in controllers)
  884. {
  885. yield return controller.SendMessage(name, messageId, data, cancellationToken);
  886. }
  887. }
  888. }
  889. return Task.WhenAll(GetTasks());
  890. }
  891. /// <inheritdoc />
  892. public async Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  893. {
  894. CheckDisposed();
  895. var session = GetSessionToRemoteControl(sessionId);
  896. var user = session.UserId == Guid.Empty ? null : _userManager.GetUserById(session.UserId);
  897. List<BaseItem> items;
  898. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  899. {
  900. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  901. .ToList();
  902. command.PlayCommand = PlayCommand.PlayNow;
  903. }
  904. else
  905. {
  906. var list = new List<BaseItem>();
  907. foreach (var itemId in command.ItemIds)
  908. {
  909. var subItems = TranslateItemForPlayback(itemId, user);
  910. list.AddRange(subItems);
  911. }
  912. items = list;
  913. }
  914. if (command.PlayCommand == PlayCommand.PlayShuffle)
  915. {
  916. items.Shuffle();
  917. command.PlayCommand = PlayCommand.PlayNow;
  918. }
  919. command.ItemIds = items.Select(i => i.Id).ToArray();
  920. if (user != null)
  921. {
  922. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  923. {
  924. throw new ArgumentException(
  925. string.Format(CultureInfo.InvariantCulture, "{0} is not allowed to play media.", user.Name));
  926. }
  927. }
  928. if (user != null
  929. && command.ItemIds.Length == 1
  930. && user.Configuration.EnableNextEpisodeAutoPlay
  931. && _libraryManager.GetItemById(command.ItemIds[0]) is Episode episode)
  932. {
  933. var series = episode.Series;
  934. if (series != null)
  935. {
  936. var episodes = series.GetEpisodes(
  937. user,
  938. new DtoOptions(false)
  939. {
  940. EnableImages = false
  941. })
  942. .Where(i => !i.IsVirtualItem)
  943. .SkipWhile(i => i.Id != episode.Id)
  944. .ToList();
  945. if (episodes.Count > 0)
  946. {
  947. command.ItemIds = episodes.Select(i => i.Id).ToArray();
  948. }
  949. }
  950. }
  951. if (!string.IsNullOrEmpty(controllingSessionId))
  952. {
  953. var controllingSession = GetSession(controllingSessionId);
  954. AssertCanControl(session, controllingSession);
  955. if (!controllingSession.UserId.Equals(Guid.Empty))
  956. {
  957. command.ControllingUserId = controllingSession.UserId;
  958. }
  959. }
  960. await SendMessageToSession(session, "Play", command, cancellationToken).ConfigureAwait(false);
  961. }
  962. private IEnumerable<BaseItem> TranslateItemForPlayback(Guid id, User user)
  963. {
  964. var item = _libraryManager.GetItemById(id);
  965. if (item == null)
  966. {
  967. _logger.LogError("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
  968. return Array.Empty<BaseItem>();
  969. }
  970. if (item is IItemByName byName)
  971. {
  972. return byName.GetTaggedItems(new InternalItemsQuery(user)
  973. {
  974. IsFolder = false,
  975. Recursive = true,
  976. DtoOptions = new DtoOptions(false)
  977. {
  978. EnableImages = false,
  979. Fields = new ItemFields[]
  980. {
  981. ItemFields.SortName
  982. }
  983. },
  984. IsVirtualItem = false,
  985. OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }
  986. });
  987. }
  988. if (item.IsFolder)
  989. {
  990. var folder = (Folder)item;
  991. return folder.GetItemList(new InternalItemsQuery(user)
  992. {
  993. Recursive = true,
  994. IsFolder = false,
  995. DtoOptions = new DtoOptions(false)
  996. {
  997. EnableImages = false,
  998. Fields = new ItemFields[]
  999. {
  1000. ItemFields.SortName
  1001. }
  1002. },
  1003. IsVirtualItem = false,
  1004. OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }
  1005. });
  1006. }
  1007. return new[] { item };
  1008. }
  1009. private IEnumerable<BaseItem> TranslateItemForInstantMix(Guid id, User user)
  1010. {
  1011. var item = _libraryManager.GetItemById(id);
  1012. if (item == null)
  1013. {
  1014. _logger.LogError("A non-existent item Id {0} was passed into TranslateItemForInstantMix", id);
  1015. return new List<BaseItem>();
  1016. }
  1017. return _musicManager.GetInstantMixFromItem(item, user, new DtoOptions(false) { EnableImages = false });
  1018. }
  1019. /// <inheritdoc />
  1020. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  1021. {
  1022. var generalCommand = new GeneralCommand
  1023. {
  1024. Name = GeneralCommandType.DisplayContent.ToString(),
  1025. Arguments =
  1026. {
  1027. ["ItemId"] = command.ItemId,
  1028. ["ItemName"] = command.ItemName,
  1029. ["ItemType"] = command.ItemType
  1030. }
  1031. };
  1032. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  1033. }
  1034. /// <inheritdoc />
  1035. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  1036. {
  1037. CheckDisposed();
  1038. var session = GetSessionToRemoteControl(sessionId);
  1039. if (!string.IsNullOrEmpty(controllingSessionId))
  1040. {
  1041. var controllingSession = GetSession(controllingSessionId);
  1042. AssertCanControl(session, controllingSession);
  1043. if (!controllingSession.UserId.Equals(Guid.Empty))
  1044. {
  1045. command.ControllingUserId = controllingSession.UserId.ToString("N", CultureInfo.InvariantCulture);
  1046. }
  1047. }
  1048. return SendMessageToSession(session, "Playstate", command, cancellationToken);
  1049. }
  1050. private static void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  1051. {
  1052. if (session == null)
  1053. {
  1054. throw new ArgumentNullException(nameof(session));
  1055. }
  1056. if (controllingSession == null)
  1057. {
  1058. throw new ArgumentNullException(nameof(controllingSession));
  1059. }
  1060. }
  1061. /// <summary>
  1062. /// Sends the restart required message.
  1063. /// </summary>
  1064. /// <param name="cancellationToken">The cancellation token.</param>
  1065. /// <returns>Task.</returns>
  1066. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  1067. {
  1068. CheckDisposed();
  1069. return SendMessageToSessions(Sessions, "RestartRequired", string.Empty, cancellationToken);
  1070. }
  1071. /// <summary>
  1072. /// Sends the server shutdown notification.
  1073. /// </summary>
  1074. /// <param name="cancellationToken">The cancellation token.</param>
  1075. /// <returns>Task.</returns>
  1076. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  1077. {
  1078. CheckDisposed();
  1079. return SendMessageToSessions(Sessions, "ServerShuttingDown", string.Empty, cancellationToken);
  1080. }
  1081. /// <summary>
  1082. /// Sends the server restart notification.
  1083. /// </summary>
  1084. /// <param name="cancellationToken">The cancellation token.</param>
  1085. /// <returns>Task.</returns>
  1086. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  1087. {
  1088. CheckDisposed();
  1089. _logger.LogDebug("Beginning SendServerRestartNotification");
  1090. return SendMessageToSessions(Sessions, "ServerRestarting", string.Empty, cancellationToken);
  1091. }
  1092. /// <summary>
  1093. /// Adds the additional user.
  1094. /// </summary>
  1095. /// <param name="sessionId">The session identifier.</param>
  1096. /// <param name="userId">The user identifier.</param>
  1097. /// <exception cref="UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1098. /// <exception cref="ArgumentException">The requested user is already the primary user of the session.</exception>
  1099. public void AddAdditionalUser(string sessionId, Guid userId)
  1100. {
  1101. CheckDisposed();
  1102. var session = GetSession(sessionId);
  1103. if (session.UserId == userId)
  1104. {
  1105. throw new ArgumentException("The requested user is already the primary user of the session.");
  1106. }
  1107. if (session.AdditionalUsers.All(i => i.UserId != userId))
  1108. {
  1109. var user = _userManager.GetUserById(userId);
  1110. var list = session.AdditionalUsers.ToList();
  1111. list.Add(new SessionUserInfo
  1112. {
  1113. UserId = userId,
  1114. UserName = user.Name
  1115. });
  1116. session.AdditionalUsers = list.ToArray();
  1117. }
  1118. }
  1119. /// <summary>
  1120. /// Removes the additional user.
  1121. /// </summary>
  1122. /// <param name="sessionId">The session identifier.</param>
  1123. /// <param name="userId">The user identifier.</param>
  1124. /// <exception cref="UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1125. /// <exception cref="ArgumentException">The requested user is already the primary user of the session.</exception>
  1126. public void RemoveAdditionalUser(string sessionId, Guid userId)
  1127. {
  1128. CheckDisposed();
  1129. var session = GetSession(sessionId);
  1130. if (session.UserId.Equals(userId))
  1131. {
  1132. throw new ArgumentException("The requested user is already the primary user of the session.");
  1133. }
  1134. var user = session.AdditionalUsers.FirstOrDefault(i => i.UserId.Equals(userId));
  1135. if (user != null)
  1136. {
  1137. var list = session.AdditionalUsers.ToList();
  1138. list.Remove(user);
  1139. session.AdditionalUsers = list.ToArray();
  1140. }
  1141. }
  1142. /// <summary>
  1143. /// Authenticates the new session.
  1144. /// </summary>
  1145. /// <param name="request">The request.</param>
  1146. /// <returns>Task{SessionInfo}.</returns>
  1147. public Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  1148. {
  1149. return AuthenticateNewSessionInternal(request, true);
  1150. }
  1151. public Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request)
  1152. {
  1153. return AuthenticateNewSessionInternal(request, false);
  1154. }
  1155. private async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enforcePassword)
  1156. {
  1157. CheckDisposed();
  1158. User user = null;
  1159. if (request.UserId != Guid.Empty)
  1160. {
  1161. user = _userManager.GetUserById(request.UserId);
  1162. }
  1163. if (user == null)
  1164. {
  1165. user = _userManager.GetUserByName(request.Username);
  1166. }
  1167. if (enforcePassword)
  1168. {
  1169. user = await _userManager.AuthenticateUser(
  1170. request.Username,
  1171. request.Password,
  1172. request.PasswordSha1,
  1173. request.RemoteEndPoint,
  1174. true).ConfigureAwait(false);
  1175. }
  1176. if (user == null)
  1177. {
  1178. AuthenticationFailed?.Invoke(this, new GenericEventArgs<AuthenticationRequest>(request));
  1179. throw new AuthenticationException("Invalid username or password entered.");
  1180. }
  1181. if (!string.IsNullOrEmpty(request.DeviceId)
  1182. && !_deviceManager.CanAccessDevice(user, request.DeviceId))
  1183. {
  1184. throw new SecurityException("User is not allowed access from this device.");
  1185. }
  1186. var token = GetAuthorizationToken(user, request.DeviceId, request.App, request.AppVersion, request.DeviceName);
  1187. var session = LogSessionActivity(
  1188. request.App,
  1189. request.AppVersion,
  1190. request.DeviceId,
  1191. request.DeviceName,
  1192. request.RemoteEndPoint,
  1193. user);
  1194. var returnResult = new AuthenticationResult
  1195. {
  1196. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1197. SessionInfo = session,
  1198. AccessToken = token,
  1199. ServerId = _appHost.SystemId
  1200. };
  1201. AuthenticationSucceeded?.Invoke(this, new GenericEventArgs<AuthenticationResult>(returnResult));
  1202. return returnResult;
  1203. }
  1204. private string GetAuthorizationToken(User user, string deviceId, string app, string appVersion, string deviceName)
  1205. {
  1206. var existing = _authRepo.Get(
  1207. new AuthenticationInfoQuery
  1208. {
  1209. DeviceId = deviceId,
  1210. UserId = user.Id,
  1211. Limit = 1
  1212. }).Items.FirstOrDefault();
  1213. var allExistingForDevice = _authRepo.Get(
  1214. new AuthenticationInfoQuery
  1215. {
  1216. DeviceId = deviceId
  1217. }).Items;
  1218. foreach (var auth in allExistingForDevice)
  1219. {
  1220. if (existing == null || !string.Equals(auth.AccessToken, existing.AccessToken, StringComparison.Ordinal))
  1221. {
  1222. try
  1223. {
  1224. Logout(auth);
  1225. }
  1226. catch (Exception ex)
  1227. {
  1228. _logger.LogError(ex, "Error while logging out.");
  1229. }
  1230. }
  1231. }
  1232. if (existing != null)
  1233. {
  1234. _logger.LogInformation("Reissuing access token: {Token}", existing.AccessToken);
  1235. return existing.AccessToken;
  1236. }
  1237. var now = DateTime.UtcNow;
  1238. var newToken = new AuthenticationInfo
  1239. {
  1240. AppName = app,
  1241. AppVersion = appVersion,
  1242. DateCreated = now,
  1243. DateLastActivity = now,
  1244. DeviceId = deviceId,
  1245. DeviceName = deviceName,
  1246. UserId = user.Id,
  1247. AccessToken = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
  1248. UserName = user.Name
  1249. };
  1250. _logger.LogInformation("Creating new access token for user {0}", user.Id);
  1251. _authRepo.Create(newToken);
  1252. return newToken.AccessToken;
  1253. }
  1254. /// <inheritdoc />
  1255. public void Logout(string accessToken)
  1256. {
  1257. CheckDisposed();
  1258. if (string.IsNullOrEmpty(accessToken))
  1259. {
  1260. throw new ArgumentNullException(nameof(accessToken));
  1261. }
  1262. var existing = _authRepo.Get(
  1263. new AuthenticationInfoQuery
  1264. {
  1265. Limit = 1,
  1266. AccessToken = accessToken
  1267. }).Items;
  1268. if (existing.Count > 0)
  1269. {
  1270. Logout(existing[0]);
  1271. }
  1272. }
  1273. /// <inheritdoc />
  1274. public void Logout(AuthenticationInfo existing)
  1275. {
  1276. CheckDisposed();
  1277. _logger.LogInformation("Logging out access token {0}", existing.AccessToken);
  1278. _authRepo.Delete(existing);
  1279. var sessions = Sessions
  1280. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1281. .ToList();
  1282. foreach (var session in sessions)
  1283. {
  1284. try
  1285. {
  1286. ReportSessionEnded(session.Id);
  1287. }
  1288. catch (Exception ex)
  1289. {
  1290. _logger.LogError("Error reporting session ended", ex);
  1291. }
  1292. }
  1293. }
  1294. /// <inheritdoc />
  1295. public void RevokeUserTokens(Guid userId, string currentAccessToken)
  1296. {
  1297. CheckDisposed();
  1298. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1299. {
  1300. UserId = userId
  1301. });
  1302. foreach (var info in existing.Items)
  1303. {
  1304. if (!string.Equals(currentAccessToken, info.AccessToken, StringComparison.OrdinalIgnoreCase))
  1305. {
  1306. Logout(info);
  1307. }
  1308. }
  1309. }
  1310. /// <inheritdoc />
  1311. public void RevokeToken(string token)
  1312. {
  1313. Logout(token);
  1314. }
  1315. /// <summary>
  1316. /// Reports the capabilities.
  1317. /// </summary>
  1318. /// <param name="sessionId">The session identifier.</param>
  1319. /// <param name="capabilities">The capabilities.</param>
  1320. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1321. {
  1322. CheckDisposed();
  1323. var session = GetSession(sessionId);
  1324. ReportCapabilities(session, capabilities, true);
  1325. }
  1326. private void ReportCapabilities(
  1327. SessionInfo session,
  1328. ClientCapabilities capabilities,
  1329. bool saveCapabilities)
  1330. {
  1331. session.Capabilities = capabilities;
  1332. if (saveCapabilities)
  1333. {
  1334. CapabilitiesChanged?.Invoke(
  1335. this,
  1336. new SessionEventArgs
  1337. {
  1338. SessionInfo = session
  1339. });
  1340. try
  1341. {
  1342. SaveCapabilities(session.DeviceId, capabilities);
  1343. }
  1344. catch (Exception ex)
  1345. {
  1346. _logger.LogError("Error saving device capabilities", ex);
  1347. }
  1348. }
  1349. }
  1350. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1351. {
  1352. return _deviceManager.GetCapabilities(deviceId);
  1353. }
  1354. private void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1355. {
  1356. _deviceManager.SaveCapabilities(deviceId, capabilities);
  1357. }
  1358. /// <summary>
  1359. /// Converts a BaseItem to a BaseItemInfo.
  1360. /// </summary>
  1361. private BaseItemDto GetItemInfo(BaseItem item, MediaSourceInfo mediaSource)
  1362. {
  1363. if (item == null)
  1364. {
  1365. throw new ArgumentNullException(nameof(item));
  1366. }
  1367. var dtoOptions = _itemInfoDtoOptions;
  1368. if (_itemInfoDtoOptions == null)
  1369. {
  1370. dtoOptions = new DtoOptions
  1371. {
  1372. AddProgramRecordingInfo = false
  1373. };
  1374. var fields = dtoOptions.Fields.ToList();
  1375. fields.Remove(ItemFields.BasicSyncInfo);
  1376. fields.Remove(ItemFields.CanDelete);
  1377. fields.Remove(ItemFields.CanDownload);
  1378. fields.Remove(ItemFields.ChildCount);
  1379. fields.Remove(ItemFields.CustomRating);
  1380. fields.Remove(ItemFields.DateLastMediaAdded);
  1381. fields.Remove(ItemFields.DateLastRefreshed);
  1382. fields.Remove(ItemFields.DateLastSaved);
  1383. fields.Remove(ItemFields.DisplayPreferencesId);
  1384. fields.Remove(ItemFields.Etag);
  1385. fields.Remove(ItemFields.InheritedParentalRatingValue);
  1386. fields.Remove(ItemFields.ItemCounts);
  1387. fields.Remove(ItemFields.MediaSourceCount);
  1388. fields.Remove(ItemFields.MediaStreams);
  1389. fields.Remove(ItemFields.MediaSources);
  1390. fields.Remove(ItemFields.People);
  1391. fields.Remove(ItemFields.PlayAccess);
  1392. fields.Remove(ItemFields.People);
  1393. fields.Remove(ItemFields.ProductionLocations);
  1394. fields.Remove(ItemFields.RecursiveItemCount);
  1395. fields.Remove(ItemFields.RemoteTrailers);
  1396. fields.Remove(ItemFields.SeasonUserData);
  1397. fields.Remove(ItemFields.Settings);
  1398. fields.Remove(ItemFields.SortName);
  1399. fields.Remove(ItemFields.Tags);
  1400. fields.Remove(ItemFields.ExtraIds);
  1401. dtoOptions.Fields = fields.ToArray();
  1402. _itemInfoDtoOptions = dtoOptions;
  1403. }
  1404. var info = _dtoService.GetBaseItemDto(item, dtoOptions);
  1405. if (mediaSource != null)
  1406. {
  1407. info.MediaStreams = mediaSource.MediaStreams.ToArray();
  1408. }
  1409. return info;
  1410. }
  1411. private string GetImageCacheTag(BaseItem item, ImageType type)
  1412. {
  1413. try
  1414. {
  1415. return _imageProcessor.GetImageCacheTag(item, type);
  1416. }
  1417. catch (Exception ex)
  1418. {
  1419. _logger.LogError(ex, "Error getting image information for {Type}", type);
  1420. return null;
  1421. }
  1422. }
  1423. /// <inheritdoc />
  1424. public void ReportNowViewingItem(string sessionId, string itemId)
  1425. {
  1426. if (string.IsNullOrEmpty(itemId))
  1427. {
  1428. throw new ArgumentNullException(nameof(itemId));
  1429. }
  1430. var item = _libraryManager.GetItemById(new Guid(itemId));
  1431. var info = GetItemInfo(item, null);
  1432. ReportNowViewingItem(sessionId, info);
  1433. }
  1434. /// <inheritdoc />
  1435. public void ReportNowViewingItem(string sessionId, BaseItemDto item)
  1436. {
  1437. var session = GetSession(sessionId);
  1438. session.NowViewingItem = item;
  1439. }
  1440. /// <inheritdoc />
  1441. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1442. {
  1443. var session = Sessions.FirstOrDefault(i =>
  1444. string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase));
  1445. if (session != null)
  1446. {
  1447. session.TranscodingInfo = info;
  1448. }
  1449. }
  1450. /// <inheritdoc />
  1451. public void ClearTranscodingInfo(string deviceId)
  1452. {
  1453. ReportTranscodingInfo(deviceId, null);
  1454. }
  1455. /// <inheritdoc />
  1456. public SessionInfo GetSession(string deviceId, string client, string version)
  1457. {
  1458. return Sessions.FirstOrDefault(i =>
  1459. string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)
  1460. && string.Equals(i.Client, client, StringComparison.OrdinalIgnoreCase));
  1461. }
  1462. /// <inheritdoc />
  1463. public SessionInfo GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1464. {
  1465. if (info == null)
  1466. {
  1467. throw new ArgumentNullException(nameof(info));
  1468. }
  1469. var user = info.UserId == Guid.Empty
  1470. ? null
  1471. : _userManager.GetUserById(info.UserId);
  1472. appVersion = string.IsNullOrEmpty(appVersion)
  1473. ? info.AppVersion
  1474. : appVersion;
  1475. var deviceName = info.DeviceName;
  1476. var appName = info.AppName;
  1477. if (string.IsNullOrEmpty(deviceId))
  1478. {
  1479. deviceId = info.DeviceId;
  1480. }
  1481. // Prevent argument exception
  1482. if (string.IsNullOrEmpty(appVersion))
  1483. {
  1484. appVersion = "1";
  1485. }
  1486. return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1487. }
  1488. /// <inheritdoc />
  1489. public SessionInfo GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1490. {
  1491. var items = _authRepo.Get(new AuthenticationInfoQuery
  1492. {
  1493. AccessToken = token,
  1494. Limit = 1
  1495. }).Items;
  1496. if (items.Count == 0)
  1497. {
  1498. return null;
  1499. }
  1500. return GetSessionByAuthenticationToken(items[0], deviceId, remoteEndpoint, null);
  1501. }
  1502. /// <inheritdoc />
  1503. public Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken)
  1504. {
  1505. CheckDisposed();
  1506. var adminUserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToList();
  1507. return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken);
  1508. }
  1509. /// <inheritdoc />
  1510. public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, Func<T> dataFn, CancellationToken cancellationToken)
  1511. {
  1512. CheckDisposed();
  1513. var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser)).ToList();
  1514. if (sessions.Count == 0)
  1515. {
  1516. return Task.CompletedTask;
  1517. }
  1518. return SendMessageToSessions(sessions, name, dataFn(), cancellationToken);
  1519. }
  1520. /// <inheritdoc />
  1521. public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, T data, CancellationToken cancellationToken)
  1522. {
  1523. CheckDisposed();
  1524. var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser));
  1525. return SendMessageToSessions(sessions, name, data, cancellationToken);
  1526. }
  1527. /// <inheritdoc />
  1528. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data, CancellationToken cancellationToken)
  1529. {
  1530. CheckDisposed();
  1531. var sessions = Sessions.Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase));
  1532. return SendMessageToSessions(sessions, name, data, cancellationToken);
  1533. }
  1534. }
  1535. }