SessionManager.cs 64 KB

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