SessionManager.cs 65 KB

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