diff --git a/app/src/main/java/it/reyboz/bustorino/data/GtfsMaintenanceWorker.kt b/app/src/main/java/it/reyboz/bustorino/data/GtfsMaintenanceWorker.kt new file mode 100644 index 0000000..1801129 --- /dev/null +++ b/app/src/main/java/it/reyboz/bustorino/data/GtfsMaintenanceWorker.kt @@ -0,0 +1,70 @@ +package it.reyboz.bustorino.data + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.Context +import android.os.Build +import android.widget.Toast +import androidx.core.app.NotificationCompat +import androidx.work.* +import it.reyboz.bustorino.R +import it.reyboz.bustorino.backend.Notifications + +class GtfsMaintenanceWorker(appContext: Context, workerParams: WorkerParameters) + : CoroutineWorker(appContext, workerParams) { + override suspend fun doWork(): Result { + val data = inputData.getString(OPERATION_TYPE) + if(data ==null){ + return Result.failure() + } + val result = when (data){ + CLEAR_GTFS_TRIPS ->clearGtfsTrips() + else -> {Result.failure()} + } + return result + } + private fun clearGtfsTrips(): Result{ + val gtfsRepository = GtfsRepository(applicationContext) + gtfsRepository.gtfsDao.deleteAllTrips() + + return Result.success() + } + override suspend fun getForegroundInfo(): ForegroundInfo { + val notificationManager = + applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val context = applicationContext + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val channel = NotificationChannel( + Notifications.DB_UPDATE_CHANNELS_ID, + context.getString(R.string.database_notification_channel), + NotificationManager.IMPORTANCE_MIN + ) + notificationManager.createNotificationChannel(channel) + } + + val notification = NotificationCompat.Builder(context, Notifications.DB_UPDATE_CHANNELS_ID) + //.setContentIntent(PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), Constants.PENDING_INTENT_FLAG_IMMUTABLE)) + .setSmallIcon(R.drawable.bus) + .setOngoing(true) + .setAutoCancel(true) + .setOnlyAlertOnce(true) + .setPriority(NotificationCompat.PRIORITY_MIN) + .setContentTitle(context.getString(R.string.app_name)) + .setLocalOnly(true) + .setVisibility(NotificationCompat.VISIBILITY_SECRET) + .setContentText("Database maintenance") + .build() + return ForegroundInfo(3671672811121.toInt(), notification) + } + companion object{ + const val CLEAR_GTFS_TRIPS="trips_clear" + const val OPERATION_TYPE="oper_type" + fun makeOneTimeRequest(type: String): OneTimeWorkRequest { + val data = Data.Builder().putString(OPERATION_TYPE, type).build() + return OneTimeWorkRequest.Builder(GtfsMaintenanceWorker::class.java) + .setInputData(data).setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) + .addTag(type) + .build() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/data/gtfs/Converters.kt b/app/src/main/java/it/reyboz/bustorino/data/gtfs/Converters.kt index 243d887..9c2d28c 100644 --- a/app/src/main/java/it/reyboz/bustorino/data/gtfs/Converters.kt +++ b/app/src/main/java/it/reyboz/bustorino/data/gtfs/Converters.kt @@ -1,103 +1,95 @@ /* BusTO - Data components Copyright (C) 2021 Fabio Mazza 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.data.gtfs import androidx.room.TypeConverter import java.text.SimpleDateFormat import java.util.* /** * Class to convert values for objects into * the needed columns * * handled automatically by Room with TypeConverter */ class Converters { @TypeConverter fun fromString(value: String?): Date? { return dateFromFmtString(value) } @TypeConverter fun dateToString(date: Date?): String? { return date?.let { stringFormat.format(it)} } @TypeConverter fun exceptionToInt(type: GtfsServiceDate.ExceptionType?): Int? { return type?.value } @TypeConverter fun fromInt(value: Int?): GtfsServiceDate.ExceptionType? { return value?.let { GtfsServiceDate.ExceptionType.getByValue(it) } } companion object{ const val DATE_FMT_STRING = "yyyyMMdd" val stringFormat = SimpleDateFormat(DATE_FMT_STRING, Locale.US) fun fromStringNum(string: String?): Boolean?{ string?.let { if (it.trim() == "1") return true else if(it.trim() == "0") return false else throw Exception("Cannot convert $string to numeric value") } return null } fun fromStringNum(string: String?, defaultVal: Boolean): Boolean{ string?.let { if (it.trim() == "1") return true else if(it.trim() == "0") return false else return defaultVal } return defaultVal } fun dateFromFmtString(value: String?): Date?{ return value?.let { stringFormat.parse(it) } } fun wheelchairFromString(string: String?): WheelchairAccess{ string?.let { if (it.trim() == "1") return WheelchairAccess.SOMETIMES else if(it.trim() == "0") return WheelchairAccess.UNKNOWN else if(it.trim() == "2") return WheelchairAccess.IMPOSSIBLE else //throw Exception("Cannot convert $string to wheelchair access") } return WheelchairAccess.UNKNOWN } return WheelchairAccess.UNKNOWN } - @TypeConverter - fun wheelchairToInt(access: WheelchairAccess): Int{ - return access.value; - } - @TypeConverter - fun wheelchairFromInt(value: Int): WheelchairAccess { - return WheelchairAccess.getByValue(value)?: WheelchairAccess.UNKNOWN - } } } \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/data/gtfs/WheelchairAccess.kt b/app/src/main/java/it/reyboz/bustorino/data/gtfs/WheelchairAccess.kt index e26b677..bc1dffb 100644 --- a/app/src/main/java/it/reyboz/bustorino/data/gtfs/WheelchairAccess.kt +++ b/app/src/main/java/it/reyboz/bustorino/data/gtfs/WheelchairAccess.kt @@ -1,12 +1,14 @@ package it.reyboz.bustorino.data.gtfs enum class WheelchairAccess(val value: Int){ UNKNOWN(0), SOMETIMES(1), IMPOSSIBLE(2); + // BE CAREFUL: WheelchairAccess is saved as a String in the DB due to a catastrophic error. + // However, everything works perfectly, so... finchè la barca va... companion object { private val VALUES = values() fun getByValue(value: Int) = VALUES.firstOrNull { it.value == value } } } \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/MapViewModel.kt b/app/src/main/java/it/reyboz/bustorino/fragments/MapViewModel.kt index 64b4adf..9d0d183 100644 --- a/app/src/main/java/it/reyboz/bustorino/fragments/MapViewModel.kt +++ b/app/src/main/java/it/reyboz/bustorino/fragments/MapViewModel.kt @@ -1,235 +1,237 @@ /* BusTO - View Models components Copyright (C) 2023 Fabio Mazza 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.fragments import android.app.Application import android.util.Log import androidx.lifecycle.* import androidx.work.* import com.android.volley.Response import com.google.transit.realtime.GtfsRealtime.VehiclePosition import it.reyboz.bustorino.backend.NetworkVolleyManager import it.reyboz.bustorino.backend.Result import it.reyboz.bustorino.backend.gtfs.GtfsPositionUpdate import it.reyboz.bustorino.backend.gtfs.GtfsRtPositionsRequest import it.reyboz.bustorino.data.* import it.reyboz.bustorino.data.gtfs.GtfsTrip import it.reyboz.bustorino.data.gtfs.TripAndPatternWithStops import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.util.concurrent.Executors /** * View Model for the map. For containing the stops, the trips and whatever */ class MapViewModel(application: Application): AndroidViewModel(application) { private val gtfsRepo = GtfsRepository(application) private val executor = Executors.newFixedThreadPool(2) private val oldRepo= OldDataRepository(executor, NextGenDB.getInstance(application)) private val matoRepository = MatoRepository(application) private val netVolleyManager = NetworkVolleyManager.getInstance(application) val positionsLiveData = MutableLiveData>() private val positionsRequestRunning = MutableLiveData() private val positionRequestListener = object: GtfsRtPositionsRequest.Companion.RequestListener{ override fun onResponse(response: ArrayList?) { Log.i(DEBUG_TI,"Got response from the GTFS RT server") response?.let {it:ArrayList -> if (it.size == 0) { Log.w(DEBUG_TI,"No position updates from the server") return } else { //Log.i(DEBUG_TI, "Posting value to positionsLiveData") viewModelScope.launch { positionsLiveData.postValue(it) } } } //whatever the result, launch again the update TODO } } private val positionRequestErrorListener = Response.ErrorListener { //error listener, it->VolleyError Log.e(DEBUG_TI, "Could not download the update, error:\n"+it.stackTrace) //TODO: launch again if needed } fun requestUpdates(){ if(positionsRequestRunning.value == null || !positionsRequestRunning.value!!) { val request = GtfsRtPositionsRequest(positionRequestErrorListener, positionRequestListener) netVolleyManager.requestQueue.add(request) Log.i(DEBUG_TI, "Requested GTFS realtime position updates") positionsRequestRunning.value = true } } /*suspend fun requestDelayedUpdates(timems: Long){ delay(timems) requestUpdates() } */ fun requestDelayedUpdates(timems: Long){ viewModelScope.launch { delay(timems) requestUpdates() } } // TRIPS IDS that have to be queried to the DB val tripsIDsInUpdates : LiveData> = positionsLiveData.map { Log.i(DEBUG_TI, "positionsLiveData changed") //allow new requests for the positions of buses positionsRequestRunning.value = false //add "gtt:" prefix because it's implicit in GTFS Realtime API return@map it.map { pos -> "gtt:"+pos.tripID } } // trips that are in the DB val gtfsTripsInDB = tripsIDsInUpdates.switchMap { //Log.i(DEBUG_TI, "tripsIds in updates changed: ${it.size}") gtfsRepo.gtfsDao.getTripPatternStops(it) } //trip IDs to query, which are not present in the DB val tripsGtfsIDsToQuery: LiveData> = gtfsTripsInDB.map { tripswithPatterns -> val tripNames=tripswithPatterns.map { twp-> twp.trip.tripID } Log.i(DEBUG_TI, "Have ${tripswithPatterns.size} trips in the DB") if (tripsIDsInUpdates.value!=null) return@map tripsIDsInUpdates.value!!.filter { !tripNames.contains(it) } else { Log.e(DEBUG_TI,"Got results for gtfsTripsInDB but not tripsIDsInUpdates??") return@map ArrayList() } } val updatesWithTripAndPatterns = gtfsTripsInDB.map { tripPatterns-> Log.i(DEBUG_TI, "Mapping trips and patterns") val mdict = HashMap>() if(positionsLiveData.value!=null) for(update in positionsLiveData.value!!){ val trID = update.tripID var found = false for(trip in tripPatterns){ if (trip.trip.tripID == "gtt:$trID"){ found = true //insert directly mdict[trID] = Pair(update,trip) break } } if (!found){ //give the update anyway mdict[trID] = Pair(update,null) } } return@map mdict } /* There are two strategies for the queries, since we cannot query a bunch of tripIDs all together to Mato API -> we need to query each separately: 1 -> wait until they are all queried to insert in the DB 2 -> after each request finishes, insert it into the DB Keep in mind that trips do not change very often, so they might only need to be inserted once every two months TODO: find a way to avoid trips getting scrubbed (check if they are really scrubbed) */ init { /* //what happens when the trips to query with Mato are determined tripsIDsQueried.addSource(tripsGtfsIDsToQuery) { tripList -> // avoid infinite loop of querying to Mato, insert in DB and // triggering another query update val tripsToQuery = Log.d(DEBUG_TI, "Querying trips IDs to Mato: $tripsToQuery") for (t in tripsToQuery){ matoRepository.requestTripUpdate(t,matoTripReqErrorList, matoTripCallback) } tripsIDsQueried.value = tripsToQuery } tripsToInsert.addSource(tripsFromMato) { matoTrips -> if (tripsIDsQueried.value == null) return@addSource val tripsIdsToInsert = matoTrips.map { trip -> trip.tripID } //val setTripsToInsert = HashSet(tripsIdsToInsert) val tripsRequested = HashSet(tripsIDsQueried.value!!) val insertInDB = tripsRequested.containsAll(tripsIdsToInsert) if(insertInDB){ gtfsRepo.gtfsDao.insertTrips(matoTrips) } Log.d(DEBUG_TI, "MatoTrips: ${matoTrips.size}, total trips req: ${tripsRequested.size}, inserting: $insertInDB") } */ Log.d(DEBUG_TI, "MapViewModel created") Log.d(DEBUG_TI, "Observers of positionsLiveData ${positionsLiveData.hasActiveObservers()}") positionsRequestRunning.value = false; } fun testCascade(){ val n = ArrayList() n.add(GtfsPositionUpdate("22920721U","lala","lalal","lol",1000.0f,1000.0f, 9000.0f, 378192810192, GtfsPositionUpdate.VehicleInfo("aj","a"), null, null )) positionsLiveData.value = n } private val queriedMatoTrips = HashSet() private val downloadedMatoTrips = ArrayList() private val failedMatoTripsDownload = HashSet() /** * Start downloading missing GtfsTrips and Insert them in the DB */ fun downloadandInsertTripsInDB(trips: List): Boolean{ if (trips.isEmpty()) return false val workManager = WorkManager.getInstance(getApplication()) val info = workManager.getWorkInfosForUniqueWork(MatoDownloadTripsWorker.WORK_TAG).get() val runNewWork = if(info.isEmpty()){ true } else info[0].state!=WorkInfo.State.RUNNING && info[0].state!=WorkInfo.State.ENQUEUED - Log.d(DEBUG_TI, "Request to download and insert ${trips.size} trips, proceed: $runNewWork") + val addDat = if(info.isEmpty()) + null else info[0].state + Log.d(DEBUG_TI, "Request to download and insert ${trips.size} trips, proceed: $runNewWork, workstate: $addDat") if(runNewWork) { val tripsArr = trips.toTypedArray() val data = Data.Builder().putStringArray(MatoDownloadTripsWorker.TRIPS_KEYS, tripsArr).build() val requ = OneTimeWorkRequest.Builder(MatoDownloadTripsWorker::class.java) .setInputData(data).setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) .addTag(MatoDownloadTripsWorker.WORK_TAG) .build() workManager.enqueueUniqueWork(MatoDownloadTripsWorker.WORK_TAG, ExistingWorkPolicy.KEEP, requ) } return true } companion object{ const val DEBUG_TI="BusTO-MapViewModel" const val DEFAULT_DELAY_REQUESTS: Long=4000 } } \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/SettingsFragment.java b/app/src/main/java/it/reyboz/bustorino/fragments/SettingsFragment.java index a2a8c01..ea04c73 100644 --- a/app/src/main/java/it/reyboz/bustorino/fragments/SettingsFragment.java +++ b/app/src/main/java/it/reyboz/bustorino/fragments/SettingsFragment.java @@ -1,189 +1,222 @@ /* BusTO - Fragments components Copyright (C) 2020 Fabio Mazza 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.fragments; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.lifecycle.Observer; import androidx.preference.*; -import androidx.room.Database; +import androidx.work.OneTimeWorkRequest; +import androidx.work.OutOfQuotaPolicy; +import androidx.work.WorkInfo; +import androidx.work.WorkManager; import it.reyboz.bustorino.R; import it.reyboz.bustorino.data.DatabaseUpdate; +import it.reyboz.bustorino.data.GtfsMaintenanceWorker; +import it.reyboz.bustorino.data.MatoDownloadTripsWorker; +import org.jetbrains.annotations.NotNull; import java.lang.ref.WeakReference; import java.util.HashSet; +import java.util.List; public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = SettingsFragment.class.getName(); private static final String DIALOG_FRAGMENT_TAG = "androidx.preference.PreferenceFragment.DIALOG"; //private static final Handler mHandler; public final static String PREF_KEY_STARTUP_SCREEN="startup_screen_to_show"; public final static String KEY_ARRIVALS_FETCHERS_USE = "arrivals_fetchers_use_setting"; private boolean setSummaryStartupPref = false; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mHandler = new Handler(); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { //getPreferenceManager().setSharedPreferencesName(getString(R.string.mainSharedPreferences)); convertStringPrefToIntIfNeeded(getString(R.string.pref_key_num_recents), getContext()); getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); setPreferencesFromResource(R.xml.preferences,rootKey); /*EditTextPreference editPref = findPreference(getString(R.string.pref_key_num_recents)); editPref.setOnBindEditTextListener(editText -> { editText.setInputType(InputType.TYPE_CLASS_NUMBER); editText.setSelection(0,editText.getText().length()); }); */ ListPreference startupScreenPref = findPreference(PREF_KEY_STARTUP_SCREEN); if(startupScreenPref !=null){ if (startupScreenPref.getValue()==null){ startupScreenPref.setSummary(getString(R.string.nav_arrivals_text)); setSummaryStartupPref = true; } } //Log.d("BusTO-PrefFrag","startup screen pref is "+startupScreenPref.getValue()); Preference dbUpdateNow = findPreference("pref_db_update_now"); if (dbUpdateNow!=null) dbUpdateNow.setOnPreferenceClickListener( new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(@NonNull Preference preference) { //trigger update if(getContext()!=null) { DatabaseUpdate.requestDBUpdateWithWork(getContext().getApplicationContext(), true, true); Toast.makeText(getContext(),R.string.requesting_db_update,Toast.LENGTH_SHORT).show(); return true; } return false; } } ); + else { Log.e("BusTO-Preferences", "Cannot find db update preference"); } + Preference clearGtfsTrips = findPreference("pref_clear_gtfs_trips"); + if (clearGtfsTrips != null) { + clearGtfsTrips.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(@NonNull @NotNull Preference preference) { + if (getContext() != null) { + OneTimeWorkRequest requ = GtfsMaintenanceWorker.Companion.makeOneTimeRequest(GtfsMaintenanceWorker.CLEAR_GTFS_TRIPS); + WorkManager.getInstance(getContext()).enqueue(requ); + WorkManager.getInstance(getContext()).getWorkInfosByTagLiveData(GtfsMaintenanceWorker.CLEAR_GTFS_TRIPS).observe(getViewLifecycleOwner(), + (Observer>) workInfos -> { + if(workInfos.isEmpty()) + return; + if(workInfos.get(0).getState()==(WorkInfo.State.SUCCEEDED)){ + Toast.makeText( + getContext(), R.string.all_trips_removed, Toast.LENGTH_SHORT + ).show(); + } + }); + return true; + } + return false; + } + }); + } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Preference pref = findPreference(key); Log.d(TAG,"Preference key "+key+" changed"); if (key.equals(SettingsFragment.KEY_ARRIVALS_FETCHERS_USE)){ Log.d(TAG, "New value is: "+sharedPreferences.getStringSet(key, new HashSet<>())); } //sometimes this happens if(getContext()==null) return; if(key.equals(PREF_KEY_STARTUP_SCREEN) && setSummaryStartupPref && pref !=null){ ListPreference listPref = (ListPreference) pref; pref.setSummary(listPref.getEntry()); } /* THIS CODE STAYS COMMENTED FOR FUTURE REFERENCES if (key.equals(getString(R.string.pref_key_num_recents))){ //check that is it an int String value = sharedPreferences.getString(key,""); boolean valid = value.length() != 0; try{ Integer intValue = Integer.parseInt(value); } catch (NumberFormatException ex){ valid = false; } if (!valid){ Toast.makeText(getContext(), R.string.invalid_number, Toast.LENGTH_SHORT).show(); if(pref instanceof EditTextPreference){ EditTextPreference prefEdit = (EditTextPreference) pref; //Intent intent = prefEdit.getIntent(); Log.d(TAG, "opening preference, dialog showing "+ (getParentFragmentManager().findFragmentByTag(DIALOG_FRAGMENT_TAG)!=null) ); //getPreferenceManager().showDialog(pref); //onDisplayPreferenceDialog(prefEdit); mHandler.postDelayed(new DelayedDisplay(prefEdit), 500); } } } */ Log.d("BusTO Settings", "changed "+key+"\n "+sharedPreferences.getAll()); } private void convertStringPrefToIntIfNeeded(String preferenceKey, Context con){ if (con == null) return; SharedPreferences defaultSharedPref = PreferenceManager.getDefaultSharedPreferences(con); try{ Integer val = defaultSharedPref.getInt(preferenceKey, 0); } catch (NumberFormatException | ClassCastException ex){ //convert the preference //final String preferenceNumRecents = getString(R.string.pref_key_num_recents); Log.d("Preference - BusTO", "Converting to integer the string preference "+preferenceKey); String currentValue = defaultSharedPref.getString(preferenceKey, "10"); int newValue; try{ newValue = Integer.parseInt(currentValue); } catch (NumberFormatException e){ newValue = 10; } final SharedPreferences.Editor editor = defaultSharedPref.edit(); editor.remove(preferenceKey); editor.putInt(preferenceKey, newValue); editor.apply(); } } class DelayedDisplay implements Runnable{ private final WeakReference preferenceWeakReference; public DelayedDisplay(DialogPreference preference) { this.preferenceWeakReference = new WeakReference<>(preference); } @Override public void run() { if(preferenceWeakReference.get()==null) return; getPreferenceManager().showDialog(preferenceWeakReference.get()); } } } diff --git a/app/src/main/res/layout/fragment_test_realtime_gtfs.xml b/app/src/main/res/layout/fragment_test_realtime_gtfs.xml index 9de1fed..5437404 100644 --- a/app/src/main/res/layout/fragment_test_realtime_gtfs.xml +++ b/app/src/main/res/layout/fragment_test_realtime_gtfs.xml @@ -1,27 +1,27 @@