aboutsummaryrefslogblamecommitdiff
path: root/appservice/server.go
blob: 8e4c263a609c933e08673819ad483fb86f1e5fe5 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

















                                                       
                           
















                                                                            
                                                             


































                                                                                            
                              
 
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")
}