diff options
| author | Xe Iaso <me@xeiaso.net> | 2024-05-24 11:21:40 -0400 |
|---|---|---|
| committer | Xe Iaso <me@xeiaso.net> | 2024-05-24 11:21:40 -0400 |
| commit | 4fe62ffff3d1cae0b9d53f720d8fcc581fdff8db (patch) | |
| tree | b6f920a5ea6bb03d828abca5ab42d6261cdf5a02 | |
| parent | 5d37f3b5cca204d822348a845c1d9dbe8909c66a (diff) | |
| download | xesite-4fe62ffff3d1cae0b9d53f720d8fcc581fdff8db.tar.xz xesite-4fe62ffff3d1cae0b9d53f720d8fcc581fdff8db.zip | |
internal/fly: add flyght tracker API client
Signed-off-by: Xe Iaso <me@xeiaso.net>
| -rw-r--r-- | internal/fly/flyghttracker/flyghttracker.go | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/internal/fly/flyghttracker/flyghttracker.go b/internal/fly/flyghttracker/flyghttracker.go new file mode 100644 index 0000000..4d960cf --- /dev/null +++ b/internal/fly/flyghttracker/flyghttracker.go @@ -0,0 +1,89 @@ +package flyghttracker + +import ( + "encoding/json" + "flag" + "fmt" + "net/http" + "strings" + "time" + + "within.website/x/web" +) + +var ( + flyghttrackerURL = flag.String("flyghttracker-url", "https://flyght-tracker.fly.dev/api/upcoming_events", "Flyghttracker URL") +) + +// Date represents a date in the format "YYYY-MM-DD" +type Date struct { + time.Time +} + +// UnmarshalJSON parses a JSON string in the format "YYYY-MM-DD" to a Date +func (d *Date) UnmarshalJSON(b []byte) error { + s := strings.Trim(string(b), "\"") + t, err := time.Parse("2006-01-02", s) + if err != nil { + return err + } + d.Time = t + return nil +} + +// MarshalJSON returns a JSON string in the format "YYYY-MM-DD" +func (d Date) MarshalJSON() ([]byte, error) { + return json.Marshal(d.Time.Format("2006-01-02")) +} + +// Event represents an event that members of DevRel will be attending. +type Event struct { + Name string `json:"name"` + URL string `json:"url"` + StartDate Date `json:"start_date"` + EndDate Date `json:"end_date"` + Location string `json:"location"` + People []string `json:"people"` +} + +// Fetch new events from the Flyght Tracker URL. +// +// It returns a list of events that end in the future and that have "Xe" as one of the attendees. +func Fetch() ([]Event, error) { + resp, err := http.Get(*flyghttrackerURL) + if err != nil { + return nil, fmt.Errorf("failed to fetch flyghttracker events: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, web.NewError(http.StatusOK, resp) + } + + var events []Event + if err := json.NewDecoder(resp.Body).Decode(&events); err != nil { + return nil, fmt.Errorf("failed to decode flyghttracker events: %w", err) + } + + var result []Event + + for _, event := range events { + if event.EndDate.Before(time.Now()) { + continue + } + + found := false + for _, person := range event.People { + if person == "Xe" { + found = true + break + } + } + + if found { + result = append(result, event) + } + } + + return result, nil +} |
