Moved to zerolog, linting fixes, update Drone configuration.
This commit is contained in:
@@ -18,7 +18,6 @@
|
||||
package matrixpusher
|
||||
|
||||
import (
|
||||
// local
|
||||
"go.dev.pztrn.name/opensaps/context"
|
||||
pusherinterface "go.dev.pztrn.name/opensaps/pushers/interface"
|
||||
)
|
||||
|
@@ -18,7 +18,6 @@
|
||||
package matrixpusher
|
||||
|
||||
import (
|
||||
// stdlib
|
||||
"bytes"
|
||||
crand "crypto/rand"
|
||||
"encoding/json"
|
||||
@@ -28,7 +27,6 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
// local
|
||||
slackmessage "go.dev.pztrn.name/opensaps/slack/message"
|
||||
)
|
||||
|
||||
@@ -40,9 +38,10 @@ const (
|
||||
)
|
||||
|
||||
type MatrixMessage struct {
|
||||
MsgType string `json:"msgtype"`
|
||||
Body string `json:"body"`
|
||||
Format string `json:"format"`
|
||||
MsgType string `json:"msgtype"`
|
||||
Body string `json:"body"`
|
||||
Format string `json:"format"`
|
||||
// nolint:tagliatelle
|
||||
FormattedBody string `json:"formatted_body"`
|
||||
}
|
||||
|
||||
@@ -65,14 +64,14 @@ type MatrixConnection struct {
|
||||
|
||||
// nolint
|
||||
func (mxc *MatrixConnection) doPostRequest(endpoint string, data string) ([]byte, error) {
|
||||
c.Log.Debugln("Data to send:", data)
|
||||
c.Log.Debug().Msgf("Data to send: %+v", data)
|
||||
|
||||
apiRoot := mxc.apiRoot + endpoint
|
||||
if mxc.token != "" {
|
||||
apiRoot += fmt.Sprintf("?access_token=%s", mxc.token)
|
||||
}
|
||||
|
||||
c.Log.Debugln("Request URL:", apiRoot)
|
||||
c.Log.Debug().Msgf("Request URL: %s", apiRoot)
|
||||
|
||||
req, _ := http.NewRequest("POST", apiRoot, bytes.NewBuffer([]byte(data)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
@@ -98,14 +97,14 @@ func (mxc *MatrixConnection) doPostRequest(endpoint string, data string) ([]byte
|
||||
|
||||
// nolint
|
||||
func (mxc *MatrixConnection) doPutRequest(endpoint string, data string) ([]byte, error) {
|
||||
c.Log.Debugln("Data to send:", data)
|
||||
c.Log.Debug().Msgf("Data to send: %+v", data)
|
||||
|
||||
apiRoot := mxc.apiRoot + endpoint
|
||||
if mxc.token != "" {
|
||||
apiRoot += fmt.Sprintf("?access_token=%s", mxc.token)
|
||||
}
|
||||
|
||||
c.Log.Debugln("Request URL:", apiRoot)
|
||||
c.Log.Debug().Msgf("Request URL: %s", apiRoot)
|
||||
|
||||
req, _ := http.NewRequest("PUT", apiRoot, bytes.NewBuffer([]byte(data)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
@@ -129,15 +128,19 @@ func (mxc *MatrixConnection) doPutRequest(endpoint string, data string) ([]byte,
|
||||
return nil, errors.New("Status: " + resp.Status + ", body: " + string(body))
|
||||
}
|
||||
|
||||
// This function should be rewritten, I think.
|
||||
// nolint
|
||||
func (mxc *MatrixConnection) generateTnxID() string {
|
||||
// Random tnxid - 16 chars.
|
||||
length := 16
|
||||
|
||||
result := make([]byte, length)
|
||||
// ToDo: figure out why this was ever needed and fix it.
|
||||
bufferSize := int(float64(length) * 1.3)
|
||||
|
||||
// Making sure that we have only letters and numbers and resulted
|
||||
// string will be exactly requested length.
|
||||
// I'm sorry for this shitty code.
|
||||
for i, j, randomBytes := 0, 0, []byte{}; i < length; j++ {
|
||||
if j%bufferSize == 0 {
|
||||
randomBytes = mxc.generateTnxIDSecureBytes(bufferSize)
|
||||
@@ -154,11 +157,10 @@ func (mxc *MatrixConnection) generateTnxID() string {
|
||||
|
||||
func (mxc *MatrixConnection) generateTnxIDSecureBytes(length int) []byte {
|
||||
// Get random bytes.
|
||||
var randomBytes = make([]byte, length)
|
||||
randomBytes := make([]byte, length)
|
||||
|
||||
_, err := crand.Read(randomBytes)
|
||||
if err != nil {
|
||||
c.Log.Fatalln("Unable to generate random bytes for transaction ID!")
|
||||
if _, err := crand.Read(randomBytes); err != nil {
|
||||
c.Log.Fatal().Msg("Unable to generate random bytes for transaction ID!")
|
||||
}
|
||||
|
||||
return randomBytes
|
||||
@@ -172,15 +174,15 @@ func (mxc *MatrixConnection) Initialize(connName string, apiRoot string, user st
|
||||
mxc.roomID = roomID
|
||||
mxc.token = ""
|
||||
|
||||
c.Log.Debugln("Trying to connect to", mxc.connName, "("+apiRoot+")")
|
||||
c.Log.Debug().Str("conn", mxc.connName).Str("api_root", apiRoot).Msg("Trying to connect server")
|
||||
|
||||
loginStr := fmt.Sprintf(`{"type": "m.login.password", "user": "%s", "password": "%s"}`, mxc.username, mxc.password)
|
||||
|
||||
c.Log.Debugln("Login string:", loginStr)
|
||||
c.Log.Debug().Msgf("Login string: %s", loginStr)
|
||||
|
||||
reply, err := mxc.doPostRequest("/login", loginStr)
|
||||
if err != nil {
|
||||
c.Log.Fatalf("Failed to login to Matrix with user '%s' (conn %s): '%s'", mxc.username, mxc.connName, err.Error())
|
||||
c.Log.Fatal().Msgf("Failed to login to Matrix with user '%s' (conn %s): '%s'", mxc.username, mxc.connName, err.Error())
|
||||
}
|
||||
|
||||
// Parse received JSON and get access token.
|
||||
@@ -188,22 +190,24 @@ func (mxc *MatrixConnection) Initialize(connName string, apiRoot string, user st
|
||||
|
||||
err1 := json.Unmarshal(reply, &data)
|
||||
if err1 != nil {
|
||||
c.Log.Fatalf("Failed to parse received JSON from Matrix for user '%s' (conn %s): %s (data was: %s)",
|
||||
mxc.username, mxc.connName, err1.Error(), reply)
|
||||
c.Log.Fatal().
|
||||
Str("username", mxc.username).
|
||||
Str("conn", mxc.connName).
|
||||
Err(err).
|
||||
Msgf("Failed to parse received JSON from Matrix: %s)", reply)
|
||||
}
|
||||
|
||||
mxc.token = data["access_token"].(string)
|
||||
mxc.deviceID = data["deviceID"].(string)
|
||||
mxc.token, _ = data["access_token"].(string)
|
||||
mxc.deviceID, _ = data["deviceID"].(string)
|
||||
|
||||
c.Log.Debugf("Login successful for conn '%s', access token is '%s', our deviceID is '%s'",
|
||||
mxc.connName, mxc.token, mxc.deviceID)
|
||||
c.Log.Debug().Str("conn", mxc.connName).Str("access_token", mxc.token).Str("device_id", mxc.deviceID).Msg("Login successful")
|
||||
|
||||
// We should check if we're already in room and, if not, join it.
|
||||
// We will do this by simply trying to join. We don't care about reply
|
||||
// here.
|
||||
_, err2 := mxc.doPostRequest("/rooms/"+mxc.roomID+"/join", "{}")
|
||||
if err2 != nil {
|
||||
c.Log.Fatalf("Failed to join room: %s", err2.Error())
|
||||
c.Log.Fatal().Err(err).Msg("Failed to join room")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,20 +217,20 @@ func (mxc *MatrixConnection) ProcessMessage(message slackmessage.SlackMessage) {
|
||||
// Prepare message body.
|
||||
messageData := c.SendToParser(message.Username, message)
|
||||
|
||||
messageToSend := messageData["message"].(string)
|
||||
messageToSend, _ := messageData["message"].(string)
|
||||
// We'll use HTML, so reformat links accordingly (if any).
|
||||
linksRaw, linksFound := messageData["links"]
|
||||
if linksFound {
|
||||
links := linksRaw.([][]string)
|
||||
links, _ := linksRaw.([][]string)
|
||||
for _, link := range links {
|
||||
messageToSend = strings.Replace(messageToSend, link[0], `<a href="`+link[1]+`">`+link[2]+`</a>`, -1)
|
||||
messageToSend = strings.ReplaceAll(messageToSend, link[0], `<a href="`+link[1]+`">`+link[2]+`</a>`)
|
||||
}
|
||||
}
|
||||
|
||||
// "\n" should be "<br>".
|
||||
messageToSend = strings.Replace(messageToSend, "\n", "<br>", -1)
|
||||
messageToSend = strings.ReplaceAll(messageToSend, "\n", "<br>")
|
||||
|
||||
c.Log.Debugln("Crafted message:", messageToSend)
|
||||
c.Log.Debug().Msgf("Crafted message: %s", messageToSend)
|
||||
|
||||
// Send message.
|
||||
mxc.SendMessage(messageToSend)
|
||||
@@ -234,19 +238,21 @@ func (mxc *MatrixConnection) ProcessMessage(message slackmessage.SlackMessage) {
|
||||
|
||||
// This function sends already prepared message to room.
|
||||
func (mxc *MatrixConnection) SendMessage(message string) {
|
||||
c.Log.Debugf("Sending message to connection '%s': '%s'", mxc.connName, message)
|
||||
c.Log.Debug().Str("conn", mxc.connName).Msgf("Sending message: '%s'", message)
|
||||
|
||||
// We should send notices as it is preferred behavior for bots and
|
||||
// appservices.
|
||||
msg := MatrixMessage{}
|
||||
msg.MsgType = "m.notice"
|
||||
msg.Body = message
|
||||
msg.Format = "org.matrix.custom.html"
|
||||
msg.FormattedBody = message
|
||||
msg := MatrixMessage{
|
||||
MsgType: "m.notice",
|
||||
Body: message,
|
||||
Format: "org.matrix.custom.html",
|
||||
FormattedBody: message,
|
||||
}
|
||||
|
||||
msgBytes, err := json.Marshal(&msg)
|
||||
if err != nil {
|
||||
c.Log.Errorln("Failed to marshal message into JSON:", err.Error())
|
||||
c.Log.Error().Err(err).Msg("Failed to marshal message into JSON.")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -254,20 +260,20 @@ func (mxc *MatrixConnection) SendMessage(message string) {
|
||||
|
||||
reply, err := mxc.doPutRequest("/rooms/"+mxc.roomID+"/send/m.room.message/"+mxc.generateTnxID(), msgStr)
|
||||
if err != nil {
|
||||
c.Log.Fatalf("Failed to send message to room '%s' (conn: '%s'): %s", mxc.roomID, mxc.connName, err.Error())
|
||||
c.Log.Fatal().Str("conn", mxc.connName).Str("room", mxc.roomID).Err(err).Msg("Failed to send message to room")
|
||||
}
|
||||
|
||||
c.Log.Debugf("Message sent, reply: %s", string(reply))
|
||||
c.Log.Debug().Msgf("Message sent, reply: %s", string(reply))
|
||||
}
|
||||
|
||||
func (mxc *MatrixConnection) Shutdown() {
|
||||
c.Log.Infof("Shutting down connection '%s'...", mxc.connName)
|
||||
c.Log.Info().Str("conn", mxc.connName).Msg("Shutting down connection...")
|
||||
|
||||
_, err := mxc.doPostRequest("/logout", "{}")
|
||||
if err != nil {
|
||||
c.Log.Errorf("Error occurred while trying to log out from Matrix (conn %s): %s", mxc.connName, err.Error())
|
||||
c.Log.Error().Err(err).Str("conn", mxc.connName).Msg("Error occurred while trying to log out from Matrix.")
|
||||
}
|
||||
|
||||
mxc.token = ""
|
||||
c.Log.Infof("Connection '%s' successfully shutted down", mxc.connName)
|
||||
c.Log.Info().Str("conn", mxc.connName).Msg("Connection successfully shutted down")
|
||||
}
|
||||
|
@@ -19,18 +19,18 @@ package matrixpusher
|
||||
|
||||
import slackmessage "go.dev.pztrn.name/opensaps/slack/message"
|
||||
|
||||
// local
|
||||
|
||||
type MatrixPusher struct{}
|
||||
|
||||
func (mp MatrixPusher) Initialize() {
|
||||
c.Log.Infoln("Initializing Matrix protocol pusher...")
|
||||
c.Log.Info().Msg("Initializing Matrix protocol pusher...")
|
||||
|
||||
// Get configuration for pushers and initialize every connection.
|
||||
cfg := c.Config.GetConfig()
|
||||
for name, config := range cfg.Matrix {
|
||||
c.Log.Infof("Initializing connection: '%s'", name)
|
||||
c.Log.Info().Str("conn", name).Msg("Initializing connection...")
|
||||
|
||||
// Fields will be filled with conn.Initialize().
|
||||
// nolint:exhaustivestruct
|
||||
conn := MatrixConnection{}
|
||||
connections[name] = &conn
|
||||
|
||||
@@ -41,16 +41,17 @@ func (mp MatrixPusher) Initialize() {
|
||||
func (mp MatrixPusher) Push(connection string, data slackmessage.SlackMessage) {
|
||||
conn, found := connections[connection]
|
||||
if !found {
|
||||
c.Log.Errorf("Connection not found: '%s'!", connection)
|
||||
c.Log.Error().Str("conn", connection).Msg("Connection not found!")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
c.Log.Debugf("Pushing data to '%s'", connection)
|
||||
c.Log.Debug().Str("conn", connection).Msg("Pushing data to connection")
|
||||
conn.ProcessMessage(data)
|
||||
}
|
||||
|
||||
func (mp MatrixPusher) Shutdown() {
|
||||
c.Log.Infoln("Shutting down Matrix pusher...")
|
||||
c.Log.Info().Msg("Shutting down Matrix pusher...")
|
||||
|
||||
for _, conn := range connections {
|
||||
conn.Shutdown()
|
||||
|
Reference in New Issue
Block a user