2016-02-09 10:01:05 +00:00
|
|
|
package tg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
)
|
|
|
|
|
2016-02-19 11:20:13 +00:00
|
|
|
// UpdateHandler is an update handler for webhook updates
|
2016-02-09 10:01:05 +00:00
|
|
|
type UpdateHandler func(broker *Broker, message APIMessage)
|
|
|
|
|
2016-02-19 11:20:13 +00:00
|
|
|
// BrokerCallback is a callback for broker responses to client requests
|
|
|
|
type BrokerCallback func(broker *Broker, update BrokerUpdate)
|
|
|
|
|
2016-02-19 11:25:38 +00:00
|
|
|
// CreateBrokerClient creates a connection to a broker and sends all webhook updates to a given function.
|
|
|
|
// This is the intended way to create clients, please refer to examples for how to make a simple client.
|
2017-05-04 14:54:23 +00:00
|
|
|
func CreateBrokerClient(brokerAddr string, updateFn UpdateHandler) error {
|
2016-02-09 10:01:05 +00:00
|
|
|
broker, err := ConnectToBroker(brokerAddr)
|
|
|
|
if err != nil {
|
2017-05-04 14:54:23 +00:00
|
|
|
return err
|
2016-02-09 10:01:05 +00:00
|
|
|
}
|
|
|
|
defer broker.Close()
|
|
|
|
|
2017-05-04 14:54:23 +00:00
|
|
|
return RunBrokerClient(broker, updateFn)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RunBrokerClient is a slimmer version of CreateBrokerClient for who wants to keep its own broker connection
|
|
|
|
func RunBrokerClient(broker *Broker, updateFn UpdateHandler) error {
|
2016-02-09 10:01:05 +00:00
|
|
|
in := bufio.NewReader(broker.Socket)
|
2017-05-04 14:54:23 +00:00
|
|
|
var buf []byte
|
2016-02-09 10:01:05 +00:00
|
|
|
for {
|
2016-02-20 21:28:30 +00:00
|
|
|
bytes, isPrefix, err := in.ReadLine()
|
2016-02-09 10:01:05 +00:00
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
2016-02-20 21:28:30 +00:00
|
|
|
buf = append(buf, bytes...)
|
|
|
|
|
|
|
|
if isPrefix {
|
|
|
|
continue
|
|
|
|
}
|
2016-02-09 10:01:05 +00:00
|
|
|
|
2016-02-19 11:20:13 +00:00
|
|
|
var update BrokerUpdate
|
2016-02-20 21:28:30 +00:00
|
|
|
err = json.Unmarshal(buf, &update)
|
2016-02-09 10:01:05 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("[tg - CreateBrokerClient] ERROR reading JSON: %s\r\n", err.Error())
|
2016-02-20 21:35:26 +00:00
|
|
|
log.Printf("%s\n", string(buf))
|
2016-02-09 10:39:00 +00:00
|
|
|
continue
|
2016-02-09 10:01:05 +00:00
|
|
|
}
|
|
|
|
|
2016-02-19 11:20:13 +00:00
|
|
|
if update.Callback == nil {
|
|
|
|
// It's a generic message: dispatch to UpdateHandler
|
|
|
|
go updateFn(broker, *(update.Message))
|
|
|
|
} else {
|
|
|
|
// It's a response to a request: retrieve callback and call it
|
|
|
|
go broker.SpliceCallback(*(update.Callback))(broker, update)
|
|
|
|
}
|
2016-02-20 21:28:30 +00:00
|
|
|
|
|
|
|
// Empty buffer
|
|
|
|
buf = []byte{}
|
2016-02-09 10:01:05 +00:00
|
|
|
}
|
2017-05-04 14:54:23 +00:00
|
|
|
|
|
|
|
return io.EOF
|
2016-02-09 10:01:05 +00:00
|
|
|
}
|