Commit 87b1e4c9 authored by Bartek Fabiszewski's avatar Bartek Fabiszewski
Browse files

Update sync settings on preferences change, fixes #57

parent 460830e0
Loading
Loading
Loading
Loading
+2 −1
Original line number Diff line number Diff line
@@ -39,6 +39,7 @@ import androidx.preference.PreferenceManager;
import static android.location.LocationProvider.AVAILABLE;
import static android.location.LocationProvider.OUT_OF_SERVICE;
import static android.location.LocationProvider.TEMPORARILY_UNAVAILABLE;
import static net.fabiszewski.ulogger.MainActivity.UPDATED_PREFS;

/**
 * Background service logging positions to database
@@ -134,7 +135,7 @@ public class LoggerService extends Service {
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Logger.DEBUG) { Log.d(TAG, "[onStartCommand]"); }

        final boolean prefsUpdated = (intent != null) && intent.getBooleanExtra(MainActivity.UPDATED_PREFS, false);
        final boolean prefsUpdated = (intent != null) && intent.getBooleanExtra(UPDATED_PREFS, false);
        if (prefsUpdated) {
            handlePrefsUpdated();
        } else {
+24 −11
Original line number Diff line number Diff line
@@ -566,11 +566,9 @@ public class MainActivity extends AppCompatActivity {
        String error = db.getError();
        if (error != null) {
            if (Logger.DEBUG) { Log.d(TAG, "[sync error: " + error + "]"); }
            syncError = true;
            syncErrorLabel.setText(error);
        } else if (syncError) {
            syncError = false;
            syncErrorLabel.setText(null);
            setSyncError(error);
        } else {
            resetSyncError();
        }
        updateSyncStatus(count);
    }
@@ -668,10 +666,7 @@ public class MainActivity extends AppCompatActivity {
                    updateSyncStatus(unsyncedCount);
                    setSyncLed(LED_GREEN);
                    // reset error flag and label
                    if (syncError) {
                        syncErrorLabel.setText(null);
                        syncError = false;
                    }
                    resetSyncError();
                    // showConfirm message if manual uploading
                    if (isUploading && unsyncedCount == 0) {
                        showToast(getString(R.string.uploading_done));
@@ -683,8 +678,7 @@ public class MainActivity extends AppCompatActivity {
                    setSyncLed(LED_RED);
                    // set error flag and label
                    String message = intent.getStringExtra("message");
                    syncErrorLabel.setText(message);
                    syncError = true;
                    setSyncError(message);
                    // showConfirm message if manual uploading
                    if (isUploading) {
                        showToast(getString(R.string.uploading_failed) + "\n" + message, Toast.LENGTH_LONG);
@@ -741,4 +735,23 @@ public class MainActivity extends AppCompatActivity {
            }
        }
    };

    /**
     * Set sync error flag and label
     * @param message Error message
     */
    private void setSyncError(String message) {
        syncError = true;
        syncErrorLabel.setText(message);
    }

    /**
     * Reset sync error flag and label
     */
    private void resetSyncError() {
        if (syncError) {
            syncErrorLabel.setText(null);
            syncError = false;
        }
    }
}
+2 −2
Original line number Diff line number Diff line
@@ -107,8 +107,8 @@ public class SettingsFragment extends PreferenceFragmentCompat {
     * On change listener to destroy session cookies if server setup has changed
     */
    private final Preference.OnPreferenceChangeListener serverSetupChanged = (preference, newValue) -> {
        // remove session cookies
        WebHelper.deauthorize();
        // update web helper settings, remove session cookies
        WebHelper.updatePreferences(preference.getContext());
        // disable live synchronization if any server preference is removed
        if (newValue.toString().trim().length() == 0) {
            disableLiveSync(preference.getContext());
+25 −4
Original line number Diff line number Diff line
@@ -87,6 +87,7 @@ class WebHelper {
    // Socket timeout in milliseconds
    static final int SOCKET_TIMEOUT = 30 * 1000;

    static boolean isAuthorized = false;

    /**
     * Constructor
@@ -94,10 +95,7 @@ class WebHelper {
     */
    WebHelper(Context ctx) {
        context = ctx;
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        user = prefs.getString(SettingsActivity.KEY_USERNAME, "NULL");
        pass = prefs.getString(SettingsActivity.KEY_PASS, "NULL");
        host = prefs.getString(SettingsActivity.KEY_HOST, "NULL").replaceAll("/+$", "");
        loadPreferences(ctx);
        userAgent = context.getString(R.string.app_name_ascii) + "/" + BuildConfig.VERSION_NAME + "; " + System.getProperty("http.agent");

        if (cookieManager == null) {
@@ -298,16 +296,39 @@ class WebHelper {
        if (error) {
            throw new WebAuthException(context.getString(R.string.e_server_response));
        }
        isAuthorized = true;
    }

    /**
     * Remove authorization by removing session cookie
     */
    static void deauthorize() {
        if (Logger.DEBUG) { Log.d(TAG, "[deauthorize]"); }
        if (cookieManager != null) {
            CookieStore store = cookieManager.getCookieStore();
            store.removeAll();
        }
        isAuthorized = false;
    }

    /**
     * Get settings from shared preferences
     * @param context Context
     */
    private static void loadPreferences(Context context) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        user = prefs.getString(SettingsActivity.KEY_USERNAME, "NULL");
        pass = prefs.getString(SettingsActivity.KEY_PASS, "NULL");
        host = prefs.getString(SettingsActivity.KEY_HOST, "NULL").replaceAll("/+$", "");
    }

    /**
     * Reload settings from shared preferences.
     * @param context Context
     */
     static void updatePreferences(Context context) {
        loadPreferences(context);
        deauthorize();
    }

    /**
+37 −21
Original line number Diff line number Diff line
@@ -43,7 +43,6 @@ public class WebSyncService extends IntentService {

    private DbAccess db;
    private WebHelper web;
    private static boolean isAuthorized = false;
    private static PendingIntent pi = null;

    final private static int FIVE_MINUTES = 1000 * 60 * 5;
@@ -74,25 +73,15 @@ public class WebSyncService extends IntentService {
    protected void onHandleIntent(Intent intent) {
        if (Logger.DEBUG) { Log.d(TAG, "[websync start]"); }

        if (pi != null) {
            // cancel pending alarm
            if (Logger.DEBUG) { Log.d(TAG, "[websync cancel alarm]"); }
            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            if (am != null) {
                am.cancel(pi);
            }
            pi = null;
        }
        cancelPending();

        if (!isAuthorized) {
        if (!WebHelper.isAuthorized) {
            try {
                web.authorize();
            } catch (WebAuthException|IOException|JSONException e) {
                handleError(e);
                return;
            }

            isAuthorized = true;
        }

        // get track id
@@ -125,11 +114,10 @@ public class WebSyncService extends IntentService {
                handleError(e);
            } catch (WebAuthException e) {
                if (Logger.DEBUG) { Log.d(TAG, "[websync auth exception: " + e + "]"); }
                isAuthorized = false;
                WebHelper.deauthorize();
                try {
                    // reauthorize and retry
                    web.authorize();
                    isAuthorized = true;
                    trackId = web.startTrack(trackName);
                    db.setTrackId(trackId);
                } catch (WebAuthException|IOException|JSONException e2) {
@@ -169,11 +157,10 @@ public class WebSyncService extends IntentService {
            if (Logger.DEBUG) {
                Log.d(TAG, "[websync auth exception: " + e + "]");
            }
            isAuthorized = false;
            WebHelper.deauthorize();
            try {
                // reauthorize and retry
                web.authorize();
                isAuthorized = true;
                doSync(trackId);
            } catch (WebAuthException | IOException | JSONException e2) {
                // schedule retry
@@ -209,6 +196,14 @@ public class WebSyncService extends IntentService {
        sendBroadcast(intent);
        // retry only if tracking is on
        if (LoggerService.isRunning()) {
            setPending();
        }
    }

    /**
     * Set pending alarm
     */
    private void setPending() {
        if (Logger.DEBUG) { Log.d(TAG, "[websync set alarm]"); }
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent syncIntent = new Intent(getApplicationContext(), WebSyncService.class);
@@ -217,6 +212,27 @@ public class WebSyncService extends IntentService {
            am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + FIVE_MINUTES, pi);
        }
    }

    /**
     * Cancel pending alarm
     */
    private void cancelPending() {
        if (hasPending()) {
            if (Logger.DEBUG) { Log.d(TAG, "[websync cancel alarm]"); }
            AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            if (am != null) {
                am.cancel(pi);
            }
            pi = null;
        }
    }

    /**
     * Is pending alarm set
     * @return True if has pending alarm set
     */
    private boolean hasPending() {
        return pi != null;
    }

    /**