Search in sources :

Example 1 with RequestDelegate

use of org.telegram.tgnet.RequestDelegate in project Telegram-FOSS by Telegram-FOSS-Team.

the class SendMessagesHelper method sendCallback.

public void sendCallback(final boolean cache, final MessageObject messageObject, final TLRPC.KeyboardButton button, TLRPC.InputCheckPasswordSRP srp, TwoStepVerificationActivity passwordFragment, final ChatActivity parentFragment) {
    if (messageObject == null || button == null || parentFragment == null) {
        return;
    }
    final boolean cacheFinal;
    int type;
    if (button instanceof TLRPC.TL_keyboardButtonUrlAuth) {
        cacheFinal = false;
        type = 3;
    } else if (button instanceof TLRPC.TL_keyboardButtonGame) {
        cacheFinal = false;
        type = 1;
    } else {
        cacheFinal = cache;
        if (button instanceof TLRPC.TL_keyboardButtonBuy) {
            type = 2;
        } else {
            type = 0;
        }
    }
    final String key = messageObject.getDialogId() + "_" + messageObject.getId() + "_" + Utilities.bytesToHex(button.data) + "_" + type;
    waitingForCallback.put(key, true);
    TLObject[] request = new TLObject[1];
    RequestDelegate requestDelegate = (response, error) -> AndroidUtilities.runOnUIThread(() -> {
        waitingForCallback.remove(key);
        if (cacheFinal && response == null) {
            sendCallback(false, messageObject, button, parentFragment);
        } else if (response != null) {
            if (passwordFragment != null) {
                passwordFragment.needHideProgress();
                passwordFragment.finishFragment();
            }
            if (button instanceof TLRPC.TL_keyboardButtonUrlAuth) {
                if (response instanceof TLRPC.TL_urlAuthResultRequest) {
                    TLRPC.TL_urlAuthResultRequest res = (TLRPC.TL_urlAuthResultRequest) response;
                    parentFragment.showRequestUrlAlert(res, (TLRPC.TL_messages_requestUrlAuth) request[0], button.url, false);
                } else if (response instanceof TLRPC.TL_urlAuthResultAccepted) {
                    TLRPC.TL_urlAuthResultAccepted res = (TLRPC.TL_urlAuthResultAccepted) response;
                    AlertsCreator.showOpenUrlAlert(parentFragment, res.url, false, false);
                } else if (response instanceof TLRPC.TL_urlAuthResultDefault) {
                    TLRPC.TL_urlAuthResultDefault res = (TLRPC.TL_urlAuthResultDefault) response;
                    AlertsCreator.showOpenUrlAlert(parentFragment, button.url, false, true);
                }
            } else if (button instanceof TLRPC.TL_keyboardButtonBuy) {
                if (response instanceof TLRPC.TL_payments_paymentForm) {
                    final TLRPC.TL_payments_paymentForm form = (TLRPC.TL_payments_paymentForm) response;
                    getMessagesController().putUsers(form.users, false);
                    parentFragment.presentFragment(new PaymentFormActivity(form, messageObject, parentFragment));
                } else if (response instanceof TLRPC.TL_payments_paymentReceipt) {
                    parentFragment.presentFragment(new PaymentFormActivity((TLRPC.TL_payments_paymentReceipt) response));
                }
            } else {
                TLRPC.TL_messages_botCallbackAnswer res = (TLRPC.TL_messages_botCallbackAnswer) response;
                if (!cacheFinal && res.cache_time != 0 && !button.requires_password) {
                    getMessagesStorage().saveBotCache(key, res);
                }
                if (res.message != null) {
                    long uid = messageObject.getFromChatId();
                    if (messageObject.messageOwner.via_bot_id != 0) {
                        uid = messageObject.messageOwner.via_bot_id;
                    }
                    String name = null;
                    if (uid > 0) {
                        TLRPC.User user = getMessagesController().getUser(uid);
                        if (user != null) {
                            name = ContactsController.formatName(user.first_name, user.last_name);
                        }
                    } else {
                        TLRPC.Chat chat = getMessagesController().getChat(-uid);
                        if (chat != null) {
                            name = chat.title;
                        }
                    }
                    if (name == null) {
                        name = "bot";
                    }
                    if (res.alert) {
                        if (parentFragment.getParentActivity() == null) {
                            return;
                        }
                        AlertDialog.Builder builder = new AlertDialog.Builder(parentFragment.getParentActivity());
                        builder.setTitle(name);
                        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                        builder.setMessage(res.message);
                        parentFragment.showDialog(builder.create());
                    } else {
                        parentFragment.showAlert(name, res.message);
                    }
                } else if (res.url != null) {
                    if (parentFragment.getParentActivity() == null) {
                        return;
                    }
                    long uid = messageObject.getFromChatId();
                    if (messageObject.messageOwner.via_bot_id != 0) {
                        uid = messageObject.messageOwner.via_bot_id;
                    }
                    TLRPC.User user = getMessagesController().getUser(uid);
                    boolean verified = user != null && user.verified;
                    if (button instanceof TLRPC.TL_keyboardButtonGame) {
                        TLRPC.TL_game game = messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame ? messageObject.messageOwner.media.game : null;
                        if (game == null) {
                            return;
                        }
                        parentFragment.showOpenGameAlert(game, messageObject, res.url, !verified && MessagesController.getNotificationsSettings(currentAccount).getBoolean("askgame_" + uid, true), uid);
                    } else {
                        AlertsCreator.showOpenUrlAlert(parentFragment, res.url, false, false);
                    }
                }
            }
        } else if (error != null) {
            if (parentFragment.getParentActivity() == null) {
                return;
            }
            if ("PASSWORD_HASH_INVALID".equals(error.text)) {
                if (srp == null) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(parentFragment.getParentActivity());
                    builder.setTitle(LocaleController.getString("BotOwnershipTransfer", R.string.BotOwnershipTransfer));
                    builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("BotOwnershipTransferReadyAlertText", R.string.BotOwnershipTransferReadyAlertText)));
                    builder.setPositiveButton(LocaleController.getString("BotOwnershipTransferChangeOwner", R.string.BotOwnershipTransferChangeOwner), (dialogInterface, i) -> {
                        TwoStepVerificationActivity fragment = new TwoStepVerificationActivity();
                        fragment.setDelegate(password -> sendCallback(cache, messageObject, button, password, fragment, parentFragment));
                        parentFragment.presentFragment(fragment);
                    });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    parentFragment.showDialog(builder.create());
                }
            } else if ("PASSWORD_MISSING".equals(error.text) || error.text.startsWith("PASSWORD_TOO_FRESH_") || error.text.startsWith("SESSION_TOO_FRESH_")) {
                if (passwordFragment != null) {
                    passwordFragment.needHideProgress();
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(parentFragment.getParentActivity());
                builder.setTitle(LocaleController.getString("EditAdminTransferAlertTitle", R.string.EditAdminTransferAlertTitle));
                LinearLayout linearLayout = new LinearLayout(parentFragment.getParentActivity());
                linearLayout.setPadding(AndroidUtilities.dp(24), AndroidUtilities.dp(2), AndroidUtilities.dp(24), 0);
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                builder.setView(linearLayout);
                TextView messageTextView = new TextView(parentFragment.getParentActivity());
                messageTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
                messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
                messageTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
                messageTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("BotOwnershipTransferAlertText", R.string.BotOwnershipTransferAlertText)));
                linearLayout.addView(messageTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
                LinearLayout linearLayout2 = new LinearLayout(parentFragment.getParentActivity());
                linearLayout2.setOrientation(LinearLayout.HORIZONTAL);
                linearLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 11, 0, 0));
                ImageView dotImageView = new ImageView(parentFragment.getParentActivity());
                dotImageView.setImageResource(R.drawable.list_circle);
                dotImageView.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(11) : 0, AndroidUtilities.dp(9), LocaleController.isRTL ? 0 : AndroidUtilities.dp(11), 0);
                dotImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogTextBlack), PorterDuff.Mode.MULTIPLY));
                messageTextView = new TextView(parentFragment.getParentActivity());
                messageTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
                messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
                messageTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
                messageTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("EditAdminTransferAlertText1", R.string.EditAdminTransferAlertText1)));
                if (LocaleController.isRTL) {
                    linearLayout2.addView(messageTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
                    linearLayout2.addView(dotImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT));
                } else {
                    linearLayout2.addView(dotImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
                    linearLayout2.addView(messageTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
                }
                linearLayout2 = new LinearLayout(parentFragment.getParentActivity());
                linearLayout2.setOrientation(LinearLayout.HORIZONTAL);
                linearLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 11, 0, 0));
                dotImageView = new ImageView(parentFragment.getParentActivity());
                dotImageView.setImageResource(R.drawable.list_circle);
                dotImageView.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(11) : 0, AndroidUtilities.dp(9), LocaleController.isRTL ? 0 : AndroidUtilities.dp(11), 0);
                dotImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogTextBlack), PorterDuff.Mode.MULTIPLY));
                messageTextView = new TextView(parentFragment.getParentActivity());
                messageTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
                messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
                messageTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
                messageTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("EditAdminTransferAlertText2", R.string.EditAdminTransferAlertText2)));
                if (LocaleController.isRTL) {
                    linearLayout2.addView(messageTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
                    linearLayout2.addView(dotImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT));
                } else {
                    linearLayout2.addView(dotImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
                    linearLayout2.addView(messageTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
                }
                if ("PASSWORD_MISSING".equals(error.text)) {
                    builder.setPositiveButton(LocaleController.getString("EditAdminTransferSetPassword", R.string.EditAdminTransferSetPassword), (dialogInterface, i) -> parentFragment.presentFragment(new TwoStepVerificationSetupActivity(TwoStepVerificationSetupActivity.TYPE_INTRO, null)));
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                } else {
                    messageTextView = new TextView(parentFragment.getParentActivity());
                    messageTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
                    messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
                    messageTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
                    messageTextView.setText(LocaleController.getString("EditAdminTransferAlertText3", R.string.EditAdminTransferAlertText3));
                    linearLayout.addView(messageTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 11, 0, 0));
                    builder.setNegativeButton(LocaleController.getString("OK", R.string.OK), null);
                }
                parentFragment.showDialog(builder.create());
            } else if ("SRP_ID_INVALID".equals(error.text)) {
                TLRPC.TL_account_getPassword getPasswordReq = new TLRPC.TL_account_getPassword();
                ConnectionsManager.getInstance(currentAccount).sendRequest(getPasswordReq, (response2, error2) -> AndroidUtilities.runOnUIThread(() -> {
                    if (error2 == null) {
                        TLRPC.TL_account_password currentPassword = (TLRPC.TL_account_password) response2;
                        passwordFragment.setCurrentPasswordInfo(null, currentPassword);
                        TwoStepVerificationActivity.initPasswordNewAlgo(currentPassword);
                        sendCallback(cache, messageObject, button, passwordFragment.getNewSrpPassword(), passwordFragment, parentFragment);
                    }
                }), ConnectionsManager.RequestFlagWithoutLogin);
            } else {
                if (passwordFragment != null) {
                    passwordFragment.needHideProgress();
                    passwordFragment.finishFragment();
                }
            }
        }
    });
    if (cacheFinal) {
        getMessagesStorage().getBotCache(key, requestDelegate);
    } else {
        if (button instanceof TLRPC.TL_keyboardButtonUrlAuth) {
            TLRPC.TL_messages_requestUrlAuth req = new TLRPC.TL_messages_requestUrlAuth();
            req.peer = getMessagesController().getInputPeer(messageObject.getDialogId());
            req.msg_id = messageObject.getId();
            req.button_id = button.button_id;
            req.flags |= 2;
            request[0] = req;
            getConnectionsManager().sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors);
        } else if (button instanceof TLRPC.TL_keyboardButtonBuy) {
            if ((messageObject.messageOwner.media.flags & 4) == 0) {
                TLRPC.TL_payments_getPaymentForm req = new TLRPC.TL_payments_getPaymentForm();
                req.msg_id = messageObject.getId();
                req.peer = getMessagesController().getInputPeer(messageObject.messageOwner.peer_id);
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("bg_color", Theme.getColor(Theme.key_windowBackgroundWhite));
                    jsonObject.put("text_color", Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
                    jsonObject.put("hint_color", Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
                    jsonObject.put("link_color", Theme.getColor(Theme.key_windowBackgroundWhiteLinkText));
                    jsonObject.put("button_color", Theme.getColor(Theme.key_featuredStickers_addButton));
                    jsonObject.put("button_text_color", Theme.getColor(Theme.key_featuredStickers_buttonText));
                    req.theme_params = new TLRPC.TL_dataJSON();
                    req.theme_params.data = jsonObject.toString();
                    req.flags |= 1;
                } catch (Exception e) {
                    FileLog.e(e);
                }
                getConnectionsManager().sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors);
            } else {
                TLRPC.TL_payments_getPaymentReceipt req = new TLRPC.TL_payments_getPaymentReceipt();
                req.msg_id = messageObject.messageOwner.media.receipt_msg_id;
                req.peer = getMessagesController().getInputPeer(messageObject.messageOwner.peer_id);
                getConnectionsManager().sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors);
            }
        } else {
            TLRPC.TL_messages_getBotCallbackAnswer req = new TLRPC.TL_messages_getBotCallbackAnswer();
            req.peer = getMessagesController().getInputPeer(messageObject.getDialogId());
            req.msg_id = messageObject.getId();
            req.game = button instanceof TLRPC.TL_keyboardButtonGame;
            if (button.requires_password) {
                req.password = req.password = srp != null ? srp : new TLRPC.TL_inputCheckPasswordEmpty();
                ;
                req.flags |= 4;
            }
            if (button.data != null) {
                req.flags |= 1;
                req.data = button.data;
            }
            getConnectionsManager().sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors);
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) LinearLayout(android.widget.LinearLayout) SparseLongArray(org.telegram.messenger.support.SparseLongArray) Bundle(android.os.Bundle) Uri(android.net.Uri) ImageView(android.widget.ImageView) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) LocationListener(android.location.LocationListener) Bulletin(org.telegram.ui.Components.Bulletin) ByteBuffer(java.nio.ByteBuffer) AudioInfo(org.telegram.messenger.audioinfo.AudioInfo) JSONObject(org.json.JSONObject) MediaCodecInfo(android.media.MediaCodecInfo) Locale(java.util.Locale) MediaStore(android.provider.MediaStore) UiThread(androidx.annotation.UiThread) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) BitmapDrawable(android.graphics.drawable.BitmapDrawable) PorterDuff(android.graphics.PorterDuff) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) SparseArray(android.util.SparseArray) CountDownLatch(java.util.concurrent.CountDownLatch) TextView(android.widget.TextView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Location(android.location.Location) LocationManager(android.location.LocationManager) ChatActivity(org.telegram.ui.ChatActivity) Context(android.content.Context) MediaMetadataRetriever(android.media.MediaMetadataRetriever) Theme(org.telegram.ui.ActionBar.Theme) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) RequestDelegate(org.telegram.tgnet.RequestDelegate) TwoStepVerificationActivity(org.telegram.ui.TwoStepVerificationActivity) Intent(android.content.Intent) BitmapFactory(android.graphics.BitmapFactory) MediaPlayer(android.media.MediaPlayer) SystemClock(android.os.SystemClock) HashMap(java.util.HashMap) AlertsCreator(org.telegram.ui.Components.AlertsCreator) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TLRPC(org.telegram.tgnet.TLRPC) Point(org.telegram.ui.Components.Point) Toast(android.widget.Toast) PaymentFormActivity(org.telegram.ui.PaymentFormActivity) TLObject(org.telegram.tgnet.TLObject) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) Build(android.os.Build) SerializedData(org.telegram.tgnet.SerializedData) LongSparseArray(androidx.collection.LongSparseArray) TwoStepVerificationSetupActivity(org.telegram.ui.TwoStepVerificationSetupActivity) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) InputContentInfoCompat(androidx.core.view.inputmethod.InputContentInfoCompat) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileInputStream(java.io.FileInputStream) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Gravity(android.view.Gravity) TypedValue(android.util.TypedValue) Bitmap(android.graphics.Bitmap) Base64(android.util.Base64) ClipDescription(android.content.ClipDescription) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) FileChannel(java.nio.channels.FileChannel) MimeTypeMap(android.webkit.MimeTypeMap) InputStream(java.io.InputStream) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) TLRPC(org.telegram.tgnet.TLRPC) PaymentFormActivity(org.telegram.ui.PaymentFormActivity) TextView(android.widget.TextView) ImageView(android.widget.ImageView) RequestDelegate(org.telegram.tgnet.RequestDelegate) TwoStepVerificationActivity(org.telegram.ui.TwoStepVerificationActivity) JSONObject(org.json.JSONObject) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) TwoStepVerificationSetupActivity(org.telegram.ui.TwoStepVerificationSetupActivity) Point(org.telegram.ui.Components.Point) TLObject(org.telegram.tgnet.TLObject) LinearLayout(android.widget.LinearLayout)

Example 2 with RequestDelegate

use of org.telegram.tgnet.RequestDelegate in project Telegram-FOSS by Telegram-FOSS-Team.

the class PassportActivity method onPasswordDone.

private void onPasswordDone(final boolean saved) {
    final String textPassword;
    if (saved) {
        textPassword = null;
    } else {
        textPassword = inputFields[FIELD_PASSWORD].getText().toString();
        if (TextUtils.isEmpty(textPassword)) {
            onPasscodeError(false);
            return;
        }
        showEditDoneProgress(true, true);
    }
    Utilities.globalQueue.postRunnable(() -> {
        TLRPC.TL_account_getPasswordSettings req = new TLRPC.TL_account_getPasswordSettings();
        final byte[] x_bytes;
        if (saved) {
            x_bytes = savedPasswordHash;
        } else if (currentPassword.current_algo instanceof TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) {
            byte[] passwordBytes = AndroidUtilities.getStringBytes(textPassword);
            TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow algo = (TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) currentPassword.current_algo;
            x_bytes = SRPHelper.getX(passwordBytes, algo);
        } else {
            x_bytes = null;
        }
        RequestDelegate requestDelegate = new RequestDelegate() {

            private void openRequestInterface() {
                if (inputFields == null) {
                    return;
                }
                if (!saved) {
                    UserConfig.getInstance(currentAccount).savePassword(x_bytes, saltedPassword);
                }
                AndroidUtilities.hideKeyboard(inputFields[FIELD_PASSWORD]);
                ignoreOnFailure = true;
                int type;
                if (currentBotId == 0) {
                    type = TYPE_MANAGE;
                } else {
                    type = TYPE_REQUEST;
                }
                PassportActivity activity = new PassportActivity(type, currentBotId, currentScope, currentPublicKey, currentPayload, currentNonce, currentCallbackUrl, currentForm, currentPassword);
                activity.currentEmail = currentEmail;
                activity.currentAccount = currentAccount;
                activity.saltedPassword = saltedPassword;
                activity.secureSecret = secureSecret;
                activity.secureSecretId = secureSecretId;
                activity.needActivityResult = needActivityResult;
                if (parentLayout == null || !parentLayout.checkTransitionAnimation()) {
                    presentFragment(activity, true);
                } else {
                    presentAfterAnimation = activity;
                }
            }

            private void resetSecret() {
                TLRPC.TL_account_updatePasswordSettings req2 = new TLRPC.TL_account_updatePasswordSettings();
                if (currentPassword.current_algo instanceof TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) {
                    TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow algo = (TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) currentPassword.current_algo;
                    req2.password = SRPHelper.startCheck(x_bytes, currentPassword.srp_id, currentPassword.srp_B, algo);
                }
                req2.new_settings = new TLRPC.TL_account_passwordInputSettings();
                req2.new_settings.new_secure_settings = new TLRPC.TL_secureSecretSettings();
                req2.new_settings.new_secure_settings.secure_secret = new byte[0];
                req2.new_settings.new_secure_settings.secure_algo = new TLRPC.TL_securePasswordKdfAlgoUnknown();
                req2.new_settings.new_secure_settings.secure_secret_id = 0;
                req2.new_settings.flags |= 4;
                ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    if (error != null && "SRP_ID_INVALID".equals(error.text)) {
                        TLRPC.TL_account_getPassword getPasswordReq = new TLRPC.TL_account_getPassword();
                        ConnectionsManager.getInstance(currentAccount).sendRequest(getPasswordReq, (response2, error2) -> AndroidUtilities.runOnUIThread(() -> {
                            if (error2 == null) {
                                currentPassword = (TLRPC.TL_account_password) response2;
                                TwoStepVerificationActivity.initPasswordNewAlgo(currentPassword);
                                resetSecret();
                            }
                        }), ConnectionsManager.RequestFlagWithoutLogin);
                        return;
                    }
                    generateNewSecret();
                }));
            }

            private void generateNewSecret() {
                Utilities.globalQueue.postRunnable(() -> {
                    Utilities.random.setSeed(currentPassword.secure_random);
                    TLRPC.TL_account_updatePasswordSettings req1 = new TLRPC.TL_account_updatePasswordSettings();
                    if (currentPassword.current_algo instanceof TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) {
                        TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow algo = (TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) currentPassword.current_algo;
                        req1.password = SRPHelper.startCheck(x_bytes, currentPassword.srp_id, currentPassword.srp_B, algo);
                    }
                    req1.new_settings = new TLRPC.TL_account_passwordInputSettings();
                    secureSecret = getRandomSecret();
                    secureSecretId = Utilities.bytesToLong(Utilities.computeSHA256(secureSecret));
                    if (currentPassword.new_secure_algo instanceof TLRPC.TL_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000) {
                        TLRPC.TL_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000 newAlgo = (TLRPC.TL_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000) currentPassword.new_secure_algo;
                        saltedPassword = Utilities.computePBKDF2(AndroidUtilities.getStringBytes(textPassword), newAlgo.salt);
                        byte[] key = new byte[32];
                        System.arraycopy(saltedPassword, 0, key, 0, 32);
                        byte[] iv = new byte[16];
                        System.arraycopy(saltedPassword, 32, iv, 0, 16);
                        Utilities.aesCbcEncryptionByteArraySafe(secureSecret, key, iv, 0, secureSecret.length, 0, 1);
                        req1.new_settings.new_secure_settings = new TLRPC.TL_secureSecretSettings();
                        req1.new_settings.new_secure_settings.secure_algo = newAlgo;
                        req1.new_settings.new_secure_settings.secure_secret = secureSecret;
                        req1.new_settings.new_secure_settings.secure_secret_id = secureSecretId;
                        req1.new_settings.flags |= 4;
                    }
                    ConnectionsManager.getInstance(currentAccount).sendRequest(req1, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                        if (error != null && "SRP_ID_INVALID".equals(error.text)) {
                            TLRPC.TL_account_getPassword getPasswordReq = new TLRPC.TL_account_getPassword();
                            ConnectionsManager.getInstance(currentAccount).sendRequest(getPasswordReq, (response2, error2) -> AndroidUtilities.runOnUIThread(() -> {
                                if (error2 == null) {
                                    currentPassword = (TLRPC.TL_account_password) response2;
                                    TwoStepVerificationActivity.initPasswordNewAlgo(currentPassword);
                                    generateNewSecret();
                                }
                            }), ConnectionsManager.RequestFlagWithoutLogin);
                            return;
                        }
                        if (currentForm == null) {
                            currentForm = new TLRPC.TL_account_authorizationForm();
                        }
                        openRequestInterface();
                    }));
                });
            }

            @Override
            public void run(final TLObject response, final TLRPC.TL_error error) {
                if (error != null && "SRP_ID_INVALID".equals(error.text)) {
                    TLRPC.TL_account_getPassword getPasswordReq = new TLRPC.TL_account_getPassword();
                    ConnectionsManager.getInstance(currentAccount).sendRequest(getPasswordReq, (response2, error2) -> AndroidUtilities.runOnUIThread(() -> {
                        if (error2 == null) {
                            currentPassword = (TLRPC.TL_account_password) response2;
                            TwoStepVerificationActivity.initPasswordNewAlgo(currentPassword);
                            onPasswordDone(saved);
                        }
                    }), ConnectionsManager.RequestFlagWithoutLogin);
                    return;
                }
                if (error == null) {
                    Utilities.globalQueue.postRunnable(() -> {
                        TLRPC.TL_account_passwordSettings settings = (TLRPC.TL_account_passwordSettings) response;
                        byte[] secure_salt;
                        if (settings.secure_settings != null) {
                            secureSecret = settings.secure_settings.secure_secret;
                            secureSecretId = settings.secure_settings.secure_secret_id;
                            if (settings.secure_settings.secure_algo instanceof TLRPC.TL_securePasswordKdfAlgoSHA512) {
                                TLRPC.TL_securePasswordKdfAlgoSHA512 algo = (TLRPC.TL_securePasswordKdfAlgoSHA512) settings.secure_settings.secure_algo;
                                secure_salt = algo.salt;
                                saltedPassword = Utilities.computeSHA512(secure_salt, AndroidUtilities.getStringBytes(textPassword), secure_salt);
                            } else if (settings.secure_settings.secure_algo instanceof TLRPC.TL_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000) {
                                TLRPC.TL_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000 algo = (TLRPC.TL_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000) settings.secure_settings.secure_algo;
                                secure_salt = algo.salt;
                                saltedPassword = Utilities.computePBKDF2(AndroidUtilities.getStringBytes(textPassword), algo.salt);
                            } else if (settings.secure_settings.secure_algo instanceof TLRPC.TL_securePasswordKdfAlgoUnknown) {
                                AndroidUtilities.runOnUIThread(() -> AlertsCreator.showUpdateAppAlert(getParentActivity(), LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert), true));
                                return;
                            } else {
                                secure_salt = new byte[0];
                            }
                        } else {
                            if (currentPassword.new_secure_algo instanceof TLRPC.TL_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000) {
                                TLRPC.TL_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000 algo = (TLRPC.TL_securePasswordKdfAlgoPBKDF2HMACSHA512iter100000) currentPassword.new_secure_algo;
                                secure_salt = algo.salt;
                                saltedPassword = Utilities.computePBKDF2(AndroidUtilities.getStringBytes(textPassword), algo.salt);
                            } else {
                                secure_salt = new byte[0];
                            }
                            secureSecret = null;
                            secureSecretId = 0;
                        }
                        AndroidUtilities.runOnUIThread(() -> {
                            currentEmail = settings.email;
                            if (saved) {
                                saltedPassword = savedSaltedPassword;
                            }
                            if (!checkSecret(decryptSecret(secureSecret, saltedPassword), secureSecretId) || secure_salt.length == 0 || secureSecretId == 0) {
                                if (saved) {
                                    UserConfig.getInstance(currentAccount).resetSavedPassword();
                                    usingSavedPassword = 0;
                                    updatePasswordInterface();
                                } else {
                                    if (currentForm != null) {
                                        currentForm.values.clear();
                                        currentForm.errors.clear();
                                    }
                                    if (secureSecret == null || secureSecret.length == 0) {
                                        generateNewSecret();
                                    } else {
                                        resetSecret();
                                    }
                                }
                            } else if (currentBotId == 0) {
                                TLRPC.TL_account_getAllSecureValues req12 = new TLRPC.TL_account_getAllSecureValues();
                                ConnectionsManager.getInstance(currentAccount).sendRequest(req12, (response1, error1) -> AndroidUtilities.runOnUIThread(() -> {
                                    if (response1 != null) {
                                        currentForm = new TLRPC.TL_account_authorizationForm();
                                        TLRPC.Vector vector = (TLRPC.Vector) response1;
                                        for (int a = 0, size = vector.objects.size(); a < size; a++) {
                                            currentForm.values.add((TLRPC.TL_secureValue) vector.objects.get(a));
                                        }
                                        openRequestInterface();
                                    } else {
                                        if ("APP_VERSION_OUTDATED".equals(error1.text)) {
                                            AlertsCreator.showUpdateAppAlert(getParentActivity(), LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert), true);
                                        } else {
                                            showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error1.text);
                                        }
                                        showEditDoneProgress(true, false);
                                    }
                                }));
                            } else {
                                openRequestInterface();
                            }
                        });
                    });
                } else {
                    AndroidUtilities.runOnUIThread(() -> {
                        if (saved) {
                            UserConfig.getInstance(currentAccount).resetSavedPassword();
                            usingSavedPassword = 0;
                            updatePasswordInterface();
                            if (inputFieldContainers != null && inputFieldContainers[FIELD_PASSWORD].getVisibility() == View.VISIBLE) {
                                inputFields[FIELD_PASSWORD].requestFocus();
                                AndroidUtilities.showKeyboard(inputFields[FIELD_PASSWORD]);
                            }
                        } else {
                            showEditDoneProgress(true, false);
                            if (error.text.equals("PASSWORD_HASH_INVALID")) {
                                onPasscodeError(true);
                            } else if (error.text.startsWith("FLOOD_WAIT")) {
                                int time = Utilities.parseInt(error.text);
                                String timeString;
                                if (time < 60) {
                                    timeString = LocaleController.formatPluralString("Seconds", time);
                                } else {
                                    timeString = LocaleController.formatPluralString("Minutes", time / 60);
                                }
                                showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString));
                            } else {
                                showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text);
                            }
                        }
                    });
                }
            }
        };
        if (currentPassword.current_algo instanceof TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) {
            TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow algo = (TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) currentPassword.current_algo;
            req.password = SRPHelper.startCheck(x_bytes, currentPassword.srp_id, currentPassword.srp_B, algo);
            if (req.password == null) {
                TLRPC.TL_error error = new TLRPC.TL_error();
                error.text = "ALGO_INVALID";
                requestDelegate.run(null, error);
                return;
            }
            int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
            ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
        } else {
            TLRPC.TL_error error = new TLRPC.TL_error();
            error.text = "PASSWORD_HASH_INVALID";
            requestDelegate.run(null, error);
        }
    });
}
Also used : RandomAccessFile(java.io.RandomAccessFile) Arrays(java.util.Arrays) Bundle(android.os.Bundle) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) Manifest(android.Manifest) RSAPublicKey(java.security.interfaces.RSAPublicKey) MediaStore(android.provider.MediaStore) Canvas(android.graphics.Canvas) TimerTask(java.util.TimerTask) ForegroundColorSpan(android.text.style.ForegroundColorSpan) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NotificationCenter(org.telegram.messenger.NotificationCenter) TextPaint(android.text.TextPaint) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) InputFilter(android.text.InputFilter) RadialProgress(org.telegram.ui.Components.RadialProgress) TextWatcher(android.text.TextWatcher) FileLoader(org.telegram.messenger.FileLoader) SlideView(org.telegram.ui.Components.SlideView) RequestDelegate(org.telegram.tgnet.RequestDelegate) Dialog(android.app.Dialog) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) AlertsCreator(org.telegram.ui.Components.AlertsCreator) Editable(android.text.Editable) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) Calendar(java.util.Calendar) TextDetailSettingsCell(org.telegram.ui.Cells.TextDetailSettingsCell) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) Menu(android.view.Menu) BuildConfig(org.telegram.messenger.BuildConfig) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) HintEditText(org.telegram.ui.Components.HintEditText) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) InputStreamReader(java.io.InputStreamReader) File(java.io.File) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ScrollView(android.widget.ScrollView) BufferedReader(java.io.BufferedReader) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) Rect(android.graphics.Rect) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) PackageManager(android.content.pm.PackageManager) Spannable(android.text.Spannable) AndroidUtilities(org.telegram.messenger.AndroidUtilities) ClickableSpan(android.text.style.ClickableSpan) Timer(java.util.Timer) Animator(android.animation.Animator) AccelerateDecelerateInterpolator(android.view.animation.AccelerateDecelerateInterpolator) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) MrzRecognizer(org.telegram.messenger.MrzRecognizer) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) JSONObject(org.json.JSONObject) ApplicationLoader(org.telegram.messenger.ApplicationLoader) Locale(java.util.Locale) MediaController(org.telegram.messenger.MediaController) View(android.view.View) ImageLoader(org.telegram.messenger.ImageLoader) ContextProgressView(org.telegram.ui.Components.ContextProgressView) Utilities(org.telegram.messenger.Utilities) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) ObjectAnimator(android.animation.ObjectAnimator) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) PorterDuff(android.graphics.PorterDuff) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) KeyFactory(java.security.KeyFactory) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) FileProvider(androidx.core.content.FileProvider) EditorInfo(android.view.inputmethod.EditorInfo) Typeface(android.graphics.Typeface) Context(android.content.Context) StaticLayout(android.text.StaticLayout) Spanned(android.text.Spanned) KeyEvent(android.view.KeyEvent) Theme(org.telegram.ui.ActionBar.Theme) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) PackageInfo(android.content.pm.PackageInfo) Cipher(javax.crypto.Cipher) MenuItem(android.view.MenuItem) SuppressLint(android.annotation.SuppressLint) PhoneNumberUtils(android.telephony.PhoneNumberUtils) MotionEvent(android.view.MotionEvent) SRPHelper(org.telegram.messenger.SRPHelper) SecureDocument(org.telegram.messenger.SecureDocument) TelephonyManager(android.telephony.TelephonyManager) ActionBar(org.telegram.ui.ActionBar.ActionBar) TLObject(org.telegram.tgnet.TLObject) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) PasswordTransformationMethod(android.text.method.PasswordTransformationMethod) BuildVars(org.telegram.messenger.BuildVars) Build(android.os.Build) DownloadController(org.telegram.messenger.DownloadController) DialogInterface(android.content.DialogInterface) Browser(org.telegram.messenger.browser.Browser) Iterator(java.util.Iterator) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) SecureDocumentKey(org.telegram.messenger.SecureDocumentKey) ChatAttachAlert(org.telegram.ui.Components.ChatAttachAlert) Bitmap(android.graphics.Bitmap) Base64(android.util.Base64) Vibrator(android.os.Vibrator) Comparator(java.util.Comparator) Activity(android.app.Activity) Collections(java.util.Collections) JSONArray(org.json.JSONArray) TLRPC(org.telegram.tgnet.TLRPC) RequestDelegate(org.telegram.tgnet.RequestDelegate) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) TLObject(org.telegram.tgnet.TLObject)

Example 3 with RequestDelegate

use of org.telegram.tgnet.RequestDelegate in project Telegram-FOSS by Telegram-FOSS-Team.

the class PaymentFormActivity method sendSavePassword.

private void sendSavePassword(final boolean clear) {
    if (!clear && codeFieldCell.getVisibility() == View.VISIBLE) {
        String code = codeFieldCell.getText();
        if (code.length() == 0) {
            shakeView(codeFieldCell);
            return;
        }
        showEditDoneProgress(true, true);
        TLRPC.TL_account_confirmPasswordEmail req = new TLRPC.TL_account_confirmPasswordEmail();
        req.code = code;
        ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
            showEditDoneProgress(true, false);
            if (error == null) {
                if (getParentActivity() == null) {
                    return;
                }
                if (shortPollRunnable != null) {
                    AndroidUtilities.cancelRunOnUIThread(shortPollRunnable);
                    shortPollRunnable = null;
                }
                goToNextStep();
            } else {
                if (error.text.startsWith("CODE_INVALID")) {
                    shakeView(codeFieldCell);
                    codeFieldCell.setText("", false);
                } else if (error.text.startsWith("FLOOD_WAIT")) {
                    int time = Utilities.parseInt(error.text);
                    String timeString;
                    if (time < 60) {
                        timeString = LocaleController.formatPluralString("Seconds", time);
                    } else {
                        timeString = LocaleController.formatPluralString("Minutes", time / 60);
                    }
                    showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString));
                } else {
                    showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text);
                }
            }
        }), ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
    } else {
        final TLRPC.TL_account_updatePasswordSettings req = new TLRPC.TL_account_updatePasswordSettings();
        final String email;
        final String firstPassword;
        if (clear) {
            doneItem.setVisibility(View.VISIBLE);
            email = null;
            firstPassword = null;
            req.new_settings = new TLRPC.TL_account_passwordInputSettings();
            req.new_settings.flags = 2;
            req.new_settings.email = "";
            req.password = new TLRPC.TL_inputCheckPasswordEmpty();
        } else {
            firstPassword = inputFields[FIELD_ENTERPASSWORD].getText().toString();
            if (TextUtils.isEmpty(firstPassword)) {
                shakeField(FIELD_ENTERPASSWORD);
                return;
            }
            String secondPassword = inputFields[FIELD_REENTERPASSWORD].getText().toString();
            if (!firstPassword.equals(secondPassword)) {
                try {
                    Toast.makeText(getParentActivity(), LocaleController.getString("PasswordDoNotMatch", R.string.PasswordDoNotMatch), Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    FileLog.e(e);
                }
                shakeField(FIELD_REENTERPASSWORD);
                return;
            }
            email = inputFields[FIELD_ENTERPASSWORDEMAIL].getText().toString();
            if (email.length() < 3) {
                shakeField(FIELD_ENTERPASSWORDEMAIL);
                return;
            }
            int dot = email.lastIndexOf('.');
            int dog = email.lastIndexOf('@');
            if (dog < 0 || dot < dog) {
                shakeField(FIELD_ENTERPASSWORDEMAIL);
                return;
            }
            req.password = new TLRPC.TL_inputCheckPasswordEmpty();
            req.new_settings = new TLRPC.TL_account_passwordInputSettings();
            req.new_settings.flags |= 1;
            req.new_settings.hint = "";
            req.new_settings.new_algo = currentPassword.new_algo;
            req.new_settings.flags |= 2;
            req.new_settings.email = email.trim();
        }
        showEditDoneProgress(true, true);
        Utilities.globalQueue.postRunnable(() -> {
            RequestDelegate requestDelegate = (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                if (error != null && "SRP_ID_INVALID".equals(error.text)) {
                    TLRPC.TL_account_getPassword getPasswordReq = new TLRPC.TL_account_getPassword();
                    ConnectionsManager.getInstance(currentAccount).sendRequest(getPasswordReq, (response2, error2) -> AndroidUtilities.runOnUIThread(() -> {
                        if (error2 == null) {
                            currentPassword = (TLRPC.TL_account_password) response2;
                            TwoStepVerificationActivity.initPasswordNewAlgo(currentPassword);
                            sendSavePassword(clear);
                        }
                    }), ConnectionsManager.RequestFlagWithoutLogin);
                    return;
                }
                showEditDoneProgress(true, false);
                if (clear) {
                    currentPassword.has_password = false;
                    currentPassword.current_algo = null;
                    delegate.currentPasswordUpdated(currentPassword);
                    finishFragment();
                } else {
                    if (error == null && response instanceof TLRPC.TL_boolTrue) {
                        if (getParentActivity() == null) {
                            return;
                        }
                        goToNextStep();
                    } else if (error != null) {
                        if (error.text.equals("EMAIL_UNCONFIRMED") || error.text.startsWith("EMAIL_UNCONFIRMED_")) {
                            emailCodeLength = Utilities.parseInt(error.text);
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> {
                                waitingForEmail = true;
                                currentPassword.email_unconfirmed_pattern = email;
                                updatePasswordFields();
                            });
                            builder.setMessage(LocaleController.getString("YourEmailAlmostThereText", R.string.YourEmailAlmostThereText));
                            builder.setTitle(LocaleController.getString("YourEmailAlmostThere", R.string.YourEmailAlmostThere));
                            Dialog dialog = showDialog(builder.create());
                            if (dialog != null) {
                                dialog.setCanceledOnTouchOutside(false);
                                dialog.setCancelable(false);
                            }
                        } else {
                            if (error.text.equals("EMAIL_INVALID")) {
                                showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("PasswordEmailInvalid", R.string.PasswordEmailInvalid));
                            } else if (error.text.startsWith("FLOOD_WAIT")) {
                                int time = Utilities.parseInt(error.text);
                                String timeString;
                                if (time < 60) {
                                    timeString = LocaleController.formatPluralString("Seconds", time);
                                } else {
                                    timeString = LocaleController.formatPluralString("Minutes", time / 60);
                                }
                                showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString));
                            } else {
                                showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text);
                            }
                        }
                    }
                }
            });
            if (!clear) {
                byte[] newPasswordBytes = AndroidUtilities.getStringBytes(firstPassword);
                if (currentPassword.new_algo instanceof TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) {
                    TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow algo = (TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) currentPassword.new_algo;
                    req.new_settings.new_password_hash = SRPHelper.getVBytes(newPasswordBytes, algo);
                    if (req.new_settings.new_password_hash == null) {
                        TLRPC.TL_error error = new TLRPC.TL_error();
                        error.text = "ALGO_INVALID";
                        requestDelegate.run(null, error);
                    }
                    ConnectionsManager.getInstance(currentAccount).sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
                } else {
                    TLRPC.TL_error error = new TLRPC.TL_error();
                    error.text = "PASSWORD_HASH_INVALID";
                    requestDelegate.run(null, error);
                }
            } else {
                ConnectionsManager.getInstance(currentAccount).sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
            }
        });
    }
}
Also used : JavascriptInterface(android.webkit.JavascriptInterface) TokenParser(com.stripe.android.net.TokenParser) HttpURLConnection(java.net.HttpURLConnection) Arrays(java.util.Arrays) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) PaymentInfoCell(org.telegram.ui.Cells.PaymentInfoCell) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) HorizontalScrollView(android.widget.HorizontalScrollView) Manifest(android.Manifest) Card(com.stripe.android.model.Card) JSONException(org.json.JSONException) CookieManager(android.webkit.CookieManager) Canvas(android.graphics.Canvas) APIException(com.stripe.android.exception.APIException) UndoView(org.telegram.ui.Components.UndoView) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) NotificationCenter(org.telegram.messenger.NotificationCenter) TextPaint(android.text.TextPaint) TextPriceCell(org.telegram.ui.Cells.TextPriceCell) Token(com.stripe.android.model.Token) RadioCell(org.telegram.ui.Cells.RadioCell) InputFilter(android.text.InputFilter) TextWatcher(android.text.TextWatcher) ViewParent(android.view.ViewParent) RequestDelegate(org.telegram.tgnet.RequestDelegate) Dialog(android.app.Dialog) AlertsCreator(org.telegram.ui.Components.AlertsCreator) Editable(android.text.Editable) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) Calendar(java.util.Calendar) WebSettings(android.webkit.WebSettings) TextDetailSettingsCell(org.telegram.ui.Cells.TextDetailSettingsCell) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) EditTextSettingsCell(org.telegram.ui.Cells.EditTextSettingsCell) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) HintEditText(org.telegram.ui.Components.HintEditText) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) TextUtils(android.text.TextUtils) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ScrollView(android.widget.ScrollView) ContactsController(org.telegram.messenger.ContactsController) Stripe(com.stripe.android.Stripe) BufferedReader(java.io.BufferedReader) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) EditText(android.widget.EditText) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) PackageManager(android.content.pm.PackageManager) URL(java.net.URL) WindowManager(android.view.WindowManager) AndroidUtilities(org.telegram.messenger.AndroidUtilities) Scanner(java.util.Scanner) ClickableSpan(android.text.style.ClickableSpan) Animator(android.animation.Animator) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) JSONObject(org.json.JSONObject) ApplicationLoader(org.telegram.messenger.ApplicationLoader) Locale(java.util.Locale) WebViewClient(android.webkit.WebViewClient) View(android.view.View) WebView(android.webkit.WebView) ContextProgressView(org.telegram.ui.Components.ContextProgressView) Utilities(org.telegram.messenger.Utilities) StripeApiHandler(com.stripe.android.net.StripeApiHandler) AsyncTask(android.os.AsyncTask) APIConnectionException(com.stripe.android.exception.APIConnectionException) ObjectAnimator(android.animation.ObjectAnimator) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) UserConfig(org.telegram.messenger.UserConfig) List(java.util.List) TextView(android.widget.TextView) Optional(java.util.Optional) EditorInfo(android.view.inputmethod.EditorInfo) Typeface(android.graphics.Typeface) Context(android.content.Context) Spanned(android.text.Spanned) Theme(org.telegram.ui.ActionBar.Theme) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) SRPHelper(org.telegram.messenger.SRPHelper) TelephonyManager(android.telephony.TelephonyManager) ActionBar(org.telegram.ui.ActionBar.ActionBar) TLObject(org.telegram.tgnet.TLObject) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) PasswordTransformationMethod(android.text.method.PasswordTransformationMethod) BuildVars(org.telegram.messenger.BuildVars) Build(android.os.Build) DialogInterface(android.content.DialogInterface) OutputStream(java.io.OutputStream) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) MessagesController(org.telegram.messenger.MessagesController) TokenCallback(com.stripe.android.TokenCallback) TextCheckCell(org.telegram.ui.Cells.TextCheckCell) Vibrator(android.os.Vibrator) Activity(android.app.Activity) Collections(java.util.Collections) JSONArray(org.json.JSONArray) InputStream(java.io.InputStream) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) SpannableStringBuilder(android.text.SpannableStringBuilder) TLRPC(org.telegram.tgnet.TLRPC) Dialog(android.app.Dialog) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) RequestDelegate(org.telegram.tgnet.RequestDelegate) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) JSONException(org.json.JSONException) APIException(com.stripe.android.exception.APIException) IOException(java.io.IOException) APIConnectionException(com.stripe.android.exception.APIConnectionException)

Example 4 with RequestDelegate

use of org.telegram.tgnet.RequestDelegate in project Telegram-FOSS by Telegram-FOSS-Team.

the class PaymentFormActivity method checkPassword.

private void checkPassword() {
    if (UserConfig.getInstance(currentAccount).tmpPassword != null) {
        if (UserConfig.getInstance(currentAccount).tmpPassword.valid_until < ConnectionsManager.getInstance(currentAccount).getCurrentTime() + 60) {
            UserConfig.getInstance(currentAccount).tmpPassword = null;
            UserConfig.getInstance(currentAccount).saveConfig(false);
        }
    }
    if (UserConfig.getInstance(currentAccount).tmpPassword != null) {
        sendData();
        return;
    }
    if (inputFields[FIELD_SAVEDPASSWORD].length() == 0) {
        Vibrator v = (Vibrator) ApplicationLoader.applicationContext.getSystemService(Context.VIBRATOR_SERVICE);
        if (v != null) {
            v.vibrate(200);
        }
        AndroidUtilities.shakeView(inputFields[FIELD_SAVEDPASSWORD], 2, 0);
        return;
    }
    final String password = inputFields[FIELD_SAVEDPASSWORD].getText().toString();
    showEditDoneProgress(true, true);
    setDonePressed(true);
    final TLRPC.TL_account_getPassword req = new TLRPC.TL_account_getPassword();
    ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
        if (error == null) {
            TLRPC.TL_account_password currentPassword = (TLRPC.TL_account_password) response;
            if (!TwoStepVerificationActivity.canHandleCurrentPassword(currentPassword, false)) {
                AlertsCreator.showUpdateAppAlert(getParentActivity(), LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert), true);
                return;
            }
            if (!currentPassword.has_password) {
                passwordOk = false;
                goToNextStep();
            } else {
                byte[] passwordBytes = AndroidUtilities.getStringBytes(password);
                Utilities.globalQueue.postRunnable(() -> {
                    final byte[] x_bytes;
                    if (currentPassword.current_algo instanceof TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) {
                        TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow algo = (TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) currentPassword.current_algo;
                        x_bytes = SRPHelper.getX(passwordBytes, algo);
                    } else {
                        x_bytes = null;
                    }
                    final TLRPC.TL_account_getTmpPassword req1 = new TLRPC.TL_account_getTmpPassword();
                    req1.period = 60 * 30;
                    RequestDelegate requestDelegate = (response1, error1) -> AndroidUtilities.runOnUIThread(() -> {
                        showEditDoneProgress(true, false);
                        setDonePressed(false);
                        if (response1 != null) {
                            passwordOk = true;
                            UserConfig.getInstance(currentAccount).tmpPassword = (TLRPC.TL_account_tmpPassword) response1;
                            UserConfig.getInstance(currentAccount).saveConfig(false);
                            goToNextStep();
                        } else {
                            if (error1.text.equals("PASSWORD_HASH_INVALID")) {
                                Vibrator v = (Vibrator) ApplicationLoader.applicationContext.getSystemService(Context.VIBRATOR_SERVICE);
                                if (v != null) {
                                    v.vibrate(200);
                                }
                                AndroidUtilities.shakeView(inputFields[FIELD_SAVEDPASSWORD], 2, 0);
                                inputFields[FIELD_SAVEDPASSWORD].setText("");
                            } else {
                                AlertsCreator.processError(currentAccount, error1, PaymentFormActivity.this, req1);
                            }
                        }
                    });
                    if (currentPassword.current_algo instanceof TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) {
                        TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow algo = (TLRPC.TL_passwordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow) currentPassword.current_algo;
                        req1.password = SRPHelper.startCheck(x_bytes, currentPassword.srp_id, currentPassword.srp_B, algo);
                        if (req1.password == null) {
                            TLRPC.TL_error error2 = new TLRPC.TL_error();
                            error2.text = "ALGO_INVALID";
                            requestDelegate.run(null, error2);
                            return;
                        }
                        ConnectionsManager.getInstance(currentAccount).sendRequest(req1, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
                    } else {
                        TLRPC.TL_error error2 = new TLRPC.TL_error();
                        error2.text = "PASSWORD_HASH_INVALID";
                        requestDelegate.run(null, error2);
                    }
                });
            }
        } else {
            AlertsCreator.processError(currentAccount, error, PaymentFormActivity.this, req);
            showEditDoneProgress(true, false);
            setDonePressed(false);
        }
    }), ConnectionsManager.RequestFlagFailOnServerErrors);
}
Also used : RequestDelegate(org.telegram.tgnet.RequestDelegate) TLRPC(org.telegram.tgnet.TLRPC) Vibrator(android.os.Vibrator)

Example 5 with RequestDelegate

use of org.telegram.tgnet.RequestDelegate in project Telegram-FOSS by Telegram-FOSS-Team.

the class SearchAdapterHelper method queryServerSearch.

public void queryServerSearch(String query, boolean allowUsername, boolean allowChats, boolean allowBots, boolean allowSelf, boolean canAddGroupsOnly, long channelId, boolean phoneNumbers, int type, int searchId, Runnable onEnd) {
    for (int reqId : pendingRequestIds) {
        ConnectionsManager.getInstance(currentAccount).cancelRequest(reqId, true);
    }
    pendingRequestIds.clear();
    if (query == null) {
        groupSearch.clear();
        groupSearchMap.clear();
        globalSearch.clear();
        globalSearchMap.clear();
        localServerSearch.clear();
        phonesSearch.clear();
        phoneSearchMap.clear();
        delegate.onDataSetChanged(searchId);
        return;
    }
    boolean hasChanged = false;
    ArrayList<Pair<TLObject, RequestDelegate>> requests = new ArrayList<>();
    if (query.length() > 0) {
        if (channelId != 0) {
            TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants();
            if (type == ChatUsersActivity.TYPE_ADMIN) {
                req.filter = new TLRPC.TL_channelParticipantsAdmins();
            } else if (type == ChatUsersActivity.TYPE_KICKED) {
                req.filter = new TLRPC.TL_channelParticipantsBanned();
            } else if (type == ChatUsersActivity.TYPE_BANNED) {
                req.filter = new TLRPC.TL_channelParticipantsKicked();
            } else {
                req.filter = new TLRPC.TL_channelParticipantsSearch();
            }
            req.filter.q = query;
            req.limit = 50;
            req.offset = 0;
            req.channel = MessagesController.getInstance(currentAccount).getInputChannel(channelId);
            requests.add(new Pair<>(req, (response, error) -> {
                if (error == null) {
                    TLRPC.TL_channels_channelParticipants res = (TLRPC.TL_channels_channelParticipants) response;
                    lastFoundChannel = query.toLowerCase();
                    MessagesController.getInstance(currentAccount).putUsers(res.users, false);
                    MessagesController.getInstance(currentAccount).putChats(res.chats, false);
                    groupSearch.clear();
                    groupSearchMap.clear();
                    groupSearch.addAll(res.participants);
                    long currentUserId = UserConfig.getInstance(currentAccount).getClientUserId();
                    for (int a = 0, N = res.participants.size(); a < N; a++) {
                        TLRPC.ChannelParticipant participant = res.participants.get(a);
                        long peerId = MessageObject.getPeerId(participant.peer);
                        if (!allowSelf && peerId == currentUserId) {
                            groupSearch.remove(participant);
                            continue;
                        }
                        groupSearchMap.put(peerId, participant);
                    }
                }
            }));
        } else {
            lastFoundChannel = query.toLowerCase();
        }
    } else {
        groupSearch.clear();
        groupSearchMap.clear();
        hasChanged = true;
    }
    if (allowUsername) {
        if (query.length() > 0) {
            TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search();
            req.q = query;
            req.limit = 20;
            requests.add(new Pair<>(req, (response, error) -> {
                if (delegate.canApplySearchResults(searchId)) {
                    if (error == null) {
                        TLRPC.TL_contacts_found res = (TLRPC.TL_contacts_found) response;
                        globalSearch.clear();
                        globalSearchMap.clear();
                        localServerSearch.clear();
                        MessagesController.getInstance(currentAccount).putChats(res.chats, false);
                        MessagesController.getInstance(currentAccount).putUsers(res.users, false);
                        MessagesStorage.getInstance(currentAccount).putUsersAndChats(res.users, res.chats, true, true);
                        LongSparseArray<TLRPC.Chat> chatsMap = new LongSparseArray<>();
                        LongSparseArray<TLRPC.User> usersMap = new LongSparseArray<>();
                        for (int a = 0; a < res.chats.size(); a++) {
                            TLRPC.Chat chat = res.chats.get(a);
                            chatsMap.put(chat.id, chat);
                        }
                        for (int a = 0; a < res.users.size(); a++) {
                            TLRPC.User user = res.users.get(a);
                            usersMap.put(user.id, user);
                        }
                        for (int b = 0; b < 2; b++) {
                            ArrayList<TLRPC.Peer> arrayList;
                            if (b == 0) {
                                if (!allResultsAreGlobal) {
                                    continue;
                                }
                                arrayList = res.my_results;
                            } else {
                                arrayList = res.results;
                            }
                            for (int a = 0; a < arrayList.size(); a++) {
                                TLRPC.Peer peer = arrayList.get(a);
                                TLRPC.User user = null;
                                TLRPC.Chat chat = null;
                                if (peer.user_id != 0) {
                                    user = usersMap.get(peer.user_id);
                                } else if (peer.chat_id != 0) {
                                    chat = chatsMap.get(peer.chat_id);
                                } else if (peer.channel_id != 0) {
                                    chat = chatsMap.get(peer.channel_id);
                                }
                                if (chat != null) {
                                    if (!allowChats || canAddGroupsOnly && !ChatObject.canAddBotsToChat(chat) || !allowGlobalResults && ChatObject.isNotInChat(chat)) {
                                        continue;
                                    }
                                    globalSearch.add(chat);
                                    globalSearchMap.put(-chat.id, chat);
                                } else if (user != null) {
                                    if (canAddGroupsOnly || !allowBots && user.bot || !allowSelf && user.self || !allowGlobalResults && b == 1 && !user.contact) {
                                        continue;
                                    }
                                    globalSearch.add(user);
                                    globalSearchMap.put(user.id, user);
                                }
                            }
                        }
                        if (!allResultsAreGlobal) {
                            for (int a = 0; a < res.my_results.size(); a++) {
                                TLRPC.Peer peer = res.my_results.get(a);
                                TLRPC.User user = null;
                                TLRPC.Chat chat = null;
                                if (peer.user_id != 0) {
                                    user = usersMap.get(peer.user_id);
                                } else if (peer.chat_id != 0) {
                                    chat = chatsMap.get(peer.chat_id);
                                } else if (peer.channel_id != 0) {
                                    chat = chatsMap.get(peer.channel_id);
                                }
                                if (chat != null) {
                                    if (!allowChats || canAddGroupsOnly && !ChatObject.canAddBotsToChat(chat)) {
                                        continue;
                                    }
                                    localServerSearch.add(chat);
                                    globalSearchMap.put(-chat.id, chat);
                                } else if (user != null) {
                                    if (canAddGroupsOnly || !allowBots && user.bot || !allowSelf && user.self) {
                                        continue;
                                    }
                                    localServerSearch.add(user);
                                    globalSearchMap.put(user.id, user);
                                }
                            }
                        }
                        lastFoundUsername = query.toLowerCase();
                    }
                }
            }));
        } else {
            globalSearch.clear();
            globalSearchMap.clear();
            localServerSearch.clear();
            hasChanged = false;
        }
    }
    if (!canAddGroupsOnly && phoneNumbers && query.startsWith("+") && query.length() > 3) {
        phonesSearch.clear();
        phoneSearchMap.clear();
        String phone = PhoneFormat.stripExceptNumbers(query);
        ArrayList<TLRPC.TL_contact> arrayList = ContactsController.getInstance(currentAccount).contacts;
        boolean hasFullMatch = false;
        for (int a = 0, N = arrayList.size(); a < N; a++) {
            TLRPC.TL_contact contact = arrayList.get(a);
            TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(contact.user_id);
            if (user == null) {
                continue;
            }
            if (user.phone != null && user.phone.startsWith(phone)) {
                if (!hasFullMatch) {
                    hasFullMatch = user.phone.length() == phone.length();
                }
                phonesSearch.add(user);
                phoneSearchMap.put(user.id, user);
            }
        }
        if (!hasFullMatch) {
            phonesSearch.add("section");
            phonesSearch.add(phone);
        }
        hasChanged = false;
    }
    if (hasChanged) {
        delegate.onDataSetChanged(searchId);
    }
    final AtomicInteger gotResponses = new AtomicInteger(0);
    final ArrayList<Pair<TLObject, TLRPC.TL_error>> responses = new ArrayList<>();
    for (int i = 0; i < requests.size(); ++i) {
        final int index = i;
        Pair<TLObject, RequestDelegate> r = requests.get(i);
        TLObject req = r.first;
        responses.add(null);
        AtomicInteger reqId = new AtomicInteger();
        reqId.set(ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
            responses.set(index, new Pair<>(response, error));
            Integer reqIdValue = reqId.get();
            if (!pendingRequestIds.contains(reqIdValue)) {
                return;
            }
            pendingRequestIds.remove(reqIdValue);
            if (gotResponses.incrementAndGet() == requests.size()) {
                for (int j = 0; j < requests.size(); ++j) {
                    RequestDelegate callback = requests.get(j).second;
                    Pair<TLObject, TLRPC.TL_error> res = responses.get(j);
                    if (res == null)
                        continue;
                    callback.run(res.first, res.second);
                }
                removeGroupSearchFromGlobal();
                if (localSearchResults != null) {
                    mergeResults(localSearchResults);
                }
                mergeExcludeResults();
                delegate.onDataSetChanged(searchId);
                if (onEnd != null) {
                    onEnd.run();
                }
            }
        })));
        pendingRequestIds.add(reqId.get());
    }
}
Also used : Array(java.lang.reflect.Array) RequestDelegate(org.telegram.tgnet.RequestDelegate) Pair(android.util.Pair) AndroidUtilities(org.telegram.messenger.AndroidUtilities) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Matcher(java.util.regex.Matcher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TLRPC(org.telegram.tgnet.TLRPC) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) LongSparseArray(androidx.collection.LongSparseArray) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement) FileLog(org.telegram.messenger.FileLog) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ShareAlert(org.telegram.ui.Components.ShareAlert) MessagesController(org.telegram.messenger.MessagesController) UserConfig(org.telegram.messenger.UserConfig) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) Pattern(java.util.regex.Pattern) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) ChatObject(org.telegram.messenger.ChatObject) Collections(java.util.Collections) ChatUsersActivity(org.telegram.ui.ChatUsersActivity) LongSparseArray(androidx.collection.LongSparseArray) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) Pair(android.util.Pair) RequestDelegate(org.telegram.tgnet.RequestDelegate) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TLObject(org.telegram.tgnet.TLObject)

Aggregations

RequestDelegate (org.telegram.tgnet.RequestDelegate)12 TLRPC (org.telegram.tgnet.TLRPC)12 ArrayList (java.util.ArrayList)10 ConnectionsManager (org.telegram.tgnet.ConnectionsManager)10 Context (android.content.Context)9 TextUtils (android.text.TextUtils)9 TLObject (org.telegram.tgnet.TLObject)9 AlertDialog (org.telegram.ui.ActionBar.AlertDialog)9 Theme (org.telegram.ui.ActionBar.Theme)9 TypedValue (android.util.TypedValue)8 TextView (android.widget.TextView)8 BaseFragment (org.telegram.ui.ActionBar.BaseFragment)8 AlertsCreator (org.telegram.ui.Components.AlertsCreator)8 Build (android.os.Build)7 Vibrator (android.os.Vibrator)7 Gravity (android.view.Gravity)7 LinearLayout (android.widget.LinearLayout)7 HashMap (java.util.HashMap)7 DialogInterface (android.content.DialogInterface)6 AndroidUtilities (org.telegram.messenger.AndroidUtilities)6