SessionManager.cs 64 KB

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