Skip to content

Commit

Permalink
IMP: Way to run the site without needing API keys
Browse files Browse the repository at this point in the history
With the API.Offline mode, you can now run the site without needing any API keys
  • Loading branch information
Owain committed Jul 8, 2022
1 parent f941e3b commit d66979d
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 50 deletions.
26 changes: 21 additions & 5 deletions Controllers/LoadMoreTweetsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using Microsoft.Extensions.Options;
using Tweetinvi;
using Tweetinvi.Models;
using Umbraco.Cms.Web.Common.Controllers;


namespace h5yr.Controllers
{
Expand All @@ -17,9 +17,11 @@ public class LoadMoreTweetsController : Controller
private readonly string? _consumerSecret;
private readonly string? _accessToken;
private readonly string? _accessTokenSecret;
private readonly ILogger<LoadMoreTweetsController> _logger;
private readonly IOptions<APISettings> _apiSettings;


public LoadMoreTweetsController(IOptions<TwitterSettings> twitterSettings)
public LoadMoreTweetsController(IOptions<TwitterSettings> twitterSettings, ILogger<LoadMoreTweetsController> logger, IOptions<APISettings> apiSettings)
{
var ts = twitterSettings.Value;
if (ts != null)
Expand All @@ -29,23 +31,37 @@ public LoadMoreTweetsController(IOptions<TwitterSettings> twitterSettings)
_accessToken = ts.AccessToken;
_accessTokenSecret = ts.AccessTokenSecret;
}
_logger = logger;
_apiSettings = apiSettings;
}

[HttpGet]
public IActionResult GetTweets()
{
var tweetsToSkip = Convert.ToInt32(HttpContext.Session.GetInt32("NumberOfTweetsDisplayed"));
List<TweetModel> 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<List<TweetModel>>(jsonString)!;
}

var list = GetAllTweets(tweetsToSkip, 12);


HttpContext.Session.SetInt32("NumberOfTweetsDisplayed", tweetsToSkip+12);

return View("Tweets/LoadMoreTweets", list);
return View("Tweets/LoadMoreTweets", tweets);
}

private List<TweetModel> 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);

Expand Down
47 changes: 24 additions & 23 deletions Core/Services/TwitterHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,45 +14,46 @@ public class TwitterHelper : ITwitterHelper
{
private readonly ILogger<TwitterHelper> logger;
private readonly IOptions<TwitterSettings> settings;
private readonly IOptions<APISettings> apiSettings;

public TwitterHelper(ILogger<TwitterHelper> logger, IOptions<TwitterSettings> settings)
public TwitterHelper(ILogger<TwitterHelper> logger, IOptions<TwitterSettings> settings, IOptions<APISettings> apiSettings)
{
this.logger = logger;
this.settings = settings;
this.apiSettings = apiSettings;
}

public List<TweetModel> 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<TweetModel> FetchTweets = new List<TweetModel>();
List<TweetModel> Tweets = new List<TweetModel>();
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;
}

}
Expand Down
7 changes: 7 additions & 0 deletions Settings/APISettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace h5yr.Settings;

public class APISettings
{
public string? Offline { get; set; }
public string? CreateOfflineFile { get; set; }
}
8 changes: 4 additions & 4 deletions Settings/TwitterSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
}
1 change: 1 addition & 0 deletions Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public void ConfigureServices(IServiceCollection services)
});

services.Configure<TwitterSettings>(_config.GetSection("Twitter"));
services.Configure<APISettings>(_config.GetSection("API"));
services.AddTransient<ITwitterHelper, TwitterHelper>();
}

Expand Down
61 changes: 45 additions & 16 deletions ViewComponents/TweetsViewComponent.cs
Original file line number Diff line number Diff line change
@@ -1,44 +1,73 @@
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> apiSettings;
private readonly ILogger<TweetsViewComponent> logger;

public TweetsViewComponent(ITwitterHelper twitterHelper)

public TweetsViewComponent(ITwitterHelper twitterHelper, IOptions<APISettings> apiSettings, ILogger<TweetsViewComponent> logger)
{
this.twitterHelper = twitterHelper;
this.apiSettings = apiSettings;
this.logger = logger;
}

public IViewComponentResult Invoke(string loadmore = "false")
{

HttpContext.Session.SetInt32("NumberOfTweetsDisplayed", 12);

List<TweetModel> tweets;

tweets = twitterHelper.GetAllTweets(0, 12);
List<TweetModel> 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<TweetModel> tweet = System.Text.Json.JsonSerializer.Deserialize<List<TweetModel>>(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<List<TweetModel>>(jsonString)!;
}
catch (Exception ex)
{
logger.LogError("Error: Unable to read Tweet Json file", ex);
}

}

return View(tweet);
}




}
}

8 changes: 6 additions & 2 deletions appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@
"ConsumerKey": "",
"ConsumerSecret": "",
"AccessToken": "",
"AccessTokenSecret": ""
}
"AccessTokenSecret": ""
},
"API": {
"Offline": "true",
"CreateOfflineFile": ""
}
}

0 comments on commit d66979d

Please sign in to comment.