SessionManager.cs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  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 MediaBrowser.Model.SyncPlay;
  29. using Microsoft.Extensions.Logging;
  30. namespace Emby.Server.Implementations.Session
  31. {
  32. /// <summary>
  33. /// Class SessionManager.
  34. /// </summary>
  35. public class SessionManager : ISessionManager, IDisposable
  36. {
  37. /// <summary>
  38. /// The user data repository.
  39. /// </summary>
  40. private readonly IUserDataManager _userDataManager;
  41. /// <summary>
  42. /// The logger.
  43. /// </summary>
  44. private readonly ILogger _logger;
  45. private readonly ILibraryManager _libraryManager;
  46. private readonly IUserManager _userManager;
  47. private readonly IMusicManager _musicManager;
  48. private readonly IDtoService _dtoService;
  49. private readonly IImageProcessor _imageProcessor;
  50. private readonly IMediaSourceManager _mediaSourceManager;
  51. private readonly IServerApplicationHost _appHost;
  52. private readonly IAuthenticationRepository _authRepo;
  53. private readonly IDeviceManager _deviceManager;
  54. /// <summary>
  55. /// The active connections.
  56. /// </summary>
  57. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  58. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  59. private Timer _idleTimer;
  60. private DtoOptions _itemInfoDtoOptions;
  61. private bool _disposed = false;
  62. public SessionManager(
  63. ILogger<SessionManager> logger,
  64. IUserDataManager userDataManager,
  65. ILibraryManager libraryManager,
  66. IUserManager userManager,
  67. IMusicManager musicManager,
  68. IDtoService dtoService,
  69. IImageProcessor imageProcessor,
  70. IServerApplicationHost appHost,
  71. IAuthenticationRepository authRepo,
  72. IDeviceManager deviceManager,
  73. IMediaSourceManager mediaSourceManager)
  74. {
  75. _logger = logger;
  76. _userDataManager = userDataManager;
  77. _libraryManager = libraryManager;
  78. _userManager = userManager;
  79. _musicManager = musicManager;
  80. _dtoService = dtoService;
  81. _imageProcessor = imageProcessor;
  82. _appHost = appHost;
  83. _authRepo = authRepo;
  84. _deviceManager = deviceManager;
  85. _mediaSourceManager = mediaSourceManager;
  86. _deviceManager.DeviceOptionsUpdated += OnDeviceManagerDeviceOptionsUpdated;
  87. }
  88. /// <inheritdoc />
  89. public event EventHandler<GenericEventArgs<AuthenticationRequest>> AuthenticationFailed;
  90. /// <inheritdoc />
  91. public event EventHandler<GenericEventArgs<AuthenticationResult>> AuthenticationSucceeded;
  92. /// <summary>
  93. /// Occurs when playback has started.
  94. /// </summary>
  95. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  96. /// <summary>
  97. /// Occurs when playback has progressed.
  98. /// </summary>
  99. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  100. /// <summary>
  101. /// Occurs when playback has stopped.
  102. /// </summary>
  103. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  104. /// <inheritdoc />
  105. public event EventHandler<SessionEventArgs> SessionStarted;
  106. /// <inheritdoc />
  107. public event EventHandler<SessionEventArgs> CapabilitiesChanged;
  108. /// <inheritdoc />
  109. public event EventHandler<SessionEventArgs> SessionEnded;
  110. /// <inheritdoc />
  111. public event EventHandler<SessionEventArgs> SessionActivity;
  112. /// <summary>
  113. /// Gets all connections.
  114. /// </summary>
  115. /// <value>All connections.</value>
  116. public IEnumerable<SessionInfo> Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate);
  117. private void OnDeviceManagerDeviceOptionsUpdated(object sender, GenericEventArgs<Tuple<string, DeviceOptions>> e)
  118. {
  119. foreach (var session in Sessions)
  120. {
  121. if (string.Equals(session.DeviceId, e.Argument.Item1, StringComparison.Ordinal))
  122. {
  123. if (!string.IsNullOrWhiteSpace(e.Argument.Item2.CustomName))
  124. {
  125. session.HasCustomDeviceName = true;
  126. session.DeviceName = e.Argument.Item2.CustomName;
  127. }
  128. else
  129. {
  130. session.HasCustomDeviceName = false;
  131. }
  132. }
  133. }
  134. }
  135. /// <inheritdoc />
  136. public void Dispose()
  137. {
  138. Dispose(true);
  139. GC.SuppressFinalize(this);
  140. }
  141. /// <summary>
  142. /// Releases unmanaged and optionally managed resources.
  143. /// </summary>
  144. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  145. protected virtual void Dispose(bool disposing)
  146. {
  147. if (_disposed)
  148. {
  149. return;
  150. }
  151. if (disposing)
  152. {
  153. _idleTimer?.Dispose();
  154. }
  155. _idleTimer = null;
  156. _deviceManager.DeviceOptionsUpdated -= OnDeviceManagerDeviceOptionsUpdated;
  157. _disposed = true;
  158. }
  159. private void CheckDisposed()
  160. {
  161. if (_disposed)
  162. {
  163. throw new ObjectDisposedException(GetType().Name);
  164. }
  165. }
  166. private void OnSessionStarted(SessionInfo info)
  167. {
  168. if (!string.IsNullOrEmpty(info.DeviceId))
  169. {
  170. var capabilities = GetSavedCapabilities(info.DeviceId);
  171. if (capabilities != null)
  172. {
  173. ReportCapabilities(info, capabilities, false);
  174. }
  175. }
  176. EventHelper.QueueEventIfNotNull(
  177. SessionStarted,
  178. this,
  179. new SessionEventArgs
  180. {
  181. SessionInfo = info
  182. },
  183. _logger);
  184. }
  185. private void OnSessionEnded(SessionInfo info)
  186. {
  187. EventHelper.QueueEventIfNotNull(
  188. SessionEnded,
  189. this,
  190. new SessionEventArgs
  191. {
  192. SessionInfo = info
  193. },
  194. _logger);
  195. info.Dispose();
  196. }
  197. /// <inheritdoc />
  198. public void UpdateDeviceName(string sessionId, string deviceName)
  199. {
  200. var session = GetSession(sessionId);
  201. if (session != null)
  202. {
  203. session.DeviceName = deviceName;
  204. }
  205. }
  206. /// <summary>
  207. /// Logs the user activity.
  208. /// </summary>
  209. /// <param name="appName">Type of the client.</param>
  210. /// <param name="appVersion">The app version.</param>
  211. /// <param name="deviceId">The device id.</param>
  212. /// <param name="deviceName">Name of the device.</param>
  213. /// <param name="remoteEndPoint">The remote end point.</param>
  214. /// <param name="user">The user.</param>
  215. /// <returns>SessionInfo.</returns>
  216. public SessionInfo LogSessionActivity(
  217. string appName,
  218. string appVersion,
  219. string deviceId,
  220. string deviceName,
  221. string remoteEndPoint,
  222. User user)
  223. {
  224. CheckDisposed();
  225. if (string.IsNullOrEmpty(appName))
  226. {
  227. throw new ArgumentNullException(nameof(appName));
  228. }
  229. if (string.IsNullOrEmpty(appVersion))
  230. {
  231. throw new ArgumentNullException(nameof(appVersion));
  232. }
  233. if (string.IsNullOrEmpty(deviceId))
  234. {
  235. throw new ArgumentNullException(nameof(deviceId));
  236. }
  237. var activityDate = DateTime.UtcNow;
  238. var session = GetSessionInfo(appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
  239. var lastActivityDate = session.LastActivityDate;
  240. session.LastActivityDate = activityDate;
  241. if (user != null)
  242. {
  243. var userLastActivityDate = user.LastActivityDate ?? DateTime.MinValue;
  244. user.LastActivityDate = activityDate;
  245. if ((activityDate - userLastActivityDate).TotalSeconds > 60)
  246. {
  247. _userManager.UpdateUser(user);
  248. }
  249. }
  250. if ((activityDate - lastActivityDate).TotalSeconds > 10)
  251. {
  252. SessionActivity?.Invoke(
  253. this,
  254. new SessionEventArgs
  255. {
  256. SessionInfo = session
  257. });
  258. }
  259. return session;
  260. }
  261. /// <inheritdoc />
  262. public void CloseIfNeeded(SessionInfo session)
  263. {
  264. if (!session.SessionControllers.Any(i => i.IsSessionActive))
  265. {
  266. var key = GetSessionKey(session.Client, session.DeviceId);
  267. _activeConnections.TryRemove(key, out _);
  268. OnSessionEnded(session);
  269. }
  270. }
  271. /// <inheritdoc />
  272. public void ReportSessionEnded(string sessionId)
  273. {
  274. CheckDisposed();
  275. var session = GetSession(sessionId, false);
  276. if (session != null)
  277. {
  278. var key = GetSessionKey(session.Client, session.DeviceId);
  279. _activeConnections.TryRemove(key, out _);
  280. OnSessionEnded(session);
  281. }
  282. }
  283. private Task<MediaSourceInfo> GetMediaSource(BaseItem item, string mediaSourceId, string liveStreamId)
  284. {
  285. return _mediaSourceManager.GetMediaSource(item, mediaSourceId, liveStreamId, false, CancellationToken.None);
  286. }
  287. /// <summary>
  288. /// Updates the now playing item id.
  289. /// </summary>
  290. /// <returns>Task.</returns>
  291. private async Task UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem, bool updateLastCheckInTime)
  292. {
  293. if (string.IsNullOrEmpty(info.MediaSourceId))
  294. {
  295. info.MediaSourceId = info.ItemId.ToString("N", CultureInfo.InvariantCulture);
  296. }
  297. if (!info.ItemId.Equals(Guid.Empty) && info.Item == null && libraryItem != null)
  298. {
  299. var current = session.NowPlayingItem;
  300. if (current == null || !info.ItemId.Equals(current.Id))
  301. {
  302. var runtimeTicks = libraryItem.RunTimeTicks;
  303. MediaSourceInfo mediaSource = null;
  304. if (libraryItem is IHasMediaSources)
  305. {
  306. mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
  307. if (mediaSource != null)
  308. {
  309. runtimeTicks = mediaSource.RunTimeTicks;
  310. }
  311. }
  312. info.Item = GetItemInfo(libraryItem, mediaSource);
  313. info.Item.RunTimeTicks = runtimeTicks;
  314. }
  315. else
  316. {
  317. info.Item = current;
  318. }
  319. }
  320. session.NowPlayingItem = info.Item;
  321. session.LastActivityDate = DateTime.UtcNow;
  322. if (updateLastCheckInTime)
  323. {
  324. session.LastPlaybackCheckIn = DateTime.UtcNow;
  325. }
  326. session.PlayState.IsPaused = info.IsPaused;
  327. session.PlayState.PositionTicks = info.PositionTicks;
  328. session.PlayState.MediaSourceId = info.MediaSourceId;
  329. session.PlayState.CanSeek = info.CanSeek;
  330. session.PlayState.IsMuted = info.IsMuted;
  331. session.PlayState.VolumeLevel = info.VolumeLevel;
  332. session.PlayState.AudioStreamIndex = info.AudioStreamIndex;
  333. session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex;
  334. session.PlayState.PlayMethod = info.PlayMethod;
  335. session.PlayState.RepeatMode = info.RepeatMode;
  336. session.PlaylistItemId = info.PlaylistItemId;
  337. var nowPlayingQueue = info.NowPlayingQueue;
  338. if (nowPlayingQueue != null)
  339. {
  340. session.NowPlayingQueue = nowPlayingQueue;
  341. }
  342. }
  343. /// <summary>
  344. /// Removes the now playing item id.
  345. /// </summary>
  346. /// <param name="session">The session.</param>
  347. private void RemoveNowPlayingItem(SessionInfo session)
  348. {
  349. session.NowPlayingItem = null;
  350. session.PlayState = new PlayerStateInfo();
  351. if (!string.IsNullOrEmpty(session.DeviceId))
  352. {
  353. ClearTranscodingInfo(session.DeviceId);
  354. }
  355. }
  356. private static string GetSessionKey(string appName, string deviceId)
  357. => appName + deviceId;
  358. /// <summary>
  359. /// Gets the connection.
  360. /// </summary>
  361. /// <param name="appName">Type of the client.</param>
  362. /// <param name="appVersion">The app version.</param>
  363. /// <param name="deviceId">The device id.</param>
  364. /// <param name="deviceName">Name of the device.</param>
  365. /// <param name="remoteEndPoint">The remote end point.</param>
  366. /// <param name="user">The user.</param>
  367. /// <returns>SessionInfo.</returns>
  368. private SessionInfo GetSessionInfo(string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
  369. {
  370. CheckDisposed();
  371. if (string.IsNullOrEmpty(deviceId))
  372. {
  373. throw new ArgumentNullException(nameof(deviceId));
  374. }
  375. var key = GetSessionKey(appName, deviceId);
  376. CheckDisposed();
  377. var sessionInfo = _activeConnections.GetOrAdd(key, k =>
  378. {
  379. return CreateSession(k, appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
  380. });
  381. sessionInfo.UserId = user == null ? Guid.Empty : user.Id;
  382. sessionInfo.UserName = user?.Name;
  383. sessionInfo.UserPrimaryImageTag = user == null ? null : GetImageCacheTag(user, ImageType.Primary);
  384. sessionInfo.RemoteEndPoint = remoteEndPoint;
  385. sessionInfo.Client = appName;
  386. if (!sessionInfo.HasCustomDeviceName || string.IsNullOrEmpty(sessionInfo.DeviceName))
  387. {
  388. sessionInfo.DeviceName = deviceName;
  389. }
  390. sessionInfo.ApplicationVersion = appVersion;
  391. if (user == null)
  392. {
  393. sessionInfo.AdditionalUsers = Array.Empty<SessionUserInfo>();
  394. }
  395. return sessionInfo;
  396. }
  397. private SessionInfo CreateSession(string key, string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
  398. {
  399. var sessionInfo = new SessionInfo(this, _logger)
  400. {
  401. Client = appName,
  402. DeviceId = deviceId,
  403. ApplicationVersion = appVersion,
  404. Id = key.GetMD5().ToString("N", CultureInfo.InvariantCulture)
  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;
  870. var messageId = Guid.NewGuid();
  871. foreach (var controller in controllers)
  872. {
  873. await controller.SendMessage(name, messageId, data, 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();
  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, 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. /// <inheritdoc />
  964. public async Task SendSyncPlayCommand(string sessionId, SendCommand command, CancellationToken cancellationToken)
  965. {
  966. CheckDisposed();
  967. var session = GetSessionToRemoteControl(sessionId);
  968. await SendMessageToSession(session, "SyncPlayCommand", command, cancellationToken).ConfigureAwait(false);
  969. }
  970. /// <inheritdoc />
  971. public async Task SendSyncPlayGroupUpdate<T>(string sessionId, GroupUpdate<T> command, CancellationToken cancellationToken)
  972. {
  973. CheckDisposed();
  974. var session = GetSessionToRemoteControl(sessionId);
  975. await SendMessageToSession(session, "SyncPlayGroupUpdate", command, cancellationToken).ConfigureAwait(false);
  976. }
  977. private IEnumerable<BaseItem> TranslateItemForPlayback(Guid id, User user)
  978. {
  979. var item = _libraryManager.GetItemById(id);
  980. if (item == null)
  981. {
  982. _logger.LogError("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
  983. return Array.Empty<BaseItem>();
  984. }
  985. if (item is IItemByName byName)
  986. {
  987. return byName.GetTaggedItems(new InternalItemsQuery(user)
  988. {
  989. IsFolder = false,
  990. Recursive = true,
  991. DtoOptions = new DtoOptions(false)
  992. {
  993. EnableImages = false,
  994. Fields = new ItemFields[]
  995. {
  996. ItemFields.SortName
  997. }
  998. },
  999. IsVirtualItem = false,
  1000. OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }
  1001. });
  1002. }
  1003. if (item.IsFolder)
  1004. {
  1005. var folder = (Folder)item;
  1006. return folder.GetItemList(new InternalItemsQuery(user)
  1007. {
  1008. Recursive = true,
  1009. IsFolder = false,
  1010. DtoOptions = new DtoOptions(false)
  1011. {
  1012. EnableImages = false,
  1013. Fields = new ItemFields[]
  1014. {
  1015. ItemFields.SortName
  1016. }
  1017. },
  1018. IsVirtualItem = false,
  1019. OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }
  1020. });
  1021. }
  1022. return new[] { item };
  1023. }
  1024. private IEnumerable<BaseItem> TranslateItemForInstantMix(Guid id, User user)
  1025. {
  1026. var item = _libraryManager.GetItemById(id);
  1027. if (item == null)
  1028. {
  1029. _logger.LogError("A non-existent item Id {0} was passed into TranslateItemForInstantMix", id);
  1030. return new List<BaseItem>();
  1031. }
  1032. return _musicManager.GetInstantMixFromItem(item, user, new DtoOptions(false) { EnableImages = false });
  1033. }
  1034. /// <inheritdoc />
  1035. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  1036. {
  1037. var generalCommand = new GeneralCommand
  1038. {
  1039. Name = GeneralCommandType.DisplayContent.ToString(),
  1040. Arguments =
  1041. {
  1042. ["ItemId"] = command.ItemId,
  1043. ["ItemName"] = command.ItemName,
  1044. ["ItemType"] = command.ItemType
  1045. }
  1046. };
  1047. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  1048. }
  1049. /// <inheritdoc />
  1050. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  1051. {
  1052. CheckDisposed();
  1053. var session = GetSessionToRemoteControl(sessionId);
  1054. if (!string.IsNullOrEmpty(controllingSessionId))
  1055. {
  1056. var controllingSession = GetSession(controllingSessionId);
  1057. AssertCanControl(session, controllingSession);
  1058. if (!controllingSession.UserId.Equals(Guid.Empty))
  1059. {
  1060. command.ControllingUserId = controllingSession.UserId.ToString("N", CultureInfo.InvariantCulture);
  1061. }
  1062. }
  1063. return SendMessageToSession(session, "Playstate", command, cancellationToken);
  1064. }
  1065. private static void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  1066. {
  1067. if (session == null)
  1068. {
  1069. throw new ArgumentNullException(nameof(session));
  1070. }
  1071. if (controllingSession == null)
  1072. {
  1073. throw new ArgumentNullException(nameof(controllingSession));
  1074. }
  1075. }
  1076. /// <summary>
  1077. /// Sends the restart required message.
  1078. /// </summary>
  1079. /// <param name="cancellationToken">The cancellation token.</param>
  1080. /// <returns>Task.</returns>
  1081. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  1082. {
  1083. CheckDisposed();
  1084. return SendMessageToSessions(Sessions, "RestartRequired", string.Empty, cancellationToken);
  1085. }
  1086. /// <summary>
  1087. /// Sends the server shutdown notification.
  1088. /// </summary>
  1089. /// <param name="cancellationToken">The cancellation token.</param>
  1090. /// <returns>Task.</returns>
  1091. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  1092. {
  1093. CheckDisposed();
  1094. return SendMessageToSessions(Sessions, "ServerShuttingDown", string.Empty, cancellationToken);
  1095. }
  1096. /// <summary>
  1097. /// Sends the server restart notification.
  1098. /// </summary>
  1099. /// <param name="cancellationToken">The cancellation token.</param>
  1100. /// <returns>Task.</returns>
  1101. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  1102. {
  1103. CheckDisposed();
  1104. _logger.LogDebug("Beginning SendServerRestartNotification");
  1105. return SendMessageToSessions(Sessions, "ServerRestarting", string.Empty, cancellationToken);
  1106. }
  1107. /// <summary>
  1108. /// Adds the additional user.
  1109. /// </summary>
  1110. /// <param name="sessionId">The session identifier.</param>
  1111. /// <param name="userId">The user identifier.</param>
  1112. /// <exception cref="UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1113. /// <exception cref="ArgumentException">The requested user is already the primary user of the session.</exception>
  1114. public void AddAdditionalUser(string sessionId, Guid userId)
  1115. {
  1116. CheckDisposed();
  1117. var session = GetSession(sessionId);
  1118. if (session.UserId == userId)
  1119. {
  1120. throw new ArgumentException("The requested user is already the primary user of the session.");
  1121. }
  1122. if (session.AdditionalUsers.All(i => i.UserId != userId))
  1123. {
  1124. var user = _userManager.GetUserById(userId);
  1125. var list = session.AdditionalUsers.ToList();
  1126. list.Add(new SessionUserInfo
  1127. {
  1128. UserId = userId,
  1129. UserName = user.Name
  1130. });
  1131. session.AdditionalUsers = list.ToArray();
  1132. }
  1133. }
  1134. /// <summary>
  1135. /// Removes the additional user.
  1136. /// </summary>
  1137. /// <param name="sessionId">The session identifier.</param>
  1138. /// <param name="userId">The user identifier.</param>
  1139. /// <exception cref="UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1140. /// <exception cref="ArgumentException">The requested user is already the primary user of the session.</exception>
  1141. public void RemoveAdditionalUser(string sessionId, Guid userId)
  1142. {
  1143. CheckDisposed();
  1144. var session = GetSession(sessionId);
  1145. if (session.UserId.Equals(userId))
  1146. {
  1147. throw new ArgumentException("The requested user is already the primary user of the session.");
  1148. }
  1149. var user = session.AdditionalUsers.FirstOrDefault(i => i.UserId.Equals(userId));
  1150. if (user != null)
  1151. {
  1152. var list = session.AdditionalUsers.ToList();
  1153. list.Remove(user);
  1154. session.AdditionalUsers = list.ToArray();
  1155. }
  1156. }
  1157. /// <summary>
  1158. /// Authenticates the new session.
  1159. /// </summary>
  1160. /// <param name="request">The request.</param>
  1161. /// <returns>Task{SessionInfo}.</returns>
  1162. public Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  1163. {
  1164. return AuthenticateNewSessionInternal(request, true);
  1165. }
  1166. public Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request)
  1167. {
  1168. return AuthenticateNewSessionInternal(request, false);
  1169. }
  1170. private async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enforcePassword)
  1171. {
  1172. CheckDisposed();
  1173. User user = null;
  1174. if (request.UserId != Guid.Empty)
  1175. {
  1176. user = _userManager.GetUserById(request.UserId);
  1177. }
  1178. if (user == null)
  1179. {
  1180. user = _userManager.GetUserByName(request.Username);
  1181. }
  1182. if (enforcePassword)
  1183. {
  1184. user = await _userManager.AuthenticateUser(
  1185. request.Username,
  1186. request.Password,
  1187. request.PasswordSha1,
  1188. request.RemoteEndPoint,
  1189. true).ConfigureAwait(false);
  1190. }
  1191. if (user == null)
  1192. {
  1193. AuthenticationFailed?.Invoke(this, new GenericEventArgs<AuthenticationRequest>(request));
  1194. throw new AuthenticationException("Invalid username or password entered.");
  1195. }
  1196. if (!string.IsNullOrEmpty(request.DeviceId)
  1197. && !_deviceManager.CanAccessDevice(user, request.DeviceId))
  1198. {
  1199. throw new SecurityException("User is not allowed access from this device.");
  1200. }
  1201. var token = GetAuthorizationToken(user, request.DeviceId, request.App, request.AppVersion, request.DeviceName);
  1202. var session = LogSessionActivity(
  1203. request.App,
  1204. request.AppVersion,
  1205. request.DeviceId,
  1206. request.DeviceName,
  1207. request.RemoteEndPoint,
  1208. user);
  1209. var returnResult = new AuthenticationResult
  1210. {
  1211. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1212. SessionInfo = session,
  1213. AccessToken = token,
  1214. ServerId = _appHost.SystemId
  1215. };
  1216. AuthenticationSucceeded?.Invoke(this, new GenericEventArgs<AuthenticationResult>(returnResult));
  1217. return returnResult;
  1218. }
  1219. private string GetAuthorizationToken(User user, string deviceId, string app, string appVersion, string deviceName)
  1220. {
  1221. var existing = _authRepo.Get(
  1222. new AuthenticationInfoQuery
  1223. {
  1224. DeviceId = deviceId,
  1225. UserId = user.Id,
  1226. Limit = 1
  1227. }).Items.FirstOrDefault();
  1228. var allExistingForDevice = _authRepo.Get(
  1229. new AuthenticationInfoQuery
  1230. {
  1231. DeviceId = deviceId
  1232. }).Items;
  1233. foreach (var auth in allExistingForDevice)
  1234. {
  1235. if (existing == null || !string.Equals(auth.AccessToken, existing.AccessToken, StringComparison.Ordinal))
  1236. {
  1237. try
  1238. {
  1239. Logout(auth);
  1240. }
  1241. catch (Exception ex)
  1242. {
  1243. _logger.LogError(ex, "Error while logging out.");
  1244. }
  1245. }
  1246. }
  1247. if (existing != null)
  1248. {
  1249. _logger.LogInformation("Reissuing access token: {Token}", existing.AccessToken);
  1250. return existing.AccessToken;
  1251. }
  1252. var now = DateTime.UtcNow;
  1253. var newToken = new AuthenticationInfo
  1254. {
  1255. AppName = app,
  1256. AppVersion = appVersion,
  1257. DateCreated = now,
  1258. DateLastActivity = now,
  1259. DeviceId = deviceId,
  1260. DeviceName = deviceName,
  1261. UserId = user.Id,
  1262. AccessToken = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
  1263. UserName = user.Name
  1264. };
  1265. _logger.LogInformation("Creating new access token for user {0}", user.Id);
  1266. _authRepo.Create(newToken);
  1267. return newToken.AccessToken;
  1268. }
  1269. /// <inheritdoc />
  1270. public void Logout(string accessToken)
  1271. {
  1272. CheckDisposed();
  1273. if (string.IsNullOrEmpty(accessToken))
  1274. {
  1275. throw new ArgumentNullException(nameof(accessToken));
  1276. }
  1277. var existing = _authRepo.Get(
  1278. new AuthenticationInfoQuery
  1279. {
  1280. Limit = 1,
  1281. AccessToken = accessToken
  1282. }).Items;
  1283. if (existing.Count > 0)
  1284. {
  1285. Logout(existing[0]);
  1286. }
  1287. }
  1288. /// <inheritdoc />
  1289. public void Logout(AuthenticationInfo existing)
  1290. {
  1291. CheckDisposed();
  1292. _logger.LogInformation("Logging out access token {0}", existing.AccessToken);
  1293. _authRepo.Delete(existing);
  1294. var sessions = Sessions
  1295. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1296. .ToList();
  1297. foreach (var session in sessions)
  1298. {
  1299. try
  1300. {
  1301. ReportSessionEnded(session.Id);
  1302. }
  1303. catch (Exception ex)
  1304. {
  1305. _logger.LogError("Error reporting session ended", ex);
  1306. }
  1307. }
  1308. }
  1309. /// <inheritdoc />
  1310. public void RevokeUserTokens(Guid userId, string currentAccessToken)
  1311. {
  1312. CheckDisposed();
  1313. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1314. {
  1315. UserId = userId
  1316. });
  1317. foreach (var info in existing.Items)
  1318. {
  1319. if (!string.Equals(currentAccessToken, info.AccessToken, StringComparison.OrdinalIgnoreCase))
  1320. {
  1321. Logout(info);
  1322. }
  1323. }
  1324. }
  1325. /// <inheritdoc />
  1326. public void RevokeToken(string token)
  1327. {
  1328. Logout(token);
  1329. }
  1330. /// <summary>
  1331. /// Reports the capabilities.
  1332. /// </summary>
  1333. /// <param name="sessionId">The session identifier.</param>
  1334. /// <param name="capabilities">The capabilities.</param>
  1335. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1336. {
  1337. CheckDisposed();
  1338. var session = GetSession(sessionId);
  1339. ReportCapabilities(session, capabilities, true);
  1340. }
  1341. private void ReportCapabilities(
  1342. SessionInfo session,
  1343. ClientCapabilities capabilities,
  1344. bool saveCapabilities)
  1345. {
  1346. session.Capabilities = capabilities;
  1347. if (saveCapabilities)
  1348. {
  1349. CapabilitiesChanged?.Invoke(
  1350. this,
  1351. new SessionEventArgs
  1352. {
  1353. SessionInfo = session
  1354. });
  1355. try
  1356. {
  1357. SaveCapabilities(session.DeviceId, capabilities);
  1358. }
  1359. catch (Exception ex)
  1360. {
  1361. _logger.LogError("Error saving device capabilities", ex);
  1362. }
  1363. }
  1364. }
  1365. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1366. {
  1367. return _deviceManager.GetCapabilities(deviceId);
  1368. }
  1369. private void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1370. {
  1371. _deviceManager.SaveCapabilities(deviceId, capabilities);
  1372. }
  1373. /// <summary>
  1374. /// Converts a BaseItem to a BaseItemInfo.
  1375. /// </summary>
  1376. private BaseItemDto GetItemInfo(BaseItem item, MediaSourceInfo mediaSource)
  1377. {
  1378. if (item == null)
  1379. {
  1380. throw new ArgumentNullException(nameof(item));
  1381. }
  1382. var dtoOptions = _itemInfoDtoOptions;
  1383. if (_itemInfoDtoOptions == null)
  1384. {
  1385. dtoOptions = new DtoOptions
  1386. {
  1387. AddProgramRecordingInfo = false
  1388. };
  1389. var fields = dtoOptions.Fields.ToList();
  1390. fields.Remove(ItemFields.BasicSyncInfo);
  1391. fields.Remove(ItemFields.CanDelete);
  1392. fields.Remove(ItemFields.CanDownload);
  1393. fields.Remove(ItemFields.ChildCount);
  1394. fields.Remove(ItemFields.CustomRating);
  1395. fields.Remove(ItemFields.DateLastMediaAdded);
  1396. fields.Remove(ItemFields.DateLastRefreshed);
  1397. fields.Remove(ItemFields.DateLastSaved);
  1398. fields.Remove(ItemFields.DisplayPreferencesId);
  1399. fields.Remove(ItemFields.Etag);
  1400. fields.Remove(ItemFields.InheritedParentalRatingValue);
  1401. fields.Remove(ItemFields.ItemCounts);
  1402. fields.Remove(ItemFields.MediaSourceCount);
  1403. fields.Remove(ItemFields.MediaStreams);
  1404. fields.Remove(ItemFields.MediaSources);
  1405. fields.Remove(ItemFields.People);
  1406. fields.Remove(ItemFields.PlayAccess);
  1407. fields.Remove(ItemFields.People);
  1408. fields.Remove(ItemFields.ProductionLocations);
  1409. fields.Remove(ItemFields.RecursiveItemCount);
  1410. fields.Remove(ItemFields.RemoteTrailers);
  1411. fields.Remove(ItemFields.SeasonUserData);
  1412. fields.Remove(ItemFields.Settings);
  1413. fields.Remove(ItemFields.SortName);
  1414. fields.Remove(ItemFields.Tags);
  1415. fields.Remove(ItemFields.ExtraIds);
  1416. dtoOptions.Fields = fields.ToArray();
  1417. _itemInfoDtoOptions = dtoOptions;
  1418. }
  1419. var info = _dtoService.GetBaseItemDto(item, dtoOptions);
  1420. if (mediaSource != null)
  1421. {
  1422. info.MediaStreams = mediaSource.MediaStreams.ToArray();
  1423. }
  1424. return info;
  1425. }
  1426. private string GetImageCacheTag(BaseItem item, ImageType type)
  1427. {
  1428. try
  1429. {
  1430. return _imageProcessor.GetImageCacheTag(item, type);
  1431. }
  1432. catch (Exception ex)
  1433. {
  1434. _logger.LogError(ex, "Error getting image information for {Type}", type);
  1435. return null;
  1436. }
  1437. }
  1438. /// <inheritdoc />
  1439. public void ReportNowViewingItem(string sessionId, string itemId)
  1440. {
  1441. if (string.IsNullOrEmpty(itemId))
  1442. {
  1443. throw new ArgumentNullException(nameof(itemId));
  1444. }
  1445. var item = _libraryManager.GetItemById(new Guid(itemId));
  1446. var info = GetItemInfo(item, null);
  1447. ReportNowViewingItem(sessionId, info);
  1448. }
  1449. /// <inheritdoc />
  1450. public void ReportNowViewingItem(string sessionId, BaseItemDto item)
  1451. {
  1452. var session = GetSession(sessionId);
  1453. session.NowViewingItem = item;
  1454. }
  1455. /// <inheritdoc />
  1456. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1457. {
  1458. var session = Sessions.FirstOrDefault(i =>
  1459. string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase));
  1460. if (session != null)
  1461. {
  1462. session.TranscodingInfo = info;
  1463. }
  1464. }
  1465. /// <inheritdoc />
  1466. public void ClearTranscodingInfo(string deviceId)
  1467. {
  1468. ReportTranscodingInfo(deviceId, null);
  1469. }
  1470. /// <inheritdoc />
  1471. public SessionInfo GetSession(string deviceId, string client, string version)
  1472. {
  1473. return Sessions.FirstOrDefault(i =>
  1474. string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)
  1475. && string.Equals(i.Client, client, StringComparison.OrdinalIgnoreCase));
  1476. }
  1477. /// <inheritdoc />
  1478. public SessionInfo GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1479. {
  1480. if (info == null)
  1481. {
  1482. throw new ArgumentNullException(nameof(info));
  1483. }
  1484. var user = info.UserId == Guid.Empty
  1485. ? null
  1486. : _userManager.GetUserById(info.UserId);
  1487. appVersion = string.IsNullOrEmpty(appVersion)
  1488. ? info.AppVersion
  1489. : appVersion;
  1490. var deviceName = info.DeviceName;
  1491. var appName = info.AppName;
  1492. if (string.IsNullOrEmpty(deviceId))
  1493. {
  1494. deviceId = info.DeviceId;
  1495. }
  1496. // Prevent argument exception
  1497. if (string.IsNullOrEmpty(appVersion))
  1498. {
  1499. appVersion = "1";
  1500. }
  1501. return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1502. }
  1503. /// <inheritdoc />
  1504. public SessionInfo GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1505. {
  1506. var items = _authRepo.Get(new AuthenticationInfoQuery
  1507. {
  1508. AccessToken = token,
  1509. Limit = 1
  1510. }).Items;
  1511. if (items.Count == 0)
  1512. {
  1513. return null;
  1514. }
  1515. return GetSessionByAuthenticationToken(items[0], deviceId, remoteEndpoint, null);
  1516. }
  1517. /// <inheritdoc />
  1518. public Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken)
  1519. {
  1520. CheckDisposed();
  1521. var adminUserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToList();
  1522. return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken);
  1523. }
  1524. /// <inheritdoc />
  1525. public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, Func<T> dataFn, CancellationToken cancellationToken)
  1526. {
  1527. CheckDisposed();
  1528. var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser)).ToList();
  1529. if (sessions.Count == 0)
  1530. {
  1531. return Task.CompletedTask;
  1532. }
  1533. return SendMessageToSessions(sessions, name, dataFn(), cancellationToken);
  1534. }
  1535. /// <inheritdoc />
  1536. public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, T data, CancellationToken cancellationToken)
  1537. {
  1538. CheckDisposed();
  1539. var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser));
  1540. return SendMessageToSessions(sessions, name, data, cancellationToken);
  1541. }
  1542. /// <inheritdoc />
  1543. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data, CancellationToken cancellationToken)
  1544. {
  1545. CheckDisposed();
  1546. var sessions = Sessions.Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase));
  1547. return SendMessageToSessions(sessions, name, data, cancellationToken);
  1548. }
  1549. }
  1550. }