diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index 722ba68..b1068e1 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -1,82 +1,83 @@ Stai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy. Cerca QR Code Numero fermata Nome fermata Inserisci il numero della fermata Inserisci il nome della fermata Alcuni caratteri non sono stati riconosciuti Verifica l\'accesso ad Internet! Nessun arrivo previsto per questa fermata Sembra che nessuna fermata abbia questo nome Errore di lettura del sito 5T/GTT (dannato sito!) Fermata: %1$s Linee: %1$s Scegli la fermata… Nessun passaggio Nessun QR code Preferiti Aiuto Informazioni Più informazioni News Invia bug Codice sorgente Licenza Incontra l\'autore Fermata aggiunta ai preferiti Preferiti Tocca il nome di una fermata per aggiungerla in questa lista Rimuovi Rinomina Rinomina fermata Reset Informazioni Tocca il nome della fermata per aggiungerla ai preferiti\n\nCome leggere gli orari:\n   12:56* Orario in tempo reale\n   12:56   Orario programmato\n\nTrascina giù per aggiornare l\'orario. OK ! Benvenuto!

Grazie per aver scelto BusTO, un\'app \"politicamente\" indipendente da GTT/5T, per spostarsi a Torino attraverso software libero:

Perchè usare BusTO?

- Non sei monitorato
- Non ci sono pubblicità
- La tua privacy è al sicuro
- Inoltre l\'app è molto leggera!

Come Funziona?

Quest\'app ottiene i passaggi dei bus in tempo reale filtrando i dati forniti pubblicamente sul sito www.5t.torino.it «per uso personale».

Ingredienti:
- Valerio Bozzolan sviluppatore principale.
- Marco Gagino intenso collaboratore, creatore dell\'icona, responsabile della grafica.
- Paolo Alloatti per l\'idea dell\'icona.
- JSoup libreria per "web scaping".
- makovkastar bottone fluttuante.
- Google icone Material Design.
- Tutti i contributori!

Licenze

L\'app e il relativo codice sorgente sono distribuiti sotto la licenza GNU General Public License v3+. Ciò significa che puoi usare, studiare, migliorare e ricondividere quest\'app con qualunque mezzo e per qualsiasi scopo: a patto di mantenere sempre questi diritti a tua volta e di dare credito a Valerio Bozzolan.

Note

Quest\'applicazione è rilasciata nella speranza che sia utile a tutti ma senza NESSUNA garanzia.

Buon utilizzo! :)

]]>
Nome troppo corto, digita più caratteri e riprova %1$s verso %2$s %s (destinazione sconosciuta) + Errore interno inaspettato che non dovrebbe mai accadere!
diff --git a/res/values/strings.xml b/res/values/strings.xml index d7f8809..bf1d6da 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,81 +1,82 @@ BusTO Stai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy. Search Scan QR Code Bus stop number Bus stop name Insert bus stop number Insert bus stop name %1$s towards %2$s %s (unknown destination) Sorry but you are using not allowed characters Verify the state of your Internet connection! No bus is supposed to arrive at this stop Seems that no bus stop have this name Error parsing the 5T/GTT website (damn site!) Name too short, type more characters and retry Arrivals at: %1$s Choose the bus stop… Lines: %1$s No passages No QR code + Unexpected internal error that should never happen! Favorites Help About More about News releases Bug submission Source code Licence Meet the author Bus stop is now in your favorites Favorites Press on a bus stop name to populate this list Delete Rename Rename the bus stop Reset About Tap the bus stop name to add it to the favourites\n\nHow to read timelines:\n   12:56* Real time arrival\n   12:56   Scheduled time of arrival\n\nPull down to refresh the timetable GOT IT! Welcome!

Thanks for using BusTO, a "politically" independent app useful to move around Torino using a Free/Libre software.

Why using this app?

- You\'ll never be tracked
- You\'ll never see boring ads
- We\'ll always respect your privacy
- Moreover, it\'s lightweight!

How does it work?

This app will show you the timetable of the buses using the information published on the site www.5t.torino.it.

Who worked on BusTO:
- Valerio Bozzolan main developer.
- Marco Gagino main contributor and icon creator.
- Paolo Alloatti original concept of the icon.
- JSoup web scraper library.
- makovkastar floating buttons.
- Google Material Design icons.
- All the contributors!

Licenses

The app and the related source code are released by Valerio Bozzolan under the terms of the GNU General Public License v3+). So everyone is allowed to use, to study, to improve and to share this app by any kind of means and for any purpose: under the conditions of maintaining this rights and of attributing the original work to Valerio Bozzolan.

Notes

This app has been developed hoping to be useful to everyone but without ANY warranty.

This translation is kindly provided by Riccardo Caniato and Marco Gagino.

Get involved! :)

]]>
diff --git a/src/it/reyboz/bustorino/ActivityMain.java b/src/it/reyboz/bustorino/ActivityMain.java index 0117d09..c9cdd10 100644 --- a/src/it/reyboz/bustorino/ActivityMain.java +++ b/src/it/reyboz/bustorino/ActivityMain.java @@ -1,874 +1,861 @@ /* 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.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; -import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; 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 java.util.List; +import java.util.concurrent.atomic.AtomicReference; import it.reyboz.bustorino.backend.ArrivalsFetcher; import it.reyboz.bustorino.backend.Fetcher; import it.reyboz.bustorino.backend.FiveTNormalizer; import it.reyboz.bustorino.backend.FiveTScraperFetcher; import it.reyboz.bustorino.backend.FiveTStopsFetcher; import it.reyboz.bustorino.backend.GTTJSONFetcher; import it.reyboz.bustorino.backend.GTTStopsFetcher; import it.reyboz.bustorino.backend.Palina; import it.reyboz.bustorino.backend.Route; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.backend.StopsFinderByName; -import it.reyboz.bustorino.lab.GTTSiteSucker.BusStop; import it.reyboz.bustorino.lab.MyDB; -import it.reyboz.bustorino.lab.asyncwget.AsyncWgetBusStopSuggestions; -import it.reyboz.bustorino.middleware.AsyncArrivalsFetcherAll; -import it.reyboz.bustorino.middleware.AsyncStopsFinderByName; +import it.reyboz.bustorino.middleware.AsyncWget; import it.reyboz.bustorino.middleware.PalinaAdapter; +import it.reyboz.bustorino.middleware.RecursionHelper; import it.reyboz.bustorino.middleware.StopAdapter; import it.reyboz.bustorino.middleware.StopsDB; public class ActivityMain extends AppCompatActivity { - private class RecursionHelper { - private int pos = 0; - public AsyncTask RunningInstance = null; // the only one that hasn't been cancelled - - public void reset() { - this.pos = 0; - if(RunningInstance != null) { - RunningInstance.cancel(true); - } - } - - public void increment() { - pos++; - } - - public int getPos() { - return pos; - } - } - /* * 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"; private StopsDB stopsDB; /** * Last successfully searched bus stop ID */ - private String lastSuccessfullySearchedBusStopID = null; - private String lastSuccessfullySearchedBusStopDisplayName = null; // TODO: set to null when renaming a stop + private @Nullable Stop lastSuccessfullySearchedBusStop = null; /* // 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()};*/ - /* - * I tried to wrap everything in a class and it didn't work right no matter what. - * Or it kinda worked, but accessing things became very ugly, especially if you wanted to - * hide the internal structure of the class. - * At least I've managed to shoehorn two variables and a method in there, the array will stay - * outside. - * - * I don't know if I should be surprised that handling recursion the C way looks a lot cleaner - * than wrapping and extending and implementing everything the Java way. - */ - private ArrivalsFetcher[] ArrivalFetchers = {new GTTJSONFetcher(), new FiveTScraperFetcher()}; - private RecursionHelper ArrivalFetchersRecursionHelper = new RecursionHelper(); - - private StopsFinderByName[] StopsFindersByName = {new GTTStopsFetcher(), new FiveTStopsFetcher()}; - private RecursionHelper StopsFindersByNameRecursionHelper = new RecursionHelper(); + private RecursionHelper ArrivalFetchersRecursionHelper = new RecursionHelper<>(new ArrivalsFetcher[] {new GTTJSONFetcher(), new FiveTScraperFetcher()}); + private RecursionHelper StopsFindersByNameRecursionHelper = new RecursionHelper<>(new StopsFinderByName[] {new GTTStopsFetcher(), new FiveTStopsFetcher()}); private SQLiteDatabase db; ///////////////////////////////// EVENT HANDLERS /////////////////////////////////////////////// /* * @see swipeRefreshLayout */ private Handler handler = new Handler(); private final Runnable refreshing = new Runnable() { public void run() { - asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStopID, true); + if (lastSuccessfullySearchedBusStop == null) { + Toast.makeText(getApplicationContext(), + R.string.query_too_short, Toast.LENGTH_SHORT).show(); + } else { + new asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStop.ID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); + } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.stopsDB = new StopsDB(getApplicationContext()); 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 // TODO: did I accidentally remove the warning? ArrivalFetchersRecursionHelper.reset(); } } else { // If you are here an intent has worked successfully setBusStopSearchByIDEditText(busStopID); - asyncWgetBusStopFromBusStopID(busStopID, true); + new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); } 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, true); + Log.d("ActivityMain", "onPostResume fired. Last successfully bus stop ID: " + lastSuccessfullySearchedBusStop); + if (searchMode == SEARCH_BY_ID && lastSuccessfullySearchedBusStop != null) { + setBusStopSearchByIDEditText(lastSuccessfullySearchedBusStop.ID); + new asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStop.ID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); } } @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) { if (searchMode == SEARCH_BY_ID) { String busStopID = busStopSearchByIDEditText.getText().toString(); - asyncWgetBusStopFromBusStopID(busStopID, true); + new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); } else { // searchMode == SEARCH_BY_NAME String query = busStopSearchByNameEditText.getText().toString(); - asyncWgetBusStopSuggestions(query, true); + new asyncWgetBusStopSuggestions(query, stopsDB, StopsFindersByNameRecursionHelper); } } /** * 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, true); + new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); } 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 ///////////////////////////////////////// - /** - * See the other asyncWget method for documentation\comments. - */ - private void asyncWgetBusStopSuggestions(String query, boolean reset) { - toggleSpinner(true); + private class asyncWgetBusStopSuggestions extends AsyncWget { + private final String query; + private AtomicReference res; + private List s; + private StopsDB db; - if(reset) { - StopsFindersByNameRecursionHelper.reset(); - } + public asyncWgetBusStopSuggestions(@Nullable String query, @NonNull StopsDB sdb, @NonNull RecursionHelper r) { + super(getApplicationContext(), r); - if(query == null || query.length() == 0) { - Toast.makeText(getApplicationContext(), - R.string.insert_bus_stop_name_error, Toast.LENGTH_SHORT).show(); - toggleSpinner(false); - return; - } + toggleSpinner(true); + this.query = query; + this.res = new AtomicReference<>(); + this.db = sdb; - if(StopsFindersByNameRecursionHelper.getPos() >= StopsFindersByName.length) { - // TODO: error message (tryed every fetcher and failed) - StopsFindersByNameRecursionHelper.reset(); - toggleSpinner(false); - return; - } + r.reset(); - if(StopsFindersByNameRecursionHelper.RunningInstance != null) { - StopsFindersByNameRecursionHelper.RunningInstance.cancel(true); + if(query == null || query.length() <= 0) { + Toast.makeText(this.c, + R.string.insert_bus_stop_name_error, Toast.LENGTH_SHORT).show(); + toggleSpinner(false); + } else { + this.execute(); + } } - StopsFindersByNameRecursionHelper.RunningInstance = new AsyncStopsFinderByName(StopsFindersByName[StopsFindersByNameRecursionHelper.getPos()], query, new AsyncStopsFinderByNameCallbackImplementation(), stopsDB).execute(); - } - - private class AsyncStopsFinderByNameCallbackImplementation implements AsyncStopsFinderByName.AsyncStopsFinderByNameCallback { - public void call(List stops, Fetcher.result res, String query) { - toggleSpinner(false); + @Override + protected boolean tryFetcher(StopsFinderByName f) { + // gets opened multiple times, whatever. + this.db.openIfNeeded(); + this.s = f.FindByName(this.query, this.db, this.res); + this.db.closeIfNeeded(); - switch (res) { + switch (this.res.get()) { case CLIENT_OFFLINE: - Toast.makeText(getApplicationContext(), - R.string.network_error, Toast.LENGTH_SHORT).show(); - break; // goto recursion + publishProgress(R.string.network_error); + return false; case SERVER_ERROR: - if(isConnected()) { - // TODO: better error message for this case - Toast.makeText(getApplicationContext(), - R.string.parsing_error, Toast.LENGTH_SHORT).show(); + if (isConnected()) { + publishProgress(R.string.parsing_error); } else { - Toast.makeText(getApplicationContext(), - R.string.network_error, Toast.LENGTH_SHORT).show(); + publishProgress(R.string.network_error); } - break; + return false; case PARSER_ERROR: - Toast.makeText(getApplicationContext(), - R.string.parsing_error, Toast.LENGTH_SHORT).show(); - break; // goto recursion + default: + publishProgress(R.string.internal_error); + return false; case QUERY_TOO_SHORT: - Toast.makeText(getApplicationContext(), - R.string.query_too_short, Toast.LENGTH_SHORT).show(); - break; + publishProgress(R.string.query_too_short); + return false; case EMPTY_RESULT_SET: - Toast.makeText(getApplicationContext(), - R.string.no_bus_stop_have_this_name, Toast.LENGTH_SHORT).show(); - break; // goto recursion + publishProgress(R.string.no_bus_stop_have_this_name); + return false; case OK: - populateBusStopsLayout(stops); - toggleSpinner(false); // recursion terminated, remove spinner - - return; // RETURN. + return true; } - StopsFindersByNameRecursionHelper.increment(); - asyncWgetBusStopSuggestions(query, false); } - } + @Override + protected void onPostExecute(Void useless) { + // something really bad happened + if(this.isCancelled() || !this.terminated || this.s == null) { + toggleSpinner(false); + this.onCancelled(); + return; + } - private void populateBusStopsLayout(List busStops) { - hideKeyboard(); + // no results + if(this.failedAll) { + toggleSpinner(false); + // TODO: an error message would be a good idea, here + return; + } - busStopNameTextView.setVisibility(View.GONE); + hideKeyboard(); - prepareGUIForBusStops(); + busStopNameTextView.setVisibility(View.GONE); - resultsListView.setAdapter(new StopAdapter(this, busStops)); - resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + prepareGUIForBusStops(); - @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 - */ - Stop busStop = (Stop) parent.getItemAtPosition(position); + resultsListView.setAdapter(new StopAdapter(this.c, this.s)); + resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - Intent intent = new Intent(ActivityMain.this, ActivityMain.class); + @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 + */ + Stop busStop = (Stop) parent.getItemAtPosition(position); + + Intent intent = new Intent(ActivityMain.this, ActivityMain.class); + + Bundle b = new Bundle(); + b.putString("bus-stop-ID", busStop.ID); + intent.putExtras(b); + startActivity(intent); + } + }); - Bundle b = new Bundle(); - b.putString("bus-stop-ID", busStop.ID); - intent.putExtras(b); - startActivity(intent); - } - }); + toggleSpinner(false); + } + + @Override + protected void onCancelled() { + toggleSpinner(false); + } } ///////////////////////////////// ARRIVALS FETCHER ///////////////////////////////////////////// - /** - * Try every fetcher until you get something usable. - * - * @param busStopID the ID - * @param reset set to true if you want to live (set to false during recursion) - */ - private void asyncWgetBusStopFromBusStopID(String busStopID, boolean reset) { - toggleSpinner(true); - - if(reset) { - ArrivalFetchersRecursionHelper.reset(); - } + private class asyncWgetBusStopFromBusStopID extends AsyncWget { + private final String stopID; + private AtomicReference res; + private Palina p; + /** + * Begins its life as a copy of lastSuccessfullySearchedBusStop, ends as null if it needs + * replacing or stays the same if it stayed the same + */ + private Stop lastSearchedBusStop; - if(busStopID == null || busStopID.length() == 0) { // TODO: this should be run only on first recursive call - Toast.makeText(getApplicationContext(), - R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show(); - toggleSpinner(false); - return; - } + asyncWgetBusStopFromBusStopID(@Nullable String stopID, @NonNull RecursionHelper r, @Nullable Stop lastSearchedBusStop) { + super(getApplicationContext(), r); - if(ArrivalFetchersRecursionHelper.getPos() >= ArrivalFetchers.length) { - // TODO: error message (tryed every fetcher and failed) - ArrivalFetchersRecursionHelper.reset(); - toggleSpinner(false); - return; - } + toggleSpinner(true); + this.stopID = stopID; + this.lastSearchedBusStop = lastSearchedBusStop; + this.res = new AtomicReference<>(); + + if(stopID == null || stopID.length() <= 0) { + // we're still in UI thread, no need to mess with Progress + Toast.makeText(this.c, + R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show(); + toggleSpinner(false); + } else { + this.execute(); + } - // cancel whatever is still running - if(ArrivalFetchersRecursionHelper.RunningInstance != null) { - // cancel() should hopefully only kill the background thread, not the one we're using for this same recursion... - ArrivalFetchersRecursionHelper.RunningInstance.cancel(true); } - // create new task, run it, store the running instance. Don't try to reorder these calls even though it's unreadable, trust me. - ArrivalFetchersRecursionHelper.RunningInstance = new AsyncArrivalsFetcherAll(ArrivalFetchers[ArrivalFetchersRecursionHelper.getPos()], busStopID, new AsyncArrivalsFetcherAllCallbackImplementation()).execute(); - } + @Override + protected boolean tryFetcher(ArrivalsFetcher f) { + this.p = f.ReadArrivalTimesAll(this.stopID, this.res); - private class AsyncArrivalsFetcherAllCallbackImplementation implements AsyncArrivalsFetcherAll.AsyncArrivalsFetcherAllCallback { - public void call(Palina p, Fetcher.result res, String stopID) { - switch (res) { + switch(this.res.get()) { case CLIENT_OFFLINE: - Toast.makeText(getApplicationContext(), - R.string.network_error, Toast.LENGTH_SHORT).show(); - break; // goto recursion + publishProgress(R.string.network_error); + return false; case SERVER_ERROR: if(isConnected()) { - Toast.makeText(getApplicationContext(), - R.string.parsing_error, Toast.LENGTH_SHORT).show(); - } else { // TODO: better error message for this case - Toast.makeText(getApplicationContext(), - R.string.network_error, Toast.LENGTH_SHORT).show(); + publishProgress(R.string.parsing_error); + } else { + publishProgress(R.string.network_error); } - break; + return false; case QUERY_TOO_SHORT: // should never happen here, but to err on the side of caution... - Toast.makeText(getApplicationContext(), - R.string.query_too_short, Toast.LENGTH_SHORT).show(); - break; + publishProgress(R.string.query_too_short); + return false; case PARSER_ERROR: - Toast.makeText(getApplicationContext(), - R.string.parsing_error, Toast.LENGTH_SHORT).show(); - break; // goto recursion + default: // there are no other cases but Android Studio is still complaining... + publishProgress(R.string.internal_error); + return false; case EMPTY_RESULT_SET: - Toast.makeText(getApplicationContext(), - R.string.no_passages, Toast.LENGTH_SHORT).show(); - break; // goto recursion + publishProgress(R.string.no_passages); + return false; case OK: - new populateBusLinesLayout(p, stopID).execute(); - return; // RETURN. populateBusLinesLayout will do the rest. - } - // indirect recursion through a callback. ...yeha. - ArrivalFetchersRecursionHelper.increment(); - asyncWgetBusStopFromBusStopID(stopID, false); - } - } - - private class populateBusLinesLayout extends AsyncTask { - private final Palina p; - private final String stopID; - private String stopName; - private final Context c; - - populateBusLinesLayout(@NonNull Palina p, @NonNull String stopID) { - this.p = p; - this.stopID = stopID; - this.c = getApplicationContext(); - if(stopID.equals(lastSuccessfullySearchedBusStopID)) { - this.stopName = lastSuccessfullySearchedBusStopDisplayName; + // WARNING: lots of branches ahead. + + // did we search for anything? + if(this.lastSearchedBusStop != null) { + // different stop? + if(!this.lastSearchedBusStop.ID.equals(p.ID)) { + // remove it, get new name + this.lastSearchedBusStop = null; + getNameOrGetRekt(); + } else { + // searched and it's the same + String sn = lastSearchedBusStop.getStopName(); + if(sn == null) { + // something really bad happened, start from scratch + this.lastSearchedBusStop = null; + getNameOrGetRekt(); + } else { + // "merge" Stop over Palina and we're good to go + this.p.setStopName(sn); + } + } + } else { + // not searched yet + getNameOrGetRekt(); + } + return true; } } - @Override - protected String doInBackground(Void... useless) { - // extreme memoization techniques. - if(this.stopName != null) { - return this.stopName; - } - - // TODO: search favorites, get (user)name if set, set this.stopName, p.setStopName() and lastSuccessfullySearchedBusStopDisplayName, return + /** + * Run this in a background thread.
+ * Sets a stop name for this.p, guaranteed not to be null! + */ + private void getNameOrGetRekt() { + String nameMaybe; - String nameMaybe = p.getStopName(); + // TODO: search favorites, get (user)name if set, set what's needed, return + // does it already have a name (for fetchers that support it)? + nameMaybe = this.p.getStopName(); if(nameMaybe != null && nameMaybe.length() > 0) { - this.stopName = nameMaybe; - lastSuccessfullySearchedBusStopDisplayName = nameMaybe; - return this.stopName; + return; } - // Palina doesn't know anything, let's see what the database has to say... + // let's try StopsDB StopsDB db = new StopsDB(this.c); db.openIfNeeded(); - nameMaybe = db.getNameFromID(this.stopID); + nameMaybe = db.getNameFromID(this.p.ID); db.closeIfNeeded(); if(nameMaybe != null && nameMaybe.length() > 0) { - p.setStopName(nameMaybe); - this.stopName = nameMaybe; - lastSuccessfullySearchedBusStopDisplayName = nameMaybe; - return this.stopName; + this.p.setStopName(nameMaybe); + return; } - p.setStopName(""); - lastSuccessfullySearchedBusStopDisplayName = ""; - return ""; + // no name to be found anywhere, don't bother searching it next time + this.p.setStopName(""); } @Override - protected void onPostExecute(String displayName) { + protected void onPostExecute(Void useless) { + // something really bad happened + if(this.isCancelled() || !this.terminated || this.p == null) { + toggleSpinner(false); + this.onCancelled(); + return; + } + + // no results + if(this.failedAll) { + toggleSpinner(false); + // TODO: an error message would be a good idea, here + return; + } + hideKeyboard(); + + if(this.lastSearchedBusStop == null) { + // did we gather any new information about this Stop? Then update it (casting from Palina) + lastSuccessfullySearchedBusStop = this.p; + } + + String displayName = p.getStopName(); String displayStuff; - if(displayName != null && displayName.length() > 0) { - displayStuff = stopID.concat(" - ").concat(p.getStopName()); + if (displayName != null && displayName.length() > 0) { + displayStuff = p.ID.concat(" - ").concat(displayName); } else { - displayStuff = stopID; + displayStuff = p.ID; } busStopNameTextView.setText(String.format( getString(R.string.passages), displayStuff)); // Shows hints - if(getOption(OPTION_SHOW_LEGEND, true)) { + if (getOption(OPTION_SHOW_LEGEND, true)) { showHints(); - } else { - hideHints(); - } + } //else { + // hideHints(); + //} prepareGUIForBusLines(); resultsListView.setAdapter(new PalinaAdapter(this.c, p)); resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override public void onItemClick(AdapterView parent, View view, int position, long id) { String routeName; Route r = (Route) parent.getItemAtPosition(position); routeName = FiveTNormalizer.routeInternalToDisplay(r.name); - if(routeName == null) { + if (routeName == null) { routeName = r.name; } - if(r.destinazione == null || r.destinazione.length() == 0) { + if (r.destinazione == null || r.destinazione.length() == 0) { Toast.makeText(getApplicationContext(), getString(R.string.route_towards_unknown, routeName), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), getString(R.string.route_towards_destination, routeName, r.destinazione), Toast.LENGTH_SHORT).show(); } } }); - lastSuccessfullySearchedBusStopID = stopID; + toggleSpinner(false); + } + @Override + protected void onCancelled() { toggleSpinner(false); } } ///////////////////////////////// OTHER STUFF ////////////////////////////////////////////////// private boolean isConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } // 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(); - } - } + // TODO: fix this +// if (lastSuccessfullySearchedBusStop != null) { +// MyDB.DBBusStop.addBusStop(db, lastSuccessfullySearchedBusStop); +// +// 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); 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/FiveTNormalizer.java b/src/it/reyboz/bustorino/backend/FiveTNormalizer.java index efdade5..2dc6ec5 100644 --- a/src/it/reyboz/bustorino/backend/FiveTNormalizer.java +++ b/src/it/reyboz/bustorino/backend/FiveTNormalizer.java @@ -1,236 +1,239 @@ /* 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; /** * Converts some weird stop IDs found on the 5T website to the form used everywhere else (including GTT website). *

* A stop ID in normalized form is:
* - a string containing a number without leading zeros
* - a string beginning with "ST" and then a number
* - whatever the GTT website uses.
*

* A bus route ID in normalized form is:
* - a string containing a number and optionally: "B", "CS", "CD", "N", "S", "C" at the end
* - the string "METRO"
* - "ST1" or "ST2" (Star 1 and Star 2)
* - a string beginning with E, N, S or W, followed by two digits (with a leading zero)
* - "RV2", "OB1"
* - "CAN" or "FTC" (railway lines)
* - ...screw it, let's just hope all the websites and APIs return something sane as route IDs.
*

* This class exists because Java doesn't support traits.
*
* Note: this class also just became useless, as 5T now uses the same format as GTT website. */ public abstract class FiveTNormalizer { public static String FiveTNormalizeRoute(String RouteID) { while (RouteID.startsWith("0")) { RouteID = RouteID.substring(1); } return RouteID; } // public static String FiveTNormalizeStop(String StopID) { // StopID = FiveTNormalizeRoute(StopID); // // is this faster than a regex? // if (StopID.length() == 5 && StopID.startsWith("ST") && Character.isLetter(StopID.charAt(2)) && Character.isLetter(StopID.charAt(3)) && Character.isLetter(StopID.charAt(4))) { // switch (StopID) { // case "STFER": // return "8210"; // case "STPAR": // return "8211"; // case "STMAR": // return "8212"; // case "STMAS": // return "8213"; // case "STPOS": // return "8214"; // case "STMGR": // return "8215"; // case "STRIV": // return "8216"; // case "STRAC": // return "8217"; // case "STBER": // return "8218"; // case "STPDA": // return "8219"; // case "STDOD": // return "8220"; // case "STPSU": // return "8221"; // case "STVIN": // return "8222"; // case "STREU": // return "8223"; // case "STPNU": // return "8224"; // case "STMCI": // return "8225"; // case "STNIZ": // return "8226"; // case "STDAN": // return "8227"; // case "STCAR": // return "8228"; // case "STSPE": // return "8229"; // case "STLGO": // return "8230"; // } // } // return StopID; // } // // public static String NormalizedToFiveT(final String StopID) { // if(StopID.startsWith("82") && StopID.length() == 4) { // switch (StopID) { // case "8230": // return "STLGO"; // case "8229": // return "STSPE"; // case "8228": // return "STCAR"; // case "8227": // return "STDAN"; // case "8226": // return "STNIZ"; // case "8225": // return "STMCI"; // case "8224": // return "STPNU"; // case "8223": // return "STREU"; // case "8222": // return "STVIN"; // case "8221": // return "STPSU"; // case "8220": // return "STDOD"; // case "8219": // return "STPDA"; // case "8218": // return "STBER"; // case "8217": // return "STRAC"; // case "8216": // return "STRIV"; // case "8215": // return "STMGR"; // case "8214": // return "STPOS"; // case "8213": // return "STMAS"; // case "8212": // return "STMAR"; // case "8211": // return "STPAR"; // case "8210": // return "STFER"; // } // } // // return StopID; // } public static Route.Type decodeType(final String routename, final String bacino) { if(routename.equals("METRO")) { return Route.Type.METRO; } else if(routename.equals("79")) { return Route.Type.RAILWAY; } 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; } } /** * Converts a route ID from internal format to display format, returns null if it has the same name. * * @param routeID ID in "internal" and normalized format * @return string with display name, null if unchanged */ public static String routeInternalToDisplay(final String routeID) { if(routeID.length() == 3 && routeID.charAt(2) == 'B') { return routeID.substring(0,2).concat("/"); } switch(routeID) { case "1C": return "1 Chieri"; case "1N": return "1 Nichelino"; case "OB1": return "1 Orbassano"; case "2C": return "2 Chieri"; case "RV2": return "2 Rivalta"; case "CO1": return "Circolare Collegno"; + case "SE1": + // TODO: determine why GTT calls this "SE1" while other absurd names have a human readable name too. + return "1 Settimo"; case "79": return "Cremagliera Sassi-Superga"; case "W01": - return "Night Buster 1 arancio"; + return "Night Buster 1 Arancio"; case "N10": - return "Night Buster 10 gialla"; + return "Night Buster 10 Gialla"; case "W15": - return "Night Buster 15 rosa"; + return "Night Buster 15 Rosa"; case "S18": - return "Night Buster 18 blu"; + return "Night Buster 18 Blu"; case "S04": - return "Night Buster 4 azzurra"; + return "Night Buster 4 Azzurra"; case "N4": - return "Night Buster 4 rossa"; + return "Night Buster 4 Rossa"; case "N57": - return "Night Buster 57 oro"; + return "Night Buster 57 Oro"; case "W60": - return "Night Buster 60 argento"; + return "Night Buster 60 Argento"; case "E68": - return "Night Buster verde 68"; + return "Night Buster 68 Verde"; case "S05": - return "Night Buster viola 5"; + return "Night Buster 5 Viola"; case "ST1": return "Star 1"; case "ST2": return "Star 2"; case "10N": return "10 navetta"; case "35N": return "35 navetta"; case "36N": return "36 navetta"; case "46N": return "46 navetta"; default: return null; } } } diff --git a/src/it/reyboz/bustorino/backend/Palina.java b/src/it/reyboz/bustorino/backend/Palina.java index fbccc7a..813c279 100644 --- a/src/it/reyboz/bustorino/backend/Palina.java +++ b/src/it/reyboz/bustorino/backend/Palina.java @@ -1,226 +1,218 @@ /* 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 java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Timetable for multiple routes.
*
* Apparently "palina" and a bunch of other terms can't really be translated into English.
* Not in a way that makes sense and keeps the code readable, at least. */ public class Palina extends Stop { private ArrayList routes = new ArrayList<>(); public Palina(String stopID) { super(stopID); } - public final void setStopName(@NonNull String name) { - this.name = name; - } - - public final String getStopName() { - return this.name; - } - /** * Adds a route to the timetable. * * @param routeID name * @param type bus, underground, railway, ... * @param destinazione end of line\terminus (underground stations have the same ID for both directions) * @return array index for this route */ public int addRoute(String routeID, String destinazione, Route.Type type) { this.routes.add(new Route(routeID, destinazione, type, new ArrayList(6))); return this.routes.size() - 1; // last inserted element and pray that direct access to ArrayList elements really is direct } /** * Adds a timetable entry to a route. * * @param TimeGTT time in GTT format (e.g. "11:22*") * @param arrayIndex position in the array for this route (returned by addRoute) */ public void addPassaggio(String TimeGTT, int arrayIndex) { this.routes.get(arrayIndex).addPassaggio(TimeGTT); } // /** // * Clears a route timetable (or creates an empty route) and returns its index // * // * @param routeID name // * @param destinazione end of line\terminus // * @return array index for this route // */ // public int updateRoute(String routeID, String destinazione) { // int s = this.routes.size(); // RouteInternal r; // // for(int i = 0; i < s; i++) { // r = routes.get(i); // if(r.name.compareTo(routeID) == 0 && r.destinazione.compareTo(destinazione) == 0) { // // capire se è possibile che ci siano stessa linea e stessa destinazione su 2 righe diverse del sito e qui una sovrascrive l'altra (probabilmente no) // r.updateFlag(); // r.deletePassaggio(); // return i; // } // } // // return this.addRoute(routeID, destinazione); // } // // /** // * Deletes routes marked as "not updated" (= disappeared from the GTT website\API\whatever). // * Sets all remaining routes to "not updated" because that's how this contraption works. // */ // public void finishUpdatingRoutes() { // RouteInternal r; // // for(Iterator itr = this.routes.iterator(); itr.hasNext(); ) { // r = itr.next(); // if(r.unupdateFlag()) { // itr.remove(); // } // } // } // /** // * Gets the current timetable for a route. Returns null if the route doesn't exist. // * This is slower than queryRouteByIndex. // * // * @return timetable (passaggi) // */ // public List queryRoute(String routeID) { // for(Route r : this.routes) { // if(routeID.equals(r.name)) { // return r.getPassaggi(); // } // } // // return null; // } // // /** // * Gets the current timetable for this route, from its index in the array. // * // * @return timetable (passaggi) // */ // public List queryRouteByIndex(int index) { // return this.routes.get(index).getPassaggi(); // } /** * Gets every route and its timetable. * * @return routes and timetables. */ public List queryAllRoutes() { return this.routes; } public void sortRoutes() { Collections.sort(this.routes); } // /** // * Route with terminus (destinazione) and timetables (passaggi), internal implementation. // * // * Contains mostly the same data as the Route public class, but methods are quite different and extending Route doesn't really work, here. // */ // private final class RouteInternal { // public final String name; // public final String destinazione; // private boolean updated; // private List passaggi; // // /** // * Creates a new route and marks it as "updated", since it's new. // * // * @param routeID name // * @param destinazione end of line\terminus // */ // public RouteInternal(String routeID, String destinazione) { // this.name = routeID; // this.destinazione = destinazione; // this.passaggi = new LinkedList<>(); // this.updated = true; // } // // /** // * Adds a time (passaggio) to the timetable for this route // * // * @param TimeGTT time in GTT format (e.g. "11:22*") // */ // public void addPassaggio(String TimeGTT) { // this.passaggi.add(new Passaggio(TimeGTT)); // } // // /** // * Deletes al times (passaggi) from the timetable. // */ // public void deletePassaggio() { // this.passaggi = new LinkedList<>(); // this.updated = true; // } // // /** // * Sets the "updated" flag to false. // * // * @return previous state // */ // public boolean unupdateFlag() { // if(this.updated) { // this.updated = false; // return true; // } else { // return false; // } // } // // /** // * Sets the "updated" flag to true. // * // * @return previous state // */ // public boolean updateFlag() { // if(this.updated) { // return true; // } else { // this.updated = true; // return false; // } // } // // /** // * Exactly what it says on the tin. // * // * @return times from the timetable // */ // public List getPassaggi() { // return this.passaggi; // } // } } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/backend/Stop.java b/src/it/reyboz/bustorino/backend/Stop.java index 11411c6..a3e8277 100644 --- a/src/it/reyboz/bustorino/backend/Stop.java +++ b/src/it/reyboz/bustorino/backend/Stop.java @@ -1,114 +1,137 @@ /* 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 java.util.List; public class Stop implements Comparable { // remove "final" in case you need to set these from outside the parser\scrapers\fetchers public final @NonNull String ID; - public @NonNull String name; + private @Nullable String name; public final @Nullable String location; public final @Nullable Route.Type type; private final @Nullable List routesThatStopHere; // leave this non-final private @Nullable String routesThatStopHereString = null; /** * Hey, look, method overloading! */ - public Stop(final @NonNull String name, final @NonNull String ID, @Nullable final String location, @Nullable final Route.Type type, @Nullable final List routesThatStopHere) { + public Stop(final @Nullable String name, final @NonNull String ID, @Nullable final String location, @Nullable final Route.Type type, @Nullable final List routesThatStopHere) { this.ID = ID; this.name = name; this.location = (location != null && location.length() == 0) ? null : location; this.type = type; this.routesThatStopHere = routesThatStopHere; } /** * Hey, look, method overloading! */ public Stop(final @NonNull String ID) { this.ID = ID; - this.name = ""; + this.name = null; this.location = null; this.type = null; this.routesThatStopHere = null; } public @Nullable String routesThatStopHereToString() { // M E M O I Z A T I O N if(this.routesThatStopHereString != null) { return this.routesThatStopHereString; } // no string yet? build it! return buildString(); } private @Nullable String buildString() { // no routes => no string if(this.routesThatStopHere == null || this.routesThatStopHere.size() == 0) { return null; } StringBuilder sb = new StringBuilder(); int i, lenMinusOne = routesThatStopHere.size() - 1; for (i = 0; i < lenMinusOne; i++) { sb.append(routesThatStopHere.get(i)).append(", "); } // last one: sb.append(routesThatStopHere.get(i)); this.routesThatStopHereString = sb.toString(); return this.routesThatStopHereString; } @Override public int compareTo(@NonNull Stop other) { int res; int thisAsInt = networkTools.failsafeParseInt(this.ID); int otherAsInt = networkTools.failsafeParseInt(other.ID); // numeric stop IDs if(thisAsInt != 0 && otherAsInt != 0) { return thisAsInt - otherAsInt; } else { // non-numeric res = this.ID.compareTo(other.ID); if (res != 0) { return res; } } // try with name, then - res = this.name.compareTo(other.name); + if(this.name != null && other.name != null) { + res = this.name.compareTo(other.name); + } // and give up return res; } + + /** + * Sets a name. + * + * @param name stop name as string (not null) + */ + public final void setStopName(@NonNull String name) { + this.name = name; + } + + /** + * Returns stop name.
+ * - empty string means "already searched everywhere, can't find it"
+ * - null means "didn't search, yet. Maybe you should try."
+ * - string means "here's the name.", obviously.
+ * + * @return string if known, null if still unknown + */ + public final @Nullable String getStopName() { + return this.name; + } } diff --git a/src/it/reyboz/bustorino/middleware/AsyncArrivalsFetcherAll.java b/src/it/reyboz/bustorino/middleware/AsyncArrivalsFetcherAll.java deleted file mode 100644 index 20c767e..0000000 --- a/src/it/reyboz/bustorino/middleware/AsyncArrivalsFetcherAll.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - 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.middleware; - -import it.reyboz.bustorino.backend.ArrivalsFetcher; -import it.reyboz.bustorino.backend.Fetcher; -import it.reyboz.bustorino.backend.Palina; - -import android.os.AsyncTask; -import android.support.annotation.NonNull; - -import java.util.concurrent.atomic.AtomicReference; - -public class AsyncArrivalsFetcherAll extends AsyncTask { - private final ArrivalsFetcher af; - private AtomicReference result; - private final String stopID; - private final AsyncArrivalsFetcherAllCallback callback; - - public AsyncArrivalsFetcherAll(@NonNull ArrivalsFetcher af, @NonNull String stopID, @NonNull AsyncArrivalsFetcherAllCallback callback) { - this.af = af; - this.stopID = stopID; - this.callback = callback; - this.result = new AtomicReference<>(); - } - - @Override protected Palina doInBackground(Void... useless) { - return af.ReadArrivalTimesAll(this.stopID, this.result); - } - - @Override protected void onPostExecute(Palina p) { - if(!this.isCancelled()) { // is this really needed? - this.callback.call(p, result.get(), this.stopID); - } - } - - /** - * Android doesn't really support JDK 8, so we have to use this hack\workaround.
- *
- * I've already tested 4 different solutions, this is the cleanest-looking so far...
- *
- * The only purpose of this interface is to glue together the AsyncArrivalsFetcherAll and whatver ActivityMain needs to do after obraining results, change parameters liberally if needed. - */ - public interface AsyncArrivalsFetcherAllCallback { - void call(Palina p, Fetcher.result res, String stopID); - } -} \ No newline at end of file diff --git a/src/it/reyboz/bustorino/middleware/AsyncStopsFinderByName.java b/src/it/reyboz/bustorino/middleware/AsyncStopsFinderByName.java deleted file mode 100644 index 2648f31..0000000 --- a/src/it/reyboz/bustorino/middleware/AsyncStopsFinderByName.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - 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.middleware; - -import android.os.AsyncTask; -import android.support.annotation.NonNull; - -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -import it.reyboz.bustorino.backend.ArrivalsFetcher; -import it.reyboz.bustorino.backend.Fetcher; -import it.reyboz.bustorino.backend.Palina; -import it.reyboz.bustorino.backend.Stop; -import it.reyboz.bustorino.backend.StopsDBInterface; -import it.reyboz.bustorino.backend.StopsFinderByName; - -public class AsyncStopsFinderByName extends AsyncTask> { - private final StopsFinderByName sf; - private AtomicReference result; - private final StopsDB db; - private final String query; - private final AsyncStopsFinderByNameCallback callback; - - /** - * Run a StopsFinderByName in a background thread - * - * @param sf some concrete implementation of StopsFinderByName - * @param query the string to search for - * @param callback callback (you don't say) - * @param sdb StopsDB - */ - public AsyncStopsFinderByName(@NonNull StopsFinderByName sf, @NonNull String query, @NonNull AsyncStopsFinderByNameCallback callback, @NonNull StopsDB sdb) { - this.sf = sf; - this.query = query; - this.callback = callback; - this.result = new AtomicReference<>(); - this.db = sdb; - } - - @Override protected List doInBackground(Void... useless) { - this.db.openIfNeeded(); - List ret = sf.FindByName(this.query, this.db, this.result); - this.db.closeIfNeeded(); - return ret; - } - - @Override protected void onPostExecute(List stops) { - if(!this.isCancelled()) { - this.callback.call(stops, result.get(), this.query); - } - } - - public interface AsyncStopsFinderByNameCallback { - void call(List stops, Fetcher.result res, String query); - } -} \ No newline at end of file diff --git a/src/it/reyboz/bustorino/middleware/AsyncWget.java b/src/it/reyboz/bustorino/middleware/AsyncWget.java new file mode 100644 index 0000000..bbb82bd --- /dev/null +++ b/src/it/reyboz/bustorino/middleware/AsyncWget.java @@ -0,0 +1,99 @@ +/* + 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.middleware; + +import android.content.Context; +import android.os.AsyncTask; +import android.widget.Toast; + +import it.reyboz.bustorino.R; + +/** + * Call this.execute() right after the constructor. Or in the constructor itself, if you're + * overriding it (also call super() constructor in that case). + */ +public abstract class AsyncWget extends AsyncTask { + protected RecursionHelper r; + /** + * True: every fetcher failed in some way + * False: at least one fetcher succeeded and loop was terminated + */ + protected boolean failedAll = false; + /** + * True: recursion\loop has terminated naturally + * False: task has been cancelled + */ + protected boolean terminated = false; + + protected final Context c; + + /** + * Try every fetcher until you get something usable.
+ */ + public AsyncWget(Context c, RecursionHelper r) { + r.reset(); + + this.r = r; + this.c = c; + } + + @Override + protected Void doInBackground(Void... useless) { + while(r.valid()) { + if(this.isCancelled()) { + return null; + } + + if(this.tryFetcher(r.getAndMoveForward())) { + this.terminated = true; + break; + } + } + + // everything failed? + if(!this.terminated) { + // well, natural termination was reached, so set "terminated" to true... + this.terminated = true; + this.failedAll = true; + } + + return null; + } + + /** + * Override this! + * + * @param f fetcher + * @return true if succeeded and want to terminate, false if failed and want to try next fetcher + */ + abstract protected boolean tryFetcher(FetcherKind f); + + /** + * Shows a toast. + * + * @param toastz resources from R, containing a message + */ + @Override + protected void onProgressUpdate(Integer... toastz) { + for(int i: toastz) { + Toast.makeText(this.c, i, Toast.LENGTH_SHORT).show(); + } + } + +} \ No newline at end of file diff --git a/src/it/reyboz/bustorino/middleware/RecursionHelper.java b/src/it/reyboz/bustorino/middleware/RecursionHelper.java new file mode 100644 index 0000000..5b4614a --- /dev/null +++ b/src/it/reyboz/bustorino/middleware/RecursionHelper.java @@ -0,0 +1,61 @@ +/* + 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.middleware; + +/** + * Holds some global data used by recursive methods to try every fetcher until you get some data.
+ * Well, those methods are now iterative but the name stuck... + * + * @param ArrivalsFetcher, StopsFinder, ... + */ +public class RecursionHelper { + private int pos = 0; + private final int len; + private final FetcherKind[] fetchers; + + public RecursionHelper(FetcherKind[] fetchers) { + this.fetchers = fetchers; + this.len = fetchers.length; + } + + /** + * Go back to square one. Or zero since arrays are zero-indexed. + */ + public void reset() { + this.pos = 0; + } + + /** + * Can you give me a valid Fetcher without throwing exceptions? + * + * @return boolean + */ + public boolean valid() { + return this.pos < len; + } + + /** + * Give me a fetcher (use valid() to check that it exists BEFORE requesting it), move to next + * + * @return the fetcher\finder\whatever + */ + public FetcherKind getAndMoveForward() { + return fetchers[this.pos++]; + } +} \ No newline at end of file diff --git a/src/it/reyboz/bustorino/middleware/StopAdapter.java b/src/it/reyboz/bustorino/middleware/StopAdapter.java index 4213d6f..f46b20b 100644 --- a/src/it/reyboz/bustorino/middleware/StopAdapter.java +++ b/src/it/reyboz/bustorino/middleware/StopAdapter.java @@ -1,114 +1,114 @@ /* 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.middleware; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import it.reyboz.bustorino.R; import it.reyboz.bustorino.backend.Stop; /** * @see PalinaAdapter */ public class StopAdapter extends ArrayAdapter { private LayoutInflater li; private static int row_layout = R.layout.entry_bus_stop; private static final int busIcon = R.drawable.bus; private static final int trainIcon = R.drawable.subway; private static final int tramIcon = R.drawable.tram; private static final int cityIcon = R.drawable.city; static class ViewHolder { TextView busStopIDTextView; TextView busStopNameTextView; //TextView busLineVehicleIcon; TextView busStopLinesTextView; TextView busStopLocaLityTextView; } public StopAdapter(Context context, List stops) { super(context, row_layout, stops); li = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder vh; if(convertView == null) { convertView = li.inflate(row_layout, null); vh = new ViewHolder(); vh.busStopIDTextView = (TextView) convertView.findViewById(R.id.busStopID); vh.busStopNameTextView = (TextView) convertView.findViewById(R.id.busStopName); vh.busStopLinesTextView = (TextView) convertView.findViewById(R.id.routesThatStopHere); vh.busStopLocaLityTextView = (TextView) convertView.findViewById(R.id.busStopLocality); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } Stop stop = getItem(position); vh.busStopIDTextView.setText(stop.ID); // NOTE: intentionally ignoring stop username: if it's in the favorites, why are you searching for it? - vh.busStopNameTextView.setText(stop.name); + vh.busStopNameTextView.setText(stop.getStopName()); String whatStopsHere = stop.routesThatStopHereToString(); if(whatStopsHere == null) { vh.busStopLinesTextView.setVisibility(View.GONE); } else { vh.busStopLinesTextView.setText(whatStopsHere); } if(stop.type == null) { vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0); } else { switch(stop.type) { case BUS: default: vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0); break; case METRO: case RAILWAY: vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(trainIcon, 0, 0, 0); break; case TRAM: vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(tramIcon, 0, 0, 0); break; case LONG_DISTANCE_BUS: // è l'opposto della città ma va beh, dettagli. vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(cityIcon, 0, 0, 0); } } if (stop.location == null) { vh.busStopLocaLityTextView.setVisibility(View.GONE); } else { vh.busStopLocaLityTextView.setText(stop.location); } return convertView; } }