SessionManager.cs 67 KB

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