SessionManager.cs 64 KB

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