forked from oderwat/slacktogo
/
slacktogo.go
432 lines (366 loc) · 9.03 KB
/
slacktogo.go
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// project main.go
package main
import (
"bitbucket.org/kardianos/osext"
"bitbucket.org/kardianos/service"
"encoding/json"
"fmt"
"github.com/BurntSushi/toml"
"log"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
)
type TeamID string
type TeamName string
type Channel string
type Team struct {
id TeamID
url string
}
type Destination struct {
url string
channel Channel
}
type MappingID struct {
id TeamID
channel Channel
}
// Special Structures for the config parsing
type configTeam struct {
ID TeamID
URL string
}
type configMapping struct {
FromTeam TeamName
FromChannel Channel
ToTeam TeamName
ToChannel Channel
}
type tomlConfig struct {
BindAddr string
Port uint16
SSLCrt string
SSLKey string
Teams map[TeamName]configTeam `toml:"team"`
Mappings []configMapping `toml:"mapping"`
}
var teams = make(map[TeamName]Team)
var team_namen = make(map[TeamID]TeamName)
var mapping = make(map[MappingID][]Destination)
var echos = 0
func AddMapping(from_team TeamName, from_channel Channel, to_team TeamName, to_channel Channel) {
id := MappingID{
id: teams[from_team].id,
channel: from_channel,
}
mapping[id] = append(mapping[id], Destination{
url: teams[to_team].url,
channel: to_channel})
}
func AddTeam(name TeamName, id TeamID, url string) {
teams[name] = Team{
id: id,
url: url}
team_namen[id] = name
}
func NoCache(w http.ResponseWriter) {
h := w.Header()
h.Add("Expires", "Mon, 1 Jan 2000 00:00:00 UTC")
h.Add("Last-Modified", time.Now().UTC().Format(time.RFC1123))
h.Add("Cache-Control", "no-store, no-cache, must-revalidate")
//h.Add("Cache-Control", "post-check=0, pre-check=0");
h.Add("Pragma", "no-cache")
}
func BotAnswers(w http.ResponseWriter, text string) {
/*
// Alternativ, but I do not like it here!
type Answer struct {
Text string `json:"text"`
}
tmp:=Answer{text}
*/
tmp := map[string]interface{}{"text": text}
js, err := json.Marshal(tmp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
return
}
func OnRequest(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
NoCache(w) // well we never want it cached!
team_id := TeamID(r.PostFormValue("team_id"))
if team_id == "" {
w.WriteHeader(http.StatusPreconditionFailed)
fmt.Fprintf(w, "Illegal access to Slackgate... (c) METATEXX GmbH 2014")
return
}
from_channel := Channel("#" + r.PostFormValue("channel_name"))
mapping_id := MappingID{
id: team_id,
channel: from_channel,
}
user_name := r.PostFormValue("user_name")
if user_name == "slackbot" {
echos++
w.WriteHeader(http.StatusNoContent)
return
}
dsts, ok := mapping[mapping_id]
if !ok {
BotAnswers(w, fmt.Sprintf("Unknown Team: %q", mapping_id))
return
}
msg_body := r.PostFormValue("text")
fmt.Printf("%s %s / %s: %q\n", team_id, from_channel, user_name, msg_body)
if msg_body == "+info" {
BotAnswers(w, "This is SlackToGo Server V0.2.1 (c) METATEXX GmbH 2014 - Written by Hans Raaf")
return
}
if msg_body == "+date" {
BotAnswers(w, time.Now().UTC().Format(time.RFC1123))
return
}
if msg_body == "+echos" {
BotAnswers(w, fmt.Sprintf("Echos: %d", echos))
return
}
if msg_body == "+routing" {
out := make([]string, 0)
for mid, maps := range mapping {
if len(out) > 0 {
out = append(out, "")
}
out = append(out, fmt.Sprintf("Routing messages from %q (%s) %s to:", team_namen[mid.id], mid.id, mid.channel))
for idx, dst := range maps {
out = append(out, fmt.Sprintf("> %d: %q @ %q", idx, dst.url, dst.channel))
}
}
BotAnswers(w, strings.Join(out, "\n"))
return
}
for _, dst := range dsts {
payload := map[string]interface{}{
"channel": dst.channel,
"username": fmt.Sprintf("*%s", user_name),
"text": msg_body,
"icon_emoji": ":twisted_rightwards_arrows:"}
js, err := json.Marshal(payload)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
/*
// Alternativ (but I do not really like it
type Payload struct {
Channel Channel `json:"channel"`
Username string `json:"username"`
Text string `json:"text"`
Icon_Emoji string `json:"icon_emoji"`
}
js, _ := json.Marshal(Payload{
dst.channel,
fmt.Sprintf("*%s",user_name),
msg_body,
":twisted_rightwards_arrows:"})
*/
resp, err := http.PostForm(dst.url,
url.Values{"payload": {string(js)}})
if err != nil {
w.Header().Set("Content-Type", "application/json")
tmp := map[string]interface{}{"text": fmt.Sprintf("Error: %q!", err.Error())}
res, _ := json.Marshal(tmp)
fmt.Fprintf(w, string(res))
return
}
if resp.StatusCode != 200 {
fmt.Println(resp)
}
resp.Body.Close()
}
return
}
func checkConfig() {
fmt.Printf("BindAddr: %q\n", config.BindAddr)
fmt.Printf("Port: %d\n", config.Port)
fmt.Printf("SSL Certificate: %q\n", config.SSLCrt)
fmt.Printf("SSL Key: %q\n", config.SSLKey)
fmt.Println("\nTeams:")
for name, team := range config.Teams {
fmt.Printf("%s (%s) %s\n",
name,
team.ID,
team.URL,
)
}
fmt.Println("\nMappings:")
for idx, mapping := range config.Mappings {
fmt.Printf("%d: %s %s -> %s %s\n",
idx,
mapping.FromTeam,
mapping.FromChannel,
mapping.ToTeam,
mapping.ToChannel,
)
}
}
var logit service.Logger
var config tomlConfig
func main() {
// Config Defaults
config.BindAddr = "[::]"
config.Port = 8080
config.SSLCrt = ""
config.SSLKey = ""
// The "go run" command creates the executable in the tmp dir of the system
// the "service" wrapper runs a strange current dir
curdir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
//dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
prgdir, err := osext.ExecutableFolder()
if err != nil {
log.Fatal(err)
}
// trying to find the config file
if _, err := toml.DecodeFile(path.Join(prgdir, "config.toml"), &config); err != nil {
if _, err := toml.DecodeFile(path.Join(curdir, "config.toml"), &config); err != nil {
fmt.Println(err)
return
}
}
// Service Setup
var name = "SlackToGo"
var displayName = "Slack Team Gateway"
var desc = "This Gateway connects two channels on different teams ins slack with each other."
s, err := service.NewService(name, displayName, desc)
logit = s
if err != nil {
fmt.Printf("%s unable to start: %s", displayName, err)
return
}
if len(os.Args) > 1 {
var err error
verb := os.Args[1]
switch verb {
case "install":
err = s.Install()
if err != nil {
fmt.Printf("Failed to install: %s\n", err)
return
}
fmt.Printf("Service %q installed.\n", displayName)
case "remove":
err = s.Remove()
if err != nil {
fmt.Printf("Failed to remove: %s\n", err)
return
}
fmt.Printf("Service %q removed.\n", displayName)
case "start":
err = s.Start()
if err != nil {
fmt.Printf("Failed to start: %s\n", err)
return
}
fmt.Printf("Service %q started.\n", displayName)
case "stop":
err = s.Stop()
if err != nil {
fmt.Printf("Failed to stop: %s\n", err)
return
}
fmt.Printf("Service %q stopped.\n", displayName)
case "restart":
err = s.Stop()
if err != nil {
fmt.Printf("Failed to stop: %s\n", err)
return
}
fmt.Printf("Service %q stopped.\n", displayName)
err = s.Start()
if err != nil {
fmt.Printf("Failed to start: %s\n", err)
return
}
fmt.Printf("Service %q started.\n", displayName)
case "check":
checkConfig()
case "run":
doWork()
}
return
}
err = s.Run(func() error {
// start
go doWork()
return nil
}, func() error {
// stop
stopWork()
return nil
})
if err != nil {
logit.Error(err.Error())
}
}
/*
func msgCreator() {
logit.Info("Notifying all target teams and channels!")
// wait a little moment so the server can start up for sure
time.Sleep(time.Millisecond * 2000)
for _, all := range mapping {
for _, dst := range all {
tmp := map[string]interface{}{
"channel": dst.channel,
"username": "*SlackToGo",
"text": "Up and ready!",
"icon_emoji": ":twisted_rightwards_arrows:" }
res, _ := json.Marshal(tmp)
resp, err := http.PostForm(dst.url,
url.Values{"payload": { string(res)}})
if(err!=nil) {
fmt.Printf("Error: %q!\n",err.Error())
return
}
if (resp.StatusCode != 200) {
fmt.Println(resp)
}
resp.Body.Close();
}
}
}
*/
func doWork() {
logit.Info("SlackToGo Server started!")
// SetupRouting
for name, team := range config.Teams {
AddTeam(name, team.ID, team.URL)
}
for _, mp := range config.Mappings {
AddMapping(mp.FromTeam, mp.FromChannel, mp.ToTeam, mp.ToChannel)
}
//go msgCreator() // will notify every receiver after 5 seconds
http.HandleFunc("/", OnRequest)
if config.SSLCrt == "" || config.SSLKey == "" {
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", config.BindAddr, config.Port),
nil))
} else {
log.Fatal(http.ListenAndServeTLS(fmt.Sprintf("%s:%d", config.BindAddr, config.Port),
config.SSLCrt,
config.SSLKey,
nil))
}
select {}
}
func stopWork() {
logit.Info("SlackToGo Server stopping!")
}