SessionManager.cs 68 KB

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