aboutsummaryrefslogtreecommitdiff
path: root/appservice/server.go
blob: 8e4c263a609c933e08673819ad483fb86f1e5fe5 (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
64
65
66
67
68
69
70
71
72
73
74
package appservice

import (
	"encoding/json"
	"fmt"
	"strings"
	"log"
	"net/http"

	"git.deuxfleurs.fr/Deuxfleurs/easybridge/mxlib"
	"github.com/gorilla/mux"
)

type Config struct {
	HttpBindAddr string
	Server string
	DbType string
	DbPath string
	MatrixDomain string
}


var registration *mxlib.Registration
var config *Config

func Start(r *mxlib.Registration, c *Config) (chan error, error) {
	registration = r
	config = c

	err := InitDb()
	if err != nil {
		return nil, err
	}

	router := mux.NewRouter()
	router.HandleFunc("/_matrix/app/v1/transactions/{txnId}", handleTxn)
	router.HandleFunc("/transactions/{txnId}", handleTxn)

	errch := make(chan error)
	go func() {
		log.Printf("Starting HTTP server on %s", config.HttpBindAddr)
		err := http.ListenAndServe(config.HttpBindAddr, checkTokenAndLog(router))
		if err != nil {
			errch <- err
		}
	}()

	return errch, nil
}

func checkTokenAndLog(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		if strings.Join(r.Form["access_token"], "") != registration.HsToken {
			http.Error(w, "Wrong or no token provided", http.StatusUnauthorized)
			return
		}

		log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
		handler.ServeHTTP(w, r)
	})
}

func handleTxn(w http.ResponseWriter, r *http.Request) {
	var txn mxlib.Transaction
	err := json.NewDecoder(r.Body).Decode(&txn)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
	}

	log.Printf("Got transaction %#v\n", txn)

	fmt.Fprintf(w, "{}\n")
}