SessionManager.cs 65 KB

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