SessionManager.cs 65 KB

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