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

85 lines
2.4 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"
"strconv"
)
// SendFileRulePrefix Rule command prefix
2022-03-14 11:10:23 +01:00
const SendFileRulePrefix = "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) {
2022-03-20 15:32:45 +01:00
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)
2022-03-15 20:27:49 +01:00
2022-03-15 17:11:31 +01:00
if utils.ReceiveFile(path, fileSize, reader) {
hashCompare, err := utils.HashFileCompare(path, fingerPrint)
if err == nil && hashCompare {
return rule.protocolRepo.ExecuteWriter(writers.SendOkRulePrefix)
}
}
2022-03-15 20:27:49 +01:00
2022-03-15 17:11:31 +01:00
os.Remove(path)
return rule.protocolRepo.ExecuteWriter(writers.SendErrorRulePrefix)
}
}
// 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)
}