Moved to zerolog, linting fixes, update Drone configuration.

This commit is contained in:
2021-11-21 16:16:10 +05:00
parent c6c3e2e76f
commit 46aee4d2ab
27 changed files with 258 additions and 169 deletions

View File

@@ -18,7 +18,6 @@
package pusherinterface
import (
// local
slackmessage "go.dev.pztrn.name/opensaps/slack/message"
)

View File

@@ -18,7 +18,6 @@
package matrixpusher
import (
// local
"go.dev.pztrn.name/opensaps/context"
pusherinterface "go.dev.pztrn.name/opensaps/pushers/interface"
)

View File

@@ -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")
}

View File

@@ -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()

View File

@@ -18,7 +18,6 @@
package telegrampusher
import (
// local
"go.dev.pztrn.name/opensaps/context"
pusherinterface "go.dev.pztrn.name/opensaps/pushers/interface"
)

View File

@@ -18,13 +18,11 @@
package telegrampusher
import (
// stdlib
"fmt"
"net/http"
"net/url"
"strings"
// local
configstruct "go.dev.pztrn.name/opensaps/config/struct"
slackmessage "go.dev.pztrn.name/opensaps/slack/message"
)
@@ -41,17 +39,17 @@ func (tc *TelegramConnection) 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>`)
}
}
c.Log.Debugln("Crafted message:", messageToSend)
c.Log.Debug().Msgf("Crafted message: %s", messageToSend)
// Send message.
tc.SendMessage(messageToSend)
@@ -64,8 +62,10 @@ func (tc *TelegramConnection) SendMessage(message string) {
msgdata.Set("parse_mode", "HTML")
// Are we should use proxy?
// nolint:exhaustivestruct
httpTransport := &http.Transport{}
// nolint:nestif
if tc.config.Proxy.Enabled {
// Compose proxy URL.
proxyURL := "http://"
@@ -82,27 +82,30 @@ func (tc *TelegramConnection) SendMessage(message string) {
proxyURLParsed, err := url.Parse(proxyURL)
if err != nil {
c.Log.Errorln("Error while constructing/parsing proxy URL:", err.Error())
c.Log.Error().Err(err).Msg("Error while constructing/parsing proxy URL")
} else {
httpTransport.Proxy = http.ProxyURL(proxyURLParsed)
}
}
// nolint:exhaustivestruct
client := &http.Client{Transport: httpTransport}
botURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", tc.config.BotID)
c.Log.Debugln("Bot URL:", botURL)
c.Log.Debug().Msgf("Bot URL: %s", botURL)
// ToDo: fix it.
// nolint
response, err := client.PostForm(botURL, msgdata)
if err != nil {
c.Log.Errorln("Error occurred while sending data to Telegram:", err.Error())
c.Log.Error().Err(err).Msg("Error occurred while sending data to Telegram")
} else {
c.Log.Debugln("Status:", response.Status)
if response.StatusCode != 200 {
c.Log.Debug().Msgf("Status: %s", response.Status)
if response.StatusCode != http.StatusOK {
body := []byte{}
_, _ = response.Body.Read(body)
response.Body.Close()
c.Log.Debugln(body)
c.Log.Debug().Msg(string(body))
}
}
}

View File

@@ -18,20 +18,20 @@
package telegrampusher
import (
// local
slackmessage "go.dev.pztrn.name/opensaps/slack/message"
)
type TelegramPusher struct{}
func (tp TelegramPusher) Initialize() {
c.Log.Infoln("Initializing Telegram protocol pusher...")
c.Log.Info().Msg("Initializing Telegram protocol pusher...")
// Get configuration for pushers and initialize every connection.
cfg := c.Config.GetConfig()
for name, config := range cfg.Telegram {
c.Log.Infof("Initializing connection: '%s'", name)
c.Log.Info().Str("conn", name).Msg("Initializing connection...")
// nolint:exhaustivestruct
conn := TelegramConnection{}
connections[name] = &conn
@@ -42,16 +42,17 @@ func (tp TelegramPusher) Initialize() {
func (tp TelegramPusher) 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")
conn.ProcessMessage(data)
}
func (tp TelegramPusher) Shutdown() {
c.Log.Infoln("Shutting down Telegram pusher...")
c.Log.Info().Msg("Shutting down Telegram pusher...")
for _, conn := range connections {
conn.Shutdown()