SessionManager.cs 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900
  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 (!string.IsNullOrEmpty(capabilities.PushToken))
  1302. {
  1303. if (string.Equals(capabilities.PushTokenType, "firebase", StringComparison.OrdinalIgnoreCase) && FirebaseSessionController.IsSupported(_appHost))
  1304. {
  1305. EnsureFirebaseController(session, capabilities.PushToken);
  1306. }
  1307. }
  1308. if (saveCapabilities)
  1309. {
  1310. CapabilitiesChanged?.Invoke(this, new SessionEventArgs
  1311. {
  1312. SessionInfo = session
  1313. });
  1314. try
  1315. {
  1316. SaveCapabilities(session.DeviceId, capabilities);
  1317. }
  1318. catch (Exception ex)
  1319. {
  1320. _logger.LogError("Error saving device capabilities", ex);
  1321. }
  1322. }
  1323. }
  1324. private void EnsureFirebaseController(SessionInfo session, string token)
  1325. {
  1326. session.EnsureController<FirebaseSessionController>(s => new FirebaseSessionController(_httpClient, _appHost, _jsonSerializer, s, token, this));
  1327. }
  1328. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1329. {
  1330. return _deviceManager.GetCapabilities(deviceId);
  1331. }
  1332. private void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1333. {
  1334. _deviceManager.SaveCapabilities(deviceId, capabilities);
  1335. }
  1336. private DtoOptions _itemInfoDtoOptions;
  1337. /// <summary>
  1338. /// Converts a BaseItem to a BaseItemInfo
  1339. /// </summary>
  1340. private BaseItemDto GetItemInfo(BaseItem item, MediaSourceInfo mediaSource)
  1341. {
  1342. if (item == null)
  1343. {
  1344. throw new ArgumentNullException("item");
  1345. }
  1346. var dtoOptions = _itemInfoDtoOptions;
  1347. if (_itemInfoDtoOptions == null)
  1348. {
  1349. dtoOptions = new DtoOptions
  1350. {
  1351. AddProgramRecordingInfo = false
  1352. };
  1353. var fields = dtoOptions.Fields.ToList();
  1354. fields.Remove(ItemFields.BasicSyncInfo);
  1355. fields.Remove(ItemFields.CanDelete);
  1356. fields.Remove(ItemFields.CanDownload);
  1357. fields.Remove(ItemFields.ChildCount);
  1358. fields.Remove(ItemFields.CustomRating);
  1359. fields.Remove(ItemFields.DateLastMediaAdded);
  1360. fields.Remove(ItemFields.DateLastRefreshed);
  1361. fields.Remove(ItemFields.DateLastSaved);
  1362. fields.Remove(ItemFields.DisplayPreferencesId);
  1363. fields.Remove(ItemFields.Etag);
  1364. fields.Remove(ItemFields.InheritedParentalRatingValue);
  1365. fields.Remove(ItemFields.ItemCounts);
  1366. fields.Remove(ItemFields.MediaSourceCount);
  1367. fields.Remove(ItemFields.MediaStreams);
  1368. fields.Remove(ItemFields.MediaSources);
  1369. fields.Remove(ItemFields.People);
  1370. fields.Remove(ItemFields.PlayAccess);
  1371. fields.Remove(ItemFields.People);
  1372. fields.Remove(ItemFields.ProductionLocations);
  1373. fields.Remove(ItemFields.RecursiveItemCount);
  1374. fields.Remove(ItemFields.RemoteTrailers);
  1375. fields.Remove(ItemFields.SeasonUserData);
  1376. fields.Remove(ItemFields.Settings);
  1377. fields.Remove(ItemFields.SortName);
  1378. fields.Remove(ItemFields.Tags);
  1379. fields.Remove(ItemFields.ExtraIds);
  1380. dtoOptions.Fields = fields.ToArray();
  1381. _itemInfoDtoOptions = dtoOptions;
  1382. }
  1383. var info = _dtoService.GetBaseItemDto(item, dtoOptions);
  1384. if (mediaSource != null)
  1385. {
  1386. info.MediaStreams = mediaSource.MediaStreams.ToArray();
  1387. }
  1388. return info;
  1389. }
  1390. private string GetImageCacheTag(BaseItem item, ImageType type)
  1391. {
  1392. try
  1393. {
  1394. return _imageProcessor.GetImageCacheTag(item, type);
  1395. }
  1396. catch (Exception ex)
  1397. {
  1398. _logger.LogError("Error getting {0} image info", ex, type);
  1399. return null;
  1400. }
  1401. }
  1402. public void ReportNowViewingItem(string sessionId, string itemId)
  1403. {
  1404. if (string.IsNullOrEmpty(itemId))
  1405. {
  1406. throw new ArgumentNullException("itemId");
  1407. }
  1408. //var item = _libraryManager.GetItemById(new Guid(itemId));
  1409. //var info = GetItemInfo(item, null, null);
  1410. //ReportNowViewingItem(sessionId, info);
  1411. }
  1412. public void ReportNowViewingItem(string sessionId, BaseItemDto item)
  1413. {
  1414. //var session = GetSession(sessionId);
  1415. //session.NowViewingItem = item;
  1416. }
  1417. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1418. {
  1419. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1420. if (session != null)
  1421. {
  1422. session.TranscodingInfo = info;
  1423. }
  1424. }
  1425. public void ClearTranscodingInfo(string deviceId)
  1426. {
  1427. ReportTranscodingInfo(deviceId, null);
  1428. }
  1429. public SessionInfo GetSession(string deviceId, string client, string version)
  1430. {
  1431. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1432. string.Equals(i.Client, client));
  1433. }
  1434. public SessionInfo GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1435. {
  1436. if (info == null)
  1437. {
  1438. throw new ArgumentNullException("info");
  1439. }
  1440. var user = info.UserId.Equals(Guid.Empty)
  1441. ? null
  1442. : _userManager.GetUserById(info.UserId);
  1443. appVersion = string.IsNullOrEmpty(appVersion)
  1444. ? info.AppVersion
  1445. : appVersion;
  1446. var deviceName = info.DeviceName;
  1447. var appName = info.AppName;
  1448. if (string.IsNullOrEmpty(deviceId))
  1449. {
  1450. deviceId = info.DeviceId;
  1451. }
  1452. // Prevent argument exception
  1453. if (string.IsNullOrEmpty(appVersion))
  1454. {
  1455. appVersion = "1";
  1456. }
  1457. return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1458. }
  1459. public SessionInfo GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1460. {
  1461. var result = _authRepo.Get(new AuthenticationInfoQuery
  1462. {
  1463. AccessToken = token
  1464. });
  1465. var info = result.Items.FirstOrDefault();
  1466. if (info == null)
  1467. {
  1468. return null;
  1469. }
  1470. return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
  1471. }
  1472. public Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken)
  1473. {
  1474. CheckDisposed();
  1475. var adminUserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToList();
  1476. return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken);
  1477. }
  1478. public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, Func<T> dataFn, CancellationToken cancellationToken)
  1479. {
  1480. CheckDisposed();
  1481. var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser)).ToList();
  1482. if (sessions.Count == 0)
  1483. {
  1484. return Task.CompletedTask;
  1485. }
  1486. var data = dataFn();
  1487. var tasks = sessions.Select(session => Task.Run(async () =>
  1488. {
  1489. try
  1490. {
  1491. await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
  1492. }
  1493. catch (Exception ex)
  1494. {
  1495. _logger.LogError("Error sending message", ex);
  1496. }
  1497. }, cancellationToken)).ToArray();
  1498. return Task.WhenAll(tasks);
  1499. }
  1500. public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, T data, CancellationToken cancellationToken)
  1501. {
  1502. CheckDisposed();
  1503. var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser)).ToList();
  1504. var tasks = sessions.Select(session => Task.Run(async () =>
  1505. {
  1506. try
  1507. {
  1508. await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
  1509. }
  1510. catch (Exception ex)
  1511. {
  1512. _logger.LogError("Error sending message", ex);
  1513. }
  1514. }, cancellationToken)).ToArray();
  1515. return Task.WhenAll(tasks);
  1516. }
  1517. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data, CancellationToken cancellationToken)
  1518. {
  1519. CheckDisposed();
  1520. var sessions = Sessions.Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
  1521. var tasks = sessions.Select(session => Task.Run(async () =>
  1522. {
  1523. try
  1524. {
  1525. await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
  1526. }
  1527. catch (Exception ex)
  1528. {
  1529. _logger.LogError("Error sending message", ex);
  1530. }
  1531. }, cancellationToken)).ToArray();
  1532. return Task.WhenAll(tasks);
  1533. }
  1534. public Task SendMessageToUserDeviceAndAdminSessions<T>(string deviceId, string name, T data, CancellationToken cancellationToken)
  1535. {
  1536. CheckDisposed();
  1537. var sessions = Sessions
  1538. .Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase) || IsAdminSession(i))
  1539. .ToList();
  1540. var tasks = sessions.Select(session => Task.Run(async () =>
  1541. {
  1542. try
  1543. {
  1544. await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
  1545. }
  1546. catch (Exception ex)
  1547. {
  1548. _logger.LogError("Error sending message", ex);
  1549. }
  1550. }, cancellationToken)).ToArray();
  1551. return Task.WhenAll(tasks);
  1552. }
  1553. private bool IsAdminSession(SessionInfo s)
  1554. {
  1555. var user = _userManager.GetUserById(s.UserId);
  1556. return user != null && user.Policy.IsAdministrator;
  1557. }
  1558. }
  1559. }