diff --git a/handler/response.go b/handler/response.go index 87f1502..0eb6e57 100644 --- a/handler/response.go +++ b/handler/response.go @@ -171,6 +171,26 @@ func AddNode(c *fiber.Ctx) error { }) } +func GiveJob(c *fiber.Ctx) error { + acceptTor := c.QueryInt("accept_tor", 0) + + moneroRepo := repo.NewMoneroRepo(database.GetDB()) + node, err := moneroRepo.GiveJob(acceptTor) + if err != nil { + return c.JSON(fiber.Map{ + "status": "error", + "message": err.Error(), + "data": nil, + }) + } + + return c.JSON(fiber.Map{ + "status": "ok", + "message": "Success", + "data": node, + }) +} + func Crons(c *fiber.Ctx) error { cronRepo := repo.NewCron(database.GetDB()) diff --git a/handler/routes.go b/handler/routes.go index 235f666..9d46b11 100644 --- a/handler/routes.go +++ b/handler/routes.go @@ -16,5 +16,6 @@ func V1Api(app *fiber.App) { v1.Post("/prober", Prober) v1.Get("/nodes", MoneroNodes) v1.Post("/nodes", AddNode) + v1.Get("/job", GiveJob) v1.Get("/crons", Crons) } diff --git a/internal/repo/monero.go b/internal/repo/monero.go index 57c431c..3b4e4f8 100644 --- a/internal/repo/monero.go +++ b/internal/repo/monero.go @@ -17,6 +17,7 @@ import ( type MoneroRepository interface { Add(protocol string, host string, port uint) error Nodes(q MoneroQueryParams) (MoneroNodes, error) + GiveJob(acceptTor int) (MoneroNode, error) } type MoneroRepo struct { @@ -187,3 +188,34 @@ func (repo *MoneroRepo) Add(protocol string, hostname string, port uint) error { return nil } + +func (repo *MoneroRepo) GiveJob(acceptTor int) (MoneroNode, error) { + queryParams := []interface{}{} + whereQueries := []string{} + where := "" + + if acceptTor != 1 { + whereQueries = append(whereQueries, "is_tor = ?") + queryParams = append(queryParams, 0) + } + + if len(whereQueries) > 0 { + where = "WHERE " + strings.Join(whereQueries, " AND ") + } + + node := MoneroNode{} + + query := fmt.Sprintf(`SELECT id, hostname, port, protocol, is_tor FROM tbl_node %s ORDER BY last_checked ASC LIMIT 1`, where) + err := repo.db.QueryRow(query, queryParams...).Scan(&node.Id, &node.Hostname, &node.Port, &node.Protocol, &node.IsTor) + if err != nil { + return node, err + } + + update := `UPDATE tbl_node SET last_checked = ? WHERE id = ?` + _, err = repo.db.Exec(update, time.Now().Unix(), node.Id) + if err != nil { + return node, err + } + + return node, nil +}