SessionManager.cs 64 KB

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