SessionManager.cs 60 KB

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