SessionManager.cs 69 KB

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