SessionManager.cs 65 KB

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