forked from Sparsh752/TLE_Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
376 lines (350 loc) · 18.1 KB
/
db.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
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
# Description: This file is used to connect to the firebase database
# Importing the required libraries
import requests
import firebase_admin
import datetime
from firebase_admin import firestore_async,credentials,firestore
from clist_api import codeforces_handle_to_number, atcoder_handle_to_number
# This is an object which is used to authenticate while connecting to the database
# Please don't change the path of the file or delete it
# Also note that firestore allows only 30 days read and write permissions, also need to change that
cred=credentials.Certificate('./firebase_key.json')
# Initializing the app and the database
app = firebase_admin.initialize_app(cred)
db = firestore_async.client()
# Database structure is as follows:
# There is a collection named "users" which contains documents of the users
# Each document is identified by the discord id of the user
# Each document has the following fields:
# 1. discord_name: string
# 2. codeforces_handle: string
# 3. atcoder_handle: string
# 4. handle_number_codeforces: string (Used in CLIST API)
# 5. handle_number_atcoder: string (Used in CLIST API)
# 6. last_checked_codeforces : integer (Tells the number of problems solved by the user when it was last time checked)
# 7. last_checked_atcoder : datetime (Tells the time when it was last time checked)
# 8. solved_codeforces: object list of id's of solved problems on codeforces
# 9. solved_atcoder: object list of id's of solved problems on atcoder
# 10. gitgud_cf: object list of id's of solved problems on codeforces using gitgud
# 11. gitgud_ac: object list of id's of solved problems on atcoder using gitgud
# 12. score_codeforces: integer (Score of the user on codeforces)
# 13. score_atcoder: integer (Score of the user on atcoder)
# 14. problem_solving_cf: tuple (Contains the problem id, time when it was given and points) of the problem given by gitgud on codeforces
# 15. problem_solving_atcoder: tuple (Contains the problem id, time when it was given and points) of the problem given by gitgud on atcoder
# Function to check if a user exists in the database and has identified himself on the given platform
# Input: context (Use to get discord id of the message sender), handle platform (cf or ac)
# Output: boolean (True if user exists, False otherwise)
async def check_user(ctx,handle):
# Getting the user details from the database
data = await db.collection('users').document(str(ctx.author.id)).get()
# Checking if the the user has identified himself on the given platform
if handle == 'cf':
if data.exists:
if 'codeforces_handle' in data.to_dict().keys():
return True
else:
return False
elif handle == 'ac':
if data.exists:
if 'atcoder_handle' in data.to_dict().keys():
return True
else:
return False
# Function to add a user to the database
# Input: context (Use to get discord id of the message sender)
# Output: None
async def add_user(ctx):
discord_name = ctx.author.name
# Adding the user to the database with the discord id as the primary key
if(await db.collection('users').document(str(ctx.author.id)).get()).exists:
await db.collection('users').document(str(ctx.author.id)).update({
'discord_name': discord_name,
})
else:
await db.collection('users').document(str(ctx.author.id)).set({
'discord_name': discord_name,
})
# Function to add a codeforces handle to the database
# Note that this function should only be called when the user has identified his username so do the error handling their itself
# We also need to add the solved problems id's of the user to the database so that we don't need to find this list again and again since it takes a lot of time
# We can also add the number of problems that were solved when it was last time checked to the database so that we don't need to check the solved problems of the user again and again
# Now whenever their is requirement to find the solved problems of a user, we can just get it from the database and get the new solved problems from the last checked time
# This way we can greatly reduce time of finding the solved problems of a user
# Input: context (Use to get discord id of the message sender), codeforces_handle
# Output: None
async def add_codeforces_handle(ctx, codeforces_handle):
handle_number_codeforces = codeforces_handle_to_number(codeforces_handle)
solved_codeforces = await find_solved_codeforces(ctx,codeforces_handle,[],0)
await db.collection('users').document(str(ctx.author.id)).update({
'codeforces_handle': codeforces_handle,
'handle_number_codeforces': handle_number_codeforces,
'solved_codeforces': solved_codeforces,
'gitgud_cf': [],
'score_codeforces':0,
})
# Function to add a atcoder handle to the database
# Note that this function should only be called when the user has identified his username so do the error handling their itself
# Again we need to add the solved problems id's of the user to the database so that we don't need to find this list again and again since it takes a lot of time
# Here we store the time when it was last checked to the database this was done because of difference in atcoder and codeforces api
# Input: context (Use to get discord id of the message sender), atcoder_handle
# Output: None
async def add_atcoder_handle(ctx, atcoder_handle):
handle_number_atcoder = atcoder_handle_to_number(atcoder_handle)
solved_atcoder = await find_solved_atcoder(ctx,atcoder_handle,[],datetime.datetime(2010,1,1,0,0,0,0,datetime.timezone.utc))
await db.collection('users').document(str(ctx.author.id)).update({
'atcoder_handle': atcoder_handle,
'handle_number_atcoder': handle_number_atcoder,
'solved_atcoder': solved_atcoder,
'gitgud_ac':[],
'score_atcoder':0,
})
#Function to remove a user from the database
# Note that this function should only be called when the user has identified so do the error handling their itself
async def remove_user(ctx):
await db.collection('users').document(str(ctx.author.id)).delete()
# Function to get the list of all codeforces handles in the database
async def get_all_codeforces_handles():
users = await db.collection('users').get()
#Simply iterate over all the users and get the codeforces handles
codeforces_handles = []
for user in users:
discord_id = user.id
user = user.to_dict()
if 'codeforces_handle' in user.keys():
codeforces_handles.append((user['codeforces_handle'],user['handle_number_codeforces'],discord_id))
return codeforces_handles
# Function to get the list of all atcoder handles in the database
async def get_all_atcoder_handles():
users = await db.collection('users').get()
#Simply iterate over all the users and get the atcoder handles
atcoder_handles = []
for user in users:
discord_id = user.id
user = user.to_dict()
if 'atcoder_handle' in user.keys():
atcoder_handles.append((user['atcoder_handle'],user['handle_number_atcoder'],discord_id))
return atcoder_handles
# Function to return the tuple of last checked time and solved problems of a user
# So that we don't need to find the solved problems of a user again and again
async def get_last_solved_problems(ctx,stage):
doc_ref=await db.collection('users').document(str(ctx.author.id)).get()
docs=doc_ref.to_dict()
if stage=='atcoder':
return (docs['last_checked_atcoder'],docs['solved_atcoder'])
else:
return (docs['last_checked_codeforces'],docs['solved_codeforces'])
# Function to update the last checked time and solved problems of a user
async def update_last_checked_codeforces(ctx, solved_codeforces, last_checked_codeforces):
await db.collection('users').document(str(ctx.author.id)).update({
'last_checked_codeforces': last_checked_codeforces,
'solved_codeforces': solved_codeforces,
})
async def update_last_checked_atcoder(ctx, solved_atcoder, last_checked_atcoder):
await db.collection('users').document(str(ctx.author.id)).update({
'last_checked_atcoder': last_checked_atcoder,
'solved_atcoder': solved_atcoder,
})
# Function to find the solved problems of a codeforces handle
# It returns a list of solved problems
# It also updates the last_checked_codeforces and last_solved_codeforces field in the database
# Input: context (Use to get discord id of the message sender), codeforces_handle, last_solved_codeforces (List of all the problem solved last time it was checked), last_checked_codeforces(Time when it was last checked)
async def find_solved_codeforces(ctx,codeforces_handle, last_solved_codeforces, last_checked_codeforces):
# This function returns the list of all the submissions of a user
url = "https://codeforces.com/api/user.status?handle="+str(codeforces_handle)+"&from="+str(1)
response = requests.get(url).json()
# Checking if the user has submitted any problem after the last checked time
total=len(response['result'])
if total == last_checked_codeforces:
return last_solved_codeforces
# If the user has submitted any problem after the last checked time then we need to find the solved problems from the last checked time to the current time
url = "https://codeforces.com/api/user.status?handle="+str(codeforces_handle)+"&count="+str(total-last_checked_codeforces)
response = requests.get(url).json()
# print(response)
if response['status'] == 'OK':
data=response['result']
# Check all the solved problems
for obj in data:
if obj['verdict']=='OK':
last_solved_codeforces.append(str(obj['problem']['contestId'])+':'+str(obj['problem']['index']))
last_checked_codeforces += len(data)
await update_last_checked_codeforces(ctx, last_solved_codeforces, last_checked_codeforces)
return last_solved_codeforces
# This function is used to find the solved problems of a atcoder handle
# It returns a list of solved problems
# It also updates the last_checked_atcoder and last_solved_atcoder field in the database
async def find_solved_atcoder(ctx,atcoder_handle, last_solved_atcoder, last_checked_atcoder):
last_checked_atcoder = last_checked_atcoder - datetime.datetime(1970,1,1,0,0,0,0,datetime.timezone.utc)
mytime = int(last_checked_atcoder.total_seconds())
url = "https://kenkoooo.com/atcoder/atcoder-api/v3/user/submissions?user="+ atcoder_handle+"&from_second="+str(int(mytime))
response = requests.get(url).json()
for obj in response:
if(obj['result']=='AC'):
last_solved_atcoder.append(obj['problem_id'])
last_checked_atcoder = datetime.datetime.now(datetime.timezone.utc)
await update_last_checked_atcoder(ctx, last_solved_atcoder, last_checked_atcoder)
return last_solved_atcoder
# Find the codeforces handle of a user with the given discord id
async def get_codeforces_handle(ctx):
user_dict=await db.collection('users').document(str(ctx.author.id)).get()
if user_dict.exists:
user_dict=user_dict.to_dict()
if 'codeforces_handle' in user_dict.keys():
return user_dict['codeforces_handle']
else:
return None
else:
return None
# Find the atcoder handle of a user with the given discord id
async def get_atcoder_handle(ctx):
user_dict=await db.collection('users').document(str(ctx.author.id)).get()
if user_dict.exists:
user_dict=user_dict.to_dict()
if 'atcoder_handle' in user_dict.keys():
return user_dict['atcoder_handle']
else:
return None
else:
return None
# This is used to increase the score of a user if he solves a problem using gitgud on codeforces
async def update_point_cf(ctx,points):
Id=ctx.author.id
old=await db.collection('users').document(str(Id)).get(field_paths={'score_codeforces'})
old=old.to_dict()['score_codeforces']
new=old+points
await db.collection('users').document(str(Id)).update({
'score_codeforces':new,
'problem_solving_cf': None,
}
)
# This is used to increase the score of a user if he solves a problem using gitgud on atcoder
async def update_point_at(ctx,points):
Id=ctx.author.id
old=await db.collection('users').document(str(Id)).get(field_paths={'score_atcoder'})
old=old.to_dict()['score_atcoder']
new=old+points
await db.collection('users').document(str(Id)).update({
'score_atcoder':new,
'problem_solving_atcoder': None,
}
)
# This is used to get the current points of a user on codeforces
async def problem_solving_cf(ctx,problem,points):
await db.collection('users').document(str(ctx.author.id)).update({
'problem_solving_cf': (problem,datetime.datetime.now(),points),
})
# This is used to get the current points of a user on atcoder
async def problem_solving_ac(ctx,problem,points):
await db.collection('users').document(str(ctx.author.id)).update({
'problem_solving_atcoder': (problem,datetime.datetime.now(),points),
})
# This is used to get the current question the user has taken from gitgud on codeforces
async def get_current_question(id, platform):
if platform == 'cf':
problem = await db.collection('users').document(str(id)).get(field_paths={'problem_solving_cf'})
if problem.to_dict()=={}:
return None
problem = problem.to_dict()['problem_solving_cf']
if problem == None:
return None
if len(problem)==0:
return None
return problem
else:
problem = await db.collection('users').document(str(id)).get(field_paths={'problem_solving_atcoder'})
if problem.to_dict()=={}:
return None
problem = problem.to_dict()['problem_solving_atcoder']
if problem == None:
return None
if len(problem)==0:
return None
return problem
# This is used to delete the current question the user has taken from gitgud on codeforces in the case of NOGUD
async def delete_current_question(id,platform):
if platform == 'cf':
await db.collection('users').document(str(id)).update({
'problem_solving_cf': firestore.DELETE_FIELD
}
)
else:
await db.collection('users').document(str(id)).update({
'problem_solving_atcoder': firestore.DELETE_FIELD
}
)
# This is used to add the question into the gitgud list of the user on codeforces or atcoder
async def add_in_gitgud_list(id, platform, problem):
if platform == 'cf':
gitgud_cf_list= await get_gitgud_list(id,platform)
gitgud_cf_list.append(problem[0])
gitgud_cf_list.append(problem[1])
gitgud_cf_list.append(problem[2])
await db.collection('users').document(str(id)).update({
'gitgud_cf': gitgud_cf_list
}
)
else:
gitgud_ac_list= await get_gitgud_list(id,platform)
gitgud_ac_list.append(problem[0])
gitgud_ac_list.append(problem[1])
gitgud_ac_list.append(problem[2])
await db.collection('users').document(str(id)).update({
'gitgud_ac': gitgud_ac_list
}
)
# This is used to get the gitgud list of the user on codeforces or atcoder
async def get_gitgud_list(id, platform):
if platform == 'cf':
problem = await db.collection('users').document(str(id)).get(field_paths={'gitgud_cf'})
problem = problem.to_dict()['gitgud_cf']
return problem
else:
problem = await db.collection('users').document(str(id)).get(field_paths={'gitgud_ac'})
problem = problem.to_dict()['gitgud_ac']
return problem
# This is the function to get the leaderboard of the users
async def Leaderboard_list(ctx , msg):
res = await ctx.channel.send(f'{ctx.author.mention} Fetching the Leaderboard ... ⌛')
if msg == 'cf':
users = db.collection(u'users')
# Get the users in descending order of their score
a=users.order_by('score_codeforces', direction=firestore.Query.DESCENDING).stream()
data = [item async for item in a]
codeforces_handles = []
for user in data:
user=user.to_dict()
if ('codeforces_handle' in user.keys()):
score = user['score_codeforces']
codeforces_handles.append({'Discord Name':user['discord_name'],'Score': score , 'Codeforces Handle': user['codeforces_handle']})
return codeforces_handles,res
elif msg == 'ac':
users = db.collection(u'users')
a=users.order_by('score_atcoder', direction=firestore.Query.DESCENDING).stream()
data = [item async for item in a]
atcoder_handles = []
for user in data:
user=user.to_dict()
if ('atcoder_handle' in user.keys()):
score = user['score_atcoder']
atcoder_handles.append({'Discord Name':user['discord_name'],'Score': score , 'Atcoder Handle': user['atcoder_handle'] } )
return atcoder_handles,res
elif msg == 'both':
# In case of both we need to get the users in descending order of their total score (codeforces + atcoder)
users = await db.collection('users').get()
handles = []
# find all the users having both codeforces and atcoder handles and get their score
for user in users:
user=user.to_dict()
if ('codeforces_handle' in user.keys()) and ('atcoder_handle' in user.keys()):
score = user['score_codeforces'] + user['score_atcoder']
handles.append({'Discord Name':user['discord_name'],'Total Score': score})
elif 'codeforces_handle' in user.keys():
score = user['score_codeforces']
handles.append({'Discord Name':user['discord_name'],'Total Score': score})
elif 'atcoder_handle' in user.keys():
score = user['score_atcoder']
handles.append({'Discord Name':user['discord_name'],'Total Score': score})
# sort the users in descending order of their total score
handles = sorted(handles, key=lambda d:d['Total Score'] , reverse=True)
return handles,res
else:
return "error",res