forked from Teyzer/ProjectEulerBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpe_api.py
More file actions
2237 lines (1464 loc) · 71.7 KB
/
pe_api.py
File metadata and controls
2237 lines (1464 loc) · 71.7 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
import requests
from bs4 import BeautifulSoup
import datetime
import pytz
import locale
import json
import time
import pe_database
import phone_api
from rich.console import Console
from rich import inspect
from typing import List, Dict, Optional, Any, Tuple, Union
TOTAL_REQUESTS = 0
TOTAL_SUCCESS_REQUESTS = 0
SESSION_REQUESTS = 0
LAST_REQUEST_SUCCESSFUL = False
LAST_REQUEST_TIME = datetime.datetime.now(pytz.utc)
CREDENTIALS_LOCATION = "session_cookies.txt"
BASE_URL = "https://projecteuler.net/minimal={0}"
NOT_MINIMAL_BASE_URL = "https://projecteuler.net/{0}"
COOKIES = {}
console = Console()
def pe_api_setup(cookies, account) -> None:
global COOKIES
COOKIES = cookies
account_name = account["username"]
console.log(f"[-] Added credential for account {account_name}")
def now_unix() -> int:
return int(time.time())
def is_recent_unix(unix_timestamp: int):
return now_unix() - unix_timestamp < 60
class ProjectEulerRequest:
@staticmethod
def request_failed() -> None:
"""
When called, increase a global variable, counting how many requests failed.
"""
global LAST_REQUEST_SUCCESSFUL
LAST_REQUEST_SUCCESSFUL = False
@staticmethod
def request_succeeded() -> None:
"""
When called, increase a global variable, counting how many requests succeeded.
"""
global LAST_REQUEST_SUCCESSFUL, LAST_REQUEST_TIME, TOTAL_SUCCESS_REQUESTS
LAST_REQUEST_SUCCESSFUL = True
LAST_REQUEST_TIME = datetime.datetime.now(pytz.utc)
TOTAL_SUCCESS_REQUESTS += 1
def __init__(self, target_url: str, need_login: bool = True) -> None:
global TOTAL_REQUESTS, SESSION_REQUESTS
TOTAL_REQUESTS += 1
SESSION_REQUESTS += 1
if need_login:
cookies = COOKIES
else:
cookies = {}
try:
# Do the request to the website, with the right cookies that emulate the account
r = requests.get(target_url, cookies=cookies)
self.status = int(r.status_code)
if r.status_code != 200:
# Phone API is sending a notifications to teyzer's phone
phone_api.bot_crashed(r.status_code)
ProjectEulerRequest.request_failed()
self.response: str | Exception | None = None
console.log(r.text)
else:
ProjectEulerRequest.request_succeeded()
self.response: str | Exception | None = r.text
self.err = None
except Exception as err:
# Previously, err was raised again at the end of this, but returning no data seems better
phone_api.bot_crashed(str(err))
ProjectEulerRequest.request_failed()
self.status = None
self.response: str | Exception | None = None
self.err = err
class Problem:
_all_problems: List[Dict[str, Union[int, 'Problem']]] = []
def __init__(self, problem_id: int, **kwargs):
self._name: Optional[str] = None
self._problem_id: Optional[int] = problem_id
self._unix_publication: Optional[int] = None
self._solves: Optional[int] = None
self._solves_in_discord: Optional[int] = None
self._difficulty_rating: Optional[int] = None
for k, val in kwargs.items():
self.__dict__[k] = val
def __str__(self) -> str:
return str(self.__dict__)
def __repr__(self) -> str:
return self.__str__()
@staticmethod
def fetch_problems() -> None:
"""
Updates the global array `PROBLEMS`, which contains every problem
"""
res_list = []
api_data = ProjectEulerRequest("https://projecteuler.net/minimal=problems", False)
rows = api_data.response.split("\n")
timestamps = [int(x.split("##")[2]) for x in rows[1:-1]]
ux_data = ProjectEulerRequest("https://projecteuler.net/progress", True)
soup = BeautifulSoup(ux_data.response, 'html.parser')
div = soup.find_all("span", class_='tooltiptext_narrow')
if len(div) == 0:
raise Exception("data could not be fetched from the website, could not update problem fields")
for element in div:
properties = list(map(
lambda x: x.text,
element.find_all("div")
))
if len(properties) == 0:
continue
problem_id = int(properties[0].split()[1])
try: # TODO: Make a better version of this, this is pure quick fix here
solvers = int(properties[1].split()[2])
except Exception as _:
solvers = 0
if len(properties) == 3:
difficulty = None
title = properties[2].replace("\"", "")
elif len(properties) == 4:
difficulty = int(properties[2].split(": ")[1].split("%")[0])
title = properties[3].replace("\"", "")
else:
raise Exception("Properties did not have 3 or 4 fields, resulted in title not being defined")
problem = Problem(problem_id, _problem_id=problem_id, _name=title, _unix_publication=timestamps[problem_id - 1], _solves=solvers, _difficulty_rating=difficulty)
res_list.append(problem)
current_time = now_unix()
Problem._all_problems = [{"problem": problem, "fetched_at": current_time} for problem in res_list]
@staticmethod
def last_update(problem_id: int) -> Optional[int]:
if len(Problem._all_problems) < problem_id:
return None
return Problem._all_problems[problem_id - 1]["fetched_at"]
@staticmethod
def oldest_last_update() -> Optional[int]:
if len(Problem._all_problems) == 0:
return None
min_timestamp = now_unix()
for element in Problem._all_problems:
fetched_at = element["fetched_at"]
min_timestamp = min(min_timestamp, fetched_at)
return min_timestamp
@staticmethod
def should_be_updated() -> bool:
latest = Problem.oldest_last_update()
if latest is None:
return True
return not is_recent_unix(latest)
@staticmethod
def complete_list() -> List['Problem']:
"""
Returns a list containing all problems. L[i - 1] is thus problem i. Each
element is a Problem instance.
"""
if Problem.should_be_updated():
Problem.fetch_problems()
return [element["problem"] for element in Problem._all_problems]
def problem_id(self) -> int:
"""
Returns the problem_id of a problem
"""
if self._problem_id is None:
raise ValueError("The problem object needs a _problem_id parameter to know which problem it is")
return self._problem_id
def update_from_project_euler(self) -> None:
"""
Will update the problem, and gather the information you can about it on Project Euler.
This function is called automatically when trying to get fields that have not yet been defined
"""
if self._problem_id is None:
raise ValueError("_problem_id field is None")
latest = Problem.last_update(self._problem_id)
if latest is None or not is_recent_unix(latest):
Problem.fetch_problems()
for field in ["_name", "_unix_publication", "_solves", "_difficulty_rating"]:
self.__dict__[field] = Problem._all_problems[self._problem_id - 1]["problem"].__dict__[field]
def name(self) -> str:
"""
Return the name (title) of the problem
"""
if self.problem_id() < 0:
return f"Bonus #{abs(self.problem_id())}"
if self._name is None and self._problem_id is None:
raise ValueError("_name and _problem_id fields are both undefined")
if self._name is None:
self.update_from_project_euler()
return self._name
def unix_publication(self) -> int:
"""
Returns the unix publication date of the problem
"""
if self.problem_id() < 0:
return 0
if self._unix_publication is None and self._problem_id is None:
raise ValueError("_unix_publication and _problem_id fields are both undefined")
if self._unix_publication is None:
self.update_from_project_euler()
return self._unix_publication
def solves(self) -> int:
"""
return the number of solves of a problem
"""
if self.problem_id() < 0:
return 0
if self._solves is None and self._problem_id is None:
raise ValueError("_solves and _problem_id fields are both undefined")
if self._solves is None:
self.update_from_project_euler()
return self._solves
def difficulty_is_defined(self) -> bool:
if self._difficulty_rating is not None:
return True
self.update_from_project_euler()
return self._difficulty_rating is not None
def difficulty(self) -> Optional[int]:
"""
Returns the difficulty a problem
"""
if self.problem_id() < 0:
return 0
if self._difficulty_rating and self._problem_id is None:
raise ValueError("_difficulty_rating and _problem_id are both undefined")
if self._difficulty_rating is None:
self.update_from_project_euler()
return self._difficulty_rating
def guess_difficulty_detailed(self, neighbors_count: int = 5) -> Tuple[int, List['Problem']]:
"""
returns the difficulty guessed by the bot with a k-neighbor algorithm, along
with its k nearest neighbors
"""
data_filename = "saved_data/fastest_solves.json"
with open(data_filename, "r") as f:
data = json.load(f)
prob_key = str(self.problem_id())
# TODO: make this a function incorporated inside the Problem object
problem_data = get_fastest_solvers(self.problem_id())
solve_count = len(problem_data.keys())
new_dictionary = {}
for prob_id in data.keys():
if prob_id == prob_key:
continue
if len(data[prob_id].keys()) < 100:
continue
new_dictionary[prob_id] = {}
for position in data[prob_id].keys():
if int(position) <= solve_count:
new_dictionary[prob_id][position] = data[prob_id][position]
def own_distance(arr1, arr2):
total = 0
for k in arr1.keys():
ratio = arr1[k]["solve_time"] / arr2[k]["solve_time"] + arr2[k]["solve_time"] / arr1[k]["solve_time"]
total += ratio
return total
nearests = sorted(new_dictionary.keys(), key=lambda k: own_distance(problem_data, new_dictionary[k]), reverse=False)
all_problems = Problem.complete_list()
to_keep: List[Problem] = list(map(lambda key: all_problems[int(key) - 1], nearests[:neighbors_count]))
to_keep_difficulties: List[int] = list(map(lambda problem: problem.difficulty(), to_keep))
difficulty = sorted(to_keep_difficulties)[neighbors_count // 2]
return difficulty, to_keep
def guess_difficulty(self) -> int:
"""
returns the difficulty guessed by the bot with a k-neighbor algorithm
"""
return self.guess_difficulty_detailed()[0]
def title(self) -> int:
"""
Alias for self.name()
"""
return self.name()
def solvers_in_discord(self) -> List['Member']:
members: List['Member'] = Member.members()
valid_solvers = []
member: 'Member'
for member in members:
if member.has_solved(self.problem_id()):
valid_solvers.append(member)
return valid_solvers
class Solve:
def __init__(self, **kwargs):
self._problem: Optional[Problem] = None
self._problem_id: Optional[int] = None
self._member: Optional[Member] = None
self._unixtime: Optional[int] = None
self._unix_is_accurate: bool = False
for k, val in kwargs.items():
self.__dict__[k] = val
def problem(self) -> Problem:
if self._problem is None and self._problem_id is None:
raise Exception("this solve object does not have a problem object or problem id attached")
if self._problem is None:
self._problem = Problem(self._problem_id)
return self._problem
def problem_id(self) -> int:
if self._problem_id is not None:
return self._problem_id
if self._problem is None and self._problem_id is None:
raise Exception("this solve object does not have a problem object or problem id attached")
return self.problem().problem_id()
def member(self) -> 'Member':
if self._member is None:
raise ValueError("_member field has not been specified")
return self._member
def unixtime(self) -> int:
if self._unixtime is None:
raise ValueError("_unixtime field has not been specified")
return self._unixtime
class Award:
def __init__(self, **kwargs):
pass
class Member:
def __init__(self, **kwargs) -> None:
self._username: Optional[str] = None # = _username
self._nickname: Optional[str] = None # = _nickname
self._country: Optional[str] = None # = _country
self._language: Optional[str] = None # = _language
self._level: Optional[int] = None # = _level
self._discord_id: Optional[str] = None # = None if _discord_id is None else str(_discord_id)
self._pe_solve_count: Optional[int] = None # = _solve_count
self._pe_solve_array: Optional[List[bool]] = None # = _solve_array
self._pe_award_count: Optional[int] = None # = _award_count
self._pe_award_array: Tuple[List[bool], List[bool], List[bool]] | None = None # = _award_array
self._pe_kudo_count: Optional[int] = None # = _kudo_count
self._pe_kudo_array: List[Tuple[int, int]] | None = None # = _kudo_array
self._pe_bonus_array: Optional[List[bool]] = None
self._database_solve_count: Optional[int] = None # = _database_solve_count
self._database_solve_array: Optional[List[bool]] = None # = _database_solve_array
self._database_award_count: Optional[int] = None # = _database_award_count
self._database_award_array: Tuple[List[bool], List[bool], List[bool]] | None = None # = _database_award_array
self._database_kudo_count: Optional[int] = None # = _database_kudo_count
self._database_kudo_array: List[Tuple[int, int]] | None = None # = _database_kudo_array
self._database_bonus_array: Optional[List[bool]] | None = None
# Elements that members can change by themselves on the discord
self._private: Optional[bool] = None # = _private
self._favorite_problem: Optional[int] = None
self._reason_favorite_problem: Optional[str] = None
for k, val in kwargs.items():
if k == "_discord_id":
self._discord_id = str(val)
continue
self.__dict__[k] = val
def __str__(self) -> str:
return f"{self._username}/{self._discord_id}/{self._pe_solve_count}/{self._database_solve_count}"
def __repr__(self) -> str:
return self.__str__()
def update_from_friend_list(self, friend_page: Optional[ProjectEulerRequest] = None) -> None:
"""
Update the Member object according to the bot's friend list.
You can pass the data of the friends page if you already have the data
and don't want to reload it.
"""
if friend_page is None:
friend_page = ProjectEulerRequest(BASE_URL.format("friends"))
if friend_page.status != 200:
ProjectEulerRequest.request_failed()
raise Exception("Request failed")
# This is because ## is used as separator in https://projecteuler.net/minimal=friends, and thus C# and F# are an issue
format_func = lambda x: x.replace("C###", "Csharp##").replace("F###", "Fsharp##").split("##")
text_response = list(map(format_func, friend_page.response.split("\n")))
target_member = None
for element in text_response:
if element[0] == self.username():
target_member = element
break
if target_member is None:
raise Exception("Member not found in friend list")
undef_func = lambda x, int_type: \
(0 if int_type else "Undefined") if x == "" else (int(x) if int_type else x)
to_solve_bool_array = lambda string_of_01: [
c == "1" for c in
filter(lambda x: x in "01", string_of_01)
]
self._nickname = undef_func(target_member[1], False)
self._country = undef_func(target_member[2], False)
self._language = undef_func(target_member[3], False)
self._pe_solve_count = undef_func(target_member[4], True)
self._level = undef_func(target_member[5], True)
self._pe_solve_array = to_solve_bool_array(target_member[6])
self._pe_bonus_array = to_solve_bool_array(target_member[7])
def update_from_award_list(self) -> None:
"""
Update the awards of the member according to their awards page.
"""
request_url = NOT_MINIMAL_BASE_URL.format(f"progress={self.username()};show=awards")
kudo_page = ProjectEulerRequest(request_url)
if kudo_page.status != 200:
ProjectEulerRequest.request_failed()
raise Exception("Request failed")
soup = BeautifulSoup(kudo_page.response, 'html.parser')
awards_section = soup.find(id="awards_section")
if awards_section is None:
raise Exception("awards section is None, this might be because the member is no longer in the friend list, or you're missing an account", self._username)
awards_container = awards_section.find_all("div", recursive=False)
div1 = awards_container[0]
div2 = awards_container[1]
div3 = awards_container[2]
problem_awards = div1.find_all(class_="award_box")
solves_problem = [1 if len(problem.find_all(class_="smaller green strong")) == 1 else 0 for problem in problem_awards]
problem_publication = div2.find_all(class_="award_box")
solves_publication = [1 if len(problem.find_all(class_="smaller green strong")) == 1 else 0 for problem in problem_publication]
forum_awards = div3.find_all(class_="award_box")
solves_forum = [1 if len(problem.find_all(class_="smaller green strong")) == 1 else 0 for problem in forum_awards]
self._pe_award_count = sum(solves_problem) + sum(solves_publication) + sum(solves_forum)
self._pe_award_array = tuple(map(
lambda x: [str(c) == "1" for c in x],
[solves_problem, solves_publication, solves_forum]
))
def update_from_post_page(self) -> None:
"""
Update the Member's posts according to their post page.
"""
request_url = NOT_MINIMAL_BASE_URL.format(f"progress={self.username()};show=posts")
post_page = ProjectEulerRequest(request_url)
if post_page.status != 200:
ProjectEulerRequest.request_failed()
raise Exception("Request failed")
soup = BeautifulSoup(post_page.response, 'html.parser')
div = soup.find(id='posts_made_section')
post_made, kudos_earned = div.find_all("h3")[0].text.split(" / ")
post_made = int(post_made.split(" ")[2])
kudos_earned = int(kudos_earned.split(" ")[2])
def format_function(element: str) -> int:
"""
Used to adapt to bonus problems
"""
if element[0] == "B":
element = "-" + element[1:]
return int(element)
posts = list(map(
lambda post: tuple(map(
lambda x: format_function(x.text),
post.find_all("span")
)), div.find_all(class_="post_made_box")
))
self._pe_kudo_count = sum(list(map(lambda x: x[1], posts)))
self._pe_kudo_array = posts
def update_from_database(self, connection = None, data = None) -> None:
"""
Downloads all the data from the database regarding this member, and updates all of its properties, so that they can be then used.
"""
key_id, value_id = self.identity()
def check_function(data_checked: Optional[List]) -> int:
"""
This function is defined for what happens after.
If the member we are looking for is within the data, we return 1 but
in any other case we return 0
"""
# If the data is None, obviously, we want to retry
if data_checked is None:
return 0
# But if the member is within the database's data, we return 1
for member in data_checked:
if member[key_id] == str(value_id):
return 1
return 0
while check_function(data) == 0:
if data is not None:
self.update_from_friend_list()
self.push_basics_to_database()
temp_query = "SELECT * FROM members;"
data = pe_database.query_option(temp_query, connection)
for element in data:
if element[key_id] == value_id:
self._username = element["username"]
self._discord_id = str(element["discord_id"])
self._nickname = element["nickname"]
self._country = element["country"]
self._language = element["language"]
self._database_solve_count = int(element["solved"])
self._database_solve_array = [c == "1" for c in element["solve_list"]]
self._database_bonus_array = [c == "1" for c in element["solve_list_bonus"]]
self._database_award_count = element["awards"]
self._database_award_array = tuple(map(
lambda x: [str(c) == "1" for c in x],
element["awards_list"].split("|")
))
self._private = (element["private"] == 1)
self._favorite_problem = element["favorite"]
self._reason_favorite_problem = element["reason_favorite"]
break
def update_from_database_kudo(self, connection = None, data = None) -> None:
key_id, value_id = self.identity()
def check_function(data_checked: Optional[List]) -> int:
"""
Returns 0 if the data does not seem correct, and anything
but 0 if there is no apparent trouble
"""
if data_checked is None:
return 0
return len(data_checked)
while check_function(data) == 0:
if data is not None:
self.update_from_post_page()
self.push_kudo_to_database()
temp_query = f"SELECT * FROM members \
INNER JOIN pe_posts ON members.username = pe_posts.username \
WHERE members.{key_id} = '{value_id}'"
data = pe_database.query_option(temp_query, connection)
for element in data:
if element[key_id] == value_id:
self._database_kudo_count = int(element["kudos"])
self._database_kudo_array = list(map(
lambda el: tuple(map(
int, el.split("n")
)), element["posts_list"].split("|")
))
break
def identity(self) -> Tuple[str, str]:
"""
Returns a list of two elements, a key, and a value.
It allows to check for the identity of the member with member[key] == value. (For a database's row)
Note that this is needed because a member can have an identity coming from discord
or from the project euler website, depending on where we have initiated the object.
"""
if self._username is not None:
return "username", self.username()
elif self._discord_id is not None:
return "discord_id", self.discord_id()
else:
raise Exception("Need either a username or a Discord ID")
def private(self) -> bool:
"""
Returns whether the user wants its username displayed somewhere or not.
"""
if self._private is None:
self.update_from_database()
return self._private
def push_privacy_to_database(self, new_privacy: bool, connection = None) -> None:
"""
Updates a member's privacy in the database. `new_privacy` set as `true` indicates the member will be private.
"""
new_value = "1" if (new_privacy == True) else "0"
dis_id = self.discord_id()
temp_query = f"UPDATE members SET private = {new_value} WHERE discord_id = '{dis_id}';"
pe_database.query_option(temp_query, connection)
self._private = new_privacy
def favorite_problem(self) -> Optional[int]:
"""
Returns the ID of the favorite problem of the member. Can be None.
"""
if self._favorite_problem is None:
self.update_from_database()
# This can be None! If the user has never made any selection
return self._favorite_problem
def reason_favorite_problem(self) -> Optional[str]:
"""
Returns the reason why the member has selected this problem as favorite. Can be None or an empty string.
"""
if self._reason_favorite_problem is None:
self.update_from_database()
# This can be None or an empty string.
return self._reason_favorite_problem
def push_favorite_to_database(self, favorite_problem: Optional[int], reason_favorite_problem: Optional[str]) -> None:
if favorite_problem is None:
favorite_problem = 'NULL'
else:
favorite_problem = f'"{favorite_problem}"'
if reason_favorite_problem is None:
reason_favorite_problem = 'NULL'
else:
reason_favorite_problem = f'"{reason_favorite_problem}"'
discord_id = self.discord_id()
temp_query = f'UPDATE members SET favorite = {favorite_problem}, reason_favorite = {reason_favorite_problem} WHERE discord_id = "{discord_id}";'
pe_database.query_single(temp_query)
def username(self) -> str:
"""
Returns the Project Euler username of the member.
"""
if self._username is None:
self.update_from_database()
return self._username
def username_option(self) -> str:
"""
Returns the Project Euler username or "Private Account" if the account is private
"""
if self.private():
return "Private Account"
return self.username()
def nickname(self) -> str:
"""
Returns the nickname of the account on Project Euler. This can be an empty string.
"""
if self._nickname is None:
self.update_from_database()
return self._nickname
def username_ping(self) -> str:
"""
Returns the username formatted for discord code blocks, along with the discord ping if available
"""
dis_id = self.discord_id()
if self.private():
return f"`Private Profile`"
if dis_id != "":
return f"`{self.username()}` (<@{dis_id}>)"
return f"`{self.username()}`"
def country(self) -> str:
"""
Returns the country of the Project Euler account
"""
if self._country is None:
self.update_from_database()
return self._country
def language(self) -> str:
"""
Returns the language of the Project Euler account.
"""
if self._language is None:
self.update_from_database()
return self._language
def solve_csv_untouched(self) -> str:
csv_url = f"https://projecteuler.net/history={self.username()}"
req = ProjectEulerRequest(csv_url)
csv_content = req.response
return csv_content
def solve_csv(self) -> str:
"""
Returns a CSV string of the solves of the member. Formatted to account for the solves that are omitted.
"""
csv_content = self.solve_csv_untouched()
lines = list(filter(lambda x: x.strip() != '', csv_content.split("\n")))
problems_ids = set(map(lambda x: x.split(',')[2], lines))
line_format = '0,01 Jan 70 (01:00),{problem_id},"random title"'
for solve in self.solved_problems():
if str(solve) not in problems_ids:
lines.append(line_format.format(problem_id=solve))
csv_content = "\n".join(lines)
return csv_content
def solves_by_csv(self) -> List[Solve]:
"""
returns a list of all the solves of an user, with the CSV available on the website
"""
seperator = ","
solves = []
if self.solve_count() == 0:
return solves
csv_string = self.solve_csv()
solves_found = set()
lines = csv_string.split("\n")
for line in lines:
elements = line.split(seperator)
if len(elements) <= 1:
continue
problem_id = int(elements[2].replace("B", "-"))
timestamp = int(elements[0])
solves.append(
Solve(
_problem=Problem(problem_id),
_problem_id=problem_id,
_member=self,
_unixtime=timestamp,
_unix_is_accurate=True
)
)
solves_found.add(problem_id)
for problem_id in self.solved_problems():
if problem_id not in solves_found:
solves.append(
Solve(
_problem=Problem(problem_id),