SessionManager.cs 65 KB

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