-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
executable file
·343 lines (295 loc) · 9.45 KB
/
main.go
File metadata and controls
executable file
·343 lines (295 loc) · 9.45 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package main
import (
"flag"
"fmt"
_ "net/http/pprof"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
"ChatWire/banlist"
"ChatWire/cfg"
"ChatWire/commands"
"ChatWire/constants"
"ChatWire/cwlog"
"ChatWire/disc"
"ChatWire/fact"
"ChatWire/factUpdater"
"ChatWire/glob"
"ChatWire/modupdate"
"ChatWire/support"
"ChatWire/util"
)
var (
discordConnectAttempts int
messageHandlerLock sync.Mutex
botReadyAdded bool
hooksAdded bool
)
func main() {
glob.DoRegisterCommands = flag.Bool("regCommands", false, "Register discord commands")
glob.DoDeregisterCommands = flag.Bool("deregCommands", false, "Deregister discord commands and quit.")
glob.LocalTestMode = flag.Bool("localTest", false, "Disable public/auth mode for testing")
glob.NoAutoLaunch = flag.Bool("noAutoLaunch", false, "Disable auto-launch")
glob.NoDiscord = flag.Bool("noDiscord", false, "Disable Discord")
cleanDB := flag.Bool("cleanDB", false, "Clean/minimize player database and exit.")
cleanBans := flag.Bool("cleanBans", false, "Clean/minimize player database, along with bans and exit.")
glob.ProxyURL = flag.String("proxy", "", "http caching proxy url. Request format: proxy/http://example.doamin/path")
flag.Parse()
/* Start cw logs */
cwlog.StartCWLog()
cwlog.StartAuditLog()
cwlog.AutoRotateLogs()
cwlog.DoLogCW("\n Starting %v Version: %v", constants.ProgName, constants.Version)
initTime()
if !*glob.LocalTestMode {
checkLockFile()
}
initMaps()
readConfigs()
modupdate.ReadModHistory()
if *cleanDB || *cleanBans {
fact.LoadPlayers(false, true, *cleanBans)
fact.WritePlayers()
fmt.Println("Database cleaned.")
_ = os.Remove("cw.lock")
return
}
/* Start Discord bot, don't wait for it.
* We want Factorio online even if Discord is down. */
if !*glob.NoDiscord {
go startbotA()
}
fact.LoadPlayers(true, false, false)
disc.ReadRoleList()
banlist.ReadBanFile(true)
fact.ReadVotes()
cwlog.StartGameLog()
if !*glob.NoDiscord {
go support.MainLoops()
go support.HandleChat()
}
//If autolaunch is off, get current factorio version
if cfg.Local.Options.AutoStart && !*glob.NoAutoLaunch {
fact.SetAutolaunch(true, false)
} else if *glob.NoAutoLaunch {
info := &factUpdater.InfoData{Xreleases: cfg.Local.Options.ExpUpdates, Build: "headless", Distro: "linux64"}
factUpdater.GetFactorioVersion(info)
fact.FactorioVersion = info.VersInt.IntToString()
cwlog.DoLogCW("Factorio version: " + fact.FactorioVersion)
}
usr1c := make(chan os.Signal, 1)
signal.Notify(usr1c, syscall.SIGUSR1)
go func() {
for range usr1c {
if !fact.QueueReboot {
fact.QueueReboot = true
cwlog.DoLogCW("SIGUSR1 received, reboot queued.")
} else {
cwlog.DoLogCW("SIGUSR1 received, reboot already queued.")
}
}
}()
usr2c := make(chan os.Signal, 1)
signal.Notify(usr2c, syscall.SIGUSR2)
go func() {
for range usr2c {
support.ReloadConfigFiles("SIGUSR2")
}
}()
/* Wait here for process signals */
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sc
_ = os.Remove("cw.lock")
fact.SetAutolaunch(false, false)
glob.DoRebootCW = false
fact.QueueReboot = false
fact.QueueFactReboot = false
fact.QuitFactorio("Server quitting...")
fact.WaitFactQuit(false)
fact.DoExit(false)
}
func startbotA() {
/* Check if Discord token is set */
if cfg.Global.Discord.Token == "" {
cwlog.DoLogCW("Discord token not set, not starting.")
return
}
/* Attempt to start bot */
cwlog.DoLogCW("Starting Discord bot...")
bot, erra := discordgo.New("Bot " + cfg.Global.Discord.Token)
/*
* If we fail, keep attempting with increasing delay and maximum tries
* We do this, in case there is a failure.
* Discord will invalidate the token if there are too many connection attempts.
*/
if erra != nil {
cwlog.DoLogCW("An error occurred when attempting to CREATE the Discord session. Details: %v", erra)
time.Sleep(time.Duration(discordConnectAttempts*5) * time.Second)
discordConnectAttempts++
if discordConnectAttempts < constants.MaxDiscordAttempts {
go startbotA()
}
return
}
startbotB(bot)
}
func startbotB(bot *discordgo.Session) {
/* We need a few intents to detect discord users and roles */
bot.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsAllWithoutPrivileged | discordgo.IntentsGuildPresences | discordgo.IntentsGuildMembers)
/* This is called when the connection is verified */
if !botReadyAdded {
botReadyAdded = true
bot.AddHandler(botReady)
}
errb := bot.Open()
/* This handles error after the initial connection */
if errb != nil {
cwlog.DoLogCW("An error occurred when attempting to OPEN the Discord session. Details: %v", errb)
time.Sleep(time.Duration(discordConnectAttempts*5) * time.Second)
discordConnectAttempts++
if discordConnectAttempts < constants.MaxDiscordAttempts {
go startbotB(bot)
}
return
}
/* This drastically reduces log spam */
bot.LogLevel = discordgo.LogWarning
}
func botReady(s *discordgo.Session, r *discordgo.Ready) {
if s != nil {
/* Save Discord descriptor, we need it */
disc.DS = s
}
/* Set the bot's Discord status message */
botstatus := cfg.Global.Paths.URLs.Domain
errc := s.UpdateGameStatus(0, botstatus)
if errc != nil {
cwlog.DoLogCW(errc.Error())
}
/* Register discord slash commands */
go func() {
commands.DeregisterCommands()
commands.RegisterCommands()
}()
/* Message and command hooks */
if !hooksAdded {
hooksAdded = true
s.AddHandler(handleDiscordMessages)
s.AddHandler(commands.SlashCommand)
}
go func() {
/* Update the string for the channel name and topic */
fact.UpdateChannelName()
/* Send the new string to discord */
fact.DoUpdateChannelNameForce()
}()
cwlog.DoLogCW("Discord bot ready.")
if cfg.Local.Channel.ChatChannel == "" || cfg.Local.Channel.ChatChannel == "MY DISCORD CHANNEL ID" {
cwlog.DoLogCW("No chat channel set, attempting to creating one.")
chname := fmt.Sprintf("%v-%v", cfg.Local.Callsign, cfg.Local.Name)
channelid, err := s.GuildChannelCreate(cfg.Global.Discord.Guild, chname, discordgo.ChannelTypeGuildText)
if err != nil {
cwlog.DoLogCW("Couldn't create chat channel: %v", err)
return
} else if channelid != nil {
cwlog.DoLogCW("Created chat channel.")
cfg.Local.Channel.ChatChannel = channelid.ID
cfg.WriteLCfg()
}
return
}
//Only on first connect
if !support.BotIsReady {
glob.SetBootMessage(disc.SmartEditDiscordEmbed(cfg.Local.Channel.ChatChannel, glob.GetBootMessage(), "Status", constants.ProgName+" "+constants.Version+" is now online.", glob.COLOR_GREEN))
if fact.FactIsRunning || fact.FactorioBooted {
glob.SetBootMessage(disc.SmartEditDiscordEmbed(cfg.Local.Channel.ChatChannel, glob.GetBootMessage(), "Ready", "Factorio "+fact.FactorioVersion+" is online.", glob.COLOR_GREEN))
}
}
//Reset attempt count, we are fully connected.
discordConnectAttempts = 0
support.BotIsReady = true
}
func checkLockFile() {
/* Handle lock file */
bstr, err := os.ReadFile("cw.lock")
if err == nil {
lastTimeStr := strings.TrimSpace(string(bstr))
lastTime, err := time.Parse(time.RFC3339Nano, lastTimeStr)
if err != nil {
cwlog.DoLogCW("Unable to parse cw.lock: " + err.Error())
_ = os.Remove("cw.lock")
} else {
cwlog.DoLogCW("Lockfile found, last run was " + glob.Uptime.Sub(lastTime).String())
/* Recent lockfile, probable crash loop */
if time.Since(lastTime) < (constants.RestartLimitMinutes * time.Minute) {
fact.LogGameCMS(false, cfg.Local.Channel.ChatChannel, fmt.Sprintf("Recent lockfile found, possible crash. Sleeping for %v minutes.", constants.RestartLimitSleepMinutes))
/* Sleep for the configured sleep minutes, not the detection window */
time.Sleep(constants.RestartLimitSleepMinutes * time.Minute)
_ = os.Remove("cw.lock")
}
}
}
/* Make lockfile */
lfile, err := os.OpenFile("cw.lock", os.O_CREATE, 0666)
if err != nil {
cwlog.DoLogCW("Couldn't create lock file!!!")
os.Exit(1)
}
lfile.Close()
buf := fmt.Sprintf("%v\n", time.Now().UTC().Round(time.Second).Format(time.RFC3339Nano))
err = os.WriteFile("cw.lock", []byte(buf), 0644)
if err != nil {
cwlog.DoLogCW("Couldn't write lock file!!!")
os.Exit(1)
}
}
func initMaps() {
/* Create our maps */
glob.AlphaValue = make(map[string]int)
glob.ChatterList = make(map[string]time.Time)
glob.ChatterSpamScore = make(map[string]int)
glob.PlayerList = make(map[string]*glob.PlayerData)
glob.PassList = make(map[string]*glob.PassData)
/* Generate number to alpha map, used for auto port assignment starting at constants.RconPortOffset */
pos := constants.RconPortOffset
for i := 'a'; i <= 'z'; i++ {
glob.AlphaValue[string(i)] = pos
pos++
}
for i := 'a'; i <= 'z'; i++ {
for j := 'a'; j <= 'z'; j++ {
glob.AlphaValue[string(i)+string(j)] = pos
pos++
}
}
}
func initTime() {
glob.LastSusWarning = time.Now().Add(time.Duration(-constants.SusWarningInterval) * time.Minute)
now := time.Now()
then := now.Add(time.Duration(-constants.MapCooldownMins+1) * time.Minute)
glob.VoteBox.LastMapChange = then.Round(time.Second)
fact.Gametime = (constants.Unknown)
glob.PausedAt = time.Now()
glob.Uptime = time.Now().UTC().Round(time.Second)
fact.LoadChannelUpdateCooldown()
}
func readConfigs() {
if cfg.ReadGCfg() {
//cfg.WriteGCfg()
} else {
time.Sleep(constants.ErrorDelayShutdown * time.Second)
os.Exit(1)
}
if cfg.ReadLCfg() {
util.SetTempFilePrefix(cfg.Local.Callsign + "-")
//cfg.WriteLCfg()
} else {
time.Sleep(constants.ErrorDelayShutdown * time.Second)
os.Exit(1)
}
}