SessionManager.cs 66 KB

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