SessionManager.cs 64 KB

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