forked from upstream-mirrors/OpenTracks
revert
This commit is contained in:
@@ -0,0 +1,380 @@
|
||||
/*
|
||||
* 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.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.util.PreferencesUtils;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
|
||||
import com.google.api.client.http.GenericUrl;
|
||||
import com.google.api.client.http.HttpResponse;
|
||||
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.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 android.accounts.Account;
|
||||
import android.content.AbstractThreadedSyncAdapter;
|
||||
import android.content.ContentProviderClient;
|
||||
import android.content.Context;
|
||||
import android.content.SyncResult;
|
||||
import android.database.Cursor;
|
||||
import android.os.Bundle;
|
||||
import android.os.RemoteException;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* SyncAdapter to sync tracks with Google Drive.
|
||||
*
|
||||
* @author Jimmy Shih
|
||||
*/
|
||||
public class SyncAdapter extends AbstractThreadedSyncAdapter {
|
||||
|
||||
private static final String TAG = SyncAdapter.class.getSimpleName();
|
||||
|
||||
// drive.about.get fields to get the largestChangeId
|
||||
private static final String ABOUT_GET_FIELDS = "largestChangeId";
|
||||
|
||||
private final Context context;
|
||||
private final MyTracksProviderUtils myTracksProviderUtils;
|
||||
private Drive drive;
|
||||
private String driveAccountName; // the account name associated with the drive
|
||||
|
||||
public SyncAdapter(Context context) {
|
||||
super(context, true);
|
||||
this.context = context;
|
||||
this.myTracksProviderUtils = MyTracksProviderUtils.Factory.get(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPerformSync(Account account, Bundle extras, String authority,
|
||||
ContentProviderClient provider, SyncResult syncResult) {
|
||||
if (!PreferencesUtils.getBoolean(
|
||||
context, R.string.drive_sync_key, PreferencesUtils.DRIVE_SYNC_DEFAULT)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (account == null) {
|
||||
return;
|
||||
}
|
||||
String googleAccount = PreferencesUtils.getString(
|
||||
context, R.string.google_account_key, PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT);
|
||||
if (googleAccount == null || googleAccount.equals(PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT)) {
|
||||
return;
|
||||
}
|
||||
if (!googleAccount.equals(account.name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
GoogleAccountCredential credential = SyncUtils.getCredential(context, account.name);
|
||||
if (credential == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (drive == null || !driveAccountName.equals(account.name)) {
|
||||
drive = SyncUtils.getDriveService(credential);
|
||||
driveAccountName = account.name;
|
||||
}
|
||||
|
||||
String folderId = SyncUtils.getMyTracksFolder(context, drive);
|
||||
if (folderId == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
long largestChangeId = PreferencesUtils.getLong(
|
||||
context, R.string.drive_largest_change_id_key);
|
||||
if (largestChangeId == PreferencesUtils.DRIVE_LARGEST_CHANGE_ID_DEFAULT) {
|
||||
performInitialSync(folderId);
|
||||
} else {
|
||||
performIncrementalSync(folderId, largestChangeId);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
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, SyncUtils.GET_KML_FILES_QUERY, folderId));
|
||||
Map<String, File> idToFileMap = new HashMap<String, File>();
|
||||
|
||||
do {
|
||||
try {
|
||||
FileList files = request.execute();
|
||||
|
||||
for (File file : files.getItems()) {
|
||||
idToFileMap.put(file.getId(), file);
|
||||
}
|
||||
request.setPageToken(files.getNextPageToken());
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "IOException", e);
|
||||
request.setPageToken(null);
|
||||
}
|
||||
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
|
||||
|
||||
// Handle new drive files
|
||||
insertNewDriveFiles(idToFileMap.values());
|
||||
PreferencesUtils.setLong(context, R.string.drive_largest_change_id_key, largestChangeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs incremental sync.
|
||||
*
|
||||
* @param folderId the folder id
|
||||
* @param largestChangeId the largest change id
|
||||
*/
|
||||
private void performIncrementalSync(String folderId, long largestChangeId) throws Exception {
|
||||
|
||||
// Move to trash in Drive all deleted tracks
|
||||
String driveDeletedList = PreferencesUtils.getString(
|
||||
context, R.string.drive_deleted_list_key, PreferencesUtils.DRIVE_DELETED_LIST_DEFAULT);
|
||||
String deletedIds[] = TextUtils.split(driveDeletedList, ";");
|
||||
for (String id : deletedIds) {
|
||||
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);
|
||||
|
||||
Map<String, File> changes = new HashMap<String, File>();
|
||||
largestChangeId = getDriveChanges(folderId, largestChangeId, changes);
|
||||
|
||||
try {
|
||||
// Get all the local tracks with drive file id
|
||||
Cursor cursor = myTracksProviderUtils.getTrackCursor(SyncUtils.DRIVE_IDS_QUERY, null, null);
|
||||
if (cursor != null && cursor.moveToFirst()) {
|
||||
do {
|
||||
Track track = myTracksProviderUtils.createTrack(cursor);
|
||||
String driveId = track.getDriveId();
|
||||
|
||||
if (changes.containsKey(driveId)) {
|
||||
|
||||
// Track has changed
|
||||
File driveFile = changes.get(driveId);
|
||||
if (driveFile == null) {
|
||||
Log.d(TAG, "Delete local track " + track.getName());
|
||||
myTracksProviderUtils.deleteTrack(track.getId());
|
||||
} else {
|
||||
mergeFiles(track, driveFile);
|
||||
}
|
||||
changes.remove(driveId);
|
||||
} else {
|
||||
|
||||
// Handle the case the track has changed
|
||||
File driveFile = drive.files().get(driveId).execute();
|
||||
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());
|
||||
}
|
||||
|
||||
// Handle new drive files
|
||||
insertNewDriveFiles(changes.values());
|
||||
PreferencesUtils.setLong(context, R.string.drive_largest_change_id_key, largestChangeId);
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "IOException", e);
|
||||
} catch (RemoteException e) {
|
||||
Log.e(TAG, "RemoteException", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts new Google Drive files.
|
||||
*
|
||||
* @param driveFiles a collection of drive files to insert
|
||||
*/
|
||||
private void insertNewDriveFiles(Collection<File> driveFiles) throws Exception {
|
||||
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);
|
||||
if (tracksIds.length == 1) {
|
||||
Track track = myTracksProviderUtils.getTrack(tracksIds[0]);
|
||||
track.setDriveId(driveFile.getId());
|
||||
track.setModifiedTime(driveFile.getModifiedDate().getValue());
|
||||
myTracksProviderUtils.updateTrack(track);
|
||||
Log.d(TAG, "Add from Google Drive " + track.getName());
|
||||
}
|
||||
// Ignore if tracksId.length != 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Drive changes in the My Tracks folder. Includes deleted files.
|
||||
*
|
||||
* @param folderId the folder id
|
||||
* @param changeId the largest change id
|
||||
* @param changes a map of drive id to file for the changes
|
||||
* @return an updated largest change id
|
||||
*/
|
||||
private long getDriveChanges(String folderId, long changeId, Map<String, File> changes) {
|
||||
try {
|
||||
Changes.List request = drive.changes().list().setStartChangeId(changeId + 1);
|
||||
do {
|
||||
ChangeList changeList = request.execute();
|
||||
long newId = changeList.getLargestChangeId().longValue();
|
||||
|
||||
for (Change change : changeList.getItems()) {
|
||||
if (change.getDeleted()) {
|
||||
changes.put(change.getFileId(), null);
|
||||
} else {
|
||||
File file = change.getFile();
|
||||
if (SyncUtils.isInFolder(file, folderId)) {
|
||||
changes.put(change.getFileId(), file.getLabels().getTrashed() ? null : file);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (newId > changeId) {
|
||||
changeId = newId;
|
||||
}
|
||||
request.setPageToken(changeList.getNextPageToken());
|
||||
} while (request.getPageToken() != null && request.getPageToken().length() > 0);
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "IOException", e);
|
||||
}
|
||||
Log.d(TAG, "Got drive changes: " + changes.size() + " - " + changeId);
|
||||
return changeId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges a track with a drive file.
|
||||
*
|
||||
* @param track the track
|
||||
* @param driveFile the drive file
|
||||
*/
|
||||
private void mergeFiles(Track track, File driveFile) throws Exception {
|
||||
long modifiedTime = track.getModifiedTime();
|
||||
long driveModifiedTime = driveFile.getModifiedDate().getValue();
|
||||
if (modifiedTime > driveModifiedTime) {
|
||||
Log.d(TAG, "Updating track change " + track.getName());
|
||||
if (!SyncUtils.updateDriveFile(context, myTracksProviderUtils, drive, driveFile, track)) {
|
||||
|
||||
// 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);
|
||||
if (inputStream == null) {
|
||||
|
||||
// TODO: Should retry if cannot download
|
||||
Log.e(TAG, "Unable to update drive change. Input stream is null for " + track.getName());
|
||||
track.setModifiedTime(driveModifiedTime);
|
||||
myTracksProviderUtils.updateTrack(track);
|
||||
} else {
|
||||
KmlImporter kmlImporter = new KmlImporter(context, track.getId());
|
||||
long[] tracksIds = kmlImporter.importFile(inputStream);
|
||||
if (tracksIds.length == 1) {
|
||||
Track newTrack = myTracksProviderUtils.getTrack(tracksIds[0]);
|
||||
newTrack.setDriveId(driveFile.getId());
|
||||
newTrack.setModifiedTime(driveModifiedTime);
|
||||
myTracksProviderUtils.updateTrack(newTrack);
|
||||
} else {
|
||||
|
||||
/*
|
||||
* 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads a drive file.
|
||||
*
|
||||
* @param driveFile the drive file
|
||||
*/
|
||||
private InputStream downloadDriveFile(File driveFile) {
|
||||
if (driveFile.getDownloadUrl() != null && driveFile.getDownloadUrl().length() > 0) {
|
||||
try {
|
||||
HttpResponse httpResponse = drive.getRequestFactory()
|
||||
.buildGetRequest(new GenericUrl(driveFile.getDownloadUrl())).execute();
|
||||
if (httpResponse != null) {
|
||||
return httpResponse.getContent();
|
||||
} else {
|
||||
Log.e(TAG, "http response is null");
|
||||
return null;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "IOException", e);
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, "Drive file download url doesn't exist: " + driveFile.getTitle());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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.sync;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.IBinder;
|
||||
|
||||
/**
|
||||
* Service to sync with Google Drive.
|
||||
*
|
||||
* @author Jimmy Shih
|
||||
*/
|
||||
public class SyncService extends Service {
|
||||
|
||||
private static final Object lock = new Object();
|
||||
|
||||
private static SyncAdapter syncAdapter = null;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
synchronized (lock) {
|
||||
if (syncAdapter == null) {
|
||||
syncAdapter = new SyncAdapter(getApplicationContext());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return syncAdapter.getSyncAdapterBinder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
/*
|
||||
* 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.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.
|
||||
*
|
||||
* @author Jimmy Shih
|
||||
*/
|
||||
public class 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 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 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels any notification to request drive permission.
|
||||
*
|
||||
* @param context the context
|
||||
*/
|
||||
public static void cancelNotification(Context context) {
|
||||
NotificationManager notificationManager = (NotificationManager) context.getSystemService(
|
||||
Context.NOTIFICATION_SERVICE);
|
||||
notificationManager.cancel(NOTIFICATION_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Syncs now for the current account.
|
||||
*
|
||||
* @param context the 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);
|
||||
for (Account account : accounts) {
|
||||
if (account.name.equals(googleAccount)) {
|
||||
ContentResolver.cancelSync(account, SYNC_AUTHORITY);
|
||||
ContentResolver.requestSync(account, SYNC_AUTHORITY, new Bundle());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables sync.
|
||||
*
|
||||
* @param account the account
|
||||
*/
|
||||
public static void disableSync(Account account) {
|
||||
ContentResolver.cancelSync(account, SYNC_AUTHORITY);
|
||||
ContentResolver.setIsSyncable(account, SYNC_AUTHORITY, 0);
|
||||
ContentResolver.setSyncAutomatically(account, SYNC_AUTHORITY, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables sync.
|
||||
*
|
||||
* @param account the account
|
||||
*/
|
||||
public static void enableSync(Account account) {
|
||||
ContentResolver.setIsSyncable(account, SYNC_AUTHORITY, 1);
|
||||
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<ParentReference> parents = new ArrayList<ParentReference>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user