81 lines
1.6 KiB
Go
81 lines
1.6 KiB
Go
package parser
|
|
|
|
import (
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
type Telegram struct {
|
|
Text string
|
|
Complete bool
|
|
Parsed bool
|
|
Fields []string
|
|
Sequence int
|
|
Type string
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
Start = "ZCZC"
|
|
End = "NNNN"
|
|
TmqRegex = `TMQ(?P<tmq>\d{4})`
|
|
FlopRegex = `^\((?P<flop>\w{3})-.*`
|
|
|
|
TypePLN = "PLN"
|
|
)
|
|
|
|
//Parse
|
|
func Parse(text string) (*Telegram, error) {
|
|
var telegram = &Telegram{Text: text}
|
|
telegram.Complete = isStartAndEnd(text)
|
|
telegram.Fields = strings.Split(strings.Replace(text, "\r\n", "\n", -1), "\n")
|
|
telegram.Fields = clean(telegram.Fields)
|
|
seq := getFields(TmqRegex, telegram.Fields[0])
|
|
telegram.Sequence, _ = strconv.Atoi( seq["tmq"])
|
|
if isPln(*telegram) {
|
|
telegram.Type = TypePLN
|
|
} else if t := getFields(FlopRegex, telegram.Fields[3]); t != nil {
|
|
telegram.Type = t["flop"]
|
|
}
|
|
return telegram, nil
|
|
}
|
|
|
|
func isStartAndEnd(s string) bool {
|
|
text := strings.TrimSpace(s)
|
|
return strings.HasPrefix(text, Start) && strings.HasSuffix(text, End)
|
|
}
|
|
|
|
func clean(fields []string) []string {
|
|
var values []string
|
|
for _, s := range fields {
|
|
values = append(values, strings.TrimSpace(s))
|
|
}
|
|
return values[:len(values)-1]
|
|
}
|
|
|
|
|
|
func getFields(regEx, field string) (fields map[string]string) {
|
|
|
|
var compRegEx = regexp.MustCompile(regEx)
|
|
match := compRegEx.FindStringSubmatch(field)
|
|
|
|
fields = make(map[string]string)
|
|
for i, name := range compRegEx.SubexpNames() {
|
|
if i > 0 && i <= len(match) {
|
|
fields[name] = match[i]
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func isPln(telegram Telegram) bool {
|
|
for _, value := range telegram.Fields {
|
|
if strings.HasPrefix(value, TypePLN) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|