timetable-mgr/cif/parse.go

70 lines
1.8 KiB
Go
Raw Permalink Normal View History

2024-04-03 22:25:27 +01:00
package cif
import (
"encoding/json"
"errors"
"io"
2024-04-03 22:25:27 +01:00
"git.fjla.uk/owlboard/go-types/pkg/upstreamApi"
"git.fjla.uk/owlboard/timetable-mgr/log"
"go.uber.org/zap"
)
2024-04-10 22:59:13 +01:00
// Accepts the CIF data as a stream and outputs parsed data
func parseCifDataStream(dataStream io.ReadCloser) (*ParsedData, error) {
defer dataStream.Close()
2024-04-14 19:03:13 +01:00
log.Debug("Starting CIF Datastream parsing")
if dataStream == nil {
return nil, errors.New("unable to parse nil pointer")
}
var parsed ParsedData
parsed.Assoc = make([]upstreamApi.JsonAssociationV1, 0)
parsed.Sched = make([]upstreamApi.JsonScheduleV1, 0)
// Create JSON Decoder
decoder := json.NewDecoder(dataStream)
// Iterate over JSON Objects using stream decoder
for decoder.More() {
2024-04-03 22:25:27 +01:00
var obj map[string]json.RawMessage
if err := decoder.Decode(&obj); err != nil {
2024-04-14 19:03:13 +01:00
log.Error("Error decoding JSON String")
return nil, err
2024-04-03 22:25:27 +01:00
}
// Handle parsed data
2024-04-03 22:25:27 +01:00
for key, value := range obj {
switch key {
case "JsonTimetableV1":
var timetable upstreamApi.JsonTimetableV1
if err := json.Unmarshal(value, &timetable); err != nil {
2024-04-14 19:03:13 +01:00
log.Error("Error decoding JSONTimetableV1 object", zap.Error(err))
2024-04-03 22:25:27 +01:00
continue
}
parsed.Header = timetable
2024-04-10 23:05:19 +01:00
case "TiplocV1":
// This data is not used and is sourced from CORPUS
continue
2024-04-03 22:25:27 +01:00
case "JsonAssociationV1":
// Association data is not currently used
// but may be used in the future
continue
2024-04-03 22:25:27 +01:00
case "JsonScheduleV1":
var schedule upstreamApi.JsonScheduleV1
if err := json.Unmarshal(value, &schedule); err != nil {
2024-04-14 19:03:13 +01:00
log.Error("Error decoding JSONScheduleV1 object", zap.Error(err))
2024-04-03 22:25:27 +01:00
continue
}
parsed.Sched = append(parsed.Sched, schedule)
case "EOF":
log.Debug("Reached EOF")
2024-04-10 23:05:19 +01:00
default:
2024-04-14 19:03:13 +01:00
log.Warn("Unknown CIF Data type", zap.String("key", key))
2024-04-03 22:25:27 +01:00
}
}
}
2024-04-14 19:03:13 +01:00
log.Debug("CIF Parsing completed")
2024-04-03 22:25:27 +01:00
return &parsed, nil
}