SessionManager.cs 67 KB

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