SessionManager.cs 63 KB

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