-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
72 lines (55 loc) · 2.15 KB
/
utils.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
import os
import json
import requests
from bs4 import BeautifulSoup
from typing import Optional
from rich.console import Console
def get_config(console: Console) -> Optional[dict]:
slash = "/" if os.name == "posix" else "\\\\"
config_path = os.path.expanduser("~") + slash + "codeforces.uwu"
if not config_path:
console.print("[bold red]ERROR: [/]Config file not found.\nPlease run `cf config`\n")
return
if not os.path.isfile(config_path):
console.print("[bold red]ERROR: [/]Config file not found.\nPlease run `cf config`\n")
return
data = None
with open(config_path, "r+") as f:
data = json.loads("".join(f.readlines()))
return data
def get_bp(lang: str) -> Optional[str]:
slash = "/" if os.name == "posix" else "\\\\"
bp_dir = os.path.expanduser("~") + slash + "cf_boilerplates"
if not os.path.isdir(bp_dir):
return
if not os.path.isfile(bp_dir + slash + "template." + lang):
return
with open(bp_dir + slash + "template." + lang, "r") as f:
return f.read()
class CFClient:
def __init__(self, username: str, password: str):
self.username = username
self.password = password
self.session = requests.Session()
self.console = Console()
def login(self) -> bool:
self.console.log("Logging in...")
csrf_token = self.get_csrf("https://codeforces.com/enter")
r2 = self.session.post("https://codeforces.com/enter", data={
"csrf_token": csrf_token,
"action": "enter",
"handleOrEmail": self.username,
"password": self.password
}, headers={
"X-Csrf-Token": csrf_token
}, allow_redirects=True)
s2 = BeautifulSoup(r2.text, "html.parser")
usr = s2.find_all("div", {"class": "lang-chooser"})[0].find_all('a')
if usr[-1].string.strip() == "Register":
return False
self.console.log("Logged in")
return True
def get_csrf(self, url) -> str:
r = self.session.get(url)
s = BeautifulSoup(r.text, "html.parser")
return s.find_all("span", {"class": "csrf-token"})[0]["data-csrf"]