-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckin.py
executable file
·183 lines (162 loc) · 7.98 KB
/
checkin.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
#!/usr/bin/env python
"""Southwest Checkin.
Usage:
checkin.py CONFIRMATION_NUMBER FIRST_NAME LAST_NAME USER_ID TEAM_ID [--email=<email_addr> | --mobile=<phone_num>] [-v | --verbose]
checkin.py (-h | --help)
checkin.py --version
Options:
-h --help Show this screen.
-v --verbose Show debugging information.
--email=<email_addr> Email address where notification will be sent to.
--mobile=<phone_num> Phone number where text notification will be sent to.
--version Show version.
"""
from datetime import datetime
from datetime import timedelta
from dateutil.parser import parse
from docopt import docopt
from math import trunc
from tzlocal import get_localzone
import pytz
import requests
import sys
import time
import json
import bot
import uuid
pyBot = bot.Bot()
slack = pyBot.client
#API_KEY = 'l7xxb3dcccc4a5674bada48fc6fcf0946bc8'
#USER_EXPERIENCE_KEY = 'AAAA3198-4545-46F4-9A05-BB3E868BEFF5'
BASE_URL = 'https://mobile.southwest.com/api/'
CHECKIN_EARLY_SECONDS = 5
CHECKIN_INTERVAL_SECONDS = 0.25
MAX_ATTEMPTS = 40
# Pulled from proxying the Southwest iOS App
#headers = {'Host': 'mobile.southwest.com', 'Content-Type': 'application/json', 'X-API-Key': API_KEY, 'X-User-Experience-Id': USER_EXPERIENCE_KEY, 'Accept': '*/*'}
def generate_headers():
config_js = requests.get('https://mobile.southwest.com/js/config.js')
if config_js.status_code == requests.codes.ok:
modded = config_js.text[config_js.text.index("API_KEY"):]
API_KEY = modded[modded.index(':') + 1:modded.index(',')].strip('"')
else:
print("Couldn't get API_KEY")
sys.exit(1)
USER_EXPERIENCE_KEY = str(uuid.uuid1()).upper()
# Pulled from proxying the Southwest iOS App
return {'Host': 'mobile.southwest.com', 'Content-Type': 'application/json', 'X-API-Key': API_KEY, 'X-User-Experience-Id': USER_EXPERIENCE_KEY, 'Accept': '*/*'}
# You might ask yourself, "Why the hell does this exist?"
# Basically, there sometimes appears a "hiccup" in Southwest where things
# aren't exactly available 24-hours before, so we try a few times
def safe_request(url, body=None):
try:
attempts = 0
headers = generate_headers()
while True:
if body is not None:
r = requests.post(url, headers=headers, json=body)
else:
r = requests.get(url, headers=headers)
data = r.json()
if 'httpStatusCode' in data and data['httpStatusCode'] in ['NOT_FOUND', 'BAD_REQUEST', 'FORBIDDEN']:
if 'message' in data and 'Reservation could not be retrieved' in data['message']:
pyBot.checkin_response(team_id, user_id, "Cannot find res")
sys.exit("Cant find res")
attempts += 1
print(data['message'])
if attempts > MAX_ATTEMPTS:
sys.exit("Unable to get data, killing self")
time.sleep(CHECKIN_INTERVAL_SECONDS)
continue
return data
except ValueError:
# Ignore responses with no json data in body
pass
def lookup_existing_reservation(number, first, last):
# Find our existing record
url = "{}mobile-misc/v1/mobile-misc/page/view-reservation/{}?first-name={}&last-name={}".format(BASE_URL, number, first, last)
data = safe_request(url)
return data['viewReservationViewPage']
def get_checkin_data(number, first, last):
url = "{}mobile-air-operations/v1/mobile-air-operations/page/check-in/{}?first-name={}&last-name={}".format(BASE_URL, number, first, last)
data = safe_request(url)
return data['checkInViewReservationPage']
def checkin(number, first, last):
data = get_checkin_data(number, first, last)
info_needed = data['_links']['checkIn']
url = "{}mobile-air-operations{}".format(BASE_URL, info_needed['href'])
print("Attempting check-in...")
pyBot.checkin_response(team_id, user_id,"Attempting check-in...")
return safe_request(url, info_needed['body'])['checkInConfirmationPage']
def send_notification(checkindata, emailaddr=None, mobilenum=None):
info_needed = checkindata['_links']['boardingPasses']
url = "{}mobile-air-operations{}".format(BASE_URL, info_needed['href'])
mbpdata = safe_request(url, info_needed['body'])
info_needed = mbpdata['checkInViewBoardingPassPage']['_links']
url = "{}mobile-air-operations{}".format(BASE_URL, info_needed['href'])
if emailaddr:
info_needed['body']['mediaType'] = 'EMAIL'
info_needed['body']['emailAddress'] = emailaddr
if mobilenum:
info_needed['body']['mediaType'] = 'SMS'
info_needed['body']['phoneNumber'] = mobilenum
print("Attempting to send boarding pass...")
safe_request(url, info_needed['body'])
def schedule_checkin(flight_time, number, first, last, user_id, team_id, mobile, email):
checkin_time = flight_time - timedelta(days=1)
current_time = datetime.now(pytz.utc).astimezone(get_localzone())
# check to see if we need to sleep until 24 hours before flight
if checkin_time > current_time:
# calculate duration to sleep
delta = (checkin_time - current_time).total_seconds() - CHECKIN_EARLY_SECONDS
# pretty print our wait time
m, s = divmod(delta, 60)
h, m = divmod(m, 60)
print("Too early to check in. Waiting {} hours, {} minutes, {} seconds".format(trunc(h), trunc(m), s))
pyBot.checkin_response(team_id, user_id, "Too early to check in. Waiting {} hours, {} minutes, {} seconds".format(trunc(h), trunc(m), s))
time.sleep(delta)
data = checkin(number, first, last)
for flight in data['flights']:
for doc in flight['passengers']:
print("{} got {}{}!".format(doc['name'], doc['boardingGroup'], doc['boardingPosition']))
pyBot.checkin_response(team_id, user_id, "{} got {}{}!".format(doc['name'], doc['boardingGroup'], doc['boardingPosition']))
if email:
send_notification(data, emailaddr=email)
elif mobile:
send_notification(data, mobilenum=mobile)
def auto_checkin(reservation_number, first_name, last_name, user_id, team_id, email=None, mobile=None):
body = lookup_existing_reservation(reservation_number, first_name, last_name)
# Get our local current time
now = datetime.now(pytz.utc).astimezone(get_localzone())
tomorrow = now + timedelta(days=1)
# find all eligible legs for checkin
for leg in body['bounds']:
# calculate departure for this leg
airport = "{}, {}".format(leg['departureAirport']['name'], leg['departureAirport']['state'])
takeoff = "{} {}".format(leg['departureDate'], leg['departureTime'])
tzrequest = {'iata': leg['departureAirport']['code'],
'country': 'ALL',
'db': 'airports',
'iatafilter': 'true',
'action': 'SEARCH',
'offset': '0'}
tzresult = requests.post("https://openflights.org/php/apsearch.php", tzrequest)
airport_tz = pytz.timezone(json.loads(tzresult.text)['airports'][0]['tz_id'])
date = airport_tz.localize(datetime.strptime(takeoff, '%Y-%m-%d %H:%M'))
if date > now:
# found a flight for checkin!
print("Flight information found, departing {} at {}".format(airport, date.strftime('%b %d %I:%M%p')))
pyBot.checkin_response(team_id, user_id, "Flight information found, departing {} at {}".format(airport, date.strftime('%b %d %I:%M%p')))
schedule_checkin(date, reservation_number, first_name, last_name, user_id, team_id, email, mobile)
if __name__ == '__main__':
arguments = docopt(__doc__, version='Southwest Checkin 0.2')
print(arguments)
# work work
reservation_number = arguments['CONFIRMATION_NUMBER']
first_name = arguments['FIRST_NAME']
last_name = arguments['LAST_NAME']
user_id = arguments['USER_ID']
team_id = arguments['TEAM_ID']
email = arguments['--email']
mobile = arguments['--mobile']
auto_checkin(reservation_number, first_name, last_name, user_id, team_id, email, mobile)