Search in sources :

Example 6 with RequestDelegate

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

the class MentionsAdapter method searchForContextBotResults.

private void searchForContextBotResults(final boolean cache, final TLRPC.User user, final String query, final String offset) {
    if (contextQueryReqid != 0) {
        ConnectionsManager.getInstance(currentAccount).cancelRequest(contextQueryReqid, true);
        contextQueryReqid = 0;
    }
    if (!inlineMediaEnabled) {
        if (delegate != null) {
            delegate.onContextSearch(false);
        }
        return;
    }
    if (query == null || user == null) {
        searchingContextQuery = null;
        return;
    }
    if (user.bot_inline_geo && lastKnownLocation == null) {
        return;
    }
    final String key = dialog_id + "_" + query + "_" + offset + "_" + dialog_id + "_" + user.id + "_" + (user.bot_inline_geo && lastKnownLocation.getLatitude() != -1000 ? lastKnownLocation.getLatitude() + lastKnownLocation.getLongitude() : "");
    final MessagesStorage messagesStorage = MessagesStorage.getInstance(currentAccount);
    RequestDelegate requestDelegate = (response, error) -> AndroidUtilities.runOnUIThread(() -> {
        if (!query.equals(searchingContextQuery)) {
            return;
        }
        contextQueryReqid = 0;
        if (cache && response == null) {
            searchForContextBotResults(false, user, query, offset);
        } else if (delegate != null) {
            delegate.onContextSearch(false);
        }
        if (response instanceof TLRPC.TL_messages_botResults) {
            TLRPC.TL_messages_botResults res = (TLRPC.TL_messages_botResults) response;
            if (!cache && res.cache_time != 0) {
                messagesStorage.saveBotCache(key, res);
            }
            nextQueryOffset = res.next_offset;
            if (searchResultBotContextSwitch == null) {
                searchResultBotContextSwitch = res.switch_pm;
            }
            for (int a = 0; a < res.results.size(); a++) {
                TLRPC.BotInlineResult result = res.results.get(a);
                if (!(result.document instanceof TLRPC.TL_document) && !(result.photo instanceof TLRPC.TL_photo) && !"game".equals(result.type) && result.content == null && result.send_message instanceof TLRPC.TL_botInlineMessageMediaAuto) {
                    res.results.remove(a);
                    a--;
                }
                result.query_id = res.query_id;
            }
            boolean added = false;
            if (searchResultBotContext == null || offset.length() == 0) {
                searchResultBotContext = res.results;
                contextMedia = res.gallery;
            } else {
                added = true;
                searchResultBotContext.addAll(res.results);
                if (res.results.isEmpty()) {
                    nextQueryOffset = "";
                }
            }
            if (cancelDelayRunnable != null) {
                AndroidUtilities.cancelRunOnUIThread(cancelDelayRunnable);
                cancelDelayRunnable = null;
            }
            searchResultHashtags = null;
            stickers = null;
            searchResultUsernames = null;
            searchResultUsernamesMap = null;
            searchResultCommands = null;
            searchResultSuggestions = null;
            searchResultCommandsHelp = null;
            searchResultCommandsUsers = null;
            if (added) {
                boolean hasTop = searchResultBotContextSwitch != null;
                notifyItemChanged(searchResultBotContext.size() - res.results.size() + (hasTop ? 1 : 0) - 1);
                notifyItemRangeInserted(searchResultBotContext.size() - res.results.size() + (hasTop ? 1 : 0), res.results.size());
            } else {
                notifyDataSetChanged();
            }
            delegate.needChangePanelVisibility(!searchResultBotContext.isEmpty() || searchResultBotContextSwitch != null);
        }
    });
    if (cache) {
        messagesStorage.getBotCache(key, requestDelegate);
    } else {
        TLRPC.TL_messages_getInlineBotResults req = new TLRPC.TL_messages_getInlineBotResults();
        req.bot = MessagesController.getInstance(currentAccount).getInputUser(user);
        req.query = query;
        req.offset = offset;
        if (user.bot_inline_geo && lastKnownLocation != null && lastKnownLocation.getLatitude() != -1000) {
            req.flags |= 1;
            req.geo_point = new TLRPC.TL_inputGeoPoint();
            req.geo_point.lat = AndroidUtilities.fixLocationCoord(lastKnownLocation.getLatitude());
            req.geo_point._long = AndroidUtilities.fixLocationCoord(lastKnownLocation.getLongitude());
        }
        if (DialogObject.isEncryptedDialog(dialog_id)) {
            req.peer = new TLRPC.TL_inputPeerEmpty();
        } else {
            req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialog_id);
        }
        contextQueryReqid = ConnectionsManager.getInstance(currentAccount).sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors);
    }
}
Also used : Arrays(java.util.Arrays) PackageManager(android.content.pm.PackageManager) AndroidUtilities(org.telegram.messenger.AndroidUtilities) Manifest(android.Manifest) View(android.view.View) Emoji(org.telegram.messenger.Emoji) RecyclerView(androidx.recyclerview.widget.RecyclerView) ImageLocation(org.telegram.messenger.ImageLocation) MentionCell(org.telegram.ui.Cells.MentionCell) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) NotificationCenter(org.telegram.messenger.NotificationCenter) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) BotSwitchCell(org.telegram.ui.Cells.BotSwitchCell) Location(android.location.Location) FileLoader(org.telegram.messenger.FileLoader) ChatActivity(org.telegram.ui.ChatActivity) Context(android.content.Context) Theme(org.telegram.ui.ActionBar.Theme) ContextLinkCell(org.telegram.ui.Cells.ContextLinkCell) RequestDelegate(org.telegram.tgnet.RequestDelegate) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) MediaDataController(org.telegram.messenger.MediaDataController) Build(android.os.Build) LongSparseArray(androidx.collection.LongSparseArray) DialogObject(org.telegram.messenger.DialogObject) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) File(java.io.File) MessagesController(org.telegram.messenger.MessagesController) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) StickerCell(org.telegram.ui.Cells.StickerCell) Comparator(java.util.Comparator) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Collections(java.util.Collections) EmojiView(org.telegram.ui.Components.EmojiView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) MessagesStorage(org.telegram.messenger.MessagesStorage) RequestDelegate(org.telegram.tgnet.RequestDelegate) TLRPC(org.telegram.tgnet.TLRPC)

Example 7 with RequestDelegate

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

the class PassportActivity method openTypeActivity.

private void openTypeActivity(TLRPC.TL_secureRequiredType requiredType, TLRPC.TL_secureRequiredType documentRequiredType, ArrayList<TLRPC.TL_secureRequiredType> availableDocumentTypes, boolean documentOnly) {
    int activityType = -1;
    final int availableDocumentTypesCount = availableDocumentTypes != null ? availableDocumentTypes.size() : 0;
    TLRPC.SecureValueType type = requiredType.type;
    TLRPC.SecureValueType documentType = documentRequiredType != null ? documentRequiredType.type : null;
    if (type instanceof TLRPC.TL_secureValueTypePersonalDetails) {
        activityType = TYPE_IDENTITY;
    } else if (type instanceof TLRPC.TL_secureValueTypeAddress) {
        activityType = TYPE_ADDRESS;
    } else if (type instanceof TLRPC.TL_secureValueTypePhone) {
        activityType = TYPE_PHONE;
    } else if (type instanceof TLRPC.TL_secureValueTypeEmail) {
        activityType = TYPE_EMAIL;
    }
    if (activityType != -1) {
        HashMap<String, String> errors = !documentOnly ? errorsMap.get(getNameForType(type)) : null;
        HashMap<String, String> documentsErrors = errorsMap.get(getNameForType(documentType));
        TLRPC.TL_secureValue value = getValueByType(requiredType, false);
        TLRPC.TL_secureValue documentsValue = getValueByType(documentRequiredType, false);
        final PassportActivity activity = new PassportActivity(activityType, currentForm, currentPassword, requiredType, value, documentRequiredType, documentsValue, typesValues.get(requiredType), documentRequiredType != null ? typesValues.get(documentRequiredType) : null);
        activity.delegate = new PassportActivityDelegate() {

            private TLRPC.InputSecureFile getInputSecureFile(SecureDocument document) {
                if (document.inputFile != null) {
                    TLRPC.TL_inputSecureFileUploaded inputSecureFileUploaded = new TLRPC.TL_inputSecureFileUploaded();
                    inputSecureFileUploaded.id = document.inputFile.id;
                    inputSecureFileUploaded.parts = document.inputFile.parts;
                    inputSecureFileUploaded.md5_checksum = document.inputFile.md5_checksum;
                    inputSecureFileUploaded.file_hash = document.fileHash;
                    inputSecureFileUploaded.secret = document.fileSecret;
                    return inputSecureFileUploaded;
                } else {
                    TLRPC.TL_inputSecureFile inputSecureFile = new TLRPC.TL_inputSecureFile();
                    inputSecureFile.id = document.secureFile.id;
                    inputSecureFile.access_hash = document.secureFile.access_hash;
                    return inputSecureFile;
                }
            }

            private void renameFile(SecureDocument oldDocument, TLRPC.TL_secureFile newSecureFile) {
                File oldFile = FileLoader.getPathToAttach(oldDocument);
                String oldKey = oldDocument.secureFile.dc_id + "_" + oldDocument.secureFile.id;
                File newFile = FileLoader.getPathToAttach(newSecureFile);
                String newKey = newSecureFile.dc_id + "_" + newSecureFile.id;
                oldFile.renameTo(newFile);
                ImageLoader.getInstance().replaceImageInCache(oldKey, newKey, null, false);
            }

            @Override
            public void saveValue(final TLRPC.TL_secureRequiredType requiredType, final String text, final String json, final TLRPC.TL_secureRequiredType documentRequiredType, final String documentsJson, final ArrayList<SecureDocument> documents, final SecureDocument selfie, final ArrayList<SecureDocument> translationDocuments, final SecureDocument front, final SecureDocument reverse, final Runnable finishRunnable, final ErrorRunnable errorRunnable) {
                TLRPC.TL_inputSecureValue inputSecureValue = null;
                if (!TextUtils.isEmpty(json)) {
                    inputSecureValue = new TLRPC.TL_inputSecureValue();
                    inputSecureValue.type = requiredType.type;
                    inputSecureValue.flags |= 1;
                    EncryptionResult result = encryptData(AndroidUtilities.getStringBytes(json));
                    inputSecureValue.data = new TLRPC.TL_secureData();
                    inputSecureValue.data.data = result.encryptedData;
                    inputSecureValue.data.data_hash = result.fileHash;
                    inputSecureValue.data.secret = result.fileSecret;
                } else if (!TextUtils.isEmpty(text)) {
                    TLRPC.SecurePlainData plainData;
                    if (type instanceof TLRPC.TL_secureValueTypeEmail) {
                        TLRPC.TL_securePlainEmail securePlainEmail = new TLRPC.TL_securePlainEmail();
                        securePlainEmail.email = text;
                        plainData = securePlainEmail;
                    } else if (type instanceof TLRPC.TL_secureValueTypePhone) {
                        TLRPC.TL_securePlainPhone securePlainPhone = new TLRPC.TL_securePlainPhone();
                        securePlainPhone.phone = text;
                        plainData = securePlainPhone;
                    } else {
                        return;
                    }
                    inputSecureValue = new TLRPC.TL_inputSecureValue();
                    inputSecureValue.type = requiredType.type;
                    inputSecureValue.flags |= 32;
                    inputSecureValue.plain_data = plainData;
                }
                if (!documentOnly && inputSecureValue == null) {
                    if (errorRunnable != null) {
                        errorRunnable.onError(null, null);
                    }
                    return;
                }
                TLRPC.TL_inputSecureValue fileInputSecureValue;
                if (documentRequiredType != null) {
                    fileInputSecureValue = new TLRPC.TL_inputSecureValue();
                    fileInputSecureValue.type = documentRequiredType.type;
                    if (!TextUtils.isEmpty(documentsJson)) {
                        fileInputSecureValue.flags |= 1;
                        EncryptionResult result = encryptData(AndroidUtilities.getStringBytes(documentsJson));
                        fileInputSecureValue.data = new TLRPC.TL_secureData();
                        fileInputSecureValue.data.data = result.encryptedData;
                        fileInputSecureValue.data.data_hash = result.fileHash;
                        fileInputSecureValue.data.secret = result.fileSecret;
                    }
                    if (front != null) {
                        fileInputSecureValue.front_side = getInputSecureFile(front);
                        fileInputSecureValue.flags |= 2;
                    }
                    if (reverse != null) {
                        fileInputSecureValue.reverse_side = getInputSecureFile(reverse);
                        fileInputSecureValue.flags |= 4;
                    }
                    if (selfie != null) {
                        fileInputSecureValue.selfie = getInputSecureFile(selfie);
                        fileInputSecureValue.flags |= 8;
                    }
                    if (translationDocuments != null && !translationDocuments.isEmpty()) {
                        fileInputSecureValue.flags |= 64;
                        for (int a = 0, size = translationDocuments.size(); a < size; a++) {
                            fileInputSecureValue.translation.add(getInputSecureFile(translationDocuments.get(a)));
                        }
                    }
                    if (documents != null && !documents.isEmpty()) {
                        fileInputSecureValue.flags |= 16;
                        for (int a = 0, size = documents.size(); a < size; a++) {
                            fileInputSecureValue.files.add(getInputSecureFile(documents.get(a)));
                        }
                    }
                    if (documentOnly) {
                        inputSecureValue = fileInputSecureValue;
                        fileInputSecureValue = null;
                    }
                } else {
                    fileInputSecureValue = null;
                }
                final PassportActivityDelegate currentDelegate = this;
                final TLRPC.TL_inputSecureValue finalFileInputSecureValue = fileInputSecureValue;
                final TLRPC.TL_account_saveSecureValue req = new TLRPC.TL_account_saveSecureValue();
                req.value = inputSecureValue;
                req.secure_secret_id = secureSecretId;
                ConnectionsManager.getInstance(currentAccount).sendRequest(req, new RequestDelegate() {

                    private void onResult(final TLRPC.TL_error error, final TLRPC.TL_secureValue newValue, final TLRPC.TL_secureValue newPendingValue) {
                        AndroidUtilities.runOnUIThread(() -> {
                            if (error != null) {
                                if (errorRunnable != null) {
                                    errorRunnable.onError(error.text, text);
                                }
                                AlertsCreator.processError(currentAccount, error, PassportActivity.this, req, text);
                            } else {
                                if (documentOnly) {
                                    if (documentRequiredType != null) {
                                        removeValue(documentRequiredType);
                                    } else {
                                        removeValue(requiredType);
                                    }
                                } else {
                                    removeValue(requiredType);
                                    removeValue(documentRequiredType);
                                }
                                if (newValue != null) {
                                    currentForm.values.add(newValue);
                                }
                                if (newPendingValue != null) {
                                    currentForm.values.add(newPendingValue);
                                }
                                if (documents != null && !documents.isEmpty()) {
                                    for (int a = 0, size = documents.size(); a < size; a++) {
                                        SecureDocument document = documents.get(a);
                                        if (document.inputFile != null) {
                                            for (int b = 0, size2 = newValue.files.size(); b < size2; b++) {
                                                TLRPC.SecureFile file = newValue.files.get(b);
                                                if (file instanceof TLRPC.TL_secureFile) {
                                                    TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) file;
                                                    if (Utilities.arraysEquals(document.fileSecret, 0, secureFile.secret, 0)) {
                                                        renameFile(document, secureFile);
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (selfie != null && selfie.inputFile != null && newValue.selfie instanceof TLRPC.TL_secureFile) {
                                    TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) newValue.selfie;
                                    if (Utilities.arraysEquals(selfie.fileSecret, 0, secureFile.secret, 0)) {
                                        renameFile(selfie, secureFile);
                                    }
                                }
                                if (front != null && front.inputFile != null && newValue.front_side instanceof TLRPC.TL_secureFile) {
                                    TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) newValue.front_side;
                                    if (Utilities.arraysEquals(front.fileSecret, 0, secureFile.secret, 0)) {
                                        renameFile(front, secureFile);
                                    }
                                }
                                if (reverse != null && reverse.inputFile != null && newValue.reverse_side instanceof TLRPC.TL_secureFile) {
                                    TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) newValue.reverse_side;
                                    if (Utilities.arraysEquals(reverse.fileSecret, 0, secureFile.secret, 0)) {
                                        renameFile(reverse, secureFile);
                                    }
                                }
                                if (translationDocuments != null && !translationDocuments.isEmpty()) {
                                    for (int a = 0, size = translationDocuments.size(); a < size; a++) {
                                        SecureDocument document = translationDocuments.get(a);
                                        if (document.inputFile != null) {
                                            for (int b = 0, size2 = newValue.translation.size(); b < size2; b++) {
                                                TLRPC.SecureFile file = newValue.translation.get(b);
                                                if (file instanceof TLRPC.TL_secureFile) {
                                                    TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) file;
                                                    if (Utilities.arraysEquals(document.fileSecret, 0, secureFile.secret, 0)) {
                                                        renameFile(document, secureFile);
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                setTypeValue(requiredType, text, json, documentRequiredType, documentsJson, documentOnly, availableDocumentTypesCount);
                                if (finishRunnable != null) {
                                    finishRunnable.run();
                                }
                            }
                        });
                    }

                    @Override
                    public void run(final TLObject response, final TLRPC.TL_error error) {
                        if (error != null) {
                            if (error.text.equals("EMAIL_VERIFICATION_NEEDED")) {
                                TLRPC.TL_account_sendVerifyEmailCode req = new TLRPC.TL_account_sendVerifyEmailCode();
                                req.email = text;
                                ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response1, error1) -> AndroidUtilities.runOnUIThread(() -> {
                                    if (response1 != null) {
                                        TLRPC.TL_account_sentEmailCode res = (TLRPC.TL_account_sentEmailCode) response1;
                                        HashMap<String, String> values = new HashMap<>();
                                        values.put("email", text);
                                        values.put("pattern", res.email_pattern);
                                        PassportActivity activity1 = new PassportActivity(TYPE_EMAIL_VERIFICATION, currentForm, currentPassword, requiredType, null, null, null, values, null);
                                        activity1.currentAccount = currentAccount;
                                        activity1.emailCodeLength = res.length;
                                        activity1.saltedPassword = saltedPassword;
                                        activity1.secureSecret = secureSecret;
                                        activity1.delegate = currentDelegate;
                                        presentFragment(activity1, true);
                                    } else {
                                        showAlertWithText(LocaleController.getString("PassportEmail", R.string.PassportEmail), error1.text);
                                        if (errorRunnable != null) {
                                            errorRunnable.onError(error1.text, text);
                                        }
                                    }
                                }));
                                return;
                            } else if (error.text.equals("PHONE_VERIFICATION_NEEDED")) {
                                AndroidUtilities.runOnUIThread(() -> errorRunnable.onError(error.text, text));
                                return;
                            }
                        }
                        if (error == null && finalFileInputSecureValue != null) {
                            final TLRPC.TL_secureValue pendingValue = (TLRPC.TL_secureValue) response;
                            final TLRPC.TL_account_saveSecureValue req = new TLRPC.TL_account_saveSecureValue();
                            req.value = finalFileInputSecureValue;
                            req.secure_secret_id = secureSecretId;
                            ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response12, error12) -> onResult(error12, (TLRPC.TL_secureValue) response12, pendingValue));
                        } else {
                            onResult(error, (TLRPC.TL_secureValue) response, null);
                        }
                    }
                });
            }

            @Override
            public SecureDocument saveFile(TLRPC.TL_secureFile secureFile) {
                String path = FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE) + "/" + secureFile.dc_id + "_" + secureFile.id + ".jpg";
                EncryptionResult result = createSecureDocument(path);
                return new SecureDocument(result.secureDocumentKey, secureFile, path, result.fileHash, result.fileSecret);
            }

            @Override
            public void deleteValue(TLRPC.TL_secureRequiredType requiredType, TLRPC.TL_secureRequiredType documentRequiredType, ArrayList<TLRPC.TL_secureRequiredType> documentRequiredTypes, boolean deleteType, Runnable finishRunnable, ErrorRunnable errorRunnable) {
                deleteValueInternal(requiredType, documentRequiredType, documentRequiredTypes, deleteType, finishRunnable, errorRunnable, documentOnly);
            }
        };
        activity.currentAccount = currentAccount;
        activity.saltedPassword = saltedPassword;
        activity.secureSecret = secureSecret;
        activity.currentBotId = currentBotId;
        activity.fieldsErrors = errors;
        activity.documentOnly = documentOnly;
        activity.documentsErrors = documentsErrors;
        activity.availableDocumentTypes = availableDocumentTypes;
        if (activityType == TYPE_EMAIL) {
            activity.currentEmail = currentEmail;
        }
        presentFragment(activity);
    }
}
Also used : HashMap(java.util.HashMap) TLRPC(org.telegram.tgnet.TLRPC) RequestDelegate(org.telegram.tgnet.RequestDelegate) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) SecureDocument(org.telegram.messenger.SecureDocument) TLObject(org.telegram.tgnet.TLObject)

Example 8 with RequestDelegate

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

the class MessagesController method setUserAdminRole.

public void setUserAdminRole(long chatId, TLRPC.User user, TLRPC.TL_chatAdminRights rights, String rank, boolean isChannel, BaseFragment parentFragment, boolean addingNew) {
    if (user == null || rights == null) {
        return;
    }
    TLRPC.Chat chat = getChat(chatId);
    if (ChatObject.isChannel(chat)) {
        TLRPC.TL_channels_editAdmin req = new TLRPC.TL_channels_editAdmin();
        req.channel = getInputChannel(chat);
        req.user_id = getInputUser(user);
        req.admin_rights = rights;
        req.rank = rank;
        getConnectionsManager().sendRequest(req, (response, error) -> {
            if (error == null) {
                processUpdates((TLRPC.Updates) response, false);
                AndroidUtilities.runOnUIThread(() -> loadFullChat(chatId, 0, true), 1000);
            } else {
                AndroidUtilities.runOnUIThread(() -> AlertsCreator.processError(currentAccount, error, parentFragment, req, isChannel));
            }
        });
    } else {
        TLRPC.TL_messages_editChatAdmin req = new TLRPC.TL_messages_editChatAdmin();
        req.chat_id = chatId;
        req.user_id = getInputUser(user);
        req.is_admin = rights.change_info || rights.delete_messages || rights.ban_users || rights.invite_users || rights.pin_messages || rights.add_admins || rights.manage_call;
        RequestDelegate requestDelegate = (response, error) -> {
            if (error == null) {
                AndroidUtilities.runOnUIThread(() -> loadFullChat(chatId, 0, true), 1000);
            } else {
                AndroidUtilities.runOnUIThread(() -> AlertsCreator.processError(currentAccount, error, parentFragment, req, false));
            }
        };
        if (req.is_admin && addingNew) {
            addUserToChat(chatId, user, 0, null, parentFragment, () -> getConnectionsManager().sendRequest(req, requestDelegate));
        } else {
            getConnectionsManager().sendRequest(req, requestDelegate);
        }
    }
}
Also used : Arrays(java.util.Arrays) Bundle(android.os.Bundle) ProfileActivity(org.telegram.ui.ProfileActivity) Locale(java.util.Locale) Looper(android.os.Looper) Map(java.util.Map) NotificationManagerCompat(androidx.core.app.NotificationManagerCompat) LongSparseLongArray(org.telegram.messenger.support.LongSparseLongArray) DialogsActivity(org.telegram.ui.DialogsActivity) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) Consumer(androidx.core.util.Consumer) SparseArray(android.util.SparseArray) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) LaunchActivity(org.telegram.ui.LaunchActivity) Location(android.location.Location) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) ChatActivity(org.telegram.ui.ChatActivity) Context(android.content.Context) VoIPService(org.telegram.messenger.voip.VoIPService) SparseIntArray(android.util.SparseIntArray) Theme(org.telegram.ui.ActionBar.Theme) RequestDelegate(org.telegram.tgnet.RequestDelegate) BulletinFactory(org.telegram.ui.Components.BulletinFactory) Intent(android.content.Intent) SystemClock(android.os.SystemClock) HashMap(java.util.HashMap) SwipeGestureSettingsView(org.telegram.ui.Components.SwipeGestureSettingsView) AlertsCreator(org.telegram.ui.Components.AlertsCreator) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TLRPC(org.telegram.tgnet.TLRPC) TelephonyManager(android.telephony.TelephonyManager) TLObject(org.telegram.tgnet.TLObject) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) EditWidgetActivity(org.telegram.ui.EditWidgetActivity) Build(android.os.Build) SQLiteException(org.telegram.SQLite.SQLiteException) SerializedData(org.telegram.tgnet.SerializedData) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) LongSparseArray(androidx.collection.LongSparseArray) JoinCallAlert(org.telegram.ui.Components.JoinCallAlert) TextUtils(android.text.TextUtils) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement) File(java.io.File) AppWidgetManager(android.appwidget.AppWidgetManager) SparseBooleanArray(android.util.SparseBooleanArray) SharedPreferences(android.content.SharedPreferences) Base64(android.util.Base64) Comparator(java.util.Comparator) Activity(android.app.Activity) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Collections(java.util.Collections) RequestDelegate(org.telegram.tgnet.RequestDelegate) TLRPC(org.telegram.tgnet.TLRPC)

Example 9 with RequestDelegate

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

the class TwoStepVerificationActivity method processDone.

private void processDone() {
    if (!passwordEntered) {
        String oldPassword = passwordEditText.getText().toString();
        if (oldPassword.length() == 0) {
            onFieldError(passwordEditText, false);
            return;
        }
        final byte[] oldPasswordBytes = AndroidUtilities.getStringBytes(oldPassword);
        needShowProgress();
        Utilities.globalQueue.postRunnable(() -> {
            final TLRPC.TL_account_getPasswordSettings req = new TLRPC.TL_account_getPasswordSettings();
            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(oldPasswordBytes, algo);
            } else {
                x_bytes = null;
            }
            RequestDelegate requestDelegate = (response, error) -> {
                if (error == null) {
                    Utilities.globalQueue.postRunnable(() -> {
                        boolean secretOk = checkSecretValues(oldPasswordBytes, (TLRPC.TL_account_passwordSettings) response);
                        AndroidUtilities.runOnUIThread(() -> {
                            if (delegate == null || !secretOk) {
                                needHideProgress();
                            }
                            if (secretOk) {
                                currentPasswordHash = x_bytes;
                                passwordEntered = true;
                                if (delegate != null) {
                                    AndroidUtilities.hideKeyboard(passwordEditText);
                                    delegate.didEnterPassword(getNewSrpPassword());
                                } else {
                                    if (!TextUtils.isEmpty(currentPassword.email_unconfirmed_pattern)) {
                                        TwoStepVerificationSetupActivity fragment = new TwoStepVerificationSetupActivity(currentAccount, TwoStepVerificationSetupActivity.TYPE_EMAIL_CONFIRM, currentPassword);
                                        fragment.setCurrentPasswordParams(currentPasswordHash, currentSecretId, currentSecret, true);
                                        presentFragment(fragment, true);
                                    } else {
                                        AndroidUtilities.hideKeyboard(passwordEditText);
                                        TwoStepVerificationActivity fragment = new TwoStepVerificationActivity();
                                        fragment.passwordEntered = true;
                                        fragment.currentPasswordHash = currentPasswordHash;
                                        fragment.currentPassword = currentPassword;
                                        fragment.currentSecret = currentSecret;
                                        fragment.currentSecretId = currentSecretId;
                                        presentFragment(fragment, true);
                                    }
                                }
                            } else {
                                AlertsCreator.showUpdateAppAlert(getParentActivity(), LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert), true);
                            }
                        });
                    });
                } else {
                    AndroidUtilities.runOnUIThread(() -> {
                        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) {
                                    currentPassword = (TLRPC.TL_account_password) response2;
                                    initPasswordNewAlgo(currentPassword);
                                    NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.didSetOrRemoveTwoStepPassword, currentPassword);
                                    processDone();
                                }
                            }), ConnectionsManager.RequestFlagWithoutLogin);
                            return;
                        }
                        needHideProgress();
                        if ("PASSWORD_HASH_INVALID".equals(error.text)) {
                            onFieldError(passwordEditText, 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;
                }
                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);
            }
        });
    }
}
Also used : ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Bundle(android.os.Bundle) FrameLayout(android.widget.FrameLayout) AndroidUtilities(org.telegram.messenger.AndroidUtilities) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Locale(java.util.Locale) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) Utilities(org.telegram.messenger.Utilities) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) NotificationCenter(org.telegram.messenger.NotificationCenter) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) EditorInfo(android.view.inputmethod.EditorInfo) Typeface(android.graphics.Typeface) Context(android.content.Context) Theme(org.telegram.ui.ActionBar.Theme) RequestDelegate(org.telegram.tgnet.RequestDelegate) LocaleController(org.telegram.messenger.LocaleController) AlertsCreator(org.telegram.ui.Components.AlertsCreator) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) SRPHelper(org.telegram.messenger.SRPHelper) TLRPC(org.telegram.tgnet.TLRPC) ActionBar(org.telegram.ui.ActionBar.ActionBar) EditTextSettingsCell(org.telegram.ui.Cells.EditTextSettingsCell) Menu(android.view.Menu) PasswordTransformationMethod(android.text.method.PasswordTransformationMethod) DialogInterface(android.content.DialogInterface) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) Gravity(android.view.Gravity) TypedValue(android.util.TypedValue) ScrollView(android.widget.ScrollView) Vibrator(android.os.Vibrator) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) RecyclerListView(org.telegram.ui.Components.RecyclerListView) RequestDelegate(org.telegram.tgnet.RequestDelegate) TLRPC(org.telegram.tgnet.TLRPC)

Example 10 with RequestDelegate

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

the class TwoStepVerificationActivity method clearPassword.

private void clearPassword() {
    final String password = firstPassword;
    final TLRPC.TL_account_updatePasswordSettings req = new TLRPC.TL_account_updatePasswordSettings();
    if (currentPasswordHash == null || currentPasswordHash.length == 0) {
        req.password = new TLRPC.TL_inputCheckPasswordEmpty();
    }
    req.new_settings = new TLRPC.TL_account_passwordInputSettings();
    UserConfig.getInstance(currentAccount).resetSavedPassword();
    currentSecret = null;
    req.new_settings.flags = 3;
    req.new_settings.hint = "";
    req.new_settings.new_password_hash = new byte[0];
    req.new_settings.new_algo = new TLRPC.TL_passwordKdfAlgoUnknown();
    req.new_settings.email = "";
    needShowProgress();
    Utilities.globalQueue.postRunnable(() -> {
        if (req.password == null) {
            if (currentPassword.current_algo == null) {
                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;
                        initPasswordNewAlgo(currentPassword);
                        NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.didSetOrRemoveTwoStepPassword, currentPassword);
                        clearPassword();
                    }
                }), ConnectionsManager.RequestFlagWithoutLogin);
                return;
            }
            req.password = getNewSrpPassword();
        }
        byte[] newPasswordBytes = null;
        byte[] newPasswordHash = null;
        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;
                        initPasswordNewAlgo(currentPassword);
                        NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.didSetOrRemoveTwoStepPassword, currentPassword);
                        clearPassword();
                    }
                }), ConnectionsManager.RequestFlagWithoutLogin);
                return;
            }
            needHideProgress();
            if (error == null && response instanceof TLRPC.TL_boolTrue) {
                currentPassword = null;
                currentPasswordHash = new byte[0];
                NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.didRemoveTwoStepPassword);
                NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.didSetOrRemoveTwoStepPassword);
                finishFragment();
            } else if (error != null) {
                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.getInstance(currentAccount).sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);
    });
}
Also used : ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Bundle(android.os.Bundle) FrameLayout(android.widget.FrameLayout) AndroidUtilities(org.telegram.messenger.AndroidUtilities) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Locale(java.util.Locale) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) Utilities(org.telegram.messenger.Utilities) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) NotificationCenter(org.telegram.messenger.NotificationCenter) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) EditorInfo(android.view.inputmethod.EditorInfo) Typeface(android.graphics.Typeface) Context(android.content.Context) Theme(org.telegram.ui.ActionBar.Theme) RequestDelegate(org.telegram.tgnet.RequestDelegate) LocaleController(org.telegram.messenger.LocaleController) AlertsCreator(org.telegram.ui.Components.AlertsCreator) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) SRPHelper(org.telegram.messenger.SRPHelper) TLRPC(org.telegram.tgnet.TLRPC) ActionBar(org.telegram.ui.ActionBar.ActionBar) EditTextSettingsCell(org.telegram.ui.Cells.EditTextSettingsCell) Menu(android.view.Menu) PasswordTransformationMethod(android.text.method.PasswordTransformationMethod) DialogInterface(android.content.DialogInterface) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) Gravity(android.view.Gravity) TypedValue(android.util.TypedValue) ScrollView(android.widget.ScrollView) Vibrator(android.os.Vibrator) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) RecyclerListView(org.telegram.ui.Components.RecyclerListView) RequestDelegate(org.telegram.tgnet.RequestDelegate) TLRPC(org.telegram.tgnet.TLRPC)

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