-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
583 lines (499 loc) · 16.1 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"log"
"math/rand"
"minituber-server/helpers"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/bwmarrin/discordgo"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/go-co-op/gocron"
)
var upgrader = websocket.Upgrader{} // use default options
// TODO: Add character frame update to websocket
func initialiseRoutes() {
r := mux.NewRouter()
r.HandleFunc("/ping", ping).Methods("GET")
r.HandleFunc("/validsession/{sessionid}", validSession).Methods("GET")
r.HandleFunc("/verify/{userid}", verify).Methods("GET")
r.HandleFunc("/verify/{userid}/{code}", verifyCode).Methods("GET")
r.HandleFunc("/request-session/{sourcesession}/{userid}", requestSession).Methods("GET")
r.HandleFunc("/allow-session/{inviteid}", allowSession).Methods("GET")
r.HandleFunc("/deny-session/{inviteid}", denySession).Methods("GET")
r.HandleFunc("/upload-avatar/{sessionid}", uploadAvatars).Methods("POST")
r.HandleFunc("/upload-own/{code}", uploadOwn).Methods("POST")
r.HandleFunc("/get-avatars/{sessionid}/{userid}", getAvatars).Methods("GET")
r.HandleFunc("/websocket/{sessionid}/{userids}", websocketHandler)
r.HandleFunc("/receive-upload/{code}", listenAvatar)
r.HandleFunc("/request-upload/{sessionid}", requestUpload)
// CORS
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
next.ServeHTTP(w, r)
})
})
server := http.Server{
Addr: ":" + config.Port,
Handler: r,
TLSConfig: &tls.Config{
NextProtos: []string{"h2", "http/1.1"},
},
}
fmt.Printf("Server listening on %s", server.Addr)
if err := server.ListenAndServe(); err != nil {
fmt.Println(err)
}
}
var config helpers.Config
var verifyCodes []helpers.VerifyCodes
var currentData []helpers.CurrentData
var session *discordgo.Session
func websocketHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
sessionid := vars["sessionid"]
userids := vars["userids"]
if !helpers.IsSessionValid(sessionid, config.Sessions) {
w.WriteHeader(401)
return
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer func(c *websocket.Conn) {
err := c.Close()
if err != nil {
helpers.HandleError(err, false)
}
}(c)
useridsSplit := strings.Split(userids, ",")
if userids == "0" {
useridsSplit = []string{}
}
for {
mt, message, err := c.ReadMessage()
helpers.HandleError(err, false)
//log.Printf("recv: %s", message)
if strings.HasPrefix(string(message), "SEND") {
modded := []byte(strings.Replace(string(message), "SEND", "", 1))
var formatted helpers.Activity
err := json.Unmarshal(modded, &formatted)
helpers.HandleError(err, false)
currentData = helpers.ReplaceOrAddCurrentData(currentData, helpers.CurrentData{
SessionID: sessionid,
Activity: formatted,
Timestamp: time.Now().Unix(),
})
err = c.WriteMessage(mt, []byte("OK"))
helpers.HandleError(err, false)
}
var response helpers.DataWrapper
for _, userid := range useridsSplit {
if !helpers.HasAccessToSession(sessionid, config.Sessions, helpers.GetSessionID(userid, config)) {
err := c.WriteMessage(mt, []byte("ERROR Session not allowed!"))
helpers.HandleError(err, false)
continue
}
if !helpers.HasCurrentData(helpers.GetSessionID(userid, config), currentData) {
continue
}
response.Data = append(response.Data, helpers.CurrentDataResponse{
UserID: userid,
Activity: helpers.GetCurrentData(helpers.GetSessionID(userid, config), currentData).Activity,
})
}
if response.Data != nil {
encoded, _ := json.Marshal(response)
err = c.WriteMessage(mt, encoded)
helpers.HandleError(err, false)
}
}
}
func listenAvatar(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
code := vars["code"]
if !helpers.IsCodeValid(code, config.UploadCodes) {
w.WriteHeader(401)
return
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
for {
//check if code is still valid
if !helpers.IsCodeValid(code, config.UploadCodes) {
// check if file uploaded
if helpers.GetUploadedAvatar(code, config.UploadedAvatar).Uploaded {
err := c.WriteMessage(websocket.TextMessage, []byte("OK"))
helpers.HandleError(err, false)
err = c.Close()
helpers.HandleError(err, false)
return
}
err := c.WriteMessage(websocket.TextMessage, []byte("ERROR Code is invalid!"))
helpers.HandleError(err, false)
err = c.Close()
helpers.HandleError(err, false)
return
}
}
}
func ping(w http.ResponseWriter, _ *http.Request) {
pingPong := helpers.Response{
Message: "Pong!",
}
_ = json.NewEncoder(w).Encode(pingPong)
}
func validSession(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["sessionid"]
if helpers.IsSessionValid(key, config.Sessions) {
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Session is valid!"})
} else {
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Session is invalid!"})
}
}
func addToVerifiedSessions(userid string, sessionid string, code string) {
config.Sessions = helpers.SessionExists(userid, config.Sessions)
config.Sessions = append(config.Sessions, helpers.Session{
SessionID: sessionid,
UserID: userid,
})
verifyCodes = helpers.RemoveVerifyCode(code, verifyCodes)
}
func verify(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["userid"]
verificationCode := ""
for {
for i := 0; i < 6; i++ {
verificationCode += strconv.Itoa(rand.Intn(9-0) + 0)
}
if helpers.DoesVerificationCodeExist(verificationCode, verifyCodes) {
verificationCode = ""
} else {
break
}
}
verifyCodes = append(verifyCodes, helpers.VerifyCodes{
VerifyCode: verificationCode,
UserID: key,
Expires: time.Now().Unix() + 300,
})
sendMessage(key, fmt.Sprintf("Please verify your identity by entering this code in the software: `%s`\n\n"+
"The code will expire in 5 minutes. If you did not request this verification code, please ignore this "+
"message.", verificationCode))
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Verification code generation initiated!"})
}
func verifyCode(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userid := vars["userid"]
code := vars["code"]
sessionId := ""
for {
for i := 0; i < 10; i++ {
sessionId += strconv.Itoa(rand.Intn(9-0) + 0)
}
if helpers.IsSessionValid(sessionId, config.Sessions) {
sessionId = ""
} else {
break
}
}
if helpers.CodeExists(code, verifyCodes) {
codeSaved := helpers.CodeGet(code, verifyCodes)
if codeSaved.UserID == userid && codeSaved.Expires > time.Time.Unix(time.Now()) {
sendMessage(userid, "Verification successful! Have fun!")
_ = json.NewEncoder(w).Encode(helpers.ResponseToken{Message: "Verification successful!", SessionID: sessionId})
addToVerifiedSessions(userid, sessionId, code)
return
} else {
sendMessage(userid, "Verification code incorrect! Please try again.")
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Verification code incorrect!"})
return
}
} else {
sendMessage(userid, "Verification code incorrect! Please try again.")
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Verification code incorrect!"})
return
}
}
func requestSession(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
sourcesession := vars["sourcesession"]
userid := vars["userid"]
if !helpers.IsSessionValid(sourcesession, config.Sessions) {
sendMessage(userid, "Invalid session ID!")
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Invalid session ID!"})
return
}
if !helpers.DoesUserExist(userid, config.Sessions) {
sendMessage(userid, "Invalid user ID!")
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Invalid user ID!"})
return
}
sessionInviteID := ""
for {
for i := 0; i < 10; i++ {
sessionInviteID += strconv.Itoa(rand.Intn(9-0) + 0)
}
if helpers.DoesInviteExist(sessionInviteID, config.SessionAskIDs) {
sessionInviteID = ""
} else {
break
}
}
config.SessionAskIDs = append(config.SessionAskIDs, helpers.SessionAskIDs{
InviteID: sessionInviteID,
SessionID: sourcesession,
AllowSessionID: helpers.GetSessionID(userid, config),
})
user, _ := session.User(userid)
sendMessage(userid, fmt.Sprintf("User <@%s> is requesting access to your session. Open this link to allow "+
"access: https://auth.awesomesauce.software/?username=%s&inviteid=%s", helpers.GetUserid(sourcesession, config), user.Username, sessionInviteID))
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Session request sent!"})
}
func allowSession(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
inviteID := vars["inviteid"]
if !helpers.DoesInviteExist(inviteID, config.SessionAskIDs) {
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Invalid invite ID!"})
return
}
sessionId := helpers.GetInvite(inviteID, config.SessionAskIDs).SessionID
allowSessionId := helpers.GetInvite(inviteID, config.SessionAskIDs).AllowSessionID
if !helpers.IsSessionValid(sessionId, config.Sessions) || !helpers.IsSessionValid(allowSessionId, config.Sessions) {
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Invalid session ID!"})
return
}
config.Sessions = helpers.AddAllowedSession(sessionId, allowSessionId, config.Sessions)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Session allowed!"})
}
func denySession(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
inviteID := vars["inviteid"]
if !helpers.DoesInviteExist(inviteID, config.SessionAskIDs) {
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Invalid invite ID!"})
return
}
config.SessionAskIDs = helpers.DenyInvite(inviteID, config.SessionAskIDs)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Session denied!"})
}
func getAvatars(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
sessionid := vars["sessionid"]
userid := vars["userid"]
if !helpers.IsSessionValid(sessionid, config.Sessions) {
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Invalid session ID!"})
return
}
if userid == "0" {
userid = helpers.GetUserid(sessionid, config)
}
err, avatars := helpers.GetAvatars(userid)
if err != nil {
w.WriteHeader(400)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: err.Error()})
return
}
_ = json.NewEncoder(w).Encode(avatars)
}
func requestUpload(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
sessionid := vars["sessionid"]
if !helpers.IsSessionValid(sessionid, config.Sessions) {
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Invalid session ID!"})
return
}
uploadCode := ""
for {
for i := 0; i < 6; i++ {
uploadCode += strconv.Itoa(rand.Intn(9-0) + 0)
}
if helpers.IsCodeValid(uploadCode, config.UploadCodes) {
log.Println("Code already exists!")
uploadCode = ""
} else {
break
}
}
config.UploadCodes = append(config.UploadCodes, helpers.UploadCode{
UploadCode: uploadCode,
UserID: helpers.GetUserid(sessionid, config),
Expires: time.Now().Add(time.Minute * 5).Unix(),
})
_ = json.NewEncoder(w).Encode(helpers.ResponseCode{Message: "Upload code requested!", Code: uploadCode})
}
func uploadAvatars(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
sessionid := vars["sessionid"]
if !helpers.IsSessionValid(sessionid, config.Sessions) {
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Invalid session ID!"})
return
}
var av helpers.Avatars
err := json.NewDecoder(r.Body).Decode(&av)
if err != nil {
w.WriteHeader(400)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: err.Error()})
return
}
err = helpers.SaveAvatars(av, helpers.GetUserid(sessionid, config))
if err != nil {
w.WriteHeader(400)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: err.Error()})
return
}
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Avatars saved!"})
}
func uploadOwn(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
code := vars["code"]
if !helpers.IsCodeValid(code, config.UploadCodes) {
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Invalid upload code!"})
return
}
var av helpers.Avatars
err := json.NewDecoder(r.Body).Decode(&av)
if err != nil {
w.WriteHeader(400)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: err.Error()})
return
}
uploadCode := helpers.GetUploadCode(code, config.UploadCodes)
if uploadCode.Expires < time.Now().Unix() {
//remove code
config.UploadCodes = helpers.RemoveUploadCode(code, config.UploadCodes)
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Upload code expired!"})
return
}
err = helpers.SaveAvatars(av, uploadCode.UserID)
if err != nil {
w.WriteHeader(400)
_ = json.NewEncoder(w).Encode(helpers.Response{Message: err.Error()})
return
}
// set UploadedAvatar.Uploaded to true
config.UploadCodes = helpers.RemoveUploadCode(code, config.UploadCodes)
config.UploadedAvatar = append(config.UploadedAvatar, helpers.UploadedAvatar{
UploadCode: code,
Uploaded: true,
})
_ = json.NewEncoder(w).Encode(helpers.Response{Message: "Avatars saved!"})
}
func sendMessage(userid string, message string) {
create, err := session.UserChannelCreate(userid)
helpers.HandleError(err, false)
_, err = session.ChannelMessageSend(create.ID, message)
helpers.HandleError(err, false)
}
func task() {
verifyCodes = helpers.RemoveExpired(verifyCodes)
currentData = helpers.RefreshCurrentData(currentData)
helpers.SaveConfig(config)
}
func prepareScheduler() {
s := gocron.NewScheduler(time.UTC)
_, err := s.Every(1).Minutes().Do(task)
if err != nil {
return
}
if err != nil {
println(err.Error())
return
}
// Start the scheduler in a thread
s.StartAsync()
}
func main() {
if helpers.DoesFileExist("config.json") {
config = helpers.LoadConfig()
if config.DiscordToken == "" {
fmt.Println("No Discord Token specified! Set it and restart!")
os.Exit(1)
}
} else {
helpers.SaveEmptyConfig()
fmt.Println("Please edit config.json and restart the server.")
os.Exit(1)
}
discord, err := discordgo.New("Bot " + config.DiscordToken)
discord.Identify.Intents = discordgo.IntentsDirectMessages
helpers.HandleError(err, true)
_, _ = discord.ApplicationCommandBulkOverwrite(config.DiscordAppID, "", []*discordgo.ApplicationCommand{
{
Name: "id",
Description: "Get your Discord ID",
},
})
discord.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.ApplicationCommandData().Name == "id" {
var userid string
if i.Member != nil {
userid = i.Member.User.ID
} else {
userid = i.User.ID
}
var fields = []*discordgo.MessageEmbedField{
{
Name: "Registered",
Value: fmt.Sprintf("%t", helpers.DoesUserExist(userid, config.Sessions)),
Inline: true,
},
}
if helpers.DoesUserExist(userid, config.Sessions) {
fields = append(fields, &discordgo.MessageEmbedField{
Name: "Session ID",
Value: fmt.Sprintf("`%s`", helpers.GetSessionID(userid, config)),
Inline: true,
})
}
embed := &discordgo.MessageEmbed{
Title: "Information",
Description: fmt.Sprintf("Your ID is `%s`", userid),
Color: 0x1264DF,
Fields: fields,
}
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Embeds: []*discordgo.MessageEmbed{embed},
},
})
}
})
session = discord
helpers.HandleError(err, true)
err = discord.Open()
err = session.UpdateWatchStatus(0, "your goofy avatars!")
helpers.HandleError(err, false)
prepareScheduler()
initialiseRoutes()
}