Jake.codes

Muni Times, for Pythonista

Tuesday, January 07, 2014

import sys
import urllib
import notification
from xml.dom.minidom import parse, parseString

def muniTimes(dist):
    locations = [
        ('T Outbound, King St & 2nd St','Inbound to Visitacion Valley via Downtown','http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=sf-muni&stopId=15234&routeTag=KT','South Beach'),
        ('K Outbound, West Portal Station','Inbound to Visitacion Valley via Downtown','http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=sf-muni&stopId=16740&routeTag=KT','West of Twin Peaks')
    ]

    for name, direction, url, district in locations:
        if (dist is not '') and (dist.lower() != district.lower()):
            continue

        times = ""
        route = parse(urllib.urlopen(url)).getElementsByTagName('direction')
        for dir in route:
            if dir.getAttribute('title') not in direction:
                continue

            for prediction in dir.getElementsByTagName('prediction'):
                if times is '':
                    times += prediction.getAttribute('minutes')
                else:
                    times += ', ' + prediction.getAttribute('minutes')
            
            notification.schedule(name + '\n' + times)

import clipboard

def getLocation():
    import location
    import time
    location.start_updates()
    time.sleep(3)
    current = location.get_location()
    location.stop_updates()
    lookup = location.reverse_geocode({'latitude': current['latitude'], 'longitude': current['longitude']})
    
    district = lookup[0]['SubLocality']
    
    where = district
    
    return where

if __name__ == '__main__':
    try:
        argument = getLocation()
    except:
        argument = ''

    muniTimes(argument)