SessionManager.cs 68 KB

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