Browse Source

public Transport added

old
Yiğit Çolakoğlu 6 years ago
parent
commit
bc1ac556db
24 changed files with 44722 additions and 6782 deletions
  1. +2
    -0
      MyCity/app/build.gradle
  2. +3
    -3
      MyCity/app/src/main/java/gq/yigit/mycity/DenunciationFragment.java
  3. +15
    -3
      MyCity/app/src/main/java/gq/yigit/mycity/MainActivity.java
  4. +4
    -4
      MyCity/app/src/main/java/gq/yigit/mycity/RateFragment.java
  5. +306
    -0
      MyCity/app/src/main/java/gq/yigit/mycity/navigation/TransitFragment.java
  6. +5
    -4
      MyCity/app/src/main/java/gq/yigit/mycity/tools/WebRequest.java
  7. +2
    -2
      MyCity/app/src/main/java/gq/yigit/mycity/utility/UtilityElectricity.java
  8. +1
    -1
      MyCity/app/src/main/java/gq/yigit/mycity/utility/UtilityMain.java
  9. +3
    -3
      MyCity/app/src/main/java/gq/yigit/mycity/votesFragment/VoteFragment.java
  10. +2
    -2
      MyCity/app/src/main/java/gq/yigit/mycity/votesFragment/VotesFragment.java
  11. +1
    -1
      MyCity/app/src/main/res/drawable-v24/magnifier.xml
  12. +12
    -0
      MyCity/app/src/main/res/drawable/circle_shape.xml
  13. +11
    -0
      MyCity/app/src/main/res/drawable/line_shape.xml
  14. +10
    -0
      MyCity/app/src/main/res/drawable/search_shape.xml
  15. +0
    -1
      MyCity/app/src/main/res/layout/fragment_main.xml
  16. +37
    -0
      MyCity/app/src/main/res/layout/fragment_transit.xml
  17. +1
    -1
      MyCity/app/src/main/res/layout/fragment_utility.xml
  18. +20
    -8
      MyCity/app/src/main/res/layout/popup_confirmation.xml
  19. +72
    -0
      MyCity/app/src/main/res/layout/transit_item.xml
  20. +1
    -0
      MyCity/app/src/main/res/values/dimens.xml
  21. BIN
      server_side/api/modules/__pycache__/denunciation.cpython-37.pyc
  22. BIN
      server_side/api/modules/__pycache__/navigation.cpython-37.pyc
  23. +44025
    -6669
      server_side/api/modules/databases/bus.json
  24. +189
    -80
      server_side/api/modules/navigation.py

+ 2
- 0
MyCity/app/build.gradle View File

@ -32,4 +32,6 @@ dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.android.libraries.places:places:1.1.0'
}

+ 3
- 3
MyCity/app/src/main/java/gq/yigit/mycity/DenunciationFragment.java View File

@ -112,7 +112,7 @@ public class DenunciationFragment extends Fragment implements WebRequest.respons
args.put("photo", "null");
}
WebRequest request = new WebRequest(url+"/denunciation",false,args);
WebRequest request = new WebRequest(url+"/denunciation",false,args,0);
request.addListener(activity);
request.execute();
}
@ -177,7 +177,7 @@ public class DenunciationFragment extends Fragment implements WebRequest.respons
void onFragmentInteraction(Uri uri);
}
public void receivedResponse(boolean success, String response) {
public void receivedResponse(boolean success, String response,int id) {
try {
JSONObject received = new JSONObject(response);
if (reps % 2 == 0) {
@ -213,7 +213,7 @@ public class DenunciationFragment extends Fragment implements WebRequest.respons
}
args.put("accepted","true");
WebRequest requestConfirm = new WebRequest(url+"/denunciation",false,args);
WebRequest requestConfirm = new WebRequest(url+"/denunciation",false,args,0);
requestConfirm.addListener(activity);
requestConfirm.execute();
}


+ 15
- 3
MyCity/app/src/main/java/gq/yigit/mycity/MainActivity.java View File

@ -1,14 +1,18 @@
package gq.yigit.mycity;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView.OnNavigationItemSelectedListener;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.*;
@ -23,6 +27,7 @@ import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import gq.yigit.mycity.navigation.MapsFragment;
import gq.yigit.mycity.navigation.TransitFragment;
import gq.yigit.mycity.tools.*;
import gq.yigit.mycity.tools.WebRequest.responseListener;
import gq.yigit.mycity.utility.UtilityMain;
@ -46,6 +51,7 @@ public class MainActivity extends AppCompatActivity
RateFragment.OnFragmentInteractionListener,
MapsFragment.OnFragmentInteractionListener,
UtilityMain.OnFragmentInteractionListener,
TransitFragment.OnFragmentInteractionListener,
OnFragmentInteractionListener,
responseListener,
imageListener {
@ -57,10 +63,13 @@ public class MainActivity extends AppCompatActivity
private ImageView avatarView;
private TextView userName;
public static Activity mainActivity;
public static String apikey = "AIzaSyBuOC03IHPA_6TPnfk18b0SAgD1uge4-dk";
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("[BOOKMARK]","Started creating activity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
@ -77,7 +86,7 @@ public class MainActivity extends AppCompatActivity
HashMap<String,String> request = new HashMap<>();
request.put("username","efe");
request.put("password","12345");
WebRequest login_manager = new WebRequest(url + "/login/",false,request);
WebRequest login_manager = new WebRequest(url + "/login/",false,request,0);
login_manager.addListener(this);
Log.d("[BOOKMARK]","Before executing login");
login_manager.execute();
@ -163,7 +172,10 @@ public class MainActivity extends AppCompatActivity
} else if (id == R.id.parking) {
} else if (id == R.id.transit) {
TransitFragment fragment = new TransitFragment();
fragmentTransaction.replace(R.id.app_bar_main, fragment);
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
} else if (id == R.id.navigation) {
MapsFragment fragment = new MapsFragment();
fragmentTransaction.replace(R.id.app_bar_main, fragment);
@ -205,7 +217,7 @@ public class MainActivity extends AppCompatActivity
}
public void receivedResponse(boolean success,String response){
public void receivedResponse(boolean success,String response,int reqid){
if(success) {
try {
JSONArray receivedData = new JSONArray(response);


+ 4
- 4
MyCity/app/src/main/java/gq/yigit/mycity/RateFragment.java View File

@ -115,7 +115,7 @@ public class RateFragment extends Fragment implements WebRequest.responseListene
Log.e("[ERROR]","An error occured with json!");
}
request.put("note",comment);
WebRequest rate_sender = new WebRequest(url + "/rate", false, request);
WebRequest rate_sender = new WebRequest(url + "/rate", false, request,0);
rate_sender.execute();
}
}
@ -139,7 +139,7 @@ public class RateFragment extends Fragment implements WebRequest.responseListene
HashMap<String,String> request = new HashMap<>();
request.put("longitude",longitude);
request.put("latitude",latitude);
WebRequest web_manager = new WebRequest(url + "/ratings",false,request);
WebRequest web_manager = new WebRequest(url + "/ratings",false,request,0);
web_manager.addListener(this);
web_manager.execute();
return rootView;
@ -175,7 +175,7 @@ public class RateFragment extends Fragment implements WebRequest.responseListene
@Override
public void receivedResponse(boolean success, String response) {
public void receivedResponse(boolean success, String response,int id) {
if(success){
try {
ratings = new JSONArray(response);
@ -223,7 +223,7 @@ public class RateFragment extends Fragment implements WebRequest.responseListene
private void downloadImg(int i) throws JSONException {
ImageDownload downloader = new ImageDownload();
downloader.addListener(this);
downloader.execute(url + ((JSONObject) ratings.get(i)).get("img"));
downloader.execute(url + ((JSONObject) ratings.get(i)).get("type"));
}


+ 306
- 0
MyCity/app/src/main/java/gq/yigit/mycity/navigation/TransitFragment.java View File

@ -0,0 +1,306 @@
package gq.yigit.mycity.navigation;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.RectangularBounds;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.AutocompleteActivity;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
import gq.yigit.mycity.R;
import gq.yigit.mycity.tools.FileActions;
import gq.yigit.mycity.tools.WebRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static gq.yigit.mycity.MainActivity.apikey;
import static gq.yigit.mycity.MainActivity.cntxt;
public class TransitFragment extends Fragment implements WebRequest.responseListener {
private OnFragmentInteractionListener mListener;
private OnRecyclerViewInteractionListener recyclerViewInteractionListener;
private TextView place_name;
private String[] place_data = {"","","",""};
private PlacesClient placesClient;
private String url;
private String longitude;
private String latitude;
private RecyclerView recyclerView;
public TransitFragment() {
// Required empty public constructor
}
public static TransitFragment newInstance(String param1, String param2) {
TransitFragment fragment = new TransitFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_transit, container, false);
LinearLayout search_button = rootView.findViewById(R.id.search_layout);
search_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Places.initialize(getContext(), apikey);
placesClient = Places.createClient(getContext());
int AUTOCOMPLETE_REQUEST_CODE = 1;
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME,Place.Field.LAT_LNG);
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields).
setLocationRestriction(RectangularBounds.newInstance(new LatLng(39.7281252,32.4848006),new LatLng(40.061707,32.9889204)))
.build(getContext());
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
}
});
place_name = rootView.findViewById(R.id.place_name);
recyclerView = rootView.findViewById(R.id.route_view);
try {
LocationManager locationManager = (LocationManager)
getContext().getSystemService(cntxt.LOCATION_SERVICE);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = String.valueOf((double)loc.getLongitude());
latitude = String.valueOf(loc.getLatitude());
}catch (SecurityException e){
Log.e("[ERROR]","An error occured with location permissions");
}
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
place_data[0] = place.getName();
place_data[1] = place.getId();
Log.i("[INFO]", "Place: " + place.getName() + ", " + place.getId());
place_name.setText(place_data[0]);
place_data[2] = String.valueOf(place.getLatLng().latitude);
place_data[3] = String.valueOf(place.getLatLng().longitude);
FileActions file_manager = new FileActions();
url = file_manager.readFromFile(cntxt,"server.config").trim();
HashMap<String,String> args = new HashMap<>();
args.put("lat_usr",latitude);
args.put("lng_usr",longitude);
args.put("lat_dest",place_data[2]);
args.put("lng_dest",place_data[3]);
WebRequest request = new WebRequest(url + "/transit",false, args,0);
request.addListener(this);
request.execute();
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
Status status = Autocomplete.getStatusFromIntent(data);
Log.i("[INFO]", status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
}
}
}
@Override
public void receivedResponse(boolean success,String response, int reqid){
Log.i("[INFO]",response);
try{
JSONObject travel = new JSONObject(response);
JSONArray routes = new JSONArray(travel.getString("routes"));
for(int i = 0; i< routes.length();i++){
JSONObject route = new JSONObject(routes.getString(i));
TransitContent.addItem(new TransitContent.TransitItem(
route.getString("name"),
(new JSONArray(route.getString("stops")).getString(0)),
(new JSONArray(route.getString("stops")).getString(1)),
(new JSONArray(route.getString("time")).getString(0)),
(new JSONArray(route.getString("time")).getString(1)),
"bus"
));
}
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(new TransitAdapter(TransitContent.ITEMS, recyclerViewInteractionListener));
}catch (JSONException e){
Log.e("[ERROR]", "Received invalid response from public transport service!");
}
}
public interface OnRecyclerViewInteractionListener {
void OnRecyclerViewInteractionListener(TransitContent.TransitItem item);
}
}
class TransitContent {
public static final List<TransitItem> ITEMS = new ArrayList<TransitItem>();
public static final Map<String, TransitItem> ITEM_MAP = new HashMap<String, TransitItem>();
public static void addItem(TransitItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.endTime, item);
}
public static class TransitItem {
public final String lineNo;
public final String startName;
public final String endName;
public final String startTime;
public final String endTime;
public final String type;
public TransitItem(String lineNo, String startName, String endName, String startTime, String endTime, String type) {
this.lineNo = lineNo;
this.startName = startName;
this.endName = endName;
this.startTime = startTime;
this.endTime = endTime;
this.type = type;
}
}
}
class TransitAdapter extends RecyclerView.Adapter<TransitAdapter.ViewHolder>{
private final List<TransitContent.TransitItem> mValues;
private final TransitFragment.OnRecyclerViewInteractionListener mListener;
public TransitAdapter(List<TransitContent.TransitItem> items, TransitFragment.OnRecyclerViewInteractionListener listener) {
mValues = items;
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.transit_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.stop1.setText(mValues.get(position).startName);
holder.stop2.setText(mValues.get(position).endName);
holder.time1.setText(mValues.get(position).startTime);
holder.time2.setText(mValues.get(position).endTime);
holder.line.setText(mValues.get(position).lineNo);
String type = mValues.get(position).type;
if(type.equals("bus")){
}else if(type.equals("subway") || type.equals("ankaray")){
}else if(type.equals("walk")){}
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
mListener.OnRecyclerViewInteractionListener(holder.mItem);
}
}
});
}
@Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final View mView;
private final TextView stop1;
private final TextView stop2;
private final ImageView type;
private final TextView line;
private final TextView time1;
private final TextView time2;
private TransitContent.TransitItem mItem;
private ViewHolder(View view) {
super(view);
mView = view;
stop1 = view.findViewById(R.id.stop1_addr);
stop2 = view.findViewById(R.id.stop2_addr);
time1 = view.findViewById(R.id.stop1_time);
time2 = view.findViewById(R.id.stop2_time);
line = view.findViewById(R.id.line_no);
type = view.findViewById(R.id.type_img);
}
}
}

+ 5
- 4
MyCity/app/src/main/java/gq/yigit/mycity/tools/WebRequest.java View File

@ -37,9 +37,9 @@ public class WebRequest extends AsyncTask<Void,Void,String> {
private HttpPost post_request;
private HttpResponse response;
private List<responseListener> listeners = new ArrayList<>();
private int reqid = 0;
public WebRequest(String url, boolean request_type, HashMap<String,String> request_content){
public WebRequest(String url, boolean request_type, HashMap<String,String> request_content,int reqid){
client = AcceptAllSSLSocketFactory.getNewHttpClient();
@ -61,6 +61,7 @@ public class WebRequest extends AsyncTask<Void,Void,String> {
}else{
post_request = new HttpPost(this.url);
}
this.reqid = reqid;
}
protected String doInBackground(Void... params){
@ -109,14 +110,14 @@ public class WebRequest extends AsyncTask<Void,Void,String> {
}
protected void onPostExecute(String result){
for (responseListener hl : listeners)
hl.receivedResponse(!result.equals("Error"),result);
hl.receivedResponse(!result.equals("Error"),result,reqid);
}
public void addListener(responseListener toAdd) {
listeners.add(toAdd);
}
public interface responseListener {
void receivedResponse(boolean success, String response);
void receivedResponse(boolean success, String response,int id);
}
}


+ 2
- 2
MyCity/app/src/main/java/gq/yigit/mycity/utility/UtilityElectricity.java View File

@ -69,7 +69,7 @@ public class UtilityElectricity extends Fragment implements WebRequest.responseL
Log.e("[ERROR]","User data not correct");
}
request.put("type","electricity");
WebRequest login_manager = new WebRequest(url + "/resources/",false,request);
WebRequest login_manager = new WebRequest(url + "/resources/",false,request,0);
login_manager.addListener(this);
login_manager.execute();
@ -106,7 +106,7 @@ public class UtilityElectricity extends Fragment implements WebRequest.responseL
void onFragmentInteraction(Uri uri);
}
public void receivedResponse(boolean success, String result){
public void receivedResponse(boolean success, String result,int reqid){
if(success){
try{
electricityUsage = new JSONObject(result);


+ 1
- 1
MyCity/app/src/main/java/gq/yigit/mycity/utility/UtilityMain.java View File

@ -36,7 +36,7 @@ public class UtilityMain extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);one_bus[i][j]
super.onCreate(savedInstanceState);
}


+ 3
- 3
MyCity/app/src/main/java/gq/yigit/mycity/votesFragment/VoteFragment.java View File

@ -75,7 +75,7 @@ public class VoteFragment extends Fragment implements responseListener, imageLis
FileActions file_manager = new FileActions();
url = file_manager.readFromFile(getContext(),"server.config").trim();
String url_vote = url + "/votings/" + vote_id;
WebRequest data_request = new WebRequest(url_vote,true,new HashMap<String, String>());
WebRequest data_request = new WebRequest(url_vote,true,new HashMap<String, String>(),0);
data_request.addListener(this);
data_request.execute();
cntxt = getContext();
@ -110,7 +110,7 @@ public class VoteFragment extends Fragment implements responseListener, imageLis
void onFragmentInteraction(Uri uri);
}
public void receivedResponse(boolean success,String response){
public void receivedResponse(boolean success,String response, int reqid){
Log.i("[INFO]",response);
if(success){
try{
@ -170,7 +170,7 @@ public class VoteFragment extends Fragment implements responseListener, imageLis
}catch (JSONException e){
Log.e("[ERROR]","Cannot get user data");
}
WebRequest vote_request = new WebRequest(url+"/vote",false, params);
WebRequest vote_request = new WebRequest(url+"/vote",false, params,0);
vote_request.execute();
}else{
Toast.makeText(cntxt,"Please selet a vote!",Toast.LENGTH_SHORT).show();


+ 2
- 2
MyCity/app/src/main/java/gq/yigit/mycity/votesFragment/VotesFragment.java View File

@ -69,7 +69,7 @@ public class VotesFragment extends Fragment implements responseListener, imageLi
}
FileActions file_manager = new FileActions();
url = (file_manager.readFromFile(context,"server.config")).trim();
WebRequest web_manager = new WebRequest(url + "/votings/",true,new HashMap<String,String>());
WebRequest web_manager = new WebRequest(url + "/votings/",true,new HashMap<String,String>(),0);
web_manager.addListener(this);
web_manager.execute();
}
@ -98,7 +98,7 @@ public class VotesFragment extends Fragment implements responseListener, imageLi
void onListFragmentInteraction(VoteItem item);
}
public void receivedResponse(boolean success, String response){
public void receivedResponse(boolean success, String response,int id){
if(success) {
try {


+ 1
- 1
MyCity/app/src/main/res/drawable-v24/magnifier.xml View File

@ -6,5 +6,5 @@
<path
android:pathData="M244.186 214.604l-54.379 -54.378c-0.289 -0.289 -0.628 -0.491 -0.93 -0.76c10.7 -16.231 16.945 -35.66 16.945 -56.554C205.822 46.075 159.747 0 102.911 0S0 46.075 0 102.911c0 56.835 46.074 102.911 102.91 102.911c20.895 0 40.323 -6.245 56.554 -16.945c0.269 0.301 0.47 0.64 0.759 0.929l54.38 54.38c8.169 8.168 21.413 8.168 29.583 0C252.354 236.017 252.354 222.773 244.186 214.604zM102.911 170.146c-37.134 0 -67.236 -30.102 -67.236 -67.235c0 -37.134 30.103 -67.236 67.236 -67.236c37.132 0 67.235 30.103 67.235 67.236C170.146 140.044 140.043 170.146 102.911 170.146z"
android:fillType="evenOdd"
android:fillColor="#000000" />
android:fillColor="#717171" />
</vector>

+ 12
- 0
MyCity/app/src/main/res/drawable/circle_shape.xml View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="1.9"
android:useLevel="false" >
<solid android:color="@android:color/transparent" />
<stroke
android:width="10dp"
android:color="@android:color/white" />
</shape>

+ 11
- 0
MyCity/app/src/main/res/drawable/line_shape.xml View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="6dp"/>
<stroke
android:width="0dp"
android:color="#c9c9c9" />
<solid android:color="#0019B9" />
</shape>

+ 10
- 0
MyCity/app/src/main/res/drawable/search_shape.xml View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="20dp"/>
<stroke
android:width="2dp"
android:color="#c9c9c9" />
<solid android:color="#e9e9e9" />
</shape>

+ 0
- 1
MyCity/app/src/main/res/layout/fragment_main.xml View File

@ -5,7 +5,6 @@
android:layout_height="match_parent"
tools:context=".MainFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"


+ 37
- 0
MyCity/app/src/main/res/layout/fragment_transit.xml View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".navigation.TransitFragment"
android:layout_marginTop="@dimen/fragment_margin"
android:orientation="vertical">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="@+id/search_layout"
android:background="@drawable/search_shape"
android:layout_marginHorizontal="10dp"
android:paddingHorizontal="5dp"
android:layout_marginBottom="30dp">
<ImageView
android:layout_width="70dp"
android:layout_height="40dp" android:id="@+id/rate_item_img"
android:layout_weight="1"
android:layout_marginRight="5dp" app:srcCompat="@drawable/magnifier"
android:layout_marginVertical="5dp"
android:layout_marginLeft="10dp"/>
<TextView
android:text="Please select a place"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/place_name" android:layout_weight="1"
android:gravity="center_vertical" android:textColor="#FF616161" android:textSize="16sp"
android:layout_marginLeft="7dp"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/route_view"
android:layout_marginLeft="8dp"/>
</LinearLayout>

+ 1
- 1
MyCity/app/src/main/res/layout/fragment_utility.xml View File

@ -6,7 +6,7 @@
android:layout_width="match_parent"
android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".utility.UtilityMain" android:orientation="vertical"
android:layout_marginTop="55dp">
android:layout_marginTop="@dimen/fragment_margin">


+ 20
- 8
MyCity/app/src/main/res/layout/popup_confirmation.xml View File

@ -1,9 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dp">
<TextView
android:text="If this alert is wrong, you will receive a penalty of "
@ -13,7 +14,11 @@
android:textStyle="normal|bold"
android:textSize="18sp"
android:layout_alignParentTop="true"
android:layout_marginTop="193dp" android:layout_centerHorizontal="true" android:textColor="#000000"/>
android:layout_centerHorizontal="true" android:textColor="#000000"
android:layout_marginTop="20dp"
app:layout_constraintTop_toBottomOf="@+id/imageView" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="8dp" android:layout_marginEnd="8dp" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"/>
<Button
android:id="@+id/confirm_button"
@ -24,12 +29,19 @@
android:textSize="18sp"
style="@android:style/Widget.Button"
tools:ignore="RtlHardcoded,RtlSymmetry"
android:layout_centerHorizontal="true" android:layout_alignParentBottom="true"
android:layout_marginBottom="211dp" android:background="@android:color/holo_red_dark"/>
android:layout_alignParentBottom="true"
android:background="@android:color/holo_red_dark"
android:layout_alignStart="@+id/imageView"
android:layout_marginTop="36dp"
app:layout_constraintTop_toBottomOf="@+id/confirm_text" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="8dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"/>
<ImageView
android:layout_width="191dp"
android:layout_height="181dp" app:srcCompat="@drawable/warning"
android:layout_centerHorizontal="true" android:id="@+id/imageView"
android:layout_alignParentTop="true"/>
android:layout_alignParentTop="true"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="8dp"/>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>

+ 72
- 0
MyCity/app/src/main/res/layout/transit_item.xml View File

@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:gravity="center"
android:background="@drawable/line_shape"
android:padding="2dp"
android:layout_marginRight="7dp">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp" app:srcCompat="@drawable/bus" android:id="@+id/type_img"
android:background="@drawable/circle_shape"
android:padding="2dp"/>
</LinearLayout>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" android:id="@+id/linearLayout">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/stop1_addr"
android:textColor="#000000"
android:textSize="15sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="8dp" android:layout_marginTop="8dp"/>
<TextView
android:text="TextView"
android:layout_width="64dp"
android:layout_height="wrap_content" android:id="@+id/stop1_time"
android:textColor="#000000" android:textSize="15sp"
app:layout_constraintTop_toTopOf="@+id/stop1_addr"
app:layout_constraintStart_toEndOf="@+id/stop1_addr" android:layout_marginStart="4dp"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/line_no"
android:textColor="#000000"
android:layout_marginTop="64dp" app:layout_constraintTop_toTopOf="parent"
android:textSize="16sp" android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="@+id/stop2_addr"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/stop2_addr"
android:textColor="#000000" android:textSize="15sp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="@+id/stop1_addr"/>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/stop2_time"
android:textColor="#000000"
android:textSize="15sp"
app:layout_constraintBottom_toBottomOf="@+id/stop2_addr"
app:layout_constraintStart_toStartOf="@+id/stop1_time"/>
</android.support.constraint.ConstraintLayout>
</LinearLayout>

+ 1
- 0
MyCity/app/src/main/res/values/dimens.xml View File

@ -6,4 +6,5 @@
<dimen name="nav_header_height">176dp</dimen>
<dimen name="fab_margin">16dp</dimen>
<dimen name="text_margin">16dp</dimen>
<dimen name="fragment_margin">65dp</dimen>
</resources>

BIN
server_side/api/modules/__pycache__/denunciation.cpython-37.pyc View File


BIN
server_side/api/modules/__pycache__/navigation.cpython-37.pyc View File


+ 44025
- 6669
server_side/api/modules/databases/bus.json
File diff suppressed because it is too large
View File


+ 189
- 80
server_side/api/modules/navigation.py View File

@ -1,26 +1,23 @@
from flask import Flask, request
from flask_restful import Resource, Api, abort
import requests
import json
import datetime
import json
import requests
from flask import Flask, request
from flask_restful import Api, Resource
app = Flask( __name__ )
api = Api( app )
app = Flask(__name__)
api = Api(app)
def send_request(url, raw):
headers = {
"User-Agent": "EGO Genel Mudurlugu-EGO Cepte-3.1.0 GT-I9500 7.1.2",
"Content-Type": "application/x-www-form-urlencoded", "Content-Length": str(len(raw))
"User-Agent": "EGO Genel Mudurlugu-EGO Cepte-3.1.0 GT-I9500 7.1.2",
"Content-Type":"application/x-www-form-urlencoded", "Content-Length":str(len(raw))
}
r = requests.post(url, headers=headers, data=raw)
content = r.content.decode("cp1252")
replace_chars = {"Ý": "I", "ý": "i", "ð": "g", "þ": "s", "Þ": "S"}
replace_chars = {"Ý":"I", "ý":"i", "ð":"g", "þ":"s", "Þ":"S"}
for key in replace_chars:
content.replace(key, replace_chars[key])
@ -31,54 +28,76 @@ def send_request(url, raw):
conn1 = send_request(
'http://88.255.141.70/mbl/android/connect.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID=%7BACB78701'
'-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=Connect',
"UID=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&UPS=TRUE")
'http://88.255.141.70/mbl/android/connect.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID=%7BACB78701'
'-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=Connect',
"UID=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&UPS=TRUE")
conn2 = send_request(
'http://88.255.141.66/mbl/android/connect.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID=%7BACB78701'
'-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=Start', "")
bus_data = open("databases/bus.json","r")
'http://88.255.141.66/mbl/android/connect.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID=%7BACB78701'
'-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=Start', "")
bus_data = open("modules/databases/bus.json", "r")
bus_json = json.loads(bus_data.read())
routes = bus_json["stops"]
bus_data.close()
print('\n',conn1, '\n\n', conn2, '\n')
print('\n', conn1, '\n\n', conn2, '\n')
def time_small(t1, t2):
time1 = datetime.datetime.strptime(t1, "%H:%M")
time2 = datetime.datetime.strptime(t2, "%H:%M")
if time1 < time2:
return False
else:
return True
def time_diff(t1, t2):
time1 = datetime.datetime.strptime(t1,"%H:%M")
time2 = datetime.datetime.strptime(t2,"%H:%M")
time1 = datetime.datetime.strptime(t1, "%H:%M")
time2 = datetime.datetime.strptime(t2, "%H:%M")
response = ""
if time2.hour-time1.hour < 10:
if abs(time2.hour - time1.hour) < 10:
response += "0"
response += str(time2.hour-time1.hour)
if time2.minute - time1.minute >= 0:
response += str(abs(time2.hour - time1.hour))
else:
response += str(abs(time2.hour - time1.hour) - 1)
response += ":"
if time2.minute-time1.minute < 10:
if abs(time2.minute - time1.minute) < 10:
response += "0"
response += str(time2.minute-time1.minute)
response += str(abs(time2.minute - time1.minute))
return response
def time_sum(t1,t2):
time1 = datetime.datetime.strptime(t1,"%H:%M")
time2 = datetime.datetime.strptime(t2,"%H:%M")
def time_sum(t1, t2):
time1 = datetime.datetime.strptime(t1, "%H:%M")
time2 = datetime.datetime.strptime(t2, "%H:%M")
response = ""
if time2.hour+time1.hour < 10:
if time2.hour + time1.hour < 10:
response += "0"
response += str(time2.hour+time1.hour)
if time2.minute + time1.minute > 60:
response += str(time2.hour + time1.hour + 1)
else:
response += str(time2.hour + time1.hour)
response += ":"
if time2.minute+time1.minute < 10:
if time2.minute + time1.minute % 60 < 10:
response += "0"
response += str(time2.minute+time1.minute)
response += str((time2.minute + time1.minute) % 60)
return response
def get_closest_time(times, time):
closest = [0, 0]
for i in times[0]:
if i.hour < time.hour or (i.hour == time.hour and i.minute-6 < time.minute):
if i.hour < time.hour or (i.hour == time.hour and i.minute - 6 < time.minute):
continue
else:
if closest[0] == 0:
@ -95,7 +114,7 @@ def get_closest_time(times, time):
return []
for i in times[1]:
if i.hour < closest[0].hour or (i.hour == closest[0].hour and i.minute-6 < closest[0].minute):
if i.hour < closest[0].hour or (i.hour == closest[0].hour and i.minute - 6 < closest[0].minute):
continue
else:
if closest[1] == 0:
@ -112,20 +131,17 @@ def get_closest_time(times, time):
return [closest[0].strftime("%H:%M"), closest[1].strftime("%H:%M")]
class Transit(Resource):
def post(self):
change = False
args = request.form
stops_raw = {"user": {}, "dest": {}}
stops_arr = {"user": {}, "dest": {}}
stops_raw = {"user":{}, "dest":{}}
stops_arr = {"user":{}, "dest":{}}
url_closestops = "http://88.255.141.66/mbl/android/action.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID" \
"=%7BACB78701"\
"-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=YakinDuraklar"
url_closestops = "http://88.255.141.66/mbl/android/action.asp?SID=0.392509188312098&VER=3.1.0&LAN=tr&UID"\
"=%7BACB78701"\
"-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=YakinDuraklar"
closestops = send_request(url_closestops, "LAT={0}&LNG={1}&MSF=500".format(args["lat_usr"], args["lng_usr"]))
for stop in closestops["data"][0]["table"]:
@ -136,32 +152,66 @@ class Transit(Resource):
stops_arr["dest"][stop["kod"]] = stop["hatlar"].split(",")
one_bus = {k.strip():
[dict({x: n for n in stops_arr["user"] for x in stops_arr["user"][n]})[k],
dict({x: n for n in stops_arr["dest"] for x in stops_arr["dest"][n]})[k]]
[dict({x:n for n in stops_arr["user"] for x in stops_arr["user"][n]})[k],
dict({x:n for n in stops_arr["dest"] for x in stops_arr["dest"][n]})[k]]
for k in(list(set([x for n in stops_arr["user"] for x in stops_arr["user"][n]])
& set([x for n in stops_arr["dest"] for x in stops_arr["dest"][n]])))}
for k in (list(set([x for n in stops_arr["user"] for x in stops_arr["user"][n]])
& set([x for n in stops_arr["dest"] for x in stops_arr["dest"][n]])))}
travel = {"routes": [], "total":[]}
# time_cur = datetime.datetime.today().time()
time_cur =datetime.datetime.strptime("13:00","%H:%M")
travel = {"routes":[], "total":[]}
# time_cur = datetime.datetime.today().time()
time_cur = datetime.datetime.strptime("13:00", "%H:%M")
if len(one_bus) > 0:
for i in one_bus:
travel["routes"].append([{"name":i,"stops":[one_bus[i][0],one_bus[i][1]]}])
for i in one_bus:
travel["routes"].append([{"name":i, "stops":[one_bus[i][0], one_bus[i][1]]}])
else:
routes_arr = {"user": {}, "dest": {}}
routes_arr = {"user":{}, "dest":{}}
stopno = {}
for i in stops_arr["user"]:
for j in stops_arr["user"][i]:
routes_arr["user"][j.strip()] = bus_json["stops"][j.strip()]
try:
routes_arr["user"][j.strip()] = bus_json["stops"][j.strip()]
except KeyError:
stops = send_request(
"http://88.255.141.66/mbl/android/action.asp?SID=0.8737969480190279&VER=3.1.0&LAN=tr"
"&UID"
"=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=HatBilgileri",
"KOD={}".format(routes_arr["user"][j.strip()]))["data"][0]["table_durak"]
bus_json["stops"][j.strip()] = [x["kod"] for x in stops]
routes_arr["user"][j.strip()] = bus_json["stops"][j.strip()]
for x in stops:
bus_json["stop_info"][x["kod"]] = {
"name": x["ad"],
"location":x["konum"],
"lat": x["lat"],
"lng": x["lng"]
}
change = True
stopno[j.strip()] = i
for i in stops_arr["dest"]:
for j in stops_arr["dest"][i]:
routes_arr["dest"][j.strip()] = bus_json["stops"][j.strip()]
try:
routes_arr["dest"][j.strip()] = bus_json["stops"][j.strip()]
except KeyError:
stops = send_request(
"http://88.255.141.66/mbl/android/action.asp?SID=0.8737969480190279&VER=3.1.0&LAN=tr"
"&UID"
"=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=HatBilgileri",
"KOD={}".format(routes_arr["dest"][j.strip()]))["data"][0]["table_durak"]
bus_json["stops"][j.strip()] = [x["kod"] for x in stops]
routes_arr["dest"][j.strip()] = bus_json["stops"][j.strip()]
for x in stops:
bus_json["stop_info"][x["kod"]] = {
"name": x["ad"],
"location":x["konum"],
"lat": x["lat"],
"lng": x["lng"]
}
change = True
stopno[j.strip()] = i
for i in routes_arr["user"]:
@ -170,14 +220,14 @@ class Transit(Resource):
for x in routes_arr["dest"][k]:
if j.strip() == x.strip():
travel["routes"].append([
{"name": i.strip(), "stops": [stopno[i.strip()], x.strip()]},
{"name": k.strip(), "stops": [x.strip(), stopno[k.strip()]]}])
{"name":i.strip(), "stops":[stopno[i.strip()], x.strip()]},
{"name":k.strip(), "stops":[x.strip(), stopno[k.strip()]]}])
for i in range(len(travel["routes"])):
for k in range(len(travel["routes"][i])):
url = "http://88.255.141.66/mbl/android/action.asp?SID=0.4474110208361718&VER=3.1.0&LAN=tr&UID"\
"=%7BACB78701-2727-4E9A-AE62-28491D671A7D%7D-130570234&FNC=DuraktanGecisSaatleri "
weekno = datetime.datetime.today().weekday()
times_anal = [[], []]
for j in range(2):
@ -187,59 +237,77 @@ class Transit(Resource):
bus_json["times"][travel["routes"][i][k]["name"]] = {}
try:
times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]
times_raw = bus_json["times"][travel["routes"][i][k]["name"]][
travel["routes"][i][k]["stops"][j]]
except Exception:
bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]] ={}
bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]] = {}
if weekno < 5:
try:
weekday = "HAFTA+%C4%B0%C3%87%C4%B0"
times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["weekday"]
times_raw =\
bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
"weekday"]
except KeyError:
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"]
times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["weekday"]
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"]
times_raw =\
bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
"weekday"]
change = True
elif weekno == 5:
try:
weekday = "CUMARTES%C4%B0"
times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["saturday"]
times_raw =\
bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
"saturday"]
except KeyError:
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"]
times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["saturday"]
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"]
times_raw =\
bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
"saturday"]
change = True
else:
try:
weekday = "PAZAR"
times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["sunday"]
times_raw =\
bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
"sunday"]
except KeyError:
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"]
times_raw = bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]]["sunday"]
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"]
times_raw =\
bus_json["times"][travel["routes"][i][k]["name"]][travel["routes"][i][k]["stops"][j]][
"sunday"]
change = True
for time in times_raw:
times_anal[j].append(datetime.datetime.strptime("{0}:{1}".format(time["saat"], time["dakika"]), "%H:%M"))
times_anal[j].append(
datetime.datetime.strptime("{0}:{1}".format(time["saat"], time["dakika"]), "%H:%M"))
closest_times = get_closest_time([times_anal[0], times_anal[1]], time_cur)
travel["routes"][i][k]["time"] = closest_times
empty = []
for i in range(len(travel["routes"])):
remove=True
remove = True
for k in range(len(travel["routes"][i])):
if remove:
if len(travel["routes"][i][k]["time"]) == 0:
empty.append(i-len(empty))
empty.append(i - len(empty))
remove = False
for i in empty:
travel["routes"].pop(i)
if change:
bus_data = open("databases/bus.json","w")
bus_data.write(json.dumps(bus_json,indent=4, sort_keys=True))
bus_data.close()
for route in travel["routes"]:
start = route[0]["time"][0]
@ -249,10 +317,51 @@ class Transit(Resource):
diff = time_sum(diff, "00:05")
travel["total"].append(diff)
return travel
shortest = 0
for i in range(len(travel["total"])):
if shortest == 0:
shortest = {"routes":travel["routes"][i], "time":travel["total"][i]}
continue
if time_small(shortest["time"], travel["total"][i]):
shortest = {"routes":travel["routes"][i], "time":travel["total"][i]}
if change:
bus_data = open("modules/databases/bus.json", "w")
bus_data.write(json.dumps(bus_json, indent=4, sort_keys=True))
bus_data.close()
for i in range(len(shortest["routes"])):
try:
shortest["routes"][i]["names"] = [bus_json["stop_info"][shortest["routes"][i][0]]["name"],bus_json["stop_info"][shortest["routes"][i][1]]["name"]]
except KeyError:
shortest["routes"][i]["names"] = []
shortest["routes"][i]["locations"] = []
shortest["routes"][i]["coordinates"] = []
for j in range(2):
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",
"QUERY={}".format(shortest["routes"][i]["stops"][j]))["data"][0]["table"][0]
bus_json["stop_info"][shortest["routes"][i]["stops"][j]] ={
"name": data["ad"],
"location": data["konum"],
"lat": data["lat"],
"lng": data["lng"]
}
shortest["routes"][i]["names"].append(bus_json["stop_info"][shortest["routes"][i]["stops"][j]]["name"])
shortest["routes"][i]["locations"].append(bus_json["stop_info"][shortest["routes"][i]["stops"][j]]["location"])
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"]})
change=True
if change:
bus_data = open("modules/databases/bus.json", "w")
bus_data.write(json.dumps(bus_json, indent=4, sort_keys=True))
bus_data.close()
return shortest
if __name__ == '__main__':
api.add_resource(Transit, '/transit', '/transit/')
app.run( host='0.0.0.0', port=5000 )
app.run(host='0.0.0.0', port=5000)

Loading…
Cancel
Save