SessionManager.cs 67 KB

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