SessionManager.cs 63 KB

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