SessionManager.cs 67 KB

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