package readers import ( "StoreBackEnd/pkg/protocol" "StoreBackEnd/pkg/protocol/repository" "StoreBackEnd/pkg/protocol/rules/writers" "StoreBackEnd/pkg/utils" "bufio" "fmt" "os" "strconv" ) // SendFileRulePrefix Rule command prefix const SendFileRulePrefix = "ffe_sendfile" // SendFileRule Storage structure for the SendFileRule type SendFileRule struct { // cmd Rule name cmd string // matcher Allow to make a regex match matcher *protocol.RegexMatcher // protocolRepo Instance de ProtocolRepository protocolRepo *repository.ProtocolRepository // storagePath Chemin de stockage du fichier storagePath string } // CreateSendFileRule Creating an instance of SendFileRule func CreateSendFileRule(pattern string, protocolRepo *repository.ProtocolRepository, storagePath string) protocol.IProtocolReader { return &SendFileRule{ cmd: SendFileRulePrefix, matcher: protocol.CreateRegexMatcher(pattern), protocolRepo: protocolRepo, storagePath: storagePath, } } // GetCmd retrieve the command name. func (rule SendFileRule) GetCmd() string { return rule.cmd } // Execute the Rule with a string command. func (rule SendFileRule) Execute(data string) (*protocol.ProtocolWriterResult, func(reader *bufio.Reader) *protocol.ProtocolWriterResult) { println(0) if rule.Match(data) { // TODO : cloture this command. values := rule.matcher.Parse(data) // Values fileName := values[1] fileSize, _ := strconv.Atoi(values[2]) fileContentHash := values[3] // function callback callback := rule.onRead(fileName, fileSize, fileContentHash) return rule.protocolRepo.ExecuteWriter(writers.SendOkRulePrefix), callback } else { return rule.protocolRepo.ExecuteWriter(writers.SendErrorRulePrefix), nil } } func (rule SendFileRule) onRead(fileName string, fileSize int, fingerPrint string) func(reader *bufio.Reader) *protocol.ProtocolWriterResult { return func(reader *bufio.Reader) *protocol.ProtocolWriterResult { path := fmt.Sprintf("%s/%s", rule.storagePath, fileName) hasReceive := utils.ReceiveFile(path, fileSize, reader) // println("OK ", utils.HashFileCompare(path, fingerPrint)) if !hasReceive { os.Remove(path) // Suppression du fichier return rule.protocolRepo.ExecuteWriter(writers.SendErrorRulePrefix) } else { return rule.protocolRepo.ExecuteWriter(writers.SendOkRulePrefix) } } } // Match make a match with the current Rule and check if it matches. func (rule SendFileRule) Match(data string) bool { return rule.matcher.Match(data) }