forked from LukeSmithxyz/shadowchat
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
4655 lines (3958 loc) · 127 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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"database/sql"
"encoding/base64"
//"encoding/hex"
"encoding/json"
"fmt"
// "github.com/davecgh/go-spew/spew"
"github.com/gabstv/go-monero/walletrpc"
"github.com/google/uuid"
_ "github.com/mattn/go-sqlite3"
qrcode "github.com/skip2/go-qrcode"
"golang.org/x/crypto/bcrypt"
"html"
"io"
"io/ioutil"
"log"
"math"
"math/big"
"mime/multipart"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"shadowchat/utils"
"sort"
"strconv"
"strings"
"text/template"
"time"
"unicode/utf8"
//"github.com/realclientip/realclientip-go"
)
const username = "admin"
var pending_donos []utils.SuperChat
var ip_requests []string
var USDMinimum float64 = 5
var MediaMin float64 = 0.025 // Currently unused
var MessageMaxChar int = 250
var NameMaxChar int = 25
var starting_port int = 28088
var host_url string = "https://ferret.cash/"
var addressSliceSolana []utils.AddressSolana
var checked string = ""
var killDono = 35.00 * time.Minute // hours it takes for a dono to be unfulfilled before it is no longer checked.
var indexTemplate *template.Template
var overflowTemplate *template.Template
var tosTemplate *template.Template
var registerTemplate *template.Template
var donationTemplate *template.Template
var payTemplate *template.Template
var alertTemplate *template.Template
var accountPayTemplate *template.Template
var billPayTemplate *template.Template
var progressbarTemplate *template.Template
var userOBSTemplate *template.Template
var viewTemplate *template.Template
var loginTemplate *template.Template
var footerTemplate *template.Template
var incorrectLoginTemplate *template.Template
var userTemplate *template.Template
var cryptoSettingsTemplate *template.Template
var logoutTemplate *template.Template
var incorrectPasswordTemplate *template.Template
var baseCheckingRate = 25
var eth_transactions []utils.Transfer
var minSolana, minMonero, minEthereum, minPaint, minHex, minPolygon, minBusd, minShib, minUsdc, minTusd, minWbtc, minPnk float64 // Global variables to hold minimum values required to equal the global value.
var minDonoValue float64 = 5.0
var solWallets = map[int]utils.SolWallet{}
var inviteCodeMap = map[string]utils.InviteCode{}
var PublicRegistrationsEnabled = false
var ServerMinMediaDono = 5
var ServerMediaEnabled = true
var xmrWallets = [][]int{}
var globalUsers = map[int]utils.User{}
var pendingGlobalUsers = map[int]utils.PendingUser{}
var db *sql.DB
var userSessions = make(map[string]int)
var amountNeeded = 1000.00
var amountSent = 200.00
var donosMap = make(map[int]utils.Dono) // initialize an empty map
var a utils.AlertPageData
var pb utils.ProgressbarData
var obsData utils.OBSDataStruct
var prices utils.CryptoPrice
var pbMessage = "Stream Tomorrow"
type Route_ struct {
Path string
Handler func(http.ResponseWriter, *http.Request)
}
var routes_ []Route_
// Define a new template that only contains the table content
var tableTemplate = template.Must(template.New("table").Parse(`
{{range .}}
<tr id="{{.ID}}">
<td>
<button onclick="replayDono('{{.ID}}')">Replay</button>
</td>
<td>{{.UpdatedAt.Format "15:04:05 01-02-2006"}}</td>
<td>{{.Name}}</td>
<td>{{.Message}}</td>
<td>{{.MediaURL}}</td>
<td>${{.USDAmount}}</td>
<td>{{.AmountSent}}</td>
<td>{{.CurrencyType}}</td>
</tr>
{{end}}
`))
func checkLoggedIn(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session_token")
if err != nil {
fmt.Println(err)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
_, valid := getUserBySessionCached(cookie.Value)
if !valid {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
}
func checkLoggedInAdmin(w http.ResponseWriter, r *http.Request) bool {
cookie, err := r.Cookie("session_token")
if err != nil {
return false
}
user, valid := getUserBySessionCached(cookie.Value)
if !valid {
return false
}
if user.Username == "admin" {
return true
} else {
return false
}
}
func generateMoreInviteCodes(codeAmount int) {
newCodes := utils.GenerateUniqueCodes(codeAmount)
for _, code := range newCodes {
err := createNewInviteCode(code.Value, code.Active)
if err != nil {
log.Println("createNewInviteCode() error:", err)
}
}
inviteCodeMap = utils.AddInviteCodes(inviteCodeMap, newCodes)
}
// Handler function for the "/donations" endpoint
func donationsHandler(w http.ResponseWriter, r *http.Request) {
log.Println("donationsHandler Called")
cookie, err := r.Cookie("session_token")
if err != nil {
return
}
user, valid := getUserBySessionCached(cookie.Value)
if !valid {
return
}
// Fetch the latest data from your database or other data source
// Retrieve data from the donos table
rows, err := db.Query("SELECT * FROM donos WHERE fulfilled = 1 AND amount_sent != '0.0' ORDER BY created_at DESC")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
// Create a slice to hold the data
var donos []utils.Dono
for rows.Next() {
var dono utils.Dono
var name, message, address, currencyType, encryptedIP, amountToSend, amountSent, mediaURL sql.NullString
var usdAmount sql.NullFloat64
var userID sql.NullInt64
var anonDono, fulfilled sql.NullBool
err := rows.Scan(&dono.ID, &userID, &address, &name, &message, &amountToSend, &amountSent, ¤cyType, &anonDono, &fulfilled, &encryptedIP, &dono.CreatedAt, &dono.UpdatedAt, &usdAmount, &mediaURL)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dono.UserID = int(userID.Int64)
dono.Address = address.String
dono.Name = name.String
dono.Message = message.String
dono.AmountToSend = amountToSend.String
dono.AmountSent = amountSent.String
dono.CurrencyType = currencyType.String
dono.AnonDono = anonDono.Bool
dono.Fulfilled = fulfilled.Bool
dono.EncryptedIP = encryptedIP.String
dono.USDAmount = usdAmount.Float64
dono.MediaURL = mediaURL.String
if dono.UserID == user.UserID {
if s, err := strconv.ParseFloat(dono.AmountSent, 64); err == nil {
if s > 0 {
donos = append(donos, dono)
}
}
}
}
if err = rows.Err(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := donos
// Execute the table template with the latest data
err = tableTemplate.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func main() {
// Open the log file in append mode, create it if it doesn't exist
file, err := os.OpenFile("logfile.txt", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Set the log output to the log file
log.SetOutput(file)
// Your script code here
// ...
// If your script crashes, log the error
defer func() {
if r := recover(); r != nil {
log.Println("Script crashed:", r)
}
}()
// Open a new database connection
db, err = sql.Open("sqlite3", "users.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Check if the database and tables exist, and create them if they don't
err = createDatabaseIfNotExists(db)
if err != nil {
panic(err)
}
// Run migrations on database
err = runDatabaseMigrations(db)
if err != nil {
panic(err)
}
go startWallets()
time.Sleep(5 * time.Second)
log.Println("Starting server")
setupRoutes()
time.Sleep(2 * time.Second)
// Schedule a function to run fetchExchangeRates every three minutes
go fetchExchangeRates()
go checkDonos()
go checkPendingAccounts()
go checkBillingAccounts()
go checkAccountBillings()
a.Refresh = 10
pb.Refresh = 1
obsData = getObsData(db, 1)
inviteCodeMap = getAllCodes()
setServerVars()
err = http.ListenAndServe(":8900", nil)
if err != nil {
panic(err)
}
}
func updateCryptosHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to read request body: %v", err), http.StatusBadRequest)
return
}
defer r.Body.Close()
var updateRequest utils.UpdateCryptosRequest
err = json.Unmarshal(body, &updateRequest)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to parse request body: %v", err), http.StatusBadRequest)
return
}
cookie, err := r.Cookie("session_token")
if err != nil {
fmt.Println(err)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
user, valid := getUserBySessionCached(cookie.Value)
if !valid {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
userID, err := strconv.Atoi(updateRequest.UserID)
log.Println(userID, user.UserID)
if userID == user.UserID {
user.CryptosEnabled = mapToCryptosEnabled(updateRequest.SelectedCryptos)
if user.CryptosEnabled.XMR && !user.WalletUploaded {
user.CryptosEnabled.XMR = false
}
log.Println(user.CryptosEnabled)
err = updateUser(user)
if err != nil {
log.Println(err)
}
}
w.WriteHeader(http.StatusOK)
}
func mapToCryptosEnabled(selectedCryptos map[string]bool) utils.CryptosEnabled {
cryptosEnabled := utils.CryptosEnabled{}
cryptosEnabled.XMR = selectedCryptos["monero"]
cryptosEnabled.SOL = selectedCryptos["solana"]
cryptosEnabled.ETH = selectedCryptos["ethereum"]
cryptosEnabled.PAINT = selectedCryptos["paint"]
cryptosEnabled.HEX = selectedCryptos["hex"]
cryptosEnabled.MATIC = selectedCryptos["matic"]
cryptosEnabled.BUSD = selectedCryptos["busd"]
cryptosEnabled.SHIB = selectedCryptos["shiba_inu"]
cryptosEnabled.PNK = selectedCryptos["pnk"]
// Return the populated CryptosEnabled struct
return cryptosEnabled
}
func setupRoutes() {
http.HandleFunc("/style.css", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/style.css")
})
http.HandleFunc("/xmr.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/xmr.svg")
})
http.HandleFunc("/bignumber.js", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/js/bignumber.js")
})
http.HandleFunc("/checkmark.png", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/xmr.png")
})
http.HandleFunc("/fcash.png", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/fcash.png")
})
http.HandleFunc("/indexfcash.png", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/indexfcash.png")
})
http.HandleFunc("/loader.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/loader.svg")
})
http.HandleFunc("/eth.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/eth.svg")
})
http.HandleFunc("/sol.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/sol.svg")
})
http.HandleFunc("/busd.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/busd.svg")
})
http.HandleFunc("/hex.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/hex.svg")
})
http.HandleFunc("/matic.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/matic.svg")
})
http.HandleFunc("/paint.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/paint.svg")
})
http.HandleFunc("/pnk.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/pnk.svg")
})
http.HandleFunc("/shiba_inu.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/shiba_inu.svg")
})
http.HandleFunc("/tether.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/tether.svg")
})
http.HandleFunc("/usdc.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/usdc.svg")
})
http.HandleFunc("/wbtc.svg", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/wbtc.svg")
})
http.Handle("/media/", http.StripPrefix("/media/", http.FileServer(http.Dir("web/obs/media/"))))
http.HandleFunc("/users/", handleUsers)
routes_ = []Route_{
{"/updatecryptos", updateCryptosHandler},
{"/update-links", updateLinksHandler},
{"/check_donation_status/", checkDonationStatusHandler},
{"/donations", donationsHandler},
{"/", indexHandler},
{"/termsofservice", tosHandler},
{"/pay", paymentHandler},
{"/alert", alertOBSHandler},
{"/viewdonos", viewDonosHandler},
{"/replaydono", replayDonoHandler},
{"/progressbar", progressbarOBSHandler},
{"/login", loginHandler},
{"/incorrect_login", incorrectLoginHandler},
{"/user", userHandler},
{"/userobs", userOBSHandler},
{"/logout", logoutHandler},
{"/changepassword", changePasswordHandler},
{"/changeuser", changeUserHandler},
{"/register", registerUserHandler},
{"/newaccount", newAccountHandler},
{"/overflow", overflowHandler},
{"/billing", accountBillingHandler},
{"/changeusermonero", changeUserMoneroHandler},
{"/usermanager", allUsersHandler},
{"/refresh", refreshHandler},
{"/testdonation", testDonoHandler},
{"/toggleUserRegistrations", toggleUserRegistrationsHandler},
{"/generatecodes", generateCodesHandler},
{"/cryptosettings", cryptoSettingsHandler},
}
for _, route_ := range routes_ {
http.HandleFunc(route_.Path, route_.Handler)
}
indexTemplate, _ = template.ParseFiles("web/index.html")
overflowTemplate, _ = template.ParseFiles("web/overflow.html")
tosTemplate, _ = template.ParseFiles("web/tos.html")
registerTemplate, _ = template.ParseFiles("web/new_account.html")
donationTemplate, _ = template.ParseFiles("web/donation.html")
footerTemplate, _ = template.ParseFiles("web/footer.html")
payTemplate, _ = template.ParseFiles("web/pay.html")
alertTemplate, _ = template.ParseFiles("web/alert.html")
accountPayTemplate, _ = template.ParseFiles("web/accountpay.html")
billPayTemplate, _ = template.ParseFiles("web/billpay.html")
userOBSTemplate, _ = template.ParseFiles("web/obs/settings.html")
progressbarTemplate, _ = template.ParseFiles("web/obs/progressbar.html")
loginTemplate, _ = template.ParseFiles("web/login.html")
incorrectLoginTemplate, _ = template.ParseFiles("web/incorrect_login.html")
userTemplate, _ = template.ParseFiles("web/user.html")
cryptoSettingsTemplate, _ = template.ParseFiles("web/cryptoselect.html")
logoutTemplate, _ = template.ParseFiles("web/logout.html")
incorrectPasswordTemplate, _ = template.ParseFiles("web/password_change_failed.html")
}
func handleUsers(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/monero") {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
// Serve the file or directory normally
http.StripPrefix("/users/", http.FileServer(http.Dir("users/"))).ServeHTTP(w, r)
}
func replayDonoHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
user, valid := getLoggedInUser(w, r)
var donation utils.Donation
err := json.NewDecoder(r.Body).Decode(&donation)
if err != nil {
fmt.Printf("Error decoding JSON")
http.Error(w, "Error decoding JSON", http.StatusBadRequest)
return
}
// Process the donation information as needed
fmt.Printf("Received donation replay: %+v\n", donation)
if valid {
replayDono(donation, user.UserID)
} else {
http.Error(w, "Invalid donation trying to be replayed", http.StatusBadRequest)
return
}
// Send response indicating success
w.WriteHeader(http.StatusOK)
}
func testDonoHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
return
}
user, valid := getLoggedInUser(w, r)
username := r.FormValue("username")
if valid && utils.CompareStringsLowercase(user.Username, username) {
donation := utils.Donation{
ID: "123",
DonationName: "John Doe",
DonationMessage: "Test message",
DonationMedia: "",
USDValue: "100",
AmountSent: "5",
Crypto: "XMR",
}
replayDono(donation, user.UserID)
}
}
func startWallets() {
printUserColumns()
users, err := getAllUsers()
if err != nil {
log.Fatalf("startWallet() error:", err)
}
for _, user := range users {
log.Println("Checking user:", user.Username, "User ID:", user.UserID, "User billing data enabled:", user.BillingData.Enabled)
if user.BillingData.Enabled {
log.Println("User valid", user.UserID, "User eth_address:", globalUsers[user.UserID].EthAddress)
if user.WalletUploaded {
log.Println("Monero wallet uploaded")
xmrWallets = append(xmrWallets, []int{user.UserID, starting_port})
go startMoneroWallet(starting_port, user.UserID, user)
starting_port++
} else {
if checkWalletExists(user.UserID) {
log.Println("Monero wallet uploaded")
xmrWallets = append(xmrWallets, []int{user.UserID, starting_port})
go startMoneroWallet(starting_port, user.UserID, user)
user.WalletUploaded = true
updateUser(user)
starting_port++
} else {
log.Println("Monero wallet not uploaded")
}
}
} else {
log.Println("startWallets() User not valid")
}
}
fmt.Println("startWallet() starting monitoring of solana addresses.")
for _, user := range users {
solWallets[user.UserID] = utils.SolWallet{
Address: user.SolAddress,
Amount: 0.00,
}
}
utils.SetSolWallets(solWallets)
go utils.StartMonitoringSolana()
}
func checkValidSubscription(DateEnabled time.Time) bool {
oneMonthAhead := DateEnabled.AddDate(0, 1, 0)
if oneMonthAhead.After(time.Now().UTC()) {
log.Println("User valid")
return true
}
log.Println("checkValidSubscription() User not valid")
return false
}
func getLoggedInUser(w http.ResponseWriter, r *http.Request) (utils.User, bool) {
cookie, err := r.Cookie("session_token")
if err != nil {
return utils.User{}, false // Return an instance of utils.User with empty/default values
}
user, valid := getUserBySessionCached(cookie.Value)
if !valid {
return utils.User{}, false // Return an instance of utils.User with empty/default values
}
return user, true
}
func allUsersHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session_token")
if err != nil {
fmt.Println(err)
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
user, valid := getUserBySessionCached(cookie.Value)
if !valid {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
if user.Username == "admin" {
// Define the data to be passed to the HTML template
data := struct {
Title string
RegistrationOpen bool
Users map[int]utils.User
InviteCodes map[string]utils.InviteCode
}{
Title: "Users Dashboard",
RegistrationOpen: PublicRegistrationsEnabled,
Users: globalUsers,
InviteCodes: inviteCodeMap,
}
// Parse the HTML template and execute it with the data
tmpl, err := template.ParseFiles("web/view_users.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
}
func generateCodesHandler(w http.ResponseWriter, r *http.Request) {
if checkLoggedInAdmin(w, r) {
generateMoreInviteCodes(5)
http.Redirect(w, r, "/usermanager", http.StatusSeeOther)
allUsersHandler(w, r)
} else {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
}
func toggleUserRegistrationsHandler(w http.ResponseWriter, r *http.Request) {
if checkLoggedInAdmin(w, r) {
PublicRegistrationsEnabled = !PublicRegistrationsEnabled
http.Redirect(w, r, "/usermanager", http.StatusSeeOther)
allUsersHandler(w, r)
} else {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
}
func refreshHandler(w http.ResponseWriter, r *http.Request) {
if checkLoggedInAdmin(w, r) {
user, _ := getUserByUsernameCached(r.FormValue("username"))
renewUserSubscription(user)
}
allUsersHandler(w, r)
}
func updateEnabledDate(userID int) error {
// Get the current time
now := time.Now()
// Update the user's enabled date in the database
_, err := db.Exec("UPDATE users SET date_enabled=? WHERE id=?", now, userID)
if err != nil {
return err
}
return nil
}
func getAllCodes() map[string]utils.InviteCode {
rows, err := db.Query("SELECT * FROM invites")
if err != nil {
log.Println(err)
return inviteCodeMap
}
defer rows.Close()
for rows.Next() {
var ic utils.InviteCode
err = rows.Scan(&ic.Value, &ic.Active)
if err != nil {
log.Println(err)
return inviteCodeMap
}
inviteCodeMap[ic.Value] = ic
}
return inviteCodeMap
}
func getAllUsers() ([]utils.User, error) {
var users []utils.User
rows, err := db.Query("SELECT * FROM users")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var user utils.User
var links, donoGIF, donoSound, alertURL, defaultCrypto, cryptosEnabled sql.NullString
err = rows.Scan(&user.UserID, &user.Username, &user.HashedPassword, &user.EthAddress,
&user.SolAddress, &user.HexcoinAddress, &user.XMRWalletPassword, &user.MinDono, &user.MinMediaDono,
&user.MediaEnabled, &user.CreationDatetime, &user.ModificationDatetime, &links, &donoGIF, &donoSound,
&alertURL, &user.DateEnabled, &user.WalletUploaded, &cryptosEnabled, &defaultCrypto)
if err != nil {
return nil, err
}
user.Links = links.String
if !links.Valid {
user.Links = ""
}
user.DonoGIF = donoGIF.String
if !donoGIF.Valid {
user.DonoGIF = "default.gif"
}
user.DonoSound = donoSound.String
if !donoSound.Valid {
user.DonoSound = "default.mp3"
}
user.DefaultCrypto = defaultCrypto.String
if !defaultCrypto.Valid {
user.DefaultCrypto = ""
}
user.AlertURL = alertURL.String
if !alertURL.Valid {
user.AlertURL = utils.GenerateUniqueURL()
}
ce := utils.CryptosEnabled{
XMR: true,
SOL: true,
ETH: false,
PAINT: false,
HEX: true,
MATIC: false,
BUSD: true,
SHIB: false,
PNK: true,
}
user.CryptosEnabled = cryptosJsonStringToStruct(cryptosEnabled.String)
if !cryptosEnabled.Valid {
log.Println("user cryptos enabled not fixed")
user.CryptosEnabled = ce
}
users = append(users, user)
}
if err = rows.Err(); err != nil {
return nil, err
}
billings, err := getAllBilling()
if err != nil {
return nil, err
}
billingMap := make(map[int]utils.BillingData)
for _, billing := range billings {
billingMap[billing.UserID] = billing
}
for i := range users {
billing, ok := billingMap[users[i].UserID]
if ok {
users[i].BillingData = billing
globalUsers[users[i].UserID] = users[i]
}
}
return users, nil
}
func getAllBilling() ([]utils.BillingData, error) {
var billings []utils.BillingData
rows, err := db.Query("SELECT * FROM billing")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var billingData utils.BillingData
err = rows.Scan(&billingData.BillingID, &billingData.UserID, &billingData.AmountThisMonth, &billingData.AmountTotal, &billingData.Enabled, &billingData.NeedToPay, &billingData.ETHAmount, &billingData.XMRAmount, &billingData.XMRPayID, &billingData.CreatedAt, &billingData.UpdatedAt)
if err != nil {
log.Println(err)
}
fmt.Println("UserID: ", billingData.UserID)
fmt.Println("Amount This Month: ", billingData.AmountThisMonth)
fmt.Println("Amount Total: ", billingData.AmountTotal)
fmt.Println("Enabled: ", billingData.Enabled)
fmt.Println("Need To Pay: ", billingData.NeedToPay)
fmt.Println("Created At: ", billingData.CreatedAt)
fmt.Println("Updated At: ", billingData.UpdatedAt)
billings = append(billings, billingData)
}
if err = rows.Err(); err != nil {
log.Println(err)
return nil, err
}
return billings, nil
}
func getActiveETHUsers(db *sql.DB) ([]*utils.User, error) {
var users []*utils.User
// Define the query to select the active ETH users
query := `SELECT * FROM users WHERE eth_address != ''`
// Execute the query
rows, err := db.Query(query)
if err != nil {
return nil, err
}
for rows.Next() {
var user utils.User
err = rows.Scan(&user.UserID, &user.Username, &user.HashedPassword, &user.EthAddress, &user.SolAddress, &user.HexcoinAddress, &user.XMRWalletPassword, &user.MinDono, &user.MinMediaDono, &user.MediaEnabled, &user.CreationDatetime, &user.ModificationDatetime, &user.Links, &user.DonoGIF, &user.DonoSound, &user.AlertURL, &user.WalletUploaded, &user.DateEnabled)
if err != nil {
return nil, err
}
oneMonthAhead := user.DateEnabled.AddDate(0, 1, 0)
if oneMonthAhead.After(time.Now().UTC()) {
users = append(users, &user)
}
}
return users, nil
}
func getActiveXMRUsers(db *sql.DB) ([]*utils.User, error) {
var users []*utils.User
// Define the query to select the active XMR users
query := `SELECT * FROM users WHERE wallet_uploaded = ?`
// Execute the query
rows, err := db.Query(query, true)
if err != nil {
return nil, err
}
for rows.Next() {
var user utils.User
err = rows.Scan(&user.UserID, &user.Username, &user.HashedPassword, &user.EthAddress, &user.SolAddress, &user.HexcoinAddress, &user.XMRWalletPassword, &user.MinDono, &user.MinMediaDono, &user.MediaEnabled, &user.CreationDatetime, &user.ModificationDatetime, &user.Links, &user.DonoGIF, &user.DonoSound, &user.AlertURL, &user.WalletUploaded, &user.DateEnabled)
if err != nil {
return nil, err
}
oneMonthAhead := user.DateEnabled.AddDate(0, 1, 0)
if oneMonthAhead.After(time.Now().UTC()) {
users = append(users, &user)
}
}
return users, nil
}
func getUserCryptosEnabled(user utils.User) (utils.User, error) {
user.CryptosEnabled.XMR = false
user.CryptosEnabled.SOL = false
user.CryptosEnabled.ETH = false
user.CryptosEnabled.PAINT = true
user.CryptosEnabled.HEX = false
user.CryptosEnabled.MATIC = true
user.CryptosEnabled.BUSD = false
user.CryptosEnabled.SHIB = true
user.CryptosEnabled.PNK = false
return user, nil
}
// get links for a user
func getUserLinks(user utils.User) ([]utils.Link, error) {
if user.Links == "" {
// Insert default links for the user
defaultLinks := []utils.Link{
{URL: "https://powerchat.live/paultown?tab=donation", Description: "Powerchat"},
{URL: "https://cozy.tv/paultown", Description: "cozy.tv/paultown"},
{URL: "http://twitter.paul.town/", Description: "Twitter"},
{URL: "https://t.me/paultownreal", Description: "Telegram"},
{URL: "http://notes.paul.town/", Description: "notes.paul.town"},
}
jsonLinks, err := json.Marshal(defaultLinks)
if err != nil {
return nil, err
}
user.Links = string(jsonLinks)
if err := updateUser(user); err != nil {
return nil, err
}
return defaultLinks, nil
}
var links []utils.Link
if err := json.Unmarshal([]byte(user.Links), &links); err != nil {
return nil, err
}
return links, nil
}