SessionManager.cs 69 KB

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