85 lines
2.4 KiB
Go
85 lines
2.4 KiB
Go
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 = "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) {
|
|
|
|
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)
|
|
|
|
if utils.ReceiveFile(path, fileSize, reader) {
|
|
hashCompare, err := utils.HashFileCompare(path, fingerPrint)
|
|
if err == nil && hashCompare {
|
|
return rule.protocolRepo.ExecuteWriter(writers.SendOkRulePrefix)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|