SessionManager.cs 67 KB

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