SessionManager.cs 65 KB

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