unit Azure.CognitiveServices.FaceDetection.HTTP;

interface

uses
  System.Classes,
  System.JSON,
  System.Net.URLClient,
  System.SysUtils,
  Azure.CognitiveServices.Core.HTTP,
  Azure.CognitiveServices.FaceDetection.Types;

type

  TAcsFaceDetectHttpBroker = class (TAcsHttpBroker<TAcsFaceDetectRequest, TAcsFaceDetectResponse>)
  private
  protected
    procedure DoCustomizeContentType(const ARequest: TAcsFaceDetectRequest;
      var AContentType: string); override;
    procedure DoCustomizeURI(const ARequest: TAcsFaceDetectRequest;
      const AURI: TURI); override;
    procedure DoParseResponseJson(const AJSONObject: TJSONObject;
      out AResponse: TAcsFaceDetectResponse); override;
    procedure DoPrepareRequestStream(const ARequest: TAcsFaceDetectRequest;
      var AStream: TStream); override;
  end;

implementation

uses
  Azure.CognitiveServices.FaceDetection.JSON;

procedure TAcsFaceDetectHttpBroker.DoCustomizeContentType(
  const ARequest: TAcsFaceDetectRequest; var AContentType: string);
begin
  if Length(ARequest.ImageUrl) > 0 then
    AContentType := 'application/json'
  else
    AContentType := 'application/octet-stream';
end;

procedure TAcsFaceDetectHttpBroker.DoCustomizeURI(const ARequest: TAcsFaceDetectRequest;
  const AURI: TURI);
begin
  inherited;
  AURI.AddParameter('returnFaceId', BoolToStr(ARequest.ReturnFaceId, True).ToLower());
  AURI.AddParameter('returnFaceLandmarks', BoolToStr(ARequest.ReturnFaceLandmarks, True).ToLower());
  AURI.AddParameter('returnFaceAttributes', ARequest.GetReturnFaceAttributesList());
  AURI.AddParameter('recognitionModel', ARequest.GetRecognitionModelName());
  AURI.AddParameter('returnRecognitionModel', BoolToStr(ARequest.ReturnRecognitionModel, True).ToLower());
  AURI.AddParameter('detectionModel', ARequest.GetDetectionModelName());
  AURI.AddParameter('faceIdTimeToLive', IntToStr(ARequest.FaceIdTimeToLive));
end;

procedure TAcsFaceDetectHttpBroker.DoParseResponseJson(
  const AJSONObject: TJSONObject; out AResponse: TAcsFaceDetectResponse);
begin
  inherited;
  TAcsFaceDetectJSON.Parse(AJSONObject, AResponse);
end;

procedure TAcsFaceDetectHttpBroker.DoPrepareRequestStream(
  const ARequest: TAcsFaceDetectRequest; var AStream: TStream);
var
  LBody: TJSONObject;
begin
  inherited;
  if Length(ARequest.ImageUrl) > 0 then
  begin
    LBody := TJSONObject.Create(TJSONPair.Create('url', ARequest.ImageUrl));
    try
      AStream := TStringStream.Create(LBody.ToString);
    finally
      LBody.Free;
    end;
  end
  else if Length(ARequest.ImageData) > 0 then
  begin
    AStream := TMemoryStream.Create;
    AStream.Write(ARequest.ImageData, Length(ARequest.ImageData));
    AStream.Seek(0, soFromBeginning);
  end
  else
    raise Exception.Create('Image URL or data not assigned');
end;

end.
