SessionManager.cs 68 KB

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