SessionManager.cs 65 KB

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