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.

258 lines
8.7 KiB

  1. from flask import Flask, request
  2. from flask_restful import Resource, Api, abort
  3. import requests
  4. import json
  5. import datetime
  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("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_diff(t1, t2):
  34. time1 = datetime.datetime.strptime(t1,"%H:%M")
  35. time2 = datetime.datetime.strptime(t2,"%H:%M")
  36. response = ""
  37. if time2.hour-time1.hour < 10:
  38. response += "0"
  39. response += str(time2.hour-time1.hour)
  40. response += ":"
  41. if time2.minute-time1.minute < 10:
  42. response += "0"
  43. response += str(time2.minute-time1.minute)
  44. return response
  45. def time_sum(t1,t2):
  46. time1 = datetime.datetime.strptime(t1,"%H:%M")
  47. time2 = datetime.datetime.strptime(t2,"%H:%M")
  48. response = ""
  49. if time2.hour+time1.hour < 10:
  50. response += "0"
  51. response += str(time2.hour+time1.hour)
  52. response += ":"
  53. if time2.minute+time1.minute < 10:
  54. response += "0"
  55. response += str(time2.minute+time1.minute)
  56. return response
  57. def get_closest_time(times, time):
  58. closest = [0, 0]
  59. for i in times[0]:
  60. if i.hour < time.hour or (i.hour == time.hour and i.minute-6 < time.minute):
  61. continue
  62. else:
  63. if closest[0] == 0:
  64. closest[0] = i
  65. continue
  66. if abs(i.hour - time.hour) < abs(closest[0].hour - time.hour):
  67. closest[0] = i
  68. continue
  69. elif abs(i.hour - time.hour) == abs(closest[0].hour - time.hour):
  70. if i.minute - time.minute < closest[0].minute - time.minute:
  71. closest[0] = i
  72. if closest[0] == 0:
  73. return []
  74. for i in times[1]:
  75. if i.hour < closest[0].hour or (i.hour == closest[0].hour and i.minute-6 < closest[0].minute):
  76. continue
  77. else:
  78. if closest[1] == 0:
  79. closest[1] = i
  80. continue
  81. if abs(i.hour - time.hour) < abs(closest[1].hour - time.hour):
  82. closest[1] = i
  83. continue
  84. elif abs(i.hour - time.hour) == abs(closest[1].hour - time.hour):
  85. if i.minute - time.minute < closest[1].minute - time.minute:
  86. closest[1] = i
  87. if closest[1] == 0:
  88. return []
  89. return [closest[0].strftime("%H:%M"), closest[1].strftime("%H:%M")]
  90. class Transit(Resource):
  91. def post(self):
  92. change = False
  93. args = request.form
  94. stops_raw = {"user": {}, "dest": {}}
  95. stops_arr = {"user": {}, "dest": {}}
  96. url_closestops = "http://88.255.141.66/mbl/android/action.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID" \
  97. "=%7BACB78701"\
  98. "-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=YakinDuraklar"
  99. closestops = send_request(url_closestops, "LAT={0}&LNG={1}&MSF=500".format(args["lat_usr"], args["lng_usr"]))
  100. for stop in closestops["data"][0]["table"]:
  101. stops_arr["user"][stop["kod"]] = stop["hatlar"].split(",")
  102. closestops = send_request(url_closestops, "LAT={0}&LNG={1}&MSF=500".format(args["lat_dest"], args["lng_dest"]))
  103. for stop in closestops["data"][0]["table"]:
  104. stops_arr["dest"][stop["kod"]] = stop["hatlar"].split(",")
  105. one_bus = {k.strip():
  106. [dict({x: n for n in stops_arr["user"] for x in stops_arr["user"][n]})[k],
  107. dict({x: n for n in stops_arr["dest"] for x in stops_arr["dest"][n]})[k]]
  108. for k in(list(set([x for n in stops_arr["user"] for x in stops_arr["user"][n]])
  109. & set([x for n in stops_arr["dest"] for x in stops_arr["dest"][n]])))}
  110. travel = {"routes": [], "total":[]}
  111. # time_cur = datetime.datetime.today().time()
  112. time_cur =datetime.datetime.strptime("13:00","%H:%M")
  113. if len(one_bus) > 0:
  114. for i in one_bus:
  115. travel["routes"].append([{"name":i,"stops":[one_bus[i][0],one_bus[i][1]]}])
  116. else:
  117. routes_arr = {"user": {}, "dest": {}}
  118. stopno = {}
  119. for i in stops_arr["user"]:
  120. for j in stops_arr["user"][i]:
  121. routes_arr["user"][j.strip()] = bus_json["stops"][j.strip()]
  122. stopno[j.strip()] = i
  123. for i in stops_arr["dest"]:
  124. for j in stops_arr["dest"][i]:
  125. routes_arr["dest"][j.strip()] = bus_json["stops"][j.strip()]
  126. stopno[j.strip()] = i
  127. for i in routes_arr["user"]:
  128. for j in routes_arr["user"][i]:
  129. for k in routes_arr["dest"]:
  130. for x in routes_arr["dest"][k]:
  131. if j.strip() == x.strip():
  132. travel["routes"].append([
  133. {"name": i.strip(), "stops": [stopno[i.strip()], x.strip()]},
  134. {"name": k.strip(), "stops": [x.strip(), stopno[k.strip()]]}])
  135. for i in range(len(travel["routes"])):
  136. for k in range(len(travel["routes"][i])):
  137. url = "http://88.255.141.66/mbl/android/action.asp?SID=0.4474110208361718&VER=3.1.0&LAN=tr&UID"\
  138. "=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=DuraktanGecisSaatleri "
  139. weekno = datetime.datetime.today().weekday()
  140. times_anal = [[], []]
  141. for j in range(2):
  142. try:
  143. times_raw = bus_json["times"][travel["routes"][i][k]["name"]]
  144. except Exception:
  145. bus_json["times"][travel["routes"][i][k]["name"]] = {}
  146. try:
  147. times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]
  148. except Exception:
  149. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]] ={}
  150. if weekno < 5:
  151. try:
  152. weekday = "HAFTA+%C4%B0%C3%87%C4%B0"
  153. times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["weekday"]
  154. except KeyError:
  155. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["weekday"] = send_request(url, "HAT={0}&DURAK={1}&TUR={2}".format(travel["routes"][i][k]["name"], travel["routes"][i][k]["stops"][j], weekday))["data"][0]["table"]
  156. times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["weekday"]
  157. change = True
  158. elif weekno == 5:
  159. try:
  160. weekday = "CUMARTES%C4%B0"
  161. times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["saturday"]
  162. except KeyError:
  163. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["saturday"] = send_request(url, "HAT={0}&DURAK={1}&TUR={2}".format(travel["routes"][i][k]["name"], travel["routes"][i][k]["stops"][j], weekday))["data"][0]["table"]
  164. times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["saturday"]
  165. change = True
  166. else:
  167. try:
  168. weekday = "PAZAR"
  169. times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["sunday"]
  170. except KeyError:
  171. bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["sunday"] = send_request(url, "HAT={0}&DURAK={1}&TUR={2}".format(travel["routes"][i][k]["name"], travel["routes"][i][k]["stops"][j], weekday))["data"][0]["table"]
  172. times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["sunday"]
  173. change = True
  174. for time in times_raw:
  175. times_anal[j].append(datetime.datetime.strptime("{0}:{1}".format(time["saat"], time["dakika"]), "%H:%M"))
  176. closest_times = get_closest_time([times_anal[0], times_anal[1]], time_cur)
  177. travel["routes"][i][k]["time"] = closest_times
  178. empty = []
  179. for i in range(len(travel["routes"])):
  180. remove=True
  181. for k in range(len(travel["routes"][i])):
  182. if remove:
  183. if len(travel["routes"][i][k]["time"]) == 0:
  184. empty.append(i-len(empty))
  185. remove = False
  186. for i in empty:
  187. travel["routes"].pop(i)
  188. if change:
  189. bus_data = open("databases/bus.json","w")
  190. bus_data.write(json.dumps(bus_json,indent=4, sort_keys=True))
  191. bus_data.close()
  192. for route in travel["routes"]:
  193. start = route[0]["time"][0]
  194. end = route[-1]["time"][1]
  195. diff = time_diff(start, end)
  196. diff = time_sum(diff, time_diff(time_cur.strftime("%H:%M"), start))
  197. diff = time_sum(diff, "00:05")
  198. travel["total"].append(diff)
  199. return travel
  200. if __name__ == '__main__':
  201. api.add_resource(Transit, '/transit', '/transit/')
  202. app.run( host='0.0.0.0', port=5000 )