bestSMS/best/smsmesn/handlers/fromto.py

108 lines
3.0 KiB
Python
Raw Normal View History

2011-07-23 12:08:39 +00:00
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from rapidsms.contrib.handlers.handlers.keyword import KeywordHandler
# from new_best.models import *
import datetime
try:
import json
except:
import simplejson as json
from settings import JSON_PATH
from os.path import join
def getStops(data, s):
stops = []
for d in data:
if d[1].lower() == s:
return [d]
else:
if d[0].lower().find(s) != -1:
stops.append(d)
return stops
def getStop(data, s):
for d in data:
if d[1] == s:
return d
return [""]
def getOptions(stops):
arr = []
for s in stops:
arr.append(s[1])
stopStr = ",".join(arr[0:4])
return '(' + stopStr + ')'
def getBuses(frm, to):
# return "hi"
from_code = frm[1].strip()
to_code = to[1].strip()
# url = "http://mesn.org/Bestbus/busesfound.html"
data = json.loads(open(join(JSON_PATH, "stopbus.json")).read().replace("\\", "/").replace(",,,", ",").replace(",,", ","))
to = getStop(data, to_code)
frm = getStop(data, from_code)
# return to[0]
stopListFrom = frm[-1]
stopListTo = to[-1]
fromArr = stopListFrom.split(",")
fromArr = [val.split("|")[0] for val in fromArr]
toArr = stopListTo.split(",")
toArr = [val.split("|")[0] for val in toArr]
intersectArr = [val for val in fromArr if val in toArr]
2011-08-06 14:23:50 +00:00
fromToStr = "from " + frm[1] + " to " + to[1] + ": "
2011-07-23 12:08:39 +00:00
# return ",".join(fromArr) + ",".join(toArr)
if (len(intersectArr) == 0):
2011-08-06 14:23:50 +00:00
return fromToStr + "no direct buses found."
2011-07-23 12:08:39 +00:00
# return "from %s to %s" % (",".join(fromArr), ",".join(toArr),)
else:
2011-08-06 14:23:50 +00:00
return fromToStr + ",".join(intersectArr)
2011-07-23 12:08:39 +00:00
class FromToHandler(KeywordHandler):
keyword = "from"
def help(self):
self.respond("Send from <place> to <place>")
def handle(self, text):
txt = text.strip()
from_to = txt.split("to")
frm = from_to[0].strip()
to = from_to[1].strip()
# print frm
# print to
data = json.loads(open(join(JSON_PATH, "stoplist.json")).read().replace("\\", "/"))
froms = getStops(data, frm)
tos = getStops(data, to)
if len(froms) == len(tos) == 1:
self.respond(getBuses(froms[0], tos[0]))
else:
if len(froms) == 0:
fromString = "From location not found."
elif len(froms) == 1:
fromString = "From %s" % (froms[0][1])
else:
fromString = "From %s" % (getOptions(froms))
if len(tos) == 0:
toString = "To location not found."
elif len(tos) == 1:
toString = "to %s" % (tos[0][1])
else:
toString = "to %s" % (getOptions(tos))
2011-08-06 14:23:50 +00:00
toString = "To location not found."
2011-07-23 12:08:39 +00:00
self.respond(fromString + " " + toString)
2011-07-23 12:32:24 +00:00
2011-07-23 12:08:39 +00:00
def time_str(no):
whole = int(no)
decimal = (no - whole) * 10
mins = int(((decimal + .0) / 10) * 60)
return str(whole) + ":" + str(mins)