Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/Barbarur/NovaPoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Barbarur committed Aug 14, 2024
2 parents 505c1df + ff0deec commit 7dac17b
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 66 deletions.
58 changes: 16 additions & 42 deletions src/NovaPointLibrary/Commands/Utilities/GraphAPIHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,15 +135,23 @@ private async Task<HttpRequestMessage> GetMessage(string url, HttpMethod method)
{
url = url.Substring(1);
}

string accessToken = await _appInfo.GetGraphAccessToken();
string apiUrl = !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? $"{_graphUrl}/{url}" : url;
_logger.LogTxt(GetType().Name, $"Writing message for '{method}' in '{apiUrl}'");

HttpRequestMessage message = new();
message.Method = method;
message.RequestUri = !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? new Uri($"{_graphUrl}/{url}") : new Uri(url);

string accessToken = await _appInfo.GetGraphAccessToken();
message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

_logger.LogTxt(GetType().Name, $"Request Message Uir {message.RequestUri}");
message.RequestUri = new Uri(apiUrl);

// MISSING:
// Header.Accept
// Content
// Additional Headers
// Content header content type


return message;
}
Expand All @@ -157,6 +165,7 @@ private async Task<string> SendMessageAsync(HttpRequestMessage message)
while (response.StatusCode == (HttpStatusCode)429)
{
var retryAfter = response.Headers.RetryAfter;
if (retryAfter == null || retryAfter.Delta == null) { break; }
await Task.Delay(retryAfter.Delta.Value.Seconds * 1000);
response = await HttpsClient.SendAsync(message);
}
Expand All @@ -169,47 +178,12 @@ private async Task<string> SendMessageAsync(HttpRequestMessage message)
}
else
{
_logger.LogTxt(GetType().Name, $"Error response");

string content = await response.Content.ReadAsStringAsync();
_logger.LogTxt(GetType().Name,$"Error Content:{content}");
string responseContent = await response.Content.ReadAsStringAsync();
string exceptionMessage = $"Request to SharePoint REST API {message.RequestUri} failed with status code {response.StatusCode} and response content: {responseContent}";

var oErrorContent = JsonConvert.DeserializeObject<GraphErrorContent>(content);
string errorMessage = oErrorContent.Error.Message.ToString();

throw new Exception(errorMessage);
throw new Exception(exceptionMessage);
}
}
}

internal class GraphtResultContent<T>
{
/// <summary>
/// Context information detailing the type of message returned
/// </summary>
[JsonProperty("@odata.context")]
public string Context { get; set; }

/// <summary>
/// NextLink detailing the link to query to fetch the next batch of results
/// </summary>
[JsonProperty("nextLink")]
public string NextLink { get; set; }

/// <summary>
/// OData NextLink detailing the link to query to fetch the next batch of results
/// </summary>
[JsonProperty("@odata.nextLink")]
public string ODataNextLink // { get; set; }
{
get { return NextLink; }
set { NextLink = value; }
}

/// <summary>
/// The items contained in the results
/// </summary>
[JsonProperty("value")]
public IEnumerable<T> Items { get; set; }
}
}
47 changes: 24 additions & 23 deletions src/NovaPointLibrary/Commands/Utilities/RESTAPIHandler.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using AngleSharp.Css.Dom;
using Microsoft.Graph;
using Newtonsoft.Json;
using NovaPointLibrary.Commands.Authentication;
using NovaPointLibrary.Commands.Utilities.GraphModel;
Expand Down Expand Up @@ -61,36 +62,39 @@ private async Task<HttpRequestMessage> GetRequestMessage(HttpMethod method, stri
_logger.LogTxt(GetType().Name, $"Writing message for '{method}' in '{apiUrl}'");

HttpRequestMessage request = new();
request.Method = method;

string spoAccessToken = await _appInfo.GetSPOAccessToken(apiUrl);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", spoAccessToken);
string accessToken = await _appInfo.GetSPOAccessToken(apiUrl);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

request.Method = method;
request.RequestUri = new Uri(apiUrl);

request.Headers.Add("Accept", "application/json");
//message.Version = new Version(2, 0);

request.Content = new StringContent(content, System.Text.Encoding.UTF8);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));


if (method == HttpMethod.Post || method == HttpMethod.Put || method.Method == "PATCH")
{
request.Content = new StringContent(content, System.Text.Encoding.UTF8);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
}


return request;
}

private async Task<string> SendMessageAsync(HttpRequestMessage message)
{
_appInfo.IsCancelled();
_logger.LogTxt(GetType().Name, $"Sending HTTP request message");

HttpResponseMessage response = await HttpsClient.SendAsync(message, _appInfo.CancelToken);
//HttpResponseMessage response = await HttpsClient.SendAsync(message);

//while (response.StatusCode == (HttpStatusCode)429)
//{
// var retryAfter = response.Headers.RetryAfter;
// await Task.Delay(retryAfter.Delta.Value.Seconds * 1000);
// response = await HttpsClient.SendAsync(message);
//}

while (response.StatusCode == (HttpStatusCode)429)
{
var retryAfter = response.Headers.RetryAfter;
if (retryAfter == null || retryAfter.Delta == null) { break; }
await Task.Delay(retryAfter.Delta.Value.Seconds * 1000);
response = await HttpsClient.SendAsync(message);
}

if (response.IsSuccessStatusCode)
{
Expand All @@ -110,13 +114,10 @@ private async Task<string> SendMessageAsync(HttpRequestMessage message)
}
else
{
string content = await response.Content.ReadAsStringAsync();
_logger.LogTxt(GetType().Name, $"Error response:{content}");

RESTErrorContent? oErrorContent = JsonConvert.DeserializeObject<RESTErrorContent>(content);
string errorMessage = oErrorContent?.Error.Message.Value != null ? oErrorContent.Error.Message.Value.ToString() : "Unknown Error";
string responseContent = await response.Content.ReadAsStringAsync();
string exceptionMessage = $"Request to SharePoint REST API {message.RequestUri} failed with status code {response.StatusCode} and response content: {responseContent}";

throw new Exception(errorMessage);
throw new Exception(exceptionMessage);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace NovaPointLibrary.Commands.Utilities.RESTModel
{
public class RESTErrorContent
{
[JsonProperty("error")]
[JsonProperty("odata.error")]
public Error Error { get; set; }
}
public class Error
Expand Down

0 comments on commit 7dac17b

Please sign in to comment.