SessionManager.cs 62 KB

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