SessionManager.cs 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  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 = await _deviceManager.RegisterDevice(deviceId, deviceName, appName, appVersion, userIdString).ConfigureAwait(false);
  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 = await _deviceManager.RegisterDevice(deviceId, deviceName, appName, appVersion, userIdString).ConfigureAwait(false);
  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. .Where(i => i.LocationType != LocationType.Virtual)
  810. .ToList();
  811. command.PlayCommand = PlayCommand.PlayNow;
  812. }
  813. else
  814. {
  815. var list = new List<BaseItem>();
  816. foreach (var itemId in command.ItemIds)
  817. {
  818. var subItems = TranslateItemForPlayback(itemId, user);
  819. list.AddRange(subItems);
  820. }
  821. items = list
  822. .Where(i => i.LocationType != LocationType.Virtual)
  823. .ToList();
  824. }
  825. if (command.PlayCommand == PlayCommand.PlayShuffle)
  826. {
  827. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  828. command.PlayCommand = PlayCommand.PlayNow;
  829. }
  830. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray(items.Count);
  831. if (user != null)
  832. {
  833. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  834. {
  835. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  836. }
  837. }
  838. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  839. {
  840. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id));
  841. }
  842. if (user != null && command.ItemIds.Length == 1 && user.Configuration.EnableNextEpisodeAutoPlay)
  843. {
  844. var episode = _libraryManager.GetItemById(command.ItemIds[0]) as Episode;
  845. if (episode != null)
  846. {
  847. var series = episode.Series;
  848. if (series != null)
  849. {
  850. var episodes = series.GetEpisodes(user, new DtoOptions(false)
  851. {
  852. EnableImages = false
  853. })
  854. .Where(i => !i.IsVirtualItem)
  855. .SkipWhile(i => i.Id != episode.Id)
  856. .ToList();
  857. if (episodes.Count > 0)
  858. {
  859. command.ItemIds = episodes.Select(i => i.Id.ToString("N")).ToArray(episodes.Count);
  860. }
  861. }
  862. }
  863. }
  864. if (!string.IsNullOrWhiteSpace(controllingSessionId))
  865. {
  866. var controllingSession = GetSession(controllingSessionId);
  867. AssertCanControl(session, controllingSession);
  868. if (controllingSession.UserId.HasValue)
  869. {
  870. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  871. }
  872. }
  873. await session.SessionController.SendPlayCommand(command, cancellationToken).ConfigureAwait(false);
  874. }
  875. private List<BaseItem> TranslateItemForPlayback(string id, User user)
  876. {
  877. var item = _libraryManager.GetItemById(id);
  878. if (item == null)
  879. {
  880. _logger.Error("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
  881. return new List<BaseItem>();
  882. }
  883. var byName = item as IItemByName;
  884. if (byName != null)
  885. {
  886. var items = byName.GetTaggedItems(new InternalItemsQuery(user)
  887. {
  888. IsFolder = false,
  889. Recursive = true,
  890. DtoOptions = new DtoOptions(false)
  891. {
  892. EnableImages = false,
  893. Fields = new ItemFields[]
  894. {
  895. ItemFields.SortName
  896. }
  897. }
  898. });
  899. return FilterToSingleMediaType(items)
  900. .OrderBy(i => i.SortName)
  901. .ToList();
  902. }
  903. if (item.IsFolder)
  904. {
  905. var folder = (Folder)item;
  906. var itemsResult = folder.GetItemList(new InternalItemsQuery(user)
  907. {
  908. Recursive = true,
  909. IsFolder = false,
  910. DtoOptions = new DtoOptions(false)
  911. {
  912. EnableImages = false,
  913. Fields = new ItemFields[]
  914. {
  915. ItemFields.SortName
  916. }
  917. }
  918. });
  919. return FilterToSingleMediaType(itemsResult)
  920. .OrderBy(i => i.SortName)
  921. .ToList();
  922. }
  923. return new List<BaseItem> { item };
  924. }
  925. private IEnumerable<BaseItem> FilterToSingleMediaType(IEnumerable<BaseItem> items)
  926. {
  927. return items
  928. .Where(i => !string.IsNullOrWhiteSpace(i.MediaType))
  929. .ToLookup(i => i.MediaType, StringComparer.OrdinalIgnoreCase)
  930. .OrderByDescending(i => i.Count())
  931. .FirstOrDefault();
  932. }
  933. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  934. {
  935. var item = _libraryManager.GetItemById(id);
  936. if (item == null)
  937. {
  938. _logger.Error("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id);
  939. return new List<BaseItem>();
  940. }
  941. return _musicManager.GetInstantMixFromItem(item, user, new DtoOptions(false) { EnableImages = false });
  942. }
  943. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  944. {
  945. var generalCommand = new GeneralCommand
  946. {
  947. Name = GeneralCommandType.DisplayContent.ToString()
  948. };
  949. generalCommand.Arguments["ItemId"] = command.ItemId;
  950. generalCommand.Arguments["ItemName"] = command.ItemName;
  951. generalCommand.Arguments["ItemType"] = command.ItemType;
  952. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  953. }
  954. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  955. {
  956. var session = GetSessionToRemoteControl(sessionId);
  957. if (!string.IsNullOrWhiteSpace(controllingSessionId))
  958. {
  959. var controllingSession = GetSession(controllingSessionId);
  960. AssertCanControl(session, controllingSession);
  961. if (controllingSession.UserId.HasValue)
  962. {
  963. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  964. }
  965. }
  966. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  967. }
  968. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  969. {
  970. if (session == null)
  971. {
  972. throw new ArgumentNullException("session");
  973. }
  974. if (controllingSession == null)
  975. {
  976. throw new ArgumentNullException("controllingSession");
  977. }
  978. }
  979. /// <summary>
  980. /// Sends the restart required message.
  981. /// </summary>
  982. /// <param name="cancellationToken">The cancellation token.</param>
  983. /// <returns>Task.</returns>
  984. public async Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  985. {
  986. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  987. var info = await _appHost.GetSystemInfo().ConfigureAwait(false);
  988. var tasks = sessions.Select(session => Task.Run(async () =>
  989. {
  990. try
  991. {
  992. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  993. }
  994. catch (Exception ex)
  995. {
  996. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  997. }
  998. }, cancellationToken));
  999. await Task.WhenAll(tasks).ConfigureAwait(false);
  1000. }
  1001. /// <summary>
  1002. /// Sends the server shutdown notification.
  1003. /// </summary>
  1004. /// <param name="cancellationToken">The cancellation token.</param>
  1005. /// <returns>Task.</returns>
  1006. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  1007. {
  1008. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1009. var tasks = sessions.Select(session => Task.Run(async () =>
  1010. {
  1011. try
  1012. {
  1013. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  1014. }
  1015. catch (Exception ex)
  1016. {
  1017. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  1018. }
  1019. }, cancellationToken));
  1020. return Task.WhenAll(tasks);
  1021. }
  1022. /// <summary>
  1023. /// Sends the server restart notification.
  1024. /// </summary>
  1025. /// <param name="cancellationToken">The cancellation token.</param>
  1026. /// <returns>Task.</returns>
  1027. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  1028. {
  1029. _logger.Debug("Beginning SendServerRestartNotification");
  1030. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1031. var tasks = sessions.Select(session => Task.Run(async () =>
  1032. {
  1033. try
  1034. {
  1035. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  1036. }
  1037. catch (Exception ex)
  1038. {
  1039. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  1040. }
  1041. }, cancellationToken));
  1042. return Task.WhenAll(tasks);
  1043. }
  1044. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1045. {
  1046. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1047. var dto = GetSessionInfoDto(sessionInfo);
  1048. var tasks = sessions.Select(session => Task.Run(async () =>
  1049. {
  1050. try
  1051. {
  1052. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  1053. }
  1054. catch (Exception ex)
  1055. {
  1056. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  1057. }
  1058. }, cancellationToken));
  1059. return Task.WhenAll(tasks);
  1060. }
  1061. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1062. {
  1063. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1064. var dto = GetSessionInfoDto(sessionInfo);
  1065. var tasks = sessions.Select(session => Task.Run(async () =>
  1066. {
  1067. try
  1068. {
  1069. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  1070. }
  1071. catch (Exception ex)
  1072. {
  1073. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  1074. }
  1075. }, cancellationToken));
  1076. return Task.WhenAll(tasks);
  1077. }
  1078. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1079. {
  1080. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1081. var dto = GetSessionInfoDto(sessionInfo);
  1082. var tasks = sessions.Select(session => Task.Run(async () =>
  1083. {
  1084. try
  1085. {
  1086. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  1087. }
  1088. catch (Exception ex)
  1089. {
  1090. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  1091. }
  1092. }, cancellationToken));
  1093. return Task.WhenAll(tasks);
  1094. }
  1095. /// <summary>
  1096. /// Adds 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 AddAdditionalUser(string sessionId, string userId)
  1103. {
  1104. var session = GetSession(sessionId);
  1105. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1106. {
  1107. throw new ArgumentException("The requested user is already the primary user of the session.");
  1108. }
  1109. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != new Guid(userId)))
  1110. {
  1111. var user = _userManager.GetUserById(userId);
  1112. var list = session.AdditionalUsers.ToList();
  1113. list.Add(new SessionUserInfo
  1114. {
  1115. UserId = userId,
  1116. UserName = user.Name
  1117. });
  1118. session.AdditionalUsers = list.ToArray(list.Count);
  1119. }
  1120. }
  1121. /// <summary>
  1122. /// Removes the additional user.
  1123. /// </summary>
  1124. /// <param name="sessionId">The session identifier.</param>
  1125. /// <param name="userId">The user identifier.</param>
  1126. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1127. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  1128. public void RemoveAdditionalUser(string sessionId, string userId)
  1129. {
  1130. var session = GetSession(sessionId);
  1131. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1132. {
  1133. throw new ArgumentException("The requested user is already the primary user of the session.");
  1134. }
  1135. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == new Guid(userId));
  1136. if (user != null)
  1137. {
  1138. var list = session.AdditionalUsers.ToList();
  1139. list.Remove(user);
  1140. session.AdditionalUsers = list.ToArray(list.Count);
  1141. }
  1142. }
  1143. /// <summary>
  1144. /// Authenticates the new session.
  1145. /// </summary>
  1146. /// <param name="request">The request.</param>
  1147. /// <returns>Task{SessionInfo}.</returns>
  1148. public Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  1149. {
  1150. return AuthenticateNewSessionInternal(request, true);
  1151. }
  1152. public Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request)
  1153. {
  1154. return AuthenticateNewSessionInternal(request, false);
  1155. }
  1156. private async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enforcePassword)
  1157. {
  1158. User user = null;
  1159. if (!string.IsNullOrWhiteSpace(request.UserId))
  1160. {
  1161. var idGuid = new Guid(request.UserId);
  1162. user = _userManager.Users
  1163. .FirstOrDefault(i => i.Id == idGuid);
  1164. }
  1165. if (user == null)
  1166. {
  1167. user = _userManager.Users
  1168. .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
  1169. }
  1170. if (user != null)
  1171. {
  1172. if (!user.IsParentalScheduleAllowed())
  1173. {
  1174. throw new SecurityException("User is not allowed access at this time.");
  1175. }
  1176. if (!string.IsNullOrWhiteSpace(request.DeviceId))
  1177. {
  1178. if (!_deviceManager.CanAccessDevice(user.Id.ToString("N"), request.DeviceId))
  1179. {
  1180. throw new SecurityException("User is not allowed access from this device.");
  1181. }
  1182. }
  1183. }
  1184. if (enforcePassword)
  1185. {
  1186. var result = await _userManager.AuthenticateUser(request.Username, request.Password, request.PasswordSha1, request.PasswordMd5, request.RemoteEndPoint).ConfigureAwait(false);
  1187. if (result == null)
  1188. {
  1189. EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1190. throw new SecurityException("Invalid user or password entered.");
  1191. }
  1192. user = result;
  1193. }
  1194. var token = GetAuthorizationToken(user.Id.ToString("N"), request.DeviceId, request.App, request.AppVersion, request.DeviceName);
  1195. EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1196. var session = await LogSessionActivity(request.App,
  1197. request.AppVersion,
  1198. request.DeviceId,
  1199. request.DeviceName,
  1200. request.RemoteEndPoint,
  1201. user)
  1202. .ConfigureAwait(false);
  1203. return new AuthenticationResult
  1204. {
  1205. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1206. SessionInfo = GetSessionInfoDto(session),
  1207. AccessToken = token,
  1208. ServerId = _appHost.SystemId
  1209. };
  1210. }
  1211. private string GetAuthorizationToken(string userId, string deviceId, string app, string appVersion, string deviceName)
  1212. {
  1213. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1214. {
  1215. DeviceId = deviceId,
  1216. IsActive = true,
  1217. UserId = userId,
  1218. Limit = 1
  1219. });
  1220. if (existing.Items.Length > 0)
  1221. {
  1222. var token = existing.Items[0].AccessToken;
  1223. _logger.Info("Reissuing access token: " + token);
  1224. return token;
  1225. }
  1226. var newToken = new AuthenticationInfo
  1227. {
  1228. AppName = app,
  1229. AppVersion = appVersion,
  1230. DateCreated = DateTime.UtcNow,
  1231. DeviceId = deviceId,
  1232. DeviceName = deviceName,
  1233. UserId = userId,
  1234. IsActive = true,
  1235. AccessToken = Guid.NewGuid().ToString("N")
  1236. };
  1237. _logger.Info("Creating new access token for user {0}", userId);
  1238. _authRepo.Create(newToken, CancellationToken.None);
  1239. return newToken.AccessToken;
  1240. }
  1241. public void Logout(string accessToken)
  1242. {
  1243. if (string.IsNullOrWhiteSpace(accessToken))
  1244. {
  1245. throw new ArgumentNullException("accessToken");
  1246. }
  1247. _logger.Info("Logging out access token {0}", accessToken);
  1248. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1249. {
  1250. Limit = 1,
  1251. AccessToken = accessToken
  1252. }).Items.FirstOrDefault();
  1253. if (existing != null)
  1254. {
  1255. existing.IsActive = false;
  1256. _authRepo.Update(existing, CancellationToken.None);
  1257. var sessions = Sessions
  1258. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1259. .ToList();
  1260. foreach (var session in sessions)
  1261. {
  1262. try
  1263. {
  1264. ReportSessionEnded(session.Id);
  1265. }
  1266. catch (Exception ex)
  1267. {
  1268. _logger.ErrorException("Error reporting session ended", ex);
  1269. }
  1270. }
  1271. }
  1272. }
  1273. public void RevokeUserTokens(string userId, string currentAccessToken)
  1274. {
  1275. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1276. {
  1277. IsActive = true,
  1278. UserId = userId
  1279. });
  1280. foreach (var info in existing.Items)
  1281. {
  1282. if (!string.Equals(currentAccessToken, info.AccessToken, StringComparison.OrdinalIgnoreCase))
  1283. {
  1284. Logout(info.AccessToken);
  1285. }
  1286. }
  1287. }
  1288. public void RevokeToken(string token)
  1289. {
  1290. Logout(token);
  1291. }
  1292. /// <summary>
  1293. /// Reports the capabilities.
  1294. /// </summary>
  1295. /// <param name="sessionId">The session identifier.</param>
  1296. /// <param name="capabilities">The capabilities.</param>
  1297. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1298. {
  1299. var session = GetSession(sessionId);
  1300. ReportCapabilities(session, capabilities, true);
  1301. }
  1302. private async void ReportCapabilities(SessionInfo session,
  1303. ClientCapabilities capabilities,
  1304. bool saveCapabilities)
  1305. {
  1306. session.Capabilities = capabilities;
  1307. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1308. {
  1309. var controller = session.SessionController as HttpSessionController;
  1310. if (controller == null)
  1311. {
  1312. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1313. }
  1314. }
  1315. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1316. {
  1317. SessionInfo = session
  1318. }, _logger);
  1319. if (saveCapabilities)
  1320. {
  1321. try
  1322. {
  1323. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1324. }
  1325. catch (Exception ex)
  1326. {
  1327. _logger.ErrorException("Error saving device capabilities", ex);
  1328. }
  1329. }
  1330. }
  1331. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1332. {
  1333. return _deviceManager.GetCapabilities(deviceId);
  1334. }
  1335. private Task SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1336. {
  1337. return _deviceManager.SaveCapabilities(deviceId, capabilities);
  1338. }
  1339. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1340. {
  1341. var dto = new SessionInfoDto
  1342. {
  1343. Client = session.Client,
  1344. DeviceId = session.DeviceId,
  1345. DeviceName = session.DeviceName,
  1346. Id = session.Id,
  1347. LastActivityDate = session.LastActivityDate,
  1348. NowViewingItem = session.NowViewingItem,
  1349. ApplicationVersion = session.ApplicationVersion,
  1350. PlayableMediaTypes = session.PlayableMediaTypes,
  1351. AdditionalUsers = session.AdditionalUsers,
  1352. SupportedCommands = session.SupportedCommands,
  1353. UserName = session.UserName,
  1354. NowPlayingItem = session.NowPlayingItem,
  1355. SupportsRemoteControl = session.SupportsMediaControl,
  1356. PlayState = session.PlayState,
  1357. AppIconUrl = session.AppIconUrl,
  1358. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1359. };
  1360. dto.ServerId = _appHost.SystemId;
  1361. if (session.UserId.HasValue)
  1362. {
  1363. dto.UserId = session.UserId.Value.ToString("N");
  1364. var user = _userManager.GetUserById(session.UserId.Value);
  1365. if (user != null)
  1366. {
  1367. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1368. }
  1369. }
  1370. return dto;
  1371. }
  1372. private DtoOptions _itemInfoDtoOptions;
  1373. /// <summary>
  1374. /// Converts a BaseItem to a BaseItemInfo
  1375. /// </summary>
  1376. private BaseItemDto GetItemInfo(BaseItem item, MediaSourceInfo mediaSource)
  1377. {
  1378. if (item == null)
  1379. {
  1380. throw new ArgumentNullException("item");
  1381. }
  1382. var dtoOptions = _itemInfoDtoOptions;
  1383. if (_itemInfoDtoOptions == null)
  1384. {
  1385. dtoOptions = new DtoOptions
  1386. {
  1387. AddProgramRecordingInfo = false
  1388. };
  1389. var fields = dtoOptions.Fields.ToList();
  1390. fields.Remove(ItemFields.BasicSyncInfo);
  1391. fields.Remove(ItemFields.SyncInfo);
  1392. fields.Remove(ItemFields.CanDelete);
  1393. fields.Remove(ItemFields.CanDownload);
  1394. fields.Remove(ItemFields.ChildCount);
  1395. fields.Remove(ItemFields.CustomRating);
  1396. fields.Remove(ItemFields.DateLastMediaAdded);
  1397. fields.Remove(ItemFields.DateLastRefreshed);
  1398. fields.Remove(ItemFields.DateLastSaved);
  1399. fields.Remove(ItemFields.DisplayPreferencesId);
  1400. fields.Remove(ItemFields.Etag);
  1401. fields.Remove(ItemFields.ExternalEtag);
  1402. fields.Remove(ItemFields.InheritedParentalRatingValue);
  1403. fields.Remove(ItemFields.ItemCounts);
  1404. fields.Remove(ItemFields.MediaSourceCount);
  1405. fields.Remove(ItemFields.MediaStreams);
  1406. fields.Remove(ItemFields.MediaSources);
  1407. fields.Remove(ItemFields.People);
  1408. fields.Remove(ItemFields.PlayAccess);
  1409. fields.Remove(ItemFields.People);
  1410. fields.Remove(ItemFields.ProductionLocations);
  1411. fields.Remove(ItemFields.RecursiveItemCount);
  1412. fields.Remove(ItemFields.RemoteTrailers);
  1413. fields.Remove(ItemFields.SeasonUserData);
  1414. fields.Remove(ItemFields.Settings);
  1415. fields.Remove(ItemFields.SortName);
  1416. fields.Remove(ItemFields.Tags);
  1417. fields.Remove(ItemFields.ThemeSongIds);
  1418. fields.Remove(ItemFields.ThemeVideoIds);
  1419. dtoOptions.Fields = fields.ToArray(fields.Count);
  1420. _itemInfoDtoOptions = dtoOptions;
  1421. }
  1422. var info = _dtoService.GetBaseItemDto(item, dtoOptions);
  1423. if (mediaSource != null)
  1424. {
  1425. info.MediaStreams = mediaSource.MediaStreams.ToArray();
  1426. }
  1427. return info;
  1428. }
  1429. private string GetImageCacheTag(BaseItem item, ImageType type)
  1430. {
  1431. try
  1432. {
  1433. return _imageProcessor.GetImageCacheTag(item, type);
  1434. }
  1435. catch (Exception ex)
  1436. {
  1437. _logger.ErrorException("Error getting {0} image info", ex, type);
  1438. return null;
  1439. }
  1440. }
  1441. private string GetDtoId(BaseItem item)
  1442. {
  1443. return _dtoService.GetDtoId(item);
  1444. }
  1445. public void ReportNowViewingItem(string sessionId, string itemId)
  1446. {
  1447. if (string.IsNullOrWhiteSpace(itemId))
  1448. {
  1449. throw new ArgumentNullException("itemId");
  1450. }
  1451. //var item = _libraryManager.GetItemById(new Guid(itemId));
  1452. //var info = GetItemInfo(item, null, null);
  1453. //ReportNowViewingItem(sessionId, info);
  1454. }
  1455. public void ReportNowViewingItem(string sessionId, BaseItemDto item)
  1456. {
  1457. //var session = GetSession(sessionId);
  1458. //session.NowViewingItem = item;
  1459. }
  1460. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1461. {
  1462. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1463. if (session != null)
  1464. {
  1465. session.TranscodingInfo = info;
  1466. }
  1467. }
  1468. public void ClearTranscodingInfo(string deviceId)
  1469. {
  1470. ReportTranscodingInfo(deviceId, null);
  1471. }
  1472. public SessionInfo GetSession(string deviceId, string client, string version)
  1473. {
  1474. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1475. string.Equals(i.Client, client));
  1476. }
  1477. public Task<SessionInfo> GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1478. {
  1479. if (info == null)
  1480. {
  1481. throw new ArgumentNullException("info");
  1482. }
  1483. var user = string.IsNullOrWhiteSpace(info.UserId)
  1484. ? null
  1485. : _userManager.GetUserById(info.UserId);
  1486. appVersion = string.IsNullOrWhiteSpace(appVersion)
  1487. ? info.AppVersion
  1488. : appVersion;
  1489. var deviceName = info.DeviceName;
  1490. var appName = info.AppName;
  1491. if (!string.IsNullOrWhiteSpace(deviceId))
  1492. {
  1493. // Replace the info from the token with more recent info
  1494. var device = _deviceManager.GetDevice(deviceId);
  1495. if (device != null)
  1496. {
  1497. deviceName = device.Name;
  1498. appName = device.AppName;
  1499. if (!string.IsNullOrWhiteSpace(device.AppVersion))
  1500. {
  1501. appVersion = device.AppVersion;
  1502. }
  1503. }
  1504. }
  1505. else
  1506. {
  1507. deviceId = info.DeviceId;
  1508. }
  1509. // Prevent argument exception
  1510. if (string.IsNullOrWhiteSpace(appVersion))
  1511. {
  1512. appVersion = "1";
  1513. }
  1514. return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1515. }
  1516. public Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1517. {
  1518. var result = _authRepo.Get(new AuthenticationInfoQuery
  1519. {
  1520. AccessToken = token
  1521. });
  1522. var info = result.Items.FirstOrDefault();
  1523. if (info == null)
  1524. {
  1525. return Task.FromResult<SessionInfo>(null);
  1526. }
  1527. return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
  1528. }
  1529. public Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken)
  1530. {
  1531. var adminUserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id.ToString("N")).ToList();
  1532. return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken);
  1533. }
  1534. public Task SendMessageToUserSessions<T>(List<string> userIds, string name, T data,
  1535. CancellationToken cancellationToken)
  1536. {
  1537. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && userIds.Any(i.ContainsUser)).ToList();
  1538. var tasks = sessions.Select(session => Task.Run(async () =>
  1539. {
  1540. try
  1541. {
  1542. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1543. }
  1544. catch (Exception ex)
  1545. {
  1546. _logger.ErrorException("Error sending message", ex);
  1547. }
  1548. }, cancellationToken));
  1549. return Task.WhenAll(tasks);
  1550. }
  1551. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data,
  1552. CancellationToken cancellationToken)
  1553. {
  1554. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
  1555. var tasks = sessions.Select(session => Task.Run(async () =>
  1556. {
  1557. try
  1558. {
  1559. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1560. }
  1561. catch (Exception ex)
  1562. {
  1563. _logger.ErrorException("Error sending message", ex);
  1564. }
  1565. }, cancellationToken));
  1566. return Task.WhenAll(tasks);
  1567. }
  1568. }
  1569. }