Last active
August 29, 2015 14:06
-
-
Save bachya/6ebf4715a09bccee9300 to your computer and use it in GitHub Desktop.
Pythonista script to trigger different Launch Center Pro actions based on internet availability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Pythonista script to trigger different Launch Center Pro | |
# actions based on internet availability | |
# Author: Aaron Bach | |
# www: http://www.bachyaproductions.com/ | |
import json | |
import re | |
import socket | |
import sys | |
import urllib | |
import webbrowser | |
def internet_reachable(): | |
""" | |
Determines internet availability by opening a socket | |
to google.com (hopefully that domain name never goes | |
away). | |
""" | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
try: | |
sock.connect(('google.com', 80)) | |
good_connection = True | |
except (OSError, Exception) as e: | |
good_connection = False | |
sock.close() | |
return good_connection | |
def quote_url_parameters(match): | |
""" | |
Takes a key=value URL argument and encodes the value portion. | |
By unquoting then requoting the URL, the script can accommodate | |
scenarious where: | |
1. URLs come in unencoded | |
2. URLs come in encoded | |
3. URLs come in with a mixture of encoding | |
""" | |
return '=' + urllib.quote(urllib.unquote(match.group(1)), '') | |
def main(): | |
""" | |
Main program. | |
RE: passing arguments to this script: LCP requires Pythonista arguments | |
to be surrounded by double quotes. Since we're using JSON loading (in | |
my opinion, the safest method of turning a dict string into an actual | |
dict), we also have to grapple with the fact the JSON parser requires | |
double quotes around arguments. Thus, the following string replacement | |
occurs: | |
""" | |
urls = json.loads(sys.argv[1].replace("'", '"')) | |
args = json.loads(sys.argv[2].replace("'", '"')) | |
try: | |
on_url = re.sub('=([^&]+)', quote_url_parameters, urls['URL On'].format(**args)) | |
except KeyError, e: | |
print 'Missing argument or invalid URL token in "On" URL: ' + str(e) | |
return | |
try: | |
off_url = re.sub('=([^&]+)', quote_url_parameters, urls['URL Off'].format(**args)) | |
except KeyError, e: | |
print 'Missing argument or invalid URL token in "Off" URL: ' + str(e) | |
return | |
webbrowser.open(on_url if internet_reachable() else off_url) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment