forked from RealistikOsu/RealistikPanel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.py
More file actions
2213 lines (2031 loc) · 82.4 KB
/
functions.py
File metadata and controls
2213 lines (2031 loc) · 82.4 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
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
#This file is responsible for all the functionality
from config import UserConfig
import mysql.connector
from colorama import init, Fore
import redis
import bcrypt
import datetime
import requests
from discord_webhook import DiscordWebhook, DiscordEmbed
import time
import hashlib
import json
import pycountry
from osrparse import *
import os
from changelogs import Changelogs
import timeago
init() #initialises colourama for colours
Changelogs.reverse()
print(fr"""{Fore.BLUE} _____ _ _ _ _ _ _____ _ _
| __ \ | (_) | | (_) | | __ \ | | |
| |__) |___ __ _| |_ ___| |_ _| | _| |__) |_ _ _ __ ___| | |
| _ // _ \/ _` | | / __| __| | |/ / ___/ _` | '_ \ / _ \ | |
| | \ \ __/ (_| | | \__ \ |_| | <| | | (_| | | | | __/ |_|
|_| \_\___|\__,_|_|_|___/\__|_|_|\_\_| \__,_|_| |_|\___|_(_)
---------------------------------------------------------------
{Fore.RESET}""")
#gotta def this here sorry
def ConsoleLog(Info: str, Additional: str="", Type: int=1):
"""Adds a log to the log file."""
### Types
# 1 = Info
# 2 = Warning
# 3 = Error
LogToAdd = {
"Type": Type,
"Info" : Info,
"Extra" : Additional,
"Timestamp" : round(time.time())
}
if not os.path.exists("realistikpanel.log"):
#if doesnt exist
with open("realistikpanel.log", "w+") as json_file:
json.dump([], json_file, indent=4)
#gets current log
with open("realistikpanel.log", "r") as Log:
Log = json.load(Log)
Log.append(LogToAdd) #adds current log
with open("realistikpanel.log", 'w') as json_file:
json.dump(Log, json_file, indent=4)
#webhook
#first we get embed colour so it isnt mixed with the actual webhook
if Type == 1: #this makes me wish python had native switch statements
Colour = "4360181"
TypeText = "log"
Icon = "https://cdn3.iconfinder.com/data/icons/bold-blue-glyphs-free-samples/32/Info_Circle_Symbol_Information_Letter-512.png"
if Type == 2:
Colour = "16562691"
TypeText = "warning"
Icon = "https://icon2.cleanpng.com/20180626/kiy/kisspng-warning-sign-computer-icons-clip-art-warning-icon-5b31bd67368be5.4827407215299864072234.jpg"
if Type == 3:
Colour = "15417396"
TypeText = "error"
Icon = "https://freeiconshop.com/wp-content/uploads/edd/error-flat.png"
#I promise to redo this, this is just proof of concept
if UserConfig["ConsoleLogWebhook"] != "":
webhook = DiscordWebhook(url=UserConfig["ConsoleLogWebhook"])
embed = DiscordEmbed(description=f"{Info}\n{Additional}", color=Colour)
embed.set_author(name=f"RealistikPanel {TypeText}!", icon_url=Icon)
embed.set_footer(text="RealistikPanel Console Log")
webhook.add_embed(embed)
webhook.execute()
try:
mydb = mysql.connector.connect(
host=UserConfig["SQLHost"],
user=UserConfig["SQLUser"],
passwd=UserConfig["SQLPassword"]
) #connects to database
print(f"{Fore.GREEN} Successfully connected to MySQL!")
mydb.autocommit = True
except Exception as e:
print(f"{Fore.RED} Failed connecting to MySQL! Abandoning!\n Error: {e}{Fore.RESET}")
ConsoleLog("Failed to connect to MySQL", f"{e}", 3)
exit()
try:
r = redis.Redis(host=UserConfig["RedisHost"], port=UserConfig["RedisPort"], password=UserConfig["RedisPassword"], db=UserConfig["RedisDb"]) #establishes redis connection
print(f"{Fore.GREEN} Successfully connected to Redis!")
except Exception as e:
print(f"{Fore.RED} Failed connecting to Redis! Abandoning!\n Error: {e}{Fore.RESET}")
ConsoleLog("Failed to connect to Redis", f"{e}", 3)
exit()
mycursor = mydb.cursor(buffered=True) #creates a thing to allow us to run mysql commands
mycursor.execute(f"USE {UserConfig['SQLDatabase']}") #Sets the db to ripple
mycursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
#fix potential crashes
#have to do it this way as the crash issue is a connector module issue
mycursor.execute("SELECT COUNT(*) FROM users_stats WHERE userpage_content = ''")
BadUserCount = mycursor.fetchone()[0]
if BadUserCount > 0:
print(f"{Fore.RED} Found {BadUserCount} users with potentially problematic data!{Fore.RESET}")
print(" Fixing...", end="")#end = "" means it doesnt do a newline
mycursor.execute("UPDATE users_stats SET userpage_content = NULL WHERE userpage_content = ''")
mydb.commit()
print(" Done!")
#public variables
PlayerCount = [] # list of players
CachedStore = {}
def DashData():
#note to self: add data caching so data isnt grabbed every time the dash is accessed
"""Grabs all the values for the dashboard."""
mycursor.execute("SELECT value_string FROM system_settings WHERE name = 'website_global_alert'")
Alert = mycursor.fetchall()
if len(Alert) == 0:
#some ps only have home alert
mycursor.execute("SELECT value_string FROM system_settings WHERE name = 'website_home_alert'")
#if also that doesnt exist
Alert = mycursor.fetchall()
if len(Alert) == 0:
Alert = [[]]
Alert = Alert[0][0]
if Alert == "": #checks if no alert
Alert = False
totalPP = r.get("ripple:total_pp")#Not calculated by every server .decode("utf-8")
RegisteredUsers = r.get("ripple:registered_users")
OnlineUsers = r.get("ripple:online_users")
TotalPlays = r.get("ripple:total_plays")
TotalScores = r.get("ripple:total_submitted_scores")
#If we dont have variable(variable is None) will set it and get it again
if not totalPP:
r.set('ripple:total_pp', 0)
totalPP = r.get("ripple:total_pp")
if not RegisteredUsers:
r.set('ripple:registered_users', 1)
RegisteredUsers = r.get("ripple:registered_users")
if not OnlineUsers:
r.set('ripple:online_users', 1)
OnlineUsers = r.get("ripple:online_users")
if not TotalPlays:
r.set('ripple:total_plays', 1)
TotalPlays = r.get("ripple:total_plays")
if not TotalScores:
r.set('ripple:total_submitted_scores', 1)
TotalScores = r.get("ripple:total_submitted_scores")
response = {
"RegisteredUsers" : RegisteredUsers.decode("utf-8") ,
"OnlineUsers" : OnlineUsers.decode("utf-8"),
"TotalPP" : f'{int(totalPP.decode("utf-8")):,}',
"TotalPlays" : f'{int(TotalPlays.decode("utf-8")):,}',
"TotalScores" : f'{int(TotalScores.decode("utf-8")):,}',
"Alert" : Alert
}
return response
def LoginHandler(username, password):
"""Checks the passwords and handles the sessions."""
mycursor.execute("SELECT username, password_md5, ban_datetime, privileges, id FROM users WHERE username_safe = %s", (RippleSafeUsername(username),))
User = mycursor.fetchall()
if len(User) == 0:
#when user not found
return [False, "User not found. Maybe a typo?"]
else:
User = User[0]
#Stores grabbed data in variables for easier access
Username = User[0]
PassHash = User[1]
IsBanned = User[2]
Privilege = User[3]
UserID = User[4]
#Converts IsBanned to bool
if IsBanned == "0" or not IsBanned:
IsBanned = False
else:
IsBanned = True
#dont allow the bot account to log in (in case the server has a MASSIVE loophole)
if UserID == 999:
return [False, "You may not log into the bot account."]
#shouldve been done during conversion but eh
if IsBanned:
return [False, "You are banned... Awkward..."]
else:
if HasPrivilege(UserID):
if checkpw(PassHash, password):
return [True, "You have been logged in!", { #creating session
"LoggedIn" : True,
"AccountId" : UserID,
"AccountName" : Username,
"Privilege" : Privilege,
"exp" : datetime.datetime.utcnow() + datetime.timedelta(hours=2) #so the token expires
}]
else:
return [False, "Incorrect password"]
else:
return [False, "Missing privileges!"]
def TimestampConverter(timestamp, NoDate=1):
"""Converts timestamps into readable time."""
date = datetime.datetime.fromtimestamp(int(timestamp)) #converting into datetime object
date += datetime.timedelta(hours=UserConfig["TimezoneOffset"]) #adding timezone offset to current time
#so we avoid things like 21:6
#hour = str(date.hour)
#minute = str(date.minute)
#if len(hour) == 1:
#hour = "0" + hour
#if len(minute) == 1:
#minute = "0" + minute
if NoDate == 1:
#return f"{hour}:{minute}"
return date.strftime("%H:%M")
if NoDate == 2:
return date.strftime("%H:%M %d/%m/%Y")
def RecentPlays(TotalPlays = 20, MinPP = 0):
"""Returns recent plays."""
#this is probably really bad
DivBy = 1
if UserConfig["HasRelax"]:
DivBy += 1
if UserConfig["HasAutopilot"]:
DivBy += 1
PerGamemode = round(TotalPlays/DivBy)
mycursor.execute("SELECT scores.beatmap_md5, users.username, scores.userid, scores.time, scores.score, scores.pp, scores.play_mode, scores.mods, scores.300_count, scores.100_count, scores.50_count, scores.misses_count FROM scores LEFT JOIN users ON users.id = scores.userid WHERE users.privileges & 1 AND scores.pp >= %s ORDER BY scores.time DESC LIMIT %s", (MinPP, PerGamemode,))
plays = mycursor.fetchall()
if UserConfig["HasRelax"]:
#adding relax plays
mycursor.execute("SELECT scores_relax.beatmap_md5, users.username, scores_relax.userid, scores_relax.time, scores_relax.score, scores_relax.pp, scores_relax.play_mode, scores_relax.mods, scores_relax.300_count, scores_relax.100_count, scores_relax.50_count, scores_relax.misses_count FROM scores_relax LEFT JOIN users ON users.id = scores_relax.userid WHERE users.privileges & 1 AND scores_relax.pp >= %s ORDER BY scores_relax.time DESC LIMIT %s", (MinPP, PerGamemode,))
playx_rx = mycursor.fetchall()
for plays_rx in playx_rx:
#addint them to the list
plays_rx = list(plays_rx)
plays.append(plays_rx)
if UserConfig["HasAutopilot"]:
#adding relax plays
mycursor.execute("SELECT scores_ap.beatmap_md5, users.username, scores_ap.userid, scores_ap.time, scores_ap.score, scores_ap.pp, scores_ap.play_mode, scores_ap.mods, scores_ap.300_count, scores_ap.100_count, scores_ap.50_count, scores_ap.misses_count FROM scores_ap LEFT JOIN users ON users.id = scores_ap.userid WHERE users.privileges & 1 AND scores_ap.pp >= %s ORDER BY scores_ap.time DESC LIMIT %s", (MinPP, PerGamemode,))
playx_ap = mycursor.fetchall()
for plays_ap in playx_ap:
#addint them to the list
plays_ap = list(plays_ap)
plays.append(plays_ap)
PlaysArray = []
#converting into lists as theyre cooler (and easier to work with)
for x in plays:
PlaysArray.append(list(x))
#converting the data into something readable
ReadableArray = []
for x in PlaysArray:
#yes im doing this
#lets get the song name
BeatmapMD5 = x[0]
mycursor.execute("SELECT song_name FROM beatmaps WHERE beatmap_md5 = %s", (BeatmapMD5,))
SongFetch = mycursor.fetchall()
if len(SongFetch) == 0:
#checking if none found
SongName = "Invalid..."
else:
SongName = list(SongFetch[0])[0]
#make and populate a readable dict
Dicti = {}
Mods = ModToText(x[7])
if Mods == "":
Dicti["SongName"] = SongName
else:
Dicti["SongName"] = SongName + " +" + Mods
Dicti["Player"] = x[1]
Dicti["PlayerId"] = x[2]
Dicti["Score"] = f'{x[4]:,}'
Dicti["pp"] = round(x[5])
Dicti["Timestamp"] = x[3]
Dicti["Time"] = TimestampConverter(x[3])
Dicti["Accuracy"] = round(GetAccuracy(x[8], x[9], x[10], x[11]), 2)
ReadableArray.append(Dicti)
ReadableArray = sorted(ReadableArray, key=lambda k: k["Timestamp"]) #sorting by time
ReadableArray.reverse()
return ReadableArray
def FetchBSData():
"""Fetches Bancho Settings."""
mycursor.execute("SELECT name, value_string, value_int FROM bancho_settings WHERE name = 'bancho_maintenance' OR name = 'menu_icon' OR name = 'login_notification'")
Query = list(mycursor.fetchall())
#bancho maintenence
if Query[0][2] == 0:
BanchoMan = False
else:
BanchoMan = True
return {
"BanchoMan" : BanchoMan,
"MenuIcon" : Query[1][1],
"LoginNotif" : Query[2][1]
}
def BSPostHandler(post, session):
BanchoMan = post[0]
MenuIcon = post[1]
LoginNotif = post[2]
#setting blanks to bools
if BanchoMan == "On":
BanchoMan = True
else:
BanchoMan = False
if MenuIcon == "":
MenuIcon = False
if LoginNotif == "":
LoginNotif = False
#SQL Queries
if MenuIcon != False: #this might be doable with just if not BanchoMan
mycursor.execute("UPDATE bancho_settings SET value_string = %s, value_int = 1 WHERE name = 'menu_icon'", (MenuIcon,))
else:
mycursor.execute("UPDATE bancho_settings SET value_string = '', value_int = 0 WHERE name = 'menu_icon'")
if LoginNotif != False:
mycursor.execute("UPDATE bancho_settings SET value_string = %s, value_int = 1 WHERE name = 'login_notification'", (LoginNotif,))
else:
mycursor.execute("UPDATE bancho_settings SET value_string = '', value_int = 0 WHERE name = 'login_notification'")
if BanchoMan:
mycursor.execute("UPDATE bancho_settings SET value_int = 1 WHERE name = 'bancho_maintenance'")
else:
mycursor.execute("UPDATE bancho_settings SET value_int = 0 WHERE name = 'bancho_maintenance'")
mydb.commit()
RAPLog(session["AccountId"], "modified the bancho settings")
def GetBmapInfo(id):
"""Gets beatmap info."""
mycursor.execute("SELECT beatmapset_id FROM beatmaps WHERE beatmap_id = %s", (id,))
Data = mycursor.fetchall()
if len(Data) == 0:
#it might be a beatmap set then
mycursor.execute("SELECT song_name, ar, difficulty_std, beatmapset_id, beatmap_id, ranked FROM beatmaps WHERE beatmapset_id = %s", (id,))
BMS_Data = mycursor.fetchall()
if len(BMS_Data) == 0: #if still havent found anything
return [{
"SongName" : "Not Found",
"Ar" : "0",
"Difficulty" : "0",
"BeatmapsetId" : "",
"BeatmapId" : 0,
"Cover" : "https://a.ussr.pl/" #why this%s idk
}]
else:
BMSID = Data[0][0]
mycursor.execute("SELECT song_name, ar, difficulty_std, beatmapset_id, beatmap_id, ranked FROM beatmaps WHERE beatmapset_id = %s", (BMSID,))
BMS_Data = mycursor.fetchall()
BeatmapList = []
for beatmap in BMS_Data:
thing = {
"SongName" : beatmap[0],
"Ar" : str(beatmap[1]),
"Difficulty" : str(round(beatmap[2], 2)),
"BeatmapsetId" : str(beatmap[3]),
"BeatmapId" : str(beatmap[4]),
"Ranked" : beatmap[5],
"Cover" : f"https://assets.ppy.sh/beatmaps/{beatmap[3]}/covers/cover.jpg"
}
BeatmapList.append(thing)
BeatmapList = sorted(BeatmapList, key = lambda i: i["Difficulty"])
#assigning each bmap a number to be later used
BMapNumber = 0
for beatmap in BeatmapList:
BMapNumber = BMapNumber + 1
beatmap["BmapNumber"] = BMapNumber
return BeatmapList
def HasPrivilege(UserID : int, ReqPriv = 2):
"""Check if the person trying to access the page has perms to do it."""
#tbh i shouldve done it where you pass the priv enum instead
# 0 = no verification
# 1 = Only registration required
# 2 = RAP Access Required
# 3 = Manage beatmaps required
# 4 = manage settings required
# 5 = Ban users required
# 6 = Manage users required
# 7 = View logs
# 8 = RealistikPanel Nominate (feature not added yet)
# 9 = RealistikPanel Nomination Accept (feature not added yet)
# 10 = RealistikPanel Overwatch (feature not added yet)
# 11 = Wipe account required
# 12 = Kick users required
# 13 = Manage Privileges
# 14 = View RealistikPanel error/console logs
# 15 = Manage Clans (RealistikPanel specific permission)
# 16 = View IPs in manage users
#THIS TOOK ME SO LONG TO FIGURE OUT WTF
NoPriv = 0
UserNormal = 2 << 0
AccessRAP = 2 << 2
ManageUsers = 2 << 3
BanUsers = 2 << 4
SilenceUsers = 2 << 5
WipeUsers = 2 << 6
ManageBeatmaps = 2 << 7
ManageServers = 2 << 8
ManageSettings = 2 << 9
ManageBetaKeys = 2 << 10
ManageReports = 2 << 11
ManageDocs = 2 << 12
ManageBadges = 2 << 13
ViewRAPLogs = 2 << 14
ManagePrivileges = 2 << 15
SendAlerts = 2 << 16
ChatMod = 2 << 17
KickUsers = 2 << 18
PendingVerification = 2 << 19
TournamentStaff = 2 << 20
Caker = 2 << 21
ViewTopScores = 2 << 22
#RealistikPanel Specific Perms
RPNominate = 2 << 23
RPNominateAccept = 2 << 24
RPOverwatch = 2 << 25
RPErrorLogs = 2 << 26
RPManageClans = 2 << 27
RPViewIPs = 2 << 28
if ReqPriv == 0: #dont use this like at all
return True
#gets users privilege
mycursor.execute("SELECT privileges FROM users WHERE id = %s", (UserID,))
Privilege = mycursor.fetchall()
if len(Privilege) == 0:
Privilege = 0
else:
Privilege = Privilege[0][0]
if ReqPriv == 1:
result = Privilege & UserNormal
elif ReqPriv == 2:
result = Privilege & AccessRAP
elif ReqPriv == 3:
result = Privilege & ManageBeatmaps
elif ReqPriv == 4:
result = Privilege & ManageSettings
elif ReqPriv == 5:
result = Privilege & BanUsers
elif ReqPriv == 6:
result = Privilege & ManageUsers
elif ReqPriv == 7:
result = Privilege & ViewRAPLogs
elif ReqPriv == 8:
result = Privilege & RPNominate
elif ReqPriv == 9:
result = Privilege & RPNominateAccept
elif ReqPriv == 10:
result = Privilege & RPOverwatch
elif ReqPriv == 11:
result = Privilege & WipeUsers
elif ReqPriv == 12:
result = Privilege & KickUsers
elif ReqPriv == 13:
result = Privilege & ManagePrivileges
elif ReqPriv == 14:
result = Privilege & RPErrorLogs
elif ReqPriv == 15:
result = Privilege & RPManageClans
elif ReqPriv == 16:
result = Privilege & RPViewIPs
if result >= 1:
return True
else:
return False
def RankBeatmap(BeatmapNumber, BeatmapId, ActionName, session):
"""Ranks a beatmap"""
#converts actions to numbers
if ActionName == "Loved":
ActionName = 5
elif ActionName == "Ranked":
ActionName = 2
elif ActionName == "Unranked":
ActionName = 0
else:
print(" Received alien input from rank. what?")
return
mycursor.execute("UPDATE beatmaps SET ranked = %s, ranked_status_freezed = 1 WHERE beatmap_id = %s LIMIT 1", (ActionName, BeatmapId,))
mycursor.execute("UPDATE scores s JOIN (SELECT userid, MAX(score) maxscore FROM scores JOIN beatmaps ON scores.beatmap_md5 = beatmaps.beatmap_md5 WHERE beatmaps.beatmap_md5 = (SELECT beatmap_md5 FROM beatmaps WHERE beatmap_id = %s LIMIT 1) GROUP BY userid) s2 ON s.score = s2.maxscore AND s.userid = s2.userid SET completed = 3", (BeatmapId,))
mydb.commit()
Webhook(BeatmapId, ActionName, session)
def FokaMessage(params) -> None:
"""Sends a fokabot message."""
requests.get(f"{UserConfig['BanchoURL']}api/v1/fokabotMessage", params=params)
def Webhook(BeatmapId, ActionName, session):
"""Beatmap rank webhook."""
URL = UserConfig["Webhook"]
if URL == "":
#if no webhook is set, dont do anything
return
mycursor.execute("SELECT song_name, beatmapset_id FROM beatmaps WHERE beatmap_id = %s", (BeatmapId,))
mapa = mycursor.fetchall()
mapa = mapa[0]
if ActionName == 0:
TitleText = "unranked :("
if ActionName == 2:
TitleText = "ranked!"
if ActionName == 5:
TitleText = "loved!"
webhook = DiscordWebhook(url=URL) #creates webhook
# me trying to learn the webhook
#EmbedJson = { #json to be sent to webhook
# "image" : f"https://assets.ppy.sh/beatmaps/{mapa[1]}/covers/cover.jpg",
# "author" : {
# "icon_url" : f"https://a.ussr.pl/{session['AccountId']}",
# "url" : f"https://ussr.pl/b/{BeatmapId}",
# "name" : f"{mapa[0]} was just {TitleText}"
# },
# "description" : f"Ranked by {session['AccountName']}",
# "footer" : {
# "text" : "via RealistikPanel!"
# }
#}
#requests.post(URL, data=EmbedJson, headers=headers) #sends the webhook data
embed = DiscordEmbed(description=f"Ranked by {session['AccountName']}", color=242424) #this is giving me discord.py vibes
embed.set_author(name=f"{mapa[0]} was just {TitleText}", url=f"{UserConfig['ServerURL']}b/{BeatmapId}", icon_url=f"{UserConfig['AvatarServer']}{session['AccountId']}")
embed.set_footer(text="via RealistikPanel!")
embed.set_image(url=f"https://assets.ppy.sh/beatmaps/{mapa[1]}/covers/cover.jpg")
webhook.add_embed(embed)
print(" * Posting webhook!")
webhook.execute()
if ActionName == 0:
Logtext = "unranked"
if ActionName == 2:
Logtext = "ranked"
if ActionName == 5:
Logtext = "loved"
RAPLog(session["AccountId"], f"{Logtext} the beatmap {mapa[0]} ({BeatmapId})")
ingamemsg = f"[https://{UserConfig['ServerURL']}u/{session['AccountId']} {session['AccountName']}] {Logtext.lower()} the map [https://osu.ppy.sh/b/{BeatmapId} {mapa[0]}]"
params = {"k": UserConfig['FokaKey'], "to": "#announce", "msg": ingamemsg}
FokaMessage(params)
def RAPLog(UserID=999, Text="forgot to assign a text value :/"):
"""Logs to the RAP log."""
Timestamp = round(time.time())
#now we putting that in oh yea
mycursor.execute("INSERT INTO rap_logs (userid, text, datetime, through) VALUES (%s, %s, %s, 'RealistikPanel!')", (UserID, Text, Timestamp,))
mydb.commit()
#webhook time
if UserConfig["AdminLogWebhook"] != "":
Username = GetUser(UserID)["Username"]
webhook = DiscordWebhook(UserConfig["AdminLogWebhook"])
embed = DiscordEmbed(description=f"{Username} {Text}", color=242424)
embed.set_footer(text="RealistikPanel Admin Logs")
embed.set_author(name=f"New action done by {Username}!", url=f"{UserConfig['ServerURL']}u/{UserID}", icon_url = f"{UserConfig['AvatarServer']}{UserID}")
webhook.add_embed(embed)
webhook.execute()
def checkpw(dbpassword, painpassword):
"""
By: kotypey
password checking...
"""
result = hashlib.md5(painpassword.encode()).hexdigest().encode('utf-8')
dbpassword = dbpassword.encode('utf-8')
check = bcrypt.checkpw(result, dbpassword)
return check
def SystemSettingsValues():
"""Fetches the system settings data."""
mycursor.execute("SELECT value_int, value_string FROM system_settings WHERE name = 'website_maintenance' OR name = 'game_maintenance' OR name = 'website_global_alert' OR name = 'website_home_alert' OR name = 'registrations_enabled'")
SqlData = mycursor.fetchall()
return {
"webman": bool(SqlData[0][0]),
"gameman" : bool(SqlData[1][0]),
"register": bool(SqlData[4][0]),
"globalalert": SqlData[2][1],
"homealert": SqlData[3][1]
}
def ApplySystemSettings(DataArray, Session):
"""Applies system settings."""
WebMan = DataArray[0]
GameMan =DataArray[1]
Register = DataArray[2]
GlobalAlert = DataArray[3]
HomeAlert = DataArray[4]
#i dont feel like this is the right way to do this but eh
if WebMan == "On":
WebMan = 1
else:
WebMan = 0
if GameMan == "On":
GameMan = 1
else:
GameMan = 0
if Register == "On":
Register = 1
else:
Register = 0
#SQL Queries
mycursor.execute("UPDATE system_settings SET value_int = %s WHERE name = 'website_maintenance'", (WebMan,))
mycursor.execute("UPDATE system_settings SET value_int = %s WHERE name = 'game_maintenance'", (GameMan,))
mycursor.execute("UPDATE system_settings SET value_int = %s WHERE name = 'registrations_enabled'", (Register,))
#if empty, disable
if GlobalAlert != "":
mycursor.execute("UPDATE system_settings SET value_int = 1, value_string = %s WHERE name = 'website_global_alert'", (GlobalAlert,))
else:
mycursor.execute("UPDATE system_settings SET value_int = 0, value_string = '' WHERE name = 'website_global_alert'")
if HomeAlert != "":
mycursor.execute("UPDATE system_settings SET value_int = 1, value_string = %s WHERE name = 'website_home_alert'", (HomeAlert,))
else:
mycursor.execute("UPDATE system_settings SET value_int = 0, value_string = '' WHERE name = 'website_home_alert'")
mydb.commit() #applies the changes
def IsOnline(AccountId: int):
"""Checks if given user is online."""
Online = requests.get(url=f"{UserConfig['BanchoURL']}api/v1/isOnline?id={AccountId}").json()
if Online["status"] == 200:
return Online["result"]
else:
return False
def CalcPP(BmapID):
"""Sends request to letsapi to calc PP for beatmap id."""
reqjson = requests.get(url=f"{UserConfig['LetsAPI']}v1/pp?b={BmapID}").json()
return round(reqjson["pp"][0], 2)
def CalcPPDT(BmapID):
"""Sends request to letsapi to calc PP for beatmap id with the double time mod."""
reqjson = requests.get(url=f"{UserConfig['LetsAPI']}v1/pp?b={BmapID}&m=64").json()
return round(reqjson["pp"][0], 2)
def Unique(Alist):
"""Returns list of unique elements of list."""
Uniques = []
for x in Alist:
if x not in Uniques:
Uniques.append(x)
return Uniques
def FetchUsers(page = 0):
"""Fetches users for the users page."""
#This is going to need a lot of patching up i can feel it
Offset = UserConfig["PageSize"] * page #for the page system to work
mycursor.execute("SELECT id, username, privileges, allowed FROM users LIMIT %s OFFSET %s", (UserConfig['PageSize'], Offset,))
People = mycursor.fetchall()
#gets list of all different privileges so an sql select call isnt ran per person
AllPrivileges = []
for person in People:
AllPrivileges.append(person[2])
UniquePrivileges = Unique(AllPrivileges)
#How the privilege data will look
#PrivilegeDict = {
# "234543": {
# "Name" : "Owner",
# "Privileges" : 234543,
# "Colour" : "success"
# }
#}
PrivilegeDict = {}
#gets all priv info
for Priv in UniquePrivileges:
mycursor.execute("SELECT name, color FROM privileges_groups WHERE privileges = %s LIMIT 1", (Priv,))
info = mycursor.fetchall()
if len(info) == 0:
PrivilegeDict[str(Priv)] = {
"Name" : f"Unknown ({Priv})",
"Privileges" : Priv,
"Colour" : "danger"
}
else:
info = info[0]
PrivilegeDict[str(Priv)] = {}
PrivilegeDict[str(Priv)]["Name"] = info[0]
PrivilegeDict[str(Priv)]["Privileges"] = Priv
PrivilegeDict[str(Priv)]["Colour"] = info[1]
if PrivilegeDict[str(Priv)]["Colour"] == "default" or PrivilegeDict[str(Priv)]["Colour"] == "":
#stisla doesnt have a default button so ill hard-code change it to a warning
PrivilegeDict[str(Priv)]["Colour"] = "warning"
#Convierting user data into cool dicts
#Structure
#[
# {
# "Id" : 999,
# "Name" : "RealistikDash",
# "Privilege" : PrivilegeDict["234543"],
# "Allowed" : True
# }
#]
Users = []
for user in People:
#country query
mycursor.execute("SELECT country FROM users_stats WHERE id = %s", (user[0],))
Country = mycursor.fetchall()
if len(Country) == 0:
Country = "XX"
else:
Country = Country[0][0]
Dict = {
"Id" : user[0],
"Name" : user[1],
"Privilege" : PrivilegeDict[str(user[2])],
"Country" : Country
}
if user[3] == 1:
Dict["Allowed"] = True
else:
Dict["Allowed"] = False
Users.append(Dict)
return Users
def GetUser(id):
"""Gets data for user. (universal)"""
mycursor.execute("SELECT id, username, pp_std, country FROM users_stats WHERE id = %s LIMIT 1", (id,))
User = mycursor.fetchone()
if User == None:
#if no one found
return {
"Id" : 0,
"Username" : "Not Found",
"pp" : 0,
"IsOnline" : False,
"Country" : "GB" #RULE BRITANNIA
}
return {
"Id" : User[0],
"Username" : User[1],
"pp" : User[2],
"IsOnline" : IsOnline(id),
"Country" : User[3]
}
def UserData(UserID):
"""Gets data for user (specialised for user edit page)."""
#fix badbad data
mycursor.execute("UPDATE users_stats SET userpage_content = NULL WHERE userpage_content = '' AND id = %s", (UserID,))
mydb.commit()
Data = GetUser(UserID)
mycursor.execute("SELECT userpage_content, user_color, username_aka FROM users_stats WHERE id = %s LIMIT 1", (UserID,))# Req 1
Data1 = mycursor.fetchone()
mycursor.execute("SELECT email, register_datetime, privileges, notes, donor_expire, silence_end, silence_reason, ban_datetime FROM users WHERE id = %s LIMIT 1", (UserID,))
Data2 = mycursor.fetchone()
#Fetches the IP
mycursor.execute("SELECT ip FROM ip_user WHERE userid = %s LIMIT 1", (UserID,))
Ip = mycursor.fetchone()
if Ip == None:
Ip = "0.0.0.0"
else:
Ip = Ip[0]
#gets privilege name
mycursor.execute("SELECT name FROM privileges_groups WHERE privileges = %s LIMIT 1", (Data2[2],))
PrivData = mycursor.fetchone()
if PrivData == None:
PrivData = [[f"Unknown ({Data2[2]})"]]
#adds new info to dict
#I dont use the discord features from RAP so i didnt include the discord settings but if you complain enough ill add them
try:
mycursor.execute("SELECT freezedate FROM users WHERE id = %s LIMIT 1", (UserID,))
Freeze = mycursor.fetchone()
except:
Freeze = False
Data["UserpageContent"] = Data1[0]
Data["UserColour"] = Data1[1]
Data["Aka"] = Data1[2]
Data["Email"] = Data2[0]
Data["RegisterTime"] = Data2[1]
Data["Privileges"] = Data2[2]
Data["Notes"] = Data2[3]
Data["DonorExpire"] = Data2[4]
Data["SilenceEnd"] = Data2[5]
Data["SilenceReason"] = Data2[6]
Data["Avatar"] = UserConfig["AvatarServer"] + str(UserID)
Data["Ip"] = Ip
Data["CountryFull"] = GetCFullName(Data["Country"])
Data["PrivName"] = PrivData[0]
Data["HasSupporter"] = Data["Privileges"] & 4
Data["DonorExpireStr"] = TimeToTimeAgo(Data["DonorExpire"])
#now for silences and ban times
Data["IsBanned"] = CoolerInt(Data2[7]) > 0
Data["BanedAgo"] = TimeToTimeAgo(CoolerInt(Data2[7]))
Data["IsSilenced"] = CoolerInt(Data2[5]) > round(time.time())
Data["SilenceEndAgo"] = TimeToTimeAgo(CoolerInt(Data2[5]))
if Freeze:
Data["IsFrozen"] = int(Freeze[0]) > 0
Data["FreezeDateNo"] = int(Freeze[0])
Data["FreezeDate"] = TimeToTimeAgo(Data["FreezeDateNo"])
else:
Data["IsFrozen"] = False
#removing "None" from user page and admin notes
if Data["Notes"] == None:
Data["Notes"] = ""
if Data["UserpageContent"] == None:
Data["UserpageContent"] = ""
return Data
def RAPFetch(page = 1):
"""Fetches RAP Logs."""
page = int(page) - 1 #makes sure is int and is in ok format
Offset = UserConfig["PageSize"] * page
mycursor.execute("SELECT * FROM rap_logs ORDER BY id DESC LIMIT %s OFFSET %s", (UserConfig['PageSize'], Offset,))
Data = mycursor.fetchall()
#Gets list of all users
Users = []
for dat in Data:
if dat[1] not in Users:
Users.append(dat[1])
#gets all unique users so a ton of lookups arent made
UniqueUsers = Unique(Users)
#now we get basic data for each user
UserDict = {}
for user in UniqueUsers:
UserData = GetUser(user)
UserDict[str(user)] = UserData
#log structure
#[
# {
# "LogId" : 1337,
# "AccountData" : 1000,
# "Text" : "did a thing",
# "Via" : "RealistikPanel",
# "Time" : 18932905234
# }
#]
LogArray = []
for log in Data:
#we making it into cool dicts
#getting the acc data
LogUserData = UserDict[str(log[1])]
TheLog = {
"LogId" : log[0],
"AccountData" : LogUserData,
"Text" : log[2],
"Time" : TimestampConverter(log[3], 2),
"Via" : log[4]
}
LogArray.append(TheLog)
return LogArray
def GetCFullName(ISO3166):
"""Gets the full name of the country provided."""
Country = pycountry.countries.get(alpha_2=ISO3166)
try:
CountryName = Country.name
except:
CountryName = "Unknown"
return CountryName
def GetPrivileges():
"""Gets list of privileges."""
mycursor.execute("SELECT * FROM privileges_groups")
priv = mycursor.fetchall()
if len(priv) == 0:
return []
Privs = []
for x in priv:
Privs.append({
"Id" : x[0],
"Name" : x[1],
"Priv" : x[2],
"Colour" : x[3]
})
return Privs
def ApplyUserEdit(form, session):
"""Apples the user settings."""
#getting variables from form
UserId = form.get("userid", False)
Username = form.get("username", False)
Aka = form.get("aka", False)
Email = form.get("email", False)
Country = form.get("country", False)
UserPage = form.get("userpage", False)
Notes = form.get("notes", False)
Privilege = form.get("privilege", False)
if not UserId or not Username:
print("Yo you seriously messed up the form")
raise NameError
#Creating safe username
SafeUsername = RippleSafeUsername(Username)
#fixing crash bug
if UserPage == "":
UserPage = None
#stop people ascending themselves
#OriginalPriv = int(session["Privilege"])
FromID = session["AccountId"]
if int(UserId) == FromID:
mycursor.execute("SELECT privileges FROM users WHERE id = %s", (FromID,))
OriginalPriv = mycursor.fetchall()
if len(OriginalPriv) == 0:
return
OriginalPriv = OriginalPriv[0][0]
if int(Privilege) > OriginalPriv:
return
#Badges
BadgeList = [int(form.get("Badge1", 0)), int(form.get("Badge2", 0)), int(form.get("Badge3", 0)), int(form.get("Badge4", 0)), int(form.get("Badge5", 0)), int(form.get("Badge6", 0))]
SetUserBadges(UserId, BadgeList)
#SQL Queries
mycursor.execute("UPDATE users SET email = %s, notes = %s, username = %s, username_safe = %s, privileges=%s WHERE id = %s", (Email, Notes, Username, SafeUsername,Privilege, UserId,))
mycursor.execute("UPDATE users_stats SET country = %s, userpage_content = %s, username_aka = %s, username = %s WHERE id = %s", (Country, UserPage, Aka, Username, UserId,))
if UserConfig["HasRelax"]:
mycursor.execute("UPDATE rx_stats SET country = %s, username_aka = %s, username = %s WHERE id = %s", (Country, Aka, Username, UserId,))
if UserConfig["HasAutopilot"]:
mycursor.execute("UPDATE ap_stats SET country = %s, username_aka = %s, username = %s WHERE id = %s", (Country, Aka, Username, UserId,))
mydb.commit()
def ModToText(mod: int):
"""Converts mod enum to cool string."""
#mod enums
Mods = ""
if mod == 0:
return ""
else:
#adding mod names to str
#they use bitwise too just like the perms
if mod & 1:
Mods += "NF"
if mod & 2:
Mods += "EZ"
if mod & 4:
Mods += "NV"
if mod & 8:
Mods += "HD"
if mod & 16:
Mods += "HR"
if mod & 32:
Mods += "SD"
if mod & 64:
Mods += "DT"
if mod & 128:
Mods += "RX"
if mod & 256:
Mods += "HT"
if mod & 512:
Mods += "NC"
if mod & 1024:
Mods += "FL"
if mod & 2048:
Mods += "AO"
if mod & 4096:
Mods += "SO"
if mod & 8192:
Mods += "AP"
if mod & 16384:
Mods += "PF"
if mod & 32768:
Mods += "K4"
if mod & 65536:
Mods += "K5"
if mod & 131072:
Mods += "K6"
if mod & 262144:
Mods += "K7"
if mod & 524288:
Mods += "K8"
if mod & 1015808:
Mods += "KM" #idk what this is
if mod & 1048576:
Mods += "FI"
if mod & 2097152:
Mods += "RM"
if mod & 4194304: