SessionManager.cs 63 KB

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