Skip to content

Commit

Permalink
Integration of TransportLayer with all endpoints except File and Subs…
Browse files Browse the repository at this point in the history
…cribe operations
  • Loading branch information
mohitpubnub committed Sep 23, 2024
1 parent 082829e commit 976d9b3
Show file tree
Hide file tree
Showing 72 changed files with 11,815 additions and 11,093 deletions.
7 changes: 7 additions & 0 deletions src/Api/PubnubApi/Builder/UriUtil.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace PubnubApi
Expand Down Expand Up @@ -196,5 +198,10 @@ private static int ConvertToUtf32(string s, int index)
// Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters.
return (int)s[index];
}

public static string BuildQueryString(Dictionary<string, string> queryStringParamMap)
{
return string.Join("&", queryStringParamMap?.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).Select(kvp => string.Format(CultureInfo.InvariantCulture, "{0}={1}", kvp.Key, kvp.Value)).ToArray());
}
}
}
6 changes: 6 additions & 0 deletions src/Api/PubnubApi/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ namespace PubnubApi
public static class Constants
{
public static readonly string Pnpres = "-pnpres";

public const string GET = "GET";
public const string POST = "POST";
public const string PATCH = "PATCH";
public const string PUT = "PUT";
public const string DELETE = "DELETE";
}
}

411 changes: 207 additions & 204 deletions src/Api/PubnubApi/EndPoint/Access/AuditOperation.cs

Large diffs are not rendered by default.

240 changes: 124 additions & 116 deletions src/Api/PubnubApi/EndPoint/Access/GrantOperation.cs

Large diffs are not rendered by default.

929 changes: 408 additions & 521 deletions src/Api/PubnubApi/EndPoint/Access/GrantTokenOperation.cs

Large diffs are not rendered by default.

302 changes: 158 additions & 144 deletions src/Api/PubnubApi/EndPoint/Access/RevokeTokenOperation.cs
Original file line number Diff line number Diff line change
@@ -1,151 +1,165 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#if !NET35 && !NET40
using System.Collections.Concurrent;
#endif
using System.Text;

namespace PubnubApi.EndPoint
{
public class RevokeTokenOperation : PubnubCoreBase
{
private readonly PNConfiguration config;
private readonly IJsonPluggableLibrary jsonLibrary;
private readonly IPubnubUnitTest unit;
private readonly IPubnubLog pubnubLog;

private string pnToken = string.Empty;
private PNCallback<PNAccessManagerRevokeTokenResult> savedCallbackRevokeToken;
private Dictionary<string, object> queryParam;

public RevokeTokenOperation(PNConfiguration pubnubConfig, IJsonPluggableLibrary jsonPluggableLibrary, IPubnubUnitTest pubnubUnit, IPubnubLog log, EndPoint.TokenManager tokenManager, Pubnub instance) : base(pubnubConfig, jsonPluggableLibrary, pubnubUnit, log, tokenManager, instance)
{
config = pubnubConfig;
jsonLibrary = jsonPluggableLibrary;
unit = pubnubUnit;
pubnubLog = log;
PubnubInstance = instance;

InitializeDefaultVariableObjectStates();
}

public RevokeTokenOperation Token(string tokenToBeRevoked)
{
this.pnToken = tokenToBeRevoked;
return this;
}

public RevokeTokenOperation QueryParam(Dictionary<string, object> customQueryParam)
{
this.queryParam = customQueryParam;
return this;
}

public void Execute(PNCallback<PNAccessManagerRevokeTokenResult> callback)
{
#if NETFX_CORE || WINDOWS_UWP || UAP || NETSTANDARD10 || NETSTANDARD11 || NETSTANDARD12
Task.Factory.StartNew(() =>
{
this.savedCallbackRevokeToken = callback;
RevokeAccess(callback);
}, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default).ConfigureAwait(false);
#else
new Thread(() =>
{
this.savedCallbackRevokeToken = callback;
RevokeAccess(callback);
})
{ IsBackground = true }.Start();
#endif
}

public async Task<PNResult<PNAccessManagerRevokeTokenResult>> ExecuteAsync()
{
return await RevokeAccess().ConfigureAwait(false);
}

internal void Retry()
{
#if NETFX_CORE || WINDOWS_UWP || UAP || NETSTANDARD10 || NETSTANDARD11 || NETSTANDARD12
Task.Factory.StartNew(() =>
{
RevokeAccess(savedCallbackRevokeToken);
}, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default).ConfigureAwait(false);
#else
new Thread(() =>
{
RevokeAccess(savedCallbackRevokeToken);
})
{ IsBackground = true }.Start();
#endif
}

internal void RevokeAccess(PNCallback<PNAccessManagerRevokeTokenResult> callback)
{
if (string.IsNullOrEmpty(config.SecretKey) || string.IsNullOrEmpty(config.SecretKey.Trim()) || config.SecretKey.Length <= 0)
{
throw new MissingMemberException("Invalid secret key");
}

RequestState<PNAccessManagerRevokeTokenResult> requestState = new RequestState<PNAccessManagerRevokeTokenResult>();
requestState.ResponseType = PNOperationType.PNAccessManagerRevokeToken;
requestState.PubnubCallback = callback;
requestState.Reconnect = false;
requestState.EndPointOperation = this;

string requestMethodName = "DELETE";
IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, null, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");
Uri request = urlBuilder.BuildRevokeV3AccessRequest(requestMethodName, null, pnToken, this.queryParam);

UrlProcessRequest(request, requestState, false).ContinueWith(r =>
{
string json = r.Result.Item1;
if (!string.IsNullOrEmpty(json))
{
List<object> result = ProcessJsonResponse(requestState, json);
ProcessResponseCallbacks(result, requestState);
}
}, TaskContinuationOptions.ExecuteSynchronously).Wait();
}

internal async Task<PNResult<PNAccessManagerRevokeTokenResult>> RevokeAccess()
{
if (string.IsNullOrEmpty(config.SecretKey) || string.IsNullOrEmpty(config.SecretKey.Trim()) || config.SecretKey.Length <= 0)
{
throw new MissingMemberException("Invalid secret key");
}

PNResult<PNAccessManagerRevokeTokenResult> ret = new PNResult<PNAccessManagerRevokeTokenResult>();

string requestMethodName = "DELETE";
IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, null, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");
Uri request = urlBuilder.BuildRevokeV3AccessRequest(requestMethodName, null, pnToken, queryParam);

RequestState<PNAccessManagerRevokeTokenResult> requestState = new RequestState<PNAccessManagerRevokeTokenResult>();
requestState.ResponseType = PNOperationType.PNAccessManagerRevokeToken;
requestState.Reconnect = false;
requestState.EndPointOperation = this;

Tuple<string, PNStatus> JsonAndStatusTuple = await UrlProcessRequest(request, requestState, false).ConfigureAwait(false);
ret.Status = JsonAndStatusTuple.Item2;
string json = JsonAndStatusTuple.Item1;
if (!string.IsNullOrEmpty(json))
{
List<object> resultList = ProcessJsonResponse(requestState, json);
if (resultList != null && resultList.Count > 0)
{
ResponseBuilder responseBuilder = new ResponseBuilder(config, jsonLibrary, pubnubLog);
PNAccessManagerRevokeTokenResult responseResult = responseBuilder.JsonToObject<PNAccessManagerRevokeTokenResult>(resultList, true);
if (responseResult != null)
{
ret.Result = responseResult;
}
}
}

return ret;
}

}
public class RevokeTokenOperation : PubnubCoreBase
{
private readonly PNConfiguration config;
private readonly IJsonPluggableLibrary jsonLibrary;
private readonly IPubnubUnitTest unit;
private readonly IPubnubLog pubnubLog;

private string pnToken = string.Empty;
private PNCallback<PNAccessManagerRevokeTokenResult> savedCallbackRevokeToken;
private Dictionary<string, object> queryParam;

public RevokeTokenOperation(PNConfiguration pubnubConfig, IJsonPluggableLibrary jsonPluggableLibrary, IPubnubUnitTest pubnubUnit, IPubnubLog log, EndPoint.TokenManager tokenManager, Pubnub instance) : base(pubnubConfig, jsonPluggableLibrary, pubnubUnit, log, tokenManager, instance)
{
config = pubnubConfig;
jsonLibrary = jsonPluggableLibrary;
unit = pubnubUnit;
pubnubLog = log;
PubnubInstance = instance;

InitializeDefaultVariableObjectStates();
}

public RevokeTokenOperation Token(string tokenToBeRevoked)
{
this.pnToken = tokenToBeRevoked;
return this;
}

public RevokeTokenOperation QueryParam(Dictionary<string, object> customQueryParam)
{
this.queryParam = customQueryParam;
return this;
}

public void Execute(PNCallback<PNAccessManagerRevokeTokenResult> callback)
{
this.savedCallbackRevokeToken = callback;
RevokeAccess(callback);
}

public async Task<PNResult<PNAccessManagerRevokeTokenResult>> ExecuteAsync()
{
return await RevokeAccess();
}

internal void Retry()
{
RevokeAccess(savedCallbackRevokeToken);
}

internal void RevokeAccess(PNCallback<PNAccessManagerRevokeTokenResult> callback)
{
if (string.IsNullOrEmpty(config.SecretKey) || string.IsNullOrEmpty(config.SecretKey.Trim()) || config.SecretKey.Length <= 0) {
throw new MissingMemberException("Invalid secret key");
}

RequestState<PNAccessManagerRevokeTokenResult> requestState = new RequestState<PNAccessManagerRevokeTokenResult>();
requestState.ResponseType = PNOperationType.PNAccessManagerRevokeToken;
requestState.PubnubCallback = callback;
requestState.Reconnect = false;
requestState.EndPointOperation = this;

var requestParameter = CreateRequestParameter();
var transportRequest = PubnubInstance.transportMiddleware.PreapareTransportRequest(requestParameter: requestParameter, operationType: PNOperationType.PNAccessManagerRevokeToken);
PubnubInstance.transportMiddleware.Send(transportRequest: transportRequest).ContinueWith(t => {
var transportResponse = t.Result;
if (transportResponse.Error == null) {
var responseString = Encoding.UTF8.GetString(t.Result.Content);
if (!string.IsNullOrEmpty(responseString)) {
List<object> result = ProcessJsonResponse(requestState, responseString);
ProcessResponseCallbacks(result, requestState);
}
} else {
int statusCode = PNStatusCodeHelper.GetHttpStatusCode(t.Result.Error.Message);
PNStatusCategory category = PNStatusCategoryHelper.GetPNStatusCategory(statusCode, t.Result.Error.Message);
PNStatus status = new StatusBuilder(config, jsonLibrary).CreateStatusResponse(PNOperationType.PNAccessManagerRevokeToken, category, requestState, statusCode, new PNException(t.Result.Error.Message, t.Result.Error));
requestState.PubnubCallback.OnResponse(default(PNAccessManagerRevokeTokenResult), status);
}
});
}

internal async Task<PNResult<PNAccessManagerRevokeTokenResult>> RevokeAccess()
{
if (string.IsNullOrEmpty(config.SecretKey) || string.IsNullOrEmpty(config.SecretKey.Trim()) || config.SecretKey.Length <= 0) {
throw new MissingMemberException("Invalid secret key");
}
PNResult<PNAccessManagerRevokeTokenResult> returnValue = new PNResult<PNAccessManagerRevokeTokenResult>();
RequestState<PNAccessManagerRevokeTokenResult> requestState = new RequestState<PNAccessManagerRevokeTokenResult>();
requestState.ResponseType = PNOperationType.PNAccessManagerRevokeToken;
requestState.Reconnect = false;
requestState.EndPointOperation = this;
Tuple<string, PNStatus> JsonAndStatusTuple;

var requestParameter = CreateRequestParameter();
var transportRequest = PubnubInstance.transportMiddleware.PreapareTransportRequest(requestParameter: requestParameter, operationType: PNOperationType.PNAccessManagerRevokeToken);
var transportResponse = await PubnubInstance.transportMiddleware.Send(transportRequest: transportRequest);
if (transportResponse.Error == null) {
var responseString = Encoding.UTF8.GetString(transportResponse.Content);
PNStatus errorStatus = GetStatusIfError(requestState, responseString);
if (errorStatus == null) {
PNStatus status = new StatusBuilder(config, jsonLibrary).CreateStatusResponse(requestState.ResponseType, PNStatusCategory.PNAcknowledgmentCategory, requestState, transportResponse.StatusCode, null);
JsonAndStatusTuple = new Tuple<string, PNStatus>(responseString, status);
} else {
JsonAndStatusTuple = new Tuple<string, PNStatus>("", errorStatus);
}
returnValue.Status = JsonAndStatusTuple.Item2;
string json = JsonAndStatusTuple.Item1;
if (!string.IsNullOrEmpty(json)) {
List<object> resultList = ProcessJsonResponse(requestState, json);
if (resultList != null && resultList.Count > 0) {
ResponseBuilder responseBuilder = new ResponseBuilder(config, jsonLibrary, pubnubLog);
PNAccessManagerRevokeTokenResult responseResult = responseBuilder.JsonToObject<PNAccessManagerRevokeTokenResult>(resultList, true);
if (responseResult != null) {
returnValue.Result = responseResult;
}
}
}
} else {
int statusCode = PNStatusCodeHelper.GetHttpStatusCode(transportResponse.Error.Message);
PNStatusCategory category = PNStatusCategoryHelper.GetPNStatusCategory(statusCode, transportResponse.Error.Message);
PNStatus status = new StatusBuilder(config, jsonLibrary).CreateStatusResponse(PNOperationType.PNAccessManagerRevokeToken, category, requestState, statusCode, new PNException(transportResponse.Error.Message, transportResponse.Error));
returnValue.Status = status;
}
return returnValue;
}

private RequestParameter CreateRequestParameter()
{
List<string> pathSegments = new List<string>() {
"v3",
"pam",
config.SubscribeKey,
"grant",
pnToken
};

Dictionary<string, string> requestQueryStringParams = new Dictionary<string, string>();

if (queryParam != null && queryParam.Count > 0) {
foreach (KeyValuePair<string, object> kvp in queryParam) {
if (!requestQueryStringParams.ContainsKey(kvp.Key)) {
requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), PNOperationType.ChannelGroupRevokeAccess, false, false, false));
}
}
}

string queryString = UriUtil.BuildQueryString(requestQueryStringParams);

var requestParameter = new RequestParameter() {
RequestType = Constants.DELETE,
PathSegment = pathSegments,
Query = requestQueryStringParams
};

return requestParameter;
}
}
}
Loading

0 comments on commit 976d9b3

Please sign in to comment.