Search in sources :

Example 1 with IMXCryptoStore

use of org.matrix.androidsdk.data.cryptostore.IMXCryptoStore in project matrix-android-sdk by matrix-org.

the class MXDeviceList method doKeyDownloadForUsers.

/**
 * Download the devices keys for a set of users.
 * It must be called in getEncryptingThreadHandler() thread.
 * The callback is called in the UI thread.
 *
 * @param downloadUsers the user ids list
 * @param callback      the asynchronous callback
 */
private void doKeyDownloadForUsers(final List<String> downloadUsers, final ApiCallback<MXUsersDevicesMap<MXDeviceInfo>> callback) {
    Log.d(LOG_TAG, "## doKeyDownloadForUsers() : doKeyDownloadForUsers " + downloadUsers);
    // get the user ids which did not already trigger a keys download
    final List<String> filteredUsers = addDownloadKeysPromise(downloadUsers, callback);
    // if there is no new keys request
    if (0 == filteredUsers.size()) {
        // trigger nothing
        return;
    }
    // sanity check
    if ((null == mxSession.getDataHandler()) || (null == mxSession.getDataHandler().getStore())) {
        return;
    }
    mIsDownloadingKeys = true;
    // track the race condition while sending requests
    // we defines a tag for each request
    // and test if the response is the latest request one
    final String downloadToken = filteredUsers.hashCode() + " " + System.currentTimeMillis();
    for (String userId : filteredUsers) {
        mPendingDownloadKeysRequestToken.put(userId, downloadToken);
    }
    mxSession.getCryptoRestClient().downloadKeysForUsers(filteredUsers, mxSession.getDataHandler().getStore().getEventStreamToken(), new ApiCallback<KeysQueryResponse>() {

        @Override
        public void onSuccess(final KeysQueryResponse keysQueryResponse) {
            mxCrypto.getEncryptingThreadHandler().post(new Runnable() {

                @Override
                public void run() {
                    Log.d(LOG_TAG, "## doKeyDownloadForUsers() : Got keys for " + filteredUsers.size() + " users");
                    MXDeviceInfo myDevice = mxCrypto.getMyDevice();
                    IMXCryptoStore cryptoStore = mxCrypto.getCryptoStore();
                    List<String> userIdsList = new ArrayList<>(filteredUsers);
                    for (String userId : userIdsList) {
                        // test if the response is the latest request one
                        if (!TextUtils.equals(mPendingDownloadKeysRequestToken.get(userId), downloadToken)) {
                            Log.e(LOG_TAG, "## doKeyDownloadForUsers() : Another update in the queue for " + userId + " not marking up-to-date");
                            filteredUsers.remove(userId);
                        } else {
                            Map<String, MXDeviceInfo> devices = keysQueryResponse.deviceKeys.get(userId);
                            Log.d(LOG_TAG, "## doKeyDownloadForUsers() : Got keys for " + userId + " : " + devices);
                            if (null != devices) {
                                HashMap<String, MXDeviceInfo> mutableDevices = new HashMap<>(devices);
                                ArrayList<String> deviceIds = new ArrayList<>(mutableDevices.keySet());
                                for (String deviceId : deviceIds) {
                                    // the user has been logged out
                                    if (null == cryptoStore) {
                                        break;
                                    }
                                    // Get the potential previously store device keys for this device
                                    MXDeviceInfo previouslyStoredDeviceKeys = cryptoStore.getUserDevice(deviceId, userId);
                                    MXDeviceInfo deviceInfo = mutableDevices.get(deviceId);
                                    // the self device must be seen as verified
                                    if (TextUtils.equals(deviceInfo.deviceId, myDevice.deviceId) && TextUtils.equals(userId, myDevice.userId)) {
                                        deviceInfo.mVerified = MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED;
                                    }
                                    // Validate received keys
                                    if (!validateDeviceKeys(deviceInfo, userId, deviceId, previouslyStoredDeviceKeys)) {
                                        // New device keys are not valid. Do not store them
                                        mutableDevices.remove(deviceId);
                                        if (null != previouslyStoredDeviceKeys) {
                                            // But keep old validated ones if any
                                            mutableDevices.put(deviceId, previouslyStoredDeviceKeys);
                                        }
                                    } else if (null != previouslyStoredDeviceKeys) {
                                        // The verified status is not sync'ed with hs.
                                        // This is a client side information, valid only for this client.
                                        // So, transfer its previous value
                                        mutableDevices.get(deviceId).mVerified = previouslyStoredDeviceKeys.mVerified;
                                    }
                                }
                                // Update the store
                                // Note that devices which aren't in the response will be removed from the stores
                                cryptoStore.storeUserDevices(userId, mutableDevices);
                            }
                            // the response is the latest request one
                            mPendingDownloadKeysRequestToken.remove(userId);
                        }
                    }
                    onKeysDownloadSucceed(filteredUsers, keysQueryResponse.failures);
                }
            });
        }

        private void onFailed() {
            mxCrypto.getEncryptingThreadHandler().post(new Runnable() {

                @Override
                public void run() {
                    List<String> userIdsList = new ArrayList<>(filteredUsers);
                    // test if the response is the latest request one
                    for (String userId : userIdsList) {
                        if (!TextUtils.equals(mPendingDownloadKeysRequestToken.get(userId), downloadToken)) {
                            Log.e(LOG_TAG, "## doKeyDownloadForUsers() : Another update in the queue for " + userId + " not marking up-to-date");
                            filteredUsers.remove(userId);
                        } else {
                            // the response is the latest request one
                            mPendingDownloadKeysRequestToken.remove(userId);
                        }
                    }
                    onKeysDownloadFailed(filteredUsers);
                }
            });
        }

        @Override
        public void onNetworkError(Exception e) {
            Log.e(LOG_TAG, "##doKeyDownloadForUsers() : onNetworkError " + e.getMessage());
            onFailed();
            if (null != callback) {
                callback.onNetworkError(e);
            }
        }

        @Override
        public void onMatrixError(MatrixError e) {
            Log.e(LOG_TAG, "##doKeyDownloadForUsers() : onMatrixError " + e.getMessage());
            onFailed();
            if (null != callback) {
                callback.onMatrixError(e);
            }
        }

        @Override
        public void onUnexpectedError(Exception e) {
            Log.e(LOG_TAG, "##doKeyDownloadForUsers() : onUnexpectedError " + e.getMessage());
            onFailed();
            if (null != callback) {
                callback.onUnexpectedError(e);
            }
        }
    });
}
Also used : IMXCryptoStore(org.matrix.androidsdk.data.cryptostore.IMXCryptoStore) HashMap(java.util.HashMap) MXDeviceInfo(org.matrix.androidsdk.crypto.data.MXDeviceInfo) ArrayList(java.util.ArrayList) KeysQueryResponse(org.matrix.androidsdk.rest.model.crypto.KeysQueryResponse) MatrixError(org.matrix.androidsdk.rest.model.MatrixError)

Example 2 with IMXCryptoStore

use of org.matrix.androidsdk.data.cryptostore.IMXCryptoStore in project matrix-android-sdk by matrix-org.

the class MXSession method enableCrypto.

/**
 * Enable / disable the crypto.
 *
 * @param cryptoEnabled true to enable the crypto
 * @param callback      the asynchronous callback called when the action has been done
 */
public void enableCrypto(boolean cryptoEnabled, final ApiCallback<Void> callback) {
    if (cryptoEnabled != isCryptoEnabled()) {
        if (cryptoEnabled) {
            Log.d(LOG_TAG, "Crypto is enabled");
            MXFileCryptoStore fileCryptoStore = new MXFileCryptoStore();
            fileCryptoStore.initWithCredentials(mAppContent, mCredentials);
            fileCryptoStore.open();
            mCrypto = new MXCrypto(this, fileCryptoStore);
            mCrypto.start(true, new ApiCallback<Void>() {

                @Override
                public void onSuccess(Void info) {
                    decryptRoomSummaries();
                    if (null != callback) {
                        callback.onSuccess(null);
                    }
                }

                @Override
                public void onNetworkError(Exception e) {
                    if (null != callback) {
                        callback.onNetworkError(e);
                    }
                }

                @Override
                public void onMatrixError(MatrixError e) {
                    if (null != callback) {
                        callback.onMatrixError(e);
                    }
                }

                @Override
                public void onUnexpectedError(Exception e) {
                    if (null != callback) {
                        callback.onUnexpectedError(e);
                    }
                }
            });
        } else if (null != mCrypto) {
            Log.d(LOG_TAG, "Crypto is disabled");
            IMXCryptoStore store = mCrypto.mCryptoStore;
            mCrypto.close();
            store.deleteStore();
            mCrypto = null;
            mDataHandler.setCrypto(null);
            decryptRoomSummaries();
            if (null != callback) {
                callback.onSuccess(null);
            }
        }
        mDataHandler.setCrypto(mCrypto);
    } else {
        if (null != callback) {
            callback.onSuccess(null);
        }
    }
}
Also used : IMXCryptoStore(org.matrix.androidsdk.data.cryptostore.IMXCryptoStore) MXFileCryptoStore(org.matrix.androidsdk.data.cryptostore.MXFileCryptoStore) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) MXCrypto(org.matrix.androidsdk.crypto.MXCrypto)

Aggregations

IMXCryptoStore (org.matrix.androidsdk.data.cryptostore.IMXCryptoStore)2 MatrixError (org.matrix.androidsdk.rest.model.MatrixError)2 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 MXCrypto (org.matrix.androidsdk.crypto.MXCrypto)1 MXDeviceInfo (org.matrix.androidsdk.crypto.data.MXDeviceInfo)1 MXFileCryptoStore (org.matrix.androidsdk.data.cryptostore.MXFileCryptoStore)1 KeysQueryResponse (org.matrix.androidsdk.rest.model.crypto.KeysQueryResponse)1