This repository has been archived by the owner on Sep 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.go
454 lines (367 loc) · 10.6 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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package main
import (
"fmt"
"log"
"os"
"strings"
"github.com/davecgh/go-spew/spew"
"github.com/diamondburned/discordgo"
"github.com/diamondburned/tcell"
"github.com/diamondburned/tview/v2"
"github.com/valyala/fasttemplate"
"gitlab.com/diamondburned/6cord/center"
"gitlab.com/diamondburned/6cord/image"
"gitlab.com/diamondburned/6cord/keyring"
"gitlab.com/diamondburned/6cord/shortener"
)
var (
app *tview.Application
appflex *tview.Flex
rightflex *tview.Flex
guildView *tview.TreeView
messagesView *tview.TextView
messagesFrame *tview.Frame
wrapFrame *tview.Frame
input *tview.InputField
autocomp *tview.List
// Channel stores the current channel's pointer
Channel *discordgo.Channel
// LastAuthor stores for appending messages
// TODO: migrate to table + lastRow
LastAuthor int64
d *discordgo.Session
prefixTpl *fasttemplate.Template
)
func main() {
// less aggressive garbage collector
// debug.SetGCPercent(200)
if err := loadCfg(); err != nil {
fmt.Println(err.Error())
panic(err)
}
t, err := fasttemplate.NewTemplate(cfg.Prop.CommandPrefix, "${", "}")
if err != nil {
fmt.Println(err.Error())
panic(err)
}
prefixTpl = t
app = tview.Initialize()
app.SetBeforeDrawFunc(func(s tcell.Screen) bool {
if cfg.Prop.BackgroundColor == -1 {
s.Clear()
}
if redrawDisabled {
return true
}
return false
})
commands = append(commands, CustomCommands...)
// Shitty app actually needs a high refresh rate LOL
tview.RefreshRate = 120 // 120Hz or 120fps max
// Initialize a bunch of global states
appflex = tview.NewFlex()
rightflex = tview.NewFlex()
guildView = tview.NewTreeView()
messagesView = tview.NewTextView()
messagesFrame = tview.NewFrame(messagesView)
input = tview.NewInputField()
autocomp = tview.NewList()
center := center.New(rightflex)
center.MaxWidth = cfg.Prop.ChatMaxWidth
tview.Borders.HorizontalFocus = tview.Borders.Horizontal
tview.Borders.VerticalFocus = tview.Borders.Vertical
tview.Borders.TopLeftFocus = tview.Borders.TopLeft
tview.Borders.TopRightFocus = tview.Borders.TopRight
tview.Borders.BottomLeftFocus = tview.Borders.BottomLeft
tview.Borders.BottomRightFocus = tview.Borders.BottomRight
tview.Borders.Horizontal = ' '
tview.Borders.Vertical = ' '
tview.Borders.TopLeft = ' '
tview.Borders.TopRight = ' '
tview.Borders.BottomLeft = ' '
tview.Borders.BottomRight = ' '
guildView.SetInputCapture(func(ev *tcell.EventKey) *tcell.EventKey {
if ev.Rune() == '/' {
app.SetFocus(input)
input.SetText("/")
}
// workaround to prevent crash when no root in tree
return nil
})
messagesView.SetRegions(true)
messagesView.SetWrap(true)
messagesView.SetWordWrap(true)
messagesView.SetScrollable(true)
messagesView.SetDynamicColors(true)
messagesView.SetTextColor(tcell.Color(cfg.Prop.ForegroundColor))
messagesView.SetBackgroundColor(tcell.Color(cfg.Prop.BackgroundColor))
messagesView.SetText(` [::b]Quick Start[::-]
- Right arrow or C-l from the server list to focus to input
- Left arrow or C-h from input to focus to the server list
- Up arrow from input to go to autocomplete/message scrollback
- Tab to show/hide channels
- /goto [#channel] jumps to that channel
- Page Up/Down jumps between the server entries`)
var login = &discordgo.Login{
Email: cfg.Username,
Password: cfg.Password,
Token: cfg.Token,
}
if cfg.Token != "" {
// Fixes hanging with broken dbus
go keyring.Set(cfg.Token)
} else {
if k := keyring.Get(); k != "" {
login.Token = k
}
}
for message, mfa := "Login to Discord:", false; ; {
if cfg.Token == "" && (cfg.Username == "" || cfg.Password == "") {
if !promptLogin(login, message, mfa) {
if message != "Login to Discord:" {
println(message)
}
os.Exit(2)
}
}
s, err := discordgo.New(*login)
if err == nil {
d = s
break
}
if err == discordgo.ErrMFA {
mfa = true
message = "Enter Discord Auth code"
} else {
message = err.Error()
}
}
d.UserAgent = `Mozilla/5.0 (X11; Linux x86_64) ` +
`AppleWebKit/537.36 (KHTML, like Gecko) ` +
`Chrome/70.0.3534.4 Safari/537.36`
d.State.MaxMessageCount = 50
// Main app page
appflex.SetDirection(tview.FlexColumn)
appflex.SetBackgroundColor(tcell.Color(cfg.Prop.BackgroundColor))
{ // Left container
guildView.SetPrefixes([]string{"", ""})
guildView.SetTopLevel(1)
guildView.SetAlign(false)
guildView.SetBorder(true)
guildView.SetBorderAttributes(tcell.AttrDim)
guildView.SetBorderPadding(0, 0, 1, 0)
guildView.SetBorderColor(tcell.Color(cfg.Prop.ForegroundColor))
guildView.SetTitle("[Servers[]")
guildView.SetTitleAlign(tview.AlignLeft)
guildView.SetBackgroundColor(tcell.Color(cfg.Prop.BackgroundColor))
guildView.SetGraphicsColor(tcell.Color(cfg.Prop.ForegroundColor))
guildView.SetTitleColor(tcell.Color(cfg.Prop.ForegroundColor))
guildView.SetInputCapture(func(ev *tcell.EventKey) *tcell.EventKey {
return nil
})
}
{ // Right container
rightflex.SetDirection(tview.FlexRow)
rightflex.SetBackgroundColor(tcell.Color(cfg.Prop.BackgroundColor))
wrapFrame = tview.NewFrame(center)
wrapFrame.SetBorder(true)
wrapFrame.SetBorderAttributes(tcell.AttrDim)
wrapFrame.SetBorders(0, 0, 0, 0, 0, 0)
wrapFrame.SetBorderColor(tcell.Color(cfg.Prop.ForegroundColor))
wrapFrame.SetTitle("")
wrapFrame.SetTitleAlign(tview.AlignLeft)
wrapFrame.SetTitleColor(tcell.Color(cfg.Prop.ForegroundColor))
wrapFrame.SetBackgroundColor(tcell.Color(cfg.Prop.BackgroundColor))
autocomp.ShowSecondaryText(false)
autocomp.SetHighlightFullLine(true)
autocomp.SetBackgroundColor(tcell.Color(cfg.Prop.BackgroundColor))
autocomp.SetMainTextColor(tcell.Color(cfg.Prop.ForegroundColor))
autocomp.SetSelectedTextColor(tcell.Color(15 - cfg.Prop.ForegroundColor))
autocomp.SetSelectedBackgroundColor(tcell.Color(cfg.Prop.ForegroundColor))
autocomp.SetShortcutColor(tcell.Color(cfg.Prop.ForegroundColor))
autocomp.SetInputCapture(autocompHandler)
resetInputBehavior()
input.SetInputCapture(inputKeyHandler)
input.SetFieldTextColor(tcell.Color(cfg.Prop.ForegroundColor))
input.SetChangedFunc(func(text string) {
if len(text) == 0 {
clearList()
stateResetter()
return
}
if text == "/" {
fuzzyCommands(text)
return
}
if string(text[len(text)-1]) == " " {
clearList()
stateResetter()
return
}
words := strings.Fields(text)
if len(words) < 1 {
clearList()
stateResetter()
return
}
switch last := words[len(words)-1]; {
case strings.HasPrefix(last, "@"):
fuzzyMentions(last)
case strings.HasPrefix(last, "#"):
fuzzyChannels(last)
case strings.HasPrefix(last, ":"):
fuzzyEmojis(last)
case strings.HasPrefix(last, "~"):
fuzzyMessages(last)
case strings.HasPrefix(text, "/upload "):
fuzzyUpload(text)
case strings.HasPrefix(text, "/"):
if len(words) == 1 {
fuzzyCommands(text)
}
default:
typingTrigger()
clearList()
stateResetter()
}
})
messagesFrame.SetBorders(0, 0, 0, 0, 0, 0)
messagesFrame.SetBackgroundColor(tcell.Color(cfg.Prop.BackgroundColor))
rightflex.AddItem(messagesFrame, 0, 1, false)
rightflex.AddItem(autocomp, 1, 1, true)
rightflex.AddItem(input, 1, 1, true)
rightflex.SetBackgroundColor(tcell.Color(cfg.Prop.BackgroundColor))
}
messagesView.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Key() {
case tcell.KeyPgDn, tcell.KeyPgUp, tcell.KeyUp, tcell.KeyDown:
handleScroll()
return event
case tcell.KeyLeft:
app.SetFocus(guildView)
return nil
case tcell.KeyEnd:
messagesView.ScrollToEnd()
return nil
}
switch event.Rune() {
case 'j', 'k':
handleScroll()
return event
case 'g', 'G':
return event
}
resetInputBehavior()
app.SetFocus(input)
return nil
})
autocomp.SetSelectedFunc(func(i int, a, b string, c rune) {
autofillfunc(i)
})
app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
switch event.Key() {
case tcell.KeyF5:
fmt.Print("\033[2J")
app.Screen.Sync()
app.Draw()
case tcell.KeyCtrlC:
app.Stop()
case tcell.KeyTab:
if autocomp.GetItemCount() < 1 {
toggleChannels()
app.ForceDraw()
return nil
}
}
return event
})
app.SetRoot(appflex, true)
toggleChannels()
// image
defer image.Close()
defer imageRendererPipeline.clean()
logFile, err := os.OpenFile(
os.TempDir()+"/6cord.log",
os.O_RDWR|os.O_CREATE|os.O_APPEND|os.O_SYNC,
0664,
)
if err != nil {
fmt.Println(err.Error())
panic(err)
}
defer logFile.Close()
log.SetOutput(logFile)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
discordgo.Logger = func(msgL, caller int, format string, a ...interface{}) {
log.Println("Discordgo:", msgL, caller, format, a)
if cfg.Debug {
// Unsure if I should have spew as a dependency
log.Println(spew.Sdump(a))
}
}
// Silent logger
d.Client.Logger = nil
d.AddHandler(onReady)
d.AddHandler(messageCreate)
d.AddHandler(messageUpdate)
d.AddHandler(messageDelete)
d.AddHandler(messageDeleteBulk)
d.AddHandler(reactionAdd)
d.AddHandler(reactionRemove)
d.AddHandler(reactionRemoveAll)
d.AddHandler(onTyping)
d.AddHandler(messageAck)
d.AddHandler(voiceStateUpdate)
d.AddHandler(userSettingsUpdate)
d.AddHandler(relationshipAdd)
d.AddHandler(relationshipRemove)
d.AddHandler(guildMemberAdd)
d.AddHandler(guildMemberUpdate)
d.AddHandler(guildMemberRemove)
if cfg.Debug {
d.AddHandler(onTyping)
d.AddHandler(func(s *discordgo.Session, r *discordgo.Resumed) {
log.Println(spew.Sdump(r))
})
d.AddHandler(func(s *discordgo.Session, dc *discordgo.Disconnect) {
log.Println(spew.Sdump(dc))
})
d.Debug = true
d.LogLevel = discordgo.LogDebug
// d.AddHandler(func(s *discordgo.Session, i interface{}) {
// log.Println(spew.Sdump(i))
// })
}
// d.AddHandler(func(s *discordgo.Session, ev *discordgo.Event) {
// log.Println(spew.Sdump(ev))
// })
d.StateEnabled = true
d.State.MaxMessageCount = 35
d.State.TrackChannels = true
d.State.TrackEmojis = true
d.State.TrackMembers = true
d.State.TrackRoles = true
d.State.TrackVoice = true
d.State.TrackPresences = true
if err := d.Open(); err != nil {
fmt.Println(err.Error())
panic(err)
}
defer d.Close()
defer app.Stop()
go messageRenderer()
go renderCallback()
imageRendererPipeline = startImageRendererPipeline()
if cfg.Prop.ShortenURL {
if err := shortener.StartHTTP("127.0.0.1"); err != nil {
fmt.Println(err.Error())
panic(err)
}
}
// Stored in syscall.go, only does something when target OS is Linux
syscallSilenceStderr(logFile)
if err := app.Run(); err != nil {
fmt.Println(err.Error())
panic(err)
}
}