Search in sources :

Example 1 with AlertDialog

use of org.telegram.ui.ActionBar.AlertDialog in project Telegram-FOSS by Telegram-FOSS-Team.

the class SecretChatHelper method startSecretChat.

public void startSecretChat(Context context, TLRPC.User user) {
    if (user == null || context == null) {
        return;
    }
    startingSecretChat = true;
    AlertDialog progressDialog = new AlertDialog(context, 3);
    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = getMessagesStorage().getLastSecretVersion();
    int reqId = getConnectionsManager().sendRequest(req, (response, error) -> {
        if (error == null) {
            TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response;
            if (response instanceof TLRPC.TL_messages_dhConfig) {
                if (!Utilities.isGoodPrime(res.p, res.g)) {
                    AndroidUtilities.runOnUIThread(() -> {
                        try {
                            if (!((Activity) context).isFinishing()) {
                                progressDialog.dismiss();
                            }
                        } catch (Exception e) {
                            FileLog.e(e);
                        }
                    });
                    return;
                }
                getMessagesStorage().setSecretPBytes(res.p);
                getMessagesStorage().setSecretG(res.g);
                getMessagesStorage().setLastSecretVersion(res.version);
                getMessagesStorage().saveSecretParams(getMessagesStorage().getLastSecretVersion(), getMessagesStorage().getSecretG(), getMessagesStorage().getSecretPBytes());
            }
            byte[] salt = new byte[256];
            for (int a = 0; a < 256; a++) {
                salt[a] = (byte) ((byte) (Utilities.random.nextDouble() * 256) ^ res.random[a]);
            }
            BigInteger i_g_a = BigInteger.valueOf(getMessagesStorage().getSecretG());
            i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, getMessagesStorage().getSecretPBytes()));
            byte[] g_a = i_g_a.toByteArray();
            if (g_a.length > 256) {
                byte[] correctedAuth = new byte[256];
                System.arraycopy(g_a, 1, correctedAuth, 0, 256);
                g_a = correctedAuth;
            }
            TLRPC.TL_messages_requestEncryption req2 = new TLRPC.TL_messages_requestEncryption();
            req2.g_a = g_a;
            req2.user_id = getMessagesController().getInputUser(user);
            req2.random_id = Utilities.random.nextInt();
            getConnectionsManager().sendRequest(req2, (response1, error1) -> {
                if (error1 == null) {
                    AndroidUtilities.runOnUIThread(() -> {
                        startingSecretChat = false;
                        if (!((Activity) context).isFinishing()) {
                            try {
                                progressDialog.dismiss();
                            } catch (Exception e) {
                                FileLog.e(e);
                            }
                        }
                        TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) response1;
                        chat.user_id = chat.participant_id;
                        chat.seq_in = -2;
                        chat.seq_out = 1;
                        chat.a_or_b = salt;
                        getMessagesController().putEncryptedChat(chat, false);
                        TLRPC.Dialog dialog = new TLRPC.TL_dialog();
                        dialog.id = DialogObject.makeEncryptedDialogId(chat.id);
                        dialog.unread_count = 0;
                        dialog.top_message = 0;
                        dialog.last_message_date = getConnectionsManager().getCurrentTime();
                        getMessagesController().dialogs_dict.put(dialog.id, dialog);
                        getMessagesController().allDialogs.add(dialog);
                        getMessagesController().sortDialogs(null);
                        getMessagesStorage().putEncryptedChat(chat, user, dialog);
                        getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload);
                        getNotificationCenter().postNotificationName(NotificationCenter.encryptedChatCreated, chat);
                        Utilities.stageQueue.postRunnable(() -> {
                            if (!delayedEncryptedChatUpdates.isEmpty()) {
                                getMessagesController().processUpdateArray(delayedEncryptedChatUpdates, null, null, false, 0);
                                delayedEncryptedChatUpdates.clear();
                            }
                        });
                    });
                } else {
                    delayedEncryptedChatUpdates.clear();
                    AndroidUtilities.runOnUIThread(() -> {
                        if (!((Activity) context).isFinishing()) {
                            startingSecretChat = false;
                            try {
                                progressDialog.dismiss();
                            } catch (Exception e) {
                                FileLog.e(e);
                            }
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                            builder.setMessage(LocaleController.getString("CreateEncryptedChatError", R.string.CreateEncryptedChatError));
                            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                            builder.show().setCanceledOnTouchOutside(true);
                        }
                    });
                }
            }, ConnectionsManager.RequestFlagFailOnServerErrors);
        } else {
            delayedEncryptedChatUpdates.clear();
            AndroidUtilities.runOnUIThread(() -> {
                startingSecretChat = false;
                if (!((Activity) context).isFinishing()) {
                    try {
                        progressDialog.dismiss();
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
            });
        }
    }, ConnectionsManager.RequestFlagFailOnServerErrors);
    progressDialog.setOnCancelListener(dialog -> getConnectionsManager().cancelRequest(reqId, true));
    try {
        progressDialog.show();
    } catch (Exception e) {
    // don't promt
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) TLRPC(org.telegram.tgnet.TLRPC) BigInteger(java.math.BigInteger)

Example 2 with AlertDialog

use of org.telegram.ui.ActionBar.AlertDialog in project Telegram-FOSS by Telegram-FOSS-Team.

the class AlertsCreator method showSecretLocationAlert.

public static AlertDialog showSecretLocationAlert(Context context, int currentAccount, final Runnable onSelectRunnable, boolean inChat, Theme.ResourcesProvider resourcesProvider) {
    ArrayList<String> arrayList = new ArrayList<>();
    ArrayList<Integer> types = new ArrayList<>();
    int providers = MessagesController.getInstance(currentAccount).availableMapProviders;
    if ((providers & 1) != 0) {
        arrayList.add(LocaleController.getString("MapPreviewProviderTelegram", R.string.MapPreviewProviderTelegram));
        types.add(0);
    }
    if ((providers & 2) != 0) {
        arrayList.add(LocaleController.getString("MapPreviewProviderGoogle", R.string.MapPreviewProviderGoogle));
        types.add(1);
    }
    if ((providers & 4) != 0) {
        arrayList.add(LocaleController.getString("MapPreviewProviderYandex", R.string.MapPreviewProviderYandex));
        types.add(3);
    }
    arrayList.add(LocaleController.getString("MapPreviewProviderNobody", R.string.MapPreviewProviderNobody));
    types.add(2);
    AlertDialog.Builder builder = new AlertDialog.Builder(context, resourcesProvider);
    builder.setTitle(LocaleController.getString("MapPreviewProviderTitle", R.string.MapPreviewProviderTitle));
    final LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    builder.setView(linearLayout);
    for (int a = 0; a < arrayList.size(); a++) {
        RadioColorCell cell = new RadioColorCell(context, resourcesProvider);
        cell.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
        cell.setTag(a);
        cell.setCheckColor(Theme.getColor(Theme.key_radioBackground), Theme.getColor(Theme.key_dialogRadioBackgroundChecked));
        cell.setTextAndValue(arrayList.get(a), SharedConfig.mapPreviewType == types.get(a));
        linearLayout.addView(cell);
        cell.setOnClickListener(v -> {
            Integer which = (Integer) v.getTag();
            SharedConfig.setSecretMapPreviewType(types.get(which));
            if (onSelectRunnable != null) {
                onSelectRunnable.run();
            }
            builder.getDismissRunnable().run();
        });
    }
    if (!inChat) {
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
    }
    AlertDialog dialog = builder.show();
    if (inChat) {
        dialog.setCanceledOnTouchOutside(false);
    }
    return dialog;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) SpannableString(android.text.SpannableString) RadioColorCell(org.telegram.ui.Cells.RadioColorCell) SuppressLint(android.annotation.SuppressLint) LinearLayout(android.widget.LinearLayout)

Example 3 with AlertDialog

use of org.telegram.ui.ActionBar.AlertDialog in project Telegram-FOSS by Telegram-FOSS-Team.

the class AlertsCreator method createDeleteMessagesAlert.

public static void createDeleteMessagesAlert(BaseFragment fragment, TLRPC.User user, TLRPC.Chat chat, TLRPC.EncryptedChat encryptedChat, TLRPC.ChatFull chatInfo, long mergeDialogId, MessageObject selectedMessage, SparseArray<MessageObject>[] selectedMessages, MessageObject.GroupedMessages selectedGroup, boolean scheduled, int loadParticipant, Runnable onDelete, Runnable hideDim, Theme.ResourcesProvider resourcesProvider) {
    if (fragment == null || user == null && chat == null && encryptedChat == null) {
        return;
    }
    Activity activity = fragment.getParentActivity();
    if (activity == null) {
        return;
    }
    int currentAccount = fragment.getCurrentAccount();
    AlertDialog.Builder builder = new AlertDialog.Builder(activity, resourcesProvider);
    builder.setDimEnabled(hideDim == null);
    int count;
    if (selectedGroup != null) {
        count = selectedGroup.messages.size();
    } else if (selectedMessage != null) {
        count = 1;
    } else {
        count = selectedMessages[0].size() + selectedMessages[1].size();
    }
    long dialogId;
    if (encryptedChat != null) {
        dialogId = DialogObject.makeEncryptedDialogId(encryptedChat.id);
    } else if (user != null) {
        dialogId = user.id;
    } else {
        dialogId = -chat.id;
    }
    int currentDate = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
    boolean hasNonDiceMessages = false;
    if (selectedMessage != null) {
        hasNonDiceMessages = !selectedMessage.isDice() || Math.abs(currentDate - selectedMessage.messageOwner.date) > 24 * 60 * 60;
    } else {
        for (int a = 0; a < 2; a++) {
            for (int b = 0; b < selectedMessages[a].size(); b++) {
                MessageObject msg = selectedMessages[a].valueAt(b);
                if (!msg.isDice() || Math.abs(currentDate - msg.messageOwner.date) > 24 * 60 * 60) {
                    hasNonDiceMessages = true;
                    break;
                }
            }
        }
    }
    final boolean[] checks = new boolean[3];
    final boolean[] deleteForAll = new boolean[1];
    TLRPC.User actionUser = null;
    TLRPC.Chat actionChat = null;
    boolean canRevokeInbox = user != null && MessagesController.getInstance(currentAccount).canRevokePmInbox;
    int revokeTimeLimit;
    if (user != null) {
        revokeTimeLimit = MessagesController.getInstance(currentAccount).revokeTimePmLimit;
    } else {
        revokeTimeLimit = MessagesController.getInstance(currentAccount).revokeTimeLimit;
    }
    boolean hasDeleteForAllCheck = false;
    boolean hasNotOut = false;
    int myMessagesCount = 0;
    boolean canDeleteInbox = encryptedChat == null && user != null && canRevokeInbox && revokeTimeLimit == 0x7fffffff;
    if (chat != null && chat.megagroup && !scheduled) {
        boolean canBan = ChatObject.canBlockUsers(chat);
        if (selectedMessage != null) {
            if (selectedMessage.messageOwner.action == null || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionEmpty || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByLink || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) {
                if (selectedMessage.messageOwner.from_id.user_id != 0) {
                    actionUser = MessagesController.getInstance(currentAccount).getUser(selectedMessage.messageOwner.from_id.user_id);
                } else if (selectedMessage.messageOwner.from_id.channel_id != 0) {
                    actionChat = MessagesController.getInstance(currentAccount).getChat(selectedMessage.messageOwner.from_id.channel_id);
                } else if (selectedMessage.messageOwner.from_id.chat_id != 0) {
                    actionChat = MessagesController.getInstance(currentAccount).getChat(selectedMessage.messageOwner.from_id.chat_id);
                }
            }
            boolean hasOutgoing = !selectedMessage.isSendError() && selectedMessage.getDialogId() == mergeDialogId && (selectedMessage.messageOwner.action == null || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) && selectedMessage.isOut() && (currentDate - selectedMessage.messageOwner.date) <= revokeTimeLimit;
            if (hasOutgoing) {
                myMessagesCount++;
            }
        } else {
            long from_id = -1;
            for (int a = 1; a >= 0; a--) {
                long channelId = 0;
                for (int b = 0; b < selectedMessages[a].size(); b++) {
                    MessageObject msg = selectedMessages[a].valueAt(b);
                    if (from_id == -1) {
                        from_id = msg.getFromChatId();
                    }
                    if (from_id < 0 || from_id != msg.getSenderId()) {
                        from_id = -2;
                        break;
                    }
                }
                if (from_id == -2) {
                    break;
                }
            }
            for (int a = 1; a >= 0; a--) {
                for (int b = 0; b < selectedMessages[a].size(); b++) {
                    MessageObject msg = selectedMessages[a].valueAt(b);
                    if (a == 1) {
                        if (msg.isOut() && msg.messageOwner.action == null) {
                            if ((currentDate - msg.messageOwner.date) <= revokeTimeLimit) {
                                myMessagesCount++;
                            }
                        }
                    }
                }
            }
            if (from_id != -1) {
                actionUser = MessagesController.getInstance(currentAccount).getUser(from_id);
            }
        }
        if ((actionUser != null && actionUser.id != UserConfig.getInstance(currentAccount).getClientUserId()) || (actionChat != null && !ChatObject.hasAdminRights(actionChat))) {
            if (loadParticipant == 1 && !chat.creator && actionUser != null) {
                final AlertDialog[] progressDialog = new AlertDialog[] { new AlertDialog(activity, 3) };
                TLRPC.TL_channels_getParticipant req = new TLRPC.TL_channels_getParticipant();
                req.channel = MessagesController.getInputChannel(chat);
                req.participant = MessagesController.getInputPeer(actionUser);
                int requestId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    try {
                        progressDialog[0].dismiss();
                    } catch (Throwable ignore) {
                    }
                    progressDialog[0] = null;
                    int loadType = 2;
                    if (response != null) {
                        TLRPC.TL_channels_channelParticipant participant = (TLRPC.TL_channels_channelParticipant) response;
                        if (!(participant.participant instanceof TLRPC.TL_channelParticipantAdmin || participant.participant instanceof TLRPC.TL_channelParticipantCreator)) {
                            loadType = 0;
                        }
                    } else if (error != null && "USER_NOT_PARTICIPANT".equals(error.text)) {
                        loadType = 0;
                    }
                    createDeleteMessagesAlert(fragment, user, chat, encryptedChat, chatInfo, mergeDialogId, selectedMessage, selectedMessages, selectedGroup, scheduled, loadType, onDelete, hideDim, resourcesProvider);
                }));
                AndroidUtilities.runOnUIThread(() -> {
                    if (progressDialog[0] == null) {
                        return;
                    }
                    progressDialog[0].setOnCancelListener(dialog -> ConnectionsManager.getInstance(currentAccount).cancelRequest(requestId, true));
                    fragment.showDialog(progressDialog[0]);
                }, 1000);
                return;
            }
            FrameLayout frameLayout = new FrameLayout(activity);
            int num = 0;
            String name = actionUser != null ? ContactsController.formatName(actionUser.first_name, actionUser.last_name) : actionChat.title;
            for (int a = 0; a < 3; a++) {
                if ((loadParticipant == 2 || !canBan) && a == 0) {
                    continue;
                }
                CheckBoxCell cell = new CheckBoxCell(activity, 1, resourcesProvider);
                cell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
                cell.setTag(a);
                if (a == 0) {
                    cell.setText(LocaleController.getString("DeleteBanUser", R.string.DeleteBanUser), "", false, false);
                } else if (a == 1) {
                    cell.setText(LocaleController.getString("DeleteReportSpam", R.string.DeleteReportSpam), "", false, false);
                } else {
                    cell.setText(LocaleController.formatString("DeleteAllFrom", R.string.DeleteAllFrom, name), "", false, false);
                }
                cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0, LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0);
                frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.TOP | Gravity.LEFT, 0, 48 * num, 0, 0));
                cell.setOnClickListener(v -> {
                    if (!v.isEnabled()) {
                        return;
                    }
                    CheckBoxCell cell13 = (CheckBoxCell) v;
                    Integer num1 = (Integer) cell13.getTag();
                    checks[num1] = !checks[num1];
                    cell13.setChecked(checks[num1], true);
                });
                num++;
            }
            builder.setView(frameLayout);
        } else if (!hasNotOut && myMessagesCount > 0 && hasNonDiceMessages) {
            hasDeleteForAllCheck = true;
            FrameLayout frameLayout = new FrameLayout(activity);
            CheckBoxCell cell = new CheckBoxCell(activity, 1, resourcesProvider);
            cell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
            if (chat != null && hasNotOut) {
                cell.setText(LocaleController.getString("DeleteForAll", R.string.DeleteForAll), "", false, false);
            } else {
                cell.setText(LocaleController.getString("DeleteMessagesOption", R.string.DeleteMessagesOption), "", false, false);
            }
            cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0, LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0);
            frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0));
            cell.setOnClickListener(v -> {
                CheckBoxCell cell12 = (CheckBoxCell) v;
                deleteForAll[0] = !deleteForAll[0];
                cell12.setChecked(deleteForAll[0], true);
            });
            builder.setView(frameLayout);
            builder.setCustomViewOffset(9);
        } else {
            actionUser = null;
        }
    } else if (!scheduled && !ChatObject.isChannel(chat) && encryptedChat == null) {
        if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId() && (!user.bot || user.support) || chat != null) {
            if (selectedMessage != null) {
                boolean hasOutgoing = !selectedMessage.isSendError() && (selectedMessage.messageOwner.action == null || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionEmpty || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionPhoneCall || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) && (selectedMessage.isOut() || canRevokeInbox || ChatObject.hasAdminRights(chat)) && (currentDate - selectedMessage.messageOwner.date) <= revokeTimeLimit;
                if (hasOutgoing) {
                    myMessagesCount++;
                }
                hasNotOut = !selectedMessage.isOut();
            } else {
                for (int a = 1; a >= 0; a--) {
                    for (int b = 0; b < selectedMessages[a].size(); b++) {
                        MessageObject msg = selectedMessages[a].valueAt(b);
                        if (!(msg.messageOwner.action == null || msg.messageOwner.action instanceof TLRPC.TL_messageActionEmpty || msg.messageOwner.action instanceof TLRPC.TL_messageActionPhoneCall || msg.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage || msg.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached)) {
                            continue;
                        }
                        if ((msg.isOut() || canRevokeInbox) || chat != null && ChatObject.canBlockUsers(chat)) {
                            if ((currentDate - msg.messageOwner.date) <= revokeTimeLimit) {
                                myMessagesCount++;
                                if (!hasNotOut && !msg.isOut()) {
                                    hasNotOut = true;
                                }
                            }
                        }
                    }
                }
            }
        }
        if (myMessagesCount > 0 && hasNonDiceMessages && (user == null || !UserObject.isDeleted(user))) {
            hasDeleteForAllCheck = true;
            FrameLayout frameLayout = new FrameLayout(activity);
            CheckBoxCell cell = new CheckBoxCell(activity, 1, resourcesProvider);
            cell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
            if (canDeleteInbox) {
                cell.setText(LocaleController.formatString("DeleteMessagesOptionAlso", R.string.DeleteMessagesOptionAlso, UserObject.getFirstName(user)), "", false, false);
            } else if (chat != null && (hasNotOut || myMessagesCount == count)) {
                cell.setText(LocaleController.getString("DeleteForAll", R.string.DeleteForAll), "", false, false);
            } else {
                cell.setText(LocaleController.getString("DeleteMessagesOption", R.string.DeleteMessagesOption), "", false, false);
            }
            cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0, LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0);
            frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0));
            cell.setOnClickListener(v -> {
                CheckBoxCell cell1 = (CheckBoxCell) v;
                deleteForAll[0] = !deleteForAll[0];
                cell1.setChecked(deleteForAll[0], true);
            });
            builder.setView(frameLayout);
            builder.setCustomViewOffset(9);
        }
    }
    final TLRPC.User userFinal = actionUser;
    final TLRPC.Chat chatFinal = actionChat;
    builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface, i) -> {
        ArrayList<Integer> ids = null;
        if (selectedMessage != null) {
            ids = new ArrayList<>();
            ArrayList<Long> random_ids = null;
            if (selectedGroup != null) {
                for (int a = 0; a < selectedGroup.messages.size(); a++) {
                    MessageObject messageObject = selectedGroup.messages.get(a);
                    ids.add(messageObject.getId());
                    if (encryptedChat != null && messageObject.messageOwner.random_id != 0 && messageObject.type != 10) {
                        if (random_ids == null) {
                            random_ids = new ArrayList<>();
                        }
                        random_ids.add(messageObject.messageOwner.random_id);
                    }
                }
            } else {
                ids.add(selectedMessage.getId());
                if (encryptedChat != null && selectedMessage.messageOwner.random_id != 0 && selectedMessage.type != 10) {
                    random_ids = new ArrayList<>();
                    random_ids.add(selectedMessage.messageOwner.random_id);
                }
            }
            MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, dialogId, deleteForAll[0], scheduled);
        } else {
            for (int a = 1; a >= 0; a--) {
                ids = new ArrayList<>();
                for (int b = 0; b < selectedMessages[a].size(); b++) {
                    ids.add(selectedMessages[a].keyAt(b));
                }
                ArrayList<Long> random_ids = null;
                long channelId = 0;
                if (!ids.isEmpty()) {
                    MessageObject msg = selectedMessages[a].get(ids.get(0));
                    if (msg.messageOwner.peer_id.channel_id != 0) {
                        channelId = msg.messageOwner.peer_id.channel_id;
                    }
                }
                if (encryptedChat != null) {
                    random_ids = new ArrayList<>();
                    for (int b = 0; b < selectedMessages[a].size(); b++) {
                        MessageObject msg = selectedMessages[a].valueAt(b);
                        if (msg.messageOwner.random_id != 0 && msg.type != 10) {
                            random_ids.add(msg.messageOwner.random_id);
                        }
                    }
                }
                MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, dialogId, deleteForAll[0], scheduled);
                selectedMessages[a].clear();
            }
        }
        if (userFinal != null || chatFinal != null) {
            if (checks[0]) {
                MessagesController.getInstance(currentAccount).deleteParticipantFromChat(chat.id, userFinal, chatFinal, chatInfo, false, false);
            }
            if (checks[1]) {
                TLRPC.TL_channels_reportSpam req = new TLRPC.TL_channels_reportSpam();
                req.channel = MessagesController.getInputChannel(chat);
                if (userFinal != null) {
                    req.participant = MessagesController.getInputPeer(userFinal);
                } else {
                    req.participant = MessagesController.getInputPeer(chatFinal);
                }
                req.id = ids;
                ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
                });
            }
            if (checks[2]) {
                MessagesController.getInstance(currentAccount).deleteUserChannelHistory(chat, userFinal, chatFinal, 0);
            }
        }
        if (onDelete != null) {
            onDelete.run();
        }
    });
    if (count == 1) {
        builder.setTitle(LocaleController.getString("DeleteSingleMessagesTitle", R.string.DeleteSingleMessagesTitle));
    } else {
        builder.setTitle(LocaleController.formatString("DeleteMessagesTitle", R.string.DeleteMessagesTitle, LocaleController.formatPluralString("messages", count)));
    }
    if (chat != null && hasNotOut) {
        if (hasDeleteForAllCheck && myMessagesCount != count) {
            builder.setMessage(LocaleController.formatString("DeleteMessagesTextGroupPart", R.string.DeleteMessagesTextGroupPart, LocaleController.formatPluralString("messages", myMessagesCount)));
        } else if (count == 1) {
            builder.setMessage(LocaleController.getString("AreYouSureDeleteSingleMessage", R.string.AreYouSureDeleteSingleMessage));
        } else {
            builder.setMessage(LocaleController.getString("AreYouSureDeleteFewMessages", R.string.AreYouSureDeleteFewMessages));
        }
    } else if (hasDeleteForAllCheck && !canDeleteInbox && myMessagesCount != count) {
        if (chat != null) {
            builder.setMessage(LocaleController.formatString("DeleteMessagesTextGroup", R.string.DeleteMessagesTextGroup, LocaleController.formatPluralString("messages", myMessagesCount)));
        } else {
            builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("DeleteMessagesText", R.string.DeleteMessagesText, LocaleController.formatPluralString("messages", myMessagesCount), UserObject.getFirstName(user))));
        }
    } else {
        if (chat != null && chat.megagroup && !scheduled) {
            if (count == 1) {
                builder.setMessage(LocaleController.getString("AreYouSureDeleteSingleMessageMega", R.string.AreYouSureDeleteSingleMessageMega));
            } else {
                builder.setMessage(LocaleController.getString("AreYouSureDeleteFewMessagesMega", R.string.AreYouSureDeleteFewMessagesMega));
            }
        } else {
            if (count == 1) {
                builder.setMessage(LocaleController.getString("AreYouSureDeleteSingleMessage", R.string.AreYouSureDeleteSingleMessage));
            } else {
                builder.setMessage(LocaleController.getString("AreYouSureDeleteFewMessages", R.string.AreYouSureDeleteFewMessages));
            }
        }
    }
    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
    builder.setOnPreDismissListener(di -> {
        if (hideDim != null) {
            hideDim.run();
        }
    });
    AlertDialog dialog = builder.create();
    fragment.showDialog(dialog);
    TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    if (button != null) {
        button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Arrays(java.util.Arrays) Bundle(android.os.Bundle) SvgHelper(org.telegram.messenger.SvgHelper) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) Drawable(android.graphics.drawable.Drawable) Manifest(android.Manifest) NotificationsController(org.telegram.messenger.NotificationsController) CacheControlActivity(org.telegram.ui.CacheControlActivity) NotificationCenter(org.telegram.messenger.NotificationCenter) Outline(android.graphics.Outline) HapticFeedbackConstants(android.view.HapticFeedbackConstants) CountDownLatch(java.util.concurrent.CountDownLatch) LaunchActivity(org.telegram.ui.LaunchActivity) Html(android.text.Html) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) InputFilter(android.text.InputFilter) TextWatcher(android.text.TextWatcher) ChatActivity(org.telegram.ui.ChatActivity) Dialog(android.app.Dialog) Editable(android.text.Editable) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) ThemePreviewActivity(org.telegram.ui.ThemePreviewActivity) Calendar(java.util.Calendar) TLRPC(org.telegram.tgnet.TLRPC) GradientDrawable(android.graphics.drawable.GradientDrawable) Toast(android.widget.Toast) Settings(android.provider.Settings) NotificationsCustomSettingsActivity(org.telegram.ui.NotificationsCustomSettingsActivity) URLSpan(android.text.style.URLSpan) SpannableString(android.text.SpannableString) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) TextUtils(android.text.TextUtils) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) VoIPHelper(org.telegram.ui.Components.voip.VoIPHelper) EditText(android.widget.EditText) ProfileNotificationsActivity(org.telegram.ui.ProfileNotificationsActivity) RequiresApi(androidx.annotation.RequiresApi) Rect(android.graphics.Rect) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) PackageManager(android.content.pm.PackageManager) Spannable(android.text.Spannable) WindowManager(android.view.WindowManager) AccountInstance(org.telegram.messenger.AccountInstance) AndroidUtilities(org.telegram.messenger.AndroidUtilities) LanguageSelectActivity(org.telegram.ui.LanguageSelectActivity) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) Locale(java.util.Locale) View(android.view.View) Button(android.widget.Button) TextColorCell(org.telegram.ui.Cells.TextColorCell) Utilities(org.telegram.messenger.Utilities) TooManyCommunitiesActivity(org.telegram.ui.TooManyCommunitiesActivity) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) BitmapDrawable(android.graphics.drawable.BitmapDrawable) PorterDuff(android.graphics.PorterDuff) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) SparseArray(android.util.SparseArray) UserConfig(org.telegram.messenger.UserConfig) List(java.util.List) TextView(android.widget.TextView) SecretChatHelper(org.telegram.messenger.SecretChatHelper) EditorInfo(android.view.inputmethod.EditorInfo) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) Context(android.content.Context) IDN(java.net.IDN) Spanned(android.text.Spanned) KeyEvent(android.view.KeyEvent) Theme(org.telegram.ui.ActionBar.Theme) ViewOutlineProvider(android.view.ViewOutlineProvider) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) NotificationsSettingsActivity(org.telegram.ui.NotificationsSettingsActivity) Build(android.os.Build) SerializedData(org.telegram.tgnet.SerializedData) DialogInterface(android.content.DialogInterface) Browser(org.telegram.messenger.browser.Browser) LoginActivity(org.telegram.ui.LoginActivity) DialogObject(org.telegram.messenger.DialogObject) FileLog(org.telegram.messenger.FileLog) AccountSelectCell(org.telegram.ui.Cells.AccountSelectCell) MessagesController(org.telegram.messenger.MessagesController) Color(android.graphics.Color) Base64(android.util.Base64) RadioColorCell(org.telegram.ui.Cells.RadioColorCell) Vibrator(android.os.Vibrator) Activity(android.app.Activity) SpannableStringBuilder(android.text.SpannableStringBuilder) CacheControlActivity(org.telegram.ui.CacheControlActivity) LaunchActivity(org.telegram.ui.LaunchActivity) ChatActivity(org.telegram.ui.ChatActivity) ThemePreviewActivity(org.telegram.ui.ThemePreviewActivity) NotificationsCustomSettingsActivity(org.telegram.ui.NotificationsCustomSettingsActivity) ProfileNotificationsActivity(org.telegram.ui.ProfileNotificationsActivity) LanguageSelectActivity(org.telegram.ui.LanguageSelectActivity) TooManyCommunitiesActivity(org.telegram.ui.TooManyCommunitiesActivity) NotificationsSettingsActivity(org.telegram.ui.NotificationsSettingsActivity) LoginActivity(org.telegram.ui.LoginActivity) Activity(android.app.Activity) SpannableString(android.text.SpannableString) TLRPC(org.telegram.tgnet.TLRPC) TextView(android.widget.TextView) SuppressLint(android.annotation.SuppressLint) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) FrameLayout(android.widget.FrameLayout) MessageObject(org.telegram.messenger.MessageObject)

Example 4 with AlertDialog

use of org.telegram.ui.ActionBar.AlertDialog in project Telegram-FOSS by Telegram-FOSS-Team.

the class AlertsCreator method performAskAQuestion.

private static void performAskAQuestion(BaseFragment fragment) {
    int currentAccount = fragment.getCurrentAccount();
    final SharedPreferences preferences = MessagesController.getMainSettings(currentAccount);
    long uid = AndroidUtilities.getPrefIntOrLong(preferences, "support_id2", 0);
    TLRPC.User supportUser = null;
    if (uid != 0) {
        supportUser = MessagesController.getInstance(currentAccount).getUser(uid);
        if (supportUser == null) {
            String userString = preferences.getString("support_user", null);
            if (userString != null) {
                try {
                    byte[] datacentersBytes = Base64.decode(userString, Base64.DEFAULT);
                    if (datacentersBytes != null) {
                        SerializedData data = new SerializedData(datacentersBytes);
                        supportUser = TLRPC.User.TLdeserialize(data, data.readInt32(false), false);
                        if (supportUser != null && supportUser.id == 333000) {
                            supportUser = null;
                        }
                        data.cleanup();
                    }
                } catch (Exception e) {
                    FileLog.e(e);
                    supportUser = null;
                }
            }
        }
    }
    if (supportUser == null) {
        final AlertDialog progressDialog = new AlertDialog(fragment.getParentActivity(), 3);
        progressDialog.setCanCacnel(false);
        progressDialog.show();
        TLRPC.TL_help_getSupport req = new TLRPC.TL_help_getSupport();
        ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
            if (error == null) {
                final TLRPC.TL_help_support res = (TLRPC.TL_help_support) response;
                AndroidUtilities.runOnUIThread(() -> {
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putLong("support_id2", res.user.id);
                    SerializedData data = new SerializedData();
                    res.user.serializeToStream(data);
                    editor.putString("support_user", Base64.encodeToString(data.toByteArray(), Base64.DEFAULT));
                    editor.commit();
                    data.cleanup();
                    try {
                        progressDialog.dismiss();
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                    ArrayList<TLRPC.User> users = new ArrayList<>();
                    users.add(res.user);
                    MessagesStorage.getInstance(currentAccount).putUsersAndChats(users, null, true, true);
                    MessagesController.getInstance(currentAccount).putUser(res.user, false);
                    Bundle args = new Bundle();
                    args.putLong("user_id", res.user.id);
                    fragment.presentFragment(new ChatActivity(args));
                });
            } else {
                AndroidUtilities.runOnUIThread(() -> {
                    try {
                        progressDialog.dismiss();
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                });
            }
        });
    } else {
        MessagesController.getInstance(currentAccount).putUser(supportUser, true);
        Bundle args = new Bundle();
        args.putLong("user_id", supportUser.id);
        fragment.presentFragment(new ChatActivity(args));
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ChatActivity(org.telegram.ui.ChatActivity) SharedPreferences(android.content.SharedPreferences) Bundle(android.os.Bundle) ArrayList(java.util.ArrayList) SerializedData(org.telegram.tgnet.SerializedData) SpannableString(android.text.SpannableString) SuppressLint(android.annotation.SuppressLint) TLRPC(org.telegram.tgnet.TLRPC)

Example 5 with AlertDialog

use of org.telegram.ui.ActionBar.AlertDialog in project Telegram-FOSS by Telegram-FOSS-Team.

the class AlertsCreator method showBlockReportSpamReplyAlert.

public static void showBlockReportSpamReplyAlert(ChatActivity fragment, MessageObject messageObject, long peerId, Theme.ResourcesProvider resourcesProvider, Runnable hideDim) {
    if (fragment == null || fragment.getParentActivity() == null || messageObject == null) {
        return;
    }
    AccountInstance accountInstance = fragment.getAccountInstance();
    TLRPC.User user = peerId > 0 ? accountInstance.getMessagesController().getUser(peerId) : null;
    TLRPC.Chat chat = peerId < 0 ? accountInstance.getMessagesController().getChat(-peerId) : null;
    if (user == null && chat == null) {
        return;
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity(), resourcesProvider);
    builder.setDimEnabled(hideDim == null);
    builder.setOnPreDismissListener(di -> {
        if (hideDim != null) {
            hideDim.run();
        }
    });
    builder.setTitle(LocaleController.getString("BlockUser", R.string.BlockUser));
    if (user != null) {
        builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("BlockUserReplyAlert", R.string.BlockUserReplyAlert, UserObject.getFirstName(user))));
    } else {
        builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("BlockUserReplyAlert", R.string.BlockUserReplyAlert, chat.title)));
    }
    CheckBoxCell[] cells = new CheckBoxCell[1];
    LinearLayout linearLayout = new LinearLayout(fragment.getParentActivity());
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    cells[0] = new CheckBoxCell(fragment.getParentActivity(), 1, resourcesProvider);
    cells[0].setBackgroundDrawable(Theme.getSelectorDrawable(false));
    cells[0].setTag(0);
    cells[0].setText(LocaleController.getString("DeleteReportSpam", R.string.DeleteReportSpam), "", true, false);
    cells[0].setPadding(LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0, LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0);
    linearLayout.addView(cells[0], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    cells[0].setOnClickListener(v -> {
        Integer num = (Integer) v.getTag();
        cells[num].setChecked(!cells[num].isChecked(), true);
    });
    builder.setCustomViewOffset(12);
    builder.setView(linearLayout);
    builder.setPositiveButton(LocaleController.getString("BlockAndDeleteReplies", R.string.BlockAndDeleteReplies), (dialogInterface, i) -> {
        if (user != null) {
            accountInstance.getMessagesStorage().deleteUserChatHistory(fragment.getDialogId(), user.id);
        } else {
            accountInstance.getMessagesStorage().deleteUserChatHistory(fragment.getDialogId(), -chat.id);
        }
        TLRPC.TL_contacts_blockFromReplies request = new TLRPC.TL_contacts_blockFromReplies();
        request.msg_id = messageObject.getId();
        request.delete_message = true;
        request.delete_history = true;
        if (cells[0].isChecked()) {
            request.report_spam = true;
            if (fragment.getParentActivity() != null) {
                if (fragment instanceof ChatActivity) {
                    fragment.getUndoView().showWithAction(0, UndoView.ACTION_REPORT_SENT, null);
                } else if (fragment != null) {
                    BulletinFactory.of(fragment).createReportSent(resourcesProvider).show();
                } else {
                    Toast.makeText(fragment.getParentActivity(), LocaleController.getString("ReportChatSent", R.string.ReportChatSent), Toast.LENGTH_SHORT).show();
                }
            }
        }
        accountInstance.getConnectionsManager().sendRequest(request, (response, error) -> {
            if (response instanceof TLRPC.Updates) {
                accountInstance.getMessagesController().processUpdates((TLRPC.Updates) response, false);
            }
        });
    });
    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
    AlertDialog dialog = builder.create();
    fragment.showDialog(dialog);
    TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    if (button != null) {
        button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ChatActivity(org.telegram.ui.ChatActivity) SpannableStringBuilder(android.text.SpannableStringBuilder) TLRPC(org.telegram.tgnet.TLRPC) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) AccountInstance(org.telegram.messenger.AccountInstance) TextView(android.widget.TextView) LinearLayout(android.widget.LinearLayout)

Aggregations

AlertDialog (org.telegram.ui.ActionBar.AlertDialog)101 TLRPC (org.telegram.tgnet.TLRPC)71 TextView (android.widget.TextView)63 FrameLayout (android.widget.FrameLayout)47 ArrayList (java.util.ArrayList)47 Context (android.content.Context)45 View (android.view.View)44 AndroidUtilities (org.telegram.messenger.AndroidUtilities)41 LocaleController (org.telegram.messenger.LocaleController)41 Theme (org.telegram.ui.ActionBar.Theme)41 R (org.telegram.messenger.R)40 BaseFragment (org.telegram.ui.ActionBar.BaseFragment)40 LinearLayout (android.widget.LinearLayout)38 Paint (android.graphics.Paint)37 MessagesController (org.telegram.messenger.MessagesController)37 SuppressLint (android.annotation.SuppressLint)36 TextUtils (android.text.TextUtils)36 FileLog (org.telegram.messenger.FileLog)36 Build (android.os.Build)34 Gravity (android.view.Gravity)34