SessionManager.cs 65 KB

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