delphimvcframework/sources/MVCFramework.JSONRPC.Client.pas

382 lines
13 KiB
ObjectPascal
Raw Normal View History

// ***************************************************************************
//
// Delphi MVC Framework
//
// Copyright (c) 2010-2020 Daniele Teti and the DMVCFramework Team
//
// https://github.com/danieleteti/delphimvcframework
//
// ***************************************************************************
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// *************************************************************************** }
unit MVCFramework.JSONRPC.Client;
interface
uses
MVCFramework.JSONRPC,
System.Net.HttpClient,
System.Net.URLClient,
2019-05-16 00:16:55 +02:00
System.Generics.Collections,
System.SysUtils,
MVCFramework.Commons,
JsonDataObjects;
type
IMVCJSONRPCExecutor = interface
['{55415094-9D28-4707-AEC5-5FCF925E82BC}']
function ExecuteRequest(const aJSONRPCRequest: IJSONRPCRequest; const UseVerb: TJSONRPCHTTPVerb = jrpcDefault)
: IJSONRPCResponse; overload;
function ExecuteRequest(const aLastEndPointSegment: string; const aJSONRPCRequest: IJSONRPCRequest;
const UseVerb: TJSONRPCHTTPVerb = jrpcDefault): IJSONRPCResponse; overload;
function ExecuteNotification(const aJSONRPCNotification: IJSONRPCNotification;
const UseVerb: TJSONRPCHTTPVerb = jrpcDefault): IJSONRPCResponse; overload;
function ExecuteNotification(const aLastEndPointSegment: string; const aJSONRPCNotification: IJSONRPCNotification;
const UseVerb: TJSONRPCHTTPVerb = jrpcDefault): IJSONRPCResponse; overload;
2020-08-05 09:50:06 +02:00
function HTTPResponse: IHTTPResponse;
// Http headers handling
procedure AddHTTPHeader(const aNetHeader: TNetHeader);
procedure ClearHTTPHeaders;
function HTTPHeadersCount: Integer;
2019-01-08 12:48:27 +01:00
function SetOnReceiveData(const aOnReceiveData: TReceiveDataEvent): IMVCJSONRPCExecutor;
2019-05-16 00:16:55 +02:00
function SetOnReceiveResponse(const aOnReceiveResponseProc: TProc<IJSONRPCObject, IJSONRPCObject>)
: IMVCJSONRPCExecutor;
function SetOnSendCommand(const aOnSendCommandProc: TProc<IJSONRPCObject>): IMVCJSONRPCExecutor;
2019-01-08 12:48:27 +01:00
function SetOnNeedClientCertificate(const aOnNeedClientCertificate: TNeedClientCertificateEvent)
: IMVCJSONRPCExecutor;
function SetOnValidateServerCertificate(const aOnValidateServerCertificate: TValidateCertificateEvent)
: IMVCJSONRPCExecutor;
function SetOnReceiveHTTPResponse(const aOnReceiveHTTPResponse: TProc<IHTTPResponse>): IMVCJSONRPCExecutor;
function ConfigureHTTPClient(const aConfigProc: TProc<THTTPClient>): IMVCJSONRPCExecutor;
end;
TMVCJSONRPCExecutor = class(TInterfacedObject, IMVCJSONRPCExecutor)
private
fDefaultHTTPVerb: TJSONRPCHTTPVerb;
2020-08-05 09:50:06 +02:00
fURL: string;
fHTTP: THTTPClient;
fRaiseExceptionOnError: Boolean;
fHTTPRequestHeaders: TList<TNetHeader>;
fHTTPResponse: IHTTPResponse;
2019-05-16 00:16:55 +02:00
fOnReceiveResponse: TProc<IJSONRPCObject, IJSONRPCObject>;
fOnReceiveHTTPResponse: TProc<IHTTPResponse>;
2019-05-16 00:16:55 +02:00
fOnSendCommand: TProc<IJSONRPCObject>;
function GetHTTPRequestHeaders: TList<TNetHeader>;
protected
function GetQueryStringParameters(const aJSONRPCObject: IJSONRPCObject): String;
2020-08-05 09:50:06 +02:00
function HTTPResponse: IHTTPResponse;
function InternalExecute(const aEndPoint: string; const aJSONRPCObject: IJSONRPCObject;
const UseVerb: TJSONRPCHTTPVerb): IJSONRPCResponse;
function ExecuteRequest(const aJSONRPCRequest: IJSONRPCRequest; const UseVerb: TJSONRPCHTTPVerb)
: IJSONRPCResponse; overload;
function ExecuteRequest(const aLastEndPointSegment: string; const aJSONRPCRequest: IJSONRPCRequest;
const UseVerb: TJSONRPCHTTPVerb): IJSONRPCResponse; overload;
function ExecuteNotification(const aJSONRPCNotification: IJSONRPCNotification; const UseVerb: TJSONRPCHTTPVerb)
: IJSONRPCResponse; overload;
function ExecuteNotification(const aLastEndPointSegment: string; const aJSONRPCNotification: IJSONRPCNotification;
const UseVerb: TJSONRPCHTTPVerb): IJSONRPCResponse; overload;
// Http headers handling
procedure AddHTTPHeader(const aNetHeader: TNetHeader);
procedure ClearHTTPHeaders;
function HTTPHeadersCount: Integer;
2019-01-08 12:48:27 +01:00
function SetOnReceiveData(const aOnReceiveData: TReceiveDataEvent): IMVCJSONRPCExecutor;
2019-05-16 00:16:55 +02:00
function SetOnReceiveResponse(const aOnReceiveResponseProc: TProc<IJSONRPCObject, IJSONRPCObject>)
: IMVCJSONRPCExecutor;
function SetOnSendCommand(const aOnSendCommandProc: TProc<IJSONRPCObject>): IMVCJSONRPCExecutor;
2019-01-08 12:48:27 +01:00
function SetOnNeedClientCertificate(const aOnNeedClientCertificate: TNeedClientCertificateEvent)
: IMVCJSONRPCExecutor;
function SetOnValidateServerCertificate(const aOnValidateServerCertificate: TValidateCertificateEvent)
: IMVCJSONRPCExecutor;
function SetOnReceiveHTTPResponse(const aOnReceiveHTTPResponse: TProc<IHTTPResponse>): IMVCJSONRPCExecutor;
function ConfigureHTTPClient(const aConfigProc: TProc<THTTPClient>): IMVCJSONRPCExecutor;
2019-01-08 12:48:27 +01:00
public
constructor Create(const aURL: string; const aRaiseExceptionOnError: Boolean = True;
const aDefaultHTTPVerb: TJSONRPCHTTPVerb = jrpcDefault); virtual;
2019-01-08 12:48:27 +01:00
destructor Destroy; override;
end;
implementation
uses
2019-05-16 00:16:55 +02:00
System.Classes;
2019-01-08 12:48:27 +01:00
procedure JSONRPCExec(const aJSONRPCURL: string; const aJSONRPCRequest: IJSONRPCRequest;
out aJSONRPCResponse: IJSONRPCResponse);
var
lSS: TStringStream;
lHttpResp: IHTTPResponse;
lHTTP: THTTPClient;
begin
lSS := TStringStream.Create(aJSONRPCRequest.AsJSONString);
try
lSS.Position := 0;
lHTTP := THTTPClient.Create;
try
lHttpResp := lHTTP.Post(aJSONRPCURL, lSS, nil, [TNetHeader.Create('content-type', 'application/json'),
TNetHeader.Create('accept', 'application/json')]);
if (lHttpResp.StatusCode <> 204) then
begin
aJSONRPCResponse := TJSONRPCResponse.Create;
aJSONRPCResponse.AsJSONString := lHttpResp.ContentAsString;
if Assigned(aJSONRPCResponse.Error) then
raise Exception.CreateFmt('Error [%d]: %s', [aJSONRPCResponse.Error.Code, aJSONRPCResponse.Error.ErrMessage]);
end;
finally
lHTTP.Free;
end;
finally
lSS.Free;
end;
end;
{ TMVCJSONRPCExecutor }
procedure TMVCJSONRPCExecutor.AddHTTPHeader(const aNetHeader: TNetHeader);
begin
GetHTTPRequestHeaders.Add(aNetHeader);
end;
procedure TMVCJSONRPCExecutor.ClearHTTPHeaders;
begin
2020-08-05 09:50:06 +02:00
if Assigned(fHTTPRequestHeaders) then
begin
2020-08-05 09:50:06 +02:00
fHTTPRequestHeaders.Clear;
end;
end;
function TMVCJSONRPCExecutor.ConfigureHTTPClient(const aConfigProc: TProc<THTTPClient>): IMVCJSONRPCExecutor;
begin
2020-08-05 09:50:06 +02:00
aConfigProc(fHTTP);
end;
constructor TMVCJSONRPCExecutor.Create(const aURL: string; const aRaiseExceptionOnError: Boolean = True;
const aDefaultHTTPVerb: TJSONRPCHTTPVerb = jrpcDefault);
begin
inherited Create;
2020-08-05 09:50:06 +02:00
fRaiseExceptionOnError := aRaiseExceptionOnError;
fURL := aURL;
fDefaultHTTPVerb := aDefaultHTTPVerb;
2020-08-05 09:50:06 +02:00
fHTTP := THTTPClient.Create;
fHTTP.ResponseTimeout := MaxInt;
fHTTPRequestHeaders := nil;
SetOnReceiveResponse(nil).SetOnReceiveData(nil).SetOnNeedClientCertificate(nil).SetOnValidateServerCertificate(nil);
end;
destructor TMVCJSONRPCExecutor.Destroy;
begin
2020-08-05 09:50:06 +02:00
fHTTP.Free;
fHTTPRequestHeaders.Free;
inherited;
end;
function TMVCJSONRPCExecutor.ExecuteNotification(const aJSONRPCNotification: IJSONRPCNotification;
const UseVerb: TJSONRPCHTTPVerb): IJSONRPCResponse;
begin
Result := ExecuteNotification('', aJSONRPCNotification, UseVerb);
end;
function TMVCJSONRPCExecutor.ExecuteRequest(const aJSONRPCRequest: IJSONRPCRequest; const UseVerb: TJSONRPCHTTPVerb)
: IJSONRPCResponse;
begin
Result := ExecuteRequest('', aJSONRPCRequest, UseVerb);
end;
function TMVCJSONRPCExecutor.GetHTTPRequestHeaders: TList<TNetHeader>;
begin
2020-08-05 09:50:06 +02:00
if not Assigned(fHTTPRequestHeaders) then
begin
2020-08-05 09:50:06 +02:00
fHTTPRequestHeaders := TList<TNetHeader>.Create;
end;
2020-08-05 09:50:06 +02:00
Result := fHTTPRequestHeaders;
end;
function TMVCJSONRPCExecutor.GetQueryStringParameters(const aJSONRPCObject: IJSONRPCObject): String;
var
lJObj: TJDOJsonObject;
begin
lJObj := aJSONRPCObject.AsJSON;
try
2021-02-25 10:50:57 +01:00
Result := 'jsonrpc=' + URLEncode(lJObj.S['jsonrpc']);
Result := Result + '&method=' + URLEncode(lJObj.S['method']);
if lJObj.Contains('id') then
begin
2021-02-25 10:50:57 +01:00
Result := Result + '&id=' + URLEncode(lJObj.S['id']);
end;
if lJObj.Contains('params') then
begin
if lJObj.Types['params'] = jdtArray then
begin
2021-02-25 10:50:57 +01:00
Result := Result + '&params=' + URLEncode(lJObj.A['params'].ToJSON());
end
else
begin
2021-02-25 10:50:57 +01:00
Result := Result + '&params=' + URLEncode(lJObj.O['params'].ToJSON());
end;
end;
finally
lJObj.Free;
end;
end;
function TMVCJSONRPCExecutor.HTTPHeadersCount: Integer;
begin
2020-08-05 09:50:06 +02:00
if Assigned(fHTTPRequestHeaders) then
begin
2020-08-05 09:50:06 +02:00
Result := fHTTPRequestHeaders.Count;
end
else
begin
Result := 0;
end;
end;
function TMVCJSONRPCExecutor.InternalExecute(const aEndPoint: string; const aJSONRPCObject: IJSONRPCObject;
const UseVerb: TJSONRPCHTTPVerb): IJSONRPCResponse;
var
lSS: TStringStream;
lHttpResp: IHTTPResponse;
lJSONRPCResponse: IJSONRPCResponse;
lCustomHeaders: TNetHeaders;
begin
lCustomHeaders := [];
2020-08-05 09:50:06 +02:00
if Assigned(fHTTPRequestHeaders) then
begin
2020-08-05 09:50:06 +02:00
lCustomHeaders := fHTTPRequestHeaders.ToArray;
end;
Result := nil;
2019-01-08 12:48:27 +01:00
lSS := TStringStream.Create(aJSONRPCObject.AsJSONString, TEncoding.UTF8);
try
lSS.Position := 0;
2019-05-16 00:16:55 +02:00
if Assigned(fOnSendCommand) then
begin
fOnSendCommand(aJSONRPCObject);
end;
2020-08-06 17:40:56 +02:00
fHTTPResponse := nil;
case UseVerb of
jrpcPOST, jrpcDefault:
begin
lHttpResp := fHTTP.Post(fURL + aEndPoint, lSS, nil,
[TNetHeader.Create('content-type', 'application/json;charset=utf8'), TNetHeader.Create('accept',
'application/json;charset=utf8')] + lCustomHeaders);
end;
jrpcGET:
begin
lHttpResp := fHTTP.Get(fURL + aEndPoint + '?' + GetQueryStringParameters(aJSONRPCObject), nil,
[TNetHeader.Create('accept', 'application/json;charset=utf8')] + lCustomHeaders);
end;
end;
2020-08-06 17:40:56 +02:00
fHTTPResponse := lHttpResp;
if Assigned(fOnReceiveHTTPResponse) then
begin
fOnReceiveHTTPResponse(fHTTPResponse);
end;
lJSONRPCResponse := nil;
2020-08-06 17:40:56 +02:00
if lHttpResp.StatusCode = HTTP_STATUS.NoContent then
begin
lJSONRPCResponse := TJSONRPCNullResponse.Create;
end
else
begin
if fHTTPResponse.HeaderValue['content-type'].Contains(TMVCMediaType.APPLICATION_JSON) then
begin
lJSONRPCResponse := TJSONRPCResponse.Create;
lJSONRPCResponse.AsJSONString := lHttpResp.ContentAsString;
end;
2020-08-06 17:40:56 +02:00
end;
fHTTPResponse := lHttpResp;
2020-08-06 17:40:56 +02:00
if Assigned(fOnReceiveResponse) then
begin
fOnReceiveResponse(aJSONRPCObject, lJSONRPCResponse);
end;
if lJSONRPCResponse = nil then
begin
raise EMVCException.CreateFmt('[REMOTE EXCEPTION][%d: %s]: %s',
[fHTTPResponse.StatusCode, fHTTPResponse.StatusText, fHTTPResponse.ContentAsString()]);
end;
2020-08-06 17:40:56 +02:00
if Assigned(lJSONRPCResponse.Error) and fRaiseExceptionOnError then
raise EMVCJSONRPCException.CreateFmt('[REMOTE EXCEPTION][%d]: %s',
[lJSONRPCResponse.Error.Code, lJSONRPCResponse.Error.ErrMessage]);
Result := lJSONRPCResponse;
finally
lSS.Free;
end;
end;
2020-08-05 09:50:06 +02:00
function TMVCJSONRPCExecutor.HTTPResponse: IHTTPResponse;
begin
Result := fHTTPResponse;
end;
2019-01-08 12:48:27 +01:00
function TMVCJSONRPCExecutor.SetOnNeedClientCertificate(const aOnNeedClientCertificate: TNeedClientCertificateEvent)
: IMVCJSONRPCExecutor;
begin
2020-08-05 09:50:06 +02:00
fHTTP.OnNeedClientCertificate := aOnNeedClientCertificate;
2019-01-08 12:48:27 +01:00
Result := Self;
end;
function TMVCJSONRPCExecutor.SetOnReceiveData(const aOnReceiveData: TReceiveDataEvent): IMVCJSONRPCExecutor;
2019-01-08 12:48:27 +01:00
begin
2020-08-05 09:50:06 +02:00
fHTTP.OnReceiveData := aOnReceiveData;
2019-01-08 12:48:27 +01:00
Result := Self;
end;
function TMVCJSONRPCExecutor.SetOnReceiveHTTPResponse(const aOnReceiveHTTPResponse: TProc<IHTTPResponse>)
: IMVCJSONRPCExecutor;
begin
fOnReceiveHTTPResponse := aOnReceiveHTTPResponse;
Result := Self;
end;
2019-05-16 00:16:55 +02:00
function TMVCJSONRPCExecutor.SetOnReceiveResponse(const aOnReceiveResponseProc: TProc<IJSONRPCObject, IJSONRPCObject>)
: IMVCJSONRPCExecutor;
begin
fOnReceiveResponse := aOnReceiveResponseProc;
Result := Self;
end;
function TMVCJSONRPCExecutor.SetOnSendCommand(const aOnSendCommandProc: TProc<IJSONRPCObject>): IMVCJSONRPCExecutor;
2019-05-16 00:16:55 +02:00
begin
fOnSendCommand := aOnSendCommandProc;
Result := Self;
end;
2019-01-08 12:48:27 +01:00
function TMVCJSONRPCExecutor.SetOnValidateServerCertificate(const aOnValidateServerCertificate
: TValidateCertificateEvent): IMVCJSONRPCExecutor;
begin
2020-08-05 09:50:06 +02:00
fHTTP.OnValidateServerCertificate := aOnValidateServerCertificate;
2019-05-16 00:16:55 +02:00
Result := Self;
2019-01-08 12:48:27 +01:00
end;
function TMVCJSONRPCExecutor.ExecuteNotification(const aLastEndPointSegment: string;
const aJSONRPCNotification: IJSONRPCNotification; const UseVerb: TJSONRPCHTTPVerb): IJSONRPCResponse;
begin
Result := InternalExecute(aLastEndPointSegment, aJSONRPCNotification as TJSONRPCObject, UseVerb);
end;
function TMVCJSONRPCExecutor.ExecuteRequest(const aLastEndPointSegment: string; const aJSONRPCRequest: IJSONRPCRequest;
const UseVerb: TJSONRPCHTTPVerb): IJSONRPCResponse;
begin
Result := InternalExecute(aLastEndPointSegment, aJSONRPCRequest, UseVerb);
end;
end.