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.

366 lines
12 KiB

  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(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.today().time()
  125. time_cur = datetime.datetime.strptime("13:00", "%H:%M")
  126. if len(one_bus) > 0:
  127. for i in one_bus:
  128. travel["routes"].append([{"name":i, "stops":[one_bus[i][0], one_bus[i][1]]}])
  129. else:
  130. routes_arr = {"user":{}, "dest":{}}
  131. stopno = {}
  132. for i in stops_arr["user"]:
  133. for j in stops_arr["user"][i]:
  134. try:
  135. routes_arr["user"][j.strip()] = bus_json["stops"][j.strip()]
  136. except KeyError:
  137. stops = send_request(
  138. "http://88.255.141.66/mbl/android/action.asp?SID=0.8737969480190279&VER=3.1.0&LAN=tr"
  139. "&UID"
  140. "=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=HatBilgileri",
  141. "KOD={}".format(routes_arr["user"][j.strip()]))["data"][0]["table_durak"]
  142. bus_json["stops"][j.strip()] = [x["kod"] for x in stops]
  143. routes_arr["user"][j.strip()] = bus_json["stops"][j.strip()]
  144. for x in stops:
  145. bus_json["stop_info"][x["kod"]] = {
  146. "name": x["ad"],
  147. "location":x["konum"],
  148. "lat": x["lat"],
  149. "lng": x["lng"]
  150. }
  151. change = True
  152. stopno[j.strip()] = i
  153. for i in stops_arr["dest"]:
  154. for j in stops_arr["dest"][i]:
  155. try:
  156. routes_arr["dest"][j.strip()] = bus_json["stops"][j.strip()]
  157. except KeyError:
  158. stops = send_request(
  159. "http://88.255.141.66/mbl/android/action.asp?SID=0.8737969480190279&VER=3.1.0&LAN=tr"
  160. "&UID"
  161. "=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=HatBilgileri",
  162. "KOD={}".format(routes_arr["dest"][j.strip()]))["data"][0]["table_durak"]
  163. bus_json["stops"][j.strip()] = [x["kod"] for x in stops]
  164. routes_arr["dest"][j.strip()] = bus_json["stops"][j.strip()]
  165. for x in stops:
  166. bus_json["stop_info"][x["kod"]] = {
  167. "name": x["ad"],
  168. "location":x["konum"],
  169. "lat": x["lat"],
  170. "lng": x["lng"]
  171. }
  172. change = True
  173. stopno[j.strip()] = i
  174. for i in routes_arr["user"]:
  175. for j in routes_arr["user"][i]:
  176. for k in routes_arr["dest"]:
  177. for x in routes_arr["dest"][k]:
  178. if j.strip() == x.strip():
  179. travel["routes"].append([
  180. {"name":i.strip(), "stops":[stopno[i.strip()], x.strip()]},
  181. {"name":k.strip(), "stops":[x.strip(), stopno[k.strip()]]}])
  182. for i in range(len(travel["routes"])):
  183. for k in range(len(travel["routes"][i])):
  184. url = "http://88.255.141.66/mbl/android/action.asp?SID=0.4474110208361718&VER=3.1.0&LAN=tr&UID"\
  185. "=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=DuraktanGecisSaatleri "
  186. weekno = datetime.datetime.today().weekday()
  187. times_anal = [[], []]
  188. for j in range(2):
  189. try:
  190. times_raw = bus_json["times"][travel["routes"][i][k]["name"]]
  191. except Exception:
  192. bus_json["times"][travel["routes"][i][k]["name"]] = {}
  193. try:
  194. times_raw = bus_json["times"][travel["routes"][i][k]["name"]][
  195. travel["routes"][i][k]["stops"][j]]
  196. except Exception:
  197. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]] = {}
  198. if weekno < 5:
  199. try:
  200. weekday = "HAFTA+%C4%B0%C3%87%C4%B0"
  201. times_raw =\
  202. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  203. "weekday"]
  204. except KeyError:
  205. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  206. "weekday"] = send_request(url, "HAT={0}&DURAK={1}&TUR={2}".format(
  207. travel["routes"][i][k]["name"], travel["routes"][i][k]["stops"][j], weekday))[
  208. "data"][0]["table"]
  209. times_raw =\
  210. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  211. "weekday"]
  212. change = True
  213. elif weekno == 5:
  214. try:
  215. weekday = "CUMARTES%C4%B0"
  216. times_raw =\
  217. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  218. "saturday"]
  219. except KeyError:
  220. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  221. "saturday"] = send_request(url, "HAT={0}&DURAK={1}&TUR={2}".format(
  222. travel["routes"][i][k]["name"], travel["routes"][i][k]["stops"][j], weekday))[
  223. "data"][0]["table"]
  224. times_raw =\
  225. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  226. "saturday"]
  227. change = True
  228. else:
  229. try:
  230. weekday = "PAZAR"
  231. times_raw =\
  232. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  233. "sunday"]
  234. except KeyError:
  235. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  236. "sunday"] = send_request(url, "HAT={0}&DURAK={1}&TUR={2}".format(
  237. travel["routes"][i][k]["name"], travel["routes"][i][k]["stops"][j], weekday))[
  238. "data"][0]["table"]
  239. times_raw =\
  240. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
  241. "sunday"]
  242. change = True
  243. for time in times_raw:
  244. times_anal[j].append(
  245. datetime.datetime.strptime("{0}:{1}".format(time["saat"], time["dakika"]), "%H:%M"))
  246. closest_times = get_closest_time([times_anal[0], times_anal[1]], time_cur)
  247. travel["routes"][i][k]["time"] = closest_times
  248. empty = []
  249. for i in range(len(travel["routes"])):
  250. remove = True
  251. for k in range(len(travel["routes"][i])):
  252. if remove:
  253. if len(travel["routes"][i][k]["time"]) == 0:
  254. empty.append(i - len(empty))
  255. remove = False
  256. for i in empty:
  257. travel["routes"].pop(i)
  258. for route in travel["routes"]:
  259. start = route[0]["time"][0]
  260. end = route[-1]["time"][1]
  261. diff = time_diff(start, end)
  262. diff = time_sum(diff, time_diff(time_cur.strftime("%H:%M"), start))
  263. diff = time_sum(diff, "00:05")
  264. travel["total"].append(diff)
  265. shortest = 0
  266. for i in range(len(travel["total"])):
  267. if shortest == 0:
  268. shortest = {"routes":travel["routes"][i], "time":travel["total"][i]}
  269. continue
  270. if time_small(shortest["time"], travel["total"][i]):
  271. shortest = {"routes":travel["routes"][i], "time":travel["total"][i]}
  272. if change:
  273. bus_data = open("modules/databases/bus.json", "w")
  274. bus_data.write(json.dumps(bus_json, indent=4, sort_keys=True))
  275. bus_data.close()
  276. for i in range(len(shortest["routes"])):
  277. try:
  278. shortest["routes"][i]["names"] = [bus_json["stop_info"][shortest["routes"][i][0]]["name"],bus_json["stop_info"][shortest["routes"][i][1]]["name"]]
  279. except KeyError:
  280. shortest["routes"][i]["names"] = []
  281. shortest["routes"][i]["locations"] = []
  282. shortest["routes"][i]["coordinates"] = []
  283. for j in range(2):
  284. 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",
  285. "QUERY={}".format(shortest["routes"][i]["stops"][j]))["data"][0]["table"][0]
  286. bus_json["stop_info"][shortest["routes"][i]["stops"][j]] ={
  287. "name": data["ad"],
  288. "location": data["konum"],
  289. "lat": data["lat"],
  290. "lng": data["lng"]
  291. }
  292. shortest["routes"][i]["names"].append(bus_json["stop_info"][shortest["routes"][i]["stops"][j]]["name"])
  293. shortest["routes"][i]["locations"].append(bus_json["stop_info"][shortest["routes"][i]["stops"][j]]["location"])
  294. 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"]})
  295. change=True
  296. if change:
  297. bus_data = open("modules/databases/bus.json", "w")
  298. bus_data.write(json.dumps(bus_json, indent=4, sort_keys=True))
  299. bus_data.close()
  300. return shortest
  301. if __name__ == '__main__':
  302. api.add_resource(Transit, '/transit', '/transit/')
  303. app.run(host='0.0.0.0', port=5000)