hook2xmpp/git/main.go

82 lines
1.9 KiB
Go
Raw Normal View History

2017-06-10 16:07:23 +02:00
package git
import (
2019-02-13 03:24:38 +01:00
"fmt"
2019-02-13 03:55:07 +01:00
2017-06-10 16:07:23 +02:00
"net/http"
libHTTP "dev.sum7.eu/genofire/golang-lib/http"
2019-02-13 03:55:07 +01:00
"github.com/bdlm/log"
2019-02-13 04:52:00 +01:00
"github.com/mitchellh/mapstructure"
2019-07-15 23:57:26 +02:00
"gosrc.io/xmpp"
2017-06-10 16:07:23 +02:00
2019-08-08 15:49:25 +02:00
"dev.sum7.eu/sum7/hook2xmpp/runtime"
2017-06-10 16:07:23 +02:00
)
var eventHeader = map[string]string{
"X-GitHub-Event": "X-Hub-Signature",
"X-Gogs-Event": "X-Gogs-Delivery",
}
2017-06-10 16:07:23 +02:00
2019-02-13 03:55:07 +01:00
const hookType = "git"
2019-02-13 03:24:38 +01:00
func init() {
2019-07-15 23:57:26 +02:00
runtime.HookRegister[hookType] = func(client xmpp.Sender, hooks []runtime.Hook) func(w http.ResponseWriter, r *http.Request) {
2019-02-13 04:52:00 +01:00
log.WithField("type", hookType).Info("loaded")
2019-02-13 03:24:38 +01:00
return func(w http.ResponseWriter, r *http.Request) {
2019-02-13 03:55:07 +01:00
logger := log.WithField("type", hookType)
2019-02-13 03:24:38 +01:00
event := ""
secret := ""
for head, headSecret := range eventHeader {
2019-02-13 03:24:38 +01:00
event = r.Header.Get(head)
if event != "" {
secret = r.Header.Get(headSecret)
2019-02-13 03:24:38 +01:00
break
}
}
2019-02-13 03:55:07 +01:00
var body map[string]interface{}
libHTTP.Read(r, &body)
if s, ok := body["secret"]; ok && secret == "" {
secret = s.(string)
}
if event == "" || secret == "" {
logger.Warnf("no secret or event found")
http.Error(w, fmt.Sprintf("no secret or event found"), http.StatusNotFound)
return
}
2019-02-13 04:32:06 +01:00
var request requestBody
if err := mapstructure.Decode(body, &request); err != nil {
logger.Errorf("no readable payload: %s", err)
2019-02-13 03:55:07 +01:00
http.Error(w, fmt.Sprintf("no readable payload"), http.StatusInternalServerError)
return
}
2019-02-13 04:32:06 +01:00
logger = logger.WithFields(map[string]interface{}{
2019-02-13 04:52:00 +01:00
"url": request.Repository.URL,
2019-02-13 04:32:06 +01:00
"msg": request.String(event),
})
2019-02-13 03:24:38 +01:00
2019-02-13 04:32:06 +01:00
ok := false
2019-07-15 23:57:26 +02:00
msg := request.String(event)
2019-02-13 03:24:38 +01:00
for _, hook := range hooks {
if secret != hook.Secret {
2019-02-13 03:24:38 +01:00
continue
}
2019-02-13 03:55:07 +01:00
logger.Infof("run hook")
2019-07-15 23:57:26 +02:00
runtime.Notify(client, hook, msg, msg)
2019-02-13 03:24:38 +01:00
ok = true
}
if !ok {
2019-02-13 03:55:07 +01:00
logger.Warnf("no hook found")
2019-02-13 04:52:00 +01:00
http.Error(w, fmt.Sprintf("no configuration for %s for url: %s", hookType, request.Repository.URL), http.StatusNotFound)
2019-02-13 03:24:38 +01:00
}
2017-06-10 16:07:23 +02:00
}
}
}