summaryrefslogtreecommitdiff
path: root/pkg/api/message.go
blob: 1c28285859c295ae39d37bf4cd7fea12dc4460f1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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) {
	if err := r.ParseForm(); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	form := r.PostForm
	a.savePointMessage(w, form.Get("tmsg"), form.Get("pauth"))
}

func (a *API) getPointHandler(w http.ResponseWriter, r *http.Request) {
	a.savePointMessage(w, r.PathValue("tmsg"), r.PathValue("pauth"))
}

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
}