SessionManager.cs 62 KB

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