From d66979dcd3bd4fcc2dd311d154612b372fbff603 Mon Sep 17 00:00:00 2001 From: Owain Date: Fri, 8 Jul 2022 17:05:42 +0100 Subject: [PATCH] IMP: Way to run the site without needing API keys With the API.Offline mode, you can now run the site without needing any API keys --- Controllers/LoadMoreTweetsController.cs | 26 +++++++++-- Core/Services/TwitterHelper.cs | 47 +++++++++---------- Settings/APISettings.cs | 7 +++ Settings/TwitterSettings.cs | 8 ++-- Startup.cs | 1 + ViewComponents/TweetsViewComponent.cs | 61 ++++++++++++++++++------- appsettings.json | 8 +++- 7 files changed, 108 insertions(+), 50 deletions(-) create mode 100644 Settings/APISettings.cs diff --git a/Controllers/LoadMoreTweetsController.cs b/Controllers/LoadMoreTweetsController.cs index b4287a0..24acbe6 100644 --- a/Controllers/LoadMoreTweetsController.cs +++ b/Controllers/LoadMoreTweetsController.cs @@ -4,7 +4,7 @@ using Microsoft.Extensions.Options; using Tweetinvi; using Tweetinvi.Models; -using Umbraco.Cms.Web.Common.Controllers; + namespace h5yr.Controllers { @@ -17,9 +17,11 @@ public class LoadMoreTweetsController : Controller private readonly string? _consumerSecret; private readonly string? _accessToken; private readonly string? _accessTokenSecret; + private readonly ILogger _logger; + private readonly IOptions _apiSettings; - public LoadMoreTweetsController(IOptions twitterSettings) + public LoadMoreTweetsController(IOptions twitterSettings, ILogger logger, IOptions apiSettings) { var ts = twitterSettings.Value; if (ts != null) @@ -29,23 +31,37 @@ public LoadMoreTweetsController(IOptions twitterSettings) _accessToken = ts.AccessToken; _accessTokenSecret = ts.AccessTokenSecret; } + _logger = logger; + _apiSettings = apiSettings; } [HttpGet] public IActionResult GetTweets() { var tweetsToSkip = Convert.ToInt32(HttpContext.Session.GetInt32("NumberOfTweetsDisplayed")); + List tweets = new(); + + if (_apiSettings.Value.Offline == null || _apiSettings.Value.Offline.ToLowerInvariant() != "true") + { + tweets = GetAllTweets(tweetsToSkip, 12); + } + else + { + string fileName = "TestTweets.json"; + string jsonString = System.IO.File.ReadAllText(fileName); + tweets = System.Text.Json.JsonSerializer.Deserialize>(jsonString)!; + } - var list = GetAllTweets(tweetsToSkip, 12); + HttpContext.Session.SetInt32("NumberOfTweetsDisplayed", tweetsToSkip+12); - return View("Tweets/LoadMoreTweets", list); + return View("Tweets/LoadMoreTweets", tweets); } private List GetAllTweets(int tweetsToSkip, int tweetsToReturn) { - // You need to make sure your app on dev.twitter.com has read and write permissions if you wish to tweet! + // You need to make your own API keys on on dev.twitter.com if you want to pull in LIVE tweets var creds = new TwitterCredentials(_consumerKey, _consumerSecret, _accessToken, _accessTokenSecret); var userClient = new TwitterClient(creds); diff --git a/Core/Services/TwitterHelper.cs b/Core/Services/TwitterHelper.cs index 22980fc..92f7a1b 100644 --- a/Core/Services/TwitterHelper.cs +++ b/Core/Services/TwitterHelper.cs @@ -14,45 +14,46 @@ public class TwitterHelper : ITwitterHelper { private readonly ILogger logger; private readonly IOptions settings; + private readonly IOptions apiSettings; - public TwitterHelper(ILogger logger, IOptions settings) + public TwitterHelper(ILogger logger, IOptions settings, IOptions apiSettings) { this.logger = logger; this.settings = settings; + this.apiSettings = apiSettings; } public List GetAllTweets(int tweetsToSkip, int tweetsToReturn) { - // You need to make sure your app on dev.twitter.com has read and write permissions if you wish to tweet! - var creds = new TwitterCredentials(settings.Value.ConsumerKey, settings.Value.ConsumerSecret, settings.Value.AccessToken, settings.Value.AccessTokenSecret); - var userClient = new TwitterClient(creds); - var searchResults = userClient.Search.SearchTweetsAsync("#h5yr"); - - - List FetchTweets = new List(); + List Tweets = new List(); + if (apiSettings.Value.Offline == null || apiSettings.Value?.Offline?.ToLowerInvariant() != "true") + { + var creds = new TwitterCredentials(settings.Value.ConsumerKey, settings.Value.ConsumerSecret, settings.Value.AccessToken, settings.Value.AccessTokenSecret); + var userClient = new TwitterClient(creds); + var searchResults = userClient.Search.SearchTweetsAsync("#h5yr"); - foreach (var tweet in searchResults.Result.Skip(tweetsToSkip).Take(tweetsToReturn)) - { - FetchTweets.Add(new TweetModel() + foreach (var tweet in searchResults.Result.Skip(tweetsToSkip).Take(tweetsToReturn)) { + Tweets.Add(new TweetModel() + { - Username = tweet.CreatedBy.ToString(), - Avatar = tweet.CreatedBy.ProfileImageUrl, - Content = tweet.Text, - ScreenName = tweet.CreatedBy.ScreenName.ToString(), - TweetedOn = tweet.CreatedAt, - NumberOfTweets = FetchTweets.Count(), - ReplyToTweet = tweet.IdStr, - Url = tweet.Url - - }); + Username = tweet.CreatedBy.ToString(), + Avatar = tweet.CreatedBy.ProfileImageUrl, + Content = tweet.Text, + ScreenName = tweet.CreatedBy.ScreenName.ToString(), + TweetedOn = tweet.CreatedAt, + NumberOfTweets = Tweets.Count(), + ReplyToTweet = tweet.IdStr, + Url = tweet.Url + }); - }; + }; + } - return FetchTweets; + return Tweets; } } diff --git a/Settings/APISettings.cs b/Settings/APISettings.cs new file mode 100644 index 0000000..80a78ea --- /dev/null +++ b/Settings/APISettings.cs @@ -0,0 +1,7 @@ +namespace h5yr.Settings; + +public class APISettings +{ + public string? Offline { get; set; } + public string? CreateOfflineFile { get; set; } +} \ No newline at end of file diff --git a/Settings/TwitterSettings.cs b/Settings/TwitterSettings.cs index f10db9c..5bed261 100644 --- a/Settings/TwitterSettings.cs +++ b/Settings/TwitterSettings.cs @@ -2,8 +2,8 @@ public class TwitterSettings { - public string ConsumerKey { get; set; } - public string ConsumerSecret { get; set; } - public string AccessToken { get; set; } - public string AccessTokenSecret { get; set; } + public string? ConsumerKey { get; set; } + public string? ConsumerSecret { get; set; } + public string? AccessToken { get; set; } + public string? AccessTokenSecret { get; set; } } \ No newline at end of file diff --git a/Startup.cs b/Startup.cs index dd35321..7a43067 100644 --- a/Startup.cs +++ b/Startup.cs @@ -47,6 +47,7 @@ public void ConfigureServices(IServiceCollection services) }); services.Configure(_config.GetSection("Twitter")); + services.Configure(_config.GetSection("API")); services.AddTransient(); } diff --git a/ViewComponents/TweetsViewComponent.cs b/ViewComponents/TweetsViewComponent.cs index 1eef8f1..99ab1eb 100644 --- a/ViewComponents/TweetsViewComponent.cs +++ b/ViewComponents/TweetsViewComponent.cs @@ -1,17 +1,23 @@ -using H5YR.Core.Services; +using h5yr.Settings; +using H5YR.Core.Services; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Newtonsoft.Json; -using System.Text.Json; namespace h5yr.ViewComponents { public class TweetsViewComponent : ViewComponent { private readonly ITwitterHelper twitterHelper; + private readonly IOptions apiSettings; + private readonly ILogger logger; - public TweetsViewComponent(ITwitterHelper twitterHelper) + + public TweetsViewComponent(ITwitterHelper twitterHelper, IOptions apiSettings, ILogger logger) { this.twitterHelper = twitterHelper; + this.apiSettings = apiSettings; + this.logger = logger; } public IViewComponentResult Invoke(string loadmore = "false") @@ -19,26 +25,49 @@ public IViewComponentResult Invoke(string loadmore = "false") HttpContext.Session.SetInt32("NumberOfTweetsDisplayed", 12); - List tweets; - - tweets = twitterHelper.GetAllTweets(0, 12); + List tweet = new(); - // var json = JsonConvert.SerializeObject(tweets); - // string fileName = "TestTweets.json"; - // string jsonString = System.Text.Json.JsonSerializer.Serialize(tweets); - // File.WriteAllText(fileName, jsonString); + if(apiSettings.Value.Offline == null || apiSettings.Value.Offline.ToLowerInvariant() != "true") + { + tweet = twitterHelper.GetAllTweets(0, 12); - string fileName = "TestTweets.json"; - string jsonString = File.ReadAllText(fileName); - List tweet = System.Text.Json.JsonSerializer.Deserialize>(jsonString)!; + // You can only create a new TestTweets file if you have + // a valid Twitter API key setup + if (apiSettings.Value.CreateOfflineFile != null || apiSettings.Value.CreateOfflineFile?.ToLowerInvariant() == "true") + { + try + { + var json = JsonConvert.SerializeObject(tweet); + string fileName = "TestTweets.json"; + string jsonString = System.Text.Json.JsonSerializer.Serialize(json); + File.WriteAllText(fileName, jsonString); + } + catch(Exception ex) + { + logger.LogError("Error: Unable to write Test Tweets Json file", ex); + } + + } + } + else + { + try + { + string fileName = "TestTweets.json"; + string jsonString = File.ReadAllText(fileName); + tweet = System.Text.Json.JsonSerializer.Deserialize>(jsonString)!; + } + catch (Exception ex) + { + logger.LogError("Error: Unable to read Tweet Json file", ex); + } + + } return View(tweet); } - - - } } diff --git a/appsettings.json b/appsettings.json index b6e0498..f63c6dc 100644 --- a/appsettings.json +++ b/appsettings.json @@ -31,6 +31,10 @@ "ConsumerKey": "", "ConsumerSecret": "", "AccessToken": "", - "AccessTokenSecret": "" - } + "AccessTokenSecret": "" + }, + "API": { + "Offline": "true", + "CreateOfflineFile": "" + } } \ No newline at end of file