diff --git a/.gitmodules b/.gitmodules
index ca01e1ac6..064be5619 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -28,3 +28,6 @@
[submodule "extern/minidns"]
path = extern/minidns
url = https://github.com/open-keychain/minidns.git
+[submodule "extern/TokenAutoComplete"]
+ path = extern/TokenAutoComplete
+ url = https://github.com/open-keychain/TokenAutoComplete
diff --git a/OpenKeychain/build.gradle b/OpenKeychain/build.gradle
index f42787806..88706f1f9 100644
--- a/OpenKeychain/build.gradle
+++ b/OpenKeychain/build.gradle
@@ -18,6 +18,7 @@ dependencies {
compile project(':extern:SuperToasts:supertoasts')
compile project(':extern:minidns')
compile project(':extern:KeybaseLib:Lib')
+ compile project(':extern:TokenAutoComplete:library')
}
diff --git a/OpenKeychain/src/main/AndroidManifest.xml b/OpenKeychain/src/main/AndroidManifest.xml
index 7af9d895f..de559fe16 100644
--- a/OpenKeychain/src/main/AndroidManifest.xml
+++ b/OpenKeychain/src/main/AndroidManifest.xml
@@ -49,6 +49,9 @@
android:name="android.hardware.touchscreen"
android:required="false" />
+
+
+
@@ -152,12 +155,13 @@
-
+
+
@@ -202,8 +206,8 @@
-
+
@@ -223,7 +227,7 @@
-
+
@@ -644,6 +648,12 @@
android:resource="@xml/custom_pgp_contacts_structure" />
+
+
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/Constants.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/Constants.java
index 33ab52bca..b679ef210 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/Constants.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/Constants.java
@@ -27,6 +27,8 @@ import org.sufficientlysecure.keychain.ui.DecryptActivity;
import org.sufficientlysecure.keychain.ui.EncryptActivity;
import org.sufficientlysecure.keychain.ui.KeyListActivity;
+import java.io.File;
+
public final class Constants {
public static final boolean DEBUG = BuildConfig.DEBUG;
@@ -51,10 +53,11 @@ public final class Constants {
public static boolean KITKAT = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
+ public static int TEMPFILE_TTL = 24*60*60*1000; // 1 day
+
public static final class Path {
- public static final String APP_DIR = Environment.getExternalStorageDirectory()
- + "/OpenKeychain";
- public static final String APP_DIR_FILE = APP_DIR + "/export.asc";
+ public static final File APP_DIR = new File(Environment.getExternalStorageDirectory(), "OpenKeychain");
+ public static final File APP_DIR_FILE = new File(APP_DIR, "export.asc");
}
public static final class Pref {
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java
index e70b134aa..181470757 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java
@@ -28,10 +28,10 @@ import android.os.Environment;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.sufficientlysecure.keychain.helper.Preferences;
import org.sufficientlysecure.keychain.helper.TlsHelper;
+import org.sufficientlysecure.keychain.provider.TemporaryStorageProvider;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.PRNGFixes;
-import java.io.File;
import java.security.Provider;
import java.security.Security;
@@ -73,8 +73,7 @@ public class KeychainApplication extends Application {
// Create APG directory on sdcard if not existing
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
- File dir = new File(Constants.Path.APP_DIR);
- if (!dir.exists() && !dir.mkdirs()) {
+ if (!Constants.Path.APP_DIR.exists() && !Constants.Path.APP_DIR.mkdirs()) {
// ignore this for now, it's not crucial
// that the directory doesn't exist at this point
}
@@ -89,6 +88,8 @@ public class KeychainApplication extends Application {
Preferences.getPreferences(this).updateKeyServers();
TlsHelper.addStaticCA("pool.sks-keyservers.net", getAssets(), "sks-keyservers.netCA.cer");
+
+ TemporaryStorageProvider.cleanUp(this);
}
public static void setupAccountAsNeeded(Context context) {
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/ContactHelper.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/ContactHelper.java
index e639824ec..8fed40a86 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/ContactHelper.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/ContactHelper.java
@@ -21,6 +21,8 @@ import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.*;
import android.database.Cursor;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
@@ -33,6 +35,7 @@ import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.util.Log;
+import java.io.InputStream;
import java.util.*;
public class ContactHelper {
@@ -60,6 +63,8 @@ public class ContactHelper {
ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?";
public static final String ID_SELECTION = ContactsContract.RawContacts._ID + "=?";
+ private static final Map photoCache = new HashMap();
+
public static List getPossibleUserEmails(Context context) {
Set accountMails = getAccountEmails(context);
accountMails.addAll(getMainProfileContactEmails(context));
@@ -232,6 +237,30 @@ public class ContactHelper {
return null;
}
+ public static Bitmap photoFromFingerprint(ContentResolver contentResolver, String fingerprint) {
+ if (fingerprint == null) return null;
+ if (!photoCache.containsKey(fingerprint)) {
+ photoCache.put(fingerprint, loadPhotoFromFingerprint(contentResolver, fingerprint));
+ }
+ return photoCache.get(fingerprint);
+ }
+
+ private static Bitmap loadPhotoFromFingerprint(ContentResolver contentResolver, String fingerprint) {
+ if (fingerprint == null) return null;
+ try {
+ int rawContactId = findRawContactId(contentResolver, fingerprint);
+ if (rawContactId == -1) return null;
+ Uri rawContactUri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawContactId);
+ Uri contactUri = ContactsContract.RawContacts.getContactLookupUri(contentResolver, rawContactUri);
+ InputStream photoInputStream =
+ ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, contactUri);
+ if (photoInputStream == null) return null;
+ return BitmapFactory.decodeStream(photoInputStream);
+ } catch (Throwable ignored) {
+ return null;
+ }
+ }
+
/**
* Write the current Keychain to the contact db
*/
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java
index 16ef28311..ae9438148 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/ExportHelper.java
@@ -30,7 +30,6 @@ import android.widget.Toast;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
-import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.service.KeychainIntentService;
@@ -39,9 +38,10 @@ import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment;
import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment;
import org.sufficientlysecure.keychain.util.Log;
+import java.io.File;
+
public class ExportHelper {
- protected FileDialogFragment mFileDialog;
- protected String mExportFilename;
+ protected File mExportFile;
ActionBarActivity mActivity;
@@ -68,47 +68,30 @@ public class ExportHelper {
/**
* Show dialog where to export keys
*/
- public void showExportKeysDialog(final long[] masterKeyIds, final String exportFilename,
+ public void showExportKeysDialog(final long[] masterKeyIds, final File exportFile,
final boolean showSecretCheckbox) {
- mExportFilename = exportFilename;
+ mExportFile = exportFile;
- // Message is received after file is selected
- Handler returnHandler = new Handler() {
+ String title = null;
+ if (masterKeyIds == null) {
+ // export all keys
+ title = mActivity.getString(R.string.title_export_keys);
+ } else {
+ // export only key specified at data uri
+ title = mActivity.getString(R.string.title_export_key);
+ }
+
+ String message = mActivity.getString(R.string.specify_file_to_export_to);
+ String checkMsg = showSecretCheckbox ?
+ mActivity.getString(R.string.also_export_secret_keys) : null;
+
+ FileHelper.saveFile(new FileHelper.FileDialogCallback() {
@Override
- public void handleMessage(Message message) {
- if (message.what == FileDialogFragment.MESSAGE_OKAY) {
- Bundle data = message.getData();
- mExportFilename = data.getString(FileDialogFragment.MESSAGE_DATA_FILENAME);
-
- exportKeys(masterKeyIds, data.getBoolean(FileDialogFragment.MESSAGE_DATA_CHECKED));
- }
+ public void onFileSelected(File file, boolean checked) {
+ mExportFile = file;
+ exportKeys(masterKeyIds, checked);
}
- };
-
- // Create a new Messenger for the communication back
- final Messenger messenger = new Messenger(returnHandler);
-
- DialogFragmentWorkaround.INTERFACE.runnableRunDelayed(new Runnable() {
- public void run() {
- String title = null;
- if (masterKeyIds == null) {
- // export all keys
- title = mActivity.getString(R.string.title_export_keys);
- } else {
- // export only key specified at data uri
- title = mActivity.getString(R.string.title_export_key);
- }
-
- String message = mActivity.getString(R.string.specify_file_to_export_to);
- String checkMsg = showSecretCheckbox ?
- mActivity.getString(R.string.also_export_secret_keys) : null;
-
- mFileDialog = FileDialogFragment.newInstance(messenger, title, message,
- exportFilename, checkMsg);
-
- mFileDialog.show(mActivity.getSupportFragmentManager(), "fileDialog");
- }
- });
+ }, mActivity.getSupportFragmentManager() ,title, message, exportFile, checkMsg);
}
/**
@@ -125,7 +108,7 @@ public class ExportHelper {
// fill values for this action
Bundle data = new Bundle();
- data.putString(KeychainIntentService.EXPORT_FILENAME, mExportFilename);
+ data.putString(KeychainIntentService.EXPORT_FILENAME, mExportFile.getAbsolutePath());
data.putBoolean(KeychainIntentService.EXPORT_SECRET, exportSecret);
if (masterKeyIds == null) {
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/FileHelper.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/FileHelper.java
index e0c94b947..615d89e0c 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/FileHelper.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/FileHelper.java
@@ -23,15 +23,22 @@ import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
+import android.graphics.Bitmap;
+import android.graphics.Point;
import android.net.Uri;
-import android.os.Build;
-import android.os.Environment;
+import android.os.*;
+import android.provider.DocumentsContract;
+import android.provider.OpenableColumns;
import android.support.v4.app.Fragment;
+import android.support.v4.app.FragmentManager;
import android.widget.Toast;
-
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
-import org.sufficientlysecure.keychain.util.Log;
+import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround;
+import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment;
+
+import java.io.File;
+import java.text.DecimalFormat;
public class FileHelper {
@@ -55,25 +62,18 @@ public class FileHelper {
* Opens the preferred installed file manager on Android and shows a toast if no manager is
* installed.
*
- * @param activity
- * @param filename default selected file, not supported by all file managers
+ * @param fragment
+ * @param last default selected Uri, not supported by all file managers
* @param mimeType can be text/plain for example
* @param requestCode requestCode used to identify the result coming back from file manager to
* onActivityResult() in your activity
*/
- public static void openFile(Activity activity, String filename, String mimeType, int requestCode) {
- Intent intent = buildFileIntent(filename, mimeType);
+ public static void openFile(Fragment fragment, Uri last, String mimeType, int requestCode) {
+ Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
+ intent.addCategory(Intent.CATEGORY_OPENABLE);
- try {
- activity.startActivityForResult(intent, requestCode);
- } catch (ActivityNotFoundException e) {
- // No compatible file manager was found.
- Toast.makeText(activity, R.string.no_filemanager_installed, Toast.LENGTH_SHORT).show();
- }
- }
-
- public static void openFile(Fragment fragment, String filename, String mimeType, int requestCode) {
- Intent intent = buildFileIntent(filename, mimeType);
+ intent.setData(last);
+ intent.setType(mimeType);
try {
fragment.startActivityForResult(intent, requestCode);
@@ -84,86 +84,147 @@ public class FileHelper {
}
}
+ public static void saveFile(final FileDialogCallback callback, final FragmentManager fragmentManager,
+ final String title, final String message, final File defaultFile,
+ final String checkMsg) {
+ // Message is received after file is selected
+ Handler returnHandler = new Handler() {
+ @Override
+ public void handleMessage(Message message) {
+ if (message.what == FileDialogFragment.MESSAGE_OKAY) {
+ callback.onFileSelected(
+ new File(message.getData().getString(FileDialogFragment.MESSAGE_DATA_FILE)),
+ message.getData().getBoolean(FileDialogFragment.MESSAGE_DATA_CHECKED));
+ }
+ }
+ };
+
+ // Create a new Messenger for the communication back
+ final Messenger messenger = new Messenger(returnHandler);
+
+ DialogFragmentWorkaround.INTERFACE.runnableRunDelayed(new Runnable() {
+ @Override
+ public void run() {
+ FileDialogFragment fileDialog = FileDialogFragment.newInstance(messenger, title, message,
+ defaultFile, checkMsg);
+
+ fileDialog.show(fragmentManager, "fileDialog");
+ }
+ });
+ }
+
+ public static void saveFile(Fragment fragment, String title, String message, File defaultFile, int requestCode) {
+ saveFile(fragment, title, message, defaultFile, requestCode, null);
+ }
+
+ public static void saveFile(final Fragment fragment, String title, String message, File defaultFile,
+ final int requestCode, String checkMsg) {
+ saveFile(new FileDialogCallback() {
+ @Override
+ public void onFileSelected(File file, boolean checked) {
+ Intent intent = new Intent();
+ intent.setData(Uri.fromFile(file));
+ fragment.onActivityResult(requestCode, Activity.RESULT_OK, intent);
+ }
+ }, fragment.getActivity().getSupportFragmentManager(), title, message, defaultFile, checkMsg);
+ }
+
+ @TargetApi(Build.VERSION_CODES.KITKAT)
+ public static void openDocument(Fragment fragment, String mimeType, int requestCode) {
+ openDocument(fragment, mimeType, false, requestCode);
+ }
/**
* Opens the storage browser on Android 4.4 or later for opening a file
* @param fragment
- * @param last default selected file
* @param mimeType can be text/plain for example
+ * @param multiple allow file chooser to return multiple files
* @param requestCode used to identify the result coming back from storage browser onActivityResult() in your
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
- public static void openDocument(Fragment fragment, Uri last, String mimeType, int requestCode) {
+ public static void openDocument(Fragment fragment, String mimeType, boolean multiple, int requestCode) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
- intent.setData(last);
intent.setType(mimeType);
+ intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple);
+
fragment.startActivityForResult(intent, requestCode);
}
/**
* Opens the storage browser on Android 4.4 or later for saving a file
* @param fragment
- * @param last default selected file
* @param mimeType can be text/plain for example
+ * @param suggestedName a filename desirable for the file to be saved
* @param requestCode used to identify the result coming back from storage browser onActivityResult() in your
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
- public static void saveDocument(Fragment fragment, Uri last, String mimeType, int requestCode) {
+ public static void saveDocument(Fragment fragment, String mimeType, String suggestedName, int requestCode) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
- intent.setData(last);
intent.setType(mimeType);
+ intent.putExtra("android.content.extra.SHOW_ADVANCED", true); // Note: This is not documented, but works
+ intent.putExtra(Intent.EXTRA_TITLE, suggestedName);
fragment.startActivityForResult(intent, requestCode);
}
- private static Intent buildFileIntent(String filename, String mimeType) {
- Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
- intent.addCategory(Intent.CATEGORY_OPENABLE);
+ public static String getFilename(Context context, Uri uri) {
+ String filename = null;
+ try {
+ Cursor cursor = context.getContentResolver().query(uri, new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null);
- intent.setData(Uri.parse("file://" + filename));
- intent.setType(mimeType);
+ if (cursor != null) {
+ if (cursor.moveToNext()) {
+ filename = cursor.getString(0);
+ }
+ cursor.close();
+ }
+ } catch (Exception ignored) {
+ // This happens in rare cases (eg: document deleted since selection) and should not cause a failure
+ }
+ if (filename == null) {
+ String[] split = uri.toString().split("/");
+ filename = split[split.length - 1];
+ }
+ return filename;
+ }
- return intent;
+ public static long getFileSize(Context context, Uri uri) {
+ long size = -1;
+ try {
+ Cursor cursor = context.getContentResolver().query(uri, new String[]{OpenableColumns.SIZE}, null, null, null);
+
+ if (cursor != null) {
+ if (cursor.moveToNext()) {
+ size = cursor.getLong(0);
+ }
+ cursor.close();
+ }
+ } catch (Exception ignored) {
+ // This happens in rare cases (eg: document deleted since selection) and should not cause a failure
+ }
+ return size;
}
/**
- * Get a file path from a Uri.
- *
- * from https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/
- * afilechooser/utils/FileUtils.java
- *
- * @param context
- * @param uri
- * @return
- * @author paulburke
+ * Retrieve thumbnail of file, document api feature and thus KitKat only
*/
- public static String getPath(Context context, Uri uri) {
- Log.d(Constants.TAG + " File -",
- "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment()
- + ", Port: " + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: "
- + uri.getScheme() + ", Host: " + uri.getHost() + ", Segments: "
- + uri.getPathSegments().toString());
-
- if ("content".equalsIgnoreCase(uri.getScheme())) {
- String[] projection = {"_data"};
- Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
- try {
- if (cursor != null && cursor.moveToFirst()) {
- int columnIndex = cursor.getColumnIndexOrThrow("_data");
- return cursor.getString(columnIndex);
- }
- } catch (Exception e) {
- // Eat it
- } finally {
- if (cursor != null) {
- cursor.close();
- }
- }
- } else if ("file".equalsIgnoreCase(uri.getScheme())) {
- return uri.getPath();
+ public static Bitmap getThumbnail(Context context, Uri uri, Point size) {
+ if (Constants.KITKAT) {
+ return DocumentsContract.getDocumentThumbnail(context.getContentResolver(), uri, size, null);
+ } else {
+ return null;
}
+ }
- return null;
+ public static String readableFileSize(long size) {
+ if(size <= 0) return "0";
+ final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
+ int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
+ return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
+ }
+
+ public static interface FileDialogCallback {
+ public void onFileSelected(File file, boolean checked);
}
}
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/TemporaryStorageProvider.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/TemporaryStorageProvider.java
new file mode 100644
index 000000000..d1864f873
--- /dev/null
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/TemporaryStorageProvider.java
@@ -0,0 +1,153 @@
+package org.sufficientlysecure.keychain.provider;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.database.MatrixCursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
+import android.net.Uri;
+import android.os.ParcelFileDescriptor;
+import android.provider.OpenableColumns;
+import org.sufficientlysecure.keychain.Constants;
+import org.sufficientlysecure.keychain.util.DatabaseUtil;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+public class TemporaryStorageProvider extends ContentProvider {
+
+ private static final String DB_NAME = "tempstorage.db";
+ private static final String TABLE_FILES = "files";
+ private static final String COLUMN_ID = "id";
+ private static final String COLUMN_NAME = "name";
+ private static final String COLUMN_TIME = "time";
+ private static final Uri BASE_URI = Uri.parse("content://org.sufficientlysecure.keychain.tempstorage/");
+ private static final int DB_VERSION = 1;
+
+ public static Uri createFile(Context context, String targetName) {
+ ContentValues contentValues = new ContentValues();
+ contentValues.put(COLUMN_NAME, targetName);
+ return context.getContentResolver().insert(BASE_URI, contentValues);
+ }
+
+ public static int cleanUp(Context context) {
+ return context.getContentResolver().delete(BASE_URI, COLUMN_TIME + "< ?",
+ new String[]{Long.toString(System.currentTimeMillis() - Constants.TEMPFILE_TTL)});
+ }
+
+ private class TemporaryStorageDatabase extends SQLiteOpenHelper {
+
+ public TemporaryStorageDatabase(Context context) {
+ super(context, DB_NAME, null, DB_VERSION);
+ }
+
+ @Override
+ public void onCreate(SQLiteDatabase db) {
+ db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_FILES + " (" +
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
+ COLUMN_NAME + " TEXT, " +
+ COLUMN_TIME + " INTEGER" +
+ ");");
+ }
+
+ @Override
+ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+
+ }
+ }
+
+ private TemporaryStorageDatabase db;
+
+ private File getFile(Uri uri) throws FileNotFoundException {
+ try {
+ return getFile(Integer.parseInt(uri.getLastPathSegment()));
+ } catch (NumberFormatException e) {
+ throw new FileNotFoundException();
+ }
+ }
+
+ private File getFile(int id) {
+ return new File(getContext().getCacheDir(), "temp/" + id);
+ }
+
+ @Override
+ public boolean onCreate() {
+ db = new TemporaryStorageDatabase(getContext());
+ return new File(getContext().getCacheDir(), "temp").mkdirs();
+ }
+
+ @Override
+ public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
+ File file;
+ try {
+ file = getFile(uri);
+ } catch (FileNotFoundException e) {
+ return null;
+ }
+ Cursor fileName = db.getReadableDatabase().query(TABLE_FILES, new String[]{COLUMN_NAME}, COLUMN_ID + "=?",
+ new String[]{uri.getLastPathSegment()}, null, null, null);
+ if (fileName != null) {
+ if (fileName.moveToNext()) {
+ MatrixCursor cursor =
+ new MatrixCursor(new String[]{OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE, "_data"});
+ cursor.newRow().add(fileName.getString(0)).add(file.length()).add(file.getAbsolutePath());
+ fileName.close();
+ return cursor;
+ }
+ fileName.close();
+ }
+ return null;
+ }
+
+ @Override
+ public String getType(Uri uri) {
+ // Note: If we can find a files mime type, we can decrypt it to temp storage and open it after
+ // encryption. The mime type is needed, else UI really sucks and some apps break.
+ return "*/*";
+ }
+
+ @Override
+ public Uri insert(Uri uri, ContentValues values) {
+ if (!values.containsKey(COLUMN_TIME)) {
+ values.put(COLUMN_TIME, System.currentTimeMillis());
+ }
+ int insert = (int) db.getWritableDatabase().insert(TABLE_FILES, null, values);
+ try {
+ getFile(insert).createNewFile();
+ } catch (IOException e) {
+ return null;
+ }
+ return Uri.withAppendedPath(BASE_URI, Long.toString(insert));
+ }
+
+ @Override
+ public int delete(Uri uri, String selection, String[] selectionArgs) {
+ if (uri.getLastPathSegment() != null) {
+ selection = DatabaseUtil.concatenateWhere(selection, COLUMN_ID + "=?");
+ selectionArgs = DatabaseUtil.appendSelectionArgs(selectionArgs, new String[]{uri.getLastPathSegment()});
+ }
+ Cursor files = db.getReadableDatabase().query(TABLE_FILES, new String[]{COLUMN_ID}, selection,
+ selectionArgs, null, null, null);
+ if (files != null) {
+ while (files.moveToNext()) {
+ getFile(files.getInt(0)).delete();
+ }
+ files.close();
+ return db.getWritableDatabase().delete(TABLE_FILES, selection, selectionArgs);
+ }
+ return 0;
+ }
+
+ @Override
+ public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+ throw new UnsupportedOperationException("Update not supported");
+ }
+
+ @Override
+ public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
+ return openFileHelper(uri, mode);
+ }
+}
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java
index c87e490be..b45359a10 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java
@@ -112,6 +112,9 @@ public class KeychainIntentService extends IntentService
public static final int IO_BYTES = 1;
public static final int IO_FILE = 2; // This was misleadingly TARGET_URI before!
public static final int IO_URI = 3;
+ public static final int IO_URIS = 4;
+
+ public static final String SELECTED_URI = "selected_uri";
// encrypt
public static final String ENCRYPT_SIGNATURE_KEY_ID = "secret_key_id";
@@ -121,8 +124,10 @@ public class KeychainIntentService extends IntentService
public static final String ENCRYPT_MESSAGE_BYTES = "message_bytes";
public static final String ENCRYPT_INPUT_FILE = "input_file";
public static final String ENCRYPT_INPUT_URI = "input_uri";
+ public static final String ENCRYPT_INPUT_URIS = "input_uris";
public static final String ENCRYPT_OUTPUT_FILE = "output_file";
public static final String ENCRYPT_OUTPUT_URI = "output_uri";
+ public static final String ENCRYPT_OUTPUT_URIS = "output_uris";
public static final String ENCRYPT_SYMMETRIC_PASSPHRASE = "passphrase";
// decrypt/verify
@@ -142,6 +147,7 @@ public class KeychainIntentService extends IntentService
// export key
public static final String EXPORT_OUTPUT_STREAM = "export_output_stream";
public static final String EXPORT_FILENAME = "export_filename";
+ public static final String EXPORT_URI = "export_uri";
public static final String EXPORT_SECRET = "export_secret";
public static final String EXPORT_ALL = "export_all";
public static final String EXPORT_KEY_RING_MASTER_KEY_ID = "export_key_ring_id";
@@ -226,6 +232,7 @@ public class KeychainIntentService extends IntentService
try {
/* Input */
int source = data.get(SOURCE) != null ? data.getInt(SOURCE) : data.getInt(TARGET);
+ Bundle resultData = new Bundle();
long signatureKeyId = data.getLong(ENCRYPT_SIGNATURE_KEY_ID);
String symmetricPassphrase = data.getString(ENCRYPT_SYMMETRIC_PASSPHRASE);
@@ -233,45 +240,49 @@ public class KeychainIntentService extends IntentService
boolean useAsciiArmor = data.getBoolean(ENCRYPT_USE_ASCII_ARMOR);
long encryptionKeyIds[] = data.getLongArray(ENCRYPT_ENCRYPTION_KEYS_IDS);
int compressionId = data.getInt(ENCRYPT_COMPRESSION_ID);
- InputData inputData = createEncryptInputData(data);
- OutputStream outStream = createCryptOutputStream(data);
+ int urisCount = data.containsKey(ENCRYPT_INPUT_URIS) ? data.getParcelableArrayList(ENCRYPT_INPUT_URIS).size() : 1;
+ for (int i = 0; i < urisCount; i++) {
+ data.putInt(SELECTED_URI, i);
+ InputData inputData = createEncryptInputData(data);
+ OutputStream outStream = createCryptOutputStream(data);
- /* Operation */
- PgpSignEncrypt.Builder builder =
- new PgpSignEncrypt.Builder(
- new ProviderHelper(this),
- PgpHelper.getFullVersion(this),
- inputData, outStream);
- builder.setProgressable(this);
+ /* Operation */
+ PgpSignEncrypt.Builder builder =
+ new PgpSignEncrypt.Builder(
+ new ProviderHelper(this),
+ PgpHelper.getFullVersion(this),
+ inputData, outStream);
+ builder.setProgressable(this);
- builder.setEnableAsciiArmorOutput(useAsciiArmor)
- .setCompressionId(compressionId)
- .setSymmetricEncryptionAlgorithm(
- Preferences.getPreferences(this).getDefaultEncryptionAlgorithm())
- .setSignatureForceV3(Preferences.getPreferences(this).getForceV3Signatures())
- .setEncryptionMasterKeyIds(encryptionKeyIds)
- .setSymmetricPassphrase(symmetricPassphrase)
- .setSignatureMasterKeyId(signatureKeyId)
- .setEncryptToSigner(true)
- .setSignatureHashAlgorithm(
- Preferences.getPreferences(this).getDefaultHashAlgorithm())
- .setSignaturePassphrase(
- PassphraseCacheService.getCachedPassphrase(this, signatureKeyId));
+ builder.setEnableAsciiArmorOutput(useAsciiArmor)
+ .setCompressionId(compressionId)
+ .setSymmetricEncryptionAlgorithm(
+ Preferences.getPreferences(this).getDefaultEncryptionAlgorithm())
+ .setSignatureForceV3(Preferences.getPreferences(this).getForceV3Signatures())
+ .setEncryptionMasterKeyIds(encryptionKeyIds)
+ .setSymmetricPassphrase(symmetricPassphrase)
+ .setSignatureMasterKeyId(signatureKeyId)
+ .setEncryptToSigner(true)
+ .setSignatureHashAlgorithm(
+ Preferences.getPreferences(this).getDefaultHashAlgorithm())
+ .setSignaturePassphrase(
+ PassphraseCacheService.getCachedPassphrase(this, signatureKeyId));
+
+ // this assumes that the bytes are cleartext (valid for current implementation!)
+ if (source == IO_BYTES) {
+ builder.setCleartextInput(true);
+ }
+
+ builder.build().execute();
+
+ outStream.close();
+
+ /* Output */
+
+ finalizeEncryptOutputStream(data, resultData, outStream);
- // this assumes that the bytes are cleartext (valid for current implementation!)
- if (source == IO_BYTES) {
- builder.setCleartextInput(true);
}
- builder.build().execute();
-
- outStream.close();
-
- /* Output */
-
- Bundle resultData = new Bundle();
- finalizeEncryptOutputStream(data, resultData, outStream);
-
OtherHelper.logDebugBundle(resultData, "resultData");
sendMessageToHandler(KeychainIntentServiceHandler.MESSAGE_OKAY, resultData);
@@ -416,13 +427,16 @@ public class KeychainIntentService extends IntentService
boolean exportSecret = data.getBoolean(EXPORT_SECRET, false);
long[] masterKeyIds = data.getLongArray(EXPORT_KEY_RING_MASTER_KEY_ID);
String outputFile = data.getString(EXPORT_FILENAME);
+ Uri outputUri = data.getParcelable(EXPORT_URI);
// If not exporting all keys get the masterKeyIds of the keys to export from the intent
boolean exportAll = data.getBoolean(EXPORT_ALL);
- // check if storage is ready
- if (!FileHelper.isStorageMounted(outputFile)) {
- throw new PgpGeneralException(getString(R.string.error_external_storage_not_ready));
+ if (outputFile != null) {
+ // check if storage is ready
+ if (!FileHelper.isStorageMounted(outputFile)) {
+ throw new PgpGeneralException(getString(R.string.error_external_storage_not_ready));
+ }
}
ArrayList publicMasterKeyIds = new ArrayList();
@@ -454,12 +468,19 @@ public class KeychainIntentService extends IntentService
}
}
+ OutputStream outStream;
+ if (outputFile != null) {
+ outStream = new FileOutputStream(outputFile);
+ } else {
+ outStream = getContentResolver().openOutputStream(outputUri);
+ }
+
PgpImportExport pgpImportExport = new PgpImportExport(this, this, this);
Bundle resultData = pgpImportExport
.exportKeyRings(publicMasterKeyIds, secretMasterKeyIds,
- new FileOutputStream(outputFile));
+ outStream);
- if (mIsCanceled) {
+ if (mIsCanceled && outputFile != null) {
new File(outputFile).delete();
}
@@ -709,8 +730,13 @@ public class KeychainIntentService extends IntentService
Uri providerUri = data.getParcelable(ENCRYPT_INPUT_URI);
// InputStream
- InputStream in = getContentResolver().openInputStream(providerUri);
- return new InputData(in, 0);
+ return new InputData(getContentResolver().openInputStream(providerUri), 0);
+
+ case IO_URIS:
+ providerUri = data.getParcelableArrayList(ENCRYPT_INPUT_URIS).get(data.getInt(SELECTED_URI));
+
+ // InputStream
+ return new InputData(getContentResolver().openInputStream(providerUri), 0);
default:
throw new PgpGeneralException("No target choosen!");
@@ -740,6 +766,11 @@ public class KeychainIntentService extends IntentService
return getContentResolver().openOutputStream(providerUri);
+ case IO_URIS:
+ providerUri = data.getParcelableArrayList(ENCRYPT_OUTPUT_URIS).get(data.getInt(SELECTED_URI));
+
+ return getContentResolver().openOutputStream(providerUri);
+
default:
throw new PgpGeneralException("No target choosen!");
}
@@ -765,6 +796,7 @@ public class KeychainIntentService extends IntentService
break;
case IO_URI:
+ case IO_URIS:
// nothing, output was written, just send okay and verification bundle
break;
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java
index dba742268..e62591b1a 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java
@@ -23,11 +23,8 @@ import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
-import android.widget.Toast;
-
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
-import org.sufficientlysecure.keychain.helper.FileHelper;
import org.sufficientlysecure.keychain.pgp.PgpHelper;
import org.sufficientlysecure.keychain.ui.adapter.PagerTabStripAdapter;
import org.sufficientlysecure.keychain.util.Log;
@@ -114,7 +111,7 @@ public class DecryptActivity extends DrawerActivity {
} else {
// Binary via content provider (could also be files)
// override uri to get stream from send
- uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
+ uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
action = ACTION_DECRYPT;
}
} else if (Intent.ACTION_VIEW.equals(action)) {
@@ -122,6 +119,7 @@ public class DecryptActivity extends DrawerActivity {
// override action
action = ACTION_DECRYPT;
+ mFileFragmentBundle.putBoolean(DecryptFileFragment.ARG_FROM_VIEW_INTENT, true);
}
String textData = extras.getString(EXTRA_TEXT);
@@ -155,21 +153,8 @@ public class DecryptActivity extends DrawerActivity {
}
}
} else if (ACTION_DECRYPT.equals(action) && uri != null) {
- // get file path from uri
- String path = FileHelper.getPath(this, uri);
-
- if (path != null) {
- mFileFragmentBundle.putString(DecryptFileFragment.ARG_FILENAME, path);
- mSwitchToTab = PAGER_TAB_FILE;
- } else {
- Log.e(Constants.TAG,
- "Direct binary data without actual file in filesystem is not supported. " +
- "Please use the Remote Service API!");
- Toast.makeText(this, R.string.error_only_files_are_supported, Toast.LENGTH_LONG)
- .show();
- // end activity
- finish();
- }
+ mFileFragmentBundle.putParcelable(DecryptFileFragment.ARG_URI, uri);
+ mSwitchToTab = PAGER_TAB_FILE;
} else if (ACTION_DECRYPT.equals(action)) {
Log.e(Constants.TAG,
"Include the extra 'text' or an Uri with setData() in your Intent!");
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFileFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFileFragment.java
index 56dfdbd95..5b61c3f52 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFileFragment.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFileFragment.java
@@ -20,13 +20,10 @@ package org.sufficientlysecure.keychain.ui;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
-import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
-import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
-import android.provider.OpenableColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -34,37 +31,35 @@ import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
+import android.widget.TextView;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.helper.FileHelper;
import org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyResult;
import org.sufficientlysecure.keychain.service.KeychainIntentService;
import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler;
-import org.sufficientlysecure.keychain.util.Notify;
import org.sufficientlysecure.keychain.ui.dialog.DeleteFileDialogFragment;
-import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment;
import org.sufficientlysecure.keychain.util.Log;
+import org.sufficientlysecure.keychain.util.Notify;
import java.io.File;
public class DecryptFileFragment extends DecryptFragment {
- public static final String ARG_FILENAME = "filename";
+ public static final String ARG_URI = "uri";
+ public static final String ARG_FROM_VIEW_INTENT = "view_intent";
- private static final int RESULT_CODE_FILE = 0x00007003;
+ private static final int REQUEST_CODE_INPUT = 0x00007003;
+ private static final int REQUEST_CODE_OUTPUT = 0x00007007;
// view
- private EditText mFilename;
+ private TextView mFilename;
private CheckBox mDeleteAfter;
- private ImageButton mBrowse;
private View mDecryptButton;
- private String mInputFilename = null;
+ // model
private Uri mInputUri = null;
- private String mOutputFilename = null;
private Uri mOutputUri = null;
- private FileDialogFragment mFileDialog;
-
/**
* Inflate the layout for this fragment
*/
@@ -72,17 +67,16 @@ public class DecryptFileFragment extends DecryptFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.decrypt_file_fragment, container, false);
- mFilename = (EditText) view.findViewById(R.id.decrypt_file_filename);
- mBrowse = (ImageButton) view.findViewById(R.id.decrypt_file_browse);
+ mFilename = (TextView) view.findViewById(R.id.decrypt_file_filename);
mDeleteAfter = (CheckBox) view.findViewById(R.id.decrypt_file_delete_after_decryption);
mDecryptButton = view.findViewById(R.id.decrypt_file_action_decrypt);
- mBrowse.setOnClickListener(new View.OnClickListener() {
+ view.findViewById(R.id.decrypt_file_browse).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (Constants.KITKAT) {
- FileHelper.openDocument(DecryptFileFragment.this, mInputUri, "*/*", RESULT_CODE_FILE);
+ FileHelper.openDocument(DecryptFileFragment.this, "*/*", REQUEST_CODE_INPUT);
} else {
- FileHelper.openFile(DecryptFileFragment.this, mFilename.getText().toString(), "*/*",
- RESULT_CODE_FILE);
+ FileHelper.openFile(DecryptFileFragment.this, mInputUri, "*/*",
+ REQUEST_CODE_INPUT);
}
}
});
@@ -100,74 +94,47 @@ public class DecryptFileFragment extends DecryptFragment {
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
- String filename = getArguments().getString(ARG_FILENAME);
- if (filename != null) {
- mFilename.setText(filename);
- }
+ setInputUri(getArguments().getParcelable(ARG_URI));
}
- private String guessOutputFilename() {
- File file = new File(mInputFilename);
- String filename = file.getName();
- if (filename.endsWith(".asc") || filename.endsWith(".gpg") || filename.endsWith(".pgp")) {
- filename = filename.substring(0, filename.length() - 4);
- }
- return Constants.Path.APP_DIR + "/" + filename;
- }
-
- private void decryptAction() {
- String currentFilename = mFilename.getText().toString();
- if (mInputFilename == null || !mInputFilename.equals(currentFilename)) {
+ private void setInputUri(Uri inputUri) {
+ if (inputUri == null) {
mInputUri = null;
- mInputFilename = mFilename.getText().toString();
- }
-
- if (mInputUri == null) {
- mOutputFilename = guessOutputFilename();
- }
-
- if (mInputFilename.equals("")) {
- Notify.showNotify(getActivity(), R.string.no_file_selected, Notify.Style.ERROR);
+ mFilename.setText("");
return;
}
- if (mInputUri == null && mInputFilename.startsWith("file")) {
- File file = new File(mInputFilename);
- if (!file.exists() || !file.isFile()) {
- Notify.showNotify(getActivity(), getString(R.string.error_message,
- getString(R.string.error_file_not_found)), Notify.Style.ERROR);
- return;
- }
+ mInputUri = inputUri;
+ mFilename.setText(FileHelper.getFilename(getActivity(), mInputUri));
+ }
+
+ private void decryptAction() {
+ if (mInputUri == null) {
+ Notify.showNotify(getActivity(), R.string.no_file_selected, Notify.Style.ERROR);
+ return;
}
askForOutputFilename();
}
+ private String removeEncryptedAppend(String name) {
+ if (name.endsWith(".asc") || name.endsWith(".gpg") || name.endsWith(".pgp")) {
+ return name.substring(0, name.length() - 4);
+ }
+ return name;
+ }
+
private void askForOutputFilename() {
- // Message is received after passphrase is cached
- Handler returnHandler = new Handler() {
- @Override
- public void handleMessage(Message message) {
- if (message.what == FileDialogFragment.MESSAGE_OKAY) {
- Bundle data = message.getData();
- if (data.containsKey(FileDialogFragment.MESSAGE_DATA_URI)) {
- mOutputUri = data.getParcelable(FileDialogFragment.MESSAGE_DATA_URI);
- } else {
- mOutputFilename = data.getString(FileDialogFragment.MESSAGE_DATA_FILENAME);
- }
- decryptStart(null);
- }
- }
- };
-
- // Create a new Messenger for the communication back
- Messenger messenger = new Messenger(returnHandler);
-
- mFileDialog = FileDialogFragment.newInstance(messenger,
- getString(R.string.title_decrypt_to_file),
- getString(R.string.specify_file_to_decrypt_to), mOutputFilename, null);
-
- mFileDialog.show(getActivity().getSupportFragmentManager(), "fileDialog");
+ String targetName = removeEncryptedAppend(FileHelper.getFilename(getActivity(), mInputUri));
+ if (!Constants.KITKAT) {
+ File file = new File(mInputUri.getPath());
+ File parentDir = file.exists() ? file.getParentFile() : Constants.Path.APP_DIR;
+ File targetFile = new File(parentDir, targetName);
+ FileHelper.saveFile(this, getString(R.string.title_decrypt_to_file),
+ getString(R.string.specify_file_to_decrypt_to), targetFile, REQUEST_CODE_OUTPUT);
+ } else {
+ FileHelper.saveDocument(this, "*/*", targetName, REQUEST_CODE_OUTPUT);
+ }
}
@Override
@@ -183,25 +150,13 @@ public class DecryptFileFragment extends DecryptFragment {
intent.setAction(KeychainIntentService.ACTION_DECRYPT_VERIFY);
// data
- Log.d(Constants.TAG, "mInputFilename=" + mInputFilename + ", mOutputFilename="
- + mOutputFilename + ",mInputUri=" + mInputUri + ", mOutputUri="
- + mOutputUri);
+ Log.d(Constants.TAG, "mInputUri=" + mInputUri + ", mOutputUri=" + mOutputUri);
- if (mInputUri != null) {
- data.putInt(KeychainIntentService.SOURCE, KeychainIntentService.IO_URI);
- data.putParcelable(KeychainIntentService.ENCRYPT_INPUT_URI, mInputUri);
- } else {
- data.putInt(KeychainIntentService.SOURCE, KeychainIntentService.IO_FILE);
- data.putString(KeychainIntentService.ENCRYPT_INPUT_FILE, mInputFilename);
- }
+ data.putInt(KeychainIntentService.SOURCE, KeychainIntentService.IO_URI);
+ data.putParcelable(KeychainIntentService.ENCRYPT_INPUT_URI, mInputUri);
- if (mOutputUri != null) {
- data.putInt(KeychainIntentService.TARGET, KeychainIntentService.IO_URI);
- data.putParcelable(KeychainIntentService.ENCRYPT_OUTPUT_URI, mOutputUri);
- } else {
- data.putInt(KeychainIntentService.TARGET, KeychainIntentService.IO_FILE);
- data.putString(KeychainIntentService.ENCRYPT_OUTPUT_FILE, mOutputFilename);
- }
+ data.putInt(KeychainIntentService.TARGET, KeychainIntentService.IO_URI);
+ data.putParcelable(KeychainIntentService.ENCRYPT_OUTPUT_URI, mOutputUri);
data.putString(KeychainIntentService.DECRYPT_PASSPHRASE, passphrase);
@@ -232,15 +187,19 @@ public class DecryptFileFragment extends DecryptFragment {
if (mDeleteAfter.isChecked()) {
// Create and show dialog to delete original file
- DeleteFileDialogFragment deleteFileDialog;
- if (mInputUri != null) {
- deleteFileDialog = DeleteFileDialogFragment.newInstance(mInputUri);
- } else {
- deleteFileDialog = DeleteFileDialogFragment
- .newInstance(mInputFilename);
- }
+ DeleteFileDialogFragment deleteFileDialog = DeleteFileDialogFragment.newInstance(mInputUri);
deleteFileDialog.show(getActivity().getSupportFragmentManager(), "deleteDialog");
+ setInputUri(null);
}
+
+ /*
+ // A future open after decryption feature
+ if () {
+ Intent viewFile = new Intent(Intent.ACTION_VIEW);
+ viewFile.setData(mOutputUri);
+ startActivity(viewFile);
+ }
+ */
}
}
}
@@ -260,28 +219,17 @@ public class DecryptFileFragment extends DecryptFragment {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
- case RESULT_CODE_FILE: {
+ case REQUEST_CODE_INPUT: {
if (resultCode == Activity.RESULT_OK && data != null) {
- if (Constants.KITKAT) {
- mInputUri = data.getData();
- Cursor cursor = getActivity().getContentResolver().query(mInputUri, new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null);
- if (cursor != null) {
- if (cursor.moveToNext()) {
- mInputFilename = cursor.getString(0);
- mFilename.setText(mInputFilename);
- }
- cursor.close();
- }
- } else {
- try {
- String path = FileHelper.getPath(getActivity(), data.getData());
- Log.d(Constants.TAG, "path=" + path);
-
- mFilename.setText(path);
- } catch (NullPointerException e) {
- Log.e(Constants.TAG, "Nullpointer while retrieving path!");
- }
- }
+ setInputUri(data.getData());
+ }
+ return;
+ }
+ case REQUEST_CODE_OUTPUT: {
+ // This happens after output file was selected, so start our operation
+ if (resultCode == Activity.RESULT_OK && data != null) {
+ mOutputUri = data.getData();
+ decryptStart(null);
}
return;
}
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFragment.java
index d4235b82b..16a7b911e 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFragment.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFragment.java
@@ -38,7 +38,7 @@ import org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyResult;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment;
-public class DecryptFragment extends Fragment {
+public abstract class DecryptFragment extends Fragment {
private static final int RESULT_CODE_LOOKUP_KEY = 0x00007006;
protected long mSignatureKeyId = 0;
@@ -217,8 +217,6 @@ public class DecryptFragment extends Fragment {
*
* @param passphrase
*/
- protected void decryptStart(String passphrase) {
-
- }
+ protected abstract void decryptStart(String passphrase);
}
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java
index cc69148c1..303db60ed 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java
@@ -18,23 +18,37 @@
package org.sufficientlysecure.keychain.ui;
+import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.Messenger;
+import android.support.v4.app.Fragment;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
-import android.widget.Toast;
-
+import android.view.Menu;
+import android.view.MenuItem;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
-import org.sufficientlysecure.keychain.helper.FileHelper;
+import org.sufficientlysecure.keychain.compatibility.ClipboardReflection;
+import org.sufficientlysecure.keychain.helper.Preferences;
+import org.sufficientlysecure.keychain.pgp.KeyRing;
+import org.sufficientlysecure.keychain.service.KeychainIntentService;
+import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler;
+import org.sufficientlysecure.keychain.service.PassphraseCacheService;
import org.sufficientlysecure.keychain.ui.adapter.PagerTabStripAdapter;
+import org.sufficientlysecure.keychain.ui.dialog.DeleteFileDialogFragment;
+import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment;
import org.sufficientlysecure.keychain.util.Log;
+import org.sufficientlysecure.keychain.util.Notify;
-public class EncryptActivity extends DrawerActivity implements
- EncryptSymmetricFragment.OnSymmetricKeySelection,
- EncryptAsymmetricFragment.OnAsymmetricKeySelection,
- EncryptActivityInterface {
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
+
+public class EncryptActivity extends DrawerActivity implements EncryptActivityInterface {
/* Intents */
public static final String ACTION_ENCRYPT = Constants.INTENT_PREFIX + "ENCRYPT";
@@ -51,7 +65,7 @@ public class EncryptActivity extends DrawerActivity implements
// view
ViewPager mViewPagerMode;
- PagerTabStrip mPagerTabStripMode;
+ //PagerTabStrip mPagerTabStripMode;
PagerTabStripAdapter mTabsAdapterMode;
ViewPager mViewPagerContent;
PagerTabStrip mPagerTabStripContent;
@@ -72,37 +86,27 @@ public class EncryptActivity extends DrawerActivity implements
// model used by message and file fragments
private long mEncryptionKeyIds[] = null;
+ private String mEncryptionUserIds[] = null;
private long mSigningKeyId = Constants.key.none;
- private String mPassphrase;
- private String mPassphraseAgain;
+ private String mPassphrase = "";
+ private boolean mUseArmor;
+ private boolean mDeleteAfterEncrypt = false;
+ private boolean mShareAfterEncrypt = false;
+ private ArrayList mInputUris;
+ private ArrayList mOutputUris;
+ private String mMessage = "";
- @Override
- public void onSigningKeySelected(long signingKeyId) {
- mSigningKeyId = signingKeyId;
- }
-
- @Override
- public void onEncryptionKeysSelected(long[] encryptionKeyIds) {
- mEncryptionKeyIds = encryptionKeyIds;
- }
-
- @Override
- public void onPassphraseUpdate(String passphrase) {
- mPassphrase = passphrase;
- }
-
- @Override
- public void onPassphraseAgainUpdate(String passphrase) {
- mPassphraseAgain = passphrase;
- }
-
- @Override
public boolean isModeSymmetric() {
- if (PAGER_MODE_SYMMETRIC == mViewPagerMode.getCurrentItem()) {
- return true;
- } else {
- return false;
- }
+ return PAGER_MODE_SYMMETRIC == mViewPagerMode.getCurrentItem();
+ }
+
+ public boolean isContentMessage() {
+ return PAGER_CONTENT_MESSAGE == mViewPagerContent.getCurrentItem();
+ }
+
+ @Override
+ public boolean isUseArmor() {
+ return mUseArmor;
}
@Override
@@ -116,19 +120,277 @@ public class EncryptActivity extends DrawerActivity implements
}
@Override
- public String getPassphrase() {
- return mPassphrase;
+ public String[] getEncryptionUsers() {
+ return mEncryptionUserIds;
}
@Override
- public String getPassphraseAgain() {
- return mPassphraseAgain;
+ public void setSignatureKey(long signatureKey) {
+ mSigningKeyId = signatureKey;
+ notifyUpdate();
}
+ @Override
+ public void setEncryptionKeys(long[] encryptionKeys) {
+ mEncryptionKeyIds = encryptionKeys;
+ notifyUpdate();
+ }
+
+ @Override
+ public void setEncryptionUsers(String[] encryptionUsers) {
+ mEncryptionUserIds = encryptionUsers;
+ notifyUpdate();
+ }
+
+ @Override
+ public void setPassphrase(String passphrase) {
+ mPassphrase = passphrase;
+ }
+
+ @Override
+ public ArrayList getInputUris() {
+ if (mInputUris == null) mInputUris = new ArrayList();
+ return mInputUris;
+ }
+
+ @Override
+ public ArrayList getOutputUris() {
+ if (mOutputUris == null) mOutputUris = new ArrayList();
+ return mOutputUris;
+ }
+
+ @Override
+ public void setInputUris(ArrayList uris) {
+ mInputUris = uris;
+ notifyUpdate();
+ }
+
+ @Override
+ public void setOutputUris(ArrayList uris) {
+ mOutputUris = uris;
+ notifyUpdate();
+ }
+
+ @Override
+ public String getMessage() {
+ return mMessage;
+ }
+
+ @Override
+ public void setMessage(String message) {
+ mMessage = message;
+ }
+
+ @Override
+ public void notifyUpdate() {
+ for (Fragment fragment : getSupportFragmentManager().getFragments()) {
+ if (fragment instanceof EncryptActivityInterface.UpdateListener) {
+ ((UpdateListener) fragment).onNotifyUpdate();
+ }
+ }
+ }
+
+ @Override
+ public void startEncrypt(boolean share) {
+ mShareAfterEncrypt = share;
+ startEncrypt();
+ }
+
+ public void startEncrypt() {
+ if (!inputIsValid()) {
+ // Notify was created by inputIsValid.
+ return;
+ }
+
+ // Send all information needed to service to edit key in other thread
+ Intent intent = new Intent(this, KeychainIntentService.class);
+ intent.setAction(KeychainIntentService.ACTION_ENCRYPT_SIGN);
+ intent.putExtra(KeychainIntentService.EXTRA_DATA, createEncryptBundle());
+
+ // Message is received after encrypting is done in KeychainIntentService
+ KeychainIntentServiceHandler serviceHandler = new KeychainIntentServiceHandler(this,
+ getString(R.string.progress_encrypting), ProgressDialog.STYLE_HORIZONTAL) {
+ public void handleMessage(Message message) {
+ // handle messages by standard KeychainIntentServiceHandler first
+ super.handleMessage(message);
+
+ if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) {
+ Notify.showNotify(EncryptActivity.this, R.string.encrypt_sign_successful, Notify.Style.INFO);
+
+ if (!isContentMessage() && mDeleteAfterEncrypt) {
+ for (Uri inputUri : mInputUris) {
+ DeleteFileDialogFragment deleteFileDialog = DeleteFileDialogFragment.newInstance(inputUri);
+ deleteFileDialog.show(getSupportFragmentManager(), "deleteDialog");
+ }
+ mInputUris.clear();
+ notifyUpdate();
+ }
+
+ if (mShareAfterEncrypt) {
+ // Share encrypted file
+ startActivity(Intent.createChooser(createSendIntent(message), getString(R.string.title_share_file)));
+ } else if (isContentMessage()) {
+ // Copy to clipboard
+ copyToClipboard(message);
+ Notify.showNotify(EncryptActivity.this,
+ R.string.encrypt_sign_clipboard_successful, Notify.Style.INFO);
+ }
+ }
+ }
+ };
+ // Create a new Messenger for the communication back
+ Messenger messenger = new Messenger(serviceHandler);
+ intent.putExtra(KeychainIntentService.EXTRA_MESSENGER, messenger);
+
+ // show progress dialog
+ serviceHandler.showProgressDialog(this);
+
+ // start service with intent
+ startService(intent);
+ }
+
+ private Bundle createEncryptBundle() {
+ // fill values for this action
+ Bundle data = new Bundle();
+
+ if (isContentMessage()) {
+ data.putInt(KeychainIntentService.TARGET, KeychainIntentService.IO_BYTES);
+ data.putByteArray(KeychainIntentService.ENCRYPT_MESSAGE_BYTES, mMessage.getBytes());
+ } else {
+ data.putInt(KeychainIntentService.SOURCE, KeychainIntentService.IO_URIS);
+ data.putParcelableArrayList(KeychainIntentService.ENCRYPT_INPUT_URIS, mInputUris);
+
+ data.putInt(KeychainIntentService.TARGET, KeychainIntentService.IO_URIS);
+ data.putParcelableArrayList(KeychainIntentService.ENCRYPT_OUTPUT_URIS, mOutputUris);
+ }
+
+ // Always use armor for messages
+ data.putBoolean(KeychainIntentService.ENCRYPT_USE_ASCII_ARMOR, mUseArmor || isContentMessage());
+
+ // TODO: Only default compression right now...
+ int compressionId = Preferences.getPreferences(this).getDefaultMessageCompression();
+ data.putInt(KeychainIntentService.ENCRYPT_COMPRESSION_ID, compressionId);
+
+ if (isModeSymmetric()) {
+ Log.d(Constants.TAG, "Symmetric encryption enabled!");
+ String passphrase = mPassphrase;
+ if (passphrase.length() == 0) {
+ passphrase = null;
+ }
+ data.putString(KeychainIntentService.ENCRYPT_SYMMETRIC_PASSPHRASE, passphrase);
+ } else {
+ data.putLong(KeychainIntentService.ENCRYPT_SIGNATURE_KEY_ID, mSigningKeyId);
+ data.putLongArray(KeychainIntentService.ENCRYPT_ENCRYPTION_KEYS_IDS, mEncryptionKeyIds);
+ }
+ return data;
+ }
+
+ private void copyToClipboard(Message message) {
+ ClipboardReflection.copyToClipboard(this, new String(message.getData().getByteArray(KeychainIntentService.RESULT_BYTES)));
+ }
+
+ private Intent createSendIntent(Message message) {
+ Intent sendIntent;
+ if (isContentMessage()) {
+ sendIntent = new Intent(Intent.ACTION_SEND);
+ sendIntent.setType("text/plain");
+ sendIntent.putExtra(Intent.EXTRA_TEXT, new String(message.getData().getByteArray(KeychainIntentService.RESULT_BYTES)));
+ } else {
+ // file
+ if (mOutputUris.size() == 1) {
+ sendIntent = new Intent(Intent.ACTION_SEND);
+ sendIntent.putExtra(Intent.EXTRA_STREAM, mOutputUris.get(0));
+ } else {
+ sendIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
+ sendIntent.putExtra(Intent.EXTRA_STREAM, mOutputUris);
+ }
+ sendIntent.setType("application/pgp-encrypted");
+ }
+ if (!isModeSymmetric() && mEncryptionUserIds != null) {
+ Set users = new HashSet();
+ for (String user : mEncryptionUserIds) {
+ String[] userId = KeyRing.splitUserId(user);
+ if (userId[1] != null) {
+ users.add(userId[1]);
+ }
+ }
+ sendIntent.putExtra(Intent.EXTRA_EMAIL, users.toArray(new String[users.size()]));
+ }
+ return sendIntent;
+ }
+
+ private boolean inputIsValid() {
+ if (isContentMessage()) {
+ if (mMessage == null) {
+ Notify.showNotify(this, R.string.error_message, Notify.Style.ERROR);
+ return false;
+ }
+ } else {
+ // file checks
+
+ if (mInputUris.isEmpty()) {
+ Notify.showNotify(this, R.string.no_file_selected, Notify.Style.ERROR);
+ return false;
+ } else if (mInputUris.size() > 1 && !mShareAfterEncrypt) {
+ // This should be impossible...
+ return false;
+ } else if (mInputUris.size() != mOutputUris.size()) {
+ // This as well
+ return false;
+ }
+ }
+
+ if (isModeSymmetric()) {
+ // symmetric encryption checks
+
+
+ if (mPassphrase == null) {
+ Notify.showNotify(this, R.string.passphrases_do_not_match, Notify.Style.ERROR);
+ return false;
+ }
+ if (mPassphrase.isEmpty()) {
+ Notify.showNotify(this, R.string.passphrase_must_not_be_empty, Notify.Style.ERROR);
+ return false;
+ }
+
+ } else {
+ // asymmetric encryption checks
+
+ boolean gotEncryptionKeys = (mEncryptionKeyIds != null
+ && mEncryptionKeyIds.length > 0);
+
+ // Files must be encrypted, only text can be signed-only right now
+ if (!gotEncryptionKeys && !isContentMessage()) {
+ Notify.showNotify(this, R.string.select_encryption_key, Notify.Style.ERROR);
+ return false;
+ }
+
+ if (!gotEncryptionKeys && mSigningKeyId == 0) {
+ Notify.showNotify(this, R.string.select_encryption_or_signature_key, Notify.Style.ERROR);
+ return false;
+ }
+
+ if (mSigningKeyId != 0 && PassphraseCacheService.getCachedPassphrase(this, mSigningKeyId) == null) {
+ PassphraseDialogFragment.show(this, mSigningKeyId,
+ new Handler() {
+ @Override
+ public void handleMessage(Message message) {
+ if (message.what == PassphraseDialogFragment.MESSAGE_OKAY) {
+ // restart
+ startEncrypt();
+ }
+ }
+ });
+
+ return false;
+ }
+ }
+ return true;
+ }
private void initView() {
mViewPagerMode = (ViewPager) findViewById(R.id.encrypt_pager_mode);
- mPagerTabStripMode = (PagerTabStrip) findViewById(R.id.encrypt_pager_tab_strip_mode);
+ //mPagerTabStripMode = (PagerTabStrip) findViewById(R.id.encrypt_pager_tab_strip_mode);
mViewPagerContent = (ViewPager) findViewById(R.id.encrypt_pager_content);
mPagerTabStripContent = (PagerTabStrip) findViewById(R.id.encrypt_pager_tab_strip_content);
@@ -165,8 +427,43 @@ public class EncryptActivity extends DrawerActivity implements
mTabsAdapterContent.addTab(EncryptMessageFragment.class,
mMessageFragmentBundle, getString(R.string.label_message));
mTabsAdapterContent.addTab(EncryptFileFragment.class,
- mFileFragmentBundle, getString(R.string.label_file));
+ mFileFragmentBundle, getString(R.string.label_files));
mViewPagerContent.setCurrentItem(mSwitchToContent);
+
+ mUseArmor = Preferences.getPreferences(this).getDefaultAsciiArmor();
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.encrypt_activity, menu);
+ menu.findItem(R.id.check_use_armor).setChecked(mUseArmor);
+ return super.onCreateOptionsMenu(menu);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (item.isCheckable()) {
+ item.setChecked(!item.isChecked());
+ }
+ switch (item.getItemId()) {
+ case R.id.check_use_symmetric:
+ mSwitchToMode = item.isChecked() ? PAGER_MODE_SYMMETRIC : PAGER_MODE_ASYMMETRIC;
+
+ mViewPagerMode.setCurrentItem(mSwitchToMode);
+ notifyUpdate();
+ break;
+ case R.id.check_use_armor:
+ mUseArmor = item.isChecked();
+ notifyUpdate();
+ break;
+ case R.id.check_delete_after_encrypt:
+ mDeleteAfterEncrypt = item.isChecked();
+ notifyUpdate();
+ break;
+ default:
+ return super.onOptionsItemSelected(item);
+ }
+ return true;
}
/**
@@ -178,12 +475,16 @@ public class EncryptActivity extends DrawerActivity implements
String action = intent.getAction();
Bundle extras = intent.getExtras();
String type = intent.getType();
- Uri uri = intent.getData();
+ ArrayList uris = new ArrayList();
if (extras == null) {
extras = new Bundle();
}
+ if (intent.getData() != null) {
+ uris.add(intent.getData());
+ }
+
/*
* Android's Action
*/
@@ -201,14 +502,19 @@ public class EncryptActivity extends DrawerActivity implements
}
} else {
// Files via content provider, override uri and action
- uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
+ uris.clear();
+ uris.add(intent.getParcelableExtra(Intent.EXTRA_STREAM));
action = ACTION_ENCRYPT;
}
}
+ if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
+ uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
+ action = ACTION_ENCRYPT;
+ }
+
if (extras.containsKey(EXTRA_ASCII_ARMOR)) {
- boolean requestAsciiArmor = extras.getBoolean(EXTRA_ASCII_ARMOR, true);
- mFileFragmentBundle.putBoolean(EncryptFileFragment.ARG_ASCII_ARMOR, requestAsciiArmor);
+ mUseArmor = extras.getBoolean(EXTRA_ASCII_ARMOR, true);
}
String textData = extras.getString(EXTRA_TEXT);
@@ -230,25 +536,10 @@ public class EncryptActivity extends DrawerActivity implements
// encrypt text based on given extra
mMessageFragmentBundle.putString(EncryptMessageFragment.ARG_TEXT, textData);
mSwitchToContent = PAGER_CONTENT_MESSAGE;
- } else if (ACTION_ENCRYPT.equals(action) && uri != null) {
+ } else if (ACTION_ENCRYPT.equals(action) && uris != null && !uris.isEmpty()) {
// encrypt file based on Uri
-
- // get file path from uri
- String path = FileHelper.getPath(this, uri);
-
- if (path != null) {
- mFileFragmentBundle.putString(EncryptFileFragment.ARG_FILENAME, path);
- mSwitchToContent = PAGER_CONTENT_FILE;
- } else {
- Log.e(Constants.TAG,
- "Direct binary data without actual file in filesystem is not supported " +
- "by Intents. Please use the Remote Service API!"
- );
- Toast.makeText(this, R.string.error_only_files_are_supported,
- Toast.LENGTH_LONG).show();
- // end activity
- finish();
- }
+ mFileFragmentBundle.putParcelableArrayList(EncryptFileFragment.ARG_URIS, uris);
+ mSwitchToContent = PAGER_CONTENT_FILE;
} else if (ACTION_ENCRYPT.equals(action)) {
Log.e(Constants.TAG,
"Include the extra 'text' or an Uri with setData() in your Intent!");
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivityInterface.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivityInterface.java
index 0786b3a16..54fe369a7 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivityInterface.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivityInterface.java
@@ -17,14 +17,41 @@
package org.sufficientlysecure.keychain.ui;
+import android.net.Uri;
+
+import java.util.ArrayList;
+
public interface EncryptActivityInterface {
- public boolean isModeSymmetric();
+ public interface UpdateListener {
+ void onNotifyUpdate();
+ }
+
+ public boolean isUseArmor();
public long getSignatureKey();
public long[] getEncryptionKeys();
+ public String[] getEncryptionUsers();
+ public void setSignatureKey(long signatureKey);
+ public void setEncryptionKeys(long[] encryptionKeys);
+ public void setEncryptionUsers(String[] encryptionUsers);
- public String getPassphrase();
- public String getPassphraseAgain();
+ public void setPassphrase(String passphrase);
+ // ArrayList on purpose as only those are parcelable
+ public ArrayList getInputUris();
+ public ArrayList getOutputUris();
+ public void setInputUris(ArrayList uris);
+ public void setOutputUris(ArrayList uris);
+
+ public String getMessage();
+ public void setMessage(String message);
+
+ /**
+ * Call this to notify the UI for changes done on the array lists or arrays,
+ * automatically called if setter is used
+ */
+ public void notifyUpdate();
+
+ public void startEncrypt(boolean share);
}
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptAsymmetricFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptAsymmetricFragment.java
index eb807792b..ed3be0e7f 100644
--- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptAsymmetricFragment.java
+++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptAsymmetricFragment.java
@@ -18,16 +18,25 @@
package org.sufficientlysecure.keychain.ui;
import android.app.Activity;
-import android.content.Intent;
+import android.content.Context;
+import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
+import android.support.v4.app.LoaderManager;
+import android.support.v4.content.CursorLoader;
+import android.support.v4.content.Loader;
+import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import android.widget.CheckBox;
+import android.widget.AdapterView;
+import android.widget.BaseAdapter;
+import android.widget.Spinner;
+import android.widget.SpinnerAdapter;
import android.widget.TextView;
-import android.widget.Button;
+
+import com.tokenautocomplete.TokenCompleteTextView;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
@@ -37,61 +46,52 @@ import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
+import org.sufficientlysecure.keychain.ui.widget.EncryptKeyCompletionView;
import org.sufficientlysecure.keychain.util.Log;
-import org.sufficientlysecure.keychain.util.Notify;
-import java.util.Vector;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
-public class EncryptAsymmetricFragment extends Fragment {
+public class EncryptAsymmetricFragment extends Fragment implements EncryptActivityInterface.UpdateListener {
public static final String ARG_SIGNATURE_KEY_ID = "signature_key_id";
public static final String ARG_ENCRYPTION_KEY_IDS = "encryption_key_ids";
- public static final int REQUEST_CODE_PUBLIC_KEYS = 0x00007001;
- public static final int REQUEST_CODE_SECRET_KEYS = 0x00007002;
-
ProviderHelper mProviderHelper;
- OnAsymmetricKeySelection mKeySelectionListener;
-
// view
- private Button mSelectKeysButton;
- private CheckBox mSign;
- private TextView mMainUserId;
- private TextView mMainUserIdRest;
+ private Spinner mSign;
+ private EncryptKeyCompletionView mEncryptKeyView;
+ private SelectSignKeyCursorAdapter mSignAdapter = new SelectSignKeyCursorAdapter();
// model
- private long mSecretKeyId = Constants.key.none;
- private long mEncryptionKeyIds[] = null;
+ private EncryptActivityInterface mEncryptInterface;
- // Container Activity must implement this interface
- public interface OnAsymmetricKeySelection {
- public void onSigningKeySelected(long signingKeyId);
+ @Override
+ public void onNotifyUpdate() {
- public void onEncryptionKeysSelected(long[] encryptionKeyIds);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
- mKeySelectionListener = (OnAsymmetricKeySelection) activity;
+ mEncryptInterface = (EncryptActivityInterface) activity;
} catch (ClassCastException e) {
- throw new ClassCastException(activity.toString() + " must implement OnAsymmetricKeySelection");
+ throw new ClassCastException(activity.toString() + " must implement EncryptActivityInterface");
}
}
private void setSignatureKeyId(long signatureKeyId) {
- mSecretKeyId = signatureKeyId;
- // update key selection in EncryptActivity
- mKeySelectionListener.onSigningKeySelected(signatureKeyId);
- updateView();
+ mEncryptInterface.setSignatureKey(signatureKeyId);
}
private void setEncryptionKeyIds(long[] encryptionKeyIds) {
- mEncryptionKeyIds = encryptionKeyIds;
- // update key selection in EncryptActivity
- mKeySelectionListener.onEncryptionKeysSelected(encryptionKeyIds);
- updateView();
+ mEncryptInterface.setEncryptionKeys(encryptionKeyIds);
+ }
+
+ private void setEncryptionUserIds(String[] encryptionUserIds) {
+ mEncryptInterface.setEncryptionUsers(encryptionUserIds);
}
/**
@@ -101,25 +101,20 @@ public class EncryptAsymmetricFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.encrypt_asymmetric_fragment, container, false);
- mSelectKeysButton = (Button) view.findViewById(R.id.btn_selectEncryptKeys);
- mSign = (CheckBox) view.findViewById(R.id.sign);
- mMainUserId = (TextView) view.findViewById(R.id.mainUserId);
- mMainUserIdRest = (TextView) view.findViewById(R.id.mainUserIdRest);
- mSelectKeysButton.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- selectPublicKeys();
- }
- });
- mSign.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- CheckBox checkBox = (CheckBox) v;
- if (checkBox.isChecked()) {
- selectSecretKey();
- } else {
- setSignatureKeyId(Constants.key.none);
- }
+ mSign = (Spinner) view.findViewById(R.id.sign);
+ mSign.setAdapter(mSignAdapter);
+ mSign.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ setSignatureKeyId(parent.getAdapter().getItemId(position));
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+ setSignatureKeyId(Constants.key.none);
}
});
+ mEncryptKeyView = (EncryptKeyCompletionView) view.findViewById(R.id.recipient_list);
return view;
}
@@ -135,6 +130,65 @@ public class EncryptAsymmetricFragment extends Fragment {
// preselect keys given by arguments (given by Intent to EncryptActivity)
preselectKeys(signatureKeyId, encryptionKeyIds, mProviderHelper);
+
+ getLoaderManager().initLoader(1, null, new LoaderManager.LoaderCallbacks() {
+ @Override
+ public Loader onCreateLoader(int id, Bundle args) {
+ // This is called when a new Loader needs to be created. This
+ // sample only has one Loader, so we don't care about the ID.
+ Uri baseUri = KeyRings.buildUnifiedKeyRingsUri();
+
+ // These are the rows that we will retrieve.
+ String[] projection = new String[]{
+ KeyRings._ID,
+ KeyRings.MASTER_KEY_ID,
+ KeyRings.KEY_ID,
+ KeyRings.USER_ID,
+ KeyRings.EXPIRY,
+ KeyRings.IS_REVOKED,
+ // can certify info only related to master key
+ KeyRings.CAN_CERTIFY,
+ // has sign may be any subkey
+ KeyRings.HAS_SIGN,
+ KeyRings.HAS_ANY_SECRET,
+ KeyRings.HAS_SECRET
+ };
+
+ String where = KeyRings.HAS_ANY_SECRET + " = 1";
+
+ // Now create and return a CursorLoader that will take care of
+ // creating a Cursor for the data being displayed.
+ return new CursorLoader(getActivity(), baseUri, projection, where, null, null);
+ /*return new CursorLoader(getActivity(), KeyRings.buildUnifiedKeyRingsUri(),
+ new String[]{KeyRings.USER_ID, KeyRings.KEY_ID, KeyRings.MASTER_KEY_ID, KeyRings.HAS_ANY_SECRET}, SIGN_KEY_SELECTION,
+ null, null);*/
+ }
+
+ @Override
+ public void onLoadFinished(Loader loader, Cursor data) {
+ mSignAdapter.swapCursor(data);
+ }
+
+ @Override
+ public void onLoaderReset(Loader loader) {
+ mSignAdapter.swapCursor(null);
+ }
+ });
+ mEncryptKeyView.setTokenListener(new TokenCompleteTextView.TokenListener() {
+ @Override
+ public void onTokenAdded(Object token) {
+ if (token instanceof EncryptKeyCompletionView.EncryptionKey) {
+ updateEncryptionKeys();
+ }
+ }
+
+ @Override
+ public void onTokenRemoved(Object token) {
+ if (token instanceof EncryptKeyCompletionView.EncryptionKey) {
+ updateEncryptionKeys();
+ }
+ }
+ });
}
/**
@@ -161,117 +215,125 @@ public class EncryptAsymmetricFragment extends Fragment {
}
if (preselectedEncryptionKeyIds != null) {
- Vector goodIds = new Vector();
- for (int i = 0; i < preselectedEncryptionKeyIds.length; ++i) {
+ for (long preselectedId : preselectedEncryptionKeyIds) {
try {
- long id = providerHelper.getCachedPublicKeyRing(
- KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(
- preselectedEncryptionKeyIds[i])
- ).getMasterKeyId();
- goodIds.add(id);
+ CachedPublicKeyRing ring = providerHelper.getCachedPublicKeyRing(
+ KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(preselectedId));
+ mEncryptKeyView.addObject(mEncryptKeyView.new EncryptionKey(ring));
} catch (PgpGeneralException e) {
Log.e(Constants.TAG, "key not found!", e);
}
}
- if (goodIds.size() > 0) {
- long[] keyIds = new long[goodIds.size()];
- for (int i = 0; i < goodIds.size(); ++i) {
- keyIds[i] = goodIds.get(i);
- }
- setEncryptionKeyIds(keyIds);
- }
+ updateEncryptionKeys();
}
}
- private void updateView() {
- if (mEncryptionKeyIds == null || mEncryptionKeyIds.length == 0) {
- mSelectKeysButton.setText(getString(R.string.select_keys_button_default));
- } else {
- mSelectKeysButton.setText(getResources().getQuantityString(
- R.plurals.select_keys_button, mEncryptionKeyIds.length,
- mEncryptionKeyIds.length));
+ private void updateEncryptionKeys() {
+ List