unit CloudURLShortener;

interface

uses
  Classes, CloudBase, SHDocVw, SysUtils, ComCtrls,
  IdCustomTCPServer, IdCustomHTTPServer, IdContext, IdHTTPServer;


const
  MAJ_VER = 1; // Major version nr.
  MIN_VER = 0; // Minor version nr.
  REL_VER = 0; // Release nr.
  BLD_VER = 1; // Build nr.

type
  TAdvURLShortener = class(TCloudBase)
  protected
    function GetVersionNr: integer; override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    function ShortenURL(URL: string): string;
  end;


implementation


uses
  DBXJSON, Windows;


{ TAdvURLShortener }

constructor TAdvURLShortener.Create(AOwner: TComponent);
begin
  inherited;
end;

destructor TAdvURLShortener.Destroy;
begin
  inherited;
end;

function TAdvURLShortener.ShortenURL(URL: string): string;
var
  FServer, FAction, FData: string;
  headers: TCoreCloudHeaders;
  resdat: ansistring;
  jv: TJSONValue;
  o: TJSONObject;
begin
    Result := '';

    FServer := 'www.googleapis.com';
    FAction := '/urlshortener/v1/url';
    AddHeader(headers, 'Content-Type', 'application/json');

    FData := '{"longUrl": "' + URL + '"}';

    HttpsPost(FServer, FAction, headers, AnsiString(FData), resdat);

//    OutputDebugString(pchar('SHORT URL= ' + string(resdat)));

    jv := TJSONObject.ParseJSONValue(string(resdat));

    if Assigned(jv) then
    begin
      try
        o := jv as TJSONObject;
        Result := GetJSONProp(o,'id');
      finally
        jv.Free;
      end;
    end;
end;

function TAdvURLShortener.GetVersionNr: integer;
begin
  Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER));
end;

end.
