Skip to content

Commit

Permalink
Minor Update
Browse files Browse the repository at this point in the history
Switched to with statement when opening the API connection (instead of relying on the destructor).

Added a timeout for the API call, default is 6 seconds.
  • Loading branch information
kgillibrand committed Aug 18, 2016
1 parent 6471298 commit 1a535b3
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions piascript.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def getCredentials (credentialsPath: str, interface: str) -> dict:

sys.exit (1)

def forwardPort (credentials: dict, endpointURL: str, encoding: str) -> dict:
def forwardPort (credentials: dict, endpointURL: str, encoding: str, timeout: int) -> dict:
'''
Contacts the PIA API to enable port forwarding and returns the API response (Dictionary)
Expand All @@ -147,28 +147,33 @@ def forwardPort (credentials: dict, endpointURL: str, encoding: str) -> dict:

parameters = urllib.parse.urlencode (credentials)

response = urllib.request.urlopen (endpointURL, str.encode (parameters)).read ()
responseString = response.decode (encoding)
with urllib.request.urlopen (endpointURL, str.encode (parameters), timeout) as connection:
response = connection.read ()

responseString = response.decode (encoding)

if DEBUG:
print ('Decoded API response as: \'%s\'' %encoding)
print ('API response JSON: \'%s\'' %responseString)
print ()
if DEBUG:
print ('Decoded API response as: \'%s\'' %encoding)
print ('API response JSON: \'%s\'' %responseString)
print ()

return json.loads (responseString)
return json.loads (responseString)

def main ():
'''Main method that takes command line arguments'''

#Local Constants
PIA_ENDPOINT = 'https://www.privateinternetaccess.com/vpninfo/port_forward_assignment'
ENDPOINT = 'https://www.privateinternetaccess.com/vpninfo/port_forward_assignment'
'''API endpoint URL'''

INTERFACE = 'tun0'
'''Network interface for VPN'''

ENCODING = 'utf-8'
'''Text encoding to use for decoding API response'''

TIMEOUT = 6
'''Timeout in seconds when connecting to the API endpoint'''

print ()
print ('%s - %s, %s' %(__title__, __copyright__, __license__))
Expand Down Expand Up @@ -196,7 +201,7 @@ def main ():

credentials = getCredentials (args.credentialsfile, INTERFACE)

response = forwardPort (credentials, PIA_ENDPOINT, ENCODING)
response = forwardPort (credentials, ENDPOINT, ENCODING, TIMEOUT)

if not DEBUG:
print ('Response recieved')
Expand Down

0 comments on commit 1a535b3

Please sign in to comment.