2
0

SessionManager.cs 61 KB

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