2
0

SessionManager.cs 68 KB

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