You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

371 lines
12 KiB

6 years ago
6 years ago
  1. import datetime
  2. import json
  3. import requests
  4. from flask import Flask, request
  5. from flask_restful import Api, Resource
  6. app = Flask(__name__)
  7. api = Api(app)
  8. def send_request(url, raw):
  9. headers = {
  10. "User-Agent": "EGO Genel Mudurlugu-EGO Cepte-3.1.0 GT-I9500 7.1.2",
  11. "Content-Type":"application/x-www-form-urlencoded", "Content-Length":str(len(raw))
  12. }
  13. r = requests.post(url, headers=headers, data=raw)
  14. content = r.content.decode("cp1252")
  15. replace_chars = {"Ý":"I", "ý":"i", "ð":"g", "þ":"s", "Þ":"S"}
  16. for key in replace_chars:
  17. content.replace(key, replace_chars[key])
  18. content = content.replace("'", '"')
  19. content = json.loads(content)
  20. return content
  21. conn1 = send_request(
  22. 'http://88.255.141.70/mbl/android/connect.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID=%7BACB78701'
  23. '-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=Connect',
  24. "UID=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&UPS=TRUE")
  25. conn2 = send_request(
  26. 'http://88.255.141.66/mbl/android/connect.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID=%7BACB78701'
  27. '-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=Start', "")
  28. bus_data = open("modules/databases/bus.json", "r")
  29. bus_json = json.loads(bus_data.read())
  30. routes = bus_json["stops"]
  31. bus_data.close()
  32. print('\n', conn1, '\n\n', conn2, '\n')
  33. def time_small(t1, t2):
  34. time1 = datetime.datetime.strptime(t1, "%H:%M")
  35. time2 = datetime.datetime.strptime(t2, "%H:%M")
  36. if time1 < time2:
  37. return False
  38. else:
  39. return True
  40. def time_diff(t1, t2):
  41. time1 = datetime.datetime.strptime(t1, "%H:%M")
  42. time2 = datetime.datetime.strptime(t2, "%H:%M")
  43. response = ""
  44. if abs(time2.hour - time1.hour) < 10:
  45. response += "0"
  46. if time2.minute - time1.minute >= 0:
  47. response += str(abs(time2.hour - time1.hour))
  48. else:
  49. response += str(abs(abs(time2.hour - time1.hour)-1))
  50. response += ":"
  51. if abs(time2.minute - time1.minute) < 10:
  52. response += "0"
  53. response += str(abs(time2.minute - time1.minute))
  54. return response
  55. def time_sum(t1, t2):
  56. time1 = datetime.datetime.strptime(t1, "%H:%M")
  57. time2 = datetime.datetime.strptime(t2, "%H:%M")
  58. response = ""
  59. if time2.hour + time1.hour < 10:
  60. response += "0"
  61. if time2.minute + time1.minute > 60:
  62. response += str(time2.hour + time1.hour + 1)
  63. else:
  64. response += str(time2.hour + time1.hour)
  65. response += ":"
  66. if time2.minute + time1.minute % 60 < 10:
  67. response += "0"
  68. response += str((time2.minute + time1.minute) % 60)
  69. return response
  70. def get_closest_time(times, time):
  71. closest = [0, 0]
  72. for i in times[0]:
  73. if i.hour < time.hour or (i.hour == time.hour and i.minute - 6 < time.minute):
  74. continue
  75. else:
  76. if closest[0] == 0:
  77. closest[0] = i
  78. continue
  79. if abs(i.hour - time.hour) < abs(closest[0].hour - time.hour):
  80. closest[0] = i
  81. continue
  82. elif abs(i.hour - time.hour) == abs(closest[0].hour - time.hour):
  83. if i.minute - time.minute < closest[0].minute - time.minute:
  84. closest[0] = i
  85. if closest[0] == 0:
  86. return []
  87. for i in times[1]:
  88. if i.hour < closest[0].hour or (i.hour == closest[0].hour and i.minute - 6 < closest[0].minute):
  89. continue
  90. else:
  91. if closest[1] == 0:
  92. closest[1] = i
  93. continue
  94. if abs(i.hour - time.hour) < abs(closest[1].hour - time.hour):
  95. closest[1] = i
  96. continue
  97. elif abs(i.hour - time.hour) == abs(closest[1].hour - time.hour):
  98. if i.minute - time.minute < closest[1].minute - time.minute:
  99. closest[1] = i
  100. if closest[1] == 0:
  101. return []
  102. return [closest[0].strftime("%H:%M"), closest[1].strftime("%H:%M")]
  103. class Transit(Resource):
  104. def post(self):
  105. change = False
  106. args = request.form
  107. stops_raw = {"user":{}, "dest":{}}
  108. stops_arr = {"user":{}, "dest":{}}
  109. url_closestops = "http://88.255.141.66/mbl/android/action.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID"\
  110. "=%7BACB78701"\
  111. "-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=YakinDuraklar"
  112. closestops = send_request(url_closestops, "LAT={0}&LNG={1}&MSF=500".format(args["lat_usr"], args["lng_usr"]))
  113. for stop in closestops["data"][0]["table"]:
  114. stops_arr["user"][stop["kod"]] = stop["hatlar"].split(",")
  115. closestops = send_request(url_closestops, "LAT={0}&LNG={1}&MSF=500".format(args["lat_dest"], args["lng_dest"]))
  116. for stop in closestops["data"][0]["table"]:
  117. stops_arr["dest"][stop["kod"]] = stop["hatlar"].split(",")
  118. one_bus = {k.strip():
  119. [dict({x:n for n in stops_arr["user"] for x in stops_arr["user"][n]})[k],
  120. dict({x:n for n in stops_arr["dest"] for x in stops_arr["dest"][n]})[k]]
  121. for k in (list(set([x for n in stops_arr["user"] for x in stops_arr["user"][n]])
  122. & set([x for n in stops_arr["dest"] for x in stops_arr["dest"][n]])))}
  123. travel = {"routes":[], "total":[]}
  124. time_cur = datetime.datetime.strptime("13:00","%H:%M")
  125. if len(one_bus) > 0:
  126. for i in one_bus:
  127. travel["routes"].append([{"name":i, "stops":[one_bus[i][0], one_bus[i][1]]}])
  128. else:
  129. routes_arr = {"user":{}, "dest":{}}
  130. stopno = {}
  131. for i in stops_arr["user"]:
  132. for j in stops_arr["user"][i]:
  133. try:
  134. routes_arr["user"][j.strip()] = bus_json["stops"][j.strip()]
  135. except KeyError:
  136. stops = send_request(
  137. "http://88.255.141.66/mbl/android/action.asp?SID=0.8737969480190279&VER=3.1.0&LAN=tr"
  138. "&UID"
  139. "=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=HatBilgileri",
  140. "KOD={}".format(j.strip()))["data"][0]["table_durak"]
  141. bus_json["stops"][j.strip()] = [x["kod"] for x in stops]
  142. routes_arr["user"][j.strip()] = bus_json["stops"][j.strip()]
  143. for x in stops:
  144. bus_json["stop_info"][x["kod"]] = {
  145. "name": x["ad"],
  146. "location":x["konum"],
  147. "lat": x["lat"],
  148. "lng": x["lng"]
  149. }
  150. change = True
  151. stopno[j.strip()] = i
  152. for i in stops_arr["dest"]:
  153. for j in stops_arr["dest"][i]:
  154. try:
  155. routes_arr["dest"][j.strip()] = bus_json["stops"][j.strip()]
  156. except KeyError:
  157. stops = send_request(
  158. "http://88.255.141.66/mbl/android/action.asp?SID=0.8737969480190279&VER=3.1.0&LAN=tr"
  159. "&UID"
  160. "=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=HatBilgileri",
  161. "KOD={}".format(j.strip()))["data"][0]["table_durak"]
  162. bus_json["stops"][j.strip()] = [x["kod"] for x in stops]
  163. routes_arr["dest"][j.strip()] = bus_json["stops"][j.strip()]
  164. for x in stops:
  165. bus_json["stop_info"][x["kod"]] = {
  166. "name": x["ad"],
  167. "location":x["konum"],
  168. "lat": x["lat"],
  169. "lng": x["lng"]
  170. }
  171. change = True
  172. stopno[j.strip()] = i
  173. for i in routes_arr["user"]:
  174. for j in routes_arr["user"][i]:
  175. for k in routes_arr["dest"]:
  176. for x in routes_arr["dest"][k]:
  177. if j.strip() == x.strip():
  178. travel["routes"].append([
  179. {"name":i.strip(), "stops":[stopno[i.strip()], x.strip()]},
  180. {"name":k.strip(), "stops":[x.strip(), stopno[k.strip()]]}])
  181. for i in range(len(travel["routes"])):
  182. for k in range(len(travel["routes"][i])):
  183. url = "http://88.255.141.66/mbl/android/action.asp?SID=0.4474110208361718&VER=3.1.0&LAN=tr&UID"\
  184. "=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=DuraktanGecisSaatleri "
  185. weekno = 4
  186. times_anal = [[], []]
  187. for j in range(2):
  188. try:
  189. times_raw = bus_json["times"][travel["routes"][i][k]["name"]]
  190. except Exception:
  191. bus_json["times"][travel["routes"][i][k]["name"]] = {}
  192. try:
  193. times_raw = bus_json["times"][travel["routes"][i][k]["name"]][
  194. travel["routes"][i][k]["stops"][j]]
  195. except Exception:
  196. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]] = {}
  197. if weekno < 5:
  198. try:
  199. weekday = "HAFTA+%C4%B0%C3%87%C4%B0"
  200. times_raw =\
  201. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  202. "weekday"]
  203. except KeyError:
  204. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  205. "weekday"] = send_request(url, "HAT={0}&DURAK={1}&TUR={2}".format(
  206. travel["routes"][i][k]["name"], travel["routes"][i][k]["stops"][j], weekday))[
  207. "data"][0]["table"]
  208. times_raw =\
  209. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  210. "weekday"]
  211. change = True
  212. elif weekno == 5:
  213. try:
  214. weekday = "CUMARTES%C4%B0"
  215. times_raw =\
  216. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  217. "saturday"]
  218. except KeyError:
  219. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  220. "saturday"] = send_request(url, "HAT={0}&DURAK={1}&TUR={2}".format(
  221. travel["routes"][i][k]["name"], travel["routes"][i][k]["stops"][j], weekday))[
  222. "data"][0]["table"]
  223. times_raw =\
  224. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  225. "saturday"]
  226. change = True
  227. else:
  228. try:
  229. weekday = "PAZAR"
  230. times_raw =\
  231. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  232. "sunday"]
  233. except KeyError:
  234. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  235. "sunday"] = send_request(url, "HAT={0}&DURAK={1}&TUR={2}".format(
  236. travel["routes"][i][k]["name"], travel["routes"][i][k]["stops"][j], weekday))[
  237. "data"][0]["table"]
  238. times_raw =\
  239. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  240. "sunday"]
  241. change = True
  242. for time in times_raw:
  243. times_anal[j].append(
  244. datetime.datetime.strptime("{0}:{1}".format(time["saat"], time["dakika"]), "%H:%M"))
  245. closest_times = get_closest_time([times_anal[0], times_anal[1]], time_cur)
  246. travel["routes"][i][k]["time"] = closest_times
  247. empty = []
  248. for i in range(len(travel["routes"])):
  249. remove = True
  250. for k in range(len(travel["routes"][i])):
  251. if remove:
  252. if len(travel["routes"][i][k]["time"]) == 0:
  253. empty.append(i - len(empty))
  254. remove = False
  255. for i in empty:
  256. travel["routes"].pop(i)
  257. if change:
  258. bus_data = open("modules/databases/bus.json", "w")
  259. bus_data.write(json.dumps(bus_json, indent=2, sort_keys=True))
  260. bus_data.close()
  261. for route in travel["routes"]:
  262. start = route[0]["time"][0]
  263. end = route[-1]["time"][1]
  264. diff = time_diff(start, end)
  265. print (route)
  266. print (diff)
  267. diff = time_sum(diff, time_diff(time_cur.strftime("%H:%M"), start))
  268. diff = time_sum(diff, "00:05")
  269. travel["total"].append(diff)
  270. shortest = 0
  271. for i in range(len(travel["total"])):
  272. if shortest == 0:
  273. shortest = {"routes":travel["routes"][i], "time":travel["total"][i]}
  274. continue
  275. if time_small(shortest["time"], travel["total"][i]):
  276. shortest = {"routes":travel["routes"][i], "time":travel["total"][i]}
  277. if change:
  278. bus_data = open("modules/databases/bus.json", "w")
  279. bus_data.write(json.dumps(bus_json, indent=2, sort_keys=True))
  280. bus_data.close()
  281. for i in range(len(shortest["routes"])):
  282. try:
  283. shortest["routes"][i]["names"] = [bus_json["stop_info"][shortest["routes"][i][0]]["name"],bus_json["stop_info"][shortest["routes"][i][1]]["name"]]
  284. except KeyError:
  285. shortest["routes"][i]["names"] = []
  286. shortest["routes"][i]["locations"] = []
  287. shortest["routes"][i]["coordinates"] = []
  288. for j in range(2):
  289. data = send_request("http://88.255.141.66/mbl/android/action.asp?SID=0.21893997000802157&VER=3.1.0&LAN=tr&UID=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=Duraklar",
  290. "QUERY={}".format(shortest["routes"][i]["stops"][j]))["data"][0]["table"][0]
  291. bus_json["stop_info"][shortest["routes"][i]["stops"][j]] ={
  292. "name": data["ad"],
  293. "location": data["konum"],
  294. "lat": data["lat"],
  295. "lng": data["lng"]
  296. }
  297. shortest["routes"][i]["names"].append(bus_json["stop_info"][shortest["routes"][i]["stops"][j]]["name"])
  298. shortest["routes"][i]["locations"].append(bus_json["stop_info"][shortest["routes"][i]["stops"][j]]["location"])
  299. shortest["routes"][i]["coordinates"].append({"lat":bus_json["stop_info"][shortest["routes"][i]["stops"][j]]["lat"], "lng":bus_json["stop_info"][shortest["routes"][i]["stops"][j]]["lng"]})
  300. change=True
  301. if change:
  302. bus_data = open("modules/databases/bus.json", "w")
  303. bus_data.write(json.dumps(bus_json, indent=2, sort_keys=True))
  304. bus_data.close()
  305. return shortest
  306. if __name__ == '__main__':
  307. api.add_resource(Transit, '/transit', '/transit/')
  308. app.run(host='0.0.0.0', port=5000)