-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
175 lines (152 loc) · 4.92 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/caarlos0/env/v8"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/crypto/cryptohelper"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
"maunium.net/go/mautrix/synapseadmin"
"maunium.net/go/mautrix/util"
"maunium.net/go/mautrix/util/dbutil"
_ "maunium.net/go/mautrix/util/dbutil/litestream"
"github.com/beeper/botbot/upgrades"
)
var (
Version = "v0.1.0"
Tag = ""
Commit = ""
BuildTime = ""
)
type Config struct {
HomeserverURL string `env:"HOMESERVER_URL,notEmpty"`
Username string `env:"USERNAME,notEmpty"`
Password string `env:"PASSWORD,notEmpty"`
DatabaseURI string `env:"DATABASE_URI" envDefault:"botbot.db"`
DatabaseType string `env:"DATABASE_TYPE" envDefault:"sqlite3-fk-wal"`
PickleKey string `env:"PICKLE_KEY" envDefault:"meow"`
BeeperAPIURL string `env:"BEEPER_API_URL"`
LoginJWTKey string `env:"LOGIN_JWT_KEY"`
RegisterSecret string `env:"REGISTER_SECRET"`
LogLevel zerolog.Level `env:"LOG_LEVEL" envDefault:"debug"`
MaxBotsPerUser int `env:"MAX_BOTS_PER_USER" envDefault:"10"`
}
var cli *mautrix.Client
var synadm *synapseadmin.Client
var db *Database
var cfg Config
var globalLog = zerolog.New(os.Stdout).With().Timestamp().Logger()
func main() {
if Tag != Version {
if Commit != "" {
Version += "+dev." + Commit[:8]
} else {
Version += "+dev.unknown"
}
}
mautrix.DefaultUserAgent = fmt.Sprintf("botbot/%s %s", Version, mautrix.DefaultUserAgent)
log := globalLog
err := env.ParseWithOptions(&cfg, env.Options{Prefix: "BOTBOT_"})
if err != nil {
log.Fatal().Err(err).Msg("Failed to parse environment variables")
}
log = log.Level(cfg.LogLevel)
globalLog = log
zerolog.TimeFieldFormat = time.RFC3339Nano
zerolog.CallerMarshalFunc = util.CallerWithFunctionName
defaultCtxLog := log.With().Bool("default_context_log", true).Caller().Logger()
zerolog.DefaultContextLogger = &defaultCtxLog
log.Info().
Str("version", Version).
Str("built_at", BuildTime).
Str("mautrix_version", mautrix.VersionWithCommit).
Msg("Initializing botbot")
cli, err = mautrix.NewClient(cfg.HomeserverURL, "", "")
if err != nil {
log.Fatal().Err(err).Msg("Failed to initialize mautrix client")
}
cli.Log = log
synadm = &synapseadmin.Client{Client: cli}
log.Debug().Msg("Initializing database")
rawDB, err := dbutil.NewWithDialect(cfg.DatabaseURI, cfg.DatabaseType)
if err != nil {
log.Fatal().Err(err).Msg("Failed to initialize database")
}
rawDB.Log = dbutil.ZeroLogger(log.With().Str("db_section", "main").Logger())
rawDB.Owner = "botbot"
rawDB.UpgradeTable = upgrades.Table
err = rawDB.Upgrade()
if err != nil {
log.Fatal().Err(err).Msg("Failed to upgrade database")
}
db = &Database{Database: rawDB}
log.Debug().Msg("Initializing crypto helper")
cryptoHelper, err := cryptohelper.NewCryptoHelper(cli, []byte(cfg.PickleKey), rawDB)
if err != nil {
log.Fatal().Err(err).Msg("Failed to create crypto helper")
}
cryptoHelper.LoginAs = &mautrix.ReqLogin{
Type: mautrix.AuthTypePassword,
Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: cfg.Username},
Password: cfg.Password,
}
cryptoHelper.DBAccountID = ""
err = cryptoHelper.Init()
if err != nil {
log.Fatal().Err(err).Msg("Failed to initialize crypto helper")
}
cli.Crypto = cryptoHelper
log.Info().Msg("Initialization complete")
syncer := cli.Syncer.(*mautrix.DefaultSyncer)
syncer.OnEventType(event.StateMember, handleMember)
syncer.OnEventType(event.EventMessage, handleMessage)
syncer.OnSync(cli.MoveInviteState)
cryptoHelper.Machine().SendKeysMinTrust = id.TrustStateCrossSignedTOFU
cryptoHelper.Machine().ShareKeysMinTrust = id.TrustStateCrossSignedTOFU
cryptoHelper.DecryptErrorCallback = func(evt *event.Event, err error) {
_, _ = cli.SendMessageEvent(evt.RoomID, event.EventMessage, &event.MessageEventContent{
MsgType: event.MsgNotice,
Body: "Failed to decrypt message",
RelatesTo: (&event.RelatesTo{}).SetReplyTo(evt.ID),
}, mautrix.ReqSendEvent{DontEncrypt: true})
}
syncCtx, cancelSync := context.WithCancel(context.Background())
var syncStopWait sync.WaitGroup
syncStopWait.Add(1)
go func() {
defer syncStopWait.Done()
log.Debug().Msg("Starting syncing")
err = cli.SyncWithContext(syncCtx)
if err != nil && !errors.Is(err, context.Canceled) {
log.WithLevel(zerolog.FatalLevel).Err(err).Msg("Fatal error in syncer")
cancelSync()
}
}()
go restartSelfDestruct()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
var exitCode int
select {
case <-c:
log.Info().Msg("Interrupt received, stopping...")
case <-syncCtx.Done():
log.Info().Msg("Syncer stopped, stopping...")
exitCode = 2
}
cancelSync()
syncStopWait.Wait()
err = cryptoHelper.Close()
if err != nil {
log.Error().Err(err).Msg("Error closing database")
}
os.Exit(exitCode)
}