diff options
Diffstat (limited to 'OpenKeychain/src/main/java')
27 files changed, 1631 insertions, 343 deletions
diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/ImportKeysListEntry.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/ImportKeysListEntry.java index 79065604a..7dac8b1e0 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/ImportKeysListEntry.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/ImportKeysListEntry.java @@ -294,8 +294,9 @@ public class ImportKeysListEntry implements Serializable, Parcelable { mKeyId = key.getKeyId(); mKeyIdHex = KeyFormattingUtils.convertKeyIdToHex(mKeyId); - mRevoked = key.isMaybeRevoked(); - mExpired = key.isMaybeExpired(); + // NOTE: Dont use maybe methods for now, they can be wrong. + mRevoked = false; //key.isMaybeRevoked(); + mExpired = false; //key.isMaybeExpired(); mFingerprintHex = KeyFormattingUtils.convertFingerprintToHex(key.getFingerprint()); mBitStrength = key.getBitStrength(); mCurveOid = key.getCurveOid(); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/operations/CertifyOperation.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/operations/CertifyOperation.java index 2e9551826..65bc6381b 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/operations/CertifyOperation.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/operations/CertifyOperation.java @@ -20,6 +20,7 @@ import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.provider.ProviderHelper.NotFoundException; import org.sufficientlysecure.keychain.service.CertifyActionsParcel; import org.sufficientlysecure.keychain.service.CertifyActionsParcel.CertifyAction; +import org.sufficientlysecure.keychain.service.ContactSyncAdapterService; import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils; import org.sufficientlysecure.keychain.util.Log; @@ -191,6 +192,9 @@ public class CertifyOperation extends BaseOperation { } log.add(LogType.MSG_CRT_SUCCESS, 0); + //since only verified keys are synced to contacts, we need to initiate a sync now + ContactSyncAdapterService.requestSync(); + return new CertifyResult(CertifyResult.RESULT_OK, log, certifyOk, certifyError, uploadOk, uploadError); } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/CanonicalizedSecretKey.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/CanonicalizedSecretKey.java index c3fccc789..ab91d7747 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/CanonicalizedSecretKey.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/CanonicalizedSecretKey.java @@ -18,9 +18,7 @@ package org.sufficientlysecure.keychain.pgp; -import org.spongycastle.bcpg.HashAlgorithmTags; import org.spongycastle.bcpg.S2K; -import org.spongycastle.bcpg.SymmetricKeyAlgorithmTags; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPPrivateKey; import org.spongycastle.openpgp.PGPPublicKey; @@ -31,7 +29,6 @@ import org.spongycastle.openpgp.PGPSignatureGenerator; import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; import org.spongycastle.openpgp.PGPSignatureSubpacketVector; import org.spongycastle.openpgp.PGPUserAttributeSubpacketVector; -import org.spongycastle.openpgp.PGPUtil; import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor; import org.spongycastle.openpgp.operator.PGPContentSignerBuilder; import org.spongycastle.openpgp.operator.PublicKeyDataDecryptorFactory; @@ -43,13 +40,11 @@ import org.spongycastle.openpgp.operator.jcajce.NfcSyncPublicKeyDataDecryptorFac import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import org.sufficientlysecure.keychain.pgp.exception.PgpKeyNotFoundException; -import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; -import java.util.LinkedList; import java.util.List; /** @@ -287,9 +282,8 @@ public class CanonicalizedSecretKey extends CanonicalizedPublicKey { // create a signatureGenerator from the supplied masterKeyId and passphrase PGPSignatureGenerator signatureGenerator; { - // TODO: SHA256 fixed? - PGPContentSignerBuilder contentSignerBuilder = getContentSignerBuilder(PGPUtil.SHA256, - nfcSignedHash, nfcCreationTimestamp); + PGPContentSignerBuilder contentSignerBuilder = getContentSignerBuilder( + PgpConstants.CERTIFY_HASH_ALGO, nfcSignedHash, nfcCreationTimestamp); signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder); try { @@ -351,9 +345,8 @@ public class CanonicalizedSecretKey extends CanonicalizedPublicKey { // create a signatureGenerator from the supplied masterKeyId and passphrase PGPSignatureGenerator signatureGenerator; { - // TODO: SHA256 fixed? - PGPContentSignerBuilder contentSignerBuilder = getContentSignerBuilder(PGPUtil.SHA256, - nfcSignedHash, nfcCreationTimestamp); + PGPContentSignerBuilder contentSignerBuilder = getContentSignerBuilder( + PgpConstants.CERTIFY_HASH_ALGO, nfcSignedHash, nfcCreationTimestamp); signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder); try { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/OpenPgpSignatureResultBuilder.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/OpenPgpSignatureResultBuilder.java index 46defebf7..ed4715681 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/OpenPgpSignatureResultBuilder.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/OpenPgpSignatureResultBuilder.java @@ -104,8 +104,8 @@ public class OpenPgpSignatureResultBuilder { setUserIds(signingRing.getUnorderedUserIds()); // either master key is expired/revoked or this specific subkey is expired/revoked - setKeyExpired(signingRing.isExpired() || signingKey.isMaybeExpired()); - setKeyRevoked(signingRing.isRevoked() || signingKey.isMaybeRevoked()); + setKeyExpired(signingRing.isExpired() || signingKey.isExpired()); + setKeyRevoked(signingRing.isRevoked() || signingKey.isRevoked()); } public OpenPgpSignatureResult build() { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConstants.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConstants.java index 90991ba15..aef9a5cdb 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConstants.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpConstants.java @@ -58,6 +58,8 @@ public class PgpConstants { sPreferredCompressionAlgorithms.add(CompressionAlgorithmTags.ZIP); } + public static final int CERTIFY_HASH_ALGO = HashAlgorithmTags.SHA256; + /* * Note: s2kcount is a number between 0 and 0xff that controls the * number of times to iterate the password hash before use. More diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedUserAttribute.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedUserAttribute.java index 8e23d36d9..2c7f0187a 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedUserAttribute.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedUserAttribute.java @@ -109,6 +109,15 @@ public class WrappedUserAttribute implements Serializable { } + public byte[][] getSubpackets() { + UserAttributeSubpacket[] subpackets = mVector.toSubpacketArray(); + byte[][] ret = new byte[subpackets.length][]; + for (int i = 0; i < subpackets.length; i++) { + ret[i] = subpackets[i].getData(); + } + return ret; + } + private void readObjectNoData() throws ObjectStreamException { } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java index b88cd6006..4a162989f 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/KeychainDatabase.java @@ -53,7 +53,7 @@ import java.io.IOException; */ public class KeychainDatabase extends SQLiteOpenHelper { private static final String DATABASE_NAME = "openkeychain.db"; - private static final int DATABASE_VERSION = 8; + private static final int DATABASE_VERSION = 9; static Boolean apgHack = false; private Context mContext; @@ -61,7 +61,7 @@ public class KeychainDatabase extends SQLiteOpenHelper { String KEY_RINGS_PUBLIC = "keyrings_public"; String KEY_RINGS_SECRET = "keyrings_secret"; String KEYS = "keys"; - String USER_PACKETS = "user_ids"; + String USER_PACKETS = "user_packets"; String CERTS = "certs"; String API_APPS = "api_apps"; String API_ACCOUNTS = "api_accounts"; @@ -119,8 +119,7 @@ public class KeychainDatabase extends SQLiteOpenHelper { + UserPacketsColumns.IS_REVOKED + " INTEGER, " + UserPacketsColumns.RANK+ " INTEGER, " - + "PRIMARY KEY(" + UserPacketsColumns.MASTER_KEY_ID + ", " + UserPacketsColumns.USER_ID + "), " - + "UNIQUE (" + UserPacketsColumns.MASTER_KEY_ID + ", " + UserPacketsColumns.RANK + "), " + + "PRIMARY KEY(" + UserPacketsColumns.MASTER_KEY_ID + ", " + UserPacketsColumns.RANK + "), " + "FOREIGN KEY(" + UserPacketsColumns.MASTER_KEY_ID + ") REFERENCES " + Tables.KEY_RINGS_PUBLIC + "(" + KeyRingsColumns.MASTER_KEY_ID + ") ON DELETE CASCADE" + ")"; @@ -267,6 +266,13 @@ public class KeychainDatabase extends SQLiteOpenHelper { } catch (Exception e) { // never mind, the column probably already existed } + case 9: + // tbale name for user_ids changed to user_packets + db.execSQL("DROP TABLE IF EXISTS certs"); + db.execSQL("DROP TABLE IF EXISTS user_ids"); + db.execSQL(CREATE_USER_PACKETS); + db.execSQL(CREATE_CERTS); + } // always do consolidate after upgrade diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java index 6366e8536..1d3934620 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/ProviderHelper.java @@ -28,6 +28,7 @@ import android.net.Uri; import android.os.RemoteException; import android.support.v4.util.LongSparseArray; +import org.spongycastle.bcpg.CompressionAlgorithmTags; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.keyimport.ParcelableKeyRing; @@ -43,6 +44,7 @@ import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey; import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.SecretKeyType; import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing; import org.sufficientlysecure.keychain.pgp.KeyRing; +import org.sufficientlysecure.keychain.pgp.PgpConstants; import org.sufficientlysecure.keychain.pgp.PgpHelper; import org.sufficientlysecure.keychain.pgp.Progressable; import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; @@ -81,15 +83,15 @@ import java.util.Iterator; import java.util.List; import java.util.Set; -/** This class contains high level methods for database access. Despite its +/** + * This class contains high level methods for database access. Despite its * name, it is not only a helper but actually the main interface for all * synchronous database operations. - * + * <p/> * Operations in this class write logs. These can be obtained from the * OperationResultParcel return values directly, but are also accumulated over * the lifetime of the executing ProviderHelper object unless the resetLog() * method is called to start a new one specifically. - * */ public class ProviderHelper { private final Context mContext; @@ -126,12 +128,13 @@ public class ProviderHelper { } public void log(LogType type) { - if(mLog != null) { + if (mLog != null) { mLog.add(type, mIndent); } } + public void log(LogType type, Object... parameters) { - if(mLog != null) { + if (mLog != null) { mLog.add(type, mIndent, parameters); } } @@ -213,7 +216,7 @@ public class ProviderHelper { } private LongSparseArray<CanonicalizedPublicKey> getTrustedMasterKeys() { - Cursor cursor = mContentResolver.query(KeyRings.buildUnifiedKeyRingsUri(), new String[] { + Cursor cursor = mContentResolver.query(KeyRings.buildUnifiedKeyRingsUri(), new String[]{ KeyRings.MASTER_KEY_ID, // we pick from cache only information that is not easily available from keyrings KeyRings.HAS_ANY_SECRET, KeyRings.VERIFIED, @@ -288,7 +291,7 @@ public class ProviderHelper { boolean hasAnySecret = cursor.getInt(0) > 0; int verified = cursor.getInt(1); byte[] blob = cursor.getBlob(2); - if(secret &! hasAnySecret) { + if (secret & !hasAnySecret) { throw new NotFoundException("Secret key not available!"); } return secret @@ -305,7 +308,7 @@ public class ProviderHelper { } // bits, in order: CESA. make SURE these are correct, we will get bad log entries otherwise!! - static final LogType LOG_TYPES_FLAG_MASTER[] = new LogType[] { + static final LogType LOG_TYPES_FLAG_MASTER[] = new LogType[]{ LogType.MSG_IP_MASTER_FLAGS_XXXX, LogType.MSG_IP_MASTER_FLAGS_CXXX, LogType.MSG_IP_MASTER_FLAGS_XEXX, LogType.MSG_IP_MASTER_FLAGS_CEXX, LogType.MSG_IP_MASTER_FLAGS_XXSX, LogType.MSG_IP_MASTER_FLAGS_CXSX, @@ -317,7 +320,7 @@ public class ProviderHelper { }; // same as above, but for subkeys - static final LogType LOG_TYPES_FLAG_SUBKEY[] = new LogType[] { + static final LogType LOG_TYPES_FLAG_SUBKEY[] = new LogType[]{ LogType.MSG_IP_SUBKEY_FLAGS_XXXX, LogType.MSG_IP_SUBKEY_FLAGS_CXXX, LogType.MSG_IP_SUBKEY_FLAGS_XEXX, LogType.MSG_IP_SUBKEY_FLAGS_CEXX, LogType.MSG_IP_SUBKEY_FLAGS_XXSX, LogType.MSG_IP_SUBKEY_FLAGS_CXSX, @@ -328,8 +331,9 @@ public class ProviderHelper { LogType.MSG_IP_SUBKEY_FLAGS_XESA, LogType.MSG_IP_SUBKEY_FLAGS_CESA }; - /** Saves an UncachedKeyRing of the public variant into the db. - * + /** + * Saves an UncachedKeyRing of the public variant into the db. + * <p/> * This method will not delete all previous data for this masterKeyId from the database prior * to inserting. All public data is effectively re-inserted, secret keyrings are left deleted * and need to be saved externally to be preserved past the operation. @@ -403,7 +407,7 @@ public class ProviderHelper { if (key.getKeyUsage() == null) { log(LogType.MSG_IP_MASTER_FLAGS_UNSPECIFIED); } else { - log(LOG_TYPES_FLAG_MASTER[(c?1:0) + (e?2:0) + (s?4:0) + (a?8:0)]); + log(LOG_TYPES_FLAG_MASTER[(c ? 1 : 0) + (e ? 2 : 0) + (s ? 4 : 0) + (a ? 8 : 0)]); } } else { if (key.getKeyUsage() == null) { @@ -492,7 +496,7 @@ public class ProviderHelper { try { cert.init(trustedKey); // if it doesn't certify, leave a note and skip - if ( ! cert.verifySignature(masterKey, rawUserId)) { + if (!cert.verifySignature(masterKey, rawUserId)) { log(LogType.MSG_IP_UID_CERT_BAD); continue; } @@ -537,7 +541,7 @@ public class ProviderHelper { ArrayList<WrappedUserAttribute> userAttributes = masterKey.getUnorderedUserAttributes(); // Don't spam the log if there aren't even any attributes - if ( ! userAttributes.isEmpty()) { + if (!userAttributes.isEmpty()) { log(LogType.MSG_IP_UAT_CLASSIFYING); } @@ -592,7 +596,7 @@ public class ProviderHelper { try { cert.init(trustedKey); // if it doesn't certify, leave a note and skip - if ( ! cert.verifySignature(masterKey, userAttribute)) { + if (!cert.verifySignature(masterKey, userAttribute)) { log(LogType.MSG_IP_UAT_CERT_BAD); continue; } @@ -660,7 +664,7 @@ public class ProviderHelper { selfCertsAreTrusted ? Certs.VERIFIED_SECRET : Certs.VERIFIED_SELF)); // iterate over signatures - for (int i = 0; i < item.trustedCerts.size() ; i++) { + for (int i = 0; i < item.trustedCerts.size(); i++) { WrappedSignature sig = item.trustedCerts.valueAt(i); // if it's a revocation if (sig.isRevocation()) { @@ -725,7 +729,7 @@ public class ProviderHelper { public int compareTo(UserPacketItem o) { // revoked keys always come last! //noinspection DoubleNegation - if ( (selfRevocation != null) != (o.selfRevocation != null)) { + if ((selfRevocation != null) != (o.selfRevocation != null)) { return selfRevocation != null ? 1 : -1; } // if one is a user id, but the other isn't, the user id always comes first. @@ -742,7 +746,8 @@ public class ProviderHelper { } } - /** Saves an UncachedKeyRing of the secret variant into the db. + /** + * Saves an UncachedKeyRing of the secret variant into the db. * This method will fail if no corresponding public keyring is in the database! */ private int saveCanonicalizedSecretKeyRing(CanonicalizedSecretKeyRing keyRing) { @@ -789,7 +794,7 @@ public class ProviderHelper { SecretKeyType mode = sub.getSecretKeyType(); values.put(Keys.HAS_SECRET, mode.getNum()); int upd = mContentResolver.update(uri, values, Keys.KEY_ID + " = ?", - new String[]{ Long.toString(id) }); + new String[]{Long.toString(id)}); if (upd == 1) { switch (mode) { case PASSPHRASE: @@ -843,8 +848,9 @@ public class ProviderHelper { return savePublicKeyRing(keyRing, new ProgressScaler()); } - /** Save a public keyring into the database. - * + /** + * Save a public keyring into the database. + * <p/> * This is a high level method, which takes care of merging all new information into the old and * keep public and secret keyrings in sync. */ @@ -949,7 +955,7 @@ public class ProviderHelper { log(LogType.MSG_IS, KeyFormattingUtils.convertKeyIdToHex(masterKeyId)); mIndent += 1; - if ( ! secretRing.isSecret()) { + if (!secretRing.isSecret()) { log(LogType.MSG_IS_BAD_TYPE_PUBLIC); return new SaveKeyringResult(SaveKeyringResult.RESULT_ERROR, mLog, null); } @@ -1076,9 +1082,8 @@ public class ProviderHelper { log.add(LogType.MSG_CON_SAVE_SECRET, indent); indent += 1; - final Cursor cursor = mContentResolver.query(KeyRings.buildUnifiedKeyRingsUri(), new String[]{ - KeyRings.PRIVKEY_DATA, KeyRings.FINGERPRINT, KeyRings.HAS_ANY_SECRET - }, KeyRings.HAS_ANY_SECRET + " = 1", null, null); + final Cursor cursor = mContentResolver.query(KeyRingData.buildSecretKeyRingUri(), + new String[]{ KeyRingData.KEY_RING_DATA }, null, null, null); if (cursor == null) { log.add(LogType.MSG_CON_ERROR_DB, indent); @@ -1100,8 +1105,7 @@ public class ProviderHelper { if (cursor.isAfterLast()) { return false; } - ring = new ParcelableKeyRing(KeyFormattingUtils.convertFingerprintToHex(cursor.getBlob(1)), cursor.getBlob(0) - ); + ring = new ParcelableKeyRing(cursor.getBlob(0)); cursor.moveToNext(); return true; } @@ -1138,9 +1142,9 @@ public class ProviderHelper { log.add(LogType.MSG_CON_SAVE_PUBLIC, indent); indent += 1; - final Cursor cursor = mContentResolver.query(KeyRings.buildUnifiedKeyRingsUri(), new String[]{ - KeyRings.PUBKEY_DATA, KeyRings.FINGERPRINT - }, null, null, null); + final Cursor cursor = mContentResolver.query( + KeyRingData.buildPublicKeyRingUri(), + new String[]{ KeyRingData.KEY_RING_DATA }, null, null, null); if (cursor == null) { log.add(LogType.MSG_CON_ERROR_DB, indent); @@ -1162,8 +1166,7 @@ public class ProviderHelper { if (cursor.isAfterLast()) { return false; } - ring = new ParcelableKeyRing(KeyFormattingUtils.convertFingerprintToHex(cursor.getBlob(1)), cursor.getBlob(0) - ); + ring = new ParcelableKeyRing(cursor.getBlob(0)); cursor.moveToNext(); return true; } @@ -1420,9 +1423,13 @@ public class ProviderHelper { ContentValues values = new ContentValues(); values.put(KeychainContract.ApiAccounts.ACCOUNT_NAME, accSettings.getAccountName()); values.put(KeychainContract.ApiAccounts.KEY_ID, accSettings.getKeyId()); - values.put(KeychainContract.ApiAccounts.COMPRESSION, accSettings.getCompression()); - values.put(KeychainContract.ApiAccounts.ENCRYPTION_ALGORITHM, accSettings.getEncryptionAlgorithm()); - values.put(KeychainContract.ApiAccounts.HASH_ALORITHM, accSettings.getHashAlgorithm()); + + // DEPRECATED and thus hardcoded + values.put(KeychainContract.ApiAccounts.COMPRESSION, CompressionAlgorithmTags.ZLIB); + values.put(KeychainContract.ApiAccounts.ENCRYPTION_ALGORITHM, + PgpConstants.OpenKeychainSymmetricKeyAlgorithmTags.USE_PREFERRED); + values.put(KeychainContract.ApiAccounts.HASH_ALORITHM, + PgpConstants.OpenKeychainHashAlgorithmTags.USE_PREFERRED); return values; } @@ -1478,12 +1485,6 @@ public class ProviderHelper { cursor.getColumnIndex(KeychainContract.ApiAccounts.ACCOUNT_NAME))); settings.setKeyId(cursor.getLong( cursor.getColumnIndex(KeychainContract.ApiAccounts.KEY_ID))); - settings.setCompression(cursor.getInt( - cursor.getColumnIndexOrThrow(KeychainContract.ApiAccounts.COMPRESSION))); - settings.setHashAlgorithm(cursor.getInt( - cursor.getColumnIndexOrThrow(KeychainContract.ApiAccounts.HASH_ALORITHM))); - settings.setEncryptionAlgorithm(cursor.getInt( - cursor.getColumnIndexOrThrow(KeychainContract.ApiAccounts.ENCRYPTION_ALGORITHM))); } } finally { if (cursor != null) { @@ -1547,26 +1548,32 @@ public class ProviderHelper { } } + public void addAllowedKeyIdForApp(Uri uri, long allowedKeyId) { + ContentValues values = new ContentValues(); + values.put(ApiAllowedKeys.KEY_ID, allowedKeyId); + mContentResolver.insert(uri, values); + } + public Set<String> getAllFingerprints(Uri uri) { - Set<String> fingerprints = new HashSet<>(); - String[] projection = new String[]{KeyRings.FINGERPRINT}; - Cursor cursor = mContentResolver.query(uri, projection, null, null, null); - try { - if(cursor != null) { - int fingerprintColumn = cursor.getColumnIndex(KeyRings.FINGERPRINT); - while(cursor.moveToNext()) { - fingerprints.add( + Set<String> fingerprints = new HashSet<>(); + String[] projection = new String[]{KeyRings.FINGERPRINT}; + Cursor cursor = mContentResolver.query(uri, projection, null, null, null); + try { + if (cursor != null) { + int fingerprintColumn = cursor.getColumnIndex(KeyRings.FINGERPRINT); + while (cursor.moveToNext()) { + fingerprints.add( KeyFormattingUtils.convertFingerprintToHex(cursor.getBlob(fingerprintColumn)) - ); - } - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return fingerprints; - } + ); + } + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return fingerprints; + } public byte[] getApiAppSignature(String packageName) { Uri queryUri = ApiApps.buildByPackageNameUri(packageName); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/AccountSettings.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/AccountSettings.java index 6cffeeb53..5d23176be 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/AccountSettings.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/AccountSettings.java @@ -17,17 +17,14 @@ package org.sufficientlysecure.keychain.remote; -import org.spongycastle.bcpg.CompressionAlgorithmTags; -import org.spongycastle.bcpg.HashAlgorithmTags; -import org.spongycastle.openpgp.PGPEncryptedData; import org.sufficientlysecure.keychain.Constants; +/** + * DEPRECATED API + */ public class AccountSettings { private String mAccountName; private long mKeyId = Constants.key.none; - private int mEncryptionAlgorithm; - private int mHashAlgorithm; - private int mCompression; public AccountSettings() { @@ -36,11 +33,6 @@ public class AccountSettings { public AccountSettings(String accountName) { super(); this.mAccountName = accountName; - - // defaults: - this.mEncryptionAlgorithm = PGPEncryptedData.AES_256; - this.mHashAlgorithm = HashAlgorithmTags.SHA256; - this.mCompression = CompressionAlgorithmTags.ZLIB; } public String getAccountName() { @@ -59,28 +51,4 @@ public class AccountSettings { this.mKeyId = scretKeyId; } - public int getEncryptionAlgorithm() { - return mEncryptionAlgorithm; - } - - public void setEncryptionAlgorithm(int encryptionAlgorithm) { - this.mEncryptionAlgorithm = encryptionAlgorithm; - } - - public int getHashAlgorithm() { - return mHashAlgorithm; - } - - public void setHashAlgorithm(int hashAlgorithm) { - this.mHashAlgorithm = hashAlgorithm; - } - - public int getCompression() { - return mCompression; - } - - public void setCompression(int compression) { - this.mCompression = compression; - } - } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java index 390e85ef8..a4bc95602 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/OpenPgpService.java @@ -47,6 +47,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.remote.ui.RemoteServiceActivity; +import org.sufficientlysecure.keychain.remote.ui.SelectSignKeyIdActivity; import org.sufficientlysecure.keychain.ui.ImportKeysActivity; import org.sufficientlysecure.keychain.ui.NfcActivity; import org.sufficientlysecure.keychain.ui.PassphraseDialogActivity; @@ -232,8 +233,7 @@ public class OpenPgpService extends RemoteService { } private Intent signImpl(Intent data, ParcelFileDescriptor input, - ParcelFileDescriptor output, AccountSettings accSettings, - boolean cleartextSign) { + ParcelFileDescriptor output, boolean cleartextSign) { InputStream is = null; OutputStream os = null; try { @@ -246,6 +246,17 @@ public class OpenPgpService extends RemoteService { Log.d(Constants.TAG, "nfcSignedHash: null"); } + Intent signKeyIdIntent = getSignKeyMasterId(data); + // NOTE: Fallback to return account settings (Old API) + if (signKeyIdIntent.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR) + == OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED) { + return signKeyIdIntent; + } + long signKeyId = signKeyIdIntent.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, Constants.key.none); + if (signKeyId == Constants.key.none) { + Log.e(Constants.TAG, "No signing key given!"); + } + // carefully: only set if timestamp exists Date nfcCreationDate = null; long nfcCreationTimestamp = data.getLongExtra(OpenPgpApi.EXTRA_NFC_SIG_CREATION_TIMESTAMP, -1); @@ -271,7 +282,7 @@ public class OpenPgpService extends RemoteService { .setDetachedSignature(!cleartextSign) .setVersionHeader(null) .setSignatureHashAlgorithm(PgpConstants.OpenKeychainHashAlgorithmTags.USE_PREFERRED) - .setSignatureMasterKeyId(accSettings.getKeyId()) + .setSignatureMasterKeyId(signKeyId) .setNfcState(nfcSignedHash, nfcCreationDate); // execute PGP operation! @@ -336,8 +347,7 @@ public class OpenPgpService extends RemoteService { } private Intent encryptAndSignImpl(Intent data, ParcelFileDescriptor input, - ParcelFileDescriptor output, AccountSettings accSettings, - boolean sign) { + ParcelFileDescriptor output, boolean sign) { InputStream is = null; OutputStream os = null; try { @@ -347,6 +357,14 @@ public class OpenPgpService extends RemoteService { originalFilename = ""; } + boolean enableCompression = data.getBooleanExtra(OpenPgpApi.EXTRA_ENABLE_COMPRESSION, true); + int compressionId; + if (enableCompression) { + compressionId = CompressionAlgorithmTags.ZLIB; + } else { + compressionId = CompressionAlgorithmTags.UNCOMPRESSED; + } + // first try to get key ids from non-ambiguous key id extra long[] keyIds = data.getLongArrayExtra(OpenPgpApi.EXTRA_KEY_IDS); if (keyIds == null) { @@ -374,14 +392,24 @@ public class OpenPgpService extends RemoteService { PgpSignEncryptInput pseInput = new PgpSignEncryptInput(); pseInput.setEnableAsciiArmorOutput(asciiArmor) .setVersionHeader(null) - .setCompressionId(CompressionAlgorithmTags.UNCOMPRESSED) + .setCompressionId(compressionId) .setSymmetricEncryptionAlgorithm(PgpConstants.OpenKeychainSymmetricKeyAlgorithmTags.USE_PREFERRED) .setEncryptionMasterKeyIds(keyIds) - .setFailOnMissingEncryptionKeyIds(true) - .setAdditionalEncryptId(accSettings.getKeyId()); // add acc key for encryption + .setFailOnMissingEncryptionKeyIds(true); if (sign) { + Intent signKeyIdIntent = getSignKeyMasterId(data); + // NOTE: Fallback to return account settings (Old API) + if (signKeyIdIntent.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR) + == OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED) { + return signKeyIdIntent; + } + long signKeyId = signKeyIdIntent.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, Constants.key.none); + if (signKeyId == Constants.key.none) { + Log.e(Constants.TAG, "No signing key given!"); + } + byte[] nfcSignedHash = data.getByteArrayExtra(OpenPgpApi.EXTRA_NFC_SIGNED_HASH); // carefully: only set if timestamp exists Date nfcCreationDate = null; @@ -392,8 +420,9 @@ public class OpenPgpService extends RemoteService { // sign and encrypt pseInput.setSignatureHashAlgorithm(PgpConstants.OpenKeychainHashAlgorithmTags.USE_PREFERRED) - .setSignatureMasterKeyId(accSettings.getKeyId()) - .setNfcState(nfcSignedHash, nfcCreationDate); + .setSignatureMasterKeyId(signKeyId) + .setNfcState(nfcSignedHash, nfcCreationDate) + .setAdditionalEncryptId(signKeyId); // add sign key for encryption } PgpSignEncryptOperation op = new PgpSignEncryptOperation(this, new ProviderHelper(getContext()), null); @@ -455,8 +484,7 @@ public class OpenPgpService extends RemoteService { } private Intent decryptAndVerifyImpl(Intent data, ParcelFileDescriptor input, - ParcelFileDescriptor output, Set<Long> allowedKeyIds, - boolean decryptMetadataOnly) { + ParcelFileDescriptor output, boolean decryptMetadataOnly) { InputStream is = null; OutputStream os = null; try { @@ -470,6 +498,16 @@ public class OpenPgpService extends RemoteService { os = new ParcelFileDescriptor.AutoCloseOutputStream(output); } + String currentPkg = getCurrentCallingPackage(); + Set<Long> allowedKeyIds; + if (data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) < 7) { + allowedKeyIds = mProviderHelper.getAllKeyIdsForApp( + ApiAccounts.buildBaseUri(currentPkg)); + } else { + allowedKeyIds = mProviderHelper.getAllowedKeyIdsForApp( + KeychainContract.ApiAllowedKeys.buildBaseUri(currentPkg)); + } + String passphrase = data.getStringExtra(OpenPgpApi.EXTRA_PASSPHRASE); long inputLength = is.available(); InputData inputData = new InputData(is, inputLength); @@ -516,9 +554,16 @@ public class OpenPgpService extends RemoteService { } } else if (pgpResult.success()) { Intent result = new Intent(); + int resultType = OpenPgpApi.RESULT_TYPE_UNENCRYPTED_UNSIGNED; OpenPgpSignatureResult signatureResult = pgpResult.getSignatureResult(); if (signatureResult != null) { + resultType |= OpenPgpApi.RESULT_TYPE_SIGNED; + if (!signatureResult.isSignatureOnly()) { + resultType |= OpenPgpApi.RESULT_TYPE_ENCRYPTED; + } + result.putExtra(OpenPgpApi.RESULT_TYPE, resultType); + result.putExtra(OpenPgpApi.RESULT_SIGNATURE, signatureResult); if (data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) < 5) { @@ -615,6 +660,27 @@ public class OpenPgpService extends RemoteService { } } + private Intent getSignKeyIdImpl(Intent data) { + String preferredUserId = data.getStringExtra(OpenPgpApi.EXTRA_USER_ID); + + Intent intent = new Intent(getBaseContext(), SelectSignKeyIdActivity.class); + String currentPkg = getCurrentCallingPackage(); + intent.setData(KeychainContract.ApiApps.buildByPackageNameUri(currentPkg)); + intent.putExtra(SelectSignKeyIdActivity.EXTRA_USER_ID, preferredUserId); + intent.putExtra(SelectSignKeyIdActivity.EXTRA_DATA, data); + + PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, + intent, + PendingIntent.FLAG_CANCEL_CURRENT); + + // return PendingIntent to be executed by client + Intent result = new Intent(); + result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); + result.putExtra(OpenPgpApi.RESULT_INTENT, pi); + + return result; + } + private Intent getKeyIdsImpl(Intent data) { // if data already contains key ids extra GET_KEY_IDS has been executed again // after user interaction. Then, we just need to return the array again! @@ -632,6 +698,35 @@ public class OpenPgpService extends RemoteService { } } + private Intent getSignKeyMasterId(Intent data) { + // NOTE: Accounts are deprecated on API version >= 7 + if (data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) < 7) { + String accName = data.getStringExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME); + // if no account name is given use name "default" + if (TextUtils.isEmpty(accName)) { + accName = "default"; + } + Log.d(Constants.TAG, "accName: " + accName); + // fallback to old API + final AccountSettings accSettings = getAccSettings(accName); + if (accSettings == null || (accSettings.getKeyId() == Constants.key.none)) { + return getCreateAccountIntent(data, accName); + } + + // NOTE: just wrapping the key id + Intent result = new Intent(); + result.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, accSettings.getKeyId()); + return result; + } else { + long signKeyId = data.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, Constants.key.none); + if (signKeyId == Constants.key.none) { + return getSignKeyIdImpl(data); + } + + return data; + } + } + /** * Check requirements: * - params != null @@ -657,12 +752,13 @@ public class OpenPgpService extends RemoteService { if (data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != 3 && data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != 4 && data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != 5 - && data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != 6) { + && data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != 6 + && data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) != 7) { Intent result = new Intent(); OpenPgpError error = new OpenPgpError (OpenPgpError.INCOMPATIBLE_API_VERSIONS, "Incompatible API versions!\n" + "used API version: " + data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) + "\n" - + "supported API versions: 3, 4, 5, 6"); + + "supported API versions: 3-7"); result.putExtra(OpenPgpApi.RESULT_ERROR, error); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); return result; @@ -677,16 +773,6 @@ public class OpenPgpService extends RemoteService { return null; } - private String getAccountName(Intent data) { - String accName = data.getStringExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME); - // if no account name is given use name "default" - if (TextUtils.isEmpty(accName)) { - accName = "default"; - } - Log.d(Constants.TAG, "accName: " + accName); - return accName; - } - // TODO: multi-threading private final IOpenPgpService.Stub mBinder = new IOpenPgpService.Stub() { @@ -698,41 +784,29 @@ public class OpenPgpService extends RemoteService { return errorResult; } - String accName = getAccountName(data); - final AccountSettings accSettings = getAccSettings(accName); - if (accSettings == null) { - return getCreateAccountIntent(data, accName); - } - String action = data.getAction(); if (OpenPgpApi.ACTION_CLEARTEXT_SIGN.equals(action)) { - return signImpl(data, input, output, accSettings, true); + return signImpl(data, input, output, true); } else if (OpenPgpApi.ACTION_SIGN.equals(action)) { // DEPRECATED: same as ACTION_CLEARTEXT_SIGN Log.w(Constants.TAG, "You are using a deprecated API call, please use ACTION_CLEARTEXT_SIGN instead of ACTION_SIGN!"); - return signImpl(data, input, output, accSettings, true); + return signImpl(data, input, output, true); } else if (OpenPgpApi.ACTION_DETACHED_SIGN.equals(action)) { - return signImpl(data, input, output, accSettings, false); + return signImpl(data, input, output, false); } else if (OpenPgpApi.ACTION_ENCRYPT.equals(action)) { - return encryptAndSignImpl(data, input, output, accSettings, false); + return encryptAndSignImpl(data, input, output, false); } else if (OpenPgpApi.ACTION_SIGN_AND_ENCRYPT.equals(action)) { - return encryptAndSignImpl(data, input, output, accSettings, true); + return encryptAndSignImpl(data, input, output, true); } else if (OpenPgpApi.ACTION_DECRYPT_VERIFY.equals(action)) { - String currentPkg = getCurrentCallingPackage(); - Set<Long> allowedKeyIds = - mProviderHelper.getAllKeyIdsForApp( - ApiAccounts.buildBaseUri(currentPkg)); - return decryptAndVerifyImpl(data, input, output, allowedKeyIds, false); + return decryptAndVerifyImpl(data, input, output, false); } else if (OpenPgpApi.ACTION_DECRYPT_METADATA.equals(action)) { - String currentPkg = getCurrentCallingPackage(); - Set<Long> allowedKeyIds = - mProviderHelper.getAllKeyIdsForApp( - ApiAccounts.buildBaseUri(currentPkg)); - return decryptAndVerifyImpl(data, input, output, allowedKeyIds, true); - } else if (OpenPgpApi.ACTION_GET_KEY.equals(action)) { - return getKeyImpl(data); + return decryptAndVerifyImpl(data, input, output, true); + } else if (OpenPgpApi.ACTION_GET_SIGN_KEY_ID.equals(action)) { + return getSignKeyIdImpl(data); } else if (OpenPgpApi.ACTION_GET_KEY_IDS.equals(action)) { return getKeyIdsImpl(data); + } else if (OpenPgpApi.ACTION_GET_KEY.equals(action)) { + return getKeyImpl(data); } else { return null; } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java index 672f59285..59dafb505 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2013-2014 Dominik Schürmann <dominik@dominikschuermann.de> + * Copyright (C) 2013-2015 Dominik Schürmann <dominik@dominikschuermann.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -154,9 +154,9 @@ public abstract class RemoteService extends Service { } /** - * Retrieves AccountSettings from database for the application calling this remote service + * DEPRECATED API * - * @return + * Retrieves AccountSettings from database for the application calling this remote service */ protected AccountSettings getAccSettings(String accountName) { String currentPkg = getCurrentCallingPackage(); @@ -164,11 +164,12 @@ public abstract class RemoteService extends Service { Uri uri = KeychainContract.ApiAccounts.buildByPackageAndAccountUri(currentPkg, accountName); - AccountSettings settings = mProviderHelper.getApiAccountSettings(uri); - - return settings; // can be null! + return mProviderHelper.getApiAccountSettings(uri); // can be null! } + /** + * Deprecated API + */ protected Intent getCreateAccountIntent(Intent data, String accountName) { String packageName = getCurrentCallingPackage(); Log.d(Constants.TAG, "getCreateAccountIntent accountName: " + accountName); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java index 4d6df24d2..507d4dea5 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsActivity.java @@ -89,9 +89,10 @@ public class AccountSettingsActivity extends BaseActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case R.id.menu_account_settings_delete: + case R.id.menu_account_settings_delete: { deleteAccount(); return true; + } } return super.onOptionsItemSelected(item); } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java index a5bc05ba8..940ae27d0 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java @@ -24,9 +24,6 @@ import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemSelectedListener; -import android.widget.Spinner; import android.widget.TextView; import org.sufficientlysecure.keychain.Constants; @@ -36,10 +33,8 @@ import org.sufficientlysecure.keychain.operations.results.SaveKeyringResult; import org.sufficientlysecure.keychain.pgp.KeyRing; import org.sufficientlysecure.keychain.remote.AccountSettings; import org.sufficientlysecure.keychain.ui.CreateKeyActivity; -import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; import org.sufficientlysecure.keychain.ui.widget.KeySpinner; import org.sufficientlysecure.keychain.ui.widget.SignKeySpinner; -import org.sufficientlysecure.keychain.util.AlgorithmNames; import org.sufficientlysecure.keychain.util.Log; public class AccountSettingsFragment extends Fragment { @@ -51,17 +46,10 @@ public class AccountSettingsFragment extends Fragment { // view private TextView mAccNameView; - private Spinner mEncryptionAlgorithm; - private Spinner mHashAlgorithm; - private Spinner mCompression; private SignKeySpinner mSelectKeySpinner; private View mCreateKeyButton; - KeyValueSpinnerAdapter mEncryptionAdapter; - KeyValueSpinnerAdapter mHashAdapter; - KeyValueSpinnerAdapter mCompressionAdapter; - public AccountSettings getAccSettings() { return mAccSettings; } @@ -71,10 +59,6 @@ public class AccountSettingsFragment extends Fragment { mAccNameView.setText(accountSettings.getAccountName()); mSelectKeySpinner.setSelectedKeyId(accountSettings.getKeyId()); - mEncryptionAlgorithm.setSelection(mEncryptionAdapter.getPosition(accountSettings - .getEncryptionAlgorithm())); - mHashAlgorithm.setSelection(mHashAdapter.getPosition(accountSettings.getHashAlgorithm())); - mCompression.setSelection(mCompressionAdapter.getPosition(accountSettings.getCompression())); } /** @@ -90,10 +74,6 @@ public class AccountSettingsFragment extends Fragment { private void initView(View view) { mSelectKeySpinner = (SignKeySpinner) view.findViewById(R.id.api_account_settings_key_spinner); mAccNameView = (TextView) view.findViewById(R.id.api_account_settings_acc_name); - mEncryptionAlgorithm = (Spinner) view - .findViewById(R.id.api_account_settings_encryption_algorithm); - mHashAlgorithm = (Spinner) view.findViewById(R.id.api_account_settings_hash_algorithm); - mCompression = (Spinner) view.findViewById(R.id.api_account_settings_compression); mCreateKeyButton = view.findViewById(R.id.api_account_settings_create_key); mSelectKeySpinner.setOnKeyChangedListener(new KeySpinner.OnKeyChangedListener() { @@ -109,52 +89,6 @@ public class AccountSettingsFragment extends Fragment { createKey(); } }); - - AlgorithmNames algorithmNames = new AlgorithmNames(getActivity()); - - mEncryptionAdapter = new KeyValueSpinnerAdapter(getActivity(), - algorithmNames.getEncryptionNames()); - mEncryptionAlgorithm.setAdapter(mEncryptionAdapter); - mEncryptionAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { - mAccSettings.setEncryptionAlgorithm((int) id); - } - - @Override - public void onNothingSelected(AdapterView<?> parent) { - } - }); - - mHashAdapter = new KeyValueSpinnerAdapter(getActivity(), algorithmNames.getHashNames()); - mHashAlgorithm.setAdapter(mHashAdapter); - mHashAlgorithm.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { - mAccSettings.setHashAlgorithm((int) id); - } - - @Override - public void onNothingSelected(AdapterView<?> parent) { - } - }); - - mCompressionAdapter = new KeyValueSpinnerAdapter(getActivity(), - algorithmNames.getCompressionNames()); - mCompression.setAdapter(mCompressionAdapter); - mCompression.setOnItemSelectedListener(new OnItemSelectedListener() { - - @Override - public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { - mAccSettings.setCompression((int) id); - } - - @Override - public void onNothingSelected(AdapterView<?> parent) { - } - }); } private void createKey() { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/SelectSignKeyIdActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/SelectSignKeyIdActivity.java new file mode 100644 index 000000000..8578bb384 --- /dev/null +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/SelectSignKeyIdActivity.java @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2015 Dominik Schürmann <dominik@dominikschuermann.de> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.app.Activity; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.view.View; +import android.widget.TextView; + +import org.openintents.openpgp.util.OpenPgpApi; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.operations.results.OperationResult; +import org.sufficientlysecure.keychain.pgp.KeyRing; +import org.sufficientlysecure.keychain.ui.BaseActivity; +import org.sufficientlysecure.keychain.ui.CreateKeyActivity; +import org.sufficientlysecure.keychain.util.Log; + +public class SelectSignKeyIdActivity extends BaseActivity { + + public static final String EXTRA_USER_ID = OpenPgpApi.EXTRA_USER_ID; + public static final String EXTRA_DATA = "data"; + + private static final int REQUEST_CODE_CREATE_KEY = 0x00008884; + + private Uri mAppUri; + private String mPreferredUserId; + + private SelectSignKeyIdListFragment mListFragment; + private TextView mActionCreateKey; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Inflate a "Done" custom action bar + setFullScreenDialogClose( + new View.OnClickListener() { + @Override + public void onClick(View v) { + setResult(RESULT_CANCELED); + finish(); + } + }); + + mActionCreateKey = (TextView) findViewById(R.id.api_select_sign_key_create_key); + mActionCreateKey.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + createKey(mPreferredUserId); + } + }); + + Intent intent = getIntent(); + mAppUri = intent.getData(); + mPreferredUserId = intent.getStringExtra(EXTRA_USER_ID); + Intent data = intent.getParcelableExtra(EXTRA_DATA); + if (mAppUri == null) { + Log.e(Constants.TAG, "Intent data missing. Should be Uri of app!"); + finish(); + return; + } else { + Log.d(Constants.TAG, "uri: " + mAppUri); + startListFragments(savedInstanceState, mAppUri, data); + } + } + + private void createKey(String userId) { + String[] userIdSplit = KeyRing.splitUserId(userId); + + Intent intent = new Intent(this, CreateKeyActivity.class); + intent.putExtra(CreateKeyActivity.EXTRA_NAME, userIdSplit[0]); + intent.putExtra(CreateKeyActivity.EXTRA_EMAIL, userIdSplit[1]); + startActivityForResult(intent, REQUEST_CODE_CREATE_KEY); + } + + private void startListFragments(Bundle savedInstanceState, Uri dataUri, Intent data) { + // However, if we're being restored from a previous state, + // then we don't need to do anything and should return or else + // we could end up with overlapping fragments. + if (savedInstanceState != null) { + return; + } + + // Create an instance of the fragments + mListFragment = SelectSignKeyIdListFragment.newInstance(dataUri, data); + // Add the fragment to the 'fragment_container' FrameLayout + // NOTE: We use commitAllowingStateLoss() to prevent weird crashes! + getSupportFragmentManager().beginTransaction() + .replace(R.id.api_select_sign_key_list_fragment, mListFragment) + .commitAllowingStateLoss(); + // do it immediately! + getSupportFragmentManager().executePendingTransactions(); + } + + @Override + protected void initLayout() { + setContentView(R.layout.api_select_sign_key_activity); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // if a result has been returned, display a notify + if (data != null && data.hasExtra(OperationResult.EXTRA_RESULT)) { + OperationResult result = data.getParcelableExtra(OperationResult.EXTRA_RESULT); + result.createNotify(this).show(); + } + + switch (requestCode) { + case REQUEST_CODE_CREATE_KEY: { + if (resultCode == Activity.RESULT_OK) { + if (data != null && data.hasExtra(OperationResult.EXTRA_RESULT)) { +// SaveKeyringResult result = data.getParcelableExtra(OperationResult.EXTRA_RESULT); + // TODO: select? +// mSelectKeySpinner.setSelectedKeyId(result.mRingMasterKeyId); + } else { + Log.e(Constants.TAG, "missing result!"); + } + } + break; + } + default: { + super.onActivityResult(requestCode, resultCode, data); + } + } + } + +} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/SelectSignKeyIdListFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/SelectSignKeyIdListFragment.java new file mode 100644 index 000000000..e547d0145 --- /dev/null +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/SelectSignKeyIdListFragment.java @@ -0,0 +1,218 @@ +/* + * Copyright (C) 2015 Dominik Schürmann <dominik@dominikschuermann.de> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package org.sufficientlysecure.keychain.remote.ui; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.CursorLoader; +import android.support.v4.content.Loader; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ListView; + +import org.openintents.openpgp.util.OpenPgpApi; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.compatibility.ListFragmentWorkaround; +import org.sufficientlysecure.keychain.provider.KeychainContract; +import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; +import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.ui.adapter.SelectKeyCursorAdapter; +import org.sufficientlysecure.keychain.ui.widget.FixedListView; +import org.sufficientlysecure.keychain.util.Log; + +public class SelectSignKeyIdListFragment extends ListFragmentWorkaround implements LoaderManager.LoaderCallbacks<Cursor> { + private static final String ARG_DATA_URI = "uri"; + public static final String ARG_DATA = "data"; + + private SelectKeyCursorAdapter mAdapter; + private ProviderHelper mProviderHelper; + + private Uri mDataUri; + + /** + * Creates new instance of this fragment + */ + public static SelectSignKeyIdListFragment newInstance(Uri dataUri, Intent data) { + SelectSignKeyIdListFragment frag = new SelectSignKeyIdListFragment(); + Bundle args = new Bundle(); + + args.putParcelable(ARG_DATA_URI, dataUri); + args.putParcelable(ARG_DATA, data); + + frag.setArguments(args); + + return frag; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mProviderHelper = new ProviderHelper(getActivity()); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View layout = super.onCreateView(inflater, container, + savedInstanceState); + ListView lv = (ListView) layout.findViewById(android.R.id.list); + ViewGroup parent = (ViewGroup) lv.getParent(); + + /* + * http://stackoverflow.com/a/15880684 + * Remove ListView and add FixedListView in its place. + * This is done here programatically to be still able to use the progressBar of ListFragment. + * + * We want FixedListView to be able to put this ListFragment inside a ScrollView + */ + int lvIndex = parent.indexOfChild(lv); + parent.removeViewAt(lvIndex); + FixedListView newLv = new FixedListView(getActivity()); + newLv.setId(android.R.id.list); + parent.addView(newLv, lvIndex, lv.getLayoutParams()); + return layout; + } + + /** + * Define Adapter and Loader on create of Activity + */ + @Override + public void onActivityCreated(Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + mDataUri = getArguments().getParcelable(ARG_DATA_URI); + final Intent resultData = getArguments().getParcelable(ARG_DATA); + + getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); + getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView<?> parent, View view, int position, long id) { + long masterKeyId = mAdapter.getMasterKeyId(position); + + Uri allowedKeysUri = mDataUri.buildUpon().appendPath(KeychainContract.PATH_ALLOWED_KEYS).build(); + Log.d(Constants.TAG, "allowedKeysUri: " + allowedKeysUri); + mProviderHelper.addAllowedKeyIdForApp(allowedKeysUri, masterKeyId); + + resultData.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, masterKeyId); + + getActivity().setResult(Activity.RESULT_OK, resultData); + getActivity().finish(); + } + }); + + // Give some text to display if there is no data. In a real + // application this would come from a resource. + setEmptyText(getString(R.string.list_empty)); + + mAdapter = new SecretKeyCursorAdapter(getActivity(), null, 0, getListView()); + + setListAdapter(mAdapter); + + // Start out with a progress indicator. + setListShown(false); + + // Prepare the loader. Either re-connect with an existing one, + // or start a new one. + getLoaderManager().initLoader(0, null, this); + } + + @Override + public Loader<Cursor> onCreateLoader(int id, Bundle args) { + Uri baseUri = KeyRings.buildUnifiedKeyRingsUri(); + + // These are the rows that we will retrieve. + String[] projection = new String[]{ + KeyRings._ID, + KeyRings.MASTER_KEY_ID, + KeyRings.USER_ID, + KeyRings.IS_EXPIRED, + KeyRings.IS_REVOKED, + KeyRings.HAS_ENCRYPT, + KeyRings.VERIFIED, + KeyRings.HAS_ANY_SECRET, + }; + + String selection = KeyRings.HAS_ANY_SECRET + " != 0"; + + String orderBy = KeyRings.USER_ID + " ASC"; + // 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, selection, null, orderBy); + } + + @Override + public void onLoadFinished(Loader<Cursor> loader, Cursor data) { + // Swap the new cursor in. (The framework will take care of closing the + // old cursor once we return.) + mAdapter.swapCursor(data); + + // The list should now be shown. + if (isResumed()) { + setListShown(true); + } else { + setListShownNoAnimation(true); + } + + } + + @Override + public void onLoaderReset(Loader<Cursor> loader) { + // This is called when the last Cursor provided to onLoadFinished() + // above is about to be closed. We need to make sure we are no + // longer using it. + mAdapter.swapCursor(null); + } + + private class SecretKeyCursorAdapter extends SelectKeyCursorAdapter { + + public SecretKeyCursorAdapter(Context context, Cursor c, int flags, ListView listView) { + super(context, c, flags, listView); + } + + @Override + protected void initIndex(Cursor cursor) { + super.initIndex(cursor); + } + + @Override + public void bindView(View view, Context context, Cursor cursor) { + super.bindView(view, context, cursor); + ViewHolderItem h = (ViewHolderItem) view.getTag(); + + h.selected.setVisibility(View.GONE); + + boolean enabled = false; + if ((Boolean) h.statusIcon.getTag()) { + h.statusIcon.setVisibility(View.GONE); + enabled = true; + } + h.setEnabled(enabled); + } + + } + +} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyActivity.java index 60cc404b6..2da5511b8 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyActivity.java @@ -39,8 +39,8 @@ public class CreateKeyActivity extends BaseActivity { super.onCreate(savedInstanceState); // pass extras into fragment - CreateKeyInputFragment frag = - CreateKeyInputFragment.newInstance( + CreateKeyNameFragment frag = + CreateKeyNameFragment.newInstance( getIntent().getStringExtra(EXTRA_NAME), getIntent().getStringExtra(EXTRA_EMAIL) ); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyEmailFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyEmailFragment.java new file mode 100644 index 000000000..66424e012 --- /dev/null +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyEmailFragment.java @@ -0,0 +1,310 @@ +/* + * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package org.sufficientlysecure.keychain.ui; + +import android.app.Activity; +import android.content.Context; +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.v7.widget.DefaultItemAnimator; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageButton; +import android.widget.TextView; + +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction; +import org.sufficientlysecure.keychain.ui.dialog.AddEmailDialogFragment; +import org.sufficientlysecure.keychain.ui.dialog.SetPassphraseDialogFragment; +import org.sufficientlysecure.keychain.ui.widget.EmailEditText; + +import java.util.ArrayList; +import java.util.List; + +public class CreateKeyEmailFragment extends Fragment { + + public static final String ARG_NAME = "name"; + public static final String ARG_EMAIL = "email"; + + CreateKeyActivity mCreateKeyActivity; + EmailEditText mEmailEdit; + RecyclerView mEmailsRecyclerView; + View mBackButton; + View mNextButton; + + String mName; + ArrayList<EmailAdapter.ViewModel> mAdditionalEmailModels; + + EmailAdapter mEmailAdapter; + + /** + * Creates new instance of this fragment + */ + public static CreateKeyEmailFragment newInstance(String name, String email) { + CreateKeyEmailFragment frag = new CreateKeyEmailFragment(); + + Bundle args = new Bundle(); + args.putString(ARG_NAME, name); + args.putString(ARG_EMAIL, email); + + frag.setArguments(args); + + return frag; + } + + /** + * Checks if text of given EditText is not empty. If it is empty an error is + * set and the EditText gets the focus. + * + * @param context + * @param editText + * @return true if EditText is not empty + */ + private static boolean isEditTextNotEmpty(Context context, EditText editText) { + boolean output = true; + if (editText.getText().toString().length() == 0) { + editText.setError(context.getString(R.string.create_key_empty)); + editText.requestFocus(); + output = false; + } else { + editText.setError(null); + } + + return output; + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.create_key_email_fragment, container, false); + + mEmailEdit = (EmailEditText) view.findViewById(R.id.create_key_email); + mBackButton = view.findViewById(R.id.create_key_back_button); + mNextButton = view.findViewById(R.id.create_key_next_button); + mEmailsRecyclerView = (RecyclerView) view.findViewById(R.id.create_key_emails); + + // initial values + mName = getArguments().getString(ARG_NAME); + String email = getArguments().getString(ARG_EMAIL); + mEmailEdit.setText(email); + + // focus empty edit fields + if (email == null) { + mEmailEdit.requestFocus(); + } + mBackButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mCreateKeyActivity.loadFragment(null, null, FragAction.TO_LEFT); + } + }); + mNextButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + createKeyCheck(); + } + }); + mEmailsRecyclerView.setHasFixedSize(true); + mEmailsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); + mEmailsRecyclerView.setItemAnimator(new DefaultItemAnimator()); + + mAdditionalEmailModels = new ArrayList<>(); + mEmailAdapter = new EmailAdapter(mAdditionalEmailModels, new View.OnClickListener() { + @Override + public void onClick(View v) { + addEmail(); + } + }); + mEmailsRecyclerView.setAdapter(mEmailAdapter); + + return view; + } + + private void addEmail() { + Handler returnHandler = new Handler() { + @Override + public void handleMessage(Message message) { + if (message.what == SetPassphraseDialogFragment.MESSAGE_OKAY) { + Bundle data = message.getData(); + + // add new user id + mEmailAdapter.add( + data.getString(AddEmailDialogFragment.MESSAGE_DATA_EMAIL) + ); + } + } + }; + + // Create a new Messenger for the communication back + Messenger messenger = new Messenger(returnHandler); + + AddEmailDialogFragment addEmailDialog = AddEmailDialogFragment.newInstance(messenger); + + addEmailDialog.show(getActivity().getSupportFragmentManager(), "addEmailDialog"); + } + + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + mCreateKeyActivity = (CreateKeyActivity) getActivity(); + } + + private void createKeyCheck() { + if (isEditTextNotEmpty(getActivity(), mEmailEdit)) { + + ArrayList<String> emails = new ArrayList<>(); + for (EmailAdapter.ViewModel holder : mAdditionalEmailModels) { + emails.add(holder.toString()); + } + + CreateKeyPassphraseFragment frag = + CreateKeyPassphraseFragment.newInstance( + mName, + mEmailEdit.getText().toString(), + emails + ); + + mCreateKeyActivity.loadFragment(null, frag, FragAction.TO_RIGHT); + } + } + + public static class EmailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { + private List<ViewModel> mDataset; + private View.OnClickListener mFooterOnClickListener; + private static final int TYPE_FOOTER = 0; + private static final int TYPE_ITEM = 1; + + public static class ViewModel { + String email; + + ViewModel(String email) { + this.email = email; + } + + @Override + public String toString() { + return email; + } + } + + // Provide a reference to the views for each data item + // Complex data items may need more than one view per item, and + // you provide access to all the views for a data item in a view holder + public static class ViewHolder extends RecyclerView.ViewHolder { + // each data item is just a string in this case + public TextView mTextView; + public ImageButton mDeleteButton; + + public ViewHolder(View itemView) { + super(itemView); + mTextView = (TextView) itemView.findViewById(R.id.create_key_email_item_email); + mDeleteButton = (ImageButton) itemView.findViewById(R.id.create_key_email_item_delete_button); + } + } + + class FooterHolder extends RecyclerView.ViewHolder { + public Button mAddButton; + + public FooterHolder(View itemView) { + super(itemView); + mAddButton = (Button) itemView.findViewById(R.id.create_key_add_email); + } + } + + // Provide a suitable constructor (depends on the kind of dataset) + public EmailAdapter(List<ViewModel> myDataset, View.OnClickListener onFooterClickListener) { + mDataset = myDataset; + mFooterOnClickListener = onFooterClickListener; + } + + // Create new views (invoked by the layout manager) + @Override + public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + if (viewType == TYPE_FOOTER) { + View v = LayoutInflater.from(parent.getContext()) + .inflate(R.layout.create_key_email_list_footer, parent, false); + return new FooterHolder(v); + } else { + //inflate your layout and pass it to view holder + View v = LayoutInflater.from(parent.getContext()) + .inflate(R.layout.create_key_email_list_item, parent, false); + return new ViewHolder(v); + } + } + + // Replace the contents of a view (invoked by the layout manager) + @Override + public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { + if (holder instanceof ViewHolder) { + ViewHolder thisHolder = (ViewHolder) holder; + // - get element from your dataset at this position + // - replace the contents of the view with that element + final ViewModel model = mDataset.get(position); + + thisHolder.mTextView.setText(model.email); + thisHolder.mDeleteButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + remove(model); + } + }); + } else if (holder instanceof FooterHolder) { + FooterHolder thisHolder = (FooterHolder) holder; + thisHolder.mAddButton.setOnClickListener(mFooterOnClickListener); + } + } + + // Return the size of your dataset (invoked by the layout manager) + @Override + public int getItemCount() { + return mDataset.size() + 1; + } + + @Override + public int getItemViewType(int position) { + if (isPositionFooter(position)) { + return TYPE_FOOTER; + } else { + return TYPE_ITEM; + } + } + + private boolean isPositionFooter(int position) { + return position == mDataset.size(); + } + + public void add(String email) { + mDataset.add(new ViewModel(email)); + notifyItemInserted(mDataset.size() - 1); + } + + public void remove(ViewModel model) { + int position = mDataset.indexOf(model); + mDataset.remove(position); + notifyItemRemoved(position); + } + } + +} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyFinalFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyFinalFragment.java index 0c3ebee72..ae42c891d 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyFinalFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyFinalFragment.java @@ -47,6 +47,9 @@ import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.Preferences; +import java.util.ArrayList; +import java.util.Iterator; + public class CreateKeyFinalFragment extends Fragment { public static final int REQUEST_EDIT_KEY = 0x00008007; @@ -63,10 +66,12 @@ public class CreateKeyFinalFragment extends Fragment { public static final String ARG_NAME = "name"; public static final String ARG_EMAIL = "email"; + public static final String ARG_ADDITIONAL_EMAILS = "emails"; public static final String ARG_PASSPHRASE = "passphrase"; String mName; String mEmail; + ArrayList<String> mAdditionalEmails; String mPassphrase; SaveKeyringParcel mSaveKeyringParcel; @@ -74,12 +79,15 @@ public class CreateKeyFinalFragment extends Fragment { /** * Creates new instance of this fragment */ - public static CreateKeyFinalFragment newInstance(String name, String email, String passphrase) { + public static CreateKeyFinalFragment newInstance(String name, String email, + ArrayList<String> additionalEmails, + String passphrase) { CreateKeyFinalFragment frag = new CreateKeyFinalFragment(); Bundle args = new Bundle(); args.putString(ARG_NAME, name); args.putString(ARG_EMAIL, email); + args.putStringArrayList(ARG_ADDITIONAL_EMAILS, additionalEmails); args.putString(ARG_PASSPHRASE, passphrase); frag.setArguments(args); @@ -95,18 +103,32 @@ public class CreateKeyFinalFragment extends Fragment { mEmailEdit = (TextView) view.findViewById(R.id.email); mUploadCheckbox = (CheckBox) view.findViewById(R.id.create_key_upload); mBackButton = view.findViewById(R.id.create_key_back_button); - mCreateButton = view.findViewById(R.id.create_key_create_button); + mCreateButton = view.findViewById(R.id.create_key_next_button); mEditText = (TextView) view.findViewById(R.id.create_key_edit_text); mEditButton = view.findViewById(R.id.create_key_edit_button); // get args mName = getArguments().getString(ARG_NAME); mEmail = getArguments().getString(ARG_EMAIL); + mAdditionalEmails = getArguments().getStringArrayList(ARG_ADDITIONAL_EMAILS); mPassphrase = getArguments().getString(ARG_PASSPHRASE); // set values mNameEdit.setText(mName); - mEmailEdit.setText(mEmail); + if (mAdditionalEmails != null && mAdditionalEmails.size() > 0) { + String emailText = mEmail + ", "; + Iterator<?> it = mAdditionalEmails.iterator(); + while (it.hasNext()) { + Object next = it.next(); + emailText += next; + if (it.hasNext()) { + emailText += ", "; + } + } + mEmailEdit.setText(emailText); + } else { + mEmailEdit.setText(mEmail); + } mCreateButton.setOnClickListener(new View.OnClickListener() { @Override @@ -167,12 +189,19 @@ public class CreateKeyFinalFragment extends Fragment { String userId = KeyRing.createUserId(mName, mEmail, null); mSaveKeyringParcel.mAddUserIds.add(userId); mSaveKeyringParcel.mChangePrimaryUserId = userId; + if (mAdditionalEmails != null && mAdditionalEmails.size() > 0) { + for (String email : mAdditionalEmails) { + String thisUserId = KeyRing.createUserId(mName, email, null); + mSaveKeyringParcel.mAddUserIds.add(thisUserId); + } + } mSaveKeyringParcel.mNewUnlock = mPassphrase != null ? new ChangeUnlockParcel(mPassphrase, null) : null; } } + private void createKey() { Intent intent = new Intent(getActivity(), KeychainIntentService.class); intent.setAction(KeychainIntentService.ACTION_EDIT_KEYRING); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyInputFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyNameFragment.java index 05408e21e..50a3bd655 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyInputFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyNameFragment.java @@ -17,6 +17,7 @@ package org.sufficientlysecure.keychain.ui; +import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; @@ -30,24 +31,23 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction; import org.sufficientlysecure.keychain.ui.widget.EmailEditText; import org.sufficientlysecure.keychain.ui.widget.NameEditText; -import org.sufficientlysecure.keychain.ui.widget.PassphraseEditText; -public class CreateKeyInputFragment extends Fragment { +public class CreateKeyNameFragment extends Fragment { public static final String ARG_NAME = "name"; public static final String ARG_EMAIL = "email"; + CreateKeyActivity mCreateKeyActivity; NameEditText mNameEdit; - EmailEditText mEmailEdit; - PassphraseEditText mPassphraseEdit; - EditText mPassphraseEditAgain; - View mCreateButton; + View mNextButton; + + String mEmail; /** * Creates new instance of this fragment */ - public static CreateKeyInputFragment newInstance(String name, String email) { - CreateKeyInputFragment frag = new CreateKeyInputFragment(); + public static CreateKeyNameFragment newInstance(String name, String email) { + CreateKeyNameFragment frag = new CreateKeyNameFragment(); Bundle args = new Bundle(); args.putString(ARG_NAME, name); @@ -94,27 +94,21 @@ public class CreateKeyInputFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.create_key_input_fragment, container, false); + View view = inflater.inflate(R.layout.create_key_name_fragment, container, false); mNameEdit = (NameEditText) view.findViewById(R.id.create_key_name); - mPassphraseEdit = (PassphraseEditText) view.findViewById(R.id.create_key_passphrase); - mEmailEdit = (EmailEditText) view.findViewById(R.id.create_key_email); - mPassphraseEditAgain = (EditText) view.findViewById(R.id.create_key_passphrase_again); - mCreateButton = view.findViewById(R.id.create_key_button); + mNextButton = view.findViewById(R.id.create_key_next_button); // initial values String name = getArguments().getString(ARG_NAME); - String email = getArguments().getString(ARG_EMAIL); + mEmail = getArguments().getString(ARG_EMAIL); mNameEdit.setText(name); - mEmailEdit.setText(email); - // focus non-empty edit fields - if (name != null && email != null) { - mPassphraseEdit.requestFocus(); - } else if (name != null) { - mEmailEdit.requestFocus(); + // focus empty edit fields + if (name == null) { + mNameEdit.requestFocus(); } - mCreateButton.setOnClickListener(new View.OnClickListener() { + mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createKeyCheck(); @@ -125,43 +119,22 @@ public class CreateKeyInputFragment extends Fragment { } @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - + public void onAttach(Activity activity) { + super.onAttach(activity); mCreateKeyActivity = (CreateKeyActivity) getActivity(); } private void createKeyCheck() { - if (isEditTextNotEmpty(getActivity(), mNameEdit) - && isEditTextNotEmpty(getActivity(), mEmailEdit) - && isEditTextNotEmpty(getActivity(), mPassphraseEdit) - && areEditTextsEqual(getActivity(), mPassphraseEdit, mPassphraseEditAgain)) { + if (isEditTextNotEmpty(getActivity(), mNameEdit)) { - CreateKeyFinalFragment frag = - CreateKeyFinalFragment.newInstance( + CreateKeyEmailFragment frag = + CreateKeyEmailFragment.newInstance( mNameEdit.getText().toString(), - mEmailEdit.getText().toString(), - mPassphraseEdit.getText().toString() + mEmail ); - hideKeyboard(); mCreateKeyActivity.loadFragment(null, frag, FragAction.TO_RIGHT); } } - private void hideKeyboard() { - if (getActivity() == null) { - return; - } - InputMethodManager inputManager = (InputMethodManager) getActivity() - .getSystemService(Context.INPUT_METHOD_SERVICE); - - // check if no view has focus - View v = getActivity().getCurrentFocus(); - if (v == null) - return; - - inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); - } - } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyPassphraseFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyPassphraseFragment.java new file mode 100644 index 000000000..055ea608b --- /dev/null +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyPassphraseFragment.java @@ -0,0 +1,197 @@ +/* + * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package org.sufficientlysecure.keychain.ui; + +import android.app.Activity; +import android.content.Context; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.text.method.HideReturnsTransformationMethod; +import android.text.method.PasswordTransformationMethod; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.inputmethod.InputMethodManager; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.EditText; + +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.ui.CreateKeyActivity.FragAction; +import org.sufficientlysecure.keychain.ui.widget.PassphraseEditText; + +import java.util.ArrayList; + +public class CreateKeyPassphraseFragment extends Fragment { + + public static final String ARG_NAME = "name"; + public static final String ARG_EMAIL = "email"; + public static final String ARG_ADDITIONAL_EMAILS = "emails"; + + // model + String mName; + String mEmail; + ArrayList<String> mAdditionalEmails; + + // view + CreateKeyActivity mCreateKeyActivity; + PassphraseEditText mPassphraseEdit; + EditText mPassphraseEditAgain; + CheckBox mShowPassphrase; + View mBackButton; + View mNextButton; + + /** + * Creates new instance of this fragment + */ + public static CreateKeyPassphraseFragment newInstance(String name, String email, + ArrayList<String> additionalEmails) { + CreateKeyPassphraseFragment frag = new CreateKeyPassphraseFragment(); + + Bundle args = new Bundle(); + args.putString(ARG_NAME, name); + args.putString(ARG_EMAIL, email); + args.putStringArrayList(ARG_ADDITIONAL_EMAILS, additionalEmails); + + frag.setArguments(args); + + return frag; + } + + /** + * Checks if text of given EditText is not empty. If it is empty an error is + * set and the EditText gets the focus. + * + * @param context + * @param editText + * @return true if EditText is not empty + */ + private static boolean isEditTextNotEmpty(Context context, EditText editText) { + boolean output = true; + if (editText.getText().toString().length() == 0) { + editText.setError(context.getString(R.string.create_key_empty)); + editText.requestFocus(); + output = false; + } else { + editText.setError(null); + } + + return output; + } + + private static boolean areEditTextsEqual(Context context, EditText editText1, EditText editText2) { + boolean output = true; + if (!editText1.getText().toString().equals(editText2.getText().toString())) { + editText2.setError(context.getString(R.string.create_key_passphrases_not_equal)); + editText2.requestFocus(); + output = false; + } else { + editText2.setError(null); + } + + return output; + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.create_key_passphrase_fragment, container, false); + + mPassphraseEdit = (PassphraseEditText) view.findViewById(R.id.create_key_passphrase); + mPassphraseEditAgain = (EditText) view.findViewById(R.id.create_key_passphrase_again); + mShowPassphrase = (CheckBox) view.findViewById(R.id.create_key_show_passphrase); + mBackButton = view.findViewById(R.id.create_key_back_button); + mNextButton = view.findViewById(R.id.create_key_next_button); + + // initial values + mName = getArguments().getString(ARG_NAME); + mEmail = getArguments().getString(ARG_EMAIL); + mAdditionalEmails = getArguments().getStringArrayList(ARG_ADDITIONAL_EMAILS); + mPassphraseEdit.requestFocus(); + mBackButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + back(); + } + }); + mNextButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + createKeyCheck(); + } + }); + mShowPassphrase.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + mPassphraseEdit.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); + mPassphraseEditAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); + } else { + mPassphraseEdit.setTransformationMethod(PasswordTransformationMethod.getInstance()); + mPassphraseEditAgain.setTransformationMethod(PasswordTransformationMethod.getInstance()); + } + } + }); + + + return view; + } + + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + mCreateKeyActivity = (CreateKeyActivity) getActivity(); + } + + private void back() { + hideKeyboard(); + mCreateKeyActivity.loadFragment(null, null, FragAction.TO_LEFT); + } + + private void createKeyCheck() { + if (isEditTextNotEmpty(getActivity(), mPassphraseEdit) + && areEditTextsEqual(getActivity(), mPassphraseEdit, mPassphraseEditAgain)) { + + CreateKeyFinalFragment frag = + CreateKeyFinalFragment.newInstance( + mName, + mEmail, + mAdditionalEmails, + mPassphraseEdit.getText().toString() + ); + + hideKeyboard(); + mCreateKeyActivity.loadFragment(null, frag, FragAction.TO_RIGHT); + } + } + + private void hideKeyboard() { + if (getActivity() == null) { + return; + } + InputMethodManager inputManager = (InputMethodManager) getActivity() + .getSystemService(Context.INPUT_METHOD_SERVICE); + + // check if no view has focus + View v = getActivity().getCurrentFocus(); + if (v == null) + return; + + inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); + } + +} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java index 9fc7a2a59..8b9323f19 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java @@ -528,7 +528,6 @@ public class EditKeyFragment extends LoaderFragment implements } private void addUserId() { - // Message is received after passphrase is cached Handler returnHandler = new Handler() { @Override public void handleMessage(Message message) { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFilesActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFilesActivity.java index d95b5cda3..b862d5b11 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFilesActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFilesActivity.java @@ -36,7 +36,6 @@ import org.sufficientlysecure.keychain.pgp.SignEncryptParcel; import org.sufficientlysecure.keychain.ui.dialog.DeleteFileDialogFragment; import org.sufficientlysecure.keychain.ui.util.Notify; import org.sufficientlysecure.keychain.util.Log; -import org.sufficientlysecure.keychain.util.Preferences; import org.sufficientlysecure.keychain.util.ShareHelper; import java.util.ArrayList; @@ -177,22 +176,36 @@ public class EncryptFilesActivity extends EncryptActivity implements EncryptActi } @Override - public void onEncryptSuccess(SignEncryptResult result) { + public void onEncryptSuccess(final SignEncryptResult result) { if (mDeleteAfterEncrypt) { - for (Uri inputUri : mInputUris) { - DeleteFileDialogFragment deleteFileDialog = DeleteFileDialogFragment.newInstance(inputUri); - deleteFileDialog.show(getSupportFragmentManager(), "deleteDialog"); - } + final Uri[] inputUris = mInputUris.toArray(new Uri[mInputUris.size()]); + DeleteFileDialogFragment deleteFileDialog = DeleteFileDialogFragment.newInstance(inputUris); + deleteFileDialog.setOnDeletedListener(new DeleteFileDialogFragment.OnDeletedListener() { + + @Override + public void onDeleted() { + if (mShareAfterEncrypt) { + // Share encrypted message/file + startActivity(sendWithChooserExcludingEncrypt()); + } else { + // Save encrypted file + result.createNotify(EncryptFilesActivity.this).show(); + } + } + + }); + deleteFileDialog.show(getSupportFragmentManager(), "deleteDialog"); + mInputUris.clear(); notifyUpdate(); - } - - if (mShareAfterEncrypt) { - // Share encrypted message/file - startActivity(sendWithChooserExcludingEncrypt()); } else { - // Save encrypted file - result.createNotify(EncryptFilesActivity.this).show(); + if (mShareAfterEncrypt) { + // Share encrypted message/file + startActivity(sendWithChooserExcludingEncrypt()); + } else { + // Save encrypted file + result.createNotify(EncryptFilesActivity.this).show(); + } } } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFilesFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFilesFragment.java index ace58b165..48737d223 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFilesFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFilesFragment.java @@ -114,6 +114,13 @@ public class EncryptFilesFragment extends Fragment implements EncryptActivityInt return; } + if (mEncryptInterface.getInputUris().contains(inputUri)) { + Notify.showNotify(getActivity(), + getActivity().getString(R.string.error_file_added_already, FileHelper.getFilename(getActivity(), inputUri)), + Notify.Style.ERROR); + return; + } + mEncryptInterface.getInputUris().add(inputUri); mEncryptInterface.notifyUpdate(); mSelectedFiles.requestFocus(); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyFragment.java index 628970b27..eae283269 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyFragment.java @@ -18,24 +18,30 @@ package org.sufficientlysecure.keychain.ui; +import android.content.ContentResolver; +import android.content.Context; +import android.content.Intent; import android.database.Cursor; +import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; +import android.provider.ContactsContract; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ListView; +import android.widget.*; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround; +import org.sufficientlysecure.keychain.pgp.KeyRing; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.ui.adapter.UserIdsAdapter; import org.sufficientlysecure.keychain.ui.dialog.UserIdInfoDialogFragment; +import org.sufficientlysecure.keychain.util.ContactHelper; import org.sufficientlysecure.keychain.util.Log; public class ViewKeyFragment extends LoaderFragment implements @@ -44,8 +50,14 @@ public class ViewKeyFragment extends LoaderFragment implements public static final String ARG_DATA_URI = "uri"; private ListView mUserIds; + //private ListView mLinkedSystemContact; boolean mIsSecret = false; + boolean mSystemContactLoaded = false; + + LinearLayout mSystemContactLayout; + ImageView mSystemContactPicture; + TextView mSystemContactName; private static final int LOADER_ID_UNIFIED = 0; private static final int LOADER_ID_USER_IDS = 1; @@ -81,6 +93,10 @@ public class ViewKeyFragment extends LoaderFragment implements } }); + mSystemContactLayout = (LinearLayout) view.findViewById(R.id.system_contact_layout); + mSystemContactName = (TextView) view.findViewById(R.id.system_contact_name); + mSystemContactPicture = (ImageView) view.findViewById(R.id.system_contact_picture); + return root; } @@ -100,6 +116,50 @@ public class ViewKeyFragment extends LoaderFragment implements } } + /** + * Checks if a system contact exists for given masterKeyId, and if it does, sets name, picture + * and onClickListener for the linked system contact's layout + * + * @param masterKeyId + */ + private void loadLinkedSystemContact(final long masterKeyId) { + final Context context = mSystemContactName.getContext(); + final ContentResolver resolver = context.getContentResolver(); + + final long contactId = ContactHelper.findContactId(resolver, masterKeyId); + final String contactName = ContactHelper.getContactName(resolver, contactId); + + if (contactName != null) {//contact name exists for given master key + mSystemContactName.setText(contactName); + + Bitmap picture = ContactHelper.loadPhotoByMasterKeyId(resolver, masterKeyId, true); + if (picture != null) mSystemContactPicture.setImageBitmap(picture); + + mSystemContactLayout.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + launchContactActivity(contactId, context); + } + }); + mSystemContactLoaded = true; + } + } + + /** + * launches the default android Contacts app to view a contact with the passed + * contactId (CONTACT_ID column from ContactsContract.RawContact table which is _ID column in + * ContactsContract.Contact table) + * + * @param contactId _ID for row in ContactsContract.Contacts table + * @param context + */ + private void launchContactActivity(final long contactId, Context context) { + Intent intent = new Intent(Intent.ACTION_VIEW); + Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId)); + intent.setData(uri); + context.startActivity(intent); + } + @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); @@ -148,6 +208,7 @@ public class ViewKeyFragment extends LoaderFragment implements getLoaderManager().initLoader(LOADER_ID_UNIFIED, null, this); } + @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { setContentShown(false); @@ -164,6 +225,7 @@ public class ViewKeyFragment extends LoaderFragment implements } } + @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { /* TODO better error handling? May cause problems when a key is deleted, * because the notification triggers faster than the activity closes. @@ -177,6 +239,11 @@ public class ViewKeyFragment extends LoaderFragment implements switch (loader.getId()) { case LOADER_ID_UNIFIED: { if (data.moveToFirst()) { + //TODO system to allow immediate refreshing of system contact on verification + if (!mSystemContactLoaded) {//ensure we load linked system contact only once + long masterKeyId = data.getLong(INDEX_MASTER_KEY_ID); + loadLinkedSystemContact(masterKeyId); + } mIsSecret = data.getInt(INDEX_HAS_ANY_SECRET) != 0; @@ -202,6 +269,7 @@ public class ViewKeyFragment extends LoaderFragment implements * This is called when the last Cursor provided to onLoadFinished() above is about to be closed. * We need to make sure we are no longer using it. */ + @Override public void onLoaderReset(Loader<Cursor> loader) { switch (loader.getId()) { case LOADER_ID_USER_IDS: { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/AddEmailDialogFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/AddEmailDialogFragment.java new file mode 100644 index 000000000..5d5ca533e --- /dev/null +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/AddEmailDialogFragment.java @@ -0,0 +1,215 @@ +/* + * Copyright (C) 2015 Dominik Schürmann <dominik@dominikschuermann.de> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package org.sufficientlysecure.keychain.ui.dialog; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.os.Bundle; +import android.os.Message; +import android.os.Messenger; +import android.os.RemoteException; +import android.support.v4.app.DialogFragment; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.View; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.TextView; +import android.widget.TextView.OnEditorActionListener; + +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.ui.widget.EmailEditText; +import org.sufficientlysecure.keychain.util.Log; + +public class AddEmailDialogFragment extends DialogFragment implements OnEditorActionListener { + private static final String ARG_MESSENGER = "messenger"; + + public static final int MESSAGE_OKAY = 1; + public static final int MESSAGE_CANCEL = 2; + + public static final String MESSAGE_DATA_EMAIL = "email"; + + private Messenger mMessenger; + private EmailEditText mEmail; + + public static AddEmailDialogFragment newInstance(Messenger messenger) { + + AddEmailDialogFragment frag = new AddEmailDialogFragment(); + Bundle args = new Bundle(); + args.putParcelable(ARG_MESSENGER, messenger); + frag.setArguments(args); + + return frag; + } + + /** + * Creates dialog + */ + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + final Activity activity = getActivity(); + mMessenger = getArguments().getParcelable(ARG_MESSENGER); + + CustomAlertDialogBuilder alert = new CustomAlertDialogBuilder(activity); + + alert.setTitle(R.string.create_key_add_email); + + LayoutInflater inflater = activity.getLayoutInflater(); + View view = inflater.inflate(R.layout.add_email_dialog, null); + alert.setView(view); + + mEmail = (EmailEditText) view.findViewById(R.id.add_email_address); + + alert.setPositiveButton(android.R.string.ok, new OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dismiss(); + + // return new user id back to activity + Bundle data = new Bundle(); + String email = mEmail.getText().toString(); + data.putString(MESSAGE_DATA_EMAIL, email); + sendMessageToHandler(MESSAGE_OKAY, data); + } + }); + + alert.setNegativeButton(android.R.string.cancel, new OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + + // Hack to open keyboard. + // This is the only method that I found to work across all Android versions + // http://turbomanage.wordpress.com/2012/05/02/show-soft-keyboard-automatically-when-edittext-receives-focus/ + // Notes: * onCreateView can't be used because we want to add buttons to the dialog + // * opening in onActivityCreated does not work on Android 4.4 + mEmail.setOnFocusChangeListener(new View.OnFocusChangeListener() { + @Override + public void onFocusChange(View v, boolean hasFocus) { + mEmail.post(new Runnable() { + @Override + public void run() { + InputMethodManager imm = (InputMethodManager) getActivity() + .getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(mEmail, InputMethodManager.SHOW_IMPLICIT); + } + }); + } + }); + mEmail.requestFocus(); + + mEmail.setImeActionLabel(getString(android.R.string.ok), EditorInfo.IME_ACTION_DONE); + mEmail.setOnEditorActionListener(this); + + return alert.show(); + } + + @Override + public void onCancel(DialogInterface dialog) { + super.onCancel(dialog); + + dismiss(); + sendMessageToHandler(MESSAGE_CANCEL); + } + + @Override + public void onDismiss(DialogInterface dialog) { + super.onDismiss(dialog); + + // hide keyboard on dismiss + hideKeyboard(); + } + + private void hideKeyboard() { + if (getActivity() == null) { + return; + } + InputMethodManager inputManager = (InputMethodManager) getActivity() + .getSystemService(Context.INPUT_METHOD_SERVICE); + + // check if no view has focus: + View v = getActivity().getCurrentFocus(); + if (v == null) + return; + + inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); + } + + /** + * Associate the "done" button on the soft keyboard with the okay button in the view + */ + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + if (EditorInfo.IME_ACTION_DONE == actionId) { + AlertDialog dialog = ((AlertDialog) getDialog()); + Button bt = dialog.getButton(AlertDialog.BUTTON_POSITIVE); + + bt.performClick(); + return true; + } + return false; + } + + /** + * Send message back to handler which is initialized in a activity + * + * @param what Message integer you want to send + */ + private void sendMessageToHandler(Integer what) { + Message msg = Message.obtain(); + msg.what = what; + + try { + mMessenger.send(msg); + } catch (RemoteException e) { + Log.w(Constants.TAG, "Exception sending message, Is handler present?", e); + } catch (NullPointerException e) { + Log.w(Constants.TAG, "Messenger is null!", e); + } + } + + /** + * Send message back to handler which is initialized in a activity + * + * @param what Message integer you want to send + */ + private void sendMessageToHandler(Integer what, Bundle data) { + Message msg = Message.obtain(); + msg.what = what; + if (data != null) { + msg.setData(data); + } + + try { + mMessenger.send(msg); + } catch (RemoteException e) { + Log.w(Constants.TAG, "Exception sending message, Is handler present?", e); + } catch (NullPointerException e) { + Log.w(Constants.TAG, "Messenger is null!", e); + } + } + +} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java index c4b437593..7737523e3 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/DeleteFileDialogFragment.java @@ -18,7 +18,6 @@ package org.sufficientlysecure.keychain.ui.dialog; import android.app.Dialog; -import android.content.ContentResolver; import android.content.DialogInterface; import android.net.Uri; import android.os.Build; @@ -34,18 +33,22 @@ import org.sufficientlysecure.keychain.util.FileHelper; import org.sufficientlysecure.keychain.util.Log; import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; public class DeleteFileDialogFragment extends DialogFragment { - private static final String ARG_DELETE_URI = "delete_uri"; + private static final String ARG_DELETE_URIS = "delete_uris"; + + private OnDeletedListener onDeletedListener; /** * Creates new instance of this delete file dialog fragment */ - public static DeleteFileDialogFragment newInstance(Uri deleteUri) { + public static DeleteFileDialogFragment newInstance(Uri... deleteUris) { DeleteFileDialogFragment frag = new DeleteFileDialogFragment(); Bundle args = new Bundle(); - args.putParcelable(ARG_DELETE_URI, deleteUri); + args.putParcelableArray(ARG_DELETE_URIS, deleteUris); frag.setArguments(args); @@ -59,12 +62,21 @@ public class DeleteFileDialogFragment extends DialogFragment { public Dialog onCreateDialog(Bundle savedInstanceState) { final FragmentActivity activity = getActivity(); - final Uri deleteUri = getArguments().getParcelable(ARG_DELETE_URI); - final String deleteFilename = FileHelper.getFilename(getActivity(), deleteUri); + final Uri[] deleteUris = (Uri[]) getArguments().getParcelableArray(ARG_DELETE_URIS); + + final StringBuilder deleteFileNames = new StringBuilder(); + //Retrieving file names after deletion gives unexpected results + final HashMap<Uri, String> deleteFileNameMap = new HashMap<>(); + for (Uri deleteUri : deleteUris) { + String deleteFileName = FileHelper.getFilename(getActivity(), deleteUri); + deleteFileNames.append('\n').append(deleteFileName); + deleteFileNameMap.put(deleteUri, deleteFileName); + } CustomAlertDialogBuilder alert = new CustomAlertDialogBuilder(activity); - alert.setMessage(this.getString(R.string.file_delete_confirmation, deleteFilename)); + alert.setTitle(getString(R.string.file_delete_confirmation_title)); + alert.setMessage(getString(R.string.file_delete_confirmation, deleteFileNames.toString())); alert.setPositiveButton(R.string.btn_delete, new DialogInterface.OnClickListener() { @@ -72,43 +84,55 @@ public class DeleteFileDialogFragment extends DialogFragment { public void onClick(DialogInterface dialog, int id) { dismiss(); - // NOTE: Use Toasts, not Snackbars. When sharing to another application snackbars - // would not show up! + ArrayList<String> failedFileNameList = new ArrayList<>(); + + for (Uri deleteUri : deleteUris) { + // Use DocumentsContract on Android >= 4.4 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + try { + if (DocumentsContract.deleteDocument(getActivity().getContentResolver(), deleteUri)) { + continue; + } + } catch (Exception e) { + Log.d(Constants.TAG, "Catched UnsupportedOperationException, can happen when delete is not supported!", e); + } + } - // Use DocumentsContract on Android >= 4.4 - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { try { - if (DocumentsContract.deleteDocument(getActivity().getContentResolver(), deleteUri)) { - Toast.makeText(getActivity(), getActivity().getString(R.string.file_delete_successful, - deleteFilename), Toast.LENGTH_LONG).show(); - return; + if (getActivity().getContentResolver().delete(deleteUri, null, null) > 0) { + continue; } - } catch (UnsupportedOperationException e) { + } catch (Exception e) { Log.d(Constants.TAG, "Catched UnsupportedOperationException, can happen when delete is not supported!", e); } - } - try { - if (getActivity().getContentResolver().delete(deleteUri, null, null) > 0) { - Toast.makeText(getActivity(), getActivity().getString(R.string.file_delete_successful, - deleteFilename), Toast.LENGTH_LONG).show(); - return; + // some Uri's a ContentResolver fails to delete is handled by the java.io.File's delete + // via the path of the Uri + if (new File(deleteUri.getPath()).delete()) { + continue; } - } catch (UnsupportedOperationException e) { - Log.d(Constants.TAG, "Catched UnsupportedOperationException, can happen when delete is not supported!", e); + + // Note: We can't delete every file... + failedFileNameList.add(deleteFileNameMap.get(deleteUri)); } - // some Uri's a ContentResolver fails to delete is handled by the java.io.File's delete - // via the path of the Uri - if (new File(deleteUri.getPath()).delete()) { - Toast.makeText(getActivity(), getActivity().getString(R.string.file_delete_successful, - deleteFilename), Toast.LENGTH_LONG).show(); - return; + StringBuilder failedFileNames = new StringBuilder(); + if (!failedFileNameList.isEmpty()) { + for (String failedFileName : failedFileNameList) { + failedFileNames.append('\n').append(failedFileName); + } + failedFileNames.append('\n').append(getActivity().getString(R.string.error_file_delete_failed)); } - // Note: We can't delete every file... - Toast.makeText(getActivity(), getActivity().getString(R.string.error_file_delete_failed, - deleteFilename), Toast.LENGTH_LONG).show(); + // NOTE: Use Toasts, not Snackbars. When sharing to another application snackbars + // would not show up! + Toast.makeText(getActivity(), getActivity().getString(R.string.file_delete_successful, + deleteUris.length - failedFileNameList.size(), deleteUris.length, failedFileNames.toString()), + Toast.LENGTH_LONG).show(); + + if (onDeletedListener != null) { + onDeletedListener.onDeleted(); + } } }); alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @@ -120,4 +144,18 @@ public class DeleteFileDialogFragment extends DialogFragment { return alert.show(); } + + public void setOnDeletedListener(OnDeletedListener onDeletedListener) { + this.onDeletedListener = onDeletedListener; + } + + /** + * Callback for performing tasks after the deletion of files + */ + public interface OnDeletedListener { + + public void onDeleted(); + + } + } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/ContactHelper.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/ContactHelper.java index 08c7c02fb..b3eb36157 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/ContactHelper.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/ContactHelper.java @@ -267,6 +267,63 @@ public class ContactHelper { return null; } + /** + * returns the CONTACT_ID of the raw contact to which a masterKeyId is associated, if the + * raw contact has not been marked for deletion + * + * @param resolver + * @param masterKeyId + * @return CONTACT_ID (id of aggregated contact) linked to masterKeyId + */ + public static long findContactId(ContentResolver resolver, long masterKeyId) { + long contactId = -1; + Cursor raw = resolver.query(ContactsContract.RawContacts.CONTENT_URI, + new String[]{ + ContactsContract.RawContacts.CONTACT_ID + }, + ContactsContract.RawContacts.ACCOUNT_TYPE + "=? AND " + + ContactsContract.RawContacts.SOURCE_ID + "=? AND " + + ContactsContract.RawContacts.DELETED + "=?", + new String[]{//"0" for "not deleted" + Constants.ACCOUNT_TYPE, Long.toString(masterKeyId), "0" + }, null); + if (raw != null) { + if (raw.moveToNext()) { + contactId = raw.getLong(0); + } + raw.close(); + } + return contactId; + } + + /** + * Returns the display name of the system contact associated with contactId, null if the + * contact does not exist + * + * @param resolver + * @param contactId + * @return primary display name of system contact associated with contactId, null if it does + * not exist + */ + public static String getContactName(ContentResolver resolver, long contactId) { + String contactName = null; + Cursor raw = resolver.query(ContactsContract.Contacts.CONTENT_URI, + new String[]{ + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + }, + ContactsContract.Contacts._ID + "=?", + new String[]{//"0" for "not deleted" + Long.toString(contactId) + }, null); + if (raw != null) { + if (raw.moveToNext()) { + contactName = raw.getString(0); + } + raw.close(); + } + return contactName; + } + public static Bitmap getCachedPhotoByMasterKeyId(ContentResolver contentResolver, long masterKeyId) { if (masterKeyId == -1) { return null; @@ -304,12 +361,16 @@ public class ContactHelper { KeychainContract.KeyRings.MASTER_KEY_ID, KeychainContract.KeyRings.USER_ID, KeychainContract.KeyRings.IS_EXPIRED, - KeychainContract.KeyRings.IS_REVOKED}; + KeychainContract.KeyRings.IS_REVOKED, + KeychainContract.KeyRings.VERIFIED, + KeychainContract.KeyRings.HAS_SECRET}; public static final int INDEX_MASTER_KEY_ID = 0; public static final int INDEX_USER_ID = 1; public static final int INDEX_IS_EXPIRED = 2; public static final int INDEX_IS_REVOKED = 3; + public static final int INDEX_VERIFIED = 4; + public static final int INDEX_HAS_SECRET = 5; /** * Write/Update the current OpenKeychain keys to the contact db @@ -344,6 +405,8 @@ public class ContactHelper { String keyIdShort = KeyFormattingUtils.convertKeyIdToHexShort(cursor.getLong(INDEX_MASTER_KEY_ID)); boolean isExpired = cursor.getInt(INDEX_IS_EXPIRED) != 0; boolean isRevoked = cursor.getInt(INDEX_IS_REVOKED) > 0; + boolean isVerified = cursor.getInt(INDEX_VERIFIED) > 0; + boolean isSecret = cursor.getInt(INDEX_HAS_SECRET) != 0; Log.d(Constants.TAG, "masterKeyId: " + masterKeyId); @@ -356,8 +419,8 @@ public class ContactHelper { ArrayList<ContentProviderOperation> ops = new ArrayList<>(); // Do not store expired or revoked keys in contact db - and remove them if they already exist - if (isExpired || isRevoked) { - Log.d(Constants.TAG, "Expired or revoked: Deleting " + rawContactId); + if (isExpired || isRevoked || !isVerified&&!isSecret) { + Log.d(Constants.TAG, "Expired or revoked or unverified: Deleting rawContactId " + rawContactId); if (rawContactId != -1) { deleteRawContactById(resolver, rawContactId); } @@ -394,12 +457,15 @@ public class ContactHelper { /** * Delete all raw contacts associated to OpenKeychain. - * <p/> - * TODO: Does this work? */ private static int debugDeleteRawContacts(ContentResolver resolver) { + //allows us to actually wipe the RawContact from the device, otherwise would be just flagged + //for deletion + Uri deleteUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon(). + appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); + Log.d(Constants.TAG, "Deleting all raw contacts associated to OK..."); - return resolver.delete(ContactsContract.RawContacts.CONTENT_URI, + return resolver.delete(deleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=?", new String[]{ Constants.ACCOUNT_TYPE @@ -407,7 +473,12 @@ public class ContactHelper { } private static int deleteRawContactById(ContentResolver resolver, long rawContactId) { - return resolver.delete(ContactsContract.RawContacts.CONTENT_URI, + //allows us to actually wipe the RawContact from the device, otherwise would be just flagged + //for deletion + Uri deleteUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon(). + appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); + + return resolver.delete(deleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=? AND " + ContactsContract.RawContacts._ID + "=?", new String[]{ Constants.ACCOUNT_TYPE, Long.toString(rawContactId) @@ -415,7 +486,12 @@ public class ContactHelper { } private static int deleteRawContactByMasterKeyId(ContentResolver resolver, long masterKeyId) { - return resolver.delete(ContactsContract.RawContacts.CONTENT_URI, + //allows us to actually wipe the RawContact from the device, otherwise would be just flagged + //for deletion + Uri deleteUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon(). + appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); + + return resolver.delete(deleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=? AND " + ContactsContract.RawContacts.SOURCE_ID + "=?", new String[]{ Constants.ACCOUNT_TYPE, Long.toString(masterKeyId) |