2
0

SessionManager.cs 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  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. EventHelper.FireEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  572. {
  573. Item = libraryItem,
  574. Users = users,
  575. PlaybackPositionTicks = session.PlayState.PositionTicks,
  576. MediaSourceId = session.PlayState.MediaSourceId,
  577. MediaInfo = info.Item,
  578. DeviceName = session.DeviceName,
  579. ClientName = session.Client,
  580. DeviceId = session.DeviceId
  581. }, _logger);
  582. StartIdleCheckTimer();
  583. }
  584. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  585. {
  586. var data = _userDataRepository.GetUserData(userId, userDataKey);
  587. if (positionTicks.HasValue)
  588. {
  589. _userDataRepository.UpdatePlayState(item, data, positionTicks.Value);
  590. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  591. }
  592. }
  593. /// <summary>
  594. /// Used to report that playback has ended for an item
  595. /// </summary>
  596. /// <param name="info">The info.</param>
  597. /// <returns>Task.</returns>
  598. /// <exception cref="System.ArgumentNullException">info</exception>
  599. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  600. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  601. {
  602. if (info == null)
  603. {
  604. throw new ArgumentNullException("info");
  605. }
  606. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  607. {
  608. throw new ArgumentOutOfRangeException("positionTicks");
  609. }
  610. var session = GetSession(info.SessionId);
  611. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  612. ? null
  613. : _libraryManager.GetItemById(new Guid(info.ItemId));
  614. // Normalize
  615. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  616. {
  617. info.MediaSourceId = info.ItemId;
  618. }
  619. if (!string.IsNullOrWhiteSpace(info.ItemId) && info.Item == null && libraryItem != null)
  620. {
  621. var current = session.NowPlayingItem;
  622. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  623. {
  624. var mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId).ConfigureAwait(false);
  625. info.Item = GetItemInfo(libraryItem, libraryItem, mediaSource);
  626. }
  627. else
  628. {
  629. info.Item = current;
  630. }
  631. }
  632. RemoveNowPlayingItem(session);
  633. var users = GetUsers(session);
  634. var playedToCompletion = false;
  635. if (libraryItem != null)
  636. {
  637. var key = libraryItem.GetUserDataKey();
  638. foreach (var user in users)
  639. {
  640. playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  641. }
  642. }
  643. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  644. {
  645. Item = libraryItem,
  646. Users = users,
  647. PlaybackPositionTicks = info.PositionTicks,
  648. PlayedToCompletion = playedToCompletion,
  649. MediaSourceId = info.MediaSourceId,
  650. MediaInfo = info.Item,
  651. DeviceName = session.DeviceName,
  652. ClientName = session.Client,
  653. DeviceId = session.DeviceId
  654. }, _logger);
  655. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  656. }
  657. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  658. {
  659. var data = _userDataRepository.GetUserData(userId, userDataKey);
  660. bool playedToCompletion;
  661. if (positionTicks.HasValue)
  662. {
  663. playedToCompletion = _userDataRepository.UpdatePlayState(item, data, positionTicks.Value);
  664. }
  665. else
  666. {
  667. // If the client isn't able to report this, then we'll just have to make an assumption
  668. data.PlayCount++;
  669. data.Played = true;
  670. data.PlaybackPositionTicks = 0;
  671. playedToCompletion = true;
  672. }
  673. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  674. return playedToCompletion;
  675. }
  676. /// <summary>
  677. /// Gets the session.
  678. /// </summary>
  679. /// <param name="sessionId">The session identifier.</param>
  680. /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
  681. /// <returns>SessionInfo.</returns>
  682. /// <exception cref="ResourceNotFoundException"></exception>
  683. private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
  684. {
  685. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  686. if (session == null && throwOnMissing)
  687. {
  688. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  689. }
  690. return session;
  691. }
  692. private SessionInfo GetSessionToRemoteControl(string sessionId)
  693. {
  694. // Accept either device id or session id
  695. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  696. if (session == null)
  697. {
  698. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  699. }
  700. return session;
  701. }
  702. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  703. {
  704. var generalCommand = new GeneralCommand
  705. {
  706. Name = GeneralCommandType.DisplayMessage.ToString()
  707. };
  708. generalCommand.Arguments["Header"] = command.Header;
  709. generalCommand.Arguments["Text"] = command.Text;
  710. if (command.TimeoutMs.HasValue)
  711. {
  712. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  713. }
  714. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  715. }
  716. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  717. {
  718. var session = GetSessionToRemoteControl(sessionId);
  719. var controllingSession = GetSession(controllingSessionId);
  720. AssertCanControl(session, controllingSession);
  721. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  722. }
  723. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  724. {
  725. var session = GetSessionToRemoteControl(sessionId);
  726. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  727. List<BaseItem> items;
  728. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  729. {
  730. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  731. .Where(i => i.LocationType != LocationType.Virtual)
  732. .ToList();
  733. command.PlayCommand = PlayCommand.PlayNow;
  734. }
  735. else
  736. {
  737. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  738. .Where(i => i.LocationType != LocationType.Virtual)
  739. .ToList();
  740. }
  741. if (command.PlayCommand == PlayCommand.PlayShuffle)
  742. {
  743. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  744. command.PlayCommand = PlayCommand.PlayNow;
  745. }
  746. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  747. if (user != null)
  748. {
  749. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  750. {
  751. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  752. }
  753. }
  754. if (command.PlayCommand != PlayCommand.PlayNow)
  755. {
  756. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  757. {
  758. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id));
  759. }
  760. }
  761. else
  762. {
  763. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  764. {
  765. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id));
  766. }
  767. }
  768. var controllingSession = GetSession(controllingSessionId);
  769. AssertCanControl(session, controllingSession);
  770. if (controllingSession.UserId.HasValue)
  771. {
  772. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  773. }
  774. return session.SessionController.SendPlayCommand(command, cancellationToken);
  775. }
  776. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  777. {
  778. var item = _libraryManager.GetItemById(new Guid(id));
  779. var byName = item as IItemByName;
  780. if (byName != null)
  781. {
  782. var itemFilter = byName.GetItemFilter();
  783. var items = user == null ?
  784. _libraryManager.RootFolder.GetRecursiveChildren(i => !i.IsFolder && itemFilter(i)) :
  785. user.RootFolder.GetRecursiveChildren(user, i => !i.IsFolder && itemFilter(i));
  786. return FilterToSingleMediaType(items)
  787. .OrderBy(i => i.SortName);
  788. }
  789. if (item.IsFolder)
  790. {
  791. var folder = (Folder)item;
  792. var items = user == null ?
  793. folder.GetRecursiveChildren(i => !i.IsFolder) :
  794. folder.GetRecursiveChildren(user, i => !i.IsFolder);
  795. return FilterToSingleMediaType(items)
  796. .OrderBy(i => i.SortName);
  797. }
  798. return new[] { item };
  799. }
  800. private IEnumerable<BaseItem> FilterToSingleMediaType(IEnumerable<BaseItem> items)
  801. {
  802. return items
  803. .Where(i => !string.IsNullOrWhiteSpace(i.MediaType))
  804. .ToLookup(i => i.MediaType, StringComparer.OrdinalIgnoreCase)
  805. .OrderByDescending(i => i.Count())
  806. .FirstOrDefault();
  807. }
  808. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  809. {
  810. var item = _libraryManager.GetItemById(id);
  811. return _musicManager.GetInstantMixFromItem(item, user);
  812. }
  813. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  814. {
  815. var generalCommand = new GeneralCommand
  816. {
  817. Name = GeneralCommandType.DisplayContent.ToString()
  818. };
  819. generalCommand.Arguments["ItemId"] = command.ItemId;
  820. generalCommand.Arguments["ItemName"] = command.ItemName;
  821. generalCommand.Arguments["ItemType"] = command.ItemType;
  822. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  823. }
  824. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  825. {
  826. var session = GetSessionToRemoteControl(sessionId);
  827. var controllingSession = GetSession(controllingSessionId);
  828. AssertCanControl(session, controllingSession);
  829. if (controllingSession.UserId.HasValue)
  830. {
  831. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  832. }
  833. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  834. }
  835. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  836. {
  837. if (session == null)
  838. {
  839. throw new ArgumentNullException("session");
  840. }
  841. if (controllingSession == null)
  842. {
  843. throw new ArgumentNullException("controllingSession");
  844. }
  845. }
  846. /// <summary>
  847. /// Sends the restart required message.
  848. /// </summary>
  849. /// <param name="cancellationToken">The cancellation token.</param>
  850. /// <returns>Task.</returns>
  851. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  852. {
  853. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  854. var info = _appHost.GetSystemInfo();
  855. var tasks = sessions.Select(session => Task.Run(async () =>
  856. {
  857. try
  858. {
  859. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  860. }
  861. catch (Exception ex)
  862. {
  863. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  864. }
  865. }, cancellationToken));
  866. return Task.WhenAll(tasks);
  867. }
  868. /// <summary>
  869. /// Sends the server shutdown notification.
  870. /// </summary>
  871. /// <param name="cancellationToken">The cancellation token.</param>
  872. /// <returns>Task.</returns>
  873. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  874. {
  875. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  876. var tasks = sessions.Select(session => Task.Run(async () =>
  877. {
  878. try
  879. {
  880. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  881. }
  882. catch (Exception ex)
  883. {
  884. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  885. }
  886. }, cancellationToken));
  887. return Task.WhenAll(tasks);
  888. }
  889. /// <summary>
  890. /// Sends the server restart notification.
  891. /// </summary>
  892. /// <param name="cancellationToken">The cancellation token.</param>
  893. /// <returns>Task.</returns>
  894. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  895. {
  896. _logger.Debug("Beginning SendServerRestartNotification");
  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.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  903. }
  904. catch (Exception ex)
  905. {
  906. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  907. }
  908. }, cancellationToken));
  909. return Task.WhenAll(tasks);
  910. }
  911. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  912. {
  913. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  914. var dto = GetSessionInfoDto(sessionInfo);
  915. var tasks = sessions.Select(session => Task.Run(async () =>
  916. {
  917. try
  918. {
  919. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  920. }
  921. catch (Exception ex)
  922. {
  923. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  924. }
  925. }, cancellationToken));
  926. return Task.WhenAll(tasks);
  927. }
  928. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  929. {
  930. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  931. var dto = GetSessionInfoDto(sessionInfo);
  932. var tasks = sessions.Select(session => Task.Run(async () =>
  933. {
  934. try
  935. {
  936. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  937. }
  938. catch (Exception ex)
  939. {
  940. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  941. }
  942. }, cancellationToken));
  943. return Task.WhenAll(tasks);
  944. }
  945. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  946. {
  947. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  948. var dto = GetSessionInfoDto(sessionInfo);
  949. var tasks = sessions.Select(session => Task.Run(async () =>
  950. {
  951. try
  952. {
  953. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  954. }
  955. catch (Exception ex)
  956. {
  957. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  958. }
  959. }, cancellationToken));
  960. return Task.WhenAll(tasks);
  961. }
  962. /// <summary>
  963. /// Adds the additional user.
  964. /// </summary>
  965. /// <param name="sessionId">The session identifier.</param>
  966. /// <param name="userId">The user identifier.</param>
  967. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  968. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  969. public void AddAdditionalUser(string sessionId, Guid userId)
  970. {
  971. var session = GetSession(sessionId);
  972. if (session.UserId.HasValue && session.UserId.Value == userId)
  973. {
  974. throw new ArgumentException("The requested user is already the primary user of the session.");
  975. }
  976. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  977. {
  978. var user = _userManager.GetUserById(userId);
  979. session.AdditionalUsers.Add(new SessionUserInfo
  980. {
  981. UserId = userId.ToString("N"),
  982. UserName = user.Name
  983. });
  984. }
  985. }
  986. /// <summary>
  987. /// Removes the additional user.
  988. /// </summary>
  989. /// <param name="sessionId">The session identifier.</param>
  990. /// <param name="userId">The user identifier.</param>
  991. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  992. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  993. public void RemoveAdditionalUser(string sessionId, Guid userId)
  994. {
  995. var session = GetSession(sessionId);
  996. if (session.UserId.HasValue && session.UserId.Value == userId)
  997. {
  998. throw new ArgumentException("The requested user is already the primary user of the session.");
  999. }
  1000. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  1001. if (user != null)
  1002. {
  1003. session.AdditionalUsers.Remove(user);
  1004. }
  1005. }
  1006. /// <summary>
  1007. /// Authenticates the new session.
  1008. /// </summary>
  1009. /// <param name="request">The request.</param>
  1010. /// <returns>Task{SessionInfo}.</returns>
  1011. public async Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  1012. {
  1013. var user = _userManager.Users
  1014. .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
  1015. if (user != null && !string.IsNullOrWhiteSpace(request.DeviceId))
  1016. {
  1017. if (!_deviceManager.CanAccessDevice(user.Id.ToString("N"), request.DeviceId))
  1018. {
  1019. throw new UnauthorizedAccessException("User is not allowed access from this device.");
  1020. }
  1021. }
  1022. var result = await _userManager.AuthenticateUser(request.Username, request.PasswordSha1, request.PasswordMd5, request.RemoteEndPoint).ConfigureAwait(false);
  1023. if (!result)
  1024. {
  1025. EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1026. throw new UnauthorizedAccessException("Invalid user or password entered.");
  1027. }
  1028. var token = await GetAuthorizationToken(user.Id.ToString("N"), request.DeviceId, request.App, request.AppVersion, request.DeviceName).ConfigureAwait(false);
  1029. EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1030. var session = await LogSessionActivity(request.App,
  1031. request.AppVersion,
  1032. request.DeviceId,
  1033. request.DeviceName,
  1034. request.RemoteEndPoint,
  1035. user)
  1036. .ConfigureAwait(false);
  1037. return new AuthenticationResult
  1038. {
  1039. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1040. SessionInfo = GetSessionInfoDto(session),
  1041. AccessToken = token,
  1042. ServerId = _appHost.SystemId
  1043. };
  1044. }
  1045. private async Task<string> GetAuthorizationToken(string userId, string deviceId, string app, string appVersion, string deviceName)
  1046. {
  1047. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1048. {
  1049. DeviceId = deviceId,
  1050. IsActive = true,
  1051. UserId = userId,
  1052. Limit = 1
  1053. });
  1054. if (existing.Items.Length > 0)
  1055. {
  1056. _logger.Debug("Reissuing access token");
  1057. return existing.Items[0].AccessToken;
  1058. }
  1059. var newToken = new AuthenticationInfo
  1060. {
  1061. AppName = app,
  1062. AppVersion = appVersion,
  1063. DateCreated = DateTime.UtcNow,
  1064. DeviceId = deviceId,
  1065. DeviceName = deviceName,
  1066. UserId = userId,
  1067. IsActive = true,
  1068. AccessToken = Guid.NewGuid().ToString("N")
  1069. };
  1070. _logger.Debug("Creating new access token for user {0}", userId);
  1071. await _authRepo.Create(newToken, CancellationToken.None).ConfigureAwait(false);
  1072. return newToken.AccessToken;
  1073. }
  1074. public async Task Logout(string accessToken)
  1075. {
  1076. if (string.IsNullOrWhiteSpace(accessToken))
  1077. {
  1078. throw new ArgumentNullException("accessToken");
  1079. }
  1080. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1081. {
  1082. Limit = 1,
  1083. AccessToken = accessToken
  1084. }).Items.FirstOrDefault();
  1085. if (existing != null)
  1086. {
  1087. existing.IsActive = false;
  1088. await _authRepo.Update(existing, CancellationToken.None).ConfigureAwait(false);
  1089. var sessions = Sessions
  1090. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1091. .ToList();
  1092. foreach (var session in sessions)
  1093. {
  1094. try
  1095. {
  1096. ReportSessionEnded(session.Id);
  1097. }
  1098. catch (Exception ex)
  1099. {
  1100. _logger.ErrorException("Error reporting session ended", ex);
  1101. }
  1102. }
  1103. }
  1104. }
  1105. public async Task RevokeUserTokens(string userId)
  1106. {
  1107. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1108. {
  1109. IsActive = true,
  1110. UserId = userId
  1111. });
  1112. foreach (var info in existing.Items)
  1113. {
  1114. await Logout(info.AccessToken).ConfigureAwait(false);
  1115. }
  1116. }
  1117. public Task RevokeToken(string token)
  1118. {
  1119. return Logout(token);
  1120. }
  1121. /// <summary>
  1122. /// Reports the capabilities.
  1123. /// </summary>
  1124. /// <param name="sessionId">The session identifier.</param>
  1125. /// <param name="capabilities">The capabilities.</param>
  1126. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1127. {
  1128. var session = GetSession(sessionId);
  1129. ReportCapabilities(session, capabilities, true);
  1130. }
  1131. private async void ReportCapabilities(SessionInfo session,
  1132. ClientCapabilities capabilities,
  1133. bool saveCapabilities)
  1134. {
  1135. session.Capabilities = capabilities;
  1136. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1137. {
  1138. var controller = session.SessionController as HttpSessionController;
  1139. if (controller == null)
  1140. {
  1141. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1142. }
  1143. }
  1144. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1145. {
  1146. SessionInfo = session
  1147. }, _logger);
  1148. if (saveCapabilities)
  1149. {
  1150. try
  1151. {
  1152. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1153. }
  1154. catch (Exception ex)
  1155. {
  1156. _logger.ErrorException("Error saving device capabilities", ex);
  1157. }
  1158. }
  1159. }
  1160. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1161. {
  1162. return _deviceManager.GetCapabilities(deviceId);
  1163. }
  1164. private Task SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1165. {
  1166. return _deviceManager.SaveCapabilities(deviceId, capabilities);
  1167. }
  1168. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1169. {
  1170. var dto = new SessionInfoDto
  1171. {
  1172. Client = session.Client,
  1173. DeviceId = session.DeviceId,
  1174. DeviceName = session.DeviceName,
  1175. Id = session.Id,
  1176. LastActivityDate = session.LastActivityDate,
  1177. NowViewingItem = session.NowViewingItem,
  1178. ApplicationVersion = session.ApplicationVersion,
  1179. QueueableMediaTypes = session.QueueableMediaTypes,
  1180. PlayableMediaTypes = session.PlayableMediaTypes,
  1181. AdditionalUsers = session.AdditionalUsers,
  1182. SupportedCommands = session.SupportedCommands,
  1183. UserName = session.UserName,
  1184. NowPlayingItem = session.NowPlayingItem,
  1185. SupportsRemoteControl = session.SupportsMediaControl,
  1186. PlayState = session.PlayState,
  1187. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1188. };
  1189. if (session.UserId.HasValue)
  1190. {
  1191. dto.UserId = session.UserId.Value.ToString("N");
  1192. var user = _userManager.GetUserById(session.UserId.Value);
  1193. if (user != null)
  1194. {
  1195. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1196. }
  1197. }
  1198. return dto;
  1199. }
  1200. /// <summary>
  1201. /// Converts a BaseItem to a BaseItemInfo
  1202. /// </summary>
  1203. /// <param name="item">The item.</param>
  1204. /// <param name="chapterOwner">The chapter owner.</param>
  1205. /// <param name="mediaSource">The media source.</param>
  1206. /// <returns>BaseItemInfo.</returns>
  1207. /// <exception cref="System.ArgumentNullException">item</exception>
  1208. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, MediaSourceInfo mediaSource)
  1209. {
  1210. if (item == null)
  1211. {
  1212. throw new ArgumentNullException("item");
  1213. }
  1214. var info = new BaseItemInfo
  1215. {
  1216. Id = GetDtoId(item),
  1217. Name = item.Name,
  1218. MediaType = item.MediaType,
  1219. Type = item.GetClientTypeName(),
  1220. RunTimeTicks = item.RunTimeTicks,
  1221. IndexNumber = item.IndexNumber,
  1222. ParentIndexNumber = item.ParentIndexNumber,
  1223. PremiereDate = item.PremiereDate,
  1224. ProductionYear = item.ProductionYear
  1225. };
  1226. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1227. if (info.PrimaryImageTag != null)
  1228. {
  1229. info.PrimaryImageItemId = GetDtoId(item);
  1230. }
  1231. var episode = item as Episode;
  1232. if (episode != null)
  1233. {
  1234. info.IndexNumberEnd = episode.IndexNumberEnd;
  1235. }
  1236. var hasSeries = item as IHasSeries;
  1237. if (hasSeries != null)
  1238. {
  1239. info.SeriesName = hasSeries.SeriesName;
  1240. }
  1241. var recording = item as ILiveTvRecording;
  1242. if (recording != null && recording.RecordingInfo != null)
  1243. {
  1244. if (recording.RecordingInfo.IsSeries)
  1245. {
  1246. info.Name = recording.RecordingInfo.EpisodeTitle;
  1247. info.SeriesName = recording.RecordingInfo.Name;
  1248. if (string.IsNullOrWhiteSpace(info.Name))
  1249. {
  1250. info.Name = recording.RecordingInfo.Name;
  1251. }
  1252. }
  1253. }
  1254. var audio = item as Audio;
  1255. if (audio != null)
  1256. {
  1257. info.Album = audio.Album;
  1258. info.Artists = audio.Artists;
  1259. if (info.PrimaryImageTag == null)
  1260. {
  1261. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1262. if (album != null && album.HasImage(ImageType.Primary))
  1263. {
  1264. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1265. if (info.PrimaryImageTag != null)
  1266. {
  1267. info.PrimaryImageItemId = GetDtoId(album);
  1268. }
  1269. }
  1270. }
  1271. }
  1272. var musicVideo = item as MusicVideo;
  1273. if (musicVideo != null)
  1274. {
  1275. info.Album = musicVideo.Album;
  1276. info.Artists = musicVideo.Artists.ToList();
  1277. }
  1278. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1279. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1280. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1281. if (thumbItem == null)
  1282. {
  1283. if (episode != null)
  1284. {
  1285. var series = episode.Series;
  1286. if (series != null && series.HasImage(ImageType.Thumb))
  1287. {
  1288. thumbItem = series;
  1289. }
  1290. }
  1291. }
  1292. if (backropItem == null)
  1293. {
  1294. if (episode != null)
  1295. {
  1296. var series = episode.Series;
  1297. if (series != null && series.HasImage(ImageType.Backdrop))
  1298. {
  1299. backropItem = series;
  1300. }
  1301. }
  1302. }
  1303. if (backropItem == null)
  1304. {
  1305. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1306. }
  1307. if (thumbItem == null)
  1308. {
  1309. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1310. }
  1311. if (logoItem == null)
  1312. {
  1313. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1314. }
  1315. if (thumbItem != null)
  1316. {
  1317. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1318. info.ThumbItemId = GetDtoId(thumbItem);
  1319. }
  1320. if (backropItem != null)
  1321. {
  1322. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1323. info.BackdropItemId = GetDtoId(backropItem);
  1324. }
  1325. if (logoItem != null)
  1326. {
  1327. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1328. info.LogoItemId = GetDtoId(logoItem);
  1329. }
  1330. if (chapterOwner != null)
  1331. {
  1332. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1333. info.Chapters = _dtoService.GetChapterInfoDtos(chapterOwner).ToList();
  1334. }
  1335. if (mediaSource != null)
  1336. {
  1337. info.MediaStreams = mediaSource.MediaStreams;
  1338. }
  1339. return info;
  1340. }
  1341. private string GetImageCacheTag(BaseItem item, ImageType type)
  1342. {
  1343. try
  1344. {
  1345. return _imageProcessor.GetImageCacheTag(item, type);
  1346. }
  1347. catch (Exception ex)
  1348. {
  1349. _logger.ErrorException("Error getting {0} image info", ex, type);
  1350. return null;
  1351. }
  1352. }
  1353. private string GetDtoId(BaseItem item)
  1354. {
  1355. return _dtoService.GetDtoId(item);
  1356. }
  1357. public void ReportNowViewingItem(string sessionId, string itemId)
  1358. {
  1359. var item = _libraryManager.GetItemById(new Guid(itemId));
  1360. var info = GetItemInfo(item, null, null);
  1361. ReportNowViewingItem(sessionId, info);
  1362. }
  1363. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1364. {
  1365. var session = GetSession(sessionId);
  1366. session.NowViewingItem = item;
  1367. }
  1368. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1369. {
  1370. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1371. if (session != null)
  1372. {
  1373. session.TranscodingInfo = info;
  1374. }
  1375. }
  1376. public void ClearTranscodingInfo(string deviceId)
  1377. {
  1378. ReportTranscodingInfo(deviceId, null);
  1379. }
  1380. public SessionInfo GetSession(string deviceId, string client, string version)
  1381. {
  1382. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1383. string.Equals(i.Client, client));
  1384. }
  1385. public Task<SessionInfo> GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1386. {
  1387. if (info == null)
  1388. {
  1389. throw new ArgumentNullException("info");
  1390. }
  1391. var user = string.IsNullOrWhiteSpace(info.UserId)
  1392. ? null
  1393. : _userManager.GetUserById(info.UserId);
  1394. appVersion = string.IsNullOrWhiteSpace(appVersion)
  1395. ? info.AppVersion
  1396. : appVersion;
  1397. var deviceName = info.DeviceName;
  1398. var appName = info.AppName;
  1399. if (!string.IsNullOrWhiteSpace(deviceId))
  1400. {
  1401. // Replace the info from the token with more recent info
  1402. var device = _deviceManager.GetDevice(deviceId);
  1403. if (device != null)
  1404. {
  1405. deviceName = device.Name;
  1406. appName = device.AppName;
  1407. if (!string.IsNullOrWhiteSpace(device.AppVersion))
  1408. {
  1409. appVersion = device.AppVersion;
  1410. }
  1411. }
  1412. }
  1413. else
  1414. {
  1415. deviceId = info.DeviceId;
  1416. }
  1417. // Prevent argument exception
  1418. if (string.IsNullOrWhiteSpace(appVersion))
  1419. {
  1420. appVersion = "1";
  1421. }
  1422. return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1423. }
  1424. public Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1425. {
  1426. var result = _authRepo.Get(new AuthenticationInfoQuery
  1427. {
  1428. AccessToken = token
  1429. });
  1430. var info = result.Items.FirstOrDefault();
  1431. if (info == null)
  1432. {
  1433. return Task.FromResult<SessionInfo>(null);
  1434. }
  1435. return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
  1436. }
  1437. public Task SendMessageToUserSessions<T>(string userId, string name, T data,
  1438. CancellationToken cancellationToken)
  1439. {
  1440. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && i.ContainsUser(userId)).ToList();
  1441. var tasks = sessions.Select(session => Task.Run(async () =>
  1442. {
  1443. try
  1444. {
  1445. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1446. }
  1447. catch (Exception ex)
  1448. {
  1449. _logger.ErrorException("Error sending message", ex);
  1450. }
  1451. }, cancellationToken));
  1452. return Task.WhenAll(tasks);
  1453. }
  1454. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data,
  1455. CancellationToken cancellationToken)
  1456. {
  1457. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
  1458. var tasks = sessions.Select(session => Task.Run(async () =>
  1459. {
  1460. try
  1461. {
  1462. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1463. }
  1464. catch (Exception ex)
  1465. {
  1466. _logger.ErrorException("Error sending message", ex);
  1467. }
  1468. }, cancellationToken));
  1469. return Task.WhenAll(tasks);
  1470. }
  1471. }
  1472. }