From d56c89ec2f2950edde4bb02984b142abbf358f04 Mon Sep 17 00:00:00 2001 From: Paul Lecuq Date: Sun, 30 Jan 2022 18:38:03 +0100 Subject: [PATCH] updated ipbl with misc fixes --- src/models/ip.go | 33 +++++++++++++++++++++++++++------ src/routers/funcs.go | 11 ++++++++++- 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/src/models/ip.go b/src/models/ip.go index 69c2533..a3e7452 100644 --- a/src/models/ip.go +++ b/src/models/ip.go @@ -22,6 +22,16 @@ func GetIPs(ctx *context.Context, config *config.Config, limit int) (apimailboxe return } +// GetIPs ... +func GetIPsLastDay(ctx *context.Context, config *config.Config, interval string) (apimailboxes []*api.IP, err error) { + var ips []IP + err = config.Db.Where(fmt.Sprintf("created >= (now()-'%s'::interval)", interval)).Desc("created").Find(&ips) + for _, ml := range ips { + apimailboxes = append(apimailboxes, ml.APIFormat()) + } + return +} + // GetIP ... func GetIP(ctx *context.Context, config *config.Config, ipquery interface{}) (apiip *api.IP, err error) { var ip IP @@ -55,14 +65,25 @@ func (i *IP) InsertIP(cfg *config.Config) (num int64, err error) { } // InsertIPBulk ... -func InsertIPBulk(cfg *config.Config, ips *[]IP) (numinserts int64, numfail int64, err error) { +func InsertIPBulk(cfg *config.Config, ips *[]IP) (numinserts int64, numupdates int64, numfail int64, err error) { for _, ip := range *ips { - num, err := cfg.Db.Insert(ip) - if err != nil { - numfail++ - continue + s_ip := IP{IP: ip.IP} + res, _ := cfg.Db.Get(&s_ip) + if res { + num, err := cfg.Db.ID(s_ip.ID).Update(&s_ip) + if err != nil { + numfail++ + continue + } + numupdates += num + } else { + num, err := cfg.Db.Insert(ip) + if err != nil { + numfail++ + continue + } + numinserts += num } - numinserts += num } return } diff --git a/src/routers/funcs.go b/src/routers/funcs.go index f483228..7254f55 100644 --- a/src/routers/funcs.go +++ b/src/routers/funcs.go @@ -52,6 +52,11 @@ func RegisterRoutes(e *echo.Echo, ctx *context.Context, cfg *config.Config) { ret, err := models.GetIPs(ctx, cfg, limit) return JSONResult(c, err, ret) }) + e.GET("/ips/lastday", func(c echo.Context) (err error) { + interval := "1 day" + ret, err := models.GetIPsLastDay(ctx, cfg, interval) + return JSONResult(c, err, ret) + }) e.POST("/ips", func(c echo.Context) (err error) { var ips = []models.IP{} var msg string @@ -59,11 +64,15 @@ func RegisterRoutes(e *echo.Echo, ctx *context.Context, cfg *config.Config) { if err != nil { return c.JSON(http.StatusInternalServerError, "Error when parsing body") } - numinsert, _, _ := models.InsertIPBulk(cfg, &ips) + numinsert, numupdate, _, _ := models.InsertIPBulk(cfg, &ips) if numinsert > 0 { msg = fmt.Sprintf("Inserted %d IP", numinsert) log.Println(msg) } + if numupdate > 0 { + msg = fmt.Sprintf("Updated %d IP", numupdate) + log.Println(msg) + } return c.JSON(http.StatusOK, msg) }) e.GET("/ips/whitelist", func(c echo.Context) (err error) {