Skip to content

Commit

Permalink
[Fix] supporting asynchronous
Browse files Browse the repository at this point in the history
  • Loading branch information
Edrisym committed Nov 3, 2024
1 parent 288ee74 commit 557fa6e
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 161 deletions.
35 changes: 12 additions & 23 deletions Controllers/GoogleCalendarController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using GoogleCalendarApi.Common.Model;
using Google.Apis.Calendar.v3.Data;
using GoogleCalendarApi.Common.Model;
using GoogleCalendarApi.Services;
using Microsoft.AspNetCore.Mvc;

Expand All @@ -9,42 +10,30 @@ namespace GoogleCalendarApi.Controllers
public class GoogleCalendarController : ControllerBase
{
private readonly IGoogleCalendarService _service;
private const string MessagePattern = "Event created for the calendar {0}";

public GoogleCalendarController(IGoogleCalendarService service)
{
_service = service;
}

[HttpPost("CreateEvent")]
public IActionResult CreateEvent([FromBody] EventModel model)
[HttpPost]
public async Task<string> CreateEvent([FromBody] EventModel model)
{
var createdEvent = _service.CreateEvent(model);
var eventId = createdEvent.Id;
if (eventId != null)
return Ok($"Creating event calendar was successfully created : {eventId}");
return BadRequest("Creating event calendar failed!");
var createdEvent = await _service.CreateEventAsync(model);
return string.Format(MessagePattern, createdEvent.Id);
}

[HttpGet("Revoke")]
public IActionResult Revoke()
public async Task<bool> Revoke()
{
var statusCode = _service.RevokeToken();
if (statusCode)
return Ok("Revoking was successfully created");
else
return BadRequest("Revoking failed!");
return await _service.RevokeTokenAsync();
}

[HttpPut("UpdateEvent{eventId}")]
public IActionResult UpdateEvent(string eventId, [FromBody] EventModel eventModel)
[HttpPut("/{eventId}")]
public async Task<Event?> UpdateEvent(string eventId, [FromBody] EventModel eventModel)
{
var createdEvent = _service.UpdateEvent(eventId, eventModel);
if (createdEvent is null)
{
return NotFound("Event with this Id was not found !");
}

return Ok(createdEvent);
return await _service.UpdateEventAsync(eventId, eventModel);
}
}
}
33 changes: 12 additions & 21 deletions Controllers/OAuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,33 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;


namespace GoogleCalendarApi.Controllers
{
[ApiController]
public class OAuthController : ControllerBase
{
private readonly IGoogleCalendarService _service;
private readonly GoogleCalendarSettings _settings;
private const string _ScopeToken = "https://oauth2.googleapis.com/token";
public OAuthController(IOptionsSnapshot<GoogleCalendarSettings> settings, IGoogleCalendarService service)

public OAuthController(IGoogleCalendarService service)
{
_settings = settings.Value;
_service = service;
_service = service;
}

[HttpGet]
[Route("oauth/callback")]
public IActionResult Callback(string code, string? error, string state)
public async Task<bool> Callback(string code, string? error, string state)
{
if (string.IsNullOrWhiteSpace(error))
if (_service.GetToken(code))
return Ok("Access token was generated successfully!");
else
return BadRequest("Access token failed!!");
return Ok("Callback method failed");
return await _service.GetTokenAsync(code);
return false;
}

[HttpPost]
[Route("/googlecalendar/generaterefreshtoken")]
public IActionResult GenerateRefreshToken()
[Route("/refreshToken")]
public async Task<bool> GenerateRefreshToken()
{

var status = _service.RefreshAccessToken(/*_settings.ClientId, _settings.ClientSecret, _ScopeToken*/);
if (status)
return Ok("Refresh token was generated successfully!");
else
return BadRequest("Refresh token failed!!");
return await _service.RefreshAccessTokenAsync();
}

[HttpGet]
Expand All @@ -51,5 +43,4 @@ public IActionResult GetOauthCode()
return BadRequest("creating Uri redirect was failed!!");
}
}
}

}
115 changes: 38 additions & 77 deletions Services/GoogleCalendarService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ public class GoogleCalendarService : IGoogleCalendarService
private const string _ScopeToken = "https://oauth2.googleapis.com/token";
private const string _TokenPath = "OAuthFiles/Token.json";
private const string _CredentialsPath = "OAuthFiles/Credentials.json";
private const string jsonFilePath = "appsettings.Development.json";

public GoogleCalendarService(IOptionsSnapshot<GoogleCalendarSettings> settings, IOAuthService oAuthService)
{
//TODO -- Value
_settings = settings;
_oAuthService = oAuthService;
}
Expand Down Expand Up @@ -64,21 +66,21 @@ private static Event MakeAnEvent(EventModel model)
return createdEvent;
}

public Event CreateEvent(EventModel model)
public async Task<Event> CreateEventAsync(EventModel model)
{
try
{
var newEvent = MakeAnEvent(model);
//TODO -- to asynchronous
var service = _oAuthService.GetCalendarService(_settings);

var eventRequest = service.Events.Insert(newEvent, _settings.Value.CalendarId);

eventRequest.SendNotifications = true;
eventRequest.ConferenceDataVersion = 1;

var createdEvent = eventRequest.Execute();
var createdEvent = await eventRequest.ExecuteAsync();
createdEvent.GuestsCanModify = false;
Console.WriteLine($"Event created: {createdEvent.Id}");

return createdEvent;
}
Expand All @@ -89,40 +91,33 @@ public Event CreateEvent(EventModel model)
}


private Event? getEventById(string eventId)
private async Task<Event?> GetEventByIdAsync(string eventId)
{
var service = _oAuthService
.GetCalendarService(_settings);

var events = service.Events.List(_settings.Value.CalendarId).Execute();

var eventItem = events.Items
.FirstOrDefault(x => x.Id == eventId);

return eventItem;
var service = _oAuthService.GetCalendarService(_settings);

var events = await service.Events.List(_settings.Value.CalendarId).ExecuteAsync();

return events.Items.FirstOrDefault(x => x.Id == eventId);
}

public Event? UpdateEvent(string eventId, EventModel eventModel)
public async Task<Event?> UpdateEventAsync(string eventId, EventModel eventModel)
{
var eventFound = getEventById(eventId);
var eventFound = await GetEventByIdAsync(eventId);
if (eventFound is null)
{
return null;
}

var madeEvent = MakeAnEvent(eventModel);

try
{
var service = _oAuthService
.GetCalendarService(_settings);

var request = service.Events
.Update(madeEvent, _settings.Value.CalendarId, eventId);

var service = _oAuthService.GetCalendarService(_settings);

var request = service.Events.Update(madeEvent, _settings.Value.CalendarId, eventId);
request.SendNotifications = true;
var eventMade = request.Execute();

var eventMade = await request.ExecuteAsync();
return eventMade;
}
catch (Exception exception)
Expand All @@ -131,10 +126,10 @@ public Event CreateEvent(EventModel model)
}
}

public bool RefreshAccessToken()
public async Task<bool> RefreshAccessTokenAsync()
{
var credentialFile = _oAuthService.CredentialsFile();
var tokenFile = _oAuthService.TokenFile();
var credentialFile = await _oAuthService.CredentialsFileAsync();
var tokenFile = await _oAuthService.TokenFileAsync();

var request = new RestRequest();

Expand All @@ -151,34 +146,30 @@ public bool RefreshAccessToken()
var newTokens = JObject.Parse(response.Content);
newTokens["refresh_token"] = tokenFile["refresh_token"].ToString();

UpdateAppSettingJson(newTokens["refresh_token"].ToString());
await UpdateAppSettingJsonAsync(newTokens["refresh_token"].ToString());

File.WriteAllText(_TokenPath, newTokens.ToString());
await File.WriteAllTextAsync(_TokenPath, newTokens.ToString());
}

return response.IsSuccessStatusCode;
}

public void UpdateAppSettingJson(string refreshToken)
private async Task UpdateAppSettingJsonAsync(string refreshToken)
{
string jsonFilePath = "appsettings.Development.json";
string jsonString = File.ReadAllText(jsonFilePath);
var jsonString = await File.ReadAllTextAsync(jsonFilePath);

dynamic jsonObj = JsonConvert.DeserializeObject(jsonString);
dynamic jsonObj = JsonConvert.DeserializeObject(jsonString)!;

jsonObj["GoogleCalendarSettings"]["RefreshToken"] = refreshToken;

string updatedJsonString = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);

File.WriteAllText(jsonFilePath, updatedJsonString);

Console.WriteLine($"RefreshToken updated successfully. {refreshToken}");
await File.WriteAllTextAsync(jsonFilePath, updatedJsonString);
}


public string GetAuthCode()
{
var credentials = JObject.Parse(System.IO.File.ReadAllText(_CredentialsPath));
try
{
string scopeURL1 =
Expand All @@ -194,39 +185,30 @@ public string GetAuthCode()
// var prompt = "select_account";
var login_hint = _settings.Value.LoginHint;
string redirect_uri_encode = Method.UrlEncodeForGoogle(redirectURL);
var mainURL = string.Format(scopeURL1, redirect_uri_encode, state, response_type, client_id, scope,
return string.Format(scopeURL1, redirect_uri_encode, state, response_type, client_id, scope,
access_type, include_granted_scopes, login_hint);

return mainURL;
}
catch (Exception ex)
{
return ex.ToString();
}
}

public bool RevokeToken()
public async Task<bool> RevokeTokenAsync()
{
var token = JObject.Parse(File.ReadAllText(Path.GetFullPath(_TokenPath)));
var token = JObject.Parse(await File.ReadAllTextAsync(Path.GetFullPath(_TokenPath)));
var request = new RestRequest();

request.AddQueryParameter("token", token["access_token"].ToString());

var restClient = new RestClient("https://oauth2.googleapis.com/revoke");
var response = restClient.ExecutePost(request);

if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var newtoken = JObject.Parse(System.IO.File.ReadAllText(_TokenPath));
Console.WriteLine("successfully revoked the token = {0}", newtoken);
}

var response = await restClient.ExecutePostAsync(request);
return response.IsSuccessStatusCode;
}

public bool GetToken(string code)
public async Task<bool> GetTokenAsync(string code)
{
var credentials = JObject.Parse(File.ReadAllText(_CredentialsPath));
var credentials = JObject.Parse(await File.ReadAllTextAsync(_CredentialsPath));

//TODO
var restClient = new RestClient();
Expand All @@ -242,36 +224,15 @@ public bool GetToken(string code)

restClient = new RestClient(_ScopeToken);

var response = restClient.ExecutePost(request);
var response = await restClient.ExecutePostAsync(request);

//TODO
if (response.IsSuccessful == true)
if (response.IsSuccessful)
{
var newTokens = JObject.Parse(response.Content);
//if (newTokens.HasValues)
//{
// UpdateAppSettingJson(newTokens["refresh_token"].ToString());
//}

Console.WriteLine("StatusCode is OK!");
Console.WriteLine("request was successfully sent!");
File.WriteAllText(_TokenPath, response.Content);
await File.WriteAllTextAsync(_TokenPath, response.Content);
}

return response.IsSuccessful;
}

public void GetColor()
{
var service = _oAuthService.GetCalendarService(_settings);
var colorRequest = service.Colors.Get();
var colors = colorRequest.Execute();

foreach (var color in colors.Event__)
{
Console.WriteLine(
$"ColorId: {color.Key}, Background: {color.Value.Background}, Foreground: {color.Value.Foreground}");
}
}
}
}
15 changes: 7 additions & 8 deletions Services/IGoogleCalendarService.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@

using Google.Apis.Calendar.v3.Data;
using Google.Apis.Calendar.v3.Data;
using GoogleCalendarApi.Common.Model;

namespace GoogleCalendarApi.Services
{
public interface IGoogleCalendarService
{
Event CreateEvent(EventModel model);
Event? UpdateEvent(string eventId,EventModel eventModel);
Task<Event> CreateEventAsync(EventModel model);
Task<Event?> UpdateEventAsync(string eventId, EventModel eventModel);
string GetAuthCode();
bool RevokeToken();
bool RefreshAccessToken(/*string clientId, string clientSecret, string scopes*/);
bool GetToken(string token);
Task<bool> RevokeTokenAsync();
Task<bool> RefreshAccessTokenAsync();
Task<bool> GetTokenAsync(string token);
}
}
}
7 changes: 3 additions & 4 deletions Services/IOAuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ namespace GoogleCalendarApi.Services;

public interface IOAuthService
{
JObject CredentialsFile();
JObject TokenFile();
Task<JObject> CredentialsFileAsync();
Task<JObject> TokenFileAsync();
CalendarService GetCalendarService(IOptionsSnapshot<GoogleCalendarSettings> calendarSetting);

}
}
Loading

0 comments on commit 557fa6e

Please sign in to comment.