StoreBackEnd/pkg/protocol/rules/readers/SendFileRule.go
2022-03-12 15:57:27 +01:00

77 lines
2.2 KiB
Go

package readers
import (
"StoreBackEnd/pkg/protocol"
"StoreBackEnd/pkg/protocol/repository"
"StoreBackEnd/pkg/protocol/rules/writers"
"StoreBackEnd/pkg/utils"
"bufio"
"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
}
// CreateSendFileRule Creating an instance of SendFileRule
func CreateSendFileRule(pattern string, protocolRepo *repository.ProtocolRepository) protocol.IProtocolReader {
return &SendFileRule{
cmd: SendFileRulePrefix,
matcher: protocol.CreateRegexMatcher(pattern),
protocolRepo: protocolRepo,
}
}
// 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.
println("OK")
values := rule.matcher.Parse(data)
// Values
fileName := values[1]
fileSize, _ := strconv.Atoi(values[2])
// fileContentHash := values[3]
println(1)
// function callback
callback := rule.onRead(fileName, fileSize)
println(2)
return rule.protocolRepo.ExecuteWriter(writers.SendOkRulePrefix), callback
} else {
return rule.protocolRepo.ExecuteWriter(writers.SendErrorRulePrefix), nil
}
}
func (rule SendFileRule) onRead(fileName string, fileSize int) func(reader *bufio.Reader) *protocol.ProtocolWriterResult {
return func(reader *bufio.Reader) *protocol.ProtocolWriterResult {
hasReceive := utils.ReceiveFile(fileName, fileSize, reader)
println(3)
if !hasReceive {
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)
}