{ $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence                                   }
{ Team Coherence is Copyright 2002 by Quality Software Components      }
{                                                                      }
{ For further information / comments, visit our WEB site at            }
{ http://www.TeamCoherence.com                                         }
{**********************************************************************}
{}
{ $Log:  13730: IdAttachmentFile.pas 
{
    Rev 1.1    5/9/2003 10:27:20 AM  BGooijen
  Attachment is now opened in fmShareDenyWrite mode
}
{
{   Rev 1.0    11/14/2002 02:12:42 PM  JPMugaas
}
unit IdAttachmentFile;

interface
uses
  IdAttachment, Classes, SysUtils, IdMessageParts;

type
  TIdAttachmentFile = class(TIdAttachment)
  protected
    FTempFileStream: TFileStream;
    FStoredPathName: TFileName;
    FFileIsTempFile: boolean;
  public
    constructor Create(Collection: TIdMessageParts; const AFileName: TFileName = ''); reintroduce;
    destructor Destroy; override;

    function OpenLoadStream: TStream; override;
    procedure CloseLoadStream; override;
    function PrepareTempStream: TStream; override;
    procedure FinishTempStream; override;

    procedure SaveToFile(const FileName: TFileName); override;

    property FileIsTempFile: boolean read FFileIsTempFile write FFileIsTempFile;
    property StoredPathName: TFileName read FStoredPathName write FStoredPathName;
  end;


implementation
uses
  IdCoreGlobal, IdGlobal, IdException, IdResourceStrings;

{ TIdAttachmentFile }

procedure TIdAttachmentFile.CloseLoadStream;
begin
  FreeAndNil(FTempFileStream);
end;

constructor TIdAttachmentFile.Create(Collection: TIdMessageParts; const AFileName: TFileName = '');
begin
  inherited Create(Collection);
  FFilename := ExtractFilename(AFilename);
  FTempFileStream := nil;
  FStoredPathName := AFileName;
  FFileIsTempFile := false;
end;

destructor TIdAttachmentFile.Destroy;
begin
  if FileIsTempFile then begin
    DeleteFile(StoredPathName);
  end;
  inherited;
end;

procedure TIdAttachmentFile.FinishTempStream;
begin
  FreeAndNil(FTempFileStream);
end;

function TIdAttachmentFile.OpenLoadStream: TStream;
begin
  FTempFileStream := TFilestream.Create(StoredPathName, fmOpenRead or fmShareDenyWrite);
  Result := FTempFileStream;
end;

function TIdAttachmentFile.PrepareTempStream: TStream;
begin
  FStoredPathName := MakeTempFilename();
  FTempFileStream := TFilestream.Create(FStoredPathName, fmCreate);
  Result := FTempFileStream;
  FFileIsTempFile := true;
end;

procedure TIdAttachmentFile.SaveToFile(const FileName: TFileName);
begin
  if not CopyFileTo(StoredPathname, FileName) then begin
    raise EIdException.Create(RSTIdMessageErrorSavingAttachment);
  end;
end;

initialization
  RegisterClass(TIdAttachmentFile);
end.
