Files
tele-proc/parser/telegram.go
T

102 lines
2.3 KiB
Go
Raw Normal View History

2020-12-31 14:31:06 +08:00
package parser
2020-12-31 17:57:24 +08:00
import (
"regexp"
"strconv"
"strings"
2021-01-04 15:33:14 +08:00
"time"
2020-12-31 17:57:24 +08:00
)
2020-12-31 14:31:06 +08:00
type Telegram struct {
2021-01-04 15:33:14 +08:00
Text string
Complete bool
Parsed bool
Fields []string
Sequence int
Type string
FlopValue []string
FlightNumber string
RegisterNumber string
Departure string
DepartureTime time.Time
Destination string
DestinationTime time.Time
DateOfFlight time.Time
ParseErrors []error
2020-12-31 14:31:06 +08:00
}
2020-12-31 17:57:24 +08:00
const (
2021-01-04 15:33:14 +08:00
Start = "ZCZC"
End = "NNNN"
2020-12-31 17:57:24 +08:00
TmqRegex = `TMQ(?P<tmq>\d{4})`
)
2020-12-31 14:31:06 +08:00
//Parse
func Parse(text string) (*Telegram, error) {
var telegram = &Telegram{Text: text}
telegram.Complete = isStartAndEnd(text)
2020-12-31 17:57:24 +08:00
telegram.Fields = strings.Split(strings.Replace(text, "\r\n", "\n", -1), "\n")
telegram.Fields = clean(telegram.Fields)
seq := getFields(TmqRegex, telegram.Fields[0])
2021-01-04 15:33:14 +08:00
telegram.Sequence, _ = strconv.Atoi(seq["tmq"])
2020-12-31 17:57:24 +08:00
if isPln(*telegram) {
telegram.Type = TypePLN
2021-01-04 15:33:14 +08:00
} else if flopValues := getFields(FlopRegex, telegram.Text); len(flopValues) > 0 {
telegram.Type = flopValues["flop"]
r := regexp.MustCompile(FlopRegex)
data := r.FindString(telegram.Text)
switch telegram.Type {
case TypeArrival:
parseArr(telegram, data)
}
2020-12-31 17:57:24 +08:00
}
2020-12-31 14:31:06 +08:00
return telegram, nil
}
func isStartAndEnd(s string) bool {
text := strings.TrimSpace(s)
return strings.HasPrefix(text, Start) && strings.HasSuffix(text, End)
}
2020-12-31 17:57:24 +08:00
func clean(fields []string) []string {
var values []string
for _, s := range fields {
values = append(values, strings.TrimSpace(s))
}
return values[:len(values)-1]
}
2021-01-04 15:33:14 +08:00
func getFields(regEx string, field string) (fields map[string]string) {
2020-12-31 17:57:24 +08:00
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
}
2021-01-04 15:33:14 +08:00
func getFlopValues(s string) []string {
// get rid of ()
s = strings.TrimSpace(s)
s = s[1 : len(s)-1]
return strings.Split(s, "-")
}
func parseFlight(s string) (flightNumber string, registerNumber string) {
if l := strings.Index(s, "/"); l > 0 {
return s[0:l], s[l+1:]
2020-12-31 17:57:24 +08:00
}
2021-01-04 15:33:14 +08:00
return s, ""
}
func getAirportAndTime(s string) (airport string, arrivalTime time.Time) {
fields := getFields(DestinationRegex, s)
arrivalTime, _ = time.Parse("1504", fields["time"])
return fields["dest"], arrivalTime
2020-12-31 17:57:24 +08:00
}