-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutils.py
233 lines (217 loc) · 9.55 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
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
from bs4 import BeautifulSoup
from functools import partial
from threading import Thread
import time
from tornado import gen
import requests, json
from config import *
import hashlib, re
import pandas as pd
import email as eb
import datetime as dt
import dateparser
from imapclient import IMAPClient
import email, time
with open ('cowin-app/lookup.json', 'r') as f:
lookup = json.load(f)
session = requests.Session()
session.headers = headers
# def get_otp(email, password):
# server = 'imap.gmail.com'
# mail = imaplib.IMAP4_SSL(server)
# mail.login(email, password)
# start = dt.datetime.now()
# while True:
# try:
# mail.select('inbox')
# status, data = mail.search(None, "UNSEEN SUBJECT", '"[SMSForwarder] new otp"')
# if data[0]:
# print(f"data: {data}")
# status, msg = mail.fetch(data[0], '(RFC822)')
# message = eb.message_from_string(msg[0][1].decode('utf-8')).get_payload()
# print(f"msg: {message}")
# return re.search(r'\d{6}', message).group()
# time.sleep(1)
# diff = (dt.datetime.now() - start).total_seconds()
# if diff > 180:
# return False
# except Exception as e:
# print(f"exception: {e}")
# return False
def get_otp(email_id, password, check_date):
HOST = "imap.gmail.com"
USERNAME = email_id
PASSWORD = password
# server = IMAPClient(HOST,use_uid=False)
# server.login(USERNAME, PASSWORD)
start = dt.datetime.now()
try:
with IMAPClient(HOST,use_uid=False,timeout=180) as server:
server.login(USERNAME, PASSWORD)
while True:
# print("checking")
server.select_folder("INBOX")
date = dt.datetime.now().strftime("%m-%b-%Y")
emails = server.search(['UNSEEN', 'SUBJECT', f'"[SMSForwarder] new otp"','SINCE', date])
if emails:
for msg_id in emails:
item = server.fetch(msg_id, "RFC822")
email_message = email.message_from_bytes(item[msg_id][b"RFC822"])
print(f"subject:{email_message.get('Subject')}")
subject = email_message.get("Subject")
if "[SMSForwarder] new otp" in subject:
email_date = dateparser.parse(subject.replace("[SMSForwarder] new otp ", ""))
print(f"email_date: {email_date}")
if email_date >= check_date:
print(f"required email found : {email_message.get_payload()}")
return re.search(r'\d{6}', email_message.get_payload()).group(), None
time.sleep(1.5)
diff = (dt.datetime.now() - start).total_seconds()
if diff > 180:
return False, "OTP Email not received"
except Exception as e:
print(f"exception: {e}")
return False, str(e)
def get_states():
try:
resp = session.get('https://cdn-api.co-vin.in/api/v2/admin/location/states', timeout=3)
if resp.status_code == 200:
states = resp.json()['states']
states = [(str(state['state_id']), state['state_name']) for state in states]
return states
except Exception as e:
print(f"Unable to fetch states: {e}")
return []
def get_districts(state_id):
try:
resp = session.get(f'https://cdn-api.co-vin.in/api/v2/admin/location/districts/{state_id}', timeout=3)
if resp.status_code == 200:
districts = [(str(district['district_id']), district['district_name']) for district in resp.json()['districts']]
return districts
except Exception as e:
print(f"Unable to fetch districts: {e}")
return []
def send_otp(mobno):
try:
data = {"secret":"U2FsdGVkX196RKSOE31ozbO/QRHGJ6RuEqacJuqWO4NQaA+7SO/1Ixzhqe/fkMtk4HjsB7Bjy1GKdC7qGOHeBg==","mobile": mobno}
resp = session.post('https://cdn-api.co-vin.in/api/v2/auth/generateMobileOTP', data=json.dumps(data), timeout=10)
if resp.status_code == 200:
print("OTP SENT SUCCESSFULLY")
out_json = resp.json()
print(f"Transaction ID: {out_json}")
return True, out_json
else:
print(f"Generate otp Status code: {resp.status_code}\n{resp.text}")
return False, resp.text
except Exception as e:
print(f"error occurred while sending otp: {e}")
return False, "Could Not Send OTP"
def send_capcha():
out = session.post("https://cdn-api.co-vin.in/api/v2/auth/getRecaptcha")
if out.status_code == 200:
captcha = out.json()['captcha']
captcha_str = solve_captcha(captcha)
return True, [captcha, captcha_str]
else:
print("capcha downloading failed: {out.text}")
return False, out.text
def verify_otp(mobno, otp, txnId):
try:
pin = hashlib.sha256(bytes(otp, 'utf-8')).hexdigest()
validate = {"otp": pin, "txnId": txnId}
resp = session.post('https://cdn-api.co-vin.in/api/v2/auth/validateMobileOtp', data=json.dumps(validate), timeout=10)
if resp.status_code == 200:
print("OTP SUCCESSFULLY VERIFIED")
out_json = resp.json()
token = out_json['token']
get_authenticated_session(token)
return True, out_json
else:
print(f"Validate otp Status code: {resp.status_code}\n{resp.text}")
return False, resp.text
except Exception as e:
print(f"error while verifying otp: {e}")
return False, str(e)
def solve_captcha(svg_string):
try:
captcha_letter = {}
svg = BeautifulSoup(svg_string,'html.parser')
for d in svg.find_all('path',{'fill' : re.compile("#")}):
svg_path = d.get('d').upper()
coords = re.findall('M(\d+)',svg_path)
letter_seq = "".join(re.findall("([A-Z])", svg_path))
captcha_letter[int(coords[0])] = lookup.get(letter_seq) #get letter from sequence
string = "".join(list(map(lambda l: l[-1], sorted(captcha_letter.items()))))
if string:
return string
else:
return None
except Exception as e:
print(f"unable to convert captch to string: {e}")
return None
def get_authenticated_session(token):
header = {'Authorization': f"Bearer {token}"}
session.headers.update(header)
def book_slot(book, capcha=None):
if capcha:
book["captcha"] = capcha
book = json.dumps(book)
resp = session.post("https://cdn-api.co-vin.in/api/v4/appointment/schedule", data=book)
if resp.status_code == 200:
print("Scheduled Successfully.")
print(f"response: {resp.json()}")
return True, resp.json()
else:
print(f"booking error. {resp.status_code}\n{resp.text}")
return False, resp.text
# def filter(sessions ,center, age_group, fees, vaccine, dose, refids):
# if (center['fee_type'] == fees or fees == 'Any') and (vaccine == 'ANY' or vaccine == sessions['vaccine']):
# capacity = sessions.get(f'available_capacity_dose{dose}', None)
# print(capacity, age_group)
# print(sessions)
# if capacity >= len(refids) and str(sessions['min_age_limit']) == age_group:
# center_details = {
# 'name': center['name'],
# 'center_id': center['center_id'],
# 'sessions': sessions
# }
# print(f"\nbooking available for below center:\n{center_details} and vaccine: {sessions['vaccine']}")
# return {
# "center_id": center['center_id'],
# "session_id": sessions['session_id'],
# "beneficiaries": refids,
# "slot": sessions['slots'][0],
# "dose": dose
# }
def filter(sessions, pincodes, age_group, fees, vaccine, dose, refids):
# allow_all_age = False
if sessions['sessions']:
df = pd.DataFrame(sessions['sessions'])
print(age_group)
# if age_group == "18+":
# age_group = "18"
# allow_all_age = True
age_group = "18" if age_group == "18" else "15"
query = f"pincode == {pincodes} and min_age_limit == {age_group} and vaccine == {vaccine}"
if fees != 'Any':
query = query + f" and fee_type == '{fees}'"
if dose == 'precaution dose':
query = query + f" and available_capacity > available_capacity_dose1 + available_capacity_dose2"
else:
query = query + f" and available_capacity_dose{dose} >= {len(refids)}"
# if allow_all_age:
# query = query + f" and allow_all_age == True"
# else:
# query = query + f" and allow_all_age == False"
df_sliced = df.query(query)
print(f"sessions: {len(df_sliced)} at {dt.datetime.now()}\tfinished filtering: {dt.datetime.now()}", end="\r")
for index, (_, row) in enumerate(df_sliced.iterrows()):
print(f"\nbooking available for below center:\n{row}")
return [{
"center_id": row['center_id'],
"session_id": row['session_id'],
"beneficiaries": refids,
"slot": row['slots'][0],
"dose": 1 if dose == 'precaution dose' else dose,
"is_precaution": True if dose == 'precaution dose' else False
},{'name': row['name'], 'session': json.loads(row.to_json()), 'pin': row['pincode']}]