You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.7 KiB

  1. using System;
  2. using System.Linq;
  3. using BirdsiteLive.Common.Settings;
  4. using BirdsiteLive.Statistics.Domain;
  5. using BirdsiteLive.Twitter.Models;
  6. using BirdsiteLive.Twitter.Tools;
  7. using Microsoft.Extensions.Logging;
  8. using Tweetinvi;
  9. using Tweetinvi.Models;
  10. namespace BirdsiteLive.Twitter
  11. {
  12. public interface ITwitterUserService
  13. {
  14. TwitterUser GetUser(string username);
  15. }
  16. public class TwitterUserService : ITwitterUserService
  17. {
  18. private readonly ITwitterAuthenticationInitializer _twitterAuthenticationInitializer;
  19. private readonly ITwitterStatisticsHandler _statisticsHandler;
  20. private readonly ILogger<TwitterUserService> _logger;
  21. #region Ctor
  22. public TwitterUserService(ITwitterAuthenticationInitializer twitterAuthenticationInitializer, ITwitterStatisticsHandler statisticsHandler, ILogger<TwitterUserService> logger)
  23. {
  24. _twitterAuthenticationInitializer = twitterAuthenticationInitializer;
  25. _statisticsHandler = statisticsHandler;
  26. _logger = logger;
  27. }
  28. #endregion
  29. public TwitterUser GetUser(string username)
  30. {
  31. _twitterAuthenticationInitializer.EnsureAuthenticationIsInitialized();
  32. ExceptionHandler.SwallowWebExceptions = false;
  33. IUser user;
  34. try
  35. {
  36. user = User.GetUserFromScreenName(username);
  37. _statisticsHandler.CalledUserApi();
  38. if (user == null)
  39. {
  40. _logger.LogWarning("User {username} not found", username);
  41. return null;
  42. }
  43. }
  44. catch (Exception e)
  45. {
  46. _logger.LogError(e, "Error retrieving user {Username}", username);
  47. // TODO keep track of error, see where to remove user if too much errors
  48. return null;
  49. }
  50. // Expand URLs
  51. var description = user.Description;
  52. foreach (var descriptionUrl in user.Entities?.Description?.Urls?.OrderByDescending(x => x.URL.Length))
  53. description = description.Replace(descriptionUrl.URL, descriptionUrl.ExpandedURL);
  54. return new TwitterUser
  55. {
  56. Id = user.Id,
  57. Acct = username,
  58. Name = user.Name,
  59. Description = description,
  60. Url = $"https://twitter.com/{username}",
  61. ProfileImageUrl = user.ProfileImageUrlFullSize.Replace("http://", "https://"),
  62. ProfileBackgroundImageUrl = user.ProfileBackgroundImageUrlHttps,
  63. ProfileBannerURL = user.ProfileBannerURL,
  64. Protected = user.Protected
  65. };
  66. }
  67. }
  68. }