-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfirebase.py
80 lines (62 loc) · 2.24 KB
/
firebase.py
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
from libdw import pyrebase
import colors
from decouple import config
dburl = config('DBURL', default=None)
email = config('EMAIL', default=None)
password = config('PASSWORD', default=None)
apikey = config('APIKEY', default=None)
authdomain = dburl.replace("https://", "") if dburl else None
fallback = True
if None in [dburl, email, password, apikey]:
print(colors.Yellow + """Missing .env variables, unable to connect to firebase
Falling back to default values""" + colors.White)
else:
config = {
"apiKey": apikey,
"authDomain": authdomain,
"databaseURL": dburl,
}
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(email, password)
db = firebase.database()
fallback = False
def get_highscores() -> dict[str, int]:
# Functions return a dict with {name: point} pairs
if fallback:
return {"benny": 10, "peter": 3}
return db.child("highscores").get().val()
def get_user_scores(name) -> dict[int, int]:
# Functions return a dict with {map: point} pairs
# Returns None if name or map is not found
if fallback:
return {1: 4, 2: 6}
info = db.child("users").child(name).child("map").get()
dic = {user.key(): user.val() for user in info.each()}
if 0 in dic:
del dic[0]
return dic
def get_user_scores_by_map(name, map) -> int:
# Functions return the points for the specific map
# Returns None if name or map is not found
if fallback:
return get_user_scores(name)[map]
return db.child("users").child(name).child("map").child(map).get().val()
def get_user_map_scores(name):
dir = db.child("users").child(name).child("map")
return dir
def update_user_scores_by_map(name, map, score):
# name (str), map (str), score (int)
db.child("users").child(name).child("map").child(map).set(score)
update_user_scores(name)
#update_user_scores_by_map("peter", "1", 4)
def update_user_scores(name):
# name (str)
total = 0
for i in db.child("users").child(name).child("map").get().each():
i = i.val()
if i != None:
total += i
db.child("highscores").child(name).set(total)
if __name__ == "__main__":
update_user_scores("benny")