SessionManager.cs 59 KB

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