SessionManager.cs 67 KB

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