From 19675f74ab1b5cdc2391b9a798ceb8663cd7ee79 Mon Sep 17 00:00:00 2001 From: Jimmy Shih Date: Fri, 25 Jan 2013 15:00:31 -0800 Subject: [PATCH] Add Sending a track to Google Drive. --- MyTracks/AndroidManifest.xml | 1 + MyTracks/res/layout/upload_result.xml | 28 ++ MyTracks/res/values/do_not_translate.xml | 1 + MyTracks/res/values/strings.xml | 26 +- .../mytracks/io/drive/SendDriveActivity.java | 74 ++++ .../mytracks/io/drive/SendDriveAsyncTask.java | 96 +++++ .../sendtogoogle/AccountChooserActivity.java | 73 ++-- .../io/sendtogoogle/PermissionCallback.java | 35 ++ .../io/sendtogoogle/UploadResultActivity.java | 14 +- .../apps/mytracks/io/sync/SyncAdapter.java | 290 +++------------ .../apps/mytracks/io/sync/SyncUtils.java | 331 +++++++++++++++++- .../settings/GoogleSettingsActivity.java | 153 +++----- .../mytracks/endtoendtest/SettingTest.java | 4 +- 13 files changed, 736 insertions(+), 390 deletions(-) create mode 100644 MyTracks/src/com/google/android/apps/mytracks/io/drive/SendDriveActivity.java create mode 100644 MyTracks/src/com/google/android/apps/mytracks/io/drive/SendDriveAsyncTask.java create mode 100644 MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/PermissionCallback.java diff --git a/MyTracks/AndroidManifest.xml b/MyTracks/AndroidManifest.xml index 32e570d0e..d515fc273 100755 --- a/MyTracks/AndroidManifest.xml +++ b/MyTracks/AndroidManifest.xml @@ -203,6 +203,7 @@ limitations under the License. + + + + + + + + + www.google.com/mobile/mytracks com.google.android.apps.mytracks.MYTRACKS_NOTIFICATIONS docs.google.com + drive.google.com google.com/fusiontables maps.google.com ANT diff --git a/MyTracks/res/values/strings.xml b/MyTracks/res/values/strings.xml index 57eb66f6e..d557d04c8 100644 --- a/MyTracks/res/values/strings.xml +++ b/MyTracks/res/values/strings.xml @@ -1721,31 +1721,29 @@ limitations under the License. Character limit: ~23 (1 line)"> Google + + This will remove any mappings between tracks and %1$s Google Drive. After removal, when sending + to Google Drive or syncing with Google Drive, all tracks will be treated as new. + Switch account - - This will remove sync with %1$s Google Drive. If sync again, all tracks will be treated as new. - - - This will sync with %1$s Google Drive ‘%2$s’ folder. All files in the folder will be - synced as new tracks. If not desired, move those files to a different folder beforehand. - - - Unable to get Google Drive permission. + Check the files in %1$s Google Drive ‘%2$s’ folder. Files not mapped to existing + tracks will be synced as new tracks. If not desired, move those files to a different folder + beforehand. next = getNextClass(isCancel); + Intent intent = IntentUtils.newIntent(this, next) + .putExtra(SendRequest.SEND_REQUEST_KEY, sendRequest); + startActivity(intent); + finish(); + } + + private Class getNextClass(boolean isCancel) { + if (isCancel) { + return UploadResultActivity.class; + } else { + if (sendRequest.isSendMaps()) { + return sendRequest.isNewMap() ? SendMapsActivity.class : ChooseMapActivity.class; + } else if (sendRequest.isSendFusionTables()) { + return SendFusionTablesActivity.class; + } else if (sendRequest.isSendDocs()) { + return SendDocsActivity.class; + } else { + return UploadResultActivity.class; + } + } + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/drive/SendDriveAsyncTask.java b/MyTracks/src/com/google/android/apps/mytracks/io/drive/SendDriveAsyncTask.java new file mode 100644 index 000000000..a125d3dcb --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/io/drive/SendDriveAsyncTask.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 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.google.android.apps.mytracks.io.drive; + +import com.google.android.apps.mytracks.content.MyTracksProviderUtils; +import com.google.android.apps.mytracks.content.Track; +import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; +import com.google.android.apps.mytracks.io.sync.SyncUtils; +import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.model.File; + +import android.accounts.Account; +import android.content.Context; +import android.util.Log; + +import java.io.IOException; + +/** + * AsyncTask to send a track to Google Drive. + * + * @author Jimmy Shih + */ +public class SendDriveAsyncTask extends AbstractSendAsyncTask { + + private static final String TAG = SendDriveAsyncTask.class.getSimpleName(); + + private final long trackId; + private final Account account; + private final Context context; + private final MyTracksProviderUtils myTracksProviderUtils; + + public SendDriveAsyncTask(SendDriveActivity activity, long trackId, Account account) { + super(activity); + this.trackId = trackId; + this.account = account; + + context = activity.getApplicationContext(); + myTracksProviderUtils = MyTracksProviderUtils.Factory.get(context); + } + + @Override + protected void closeConnection() {} + + @Override + protected void saveResult() {} + + @Override + protected boolean performTask() { + GoogleAccountCredential credential = SyncUtils.getCredential(context, account.name); + if (credential == null) { + return false; + } + + Drive drive = SyncUtils.getDriveService(credential); + String folderId = SyncUtils.getMyTracksFolder(context, drive); + if (folderId == null) { + return false; + } + + try { + Track track = myTracksProviderUtils.getTrack(trackId); + String driveId = track.getDriveId(); + if (driveId != null && !driveId.equals("")) { + File driveFile = drive.files().get(driveId).execute(); + if (SyncUtils.isDriveFileValid(driveFile, folderId)) { + return SyncUtils.updateDriveFile(context, myTracksProviderUtils, drive, driveFile, track); + } + track.setDriveId(""); + track.setModifiedTime(-1L); + myTracksProviderUtils.updateTrack(track); + } + return SyncUtils.addDriveFile(context, myTracksProviderUtils, drive, folderId, track); + } catch (IOException e) { + Log.e(TAG, "IOException", e); + return false; + } + } + + @Override + protected void invalidateToken() {} +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/AccountChooserActivity.java b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/AccountChooserActivity.java index a9fe75861..b2b9c8550 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/AccountChooserActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/AccountChooserActivity.java @@ -13,10 +13,12 @@ * License for the specific language governing permissions and limitations under * the License. */ + package com.google.android.apps.mytracks.io.sendtogoogle; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.io.docs.SendDocsActivity; +import com.google.android.apps.mytracks.io.drive.SendDriveActivity; import com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesActivity; import com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesUtils; import com.google.android.apps.mytracks.io.gdata.docs.DocumentsClient; @@ -24,6 +26,7 @@ import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient; import com.google.android.apps.mytracks.io.gdata.maps.MapsConstants; import com.google.android.apps.mytracks.io.maps.ChooseMapActivity; import com.google.android.apps.mytracks.io.maps.SendMapsActivity; +import com.google.android.apps.mytracks.io.sync.SyncUtils; import com.google.android.apps.mytracks.util.IntentUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; @@ -52,29 +55,10 @@ import java.io.IOException; */ public class AccountChooserActivity extends Activity { - private static final String TAG = AccountChooserActivity.class.getSimpleName(); - + private static final String TAG = AccountChooserActivity.class.getSimpleName(); private static final int DIALOG_NO_ACCOUNT_ID = 0; private static final int DIALOG_CHOOSER_ID = 1; - /** - * A callback after getting the permission to access a Google service. - * - * @author Jimmy Shih - */ - private interface PermissionCallback { - - /** - * To be invoked when the permission is granted. - */ - public void onSuccess(); - - /** - * To be invoked when the permission is not granted. - */ - public void onFailure(); - } - private SendRequest sendRequest; private Account[] accounts; @@ -92,7 +76,7 @@ public class AccountChooserActivity extends Activity { if (accounts.length == 1) { sendRequest.setAccount(accounts[0]); PreferencesUtils.setString(this, R.string.google_account_key, accounts[0].name); - getPermission(MapsConstants.SERVICE_NAME, sendRequest.isSendMaps(), mapsCallback); + checkDrivePermission(accounts[0].name); return; } @@ -101,13 +85,28 @@ public class AccountChooserActivity extends Activity { for (int i = 0; i < accounts.length; i++) { if (accounts[i].name.equals(googleAccount)) { sendRequest.setAccount(accounts[i]); - getPermission(MapsConstants.SERVICE_NAME, sendRequest.isSendMaps(), mapsCallback); + checkDrivePermission(accounts[i].name); return; } } showDialog(DIALOG_CHOOSER_ID); } + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch (requestCode) { + case SyncUtils.DRIVE_PERMISSION_REQUEST_CODE: + if (resultCode == Activity.RESULT_OK) { + driveCallback.onSuccess(); + } else { + driveCallback.onFailure(); + } + break; + default: + super.onActivityResult(requestCode, resultCode, data); + } + } + @Override protected Dialog onCreateDialog(int id) { switch (id) { @@ -163,7 +162,7 @@ public class AccountChooserActivity extends Activity { PreferencesUtils.setString( AccountChooserActivity.this, R.string.google_account_key, account.name); sendRequest.setAccount(account); - getPermission(MapsConstants.SERVICE_NAME, sendRequest.isSendMaps(), mapsCallback); + checkDrivePermission(account.name); } }) .setSingleChoiceItems(choices, 0, null) @@ -171,6 +170,19 @@ public class AccountChooserActivity extends Activity { .create(); } + /** + * Checks the Drive permission. + * + * @param accountName the account name + */ + private void checkDrivePermission(String accountName) { + if (sendRequest.isSendDrive()) { + SyncUtils.checkPermissionByActivity(this, accountName, driveCallback); + } else { + driveCallback.onSuccess(); + } + } + private PermissionCallback spreadsheetsCallback = new PermissionCallback() { @Override public void onSuccess() { @@ -216,6 +228,17 @@ public class AccountChooserActivity extends Activity { } }; + private PermissionCallback driveCallback = new PermissionCallback() { + @Override + public void onSuccess() { + getPermission(MapsConstants.SERVICE_NAME, sendRequest.isSendMaps(), mapsCallback); + } + @Override + public void onFailure() { + handleNoAccountPermission(); + } + }; + /** * Gets the user permission to access a service. * @@ -270,7 +293,9 @@ public class AccountChooserActivity extends Activity { */ private void startNextActivity() { Class next; - if (sendRequest.isSendMaps()) { + if (sendRequest.isSendDrive()) { + next = SendDriveActivity.class; + } else if (sendRequest.isSendMaps()) { next = sendRequest.isNewMap() ? SendMapsActivity.class : ChooseMapActivity.class; } else if (sendRequest.isSendFusionTables()) { next = SendFusionTablesActivity.class; diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/PermissionCallback.java b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/PermissionCallback.java new file mode 100644 index 000000000..775c6e67d --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/PermissionCallback.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 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.google.android.apps.mytracks.io.sendtogoogle; + +/** + * A callback after getting the permission to access a Google service. + * + * @author Jimmy Shih + */ +public interface PermissionCallback { + + /** + * To be invoked when the permission is granted. + */ + public void onSuccess(); + + /** + * To be invoked when the permission is not granted. + */ + public void onFailure(); +} \ No newline at end of file diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadResultActivity.java b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadResultActivity.java index 33366ff58..e3e590296 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadResultActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadResultActivity.java @@ -13,6 +13,7 @@ * License for the specific language governing permissions and limitations under * the License. */ + package com.google.android.apps.mytracks.io.sendtogoogle; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; @@ -90,11 +91,13 @@ public class UploadResultActivity extends FragmentActivity { } view = getLayoutInflater().inflate(R.layout.upload_result, null); + LinearLayout driveResult = (LinearLayout) view.findViewById(R.id.upload_result_drive_result); LinearLayout mapsResult = (LinearLayout) view.findViewById(R.id.upload_result_maps_result); LinearLayout fusionTablesResult = (LinearLayout) view.findViewById( R.id.upload_result_fusion_tables_result); LinearLayout docsResult = (LinearLayout) view.findViewById(R.id.upload_result_docs_result); + ImageView driveResultIcon = (ImageView) view.findViewById(R.id.upload_result_drive_result_icon); ImageView mapsResultIcon = (ImageView) view.findViewById(R.id.upload_result_maps_result_icon); ImageView fusionTablesResultIcon = (ImageView) view.findViewById( R.id.upload_result_fusion_tables_result_icon); @@ -104,6 +107,16 @@ public class UploadResultActivity extends FragmentActivity { TextView errorFooter = (TextView) view.findViewById(R.id.upload_result_error_footer); boolean hasError = false; + if (!sendRequest.isSendDrive()) { + driveResult.setVisibility(View.GONE); + } else { + if (!sendRequest.isDriveSuccess()) { + driveResultIcon.setImageResource(R.drawable.failure); + driveResultIcon.setContentDescription(getString(R.string.generic_error_title)); + hasError = true; + } + } + if (!sendRequest.isSendMaps()) { mapsResult.setVisibility(View.GONE); } else { @@ -173,5 +186,4 @@ public class UploadResultActivity extends FragmentActivity { resultDialog = builder.create(); return resultDialog; } - } diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncAdapter.java b/MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncAdapter.java index 376695f91..637c51929 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncAdapter.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncAdapter.java @@ -19,50 +19,33 @@ package com.google.android.apps.mytracks.io.sync; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.io.file.KmlImporter; -import com.google.android.apps.mytracks.io.file.TrackFileFormat; -import com.google.android.apps.mytracks.io.file.TrackWriter; -import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; -import com.google.android.gms.auth.GoogleAuthException; -import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.maps.mytracks.R; -import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; -import com.google.api.client.http.FileContent; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpResponse; -import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; import com.google.api.services.drive.Drive.Changes; import com.google.api.services.drive.Drive.Files; -import com.google.api.services.drive.Drive.Files.List; import com.google.api.services.drive.model.About; import com.google.api.services.drive.model.Change; import com.google.api.services.drive.model.ChangeList; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; -import com.google.api.services.drive.model.ParentReference; import android.accounts.Account; -import android.app.NotificationManager; -import android.app.PendingIntent; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.Context; -import android.content.Intent; import android.content.SyncResult; import android.database.Cursor; import android.os.Bundle; import android.os.RemoteException; -import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.util.Log; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Locale; @@ -76,14 +59,6 @@ import java.util.Map; public class SyncAdapter extends AbstractThreadedSyncAdapter { private static final String TAG = SyncAdapter.class.getSimpleName(); - private static final String KML_MIME_TYPE = "application/vnd.google-earth.kml+xml"; - private static final String FOLDER_MIME_TYPE = "application/vnd.google-apps.folder"; - private static final String GET_KML_FILES_QUERY = "'%s' in parents and mimeType = '" - + KML_MIME_TYPE + "' and trashed = false"; - private static final String GET_MY_TRACKS_FOLDER_QUERY = - "'root' in parents and title = '%s' and mimeType = '" + FOLDER_MIME_TYPE - + "' and trashed = false"; - private static final int NOTIFICATION_ID = 0; // drive.about.get fields to get the largestChangeId private static final String ABOUT_GET_FIELDS = "largestChangeId"; @@ -119,17 +94,17 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { return; } - GoogleAccountCredential credential = getCredential(account.name); + GoogleAccountCredential credential = SyncUtils.getCredential(context, account.name); if (credential == null) { return; } - drive = getDriveService(account, credential); - if (drive == null) { - return; + if (drive == null || !driveAccountName.equals(account.name)) { + drive = SyncUtils.getDriveService(credential); + driveAccountName = account.name; } - String folderId = getMyTracksFolder(); + String folderId = SyncUtils.getMyTracksFolder(context, drive); if (folderId == null) { return; } @@ -142,96 +117,39 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { } else { performIncrementalSync(folderId, largestChangeId); } - insertNewTracks(folderId); + // Insert tracks without driveid as new files in Drive + Cursor cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.NO_DRIVE_ID_QUERY, null, null); + long recordingTrackId = PreferencesUtils.getLong(context, R.string.recording_track_id_key); + + if (cursor != null && cursor.moveToFirst()) { + do { + Track track = myTracksProviderUtils.createTrack(cursor); + if (track.getId() == recordingTrackId) { + continue; + } + // Note, will retry on the next sync if unable to add drive file + SyncUtils.addDriveFile(context, myTracksProviderUtils, drive, folderId, track); + } while (cursor.moveToNext()); + } } catch (Exception e) { Log.e(TAG, "Exception", e); } } - /** - * Gets the google account credential for an account. - * - * @param accountName the account name - */ - private GoogleAccountCredential getCredential(String accountName) { - try { - return SyncUtils.checkDrivePermission(context, accountName); - } catch (UserRecoverableAuthException e) { - Intent intent = e.getIntent(); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_FROM_BACKGROUND); - - PendingIntent pendingIntent = PendingIntent.getActivity( - context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); - NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setAutoCancel( - true).setContentIntent(pendingIntent) - .setContentText(context.getString(R.string.permission_request_message, accountName)) - .setContentTitle(context.getString(R.string.permission_request_title)) - .setSmallIcon(android.R.drawable.ic_dialog_alert) - .setTicker(context.getString(R.string.permission_request_title)); - NotificationManager notificationManager = (NotificationManager) context.getSystemService( - Context.NOTIFICATION_SERVICE); - notificationManager.notify(NOTIFICATION_ID, builder.build()); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } catch (GoogleAuthException e) { - Log.e(TAG, "GoogleAuthException", e); - } - return null; - } - - /** - * Gets the drive service. - * - * @param account the account - * @param credential the credential - */ - private Drive getDriveService(Account account, GoogleAccountCredential credential) { - if (drive == null || !driveAccountName.equals(account.name)) { - drive = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential) - .build(); - driveAccountName = account.name; - } - return drive; - } - - /** - * Gets the My Tracks folder. - */ - private String getMyTracksFolder() { - try { - String folderName = context.getString(R.string.my_tracks_app_name); - List list = drive.files() - .list().setQ(String.format(Locale.US, GET_MY_TRACKS_FOLDER_QUERY, folderName)); - FileList result = list.execute(); - for (File file : result.getItems()) { - if (file.getTitle().equals(folderName)) { - return file.getId(); - } - } - File file = new File(); - file.setTitle(folderName); - file.setMimeType(FOLDER_MIME_TYPE); - return drive.files().insert(file).execute().getId(); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - return null; - } - } - /** * Performs initial sync. * * @param folderId the folder id */ private void performInitialSync(String folderId) throws Exception { - - // Get the largest change Id first to avoid race conditions + + // Get the largest change id first to avoid race conditions About about = drive.about().get().setFields(ABOUT_GET_FIELDS).execute(); long largestChangeId = about.getLargestChangeId(); // Get all drive files Files.List request = drive.files() - .list().setQ(String.format(Locale.US, GET_KML_FILES_QUERY, folderId)); + .list().setQ(String.format(Locale.US, SyncUtils.GET_KML_FILES_QUERY, folderId)); Map idToFileMap = new HashMap(); do { @@ -266,7 +184,10 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { context, R.string.drive_deleted_list_key, PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT); String deletedIds[] = TextUtils.split(driveDeletedList, ";"); for (String id : deletedIds) { - drive.files().trash(id).execute(); + File driveFile = drive.files().get(id).execute(); + if (SyncUtils.isDriveFileValid(driveFile, folderId)) { + drive.files().trash(id).execute(); + } } PreferencesUtils.setString( context, R.string.drive_deleted_list_key, PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT); @@ -297,7 +218,17 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { // Handle the case the track has changed File driveFile = drive.files().get(driveId).execute(); - mergeFiles(track, driveFile); + if (SyncUtils.isDriveFileValid(driveFile, folderId)) { + mergeFiles(track, driveFile); + } else { + /* + * Track has a drive id, but the drive id is no longer valid. + * E.g., the file is moved to another folder. Clear the drive id. + */ + track.setDriveId(""); + track.setModifiedTime(-1L); + myTracksProviderUtils.updateTrack(track); + } } } while (cursor.moveToNext()); } @@ -312,61 +243,6 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { } } - /** - * Inserts new tracks to Drive. - * - * @param folderId the folder id - */ - private void insertNewTracks(String folderId) throws IOException { - - // Get tracks without driveid - Cursor cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.NO_DRIVE_ID_QUERY, null, null); - long recordingTrackId = PreferencesUtils.getLong(context, R.string.recording_track_id_key); - - if (cursor != null && cursor.moveToFirst()) { - do { - Track track = myTracksProviderUtils.createTrack(cursor); - if (track.getId() == recordingTrackId) { - continue; - } - - java.io.File file = getFile(track); - if (file == null) { - Log.e(TAG, "Unable to insert new track. File is null for " + track.getName()); - continue; - } - - try { - Log.d(TAG, "Add to Google Drive " + track.getName()); - FileContent fileContent = new FileContent(KML_MIME_TYPE, file); - - // file's parent - ParentReference parentReference = new ParentReference(); - parentReference.setId(folderId); - ArrayList parents = new ArrayList(); - parents.add(parentReference); - - // file's metadata - File newMetaData = new File(); - newMetaData.setTitle(track.getName() + "." + TrackFileFormat.KML.getExtension()); - newMetaData.setMimeType(KML_MIME_TYPE); - newMetaData.setParents(parents); - - File insertedFile = drive.files().insert(newMetaData, fileContent).execute(); - if (insertedFile == null) { - Log.e(TAG, "Unable to insert new track. Inserted file is null for " + track.getName()); - } else { - track.setDriveId(insertedFile.getId()); - track.setModifiedTime(insertedFile.getModifiedDate().getValue()); - myTracksProviderUtils.updateTrack(track); - } - } finally { - file.delete(); - } - } while (cursor.moveToNext()); - } - } - /** * Inserts new Google Drive files. * @@ -376,6 +252,7 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { for (File driveFile : driveFiles) { if (driveFile != null) { InputStream inputStream = downloadDriveFile(driveFile); + // TODO: should retry if inputStream is null if (inputStream != null) { KmlImporter kmlImporter = new KmlImporter(context, -1L); long[] tracksIds = kmlImporter.importFile(inputStream); @@ -386,13 +263,14 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { myTracksProviderUtils.updateTrack(track); Log.d(TAG, "Add from Google Drive " + track.getName()); } + // Ignore if tracksId.length != 1 } } } } /** - * Gets the Drive changes. + * Gets the Drive changes in the My Tracks folder. Includes deleted files. * * @param folderId the folder id * @param changeId the largest change id @@ -411,12 +289,8 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { changes.put(change.getFileId(), null); } else { File file = change.getFile(); - if (KML_MIME_TYPE.equals(file.getMimeType())) { - for (ParentReference parentReference : file.getParents()) { - if (parentReference.getId().equals(folderId)) { - changes.put(change.getFileId(), file.getLabels().getTrashed() ? null : file); - } - } + if (SyncUtils.isInFolder(file, folderId)) { + changes.put(change.getFileId(), file.getLabels().getTrashed() ? null : file); } } } @@ -443,68 +317,38 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { long driveModifiedTime = driveFile.getModifiedDate().getValue(); if (modifiedTime > driveModifiedTime) { Log.d(TAG, "Updating track change " + track.getName()); - java.io.File file = getFile(track); + if (!SyncUtils.updateDriveFile(context, myTracksProviderUtils, drive, driveFile, track)) { - long newModifiedTime = -1L; - if (file == null) { - - // Do not retry, skip this track change - Log.e(TAG, "Unable to update track change. File is null for " + track.getName()); - newModifiedTime = driveModifiedTime; - } else { - try { - FileContent fileContent = new FileContent(KML_MIME_TYPE, file); - - driveFile.setTitle(track.getName() + "." + TrackFileFormat.KML.getExtension()); - File updatedFile = drive.files() - .update(driveFile.getId(), driveFile, fileContent).execute(); - if (updatedFile == null) { - - // Do no retry, skip this track change - Log.e(TAG, "Unable to update track change. Update file is null for " + track.getName()); - newModifiedTime = driveModifiedTime; - } else { - newModifiedTime = updatedFile.getModifiedDate().getValue(); - } - } finally { - file.delete(); - } - } - if (modifiedTime != -1L) { - track.setModifiedTime(newModifiedTime); + // TODO: Should inform the user if cannot update the file + track.setModifiedTime(driveModifiedTime); myTracksProviderUtils.updateTrack(track); } } else if (modifiedTime < driveModifiedTime) { Log.d(TAG, "Updating drive change " + track.getName()); InputStream inputStream = downloadDriveFile(driveFile); - Track newTrack = null; if (inputStream == null) { - // Do not retry, skip this drive change + // TODO: Should retry if cannot download Log.e(TAG, "Unable to update drive change. Input stream is null for " + track.getName()); - newTrack = track; + track.setModifiedTime(driveModifiedTime); + myTracksProviderUtils.updateTrack(track); } else { KmlImporter kmlImporter = new KmlImporter(context, track.getId()); long[] tracksIds = kmlImporter.importFile(inputStream); if (tracksIds.length == 1) { - newTrack = myTracksProviderUtils.getTrack(tracksIds[0]); + Track newTrack = myTracksProviderUtils.getTrack(tracksIds[0]); + newTrack.setDriveId(driveFile.getId()); + newTrack.setModifiedTime(driveModifiedTime); + myTracksProviderUtils.updateTrack(newTrack); } else { /* - * Do not retry, skip this drive change. Note at this point, the track - * waypoints and track points are deleted. + * TODO: Should revert the track back to the original. */ Log.e( TAG, "Unable to update drive change. Imported size is not 1 for " + track.getName()); - newTrack = track; } } - - if (newTrack != null) { - newTrack.setDriveId(driveFile.getId()); - newTrack.setModifiedTime(driveModifiedTime); - myTracksProviderUtils.updateTrack(newTrack); - } } } @@ -533,32 +377,4 @@ public class SyncAdapter extends AbstractThreadedSyncAdapter { return null; } } - - /** - * Gets a file from a track. - * - * @param track the track - */ - private java.io.File getFile(Track track) throws FileNotFoundException { - TrackFileFormat trackFileFormat = TrackFileFormat.KML; - - java.io.File directory = new java.io.File( - context.getCacheDir(), trackFileFormat.getExtension()); - if (!FileUtils.ensureDirectoryExists(directory)) { - Log.d(TAG, "Unable to create " + directory.getAbsolutePath()); - return null; - } - - java.io.File file = new java.io.File(directory, - FileUtils.buildUniqueFileName(directory, track.getName(), trackFileFormat.getExtension())); - - TrackWriter trackWriter = new TrackWriter( - context, myTracksProviderUtils, track, trackFileFormat, null); - trackWriter.writeTrack(new FileOutputStream(file)); - if (trackWriter.wasSuccess()) { - return file; - } - Log.d(TAG, "Unable to get file for track " + track.getName()); - return null; - } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncUtils.java b/MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncUtils.java index 3681aedf1..1706791d2 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncUtils.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/sync/SyncUtils.java @@ -17,20 +17,45 @@ package com.google.android.apps.mytracks.io.sync; import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.content.MyTracksProviderUtils; +import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; +import com.google.android.apps.mytracks.io.file.TrackFileFormat; +import com.google.android.apps.mytracks.io.file.TrackWriter; +import com.google.android.apps.mytracks.io.sendtogoogle.PermissionCallback; +import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.gms.auth.GoogleAuthException; +import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.maps.mytracks.R; +import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; +import com.google.api.client.http.FileContent; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.Drive.Files.List; import com.google.api.services.drive.DriveScopes; +import com.google.api.services.drive.model.File; +import com.google.api.services.drive.model.FileList; +import com.google.api.services.drive.model.ParentReference; import android.accounts.Account; import android.accounts.AccountManager; +import android.app.Activity; +import android.app.NotificationManager; +import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; +import android.content.Intent; import android.os.Bundle; +import android.support.v4.app.NotificationCompat; +import android.util.Log; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.io.IOException; +import java.util.ArrayList; +import java.util.Locale; /** * Utilites for Google Drive sync. @@ -39,28 +64,103 @@ import java.io.IOException; */ public class SyncUtils { - private SyncUtils() {} + public static final int DRIVE_PERMISSION_REQUEST_CODE = 1; public static final String DRIVE_IDS_QUERY = TracksColumns.DRIVEID + " IS NOT NULL AND " + TracksColumns.DRIVEID + "!=''"; public static final String NO_DRIVE_ID_QUERY = TracksColumns.DRIVEID + " IS NULL OR " + TracksColumns.DRIVEID + "=''"; - + + public static final String KML_MIME_TYPE = "application/vnd.google-earth.kml+xml"; + public static final String GET_KML_FILES_QUERY = "'%s' in parents and mimeType = '" + + KML_MIME_TYPE + "' and trashed = false"; + + private static final String FOLDER_MIME_TYPE = "application/vnd.google-apps.folder"; + private static final String GET_MY_TRACKS_FOLDER_QUERY = + "'root' in parents and title = '%s' and mimeType = '" + FOLDER_MIME_TYPE + + "' and trashed = false"; + + private static final String TAG = SyncUtils.class.getSimpleName(); private static final String SYNC_AUTHORITY = "com.google.android.maps.mytracks"; - + private static final int NOTIFICATION_ID = 0; + + private SyncUtils() {} + /** - * Checks permission to access Google Drive. + * Checks permission by an activity. Will start an activity to request + * permission with request code {@link #DRIVE_PERMISSION_REQUEST_CODE}. + * + * @param activity the activity + * @param accountName the account name + * @param permissionCallback the permission callback + */ + public static void checkPermissionByActivity(final Activity activity, final String accountName, + final PermissionCallback permissionCallback) { + Thread thread = new Thread(new Runnable() { + @Override + public void run() { + try { + getGoogleAccountCredential(activity, accountName); + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + permissionCallback.onSuccess(); + } + }); + } catch (UserRecoverableAuthException e) { + activity.startActivityForResult(e.getIntent(), DRIVE_PERMISSION_REQUEST_CODE); + } catch (IOException e) { + Log.e(TAG, "IOException", e); + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + permissionCallback.onFailure(); + } + }); + } catch (GoogleAuthException e) { + Log.e(TAG, "GoogleAuthException", e); + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + permissionCallback.onFailure(); + } + }); + } + } + }); + thread.start(); + } + + /** + * Gets the drive credential. Needs to be run in a background thread. * * @param context the context * @param accountName the account name */ - public static GoogleAccountCredential checkDrivePermission(Context context, String accountName) - throws IOException, GoogleAuthException { - GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2( - context, DriveScopes.DRIVE); - credential.setSelectedAccountName(accountName); - credential.getToken(); - return credential; + public static GoogleAccountCredential getCredential(Context context, String accountName) { + try { + return getGoogleAccountCredential(context, accountName); + } catch (UserRecoverableAuthException e) { + Intent intent = e.getIntent(); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_FROM_BACKGROUND); + + PendingIntent pendingIntent = PendingIntent.getActivity( + context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); + NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setAutoCancel( + true).setContentIntent(pendingIntent) + .setContentText(context.getString(R.string.permission_request_message, accountName)) + .setContentTitle(context.getString(R.string.permission_request_title)) + .setSmallIcon(android.R.drawable.ic_dialog_alert) + .setTicker(context.getString(R.string.permission_request_title)); + NotificationManager notificationManager = (NotificationManager) context.getSystemService( + Context.NOTIFICATION_SERVICE); + notificationManager.notify(NOTIFICATION_ID, builder.build()); + } catch (IOException e) { + Log.e(TAG, "IOException", e); + } catch (GoogleAuthException e) { + Log.e(TAG, "GoogleAuthException", e); + } + return null; } /** @@ -68,7 +168,7 @@ public class SyncUtils { * * @param context the context */ - public static void syncNow(Context context) { + public static void syncNow(Context context) { Account[] accounts = AccountManager.get(context).getAccountsByType(Constants.ACCOUNT_TYPE); String googleAccount = PreferencesUtils.getString( context, R.string.google_account_key, PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT); @@ -102,4 +202,211 @@ public class SyncUtils { ContentResolver.setSyncAutomatically(account, SYNC_AUTHORITY, true); ContentResolver.requestSync(account, SYNC_AUTHORITY, new Bundle()); } + + /** + * Gets the drive service. + * + * @param credential the credential + */ + public static Drive getDriveService(GoogleAccountCredential credential) { + return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential) + .build(); + } + + /** + * Gets the My Tracks folder. Creates one if necessary. + * + * @param context the context + * @param drive the drive + */ + public static String getMyTracksFolder(Context context, Drive drive) { + try { + String folderName = context.getString(R.string.my_tracks_app_name); + List list = drive.files() + .list().setQ(String.format(Locale.US, GET_MY_TRACKS_FOLDER_QUERY, folderName)); + FileList result = list.execute(); + for (File file : result.getItems()) { + if (file.getTitle().equals(folderName)) { + return file.getId(); + } + } + File file = new File(); + file.setTitle(folderName); + file.setMimeType(FOLDER_MIME_TYPE); + return drive.files().insert(file).execute().getId(); + } catch (IOException e) { + Log.e(TAG, "IOException", e); + return null; + } + } + + /** + * Returns true if the drive file is a kml file in the My Tracks folder and + * not trashed. + * + * @param driveFile the drive file + * @param folderId the My Tracks folder id + */ + public static boolean isDriveFileValid(File driveFile, String folderId) { + if (isInFolder(driveFile, folderId)) { + return !driveFile.getLabels().getTrashed(); + } + return false; + } + + /** + * Returns true if the drive file is a kml file in the My Tracks folder. + * + * @param driveFile the drive file + * @param folderId the My Tracks folder id + */ + public static boolean isInFolder(File driveFile, String folderId) { + if (driveFile == null) { + return false; + } + if (!SyncUtils.KML_MIME_TYPE.equals(driveFile.getMimeType())) { + return false; + } + for (ParentReference parentReference : driveFile.getParents()) { + String id = parentReference.getId(); + if (id != null && id.equals(folderId)) { + return true; + } + } + return false; + } + + /** + * Adds a Drive file. + * + * @param context the context + * @param myTracksProviderUtils the myTracksProviderUtils + * @param drive the drive + * @param folderId the folder id + * @param track the track + */ + public static boolean addDriveFile(Context context, MyTracksProviderUtils myTracksProviderUtils, + Drive drive, String folderId, Track track) throws IOException { + java.io.File file = getFile(context, myTracksProviderUtils, track); + if (file == null) { + Log.e(TAG, "Unable to add Drive file. File is null for track " + track.getName()); + return false; + } + + try { + Log.d(TAG, "Add Drive file for track " + track.getName()); + FileContent fileContent = new FileContent(KML_MIME_TYPE, file); + + // file's parent + ParentReference parentReference = new ParentReference(); + parentReference.setId(folderId); + ArrayList parents = new ArrayList(); + parents.add(parentReference); + + // file's metadata + File newMetaData = new File(); + newMetaData.setTitle(track.getName() + "." + TrackFileFormat.KML.getExtension()); + newMetaData.setMimeType(KML_MIME_TYPE); + newMetaData.setParents(parents); + + File uploadedFile = drive.files().insert(newMetaData, fileContent).execute(); + if (uploadedFile == null) { + Log.e(TAG, "Unable to add Drive file. Uploaded file is null for track " + track.getName()); + return false; + } + track.setDriveId(uploadedFile.getId()); + track.setModifiedTime(uploadedFile.getModifiedDate().getValue()); + myTracksProviderUtils.updateTrack(track); + return true; + } finally { + file.delete(); + } + } + + /** + * Updates a Drive file. + * + * @param context the context + * @param myTracksProviderUtils the myTracksProviderUtils + * @param drive the drive + * @param driveFile the drive file + * @param track the track + */ + public static boolean updateDriveFile(Context context, + MyTracksProviderUtils myTracksProviderUtils, Drive drive, File driveFile, Track track) + throws IOException { + Log.d(TAG, "Update drive file for track " + track.getName()); + java.io.File file = SyncUtils.getFile(context, myTracksProviderUtils, track); + + if (file == null) { + Log.e(TAG, "Unable to update drive file. File is null for track " + track.getName()); + return false; + } else { + try { + FileContent fileContent = new FileContent(KML_MIME_TYPE, file); + + driveFile.setTitle(track.getName() + "." + TrackFileFormat.KML.getExtension()); + File updatedFile = drive.files() + .update(driveFile.getId(), driveFile, fileContent).execute(); + if (updatedFile == null) { + Log.e(TAG, + "Unable to update drive file. Updated file is null for track " + track.getName()); + return false; + } + long newModifiedTime = updatedFile.getModifiedDate().getValue(); + track.setModifiedTime(newModifiedTime); + myTracksProviderUtils.updateTrack(track); + return true; + } finally { + file.delete(); + } + } + } + + /** + * Gets the google account credential. + * + * @param context the context + * @param accountName the account name + */ + private static GoogleAccountCredential getGoogleAccountCredential( + Context context, String accountName) throws IOException, GoogleAuthException { + GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2( + context, DriveScopes.DRIVE); + credential.setSelectedAccountName(accountName); + credential.getToken(); + return credential; + } + + /** + * Gets a file from a track. + * + * @param context the context + * @param myTracksProviderUtils the myTracksProviderUtils + * @param track the track + */ + private static java.io.File getFile( + Context context, MyTracksProviderUtils myTracksProviderUtils, Track track) + throws FileNotFoundException { + TrackFileFormat trackFileFormat = TrackFileFormat.KML; + java.io.File directory = new java.io.File( + context.getCacheDir(), trackFileFormat.getExtension()); + + if (!FileUtils.ensureDirectoryExists(directory)) { + Log.d(TAG, "Unable to create " + directory.getAbsolutePath()); + return null; + } + + java.io.File file = new java.io.File(directory, + FileUtils.buildUniqueFileName(directory, track.getName(), trackFileFormat.getExtension())); + TrackWriter trackWriter = new TrackWriter( + context, myTracksProviderUtils, track, trackFileFormat, null); + + trackWriter.writeTrack(new FileOutputStream(file)); + if (trackWriter.wasSuccess()) { + return file; + } + Log.d(TAG, "Unable to get file for track " + track.getName()); + return null; + } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/GoogleSettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/GoogleSettingsActivity.java index 7ef1c307d..66f6e0e0f 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/settings/GoogleSettingsActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/GoogleSettingsActivity.java @@ -19,11 +19,10 @@ package com.google.android.apps.mytracks.settings; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; +import com.google.android.apps.mytracks.io.sendtogoogle.PermissionCallback; import com.google.android.apps.mytracks.io.sync.SyncUtils; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; -import com.google.android.gms.auth.GoogleAuthException; -import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.maps.mytracks.R; import android.accounts.Account; @@ -32,7 +31,6 @@ import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentResolver; -import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; @@ -41,10 +39,8 @@ import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; -import android.util.Log; import android.widget.Toast; -import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -55,13 +51,23 @@ import java.util.List; */ public class GoogleSettingsActivity extends AbstractSettingsActivity { - private static final String TAG = GoogleSettingsActivity.class.getSimpleName(); - private static final int REQUEST_AUTHORIZATION = 1; - private static final String ACCOUNT_NAME_KEY = "accountName"; private static final int DIALOG_CONFIRM_SWITCH_ACCOUNT = 0; private static final int DIALOG_CONFIRM_DRIVE_SYNC_ON = 1; - private static final int DIALOG_CONFIRM_DRIVE_SYNC_OFF = 2; + + private PermissionCallback permissionCallback = new PermissionCallback() { + @Override + public void onSuccess() { + handleSync(true); + } + + @Override + public void onFailure() { + Toast.makeText( + GoogleSettingsActivity.this, R.string.send_google_no_account_message, Toast.LENGTH_LONG) + .show(); + } + }; private ListPreference googleAccountPreference; private CheckBoxPreference driveSyncPreference; @@ -93,17 +99,12 @@ public class GoogleSettingsActivity extends AbstractSettingsActivity { String googleAccount = PreferencesUtils.getString( GoogleSettingsActivity.this, R.string.google_account_key, PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT); - boolean driveSync = PreferencesUtils.getBoolean( - GoogleSettingsActivity.this, R.string.drive_sync_key, - PreferencesUtils.DRIVE_SYNC_DEFAULT); - if (driveSync && !newGoogleAccount.equals(googleAccount)) { + if (!newGoogleAccount.equals(googleAccount)) { Bundle newBundle = new Bundle(); newBundle.putString(ACCOUNT_NAME_KEY, newGoogleAccount); showDialog(DIALOG_CONFIRM_SWITCH_ACCOUNT, newBundle); - return false; } - updateUiByAccountName(newGoogleAccount); - return true; + return false; } }); @@ -111,8 +112,11 @@ public class GoogleSettingsActivity extends AbstractSettingsActivity { driveSyncPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { - showDialog( - (Boolean) newValue ? DIALOG_CONFIRM_DRIVE_SYNC_ON : DIALOG_CONFIRM_DRIVE_SYNC_OFF); + if ((Boolean) newValue) { + showDialog(DIALOG_CONFIRM_DRIVE_SYNC_ON); + } else { + handleSync(false); + } return false; } }); @@ -133,11 +137,11 @@ public class GoogleSettingsActivity extends AbstractSettingsActivity { @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { - case REQUEST_AUTHORIZATION: + case SyncUtils.DRIVE_PERMISSION_REQUEST_CODE: if (resultCode == Activity.RESULT_OK) { - handleSync(true); + permissionCallback.onSuccess(); } else { - showDriveNoPermission(this); + permissionCallback.onFailure(); } break; default: @@ -151,28 +155,19 @@ public class GoogleSettingsActivity extends AbstractSettingsActivity { switch (id) { case DIALOG_CONFIRM_SWITCH_ACCOUNT: dialog = DialogUtils.createConfirmationDialog( - this, R.string.settings_google_drive_sync_confirm_message_off, null); + this, R.string.settings_google_account_confirm_message, null); break; case DIALOG_CONFIRM_DRIVE_SYNC_ON: dialog = DialogUtils.createConfirmationDialog(this, - R.string.settings_google_drive_sync_confirm_message_on, + R.string.settings_google_drive_sync_confirm_message, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int button) { String googleAccount = PreferencesUtils.getString( GoogleSettingsActivity.this, R.string.google_account_key, PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT); - checkDrivePermission(GoogleSettingsActivity.this, googleAccount); - } - }); - break; - case DIALOG_CONFIRM_DRIVE_SYNC_OFF: - dialog = DialogUtils.createConfirmationDialog(this, - R.string.settings_google_drive_sync_confirm_message_off, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface d, int button) { - handleSync(false); + SyncUtils.checkPermissionByActivity( + GoogleSettingsActivity.this, googleAccount, permissionCallback); } }); break; @@ -191,12 +186,13 @@ public class GoogleSettingsActivity extends AbstractSettingsActivity { case DIALOG_CONFIRM_SWITCH_ACCOUNT: final String newValue = bundle.getString(ACCOUNT_NAME_KEY); alertDialog.setMessage( - getString(R.string.settings_google_drive_sync_confirm_message_off, googleAccount)); + getString(R.string.settings_google_account_confirm_message, googleAccount)); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int button) { googleAccountPreference.setValue(newValue); + clearSyncState(); handleSync(false); updateUiByAccountName(newValue); } @@ -204,18 +200,36 @@ public class GoogleSettingsActivity extends AbstractSettingsActivity { break; case DIALOG_CONFIRM_DRIVE_SYNC_ON: alertDialog.setMessage(getString( - R.string.settings_google_drive_sync_confirm_message_on, googleAccount, + R.string.settings_google_drive_sync_confirm_message, googleAccount, getString(R.string.my_tracks_app_name))); break; - case DIALOG_CONFIRM_DRIVE_SYNC_OFF: - alertDialog.setMessage( - getString(R.string.settings_google_drive_sync_confirm_message_off, googleAccount)); - break; default: } super.onPrepareDialog(id, dialog, bundle); } + /** + * Clears the sync state. + */ + private void clearSyncState() { + PreferencesUtils.setLong(this, R.string.drive_largest_change_id_key, + PreferencesUtils.DRIVE_LARGEST_CHANGE_ID_DEFAULT); + PreferencesUtils.setString( + this, R.string.drive_deleted_list_key, PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT); + + MyTracksProviderUtils myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this); + Cursor cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.DRIVE_IDS_QUERY, null, null); + if (cursor != null && cursor.moveToFirst()) { + do { + Track track = myTracksProviderUtils.createTrack(cursor); + track.setDriveId(""); + track.setModifiedTime(-1L); + track.setSharedWithMe(false); + myTracksProviderUtils.updateTrack(track); + } while (cursor.moveToNext()); + } + } + /** * Handles sync. * @@ -231,23 +245,6 @@ public class GoogleSettingsActivity extends AbstractSettingsActivity { SyncUtils.disableSync(account); } - PreferencesUtils.setLong(this, R.string.drive_largest_change_id_key, - PreferencesUtils.DRIVE_LARGEST_CHANGE_ID_DEFAULT); - PreferencesUtils.setString( - this, R.string.drive_deleted_list_key, PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT); - MyTracksProviderUtils myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this); - - Cursor cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.DRIVE_IDS_QUERY, null, null); - if (cursor != null && cursor.moveToFirst()) { - do { - Track track = myTracksProviderUtils.createTrack(cursor); - track.setDriveId(""); - track.setModifiedTime(-1L); - track.setSharedWithMe(false); - myTracksProviderUtils.updateTrack(track); - } while (cursor.moveToNext()); - } - if (value) { // Turn on sync @@ -278,46 +275,4 @@ public class GoogleSettingsActivity extends AbstractSettingsActivity { driveSyncPreference.setSummaryOn( getString(R.string.settings_google_drive_sync_summary_on, accountName)); } - - /** - * Checks Drive permission. - * - * @param context the context - * @param accountName the account name - */ - private void checkDrivePermission(final Context context, final String accountName) { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - SyncUtils.checkDrivePermission(context, accountName); - runOnUiThread(new Runnable() { - @Override - public void run() { - handleSync(true); - } - }); - } catch (UserRecoverableAuthException e) { - startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - showDriveNoPermission(context); - } catch (GoogleAuthException e) { - Log.e(TAG, "GoogleAuthException", e); - showDriveNoPermission(context); - } - } - }); - thread.start(); - } - - /** - * Shows Drive no permission toast. - * - * @param context the context - */ - private void showDriveNoPermission(Context context) { - Toast.makeText(context, R.string.settings_google_drive_sync_no_permission, Toast.LENGTH_LONG) - .show(); - } } diff --git a/MyTracksTest_E2E/src/com/google/android/apps/mytracks/endtoendtest/SettingTest.java b/MyTracksTest_E2E/src/com/google/android/apps/mytracks/endtoendtest/SettingTest.java index c9898b994..29cb33a40 100644 --- a/MyTracksTest_E2E/src/com/google/android/apps/mytracks/endtoendtest/SettingTest.java +++ b/MyTracksTest_E2E/src/com/google/android/apps/mytracks/endtoendtest/SettingTest.java @@ -398,12 +398,10 @@ public class SettingTest extends ActivityInstrumentationTestCase2