SessionManager.cs 64 KB

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