SessionManager.cs 64 KB

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