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);
}
}
}
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);
}
});
}
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);
}
});
}
}
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);
}
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());
}
}
Aggregations