SessionManager.cs 62 KB

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