SessionManager.cs 61 KB

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