SessionManager.cs 62 KB

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