From 43139c526890ef68c3ccc599be468a47a03fe002 Mon Sep 17 00:00:00 2001 From: Alex Baker Date: Tue, 10 Jun 2014 08:38:22 -0500 Subject: [PATCH] More context cleanup --- .../astrid/sync/SyncProviderUtilities.java | 128 ------------------ .../astrid/activity/ShareLinkActivity.java | 6 +- .../astrid/gtasks/GtasksFilterExposer.java | 3 +- .../gtasks/GtasksPreferenceService.java | 13 +- .../gtasks/auth/GtasksTokenValidator.java | 7 +- .../gtasks/sync/GtasksSyncV2Provider.java | 14 +- .../astrid/notes/EditNoteActivity.java | 3 +- .../astrid/service/StartupService.java | 53 ++++---- .../todoroo/astrid/service/SyncV2Service.java | 14 +- .../WidgetUpdatingCallbackWrapper.java | 9 +- .../astrid/sync/SyncProviderUtilities.java | 109 +++++++++++++++ .../todoroo/astrid/sync/SyncV2Provider.java | 4 +- .../com/todoroo/astrid/ui/QuickAddBar.java | 13 +- .../org/tasks/voice/VoiceCommandActivity.java | 4 +- 14 files changed, 176 insertions(+), 204 deletions(-) delete mode 100644 api/src/main/java/com/todoroo/astrid/sync/SyncProviderUtilities.java create mode 100644 astrid/src/main/java/com/todoroo/astrid/sync/SyncProviderUtilities.java rename {api => astrid}/src/main/java/com/todoroo/astrid/sync/SyncV2Provider.java (92%) diff --git a/api/src/main/java/com/todoroo/astrid/sync/SyncProviderUtilities.java b/api/src/main/java/com/todoroo/astrid/sync/SyncProviderUtilities.java deleted file mode 100644 index cca16688e..000000000 --- a/api/src/main/java/com/todoroo/astrid/sync/SyncProviderUtilities.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright (c) 2012 Todoroo Inc - * - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.sync; - -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; -import android.preference.PreferenceManager; - -import com.todoroo.andlib.service.ContextManager; -import com.todoroo.andlib.utility.DateUtilities; - -/** - * Sync Provider Utility class for accessing preferences - */ -abstract public class SyncProviderUtilities { - - /** - * @return your plugin identifier - */ - abstract public String getIdentifier(); - - /** - * @return key for sync interval - */ - abstract public int getSyncIntervalKey(); - - // --- implementation - - protected static final String PREF_TOKEN = "_token"; //$NON-NLS-1$ - - protected static final String PREF_LAST_SYNC = "_last_sync"; //$NON-NLS-1$ - - protected static final String PREF_LAST_ATTEMPTED_SYNC = "_last_attempted"; //$NON-NLS-1$ - - protected static final String PREF_LAST_ERROR = "_last_err"; //$NON-NLS-1$ - - protected static final String PREF_LAST_ERROR_TYPE = "_last_err_type"; //$NON-NLS-1$ - - protected static final String PREF_ONGOING = "_ongoing"; //$NON-NLS-1$ - - /** Get preferences object from the context */ - protected static SharedPreferences getPrefs() { - return PreferenceManager.getDefaultSharedPreferences(ContextManager.getContext()); - } - - /** - * @return true if we have a token for this user, false otherwise - */ - public boolean isLoggedIn() { - return getPrefs().getString(getIdentifier() + PREF_TOKEN, null) != null; - } - - /** authentication token, or null if doesn't exist */ - public String getToken() { - return getPrefs().getString(getIdentifier() + PREF_TOKEN, null); - } - - /** Sets the authentication token. Set to null to clear. */ - public void setToken(String setting) { - Editor editor = getPrefs().edit(); - editor.putString(getIdentifier() + PREF_TOKEN, setting); - editor.commit(); - } - - /** @return Last Successful Sync Date, or 0 */ - public long getLastSyncDate() { - return getPrefs().getLong(getIdentifier() + PREF_LAST_SYNC, 0); - } - - /** @return Last Attempted Sync Date, or 0 if it was successful */ - public long getLastAttemptedSyncDate() { - return getPrefs().getLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0); - } - - /** @return Last Error, or null if no last error */ - public String getLastError() { - return getPrefs().getString(getIdentifier() + PREF_LAST_ERROR, null); - } - - /** @return Last Error, or null if no last error */ - public boolean isOngoing() { - return getPrefs().getBoolean(getIdentifier() + PREF_ONGOING, false); - } - - /** Deletes Last Successful Sync Date */ - public void clearLastSyncDate() { - Editor editor = getPrefs().edit(); - editor.remove(getIdentifier() + PREF_LAST_SYNC); - editor.commit(); - } - - /** Set Last Error */ - public void setLastError(String error, String type) { - Editor editor = getPrefs().edit(); - editor.putString(getIdentifier() + PREF_LAST_ERROR, error); - editor.putString(getIdentifier() + PREF_LAST_ERROR_TYPE, type); - editor.commit(); - } - - /** Set Ongoing */ - public void stopOngoing() { - Editor editor = getPrefs().edit(); - editor.putBoolean(getIdentifier() + PREF_ONGOING, false); - editor.commit(); - } - - /** Set Last Successful Sync Date */ - public void recordSuccessfulSync() { - Editor editor = getPrefs().edit(); - editor.putLong(getIdentifier() + PREF_LAST_SYNC, DateUtilities.now() + 1000); - editor.putLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0); - editor.commit(); - } - - /** Set Last Attempted Sync Date */ - public void recordSyncStart() { - Editor editor = getPrefs().edit(); - editor.putLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, - DateUtilities.now()); - editor.remove(getIdentifier() + PREF_LAST_ERROR); - editor.remove(getIdentifier() + PREF_LAST_ERROR_TYPE); - editor.putBoolean(getIdentifier() + PREF_ONGOING, true); - editor.commit(); - } -} diff --git a/astrid/src/main/java/com/todoroo/astrid/activity/ShareLinkActivity.java b/astrid/src/main/java/com/todoroo/astrid/activity/ShareLinkActivity.java index 7e80a24c3..0b94ca171 100644 --- a/astrid/src/main/java/com/todoroo/astrid/activity/ShareLinkActivity.java +++ b/astrid/src/main/java/com/todoroo/astrid/activity/ShareLinkActivity.java @@ -3,6 +3,7 @@ */ package com.todoroo.astrid.activity; +import android.content.Context; import android.content.Intent; import android.os.Bundle; @@ -13,7 +14,7 @@ import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.ui.QuickAddBar; -import org.tasks.preferences.Preferences; +import org.tasks.injection.ForApplication; import javax.inject.Inject; @@ -28,6 +29,7 @@ public final class ShareLinkActivity extends TaskListActivity { @Inject TagService tagService; @Inject MetadataService metadataService; @Inject GCalHelper gcalHelper; + @Inject @ForApplication Context context; private String subject; private boolean handled; @@ -52,7 +54,7 @@ public final class ShareLinkActivity extends TaskListActivity { if (!handled) { Intent callerIntent = getIntent(); - Task task = QuickAddBar.basicQuickAddTask(gcalHelper, taskService, metadataService, tagService, subject); + Task task = QuickAddBar.basicQuickAddTask(context, gcalHelper, taskService, metadataService, tagService, subject); if (task != null) { task.setNotes(callerIntent.getStringExtra(Intent.EXTRA_TEXT)); taskService.save(task); diff --git a/astrid/src/main/java/com/todoroo/astrid/gtasks/GtasksFilterExposer.java b/astrid/src/main/java/com/todoroo/astrid/gtasks/GtasksFilterExposer.java index 1fa91f906..c3ff91f0c 100644 --- a/astrid/src/main/java/com/todoroo/astrid/gtasks/GtasksFilterExposer.java +++ b/astrid/src/main/java/com/todoroo/astrid/gtasks/GtasksFilterExposer.java @@ -10,7 +10,6 @@ import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.Intent; -import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import com.todoroo.andlib.data.AbstractModel; @@ -70,7 +69,7 @@ public class GtasksFilterExposer extends InjectingBroadcastReceiver implements A GtasksMetadata.LIST_ID.eq(list.getValue(GtasksList.REMOTE_ID)))).orderBy( Order.asc(Functions.cast(GtasksMetadata.ORDER, "LONG"))), //$NON-NLS-1$ values); - filter.customTaskList = new ComponentName(ContextManager.getContext(), GtasksListFragment.class); + filter.customTaskList = new ComponentName(context, GtasksListFragment.class); Bundle extras = new Bundle(); extras.putLong(GtasksListFragment.TOKEN_STORE_ID, list.getId()); filter.customExtras = extras; diff --git a/astrid/src/main/java/com/todoroo/astrid/gtasks/GtasksPreferenceService.java b/astrid/src/main/java/com/todoroo/astrid/gtasks/GtasksPreferenceService.java index 74ca19adf..b630315d5 100644 --- a/astrid/src/main/java/com/todoroo/astrid/gtasks/GtasksPreferenceService.java +++ b/astrid/src/main/java/com/todoroo/astrid/gtasks/GtasksPreferenceService.java @@ -22,13 +22,14 @@ import javax.inject.Singleton; @Singleton public class GtasksPreferenceService extends SyncProviderUtilities { - /** add-on identifier */ public static final String IDENTIFIER = "gtasks"; //$NON-NLS-1$ - private final Preferences preferences; + + private static final String PREF_DEFAULT_LIST = IDENTIFIER + "_defaultlist"; //$NON-NLS-1$ + private static final String PREF_USER_NAME = IDENTIFIER + "_user"; //$NON-NLS-1$ @Inject public GtasksPreferenceService(Preferences preferences) { - this.preferences = preferences; + super(preferences); } @Override @@ -56,10 +57,4 @@ public class GtasksPreferenceService extends SyncProviderUtilities { public void setUserName(String userName) { preferences.setString(PREF_USER_NAME, userName); } - - /** GTasks user's default list id */ - private static final String PREF_DEFAULT_LIST = IDENTIFIER + "_defaultlist"; //$NON-NLS-1$ - - /** GTasks user name */ - public static final String PREF_USER_NAME = IDENTIFIER + "_user"; //$NON-NLS-1$ } diff --git a/astrid/src/main/java/com/todoroo/astrid/gtasks/auth/GtasksTokenValidator.java b/astrid/src/main/java/com/todoroo/astrid/gtasks/auth/GtasksTokenValidator.java index 331880350..88d2cc3a0 100644 --- a/astrid/src/main/java/com/todoroo/astrid/gtasks/auth/GtasksTokenValidator.java +++ b/astrid/src/main/java/com/todoroo/astrid/gtasks/auth/GtasksTokenValidator.java @@ -20,7 +20,6 @@ import com.todoroo.astrid.gtasks.api.GoogleTasksException; import com.todoroo.astrid.gtasks.api.GtasksInvoker; import org.tasks.R; -import org.tasks.preferences.Preferences; import java.io.IOException; @@ -33,10 +32,10 @@ public class GtasksTokenValidator { private static final String TOKEN_INTENT_RECEIVED = "intent!"; //$NON-NLS-1$ private static final int REVALIDATION_TRIES = 4; - private final Preferences preferences; + private final GtasksPreferenceService preferences; @Inject - public GtasksTokenValidator(Preferences preferences) { + public GtasksTokenValidator(GtasksPreferenceService preferences) { this.preferences = preferences; } @@ -53,7 +52,7 @@ public class GtasksTokenValidator { } // If fail, token may have expired -- get a new one and return that - String accountName = preferences.getStringValue(GtasksPreferenceService.PREF_USER_NAME); + String accountName = preferences.getUserName(); Account a = accountManager.getAccountByName(accountName); if (a == null) { throw new GoogleTasksException(c.getString(R.string.gtasks_error_accountNotFound, accountName), "account-not-found"); diff --git a/astrid/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java b/astrid/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java index cd1603233..9f2223092 100644 --- a/astrid/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java +++ b/astrid/src/main/java/com/todoroo/astrid/gtasks/sync/GtasksSyncV2Provider.java @@ -126,10 +126,8 @@ public class GtasksSyncV2Provider extends SyncV2Provider { final GtasksInvoker invoker = new GtasksInvoker(gtasksTokenValidator, authToken); try { gtasksListService.updateLists(invoker.allGtaskLists()); - } catch (GoogleTasksException e) { - handler.handleException("gtasks-sync=io", e, e.getType()); //$NON-NLS-1$ } catch (IOException e) { - handler.handleException("gtasks-sync=io", e, e.toString()); //$NON-NLS-1$ + handler.handleException("gtasks-sync=io", e); //$NON-NLS-1$ } StoreObject[] lists = gtasksListService.getLists(); @@ -173,10 +171,8 @@ public class GtasksSyncV2Provider extends SyncV2Provider { task.readFromCursor(queued); try { gtasksSyncService.pushTaskOnSave(task, task.getMergedValues(), invoker); - } catch (GoogleTasksException e) { - handler.handleException("gtasks-sync-io", e, e.getType()); //$NON-NLS-1$ } catch (IOException e) { - handler.handleException("gtasks-sync-io", e, e.toString()); //$NON-NLS-1$ + handler.handleException("gtasks-sync-io", e); //$NON-NLS-1$ } } } finally { @@ -286,13 +282,9 @@ public class GtasksSyncV2Provider extends SyncV2Provider { gtasksTaskListUpdater.correctOrderAndIndentForList(listId); } - } catch (GoogleTasksException e) { - if (errorHandler != null) { - errorHandler.handleException("gtasks-sync-io", e, e.getType()); //$NON-NLS-1$ - } } catch (IOException e) { if (errorHandler != null) { - errorHandler.handleException("gtasks-sync-io", e, e.toString()); //$NON-NLS-1$ + errorHandler.handleException("gtasks-sync-io", e); //$NON-NLS-1$ } } } diff --git a/astrid/src/main/java/com/todoroo/astrid/notes/EditNoteActivity.java b/astrid/src/main/java/com/todoroo/astrid/notes/EditNoteActivity.java index c6fe68e86..f90a12c80 100644 --- a/astrid/src/main/java/com/todoroo/astrid/notes/EditNoteActivity.java +++ b/astrid/src/main/java/com/todoroo/astrid/notes/EditNoteActivity.java @@ -32,7 +32,6 @@ import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.todoroo.andlib.data.TodorooCursor; -import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.actfm.ActFmCameraModule; @@ -145,7 +144,7 @@ public class EditNoteActivity extends LinearLayout implements TimerActionListene try { fetchTask(t); } catch (SQLiteException e) { - StartupService.handleSQLiteError(ContextManager.getContext(), e); + StartupService.handleSQLiteError(fragment.getActivity(), e); } if(task == null) { return; diff --git a/astrid/src/main/java/com/todoroo/astrid/service/StartupService.java b/astrid/src/main/java/com/todoroo/astrid/service/StartupService.java index 4109ca7f9..980be9d40 100644 --- a/astrid/src/main/java/com/todoroo/astrid/service/StartupService.java +++ b/astrid/src/main/java/com/todoroo/astrid/service/StartupService.java @@ -105,19 +105,19 @@ public class StartupService { private static boolean hasStartedUp = false; /** Called when this application is started up */ - public synchronized void onStartupApplication(final Activity context) { - if(hasStartedUp || context == null) { + public synchronized void onStartupApplication(final Activity activity) { + if(hasStartedUp || activity == null) { return; } - // sets up context manager - ContextManager.setContext(context); + // sets up activity manager + ContextManager.setContext(activity); database.addListener(new AbstractDatabase.DatabaseUpdateListener() { @Override public void onDatabaseUpdated() { - Astrid2TaskProvider.notifyDatabaseModification(context); - Astrid3ContentProvider.notifyDatabaseModification(context); + Astrid2TaskProvider.notifyDatabaseModification(activity); + Astrid3ContentProvider.notifyDatabaseModification(activity); } }); @@ -125,19 +125,16 @@ public class StartupService { database.openForWriting(); checkForMissingColumns(); } catch (SQLiteException e) { - handleSQLiteError(context, e); + handleSQLiteError(activity, e); return; } // show notification if reminders are silenced - if(context instanceof Activity) { - AudioManager audioManager = (AudioManager)context.getSystemService( - Context.AUDIO_SERVICE); - if(!preferences.getBoolean(R.string.p_rmd_enabled, true)) { - Toast.makeText(context, R.string.TLA_notification_disabled, Toast.LENGTH_LONG).show(); - } else if(audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) == 0) { - Toast.makeText(context, R.string.TLA_notification_volume_low, Toast.LENGTH_LONG).show(); - } + AudioManager audioManager = (AudioManager)activity.getSystemService( Context.AUDIO_SERVICE); + if(!preferences.getBoolean(R.string.p_rmd_enabled, true)) { + Toast.makeText(activity, R.string.TLA_notification_disabled, Toast.LENGTH_LONG).show(); + } else if(audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) == 0) { + Toast.makeText(activity, R.string.TLA_notification_volume_low, Toast.LENGTH_LONG).show(); } // read current version @@ -151,7 +148,7 @@ public class StartupService { int version = 0; String versionName = "0"; //$NON-NLS-1$ try { - PackageManager pm = context.getPackageManager(); + PackageManager pm = activity.getPackageManager(); PackageInfo pi = pm.getPackageInfo(Constants.PACKAGE, PackageManager.GET_META_DATA); version = pi.versionCode; versionName = pi.versionName; @@ -162,13 +159,13 @@ public class StartupService { Log.i("astrid", "Astrid Startup. " + latestSetVersion + //$NON-NLS-1$ //$NON-NLS-2$ " => " + version); //$NON-NLS-1$ - databaseRestoreIfEmpty(context); + databaseRestoreIfEmpty(activity); // invoke upgrade service boolean justUpgraded = latestSetVersion != version; if(justUpgraded && version > 0) { if(latestSetVersion > 0) { - upgradeService.performUpgrade(context, latestSetVersion); + upgradeService.performUpgrade(activity, latestSetVersion); } preferences.setCurrentVersion(version); preferences.setCurrentVersionName(versionName); @@ -188,23 +185,23 @@ public class StartupService { gtasksPreferenceService.stopOngoing(); // perform initialization - ReminderStartupReceiver.startReminderSchedulingService(context); - BackupService.scheduleService(preferences, context); + ReminderStartupReceiver.startReminderSchedulingService(activity); + BackupService.scheduleService(preferences, activity); gtasksSyncService.initialize(); // get and display update messages if (finalLatestVersion != 0) { -// new UpdateMessageService(context).processUpdates(); +// new UpdateMessageService(activity).processUpdates(); } } }).start(); preferences.setDefaults(); - calendarAlarmScheduler.scheduleCalendarAlarms(context, false); // This needs to be after set preference defaults for the purposes of ab testing + calendarAlarmScheduler.scheduleCalendarAlarms(activity, false); // This needs to be after set preference defaults for the purposes of ab testing - showTaskKillerHelp(context); + showTaskKillerHelp(activity); hasStartedUp = true; } @@ -228,13 +225,9 @@ public class StartupService { }); } - public static void handleSQLiteError(Context context, final SQLiteException e) { - if (context instanceof Activity) { - Activity activity = (Activity) context; - DialogUtilities.okDialog(activity, activity.getString(R.string.DB_corrupted_title), - 0, activity.getString(R.string.DB_corrupted_body)); - } - e.printStackTrace(); + public static void handleSQLiteError(Activity activity, final SQLiteException e) { + log.error(e.getMessage(), e); + DialogUtilities.okDialog(activity, activity.getString(R.string.DB_corrupted_title), 0, activity.getString(R.string.DB_corrupted_body)); } private void checkForMissingColumns() { diff --git a/astrid/src/main/java/com/todoroo/astrid/service/SyncV2Service.java b/astrid/src/main/java/com/todoroo/astrid/service/SyncV2Service.java index 8d1a8bfbd..566543fd4 100644 --- a/astrid/src/main/java/com/todoroo/astrid/service/SyncV2Service.java +++ b/astrid/src/main/java/com/todoroo/astrid/service/SyncV2Service.java @@ -5,10 +5,14 @@ */ package com.todoroo.astrid.service; +import android.content.Context; + import com.todoroo.astrid.gtasks.sync.GtasksSyncV2Provider; import com.todoroo.astrid.sync.SyncResultCallback; import com.todoroo.astrid.sync.SyncV2Provider; +import org.tasks.injection.ForApplication; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -32,9 +36,11 @@ public class SyncV2Service { * for responding to sync requests through this new API. */ private final SyncV2Provider[] providers; + private final Context context; @Inject - public SyncV2Service(GtasksSyncV2Provider gtasksSyncV2Provider) { + public SyncV2Service(@ForApplication Context context, GtasksSyncV2Provider gtasksSyncV2Provider) { + this.context = context; providers = new SyncV2Provider[] { gtasksSyncV2Provider }; @@ -68,9 +74,9 @@ public class SyncV2Service { } if (active.size() > 1) { // This should never happen anymore--they can't be active at the same time, but if for some reason they both are, just use ActFm - active.get(1).synchronizeActiveTasks(manual, new WidgetUpdatingCallbackWrapper(callback)); + active.get(1).synchronizeActiveTasks(manual, new WidgetUpdatingCallbackWrapper(context, callback)); } else if (active.size() == 1) { - active.get(0).synchronizeActiveTasks(manual, new WidgetUpdatingCallbackWrapper(callback)); + active.get(0).synchronizeActiveTasks(manual, new WidgetUpdatingCallbackWrapper(context, callback)); } return true; @@ -86,7 +92,7 @@ public class SyncV2Service { public void synchronizeList(Object list, boolean manual, SyncResultCallback callback) { for(SyncV2Provider provider : providers) { if(provider.isActive()) { - provider.synchronizeList(list, manual, new WidgetUpdatingCallbackWrapper(callback)); + provider.synchronizeList(list, manual, new WidgetUpdatingCallbackWrapper(context, callback)); } } } diff --git a/astrid/src/main/java/com/todoroo/astrid/service/WidgetUpdatingCallbackWrapper.java b/astrid/src/main/java/com/todoroo/astrid/service/WidgetUpdatingCallbackWrapper.java index 8d76e6df6..fe36c6cad 100644 --- a/astrid/src/main/java/com/todoroo/astrid/service/WidgetUpdatingCallbackWrapper.java +++ b/astrid/src/main/java/com/todoroo/astrid/service/WidgetUpdatingCallbackWrapper.java @@ -1,15 +1,18 @@ package com.todoroo.astrid.service; -import com.todoroo.andlib.service.ContextManager; +import android.content.Context; + import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.sync.SyncResultCallback; import com.todoroo.astrid.widget.TasksWidget; public class WidgetUpdatingCallbackWrapper implements SyncResultCallback { + private final Context context; private SyncResultCallback wrap; - public WidgetUpdatingCallbackWrapper(SyncResultCallback wrap) { + public WidgetUpdatingCallbackWrapper(Context context, SyncResultCallback wrap) { + this.context = context; this.wrap = wrap; } @@ -23,6 +26,6 @@ public class WidgetUpdatingCallbackWrapper implements SyncResultCallback { public void finished() { wrap.finished(); TasksWidget.suppressUpdateFlag = 0L; - TasksWidget.updateWidgets(ContextManager.getContext()); + TasksWidget.updateWidgets(context); } } diff --git a/astrid/src/main/java/com/todoroo/astrid/sync/SyncProviderUtilities.java b/astrid/src/main/java/com/todoroo/astrid/sync/SyncProviderUtilities.java new file mode 100644 index 000000000..cf2cdfbf1 --- /dev/null +++ b/astrid/src/main/java/com/todoroo/astrid/sync/SyncProviderUtilities.java @@ -0,0 +1,109 @@ +/** + * Copyright (c) 2012 Todoroo Inc + * + * See the file "LICENSE" for the full license governing this code. + */ +package com.todoroo.astrid.sync; + +import com.todoroo.andlib.utility.DateUtilities; + +import org.tasks.preferences.Preferences; + +/** + * Sync Provider Utility class for accessing preferences + */ +abstract public class SyncProviderUtilities { + + protected final Preferences preferences; + + public SyncProviderUtilities(Preferences preferences) { + this.preferences = preferences; + } + + /** + * @return your plugin identifier + */ + abstract public String getIdentifier(); + + /** + * @return key for sync interval + */ + abstract public int getSyncIntervalKey(); + + // --- implementation + + protected static final String PREF_TOKEN = "_token"; //$NON-NLS-1$ + + protected static final String PREF_LAST_SYNC = "_last_sync"; //$NON-NLS-1$ + + protected static final String PREF_LAST_ATTEMPTED_SYNC = "_last_attempted"; //$NON-NLS-1$ + + protected static final String PREF_LAST_ERROR = "_last_err"; //$NON-NLS-1$ + + protected static final String PREF_ONGOING = "_ongoing"; //$NON-NLS-1$ + + /** + * @return true if we have a token for this user, false otherwise + */ + public boolean isLoggedIn() { + return preferences.getStringValue(getIdentifier() + PREF_TOKEN) != null; + } + + /** authentication token, or null if doesn't exist */ + public String getToken() { + return preferences.getStringValue(getIdentifier() + PREF_TOKEN); + } + + /** Sets the authentication token. Set to null to clear. */ + public void setToken(String setting) { + preferences.setString(getIdentifier() + PREF_TOKEN, setting); + } + + /** @return Last Successful Sync Date, or 0 */ + public long getLastSyncDate() { + return preferences.getLong(getIdentifier() + PREF_LAST_SYNC, 0); + } + + /** @return Last Attempted Sync Date, or 0 if it was successful */ + public long getLastAttemptedSyncDate() { + return preferences.getLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0); + } + + /** @return Last Error, or null if no last error */ + public String getLastError() { + return preferences.getStringValue(getIdentifier() + PREF_LAST_ERROR); + } + + /** @return Last Error, or null if no last error */ + public boolean isOngoing() { + return preferences.getBoolean(getIdentifier() + PREF_ONGOING, false); + } + + /** Deletes Last Successful Sync Date */ + public void clearLastSyncDate() { + preferences.clear(getIdentifier() + PREF_LAST_SYNC); + } + + /** Set Last Error */ + public void setLastError(String error) { + preferences.setString(getIdentifier() + PREF_LAST_ERROR, error); + } + + /** Set Ongoing */ + public void stopOngoing() { + preferences.setBoolean(getIdentifier() + PREF_ONGOING, false); + } + + /** Set Last Successful Sync Date */ + public void recordSuccessfulSync() { + preferences.setLong(getIdentifier() + PREF_LAST_SYNC, DateUtilities.now() + 1000); + preferences.setLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0); + } + + /** Set Last Attempted Sync Date */ + public void recordSyncStart() { + preferences.setLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, DateUtilities.now()); + preferences.clear(getIdentifier() + PREF_LAST_ERROR); + preferences.setBoolean(getIdentifier() + PREF_ONGOING, true); + } +} diff --git a/api/src/main/java/com/todoroo/astrid/sync/SyncV2Provider.java b/astrid/src/main/java/com/todoroo/astrid/sync/SyncV2Provider.java similarity index 92% rename from api/src/main/java/com/todoroo/astrid/sync/SyncV2Provider.java rename to astrid/src/main/java/com/todoroo/astrid/sync/SyncV2Provider.java index ed30fa2e5..5adc9f993 100644 --- a/api/src/main/java/com/todoroo/astrid/sync/SyncV2Provider.java +++ b/astrid/src/main/java/com/todoroo/astrid/sync/SyncV2Provider.java @@ -14,8 +14,8 @@ abstract public class SyncV2Provider { private static final Logger log = LoggerFactory.getLogger(SyncV2Provider.class); public class SyncExceptionHandler { - public void handleException(String tag, Exception e, String type) { - getUtilities().setLastError(e.toString(), type); + public void handleException(String tag, Exception e) { + getUtilities().setLastError(e.toString()); log.error("{}: {}", tag, e.getMessage(), e); } } diff --git a/astrid/src/main/java/com/todoroo/astrid/ui/QuickAddBar.java b/astrid/src/main/java/com/todoroo/astrid/ui/QuickAddBar.java index 7bee45ac5..fcea1f10f 100644 --- a/astrid/src/main/java/com/todoroo/astrid/ui/QuickAddBar.java +++ b/astrid/src/main/java/com/todoroo/astrid/ui/QuickAddBar.java @@ -24,7 +24,6 @@ import android.widget.LinearLayout; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; -import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.astrid.activity.AstridActivity; import com.todoroo.astrid.activity.TaskEditFragment; @@ -46,6 +45,7 @@ import com.todoroo.astrid.voice.VoiceRecognizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tasks.R; +import org.tasks.injection.ForApplication; import org.tasks.injection.Injector; import org.tasks.preferences.ActivityPreferences; @@ -79,6 +79,7 @@ public class QuickAddBar extends LinearLayout { @Inject GCalHelper gcalHelper; @Inject ActivityPreferences preferences; @Inject DateChangedAlerts dateChangedAlerts; + @Inject @ForApplication Context context; private VoiceRecognizer voiceRecognizer; @@ -283,7 +284,7 @@ public class QuickAddBar extends LinearLayout { resetControlSets(); - addToCalendar(gcalHelper, taskService, task, title); + addToCalendar(context, gcalHelper, taskService, task, title); TextView quickAdd = (TextView) findViewById(R.id.quickAddText); quickAdd.setText(""); //$NON-NLS-1$ @@ -307,13 +308,13 @@ public class QuickAddBar extends LinearLayout { } } - private static void addToCalendar(GCalHelper gcalHelper, TaskService taskService, Task task, String title) { + private static void addToCalendar(Context context, GCalHelper gcalHelper, TaskService taskService, Task task, String title) { boolean gcalCreateEventEnabled = gcalHelper.getDefaultCalendar() != null && !gcalHelper.getDefaultCalendar().equals("-1") && task.hasDueDate(); //$NON-NLS-1$ if (!TextUtils.isEmpty(title) && gcalCreateEventEnabled && TextUtils.isEmpty(task.getCalendarURI())) { Uri calendarUri = gcalHelper.createTaskEvent(task, - ContextManager.getContext().getContentResolver(), new ContentValues()); + context.getContentResolver(), new ContentValues()); task.setCalendarUri(calendarUri.toString()); task.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true); taskService.save(task); @@ -324,7 +325,7 @@ public class QuickAddBar extends LinearLayout { * Static method to quickly add tasks without all the control set nonsense. * Used from the share link activity. */ - public static Task basicQuickAddTask(GCalHelper gcalHelper, TaskService taskService, MetadataService metadataService, TagService tagService, String title) { + public static Task basicQuickAddTask(Context context, GCalHelper gcalHelper, TaskService taskService, MetadataService metadataService, TagService tagService, String title) { if (TextUtils.isEmpty(title)) { return null; } @@ -332,7 +333,7 @@ public class QuickAddBar extends LinearLayout { title = title.trim(); Task task = TaskService.createWithValues(taskService, metadataService, tagService, null, title); - addToCalendar(gcalHelper, taskService, task, title); + addToCalendar(context, gcalHelper, taskService, task, title); return task; } diff --git a/astrid/src/main/java/org/tasks/voice/VoiceCommandActivity.java b/astrid/src/main/java/org/tasks/voice/VoiceCommandActivity.java index 25c1ff5b0..c751fc7c0 100644 --- a/astrid/src/main/java/org/tasks/voice/VoiceCommandActivity.java +++ b/astrid/src/main/java/org/tasks/voice/VoiceCommandActivity.java @@ -11,6 +11,7 @@ import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.tags.TagService; import org.tasks.R; +import org.tasks.injection.ForApplication; import org.tasks.injection.InjectingActivity; import javax.inject.Inject; @@ -23,6 +24,7 @@ public class VoiceCommandActivity extends InjectingActivity { @Inject MetadataService metadataService; @Inject TagService tagService; @Inject TaskService taskService; + @Inject @ForApplication Context context; @Override protected void onCreate(Bundle savedInstanceState) { @@ -33,7 +35,7 @@ public class VoiceCommandActivity extends InjectingActivity { switch (intent.getAction()) { case "com.google.android.gm.action.AUTO_SEND": final String text = intent.getStringExtra(Intent.EXTRA_TEXT); - basicQuickAddTask(gcalHelper, taskService, metadataService, tagService, text); + basicQuickAddTask(context, gcalHelper, taskService, metadataService, tagService, text); Context context = getApplicationContext(); if (context != null) { Toast.makeText(context, getString(R.string.voice_command_added_task), Toast.LENGTH_LONG).show();