SessionManager.cs 68 KB

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