idecnode/pkg/api/message.go

69 lines
1.5 KiB
Go
Raw Normal View History

2024-10-20 03:39:07 +03:00
package api
import (
"encoding/base64"
"fmt"
"log"
"net/http"
"strings"
)
func (a *API) getBundleHandler(w http.ResponseWriter, r *http.Request) {
ids := strings.Split(r.PathValue("ids"), "/")
for _, messageID := range ids {
msg, err := a.idec.GetMessage(messageID)
if err != nil {
log.Println("cant read file for message", messageID, err)
continue
}
b64msg := base64.StdEncoding.EncodeToString([]byte(msg.Bundle()))
fmt.Fprintf(w, "%s:%s\n", messageID, b64msg)
}
}
func (a *API) getMessageHandler(w http.ResponseWriter, r *http.Request) {
msgID := r.PathValue("msgID")
msg, err := a.idec.GetMessage(msgID)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
_, err = fmt.Fprintln(w, msg.Bundle())
}
func (a *API) postPointHandler(w http.ResponseWriter, r *http.Request) {
msg, pauth := r.PathValue("tmsg"), r.PathValue("pauth")
2024-10-20 03:39:07 +03:00
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
2024-10-20 03:39:07 +03:00
form := r.PostForm
if form.Has("tmsg") {
msg = form.Get("tmsg")
}
if form.Has("pauth") {
pauth = form.Get("pauth")
}
2024-10-20 03:39:07 +03:00
a.savePointMessage(w, msg, pauth)
2024-10-20 03:39:07 +03:00
}
func (a *API) savePointMessage(w http.ResponseWriter, rawMessage, auth string) error {
point, err := a.idec.GetPointByAuth(auth)
if err != nil {
fmt.Fprintln(w, "error: no auth - wrong authstring")
return err
}
if err := a.idec.SavePointMessage(point.Username, rawMessage); err != nil {
return err
}
fmt.Fprintln(w, "msg ok")
return nil
}