Skip to content

Commit

Permalink
Update DropBox API from v1 to v2 - fixes #552
Browse files Browse the repository at this point in the history
Remove DropBox sync API libraries and dependencies
Fixes bug where Dropbox production app_key is used in development mode
Now there should be no conflict when linking dropbox app from production and development flavours on the same device
  • Loading branch information
codinguser committed Oct 20, 2016
1 parent a30b36b commit a74a9cb
Show file tree
Hide file tree
Showing 13 changed files with 179 additions and 66 deletions.
36 changes: 26 additions & 10 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,6 @@ android {
buildConfigField "boolean", "CAN_REQUEST_RATING", "false"
buildConfigField "String", "BUILD_TIME", "\"${buildTime()}\""

if (project.hasProperty("RELEASE_DROPBOX_APP_KEY")){
resValue "string", "dropbox_app_key", RELEASE_DROPBOX_APP_KEY
resValue "string", "dropbox_app_secret", RELEASE_DROPBOX_APP_SECRET
resValue "string", "manifest_dropbox_app_key", "db-${RELEASE_DROPBOX_APP_KEY}"
} else {
resValue "string", "dropbox_app_key", "dhjh8ke9wf05948"
resValue "string", "dropbox_app_secret", "h2t9fphj3nr4wkw"
resValue "string", "manifest_dropbox_app_key", "db-dhjh8ke9wf05948"
}
testInstrumentationRunner "org.gnucash.android.test.ui.util.GnucashAndroidTestRunner"

}
Expand Down Expand Up @@ -108,17 +99,41 @@ android {
resValue "string", "app_name", "GnuCash-devel"
versionName "${versionMajor}.${versionMinor}.${versionPatch}-dev${versionBuild}_r${gitSha()}"
resValue "string", "app_version_name", "${versionName}"

resValue "string", "dropbox_app_key", "dhjh8ke9wf05948"
resValue "string", "dropbox_app_secret", "h2t9fphj3nr4wkw"
resValue "string", "manifest_dropbox_app_key", "db-dhjh8ke9wf05948"
}

beta {
resValue "string", "app_name", "GnuCash - beta"
versionName "${versionMajor}.${versionMinor}.${versionPatch}-beta${versionBuild}"
resValue "string", "app_version_name", "${versionName}"

if (project.hasProperty("RELEASE_DROPBOX_APP_KEY")){
resValue "string", "dropbox_app_key", RELEASE_DROPBOX_APP_KEY
resValue "string", "dropbox_app_secret", RELEASE_DROPBOX_APP_SECRET
resValue "string", "manifest_dropbox_app_key", "db-${RELEASE_DROPBOX_APP_KEY}"
} else {
resValue "string", "dropbox_app_key", "dhjh8ke9wf05948"
resValue "string", "dropbox_app_secret", "h2t9fphj3nr4wkw"
resValue "string", "manifest_dropbox_app_key", "db-dhjh8ke9wf05948"
}
}

production {
resValue "string", "app_name", "GnuCash"
buildConfigField "boolean", "CAN_REQUEST_RATING", "true"

if (project.hasProperty("RELEASE_DROPBOX_APP_KEY")){
resValue "string", "dropbox_app_key", RELEASE_DROPBOX_APP_KEY
resValue "string", "dropbox_app_secret", RELEASE_DROPBOX_APP_SECRET
resValue "string", "manifest_dropbox_app_key", "db-${RELEASE_DROPBOX_APP_KEY}"
} else {
resValue "string", "dropbox_app_key", "dhjh8ke9wf05948"
resValue "string", "dropbox_app_secret", "h2t9fphj3nr4wkw"
resValue "string", "manifest_dropbox_app_key", "db-dhjh8ke9wf05948"
}
}

}
Expand Down Expand Up @@ -185,7 +200,8 @@ dependencies {
'com.squareup:android-times-square:1.6.5@aar',
'com.github.techfreak:wizardpager:1.0.3',
'net.objecthunter:exp4j:0.4.7',
'org.apache.jackrabbit:jackrabbit-webdav:2.13.3'
'org.apache.jackrabbit:jackrabbit-webdav:2.13.3',
'com.dropbox.core:dropbox-core-sdk:2.1.2'
)

compile 'com.jakewharton:butterknife:8.4.0'
Expand Down
Binary file removed app/libs/dropbox-sync-sdk-android.jar
Binary file not shown.
8 changes: 1 addition & 7 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,8 @@
android:theme="@style/Theme.GnucashTheme" />
<activity android:name=".ui.settings.PreferenceActivity"
android:theme="@style/Theme.GnucashTheme" />
<activity android:name="com.dropbox.sync.android.DbxAuthActivity" />
<activity
android:name="com.dropbox.client2.android.AuthActivity"
android:name="com.dropbox.core.android.AuthActivity"
android:launchMode="singleTask"
android:configChanges="orientation|keyboard">
<intent-filter>
Expand All @@ -120,11 +119,6 @@
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name="com.dropbox.sync.android.DbxSyncService"
android:enabled="true"
android:exported="false"
android:label="Dropbox Sync" />
<service android:name=".service.ScheduledActionService"
android:exported="false"
android:label="GnuCash Android Scheduler Execution Service"/>
Expand Down
93 changes: 93 additions & 0 deletions app/src/main/java/org/gnucash/android/export/DropboxHelper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright (c) 2016 Ngewi Fet <ngewif@gmail.com>
*
* 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 org.gnucash.android.export;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.preference.PreferenceManager;

import com.dropbox.core.DbxRequestConfig;
import com.dropbox.core.android.Auth;
import com.dropbox.core.v2.DbxClientV2;

import org.gnucash.android.BuildConfig;
import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;

/**
* Helper class for commonly used DropBox methods
*/
public class DropboxHelper {

/**
* DropBox API v2 client for making requests to DropBox
*/
private static DbxClientV2 sDbxClient;
/**
* Retrieves the access token after DropBox OAuth authentication and saves it to preferences file
* <p>This method should typically by called in the {@link Activity#onResume()} method of the
* Activity or Fragment which called {@link Auth#startOAuth2Authentication(Context, String)}
* </p>
* @return Retrieved access token. Could be null if authentication failed or was canceled.
*/
public static String retrieveAndSaveToken(){
Context context = GnuCashApplication.getAppContext();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String keyAccessToken = context.getString(R.string.key_dropbox_access_token);
String accessToken = sharedPrefs.getString(keyAccessToken, null);
if (accessToken != null)
return accessToken;

accessToken = Auth.getOAuth2Token();
sharedPrefs.edit()
.putString(keyAccessToken, accessToken)
.apply();
return accessToken;
}

/**
* Return a DropBox client for making requests
* @return DropBox client for API v2
*/
public static DbxClientV2 getClient(){
if (sDbxClient != null)
return sDbxClient;

Context context = GnuCashApplication.getAppContext();
String accessToken = PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.key_dropbox_access_token), null);
if (accessToken == null)
accessToken = Auth.getOAuth2Token();

DbxRequestConfig config = new DbxRequestConfig(BuildConfig.APPLICATION_ID);
sDbxClient = new DbxClientV2(config, accessToken);

return sDbxClient;
}

/**
* Checks if the app holds an access token for dropbox
* @return {@code true} if token exists, {@code false} otherwise
*/
public static boolean hasToken(){
Context context = GnuCashApplication.getAppContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String accessToken = prefs.getString(context.getString(R.string.key_dropbox_access_token), null);
return accessToken != null;
}
}
53 changes: 26 additions & 27 deletions app/src/main/java/org/gnucash/android/export/ExportAsyncTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
Expand All @@ -36,11 +35,9 @@
import android.widget.Toast;

import com.crashlytics.android.Crashlytics;
import com.dropbox.sync.android.DbxAccountManager;
import com.dropbox.sync.android.DbxException;
import com.dropbox.sync.android.DbxFile;
import com.dropbox.sync.android.DbxFileSystem;
import com.dropbox.sync.android.DbxPath;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.v2.files.FileMetadata;
import com.dropbox.core.v2.files.Metadata;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
Expand Down Expand Up @@ -335,31 +332,33 @@ public void onResult(DriveApi.DriveContentsResult result) {
});
}

/**
* Move the exported files (in the cache directory) to Dropbox
*/
private void moveExportToDropbox() {
Log.i(TAG, "Copying exported file to DropBox");
Log.i(TAG, "Uploading exported files to DropBox");
String dropboxAppKey = mContext.getString(R.string.dropbox_app_key, BackupPreferenceFragment.DROPBOX_APP_KEY);
String dropboxAppSecret = mContext.getString(R.string.dropbox_app_secret, BackupPreferenceFragment.DROPBOX_APP_SECRET);
DbxAccountManager mDbxAcctMgr = DbxAccountManager.getInstance(mContext.getApplicationContext(),
dropboxAppKey, dropboxAppSecret);
DbxFile dbExportFile = null;
try {
DbxFileSystem dbxFileSystem = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount());
for (String exportedFilePath : mExportedFiles) {
File exportedFile = new File(exportedFilePath);
dbExportFile = dbxFileSystem.create(new DbxPath(exportedFile.getName()));
dbExportFile.writeFromExistingFile(exportedFile, false);

DbxClientV2 dbxClient = DropboxHelper.getClient();

for (String exportedFilePath : mExportedFiles) {
File exportedFile = new File(exportedFilePath);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(exportedFile);
List<Metadata> entries = dbxClient.files().listFolder("").getEntries();

FileMetadata metadata = dbxClient.files()
.uploadBuilder("/" + exportedFile.getName())
.uploadAndFinish(inputStream);
inputStream.close();
exportedFile.delete();
}
} catch (DbxException.Unauthorized unauthorized) {
Crashlytics.logException(unauthorized);
Log.e(TAG, unauthorized.getMessage());
throw new Exporter.ExporterException(mExportParams);
} catch (IOException e) {
Crashlytics.logException(e);
Log.e(TAG, e.getMessage());
} finally {
if (dbExportFile != null) {
dbExportFile.close();
} catch (IOException e) {
Crashlytics.logException(e);
Log.e(TAG, e.getMessage());
} catch (com.dropbox.core.DbxException e) {
e.printStackTrace();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,13 @@
import com.codetroopers.betterpickers.recurrencepicker.EventRecurrence;
import com.codetroopers.betterpickers.recurrencepicker.EventRecurrenceFormatter;
import com.codetroopers.betterpickers.recurrencepicker.RecurrencePickerDialogFragment;
import com.dropbox.sync.android.DbxAccountManager;
import com.dropbox.core.android.Auth;

import org.gnucash.android.R;
import org.gnucash.android.app.GnuCashApplication;
import org.gnucash.android.db.adapter.DatabaseAdapter;
import org.gnucash.android.db.adapter.ScheduledActionDbAdapter;
import org.gnucash.android.export.DropboxHelper;
import org.gnucash.android.export.ExportAsyncTask;
import org.gnucash.android.export.ExportFormat;
import org.gnucash.android.export.ExportParams;
Expand Down Expand Up @@ -235,7 +236,13 @@ public void onActivityCreated(Bundle savedInstanceState) {
getSDWritePermission();
}

@Override
@Override
public void onResume() {
super.onResume();
DropboxHelper.retrieveAndSaveToken();
}

@Override
public void onPause() {
super.onPause();
// When the user try to export sharing to 3rd party service like DropBox
Expand Down Expand Up @@ -317,10 +324,9 @@ public void onItemSelected(AdapterView<?> parent, View view, int position, long
mExportTarget = ExportParams.ExportTarget.DROPBOX;
String dropboxAppKey = getString(R.string.dropbox_app_key, BackupPreferenceFragment.DROPBOX_APP_KEY);
String dropboxAppSecret = getString(R.string.dropbox_app_secret, BackupPreferenceFragment.DROPBOX_APP_SECRET);
DbxAccountManager mDbxAccountManager = DbxAccountManager.getInstance(getActivity().getApplicationContext(),
dropboxAppKey, dropboxAppSecret);
if (!mDbxAccountManager.hasLinkedAccount()) {
mDbxAccountManager.startLink(getActivity(), 0);

if (!DropboxHelper.hasToken()) {
Auth.startOAuth2Authentication(getActivity(), dropboxAppKey);
}
break;
case 2:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.dropbox.sync.android.DbxAccountManager;
import com.dropbox.core.android.Auth;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
Expand Down Expand Up @@ -84,9 +84,12 @@ public class BackupPreferenceFragment extends PreferenceFragmentCompat implement
* Testing app secret for DropBox API
*/
final static public String DROPBOX_APP_SECRET = "h2t9fphj3nr4wkw";

/**
* String for tagging log statements
*/
public static final String LOG_TAG = "BackupPrefFragment";

private DbxAccountManager mDbxAccountManager;
/**
* Client for Google Drive Sync
*/
Expand All @@ -107,31 +110,28 @@ public void onCreate(Bundle savedInstanceState) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.title_backup_prefs);

String dropboxAppKey = getString(R.string.dropbox_app_key, DROPBOX_APP_KEY);
String dropboxAppSecret = getString(R.string.dropbox_app_secret, DROPBOX_APP_SECRET);
mDbxAccountManager = DbxAccountManager.getInstance(getActivity().getApplicationContext(),
dropboxAppKey, dropboxAppSecret);

mGoogleApiClient = getGoogleApiClient(getActivity());

}

@Override
public void onResume() {
super.onResume();
SharedPreferences manager = PreferenceManager.getDefaultSharedPreferences(getActivity());

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

//if we are returning from DropBox authentication, save the key which was generated

String keyDefaultEmail = getString(R.string.key_default_export_email);
Preference pref = findPreference(keyDefaultEmail);
String defaultEmail = manager.getString(keyDefaultEmail, null);
String defaultEmail = sharedPrefs.getString(keyDefaultEmail, null);
if (defaultEmail != null && !defaultEmail.trim().isEmpty()){
pref.setSummary(defaultEmail);
}
pref.setOnPreferenceChangeListener(this);

String keyDefaultExportFormat = getString(R.string.key_default_export_format);
pref = findPreference(keyDefaultExportFormat);
String defaultExportFormat = manager.getString(keyDefaultExportFormat, null);
String defaultExportFormat = sharedPrefs.getString(keyDefaultExportFormat, null);
if (defaultExportFormat != null && !defaultExportFormat.trim().isEmpty()){
pref.setSummary(defaultExportFormat);
}
Expand Down Expand Up @@ -225,7 +225,9 @@ public boolean onPreferenceChange(Preference preference, Object newValue) {
* @param pref DropBox Sync preference
*/
public void toggleDropboxPreference(Preference pref) {
((CheckBoxPreference)pref).setChecked(mDbxAccountManager.hasLinkedAccount());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String accessToken = prefs.getString(getString(R.string.key_dropbox_access_token), null);
((CheckBoxPreference)pref).setChecked(accessToken != null);
}

/**
Expand Down Expand Up @@ -253,10 +255,12 @@ public void toggleGoogleDrivePreference(Preference pref){
* If a link exists, it is removed else DropBox authorization is started
*/
private void toggleDropboxSync() {
if (mDbxAccountManager.hasLinkedAccount()){
mDbxAccountManager.unlink();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String accessToken = prefs.getString(getString(R.string.key_dropbox_access_token), null);
if (accessToken == null){
Auth.startOAuth2Authentication(getActivity(), getString(R.string.dropbox_app_key));
} else {
mDbxAccountManager.startLink(getActivity(), REQUEST_LINK_TO_DBX);
prefs.edit().remove(getString(R.string.key_dropbox_access_token)).apply();
}
}

Expand Down
Binary file removed app/src/main/jniLibs/armeabi-v7a/libDropboxSync.so
Binary file not shown.
Binary file removed app/src/main/jniLibs/armeabi/libDropboxSync.so
Binary file not shown.
Binary file removed app/src/main/jniLibs/mips/libDropboxSync.so
Binary file not shown.
Binary file removed app/src/main/jniLibs/x86/libDropboxSync.so
Binary file not shown.
Loading

0 comments on commit a74a9cb

Please sign in to comment.