SessionManager.cs 59 KB

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