SessionManager.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Configuration;
  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.Entities;
  17. using MediaBrowser.Model.Events;
  18. using MediaBrowser.Model.Library;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.Serialization;
  21. using MediaBrowser.Model.Session;
  22. using MediaBrowser.Model.Users;
  23. using MediaBrowser.Server.Implementations.Security;
  24. using System;
  25. using System.Collections.Concurrent;
  26. using System.Collections.Generic;
  27. using System.Globalization;
  28. using System.IO;
  29. using System.Linq;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32. namespace MediaBrowser.Server.Implementations.Session
  33. {
  34. /// <summary>
  35. /// Class SessionManager
  36. /// </summary>
  37. public class SessionManager : ISessionManager
  38. {
  39. /// <summary>
  40. /// The _user data repository
  41. /// </summary>
  42. private readonly IUserDataManager _userDataRepository;
  43. /// <summary>
  44. /// The _user repository
  45. /// </summary>
  46. private readonly IUserRepository _userRepository;
  47. /// <summary>
  48. /// The _logger
  49. /// </summary>
  50. private readonly ILogger _logger;
  51. private readonly ILibraryManager _libraryManager;
  52. private readonly IUserManager _userManager;
  53. private readonly IMusicManager _musicManager;
  54. private readonly IDtoService _dtoService;
  55. private readonly IImageProcessor _imageProcessor;
  56. private readonly IItemRepository _itemRepo;
  57. private readonly IHttpClient _httpClient;
  58. private readonly IJsonSerializer _jsonSerializer;
  59. private readonly IServerApplicationHost _appHost;
  60. private readonly IAuthenticationRepository _authRepo;
  61. /// <summary>
  62. /// Gets or sets the configuration manager.
  63. /// </summary>
  64. /// <value>The configuration manager.</value>
  65. private readonly IServerConfigurationManager _configurationManager;
  66. /// <summary>
  67. /// The _active connections
  68. /// </summary>
  69. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  70. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  71. public event EventHandler<GenericEventArgs<AuthenticationRequest>> AuthenticationFailed;
  72. public event EventHandler<GenericEventArgs<AuthenticationRequest>> AuthenticationSucceeded;
  73. /// <summary>
  74. /// Occurs when [playback start].
  75. /// </summary>
  76. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  77. /// <summary>
  78. /// Occurs when [playback progress].
  79. /// </summary>
  80. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  81. /// <summary>
  82. /// Occurs when [playback stopped].
  83. /// </summary>
  84. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  85. public event EventHandler<SessionEventArgs> SessionStarted;
  86. public event EventHandler<SessionEventArgs> CapabilitiesChanged;
  87. public event EventHandler<SessionEventArgs> SessionEnded;
  88. public event EventHandler<SessionEventArgs> SessionActivity;
  89. private IEnumerable<ISessionControllerFactory> _sessionFactories = new List<ISessionControllerFactory>();
  90. private readonly SemaphoreSlim _sessionLock = new SemaphoreSlim(1, 1);
  91. /// <summary>
  92. /// Initializes a new instance of the <see cref="SessionManager" /> class.
  93. /// </summary>
  94. /// <param name="userDataRepository">The user data repository.</param>
  95. /// <param name="configurationManager">The configuration manager.</param>
  96. /// <param name="logger">The logger.</param>
  97. /// <param name="userRepository">The user repository.</param>
  98. /// <param name="libraryManager">The library manager.</param>
  99. public SessionManager(IUserDataManager userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository, ILibraryManager libraryManager, IUserManager userManager, IMusicManager musicManager, IDtoService dtoService, IImageProcessor imageProcessor, IItemRepository itemRepo, IJsonSerializer jsonSerializer, IServerApplicationHost appHost, IHttpClient httpClient, IAuthenticationRepository authRepo)
  100. {
  101. _userDataRepository = userDataRepository;
  102. _configurationManager = configurationManager;
  103. _logger = logger;
  104. _userRepository = userRepository;
  105. _libraryManager = libraryManager;
  106. _userManager = userManager;
  107. _musicManager = musicManager;
  108. _dtoService = dtoService;
  109. _imageProcessor = imageProcessor;
  110. _itemRepo = itemRepo;
  111. _jsonSerializer = jsonSerializer;
  112. _appHost = appHost;
  113. _httpClient = httpClient;
  114. _authRepo = authRepo;
  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. ReportCapabilities(info, capabilities, false);
  144. }
  145. }
  146. }
  147. private async void OnSessionEnded(SessionInfo info)
  148. {
  149. try
  150. {
  151. await SendSessionEndedNotification(info, CancellationToken.None).ConfigureAwait(false);
  152. }
  153. catch (Exception ex)
  154. {
  155. _logger.ErrorException("Error in SendSessionEndedNotification", ex);
  156. }
  157. EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
  158. {
  159. SessionInfo = info
  160. }, _logger);
  161. var disposable = info.SessionController as IDisposable;
  162. if (disposable != null)
  163. {
  164. _logger.Debug("Disposing session controller {0}", disposable.GetType().Name);
  165. try
  166. {
  167. disposable.Dispose();
  168. }
  169. catch (Exception ex)
  170. {
  171. _logger.ErrorException("Error disposing session controller", ex);
  172. }
  173. }
  174. }
  175. /// <summary>
  176. /// Logs the user activity.
  177. /// </summary>
  178. /// <param name="clientType">Type of the client.</param>
  179. /// <param name="appVersion">The app version.</param>
  180. /// <param name="deviceId">The device id.</param>
  181. /// <param name="deviceName">Name of the device.</param>
  182. /// <param name="remoteEndPoint">The remote end point.</param>
  183. /// <param name="user">The user.</param>
  184. /// <returns>Task.</returns>
  185. /// <exception cref="System.ArgumentNullException">user</exception>
  186. /// <exception cref="System.UnauthorizedAccessException"></exception>
  187. public async Task<SessionInfo> LogSessionActivity(string clientType,
  188. string appVersion,
  189. string deviceId,
  190. string deviceName,
  191. string remoteEndPoint,
  192. User user)
  193. {
  194. if (string.IsNullOrEmpty(clientType))
  195. {
  196. throw new ArgumentNullException("clientType");
  197. }
  198. if (string.IsNullOrEmpty(appVersion))
  199. {
  200. throw new ArgumentNullException("appVersion");
  201. }
  202. if (string.IsNullOrEmpty(deviceId))
  203. {
  204. throw new ArgumentNullException("deviceId");
  205. }
  206. if (string.IsNullOrEmpty(deviceName))
  207. {
  208. throw new ArgumentNullException("deviceName");
  209. }
  210. if (user != null && user.Configuration.IsDisabled)
  211. {
  212. throw new AuthenticationException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  213. }
  214. var activityDate = DateTime.UtcNow;
  215. var userId = user == null ? (Guid?)null : user.Id;
  216. var username = user == null ? null : user.Name;
  217. var session = await GetSessionInfo(clientType, appVersion, deviceId, deviceName, remoteEndPoint, userId, username).ConfigureAwait(false);
  218. session.LastActivityDate = activityDate;
  219. if (user == null)
  220. {
  221. return session;
  222. }
  223. var lastActivityDate = user.LastActivityDate;
  224. user.LastActivityDate = activityDate;
  225. // Don't log in the db anymore frequently than 10 seconds
  226. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  227. {
  228. return session;
  229. }
  230. // Save this directly. No need to fire off all the events for this.
  231. await _userRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  232. EventHelper.FireEventIfNotNull(SessionActivity, this, new SessionEventArgs
  233. {
  234. SessionInfo = session
  235. }, _logger);
  236. return session;
  237. }
  238. public async void ReportSessionEnded(string sessionId)
  239. {
  240. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  241. try
  242. {
  243. var session = GetSession(sessionId, false);
  244. if (session != null)
  245. {
  246. var key = GetSessionKey(session.Client, session.ApplicationVersion, session.DeviceId);
  247. SessionInfo removed;
  248. if (_activeConnections.TryRemove(key, out removed))
  249. {
  250. OnSessionEnded(removed);
  251. }
  252. }
  253. }
  254. finally
  255. {
  256. _sessionLock.Release();
  257. }
  258. }
  259. /// <summary>
  260. /// Updates the now playing item id.
  261. /// </summary>
  262. /// <param name="session">The session.</param>
  263. /// <param name="info">The information.</param>
  264. /// <param name="libraryItem">The library item.</param>
  265. private void UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem)
  266. {
  267. var runtimeTicks = libraryItem == null ? null : libraryItem.RunTimeTicks;
  268. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  269. {
  270. info.MediaSourceId = info.ItemId;
  271. }
  272. if (!string.Equals(info.ItemId, info.MediaSourceId) &&
  273. !string.IsNullOrWhiteSpace(info.MediaSourceId))
  274. {
  275. runtimeTicks = _libraryManager.GetItemById(new Guid(info.MediaSourceId)).RunTimeTicks;
  276. }
  277. if (!string.IsNullOrWhiteSpace(info.ItemId) && libraryItem != null)
  278. {
  279. var current = session.NowPlayingItem;
  280. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  281. {
  282. info.Item = GetItemInfo(libraryItem, libraryItem, info.MediaSourceId);
  283. }
  284. else
  285. {
  286. info.Item = current;
  287. }
  288. info.Item.RunTimeTicks = runtimeTicks;
  289. }
  290. session.NowPlayingItem = info.Item;
  291. session.LastActivityDate = DateTime.UtcNow;
  292. session.PlayState.IsPaused = info.IsPaused;
  293. session.PlayState.PositionTicks = info.PositionTicks;
  294. session.PlayState.MediaSourceId = info.MediaSourceId;
  295. session.PlayState.CanSeek = info.CanSeek;
  296. session.PlayState.IsMuted = info.IsMuted;
  297. session.PlayState.VolumeLevel = info.VolumeLevel;
  298. session.PlayState.AudioStreamIndex = info.AudioStreamIndex;
  299. session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex;
  300. session.PlayState.PlayMethod = info.PlayMethod;
  301. }
  302. /// <summary>
  303. /// Removes the now playing item id.
  304. /// </summary>
  305. /// <param name="session">The session.</param>
  306. /// <exception cref="System.ArgumentNullException">item</exception>
  307. private void RemoveNowPlayingItem(SessionInfo session)
  308. {
  309. session.NowPlayingItem = null;
  310. session.PlayState = new PlayerStateInfo();
  311. if (!string.IsNullOrEmpty(session.DeviceId))
  312. {
  313. ClearTranscodingInfo(session.DeviceId);
  314. }
  315. }
  316. private string GetSessionKey(string clientType, string appVersion, string deviceId)
  317. {
  318. return clientType + deviceId;
  319. }
  320. /// <summary>
  321. /// Gets the connection.
  322. /// </summary>
  323. /// <param name="clientType">Type of the client.</param>
  324. /// <param name="appVersion">The app version.</param>
  325. /// <param name="deviceId">The device id.</param>
  326. /// <param name="deviceName">Name of the device.</param>
  327. /// <param name="remoteEndPoint">The remote end point.</param>
  328. /// <param name="userId">The user identifier.</param>
  329. /// <param name="username">The username.</param>
  330. /// <returns>SessionInfo.</returns>
  331. private async Task<SessionInfo> GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username)
  332. {
  333. var key = GetSessionKey(clientType, appVersion, deviceId);
  334. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  335. try
  336. {
  337. var connection = _activeConnections.GetOrAdd(key, keyName =>
  338. {
  339. var sessionInfo = new SessionInfo
  340. {
  341. Client = clientType,
  342. DeviceId = deviceId,
  343. ApplicationVersion = appVersion,
  344. Id = Guid.NewGuid().ToString("N")
  345. };
  346. sessionInfo.DeviceName = deviceName;
  347. sessionInfo.UserId = userId;
  348. sessionInfo.UserName = username;
  349. sessionInfo.RemoteEndPoint = remoteEndPoint;
  350. OnSessionStarted(sessionInfo);
  351. return sessionInfo;
  352. });
  353. connection.DeviceName = deviceName;
  354. connection.UserId = userId;
  355. connection.UserName = username;
  356. connection.RemoteEndPoint = remoteEndPoint;
  357. if (!userId.HasValue)
  358. {
  359. connection.AdditionalUsers.Clear();
  360. }
  361. if (connection.SessionController == null)
  362. {
  363. connection.SessionController = _sessionFactories
  364. .Select(i => i.GetSessionController(connection))
  365. .FirstOrDefault(i => i != null);
  366. }
  367. return connection;
  368. }
  369. finally
  370. {
  371. _sessionLock.Release();
  372. }
  373. }
  374. private List<User> GetUsers(SessionInfo session)
  375. {
  376. var users = new List<User>();
  377. if (session.UserId.HasValue)
  378. {
  379. var user = _userManager.GetUserById(session.UserId.Value);
  380. if (user == null)
  381. {
  382. throw new InvalidOperationException("User not found");
  383. }
  384. users.Add(user);
  385. var additionalUsers = session.AdditionalUsers
  386. .Select(i => _userManager.GetUserById(i.UserId))
  387. .Where(i => i != null);
  388. users.AddRange(additionalUsers);
  389. }
  390. return users;
  391. }
  392. /// <summary>
  393. /// Used to report that playback has started for an item
  394. /// </summary>
  395. /// <param name="info">The info.</param>
  396. /// <returns>Task.</returns>
  397. /// <exception cref="System.ArgumentNullException">info</exception>
  398. public async Task OnPlaybackStart(PlaybackStartInfo info)
  399. {
  400. if (info == null)
  401. {
  402. throw new ArgumentNullException("info");
  403. }
  404. var session = GetSession(info.SessionId);
  405. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  406. ? null
  407. : _libraryManager.GetItemById(new Guid(info.ItemId));
  408. UpdateNowPlayingItem(session, info, libraryItem);
  409. if (!string.IsNullOrEmpty(session.DeviceId) && info.PlayMethod != PlayMethod.Transcode)
  410. {
  411. ClearTranscodingInfo(session.DeviceId);
  412. }
  413. session.QueueableMediaTypes = info.QueueableMediaTypes;
  414. var users = GetUsers(session);
  415. if (libraryItem != null)
  416. {
  417. var key = libraryItem.GetUserDataKey();
  418. foreach (var user in users)
  419. {
  420. await OnPlaybackStart(user.Id, key, libraryItem).ConfigureAwait(false);
  421. }
  422. }
  423. // Nothing to save here
  424. // Fire events to inform plugins
  425. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  426. {
  427. Item = libraryItem,
  428. Users = users,
  429. MediaSourceId = info.MediaSourceId,
  430. MediaInfo = info.Item,
  431. DeviceName = session.DeviceName,
  432. ClientName = session.Client,
  433. DeviceId = session.DeviceId
  434. }, _logger);
  435. await SendPlaybackStartNotification(session, CancellationToken.None).ConfigureAwait(false);
  436. }
  437. /// <summary>
  438. /// Called when [playback start].
  439. /// </summary>
  440. /// <param name="userId">The user identifier.</param>
  441. /// <param name="userDataKey">The user data key.</param>
  442. /// <param name="item">The item.</param>
  443. /// <returns>Task.</returns>
  444. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  445. {
  446. var data = _userDataRepository.GetUserData(userId, userDataKey);
  447. data.PlayCount++;
  448. data.LastPlayedDate = DateTime.UtcNow;
  449. if (!(item is Video))
  450. {
  451. data.Played = true;
  452. }
  453. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  454. }
  455. /// <summary>
  456. /// Used to report playback progress for an item
  457. /// </summary>
  458. /// <param name="info">The info.</param>
  459. /// <returns>Task.</returns>
  460. /// <exception cref="System.ArgumentNullException"></exception>
  461. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  462. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  463. {
  464. if (info == null)
  465. {
  466. throw new ArgumentNullException("info");
  467. }
  468. var session = GetSession(info.SessionId);
  469. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  470. ? null
  471. : _libraryManager.GetItemById(new Guid(info.ItemId));
  472. UpdateNowPlayingItem(session, info, libraryItem);
  473. var users = GetUsers(session);
  474. if (libraryItem != null)
  475. {
  476. var key = libraryItem.GetUserDataKey();
  477. foreach (var user in users)
  478. {
  479. await OnPlaybackProgress(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  480. }
  481. }
  482. EventHelper.FireEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  483. {
  484. Item = libraryItem,
  485. Users = users,
  486. PlaybackPositionTicks = session.PlayState.PositionTicks,
  487. MediaSourceId = session.PlayState.MediaSourceId,
  488. MediaInfo = info.Item,
  489. DeviceName = session.DeviceName,
  490. ClientName = session.Client,
  491. DeviceId = session.DeviceId
  492. }, _logger);
  493. }
  494. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  495. {
  496. var data = _userDataRepository.GetUserData(userId, userDataKey);
  497. if (positionTicks.HasValue)
  498. {
  499. UpdatePlayState(item, data, positionTicks.Value);
  500. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  501. }
  502. }
  503. /// <summary>
  504. /// Used to report that playback has ended for an item
  505. /// </summary>
  506. /// <param name="info">The info.</param>
  507. /// <returns>Task.</returns>
  508. /// <exception cref="System.ArgumentNullException">info</exception>
  509. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  510. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  511. {
  512. if (info == null)
  513. {
  514. throw new ArgumentNullException("info");
  515. }
  516. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  517. {
  518. throw new ArgumentOutOfRangeException("positionTicks");
  519. }
  520. var session = GetSession(info.SessionId);
  521. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  522. ? null
  523. : _libraryManager.GetItemById(new Guid(info.ItemId));
  524. // Normalize
  525. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  526. {
  527. info.MediaSourceId = info.ItemId;
  528. }
  529. if (!string.IsNullOrWhiteSpace(info.ItemId) && libraryItem != null)
  530. {
  531. var current = session.NowPlayingItem;
  532. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  533. {
  534. info.Item = GetItemInfo(libraryItem, libraryItem, info.MediaSourceId);
  535. }
  536. else
  537. {
  538. info.Item = current;
  539. }
  540. }
  541. RemoveNowPlayingItem(session);
  542. var users = GetUsers(session);
  543. var playedToCompletion = false;
  544. if (libraryItem != null)
  545. {
  546. var key = libraryItem.GetUserDataKey();
  547. foreach (var user in users)
  548. {
  549. playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  550. }
  551. }
  552. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  553. {
  554. Item = libraryItem,
  555. Users = users,
  556. PlaybackPositionTicks = info.PositionTicks,
  557. PlayedToCompletion = playedToCompletion,
  558. MediaSourceId = info.MediaSourceId,
  559. MediaInfo = info.Item,
  560. DeviceName = session.DeviceName,
  561. ClientName = session.Client,
  562. DeviceId = session.DeviceId
  563. }, _logger);
  564. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  565. }
  566. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  567. {
  568. var data = _userDataRepository.GetUserData(userId, userDataKey);
  569. bool playedToCompletion;
  570. if (positionTicks.HasValue)
  571. {
  572. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  573. }
  574. else
  575. {
  576. // If the client isn't able to report this, then we'll just have to make an assumption
  577. data.PlayCount++;
  578. data.Played = true;
  579. data.PlaybackPositionTicks = 0;
  580. playedToCompletion = true;
  581. }
  582. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  583. return playedToCompletion;
  584. }
  585. /// <summary>
  586. /// Updates playstate position for an item but does not save
  587. /// </summary>
  588. /// <param name="item">The item</param>
  589. /// <param name="data">User data for the item</param>
  590. /// <param name="positionTicks">The current playback position</param>
  591. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  592. {
  593. var playedToCompletion = false;
  594. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  595. // If a position has been reported, and if we know the duration
  596. if (positionTicks > 0 && hasRuntime)
  597. {
  598. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  599. // Don't track in very beginning
  600. if (pctIn < _configurationManager.Configuration.MinResumePct)
  601. {
  602. positionTicks = 0;
  603. }
  604. // If we're at the end, assume completed
  605. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  606. {
  607. positionTicks = 0;
  608. data.Played = playedToCompletion = true;
  609. }
  610. else
  611. {
  612. // Enforce MinResumeDuration
  613. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  614. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  615. {
  616. positionTicks = 0;
  617. data.Played = playedToCompletion = true;
  618. }
  619. }
  620. }
  621. else if (!hasRuntime)
  622. {
  623. // If we don't know the runtime we'll just have to assume it was fully played
  624. data.Played = playedToCompletion = true;
  625. positionTicks = 0;
  626. }
  627. if (item is Audio)
  628. {
  629. positionTicks = 0;
  630. }
  631. data.PlaybackPositionTicks = positionTicks;
  632. return playedToCompletion;
  633. }
  634. /// <summary>
  635. /// Gets the session.
  636. /// </summary>
  637. /// <param name="sessionId">The session identifier.</param>
  638. /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
  639. /// <returns>SessionInfo.</returns>
  640. /// <exception cref="ResourceNotFoundException"></exception>
  641. private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
  642. {
  643. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  644. if (session == null && throwOnMissing)
  645. {
  646. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  647. }
  648. return session;
  649. }
  650. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  651. {
  652. var generalCommand = new GeneralCommand
  653. {
  654. Name = GeneralCommandType.DisplayMessage.ToString()
  655. };
  656. generalCommand.Arguments["Header"] = command.Header;
  657. generalCommand.Arguments["Text"] = command.Text;
  658. if (command.TimeoutMs.HasValue)
  659. {
  660. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  661. }
  662. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  663. }
  664. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  665. {
  666. var session = GetSession(sessionId);
  667. var controllingSession = GetSession(controllingSessionId);
  668. AssertCanControl(session, controllingSession);
  669. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  670. }
  671. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  672. {
  673. var session = GetSession(sessionId);
  674. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  675. List<BaseItem> items;
  676. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  677. {
  678. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  679. .Where(i => i.LocationType != LocationType.Virtual)
  680. .ToList();
  681. command.PlayCommand = PlayCommand.PlayNow;
  682. }
  683. else
  684. {
  685. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  686. .Where(i => i.LocationType != LocationType.Virtual)
  687. .ToList();
  688. }
  689. if (command.PlayCommand == PlayCommand.PlayShuffle)
  690. {
  691. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  692. command.PlayCommand = PlayCommand.PlayNow;
  693. }
  694. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  695. if (user != null)
  696. {
  697. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  698. {
  699. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  700. }
  701. }
  702. if (command.PlayCommand != PlayCommand.PlayNow)
  703. {
  704. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  705. {
  706. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  707. }
  708. }
  709. else
  710. {
  711. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  712. {
  713. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  714. }
  715. }
  716. var controllingSession = GetSession(controllingSessionId);
  717. AssertCanControl(session, controllingSession);
  718. if (controllingSession.UserId.HasValue)
  719. {
  720. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  721. }
  722. return session.SessionController.SendPlayCommand(command, cancellationToken);
  723. }
  724. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  725. {
  726. var item = _libraryManager.GetItemById(new Guid(id));
  727. if (item.IsFolder)
  728. {
  729. var folder = (Folder)item;
  730. var items = user == null ? folder.RecursiveChildren :
  731. folder.GetRecursiveChildren(user);
  732. items = items.Where(i => !i.IsFolder);
  733. items = items.OrderBy(i => i.SortName);
  734. return items;
  735. }
  736. return new[] { item };
  737. }
  738. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  739. {
  740. var item = _libraryManager.GetItemById(new Guid(id));
  741. var audio = item as Audio;
  742. if (audio != null)
  743. {
  744. return _musicManager.GetInstantMixFromSong(audio, user);
  745. }
  746. var artist = item as MusicArtist;
  747. if (artist != null)
  748. {
  749. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  750. }
  751. var album = item as MusicAlbum;
  752. if (album != null)
  753. {
  754. return _musicManager.GetInstantMixFromAlbum(album, user);
  755. }
  756. var genre = item as MusicGenre;
  757. if (genre != null)
  758. {
  759. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  760. }
  761. return new BaseItem[] { };
  762. }
  763. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  764. {
  765. var generalCommand = new GeneralCommand
  766. {
  767. Name = GeneralCommandType.DisplayContent.ToString()
  768. };
  769. generalCommand.Arguments["ItemId"] = command.ItemId;
  770. generalCommand.Arguments["ItemName"] = command.ItemName;
  771. generalCommand.Arguments["ItemType"] = command.ItemType;
  772. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  773. }
  774. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  775. {
  776. var session = GetSession(sessionId);
  777. var controllingSession = GetSession(controllingSessionId);
  778. AssertCanControl(session, controllingSession);
  779. if (controllingSession.UserId.HasValue)
  780. {
  781. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  782. }
  783. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  784. }
  785. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  786. {
  787. if (session == null)
  788. {
  789. throw new ArgumentNullException("session");
  790. }
  791. if (controllingSession == null)
  792. {
  793. throw new ArgumentNullException("controllingSession");
  794. }
  795. }
  796. /// <summary>
  797. /// Sends the restart required message.
  798. /// </summary>
  799. /// <param name="cancellationToken">The cancellation token.</param>
  800. /// <returns>Task.</returns>
  801. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  802. {
  803. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  804. var info = _appHost.GetSystemInfo();
  805. var tasks = sessions.Select(session => Task.Run(async () =>
  806. {
  807. try
  808. {
  809. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  810. }
  811. catch (Exception ex)
  812. {
  813. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  814. }
  815. }, cancellationToken));
  816. return Task.WhenAll(tasks);
  817. }
  818. /// <summary>
  819. /// Sends the server shutdown notification.
  820. /// </summary>
  821. /// <param name="cancellationToken">The cancellation token.</param>
  822. /// <returns>Task.</returns>
  823. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  824. {
  825. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  826. var tasks = sessions.Select(session => Task.Run(async () =>
  827. {
  828. try
  829. {
  830. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  831. }
  832. catch (Exception ex)
  833. {
  834. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  835. }
  836. }, cancellationToken));
  837. return Task.WhenAll(tasks);
  838. }
  839. /// <summary>
  840. /// Sends the server restart notification.
  841. /// </summary>
  842. /// <param name="cancellationToken">The cancellation token.</param>
  843. /// <returns>Task.</returns>
  844. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  845. {
  846. _logger.Debug("Beginning SendServerRestartNotification");
  847. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  848. var tasks = sessions.Select(session => Task.Run(async () =>
  849. {
  850. try
  851. {
  852. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  853. }
  854. catch (Exception ex)
  855. {
  856. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  857. }
  858. }, cancellationToken));
  859. return Task.WhenAll(tasks);
  860. }
  861. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  862. {
  863. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  864. var dto = GetSessionInfoDto(sessionInfo);
  865. var tasks = sessions.Select(session => Task.Run(async () =>
  866. {
  867. try
  868. {
  869. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  870. }
  871. catch (Exception ex)
  872. {
  873. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  874. }
  875. }, cancellationToken));
  876. return Task.WhenAll(tasks);
  877. }
  878. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  879. {
  880. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  881. var dto = GetSessionInfoDto(sessionInfo);
  882. var tasks = sessions.Select(session => Task.Run(async () =>
  883. {
  884. try
  885. {
  886. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  887. }
  888. catch (Exception ex)
  889. {
  890. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  891. }
  892. }, cancellationToken));
  893. return Task.WhenAll(tasks);
  894. }
  895. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  896. {
  897. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  898. var dto = GetSessionInfoDto(sessionInfo);
  899. var tasks = sessions.Select(session => Task.Run(async () =>
  900. {
  901. try
  902. {
  903. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  904. }
  905. catch (Exception ex)
  906. {
  907. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  908. }
  909. }, cancellationToken));
  910. return Task.WhenAll(tasks);
  911. }
  912. /// <summary>
  913. /// Adds the additional user.
  914. /// </summary>
  915. /// <param name="sessionId">The session identifier.</param>
  916. /// <param name="userId">The user identifier.</param>
  917. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  918. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  919. public void AddAdditionalUser(string sessionId, Guid userId)
  920. {
  921. var session = GetSession(sessionId);
  922. if (session.UserId.HasValue && session.UserId.Value == userId)
  923. {
  924. throw new ArgumentException("The requested user is already the primary user of the session.");
  925. }
  926. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  927. {
  928. var user = _userManager.GetUserById(userId);
  929. session.AdditionalUsers.Add(new SessionUserInfo
  930. {
  931. UserId = userId.ToString("N"),
  932. UserName = user.Name
  933. });
  934. }
  935. }
  936. /// <summary>
  937. /// Removes the additional user.
  938. /// </summary>
  939. /// <param name="sessionId">The session identifier.</param>
  940. /// <param name="userId">The user identifier.</param>
  941. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  942. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  943. public void RemoveAdditionalUser(string sessionId, Guid userId)
  944. {
  945. var session = GetSession(sessionId);
  946. if (session.UserId.HasValue && session.UserId.Value == userId)
  947. {
  948. throw new ArgumentException("The requested user is already the primary user of the session.");
  949. }
  950. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  951. if (user != null)
  952. {
  953. session.AdditionalUsers.Remove(user);
  954. }
  955. }
  956. public void ValidateSecurityToken(string token)
  957. {
  958. if (string.IsNullOrWhiteSpace(token))
  959. {
  960. throw new AuthenticationException();
  961. }
  962. var result = _authRepo.Get(new AuthenticationInfoQuery
  963. {
  964. AccessToken = token
  965. });
  966. var info = result.Items.FirstOrDefault();
  967. if (info == null)
  968. {
  969. throw new AuthenticationException();
  970. }
  971. if (!info.IsActive)
  972. {
  973. throw new AuthenticationException("Access token has expired.");
  974. }
  975. if (!string.IsNullOrWhiteSpace(info.UserId))
  976. {
  977. var user = _userManager.GetUserById(info.UserId);
  978. if (user == null || user.Configuration.IsDisabled)
  979. {
  980. throw new AuthenticationException("User account has been disabled.");
  981. }
  982. }
  983. }
  984. /// <summary>
  985. /// Authenticates the new session.
  986. /// </summary>
  987. /// <param name="request">The request.</param>
  988. /// <param name="isLocal">if set to <c>true</c> [is local].</param>
  989. /// <returns>Task{SessionInfo}.</returns>
  990. /// <exception cref="AuthenticationException">Invalid user or password entered.</exception>
  991. /// <exception cref="System.UnauthorizedAccessException">Invalid user or password entered.</exception>
  992. /// <exception cref="UnauthorizedAccessException">Invalid user or password entered.</exception>
  993. public async Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request,
  994. bool isLocal)
  995. {
  996. var result = (isLocal && string.Equals(request.App, "Dashboard", StringComparison.OrdinalIgnoreCase)) ||
  997. await _userManager.AuthenticateUser(request.Username, request.Password, request.RemoteEndPoint).ConfigureAwait(false);
  998. if (!result)
  999. {
  1000. EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1001. throw new AuthenticationException("Invalid user or password entered.");
  1002. }
  1003. var user = _userManager.Users
  1004. .First(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
  1005. var token = await GetAuthorizationToken(user.Id.ToString("N"), request.DeviceId, request.App, request.DeviceName).ConfigureAwait(false);
  1006. EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1007. var session = await LogSessionActivity(request.App,
  1008. request.AppVersion,
  1009. request.DeviceId,
  1010. request.DeviceName,
  1011. request.RemoteEndPoint,
  1012. user)
  1013. .ConfigureAwait(false);
  1014. return new AuthenticationResult
  1015. {
  1016. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1017. SessionInfo = GetSessionInfoDto(session),
  1018. AccessToken = token,
  1019. ServerId = _appHost.SystemId
  1020. };
  1021. }
  1022. private async Task<string> GetAuthorizationToken(string userId, string deviceId, string app, string deviceName)
  1023. {
  1024. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1025. {
  1026. DeviceId = deviceId,
  1027. IsActive = true,
  1028. UserId = userId,
  1029. Limit = 1
  1030. });
  1031. if (existing.Items.Length > 0)
  1032. {
  1033. _logger.Debug("Reissuing access token");
  1034. return existing.Items[0].AccessToken;
  1035. }
  1036. var newToken = new AuthenticationInfo
  1037. {
  1038. AppName = app,
  1039. DateCreated = DateTime.UtcNow,
  1040. DeviceId = deviceId,
  1041. DeviceName = deviceName,
  1042. UserId = userId,
  1043. IsActive = true,
  1044. AccessToken = Guid.NewGuid().ToString("N")
  1045. };
  1046. _logger.Debug("Creating new access token for user {0}", userId);
  1047. await _authRepo.Create(newToken, CancellationToken.None).ConfigureAwait(false);
  1048. return newToken.AccessToken;
  1049. }
  1050. public async Task Logout(string accessToken)
  1051. {
  1052. if (string.IsNullOrWhiteSpace(accessToken))
  1053. {
  1054. throw new ArgumentNullException("accessToken");
  1055. }
  1056. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1057. {
  1058. Limit = 1,
  1059. AccessToken = accessToken
  1060. }).Items.FirstOrDefault();
  1061. if (existing != null)
  1062. {
  1063. existing.IsActive = false;
  1064. await _authRepo.Update(existing, CancellationToken.None).ConfigureAwait(false);
  1065. var sessions = Sessions
  1066. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1067. .ToList();
  1068. foreach (var session in sessions)
  1069. {
  1070. try
  1071. {
  1072. ReportSessionEnded(session.Id);
  1073. }
  1074. catch (Exception ex)
  1075. {
  1076. _logger.ErrorException("Error reporting session ended", ex);
  1077. }
  1078. }
  1079. }
  1080. }
  1081. public async Task RevokeUserTokens(string userId)
  1082. {
  1083. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1084. {
  1085. IsActive = true,
  1086. UserId = userId
  1087. });
  1088. foreach (var info in existing.Items)
  1089. {
  1090. await Logout(info.AccessToken).ConfigureAwait(false);
  1091. }
  1092. }
  1093. public Task RevokeToken(string token)
  1094. {
  1095. return Logout(token);
  1096. }
  1097. /// <summary>
  1098. /// Reports the capabilities.
  1099. /// </summary>
  1100. /// <param name="sessionId">The session identifier.</param>
  1101. /// <param name="capabilities">The capabilities.</param>
  1102. public void ReportCapabilities(string sessionId, SessionCapabilities capabilities)
  1103. {
  1104. var session = GetSession(sessionId);
  1105. ReportCapabilities(session, capabilities, true);
  1106. }
  1107. private async void ReportCapabilities(SessionInfo session,
  1108. SessionCapabilities capabilities,
  1109. bool saveCapabilities)
  1110. {
  1111. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  1112. session.SupportedCommands = capabilities.SupportedCommands;
  1113. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1114. {
  1115. var controller = session.SessionController as HttpSessionController;
  1116. if (controller == null)
  1117. {
  1118. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1119. }
  1120. }
  1121. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1122. {
  1123. SessionInfo = session
  1124. }, _logger);
  1125. if (saveCapabilities)
  1126. {
  1127. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1128. }
  1129. }
  1130. private string GetCapabilitiesFilePath(string deviceId)
  1131. {
  1132. var filename = deviceId.GetMD5().ToString("N") + ".json";
  1133. return Path.Combine(_configurationManager.ApplicationPaths.CachePath, "devices", filename);
  1134. }
  1135. private SessionCapabilities GetSavedCapabilities(string deviceId)
  1136. {
  1137. var path = GetCapabilitiesFilePath(deviceId);
  1138. try
  1139. {
  1140. return _jsonSerializer.DeserializeFromFile<SessionCapabilities>(path);
  1141. }
  1142. catch (DirectoryNotFoundException)
  1143. {
  1144. return null;
  1145. }
  1146. catch (FileNotFoundException)
  1147. {
  1148. return null;
  1149. }
  1150. catch (Exception ex)
  1151. {
  1152. _logger.ErrorException("Error getting saved capabilities", ex);
  1153. return null;
  1154. }
  1155. }
  1156. private readonly SemaphoreSlim _capabilitiesLock = new SemaphoreSlim(1, 1);
  1157. private async Task SaveCapabilities(string deviceId, SessionCapabilities capabilities)
  1158. {
  1159. var path = GetCapabilitiesFilePath(deviceId);
  1160. Directory.CreateDirectory(Path.GetDirectoryName(path));
  1161. await _capabilitiesLock.WaitAsync().ConfigureAwait(false);
  1162. try
  1163. {
  1164. _jsonSerializer.SerializeToFile(capabilities, path);
  1165. }
  1166. catch (Exception ex)
  1167. {
  1168. _logger.ErrorException("Error saving to {0}", ex, path);
  1169. }
  1170. finally
  1171. {
  1172. _capabilitiesLock.Release();
  1173. }
  1174. }
  1175. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1176. {
  1177. var dto = new SessionInfoDto
  1178. {
  1179. Client = session.Client,
  1180. DeviceId = session.DeviceId,
  1181. DeviceName = session.DeviceName,
  1182. Id = session.Id,
  1183. LastActivityDate = session.LastActivityDate,
  1184. NowViewingItem = session.NowViewingItem,
  1185. ApplicationVersion = session.ApplicationVersion,
  1186. QueueableMediaTypes = session.QueueableMediaTypes,
  1187. PlayableMediaTypes = session.PlayableMediaTypes,
  1188. AdditionalUsers = session.AdditionalUsers,
  1189. SupportedCommands = session.SupportedCommands,
  1190. UserName = session.UserName,
  1191. NowPlayingItem = session.NowPlayingItem,
  1192. SupportsRemoteControl = session.SupportsMediaControl,
  1193. PlayState = session.PlayState,
  1194. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1195. };
  1196. if (session.UserId.HasValue)
  1197. {
  1198. dto.UserId = session.UserId.Value.ToString("N");
  1199. var user = _userManager.GetUserById(session.UserId.Value);
  1200. if (user != null)
  1201. {
  1202. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1203. }
  1204. }
  1205. return dto;
  1206. }
  1207. /// <summary>
  1208. /// Converts a BaseItem to a BaseItemInfo
  1209. /// </summary>
  1210. /// <param name="item">The item.</param>
  1211. /// <param name="chapterOwner">The chapter owner.</param>
  1212. /// <param name="mediaSourceId">The media source identifier.</param>
  1213. /// <returns>BaseItemInfo.</returns>
  1214. /// <exception cref="System.ArgumentNullException">item</exception>
  1215. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, string mediaSourceId)
  1216. {
  1217. if (item == null)
  1218. {
  1219. throw new ArgumentNullException("item");
  1220. }
  1221. var info = new BaseItemInfo
  1222. {
  1223. Id = GetDtoId(item),
  1224. Name = item.Name,
  1225. MediaType = item.MediaType,
  1226. Type = item.GetClientTypeName(),
  1227. RunTimeTicks = item.RunTimeTicks,
  1228. IndexNumber = item.IndexNumber,
  1229. ParentIndexNumber = item.ParentIndexNumber,
  1230. PremiereDate = item.PremiereDate,
  1231. ProductionYear = item.ProductionYear
  1232. };
  1233. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1234. if (info.PrimaryImageTag != null)
  1235. {
  1236. info.PrimaryImageItemId = GetDtoId(item);
  1237. }
  1238. var episode = item as Episode;
  1239. if (episode != null)
  1240. {
  1241. info.IndexNumberEnd = episode.IndexNumberEnd;
  1242. }
  1243. var hasSeries = item as IHasSeries;
  1244. if (hasSeries != null)
  1245. {
  1246. info.SeriesName = hasSeries.SeriesName;
  1247. }
  1248. var recording = item as ILiveTvRecording;
  1249. if (recording != null && recording.RecordingInfo != null)
  1250. {
  1251. if (recording.RecordingInfo.IsSeries)
  1252. {
  1253. info.Name = recording.RecordingInfo.EpisodeTitle;
  1254. info.SeriesName = recording.RecordingInfo.Name;
  1255. if (string.IsNullOrWhiteSpace(info.Name))
  1256. {
  1257. info.Name = recording.RecordingInfo.Name;
  1258. }
  1259. }
  1260. }
  1261. var audio = item as Audio;
  1262. if (audio != null)
  1263. {
  1264. info.Album = audio.Album;
  1265. info.Artists = audio.Artists;
  1266. if (info.PrimaryImageTag == null)
  1267. {
  1268. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1269. if (album != null && album.HasImage(ImageType.Primary))
  1270. {
  1271. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1272. if (info.PrimaryImageTag != null)
  1273. {
  1274. info.PrimaryImageItemId = GetDtoId(album);
  1275. }
  1276. }
  1277. }
  1278. }
  1279. var musicVideo = item as MusicVideo;
  1280. if (musicVideo != null)
  1281. {
  1282. info.Album = musicVideo.Album;
  1283. if (!string.IsNullOrWhiteSpace(musicVideo.Artist))
  1284. {
  1285. info.Artists.Add(musicVideo.Artist);
  1286. }
  1287. }
  1288. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1289. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1290. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1291. if (thumbItem == null)
  1292. {
  1293. if (episode != null)
  1294. {
  1295. var series = episode.Series;
  1296. if (series != null && series.HasImage(ImageType.Thumb))
  1297. {
  1298. thumbItem = series;
  1299. }
  1300. }
  1301. }
  1302. if (backropItem == null)
  1303. {
  1304. if (episode != null)
  1305. {
  1306. var series = episode.Series;
  1307. if (series != null && series.HasImage(ImageType.Backdrop))
  1308. {
  1309. backropItem = series;
  1310. }
  1311. }
  1312. }
  1313. if (backropItem == null)
  1314. {
  1315. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1316. }
  1317. if (thumbItem == null)
  1318. {
  1319. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1320. }
  1321. if (logoItem == null)
  1322. {
  1323. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1324. }
  1325. if (thumbItem != null)
  1326. {
  1327. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1328. info.ThumbItemId = GetDtoId(thumbItem);
  1329. }
  1330. if (backropItem != null)
  1331. {
  1332. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1333. info.BackdropItemId = GetDtoId(backropItem);
  1334. }
  1335. if (logoItem != null)
  1336. {
  1337. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1338. info.LogoItemId = GetDtoId(logoItem);
  1339. }
  1340. if (chapterOwner != null)
  1341. {
  1342. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1343. info.Chapters = _itemRepo.GetChapters(chapterOwner.Id).Select(i => _dtoService.GetChapterInfoDto(i, chapterOwner)).ToList();
  1344. }
  1345. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  1346. {
  1347. info.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  1348. {
  1349. ItemId = new Guid(mediaSourceId)
  1350. }).ToList();
  1351. }
  1352. return info;
  1353. }
  1354. private string GetImageCacheTag(BaseItem item, ImageType type)
  1355. {
  1356. try
  1357. {
  1358. return _imageProcessor.GetImageCacheTag(item, type);
  1359. }
  1360. catch (Exception ex)
  1361. {
  1362. _logger.ErrorException("Error getting {0} image info", ex, type);
  1363. return null;
  1364. }
  1365. }
  1366. private string GetDtoId(BaseItem item)
  1367. {
  1368. return _dtoService.GetDtoId(item);
  1369. }
  1370. public void ReportNowViewingItem(string sessionId, string itemId)
  1371. {
  1372. var item = _libraryManager.GetItemById(new Guid(itemId));
  1373. var info = GetItemInfo(item, null, null);
  1374. ReportNowViewingItem(sessionId, info);
  1375. }
  1376. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1377. {
  1378. var session = GetSession(sessionId);
  1379. session.NowViewingItem = item;
  1380. }
  1381. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1382. {
  1383. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1384. if (session != null)
  1385. {
  1386. session.TranscodingInfo = info;
  1387. }
  1388. }
  1389. public void ClearTranscodingInfo(string deviceId)
  1390. {
  1391. ReportTranscodingInfo(deviceId, null);
  1392. }
  1393. public SessionInfo GetSession(string deviceId, string client, string version)
  1394. {
  1395. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1396. string.Equals(i.Client, client));
  1397. }
  1398. }
  1399. }