SessionManager.cs 63 KB

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