SessionManager.cs 63 KB

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