-
Notifications
You must be signed in to change notification settings - Fork 238
/
visa.py
283 lines (222 loc) · 8.37 KB
/
visa.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
# -*- coding: utf8 -*-
import time
import json
import random
import platform
import configparser
from datetime import datetime
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as Wait
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
config = configparser.ConfigParser()
config.read('config.ini')
USERNAME = config['USVISA']['USERNAME']
PASSWORD = config['USVISA']['PASSWORD']
SCHEDULE_ID = config['USVISA']['SCHEDULE_ID']
MY_SCHEDULE_DATE = config['USVISA']['MY_SCHEDULE_DATE']
COUNTRY_CODE = config['USVISA']['COUNTRY_CODE']
FACILITY_ID = config['USVISA']['FACILITY_ID']
SENDGRID_API_KEY = config['SENDGRID']['SENDGRID_API_KEY']
PUSH_TOKEN = config['PUSHOVER']['PUSH_TOKEN']
PUSH_USER = config['PUSHOVER']['PUSH_USER']
LOCAL_USE = config['CHROMEDRIVER'].getboolean('LOCAL_USE')
HUB_ADDRESS = config['CHROMEDRIVER']['HUB_ADDRESS']
REGEX_CONTINUE = "//a[contains(text(),'Continuar')]"
# def MY_CONDITION(month, day): return int(month) == 11 and int(day) >= 5
def MY_CONDITION(month, day): return True # No custom condition wanted for the new scheduled date
STEP_TIME = 0.5 # time between steps (interactions with forms): 0.5 seconds
RETRY_TIME = 60*10 # wait time between retries/checks for available dates: 10 minutes
EXCEPTION_TIME = 60*30 # wait time when an exception occurs: 30 minutes
COOLDOWN_TIME = 60*60 # wait time when temporary banned (empty list): 60 minutes
DATE_URL = f"https://ais.usvisa-info.com/{COUNTRY_CODE}/niv/schedule/{SCHEDULE_ID}/appointment/days/{FACILITY_ID}.json?appointments[expedite]=false"
TIME_URL = f"https://ais.usvisa-info.com/{COUNTRY_CODE}/niv/schedule/{SCHEDULE_ID}/appointment/times/{FACILITY_ID}.json?date=%s&appointments[expedite]=false"
APPOINTMENT_URL = f"https://ais.usvisa-info.com/{COUNTRY_CODE}/niv/schedule/{SCHEDULE_ID}/appointment"
EXIT = False
def send_notification(msg):
print(f"Sending notification: {msg}")
if SENDGRID_API_KEY:
message = Mail(
from_email=USERNAME,
to_emails=USERNAME,
subject=msg,
html_content=msg)
try:
sg = SendGridAPIClient(SENDGRID_API_KEY)
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)
if PUSH_TOKEN:
url = "https://api.pushover.net/1/messages.json"
data = {
"token": PUSH_TOKEN,
"user": PUSH_USER,
"message": msg
}
requests.post(url, data)
def get_driver():
if LOCAL_USE:
dr = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
else:
dr = webdriver.Remote(command_executor=HUB_ADDRESS, options=webdriver.ChromeOptions())
return dr
driver = get_driver()
def login():
# Bypass reCAPTCHA
driver.get(f"https://ais.usvisa-info.com/{COUNTRY_CODE}/niv")
time.sleep(STEP_TIME)
a = driver.find_element(By.XPATH, '//a[@class="down-arrow bounce"]')
a.click()
time.sleep(STEP_TIME)
print("Login start...")
href = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div[1]/div[1]/div[2]/div[1]/ul/li[3]/a')
href.click()
time.sleep(STEP_TIME)
Wait(driver, 60).until(EC.presence_of_element_located((By.NAME, "commit")))
print("\tclick bounce")
a = driver.find_element(By.XPATH, '//a[@class="down-arrow bounce"]')
a.click()
time.sleep(STEP_TIME)
do_login_action()
def do_login_action():
print("\tinput email")
user = driver.find_element(By.ID, 'user_email')
user.send_keys(USERNAME)
time.sleep(random.randint(1, 3))
print("\tinput pwd")
pw = driver.find_element(By.ID, 'user_password')
pw.send_keys(PASSWORD)
time.sleep(random.randint(1, 3))
print("\tclick privacy")
box = driver.find_element(By.CLASS_NAME, 'icheckbox')
box .click()
time.sleep(random.randint(1, 3))
print("\tcommit")
btn = driver.find_element(By.NAME, 'commit')
btn.click()
time.sleep(random.randint(1, 3))
Wait(driver, 60).until(
EC.presence_of_element_located((By.XPATH, REGEX_CONTINUE)))
print("\tlogin successful!")
def get_date():
driver.get(DATE_URL)
if not is_logged_in():
login()
return get_date()
else:
content = driver.find_element(By.TAG_NAME, 'pre').text
date = json.loads(content)
return date
def get_time(date):
time_url = TIME_URL % date
driver.get(time_url)
content = driver.find_element(By.TAG_NAME, 'pre').text
data = json.loads(content)
time = data.get("available_times")[-1]
print(f"Got time successfully! {date} {time}")
return time
def reschedule(date):
global EXIT
print(f"Starting Reschedule ({date})")
time = get_time(date)
driver.get(APPOINTMENT_URL)
data = {
"utf8": driver.find_element(by=By.NAME, value='utf8').get_attribute('value'),
"authenticity_token": driver.find_element(by=By.NAME, value='authenticity_token').get_attribute('value'),
"confirmed_limit_message": driver.find_element(by=By.NAME, value='confirmed_limit_message').get_attribute('value'),
"use_consulate_appointment_capacity": driver.find_element(by=By.NAME, value='use_consulate_appointment_capacity').get_attribute('value'),
"appointments[consulate_appointment][facility_id]": FACILITY_ID,
"appointments[consulate_appointment][date]": date,
"appointments[consulate_appointment][time]": time,
}
headers = {
"User-Agent": driver.execute_script("return navigator.userAgent;"),
"Referer": APPOINTMENT_URL,
"Cookie": "_yatri_session=" + driver.get_cookie("_yatri_session")["value"]
}
r = requests.post(APPOINTMENT_URL, headers=headers, data=data)
if(r.text.find('Successfully Scheduled') != -1):
msg = f"Rescheduled Successfully! {date} {time}"
send_notification(msg)
EXIT = True
else:
msg = f"Reschedule Failed. {date} {time}"
send_notification(msg)
def is_logged_in():
content = driver.page_source
if(content.find("error") != -1):
return False
return True
def print_dates(dates):
print("Available dates:")
for d in dates:
print("%s \t business_day: %s" % (d.get('date'), d.get('business_day')))
print()
last_seen = None
def get_available_date(dates):
global last_seen
def is_earlier(date):
my_date = datetime.strptime(MY_SCHEDULE_DATE, "%Y-%m-%d")
new_date = datetime.strptime(date, "%Y-%m-%d")
result = my_date > new_date
print(f'Is {my_date} > {new_date}:\t{result}')
return result
print("Checking for an earlier date:")
for d in dates:
date = d.get('date')
if is_earlier(date) and date != last_seen:
_, month, day = date.split('-')
if(MY_CONDITION(month, day)):
last_seen = date
return date
def push_notification(dates):
msg = "date: "
for d in dates:
msg = msg + d.get('date') + '; '
send_notification(msg)
if __name__ == "__main__":
login()
retry_count = 0
while 1:
if retry_count > 6:
break
try:
print("------------------")
print(datetime.today())
print(f"Retry count: {retry_count}")
print()
dates = get_date()[:5]
if not dates:
msg = "List is empty"
send_notification(msg)
EXIT = True
print_dates(dates)
date = get_available_date(dates)
print()
print(f"New date: {date}")
if date:
reschedule(date)
push_notification(dates)
if(EXIT):
print("------------------exit")
break
if not dates:
msg = "List is empty"
send_notification(msg)
#EXIT = True
time.sleep(COOLDOWN_TIME)
else:
time.sleep(RETRY_TIME)
except:
retry_count += 1
time.sleep(EXCEPTION_TIME)
if(not EXIT):
send_notification("HELP! Crashed.")