#!/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] fromToStr = frm[1] + " to " + to[1] + ": " # return ",".join(fromArr) + ",".join(toArr) if (len(intersectArr) == 0): return fromToStr + "no direct buses found." # return "from %s to %s" % (",".join(fromArr), ",".join(toArr),) else: return fromToStr + ",".join(intersectArr) class FromToHandler(KeywordHandler): keyword = "from" def help(self): self.respond("Send from to ") 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)) toString = "To location not found." self.respond(fromString + " " + toString) def time_str(no): whole = int(no) decimal = (no - whole) * 10 mins = int(((decimal + .0) / 10) * 60) return str(whole) + ":" + str(mins)