Sort events by date

This commit is contained in:
davidnewhall2 2020-06-24 03:11:33 -07:00
parent 724cc6fdfd
commit f32bebec61
2 changed files with 43 additions and 2 deletions

View File

@ -3,6 +3,7 @@ package unifi
import (
"encoding/json"
"fmt"
"sort"
"time"
)
@ -48,7 +49,7 @@ func (u *Unifi) GetSiteEvents(site *Site, hours time.Duration) ([]*Event, error)
params = fmt.Sprintf(`{"_limit":%d,"within":%d,"_sort":"-time"}}`,
eventLimit, int(hours.Round(time.Hour).Hours()))
event struct {
Data []*Event `json:"data"`
Data events `json:"data"`
}
)
@ -63,9 +64,14 @@ func (u *Unifi) GetSiteEvents(site *Site, hours time.Duration) ([]*Event, error)
event.Data[i].SiteName = site.Desc + " (" + site.Name + ")"
}
sort.Sort(event.Data)
return event.Data, nil
}
// Events satisfied the sort.Interface.
type events []*Event
// Event describes a UniFi Event.
// API Path: /api/s/default/stat/event.
type Event struct {
@ -152,6 +158,21 @@ type GeoIP struct {
Organization string `json:"organization"`
}
// Len satisfies sort.Interface.
func (e events) Len() int {
return len(e)
}
// Swap satisfies sort.Interface.
func (e events) Swap(i, j int) {
e[i], e[j] = e[j], e[i]
}
// Less satisfies sort.Interface. Sort our list by date/time.
func (e events) Less(i, j int) bool {
return e[i].Datetime.Before(e[j].Datetime)
}
// UnmarshalJSON is required because sometimes the unifi api returns
// an empty array instead of a struct filled with data.
func (v *IPGeo) UnmarshalJSON(data []byte) error {

View File

@ -3,9 +3,12 @@ package unifi
import (
"encoding/json"
"fmt"
"sort"
"time"
)
type idsList []*IDS
// IDS holds an Intrusion Prevention System Event.
type IDS struct {
Archived FlexBool `json:"archived"`
@ -52,6 +55,21 @@ type IDS struct {
USGIPGeo IPGeo `json:"usgipGeo"`
}
// Len satisfies sort.Interface.
func (e idsList) Len() int {
return len(e)
}
// Swap satisfies sort.Interface.
func (e idsList) Swap(i, j int) {
e[i], e[j] = e[j], e[i]
}
// Less satisfies sort.Interface. Sort our list by Datetime.
func (e idsList) Less(i, j int) bool {
return e[i].Datetime.Before(e[j].Datetime)
}
// GetIDS returns Intrusion Detection Systems events for a list of Sites.
// timeRange may have a length of 0, 1 or 2. The first time is Start, the second is End.
// Events between start and end are returned. End defaults to time.Now().
@ -83,7 +101,7 @@ func (u *Unifi) GetIDSSite(site *Site, timeRange ...time.Time) ([]*IDS, error) {
var (
path = fmt.Sprintf(APIEventPathIDS, site.Name)
ids struct {
Data []*IDS `json:"data"`
Data idsList `json:"data"`
}
)
@ -100,6 +118,8 @@ func (u *Unifi) GetIDSSite(site *Site, timeRange ...time.Time) ([]*IDS, error) {
ids.Data[i].SiteName = site.Desc + " (" + site.Name + ")"
}
sort.Sort(ids.Data)
return ids.Data, nil
}