SessionManager.cs 61 KB

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