SessionManager.cs 64 KB

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