SessionManager.cs 64 KB

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