1
0
mirror of https://github.com/pinpox/gitea-matrix-bot synced 2024-11-22 19:31:58 +01:00
gitea-matrix-bot/giteabot.go

86 lines
1.9 KiB
Go
Raw Normal View History

2019-04-14 22:38:13 +02:00
package main
import (
2019-04-19 11:28:21 +02:00
"crypto/rand"
2019-04-14 22:38:13 +02:00
"fmt"
2019-04-19 21:35:01 +02:00
// "strings"
matrixbot "github.com/binaryplease/matrix-bot"
2019-04-14 22:38:13 +02:00
)
2019-04-14 22:51:52 +02:00
//GiteaBot is the main struct to hold the bot
2019-04-14 22:38:13 +02:00
type GiteaBot struct {
2019-04-14 22:51:52 +02:00
*matrixbot.MatrixBot
//map rooms to tokens
Tokens map[string]string
2019-04-19 21:35:01 +02:00
db *GiteaDB
2019-04-14 22:38:13 +02:00
}
2019-04-14 22:51:52 +02:00
//NewGiteaBot creates a new bot form user credentials
2019-04-19 21:35:01 +02:00
func NewGiteaBot(user, pass string, DBPath string) *GiteaBot {
2019-04-14 22:38:13 +02:00
2019-04-19 21:35:01 +02:00
bot, err := matrixbot.NewMatrixBot(user, pass, "gitea")
2019-04-14 22:38:13 +02:00
if err != nil {
panic(err)
}
2019-04-19 21:35:01 +02:00
db := NewGiteaDB(DBPath)
2019-04-14 22:38:13 +02:00
gbot := &GiteaBot{
bot,
2019-04-19 21:35:01 +02:00
db.GetAll(),
db,
2019-04-14 22:38:13 +02:00
}
2019-04-19 21:35:01 +02:00
bot.RegisterCommand("secret", 0, "Request token for a webhook", gbot.handleCommandSecret)
bot.RegisterCommand("reset", 0, "Delete the room's token", gbot.handleCommandReset)
2019-04-14 22:51:52 +02:00
2019-04-14 22:38:13 +02:00
return gbot
}
2019-04-19 11:28:21 +02:00
func tokenGenerator() string {
//TODO make token length configurable
b := make([]byte, 20)
2019-04-19 11:28:21 +02:00
rand.Read(b)
return fmt.Sprintf("%x", b)
}
2019-04-19 21:35:01 +02:00
func (gb *GiteaBot) checkToken(room, token string) bool {
return token == gb.db.GetToken(room)
}
func (gb *GiteaBot) handleCommandReset(message, room, sender string) {
gb.db.Unset(room, gb.Tokens[room])
_, ok := gb.Tokens[room]
if ok {
delete(gb.Tokens, room)
2019-04-14 22:38:13 +02:00
}
}
func (gb *GiteaBot) handleCommandSecret(message, room, sender string) {
2019-04-14 22:38:13 +02:00
2019-04-20 00:00:09 +02:00
//TODO make the room a parameter (dont use the current room as room)
//Check if room already has a token
if gb.Tokens[room] != "" {
gb.SendToRoom(room, "This room already has a token. Your secert token is:")
gb.SendToRoom(room, gb.Tokens[room])
2019-04-19 21:35:01 +02:00
gb.SendToRoom(room, "To remove all tokens of this room use !gitea reset")
return
2019-04-14 22:38:13 +02:00
}
token := tokenGenerator()
gb.Tokens[room] = token
2019-04-19 21:35:01 +02:00
gb.db.Set(room, token)
2019-04-14 22:38:13 +02:00
gb.SendToRoom(room, "Your secert token is:")
gb.SendToRoom(room, token)
2019-04-14 22:38:13 +02:00
gb.SendToRoom(room, "Set up a weebhook in gitea with that token as secret")
2019-04-14 22:38:13 +02:00
//TODO change this to a real URL or make it configurable
2019-04-19 21:35:01 +02:00
gb.SendToRoom(room, "http://192.168.2.33:9000/post/"+room)
2019-04-14 22:38:13 +02:00
}