diff --git a/src/it/reyboz/bustorino/ActivityMain.java b/src/it/reyboz/bustorino/ActivityMain.java index 264a0c9..92fdc55 100644 --- a/src/it/reyboz/bustorino/ActivityMain.java +++ b/src/it/reyboz/bustorino/ActivityMain.java @@ -1,755 +1,756 @@ /* BusTO - Arrival times for Turin public transports. Copyright (C) 2014 Valerio Bozzolan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.NavUtils; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.melnykov.fab.FloatingActionButton; import java.io.UnsupportedEncodingException; import it.reyboz.bustorino.backend.ArrivalsFetcher; import it.reyboz.bustorino.backend.Fetcher; import it.reyboz.bustorino.backend.FiveTScraperFetcher; import it.reyboz.bustorino.backend.GTTJSONFetcher; import it.reyboz.bustorino.backend.Palina; import it.reyboz.bustorino.lab.GTTSiteSucker.BusStop; import it.reyboz.bustorino.lab.MyDB; import it.reyboz.bustorino.lab.adapters.AdapterBusStops; import it.reyboz.bustorino.lab.asyncwget.AsyncWgetBusStopSuggestions; import it.reyboz.bustorino.middleware.AsyncArrivalsFetcherAll; import it.reyboz.bustorino.middleware.PalinaAdapter; public class ActivityMain extends AppCompatActivity { /* * Layout elements */ private EditText busStopSearchByIDEditText; private EditText busStopSearchByNameEditText; private TextView busStopNameTextView; private ProgressBar progressBar; private TextView howDoesItWorkTextView; private Button hideHintButton; private MenuItem actionHelpMenuItem; private SwipeRefreshLayout swipeRefreshLayout; private ListView resultsListView; private FloatingActionButton floatingActionButton; /* * Serach mode */ private static final int SEARCH_BY_NAME = 0; private static final int SEARCH_BY_ID = 1; private static final int SEARCH_BY_ROUTE = 2; // TODO: implement this (bug #1512948) private int searchMode; /* * Options */ private final String OPTION_SHOW_LEGEND = "show_legend"; /** * Last successfully searched bus stop ID */ private String lastSuccessfullySearchedBusStopID = null; AsyncWgetBusStopSuggestions asyncWgetBusStopSuggestions; /* // useful for testing: public class MockFetcher implements ArrivalsFetcher { @Override public Palina ReadArrivalTimesAll(String routeID, AtomicReference res) { SystemClock.sleep(5000); res.set(result.SERVER_ERROR); return new Palina(); } } private ArrivalsFetcher[] ArrivalFetchers = {new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher()};*/ /* * Arrays of fetchers, tryed in this order */ private ArrivalsFetcher[] ArrivalFetchers = {new GTTJSONFetcher(), new FiveTScraperFetcher()}; private int ArrivalFetchersPos; // position in the array (don't set it manually!) private AsyncArrivalsFetcherAll AsyncArrivalsFetcherRunningInstance; // the only one that hasn't been cancelled private SQLiteDatabase db; ///////////////////////////////// EVENT HANDLERS /////////////////////////////////////////////// /* * @see swipeRefreshLayout */ private Handler handler = new Handler(); private final Runnable refreshing = new Runnable() { public void run() { asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStopID, 0); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); busStopSearchByIDEditText = (EditText) findViewById(R.id.busStopSearchByIDEditText); busStopSearchByNameEditText = (EditText) findViewById(R.id.busStopSearchByNameEditText); busStopNameTextView = (TextView) findViewById(R.id.busStopNameTextView); progressBar = (ProgressBar) findViewById(R.id.progressBar); howDoesItWorkTextView = (TextView) findViewById(R.id.howDoesItWorkTextView); hideHintButton = (Button) findViewById(R.id.hideHintButton); resultsListView = (ListView) findViewById(R.id.resultsListView); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton); if (floatingActionButton != null) { floatingActionButton.attachToListView(resultsListView); } busStopSearchByIDEditText.setSelectAllOnFocus(true); busStopSearchByIDEditText .setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // IME_ACTION_SEARCH alphabetical option if (actionId == EditorInfo.IME_ACTION_SEARCH) { onSearchClick(v); return true; } return false; } }); busStopSearchByNameEditText .setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // IME_ACTION_SEARCH alphabetical option if (actionId == EditorInfo.IME_ACTION_SEARCH) { onSearchClick(v); return true; } return false; } }); // Get database in write mode MyDB mDbHelper = new MyDB(this); db = mDbHelper.getWritableDatabase(); // Called when the layout is pulled down swipeRefreshLayout .setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { handler.post(refreshing); } }); /** * @author Marco Gagino!!! */ swipeRefreshLayout.setColorSchemeColors(R.color.blue_500, R.color.orange_500); // setColorScheme is deprecated, setColorSchemeColors isn't setSearchModeBusStopID(); //---------------------------- START INTENT CHECK QUEUE ------------------------------------ // Intercept calls from URL intent boolean tryedFromIntent = false; String busStopID = null; Uri data = getIntent().getData(); if (data != null) { busStopID = getBusStopIDFromUri(data); tryedFromIntent = true; } // Intercept calls from other activities if (!tryedFromIntent) { Bundle b = getIntent().getExtras(); if (b != null) { busStopID = b.getString("bus-stop-ID"); /** * I'm not very sure if you are coming from an Intent. * Some launchers work in strange ways. */ tryedFromIntent = busStopID != null; } } //---------------------------- END INTENT CHECK QUEUE -------------------------------------- if (busStopID == null) { // Show keyboard if can't start from intent showKeyboard(); // You haven't obtained anything... from an intent? if (tryedFromIntent) { // This shows a luser warning asyncWgetBusStopFromBusStopIDReset(); } } else { // If you are here an intent has worked successfully setBusStopSearchByIDEditText(busStopID); asyncWgetBusStopFromBusStopID(busStopID, 0); } Log.d("MainActivity", "Created"); } /** * Reload bus stop timetable when it's fulled resumed from background. */ @Override protected void onPostResume() { super.onPostResume(); Log.d("ActivityMain", "onPostResume fired. Last successfully bus stop ID: " + lastSuccessfullySearchedBusStopID); if (searchMode == SEARCH_BY_ID && lastSuccessfullySearchedBusStopID != null && lastSuccessfullySearchedBusStopID.length() != 0) { setBusStopSearchByIDEditText(lastSuccessfullySearchedBusStopID); asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStopID, 0); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); actionHelpMenuItem = menu.findItem(R.id.action_help); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case android.R.id.home: // Respond to the action bar's Up/Home button NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_help: showHints(); return true; case R.id.action_favorites: startActivity(new Intent(ActivityMain.this, ActivityFavorites.class)); return true; case R.id.action_about: startActivity(new Intent(ActivityMain.this, ActivityAbout.class)); return true; case R.id.action_news: openIceweasel("http://blog.reyboz.it/tag/busto/"); return true; case R.id.action_bugs: openIceweasel("https://bugs.launchpad.net/bus-torino"); return true; case R.id.action_source: openIceweasel("https://code.launchpad.net/bus-torino"); return true; case R.id.action_licence: openIceweasel("http://www.gnu.org/licenses/gpl-3.0.html"); return true; case R.id.action_author: openIceweasel("http://boz.reyboz.it?lovebusto"); return true; } return super.onOptionsItemSelected(item); } /** * OK this is pure shit * * @param v View clicked */ public void onSearchClick(View v) { // TODO: do we need toggleSpinner(true) here? if (searchMode == SEARCH_BY_ID) { String busStopID = busStopSearchByIDEditText.getText().toString(); asyncWgetBusStopFromBusStopID(busStopID, 0); } else { // searchMode == SEARCH_BY_NAME String query = busStopSearchByNameEditText.getText().toString(); asyncWgetBusStopSuggestions(query); } } /** * QR scan button clicked * * @param v View QRButton clicked */ public void onQRButtonClick(View v) { IntentIntegrator integrator = new IntentIntegrator(this); integrator.initiateScan(); } /** * Receive the Barcode Scanner Intent * */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); Uri uri; try { uri = Uri.parse(scanResult != null ? scanResult.getContents() : null); // this apparently prevents NullPointerException. Somehow. } catch (NullPointerException e) { Toast.makeText(getApplicationContext(), R.string.no_qrcode, Toast.LENGTH_SHORT).show(); return; } String busStopID = getBusStopIDFromUri(uri); busStopSearchByIDEditText.setText(busStopID); asyncWgetBusStopFromBusStopID(busStopID, 0); } public void onHideHint(View v) { hideHints(); setOption(OPTION_SHOW_LEGEND, false); } public void onToggleKeyboardLayout(View v) { if (searchMode == SEARCH_BY_NAME) { setSearchModeBusStopID(); if (busStopSearchByIDEditText.requestFocus()) { showKeyboard(); } } else { // searchMode == SEARCH_BY_ID setSearchModeBusStopName(); if (busStopSearchByNameEditText.requestFocus()) { showKeyboard(); } } } ////////////////////// STOPS FINDER BY NAME (NEEDS REFACTORING) //////////////////////////////// /** * It's pure magic <3 * * @param query Part of the busStopName */ private void asyncWgetBusStopSuggestions(String query) { if (query == null || query.length() == 0) { Toast.makeText(getApplicationContext(), R.string.insert_bus_stop_name_error, Toast.LENGTH_SHORT).show(); toggleSpinner(false); return; } if (!NetworkTools.isConnected(getApplicationContext())) { NetworkTools.showNetworkError(getApplicationContext()); toggleSpinner(false); return; } if (asyncWgetBusStopSuggestions != null) { asyncWgetBusStopSuggestions.cancel(true); asyncWgetBusStopSuggestions = null; } try { asyncWgetBusStopSuggestions = new AsyncWgetBusStopSuggestions(query) { public void onReceivedBusStopNames(BusStop[] busStops, int status) { toggleSpinner(false); switch (status) { case AsyncWgetBusStopSuggestions.ERROR_EMPTY_DOM: case AsyncWgetBusStopSuggestions.ERROR_DOM: Toast.makeText(getApplicationContext(), R.string.parsing_error, Toast.LENGTH_SHORT).show(); break; case AsyncWgetBusStopSuggestions.ERROR_NONE: if (busStops.length == 0) { Toast.makeText(getApplicationContext(), R.string.no_bus_stop_have_this_name, Toast.LENGTH_SHORT).show(); } else { for (BusStop busStop : busStops) { MyDB.DBBusStop.addBusStop(db, busStop); } populateBusStopsLayout(busStops); } break; } } }; } catch (UnsupportedEncodingException e) { Toast.makeText(getApplicationContext(), R.string.encoding_error, Toast.LENGTH_SHORT).show(); } } private void populateBusStopsLayout(BusStop[] busStops) { busStopNameTextView.setVisibility(View.GONE); hideKeyboard(); prepareGUIForBusStops(); resultsListView.setAdapter(new AdapterBusStops(this, R.layout.entry_bus_stop, busStops)); resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { /** * Casting because of Javamerda * @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener */ BusStop busStop = (BusStop) parent.getItemAtPosition(position); Intent intent = new Intent(ActivityMain.this, ActivityMain.class); Bundle b = new Bundle(); b.putString("bus-stop-ID", busStop.getBusStopID()); intent.putExtras(b); startActivity(intent); } }); } ///////////////////////////////// ARRIVALS FETCHER ///////////////////////////////////////////// /** * Try every fetcher until you get something usable. * * @param busStopID the ID * @param whichArrivalsFetcher set to 0 if you want to live (used internally by the recursion) */ private void asyncWgetBusStopFromBusStopID(String busStopID, int whichArrivalsFetcher) { toggleSpinner(true); // using a "global" variable to avoid adding parameters to AsyncArrivalsFetcherAll: the fact // that this method uses recursion is a mere implementation detail. this.ArrivalFetchersPos = whichArrivalsFetcher; if(busStopID == null || busStopID.length() == 0) { Toast.makeText(getApplicationContext(), R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show(); toggleSpinner(false); return; } // TODO: remove this once we're sure fetchers can handle this case if (!NetworkTools.isConnected(getApplicationContext())) { NetworkTools.showNetworkError(getApplicationContext()); toggleSpinner(false); return; } if(whichArrivalsFetcher >= ArrivalFetchers.length) { // TODO: error message (tryed every fetcher and failed) asyncWgetBusStopFromBusStopIDReset(); toggleSpinner(false); return; } // cancel whatever is still running if(AsyncArrivalsFetcherRunningInstance != null) { // cancel() should hopefully only kill the background thread, not the one we're using for this same recursion... AsyncArrivalsFetcherRunningInstance.cancel(true); } AsyncArrivalsFetcherRunningInstance = new AsyncArrivalsFetcherAll(ArrivalFetchers[whichArrivalsFetcher], busStopID, new AsyncArrivalsFetcherAllCallbackImplementation()); AsyncArrivalsFetcherRunningInstance.execute(); } private void asyncWgetBusStopFromBusStopIDReset() { this.ArrivalFetchersPos = 0; if(AsyncArrivalsFetcherRunningInstance != null) { AsyncArrivalsFetcherRunningInstance.cancel(true); } } private class AsyncArrivalsFetcherAllCallbackImplementation implements AsyncArrivalsFetcherAll.AsyncArrivalsFetcherAllCallback { public void call(Palina p, Fetcher.result res, String stopID) { switch (res) { case CLIENT_OFFLINE: if (!NetworkTools.isConnected(getApplicationContext())) { NetworkTools.showNetworkError(getApplicationContext()); } break; // goto recursion case SERVER_ERROR: // TODO: better error message for this case case PARSER_ERROR: Toast.makeText(getApplicationContext(), R.string.parsing_error, Toast.LENGTH_SHORT).show(); break; // goto recursion case EMPTY_RESULT_SET: Toast.makeText(getApplicationContext(), R.string.no_passages, Toast.LENGTH_SHORT).show(); break; // goto recursion case OK: lastSuccessfullySearchedBusStopID = stopID; hideKeyboard(); //MyDB.DBBusStop.addBusStop(db, busStop); // TODO: determine why this was needed populateBusLinesLayout(p, stopID); toggleSpinner(false); // recursion terminated, remove spinner return; // RETURN. } // TODO: what do we do if a fetcher says no such stop/route exists? try next fetcher or give up? // indirect recursion through a callback. ...yeha. asyncWgetBusStopFromBusStopID(stopID, ArrivalFetchersPos+1); } } private void populateBusLinesLayout(Palina p, String stopID) { /* TODO: determine if there was a reason to store everything in the database, other than * showing the last timetable when "resuming" the app (which wasn't currently done, I think * it just fetches new timetables every time) */ //BusStop dbBusStop = MyDB.DBBusStop.getBusStop(db, busStop.getBusStopID()); // TODO: implement favorites username /*if(dbBusStop != null && dbBusStop.getBusStopUsername() != null) { busStopNameDisplay = dbBusStop.getBusStopUsername(); } else if (busStop.getBusStopName() != null) { busStopNameDisplay = busStop.getBusStopName(); } else { busStopNameDisplay = String.valueOf(busStopID); }*/ busStopNameTextView.setText(String.format( getString(R.string.passages), p.getStopName().length() == 0 ? stopID : stopID.concat(" - ").concat(p.getStopName()))); // keyboard is already hidden, at this point // Shows hints if(getOption(OPTION_SHOW_LEGEND, true)) { showHints(); } else { hideHints(); } prepareGUIForBusLines(); resultsListView.setAdapter(new PalinaAdapter(this, p)); // TODO: do something useful on click (e.g. refresh timetables and show only that route) /*resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { *//* * Casting because of Javamerda * @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener *//* BusLine busLine = (BusLine) parent.getItemAtPosition(position); Log.i("ActivityMain", "Tapped busLine " + busLine.toString()); } });*/ } ///////////////////////////////// OTHER STUFF ////////////////////////////////////////////////// // TODO: try to move these 3 methods to a separate class public void addInFavorites(View v) { if (lastSuccessfullySearchedBusStopID != null) { BusStop busStop = new BusStop(lastSuccessfullySearchedBusStopID); busStop.setIsFavorite(true); MyDB.DBBusStop.addBusStop(db, busStop); BusStop dbBusStop = MyDB.DBBusStop.getBusStop(db, busStop.getBusStopID()); if (dbBusStop == null || dbBusStop.getBusStopLocality() == null) { // This will also scrape the busStopLocality try { new AsyncWgetBusStopSuggestions(busStop.getBusStopID()) { @Override public void onReceivedBusStopNames(BusStop[] busStops, int status) { if (status == AsyncWgetBusStopSuggestions.ERROR_NONE) { for (BusStop busStop : busStops) { MyDB.DBBusStop.addBusStop(db, busStop); } } } }; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } Toast.makeText(getApplicationContext(), R.string.added_in_favorites, Toast.LENGTH_SHORT).show(); } } private void setOption(String optionName, boolean value) { SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putBoolean(optionName, value); editor.commit(); } private boolean getOption(String optionName, boolean optDefault) { SharedPreferences preferences = getPreferences(MODE_PRIVATE); return preferences.getBoolean(optionName, optDefault); } ////////////////////////////////////// GUI HELPERS ///////////////////////////////////////////// private void showKeyboard() { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); View view = searchMode == SEARCH_BY_ID ? busStopSearchByIDEditText : busStopSearchByNameEditText; imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); } private void hideKeyboard() { View view = getCurrentFocus(); if (view != null) { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } private void setSearchModeBusStopID() { searchMode = SEARCH_BY_ID; busStopSearchByNameEditText.setVisibility(View.GONE); busStopSearchByNameEditText.setText(""); busStopSearchByIDEditText.setVisibility(View.VISIBLE); floatingActionButton.setImageResource(R.drawable.alphabetical); } private void setSearchModeBusStopName() { searchMode = SEARCH_BY_NAME; busStopSearchByIDEditText.setVisibility(View.GONE); busStopSearchByIDEditText.setText(""); busStopSearchByNameEditText.setVisibility(View.VISIBLE); floatingActionButton.setImageResource(R.drawable.numeric); } /** * Having that cursor at the left of the edit text makes me cancer. * @param busStopID bus stop ID */ private void setBusStopSearchByIDEditText(String busStopID) { busStopSearchByIDEditText.setText(busStopID); busStopSearchByIDEditText.setSelection(busStopID.length()); } private void showHints() { howDoesItWorkTextView.setVisibility(View.VISIBLE); hideHintButton.setVisibility(View.VISIBLE); actionHelpMenuItem.setVisible(false); } private void hideHints() { howDoesItWorkTextView.setVisibility(View.GONE); hideHintButton.setVisibility(View.GONE); actionHelpMenuItem.setVisible(true); } private void toggleSpinner(boolean enable) { if (enable) { + //already set by the RefreshListener when needed //swipeRefreshLayout.setRefreshing(true); progressBar.setVisibility(View.VISIBLE); } else { - //swipeRefreshLayout.setRefreshing(false); + swipeRefreshLayout.setRefreshing(false); progressBar.setVisibility(View.GONE); } } private void prepareGUIForBusLines() { busStopNameTextView.setVisibility(View.VISIBLE); busStopNameTextView.setClickable(true); swipeRefreshLayout.setEnabled(true); swipeRefreshLayout.setVisibility(View.VISIBLE); resultsListView.setVisibility(View.VISIBLE); actionHelpMenuItem.setVisible(true); } private void prepareGUIForBusStops() { busStopNameTextView.setText(getString(R.string.results)); busStopNameTextView.setClickable(false); busStopNameTextView.setVisibility(View.VISIBLE); swipeRefreshLayout.setEnabled(false); swipeRefreshLayout.setVisibility(View.VISIBLE); resultsListView.setVisibility(View.VISIBLE); actionHelpMenuItem.setVisible(false); } /** * Open an URL in the default browser. * * @param url URL */ public void openIceweasel(String url) { Intent browserIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent1); } ///////////////////// INTENT HELPER //////////////////////////////////////////////////////////// /** * Try to extract the bus stop ID from a URi * * @param uri The URL * @return bus stop ID or null */ public static String getBusStopIDFromUri(Uri uri) { String busStopID; switch (uri.getHost()) { case "m.gtt.to.it": // http://m.gtt.to.it/m/it/arrivi.jsp?n=1254 busStopID = uri.getQueryParameter("n"); if (busStopID == null) { Log.e("ActivityMain", "Expected ?n from: " + uri); } break; case "www.gtt.to.it": case "gtt.to.it": // http://www.gtt.to.it/cms/percorari/arrivi?palina=1254 busStopID = uri.getQueryParameter("palina"); if (busStopID == null) { Log.e("ActivityMain", "Expected ?palina from: " + uri); } break; default: Log.e("ActivityMain", "Unexpected intent URL: " + uri); busStopID = null; } return busStopID; } } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java b/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java index 6c37aaa..5045412 100644 --- a/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java +++ b/src/it/reyboz/bustorino/backend/FiveTScraperFetcher.java @@ -1,195 +1,231 @@ /* BusTO - Arrival times for Turin public transports. Copyright (C) 2014 Valerio Bozzolan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; //import android.util.Log; /** * Contains large chunks of code taken from the old GTTSiteSucker, AsyncWget and AsyncWgetBusStopFromBusStopID classes.
*
* «BusTO, because sucking happens»
*
* @author Valerio Bozzolan */ public class FiveTScraperFetcher extends FiveTNormalizer implements ArrivalsFetcher { /** * Execute regexes. * * @param needle Regex * @param haystack Entire string * @return Matched string */ public static String grep(String needle, String haystack) { String matched = null; Matcher matcher = Pattern.compile( needle).matcher(haystack); if (matcher.find()) { matched = matcher.group(1); } return matched; } /** * Javammerda! Lasciami null senza suicidarti! */ public static Integer string2Integer(String str) { try { return Integer.parseInt(str); } catch(NumberFormatException e) { return null; } } private String getDOM(final String routeID, final AtomicReference res) { //Log.d("asyncwget", "Catching URL in background: " + uri[0]); HttpURLConnection urlConnection; StringBuilder result = null; try { URL url = new URL("http://www.5t.torino.it/5t/trasporto/arrival-times-byline.jsp?action=getTransitsByLine&shortName=" + routeID); urlConnection = (HttpURLConnection) url.openConnection(); } catch(IOException e) { res.set(Fetcher.result.CLIENT_OFFLINE); return null; } try { InputStream in = new BufferedInputStream( urlConnection.getInputStream()); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } } catch (Exception e) { //Log.e("asyncwget", e.getMessage()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (result == null) { res.set(Fetcher.result.PARSER_ERROR); return null; } res.set(Fetcher.result.SERVER_ERROR); // will be set to "OK" later, this is a safety net in case StringBuilder returns null, the website returns an HTTP 204 or something like that. return result.toString(); } @Override public Palina ReadArrivalTimesAll(final String routeID, final AtomicReference res) { Palina p = new Palina(); int routeIndex; String responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas = getDOM(routeID, res); if(responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas == null) { return p; } Document doc = Jsoup.parse(responseInDOMFormatBecause5THaveAbsolutelyNoIdeaWhatJSONWas); Element span = doc.select("span").first(); String busStopID = grep("^(.+) ", span.html()); if (busStopID == null) { //Log.e("BusStop", "Empty busStopID from " + span.html()); res.set(result.EMPTY_RESULT_SET); return p; } // this also appears when no stops are found, but that case has already been handled above Element error = doc.select("p.errore").first(); if (error != null) { res.set(result.SERVER_ERROR); return p; } String busStopName = grep("^.+ (.+)", span.html()); // The first "dot" is the single strange space character in the middle of "39{HERE→} {←HERE}PORTA NUOVA" if (busStopName == null) { //Log.e("BusStop", "Empty busStopName from " + span.html()); res.set(result.SERVER_ERROR); return p; } p.setStopName(busStopName.trim()); // Every table row is a busLine Elements trs = doc.select("table tr"); for (Element tr : trs) { Element line = tr.select("td.line a").first(); if (!line.hasText()) { res.set(result.SERVER_ERROR); return p; } String busLineName = line.text(); // this is yet another ID, that has no known use so we can safely ignore it // Integer busLineID = string2Integer( // grep( // "([0-9]+)$", // line.attr("href") // ) // ); if (busLineName == null) { res.set(result.SERVER_ERROR); return p; } if(busLineName.equals("METRO")) { routeIndex = p.addRoute(busLineName, "", Route.Type.METRO); } else { routeIndex = p.addRoute(busLineName, "", Route.Type.BUS); } // Every busLine have passages Elements tds = tr.select("td:not(.line)"); for (Element td : tds) { //boolean isInRealTime = td.select("i").size() > 0; //td.select("i").remove(); // Stripping "*" String time = td.text().trim(); if (time.equals("")) { // Yes... Sometimes there is an EMPTY td ._. continue; } p.addPassaggio(time, routeIndex); } } res.set(result.OK); return p; } + + // preserved for future generations: +// /* +// * I've sent many emails to the public email info@5t.torino.it to write down something like: +// * «YOUR SITE EXPLODE IF I USE **YOUR** BUS LINE IDs STARTING WITH ZERO!!!!!» +// * So, waiting for a response, I must purge the busStopID from "0"s .__. +// * IN YOUR FACE 5T/GTT. IN YOUR FACE. +// * +// * @param busStopID +// * @return parseInt(busStopID) +// * @antifeatured yep +// * @notabug yep +// * @wontfix yep +// */ +// protected final String getFilteredBusStopID(String busStopID) { +// /* +// * OK leds me ezplain why 'm dong this shot of shittt. OK zo swhy? +// * Bhumm thads because the GTT/5T site-"developer" ids obviusli drunk. +// */ +// String enableGTTDeveloperSimulator = "on"; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// final char ZZZZZZZEEEEROOOOOO = '0'; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// char[] cinquettiBarraGtt = busStopID.toCharArray(); // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// int merda = 0; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// while (merda < cinquettiBarraGtt.length && cinquettiBarraGtt[merda] == ZZZZZZZEEEEROOOOOO) { +// // COMPLETELELELLELEEELY DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// Log.i("AsyncWgetBusStop", "scimmie ubriache assunte per tirar su il sito 5T/GTT"); // DR +// merda++; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// } // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// String trenoDiMerda = ""; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// for (; merda < cinquettiBarraGtt.length; merda++) { // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// trenoDiMerda += cinquettiBarraGtt[merda]; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// } // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// enableGTTDeveloperSimulator = "off"; // DRUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUNK +// +// return trenoDiMerda; +// } } diff --git a/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java b/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java index 4dba025..306131b 100644 --- a/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java +++ b/src/it/reyboz/bustorino/backend/GTTJSONFetcher.java @@ -1,178 +1,173 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Scanner; import java.util.concurrent.atomic.AtomicReference; public class GTTJSONFetcher implements ArrivalsFetcher { -// @Override -// public Palina ReadArrivalTimesRoute(String stopID, String routeID, AtomicReference res) { -// return this.ReadArrivalTimesAll(routeID, res); // TODO: implement this when it's needed (never?) -// } - @Override @NonNull public Palina ReadArrivalTimesAll(String routeID, AtomicReference res) { URL url; Palina p = new Palina(); String routename; String bacino; JSONArray json; int howManyRoutes, howManyPassaggi, i, j, pos; // il misto inglese-italiano è un po' ridicolo ma tanto vale... JSONObject thisroute; JSONArray passaggi; try { url = new URL("http://www.gtt.to.it/cms/index.php?option=com_gtt&task=palina.getTransiti&palina=" + routeID + "&realtime=true"); } catch (MalformedURLException e) { res.set(result.PARSER_ERROR); return p; } json = queryURL(url, res); if(json == null) { return p; } howManyRoutes = json.length(); if(howManyRoutes == 0) { res.set(result.EMPTY_RESULT_SET); return p; } try { for(i = 0; i < howManyRoutes; i++) { thisroute = json.getJSONObject(i); routename = thisroute.getString("Linea"); try { bacino = thisroute.getString("Bacino"); } catch (JSONException ignored) { // if "Bacino" gets removed... bacino = "U"; } pos = p.addRoute(routename, thisroute.getString("Direzione"), decodeType(routename, bacino)); /* * Okay, this is just absurd. * The underground always has 4 non-real-time timetable entries; however, the first * two are old\stale\bogus, as they're in the past. The other two are exactly the * same ones that appear on the screens in the stations. */ if(routename.equals("METRO")) { j = 2; } else { j = 0; } passaggi = thisroute.getJSONArray("PassaggiRT"); howManyPassaggi = passaggi.length(); for(; j < howManyPassaggi; j++) { p.addPassaggio(passaggi.getString(j).concat("*"), pos); } passaggi = thisroute.getJSONArray("Passaggi"); // now the non-real-time ones howManyPassaggi = passaggi.length(); for(; j < howManyPassaggi; j++) { p.addPassaggio(passaggi.getString(j), pos); } } } catch (JSONException e) { res.set(result.PARSER_ERROR); return p; } res.set(result.OK); return p; } @Nullable private JSONArray queryURL(URL url, AtomicReference res) { HttpURLConnection urlConnection; InputStream in = null; JSONArray json; try { urlConnection = (HttpURLConnection) url.openConnection(); } catch(IOException e) { res.set(result.SERVER_ERROR); // TODO: can we assume this is CLIENT_OFFLINE? return null; } try { in = urlConnection.getInputStream(); json = new JSONArray(streamToString(in)); } catch (Exception e) { res.set(result.PARSER_ERROR); return null; } finally { try { if (in != null) {in.close();} // this is getting ureadable quite fast. } catch(Exception ignored) {} urlConnection.disconnect(); } try { // returns [{"PassaggiRT":[],"Passaggi":[]}] for non existing stops! json.getJSONObject(0).getString("Linea"); // if we can get this, then there's something useful in the array. } catch(JSONException e) { res.set(result.EMPTY_RESULT_SET); return null; } return json; } // https://stackoverflow.com/a/5445161 private static String streamToString(InputStream is) { Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } private static Route.Type decodeType(final String routename, final String bacino) { if(routename.equals("METRO")) { return Route.Type.METRO; } switch (bacino) { case "U": return Route.Type.BUS; case "F": return Route.Type.RAILWAY; case "E": return Route.Type.LONG_DISTANCE_BUS; default: return Route.Type.BUS; } } }