2019-05-06 01:40:41 +03:00
|
|
|
package routes
|
2019-05-05 23:36:49 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
|
2019-05-06 01:40:41 +03:00
|
|
|
"github.com/n1try/wakapi/services"
|
2019-05-09 01:07:38 +03:00
|
|
|
"github.com/n1try/wakapi/utils"
|
2019-05-06 01:40:41 +03:00
|
|
|
|
2019-05-05 23:36:49 +03:00
|
|
|
"github.com/n1try/wakapi/models"
|
|
|
|
)
|
|
|
|
|
2019-05-06 01:40:41 +03:00
|
|
|
type HeartbeatHandler struct {
|
|
|
|
HeartbeatSrvc *services.HeartbeatService
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HeartbeatHandler) Post(w http.ResponseWriter, r *http.Request) {
|
2019-05-19 20:49:27 +03:00
|
|
|
if r.Method != http.MethodPost {
|
|
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
2019-05-05 23:36:49 +03:00
|
|
|
return
|
|
|
|
}
|
2019-05-09 01:07:38 +03:00
|
|
|
|
2019-05-17 09:40:03 +03:00
|
|
|
var heartbeats []*models.Heartbeat
|
2019-05-11 18:49:56 +03:00
|
|
|
user := r.Context().Value(models.UserKey).(*models.User)
|
2019-05-09 01:07:38 +03:00
|
|
|
opSys, editor, _ := utils.ParseUserAgent(r.Header.Get("User-Agent"))
|
|
|
|
|
2019-05-05 23:36:49 +03:00
|
|
|
dec := json.NewDecoder(r.Body)
|
2019-05-11 18:49:56 +03:00
|
|
|
if err := dec.Decode(&heartbeats); err != nil {
|
2019-05-19 20:49:27 +03:00
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
2019-05-05 23:36:49 +03:00
|
|
|
w.Write([]byte(err.Error()))
|
|
|
|
return
|
|
|
|
}
|
2019-05-11 18:49:56 +03:00
|
|
|
|
2019-05-17 09:40:03 +03:00
|
|
|
for _, h := range heartbeats {
|
2019-05-09 01:07:38 +03:00
|
|
|
h.OperatingSystem = opSys
|
|
|
|
h.Editor = editor
|
2019-05-11 18:49:56 +03:00
|
|
|
h.User = user
|
|
|
|
h.UserID = user.ID
|
|
|
|
|
|
|
|
if !h.Valid() {
|
2019-05-19 20:49:27 +03:00
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
2019-05-11 18:49:56 +03:00
|
|
|
w.Write([]byte("Invalid heartbeat object."))
|
|
|
|
return
|
|
|
|
}
|
2019-05-09 01:07:38 +03:00
|
|
|
}
|
2019-05-05 23:36:49 +03:00
|
|
|
|
2019-05-17 09:40:03 +03:00
|
|
|
if err := h.HeartbeatSrvc.InsertBatch(heartbeats); err != nil {
|
2019-05-19 20:49:27 +03:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2019-05-05 23:36:49 +03:00
|
|
|
os.Stderr.WriteString(err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-05-19 20:49:27 +03:00
|
|
|
w.WriteHeader(http.StatusOK)
|
2019-05-05 23:36:49 +03:00
|
|
|
}
|