SessionManager.cs 69 KB

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