Search in sources :

Example 31 with TLObject

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

the class PassportActivity method onPasswordDone.

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

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

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

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

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

Example 32 with TLObject

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

the class PhotoPickerActivity method searchImages.

private void searchImages(boolean gif, final String query, final String offset, boolean searchUser) {
    if (searching) {
        searching = false;
        if (imageReqId != 0) {
            ConnectionsManager.getInstance(currentAccount).cancelRequest(imageReqId, true);
            imageReqId = 0;
        }
    }
    lastSearchImageString = query;
    searching = true;
    TLObject object = MessagesController.getInstance(currentAccount).getUserOrChat(gif ? MessagesController.getInstance(currentAccount).gifSearchBot : MessagesController.getInstance(currentAccount).imageSearchBot);
    if (!(object instanceof TLRPC.User)) {
        if (searchUser) {
            searchBotUser(gif);
        }
        return;
    }
    TLRPC.User user = (TLRPC.User) object;
    TLRPC.TL_messages_getInlineBotResults req = new TLRPC.TL_messages_getInlineBotResults();
    req.query = query == null ? "" : query;
    req.bot = MessagesController.getInstance(currentAccount).getInputUser(user);
    req.offset = offset;
    if (chatActivity != null) {
        long dialogId = chatActivity.getDialogId();
        if (DialogObject.isEncryptedDialog(dialogId)) {
            req.peer = new TLRPC.TL_inputPeerEmpty();
        } else {
            req.peer = getMessagesController().getInputPeer(dialogId);
        }
    } else {
        req.peer = new TLRPC.TL_inputPeerEmpty();
    }
    final int token = ++lastSearchToken;
    imageReqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
        if (token != lastSearchToken) {
            return;
        }
        int addedCount = 0;
        int oldCount = searchResult.size();
        if (response != null) {
            TLRPC.messages_BotResults res = (TLRPC.messages_BotResults) response;
            nextImagesSearchOffset = res.next_offset;
            for (int a = 0, count = res.results.size(); a < count; a++) {
                TLRPC.BotInlineResult result = res.results.get(a);
                if (!gif && !"photo".equals(result.type) || gif && !"gif".equals(result.type)) {
                    continue;
                }
                if (searchResultKeys.containsKey(result.id)) {
                    continue;
                }
                MediaController.SearchImage image = new MediaController.SearchImage();
                if (gif && result.document != null) {
                    for (int b = 0; b < result.document.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = result.document.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            image.width = attribute.w;
                            image.height = attribute.h;
                            break;
                        }
                    }
                    image.document = result.document;
                    image.size = 0;
                    if (result.photo != null) {
                        TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(result.photo.sizes, itemSize, true);
                        if (size != null) {
                            result.document.thumbs.add(size);
                            result.document.flags |= 1;
                        }
                    }
                } else if (!gif && result.photo != null) {
                    TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(result.photo.sizes, AndroidUtilities.getPhotoSize());
                    TLRPC.PhotoSize size2 = FileLoader.getClosestPhotoSizeWithSize(result.photo.sizes, 320);
                    if (size == null) {
                        continue;
                    }
                    image.width = size.w;
                    image.height = size.h;
                    image.photoSize = size;
                    image.photo = result.photo;
                    image.size = size.size;
                    image.thumbPhotoSize = size2;
                } else {
                    if (result.content == null) {
                        continue;
                    }
                    for (int b = 0; b < result.content.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = result.content.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize) {
                            image.width = attribute.w;
                            image.height = attribute.h;
                            break;
                        }
                    }
                    if (result.thumb != null) {
                        image.thumbUrl = result.thumb.url;
                    } else {
                        image.thumbUrl = null;
                    }
                    image.imageUrl = result.content.url;
                    image.size = gif ? 0 : result.content.size;
                }
                image.id = result.id;
                image.type = gif ? 1 : 0;
                image.inlineResult = result;
                image.params = new HashMap<>();
                image.params.put("id", result.id);
                image.params.put("query_id", "" + res.query_id);
                image.params.put("bot_name", user.username);
                searchResult.add(image);
                searchResultKeys.put(image.id, image);
                addedCount++;
            }
            imageSearchEndReached = oldCount == searchResult.size() || nextImagesSearchOffset == null;
        }
        searching = false;
        if (addedCount != 0) {
            listAdapter.notifyItemRangeInserted(oldCount, addedCount);
        } else if (imageSearchEndReached) {
            listAdapter.notifyItemRemoved(searchResult.size() - 1);
        }
        if (searching && searchResult.isEmpty()) {
            emptyView.showProgress();
        } else {
            emptyView.showTextView();
        }
    }));
    ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(imageReqId, classGuid);
}
Also used : ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) SharedDocumentCell(org.telegram.ui.Cells.SharedDocumentCell) WindowManager(android.view.WindowManager) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) AndroidUtilities(org.telegram.messenger.AndroidUtilities) Animator(android.animation.Animator) RecyclerViewItemRangeSelector(org.telegram.ui.Components.RecyclerViewItemRangeSelector) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) RadialProgressView(org.telegram.ui.Components.RadialProgressView) ApplicationLoader(org.telegram.messenger.ApplicationLoader) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) TextCell(org.telegram.ui.Cells.TextCell) MediaController(org.telegram.messenger.MediaController) View(android.view.View) Button(android.widget.Button) Canvas(android.graphics.Canvas) RecyclerView(androidx.recyclerview.widget.RecyclerView) RectF(android.graphics.RectF) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) ObjectAnimator(android.animation.ObjectAnimator) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) PorterDuff(android.graphics.PorterDuff) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) NotificationCenter(org.telegram.messenger.NotificationCenter) Outline(android.graphics.Outline) HapticFeedbackConstants(android.view.HapticFeedbackConstants) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) TextPaint(android.text.TextPaint) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) InputFilter(android.text.InputFilter) DividerCell(org.telegram.ui.Cells.DividerCell) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) TextWatcher(android.text.TextWatcher) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) FileLoader(org.telegram.messenger.FileLoader) Context(android.content.Context) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) KeyEvent(android.view.KeyEvent) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) Theme(org.telegram.ui.ActionBar.Theme) ViewOutlineProvider(android.view.ViewOutlineProvider) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) AlertsCreator(org.telegram.ui.Components.AlertsCreator) Editable(android.text.Editable) ArrayList(java.util.ArrayList) SuppressLint(android.annotation.SuppressLint) VideoEditedInfo(org.telegram.messenger.VideoEditedInfo) MotionEvent(android.view.MotionEvent) TLRPC(org.telegram.tgnet.TLRPC) ActionBar(org.telegram.ui.ActionBar.ActionBar) TLObject(org.telegram.tgnet.TLObject) EditTextEmoji(org.telegram.ui.Components.EditTextEmoji) AnimatorSet(android.animation.AnimatorSet) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) SharedConfig(org.telegram.messenger.SharedConfig) MessageObject(org.telegram.messenger.MessageObject) Build(android.os.Build) DialogInterface(android.content.DialogInterface) SimpleTextView(org.telegram.ui.ActionBar.SimpleTextView) DialogObject(org.telegram.messenger.DialogObject) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) PhotoAttachPhotoCell(org.telegram.ui.Cells.PhotoAttachPhotoCell) BackupImageView(org.telegram.ui.Components.BackupImageView) TextUtils(android.text.TextUtils) LayoutHelper(org.telegram.ui.Components.LayoutHelper) MessagesController(org.telegram.messenger.MessagesController) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) MessagesStorage(org.telegram.messenger.MessagesStorage) OvershootInterpolator(android.view.animation.OvershootInterpolator) Activity(android.app.Activity) ChatObject(org.telegram.messenger.ChatObject) ImageReceiver(org.telegram.messenger.ImageReceiver) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) EditText(android.widget.EditText) RecyclerListView(org.telegram.ui.Components.RecyclerListView) MediaController(org.telegram.messenger.MediaController) TLRPC(org.telegram.tgnet.TLRPC) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) TLObject(org.telegram.tgnet.TLObject)

Example 33 with TLObject

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

the class PhotoViewer method checkProgress.

private void checkProgress(int a, boolean scroll, boolean animated) {
    int index = currentIndex;
    if (a == 1) {
        index += 1;
    } else if (a == 2) {
        index -= 1;
    }
    if (currentFileNames[a] != null) {
        File f1 = null;
        File f2 = null;
        boolean isVideo = false;
        boolean canStream = false;
        boolean canAutoPlay = false;
        MessageObject messageObject = null;
        if (currentMessageObject != null) {
            if (index < 0 || index >= imagesArr.size()) {
                photoProgressViews[a].setBackgroundState(PROGRESS_NONE, animated, true);
                return;
            }
            messageObject = imagesArr.get(index);
            canAutoPlay = shouldMessageObjectAutoPlayed(messageObject);
            if (sharedMediaType == MediaDataController.MEDIA_FILE && !messageObject.canPreviewDocument()) {
                photoProgressViews[a].setBackgroundState(PROGRESS_NONE, animated, true);
                return;
            }
            if (!TextUtils.isEmpty(messageObject.messageOwner.attachPath)) {
                f1 = new File(messageObject.messageOwner.attachPath);
            }
            if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageObject.messageOwner.media.webpage != null && messageObject.messageOwner.media.webpage.document == null) {
                TLObject fileLocation = getFileLocation(index, null);
                f2 = FileLoader.getPathToAttach(fileLocation, true);
            } else {
                f2 = FileLoader.getPathToMessage(messageObject.messageOwner);
            }
            if (messageObject.isVideo()) {
                canStream = SharedConfig.streamMedia && messageObject.canStreamVideo() && !DialogObject.isEncryptedDialog(messageObject.getDialogId());
                isVideo = true;
            }
        } else if (currentBotInlineResult != null) {
            if (index < 0 || index >= imagesArrLocals.size()) {
                photoProgressViews[a].setBackgroundState(PROGRESS_NONE, animated, true);
                return;
            }
            TLRPC.BotInlineResult botInlineResult = (TLRPC.BotInlineResult) imagesArrLocals.get(index);
            if (botInlineResult.type.equals("video") || MessageObject.isVideoDocument(botInlineResult.document)) {
                if (botInlineResult.document != null) {
                    f1 = FileLoader.getPathToAttach(botInlineResult.document);
                } else if (botInlineResult.content instanceof TLRPC.TL_webDocument) {
                    f1 = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(botInlineResult.content.url) + "." + ImageLoader.getHttpUrlExtension(botInlineResult.content.url, "mp4"));
                }
                isVideo = true;
            } else if (botInlineResult.document != null) {
                f1 = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_DOCUMENT), currentFileNames[a]);
            } else if (botInlineResult.photo != null) {
                f1 = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_IMAGE), currentFileNames[a]);
            }
            f2 = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), currentFileNames[a]);
        } else if (currentFileLocation != null) {
            if (index < 0 || index >= imagesArrLocationsVideo.size()) {
                photoProgressViews[a].setBackgroundState(PROGRESS_NONE, animated, true);
                return;
            }
            ImageLocation location = imagesArrLocationsVideo.get(index);
            f1 = FileLoader.getPathToAttach(location.location, getFileLocationExt(location), avatarsDialogId != 0 || isEvent);
        } else if (currentSecureDocument != null) {
            if (index < 0 || index >= secureDocuments.size()) {
                photoProgressViews[a].setBackgroundState(PROGRESS_NONE, animated, true);
                return;
            }
            SecureDocument location = secureDocuments.get(index);
            f1 = FileLoader.getPathToAttach(location, true);
        } else if (currentPathObject != null) {
            f1 = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_DOCUMENT), currentFileNames[a]);
            f2 = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), currentFileNames[a]);
        } else if (pageBlocksAdapter != null) {
            f1 = pageBlocksAdapter.getFile(index);
            isVideo = pageBlocksAdapter.isVideo(index);
            canAutoPlay = shouldIndexAutoPlayed(index);
        }
        File f1Final = f1;
        File f2Final = f2;
        MessageObject messageObjectFinal = messageObject;
        boolean canStreamFinal = canStream;
        boolean canAutoPlayFinal = !(a == 0 && dontAutoPlay) && canAutoPlay;
        boolean isVideoFinal = isVideo;
        Utilities.globalQueue.postRunnable(() -> {
            boolean exists = false;
            if (f1Final != null) {
                exists = f1Final.exists();
            }
            if (!exists && f2Final != null) {
                exists = f2Final.exists();
            }
            if (!exists && a != 0 && messageObjectFinal != null && canStreamFinal) {
                if (DownloadController.getInstance(currentAccount).canDownloadMedia(messageObjectFinal.messageOwner) != 0) {
                    if ((parentChatActivity == null || parentChatActivity.getCurrentEncryptedChat() == null) && !messageObjectFinal.shouldEncryptPhotoOrVideo()) {
                        final TLRPC.Document document = messageObjectFinal.getDocument();
                        if (document != null) {
                            FileLoader.getInstance(currentAccount).loadFile(document, messageObjectFinal, 0, 10);
                        }
                    }
                }
            }
            boolean existsFinal = exists;
            AndroidUtilities.runOnUIThread(() -> {
                if (shownControlsByEnd && !actionBarWasShownBeforeByEnd && isPlaying) {
                    photoProgressViews[a].setBackgroundState(PROGRESS_PLAY, false, false);
                    return;
                }
                if ((f1Final != null || f2Final != null) && (existsFinal || canStreamFinal)) {
                    if (a != 0 || !isPlaying) {
                        if (isVideoFinal && (!canAutoPlayFinal || a == 0 && playerWasPlaying)) {
                            photoProgressViews[a].setBackgroundState(PROGRESS_PLAY, animated, true);
                        } else {
                            photoProgressViews[a].setBackgroundState(PROGRESS_NONE, animated, true);
                        }
                    }
                    if (a == 0) {
                        if (!existsFinal) {
                            if (!FileLoader.getInstance(currentAccount).isLoadingFile(currentFileNames[a])) {
                                menuItem.hideSubItem(gallery_menu_cancel_loading);
                            } else {
                                menuItem.showSubItem(gallery_menu_cancel_loading);
                            }
                        } else {
                            menuItem.hideSubItem(gallery_menu_cancel_loading);
                        }
                    }
                } else {
                    if (isVideoFinal) {
                        if (!FileLoader.getInstance(currentAccount).isLoadingFile(currentFileNames[a])) {
                            photoProgressViews[a].setBackgroundState(PROGRESS_LOAD, false, true);
                        } else {
                            photoProgressViews[a].setBackgroundState(PROGRESS_CANCEL, false, true);
                        }
                    } else {
                        photoProgressViews[a].setBackgroundState(PROGRESS_EMPTY, animated, true);
                    }
                    Float progress = ImageLoader.getInstance().getFileProgress(currentFileNames[a]);
                    if (progress == null) {
                        progress = 0.0f;
                    }
                    photoProgressViews[a].setProgress(progress, false);
                }
                if (a == 0) {
                    canZoom = !isEmbedVideo && (!imagesArrLocals.isEmpty() || (currentFileNames[0] != null && photoProgressViews[0].backgroundState != 0));
                }
            });
        });
    } else {
        boolean isLocalVideo = false;
        if (!imagesArrLocals.isEmpty() && index >= 0 && index < imagesArrLocals.size()) {
            Object object = imagesArrLocals.get(index);
            if (object instanceof MediaController.PhotoEntry) {
                MediaController.PhotoEntry photoEntry = ((MediaController.PhotoEntry) object);
                isLocalVideo = photoEntry.isVideo;
            }
        }
        if (isLocalVideo) {
            photoProgressViews[a].setBackgroundState(PROGRESS_PLAY, animated, true);
        } else {
            photoProgressViews[a].setBackgroundState(PROGRESS_NONE, animated, true);
        }
    }
}
Also used : MediaController(org.telegram.messenger.MediaController) Paint(android.graphics.Paint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) TLRPC(org.telegram.tgnet.TLRPC) ImageLocation(org.telegram.messenger.ImageLocation) SecureDocument(org.telegram.messenger.SecureDocument) TLObject(org.telegram.tgnet.TLObject) UserObject(org.telegram.messenger.UserObject) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) DialogObject(org.telegram.messenger.DialogObject) ChatObject(org.telegram.messenger.ChatObject) WebFile(org.telegram.messenger.WebFile) File(java.io.File) MessageObject(org.telegram.messenger.MessageObject)

Example 34 with TLObject

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

the class PhotoViewer method setIndexToImage.

private void setIndexToImage(ImageReceiver imageReceiver, int index) {
    imageReceiver.setOrientation(0, false);
    if (!secureDocuments.isEmpty()) {
        if (index >= 0 && index < secureDocuments.size()) {
            Object object = secureDocuments.get(index);
            int size = (int) (AndroidUtilities.getPhotoSize() / AndroidUtilities.density);
            ImageReceiver.BitmapHolder placeHolder = null;
            if (currentThumb != null && imageReceiver == centerImage) {
                placeHolder = currentThumb;
            }
            if (placeHolder == null) {
                placeHolder = placeProvider.getThumbForPhoto(null, null, index);
            }
            SecureDocument document = secureDocuments.get(index);
            int imageSize = document.secureFile.size;
            imageReceiver.setImage(ImageLocation.getForSecureDocument(document), "d", null, null, placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, imageSize, null, null, 0);
        }
    } else if (!imagesArrLocals.isEmpty()) {
        if (index >= 0 && index < imagesArrLocals.size()) {
            Object object = imagesArrLocals.get(index);
            int size = (int) (AndroidUtilities.getPhotoSize() / AndroidUtilities.density);
            ImageReceiver.BitmapHolder placeHolder = null;
            if (currentThumb != null && imageReceiver == centerImage) {
                placeHolder = currentThumb;
            }
            if (placeHolder == null) {
                placeHolder = placeProvider.getThumbForPhoto(null, null, index);
            }
            String path = null;
            TLRPC.Document document = null;
            WebFile webDocument = null;
            ImageLocation videoThumb = null;
            TLRPC.PhotoSize photo = null;
            TLObject photoObject = null;
            int imageSize = 0;
            String filter = null;
            boolean isVideo = false;
            int cacheType = 0;
            if (object instanceof MediaController.PhotoEntry) {
                MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) object;
                isVideo = photoEntry.isVideo;
                if (photoEntry.isVideo) {
                    if (photoEntry.thumbPath != null) {
                        if (fromCamera) {
                            Bitmap b = BitmapFactory.decodeFile(photoEntry.thumbPath);
                            if (b != null) {
                                placeHolder = new ImageReceiver.BitmapHolder(b);
                                photoEntry.thumbPath = null;
                            }
                        } else {
                            path = photoEntry.thumbPath;
                        }
                    } else {
                        path = "vthumb://" + photoEntry.imageId + ":" + photoEntry.path;
                    }
                } else {
                    if (photoEntry.filterPath != null) {
                        path = photoEntry.filterPath;
                    } else {
                        imageReceiver.setOrientation(photoEntry.orientation, false);
                        path = photoEntry.path;
                    }
                    filter = String.format(Locale.US, "%d_%d", size, size);
                }
            } else if (object instanceof TLRPC.BotInlineResult) {
                cacheType = 1;
                TLRPC.BotInlineResult botInlineResult = ((TLRPC.BotInlineResult) object);
                if (botInlineResult.type.equals("video") || MessageObject.isVideoDocument(botInlineResult.document)) {
                    if (botInlineResult.document != null) {
                        photo = FileLoader.getClosestPhotoSizeWithSize(botInlineResult.document.thumbs, 90);
                        photoObject = botInlineResult.document;
                    } else if (botInlineResult.thumb instanceof TLRPC.TL_webDocument) {
                        webDocument = WebFile.createWithWebDocument(botInlineResult.thumb);
                    }
                } else if (botInlineResult.type.equals("gif") && botInlineResult.document != null) {
                    document = botInlineResult.document;
                    imageSize = botInlineResult.document.size;
                    TLRPC.VideoSize videoSize = MessageObject.getDocumentVideoThumb(botInlineResult.document);
                    if (videoSize != null) {
                        videoThumb = ImageLocation.getForDocument(videoSize, document);
                    }
                    filter = "d";
                } else if (botInlineResult.photo != null) {
                    TLRPC.PhotoSize sizeFull = FileLoader.getClosestPhotoSizeWithSize(botInlineResult.photo.sizes, AndroidUtilities.getPhotoSize());
                    photo = sizeFull;
                    photoObject = botInlineResult.photo;
                    imageSize = sizeFull.size;
                    filter = String.format(Locale.US, "%d_%d", size, size);
                } else if (botInlineResult.content instanceof TLRPC.TL_webDocument) {
                    if (botInlineResult.type.equals("gif")) {
                        filter = "d";
                        if (botInlineResult.thumb instanceof TLRPC.TL_webDocument && "video/mp4".equals(botInlineResult.thumb.mime_type)) {
                            videoThumb = ImageLocation.getForWebFile(WebFile.createWithWebDocument(botInlineResult.thumb));
                        }
                    } else {
                        filter = String.format(Locale.US, "%d_%d", size, size);
                    }
                    webDocument = WebFile.createWithWebDocument(botInlineResult.content);
                }
            } else if (object instanceof MediaController.SearchImage) {
                cacheType = 1;
                MediaController.SearchImage photoEntry = (MediaController.SearchImage) object;
                if (photoEntry.photoSize != null) {
                    photo = photoEntry.photoSize;
                    photoObject = photoEntry.photo;
                    imageSize = photoEntry.photoSize.size;
                } else if (photoEntry.filterPath != null) {
                    path = photoEntry.filterPath;
                } else if (photoEntry.document != null) {
                    document = photoEntry.document;
                    imageSize = photoEntry.document.size;
                } else {
                    path = photoEntry.imageUrl;
                    imageSize = photoEntry.size;
                }
                filter = "d";
            }
            if (document != null) {
                TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 90);
                if (videoThumb != null) {
                    imageReceiver.setImage(ImageLocation.getForDocument(document), "d", videoThumb, null, placeHolder == null ? ImageLocation.getForDocument(thumb, document) : null, String.format(Locale.US, "%d_%d", size, size), placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, imageSize, null, object, cacheType);
                } else {
                    imageReceiver.setImage(ImageLocation.getForDocument(document), "d", placeHolder == null ? ImageLocation.getForDocument(thumb, document) : null, String.format(Locale.US, "%d_%d", size, size), placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, imageSize, null, object, cacheType);
                }
            } else if (photo != null) {
                imageReceiver.setImage(ImageLocation.getForObject(photo, photoObject), filter, placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, imageSize, null, object, cacheType);
            } else if (webDocument != null) {
                if (videoThumb != null) {
                    imageReceiver.setImage(ImageLocation.getForWebFile(webDocument), filter, videoThumb, null, (Drawable) null, object, cacheType);
                } else {
                    imageReceiver.setImage(ImageLocation.getForWebFile(webDocument), filter, placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : (isVideo && parentActivity != null ? parentActivity.getResources().getDrawable(R.drawable.nophotos) : null), null, object, cacheType);
                }
            } else {
                imageReceiver.setImage(path, filter, placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : (isVideo && parentActivity != null ? parentActivity.getResources().getDrawable(R.drawable.nophotos) : null), null, imageSize);
            }
        } else {
            imageReceiver.setImageBitmap((Bitmap) null);
        }
    } else if (pageBlocksAdapter != null) {
        int[] size = new int[1];
        TLObject media = pageBlocksAdapter.getMedia(index);
        TLRPC.PhotoSize fileLocation = pageBlocksAdapter.getFileLocation(media, size);
        if (fileLocation != null) {
            if (media instanceof TLRPC.Photo) {
                TLRPC.Photo photo = (TLRPC.Photo) media;
                ImageReceiver.BitmapHolder placeHolder = null;
                if (currentThumb != null && imageReceiver == centerImage) {
                    placeHolder = currentThumb;
                }
                if (size[0] == 0) {
                    size[0] = -1;
                }
                TLRPC.PhotoSize thumbLocation = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 80);
                imageReceiver.setImage(ImageLocation.getForPhoto(fileLocation, photo), null, ImageLocation.getForPhoto(thumbLocation, photo), "b", placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, size[0], null, pageBlocksAdapter.getParentObject(), 1);
            } else if (pageBlocksAdapter.isVideo(index)) {
                if (!(fileLocation.location instanceof TLRPC.TL_fileLocationUnavailable)) {
                    ImageReceiver.BitmapHolder placeHolder = null;
                    if (currentThumb != null && imageReceiver == centerImage) {
                        placeHolder = currentThumb;
                    }
                    imageReceiver.setImage(null, null, placeHolder == null ? ImageLocation.getForDocument(fileLocation, (TLRPC.Document) media) : null, "b", placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, 0, null, pageBlocksAdapter.getParentObject(), 1);
                } else {
                    imageReceiver.setImageBitmap(parentActivity.getResources().getDrawable(R.drawable.photoview_placeholder));
                }
            } else if (currentAnimation != null) {
                imageReceiver.setImageBitmap(currentAnimation);
                currentAnimation.addSecondParentView(containerView);
            }
        } else {
            if (size[0] == 0) {
                imageReceiver.setImageBitmap((Bitmap) null);
            } else {
                imageReceiver.setImageBitmap(parentActivity.getResources().getDrawable(R.drawable.photoview_placeholder));
            }
        }
    } else {
        MessageObject messageObject;
        if (!imagesArr.isEmpty() && index >= 0 && index < imagesArr.size()) {
            messageObject = imagesArr.get(index);
            imageReceiver.setShouldGenerateQualityThumb(true);
        } else {
            messageObject = null;
        }
        if (messageObject != null) {
            String restrictionReason = MessagesController.getRestrictionReason(messageObject.messageOwner.restriction_reason);
            if (!TextUtils.isEmpty(restrictionReason)) {
                imageReceiver.setImageBitmap(parentActivity.getResources().getDrawable(R.drawable.photoview_placeholder));
                return;
            } else if (messageObject.isVideo()) {
                if (messageObject.photoThumbs != null && !messageObject.photoThumbs.isEmpty()) {
                    ImageReceiver.BitmapHolder placeHolder = null;
                    if (currentThumb != null && imageReceiver == centerImage) {
                        placeHolder = currentThumb;
                    }
                    TLRPC.PhotoSize thumbLocation = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 320);
                    imageReceiver.setNeedsQualityThumb(thumbLocation.w < 100 && thumbLocation.h < 100);
                    imageReceiver.setImage(null, null, placeHolder == null ? ImageLocation.getForObject(thumbLocation, messageObject.photoThumbsObject) : null, "b", placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, 0, null, messageObject, 1);
                    if (currentThumb != null) {
                        imageReceiver.setOrientation(currentThumb.orientation, false);
                    }
                } else {
                    imageReceiver.setImageBitmap(parentActivity.getResources().getDrawable(R.drawable.photoview_placeholder));
                }
                return;
            } else if (currentAnimation != null) {
                currentAnimation.addSecondParentView(containerView);
                imageReceiver.setImageBitmap(currentAnimation);
                return;
            } else if (sharedMediaType == MediaDataController.MEDIA_FILE) {
                if (messageObject.canPreviewDocument()) {
                    TLRPC.Document document = messageObject.getDocument();
                    imageReceiver.setNeedsQualityThumb(true);
                    ImageReceiver.BitmapHolder placeHolder = null;
                    if (currentThumb != null && imageReceiver == centerImage) {
                        placeHolder = currentThumb;
                    }
                    TLRPC.PhotoSize thumbLocation = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 100);
                    int size = (int) (2048 / AndroidUtilities.density);
                    imageReceiver.setImage(ImageLocation.getForDocument(document), String.format(Locale.US, "%d_%d", size, size), placeHolder == null ? ImageLocation.getForDocument(thumbLocation, document) : null, "b", placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, document.size, null, messageObject, 0);
                } else {
                    OtherDocumentPlaceholderDrawable drawable = new OtherDocumentPlaceholderDrawable(parentActivity, containerView, messageObject);
                    imageReceiver.setImageBitmap(drawable);
                }
                return;
            }
        }
        int[] size = new int[1];
        ImageLocation imageLocation = getImageLocation(index, size);
        TLObject fileLocation = getFileLocation(index, size);
        imageReceiver.setNeedsQualityThumb(true);
        if (imageLocation != null) {
            ImageReceiver.BitmapHolder placeHolder = null;
            if (currentThumb != null && imageReceiver == centerImage) {
                placeHolder = currentThumb;
            }
            if (size[0] == 0) {
                size[0] = -1;
            }
            TLRPC.PhotoSize thumbLocation;
            TLObject photoObject;
            if (messageObject != null) {
                thumbLocation = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 100);
                photoObject = messageObject.photoThumbsObject;
            } else {
                thumbLocation = null;
                photoObject = null;
            }
            if (thumbLocation != null && thumbLocation == fileLocation) {
                thumbLocation = null;
            }
            boolean cacheOnly = messageObject != null && messageObject.isWebpage() || avatarsDialogId != 0 || isEvent;
            Object parentObject;
            ImageLocation videoThumb = null;
            if (messageObject != null) {
                parentObject = messageObject;
                if (sharedMediaType == MediaDataController.MEDIA_GIF) {
                    TLRPC.Document document = messageObject.getDocument();
                    TLRPC.VideoSize videoSize = MessageObject.getDocumentVideoThumb(document);
                    if (videoSize != null) {
                        videoThumb = ImageLocation.getForDocument(videoSize, document);
                    }
                }
            } else if (avatarsDialogId != 0) {
                if (avatarsDialogId > 0) {
                    parentObject = MessagesController.getInstance(currentAccount).getUser(avatarsDialogId);
                } else {
                    parentObject = MessagesController.getInstance(currentAccount).getChat(-avatarsDialogId);
                }
            } else {
                parentObject = null;
            }
            if (videoThumb != null) {
                imageReceiver.setImage(imageLocation, null, videoThumb, null, placeHolder == null ? ImageLocation.getForObject(thumbLocation, photoObject) : null, "b", placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, size[0], null, parentObject, cacheOnly ? 1 : 0);
            } else {
                String filter;
                if (avatarsDialogId != 0) {
                    filter = imageLocation.imageType == FileLoader.IMAGE_TYPE_ANIMATION ? ImageLoader.AUTOPLAY_FILTER : null;
                } else {
                    filter = null;
                }
                imageReceiver.setImage(imageLocation, filter, placeHolder == null ? ImageLocation.getForObject(thumbLocation, photoObject) : null, "b", placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, size[0], null, parentObject, cacheOnly ? 1 : 0);
            }
        } else {
            if (size[0] == 0) {
                imageReceiver.setImageBitmap((Bitmap) null);
            } else {
                imageReceiver.setImageBitmap(parentActivity.getResources().getDrawable(R.drawable.photoview_placeholder));
            }
        }
    }
}
Also used : MediaController(org.telegram.messenger.MediaController) SizeNotifierFrameLayoutPhoto(org.telegram.ui.Components.SizeNotifierFrameLayoutPhoto) SpannableString(android.text.SpannableString) SecureDocument(org.telegram.messenger.SecureDocument) WebFile(org.telegram.messenger.WebFile) ImageLocation(org.telegram.messenger.ImageLocation) TLRPC(org.telegram.tgnet.TLRPC) ImageReceiver(org.telegram.messenger.ImageReceiver) Bitmap(android.graphics.Bitmap) OtherDocumentPlaceholderDrawable(org.telegram.ui.Components.OtherDocumentPlaceholderDrawable) AnimatedFileDrawable(org.telegram.ui.Components.AnimatedFileDrawable) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) GradientDrawable(android.graphics.drawable.GradientDrawable) VideoForwardDrawable(org.telegram.ui.Components.VideoForwardDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) OtherDocumentPlaceholderDrawable(org.telegram.ui.Components.OtherDocumentPlaceholderDrawable) PlayPauseDrawable(org.telegram.ui.Components.PlayPauseDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) Paint(android.graphics.Paint) TextPaint(android.text.TextPaint) SuppressLint(android.annotation.SuppressLint) SecureDocument(org.telegram.messenger.SecureDocument) TLObject(org.telegram.tgnet.TLObject) UserObject(org.telegram.messenger.UserObject) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) DialogObject(org.telegram.messenger.DialogObject) ChatObject(org.telegram.messenger.ChatObject) MessageObject(org.telegram.messenger.MessageObject)

Example 35 with TLObject

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

the class FileRefController method onRequestComplete.

private boolean onRequestComplete(String locationKey, String parentKey, TLObject response, boolean cache, boolean fromCache) {
    boolean found = false;
    String cacheKey = parentKey;
    if (response instanceof TLRPC.TL_account_wallPapers) {
        cacheKey = "wallpaper";
    } else if (response instanceof TLRPC.TL_messages_savedGifs) {
        cacheKey = "gif";
    } else if (response instanceof TLRPC.TL_messages_recentStickers) {
        cacheKey = "recent";
    } else if (response instanceof TLRPC.TL_messages_favedStickers) {
        cacheKey = "fav";
    }
    if (parentKey != null) {
        ArrayList<Requester> arrayList = parentRequester.get(parentKey);
        if (arrayList != null) {
            for (int q = 0, N = arrayList.size(); q < N; q++) {
                Requester requester = arrayList.get(q);
                if (requester.completed) {
                    continue;
                }
                if (onRequestComplete(requester.locationKey, null, response, cache && !found, fromCache)) {
                    found = true;
                }
            }
            if (found) {
                putReponseToCache(cacheKey, response);
            }
            parentRequester.remove(parentKey);
        }
    }
    byte[] result = null;
    TLRPC.InputFileLocation[] locationReplacement = null;
    boolean[] needReplacement = null;
    ArrayList<Requester> arrayList = locationRequester.get(locationKey);
    if (arrayList == null) {
        return found;
    }
    cacheKey = locationKey;
    for (int q = 0, N = arrayList.size(); q < N; q++) {
        Requester requester = arrayList.get(q);
        if (requester.completed) {
            continue;
        }
        if (requester.location instanceof TLRPC.TL_inputFileLocation || requester.location instanceof TLRPC.TL_inputPeerPhotoFileLocation) {
            locationReplacement = new TLRPC.InputFileLocation[1];
            needReplacement = new boolean[1];
        }
        requester.completed = true;
        if (response instanceof TLRPC.messages_Messages) {
            TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
            if (!res.messages.isEmpty()) {
                for (int i = 0, size3 = res.messages.size(); i < size3; i++) {
                    TLRPC.Message message = res.messages.get(i);
                    if (message.media != null) {
                        if (message.media.document != null) {
                            result = getFileReference(message.media.document, requester.location, needReplacement, locationReplacement);
                        } else if (message.media.game != null) {
                            result = getFileReference(message.media.game.document, requester.location, needReplacement, locationReplacement);
                            if (result == null) {
                                result = getFileReference(message.media.game.photo, requester.location, needReplacement, locationReplacement);
                            }
                        } else if (message.media.photo != null) {
                            result = getFileReference(message.media.photo, requester.location, needReplacement, locationReplacement);
                        } else if (message.media.webpage != null) {
                            result = getFileReference(message.media.webpage, requester.location, needReplacement, locationReplacement);
                        }
                    } else if (message.action instanceof TLRPC.TL_messageActionChatEditPhoto) {
                        result = getFileReference(message.action.photo, requester.location, needReplacement, locationReplacement);
                    }
                    if (result != null) {
                        if (cache) {
                            getMessagesStorage().replaceMessageIfExists(message, res.users, res.chats, false);
                        }
                        break;
                    }
                }
                if (result == null) {
                    getMessagesStorage().replaceMessageIfExists(res.messages.get(0), res.users, res.chats, true);
                    if (BuildVars.DEBUG_VERSION) {
                        FileLog.d("file ref not found in messages, replacing message");
                    }
                }
            }
        } else if (response instanceof TLRPC.TL_help_appUpdate) {
            TLRPC.TL_help_appUpdate appUpdate = (TLRPC.TL_help_appUpdate) response;
            result = getFileReference(appUpdate.document, requester.location, needReplacement, locationReplacement);
            if (result == null) {
                result = getFileReference(appUpdate.sticker, requester.location, needReplacement, locationReplacement);
            }
        } else if (response instanceof TLRPC.WebPage) {
            result = getFileReference((TLRPC.WebPage) response, requester.location, needReplacement, locationReplacement);
        } else if (response instanceof TLRPC.TL_account_wallPapers) {
            TLRPC.TL_account_wallPapers accountWallPapers = (TLRPC.TL_account_wallPapers) response;
            for (int i = 0, size10 = accountWallPapers.wallpapers.size(); i < size10; i++) {
                result = getFileReference(((TLRPC.WallPaper) accountWallPapers.wallpapers.get(i)).document, requester.location, needReplacement, locationReplacement);
                if (result != null) {
                    break;
                }
            }
            if (result != null && cache) {
                getMessagesStorage().putWallpapers(accountWallPapers.wallpapers, 1);
            }
        } else if (response instanceof TLRPC.TL_wallPaper) {
            TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) response;
            result = getFileReference(wallPaper.document, requester.location, needReplacement, locationReplacement);
            if (result != null && cache) {
                ArrayList<TLRPC.WallPaper> wallpapers = new ArrayList<>();
                wallpapers.add(wallPaper);
                getMessagesStorage().putWallpapers(wallpapers, 0);
            }
        } else if (response instanceof TLRPC.TL_theme) {
            TLRPC.TL_theme theme = (TLRPC.TL_theme) response;
            result = getFileReference(theme.document, requester.location, needReplacement, locationReplacement);
            if (result != null && cache) {
                AndroidUtilities.runOnUIThread(() -> Theme.setThemeFileReference(theme));
            }
        } else if (response instanceof TLRPC.Vector) {
            TLRPC.Vector vector = (TLRPC.Vector) response;
            if (!vector.objects.isEmpty()) {
                for (int i = 0, size10 = vector.objects.size(); i < size10; i++) {
                    Object object = vector.objects.get(i);
                    if (object instanceof TLRPC.User) {
                        TLRPC.User user = (TLRPC.User) object;
                        result = getFileReference(user, requester.location, needReplacement, locationReplacement);
                        if (cache && result != null) {
                            ArrayList<TLRPC.User> arrayList1 = new ArrayList<>();
                            arrayList1.add(user);
                            getMessagesStorage().putUsersAndChats(arrayList1, null, true, true);
                            AndroidUtilities.runOnUIThread(() -> getMessagesController().putUser(user, false));
                        }
                    } else if (object instanceof TLRPC.Chat) {
                        TLRPC.Chat chat = (TLRPC.Chat) object;
                        result = getFileReference(chat, requester.location, needReplacement, locationReplacement);
                        if (cache && result != null) {
                            ArrayList<TLRPC.Chat> arrayList1 = new ArrayList<>();
                            arrayList1.add(chat);
                            getMessagesStorage().putUsersAndChats(null, arrayList1, true, true);
                            AndroidUtilities.runOnUIThread(() -> getMessagesController().putChat(chat, false));
                        }
                    }
                    if (result != null) {
                        break;
                    }
                }
            }
        } else if (response instanceof TLRPC.TL_messages_chats) {
            TLRPC.TL_messages_chats res = (TLRPC.TL_messages_chats) response;
            if (!res.chats.isEmpty()) {
                for (int i = 0, size10 = res.chats.size(); i < size10; i++) {
                    TLRPC.Chat chat = res.chats.get(i);
                    result = getFileReference(chat, requester.location, needReplacement, locationReplacement);
                    if (result != null) {
                        if (cache) {
                            ArrayList<TLRPC.Chat> arrayList1 = new ArrayList<>();
                            arrayList1.add(chat);
                            getMessagesStorage().putUsersAndChats(null, arrayList1, true, true);
                            AndroidUtilities.runOnUIThread(() -> getMessagesController().putChat(chat, false));
                        }
                        break;
                    }
                }
            }
        } else if (response instanceof TLRPC.TL_messages_savedGifs) {
            TLRPC.TL_messages_savedGifs savedGifs = (TLRPC.TL_messages_savedGifs) response;
            for (int b = 0, size2 = savedGifs.gifs.size(); b < size2; b++) {
                result = getFileReference(savedGifs.gifs.get(b), requester.location, needReplacement, locationReplacement);
                if (result != null) {
                    break;
                }
            }
            if (cache) {
                getMediaDataController().processLoadedRecentDocuments(MediaDataController.TYPE_IMAGE, savedGifs.gifs, true, 0, true);
            }
        } else if (response instanceof TLRPC.TL_messages_stickerSet) {
            TLRPC.TL_messages_stickerSet stickerSet = (TLRPC.TL_messages_stickerSet) response;
            if (result == null) {
                for (int b = 0, size2 = stickerSet.documents.size(); b < size2; b++) {
                    result = getFileReference(stickerSet.documents.get(b), requester.location, needReplacement, locationReplacement);
                    if (result != null) {
                        break;
                    }
                }
            }
            if (cache) {
                AndroidUtilities.runOnUIThread(() -> getMediaDataController().replaceStickerSet(stickerSet));
            }
        } else if (response instanceof TLRPC.TL_messages_recentStickers) {
            TLRPC.TL_messages_recentStickers recentStickers = (TLRPC.TL_messages_recentStickers) response;
            for (int b = 0, size2 = recentStickers.stickers.size(); b < size2; b++) {
                result = getFileReference(recentStickers.stickers.get(b), requester.location, needReplacement, locationReplacement);
                if (result != null) {
                    break;
                }
            }
            if (cache) {
                getMediaDataController().processLoadedRecentDocuments(MediaDataController.TYPE_IMAGE, recentStickers.stickers, false, 0, true);
            }
        } else if (response instanceof TLRPC.TL_messages_favedStickers) {
            TLRPC.TL_messages_favedStickers favedStickers = (TLRPC.TL_messages_favedStickers) response;
            for (int b = 0, size2 = favedStickers.stickers.size(); b < size2; b++) {
                result = getFileReference(favedStickers.stickers.get(b), requester.location, needReplacement, locationReplacement);
                if (result != null) {
                    break;
                }
            }
            if (cache) {
                getMediaDataController().processLoadedRecentDocuments(MediaDataController.TYPE_FAVE, favedStickers.stickers, false, 0, true);
            }
        } else if (response instanceof TLRPC.photos_Photos) {
            TLRPC.photos_Photos res = (TLRPC.photos_Photos) response;
            for (int b = 0, size = res.photos.size(); b < size; b++) {
                result = getFileReference(res.photos.get(b), requester.location, needReplacement, locationReplacement);
                if (result != null) {
                    break;
                }
            }
        }
        if (result != null) {
            if (onUpdateObjectReference(requester, result, locationReplacement != null ? locationReplacement[0] : null, fromCache)) {
                found = true;
            }
        } else {
            sendErrorToObject(requester.args, 1);
        }
    }
    locationRequester.remove(locationKey);
    if (found) {
        putReponseToCache(cacheKey, response);
    }
    return found;
}
Also used : ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) TLObject(org.telegram.tgnet.TLObject)

Aggregations

TLObject (org.telegram.tgnet.TLObject)85 TLRPC (org.telegram.tgnet.TLRPC)79 Paint (android.graphics.Paint)36 ArrayList (java.util.ArrayList)36 TextPaint (android.text.TextPaint)25 SuppressLint (android.annotation.SuppressLint)22 ConnectionsManager (org.telegram.tgnet.ConnectionsManager)22 File (java.io.File)21 HashMap (java.util.HashMap)20 Context (android.content.Context)19 Build (android.os.Build)19 TextUtils (android.text.TextUtils)19 MessageObject (org.telegram.messenger.MessageObject)19 Theme (org.telegram.ui.ActionBar.Theme)19 BaseFragment (org.telegram.ui.ActionBar.BaseFragment)18 LongSparseArray (androidx.collection.LongSparseArray)17 AlertDialog (org.telegram.ui.ActionBar.AlertDialog)17 Bundle (android.os.Bundle)16 SpannableStringBuilder (android.text.SpannableStringBuilder)16 ChatObject (org.telegram.messenger.ChatObject)16