SessionManager.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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.ToString()));
  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.ToString()));
  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. if (item.IsFolder)
  742. {
  743. var folder = (Folder)item;
  744. var items = user == null ?
  745. folder.GetRecursiveChildren(i => !i.IsFolder) :
  746. folder.GetRecursiveChildren(user, i => !i.IsFolder);
  747. items = items.OrderBy(i => i.SortName);
  748. return items;
  749. }
  750. return new[] { item };
  751. }
  752. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  753. {
  754. var item = _libraryManager.GetItemById(new Guid(id));
  755. var audio = item as Audio;
  756. if (audio != null)
  757. {
  758. return _musicManager.GetInstantMixFromSong(audio, user);
  759. }
  760. var artist = item as MusicArtist;
  761. if (artist != null)
  762. {
  763. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  764. }
  765. var album = item as MusicAlbum;
  766. if (album != null)
  767. {
  768. return _musicManager.GetInstantMixFromAlbum(album, user);
  769. }
  770. var genre = item as MusicGenre;
  771. if (genre != null)
  772. {
  773. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  774. }
  775. return new BaseItem[] { };
  776. }
  777. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  778. {
  779. var generalCommand = new GeneralCommand
  780. {
  781. Name = GeneralCommandType.DisplayContent.ToString()
  782. };
  783. generalCommand.Arguments["ItemId"] = command.ItemId;
  784. generalCommand.Arguments["ItemName"] = command.ItemName;
  785. generalCommand.Arguments["ItemType"] = command.ItemType;
  786. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  787. }
  788. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  789. {
  790. var session = GetSession(sessionId);
  791. var controllingSession = GetSession(controllingSessionId);
  792. AssertCanControl(session, controllingSession);
  793. if (controllingSession.UserId.HasValue)
  794. {
  795. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  796. }
  797. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  798. }
  799. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  800. {
  801. if (session == null)
  802. {
  803. throw new ArgumentNullException("session");
  804. }
  805. if (controllingSession == null)
  806. {
  807. throw new ArgumentNullException("controllingSession");
  808. }
  809. }
  810. /// <summary>
  811. /// Sends the restart required message.
  812. /// </summary>
  813. /// <param name="cancellationToken">The cancellation token.</param>
  814. /// <returns>Task.</returns>
  815. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  816. {
  817. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  818. var info = _appHost.GetSystemInfo();
  819. var tasks = sessions.Select(session => Task.Run(async () =>
  820. {
  821. try
  822. {
  823. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  824. }
  825. catch (Exception ex)
  826. {
  827. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  828. }
  829. }, cancellationToken));
  830. return Task.WhenAll(tasks);
  831. }
  832. /// <summary>
  833. /// Sends the server shutdown notification.
  834. /// </summary>
  835. /// <param name="cancellationToken">The cancellation token.</param>
  836. /// <returns>Task.</returns>
  837. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  838. {
  839. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  840. var tasks = sessions.Select(session => Task.Run(async () =>
  841. {
  842. try
  843. {
  844. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  845. }
  846. catch (Exception ex)
  847. {
  848. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  849. }
  850. }, cancellationToken));
  851. return Task.WhenAll(tasks);
  852. }
  853. /// <summary>
  854. /// Sends the server restart notification.
  855. /// </summary>
  856. /// <param name="cancellationToken">The cancellation token.</param>
  857. /// <returns>Task.</returns>
  858. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  859. {
  860. _logger.Debug("Beginning SendServerRestartNotification");
  861. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  862. var tasks = sessions.Select(session => Task.Run(async () =>
  863. {
  864. try
  865. {
  866. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  867. }
  868. catch (Exception ex)
  869. {
  870. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  871. }
  872. }, cancellationToken));
  873. return Task.WhenAll(tasks);
  874. }
  875. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  876. {
  877. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  878. var dto = GetSessionInfoDto(sessionInfo);
  879. var tasks = sessions.Select(session => Task.Run(async () =>
  880. {
  881. try
  882. {
  883. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  884. }
  885. catch (Exception ex)
  886. {
  887. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  888. }
  889. }, cancellationToken));
  890. return Task.WhenAll(tasks);
  891. }
  892. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  893. {
  894. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  895. var dto = GetSessionInfoDto(sessionInfo);
  896. var tasks = sessions.Select(session => Task.Run(async () =>
  897. {
  898. try
  899. {
  900. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  901. }
  902. catch (Exception ex)
  903. {
  904. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  905. }
  906. }, cancellationToken));
  907. return Task.WhenAll(tasks);
  908. }
  909. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  910. {
  911. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  912. var dto = GetSessionInfoDto(sessionInfo);
  913. var tasks = sessions.Select(session => Task.Run(async () =>
  914. {
  915. try
  916. {
  917. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  918. }
  919. catch (Exception ex)
  920. {
  921. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  922. }
  923. }, cancellationToken));
  924. return Task.WhenAll(tasks);
  925. }
  926. /// <summary>
  927. /// Adds the additional user.
  928. /// </summary>
  929. /// <param name="sessionId">The session identifier.</param>
  930. /// <param name="userId">The user identifier.</param>
  931. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  932. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  933. public void AddAdditionalUser(string sessionId, Guid userId)
  934. {
  935. var session = GetSession(sessionId);
  936. if (session.UserId.HasValue && session.UserId.Value == userId)
  937. {
  938. throw new ArgumentException("The requested user is already the primary user of the session.");
  939. }
  940. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  941. {
  942. var user = _userManager.GetUserById(userId);
  943. session.AdditionalUsers.Add(new SessionUserInfo
  944. {
  945. UserId = userId.ToString("N"),
  946. UserName = user.Name
  947. });
  948. }
  949. }
  950. /// <summary>
  951. /// Removes the additional user.
  952. /// </summary>
  953. /// <param name="sessionId">The session identifier.</param>
  954. /// <param name="userId">The user identifier.</param>
  955. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  956. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  957. public void RemoveAdditionalUser(string sessionId, Guid userId)
  958. {
  959. var session = GetSession(sessionId);
  960. if (session.UserId.HasValue && session.UserId.Value == userId)
  961. {
  962. throw new ArgumentException("The requested user is already the primary user of the session.");
  963. }
  964. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  965. if (user != null)
  966. {
  967. session.AdditionalUsers.Remove(user);
  968. }
  969. }
  970. /// <summary>
  971. /// Authenticates the new session.
  972. /// </summary>
  973. /// <param name="request">The request.</param>
  974. /// <returns>Task{SessionInfo}.</returns>
  975. public async Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  976. {
  977. var user = _userManager.Users
  978. .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
  979. if (user != null && !string.IsNullOrWhiteSpace(request.DeviceId))
  980. {
  981. if (!_deviceManager.CanAccessDevice(user.Id.ToString("N"), request.DeviceId))
  982. {
  983. throw new UnauthorizedAccessException("User is not allowed access from this device.");
  984. }
  985. }
  986. var result = await _userManager.AuthenticateUser(request.Username, request.PasswordSha1, request.PasswordMd5, request.RemoteEndPoint).ConfigureAwait(false);
  987. if (!result)
  988. {
  989. EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  990. throw new UnauthorizedAccessException("Invalid user or password entered.");
  991. }
  992. var token = await GetAuthorizationToken(user.Id.ToString("N"), request.DeviceId, request.App, request.DeviceName).ConfigureAwait(false);
  993. EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  994. var session = await LogSessionActivity(request.App,
  995. request.AppVersion,
  996. request.DeviceId,
  997. request.DeviceName,
  998. request.RemoteEndPoint,
  999. user)
  1000. .ConfigureAwait(false);
  1001. return new AuthenticationResult
  1002. {
  1003. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1004. SessionInfo = GetSessionInfoDto(session),
  1005. AccessToken = token,
  1006. ServerId = _appHost.SystemId
  1007. };
  1008. }
  1009. private async Task<string> GetAuthorizationToken(string userId, string deviceId, string app, string deviceName)
  1010. {
  1011. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1012. {
  1013. DeviceId = deviceId,
  1014. IsActive = true,
  1015. UserId = userId,
  1016. Limit = 1
  1017. });
  1018. if (existing.Items.Length > 0)
  1019. {
  1020. _logger.Debug("Reissuing access token");
  1021. return existing.Items[0].AccessToken;
  1022. }
  1023. var newToken = new AuthenticationInfo
  1024. {
  1025. AppName = app,
  1026. DateCreated = DateTime.UtcNow,
  1027. DeviceId = deviceId,
  1028. DeviceName = deviceName,
  1029. UserId = userId,
  1030. IsActive = true,
  1031. AccessToken = Guid.NewGuid().ToString("N")
  1032. };
  1033. _logger.Debug("Creating new access token for user {0}", userId);
  1034. await _authRepo.Create(newToken, CancellationToken.None).ConfigureAwait(false);
  1035. return newToken.AccessToken;
  1036. }
  1037. public async Task Logout(string accessToken)
  1038. {
  1039. if (string.IsNullOrWhiteSpace(accessToken))
  1040. {
  1041. throw new ArgumentNullException("accessToken");
  1042. }
  1043. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1044. {
  1045. Limit = 1,
  1046. AccessToken = accessToken
  1047. }).Items.FirstOrDefault();
  1048. if (existing != null)
  1049. {
  1050. existing.IsActive = false;
  1051. await _authRepo.Update(existing, CancellationToken.None).ConfigureAwait(false);
  1052. var sessions = Sessions
  1053. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1054. .ToList();
  1055. foreach (var session in sessions)
  1056. {
  1057. try
  1058. {
  1059. ReportSessionEnded(session.Id);
  1060. }
  1061. catch (Exception ex)
  1062. {
  1063. _logger.ErrorException("Error reporting session ended", ex);
  1064. }
  1065. }
  1066. }
  1067. }
  1068. public async Task RevokeUserTokens(string userId)
  1069. {
  1070. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1071. {
  1072. IsActive = true,
  1073. UserId = userId
  1074. });
  1075. foreach (var info in existing.Items)
  1076. {
  1077. await Logout(info.AccessToken).ConfigureAwait(false);
  1078. }
  1079. }
  1080. public Task RevokeToken(string token)
  1081. {
  1082. return Logout(token);
  1083. }
  1084. /// <summary>
  1085. /// Reports the capabilities.
  1086. /// </summary>
  1087. /// <param name="sessionId">The session identifier.</param>
  1088. /// <param name="capabilities">The capabilities.</param>
  1089. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1090. {
  1091. var session = GetSession(sessionId);
  1092. ReportCapabilities(session, capabilities, true);
  1093. }
  1094. private async void ReportCapabilities(SessionInfo session,
  1095. ClientCapabilities capabilities,
  1096. bool saveCapabilities)
  1097. {
  1098. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  1099. session.SupportedCommands = capabilities.SupportedCommands;
  1100. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1101. {
  1102. var controller = session.SessionController as HttpSessionController;
  1103. if (controller == null)
  1104. {
  1105. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1106. }
  1107. }
  1108. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1109. {
  1110. SessionInfo = session
  1111. }, _logger);
  1112. if (saveCapabilities)
  1113. {
  1114. try
  1115. {
  1116. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1117. }
  1118. catch (Exception ex)
  1119. {
  1120. _logger.ErrorException("Error saving device capabilities", ex);
  1121. }
  1122. }
  1123. }
  1124. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1125. {
  1126. return _deviceManager.GetCapabilities(deviceId);
  1127. }
  1128. private Task SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1129. {
  1130. return _deviceManager.SaveCapabilities(deviceId, capabilities);
  1131. }
  1132. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1133. {
  1134. var dto = new SessionInfoDto
  1135. {
  1136. Client = session.Client,
  1137. DeviceId = session.DeviceId,
  1138. DeviceName = session.DeviceName,
  1139. Id = session.Id,
  1140. LastActivityDate = session.LastActivityDate,
  1141. NowViewingItem = session.NowViewingItem,
  1142. ApplicationVersion = session.ApplicationVersion,
  1143. QueueableMediaTypes = session.QueueableMediaTypes,
  1144. PlayableMediaTypes = session.PlayableMediaTypes,
  1145. AdditionalUsers = session.AdditionalUsers,
  1146. SupportedCommands = session.SupportedCommands,
  1147. UserName = session.UserName,
  1148. NowPlayingItem = session.NowPlayingItem,
  1149. SupportsRemoteControl = session.SupportsMediaControl,
  1150. PlayState = session.PlayState,
  1151. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1152. };
  1153. if (session.UserId.HasValue)
  1154. {
  1155. dto.UserId = session.UserId.Value.ToString("N");
  1156. var user = _userManager.GetUserById(session.UserId.Value);
  1157. if (user != null)
  1158. {
  1159. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1160. }
  1161. }
  1162. return dto;
  1163. }
  1164. /// <summary>
  1165. /// Converts a BaseItem to a BaseItemInfo
  1166. /// </summary>
  1167. /// <param name="item">The item.</param>
  1168. /// <param name="chapterOwner">The chapter owner.</param>
  1169. /// <param name="mediaSourceId">The media source identifier.</param>
  1170. /// <returns>BaseItemInfo.</returns>
  1171. /// <exception cref="System.ArgumentNullException">item</exception>
  1172. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, string mediaSourceId)
  1173. {
  1174. if (item == null)
  1175. {
  1176. throw new ArgumentNullException("item");
  1177. }
  1178. var info = new BaseItemInfo
  1179. {
  1180. Id = GetDtoId(item),
  1181. Name = item.Name,
  1182. MediaType = item.MediaType,
  1183. Type = item.GetClientTypeName(),
  1184. RunTimeTicks = item.RunTimeTicks,
  1185. IndexNumber = item.IndexNumber,
  1186. ParentIndexNumber = item.ParentIndexNumber,
  1187. PremiereDate = item.PremiereDate,
  1188. ProductionYear = item.ProductionYear
  1189. };
  1190. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1191. if (info.PrimaryImageTag != null)
  1192. {
  1193. info.PrimaryImageItemId = GetDtoId(item);
  1194. }
  1195. var episode = item as Episode;
  1196. if (episode != null)
  1197. {
  1198. info.IndexNumberEnd = episode.IndexNumberEnd;
  1199. }
  1200. var hasSeries = item as IHasSeries;
  1201. if (hasSeries != null)
  1202. {
  1203. info.SeriesName = hasSeries.SeriesName;
  1204. }
  1205. var recording = item as ILiveTvRecording;
  1206. if (recording != null && recording.RecordingInfo != null)
  1207. {
  1208. if (recording.RecordingInfo.IsSeries)
  1209. {
  1210. info.Name = recording.RecordingInfo.EpisodeTitle;
  1211. info.SeriesName = recording.RecordingInfo.Name;
  1212. if (string.IsNullOrWhiteSpace(info.Name))
  1213. {
  1214. info.Name = recording.RecordingInfo.Name;
  1215. }
  1216. }
  1217. }
  1218. var audio = item as Audio;
  1219. if (audio != null)
  1220. {
  1221. info.Album = audio.Album;
  1222. info.Artists = audio.Artists;
  1223. if (info.PrimaryImageTag == null)
  1224. {
  1225. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1226. if (album != null && album.HasImage(ImageType.Primary))
  1227. {
  1228. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1229. if (info.PrimaryImageTag != null)
  1230. {
  1231. info.PrimaryImageItemId = GetDtoId(album);
  1232. }
  1233. }
  1234. }
  1235. }
  1236. var musicVideo = item as MusicVideo;
  1237. if (musicVideo != null)
  1238. {
  1239. info.Album = musicVideo.Album;
  1240. info.Artists = musicVideo.Artists.ToList();
  1241. }
  1242. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1243. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1244. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1245. if (thumbItem == null)
  1246. {
  1247. if (episode != null)
  1248. {
  1249. var series = episode.Series;
  1250. if (series != null && series.HasImage(ImageType.Thumb))
  1251. {
  1252. thumbItem = series;
  1253. }
  1254. }
  1255. }
  1256. if (backropItem == null)
  1257. {
  1258. if (episode != null)
  1259. {
  1260. var series = episode.Series;
  1261. if (series != null && series.HasImage(ImageType.Backdrop))
  1262. {
  1263. backropItem = series;
  1264. }
  1265. }
  1266. }
  1267. if (backropItem == null)
  1268. {
  1269. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1270. }
  1271. if (thumbItem == null)
  1272. {
  1273. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1274. }
  1275. if (logoItem == null)
  1276. {
  1277. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1278. }
  1279. if (thumbItem != null)
  1280. {
  1281. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1282. info.ThumbItemId = GetDtoId(thumbItem);
  1283. }
  1284. if (backropItem != null)
  1285. {
  1286. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1287. info.BackdropItemId = GetDtoId(backropItem);
  1288. }
  1289. if (logoItem != null)
  1290. {
  1291. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1292. info.LogoItemId = GetDtoId(logoItem);
  1293. }
  1294. if (chapterOwner != null)
  1295. {
  1296. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1297. info.Chapters = _dtoService.GetChapterInfoDtos(chapterOwner).ToList();
  1298. }
  1299. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  1300. {
  1301. info.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  1302. {
  1303. ItemId = new Guid(mediaSourceId)
  1304. }).ToList();
  1305. }
  1306. return info;
  1307. }
  1308. private string GetImageCacheTag(BaseItem item, ImageType type)
  1309. {
  1310. try
  1311. {
  1312. return _imageProcessor.GetImageCacheTag(item, type);
  1313. }
  1314. catch (Exception ex)
  1315. {
  1316. _logger.ErrorException("Error getting {0} image info", ex, type);
  1317. return null;
  1318. }
  1319. }
  1320. private string GetDtoId(BaseItem item)
  1321. {
  1322. return _dtoService.GetDtoId(item);
  1323. }
  1324. public void ReportNowViewingItem(string sessionId, string itemId)
  1325. {
  1326. var item = _libraryManager.GetItemById(new Guid(itemId));
  1327. var info = GetItemInfo(item, null, null);
  1328. ReportNowViewingItem(sessionId, info);
  1329. }
  1330. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1331. {
  1332. var session = GetSession(sessionId);
  1333. session.NowViewingItem = item;
  1334. }
  1335. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1336. {
  1337. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1338. if (session != null)
  1339. {
  1340. session.TranscodingInfo = info;
  1341. }
  1342. }
  1343. public void ClearTranscodingInfo(string deviceId)
  1344. {
  1345. ReportTranscodingInfo(deviceId, null);
  1346. }
  1347. public SessionInfo GetSession(string deviceId, string client, string version)
  1348. {
  1349. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1350. string.Equals(i.Client, client));
  1351. }
  1352. public Task SendMessageToUserSessions<T>(string userId, string name, T data,
  1353. CancellationToken cancellationToken)
  1354. {
  1355. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && i.ContainsUser(userId)).ToList();
  1356. var tasks = sessions.Select(session => Task.Run(async () =>
  1357. {
  1358. try
  1359. {
  1360. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1361. }
  1362. catch (Exception ex)
  1363. {
  1364. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  1365. }
  1366. }, cancellationToken));
  1367. return Task.WhenAll(tasks);
  1368. }
  1369. }
  1370. }