2
0

SessionManager.cs 64 KB

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