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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
"os"
)
const TOKEN_FNAME = "tokens.txt"
const SOCKET_DIR = "/srv/apiobot/ch/"
// const SOCKET_DIR = "./socks/"
var CHANNELS = [...]string{"a","b","g"}
var tokens map[string]string
var msg_chs map[string]chan<- beeMsg
func loadTokens() map[string]string {
out := make(map[string]string)
file, err := os.Open(TOKEN_FNAME)
if err != nil {
log.Fatal(err)
}
defer file.Close()
for {
var token, name string
_, err := fmt.Fscanf(file, "%s %s\n", &token, &name)
if err == io.EOF {
break
} else if err != nil {
log.Fatalf("%#v", err)
}
out[token] = name
}
return out
}
type beeMsg struct {
from string
text string
}
func sendSock(msgs <-chan beeMsg, w io.Writer) {
for msg := range msgs {
fmt.Fprintf(w, "%s: %s", msg.from, msg.text)
}
}
func handleHttp(w http.ResponseWriter, r *http.Request) {
tok := r.FormValue("key")
msg := r.FormValue("message")
irc_ch := r.FormValue("channel")
if tok == "" {
w.WriteHeader(400)
fmt.Fprintln(w,"missing key")
return
}
if msg == "" {
w.WriteHeader(400)
fmt.Fprintln(w,"missing message")
return
}
clientname, ok := tokens[tok]
if !ok {
w.WriteHeader(401)
fmt.Fprintln(w,"bad key")
return
}
if len(msg) > 300 {
w.WriteHeader(400)
fmt.Fprintln(w,"msg too long")
return
}
if irc_ch == "" {
irc_ch = "a"
}
msg_ch, ok := msg_chs[irc_ch]
if !ok {
w.WriteHeader(400)
fmt.Fprintf(w,"invalid channel name, valid channels are %v.",CHANNELS)
return
}
msg_ch <- beeMsg{from: clientname, text:msg}
}
func init() {
tokens = loadTokens()
msg_chs = make(map[string]chan<- beeMsg)
for _,ch := range CHANNELS {
sock, err := net.Dial("unixgram", SOCKET_DIR+ch+".sock")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
mc := make(chan beeMsg)
msg_chs[ch] = mc
go sendSock(mc, sock)
}
}
func main() {
fmt.Println("ok")
http.HandleFunc("/", handleHttp)
log.Fatal(http.ListenAndServe(":3236", nil))
}
|