aboutsummaryrefslogblamecommitdiff
path: root/appservice/server.go
blob: 395d3836a5d7c7f35b2b46b8ad7e3b9551e633e8 (plain) (tree)







































































                                                                                            
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
}


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)

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