summaryrefslogtreecommitdiff
path: root/handler.go
blob: 61564b875b6766965661bd96521bcbb483bed3c5 (plain)
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
package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"os"
)

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("Wrong URL.")
	w.WriteHeader(400)
	w.Write([]byte("Wrong URL."))
}

func WebhookFailureHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("Getting not-Post request on /webhook")
	w.WriteHeader(400)
	w.Write([]byte("Accepts only POST requests."))
}

func WebhookHandler(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)

	var hook Webhook
	defer r.Body.Close()

	err := decoder.Decode(&hook)
	if err != nil {
		var body string
		content, cError := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Println("Can't read r.Body.", cError)
			body = "Message not readable."
		} else {
			body = string(content)
		}

		log.Print("Wrong JSON.", err, "Original message: "+body)

		w.WriteHeader(400)
		w.Write([]byte("Wrong JSON. " + err.Error() + " Original message: " + body))
		return
	}

	if hook.Join != "" {
		log.Println("Joining #" + hook.Join)
		con.Join("#" + hook.Join)

		log.Println("Sending private message to " + hook.Join + ": " + hook.Message)
		con.Privmsg("#"+hook.Join, hook.Message)

		if fjoin := os.Getenv("WEB2IRC_IRC_JOIN"); fjoin != hook.Join {
			log.Println("Leaving #" + hook.Join)
			con.Part("#" + hook.Join)
		}

		if hook.Target != "" {
			log.Println("Sending private message to " + hook.Target + ": " + hook.Message)
			con.Privmsg(hook.Target, hook.Message)
		}
	} else {
		log.Println("Sending private message to " + hook.Target + ": " + hook.Message)
		con.Privmsg(hook.Target, hook.Message)
	}
}