2
0

SessionManager.cs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  1. using MediaBrowser.Common.Events;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Configuration;
  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.Entities;
  17. using MediaBrowser.Model.Library;
  18. using MediaBrowser.Model.Logging;
  19. using MediaBrowser.Model.Serialization;
  20. using MediaBrowser.Model.Session;
  21. using MediaBrowser.Model.Users;
  22. using System;
  23. using System.Collections.Concurrent;
  24. using System.Collections.Generic;
  25. using System.Globalization;
  26. using System.IO;
  27. using System.Linq;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. namespace MediaBrowser.Server.Implementations.Session
  31. {
  32. /// <summary>
  33. /// Class SessionManager
  34. /// </summary>
  35. public class SessionManager : ISessionManager
  36. {
  37. /// <summary>
  38. /// The _user data repository
  39. /// </summary>
  40. private readonly IUserDataManager _userDataRepository;
  41. /// <summary>
  42. /// The _user repository
  43. /// </summary>
  44. private readonly IUserRepository _userRepository;
  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 IItemRepository _itemRepo;
  55. private readonly IHttpClient _httpClient;
  56. private readonly IJsonSerializer _jsonSerializer;
  57. private readonly IServerApplicationHost _appHost;
  58. private readonly IAuthenticationRepository _authRepo;
  59. /// <summary>
  60. /// Gets or sets the configuration manager.
  61. /// </summary>
  62. /// <value>The configuration manager.</value>
  63. private readonly IServerConfigurationManager _configurationManager;
  64. /// <summary>
  65. /// The _active connections
  66. /// </summary>
  67. private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
  68. new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
  69. /// <summary>
  70. /// Occurs when [playback start].
  71. /// </summary>
  72. public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
  73. /// <summary>
  74. /// Occurs when [playback progress].
  75. /// </summary>
  76. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  77. /// <summary>
  78. /// Occurs when [playback stopped].
  79. /// </summary>
  80. public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
  81. public event EventHandler<SessionEventArgs> SessionStarted;
  82. public event EventHandler<SessionEventArgs> CapabilitiesChanged;
  83. public event EventHandler<SessionEventArgs> SessionEnded;
  84. public event EventHandler<SessionEventArgs> SessionActivity;
  85. private IEnumerable<ISessionControllerFactory> _sessionFactories = new List<ISessionControllerFactory>();
  86. private readonly SemaphoreSlim _sessionLock = new SemaphoreSlim(1, 1);
  87. /// <summary>
  88. /// Initializes a new instance of the <see cref="SessionManager" /> class.
  89. /// </summary>
  90. /// <param name="userDataRepository">The user data repository.</param>
  91. /// <param name="configurationManager">The configuration manager.</param>
  92. /// <param name="logger">The logger.</param>
  93. /// <param name="userRepository">The user repository.</param>
  94. /// <param name="libraryManager">The library manager.</param>
  95. public SessionManager(IUserDataManager userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository, ILibraryManager libraryManager, IUserManager userManager, IMusicManager musicManager, IDtoService dtoService, IImageProcessor imageProcessor, IItemRepository itemRepo, IJsonSerializer jsonSerializer, IServerApplicationHost appHost, IHttpClient httpClient, IAuthenticationRepository authRepo)
  96. {
  97. _userDataRepository = userDataRepository;
  98. _configurationManager = configurationManager;
  99. _logger = logger;
  100. _userRepository = userRepository;
  101. _libraryManager = libraryManager;
  102. _userManager = userManager;
  103. _musicManager = musicManager;
  104. _dtoService = dtoService;
  105. _imageProcessor = imageProcessor;
  106. _itemRepo = itemRepo;
  107. _jsonSerializer = jsonSerializer;
  108. _appHost = appHost;
  109. _httpClient = httpClient;
  110. _authRepo = authRepo;
  111. }
  112. /// <summary>
  113. /// Adds the parts.
  114. /// </summary>
  115. /// <param name="sessionFactories">The session factories.</param>
  116. public void AddParts(IEnumerable<ISessionControllerFactory> sessionFactories)
  117. {
  118. _sessionFactories = sessionFactories.ToList();
  119. }
  120. /// <summary>
  121. /// Gets all connections.
  122. /// </summary>
  123. /// <value>All connections.</value>
  124. public IEnumerable<SessionInfo> Sessions
  125. {
  126. get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList(); }
  127. }
  128. private void OnSessionStarted(SessionInfo info)
  129. {
  130. EventHelper.QueueEventIfNotNull(SessionStarted, this, new SessionEventArgs
  131. {
  132. SessionInfo = info
  133. }, _logger);
  134. if (!string.IsNullOrWhiteSpace(info.DeviceId))
  135. {
  136. var capabilities = GetSavedCapabilities(info.DeviceId);
  137. if (capabilities != null)
  138. {
  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="clientType">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 clientType,
  184. string appVersion,
  185. string deviceId,
  186. string deviceName,
  187. string remoteEndPoint,
  188. User user)
  189. {
  190. if (string.IsNullOrEmpty(clientType))
  191. {
  192. throw new ArgumentNullException("clientType");
  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. if (user != null && user.Configuration.IsDisabled)
  207. {
  208. throw new UnauthorizedAccessException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
  209. }
  210. var activityDate = DateTime.UtcNow;
  211. var userId = user == null ? (Guid?)null : user.Id;
  212. var username = user == null ? null : user.Name;
  213. var session = await GetSessionInfo(clientType, appVersion, deviceId, deviceName, remoteEndPoint, userId, username).ConfigureAwait(false);
  214. session.LastActivityDate = activityDate;
  215. if (user == null)
  216. {
  217. return session;
  218. }
  219. var lastActivityDate = user.LastActivityDate;
  220. user.LastActivityDate = activityDate;
  221. // Don't log in the db anymore frequently than 10 seconds
  222. if (lastActivityDate.HasValue && (activityDate - lastActivityDate.Value).TotalSeconds < 10)
  223. {
  224. return session;
  225. }
  226. // Save this directly. No need to fire off all the events for this.
  227. await _userRepository.SaveUser(user, CancellationToken.None).ConfigureAwait(false);
  228. EventHelper.FireEventIfNotNull(SessionActivity, this, new SessionEventArgs
  229. {
  230. SessionInfo = session
  231. }, _logger);
  232. return session;
  233. }
  234. public async void ReportSessionEnded(string sessionId)
  235. {
  236. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  237. try
  238. {
  239. var session = GetSession(sessionId, false);
  240. if (session != null)
  241. {
  242. var key = GetSessionKey(session.Client, session.ApplicationVersion, session.DeviceId);
  243. SessionInfo removed;
  244. if (_activeConnections.TryRemove(key, out removed))
  245. {
  246. OnSessionEnded(removed);
  247. }
  248. }
  249. }
  250. finally
  251. {
  252. _sessionLock.Release();
  253. }
  254. }
  255. /// <summary>
  256. /// Updates the now playing item id.
  257. /// </summary>
  258. /// <param name="session">The session.</param>
  259. /// <param name="info">The information.</param>
  260. /// <param name="libraryItem">The library item.</param>
  261. private void UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem)
  262. {
  263. var runtimeTicks = libraryItem == null ? null : libraryItem.RunTimeTicks;
  264. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  265. {
  266. info.MediaSourceId = info.ItemId;
  267. }
  268. if (!string.Equals(info.ItemId, info.MediaSourceId) &&
  269. !string.IsNullOrWhiteSpace(info.MediaSourceId))
  270. {
  271. runtimeTicks = _libraryManager.GetItemById(new Guid(info.MediaSourceId)).RunTimeTicks;
  272. }
  273. if (!string.IsNullOrWhiteSpace(info.ItemId) && libraryItem != null)
  274. {
  275. var current = session.NowPlayingItem;
  276. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  277. {
  278. info.Item = GetItemInfo(libraryItem, libraryItem, info.MediaSourceId);
  279. }
  280. else
  281. {
  282. info.Item = current;
  283. }
  284. info.Item.RunTimeTicks = runtimeTicks;
  285. }
  286. session.NowPlayingItem = info.Item;
  287. session.LastActivityDate = DateTime.UtcNow;
  288. session.PlayState.IsPaused = info.IsPaused;
  289. session.PlayState.PositionTicks = info.PositionTicks;
  290. session.PlayState.MediaSourceId = info.MediaSourceId;
  291. session.PlayState.CanSeek = info.CanSeek;
  292. session.PlayState.IsMuted = info.IsMuted;
  293. session.PlayState.VolumeLevel = info.VolumeLevel;
  294. session.PlayState.AudioStreamIndex = info.AudioStreamIndex;
  295. session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex;
  296. session.PlayState.PlayMethod = info.PlayMethod;
  297. }
  298. /// <summary>
  299. /// Removes the now playing item id.
  300. /// </summary>
  301. /// <param name="session">The session.</param>
  302. /// <exception cref="System.ArgumentNullException">item</exception>
  303. private void RemoveNowPlayingItem(SessionInfo session)
  304. {
  305. session.NowPlayingItem = null;
  306. session.PlayState = new PlayerStateInfo();
  307. if (!string.IsNullOrEmpty(session.DeviceId))
  308. {
  309. ClearTranscodingInfo(session.DeviceId);
  310. }
  311. }
  312. private string GetSessionKey(string clientType, string appVersion, string deviceId)
  313. {
  314. return clientType + deviceId;
  315. }
  316. /// <summary>
  317. /// Gets the connection.
  318. /// </summary>
  319. /// <param name="clientType">Type of the client.</param>
  320. /// <param name="appVersion">The app version.</param>
  321. /// <param name="deviceId">The device id.</param>
  322. /// <param name="deviceName">Name of the device.</param>
  323. /// <param name="remoteEndPoint">The remote end point.</param>
  324. /// <param name="userId">The user identifier.</param>
  325. /// <param name="username">The username.</param>
  326. /// <returns>SessionInfo.</returns>
  327. private async Task<SessionInfo> GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username)
  328. {
  329. var key = GetSessionKey(clientType, appVersion, deviceId);
  330. await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  331. try
  332. {
  333. var connection = _activeConnections.GetOrAdd(key, keyName =>
  334. {
  335. var sessionInfo = new SessionInfo
  336. {
  337. Client = clientType,
  338. DeviceId = deviceId,
  339. ApplicationVersion = appVersion,
  340. Id = Guid.NewGuid().ToString("N")
  341. };
  342. OnSessionStarted(sessionInfo);
  343. return sessionInfo;
  344. });
  345. connection.DeviceName = deviceName;
  346. connection.UserId = userId;
  347. connection.UserName = username;
  348. connection.RemoteEndPoint = remoteEndPoint;
  349. if (!userId.HasValue)
  350. {
  351. connection.AdditionalUsers.Clear();
  352. }
  353. if (connection.SessionController == null)
  354. {
  355. connection.SessionController = _sessionFactories
  356. .Select(i => i.GetSessionController(connection))
  357. .FirstOrDefault(i => i != null);
  358. }
  359. return connection;
  360. }
  361. finally
  362. {
  363. _sessionLock.Release();
  364. }
  365. }
  366. private List<User> GetUsers(SessionInfo session)
  367. {
  368. var users = new List<User>();
  369. if (session.UserId.HasValue)
  370. {
  371. var user = _userManager.GetUserById(session.UserId.Value);
  372. if (user == null)
  373. {
  374. throw new InvalidOperationException("User not found");
  375. }
  376. users.Add(user);
  377. var additionalUsers = session.AdditionalUsers
  378. .Select(i => _userManager.GetUserById(new Guid(i.UserId)))
  379. .Where(i => i != null);
  380. users.AddRange(additionalUsers);
  381. }
  382. return users;
  383. }
  384. /// <summary>
  385. /// Used to report that playback has started for an item
  386. /// </summary>
  387. /// <param name="info">The info.</param>
  388. /// <returns>Task.</returns>
  389. /// <exception cref="System.ArgumentNullException">info</exception>
  390. public async Task OnPlaybackStart(PlaybackStartInfo info)
  391. {
  392. if (info == null)
  393. {
  394. throw new ArgumentNullException("info");
  395. }
  396. var session = GetSession(info.SessionId);
  397. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  398. ? null
  399. : _libraryManager.GetItemById(new Guid(info.ItemId));
  400. UpdateNowPlayingItem(session, info, libraryItem);
  401. if (!string.IsNullOrEmpty(session.DeviceId) && info.PlayMethod != PlayMethod.Transcode)
  402. {
  403. ClearTranscodingInfo(session.DeviceId);
  404. }
  405. session.QueueableMediaTypes = info.QueueableMediaTypes;
  406. var users = GetUsers(session);
  407. if (libraryItem != null)
  408. {
  409. var key = libraryItem.GetUserDataKey();
  410. foreach (var user in users)
  411. {
  412. await OnPlaybackStart(user.Id, key, libraryItem).ConfigureAwait(false);
  413. }
  414. }
  415. // Nothing to save here
  416. // Fire events to inform plugins
  417. EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
  418. {
  419. Item = libraryItem,
  420. Users = users,
  421. MediaSourceId = info.MediaSourceId,
  422. MediaInfo = info.Item,
  423. DeviceName = session.DeviceName,
  424. ClientName = session.Client,
  425. DeviceId = session.DeviceId
  426. }, _logger);
  427. await SendPlaybackStartNotification(session, CancellationToken.None).ConfigureAwait(false);
  428. }
  429. /// <summary>
  430. /// Called when [playback start].
  431. /// </summary>
  432. /// <param name="userId">The user identifier.</param>
  433. /// <param name="userDataKey">The user data key.</param>
  434. /// <param name="item">The item.</param>
  435. /// <returns>Task.</returns>
  436. private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item)
  437. {
  438. var data = _userDataRepository.GetUserData(userId, userDataKey);
  439. data.PlayCount++;
  440. data.LastPlayedDate = DateTime.UtcNow;
  441. if (!(item is Video))
  442. {
  443. data.Played = true;
  444. }
  445. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None).ConfigureAwait(false);
  446. }
  447. /// <summary>
  448. /// Used to report playback progress for an item
  449. /// </summary>
  450. /// <param name="info">The info.</param>
  451. /// <returns>Task.</returns>
  452. /// <exception cref="System.ArgumentNullException"></exception>
  453. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  454. public async Task OnPlaybackProgress(PlaybackProgressInfo info)
  455. {
  456. if (info == null)
  457. {
  458. throw new ArgumentNullException("info");
  459. }
  460. var session = GetSession(info.SessionId);
  461. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  462. ? null
  463. : _libraryManager.GetItemById(new Guid(info.ItemId));
  464. UpdateNowPlayingItem(session, info, libraryItem);
  465. var users = GetUsers(session);
  466. if (libraryItem != null)
  467. {
  468. var key = libraryItem.GetUserDataKey();
  469. foreach (var user in users)
  470. {
  471. await OnPlaybackProgress(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  472. }
  473. }
  474. EventHelper.FireEventIfNotNull(PlaybackProgress, this, new PlaybackProgressEventArgs
  475. {
  476. Item = libraryItem,
  477. Users = users,
  478. PlaybackPositionTicks = session.PlayState.PositionTicks,
  479. MediaSourceId = session.PlayState.MediaSourceId,
  480. MediaInfo = info.Item,
  481. DeviceName = session.DeviceName,
  482. ClientName = session.Client,
  483. DeviceId = session.DeviceId
  484. }, _logger);
  485. }
  486. private async Task OnPlaybackProgress(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  487. {
  488. var data = _userDataRepository.GetUserData(userId, userDataKey);
  489. if (positionTicks.HasValue)
  490. {
  491. UpdatePlayState(item, data, positionTicks.Value);
  492. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None).ConfigureAwait(false);
  493. }
  494. }
  495. /// <summary>
  496. /// Used to report that playback has ended for an item
  497. /// </summary>
  498. /// <param name="info">The info.</param>
  499. /// <returns>Task.</returns>
  500. /// <exception cref="System.ArgumentNullException">info</exception>
  501. /// <exception cref="System.ArgumentOutOfRangeException">positionTicks</exception>
  502. public async Task OnPlaybackStopped(PlaybackStopInfo info)
  503. {
  504. if (info == null)
  505. {
  506. throw new ArgumentNullException("info");
  507. }
  508. if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
  509. {
  510. throw new ArgumentOutOfRangeException("positionTicks");
  511. }
  512. var session = GetSession(info.SessionId);
  513. var libraryItem = string.IsNullOrWhiteSpace(info.ItemId)
  514. ? null
  515. : _libraryManager.GetItemById(new Guid(info.ItemId));
  516. // Normalize
  517. if (string.IsNullOrWhiteSpace(info.MediaSourceId))
  518. {
  519. info.MediaSourceId = info.ItemId;
  520. }
  521. if (!string.IsNullOrWhiteSpace(info.ItemId) && libraryItem != null)
  522. {
  523. var current = session.NowPlayingItem;
  524. if (current == null || !string.Equals(current.Id, info.ItemId, StringComparison.OrdinalIgnoreCase))
  525. {
  526. info.Item = GetItemInfo(libraryItem, libraryItem, info.MediaSourceId);
  527. }
  528. else
  529. {
  530. info.Item = current;
  531. }
  532. }
  533. RemoveNowPlayingItem(session);
  534. var users = GetUsers(session);
  535. var playedToCompletion = false;
  536. if (libraryItem != null)
  537. {
  538. var key = libraryItem.GetUserDataKey();
  539. foreach (var user in users)
  540. {
  541. playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks).ConfigureAwait(false);
  542. }
  543. }
  544. EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
  545. {
  546. Item = libraryItem,
  547. Users = users,
  548. PlaybackPositionTicks = info.PositionTicks,
  549. PlayedToCompletion = playedToCompletion,
  550. MediaSourceId = info.MediaSourceId,
  551. MediaInfo = info.Item,
  552. DeviceName = session.DeviceName,
  553. ClientName = session.Client,
  554. DeviceId = session.DeviceId
  555. }, _logger);
  556. await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false);
  557. }
  558. private async Task<bool> OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks)
  559. {
  560. var data = _userDataRepository.GetUserData(userId, userDataKey);
  561. bool playedToCompletion;
  562. if (positionTicks.HasValue)
  563. {
  564. playedToCompletion = UpdatePlayState(item, data, positionTicks.Value);
  565. }
  566. else
  567. {
  568. // If the client isn't able to report this, then we'll just have to make an assumption
  569. data.PlayCount++;
  570. data.Played = true;
  571. data.PlaybackPositionTicks = 0;
  572. playedToCompletion = true;
  573. }
  574. await _userDataRepository.SaveUserData(userId, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None).ConfigureAwait(false);
  575. return playedToCompletion;
  576. }
  577. /// <summary>
  578. /// Updates playstate position for an item but does not save
  579. /// </summary>
  580. /// <param name="item">The item</param>
  581. /// <param name="data">User data for the item</param>
  582. /// <param name="positionTicks">The current playback position</param>
  583. private bool UpdatePlayState(BaseItem item, UserItemData data, long positionTicks)
  584. {
  585. var playedToCompletion = false;
  586. var hasRuntime = item.RunTimeTicks.HasValue && item.RunTimeTicks > 0;
  587. // If a position has been reported, and if we know the duration
  588. if (positionTicks > 0 && hasRuntime)
  589. {
  590. var pctIn = Decimal.Divide(positionTicks, item.RunTimeTicks.Value) * 100;
  591. // Don't track in very beginning
  592. if (pctIn < _configurationManager.Configuration.MinResumePct)
  593. {
  594. positionTicks = 0;
  595. }
  596. // If we're at the end, assume completed
  597. else if (pctIn > _configurationManager.Configuration.MaxResumePct || positionTicks >= item.RunTimeTicks.Value)
  598. {
  599. positionTicks = 0;
  600. data.Played = playedToCompletion = true;
  601. }
  602. else
  603. {
  604. // Enforce MinResumeDuration
  605. var durationSeconds = TimeSpan.FromTicks(item.RunTimeTicks.Value).TotalSeconds;
  606. if (durationSeconds < _configurationManager.Configuration.MinResumeDurationSeconds)
  607. {
  608. positionTicks = 0;
  609. data.Played = playedToCompletion = true;
  610. }
  611. }
  612. }
  613. else if (!hasRuntime)
  614. {
  615. // If we don't know the runtime we'll just have to assume it was fully played
  616. data.Played = playedToCompletion = true;
  617. positionTicks = 0;
  618. }
  619. if (item is Audio)
  620. {
  621. positionTicks = 0;
  622. }
  623. data.PlaybackPositionTicks = positionTicks;
  624. return playedToCompletion;
  625. }
  626. /// <summary>
  627. /// Gets the session.
  628. /// </summary>
  629. /// <param name="sessionId">The session identifier.</param>
  630. /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
  631. /// <returns>SessionInfo.</returns>
  632. /// <exception cref="ResourceNotFoundException"></exception>
  633. private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
  634. {
  635. var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
  636. if (session == null && throwOnMissing)
  637. {
  638. throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
  639. }
  640. return session;
  641. }
  642. public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
  643. {
  644. var generalCommand = new GeneralCommand
  645. {
  646. Name = GeneralCommandType.DisplayMessage.ToString()
  647. };
  648. generalCommand.Arguments["Header"] = command.Header;
  649. generalCommand.Arguments["Text"] = command.Text;
  650. if (command.TimeoutMs.HasValue)
  651. {
  652. generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
  653. }
  654. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  655. }
  656. public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
  657. {
  658. var session = GetSession(sessionId);
  659. var controllingSession = GetSession(controllingSessionId);
  660. AssertCanControl(session, controllingSession);
  661. return session.SessionController.SendGeneralCommand(command, cancellationToken);
  662. }
  663. public Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
  664. {
  665. var session = GetSession(sessionId);
  666. var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null;
  667. List<BaseItem> items;
  668. if (command.PlayCommand == PlayCommand.PlayInstantMix)
  669. {
  670. items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
  671. .Where(i => i.LocationType != LocationType.Virtual)
  672. .ToList();
  673. command.PlayCommand = PlayCommand.PlayNow;
  674. }
  675. else
  676. {
  677. items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user))
  678. .Where(i => i.LocationType != LocationType.Virtual)
  679. .ToList();
  680. }
  681. if (command.PlayCommand == PlayCommand.PlayShuffle)
  682. {
  683. items = items.OrderBy(i => Guid.NewGuid()).ToList();
  684. command.PlayCommand = PlayCommand.PlayNow;
  685. }
  686. command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray();
  687. if (user != null)
  688. {
  689. if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
  690. {
  691. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  692. }
  693. }
  694. if (command.PlayCommand != PlayCommand.PlayNow)
  695. {
  696. if (items.Any(i => !session.QueueableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  697. {
  698. throw new ArgumentException(string.Format("{0} is unable to queue the requested media type.", session.DeviceName ?? session.Id.ToString()));
  699. }
  700. }
  701. else
  702. {
  703. if (items.Any(i => !session.PlayableMediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
  704. {
  705. throw new ArgumentException(string.Format("{0} is unable to play the requested media type.", session.DeviceName ?? session.Id.ToString()));
  706. }
  707. }
  708. var controllingSession = GetSession(controllingSessionId);
  709. AssertCanControl(session, controllingSession);
  710. if (controllingSession.UserId.HasValue)
  711. {
  712. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  713. }
  714. return session.SessionController.SendPlayCommand(command, cancellationToken);
  715. }
  716. private IEnumerable<BaseItem> TranslateItemForPlayback(string id, User user)
  717. {
  718. var item = _libraryManager.GetItemById(new Guid(id));
  719. if (item.IsFolder)
  720. {
  721. var folder = (Folder)item;
  722. var items = user == null ? folder.RecursiveChildren :
  723. folder.GetRecursiveChildren(user);
  724. items = items.Where(i => !i.IsFolder);
  725. items = items.OrderBy(i => i.SortName);
  726. return items;
  727. }
  728. return new[] { item };
  729. }
  730. private IEnumerable<BaseItem> TranslateItemForInstantMix(string id, User user)
  731. {
  732. var item = _libraryManager.GetItemById(new Guid(id));
  733. var audio = item as Audio;
  734. if (audio != null)
  735. {
  736. return _musicManager.GetInstantMixFromSong(audio, user);
  737. }
  738. var artist = item as MusicArtist;
  739. if (artist != null)
  740. {
  741. return _musicManager.GetInstantMixFromArtist(artist.Name, user);
  742. }
  743. var album = item as MusicAlbum;
  744. if (album != null)
  745. {
  746. return _musicManager.GetInstantMixFromAlbum(album, user);
  747. }
  748. var genre = item as MusicGenre;
  749. if (genre != null)
  750. {
  751. return _musicManager.GetInstantMixFromGenres(new[] { genre.Name }, user);
  752. }
  753. return new BaseItem[] { };
  754. }
  755. public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
  756. {
  757. var generalCommand = new GeneralCommand
  758. {
  759. Name = GeneralCommandType.DisplayContent.ToString()
  760. };
  761. generalCommand.Arguments["ItemId"] = command.ItemId;
  762. generalCommand.Arguments["ItemName"] = command.ItemName;
  763. generalCommand.Arguments["ItemType"] = command.ItemType;
  764. return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
  765. }
  766. public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
  767. {
  768. var session = GetSession(sessionId);
  769. var controllingSession = GetSession(controllingSessionId);
  770. AssertCanControl(session, controllingSession);
  771. if (controllingSession.UserId.HasValue)
  772. {
  773. command.ControllingUserId = controllingSession.UserId.Value.ToString("N");
  774. }
  775. return session.SessionController.SendPlaystateCommand(command, cancellationToken);
  776. }
  777. private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
  778. {
  779. if (session == null)
  780. {
  781. throw new ArgumentNullException("session");
  782. }
  783. if (controllingSession == null)
  784. {
  785. throw new ArgumentNullException("controllingSession");
  786. }
  787. }
  788. /// <summary>
  789. /// Sends the restart required message.
  790. /// </summary>
  791. /// <param name="cancellationToken">The cancellation token.</param>
  792. /// <returns>Task.</returns>
  793. public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
  794. {
  795. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  796. var info = _appHost.GetSystemInfo();
  797. var tasks = sessions.Select(session => Task.Run(async () =>
  798. {
  799. try
  800. {
  801. await session.SessionController.SendRestartRequiredNotification(info, cancellationToken).ConfigureAwait(false);
  802. }
  803. catch (Exception ex)
  804. {
  805. _logger.ErrorException("Error in SendRestartRequiredNotification.", ex);
  806. }
  807. }, cancellationToken));
  808. return Task.WhenAll(tasks);
  809. }
  810. /// <summary>
  811. /// Sends the server shutdown notification.
  812. /// </summary>
  813. /// <param name="cancellationToken">The cancellation token.</param>
  814. /// <returns>Task.</returns>
  815. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  816. {
  817. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  818. var tasks = sessions.Select(session => Task.Run(async () =>
  819. {
  820. try
  821. {
  822. await session.SessionController.SendServerShutdownNotification(cancellationToken).ConfigureAwait(false);
  823. }
  824. catch (Exception ex)
  825. {
  826. _logger.ErrorException("Error in SendServerShutdownNotification.", ex);
  827. }
  828. }, cancellationToken));
  829. return Task.WhenAll(tasks);
  830. }
  831. /// <summary>
  832. /// Sends the server restart notification.
  833. /// </summary>
  834. /// <param name="cancellationToken">The cancellation token.</param>
  835. /// <returns>Task.</returns>
  836. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  837. {
  838. _logger.Debug("Beginning SendServerRestartNotification");
  839. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  840. var tasks = sessions.Select(session => Task.Run(async () =>
  841. {
  842. try
  843. {
  844. await session.SessionController.SendServerRestartNotification(cancellationToken).ConfigureAwait(false);
  845. }
  846. catch (Exception ex)
  847. {
  848. _logger.ErrorException("Error in SendServerRestartNotification.", ex);
  849. }
  850. }, cancellationToken));
  851. return Task.WhenAll(tasks);
  852. }
  853. public Task SendSessionEndedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  854. {
  855. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  856. var dto = GetSessionInfoDto(sessionInfo);
  857. var tasks = sessions.Select(session => Task.Run(async () =>
  858. {
  859. try
  860. {
  861. await session.SessionController.SendSessionEndedNotification(dto, cancellationToken).ConfigureAwait(false);
  862. }
  863. catch (Exception ex)
  864. {
  865. _logger.ErrorException("Error in SendSessionEndedNotification.", ex);
  866. }
  867. }, cancellationToken));
  868. return Task.WhenAll(tasks);
  869. }
  870. public Task SendPlaybackStartNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  871. {
  872. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  873. var dto = GetSessionInfoDto(sessionInfo);
  874. var tasks = sessions.Select(session => Task.Run(async () =>
  875. {
  876. try
  877. {
  878. await session.SessionController.SendPlaybackStartNotification(dto, cancellationToken).ConfigureAwait(false);
  879. }
  880. catch (Exception ex)
  881. {
  882. _logger.ErrorException("Error in SendPlaybackStartNotification.", ex);
  883. }
  884. }, cancellationToken));
  885. return Task.WhenAll(tasks);
  886. }
  887. public Task SendPlaybackStoppedNotification(SessionInfo sessionInfo, CancellationToken cancellationToken)
  888. {
  889. var sessions = Sessions.Where(i => i.IsActive && i.SessionController != null).ToList();
  890. var dto = GetSessionInfoDto(sessionInfo);
  891. var tasks = sessions.Select(session => Task.Run(async () =>
  892. {
  893. try
  894. {
  895. await session.SessionController.SendPlaybackStoppedNotification(dto, cancellationToken).ConfigureAwait(false);
  896. }
  897. catch (Exception ex)
  898. {
  899. _logger.ErrorException("Error in SendPlaybackStoppedNotification.", ex);
  900. }
  901. }, cancellationToken));
  902. return Task.WhenAll(tasks);
  903. }
  904. /// <summary>
  905. /// Adds the additional user.
  906. /// </summary>
  907. /// <param name="sessionId">The session identifier.</param>
  908. /// <param name="userId">The user identifier.</param>
  909. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  910. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  911. public void AddAdditionalUser(string sessionId, Guid userId)
  912. {
  913. var session = GetSession(sessionId);
  914. if (!session.UserId.HasValue)
  915. {
  916. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  917. }
  918. if (session.UserId.Value == userId)
  919. {
  920. throw new ArgumentException("The requested user is already the primary user of the session.");
  921. }
  922. if (session.AdditionalUsers.All(i => new Guid(i.UserId) != userId))
  923. {
  924. var user = _userManager.GetUserById(userId);
  925. session.AdditionalUsers.Add(new SessionUserInfo
  926. {
  927. UserId = userId.ToString("N"),
  928. UserName = user.Name
  929. });
  930. }
  931. }
  932. /// <summary>
  933. /// Removes the additional user.
  934. /// </summary>
  935. /// <param name="sessionId">The session identifier.</param>
  936. /// <param name="userId">The user identifier.</param>
  937. /// <exception cref="System.UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
  938. /// <exception cref="System.ArgumentException">The requested user is already the primary user of the session.</exception>
  939. public void RemoveAdditionalUser(string sessionId, Guid userId)
  940. {
  941. var session = GetSession(sessionId);
  942. if (!session.UserId.HasValue)
  943. {
  944. throw new UnauthorizedAccessException("Cannot modify additional users without authenticating first.");
  945. }
  946. if (session.UserId.Value == userId)
  947. {
  948. throw new ArgumentException("The requested user is already the primary user of the session.");
  949. }
  950. var user = session.AdditionalUsers.FirstOrDefault(i => new Guid(i.UserId) == userId);
  951. if (user != null)
  952. {
  953. session.AdditionalUsers.Remove(user);
  954. }
  955. }
  956. public void ValidateSecurityToken(string token)
  957. {
  958. if (string.IsNullOrWhiteSpace(token))
  959. {
  960. throw new UnauthorizedAccessException();
  961. }
  962. var result = _authRepo.Get(new AuthenticationInfoQuery
  963. {
  964. AccessToken = token
  965. });
  966. var info = result.Items.FirstOrDefault();
  967. if (info == null)
  968. {
  969. throw new UnauthorizedAccessException();
  970. }
  971. if (!info.IsActive)
  972. {
  973. throw new UnauthorizedAccessException("Access token has expired.");
  974. }
  975. if (!string.IsNullOrWhiteSpace(info.UserId))
  976. {
  977. var user = _userManager.GetUserById(new Guid(info.UserId));
  978. if (user == null || user.Configuration.IsDisabled)
  979. {
  980. throw new UnauthorizedAccessException("User account has been disabled.");
  981. }
  982. }
  983. }
  984. /// <summary>
  985. /// Authenticates the new session.
  986. /// </summary>
  987. /// <param name="username">The username.</param>
  988. /// <param name="password">The password.</param>
  989. /// <param name="clientType">Type of the client.</param>
  990. /// <param name="appVersion">The application version.</param>
  991. /// <param name="deviceId">The device identifier.</param>
  992. /// <param name="deviceName">Name of the device.</param>
  993. /// <param name="remoteEndPoint">The remote end point.</param>
  994. /// <param name="isLocal">if set to <c>true</c> [is local].</param>
  995. /// <returns>Task{SessionInfo}.</returns>
  996. /// <exception cref="System.UnauthorizedAccessException">Invalid user or password entered.</exception>
  997. /// <exception cref="UnauthorizedAccessException">Invalid user or password entered.</exception>
  998. public async Task<AuthenticationResult> AuthenticateNewSession(string username,
  999. string password,
  1000. string clientType,
  1001. string appVersion,
  1002. string deviceId,
  1003. string deviceName,
  1004. string remoteEndPoint,
  1005. bool isLocal)
  1006. {
  1007. var result = (isLocal && string.Equals(clientType, "Dashboard", StringComparison.OrdinalIgnoreCase)) ||
  1008. await _userManager.AuthenticateUser(username, password).ConfigureAwait(false);
  1009. if (!result)
  1010. {
  1011. throw new UnauthorizedAccessException("Invalid user or password entered.");
  1012. }
  1013. var user = _userManager.Users
  1014. .First(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
  1015. var token = await GetAuthorizationToken(user.Id.ToString("N"), deviceId, clientType, deviceName).ConfigureAwait(false);
  1016. var session = await LogSessionActivity(clientType,
  1017. appVersion,
  1018. deviceId,
  1019. deviceName,
  1020. remoteEndPoint,
  1021. user)
  1022. .ConfigureAwait(false);
  1023. return new AuthenticationResult
  1024. {
  1025. User = _dtoService.GetUserDto(user),
  1026. SessionInfo = GetSessionInfoDto(session),
  1027. AccessToken = token
  1028. };
  1029. }
  1030. private async Task<string> GetAuthorizationToken(string userId, string deviceId, string app, string deviceName)
  1031. {
  1032. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1033. {
  1034. DeviceId = deviceId,
  1035. IsActive = true,
  1036. UserId = userId,
  1037. Limit = 1
  1038. });
  1039. if (existing.Items.Length > 0)
  1040. {
  1041. _logger.Debug("Reissuing access token");
  1042. return existing.Items[0].AccessToken;
  1043. }
  1044. var newToken = new AuthenticationInfo
  1045. {
  1046. AppName = app,
  1047. DateCreated = DateTime.UtcNow,
  1048. DeviceId = deviceId,
  1049. DeviceName = deviceName,
  1050. UserId = userId,
  1051. IsActive = true,
  1052. AccessToken = Guid.NewGuid().ToString("N")
  1053. };
  1054. _logger.Debug("Creating new access token for user {0}", userId);
  1055. await _authRepo.Create(newToken, CancellationToken.None).ConfigureAwait(false);
  1056. return newToken.AccessToken;
  1057. }
  1058. public async Task Logout(string accessToken)
  1059. {
  1060. if (string.IsNullOrWhiteSpace(accessToken))
  1061. {
  1062. throw new ArgumentNullException("accessToken");
  1063. }
  1064. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1065. {
  1066. Limit = 1,
  1067. AccessToken = accessToken
  1068. }).Items.FirstOrDefault();
  1069. if (existing != null)
  1070. {
  1071. existing.IsActive = false;
  1072. await _authRepo.Update(existing, CancellationToken.None).ConfigureAwait(false);
  1073. var sessions = Sessions
  1074. .Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
  1075. .ToList();
  1076. foreach (var session in sessions)
  1077. {
  1078. try
  1079. {
  1080. ReportSessionEnded(session.Id);
  1081. }
  1082. catch (Exception ex)
  1083. {
  1084. _logger.ErrorException("Error reporting session ended", ex);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. public async Task RevokeUserTokens(string userId)
  1090. {
  1091. var existing = _authRepo.Get(new AuthenticationInfoQuery
  1092. {
  1093. IsActive = true,
  1094. UserId = userId
  1095. });
  1096. foreach (var info in existing.Items)
  1097. {
  1098. await Logout(info.AccessToken).ConfigureAwait(false);
  1099. }
  1100. }
  1101. public Task RevokeToken(string token)
  1102. {
  1103. return Logout(token);
  1104. }
  1105. /// <summary>
  1106. /// Reports the capabilities.
  1107. /// </summary>
  1108. /// <param name="sessionId">The session identifier.</param>
  1109. /// <param name="capabilities">The capabilities.</param>
  1110. public void ReportCapabilities(string sessionId, SessionCapabilities capabilities)
  1111. {
  1112. var session = GetSession(sessionId);
  1113. ReportCapabilities(session, capabilities, true);
  1114. }
  1115. private async void ReportCapabilities(SessionInfo session,
  1116. SessionCapabilities capabilities,
  1117. bool saveCapabilities)
  1118. {
  1119. session.PlayableMediaTypes = capabilities.PlayableMediaTypes;
  1120. session.SupportedCommands = capabilities.SupportedCommands;
  1121. if (!string.IsNullOrWhiteSpace(capabilities.MessageCallbackUrl))
  1122. {
  1123. var controller = session.SessionController as HttpSessionController;
  1124. if (controller == null)
  1125. {
  1126. session.SessionController = new HttpSessionController(_httpClient, _jsonSerializer, session, capabilities.MessageCallbackUrl, this);
  1127. }
  1128. }
  1129. EventHelper.FireEventIfNotNull(CapabilitiesChanged, this, new SessionEventArgs
  1130. {
  1131. SessionInfo = session
  1132. }, _logger);
  1133. if (saveCapabilities)
  1134. {
  1135. await SaveCapabilities(session.DeviceId, capabilities).ConfigureAwait(false);
  1136. }
  1137. }
  1138. private string GetCapabilitiesFilePath(string deviceId)
  1139. {
  1140. var filename = deviceId.GetMD5().ToString("N") + ".json";
  1141. return Path.Combine(_configurationManager.ApplicationPaths.CachePath, "devices", filename);
  1142. }
  1143. private SessionCapabilities GetSavedCapabilities(string deviceId)
  1144. {
  1145. var path = GetCapabilitiesFilePath(deviceId);
  1146. try
  1147. {
  1148. return _jsonSerializer.DeserializeFromFile<SessionCapabilities>(path);
  1149. }
  1150. catch (DirectoryNotFoundException)
  1151. {
  1152. return null;
  1153. }
  1154. catch (FileNotFoundException)
  1155. {
  1156. return null;
  1157. }
  1158. catch (Exception ex)
  1159. {
  1160. _logger.ErrorException("Error getting saved capabilities", ex);
  1161. return null;
  1162. }
  1163. }
  1164. private readonly SemaphoreSlim _capabilitiesLock = new SemaphoreSlim(1, 1);
  1165. private async Task SaveCapabilities(string deviceId, SessionCapabilities capabilities)
  1166. {
  1167. var path = GetCapabilitiesFilePath(deviceId);
  1168. Directory.CreateDirectory(Path.GetDirectoryName(path));
  1169. await _capabilitiesLock.WaitAsync().ConfigureAwait(false);
  1170. try
  1171. {
  1172. _jsonSerializer.SerializeToFile(capabilities, path);
  1173. }
  1174. finally
  1175. {
  1176. _capabilitiesLock.Release();
  1177. }
  1178. }
  1179. public SessionInfoDto GetSessionInfoDto(SessionInfo session)
  1180. {
  1181. var dto = new SessionInfoDto
  1182. {
  1183. Client = session.Client,
  1184. DeviceId = session.DeviceId,
  1185. DeviceName = session.DeviceName,
  1186. Id = session.Id,
  1187. LastActivityDate = session.LastActivityDate,
  1188. NowViewingItem = session.NowViewingItem,
  1189. ApplicationVersion = session.ApplicationVersion,
  1190. QueueableMediaTypes = session.QueueableMediaTypes,
  1191. PlayableMediaTypes = session.PlayableMediaTypes,
  1192. AdditionalUsers = session.AdditionalUsers,
  1193. SupportedCommands = session.SupportedCommands,
  1194. UserName = session.UserName,
  1195. NowPlayingItem = session.NowPlayingItem,
  1196. SupportsRemoteControl = session.SupportsMediaControl,
  1197. PlayState = session.PlayState,
  1198. TranscodingInfo = session.NowPlayingItem == null ? null : session.TranscodingInfo
  1199. };
  1200. if (session.UserId.HasValue)
  1201. {
  1202. dto.UserId = session.UserId.Value.ToString("N");
  1203. var user = _userManager.GetUserById(session.UserId.Value);
  1204. if (user != null)
  1205. {
  1206. dto.UserPrimaryImageTag = GetImageCacheTag(user, ImageType.Primary);
  1207. }
  1208. }
  1209. return dto;
  1210. }
  1211. /// <summary>
  1212. /// Converts a BaseItem to a BaseItemInfo
  1213. /// </summary>
  1214. /// <param name="item">The item.</param>
  1215. /// <param name="chapterOwner">The chapter owner.</param>
  1216. /// <param name="mediaSourceId">The media source identifier.</param>
  1217. /// <returns>BaseItemInfo.</returns>
  1218. /// <exception cref="System.ArgumentNullException">item</exception>
  1219. private BaseItemInfo GetItemInfo(BaseItem item, BaseItem chapterOwner, string mediaSourceId)
  1220. {
  1221. if (item == null)
  1222. {
  1223. throw new ArgumentNullException("item");
  1224. }
  1225. var info = new BaseItemInfo
  1226. {
  1227. Id = GetDtoId(item),
  1228. Name = item.Name,
  1229. MediaType = item.MediaType,
  1230. Type = item.GetClientTypeName(),
  1231. RunTimeTicks = item.RunTimeTicks,
  1232. IndexNumber = item.IndexNumber,
  1233. ParentIndexNumber = item.ParentIndexNumber,
  1234. PremiereDate = item.PremiereDate,
  1235. ProductionYear = item.ProductionYear
  1236. };
  1237. info.PrimaryImageTag = GetImageCacheTag(item, ImageType.Primary);
  1238. if (info.PrimaryImageTag != null)
  1239. {
  1240. info.PrimaryImageItemId = GetDtoId(item);
  1241. }
  1242. var episode = item as Episode;
  1243. if (episode != null)
  1244. {
  1245. info.IndexNumberEnd = episode.IndexNumberEnd;
  1246. }
  1247. var hasSeries = item as IHasSeries;
  1248. if (hasSeries != null)
  1249. {
  1250. info.SeriesName = hasSeries.SeriesName;
  1251. }
  1252. var recording = item as ILiveTvRecording;
  1253. if (recording != null && recording.RecordingInfo != null)
  1254. {
  1255. if (recording.RecordingInfo.IsSeries)
  1256. {
  1257. info.Name = recording.RecordingInfo.EpisodeTitle;
  1258. info.SeriesName = recording.RecordingInfo.Name;
  1259. if (string.IsNullOrWhiteSpace(info.Name))
  1260. {
  1261. info.Name = recording.RecordingInfo.Name;
  1262. }
  1263. }
  1264. }
  1265. var audio = item as Audio;
  1266. if (audio != null)
  1267. {
  1268. info.Album = audio.Album;
  1269. info.Artists = audio.Artists;
  1270. if (info.PrimaryImageTag == null)
  1271. {
  1272. var album = audio.Parents.OfType<MusicAlbum>().FirstOrDefault();
  1273. if (album != null && album.HasImage(ImageType.Primary))
  1274. {
  1275. info.PrimaryImageTag = GetImageCacheTag(album, ImageType.Primary);
  1276. if (info.PrimaryImageTag != null)
  1277. {
  1278. info.PrimaryImageItemId = GetDtoId(album);
  1279. }
  1280. }
  1281. }
  1282. }
  1283. var musicVideo = item as MusicVideo;
  1284. if (musicVideo != null)
  1285. {
  1286. info.Album = musicVideo.Album;
  1287. if (!string.IsNullOrWhiteSpace(musicVideo.Artist))
  1288. {
  1289. info.Artists.Add(musicVideo.Artist);
  1290. }
  1291. }
  1292. var backropItem = item.HasImage(ImageType.Backdrop) ? item : null;
  1293. var thumbItem = item.HasImage(ImageType.Thumb) ? item : null;
  1294. var logoItem = item.HasImage(ImageType.Logo) ? item : null;
  1295. if (thumbItem == null)
  1296. {
  1297. if (episode != null)
  1298. {
  1299. var series = episode.Series;
  1300. if (series != null && series.HasImage(ImageType.Thumb))
  1301. {
  1302. thumbItem = series;
  1303. }
  1304. }
  1305. }
  1306. if (backropItem == null)
  1307. {
  1308. if (episode != null)
  1309. {
  1310. var series = episode.Series;
  1311. if (series != null && series.HasImage(ImageType.Backdrop))
  1312. {
  1313. backropItem = series;
  1314. }
  1315. }
  1316. }
  1317. if (backropItem == null)
  1318. {
  1319. backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop));
  1320. }
  1321. if (thumbItem == null)
  1322. {
  1323. thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb));
  1324. }
  1325. if (logoItem == null)
  1326. {
  1327. logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo));
  1328. }
  1329. if (thumbItem != null)
  1330. {
  1331. info.ThumbImageTag = GetImageCacheTag(thumbItem, ImageType.Thumb);
  1332. info.ThumbItemId = GetDtoId(thumbItem);
  1333. }
  1334. if (backropItem != null)
  1335. {
  1336. info.BackdropImageTag = GetImageCacheTag(backropItem, ImageType.Backdrop);
  1337. info.BackdropItemId = GetDtoId(backropItem);
  1338. }
  1339. if (logoItem != null)
  1340. {
  1341. info.LogoImageTag = GetImageCacheTag(logoItem, ImageType.Logo);
  1342. info.LogoItemId = GetDtoId(logoItem);
  1343. }
  1344. if (chapterOwner != null)
  1345. {
  1346. info.ChapterImagesItemId = chapterOwner.Id.ToString("N");
  1347. info.Chapters = _itemRepo.GetChapters(chapterOwner.Id).Select(i => _dtoService.GetChapterInfoDto(i, chapterOwner)).ToList();
  1348. }
  1349. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  1350. {
  1351. info.MediaStreams = _itemRepo.GetMediaStreams(new MediaStreamQuery
  1352. {
  1353. ItemId = new Guid(mediaSourceId)
  1354. }).ToList();
  1355. }
  1356. return info;
  1357. }
  1358. private string GetImageCacheTag(BaseItem item, ImageType type)
  1359. {
  1360. try
  1361. {
  1362. return _imageProcessor.GetImageCacheTag(item, type);
  1363. }
  1364. catch (Exception ex)
  1365. {
  1366. _logger.ErrorException("Error getting {0} image info", ex, type);
  1367. return null;
  1368. }
  1369. }
  1370. private string GetDtoId(BaseItem item)
  1371. {
  1372. return _dtoService.GetDtoId(item);
  1373. }
  1374. public void ReportNowViewingItem(string sessionId, string itemId)
  1375. {
  1376. var item = _libraryManager.GetItemById(new Guid(itemId));
  1377. var info = GetItemInfo(item, null, null);
  1378. ReportNowViewingItem(sessionId, info);
  1379. }
  1380. public void ReportNowViewingItem(string sessionId, BaseItemInfo item)
  1381. {
  1382. var session = GetSession(sessionId);
  1383. session.NowViewingItem = item;
  1384. }
  1385. public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
  1386. {
  1387. var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
  1388. if (session != null)
  1389. {
  1390. session.TranscodingInfo = info;
  1391. }
  1392. }
  1393. public void ClearTranscodingInfo(string deviceId)
  1394. {
  1395. ReportTranscodingInfo(deviceId, null);
  1396. }
  1397. public SessionInfo GetSession(string deviceId, string client, string version)
  1398. {
  1399. return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
  1400. string.Equals(i.Client, client));
  1401. }
  1402. }
  1403. }