SessionManager.cs 64 KB

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