StoreBackEnd/pkg/protocol/rules/readers/RetrieveFileRule.go

62 lines
1.8 KiB
Go
Raw Normal View History

package readers
import (
"StoreBackEnd/pkg/protocol"
"StoreBackEnd/pkg/protocol/repository"
"StoreBackEnd/pkg/protocol/rules/writers"
"StoreBackEnd/pkg/utils"
"bufio"
"fmt"
"os"
)
// RetrieveFileRulePrefix Identifiant de cette règle
const RetrieveFileRulePrefix = "RETRIEVEFILE"
// RetrieveFileRule Demande de suppression d'un fichier
type RetrieveFileRule struct {
// Cmd Nom de la règle
Cmd string
// matcher Permet de vérifier le matching
matcher *protocol.RegexMatcher
// protocolRepo Instance de ProtocolRepository
protocolRepo *repository.ProtocolRepository
// storagePath Chemin de stockage du fichier
storagePath string
}
// CreateRetrieveFileRule Création d'une instance de RetrieveFileRule
func CreateRetrieveFileRule(pattern string, protocolRepo *repository.ProtocolRepository, storagePath string) protocol.IProtocolReader {
return &RetrieveFileRule{
Cmd: RetrieveFileRulePrefix,
matcher: protocol.CreateRegexMatcher(pattern),
protocolRepo: protocolRepo,
storagePath: storagePath,
}
}
func (rule RetrieveFileRule) GetCmd() string {
return rule.Cmd
}
func (rule RetrieveFileRule) Execute(data string) (*protocol.ProtocolWriterResult, func(reader *bufio.Reader) *protocol.ProtocolWriterResult) {
if rule.Match(data) {
values := rule.matcher.Parse(data)
hashFileName := values[1]
path := fmt.Sprintf("%s/%s", rule.storagePath, hashFileName)
if fileinfo, err := os.Stat(path); err == nil {
2022-03-15 17:11:31 +01:00
// Retrieve fingerprint sha256
fileFingerprint, err := utils.HashFile(path)
if err == nil {
return rule.protocolRepo.ExecuteWriter(writers.RetrieveOkRulePrefix, hashFileName, fmt.Sprintf("%d", fileinfo.Size()), fileFingerprint), nil
}
}
}
return rule.protocolRepo.ExecuteWriter(writers.RetrieveErrorRulePrefix), nil
}
func (rule RetrieveFileRule) Match(data string) bool {
return rule.matcher.Match(data)
}