More full-featured version of the Southwest airlines checkin program that I submitted several years ago. This version includes a GUI and adds support for multiple passengers and multiple flight legs. Also fixed tons of bugs, added threads, and fixed the time zone issues.
| Python |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 | #! /usr/local/bin/python
# ========================================================================
# (c) Copyright belongs to Ken Washington
# All rights reserved
# ========================================================================
# imports
import os
import re
import sys
import time
import sched
import string
import urllib
import httplib
import thread
from HTMLParser import HTMLParser
from Tkinter import *
# ========================================================================
# Change log and instructions
#
# Jan 20
# converted text interface to a class
# implemented thread for the wait function
# miscelleneous clean up and debugging
#
# Jan 18
# added GUI with timer capability
# enhanced error checking before trying to retrieve flights
# replaced hardwired debug files with static array
# added support for multiple flyers
# added support for multiple flight segments
# completely rewrote the logic to retrieve flight information
# changed routines to return error codes instead of hard crash
#
#
# the DEBUG_SCH should be 0 to run delayed scheduling automatically
# set to 1 in non-GUI mode, skip use of time.sleep if we are not within 24 hours
# immediate calls to the Internet will be made if within 24 hrs
# note - this is treated like 0 for GUI mode
# set to 2 to simulate Internet calls. Locally saved .htm files
# must be present with specific names for this to work
# set to 3 for additional debug printout statements - for code checking
# ========================================================================
confirmation = 'ABCDEF'
firstname = 'Firstname'
lastname = 'Lastname'
# ========================================================================
DEBUG_SCH = 2
is_GUI = True
# debugfiles = ["retrieveItinerary.html", "viewPnr.htm", "retrieveCheckinDoc.html", "selectBoardingPass.htm", "viewBoardingPass.htm"]
# debugfiles = ["retrieveItinerary.html", "viewPnr-error.htm", "retrieveCheckinDoc.html", "selectBoardingPass-error.htm", "viewBoardingPass.htm"]
debugfiles = ["retrieveItinerary.html", "viewPnr-dual.htm", "retrieveCheckinDoc.html", "selectBoardingPass-dual.htm", "viewBoardingPass-dual.htm"]
# ========================================================================
# fill in these parameters if you want the script to email you
# to disable make the emailaddr = None
emailaddr = ""
smtpserver = "smtpout.secureserver.net"
smtpauth = False
smtpport = 80
smtpuser = "username"
smtppass = "password"
# ========================================================================
# fixed page locations and parameters - updated to bypass Ajax front page
# DO NOT change these parameters
main_url = 'www.southwest.com'
checkin_url = '/content/travel_center/retrieveCheckinDoc.html'
retrieve_url = '/travel_center/retrieveItinerary.html'
defaultboxes = ["recordLocator", "firstName", "lastName"]
months = "JanFebMarAprMayJunJulAugSepOctNovDec"
# ========================================================================
# =========== function definitions =======================================
# this is a parser for the Southwest pages
class HTMLSouthwestParser(HTMLParser):
def __init__(self, swdata):
self._reset()
HTMLParser.__init__(self)
# if a web page string is passed, feed it
if swdata != None and len(swdata)>0:
self.feed(swdata)
self.close()
def _reset(self):
self.searchtags = []
self.hiddentags = [] # {} change to a list of tuples
self.searchaction = ""
self.formaction = ""
self.is_search = False
self.textnames = []
# override the feed function to reset our parameters
# and then call the original feed function
def feed(self, formdata):
self._reset()
HTMLParser.feed(self, formdata)
# handle tags in web pages
# this is where the real magic is done
def handle_starttag(self, tag, attrs):
if tag=="input":
ishidden = False
ischeckbox = False
istext = False
issubmit = False
thevalue = ""
thename = None
for attr in attrs:
if attr[0]=="type":
if attr[1]=="hidden":
ishidden= True
elif attr[1]=="checkbox" or attr[1]=="radio":
ischeckbox = True
elif attr[1]=="text":
istext = True
elif attr[1]=="submit":
issubmit = True
elif attr[0]=="name":
thename= attr[1]
istext = True
elif attr[0]=="value":
thevalue= attr[1]
# store the tag for search forms separately
# from the tags for non-search forms
if ishidden or ischeckbox:
if self.is_search:
self.searchtags.append( (thename,thevalue) )
else:
self.hiddentags.append( (thename,thevalue) )
# otherwise, append the name of the text fields
elif istext and self.is_search==False and issubmit==False:
self.textnames.append(thename)
elif tag=="form":
for attr in attrs:
if attr[0]=="action":
theaction = attr[1]
# check to see if this is a search form
if theaction.find("search") > 0:
self.searchaction = theaction
self.is_search = True
else:
self.formaction = theaction
self.is_search = False
# function to send an simple text email message
def sendEmail(wdata, emailaddr, smtpserver, smtpport= 25, \
smtpauth=False, smtpuser="", smtppass=""):
import smtplib
from email.MIMEText import MIMEText
# Create a text/plain message
msg = MIMEText(wdata)
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'Results of Southwest checkin script'
msg['From'] = emailaddr
msg['To'] = emailaddr
s = smtplib.SMTP()
# connect on the designated port - will be 25 or 80
try:
s.connect(smtpserver, 80)
except Exception, connerror:
print connerror.__class__, connerror
return False
if smtpauth:
try:
s.login(smtpuser, smtppass)
except Exception, connerror:
print connerror.__class__, connerror
return False
try:
s.sendmail(emailaddr, emailaddr, msg.as_string())
except Exception, connerror:
print connerror.__class__, connerror
return False
s.close()
return True
# this function reads a URL and returns the text of the page
def ReadUrl(host, req):
wdata = ""
try:
conn = httplib.HTTPConnection(host)
conn.request("GET", req)
resp = conn.getresponse()
except:
print "Error: Cannot connect in GET mode to ", host+req
sys.exit(1)
if resp.status == 200:
wdata = resp.read()
else:
print "Error: Cannot read data from ", host+req
print "Response: ", resp.status, resp.reason
sys.exit(1)
return wdata
# this function sends a post just like you clicked on a submit button
def PostUrl(host, req, dparams):
wdata = ""
params = urllib.urlencode(dparams)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
try:
conn = httplib.HTTPConnection(host)
conn.request("POST", req, params, headers)
resp = conn.getresponse()
except:
print "Error: Cannot connect in POST mode to ", host+req
print "Params = ", dparams
sys.exit(1)
if resp.status == 200:
wdata = resp.read()
else:
print "Error: Cannot post data to ", host+req
print "Params = ", dparams
print "Response: ",resp.status, resp.reason
sys.exit(1)
return wdata
# fill the confirmation and name boxes for the standard Southwest query post
def setInputBoxes(textnames, conf_number, first_name, last_name):
if len(textnames) == 3:
boxes = textnames
else:
boxes = default_boxes
params = {}
params[boxes[0]] = conf_number
params[boxes[1]] = first_name
params[boxes[2]] = last_name
return params
# return time zone for a specific airport code
def airportCodeTZ(code):
airportzone = {}
airportzone["ALB"] = "US/Eastern"
airportzone["ABQ"] = "US/Mountain"
airportzone["AMA"] = "US/Central"
airportzone["AUS"] = "US/Central"
airportzone["BWI"] = "US/Eastern"
airportzone["BHM"] = "US/Central"
airportzone["BOI"] = "US/Mountain"
airportzone["BUF"] = "US/Eastern"
airportzone["BUR"] = "US/Pacific"
airportzone["MDW"] = "US/Central"
airportzone["CLE"] = "US/Eastern"
airportzone["CMH"] = "US/Eastern"
airportzone["CRP"] = "US/Central"
airportzone["DAL"] = "US/Central"
airportzone["DEN"] = "US/Mountain"
airportzone["DTW"] = "US/Eastern"
airportzone["ELP"] = "US/Mountain"
airportzone["FLL"] = "US/Eastern"
airportzone["RSW"] = "US/Eastern"
airportzone["HRL"] = "US/Central"
airportzone["BDL"] = "US/Eastern"
airportzone["HOU"] = "US/Central"
airportzone["IND"] = "US/Eastern"
airportzone["JAN"] = "US/Central"
airportzone["JAX"] = "US/Eastern"
airportzone["MCI"] = "US/Central"
airportzone["LAS"] = "US/Pacific"
airportzone["LIT"] = "US/Central"
airportzone["ISP"] = "US/Eastern"
airportzone["LAX"] = "US/Pacific"
airportzone["SDF"] = "US/Eastern"
airportzone["LBB"] = "US/Central"
airportzone["MHT"] = "US/Eastern"
airportzone["MAF"] = "US/Central"
airportzone["BNA"] = "US/Central"
airportzone["MSY"] = "US/Central"
airportzone["ORF"] = "US/Eastern"
airportzone["OAK"] = "US/Pacific"
airportzone["OKC"] = "US/Central"
airportzone["OMA"] = "US/Central"
airportzone["ONT"] = "US/Pacific"
airportzone["SNA"] = "US/Pacific"
airportzone["MCO"] = "US/Eastern"
airportzone["PHL"] = "US/Eastern"
airportzone["PHX"] = "US/Arizona"
airportzone["PIT"] = "US/Eastern"
airportzone["PDX"] = "US/Pacific"
airportzone["PVD"] = "US/Eastern"
airportzone["RDU"] = "US/Eastern"
airportzone["RNO"] = "US/Pacific"
airportzone["SMF"] = "US/Pacific"
airportzone["SLC"] = "US/Mountain"
airportzone["SAT"] = "US/Central"
airportzone["SAN"] = "US/Pacific"
airportzone["SJC"] = "US/Pacific"
airportzone["SFO"] = "US/Pacific"
airportzone["SEA"] = "US/Pacific"
airportzone["GEG"] = "US/Pacific"
airportzone["STL"] = "US/Central"
airportzone["TPA"] = "US/Eastern"
airportzone["TUS"] = "US/Arizona"
airportzone["TUL"] = "US/Central"
airportzone["IAD"] = "US/Eastern"
airportzone["PBI"] = "US/Eastern"
# use pacific as default if not found
try:
TZcode = airportzone[code]
except:
TZcode = "US/Pacific"
return TZcode
# determine if the information provided is valid or not
def checkValidFlight(the_url, conf_number, first_name, last_name):
if DEBUG_SCH > 1:
fd = open(debugfiles[0],"r")
swdata = fd.read(-1)
fd.close()
else:
swdata = ReadUrl(main_url, the_url)
if swdata==None or len(swdata)==0:
return False, "Error: no data returned from " +main_url+the_url
gh = HTMLSouthwestParser(swdata)
# get the post action name from the parser
post_url = gh.formaction
if post_url==None or post_url=="":
return False, "Error: no POST action found in " + main_url+the_url
# load the parameters into the text boxes
params = setInputBoxes(gh.textnames, conf_number, first_name, last_name)
# submit the request to pull up the reservations on this confirmation number
if DEBUG_SCH > 1:
fd = open(debugfiles[1],"r")
reservations = fd.read(-1)
fd.close()
else:
reservations = PostUrl(main_url, post_url, params)
if reservations==None or len(reservations)==0:
return False, "Error: no reservation found for confirmation number: " + conf_number+ " at URL = "+ main_url+post_url
# check for the southwest error header image or the What happened text
errloc1 = reservations.find("http://www.southwest.com/images/error_header.gif")
errloc2 = reservations.find("What happened?")
goodloc1 = reservations.find("Flight Information")
goodloc2 = reservations.find("bookingFormText")
if (errloc1>0 or errloc2>0 or goodloc1<0 or goodloc2<0):
return False, "Southwest was unable to identify a reservation\nConfirmation: "+conf_number+" Name: "+first_name+" "+last_name
return True, reservations
# this routine extracts the departure date and time
# completely rewritten to do multiple passengers and multple legs
def getFlightInfo(reservations):
depart_date = []
depart_time = []
depart_tz = []
arrive_time = []
arrive_tz = []
flyers = []
now = time.time()
current_time = time.localtime(now)
thisyear = current_time[0];
thismonth = time.strftime("%b",current_time)
# first parse the reservations file to determine number of travelers
numflyers = reservations.count("bookingConfirmation")
flyersre = re.compile("bookingFormText\"\>([A-Za-z]* [A-Za-z]*) ")
flyers = flyersre.findall(reservations)
# find start of the search proces
pagestart = reservations.find("Flight Information")
# parse the departure information using regular expressions
# 0= City, 1= Airport, 2= Time, 3= City, 4= Airport, 5= Time
depre = re.compile("Depart ([A-Za-z. -]*)\((...)\) at (\d{1,2}\:\d{1,2}[apAP][mM])\<br\>Arrive in ([A-Za-z. -]*)\((...)\) at (\d{1,2}\:\d{1,2}[apAP][mM])")
dateinfo = depre.findall(reservations, pagestart)
numlegs = len(dateinfo)
bookoptpre = re.compile("bookingOptionsHeader\"\>([A-Za-z. -]*) to ([A-Za-z. -]*)")
cities = bookoptpre.findall(reservations, pagestart)
# get the booking table contents in groups of 5
# bookings_re = re.compile("bookingFormText\"\>(.*)\<\/td\>", pagestart)
monthre = re.compile("bookingFormText\"\>([A-Za-z]{1,3} \d{1,2})")
flymonths = monthre.findall(reservations)
numcities = len(cities)
if ( numcities == 0 ):
print "Problem parsing the departure and destination cities"
sys.exit(2)
city = 0
i = 0
iret = 0
km = 0
# get the first month and a guess at the year based on when we are running this
oldmonth = flymonths[0][:3]
oldyear = thisyear
# back up to prior year if we are running the script in a new year
if (months.find(oldmonth) > months.find(thismonth)):
oldyear = oldyear-1
while ( city < numcities):
# get the first departing leg
i = iret
while ( i < numlegs ):
if (dateinfo[i][0] == cities[city][0]):
depart_time.append(dateinfo[i][2])
depart_tz.append(airportCodeTZ(dateinfo[i][1]))
# get the month
to_month = flymonths[km][:3]
if (months.find(to_month) < months.find(oldmonth)):
oldmonth = to_month
oldyear = oldyear+1
# set the departure date as Month dd, Year
thedate = flymonths[km] + ", "+str(oldyear)
depart_date.append(thedate)
km = km + 1
if (dateinfo[i][3] == cities[city][1]):
arrive_time.append(dateinfo[i][5])
arrive_tz.append(airportCodeTZ(dateinfo[i][4]))
iret = i+1
break
i = i+1
city = city + 1
if DEBUG_SCH>2:
print "Flyers= ", flyers, "\nCities= ", cities
print numlegs, " Flight legs\nRaw dateinfo: ", dateinfo
print "Depart date, time, zone: ", depart_date, depart_time, depart_tz
print "Arrive time, zone: ", arrive_time, arrive_tz
# now we include the time zones so we can create a UTC time conversion later
# departure = (to_date, to_depart_time, to_arrive_time, to_tz, to_dest_tz, \
# fr_date, fr_depart_time, fr_arrive_time, fr_tz, fr_dest_tz )
# return departure information and flyer count information
return (depart_date, depart_time, depart_tz, arrive_time, arrive_tz, flyers, cities)
# main processing of the boarding pass on the Internet
# whatever flight is ready to be processed will be done here
def getBoardingPass(the_url, conf_number, first_name, last_name, leg):
checkin = False
# read the southwest checkin web site
if DEBUG_SCH > 1:
fd = open(debugfiles[2],"r")
swdata = fd.read(-1)
fd.close()
else:
swdata = ReadUrl(main_url, the_url)
if swdata==None or len(swdata)==0:
msg = "Error: no data returned from " + main_url+the_url
return (checkin, msg)
# sys.exit(1)
# parse the data
gh = HTMLSouthwestParser(swdata)
# get the post action name from the parser
post_url = gh.formaction
if post_url==None or post_url=="":
print "Error: no POST action found in ", main_url+the_url
sys.exit(1)
# load the parameters into the text boxes by name
# where the names are obtained from the parser
params = setInputBoxes(gh.textnames, conf_number, first_name, last_name)
if DEBUG_SCH > 2:
print "Submit textboxes: ",params
# submit the request to pull up the reservations
if DEBUG_SCH > 1:
fd = open(debugfiles[3],"r")
reservations = fd.read(-1)
fd.close()
else:
reservations = PostUrl(main_url, post_url, params)
if reservations==None or len(reservations)==0:
msg = "Error: no data returned from " + main_url+post_url
# print Params = ", params
return (checkin, msg)
# sys.exit(1)
# parse the returned reservations page
rh = HTMLSouthwestParser(reservations)
# Extract the name of the post function to check into the flight
final_url = rh.formaction
# the returned web page contains three unique security-related hidden fields
# plus a dynamically generated value for each checkbox or radio button for every passenger
# these must be sent to the next submit post to work properly
# they are obtained from the parser object
params = rh.hiddentags
if DEBUG_SCH > 2:
print "Hidden submit checkboxes: ",params
if len(params) < 4:
msg = "Error: Fewer than the expect 4 special fields returned from " + main_url+post_url
# print " Params = ", params
return (checkin, msg)
# sys.exit(1)
# finally, lets check in the flight and make our success file
if DEBUG_SCH > 1:
fd = open(debugfiles[4],"r")
checkinresult = fd.read(-1)
fd.close()
else:
checkinresult = PostUrl(main_url, final_url, params)
# write the returned page to a file for later inspection
if checkinresult==None or len(checkinresult)==0:
msg = "Error: no data returned from " + main_url+final_url
# print "Params = ", params
return (checkin, msg)
# sys.exit(1)
# always save the returned file for later viewing - each leg gets its own version
bpname = "boardingpass_"+str(leg)+".htm"
fd = open(bpname,"w")
fd.write(checkinresult)
fd.close()
# look for what boarding letter and number we got in the file
# now we use re for both letter and number
checkin = True
myre = re.compile("boarding[ABC]\.gif")
bgroup = myre.findall(checkinresult)
if (len(bgroup) >0):
bletter = bgroup[0][8]
else:
bletter = "Unknown"
# logic below allows a valid letter and an unknown number
myre2 = re.compile("boarding(\d).gif")
bnumarr = myre2.findall(checkinresult)
if(len(bnumarr) > 0):
bnumber = bnumarr[0]
else:
bnumber = "Unknown"
if (len(bnumarr) > 1):
bnumber = bnumber + bnumarr[1]
if len(bgroup)>0:
msg = "Boarding group = " + bletter + " Boarding number = " + bnumber
else:
msg = "Boarding group and number are unknown"
# email this information to self if requested
if emailaddr and len(emailaddr)>0:
try:
sendEmail(msg, emailaddr, smtpserver, smtpport, smtpauth, smtpuser, smtppass)
except:
msg = msg + "\nUnable to email result to " + emailaddr
return (checkin, msg)
# determine the time when we can submit checkin successfully and a message
def getDelay(leave_time, now):
# start with 24 hours before departure and pad it by 1 minute just to be sure
sched_time = leave_time - 24.0*3600.0
sched_time = sched_time + 60.0
# now = time.time()
sec_left = int(sched_time - now)
abssec = abs(sec_left)
days = abssec / (3600*24)
hours = (abssec - days*24*3600) / 3600
minutes = (abssec - days*24*3600 - hours*3600) / 60
seconds = abssec - days*24*3600 - hours*3600 - minutes*60
# print "Departure time: ", time.strftime("%A %B %d, %Y at %I:%M %p",leave_time)
# print a different message if the time to check in ahead of time is in the past
if ( sec_left <= 0 ):
msg = "Checkin time was %d days, %d hrs, %d min, %d seconds ago." % \
(days, hours, minutes, seconds)
else:
msg = "%d days, %d hrs, %d min, %d seconds to check in." % \
(days, hours, minutes, seconds)
return (sec_left, msg)
# modified paul's routine to use the year from earlier logic
# and replace the Unix specific time zone trick with a generic one
def makedate(monthdayyear, daytime, TZ):
# the following code doesn't work on Windows
# os.environ['TZ'] = TZ
# time.tzset()
# need to enter number of seconds for each TZ instead
# set the time zone delta based on the name
tzdelta = 8
if ( TZ == "US/Eastern" ):
tzdelta = 5
if ( TZ == "US/Central" ):
tzdelta = 6
if ( TZ == "US/Mountain" ):
tzdelta = 7
if ( TZ == "US/Arizona" ):
tzdelta = 7
if ( TZ == "US/Pacific" ):
tzdelta = 8
to_time = "%s %s" % (monthdayyear, daytime)
time_struct = time.strptime(to_time, "%b %d, %Y %I:%M%p")
time_UTC = time.mktime(time_struct)+tzdelta*3600.0
time_struct = time.localtime(time_UTC)
# print to_time, " ", time_struct, " ", time_UTC
return (time_UTC, time_struct)
def getCurrentTime():
# get the current time
now = time.time()
local_time = time.localtime(now)
current_date = time.strftime("%b %d, %Y", local_time)
current_time = time.strftime("%I:%M%p", local_time)
current_zone = time.tzname[0]
struct_UTC = time.gmtime(now)
current_UTC = time.mktime(struct_UTC)
return (local_time, current_date, current_time, current_zone, current_UTC, struct_UTC)
# produce a printable string of flight information for both user interfaces
def showFlightInfo(depart_date, depart_time, depart_tz, arrive_time, arrive_tz, confnum, firstname, lastname, flyers, cities):
(local_time, current_date, current_time, current_tz, current_UTC, struct_UTC) = getCurrentTime()
msg = "Current date: "+current_date+" "+current_time+" "+current_tz
# print "Current UTC: ", current_UTC
if DEBUG_SCH>2:
msg = msg + "\n" + "Current UTC: "+time.strftime("%b %d, %Y %I:%M%p UTC", struct_UTC)
msg = msg + "\n" + "================================================================="
msg = msg + "\n "
k = 0
while ( k < len(depart_date) ):
(depart_UTC, depart_struct) = makedate(depart_date[k], depart_time[k], depart_tz[k])
(arrive_UTC, arrive_struct) = makedate(depart_date[k], arrive_time[k], arrive_tz[k])
msg = msg + "\nDepart from: "+cities[k][0]+" "+depart_date[k]+" "+depart_time[k]+" "+depart_tz[k]
if DEBUG_SCH>2:
msg = msg + "\nDeparture UTC : "+time.strftime("%b %d, %Y %I:%M%p UTC", depart_struct)
msg = msg + "\nArrive in: "+cities[k][1]+" "+depart_date[k]+" "+arrive_time[k]+" "+arrive_tz[k]
if DEBUG_SCH>2:
msg = msg + "\nArrival UTC : "+time.strftime("%b %d, %Y %I:%M%p UTC", arrive_struct)
# find the time when we can check in within the 24 hour time window
(timeleft, delayText) = getDelay(depart_UTC, current_UTC)
msg = msg + "\n-----------------------------------------------------------------"
msg = msg + "\n"+delayText
msg = msg + "\n=================================================================\n"
k = k+1
return msg
# return index of the next leg that is in the future to process
def getNextleg(depart_date, depart_time, depart_tz, checkedin):
nextleg = -1
k = 0
(local_time, current_date, current_time, current_tz, current_UTC, current_struct) = getCurrentTime()
while ( k < len(depart_date) ):
if ( not checkedin[k] ):
(depart_UTC, depart_struct) = makedate(depart_date[k], depart_time[k], depart_tz[k])
if ( depart_UTC > current_UTC ):
nextleg = k
break
# try the next leg
k = k+1
return nextleg
# class to process flight reservations in non-GUI mode
class TextFlight:
def __init__(self, confirmation, firstname, lastname):
self.confirmation = confirmation
self.firstname = firstname
self.lastname = lastname
self.isvalid = False
self.alldone = False
self.is_retrieve = False
# retrieve the flight information and start a thread
self.Retrieve()
if (self.isvalid):
self.mythread = thread.start_new_thread(self.Checkin, (1,) )
else:
self.alldone = True
# get flight information in non-GUI mode
def Retrieve(self):
self.is_retrieve = False
self.isvalid, reservations = checkValidFlight(retrieve_url, self.confirmation, self.firstname, self.lastname)
if (not self.isvalid):
print reservations
return
# get the passenger and flight information and print it
(depart_date, depart_time, depart_tz, arrive_time, arrive_tz, flyers, cities) = \
getFlightInfo(reservations)
print "================================================================="
print "Confirmation number: ", confirmation
print "First Name used to check in: ", firstname
print "Last Name used to check in: ", lastname
print "-----------------------------------------------------------------"
print "Passengers available for check in: ", len(flyers)
for flyer in flyers:
print flyer
print "================================================================="
# primary flight leg information printout
msg = showFlightInfo(depart_date, depart_time, depart_tz, arrive_time, arrive_tz, confirmation, firstname, lastname, flyers, cities)
print msg
# save the flight information for later use
self.depart_date = depart_date
self.depart_time = depart_time
self.depart_tz = depart_tz
self.arrive_time = arrive_time
self.arrive_tz = arrive_tz
self.flyers = flyers
self.cities = cities
self.is_retrieve = True
self.printflag = 0
self.checkedin = []
for k in range(len(depart_date)):
self.checkedin.append(False)
# routine that we run in a thread to perform repeat processing
# when this thread finishes we set the alldone variable
def Checkin(self, thread_id):
if (not self.isvalid):
self.alldone= True
return
while ( not self.alldone ):
(local_time, current_date, current_time, current_tz, current_UTC, current_struct) = getCurrentTime()
clockstr = time.strftime("%a %B %d, %Y %I:%M:%S %p", current_struct)
k = -1
dt = 1
timedelay = 15
self.printflag = self.printflag + timedelay
k = getNextleg(self.depart_date, self.depart_time, self.depart_tz, self.checkedin)
if (k >= 0):
(depart_UTC, depart_struct) = makedate(self.depart_date[k], self.depart_time[k], self.depart_tz[k])
(dt, timemsg) = getDelay(depart_UTC, current_UTC)
# print a status string every two minutes
if (self.printflag > 120):
self.printflag = 0
print "Waiting... "
print timemsg
if (dt > 0 and DEBUG_SCH > 1):
simpause = "\n.............................................."
simpause = simpause + "\nSimulated debug pause for "+str(dt)+" sec"
simpause = simpause + "\n.............................................."
print simpause
dt = 0
# check in if time left is zero
if (k>=0 and dt<=0 and (not self.checkedin[k])):
self.checkedin[k] = self.textCheckin(k)
if ( k < len(self.checkedin)-1 ):
print "Moving on to the next leg: "+self.cities[k+1][0]+" to "+self.cities[k+1][1]+"\n"
timedelay = 1
else:
print "Done processing all flight legs\n"
self.alldone = True
if (self.is_retrieve and k<0):
print "All flights checked in or are in the past"
self.alldone = True
# repeat loop
if (not self.alldone): time.sleep(timedelay)
# check in and print result
def textCheckin(self, k):
(checkedin, checkinText) = getBoardingPass(checkin_url, self.confirmation, self.firstname, self.lastname, k)
if ( checkedin ):
checkinText = "\n" + self.cities[k][0]+" to " + self.cities[k][1] + " checked in successfully\n" + checkinText
else:
checkinText = "\nFailed to check in\n" + checkinText
print checkinText
return checkedin
# =========== user interface functions ===================================
class GuiFlight:
def __init__(self, labels, entrysize, parent=None):
self.root = parent
self.is_retrieve = False
self.maxflyers = 10
self.showtimer = True
# =============================================================================================================
box = Frame(self.root)
box.pack(expand=YES, padx=10, pady=10, fill=X)
# -------------------------------------------------------------------------------------------------------------
clockrow = Frame(box, bd=2, relief=GROOVE)
clockrow.grid(row=1, column=0, sticky=NW, padx=10, pady=5)
Label(clockrow, text="Current UTC time: ", width=25).grid(row=0, column=0, sticky=NW, padx=2, pady=2)
self.wallclock = Entry(clockrow, width=50)
self.wallclock.grid(row=0, column=1, sticky=NW, padx=10, pady=2)
Label(clockrow, text="Next UTC Departure: ", width=25).grid(row=1, column=0, sticky=NW, padx=2, pady=2)
self.departclock = Entry(clockrow, width=50)
self.departclock.grid(row=1, column=1, sticky=NW, padx=10, pady=2)
Label(clockrow, text="Flying from/to: ", width=25).grid(row=2, column=0, sticky=NW, padx=2, pady=2)
self.cityfield = Entry(clockrow, width=50)
self.cityfield.grid(row=2, column=1, sticky=NW, padx=10, pady=2)
Label(clockrow, text="Time before checkin: ", width=25).grid(row=3, column=0, sticky=NW, padx=2, pady=2)
self.timeleft = Entry(clockrow, width=50)
self.timeleft.grid(row=3, column=1, sticky=NW, padx=10, pady=2)
rows = Frame(box, bd=2, relief=GROOVE)
rows.grid(row=0, column=0, sticky=NSEW, padx=10, pady=5)
# -------------------------------------------------------------------------------------------------------------
lcol = Frame(rows)
lcol.pack(side=LEFT, padx=5, pady=5, fill=Y)
rcol = Frame(rows)
rcol.pack(side=LEFT, padx=5, pady=5, expand=YES, fill=BOTH)
i = 0
self.content = {} # empty dictionary with content
for label in labels:
Label(lcol, text=label).pack(side=TOP, pady=2)
entry = Entry(rcol, width=entrysize[i])
entry.pack(side=TOP, fill=X, pady=2)
self.content[label] = entry
i= i+1
if DEBUG_SCH>0:
Label(lcol, text="*** Debug Mode = "+str(DEBUG_SCH)+" ***").pack(side=TOP, pady=4)
# =============================================================================================================
buttons = Frame(rows, width=30)
buttons.pack(side=RIGHT, padx=5, pady=5, fill=Y)
# buttons.grid(row=0, column=1, sticky=NE, padx=5, pady=5)
# -------------------------------------------------------------------------------------------------------------
Button(buttons, text='Checkin Flight', width=16, command=self.onRetrieve).pack(side=TOP, pady=2)
Button(buttons, text='Reset', width=16, command=self.onReset).pack(side=TOP, pady=2)
# Button(buttons, text='Options', width=16, command=self.onOptions).pack(side=TOP, pady=2)
Button(buttons, text='Quit', width=16, command=self.onCancel).pack(side=TOP, pady=2)
# =============================================================================================================
flightbox = Frame(box, bd=2, relief=GROOVE)
flightbox.grid(row=2, column=0, sticky=NW, padx=5, pady=5)
# -------------------------------------------------------------------------------------------------------------
lcol = Frame(flightbox)
lcol.pack(side=LEFT, padx=5, pady=5, fill=Y)
rcol = Frame(flightbox)
rcol.pack(side=RIGHT, padx=5, pady=5, expand=YES, fill=X)
self.flyerfields = []
Label(lcol, text="Passengers:").pack(side=TOP, pady=2)
for i in range(self.maxflyers):
flyerlabel = Entry(lcol, width=25, state="disabled")
flyerlabel.pack(side=TOP, fill=X, pady=2)
self.flyerfields.append(flyerlabel)
# =============================================================================================================
# flightbox2 = Frame(box, bd=2, relief=SUNKEN)
# flightbox2.grid(row=1, column=1, sticky=NSEW, padx=10, pady=10)
# -------------------------------------------------------------------------------------------------------------
Label(rcol, text="Flight Information:").pack(side=TOP, padx=2, pady=2)
self.flightinfo = Text(rcol, height=20, width=70, state="disabled")
self.flightinfo.pack(side=TOP, expand=YES, fill=BOTH, padx=2, pady=2)
# reset all variables and start the timer
self.onReset()
self.updateClock()
def updateHidden(self, field, str):
field.config(state="normal")
field.delete(0,END)
field.insert(0, str)
field.config(state="readonly")
return field
def updateFlightinfo(self, str):
self.flightinfo.config(state="normal")
self.flightinfo.insert(END, str)
self.flightinfo.config(state="disabled")
def onRetrieve(self):
self.onReset()
self.is_retrieve = False
confirmation = self.content["Confirmation"].get()
firstname = self.content["Firstname"].get()
lastname = self.content["Lastname"].get()
isvalid, reservations = checkValidFlight(retrieve_url, confirmation, firstname, lastname)
if (not isvalid):
self.updateHidden(self.flyerinfo,reservations)
return
(depart_date, depart_time, depart_tz, arrive_time, arrive_tz, flyers, cities) = \
getFlightInfo(reservations)
k = 0
for flyer in flyers:
self.updateHidden(self.flyerfields[k],flyer)
k = k+1
if (k >= self.maxflyers): break
# for now use the non-gui version
msg = showFlightInfo(depart_date, depart_time, depart_tz, arrive_time, arrive_tz, confirmation, firstname, lastname, flyers, cities)
# print msg
self.flightinfo.config(state="normal")
self.flightinfo.delete('1.0',END)
self.flightinfo.insert('1.0', msg)
self.flightinfo.config(state="disabled")
# save the flight information for later use
self.confirmation = confirmation
self.firstname = firstname
self.lastname = lastname
self.depart_date = depart_date
self.depart_time = depart_time
self.depart_tz = depart_tz
self.arrive_time = arrive_time
self.arrive_tz = arrive_tz
self.flyers = flyers
self.cities = cities
self.is_retrieve = True
self.checkedin = []
for k in range(len(depart_date)):
self.checkedin.append(False)
def updateClock(self):
(local_time, current_date, current_time, current_tz, current_UTC, current_struct) = getCurrentTime()
clockstr = time.strftime("%a %B %d, %Y %I:%M:%S %p", current_struct)
self.updateHidden(self.wallclock, clockstr)
k = -1
dt = 1
timedelay = 1000
# clear the info fields
self.updateHidden(self.departclock," ")
self.updateHidden(self.timeleft," ")
self.updateHidden(self.cityfield, " ")
if self.is_retrieve:
k = getNextleg(self.depart_date, self.depart_time, self.depart_tz, self.checkedin)
if (k >= 0):
(depart_UTC, depart_struct) = makedate(self.depart_date[k], self.depart_time[k], self.depart_tz[k])
clockstr = time.strftime("%a %B %d, %Y %I:%M:%S %p", depart_struct)
self.updateHidden(self.departclock, clockstr)
(dt, timemsg) = getDelay(depart_UTC, current_UTC)
self.updateHidden(self.timeleft, timemsg)
self.updateHidden(self.cityfield, self.cities[k][0]+" to "+self.cities[k][1])
# check in if time left is zero
if (k>=0 and dt<=0 and (not self.checkedin[k])):
self.checkedin[k] = self.guiCheckin(k)
if ( k < len(self.checkedin)-1 ):
self.updateFlightinfo("\nMoving on to the next leg: "+self.cities[k+1][0]+" to "+self.cities[k+1][1]+"\n")
else:
self.updateFlightinfo("\n\nDone processing all flight legs\n")
self.updateHidden(self.departclock," ")
self.updateHidden(self.timeleft," ")
self.updateHidden(self.cityfield, " ")
self.showtimer = False
if (self.is_retrieve and k<0):
self.updateHidden(self.timeleft,"All flights checked in or are in the past")
self.showtime = False
# if clock is on then update the screen every second
if self.showtimer:
self.wallclock.after(timedelay, self.updateClock)
def onReset(self):
self.confirmation = ""
self.firstname = ""
self.lastname = ""
self.depart_date = []
self.depart_time = []
self.depart_tz = []
self.arrive_time = []
self.arrive_tz = []
self.flyers = []
self.cities = []
self.is_retrieve = False
self.checkedin = []
self.showtimer = True
# clear passengers
for flyerfield in self.flyerfields:
self.updateHidden(flyerfield,"")
# clear flight info area
self.flightinfo.config(state="normal")
self.flightinfo.delete('1.0',END)
self.flightinfo.config(state="disabled")
def guiCheckin(self, k):
# (checkedin, checkinText) = doCheckin(self.depart_date, self.depart_time, self.depart_tz, \
# self.confirmation, self.firstname, self.lastname, self.cities)
(checkedin, checkinText) = getBoardingPass(checkin_url, self.confirmation, self.firstname, self.lastname, k)
if ( checkedin ):
checkinText = "\n" + self.cities[k][0]+" to " + self.cities[k][1] + " checked in successfully\n" + checkinText
else:
checkinText = "\nFailed to check in\n" + checkinText
self.updateFlightinfo(checkinText)
return checkedin
# eventually add option to set email and other features
def onOptions(self):
pass
def onCancel(self):
if self.root:
self.root.quit()
else:
Tk().quit()
# main program
def main():
# create the GUI class that includes a widget after loop
if (is_GUI ):
root = Tk()
mylabels = ['Confirmation', 'Firstname', 'Lastname']
myform = GuiFlight(mylabels, [15,40,40], root)
root.mainloop()
# create the non-GUI class that includes thread loop
else:
mytext = TextFlight(confirmation, firstname, lastname)
# wait a few seconds after thread sets done variable to finish program
while (not mytext.alldone):
pass
time.sleep(2)
if __name__=='__main__':
main()
|
Discussion
This solves a common problem of getting the "A" every time. Several cool programming tips are included in this well documented code.


Comments
Excellent! Had been playing with your older script recently and had made a few tweaks: 1. edited sendemail function to optionally use tls for gmail compatibility; 2. preserve base url's when saving boarding pass so it can be opened and printed; 3. changed scheduler to use correct timefunc.
I assume 3 has been fixed in this version. I am a complete python novice so it will take me a little while to filter through the new code. New debug stuff looks useful for dealing with any server-side changes. Thanks for sharing.
Update: Tested on a trip I've only completed the first leg of and it says "All flights checked in or in the past". Few general thoughts: Might be nice to fill the gui textboxes with the confirmation,firstname,lastname values in the script as default and have a debugging option that uses live url's but still gives the verbose output.
I also have completed the first leg and am getting the same error as the comments from AZ1324
Nice to see some full-bodied GUI code that does something and looks reusable.
I have no idea why some raters are so tough on some recipes. Perhaps they are purists that only want to see small, specific, clever hacks. Or maybe they are being tough on any problems found immediately -- like exceptions reported when clicking "Checkin flight."
Man I love this script! However, I have about 5 people in my family that like to use it. I have to configure it every time for them.
Have you ever considered building a web front end to this where a user could fill in their first, last names and confirmation number?
I've read through the original and this new script comments and code, but I'm new to python (and scripting in general). After setting the debug to 0 and setting up the email, i tried my first checkin (for a reservation thats about a month out, and for one in a few days) and got the "All flights checked in or are in the past"? I would really like to get this up and running so anywhere I can go to get more information on how to get working would be appreciated, Thx TRM
This program worked fine after making the following 2 bug fixes:
change line 402 and add space and / after the br to match Southwest's current output. New line is:
depre = re.compile("Depart ([A-Za-z. -])((...)) at (\d{1,2}\:\d{1,2}[apAP][mM])\<br /\>Arrive in ([A-Za-z. -])((...)) at (\d{1,2}\:\d{1,2}[apAP][mM])")
Added tabs to align two lines properly around line 823. The new lines should look like:
The first bug fix fixes the problem reported in comment 6 above "All flights checked in or are in the past". The second bug fix fixes a problem that resulted in continuous printout saying ""Moving on to the next leg:..."
madhavmarathe, I tried the fixes you posted, still not working. same errors. If you have a working script (or anyone else) could you please post it, or email it to me? Thanks, TRM
Regarding madhavmarathe's 2 fixes in comment 7:
1.a. You say line 402, but on mine it's 398. Did you use the "Download this recipe" link or did you copy-paste text off this page? I trust download more than copy-paste for Python code.
1.b. Are you saying Southwest made the error of putting " /" inside their HTML BREAK tag? Then I guess we'll have to keep an eye out in case they fix it....
2.a. You say around line 823, but on mine the snippet is 812-825.
2.b. I think I see (smell?) the author's brainfart. I think the "if (k>=0 and dt<=0 and (not self.checkedin[k]))" clause was supposed to go inside the "if (k >= 0)" clause as you say, and its thus-redundant "k>=0 and" expression omitted. This has no effect on execution. I also think the "if ( k < len(self.checkedin)-1 )" clause was supposed to go inside the "if (k >= 0)" clause as you say, to prevent execution when k = -1. But I think the "else" clause was supposed to be associated with the "if (k >= 0)" clause, otherwise it would never execute when k = -1, so it's existing indentation is correct. Indenting only 812-818, deleting the redudant expression, and adding a blank line above the "else" for clarity results in 810-820 looking like:
-Ken 2
Wait, forget 2.b. After looking at it some more, I'm not so sure. I'd edit it out of the post but there doesn't seem to be a way.
I downloaded your script via the "Download this recipe" link. Didn't work for me. It doesn't actually check me in. The script responds as having successfully checked me in only AFTER I have manually checked in online.
Also, the timezone for PHX airport is wrong now that we've changed clocks.
I'm not a coder, but I fly all the time. More than happy to be a guinea pig and/or tester if you need someone.
I tried again today for an active flight, but was unsuccessful. Here are further details.
1)As I mentioned in the previous post, the script never actually checks me into a flight. It sits with the following message well after the checkin time has passed:
You have 0 days, 0 hours, and 1 minutes remaining to check in. Please wait for the scheduler to check in the departing flight...
I initially thought this might be an issue with the script not kicking off the checkin process.
2)If I run/initialize/start the script AFTER the checkin time has passed, it sits with the following message:
You were ready to check in 0 days, 0 hours, and 2 minutes ago. Please wait for the scheduler to check in the departing flight...
3)If I manually checkin online, then run the script, this is what it says:
You were ready to check in 0 days, 0 hours, and 5 minutes ago. Obtaining departing flight boarding pass right now... <class 'socket.error'> (111, 'Connection refused') Departing flight has been checked in - see boardingpass.htm for details Boarding group = A Boarding number = 19
I'm not sure if any of this will help....
Sign in to comment