pnut-bridge/pnut-bridge.go

370 lines
9.2 KiB
Go
Raw Normal View History

2021-07-02 23:32:03 +00:00
package main
import (
"bytes"
"encoding/base64"
2021-07-02 23:32:03 +00:00
"encoding/json"
"flag"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
2021-07-02 23:32:03 +00:00
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
2021-07-02 23:32:03 +00:00
"time"
"git.sr.ht/~thrrgilag/woodstock"
"github.com/gabriel-vasile/mimetype"
2021-07-02 23:32:03 +00:00
"github.com/gorilla/websocket"
"github.com/mitchellh/go-wordwrap"
2021-07-02 23:32:03 +00:00
"gopkg.in/ini.v1"
)
var cfgfile *string
var done chan interface{}
var interrupt chan os.Signal
type Config struct {
PnutAccessToken string `ini:"pnut_access_token"`
PnutUsername string `ini:"pnut_username"`
MbUrl string `ini:"matterbridge_url"`
MbToken string `ini:"matterbridge_token"`
Rooms []Room
}
type Room struct {
ChannelID string `ini:"pnut_channel"`
Gateway string `ini:"gateway"`
}
type Meta struct {
Timestamp int `json:"timestamp"`
Id string `json:"id"`
ChannelType string `json:"channel_type"`
SubscriptionIds []string `json:"subscription_ids"`
Stream Stream `json:"stream"`
ConnectionId string `json:"connection_id"`
}
type Stream struct {
Endpoint string `json:"endpoint"`
}
type Msg struct {
Meta Meta `json:"meta"`
}
type Messages struct {
Meta Meta `json:"meta"`
Data []woodstock.Message `json:"data"`
}
type MbMessage struct {
Text string `json:"text"`
Channel string `json:"channel"`
Username string `json:"username"`
UserID string `json:"userid"`
Avatar string `json:"avatar"`
Account string `json:"account"`
Event string `json:"event"`
Protocol string `json:"protocol"`
Gateway string `json:"gateway"`
ParentID string `json:"parent_id"`
Timestamp string `json:"timestamp"`
ID string `json:"id"`
Extra MbExtra `json"extra"`
}
type MbExtra struct {
File []MbFile `json:"file"`
}
type MbFile struct {
Name string `json:"name"`
Data string `json:"data"`
Comment string `json:"comment"`
URL string `json:"url"`
Size int `json:"size"`
Avatar bool `json:"avatar"`
SHA string `json:"sha"`
}
type MbOutMsg struct {
Text string `json:"text"`
Username string `json:"username"`
Gateway string `json:"gateway"`
}
type PnutOembed struct {
Version string `json:"version"`
Type string `json:"type"`
Title string `json:"title"`
Url string `json:"url"`
Width int `json:"width"`
Height int `json:"height"`
2021-07-02 23:32:03 +00:00
}
func subscribe(connection_id string, access_token string, rooms []Room) {
params := url.Values{}
params.Set("connection_id", connection_id)
for _, _room := range rooms {
log.Printf(">> connecting channel %s ...", _room.ChannelID)
url := "https://api.pnut.io/v1/channels/" + _room.ChannelID + "/messages?" + params.Encode()
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("!! unable to create request", err)
}
req.Header.Set("User-Agent", "pnut-bridge")
req.Header.Add("Authorization", "Bearer "+access_token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("!! error on reponse", err)
}
defer resp.Body.Close()
log.Printf("<< %s", resp.Status)
}
}
func receiveHandler(connection *websocket.Conn, conf *Config) {
defer close(done)
for {
_, msg, err := connection.ReadMessage()
if err != nil {
log.Println("!! error in websocket receive:", err)
return
}
log.Printf("<< received: %s", msg)
var m Msg
if err := json.Unmarshal(msg, &m); err != nil {
log.Println("!! error unmarshaling msg", err)
}
if len(m.Meta.ConnectionId) > 0 {
log.Println("<< connection", m.Meta.ConnectionId)
subscribe(m.Meta.ConnectionId, conf.PnutAccessToken, conf.Rooms)
continue
}
switch m.Meta.ChannelType {
case "io.pnut.core.chat":
var messages Messages
if err := json.Unmarshal(msg, &messages); err != nil {
log.Println("!! error unmarshaling message objects", err)
}
for _, _message := range messages.Data {
pnutMsgHandler(conf, _message)
}
default:
}
}
}
func pnutMsgHandler(conf *Config, msg woodstock.Message) {
gateway := getRoomGateway(conf.Rooms, msg.ChannelID)
if len(gateway) < 1 {
return
}
if msg.User.Username == conf.PnutUsername {
return
}
log.Printf(">> sending message from channel %s to %s ...", msg.ChannelID, gateway)
data := MbOutMsg{
Text: msg.Content.Text,
Username: msg.User.Username,
Gateway: gateway,
}
jsonStr, err := json.Marshal(data)
if err != nil {
log.Println("!! there is a problem creating json string", err)
return
}
url := conf.MbUrl + "/api/message"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
if err != nil {
log.Println("!! unable to create request", err)
}
req.Header.Set("User-Agent", "pnut-bridge")
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
req.Header.Add("Authorization", "Bearer "+conf.MbToken)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("!! error on reponse", err)
}
defer resp.Body.Close()
log.Printf("<< %s", resp.Status)
}
func getRoomGateway(rooms []Room, chan_id string) string {
for _, v := range rooms {
if v.ChannelID == chan_id {
return v.Gateway
}
}
return ""
}
func bridgeMsgHandler(conf *Config, msg MbMessage) {
client := woodstock.NewClient("", "")
client.SetAccessToken(conf.PnutAccessToken)
channel_id := getPnutChannel(conf.Rooms, msg.Gateway)
text := msg.Text
var raw []woodstock.Raw
2021-07-02 23:32:03 +00:00
for _, file := range msg.Extra.File {
fdata, err := base64.StdEncoding.DecodeString(file.Data)
if err != nil {
log.Println("!! error decoding file", err)
}
mtype := mimetype.Detect(fdata)
ir := bytes.NewReader(fdata)
im, _, err := image.DecodeConfig(ir)
if err != nil {
log.Println("Couldn't decode image?", err)
}
if strings.HasPrefix(mtype.String(), "image") {
oembed := PnutOembed{
Version: "1.0",
Type: "photo",
Title: file.Name,
Url: file.URL,
Width: im.Width,
Height: im.Height,
}
raw = append(raw, woodstock.Raw{Type: "io.pnut.core.oembed", Value: oembed})
} else {
text = text + "\n" + file.URL
}
2021-07-02 23:32:03 +00:00
}
maxlen := 2048
prelen := len(msg.Username) + 1
wrapped := wordwrap.WrapString(text, uint(maxlen-prelen))
lines := strings.Split(wrapped, "\n")
for _, line := range lines {
line := msg.Username + " " + line
log.Printf(">> sending message from %s to channel %s ...", msg.Gateway, channel_id)
newmessage := woodstock.NewMessage{Text: line, Raw: raw}
_, err := client.CreateMessage(channel_id, newmessage)
if err != nil {
log.Println("!! problem posting message to pnut.io", err)
}
log.Println("<< ok")
raw = nil
2021-07-02 23:32:03 +00:00
}
}
func getPnutChannel(rooms []Room, gateway string) string {
for _, v := range rooms {
if v.Gateway == gateway {
return v.ChannelID
}
}
return ""
}
func init() {
cfgfile = flag.String("c", "config.ini", "config file")
}
func main() {
flag.Parse()
done = make(chan interface{})
interrupt = make(chan os.Signal)
conf := new(Config)
file, err := ini.Load(*cfgfile)
if err != nil {
log.Printf("!! there was a problem loading the config: %v", err)
os.Exit(1)
}
var rooms []Room
for _, _sec := range file.SectionStrings() {
if _sec == "DEFAULT" {
err = file.Section("DEFAULT").MapTo(conf)
if err != nil {
log.Println("!! unable to map default config section", err)
}
} else {
room := new(Room)
err = file.Section(_sec).MapTo(room)
if err != nil {
log.Printf("!! unable to map config section %s: %v", _sec, err)
}
rooms = append(rooms, *room)
}
}
conf.Rooms = rooms
params := url.Values{}
params.Set("access_token", conf.PnutAccessToken)
socketUrl := "wss://stream.pnut.io/v1/user?" + params.Encode()
conn, _, err := websocket.DefaultDialer.Dial(socketUrl, nil)
if err != nil {
log.Fatal("!! error connectiong to pnut.io:", err)
}
defer conn.Close()
go receiveHandler(conn, conf)
for {
select {
case <-time.After(time.Duration(1) * time.Millisecond * 1000):
err := conn.WriteMessage(websocket.TextMessage, []byte("."))
if err != nil {
2021-08-14 04:31:26 +00:00
log.Fatal("!! error during write to websocket:", err)
2021-07-02 23:32:03 +00:00
}
url := conf.MbUrl + "/api/messages"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("!! unable to create request", err)
}
req.Header.Set("User-Agent", "pnut-bridge")
req.Header.Add("Authorization", "Bearer "+conf.MbToken)
client := &http.Client{
Timeout: 10 * time.Second,
}
2021-07-02 23:32:03 +00:00
resp, err := client.Do(req)
if err != nil {
log.Println(">> error on reponse", err)
}
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
2021-07-02 23:32:03 +00:00
//log.Println("<< ", string([]byte(body)))
var m []MbMessage
jerr := json.Unmarshal(body, &m)
if jerr != nil {
log.Println("Error unmarshaling msg", jerr)
}
if len(m) > 0 {
for _, _m := range m {
bridgeMsgHandler(conf, _m)
}
}
case <-interrupt:
log.Println("Received SIGINT.")
err := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("Error during closing websocket:", err)
return
}
select {
case <-done:
log.Println("Receiver Channel Closed! Exiting...")
case <-time.After(time.Duration(1) * time.Second):
log.Println("Timeout in closing receiving channel. Exiting...")
}
return
}
}
}