SessionManager.cs 65 KB

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