SessionManager.cs 64 KB

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