SessionManager.cs 65 KB

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