unit uHTTPRequests;
{<

contains all HTTP Requests to Server of the component PS_HTTPClient
all other units use it as the library

}

interface

uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdHTTP,IdException,


  HTTPApp,
  IdMultipartFormData, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
  FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, Data.DB,
  FireDAC.Comp.Client, System.IOUtils, System.Types,System.JSON,uCreateUniqueName,
  System.NetEncoding,

  //MyUnits

  uHTTP_ConnectionParams,uEtcetra_PS_HTTPClient,uSendFileInChunks,uSendFileInChunks2,
  IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack;// IdSSL, IdSSLOpenSSL

type
  THTTPRequests = class(TDataModule)
  private


    FSendFileInChunks:TSendFileInChunks;
    FSendFileInChunks2:TSendFileInChunks2;


    FIsKeep2Share:boolean;



    { Private declarations }
  public
    { Public declarations }

    constructor Create(Aowner:TComponent); override;

    procedure IsFileOnServer( AFileName:string; AdirOnServer: string; var AMyServerResponse: string; idUser:integer);
    function IsHTTPConnectionOk(var Error:string; var ResponseText:string ):boolean; overload;
    function IsHTTPConnectionOk():boolean; overload;

    {Sending One File to Server and Putting to some Dir;
    dirOnServer is dir on Server to Put File relatively to HTTPServer.exe}
    procedure SendOneFile(Filepath:string; dirOnServer:string); overload;

    procedure SendOneFile(AFilepath:string; AdirOnServer:string; AFileNameOnServer:string); overload;

    procedure SendOneFileWithoutLog(AFilepath, AdirOnServer, AFileNameOnServer: string; AidUsersString:String);


    procedure SendManyFiles(FilepathesSL:TStringList; dirOnServer: string);
     {<Sending many files and putting them to dirOnSerer
    dirOnServer is dir on Server to Put File relatively to HTTPServer.exe}


      {Sending many files and putting them to dirOnSerer
    dirOnServer is dir on Server to Put File relatively to HTTPServer.exe

    dirOnClient is the dir where chunks are
    }
    procedure SendManyFiles2(AbsDirOnClient, AbsDirOnServer: string);


    {Gathering and Sending chunks info on Server in String - doesn't worl well}
    procedure SendChunksInfo(AChunksDir, AChunksDirOnServer: string;AFileSize:int64);


    {Gathering and Sending chunks info on Server in File}
    procedure SendChunksInfoInFile(AChunksDir, AchunksDirOnServer: string; AFileSize: int64;ChunksInfoFileName:string);

    { this method will read ChunksInfo.txt on Server in dirOnServer
      and will check if all chunks are on Server

    }
    function IsCheckChunksIntegrityOk(AdirOnServer:string; AChunksInfoFileName:string):boolean;



    procedure CreateDirOnServer(dir:string);
    {<creates dir on Server Relatively to HTTPServer.exe}

    procedure CreateCurrentDayDirOnServer;
    procedure CreateCurrentDayDirThumbsOnServer;
    procedure CreateTempFolderForFileChunks(Filename: string);


    procedure DeleteDirOnServer(dir: string);
    procedure DeleteTempFolderForFileChunks(Filename: string);

    {Delete File On Server}
    procedure DeleteFileOnServer(AFilePath, AMyServerResponse: string);
    procedure DeleteTempFileOnServer(Adir, AFileName, AMyServerResponse: string);


    procedure DeleteFoldersAndFilesOnServerWithDataBase(AIDValuesJSONString:string);
    {< deletes files from system and disk by ID}

    procedure GatherFileFromChunks(AChunksDirOnServer:string; AOutPutDirOnServer:string; AOutPutFileName:string;AidUserString:String); overload;


    procedure SendPostParamsForTest;

    procedure SendFile2Keep2Share(dirOnServer, FileNameOnServer: string; var MyServerResponse:string);

    procedure AddFileToDB(ADirOnServer:string; AFileName:string; AidUsersString:String);


    property SendFileInChunks:TSendFileInChunks read FSendFileInChunks
    write FSendFileInChunks;

    property SendFileInChunks2:TSendFileInChunks2 read FSendFileInChunks2
    write FSendFileInChunks2;




    property IsKeep2Share:boolean read FIsKeep2Share write FIsKeep2Share;




  end;

var
  HTTPRequests: THTTPRequests;

implementation


uses uVisualFrame;

var VisualFrame_HTTP_UnitVar:TVisualFrame_HTTP;


{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}




procedure THTTPRequests.AddFileToDB(ADirOnServer, AFileName, AidUsersString: String);

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  MyServerResponse:string;

begin

    with VisualFrame_HTTP_UnitVar do begin


        begin

              if not IsHTTPConnectionOk(Error,MyServerResponse) then Exit;


                      PostData := TIdMultiPartFormDataStream.Create;

                      AFileName:=TNetEncoding.URL.Encode(AFileName);
                      AdirOnServer:=TNetEncoding.URL.Encode(ADirOnServer);

                      try

                        idHTTP.Request.Referer := HTTPServerToRequest+'/AddFileToDB';

                        idHTTP.Request.ContentType := 'multipart/form-data';

                        PostData.AddFormField('Login', 'SomeLogin');
                        PostData.AddFormField('Password', 'SomePassword');
                        PostData.AddFormField('ADirOnServer', AdirOnServer);
                        PostData.AddFormField('AFileName', AFileName);
                        PostData.AddFormField('AidUsersString', AidUsersString);



                        MyServerResponse:=
                        idHTTP.Post(HTTPServerToRequest+'/AddFileToDB', PostData);



                        if MyServerResponse<>'ok' then
                       raise Exception.Create('Server Response '+MyServerResponse);


                        Application.ProcessMessages;
                      finally

                        if(Assigned(PostData)) then PostData.Free;

                         // ShowMessage('idHTTP Sent OK');
                        // StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                      end;


              end;


    end;


end;



function THTTPRequests.
IsCheckChunksIntegrityOk(AdirOnServer:string; AChunksInfoFileName:string):boolean;

var

  PostData: TIdMultiPartFormDataStream;
  MyServerResponse:String;


begin

Result:=false;

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk() then Exit;




                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/checkChunksIntegrity';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');
                    PostData.AddFormField('dirOnServer', AdirOnServer);
                    PostData.AddFormField('ChunksInfoFileName', AChunksInfoFileName);



                  MyServerResponse:=
                  idHTTP.Post(HTTPServerToRequest+'/checkChunksIntegrity', PostData);

                  if MyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+MyServerResponse);

                  Result:=true;

                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                    // StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;

                  end;


          end;


    end;


end;



procedure THTTPRequests.IsFileOnServer(
AFileName:string;
AdirOnServer:string;
var AMyServerResponse:string;
idUser:Integer
);

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  ResponseText:string;
  EncodedFileName: string;


begin

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk(Error,ResponseText) then Exit;




                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/isfileonserver';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');
                    PostData.AddFormField('dirOnServer', AdirOnServer);
                    PostData.AddFormField('idUser', idUser.ToString());

                  //  EncodedFileName:=TNetEncoding.URL.Encode(AFileName);
                    //PostData.AddFormField('FileName', EncodedFileName);
                    PostData.AddFormField('FileName', AFileName);


                  AMyServerResponse:=
                  idHTTP.Post(HTTPServerToRequest+'/isfileonserver', PostData);

                  if AMyServerResponse<>'ok' then
                  raise Exception.Create('Server Response '+AMyServerResponse);


                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                    // StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                  end;


          end;


    end;


end;






constructor THTTPRequests.Create(Aowner: TComponent);
begin
  inherited;

  if (Aowner is TVisualFrame_HTTP) then
  VisualFrame_HTTP_UnitVar:=(Aowner as TVisualFrame_HTTP);


//  if (Aowner is TSendFileInChunks) then
//  SendFileInChunks_UnitVar


end;

//---------------------------------------------------------------------------------

{Checking if HTTPServer Connection Ok}
function THTTPRequests.IsHTTPConnectionOk(var Error, ResponseText: string): boolean;

begin

with VisualFrame_HTTP_UnitVar do begin


Result:=false;

    try

          ResponseText:=IdHTTP.Get(HTTPServerToRequest+'/testConnection'); // //for example like http://localhost:40000

          if IdHTTP.ResponseCode=200 then// ResponseText='HTTP/1.1 200 OK' then
          Result:=true; // <<<< If Succeded



    except

    on E:Exception do

      begin
      ResponseText:=IdHTTP.ResponseText;

      raise Exception.Create('Server Connection Error '+ E.ClassName + 'error'+E.Message);
      //ShowMessage(E.ClassName + 'error'+E.Message );
      end;


    end;


end;


end;


function THTTPRequests.IsHTTPConnectionOk(): boolean;

begin

with VisualFrame_HTTP_UnitVar do begin


Result:=false;

    try

          IdHTTP.Get(HTTPServerToRequest+'/testConnection'); // //for example like http://localhost:40000

          if IdHTTP.ResponseCode=200 then// ResponseText='HTTP/1.1 200 OK' then
          Result:=true; // <<<< If Succeded



    except

    on E:Exception do

      begin
      IdHTTP.ResponseText;

      raise Exception.
      Create('Server Connection Error '+ E.ClassName + 'error'+E.Message+' ResponseText: '+IdHTTP.ResponseText);

      end;


    end;


end;


end;





//------------------------------------------------------------------


procedure THTTPRequests.SendOneFile(
Filepath:string; dirOnServer: string );

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  ResponseText:string;
  MyServerResponse:string;


begin

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk(Error,ResponseText) then Exit;



                  if FilePath='' then Exit;


                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/sendfile';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');

                    PostData.AddFormField('dirOnServer', dirOnServer);

                    PostData.AddFile('attach', FilePath, 'application/x-rar-compressed');
                  //
                  //  PostData.AddFormField('action', 'post');



                  MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/sendfile', PostData);

                   if MyServerResponse<>'ok' then
                   raise Exception.Create('Server Response '+MyServerResponse);


                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                     //StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                  end;


          end;


    end;


end;



procedure THTTPRequests.SendOneFile(

      AFilepath:string;
      AdirOnServer: string;
      AFileNameOnServer:string

  );

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  ResponseText:string;
  MyServerResponse:string;
  EncodedFileNameOnServer:string;


begin

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk() then Exit;



                  if AFilePath='' then Exit;


                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/sendfile';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');
                    PostData.AddFormField('dirOnServer', AdirOnServer);

                    if FIsKeep2Share then
                    PostData.AddFormField('IsKeep2Share', 'true') else
                    PostData.AddFormField('IsKeep2Share', 'false');


                    PostData.AddFormField('FileNameOnServer',AFileNameOnServer);
                    PostData.AddFile('attach', AFilePath, 'application/x-rar-compressed');


                  MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/sendfile', PostData);

                   if MyServerResponse<>'ok' then
                   raise Exception.Create('Server Response '+MyServerResponse);


                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                    // StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                  end;


          end;


    end;


end;




procedure THTTPRequests.SendOneFileWithoutLog(

      AFilepath:string;
      AdirOnServer: string;
      AFileNameOnServer:string;
      AidUsersString:String

  );

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  ResponseText:string;
  MyServerResponse:string;
  EncodedFileNameOnServer:string;


begin

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk() then Exit;

                  EncodedFileNameOnServer:=TNetEncoding.URL.Encode(AFileNameOnServer);

                  if AFilePath='' then Exit;


                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/sendfilewithoutlog';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');
                    PostData.AddFormField('dirOnServer', AdirOnServer);

                    PostData.AddFormField('FileNameOnServer',EncodedFileNameOnServer);
                    PostData.AddFormField('AidUsersString',AidUsersString);



                    PostData.AddFile('attach', AFilePath, 'application/x-rar-compressed');


                  MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/sendfilewithoutlog', PostData);

                   if MyServerResponse<>'ok' then
                   raise Exception.Create('Server Response '+MyServerResponse);


                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                    // StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                  end;


          end;


    end;


end;



//--------------------------------------------------------------------

procedure THTTPRequests.SendFile2Keep2Share( dirOnServer: string; FileNameOnServer:string; var MyServerResponse:string  );

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  ResponseText:string;

  EncodedFileNameOnServer:string;


begin

    with VisualFrame_HTTP_UnitVar do begin


    begin

          if not IsHTTPConnectionOk(Error,ResponseText) then Exit;


                  PostData := TIdMultiPartFormDataStream.Create;

                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/SendFile2Keep2Share';

                    idHTTP.Request.ContentType := 'multipart/form-data';

                    PostData.AddFormField('Login', 'SomeLogin');
                    PostData.AddFormField('Password', 'SomePassword');

                    PostData.AddFormField('dirOnServer', dirOnServer);
                    PostData.AddFormField('FileNameOnServer',FileNameOnServer);

                    MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/SendFile2Keep2Share', PostData);

                  //  if idHTTP.ResponseCode<>200 then;
                  //  raise Exception.Create('Some Error On Server during SendFile2Keep2Share');

                   // if MyServerResponse<>'ok' then
                   // raise Exception.Create('Server Response '+MyServerResponse);


                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;
                     // ShowMessage('idHTTP Sent OK');
                    // StandartServerResponse:=IdHTTP.Response.ResponseText;//IdHTTP.ResponseText;




                  end;


          end;


    end;


end;





procedure THTTPRequests.SendManyFiles(FilepathesSL:TStringList; dirOnServer: string);

var  i: integer;



begin

    with VisualFrame_HTTP_UnitVar do begin


    if not IsHTTPConnectionOk() then Exit;

       // Sending files here
      for i := 0 to FilepathesSL.Count-1  do

       SendOneFile(FilepathesSL[i],dirOnServer);



    end;


end;
//------------------------------------------------

procedure THTTPRequests.SendManyFiles2(AbsDirOnClient:string; AbsDirOnServer: string);

var

  PostData: TIdMultiPartFormDataStream;
  Error:string;
  StandartServerResponse:string;
  MyServerResponse:string;
  i: integer;

  FilesSDA:TStringDynArray;
  AppPath: string;
  ChunkSize: Int64;
  TotalChunkSizeSent: Int64;
  SplittedString: TArray<String>;

begin

  TotalChunkSizeSent:=0;


  //------------1 GAthering chunk files from dir on Client

   FilesSDA:=TDirectory.GetFiles(AbsDirOnClient);


    with VisualFrame_HTTP_UnitVar do begin


    if not IsHTTPConnectionOk() then Exit;


     for i := 0 to High(FilesSDA) do


        begin

        SendOneFile(FilesSDA[i],AbsDirOnServer);


           // fire event here // Informing how much bytes sent to Server
           //  with VisualFrame_HTTP_UnitVar do begin

                 //Measuring chunks size

                     SplittedString:=FilesSDA[i].Split(['\']);
                     if SplittedString[High(SplittedString)]<>'ChunksInfo.txt' then
                                         { TODO : Check if High(SplittedString) works correct, not High(SplittedString)-1 }

                      begin
                      ChunkSize:=TEtcetra.GetFileSize(FilesSDA[i]);
                      TotalChunkSizeSent:=TotalChunkSizeSent+ChunkSize;
                       end;



                 // firing only unit Event
                 if Assigned(FSendFileInChunks) then
                 if Assigned (FSendFileInChunks.OnUploadInChunks) then
                 FSendFileInChunks.OnUploadInChunks(Self,TotalChunkSizeSent);


                 // firing only unit Event
                 if Assigned(FSendFileInChunks2) then
                 if Assigned (FSendFileInChunks2.OnUploadInChunks) then
                 FSendFileInChunks2.OnUploadInChunks(Self,TotalChunkSizeSent);



        end;






    end;


end;


procedure THTTPRequests.SendChunksInfo(AChunksDir:string; AchunksDirOnServer:string;AFileSize:int64);

var ChunksSDA:TStringDynArray;

    JsonObject:TJsonObject;
    NumberOfChunksAtAll: Integer;
    i: Integer;
    Filename:string;

    CurrentChunkNumber:string;
    ChunksInfoString: string;


    Error:string;
  ResponseText:string;
  PostData: TIdMultiPartFormDataStream;

begin

//-------------1 Gather info about chunks

ChunksSDA:=TDirectory.GetFiles(AChunksDir);
NumberOfChunksAtAll:=Length(ChunksSDA);
JSONObject:=TJSONObject.Create;

      try

      JSONObject.AddPair( (TJSONPair.Create('ChunksNumber',NumberOfChunksAtAll.ToString )) );
      JSONObject.AddPair( (TJSONPair.Create('FileSize',AFileSize.ToString )) );

                for i := 0 to High(ChunksSDA) do

                begin
                Filename:=ExtractFileName(ChunksSDA[i]);
                if not Filename.Contains('chunk')  then Continue;  // All filenames should contain chunk word

                CurrentChunkNumber:=
                TCreateUniqueName.GetParamValueFromFileName(Filename,'chunk');

                JSONObject.AddPair( (TJSONPair.Create(Filename,CurrentChunkNumber )) );

                end;


      ChunksInfoString:=JSONObject.ToString;

      //TFile.WriteAllText('ChunksInfo.txt',ChunksInfoString);


      //-------------2 Sending


                 if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

                  with VisualFrame_HTTP_UnitVar do begin


                  begin


                            PostData := TIdMultiPartFormDataStream.Create;

                            try

                              idHTTP.Request.Referer := HTTPServerToRequest+'/SendChunksInfo'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                              idHTTP.Request.ContentType := 'multipart/form-data';

                              PostData.AddFormField('Login', 'SomeLogin');
                              PostData.AddFormField('Password', 'SomePassword');

                              PostData.AddFormField('ChunksInfoString', ChunksInfoString);
                              PostData.AddFormField('AchunksDirOnServer', AchunksDirOnServer);

                            //  PostData.AddFile('attach', FileName, 'application/x-rar-compressed');
                            //  PostData.AddFormField('action', 'post');

                              idHTTP.Post(HTTPServerToRequest+'/SendChunksInfo', PostData);

                              Application.ProcessMessages;
                            finally

                              if(Assigned(PostData)) then PostData.Free;
                            //    ShowMessage('idHTTP Sent OK');

                            end;



                  end;


              end;

      finally
        FreeAndNil(JSONObject);
      end;

end;



procedure THTTPRequests.
SendChunksInfoInFile(AChunksDir:string; AchunksDirOnServer:string;AFileSize:int64; ChunksInfoFileName:string);

var ChunksSDA:TStringDynArray;

    JsonObject:TJsonObject;
    NumberOfChunksAtAll: Integer;
    i: Integer;
    TempFilename:string;

    CurrentChunkNumber:string;
    ChunksInfoString: string;

    ChunksInfoPath:string;

    Error:string;
    ResponseText:string;
    PostData: TIdMultiPartFormDataStream;

    MyServerResponse:string;

begin

//-------------1 Gather info about chunks

ChunksSDA:=TDirectory.GetFiles(AChunksDir);
NumberOfChunksAtAll:=Length(ChunksSDA);
JSONObject:=TJSONObject.Create;

try

JSONObject.AddPair( (TJSONPair.Create('ChunksNumber',NumberOfChunksAtAll.ToString )) );
JSONObject.AddPair( (TJSONPair.Create('FileSize',AFileSize.ToString )) );

for i := 0 to High(ChunksSDA) do

begin
TempFilename:=ExtractFileName(ChunksSDA[i]);
if not TempFilename.Contains('chunk')  then Continue;  // All filenames should contain chunk word

CurrentChunkNumber:=
TCreateUniqueName.GetParamValueFromFileName(TempFilename,'chunk');  // No errror handling here - could be troubles

JSONObject.AddPair( (TJSONPair.Create(TempFilename,CurrentChunkNumber )) );

end;




ChunksInfoString:=JSONObject.ToString;

ChunksInfoPath:=AChunksDir+'\'+ChunksInfoFileName;//'ChunksInfo.txt';

TFile.WriteAllText(ChunksInfoPath,ChunksInfoString);


//-------------2 Sending


   if not IsHTTPConnectionOk() then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/SendChunksInfo'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');


                PostData.AddFormField('AchunksDirOnServer', AchunksDirOnServer);

                PostData.AddFile('attach', ChunksInfoPath, 'application/x-rar-compressed');




                MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/SendChunksInfo', PostData);

               if MyServerResponse<>'ok' then
               raise Exception.Create('Server Response '+MyServerResponse);


                Application.ProcessMessages;
              finally

                if(Assigned(PostData)) then PostData.Free;
              //    ShowMessage('idHTTP Sent OK');

              end;



    end;


end;

finally
  FreeAndNil(JSONObject);
end;

end;







procedure THTTPRequests.CreateDirOnServer(dir:string);
{Creating dir on Server}

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  MyServerResponse:string;

begin

   if not IsHTTPConnectionOk() then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/CreateDirOnServer'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('DirectoryToCreate', dir);


                MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/CreateDirOnServer', PostData);

                if MyServerResponse<>'ok' then
                raise Exception.Create(MyServerResponse);

                Application.ProcessMessages;


              finally

                if(Assigned(PostData)) then PostData.Free;
              //    ShowMessage('idHTTP Sent OK');

              end;



    end;


end;

end;

//-----------------------------------------------------------------------------------------


procedure THTTPRequests.DeleteDirOnServer(dir:string);

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;
  MyServerResponse:string;


begin

   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/CreateDirOnServer'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('DirectoryToDelete', dir);


                 MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/DeleteDirOnServer', PostData);

                 if MyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+MyServerResponse);

                Application.ProcessMessages;



               
              finally

                if(Assigned(PostData)) then PostData.Free;
              //    ShowMessage('idHTTP Sent OK');

              end;



    end;


end;
end;




procedure THTTPRequests.DeleteFileOnServer(AFilePath:string; AMyServerResponse:string);

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;


begin

   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/DeleteFileOnServer';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('Filepath', AFilePath);



                 AMyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/DeleteFileOnServer', PostData);

                 if AMyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+ AMyServerResponse);

                Application.ProcessMessages;


              finally

                if(Assigned(PostData)) then PostData.Free;

              end;



    end;


end;




end;



procedure THTTPRequests.DeleteFoldersAndFilesOnServerWithDataBase(AIDValuesJSONString:string);

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;
  MyServerResponse:string;

begin

   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/DeleteFoldersAndFilesOnServerWithDataBase';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('AIDValuesJSONString', AIDValuesJSONString);



                 MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/DeleteFoldersAndFilesOnServerWithDataBase', PostData);

                 if MyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+ MyServerResponse);

                Application.ProcessMessages;


              finally

                if(Assigned(PostData)) then PostData.Free;

              end;



    end;


end;




end;






procedure THTTPRequests.DeleteTempFileOnServer(Adir:string; AFileName:string; AMyServerResponse:string);

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;


begin

   if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/DeleteTempFileOnServer';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('dir', Adir);

                PostData.AddFormField('filename',Afilename);


                 AMyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/DeleteTempFileOnServer', PostData);

                 if AMyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+ AMyServerResponse);

                Application.ProcessMessages;


              finally

                if(Assigned(PostData)) then PostData.Free;

              end;



    end;


end;
end;




{Creating CurrentDayDir on Server
Example public/files/User_ID123/2016/10/28
}

procedure THTTPRequests.CreateCurrentDayDirOnServer;

var

  Year, Month, Day : Word;
  dir: string;
  MyServerResponse:string;

begin

  DecodeDate(Now, Year, Month, Day);

  // building dir
  with VisualFrame_HTTP_UnitVar.HTTP_ConnectionParams do
  dir:='public\files\'+User+'_ID'+IDUser+'\'+
  Year.ToString+'\'+
  Month.ToString+'\'+
  Day.ToString;


  CreateDirOnServer(dir);


end;

//------------------------------------------------------------

{Creating CurrentDayDir on Server
Example public/files/User_ID123/2016/10/28
}

procedure THTTPRequests.CreateCurrentDayDirThumbsOnServer;

var

  Year, Month, Day : Word;
  dir: string;
  MyServerResponse:string;


begin

  DecodeDate(Now, Year, Month, Day);

  // buildind dir
  with VisualFrame_HTTP_UnitVar.HTTP_ConnectionParams do
  dir:='public\files\'+User+'_ID'+IDUser+'\'+
  Year.ToString+'\'+
  Month.ToString+'\'+
  Day.ToString+'\'+
  'thumbs';

  CreateDirOnServer(dir);



end;

//---------------------------------------------------------------

{Creates Folder for File Chunks on Server}
procedure THTTPRequests.CreateTempFolderForFileChunks(Filename:string);

var

  Year, Month, Day : Word;
  dir: string;


begin

  DecodeDate(Now, Year, Month, Day);

  // buildind dir
  with VisualFrame_HTTP_UnitVar.HTTP_ConnectionParams do
  dir:='public\files\'+User+'_ID'+IDUser+'\'+
  Year.ToString+'\'+
  Month.ToString+'\'+
  Day.ToString+'\'+
  'temp'+'\'+
  Filename
  ;


CreateDirOnServer(dir);


end;

//-----------------------------------------------------------------

{Deleting Folder for File Chunks on Server}
procedure THTTPRequests.DeleteTempFolderForFileChunks(Filename:string);

var

  Year, Month, Day : Word;
  dir: string;
  MyServerResponse:string;


begin

  DecodeDate(Now, Year, Month, Day);

  // buildind dir
  with VisualFrame_HTTP_UnitVar.HTTP_ConnectionParams do
  dir:='public\files\'+User+'_ID'+IDUser+'\'+
  Year.ToString+'\'+
  Month.ToString+'\'+
  Day.ToString+'\'+
  'temp'+'\'+
  Filename
  ;

DeleteDirOnServer(dir);

end;



procedure THTTPRequests.GatherFileFromChunks(AChunksDirOnServer, AOutPutDirOnServer, AOutPutFileName: string; AidUserString:String);
var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;

  MyServerResponse: string;


begin

   if not IsHTTPConnectionOk() then Exit;

    with VisualFrame_HTTP_UnitVar do begin


    begin


              PostData := TIdMultiPartFormDataStream.Create;

              try

                idHTTP.Request.Referer := HTTPServerToRequest+'/GatherFileFromChunks'; // 'http://localhost:40000/sendfile'; //   http://www.link.net/download';
                idHTTP.Request.ContentType := 'multipart/form-data';

                PostData.AddFormField('Login', 'SomeLogin');
                PostData.AddFormField('Password', 'SomePassword');

                PostData.AddFormField('AChunksDir', AChunksDirOnServer);
                PostData.AddFormField('AOutPutDir', AOutPutDirOnServer);
                PostData.AddFormField('AOutPutFileName', AOutPutFileName);
                PostData.AddFormField('AidUserString', AidUserString);


                 if FIsKeep2Share then
                    PostData.AddFormField('IsKeep2Share', 'true') else
                    PostData.AddFormField('IsKeep2Share', 'false');


              //  PostData.AddFile('attach', FileName, 'application/x-rar-compressed');
              //  PostData.AddFormField('action', 'post');

              MyServerResponse:=idHTTP.Post(HTTPServerToRequest+'/GatherFileFromChunks', PostData);

                if MyServerResponse<>'ok' then
                 raise Exception.Create('Server Response '+MyServerResponse);


              //  Application.ProcessMessages;
              finally

                if(Assigned(PostData)) then PostData.Free;
              //    ShowMessage('idHTTP Sent OK');

              end;



    end;


end;
end;



function StringToOleVariant(const Value: string): OleVariant;
  var Data: PByteArray;
      ss: TStringStream;
begin
  Result:=null;
  if Value='' then Exit;
  ss:=TStringStream.Create(Value);
  try
    Result := VarArrayCreate ([0, ss.Size - 1], varByte);
    Data := VarArrayLock(Result);
    try
      ss.Position := 0;
      ss.ReadBuffer(Data^, ss.Size);
    finally
      VarArrayUnlock(Result);
    end;
  finally
    ss.Free;
  end;
end;



 {Sending PostParams}
procedure THTTPRequests.SendPostParamsForTest;

var
  PostData: TIdMultiPartFormDataStream;
  FileName:string;
  Error:string;
  ResponseText:string;

  RussianWord: string;

begin



    with VisualFrame_HTTP_UnitVar do begin


    begin


      if not IsHTTPConnectionOk(Error,ResponseText) then Exit;

        PostData := TIdMultiPartFormDataStream.Create;




                  try

                    idHTTP.Request.Referer := HTTPServerToRequest+'/SomeURICommand';
                   // idHTTP.Request.ContentType := 'multipart/form-data';

                   idHTTP.Request.ContentType := 'application/x-www-form-urlencoded';





                    RussianWord:=TNetEncoding.URL.Encode('Русское слово'); // IdHTTP.URL.ParamsEncode('Русское слово');



                    PostData.AddFormField('SomePOSTParam1',RussianWord);
                    PostData.AddFormField('SomePOSTParam2','public\files\SomeUser_ID123\2016\11\2\temp\SynKernelD{F1B66A6B-91A3-4D5F-8376-FBCD425CC3CD}.log');


                   // PostData.AddFormField('SomePOSTParam1','SomePostParamValue1');
                   // PostData.AddFormField('SomePOSTParam2','SomePostParamValue2');

                  //  PostData.AddFile('attach', FileName, 'application/x-rar-compressed');
                  //  PostData.AddFormField('field2', 'msg2');
                  //  PostData.AddFormField('action', 'post');

                    idHTTP.Post(HTTPServerToRequest+'/SomeURICommand', PostData);



                    Application.ProcessMessages;
                  finally

                    if(Assigned(PostData)) then PostData.Free;



                    //  ShowMessage('idHTTP Sent OK');

                  end;


    end;


end;
end;







end.
