SessionManager.cs 64 KB

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