SessionManager.cs 65 KB

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