SessionManager.cs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812
  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(new Guid(id));
  809. var byName = item as IItemByName;
  810. if (byName != null)
  811. {
  812. var itemFilter = byName.GetItemFilter();
  813. var items = user == null ?
  814. _libraryManager.RootFolder.GetRecursiveChildren(i => !i.IsFolder && itemFilter(i)) :
  815. user.RootFolder.GetRecursiveChildren(user, i => !i.IsFolder && itemFilter(i));
  816. return FilterToSingleMediaType(items)
  817. .OrderBy(i => i.SortName);
  818. }
  819. if (item.IsFolder)
  820. {
  821. var folder = (Folder)item;
  822. var items = user == null ?
  823. folder.GetRecursiveChildren(i => !i.IsFolder) :
  824. folder.GetRecursiveChildren(user, i => !i.IsFolder);
  825. return FilterToSingleMediaType(items)
  826. .OrderBy(i => i.SortName);
  827. }
  828. return new[] { item };
  829. }
  830. private IEnumerable<BaseItem> FilterToSingleMediaType(IEnumerable<BaseItem> items)
  831. {
  832. return items
  833. .Where(i => !string.IsNullOrWhiteSpace(i.MediaType))
  834. .ToLookup(i => i.MediaType, StringComparer.OrdinalIgnoreCase)
  835. .OrderByDescending(i => i.Count())
  836. .FirstOrDefault();
  837. }
  838. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  839. {
  840. var item = _libraryManager.GetItemById(id);
  841. return _musicManager.GetInstantMixFromItem(item, user);
  842. }
  843. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  844. {
  845. var generalCommand = new GeneralCommand
  846. {
  847. Name = GeneralCommandType.DisplayContent.ToString()
  848. };
  849. generalCommand.Arguments["ItemId"] = command.ItemId;
  850. generalCommand.Arguments["ItemName"] = command.ItemName;
  851. generalCommand.Arguments["ItemType"] = command.ItemType;
  852. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  853. }
  854. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  855. {
  856. var session = GetSessionToRemoteControl(sessionId);
  857. var controllingSession = GetSession(controllingSessionId);
  858. AssertCanControl(session, controllingSession);
  859. if (controllingSession.UserId.HasValue)
  860. {
  861. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  862. }
  863. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  864. }
  865. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  866. {
  867. if (session == null)
  868. {
  869. throw new ArgumentNullException("session");
  870. }
  871. if (controllingSession == null)
  872. {
  873. throw new ArgumentNullException("controllingSession");
  874. }
  875. }
  876. /// <summary>
  877. /// Sends the restart required message.
  878. /// </summary>
  879. /// <param name="cancellationToken">The cancellation token.</param>
  880. /// <returns>Task.</returns>
  881. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  882. {
  883. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  884. var info = _appHost.GetSystemInfo();
  885. var tasks = sessions.Select(session => Task.Run(async () =>
  886. {
  887. try
  888. {
  889. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  890. }
  891. catch (Exception ex)
  892. {
  893. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  894. }
  895. }, cancellationToken));
  896. return Task.WhenAll(tasks);
  897. }
  898. /// <summary>
  899. /// Sends the server shutdown notification.
  900. /// </summary>
  901. /// <param name="cancellationToken">The cancellation token.</param>
  902. /// <returns>Task.</returns>
  903. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  904. {
  905. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  906. var tasks = sessions.Select(session => Task.Run(async () =>
  907. {
  908. try
  909. {
  910. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  911. }
  912. catch (Exception ex)
  913. {
  914. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  915. }
  916. }, cancellationToken));
  917. return Task.WhenAll(tasks);
  918. }
  919. /// <summary>
  920. /// Sends the server restart notification.
  921. /// </summary>
  922. /// <param name="cancellationToken">The cancellation token.</param>
  923. /// <returns>Task.</returns>
  924. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  925. {
  926. _logger.Debug("Beginning SendServerRestartNotification");
  927. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  928. var tasks = sessions.Select(session => Task.Run(async () =>
  929. {
  930. try
  931. {
  932. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  933. }
  934. catch (Exception ex)
  935. {
  936. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  937. }
  938. }, cancellationToken));
  939. return Task.WhenAll(tasks);
  940. }
  941. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  942. {
  943. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  944. var dto = GetSessionInfoDto(sessionInfo);
  945. var tasks = sessions.Select(session => Task.Run(async () =>
  946. {
  947. try
  948. {
  949. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  950. }
  951. catch (Exception ex)
  952. {
  953. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  954. }
  955. }, cancellationToken));
  956. return Task.WhenAll(tasks);
  957. }
  958. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  959. {
  960. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  961. var dto = GetSessionInfoDto(sessionInfo);
  962. var tasks = sessions.Select(session => Task.Run(async () =>
  963. {
  964. try
  965. {
  966. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  967. }
  968. catch (Exception ex)
  969. {
  970. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  971. }
  972. }, cancellationToken));
  973. return Task.WhenAll(tasks);
  974. }
  975. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  976. {
  977. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  978. var dto = GetSessionInfoDto(sessionInfo);
  979. var tasks = sessions.Select(session => Task.Run(async () =>
  980. {
  981. try
  982. {
  983. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  984. }
  985. catch (Exception ex)
  986. {
  987. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  988. }
  989. }, cancellationToken));
  990. return Task.WhenAll(tasks);
  991. }
  992. /// <summary>
  993. /// Adds the additional user.
  994. /// </summary>
  995. /// <param name="sessionId">The session identifier.</param>
  996. /// <param name="userId">The user identifier.</param>
  997. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  998. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  999. public void AddAdditionalUser(string sessionId, string userId)
  1000. {
  1001. var session = GetSession(sessionId);
  1002. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1003. {
  1004. throw new ArgumentException("The requested user is already the primary user of the session.");
  1005. }
  1006. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != new Guid(userId)))
  1007. {
  1008. var user = _userManager.GetUserById(userId);
  1009. session.AdditionalUsers.Add(new SessionUserInfo
  1010. {
  1011. UserId = userId,
  1012. UserName = user.Name
  1013. });
  1014. }
  1015. }
  1016. /// <summary>
  1017. /// Removes the additional user.
  1018. /// </summary>
  1019. /// <param name="sessionId">The session identifier.</param>
  1020. /// <param name="userId">The user identifier.</param>
  1021. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  1022. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  1023. public void RemoveAdditionalUser(string sessionId, string userId)
  1024. {
  1025. var session = GetSession(sessionId);
  1026. if (session.UserId.HasValue && session.UserId.Value == new Guid(userId))
  1027. {
  1028. throw new ArgumentException("The requested user is already the primary user of the session.");
  1029. }
  1030. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == new Guid(userId));
  1031. if (user != null)
  1032. {
  1033. session.AdditionalUsers.Remove(user);
  1034. }
  1035. }
  1036. /// <summary>
  1037. /// Authenticates the new session.
  1038. /// </summary>
  1039. /// <param name="request">The request.</param>
  1040. /// <returns>Task{SessionInfo}.</returns>
  1041. public async Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
  1042. {
  1043. var user = _userManager.Users
  1044. .FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
  1045. if (user != null && !string.IsNullOrWhiteSpace(request.DeviceId))
  1046. {
  1047. if (!_deviceManager.CanAccessDevice(user.Id.ToString("N"), request.DeviceId))
  1048. {
  1049. throw new UnauthorizedAccessException("User is not allowed access from this device.");
  1050. }
  1051. }
  1052. var result = await _userManager.AuthenticateUser(request.Username, request.PasswordSha1, request.PasswordMd5, request.RemoteEndPoint).ConfigureAwait(false);
  1053. if (!result)
  1054. {
  1055. EventHelper.FireEventIfNotNull(AuthenticationFailed, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1056. throw new UnauthorizedAccessException("Invalid user or password entered.");
  1057. }
  1058. var token = await GetAuthorizationToken(user.Id.ToString("N"), request.DeviceId, request.App, request.AppVersion, request.DeviceName).ConfigureAwait(false);
  1059. EventHelper.FireEventIfNotNull(AuthenticationSucceeded, this, new GenericEventArgs<AuthenticationRequest>(request), _logger);
  1060. var session = await LogSessionActivity(request.App,
  1061. request.AppVersion,
  1062. request.DeviceId,
  1063. request.DeviceName,
  1064. request.RemoteEndPoint,
  1065. user)
  1066. .ConfigureAwait(false);
  1067. return new AuthenticationResult
  1068. {
  1069. User = _userManager.GetUserDto(user, request.RemoteEndPoint),
  1070. SessionInfo = GetSessionInfoDto(session),
  1071. AccessToken = token,
  1072. ServerId = _appHost.SystemId
  1073. };
  1074. }
  1075. private async Task<string> GetAuthorizationToken(string userId, string deviceId, string app, string appVersion, string deviceName)
  1076. {
  1077. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1078. {
  1079. DeviceId = deviceId,
  1080. IsActive = true,
  1081. UserId = userId,
  1082. Limit = 1
  1083. });
  1084. if (existing.Items.Length > 0)
  1085. {
  1086. _logger.Debug("Reissuing access token");
  1087. return existing.Items[0].AccessToken;
  1088. }
  1089. var newToken = new AuthenticationInfo
  1090. {
  1091. AppName = app,
  1092. AppVersion = appVersion,
  1093. DateCreated = DateTime.UtcNow,
  1094. DeviceId = deviceId,
  1095. DeviceName = deviceName,
  1096. UserId = userId,
  1097. IsActive = true,
  1098. AccessToken = Guid.NewGuid().ToString("N")
  1099. };
  1100. _logger.Debug("Creating new access token for user {0}", userId);
  1101. await _authRepo.Create(newToken, CancellationToken.None).ConfigureAwait(false);
  1102. return newToken.AccessToken;
  1103. }
  1104. public async Task Logout(string accessToken)
  1105. {
  1106. if (string.IsNullOrWhiteSpace(accessToken))
  1107. {
  1108. throw new ArgumentNullException("accessToken");
  1109. }
  1110. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1111. {
  1112. Limit = 1,
  1113. AccessToken = accessToken
  1114. }).Items.FirstOrDefault();
  1115. if (existing != null)
  1116. {
  1117. existing.IsActive = false;
  1118. await _authRepo.Update(existing, CancellationToken.None).ConfigureAwait(false);
  1119. var sessions = Sessions
  1120. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1121. .ToList();
  1122. foreach (var session in sessions)
  1123. {
  1124. try
  1125. {
  1126. ReportSessionEnded(session.Id);
  1127. }
  1128. catch (Exception ex)
  1129. {
  1130. _logger.ErrorException("Error reporting session ended", ex);
  1131. }
  1132. }
  1133. }
  1134. }
  1135. public async Task RevokeUserTokens(string userId)
  1136. {
  1137. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1138. {
  1139. IsActive = true,
  1140. UserId = userId
  1141. });
  1142. foreach (var info in existing.Items)
  1143. {
  1144. await Logout(info.AccessToken).ConfigureAwait(false);
  1145. }
  1146. }
  1147. public Task RevokeToken(string token)
  1148. {
  1149. return Logout(token);
  1150. }
  1151. /// <summary>
  1152. /// Reports the capabilities.
  1153. /// </summary>
  1154. /// <param name="sessionId">The session identifier.</param>
  1155. /// <param name="capabilities">The capabilities.</param>
  1156. public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
  1157. {
  1158. var session = GetSession(sessionId);
  1159. ReportCapabilities(session, capabilities, true);
  1160. }
  1161. private async void ReportCapabilities(SessionInfo session,
  1162. ClientCapabilities capabilities,
  1163. bool saveCapabilities)
  1164. {
  1165. session.Capabilities = capabilities;
  1166. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1167. {
  1168. var controller = session.SessionController as HttpSessionController;
  1169. if (controller == null)
  1170. {
  1171. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1172. }
  1173. }
  1174. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1175. {
  1176. SessionInfo = session
  1177. }, _logger);
  1178. if (saveCapabilities)
  1179. {
  1180. try
  1181. {
  1182. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1183. }
  1184. catch (Exception ex)
  1185. {
  1186. _logger.ErrorException("Error saving device capabilities", ex);
  1187. }
  1188. }
  1189. }
  1190. private ClientCapabilities GetSavedCapabilities(string deviceId)
  1191. {
  1192. return _deviceManager.GetCapabilities(deviceId);
  1193. }
  1194. private Task SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  1195. {
  1196. return _deviceManager.SaveCapabilities(deviceId, capabilities);
  1197. }
  1198. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1199. {
  1200. var dto = new SessionInfoDto
  1201. {
  1202. Client = session.Client,
  1203. DeviceId = session.DeviceId,
  1204. DeviceName = session.DeviceName,
  1205. Id = session.Id,
  1206. LastActivityDate = session.LastActivityDate,
  1207. NowViewingItem = session.NowViewingItem,
  1208. ApplicationVersion = session.ApplicationVersion,
  1209. QueueableMediaTypes = session.QueueableMediaTypes,
  1210. PlayableMediaTypes = session.PlayableMediaTypes,
  1211. AdditionalUsers = session.AdditionalUsers,
  1212. SupportedCommands = session.SupportedCommands,
  1213. UserName = session.UserName,
  1214. NowPlayingItem = session.NowPlayingItem,
  1215. SupportsRemoteControl = session.SupportsMediaControl,
  1216. PlayState = session.PlayState,
  1217. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1218. };
  1219. if (session.UserId.HasValue)
  1220. {
  1221. dto.UserId = session.UserId.Value.ToString("N");
  1222. var user = _userManager.GetUserById(session.UserId.Value);
  1223. if (user != null)
  1224. {
  1225. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1226. }
  1227. }
  1228. return dto;
  1229. }
  1230. /// <summary>
  1231. /// Converts a BaseItem to a BaseItemInfo
  1232. /// </summary>
  1233. /// <param name="item">The item.</param>
  1234. /// <param name="chapterOwner">The chapter owner.</param>
  1235. /// <param name="mediaSource">The media source.</param>
  1236. /// <returns>BaseItemInfo.</returns>
  1237. /// <exception cref="System.ArgumentNullException">item</exception>
  1238. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, MediaSourceInfo mediaSource)
  1239. {
  1240. if (item == null)
  1241. {
  1242. throw new ArgumentNullException("item");
  1243. }
  1244. var info = new BaseItemInfo
  1245. {
  1246. Id = GetDtoId(item),
  1247. Name = item.Name,
  1248. MediaType = item.MediaType,
  1249. Type = item.GetClientTypeName(),
  1250. RunTimeTicks = item.RunTimeTicks,
  1251. IndexNumber = item.IndexNumber,
  1252. ParentIndexNumber = item.ParentIndexNumber,
  1253. PremiereDate = item.PremiereDate,
  1254. ProductionYear = item.ProductionYear
  1255. };
  1256. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1257. if (info.PrimaryImageTag != null)
  1258. {
  1259. info.PrimaryImageItemId = GetDtoId(item);
  1260. }
  1261. var episode = item as Episode;
  1262. if (episode != null)
  1263. {
  1264. info.IndexNumberEnd = episode.IndexNumberEnd;
  1265. }
  1266. var hasSeries = item as IHasSeries;
  1267. if (hasSeries != null)
  1268. {
  1269. info.SeriesName = hasSeries.SeriesName;
  1270. }
  1271. var recording = item as ILiveTvRecording;
  1272. if (recording != null && recording.RecordingInfo != null)
  1273. {
  1274. if (recording.RecordingInfo.IsSeries)
  1275. {
  1276. info.Name = recording.RecordingInfo.EpisodeTitle;
  1277. info.SeriesName = recording.RecordingInfo.Name;
  1278. if (string.IsNullOrWhiteSpace(info.Name))
  1279. {
  1280. info.Name = recording.RecordingInfo.Name;
  1281. }
  1282. }
  1283. }
  1284. var audio = item as Audio;
  1285. if (audio != null)
  1286. {
  1287. info.Album = audio.Album;
  1288. info.Artists = audio.Artists;
  1289. if (info.PrimaryImageTag == null)
  1290. {
  1291. var album = audio.AlbumEntity;
  1292. if (album != null && album.HasImage(ImageType.Primary))
  1293. {
  1294. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1295. if (info.PrimaryImageTag != null)
  1296. {
  1297. info.PrimaryImageItemId = GetDtoId(album);
  1298. }
  1299. }
  1300. }
  1301. }
  1302. var musicVideo = item as MusicVideo;
  1303. if (musicVideo != null)
  1304. {
  1305. info.Album = musicVideo.Album;
  1306. info.Artists = musicVideo.Artists.ToList();
  1307. }
  1308. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1309. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1310. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1311. if (thumbItem == null)
  1312. {
  1313. if (episode != null)
  1314. {
  1315. var series = episode.Series;
  1316. if (series != null && series.HasImage(ImageType.Thumb))
  1317. {
  1318. thumbItem = series;
  1319. }
  1320. }
  1321. }
  1322. if (backropItem == null)
  1323. {
  1324. if (episode != null)
  1325. {
  1326. var series = episode.Series;
  1327. if (series != null && series.HasImage(ImageType.Backdrop))
  1328. {
  1329. backropItem = series;
  1330. }
  1331. }
  1332. }
  1333. if (backropItem == null)
  1334. {
  1335. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1336. }
  1337. if (thumbItem == null)
  1338. {
  1339. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1340. }
  1341. if (logoItem == null)
  1342. {
  1343. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1344. }
  1345. if (thumbItem != null)
  1346. {
  1347. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1348. info.ThumbItemId = GetDtoId(thumbItem);
  1349. }
  1350. if (backropItem != null)
  1351. {
  1352. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1353. info.BackdropItemId = GetDtoId(backropItem);
  1354. }
  1355. if (logoItem != null)
  1356. {
  1357. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1358. info.LogoItemId = GetDtoId(logoItem);
  1359. }
  1360. if (chapterOwner != null)
  1361. {
  1362. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1363. info.Chapters = _dtoService.GetChapterInfoDtos(chapterOwner).ToList();
  1364. }
  1365. if (mediaSource != null)
  1366. {
  1367. info.MediaStreams = mediaSource.MediaStreams;
  1368. }
  1369. return info;
  1370. }
  1371. private string GetImageCacheTag(BaseItem item, ImageType type)
  1372. {
  1373. try
  1374. {
  1375. return _imageProcessor.GetImageCacheTag(item, type);
  1376. }
  1377. catch (Exception ex)
  1378. {
  1379. _logger.ErrorException("Error getting {0} image info", ex, type);
  1380. return null;
  1381. }
  1382. }
  1383. private string GetDtoId(BaseItem item)
  1384. {
  1385. return _dtoService.GetDtoId(item);
  1386. }
  1387. public void ReportNowViewingItem(string sessionId, string itemId)
  1388. {
  1389. var item = _libraryManager.GetItemById(new Guid(itemId));
  1390. var info = GetItemInfo(item, null, null);
  1391. ReportNowViewingItem(sessionId, info);
  1392. }
  1393. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1394. {
  1395. var session = GetSession(sessionId);
  1396. session.NowViewingItem = item;
  1397. }
  1398. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1399. {
  1400. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1401. if (session != null)
  1402. {
  1403. session.TranscodingInfo = info;
  1404. }
  1405. }
  1406. public void ClearTranscodingInfo(string deviceId)
  1407. {
  1408. ReportTranscodingInfo(deviceId, null);
  1409. }
  1410. public SessionInfo GetSession(string deviceId, string client, string version)
  1411. {
  1412. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1413. string.Equals(i.Client, client));
  1414. }
  1415. public Task<SessionInfo> GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
  1416. {
  1417. if (info == null)
  1418. {
  1419. throw new ArgumentNullException("info");
  1420. }
  1421. var user = string.IsNullOrWhiteSpace(info.UserId)
  1422. ? null
  1423. : _userManager.GetUserById(info.UserId);
  1424. appVersion = string.IsNullOrWhiteSpace(appVersion)
  1425. ? info.AppVersion
  1426. : appVersion;
  1427. var deviceName = info.DeviceName;
  1428. var appName = info.AppName;
  1429. if (!string.IsNullOrWhiteSpace(deviceId))
  1430. {
  1431. // Replace the info from the token with more recent info
  1432. var device = _deviceManager.GetDevice(deviceId);
  1433. if (device != null)
  1434. {
  1435. deviceName = device.Name;
  1436. appName = device.AppName;
  1437. if (!string.IsNullOrWhiteSpace(device.AppVersion))
  1438. {
  1439. appVersion = device.AppVersion;
  1440. }
  1441. }
  1442. }
  1443. else
  1444. {
  1445. deviceId = info.DeviceId;
  1446. }
  1447. // Prevent argument exception
  1448. if (string.IsNullOrWhiteSpace(appVersion))
  1449. {
  1450. appVersion = "1";
  1451. }
  1452. return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
  1453. }
  1454. public Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
  1455. {
  1456. var result = _authRepo.Get(new AuthenticationInfoQuery
  1457. {
  1458. AccessToken = token
  1459. });
  1460. var info = result.Items.FirstOrDefault();
  1461. if (info == null)
  1462. {
  1463. return Task.FromResult<SessionInfo>(null);
  1464. }
  1465. return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
  1466. }
  1467. public Task SendMessageToUserSessions<T>(string userId, string name, T data,
  1468. CancellationToken cancellationToken)
  1469. {
  1470. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && i.ContainsUser(userId)).ToList();
  1471. var tasks = sessions.Select(session => Task.Run(async () =>
  1472. {
  1473. try
  1474. {
  1475. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1476. }
  1477. catch (Exception ex)
  1478. {
  1479. _logger.ErrorException("Error sending message", ex);
  1480. }
  1481. }, cancellationToken));
  1482. return Task.WhenAll(tasks);
  1483. }
  1484. public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data,
  1485. CancellationToken cancellationToken)
  1486. {
  1487. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null && string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
  1488. var tasks = sessions.Select(session => Task.Run(async () =>
  1489. {
  1490. try
  1491. {
  1492. await session.SessionController.SendMessage(name, data, cancellationToken).ConfigureAwait(false);
  1493. }
  1494. catch (Exception ex)
  1495. {
  1496. _logger.ErrorException("Error sending message", ex);
  1497. }
  1498. }, cancellationToken));
  1499. return Task.WhenAll(tasks);
  1500. }
  1501. }
  1502. }