Search in sources :

Example 16 with Jid

use of eu.siacs.conversations.xmpp.Jid in project Conversations by siacs.

the class AxolotlService method createSessionsIfNeeded.

public boolean createSessionsIfNeeded(final Conversation conversation) {
    final List<Jid> jidsWithEmptyDeviceList = getCryptoTargets(conversation);
    for (Iterator<Jid> iterator = jidsWithEmptyDeviceList.iterator(); iterator.hasNext(); ) {
        final Jid jid = iterator.next();
        if (!hasEmptyDeviceList(jid)) {
            iterator.remove();
        }
    }
    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": createSessionsIfNeeded() - jids with empty device list: " + jidsWithEmptyDeviceList);
    if (jidsWithEmptyDeviceList.size() > 0) {
        fetchDeviceIds(jidsWithEmptyDeviceList, () -> createSessionsIfNeededActual(conversation));
        return true;
    } else {
        return createSessionsIfNeededActual(conversation);
    }
}
Also used : Jid(eu.siacs.conversations.xmpp.Jid)

Example 17 with Jid

use of eu.siacs.conversations.xmpp.Jid in project Conversations by siacs.

the class ImportBackupService method importBackup.

private boolean importBackup(final Uri uri, final String password) {
    Log.d(Config.LOGTAG, "importing backup from " + uri);
    final Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        final SQLiteDatabase db = mDatabaseBackend.getWritableDatabase();
        final InputStream inputStream;
        final String path = uri.getPath();
        final long fileSize;
        if ("file".equals(uri.getScheme()) && path != null) {
            final File file = new File(path);
            inputStream = new FileInputStream(file);
            fileSize = file.length();
        } else {
            final Cursor returnCursor = getContentResolver().query(uri, null, null, null, null);
            if (returnCursor == null) {
                fileSize = 0;
            } else {
                returnCursor.moveToFirst();
                fileSize = returnCursor.getLong(returnCursor.getColumnIndex(OpenableColumns.SIZE));
                returnCursor.close();
            }
            inputStream = getContentResolver().openInputStream(uri);
        }
        if (inputStream == null) {
            synchronized (mOnBackupProcessedListeners) {
                for (final OnBackupProcessed l : mOnBackupProcessedListeners) {
                    l.onBackupRestoreFailed();
                }
            }
            return false;
        }
        final CountingInputStream countingInputStream = new CountingInputStream(inputStream);
        final DataInputStream dataInputStream = new DataInputStream(countingInputStream);
        final BackupFileHeader backupFileHeader = BackupFileHeader.read(dataInputStream);
        Log.d(Config.LOGTAG, backupFileHeader.toString());
        if (mDatabaseBackend.getAccountJids(false).contains(backupFileHeader.getJid())) {
            synchronized (mOnBackupProcessedListeners) {
                for (OnBackupProcessed l : mOnBackupProcessedListeners) {
                    l.onAccountAlreadySetup();
                }
            }
            return false;
        }
        final byte[] key = ExportBackupService.getKey(password, backupFileHeader.getSalt());
        final AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
        cipher.init(false, new AEADParameters(new KeyParameter(key), 128, backupFileHeader.getIv()));
        final CipherInputStream cipherInputStream = new CipherInputStream(countingInputStream, cipher);
        final GZIPInputStream gzipInputStream = new GZIPInputStream(cipherInputStream);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream, Charsets.UTF_8));
        db.beginTransaction();
        String line;
        StringBuilder multiLineQuery = null;
        while ((line = reader.readLine()) != null) {
            int count = count(line, '\'');
            if (multiLineQuery != null) {
                multiLineQuery.append('\n');
                multiLineQuery.append(line);
                if (count % 2 == 1) {
                    db.execSQL(multiLineQuery.toString());
                    multiLineQuery = null;
                    updateImportBackupNotification(fileSize, countingInputStream.getCount());
                }
            } else {
                if (count % 2 == 0) {
                    db.execSQL(line);
                    updateImportBackupNotification(fileSize, countingInputStream.getCount());
                } else {
                    multiLineQuery = new StringBuilder(line);
                }
            }
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        final Jid jid = backupFileHeader.getJid();
        final Cursor countCursor = db.rawQuery("select count(messages.uuid) from messages join conversations on conversations.uuid=messages.conversationUuid join accounts on conversations.accountUuid=accounts.uuid where accounts.username=? and accounts.server=?", new String[] { jid.getEscapedLocal(), jid.getDomain().toEscapedString() });
        countCursor.moveToFirst();
        final int count = countCursor.getInt(0);
        Log.d(Config.LOGTAG, String.format("restored %d messages in %s", count, stopwatch.stop().toString()));
        countCursor.close();
        stopBackgroundService();
        synchronized (mOnBackupProcessedListeners) {
            for (OnBackupProcessed l : mOnBackupProcessedListeners) {
                l.onBackupRestored();
            }
        }
        return true;
    } catch (final Exception e) {
        final Throwable throwable = e.getCause();
        final boolean reasonWasCrypto = throwable instanceof BadPaddingException || e instanceof ZipException;
        synchronized (mOnBackupProcessedListeners) {
            for (OnBackupProcessed l : mOnBackupProcessedListeners) {
                if (reasonWasCrypto) {
                    l.onBackupDecryptionFailed();
                } else {
                    l.onBackupRestoreFailed();
                }
            }
        }
        Log.d(Config.LOGTAG, "error restoring backup " + uri, e);
        return false;
    }
}
Also used : KeyParameter(org.bouncycastle.crypto.params.KeyParameter) Stopwatch(com.google.common.base.Stopwatch) BadPaddingException(javax.crypto.BadPaddingException) Cursor(android.database.Cursor) GZIPInputStream(java.util.zip.GZIPInputStream) AEADBlockCipher(org.bouncycastle.crypto.modes.AEADBlockCipher) AESEngine(org.bouncycastle.crypto.engines.AESEngine) CipherInputStream(org.bouncycastle.crypto.io.CipherInputStream) InputStreamReader(java.io.InputStreamReader) Jid(eu.siacs.conversations.xmpp.Jid) GZIPInputStream(java.util.zip.GZIPInputStream) CountingInputStream(com.google.common.io.CountingInputStream) CipherInputStream(org.bouncycastle.crypto.io.CipherInputStream) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CountingInputStream(com.google.common.io.CountingInputStream) ZipException(java.util.zip.ZipException) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) ZipException(java.util.zip.ZipException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) BackupFileHeader(eu.siacs.conversations.utils.BackupFileHeader) AEADParameters(org.bouncycastle.crypto.params.AEADParameters) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) BufferedReader(java.io.BufferedReader) File(java.io.File) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher)

Example 18 with Jid

use of eu.siacs.conversations.xmpp.Jid in project Conversations by siacs.

the class EasyOnboardingInviteActivity method onBackendConnected.

@Override
void onBackendConnected() {
    if (easyOnboardingInvite != null) {
        return;
    }
    final Intent launchIntent = getIntent();
    final String accountExtra = launchIntent.getStringExtra(EXTRA_ACCOUNT);
    final Jid jid = accountExtra == null ? null : Jid.ofEscaped(accountExtra);
    if (jid == null) {
        return;
    }
    final Account account = xmppConnectionService.findAccountByJid(jid);
    xmppConnectionService.requestEasyOnboardingInvite(account, this);
}
Also used : Account(eu.siacs.conversations.entities.Account) Jid(eu.siacs.conversations.xmpp.Jid) Intent(android.content.Intent)

Example 19 with Jid

use of eu.siacs.conversations.xmpp.Jid in project Conversations by siacs.

the class MagicCreateActivity method onCreate.

@Override
protected void onCreate(final Bundle savedInstanceState) {
    final Intent data = getIntent();
    this.domain = data == null ? null : data.getStringExtra(EXTRA_DOMAIN);
    this.preAuth = data == null ? null : data.getStringExtra(EXTRA_PRE_AUTH);
    this.username = data == null ? null : data.getStringExtra(EXTRA_USERNAME);
    if (getResources().getBoolean(R.bool.portrait_only)) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    super.onCreate(savedInstanceState);
    this.binding = DataBindingUtil.setContentView(this, R.layout.magic_create);
    setSupportActionBar(this.binding.toolbar);
    configureActionBar(getSupportActionBar(), this.domain == null);
    if (username != null && domain != null) {
        binding.title.setText(R.string.your_server_invitation);
        binding.instructions.setText(getString(R.string.magic_create_text_fixed, domain));
        binding.finePrint.setVisibility(View.INVISIBLE);
        binding.username.setEnabled(false);
        binding.username.setText(this.username);
        updateFullJidInformation(this.username);
    } else if (domain != null) {
        binding.instructions.setText(getString(R.string.magic_create_text_on_x, domain));
        binding.finePrint.setVisibility(View.INVISIBLE);
    }
    binding.createAccount.setOnClickListener(v -> {
        try {
            final String username = binding.username.getText().toString();
            final Jid jid;
            final boolean fixedUsername;
            if (this.domain != null && this.username != null) {
                fixedUsername = true;
                jid = Jid.ofLocalAndDomainEscaped(this.username, this.domain);
            } else if (this.domain != null) {
                fixedUsername = false;
                jid = Jid.ofLocalAndDomainEscaped(username, this.domain);
            } else {
                fixedUsername = false;
                jid = Jid.ofLocalAndDomainEscaped(username, Config.MAGIC_CREATE_DOMAIN);
            }
            if (!jid.getEscapedLocal().equals(jid.getLocal()) || (this.username == null && username.length() < 3)) {
                binding.username.setError(getString(R.string.invalid_username));
                binding.username.requestFocus();
            } else {
                binding.username.setError(null);
                Account account = xmppConnectionService.findAccountByJid(jid);
                if (account == null) {
                    account = new Account(jid, CryptoHelper.createPassword(new SecureRandom()));
                    account.setOption(Account.OPTION_REGISTER, true);
                    account.setOption(Account.OPTION_DISABLED, true);
                    account.setOption(Account.OPTION_MAGIC_CREATE, true);
                    account.setOption(Account.OPTION_FIXED_USERNAME, fixedUsername);
                    if (this.preAuth != null) {
                        account.setKey(Account.PRE_AUTH_REGISTRATION_TOKEN, this.preAuth);
                    }
                    xmppConnectionService.createAccount(account);
                }
                Intent intent = new Intent(MagicCreateActivity.this, EditAccountActivity.class);
                intent.putExtra("jid", account.getJid().asBareJid().toString());
                intent.putExtra("init", true);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                Toast.makeText(MagicCreateActivity.this, R.string.secure_password_generated, Toast.LENGTH_SHORT).show();
                StartConversationActivity.addInviteUri(intent, getIntent());
                startActivity(intent);
            }
        } catch (IllegalArgumentException e) {
            binding.username.setError(getString(R.string.invalid_username));
            binding.username.requestFocus();
        }
    });
    binding.username.addTextChangedListener(this);
}
Also used : Account(eu.siacs.conversations.entities.Account) Jid(eu.siacs.conversations.xmpp.Jid) SecureRandom(java.security.SecureRandom) Intent(android.content.Intent)

Example 20 with Jid

use of eu.siacs.conversations.xmpp.Jid in project Conversations by siacs.

the class JabberIdContact method load.

public static Map<Jid, JabberIdContact> load(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        return Collections.emptyMap();
    }
    try (final Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, PROJECTION, SELECTION, SELECTION_ARGS, null)) {
        if (cursor == null) {
            return Collections.emptyMap();
        }
        final HashMap<Jid, JabberIdContact> contacts = new HashMap<>();
        while (cursor.moveToNext()) {
            try {
                final JabberIdContact contact = new JabberIdContact(cursor);
                final JabberIdContact preexisting = contacts.put(contact.getJid(), contact);
                if (preexisting == null || preexisting.rating() < contact.rating()) {
                    contacts.put(contact.getJid(), contact);
                }
            } catch (final IllegalArgumentException e) {
                Log.d(Config.LOGTAG, "unable to create jabber id contact");
            }
        }
        return contacts;
    } catch (final Exception e) {
        Log.d(Config.LOGTAG, "unable to query", e);
        return Collections.emptyMap();
    }
}
Also used : Jid(eu.siacs.conversations.xmpp.Jid) HashMap(java.util.HashMap) Cursor(android.database.Cursor)

Aggregations

Jid (eu.siacs.conversations.xmpp.Jid)106 Account (eu.siacs.conversations.entities.Account)35 Element (eu.siacs.conversations.xml.Element)24 Conversation (eu.siacs.conversations.entities.Conversation)22 Contact (eu.siacs.conversations.entities.Contact)17 InvalidJid (eu.siacs.conversations.xmpp.InvalidJid)16 IqPacket (eu.siacs.conversations.xmpp.stanzas.IqPacket)16 Intent (android.content.Intent)15 ArrayList (java.util.ArrayList)13 MucOptions (eu.siacs.conversations.entities.MucOptions)12 Bookmark (eu.siacs.conversations.entities.Bookmark)10 AxolotlService (eu.siacs.conversations.crypto.axolotl.AxolotlService)7 Message (eu.siacs.conversations.entities.Message)7 OnIqPacketReceived (eu.siacs.conversations.xmpp.OnIqPacketReceived)6 MessagePacket (eu.siacs.conversations.xmpp.stanzas.MessagePacket)6 Map (java.util.Map)6 XmppUri (eu.siacs.conversations.utils.XmppUri)5 XmppConnectionService (eu.siacs.conversations.services.XmppConnectionService)4 Avatar (eu.siacs.conversations.xmpp.pep.Avatar)4 HashMap (java.util.HashMap)4