2
0

SessionManager.cs 65 KB

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