SessionManager.cs 67 KB

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