unit uHTTPServer_Main;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, IdComponent, IdCustomTCPServer, IdCustomHTTPServer,
  IdHTTPServer, Vcl.StdCtrls,ShellAPI,

  HTTPApp,
  IdMultipartFormData, IdContext, System.IOUtils,
  IdServerIOHandler, IdSSL, IdSSLOpenSSL, IdSSLOpenSSLHeaders, System.json,
  Contnrs,System.NetEncoding,
   RegularExpressions,

  //myUnits
  uDecodePOstRequest,uHTTPServerCommandGet, uDataBaseUnitServer,uGetFoldersAndFiles,
  System.Types,uDeleteServer,uAddFoldersAndFilesToDB,

  Vcl.ExtCtrls, IdIPWatch, IdTCPConnection, IdTCPClient, IdHTTP, Vcl.AppEvnts, System.ImageList, Vcl.ImgList, Vcl.Menus,
  Vcl.ComCtrls
  ;



type

  TfHTTPServer = class(TForm)
    IdServerIOHandlerSSLOpenSSL: TIdServerIOHandlerSSLOpenSSL;
    TrayIcon: TTrayIcon;
    IdIPWatch: TIdIPWatch;
    OpenDialog: TOpenDialog;
    ApplicationEvents: TApplicationEvents;
    ilTrayIcon: TImageList;
    PopupMenu: TPopupMenu;
    pNormalWindow: TMenuItem;
    pExit: TMenuItem;
    PageControl: TPageControl;
    tsMain: TTabSheet;
    tsTest: TTabSheet;
    bToggleStartStopServer: TButton;
    MemoTest: TMemo;
    tsLogging: TTabSheet;
    mmo1: TMemo;
    mmo2: TMemo;
    mmo3: TMemo;
    bTest: TButton;
    lServer: TLabel;
    lProtocol: TLabel;
    eServer: TEdit;
    eProtocol: TEdit;
    lPort: TLabel;
    ePort: TEdit;
    IdHTTPServer: TIdHTTPServer;
    pTopPanelLogging: TPanel;
    cbEnableLogging: TCheckBox;
    lTimeOfWorking: TLabel;
    tWorkingTime: TTimer;
    procedure bToggleStartStopServerClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure IdHTTPServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
      AResponseInfo: TIdHTTPResponseInfo);
    procedure IdServerIOHandlerSSLOpenSSLGetPassword(var Password: string);
    procedure FormDestroy(Sender: TObject);
    procedure IdServerIOHandlerSSLOpenSSLStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string);
    procedure IdServerIOHandlerSSLOpenSSLStatusInfo(const AMsg: string);
    procedure IdServerIOHandlerSSLOpenSSLStatusInfoEx(ASender: TObject; const AsslSocket: PSSL; const AWhere,
      Aret: Integer; const AType, AMsg: string);
    procedure TrayIconClick(Sender: TObject);
    procedure bTestClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure ApplicationEventsMinimize(Sender: TObject);
    procedure TrayIconDblClick(Sender: TObject);
    procedure pExitClick(Sender: TObject);
    procedure pNormalWindowClick(Sender: TObject);
    procedure FormResize(Sender: TObject);
    procedure tWorkingTimeTimer(Sender: TObject);
    procedure cbEnableLoggingClick(Sender: TObject);

  private

    FDataBaseUnitServer:TDataBaseUnitServer;

    FGetFoldersAndFiles:TGetFoldersAndFiles;

    FIsListening:Boolean;

    FHTTPServerCommandGet:THTTPServerCommandGet;

    FDeleteServer:TDelete;

    FAddFoldersAndFilesToDB:TAddFoldersAndFilesToDB;

    FMyIcon:TIcon;

    FStartDateTime:TDateTime;

    procedure OnMinimizeProc(Sender: TObject);
    procedure Tray(n: Integer; Icon: TIcon);

    procedure ArrangeElements;
    procedure AdjustTrayIcon;

  public
    { Public declarations }


    constructor Create(AOwner:TComponent); override;

property  DataBaseUnitServer:TDataBaseUnitServer read FDataBaseUnitServer write FDataBaseUnitServer;
property  DeleteServer:TDelete read FDeleteServer write FDeleteServer;
property  AddFoldersAndFilesToDB:TAddFoldersAndFilesToDB read FAddFoldersAndFilesToDB write FAddFoldersAndFilesToDB;

  end;

var
  fHTTPServer: TfHTTPServer;

implementation

{$R *.dfm}






procedure TfHTTPServer.ApplicationEventsMinimize(Sender: TObject);
begin

  TrayIcon.Visible := True;

  Application.ShowMainForm:=False;


  ShowWindow(Handle, SW_HIDE);

  //TrayIcon.Animate := True;
  //TrayIcon.ShowBalloonHint;


end;

procedure TfHTTPServer.ArrangeElements;
begin

bToggleStartStopServer.Left:=

 Trunc( Self.Width/2 - bToggleStartStopServer.Width/2 );

lTimeOfWorking.Left:=

 Trunc( Self.Width/2 - lTimeOfWorking.Width/2 );


end;

procedure TfHTTPServer.bTestClick(Sender: TObject);



begin

 if OpenDialog.Execute then begin

 if DataBaseUnitServer.FileTypeServer.IsFilePicture(OpenDialog.FileName) then
  ShowMessage('Picture') else ShowMessage('NotPicture');


 end;


end;

procedure TfHTTPServer.bToggleStartStopServerClick(Sender: TObject);
begin

//if FIsListening then

if IdHTTPServer.Active then
    begin

    Self.Caption:=Self.Name+' Server Stopped';
    bToggleStartStopServer.Caption:='Start Server';

    idHTTPServer.Active:=false;
    //FIsListening:=false;
    idHTTPServer.StopListening;

    idHTTPServer.Bindings.Clear;

    tWorkingTime.Enabled:=false;

    end else

    begin

    Self.Caption:=Self.Name+' Server Started';
    bToggleStartStopServer.Caption:='Stop Server';

    //idHTTPServer.StartListening;
    idHTTPServer.Active:=true;
    //FIsListening:=True;

    FStartDateTime:=Now();
    tWorkingTime.Enabled:=True;

    end;


end;


procedure TfHTTPServer.cbEnableLoggingClick(Sender: TObject);
begin
if cbEnableLogging.Checked then

 begin
 mmo1.Lines.Clear;
 mmo2.Lines.Clear;
 mmo3.Lines.Clear;

 cbEnableLogging.Checked:=false;
 end;
end;

constructor TfHTTPServer.Create(AOwner: TComponent);
begin
  inherited;

FDeleteServer:=TDelete.Create(Self);
FAddFoldersAndFilesToDB:=TAddFoldersAndFilesToDB.Create(Self);

Self.WindowState:=wsMinimized;

end;

procedure TfHTTPServer.AdjustTrayIcon;
begin


  //------------ ICON
  TrayIcon.Icons := ilTrayIcon;
  FMyIcon := TIcon.Create;
  FMyIcon.LoadFromFile(ExtractFilePath(Application.ExeName) + 'favicon.ico');
  TrayIcon.Icon.Assign(FMyIcon);
  TrayIcon.Icons.AddIcon(FMyIcon);

  TrayIcon.Hint := 'HTTPServer - Double click to open';
  TrayIcon.BalloonTitle := 'Restoring the window.';
  TrayIcon.BalloonHint := 'Double click the system tray icon to restore the window.';
  Application.ShowMainForm := False;
  TrayIcon.BalloonFlags := bfInfo;

end;

//------------------------------------CREATE DESTROY------------

procedure TfHTTPServer.FormCreate(Sender: TObject);



begin


  idHTTPServer.DefaultPort := 40000;
  idHTTPServer.Active := false;

// Activating Server Here
bToggleStartStopServer.Click;
FIsListening:=true;

//IdHTTPServer.Bindings.Add.Port := 80;
//IdHTTPServer.Bindings.Add.Port := 443;
IdHTTPServer.Bindings.Add.Port := 40000;

FDataBaseUnitServer:=TDataBaseUnitServer.Create(Self);
FGetFoldersAndFiles:=TGetFoldersAndFiles.Create(Self);


FHTTPServerCommandGet:=THTTPServerCommandGet.Create(Self);

 //eServer.Text:=IdIPWatch.LocalIP;

AdjustTrayIcon;



{ Keep2Share

MemoTest
47kefgrm2vlv640f4k8fdut3e1hvv7cpobject(stdClass)#3 (5) {

["status"]=>
  string(7) "success"
  ["success"]=>
  bool(true)

["status_code"]=>
  int(200)
  ["user_file_id"]=>
  string(13)
"77b4f5404a2f8"
  ["link"]=>
  string(32)
"http://k2s.cc/file/77b4f5404a2f8"
}




ReportMemoryLeaksOnShutdown:=true;
end;



procedure TfHTTPServer.FormDestroy(Sender: TObject);
begin
IdHTTPServer.Active:=false; // To Prevent memory leaks

FreeAndNil(FMyIcon);
end;



procedure TfHTTPServer.FormResize(Sender: TObject);
begin
ArrangeElements;
end;

procedure TfHTTPServer.tWorkingTimeTimer(Sender: TObject);

var WorkingTime:TDateTime;

begin

WorkingTime:=Now-FStartDateTime;
lTimeOfWorking.Caption:=FormatDateTime('hh:mm:ss',WorkingTime);

end;

Procedure TfHTTPServer.Tray(n:Integer;Icon:TIcon);
Var Nim:TNotifyIconData;

begin
{
 With Nim do
  Begin
   cbSize:=SizeOf(Nim); //размер структуры
   Wnd:=Self.Handle;    //хендл формы
   uID:=1;
   uFlags:=NIF_ICON or NIF_MESSAGE or NIF_TIP; //флаги
   hicon:=Icon.Handle;  //хендл иконки передаваемой в качестве параметра
   szTip :='ToolTip';      //подсказка
  End;

 Case n OF
  1: Shell_NotifyIcon(Nim_Add,@Nim);         //дабавляем иконку в трей
  2: Shell_NotifyIcon(Nim_Delete,@Nim);      //удаляем
  3: Shell_NotifyIcon(Nim_Modify,@Nim);      //изменяем существующую
 End;
}
 end;


procedure TfHTTPServer.FormShow(Sender: TObject);
begin
//PostMessage(Handle,WM_SYSCOMMAND,SC_MINIMIZE,0);
end;


Procedure TfHTTPServer.OnMinimizeProc(Sender:TObject);
Begin
PostMessage(Handle,WM_SYSCOMMAND,SC_MINIMIZE,0);
End;

procedure TfHTTPServer.pExitClick(Sender: TObject);
begin
Self.Close;
end;

procedure TfHTTPServer.pNormalWindowClick(Sender: TObject);
begin
TrayIconDblClick(Self);
end;

procedure TfHTTPServer.IdHTTPServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
  AResponseInfo: TIdHTTPResponseInfo);


var DecodePostRequest:TDecodePostRequest;
    PostParams:TStringList;
    dir: string;

    ChunksInfo:string;

    DecodedParam:string;
    EncodedParamValue: string;

    AppPath:string;
    filepath: string;
    WebPageContent: string;
    IsWebPage: Boolean;


  URIDecoded:string;

begin



  if ARequestInfo.URI='/testConnection' then

  begin
//  AResponseInfo.ContentText := 'ok';
     AResponseInfo.ResponseNo := 200;
     AResponseInfo.WriteContent;

  end else
//
//  if ARequestInfo.URI='//' then AResponseInfo.ResponseNo := 200;


  if ARequestInfo.URI=('/sendfile') then
  FHTTPServerCommandGet.ReceiveFile(AContext,ARequestInfo,AResponseInfo) else

    if ARequestInfo.URI=('/sendfilewithoutlog') then
  FHTTPServerCommandGet.ReceiveFileWithoutLog(AContext,ARequestInfo,AResponseInfo) else

  if ARequestInfo.URI=('/AddFileToDB') then
  FHTTPServerCommandGet.AddFileToDBResponse(AContext,ARequestInfo,AResponseInfo) else


  if ARequestInfo.URI=('/SendFile2Keep2Share') then
  FHTTPServerCommandGet.SendFile2Keep2Share(AContext,ARequestInfo,AResponseInfo) else

  if ARequestInfo.URI=('/connectToDB') then
   else



if ARequestInfo.URI=('/CreateDirOnServer') then
FHTTPServerCommandGet.CreateDirOnServer(AContext,ARequestInfo,AResponseInfo) else

if ARequestInfo.URI=('/DeleteDirOnServer') then
FHTTPServerCommandGet.DeleteDirOnServer(AContext,ARequestInfo,AResponseInfo) else

if ARequestInfo.URI=('/DeleteTempFileOnServer') then
FHTTPServerCommandGet.DeleteTempFileOnServer(AContext,ARequestInfo,AResponseInfo) else

if ARequestInfo.URI=('/DeleteFileOnServer') then
FHTTPServerCommandGet.DeleteFileOnServer(AContext,ARequestInfo,AResponseInfo) else


if ARequestInfo.URI=('/DeleteFoldersAndFilesOnServerWithDataBase') then
FHTTPServerCommandGet.DeleteFoldersAndFilesOnServerWithDataBase(AContext,ARequestInfo,AResponseInfo) else



if ARequestInfo.URI=('/SendChunksInfo') then
FHTTPServerCommandGet.ReceiveChunksInfo(AContext,ARequestInfo,AResponseInfo,ChunksInfo) else


if ARequestInfo.URI=('/GatherFileFromChunks') then
FHTTPServerCommandGet.GatherFileFromChunks(AContext,ARequestInfo,AResponseInfo) else

if ARequestInfo.URI=('/checkChunksIntegrity') then
FHTTPServerCommandGet.CheckChunksIntegrity(AContext,ARequestInfo,AResponseInfo) else

if ARequestInfo.URI=('/isfileonserver') then
FHTTPServerCommandGet.IsFileOnServer(AContext,ARequestInfo,AResponseInfo) else



if ARequestInfo.URI=('/SomeURICommand') then

   begin

   PostParams:=TStringList.Create;
   PostParams.Clear;
   DecodePostRequest:=TDecodePostRequest.Create(Self);
   DecodePostRequest.DecodePostParamsAnsi(AContext,ARequestInfo,AResponseInfo,PostParams);
   FreeAndNil(DecodePostRequest);



 //  EncodedParamValue:=PostParams.Values['SomePOSTParam1'];

//   EncodedParamValue:=StringReplace(EncodedParamValue,'='#$D#$A'','',[rfReplaceAll]);




//   DecodedParam:=TNetEncoding.URL.Decode(EncodedParamValue);



   ShowMessage(

 //  'SomePOSTParam1='+DecodedParam+

   PostParams.Values['SomePOSTParam1']+

   #13#10+

      'SomePOSTParam2='+

      (PostParams.Values['SomePOSTParam2'])


   );


   FreeAndNil(PostParams);

   end else


    //Preparing file for download if it is on the Server

    begin

     URIDecoded:=TNetEncoding.URL.Decode(ARequestInfo.URI);

    if FHTTPServerCommandGet.IsFileOnServerByURI(URIDecoded,filepath,IsWebPage,WebPageContent) then

     begin

       AResponseInfo.ResponseNo := 200;

       if IsWebPage then
       AResponseInfo.ContentText:=WebPageContent else
       AResponseInfo.ServeFile(AContext, filepath);


     end else


     AresponseInfo.ResponseNo := 404;

    end;


end;


procedure TfHTTPServer.IdServerIOHandlerSSLOpenSSLGetPassword(var Password: string);
begin
Password:='123';
end;

procedure TfHTTPServer.IdServerIOHandlerSSLOpenSSLStatus(ASender: TObject; const AStatus: TIdStatus;
  const AStatusText: string);
begin

if not TFile.Exists('Log.txt') then TFile.Create('Log.txt');


TFile.AppendAllText('Log.txt',' '+AStatusText);


end;

procedure TfHTTPServer.IdServerIOHandlerSSLOpenSSLStatusInfo(const AMsg: string);
begin


if not TFile.Exists('Log.txt') then TFile.Create('Log.txt');


TFile.AppendAllText('Log.txt',' '+AMsg);


end;

procedure TfHTTPServer.IdServerIOHandlerSSLOpenSSLStatusInfoEx(ASender: TObject; const AsslSocket: PSSL; const AWhere,
  Aret: Integer; const AType, AMsg: string);
begin

if not TFile.Exists('Log.txt') then TFile.Create('Log.txt');


TFile.AppendAllText('Log.txt',' '+AMsg);


end;

procedure TfHTTPServer.TrayIconClick(Sender: TObject);
begin

//  TrayIcon.Visible := False;
//  Application.MainForm.Show;



end;

procedure TfHTTPServer.TrayIconDblClick(Sender: TObject);
begin
  { Hide the tray icon and show the window,
  setting its state property to wsNormal. }
  TrayIcon.Visible := False;
  Show();
  WindowState := wsNormal;
  Application.BringToFront();


end;

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






end.
