SessionManager.cs 68 KB

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