Remove unused gtasks code

Alex Baker 13 years ago
parent d67763c980
commit 744155ec26

@ -1,126 +0,0 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.todoroo.astrid.gtasks.auth;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
/**
* Choose which account to upload track information to.
*
* @author Sandor Dornbush
*/
public class AccountChooser {
/**
* The last selected account.
*/
private int selectedAccountIndex = -1;
private Account selectedAccount = null;
/**
* An interface for receiving updates once the user has selected the account.
*/
public interface AccountHandler {
/**
* Handle the account being selected.
*
* @param account The selected account or null if none could be found
*/
public void handleAccountSelected(Account account);
}
/**
* Chooses the best account to upload to.
* If no account is found the user will be alerted.
* If only one account is found that will be used.
* If multiple accounts are found the user will be allowed to choose.
*
* @param activity The parent activity
* @param handler The handler to be notified when an account has been selected
*/
public void chooseAccount(final Activity activity,
final AccountHandler handler) {
final Account[] accounts = AccountManager.get(activity)
.getAccountsByType("com.google"); //$NON-NLS-1$
if (accounts.length < 1) {
alertNoAccounts(activity, handler);
return;
}
if (accounts.length == 1) {
handler.handleAccountSelected(accounts[0]);
return;
}
// TODO This should be read out of a preference.
if (selectedAccount != null) {
handler.handleAccountSelected(selectedAccount);
return;
}
// Let the user choose.
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectedAccount = accounts[selectedAccountIndex];
handler.handleAccountSelected(selectedAccount);
}
});
builder.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.handleAccountSelected(null);
}
});
String[] choices = new String[accounts.length];
for (int i = 0; i < accounts.length; i++) {
choices[i] = accounts[i].name;
}
builder.setSingleChoiceItems(choices, selectedAccountIndex,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectedAccountIndex = which;
}
});
builder.show();
}
/**
* Puts up a dialog alerting the user that no suitable account was found.
*/
private void alertNoAccounts(final Activity activity,
final AccountHandler handler) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("No Accounts Found."); //$NON-NLS-1$
builder.setCancelable(true);
builder.setNegativeButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.handleAccountSelected(null);
}
});
builder.show();
}
}

@ -1,77 +0,0 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.todoroo.astrid.gtasks.auth;
import android.content.Intent;
/**
* This interface describes a class that will fetch and maintain a Google
* authentication token.
*
* @author Sandor Dornbush
*/
public interface AuthManager {
/**
* Initializes the login process. The user should be asked to login if they
* haven't already. The {@link Runnable} provided will be executed when the
* auth token is successfully fetched.
*
* @param whenFinished A {@link Runnable} to execute when the auth token
* has been successfully fetched and is available via
* {@link #getAuthToken()}
*/
public abstract void doLogin(Runnable whenFinished, Object o);
/**
* The {@link android.app.Activity} owner of this class should call this
* function when it gets {@link android.app.Activity#onActivityResult} with
* the request code passed into the constructor. The resultCode and results
* should come directly from the {@link android.app.Activity#onActivityResult}
* function. This function will return true if an auth token was successfully
* fetched or the process is not finished.
*
* @param resultCode The result code passed in to the
* {@link android.app.Activity}'s
* {@link android.app.Activity#onActivityResult} function
* @param results The data passed in to the {@link android.app.Activity}'s
* {@link android.app.Activity#onActivityResult} function
* @return True if the auth token was fetched or we aren't done fetching
* the auth token, or False if there was an error or the request was
* canceled
*/
public abstract boolean authResult(Intent results);
/**
* Returns the current auth token. Response may be null if no valid auth
* token has been fetched.
*
* @return The current auth token or null if no auth token has been
* fetched
*/
public abstract String getAuthToken();
/**
* Invalidates the existing auth token and request a new one. The
* {@link Runnable} provided will be executed when the new auth token is
* successfully fetched.
*
* @param whenFinished A {@link Runnable} to execute when a new auth token
* is successfully fetched
*/
public abstract void invalidateAndRefresh(Runnable whenFinished);
}

@ -1,237 +0,0 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.todoroo.astrid.gtasks.auth;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import java.io.IOException;
import java.util.ArrayList;
/**
* AuthManager keeps track of the current auth token for a user. The advantage
* over just passing around a String is that this class can renew the auth
* token if necessary, and it will change for all classes using this
* AuthManager.
*/
public class ModernAuthManager implements AuthManager {
protected static final int GET_LOGIN_REQUEST = 1;
/**
* The activity that will handle auth result callbacks.
*/
private final Activity activity;
/**
* The name of the service to authorize for.
*/
private final String service;
/**
* The most recently fetched auth token or null if none is available.
*/
private String authToken;
private final AccountManager accountManager;
private Runnable whenFinished;
/**
* AuthManager requires many of the same parameters as
* {@link com.google.android.googlelogindist.GoogleLoginServiceHelper
* #getCredentials(Activity, int, Bundle, boolean, String, boolean)}.
* The activity must have a handler in {@link Activity#onActivityResult} that
* calls {@link #authResult(int, Intent)} if the request code is the code
* given here.
*
* @param activity An activity with a handler in
* {@link Activity#onActivityResult} that calls
* {@link #authResult(int, Intent)} when {@literal code} is the request
* code
* @param code The request code to pass to
* {@link Activity#onActivityResult} when
* {@link #authResult(int, Intent)} should be called
* @param extras A {@link Bundle} of extras for
* {@link com.google.android.googlelogindist.GoogleLoginServiceHelper}
* @param requireGoogle True if the account must be a Google account
* @param service The name of the service to authenticate as
*/
public ModernAuthManager(Activity activity, String service) {
this.activity = activity;
this.service = service;
this.accountManager = AccountManager.get(activity);
}
/**
* Call this to do the initial login. The user will be asked to login if
* they haven't already. The {@link Runnable} provided will be executed
* when the auth token is successfully fetched.
*
* @param runnable A {@link Runnable} to execute when the auth token
* has been successfully fetched and is available via
* {@link #getAuthToken()}
*/
@Override
public void doLogin(final Runnable runnable, Object o) {
this.whenFinished = runnable;
if (!(o instanceof Account)) {
throw new IllegalArgumentException("FroyoAuthManager requires an account.");
}
Account account = (Account) o;
accountManager.getAuthToken(account, service, true,
new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle result = future.getResult();
// AccountManager needs user to grant permission
if (result.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = (Intent) result.get(AccountManager.KEY_INTENT);
clearNewTaskFlag(intent);
activity.startActivityForResult(intent, GET_LOGIN_REQUEST);
return;
}
authToken = result.getString(
AccountManager.KEY_AUTHTOKEN);
Log.e("gtasks-auth", "Got auth token.");
runWhenFinished();
} catch (OperationCanceledException e) {
Log.e("gtasks-auth", "Operation Canceled", e);
} catch (IOException e) {
Log.e("gtasks-auth", "IOException", e);
} catch (AuthenticatorException e) {
Log.e("gtasks-auth", "Authentication Failed", e);
}
}
}, null /* handler */);
}
private static void clearNewTaskFlag(Intent intent) {
int flags = intent.getFlags();
flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
intent.setFlags(flags);
}
/**
* The {@link Activity} passed into the constructor should call this
* function when it gets {@link Activity#onActivityResult} with the request
* code passed into the constructor. The resultCode and results should
* come directly from the {@link Activity#onActivityResult} function. This
* function will return true if an auth token was successfully fetched or
* the process is not finished.
*
* @param resultCode The result code passed in to the {@link Activity}'s
* {@link Activity#onActivityResult} function
* @param results The data passed in to the {@link Activity}'s
* {@link Activity#onActivityResult} function
* @return True if the auth token was fetched or we aren't done fetching
* the auth token, or False if there was an error or the request was
* canceled
*/
@Override
public boolean authResult(Intent results) {
if (results != null) {
authToken = results.getStringExtra(
AccountManager.KEY_AUTHTOKEN);
Log.w("google-auth", "authResult: " + authToken);
} else {
Log.e("google-auth", "No auth result results!!");
}
runWhenFinished();
return authToken != null;
}
/**
* Returns the current auth token. Response may be null if no valid auth
* token has been fetched.
*
* @return The current auth token or null if no auth token has been
* fetched
*/
@Override
public String getAuthToken() {
return authToken;
}
/**
* Invalidates the existing auth token and request a new one. The
* {@link Runnable} provided will be executed when the new auth token is
* successfully fetched.
*
* @param runnable A {@link Runnable} to execute when a new auth token
* is successfully fetched
*/
@Override
public void invalidateAndRefresh(final Runnable runnable) {
this.whenFinished = runnable;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
accountManager.invalidateAuthToken("com.google", authToken); //$NON-NLS-1$
new AccountChooser().chooseAccount(activity,
new AccountChooser.AccountHandler() {
@Override
public void handleAccountSelected(Account account) {
if (account != null) {
doLogin(whenFinished, account);
} else {
runWhenFinished();
}
}
});
}
});
}
private void runWhenFinished() {
if (whenFinished != null) {
new Thread() {
@Override
public void run() {
whenFinished.run();
}
}.start();
}
}
public static String[] getAccounts(Activity activity) {
try {
GoogleAccountManager accountManager = new GoogleAccountManager(activity);
Account[] accounts = accountManager.getAccounts();
ArrayList<String> accountNames = new ArrayList<String>();
for (Account a : accounts) {
accountNames.add(a.name);
}
return accountNames.toArray(new String[accountNames.size()]);
} catch (Exception e) {
return new String[]{}; // Empty array on failure
}
}
}

@ -1,172 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.gtasks.sync;
import com.google.api.services.tasks.model.TaskList;
import com.google.api.services.tasks.model.TaskLists;
import com.google.api.services.tasks.model.Tasks;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.sql.Query;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.gtasks.GtasksListService;
import com.todoroo.astrid.gtasks.GtasksMetadata;
import com.todoroo.astrid.gtasks.GtasksMetadataService;
import com.todoroo.astrid.gtasks.GtasksPreferenceService;
import com.todoroo.astrid.gtasks.api.GtasksInvoker;
import com.todoroo.astrid.service.AstridDependencyInjector;
import com.todoroo.astrid.service.MetadataService;
import com.todoroo.astrid.service.TaskService;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
/**
* Class to handle migration of legacy metadata (old remote ids) to new
* metadata based on the official remote ids returned by the api.
*
* @author Sam Bosley
*/
public class GtasksLegacyMigrator {
@Autowired
GtasksMetadataService gtasksMetadataService;
@Autowired
TaskService taskService;
@Autowired
MetadataService metadataService;
@Autowired
GtasksListService gtasksListService;
@Autowired
GtasksPreferenceService gtasksPreferenceService;
private final GtasksInvoker gtasksService;
private final GtasksListService listService;
private final TaskLists allLists;
static {
AstridDependencyInjector.initialize();
}
public GtasksLegacyMigrator(GtasksInvoker service, GtasksListService listService, TaskLists allLists) {
DependencyInjectionService.getInstance().inject(this);
this.gtasksService = service;
this.listService = listService;
this.allLists = allLists;
}
public void checkAndMigrateLegacy() throws IOException {
if (!gtasksPreferenceService.migrationHasOccurred()) {
//Fetch all tasks that have associated gtask metadata
String defaultListTitle = gtasksListService.getListName(Preferences.getStringValue(GtasksPreferenceService.PREF_DEFAULT_LIST));
String defaultListId = null;
TodorooCursor<Task> allTasksWithGtaskData = taskService.query(Query.select(Task.PROPERTIES).
where(Task.ID.in(
Query.select(Metadata.TASK).from(Metadata.TABLE).
where(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY)))));
try {
if (allTasksWithGtaskData.getCount() > 0) {
//Fetch all remote tasks from all remote lists (this may be an expensive operation)
//and map their titles to their real remote ids
HashMap<String, String> taskAndListTitlesToRemoteTaskIds = new HashMap<String, String>();
List<TaskList> items = allLists.getItems();
for (TaskList list : items) {
if (list.getTitle().equals(defaultListTitle)) {
defaultListId = list.getId();
}
Tasks allTasks = gtasksService.getAllGtasksFromListId(list.getId(), false, false, 0);
List<com.google.api.services.tasks.model.Task> tasksItems = allTasks.getItems();
if (tasksItems != null) {
for (com.google.api.services.tasks.model.Task t : tasksItems) {
String key = constructKeyFromTitles(t.getTitle(), list.getTitle());
taskAndListTitlesToRemoteTaskIds.put(key, t.getId());
}
}
}
if (defaultListId == null) {
com.google.api.services.tasks.model.TaskList defaultList = gtasksService.getGtaskList("@default"); //$NON-NLS-1$
defaultListId = defaultList.getId();
}
Preferences.setString(GtasksPreferenceService.PREF_DEFAULT_LIST, defaultListId);
//For each local task, check to see if its title paired with any list title has a match in the map
for (allTasksWithGtaskData.moveToFirst(); !allTasksWithGtaskData.isAfterLast(); allTasksWithGtaskData.moveToNext()) {
GtasksTaskContainer container = gtasksMetadataService.readTaskAndMetadata(allTasksWithGtaskData);
// memorize the original listname for the case that the task is not matched,
// then it should at least be recreated in the correct list
String originalListName = gtasksListService.getListName(
container.gtaskMetadata.getValue(GtasksMetadata.LIST_ID));
String originalListId = null;
//Search through lists to see if one of them has match
String taskTitle = container.task.getValue(Task.TITLE);
boolean foundMatch = false;
items = allLists.getItems();
for (TaskList list : items) {
String expectedKey = constructKeyFromTitles(taskTitle, list.getTitle());
// save the new id of the current list
// if it matches the listname of the current task
if (list.getTitle() != null && list.getTitle().equals(originalListName)) {
originalListId = list.getId();
}
if (taskAndListTitlesToRemoteTaskIds.containsKey(expectedKey)) {
foundMatch = true;
String newRemoteTaskId = taskAndListTitlesToRemoteTaskIds.get(expectedKey);
String newRemoteListId = list.getId();
container.gtaskMetadata.setValue(GtasksMetadata.ID, newRemoteTaskId);
container.gtaskMetadata.setValue(GtasksMetadata.LIST_ID, newRemoteListId);
gtasksMetadataService.saveTaskAndMetadata(container);
break;
}
}
if (!foundMatch) {
//For non-matches, make the task look newly created
container.gtaskMetadata = GtasksMetadata.createEmptyMetadata(container.task.getId());
container.gtaskMetadata.setValue(GtasksMetadata.ID, ""); //$NON-NLS-1$
if (originalListId != null) {
// set the list-id based on the original listname, saved above during for-loop
container.gtaskMetadata.setValue(GtasksMetadata.LIST_ID, originalListId);
} else {
// remote list or local list was renamed, so put this unmatched task in the default list
container.gtaskMetadata.setValue(GtasksMetadata.LIST_ID, defaultListId);
}
gtasksMetadataService.saveTaskAndMetadata(container);
break;
}
}
}
// migrate the list-id's afterwards, so that we can put the non-matched tasks in their original lists
// if the listnames didnt change before migration (defaultlist otherwise)
listService.migrateListIds(allLists);
} finally {
allTasksWithGtaskData.close();
}
Preferences.setBoolean(GtasksPreferenceService.PREF_MIGRATION_HAS_OCCURRED, true); //Record successful migration
}
}
private String constructKeyFromTitles(String taskTitle, String listTitle) {
return taskTitle + "//" + listTitle; //$NON-NLS-1$
}
}
Loading…
Cancel
Save