SessionManager.cs 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  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.Audio;
  10. using MediaBrowser.Controller.Entities.TV;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.LiveTv;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Security;
  15. using MediaBrowser.Controller.Session;
  16. using MediaBrowser.Model.Devices;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.Events;
  20. using MediaBrowser.Model.Library;
  21. using MediaBrowser.Model.Logging;
  22. using MediaBrowser.Model.Serialization;
  23. using MediaBrowser.Model.Session;
  24. using MediaBrowser.Model.Users;
  25. using System;
  26. using System.Collections.Concurrent;
  27. using System.Collections.Generic;
  28. using System.Globalization;
  29. using System.Linq;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32. using MediaBrowser.Controller.Net;
  33. using MediaBrowser.Model.Threading;
  34. namespace Emby.Server.Implementations.Session
  35. {
  36. /// <summary>
  37. /// Class SessionManager
  38. /// </summary>
  39. public class SessionManager : ISessionManager
  40. {
  41. /// <summary>
  42. /// The _user data repository
  43. /// </summary>
  44. private readonly IUserDataManager _userDataManager;
  45. /// <summary>
  46. /// The _logger
  47. /// </summary>
  48. private readonly ILogger _logger;
  49. private readonly ILibraryManager _libraryManager;
  50. private readonly IUserManager _userManager;
  51. private readonly IMusicManager _musicManager;
  52. private readonly IDtoService _dtoService;
  53. private readonly IImageProcessor _imageProcessor;
  54. private readonly IMediaSourceManager _mediaSourceManager;
  55. private readonly IHttpClient _httpClient;
  56. private readonly IJsonSerializer _jsonSerializer;
  57. private readonly IServerApplicationHost _appHost;
  58. private readonly IAuthenticationRepository _authRepo;
  59. private readonly IDeviceManager _deviceManager;
  60. private readonly ITimerFactory _timerFactory;
  61. /// <summary>
  62. /// The _active connections
  63. /// </summary>
  64. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  65. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  66. public event EventHandler<GenericEventArgs<AuthenticationRequest>> AuthenticationFailed;
  67. public event EventHandler<GenericEventArgs<AuthenticationRequest>> AuthenticationSucceeded;
  68. /// <summary>
  69. /// Occurs when [playback start].
  70. /// </summary>
  71. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  72. /// <summary>
  73. /// Occurs when [playback progress].
  74. /// </summary>
  75. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  76. /// <summary>
  77. /// Occurs when [playback stopped].
  78. /// </summary>
  79. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  80. public event EventHandler<SessionEventArgs> SessionStarted;
  81. public event EventHandler<SessionEventArgs> CapabilitiesChanged;
  82. public event EventHandler<SessionEventArgs> SessionEnded;
  83. public event EventHandler<SessionEventArgs> SessionActivity;
  84. private IEnumerable<ISessionControllerFactory> _sessionFactories = new List<ISessionControllerFactory>();
  85. private readonly SemaphoreSlim _sessionLock = new SemaphoreSlim(1, 1);
  86. 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)
  87. {
  88. _userDataManager = userDataManager;
  89. _logger = logger;
  90. _libraryManager = libraryManager;
  91. _userManager = userManager;
  92. _musicManager = musicManager;
  93. _dtoService = dtoService;
  94. _imageProcessor = imageProcessor;
  95. _jsonSerializer = jsonSerializer;
  96. _appHost = appHost;
  97. _httpClient = httpClient;
  98. _authRepo = authRepo;
  99. _deviceManager = deviceManager;
  100. _mediaSourceManager = mediaSourceManager;
  101. _timerFactory = timerFactory;
  102. _deviceManager.DeviceOptionsUpdated += _deviceManager_DeviceOptionsUpdated;
  103. }
  104. void _deviceManager_DeviceOptionsUpdated(object sender, GenericEventArgs<DeviceInfo> e)
  105. {
  106. foreach (var session in Sessions)
  107. {
  108. if (string.Equals(session.DeviceId, e.Argument.Id))
  109. {
  110. session.DeviceName = e.Argument.Name;
  111. }
  112. }
  113. }
  114. /// <summary>
  115. /// Adds the parts.
  116. /// </summary>
  117. /// <param name="sessionFactories">The session factories.</param>
  118. public void AddParts(IEnumerable<ISessionControllerFactory> sessionFactories)
  119. {
  120. _sessionFactories = sessionFactories.ToList();
  121. }
  122. /// <summary>
  123. /// Gets all connections.
  124. /// </summary>
  125. /// <value>All connections.</value>
  126. public IEnumerable<SessionInfo> Sessions
  127. {
  128. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList(); }
  129. }
  130. private void OnSessionStarted(SessionInfo info)
  131. {
  132. EventHelper.QueueEventIfNotNull(SessionStarted, this, new SessionEventArgs
  133. {
  134. SessionInfo = info
  135. }, _logger);
  136. if (!string.IsNullOrWhiteSpace(info.DeviceId))
  137. {
  138. var capabilities = GetSavedCapabilities(info.DeviceId);
  139. if (capabilities != null)
  140. {
  141. info.AppIconUrl = capabilities.IconUrl;
  142. ReportCapabilities(info, capabilities, false);
  143. }
  144. }
  145. }
  146. private async void OnSessionEnded(SessionInfo info)
  147. {
  148. try
  149. {
  150. await SendSessionEndedNotification(info, CancellationToken.None).ConfigureAwait(false);
  151. }
  152. catch (Exception ex)
  153. {
  154. _logger.ErrorException("Error in SendSessionEndedNotification", ex);
  155. }
  156. EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
  157. {
  158. SessionInfo = info
  159. }, _logger);
  160. var disposable = info.SessionController as IDisposable;
  161. if (disposable != null)
  162. {
  163. _logger.Debug("Disposing session controller {0}", disposable.GetType().Name);
  164. try
  165. {
  166. disposable.Dispose();
  167. }
  168. catch (Exception ex)
  169. {
  170. _logger.ErrorException("Error disposing session controller", ex);
  171. }
  172. }
  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. await _userManager.UpdateUser(user).ConfigureAwait(false);
  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. /// <param name="session">The session.</param>
  270. /// <param name="info">The information.</param>
  271. /// <param name="libraryItem">The library item.</param>
  272. private async Task UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem)
  273. {
  274. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  275. {
  276. info.MediaSourceId = info.ItemId;
  277. }
  278. if (!string.IsNullOrWhiteSpace(info.ItemId) && info.Item == null && libraryItem != null)
  279. {
  280. var current = session.NowPlayingItem;
  281. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  282. {
  283. var runtimeTicks = libraryItem.RunTimeTicks;
  284. MediaSourceInfo mediaSource = null;
  285. var hasMediaSources = libraryItem as IHasMediaSources;
  286. if (hasMediaSources != null)
  287. {
  288. mediaSource = await GetMediaSource(hasMediaSources, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
  289. if (mediaSource != null)
  290. {
  291. runtimeTicks = mediaSource.RunTimeTicks;
  292. }
  293. }
  294. info.Item = GetItemInfo(libraryItem, libraryItem, mediaSource);
  295. info.Item.RunTimeTicks = runtimeTicks;
  296. }
  297. else
  298. {
  299. info.Item = current;
  300. }
  301. }
  302. session.NowPlayingItem = info.Item;
  303. session.LastActivityDate = DateTime.UtcNow;
  304. session.LastPlaybackCheckIn = DateTime.UtcNow;
  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
  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.Clear();
  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).ConfigureAwait(false);
  513. if (!string.IsNullOrEmpty(session.DeviceId) && info.PlayMethod != PlayMethod.Transcode)
  514. {
  515. ClearTranscodingInfo(session.DeviceId);
  516. }
  517. session.QueueableMediaTypes = info.QueueableMediaTypes;
  518. var users = GetUsers(session);
  519. if (libraryItem != null)
  520. {
  521. foreach (var user in users)
  522. {
  523. await OnPlaybackStart(user.Id, libraryItem).ConfigureAwait(false);
  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. /// <returns>Task.</returns>
  547. private async Task OnPlaybackStart(Guid userId, IHasUserData item)
  548. {
  549. var data = _userDataManager.GetUserData(userId, item);
  550. data.PlayCount++;
  551. data.LastPlayedDate = DateTime.UtcNow;
  552. if (item.SupportsPlayedStatus)
  553. {
  554. if (!(item is Video))
  555. {
  556. data.Played = true;
  557. }
  558. }
  559. else
  560. {
  561. data.Played = false;
  562. }
  563. await _userDataManager.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  564. }
  565. /// <summary>
  566. /// Used to report playback progress for an item
  567. /// </summary>
  568. /// <param name="info">The info.</param>
  569. /// <returns>Task.</returns>
  570. /// <exception cref="System.ArgumentNullException"></exception>
  571. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  572. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  573. {
  574. if (info == null)
  575. {
  576. throw new ArgumentNullException("info");
  577. }
  578. var session = GetSession(info.SessionId);
  579. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  580. ? null
  581. : GetNowPlayingItem(session, info.ItemId);
  582. await UpdateNowPlayingItem(session, info, libraryItem).ConfigureAwait(false);
  583. var users = GetUsers(session);
  584. if (libraryItem != null)
  585. {
  586. foreach (var user in users)
  587. {
  588. await OnPlaybackProgress(user, libraryItem, info).ConfigureAwait(false);
  589. }
  590. }
  591. if (!string.IsNullOrWhiteSpace(info.LiveStreamId))
  592. {
  593. try
  594. {
  595. await _mediaSourceManager.PingLiveStream(info.LiveStreamId, CancellationToken.None).ConfigureAwait(false);
  596. }
  597. catch (Exception ex)
  598. {
  599. _logger.ErrorException("Error closing live stream", ex);
  600. }
  601. }
  602. EventHelper.FireEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  603. {
  604. Item = libraryItem,
  605. Users = users,
  606. PlaybackPositionTicks = session.PlayState.PositionTicks,
  607. MediaSourceId = session.PlayState.MediaSourceId,
  608. MediaInfo = info.Item,
  609. DeviceName = session.DeviceName,
  610. ClientName = session.Client,
  611. DeviceId = session.DeviceId,
  612. IsPaused = info.IsPaused,
  613. PlaySessionId = info.PlaySessionId
  614. }, _logger);
  615. StartIdleCheckTimer();
  616. }
  617. private async Task OnPlaybackProgress(User user, BaseItem item, PlaybackProgressInfo info)
  618. {
  619. var data = _userDataManager.GetUserData(user.Id, item);
  620. var positionTicks = info.PositionTicks;
  621. if (positionTicks.HasValue)
  622. {
  623. _userDataManager.UpdatePlayState(item, data, positionTicks.Value);
  624. UpdatePlaybackSettings(user, info, data);
  625. await _userDataManager.SaveUserData(user.Id, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  626. }
  627. }
  628. private void UpdatePlaybackSettings(User user, PlaybackProgressInfo info, UserItemData data)
  629. {
  630. if (user.Configuration.RememberAudioSelections)
  631. {
  632. data.AudioStreamIndex = info.AudioStreamIndex;
  633. }
  634. else
  635. {
  636. data.AudioStreamIndex = null;
  637. }
  638. if (user.Configuration.RememberSubtitleSelections)
  639. {
  640. data.SubtitleStreamIndex = info.SubtitleStreamIndex;
  641. }
  642. else
  643. {
  644. data.SubtitleStreamIndex = null;
  645. }
  646. }
  647. /// <summary>
  648. /// Used to report that playback has ended for an item
  649. /// </summary>
  650. /// <param name="info">The info.</param>
  651. /// <returns>Task.</returns>
  652. /// <exception cref="System.ArgumentNullException">info</exception>
  653. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  654. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  655. {
  656. if (info == null)
  657. {
  658. throw new ArgumentNullException("info");
  659. }
  660. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  661. {
  662. throw new ArgumentOutOfRangeException("positionTicks");
  663. }
  664. var session = GetSession(info.SessionId);
  665. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  666. ? null
  667. : GetNowPlayingItem(session, info.ItemId);
  668. // Normalize
  669. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  670. {
  671. info.MediaSourceId = info.ItemId;
  672. }
  673. if (!string.IsNullOrWhiteSpace(info.ItemId) && info.Item == null && libraryItem != null)
  674. {
  675. var current = session.NowPlayingItem;
  676. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  677. {
  678. MediaSourceInfo mediaSource = null;
  679. var hasMediaSources = libraryItem as IHasMediaSources;
  680. if (hasMediaSources != null)
  681. {
  682. mediaSource = await GetMediaSource(hasMediaSources, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
  683. }
  684. info.Item = GetItemInfo(libraryItem, libraryItem, mediaSource);
  685. }
  686. else
  687. {
  688. info.Item = current;
  689. }
  690. }
  691. if (info.Item != null)
  692. {
  693. var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.InvariantCulture) : "unknown";
  694. _logger.Info("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
  695. session.Client,
  696. session.ApplicationVersion,
  697. info.Item.Name,
  698. msString);
  699. }
  700. RemoveNowPlayingItem(session);
  701. var users = GetUsers(session);
  702. var playedToCompletion = false;
  703. if (libraryItem != null)
  704. {
  705. foreach (var user in users)
  706. {
  707. playedToCompletion = await OnPlaybackStopped(user.Id, libraryItem, info.PositionTicks, info.Failed).ConfigureAwait(false);
  708. }
  709. }
  710. if (!string.IsNullOrWhiteSpace(info.LiveStreamId))
  711. {
  712. try
  713. {
  714. await _mediaSourceManager.CloseLiveStream(info.LiveStreamId).ConfigureAwait(false);
  715. }
  716. catch (Exception ex)
  717. {
  718. _logger.ErrorException("Error closing live stream", ex);
  719. }
  720. }
  721. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  722. {
  723. Item = libraryItem,
  724. Users = users,
  725. PlaybackPositionTicks = info.PositionTicks,
  726. PlayedToCompletion = playedToCompletion,
  727. MediaSourceId = info.MediaSourceId,
  728. MediaInfo = info.Item,
  729. DeviceName = session.DeviceName,
  730. ClientName = session.Client,
  731. DeviceId = session.DeviceId
  732. }, _logger);
  733. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  734. }
  735. private async Task<bool> OnPlaybackStopped(Guid userId, BaseItem item, long? positionTicks, bool playbackFailed)
  736. {
  737. bool playedToCompletion = false;
  738. if (!playbackFailed)
  739. {
  740. var data = _userDataManager.GetUserData(userId, item);
  741. if (positionTicks.HasValue)
  742. {
  743. playedToCompletion = _userDataManager.UpdatePlayState(item, data, positionTicks.Value);
  744. }
  745. else
  746. {
  747. // If the client isn't able to report this, then we'll just have to make an assumption
  748. data.PlayCount++;
  749. data.Played = item.SupportsPlayedStatus;
  750. data.PlaybackPositionTicks = 0;
  751. playedToCompletion = true;
  752. }
  753. await _userDataManager.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  754. }
  755. return playedToCompletion;
  756. }
  757. /// <summary>
  758. /// Gets the session.
  759. /// </summary>
  760. /// <param name="sessionId">The session identifier.</param>
  761. /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
  762. /// <returns>SessionInfo.</returns>
  763. /// <exception cref="ResourceNotFoundException"></exception>
  764. private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
  765. {
  766. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  767. if (session == null && throwOnMissing)
  768. {
  769. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  770. }
  771. return session;
  772. }
  773. private SessionInfo GetSessionToRemoteControl(string sessionId)
  774. {
  775. // Accept either device id or session id
  776. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  777. if (session == null)
  778. {
  779. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  780. }
  781. return session;
  782. }
  783. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  784. {
  785. var generalCommand = new GeneralCommand
  786. {
  787. Name = GeneralCommandType.DisplayMessage.ToString()
  788. };
  789. generalCommand.Arguments["Header"] = command.Header;
  790. generalCommand.Arguments["Text"] = command.Text;
  791. if (command.TimeoutMs.HasValue)
  792. {
  793. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  794. }
  795. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  796. }
  797. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  798. {
  799. var session = GetSessionToRemoteControl(sessionId);
  800. var controllingSession = GetSession(controllingSessionId);
  801. AssertCanControl(session, controllingSession);
  802. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  803. }
  804. public async Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  805. {
  806. var session = GetSessionToRemoteControl(sessionId);
  807. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  808. List<BaseItem> items;
  809. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  810. {
  811. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  812. .Where(i => i.LocationType != LocationType.Virtual)
  813. .ToList();
  814. command.PlayCommand = PlayCommand.PlayNow;
  815. }
  816. else
  817. {
  818. var list = new List<BaseItem>();
  819. foreach (var itemId in command.ItemIds)
  820. {
  821. var subItems = await TranslateItemForPlayback(itemId, user).ConfigureAwait(false);
  822. list.AddRange(subItems);
  823. }
  824. items = list
  825. .Where(i => i.LocationType != LocationType.Virtual)
  826. .ToList();
  827. }
  828. if (command.PlayCommand == PlayCommand.PlayShuffle)
  829. {
  830. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  831. command.PlayCommand = PlayCommand.PlayNow;
  832. }
  833. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  834. if (user != null)
  835. {
  836. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  837. {
  838. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  839. }
  840. }
  841. if (command.PlayCommand != PlayCommand.PlayNow)
  842. {
  843. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  844. {
  845. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id));
  846. }
  847. }
  848. else
  849. {
  850. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  851. {
  852. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id));
  853. }
  854. }
  855. if (user != null && command.ItemIds.Length == 1 && user.Configuration.EnableNextEpisodeAutoPlay)
  856. {
  857. var episode = _libraryManager.GetItemById(command.ItemIds[0]) as Episode;
  858. if (episode != null)
  859. {
  860. var series = episode.Series;
  861. if (series != null)
  862. {
  863. var episodes = series.GetEpisodes(user)
  864. .Where(i => !i.IsVirtualItem)
  865. .SkipWhile(i => i.Id != episode.Id)
  866. .ToList();
  867. if (episodes.Count > 0)
  868. {
  869. command.ItemIds = episodes.Select(i => i.Id.ToString("N")).ToArray();
  870. }
  871. }
  872. }
  873. }
  874. var controllingSession = GetSession(controllingSessionId);
  875. AssertCanControl(session, controllingSession);
  876. if (controllingSession.UserId.HasValue)
  877. {
  878. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  879. }
  880. await session.SessionController.SendPlayCommand(command, cancellationToken).ConfigureAwait(false);
  881. }
  882. private async Task<List<BaseItem>> TranslateItemForPlayback(string id, User user)
  883. {
  884. var item = _libraryManager.GetItemById(id);
  885. if (item == null)
  886. {
  887. _logger.Error("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
  888. return new List<BaseItem>();
  889. }
  890. var byName = item as IItemByName;
  891. if (byName != null)
  892. {
  893. var items = byName.GetTaggedItems(new InternalItemsQuery(user)
  894. {
  895. IsFolder = false,
  896. Recursive = true
  897. });
  898. return FilterToSingleMediaType(items)
  899. .OrderBy(i => i.SortName)
  900. .ToList();
  901. }
  902. if (item.IsFolder)
  903. {
  904. var folder = (Folder)item;
  905. var itemsResult = await folder.GetItems(new InternalItemsQuery(user)
  906. {
  907. Recursive = true,
  908. IsFolder = false
  909. }).ConfigureAwait(false);
  910. return FilterToSingleMediaType(itemsResult.Items)
  911. .OrderBy(i => i.SortName)
  912. .ToList();
  913. }
  914. return new List<BaseItem> { item };
  915. }
  916. private IEnumerable<BaseItem> FilterToSingleMediaType(IEnumerable<BaseItem> items)
  917. {
  918. return items
  919. .Where(i => !string.IsNullOrWhiteSpace(i.MediaType))
  920. .ToLookup(i => i.MediaType, StringComparer.OrdinalIgnoreCase)
  921. .OrderByDescending(i => i.Count())
  922. .FirstOrDefault();
  923. }
  924. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  925. {
  926. var item = _libraryManager.GetItemById(id);
  927. if (item == null)
  928. {
  929. _logger.Error("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id);
  930. return new List<BaseItem>();
  931. }
  932. return _musicManager.GetInstantMixFromItem(item, user);
  933. }
  934. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  935. {
  936. var generalCommand = new GeneralCommand
  937. {
  938. Name = GeneralCommandType.DisplayContent.ToString()
  939. };
  940. generalCommand.Arguments["ItemId"] = command.ItemId;
  941. generalCommand.Arguments["ItemName"] = command.ItemName;
  942. generalCommand.Arguments["ItemType"] = command.ItemType;
  943. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  944. }
  945. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  946. {
  947. var session = GetSessionToRemoteControl(sessionId);
  948. var controllingSession = GetSession(controllingSessionId);
  949. AssertCanControl(session, controllingSession);
  950. if (controllingSession.UserId.HasValue)
  951. {
  952. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  953. }
  954. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  955. }
  956. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  957. {
  958. if (session == null)
  959. {
  960. throw new ArgumentNullException("session");
  961. }
  962. if (controllingSession == null)
  963. {
  964. throw new ArgumentNullException("controllingSession");
  965. }
  966. }
  967. /// <summary>
  968. /// Sends the restart required message.
  969. /// </summary>
  970. /// <param name="cancellationToken">The cancellation token.</param>
  971. /// <returns>Task.</returns>
  972. public async Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  973. {
  974. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  975. var info = await _appHost.GetSystemInfo().ConfigureAwait(false);
  976. var tasks = sessions.Select(session => Task.Run(async () =>
  977. {
  978. try
  979. {
  980. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  981. }
  982. catch (Exception ex)
  983. {
  984. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  985. }
  986. }, cancellationToken));
  987. await Task.WhenAll(tasks).ConfigureAwait(false);
  988. }
  989. /// <summary>
  990. /// Sends the server shutdown notification.
  991. /// </summary>
  992. /// <param name="cancellationToken">The cancellation token.</param>
  993. /// <returns>Task.</returns>
  994. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  995. {
  996. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  997. var tasks = sessions.Select(session => Task.Run(async () =>
  998. {
  999. try
  1000. {
  1001. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  1002. }
  1003. catch (Exception ex)
  1004. {
  1005. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  1006. }
  1007. }, cancellationToken));
  1008. return Task.WhenAll(tasks);
  1009. }
  1010. /// <summary>
  1011. /// Sends the server restart notification.
  1012. /// </summary>
  1013. /// <param name="cancellationToken">The cancellation token.</param>
  1014. /// <returns>Task.</returns>
  1015. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  1016. {
  1017. _logger.Debug("Beginning SendServerRestartNotification");
  1018. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1019. var tasks = sessions.Select(session => Task.Run(async () =>
  1020. {
  1021. try
  1022. {
  1023. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  1024. }
  1025. catch (Exception ex)
  1026. {
  1027. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  1028. }
  1029. }, cancellationToken));
  1030. return Task.WhenAll(tasks);
  1031. }
  1032. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1033. {
  1034. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1035. var dto = GetSessionInfoDto(sessionInfo);
  1036. var tasks = sessions.Select(session => Task.Run(async () =>
  1037. {
  1038. try
  1039. {
  1040. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  1041. }
  1042. catch (Exception ex)
  1043. {
  1044. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  1045. }
  1046. }, cancellationToken));
  1047. return Task.WhenAll(tasks);
  1048. }
  1049. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1050. {
  1051. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1052. var dto = GetSessionInfoDto(sessionInfo);
  1053. var tasks = sessions.Select(session => Task.Run(async () =>
  1054. {
  1055. try
  1056. {
  1057. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  1058. }
  1059. catch (Exception ex)
  1060. {
  1061. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  1062. }
  1063. }, cancellationToken));
  1064. return Task.WhenAll(tasks);
  1065. }
  1066. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  1067. {
  1068. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  1069. var dto = GetSessionInfoDto(sessionInfo);
  1070. var tasks = sessions.Select(session => Task.Run(async () =>
  1071. {
  1072. try
  1073. {
  1074. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  1075. }
  1076. catch (Exception ex)
  1077. {
  1078. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  1079. }
  1080. }, cancellationToken));
  1081. return Task.WhenAll(tasks);
  1082. }
  1083. /// <summary>
  1084. /// Adds the additional user.
  1085. /// </summary>
  1086. /// <param name="sessionId">The session identifier.</param>
  1087. /// <param name="userId">The user identifier.</param>
  1088. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1089. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  1090. public void AddAdditionalUser(string sessionId, string userId)
  1091. {
  1092. var session = GetSession(sessionId);
  1093. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1094. {
  1095. throw new ArgumentException("The requested user is already the primary user of the session.");
  1096. }
  1097. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != new Guid(userId)))
  1098. {
  1099. var user = _userManager.GetUserById(userId);
  1100. session.AdditionalUsers.Add(new SessionUserInfo
  1101. {
  1102. UserId = userId,
  1103. UserName = user.Name
  1104. });
  1105. }
  1106. }
  1107. /// <summary>
  1108. /// Removes the additional user.
  1109. /// </summary>
  1110. /// <param name="sessionId">The session identifier.</param>
  1111. /// <param name="userId">The user identifier.</param>
  1112. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1113. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  1114. public void RemoveAdditionalUser(string sessionId, string userId)
  1115. {
  1116. var session = GetSession(sessionId);
  1117. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1118. {
  1119. throw new ArgumentException("The requested user is already the primary user of the session.");
  1120. }
  1121. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == new Guid(userId));
  1122. if (user != null)
  1123. {
  1124. session.AdditionalUsers.Remove(user);
  1125. }
  1126. }
  1127. /// <summary>
  1128. /// Authenticates the new session.
  1129. /// </summary>
  1130. /// <param name="request">The request.</param>
  1131. /// <returns>Task{SessionInfo}.</returns>
  1132. public Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  1133. {
  1134. return AuthenticateNewSessionInternal(request, true);
  1135. }
  1136. public Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request)
  1137. {
  1138. return AuthenticateNewSessionInternal(request, false);
  1139. }
  1140. private async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enforcePassword)
  1141. {
  1142. User user = null;
  1143. if (!string.IsNullOrWhiteSpace(request.UserId))
  1144. {
  1145. var idGuid = new Guid(request.UserId);
  1146. user = _userManager.Users
  1147. .FirstOrDefault(i => i.Id == idGuid);
  1148. }
  1149. if (user == null)
  1150. {
  1151. user = _userManager.Users
  1152. .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
  1153. }
  1154. if (user != null && !string.IsNullOrWhiteSpace(request.DeviceId))
  1155. {
  1156. if (!_deviceManager.CanAccessDevice(user.Id.ToString("N"), request.DeviceId))
  1157. {
  1158. throw new SecurityException("User is not allowed access from this device.");
  1159. }
  1160. }
  1161. if (enforcePassword)
  1162. {
  1163. var result = await _userManager.AuthenticateUser(request.Username, request.PasswordSha1, request.PasswordMd5, request.RemoteEndPoint).ConfigureAwait(false);
  1164. if (!result)
  1165. {
  1166. EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1167. throw new SecurityException("Invalid user or password entered.");
  1168. }
  1169. }
  1170. var token = await GetAuthorizationToken(user.Id.ToString("N"), request.DeviceId, request.App, request.AppVersion, request.DeviceName).ConfigureAwait(false);
  1171. EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1172. var session = await LogSessionActivity(request.App,
  1173. request.AppVersion,
  1174. request.DeviceId,
  1175. request.DeviceName,
  1176. request.RemoteEndPoint,
  1177. user)
  1178. .ConfigureAwait(false);
  1179. return new AuthenticationResult
  1180. {
  1181. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1182. SessionInfo = GetSessionInfoDto(session),
  1183. AccessToken = token,
  1184. ServerId = _appHost.SystemId
  1185. };
  1186. }
  1187. private async Task<string> GetAuthorizationToken(string userId, string deviceId, string app, string appVersion, string deviceName)
  1188. {
  1189. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1190. {
  1191. DeviceId = deviceId,
  1192. IsActive = true,
  1193. UserId = userId,
  1194. Limit = 1
  1195. });
  1196. if (existing.Items.Length > 0)
  1197. {
  1198. var token = existing.Items[0].AccessToken;
  1199. _logger.Info("Reissuing access token: " + token);
  1200. return token;
  1201. }
  1202. var newToken = new AuthenticationInfo
  1203. {
  1204. AppName = app,
  1205. AppVersion = appVersion,
  1206. DateCreated = DateTime.UtcNow,
  1207. DeviceId = deviceId,
  1208. DeviceName = deviceName,
  1209. UserId = userId,
  1210. IsActive = true,
  1211. AccessToken = Guid.NewGuid().ToString("N")
  1212. };
  1213. _logger.Info("Creating new access token for user {0}", userId);
  1214. await _authRepo.Create(newToken, CancellationToken.None).ConfigureAwait(false);
  1215. return newToken.AccessToken;
  1216. }
  1217. public async Task Logout(string accessToken)
  1218. {
  1219. if (string.IsNullOrWhiteSpace(accessToken))
  1220. {
  1221. throw new ArgumentNullException("accessToken");
  1222. }
  1223. _logger.Info("Logging out access token {0}", accessToken);
  1224. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1225. {
  1226. Limit = 1,
  1227. AccessToken = accessToken
  1228. }).Items.FirstOrDefault();
  1229. if (existing != null)
  1230. {
  1231. existing.IsActive = false;
  1232. await _authRepo.Update(existing, CancellationToken.None).ConfigureAwait(false);
  1233. var sessions = Sessions
  1234. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1235. .ToList();
  1236. foreach (var session in sessions)
  1237. {
  1238. try
  1239. {
  1240. ReportSessionEnded(session.Id);
  1241. }
  1242. catch (Exception ex)
  1243. {
  1244. _logger.ErrorException("Error reporting session ended", ex);
  1245. }
  1246. }
  1247. }
  1248. }
  1249. public async Task RevokeUserTokens(string userId, string currentAccessToken)
  1250. {
  1251. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1252. {
  1253. IsActive = true,
  1254. UserId = userId
  1255. });
  1256. foreach (var info in existing.Items)
  1257. {
  1258. if (!string.Equals(currentAccessToken, info.AccessToken, StringComparison.OrdinalIgnoreCase))
  1259. {
  1260. await Logout(info.AccessToken).ConfigureAwait(false);
  1261. }
  1262. }
  1263. }
  1264. public Task RevokeToken(string token)
  1265. {
  1266. return Logout(token);
  1267. }
  1268. /// <summary>
  1269. /// Reports the capabilities.
  1270. /// </summary>
  1271. /// <param name="sessionId">The session identifier.</param>
  1272. /// <param name="capabilities">The capabilities.</param>
  1273. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1274. {
  1275. var session = GetSession(sessionId);
  1276. ReportCapabilities(session, capabilities, true);
  1277. }
  1278. private async void ReportCapabilities(SessionInfo session,
  1279. ClientCapabilities capabilities,
  1280. bool saveCapabilities)
  1281. {
  1282. session.Capabilities = capabilities;
  1283. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1284. {
  1285. var controller = session.SessionController as HttpSessionController;
  1286. if (controller == null)
  1287. {
  1288. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1289. }
  1290. }
  1291. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1292. {
  1293. SessionInfo = session
  1294. }, _logger);
  1295. if (saveCapabilities)
  1296. {
  1297. try
  1298. {
  1299. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1300. }
  1301. catch (Exception ex)
  1302. {
  1303. _logger.ErrorException("Error saving device capabilities", ex);
  1304. }
  1305. }
  1306. }
  1307. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1308. {
  1309. return _deviceManager.GetCapabilities(deviceId);
  1310. }
  1311. private Task SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1312. {
  1313. return _deviceManager.SaveCapabilities(deviceId, capabilities);
  1314. }
  1315. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1316. {
  1317. var dto = new SessionInfoDto
  1318. {
  1319. Client = session.Client,
  1320. DeviceId = session.DeviceId,
  1321. DeviceName = session.DeviceName,
  1322. Id = session.Id,
  1323. LastActivityDate = session.LastActivityDate,
  1324. NowViewingItem = session.NowViewingItem,
  1325. ApplicationVersion = session.ApplicationVersion,
  1326. QueueableMediaTypes = session.QueueableMediaTypes,
  1327. PlayableMediaTypes = session.PlayableMediaTypes,
  1328. AdditionalUsers = session.AdditionalUsers,
  1329. SupportedCommands = session.SupportedCommands,
  1330. UserName = session.UserName,
  1331. NowPlayingItem = session.NowPlayingItem,
  1332. SupportsRemoteControl = session.SupportsMediaControl,
  1333. PlayState = session.PlayState,
  1334. AppIconUrl = session.AppIconUrl,
  1335. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1336. };
  1337. if (session.UserId.HasValue)
  1338. {
  1339. dto.UserId = session.UserId.Value.ToString("N");
  1340. var user = _userManager.GetUserById(session.UserId.Value);
  1341. if (user != null)
  1342. {
  1343. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1344. }
  1345. }
  1346. return dto;
  1347. }
  1348. /// <summary>
  1349. /// Converts a BaseItem to a BaseItemInfo
  1350. /// </summary>
  1351. /// <param name="item">The item.</param>
  1352. /// <param name="chapterOwner">The chapter owner.</param>
  1353. /// <param name="mediaSource">The media source.</param>
  1354. /// <returns>BaseItemInfo.</returns>
  1355. /// <exception cref="System.ArgumentNullException">item</exception>
  1356. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, MediaSourceInfo mediaSource)
  1357. {
  1358. if (item == null)
  1359. {
  1360. throw new ArgumentNullException("item");
  1361. }
  1362. var info = new BaseItemInfo
  1363. {
  1364. Id = GetDtoId(item),
  1365. Name = item.Name,
  1366. MediaType = item.MediaType,
  1367. Type = item.GetClientTypeName(),
  1368. RunTimeTicks = item.RunTimeTicks,
  1369. IndexNumber = item.IndexNumber,
  1370. ParentIndexNumber = item.ParentIndexNumber,
  1371. PremiereDate = item.PremiereDate,
  1372. ProductionYear = item.ProductionYear,
  1373. IsThemeMedia = item.IsThemeMedia
  1374. };
  1375. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1376. if (info.PrimaryImageTag != null)
  1377. {
  1378. info.PrimaryImageItemId = GetDtoId(item);
  1379. }
  1380. var episode = item as Episode;
  1381. if (episode != null)
  1382. {
  1383. info.IndexNumberEnd = episode.IndexNumberEnd;
  1384. }
  1385. var hasSeries = item as IHasSeries;
  1386. if (hasSeries != null)
  1387. {
  1388. info.SeriesName = hasSeries.SeriesName;
  1389. }
  1390. var recording = item as ILiveTvRecording;
  1391. if (recording != null)
  1392. {
  1393. if (recording.IsSeries)
  1394. {
  1395. info.Name = recording.EpisodeTitle;
  1396. info.SeriesName = recording.Name;
  1397. if (string.IsNullOrWhiteSpace(info.Name))
  1398. {
  1399. info.Name = recording.Name;
  1400. }
  1401. }
  1402. }
  1403. var audio = item as Audio;
  1404. if (audio != null)
  1405. {
  1406. info.Album = audio.Album;
  1407. info.Artists = audio.Artists;
  1408. if (info.PrimaryImageTag == null)
  1409. {
  1410. var album = audio.AlbumEntity;
  1411. if (album != null && album.HasImage(ImageType.Primary))
  1412. {
  1413. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1414. if (info.PrimaryImageTag != null)
  1415. {
  1416. info.PrimaryImageItemId = GetDtoId(album);
  1417. }
  1418. }
  1419. }
  1420. }
  1421. var musicVideo = item as MusicVideo;
  1422. if (musicVideo != null)
  1423. {
  1424. info.Album = musicVideo.Album;
  1425. info.Artists = musicVideo.Artists.ToList();
  1426. }
  1427. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1428. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1429. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1430. if (thumbItem == null)
  1431. {
  1432. if (episode != null)
  1433. {
  1434. var series = episode.Series;
  1435. if (series != null && series.HasImage(ImageType.Thumb))
  1436. {
  1437. thumbItem = series;
  1438. }
  1439. }
  1440. }
  1441. if (backropItem == null)
  1442. {
  1443. if (episode != null)
  1444. {
  1445. var series = episode.Series;
  1446. if (series != null && series.HasImage(ImageType.Backdrop))
  1447. {
  1448. backropItem = series;
  1449. }
  1450. }
  1451. }
  1452. if (backropItem == null)
  1453. {
  1454. backropItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1455. }
  1456. if (thumbItem == null)
  1457. {
  1458. thumbItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1459. }
  1460. if (logoItem == null)
  1461. {
  1462. logoItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1463. }
  1464. if (thumbItem != null)
  1465. {
  1466. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1467. info.ThumbItemId = GetDtoId(thumbItem);
  1468. }
  1469. if (backropItem != null)
  1470. {
  1471. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1472. info.BackdropItemId = GetDtoId(backropItem);
  1473. }
  1474. if (logoItem != null)
  1475. {
  1476. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1477. info.LogoItemId = GetDtoId(logoItem);
  1478. }
  1479. if (chapterOwner != null)
  1480. {
  1481. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1482. info.Chapters = _dtoService.GetChapterInfoDtos(chapterOwner).ToList();
  1483. }
  1484. if (mediaSource != null)
  1485. {
  1486. info.MediaStreams = mediaSource.MediaStreams;
  1487. }
  1488. return info;
  1489. }
  1490. private string GetImageCacheTag(BaseItem item, ImageType type)
  1491. {
  1492. try
  1493. {
  1494. return _imageProcessor.GetImageCacheTag(item, type);
  1495. }
  1496. catch (Exception ex)
  1497. {
  1498. _logger.ErrorException("Error getting {0} image info", ex, type);
  1499. return null;
  1500. }
  1501. }
  1502. private string GetDtoId(BaseItem item)
  1503. {
  1504. return _dtoService.GetDtoId(item);
  1505. }
  1506. public void ReportNowViewingItem(string sessionId, string itemId)
  1507. {
  1508. if (string.IsNullOrWhiteSpace(itemId))
  1509. {
  1510. throw new ArgumentNullException("itemId");
  1511. }
  1512. //var item = _libraryManager.GetItemById(new Guid(itemId));
  1513. //var info = GetItemInfo(item, null, null);
  1514. //ReportNowViewingItem(sessionId, info);
  1515. }
  1516. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1517. {
  1518. //var session = GetSession(sessionId);
  1519. //session.NowViewingItem = item;
  1520. }
  1521. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1522. {
  1523. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1524. if (session != null)
  1525. {
  1526. session.TranscodingInfo = info;
  1527. }
  1528. }
  1529. public void ClearTranscodingInfo(string deviceId)
  1530. {
  1531. ReportTranscodingInfo(deviceId, null);
  1532. }
  1533. public SessionInfo GetSession(string deviceId, string client, string version)
  1534. {
  1535. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1536. string.Equals(i.Client, client));
  1537. }
  1538. public Task<SessionInfo> GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1539. {
  1540. if (info == null)
  1541. {
  1542. throw new ArgumentNullException("info");
  1543. }
  1544. var user = string.IsNullOrWhiteSpace(info.UserId)
  1545. ? null
  1546. : _userManager.GetUserById(info.UserId);
  1547. appVersion = string.IsNullOrWhiteSpace(appVersion)
  1548. ? info.AppVersion
  1549. : appVersion;
  1550. var deviceName = info.DeviceName;
  1551. var appName = info.AppName;
  1552. if (!string.IsNullOrWhiteSpace(deviceId))
  1553. {
  1554. // Replace the info from the token with more recent info
  1555. var device = _deviceManager.GetDevice(deviceId);
  1556. if (device != null)
  1557. {
  1558. deviceName = device.Name;
  1559. appName = device.AppName;
  1560. if (!string.IsNullOrWhiteSpace(device.AppVersion))
  1561. {
  1562. appVersion = device.AppVersion;
  1563. }
  1564. }
  1565. }
  1566. else
  1567. {
  1568. deviceId = info.DeviceId;
  1569. }
  1570. // Prevent argument exception
  1571. if (string.IsNullOrWhiteSpace(appVersion))
  1572. {
  1573. appVersion = "1";
  1574. }
  1575. return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1576. }
  1577. public Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1578. {
  1579. var result = _authRepo.Get(new AuthenticationInfoQuery
  1580. {
  1581. AccessToken = token
  1582. });
  1583. var info = result.Items.FirstOrDefault();
  1584. if (info == null)
  1585. {
  1586. return Task.FromResult<SessionInfo>(null);
  1587. }
  1588. return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
  1589. }
  1590. public Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken)
  1591. {
  1592. var adminUserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id.ToString("N")).ToList();
  1593. return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken);
  1594. }
  1595. public Task SendMessageToUserSessions<T>(List<string> userIds, string name, T data,
  1596. CancellationToken cancellationToken)
  1597. {
  1598. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && userIds.Any(i.ContainsUser)).ToList();
  1599. var tasks = sessions.Select(session => Task.Run(async () =>
  1600. {
  1601. try
  1602. {
  1603. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1604. }
  1605. catch (Exception ex)
  1606. {
  1607. _logger.ErrorException("Error sending message", ex);
  1608. }
  1609. }, cancellationToken));
  1610. return Task.WhenAll(tasks);
  1611. }
  1612. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data,
  1613. CancellationToken cancellationToken)
  1614. {
  1615. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
  1616. var tasks = sessions.Select(session => Task.Run(async () =>
  1617. {
  1618. try
  1619. {
  1620. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1621. }
  1622. catch (Exception ex)
  1623. {
  1624. _logger.ErrorException("Error sending message", ex);
  1625. }
  1626. }, cancellationToken));
  1627. return Task.WhenAll(tasks);
  1628. }
  1629. }
  1630. }