mcchunkie/main.go

408 lines
9.5 KiB
Go
Raw Normal View History

package main
import (
"flag"
"fmt"
"log"
2021-03-18 07:54:40 -06:00
"net"
"net/http"
2021-03-18 07:54:40 -06:00
"net/http/pprof"
"os"
"regexp"
2020-02-24 18:05:00 -07:00
"strconv"
"strings"
"time"
"github.com/matrix-org/gomatrix"
"golang.org/x/crypto/bcrypt"
2020-02-11 17:49:33 -07:00
"suah.dev/mcchunkie/plugins"
2020-05-08 16:47:16 -06:00
"suah.dev/protect"
)
2020-03-13 08:08:10 -06:00
const header = `
# mcchunkie
2021-03-19 07:39:37 -06:00
[![builds.sr.ht status](https://builds.sr.ht/~qbit/mcchunkie.svg)](https://builds.sr.ht/~qbit/mcchunkie?)
A [Matrix](https://matrix.org) chat bot.`
2020-03-13 08:08:10 -06:00
func main() {
2021-03-18 07:54:40 -06:00
var username, shortName, password, userID, accessToken, server, db, avatar, botOwner, prof string
var key, value, get string
2020-03-04 07:34:52 -07:00
var setup, doc, verbose bool
flag.BoolVar(&doc, "doc", false, "print plugin information and exit")
flag.BoolVar(&setup, "s", false, "setup account")
2020-03-04 07:34:52 -07:00
flag.BoolVar(&verbose, "v", false, "print verbose messages")
flag.StringVar(&avatar, "avatar", "", "set the avatar of the bot to specified url")
flag.StringVar(&db, "db", "db", "full path to database directory")
flag.StringVar(&get, "get", "", "grab an entry from the store")
flag.StringVar(&key, "key", "", "create an entry in the data store listed under 'key'")
flag.StringVar(&server, "server", "", "matrix server")
flag.StringVar(&username, "user", "", "username to connect to matrix server with")
flag.StringVar(&value, "value", "", "set the value of 'key' to be stored")
2021-03-18 07:54:40 -06:00
flag.StringVar(&prof, "prof", "", "listen string for pprof")
flag.Parse()
2020-05-13 16:54:52 -06:00
_ = protect.Pledge("stdio unveil rpath wpath cpath flock dns inet tty")
_ = protect.Unveil("/etc/resolv.conf", "r")
_ = protect.Unveil("/etc/ssl/cert.pem", "r")
_ = protect.Unveil(db, "rwc")
var err = protect.UnveilBlock()
if err != nil {
log.Fatal(err)
}
var help = `^help: (\w+)$`
var helpRE = regexp.MustCompile(help)
var kvRE = regexp.MustCompile(`^(.+)\s->\s(.+)$`)
2020-05-13 16:56:47 -06:00
store, err := NewStore(db)
if err != nil {
log.Fatalf("%s\n", err)
}
if key != "" && value != "" {
2020-02-05 22:04:04 -07:00
store.Set(key, value)
os.Exit(0)
}
if doc {
2020-03-13 08:08:10 -06:00
fmt.Println(header)
2020-05-13 17:36:26 -06:00
fmt.Println("\n|Plugin Name|Match|Description|")
2020-02-11 07:58:48 -07:00
fmt.Println("|----|---|---|")
for _, p := range plugins.Plugs {
fmt.Printf("|%s|`%s`|%s|\n", p.Name(), strings.ReplaceAll(p.Re(), "|", "\\|"), p.Descr())
}
os.Exit(0)
}
if get != "" {
2020-02-05 22:04:04 -07:00
val, err := store.Get(get)
if err != nil {
log.Fatalf("%s\n", err)
}
fmt.Println(val)
os.Exit(0)
}
if server == "" {
2020-02-05 22:04:04 -07:00
server, err = store.Get("server")
2020-02-10 16:08:33 -07:00
if err != nil {
if err != nil {
log.Fatalf("%s\n", err)
}
}
if server == "" {
log.Fatalln("please specify a server")
}
} else {
2020-02-05 22:04:04 -07:00
store.Set("server", server)
}
log.Printf("connecting to %s\n", server)
2021-03-18 07:54:40 -06:00
if prof != "" {
mux := http.NewServeMux()
mux.Handle("/", http.RedirectHandler("/pprof/", http.StatusSeeOther))
mux.HandleFunc("/pprof/", pprof.Index)
mux.HandleFunc("/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/pprof/profile", pprof.Profile)
mux.HandleFunc("/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/pprof/trace", pprof.Trace)
lis, err := net.Listen("tcp", prof)
if err != nil {
log.Fatalln(err)
}
log.Printf("pprof server listening on %s", lis.Addr())
s := http.Server{Handler: mux}
go func() { log.Println(s.Serve(lis)) }()
}
cli, err := gomatrix.NewClient(
server,
"",
"",
)
2020-02-10 16:08:33 -07:00
if err != nil {
log.Fatalf("%s\n", err)
}
if setup {
log.Println("requesting access token")
password, err = prompt(fmt.Sprintf("Password for '%s': ", username))
if err != nil {
log.Fatalln(err)
}
fmt.Println()
resp, err := cli.Login(&gomatrix.ReqLogin{
Type: "m.login.password",
User: username,
Password: password,
})
if err != nil {
log.Fatalln(err)
}
2020-02-03 20:42:19 -07:00
// No longer need tty now that we have our info
2020-05-13 16:54:52 -06:00
_ = protect.Pledge("stdio unveil rpath wpath cpath flock dns inet")
2020-02-03 20:42:19 -07:00
2020-02-05 22:04:04 -07:00
store.Set("username", username)
store.Set("access_token", resp.AccessToken)
store.Set("user_id", resp.UserID)
accessToken = resp.AccessToken
userID = resp.UserID
} else {
2020-02-05 22:04:04 -07:00
username, _ = store.Get("username")
accessToken, _ = store.Get("access_token")
userID, _ = store.Get("user_id")
2020-02-12 20:11:38 -07:00
botOwner, _ = store.Get("bot_owner")
}
2020-05-13 16:56:03 -06:00
shortName = plugins.NameRE.ReplaceAllString(username, "$1")
cli.SetCredentials(userID, accessToken)
cli.Store = store
syncer := gomatrix.NewDefaultSyncer(username, store)
cli.Client = http.DefaultClient
cli.Syncer = syncer
2020-02-12 20:11:38 -07:00
syncer.OnEventType("m.room.member", func(ev *gomatrix.Event) {
if ev.Sender == username {
return
2020-01-30 06:48:37 -07:00
}
switch ev.Sender {
case botOwner:
if ev.Content["membership"] == "invite" {
log.Printf("Joining %s (invite from %s)\n", ev.RoomID, ev.Sender)
if _, err := cli.JoinRoom(ev.RoomID, "", nil); err != nil {
log.Fatalln(err)
}
return
2020-02-12 20:11:38 -07:00
}
2020-02-01 20:56:55 -07:00
}
2020-02-12 20:11:38 -07:00
})
2020-10-20 18:51:53 -06:00
var gotPort, _ = store.Get("got_listen")
if gotPort != "" {
go func() {
var htpass, _ = store.Get("got_htpass")
var gotRoom, _ = store.Get("got_room")
log.Printf("GOT: listening on %q and sending messages to %q\n", gotPort, gotRoom)
http.HandleFunc("/_got", func(w http.ResponseWriter, r *http.Request) {
var msg string
user, pass, ok := r.BasicAuth()
err := bcrypt.CompareHashAndPassword([]byte(htpass), []byte(pass))
if !(ok && err == nil && user == "got") {
log.Printf("GOT: failed auth '%s'\n", user)
w.Header().Set("WWW-Authenticate", `Basic realm="got notify"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
2020-10-20 18:51:53 -06:00
err = r.ParseForm()
if err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
2020-10-20 18:51:53 -06:00
switch r.Method {
case http.MethodGet:
msg = r.Form.Get("message")
case http.MethodPost:
msg = r.Form.Get("file")
default:
http.Error(
w,
fmt.Sprintf("method %q not implemented", r.Method),
http.StatusMethodNotAllowed,
)
2020-10-20 18:51:53 -06:00
return
}
2020-10-20 18:51:53 -06:00
msg = strings.TrimSuffix(msg, "\n")
2020-10-20 18:51:53 -06:00
if msg == "" {
fmt.Fprintf(w, "empty message")
return
}
2020-10-20 18:51:53 -06:00
for _, line := range strings.Split(msg, "\n") {
log.Printf("GOT: sending '%s'\n", line)
err = plugins.SendUnescNotice(cli, gotRoom, line)
2020-10-20 18:51:53 -06:00
if err != nil {
http.Error(
w,
fmt.Sprintf("can not send commit info: %s", err),
http.StatusInternalServerError,
)
2020-10-20 18:51:53 -06:00
return
}
}
fmt.Fprintf(w, "ok")
2020-10-20 18:51:53 -06:00
})
2020-10-20 18:51:53 -06:00
log.Fatal(http.ListenAndServe(gotPort, nil))
}()
}
2020-02-24 18:05:00 -07:00
go func() {
for {
errataCount := 0
storeCount, _ := store.Get("errata_count")
openbsdRelease, _ := store.Get("openbsd_release")
errataCount, err = strconv.Atoi(storeCount)
2020-02-24 18:05:00 -07:00
got, err := ParseRemoteErrata(
fmt.Sprintf("http://ftp.openbsd.org/pub/OpenBSD/patches/%s/common/",
openbsdRelease,
),
2020-02-24 18:05:00 -07:00
)
if err != nil {
fmt.Println(err)
time.Sleep(2 * time.Hour)
continue
2020-02-24 18:05:00 -07:00
}
2020-03-29 15:42:12 -06:00
l := len(got.List)
2020-02-24 18:05:00 -07:00
if l > errataCount {
alertRooms, _ := store.Get("errata_rooms")
c := 0
2020-03-29 15:42:12 -06:00
for _, erratum := range got.List {
2020-02-24 18:05:00 -07:00
if c+1 > errataCount {
2020-03-29 15:42:12 -06:00
log.Printf("Notifying for erratum %03d\n", erratum.ID)
err = erratum.Fetch()
if err != nil {
fmt.Println(err)
break
}
2020-02-24 18:05:00 -07:00
for _, room := range strings.Split(alertRooms, ",") {
2020-05-13 16:53:31 -06:00
err = plugins.SendMDNotice(cli, room, PrintErrataMD(&erratum))
if err != nil {
fmt.Println(err)
}
2020-02-24 18:05:00 -07:00
}
}
c = c + 1
}
errataCount = l
}
2020-02-26 16:10:43 -07:00
store.Set("errata_count", strconv.Itoa(l))
2020-02-24 18:05:00 -07:00
time.Sleep(2 * time.Hour)
}
}()
syncer.OnEventType("m.room.message", func(ev *gomatrix.Event) {
if ev.Sender == username {
return
}
switch ev.Sender {
case botOwner:
var post string
var ok bool
if post, ok = ev.Body(); !ok {
return
}
if plugins.ToMe(username, post) {
2020-05-13 16:56:03 -06:00
mp := plugins.RemoveName(shortName, post)
if kvRE.MatchString(mp) {
key := kvRE.ReplaceAllString(mp, "$1")
val := kvRE.ReplaceAllString(mp, "$2")
store.Set(key, val)
log.Printf("Setting %q to %q", key, val)
2020-05-13 16:53:31 -06:00
err := plugins.SendMD(cli, ev.RoomID, fmt.Sprintf("Set **%q** = *%q*", key, val))
if err != nil {
log.Println(err)
}
return
}
}
}
// Sending a response per plugin hits issues, so save them and
// send as one message.
2020-05-13 16:57:07 -06:00
var helps []string
2020-01-31 19:57:40 -07:00
for _, p := range plugins.Plugs {
var post string
var ok bool
if post, ok = ev.Body(); !ok {
// Invaild body, for some reason
return
}
if mtype, ok := ev.MessageType(); ok {
switch mtype {
case "m.text":
if helpRE.Match([]byte(post)) {
pn := p.Name()
hName := helpRE.ReplaceAllString(post, "$1")
if hName == pn || hName == "puke" {
helps = append(helps, fmt.Sprintf("**%s**: `%s` - _%s_\n", p.Name(), p.Re(), p.Descr()))
}
}
2020-02-10 17:10:57 -07:00
if p.Match(username, post) {
2020-03-04 07:15:51 -07:00
log.Printf("%s: responding to '%s'", p.Name(), ev.Sender)
2020-02-10 17:10:57 -07:00
p.SetStore(store)
2020-03-04 07:15:51 -07:00
start := time.Now()
2020-05-13 16:53:31 -06:00
err := p.RespondText(cli, ev, username, post)
if err != nil {
fmt.Println(err)
}
2020-03-04 07:15:51 -07:00
elapsed := time.Since(start)
2020-03-04 07:34:52 -07:00
if verbose {
2020-03-04 07:15:51 -07:00
log.Printf("%s took %s to run\n", p.Name(), elapsed)
}
2020-02-10 17:10:57 -07:00
}
}
}
}
if len(helps) > 0 {
2020-05-13 16:53:31 -06:00
err := plugins.SendMD(cli, ev.RoomID, strings.Join(helps, "\n"))
if err != nil {
log.Println(err)
}
}
})
if avatar != "" {
log.Printf("Setting avatar to: '%s'", avatar)
rmu, err := cli.UploadLink(avatar)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = cli.SetAvatarURL(rmu.ContentURI)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Exit(0)
}
for {
log.Println("syncing..")
if err := cli.Sync(); err != nil {
fmt.Println("Sync() returned ", err)
}
time.Sleep(1 * time.Second)
}
}