Search in sources :

Example 1 with LongSparseIntArray

use of org.telegram.messenger.support.LongSparseIntArray in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesController method processUpdateArray.

public boolean processUpdateArray(ArrayList<TLRPC.Update> updates, ArrayList<TLRPC.User> usersArr, ArrayList<TLRPC.Chat> chatsArr, boolean fromGetDifference, int date) {
    if (updates.isEmpty()) {
        if (usersArr != null || chatsArr != null) {
            AndroidUtilities.runOnUIThread(() -> {
                putUsers(usersArr, false);
                putChats(chatsArr, false);
            });
        }
        return true;
    }
    long currentTime = System.currentTimeMillis();
    boolean printChanged = false;
    LongSparseArray<ArrayList<MessageObject>> messages = null;
    LongSparseArray<ArrayList<MessageObject>> scheduledMessages = null;
    LongSparseArray<TLRPC.WebPage> webPages = null;
    ArrayList<MessageObject> pushMessages = null;
    ArrayList<TLRPC.Message> messagesArr = null;
    ArrayList<TLRPC.TL_sendMessageEmojiInteraction> emojiInteractions = null;
    ArrayList<TLRPC.Message> scheduledMessagesArr = null;
    LongSparseArray<ArrayList<MessageObject>> editingMessages = null;
    LongSparseArray<SparseIntArray> channelViews = null;
    LongSparseArray<SparseIntArray> channelForwards = null;
    LongSparseArray<SparseArray<TLRPC.MessageReplies>> channelReplies = null;
    LongSparseIntArray markAsReadMessagesInbox = null;
    LongSparseIntArray markAsReadMessagesOutbox = null;
    LongSparseArray<ArrayList<Integer>> markContentAsReadMessages = null;
    SparseIntArray markAsReadEncrypted = null;
    LongSparseArray<ArrayList<Integer>> deletedMessages = null;
    LongSparseArray<ArrayList<Integer>> scheduledDeletedMessages = null;
    LongSparseArray<ArrayList<Long>> groupSpeakingActions = null;
    LongSparseIntArray importingActions = null;
    LongSparseIntArray clearHistoryMessages = null;
    ArrayList<TLRPC.ChatParticipants> chatInfoToUpdate = null;
    ArrayList<TLRPC.Update> updatesOnMainThread = null;
    ArrayList<TLRPC.TL_updateFolderPeers> folderUpdates = null;
    ArrayList<TLRPC.TL_updateEncryptedMessagesRead> tasks = null;
    ArrayList<Long> contactsIds = null;
    ArrayList<ImageLoader.MessageThumb> messageThumbs = null;
    ConcurrentHashMap<Long, TLRPC.User> usersDict;
    ConcurrentHashMap<Long, TLRPC.Chat> chatsDict;
    if (usersArr != null) {
        usersDict = new ConcurrentHashMap<>();
        for (int a = 0, size = usersArr.size(); a < size; a++) {
            TLRPC.User user = usersArr.get(a);
            usersDict.put(user.id, user);
        }
    } else {
        usersDict = users;
    }
    if (chatsArr != null) {
        chatsDict = new ConcurrentHashMap<>();
        for (int a = 0, size = chatsArr.size(); a < size; a++) {
            TLRPC.Chat chat = chatsArr.get(a);
            chatsDict.put(chat.id, chat);
        }
    } else {
        chatsDict = chats;
    }
    if (usersArr != null || chatsArr != null) {
        AndroidUtilities.runOnUIThread(() -> {
            putUsers(usersArr, false);
            putChats(chatsArr, false);
        });
    }
    int interfaceUpdateMask = 0;
    long clientUserId = getUserConfig().getClientUserId();
    for (int c = 0, size3 = updates.size(); c < size3; c++) {
        TLRPC.Update baseUpdate = updates.get(c);
        if (BuildVars.LOGS_ENABLED) {
            FileLog.d("process update " + baseUpdate);
        }
        if (baseUpdate instanceof TLRPC.TL_updateNewMessage || baseUpdate instanceof TLRPC.TL_updateNewChannelMessage || baseUpdate instanceof TLRPC.TL_updateNewScheduledMessage) {
            TLRPC.Message message;
            if (baseUpdate instanceof TLRPC.TL_updateNewMessage) {
                message = ((TLRPC.TL_updateNewMessage) baseUpdate).message;
            } else if (baseUpdate instanceof TLRPC.TL_updateNewScheduledMessage) {
                message = ((TLRPC.TL_updateNewScheduledMessage) baseUpdate).message;
            } else {
                message = ((TLRPC.TL_updateNewChannelMessage) baseUpdate).message;
                if (BuildVars.LOGS_ENABLED) {
                    FileLog.d(baseUpdate + " channelId = " + message.peer_id.channel_id);
                }
                if (!message.out && message.from_id instanceof TLRPC.TL_peerUser && message.from_id.user_id == getUserConfig().getClientUserId()) {
                    message.out = true;
                }
            }
            if (message instanceof TLRPC.TL_messageEmpty) {
                continue;
            }
            TLRPC.Chat chat = null;
            long chatId = 0;
            long userId = 0;
            if (message.peer_id.channel_id != 0) {
                chatId = message.peer_id.channel_id;
            } else if (message.peer_id.chat_id != 0) {
                chatId = message.peer_id.chat_id;
            } else if (message.peer_id.user_id != 0) {
                userId = message.peer_id.user_id;
            }
            if (chatId != 0) {
                chat = chatsDict.get(chatId);
                if (chat == null || chat.min) {
                    chat = getChat(chatId);
                }
                if (chat == null || chat.min) {
                    chat = getMessagesStorage().getChatSync(chatId);
                    putChat(chat, true);
                }
            }
            if (!fromGetDifference) {
                if (chatId != 0) {
                    if (chat == null) {
                        if (BuildVars.LOGS_ENABLED) {
                            FileLog.d("not found chat " + chatId);
                        }
                        return false;
                    }
                }
                int count = 3 + message.entities.size();
                for (int a = 0; a < count; a++) {
                    boolean allowMin = false;
                    if (a != 0) {
                        if (a == 1) {
                            userId = message.from_id instanceof TLRPC.TL_peerUser ? message.from_id.user_id : 0;
                            if (message.post) {
                                allowMin = true;
                            }
                        } else if (a == 2) {
                            userId = message.fwd_from != null && message.fwd_from.from_id instanceof TLRPC.TL_peerUser ? message.fwd_from.from_id.user_id : 0;
                        } else {
                            TLRPC.MessageEntity entity = message.entities.get(a - 3);
                            userId = entity instanceof TLRPC.TL_messageEntityMentionName ? ((TLRPC.TL_messageEntityMentionName) entity).user_id : 0;
                        }
                    }
                    if (userId > 0) {
                        TLRPC.User user = usersDict.get(userId);
                        if (user == null || !allowMin && user.min) {
                            user = getUser(userId);
                        }
                        if (user == null || !allowMin && user.min) {
                            user = getMessagesStorage().getUserSync(userId);
                            if (user != null && !allowMin && user.min) {
                                user = null;
                            }
                            putUser(user, true);
                        }
                        if (user == null) {
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("not found user " + userId);
                            }
                            return false;
                        }
                        if (!message.out && a == 1 && user.status != null && user.status.expires <= 0 && Math.abs(getConnectionsManager().getCurrentTime() - message.date) < 30) {
                            onlinePrivacy.put(userId, message.date);
                            interfaceUpdateMask |= UPDATE_MASK_STATUS;
                        }
                    }
                }
            }
            if (message.action instanceof TLRPC.TL_messageActionChatDeleteUser) {
                TLRPC.User user = usersDict.get(message.action.user_id);
                if (user != null && user.bot) {
                    message.reply_markup = new TLRPC.TL_replyKeyboardHide();
                    message.flags |= 64;
                } else if (message.from_id instanceof TLRPC.TL_peerUser && message.from_id.user_id == clientUserId && message.action.user_id == clientUserId) {
                    continue;
                }
            }
            ImageLoader.saveMessageThumbs(message);
            MessageObject.getDialogId(message);
            if (baseUpdate instanceof TLRPC.TL_updateNewChannelMessage && message.reply_to != null && !(message.action instanceof TLRPC.TL_messageActionPinMessage)) {
                if (channelReplies == null) {
                    channelReplies = new LongSparseArray<>();
                }
                SparseArray<TLRPC.MessageReplies> replies = channelReplies.get(message.dialog_id);
                if (replies == null) {
                    replies = new SparseArray<>();
                    channelReplies.put(message.dialog_id, replies);
                }
                int id = message.reply_to.reply_to_top_id != 0 ? message.reply_to.reply_to_top_id : message.reply_to.reply_to_msg_id;
                TLRPC.MessageReplies messageReplies = replies.get(id);
                if (messageReplies == null) {
                    messageReplies = new TLRPC.TL_messageReplies();
                    replies.put(id, messageReplies);
                }
                if (message.from_id != null) {
                    messageReplies.recent_repliers.add(0, message.from_id);
                }
                messageReplies.replies++;
            }
            if (createdDialogIds.contains(message.dialog_id) && message.grouped_id == 0) {
                ImageLoader.MessageThumb messageThumb = ImageLoader.generateMessageThumb(message);
                if (messageThumb != null) {
                    if (messageThumbs == null) {
                        messageThumbs = new ArrayList<>();
                    }
                    messageThumbs.add(messageThumb);
                }
            }
            if (baseUpdate instanceof TLRPC.TL_updateNewScheduledMessage) {
                if (scheduledMessagesArr == null) {
                    scheduledMessagesArr = new ArrayList<>();
                }
                scheduledMessagesArr.add(message);
                boolean isDialogCreated = createdScheduledDialogIds.contains(message.dialog_id);
                MessageObject obj = new MessageObject(currentAccount, message, usersDict, chatsDict, isDialogCreated, isDialogCreated);
                obj.scheduled = true;
                if (scheduledMessages == null) {
                    scheduledMessages = new LongSparseArray<>();
                }
                ArrayList<MessageObject> arr = scheduledMessages.get(message.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<>();
                    scheduledMessages.put(message.dialog_id, arr);
                }
                arr.add(obj);
            } else {
                if (messagesArr == null) {
                    messagesArr = new ArrayList<>();
                }
                messagesArr.add(message);
                ConcurrentHashMap<Long, Integer> read_max = message.out ? dialogs_read_outbox_max : dialogs_read_inbox_max;
                Integer value = read_max.get(message.dialog_id);
                if (value == null) {
                    value = getMessagesStorage().getDialogReadMax(message.out, message.dialog_id);
                    read_max.put(message.dialog_id, value);
                }
                message.unread = !(value >= message.id || chat != null && ChatObject.isNotInChat(chat) || message.action instanceof TLRPC.TL_messageActionChatMigrateTo || message.action instanceof TLRPC.TL_messageActionChannelCreate);
                if (message.dialog_id == clientUserId) {
                    if (!message.from_scheduled) {
                        message.unread = false;
                    }
                    message.media_unread = false;
                    message.out = true;
                }
                boolean isDialogCreated = createdDialogIds.contains(message.dialog_id);
                MessageObject obj = new MessageObject(currentAccount, message, usersDict, chatsDict, isDialogCreated, isDialogCreated);
                if (obj.type == 11) {
                    interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR;
                } else if (obj.type == 10) {
                    interfaceUpdateMask |= UPDATE_MASK_CHAT_NAME;
                }
                if (messages == null) {
                    messages = new LongSparseArray<>();
                }
                ArrayList<MessageObject> arr = messages.get(message.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<>();
                    messages.put(message.dialog_id, arr);
                }
                arr.add(obj);
                if ((!obj.isOut() || obj.messageOwner.from_scheduled) && obj.isUnread() && (chat == null || !ChatObject.isNotInChat(chat) && !chat.min)) {
                    if (pushMessages == null) {
                        pushMessages = new ArrayList<>();
                    }
                    pushMessages.add(obj);
                }
            }
        } else if (baseUpdate instanceof TLRPC.TL_updateReadMessagesContents) {
            TLRPC.TL_updateReadMessagesContents update = (TLRPC.TL_updateReadMessagesContents) baseUpdate;
            if (markContentAsReadMessages == null) {
                markContentAsReadMessages = new LongSparseArray<>();
            }
            ArrayList<Integer> ids = markContentAsReadMessages.get(0);
            if (ids == null) {
                ids = new ArrayList<>();
                markContentAsReadMessages.put(0, ids);
            }
            ids.addAll(update.messages);
        } else if (baseUpdate instanceof TLRPC.TL_updateChannelReadMessagesContents) {
            TLRPC.TL_updateChannelReadMessagesContents update = (TLRPC.TL_updateChannelReadMessagesContents) baseUpdate;
            if (markContentAsReadMessages == null) {
                markContentAsReadMessages = new LongSparseArray<>();
            }
            long dialogId = -update.channel_id;
            ArrayList<Integer> ids = markContentAsReadMessages.get(dialogId);
            if (ids == null) {
                ids = new ArrayList<>();
                markContentAsReadMessages.put(dialogId, ids);
            }
            ids.addAll(update.messages);
        } else if (baseUpdate instanceof TLRPC.TL_updateReadHistoryInbox) {
            TLRPC.TL_updateReadHistoryInbox update = (TLRPC.TL_updateReadHistoryInbox) baseUpdate;
            long dialogId;
            if (markAsReadMessagesInbox == null) {
                markAsReadMessagesInbox = new LongSparseIntArray();
            }
            if (update.peer.chat_id != 0) {
                markAsReadMessagesInbox.put(-update.peer.chat_id, update.max_id);
                dialogId = -update.peer.chat_id;
            } else {
                markAsReadMessagesInbox.put(update.peer.user_id, update.max_id);
                dialogId = update.peer.user_id;
            }
            Integer value = dialogs_read_inbox_max.get(dialogId);
            if (value == null) {
                value = getMessagesStorage().getDialogReadMax(false, dialogId);
            }
            dialogs_read_inbox_max.put(dialogId, Math.max(value, update.max_id));
        } else if (baseUpdate instanceof TLRPC.TL_updateReadHistoryOutbox) {
            TLRPC.TL_updateReadHistoryOutbox update = (TLRPC.TL_updateReadHistoryOutbox) baseUpdate;
            long dialogId;
            if (markAsReadMessagesOutbox == null) {
                markAsReadMessagesOutbox = new LongSparseIntArray();
            }
            if (update.peer.chat_id != 0) {
                markAsReadMessagesOutbox.put(-update.peer.chat_id, update.max_id);
                dialogId = -update.peer.chat_id;
            } else {
                markAsReadMessagesOutbox.put(update.peer.user_id, update.max_id);
                dialogId = update.peer.user_id;
                TLRPC.User user = getUser(update.peer.user_id);
                if (user != null && user.status != null && user.status.expires <= 0 && Math.abs(getConnectionsManager().getCurrentTime() - date) < 30) {
                    onlinePrivacy.put(update.peer.user_id, date);
                    interfaceUpdateMask |= UPDATE_MASK_STATUS;
                }
            }
            Integer value = dialogs_read_outbox_max.get(dialogId);
            if (value == null) {
                value = getMessagesStorage().getDialogReadMax(true, dialogId);
            }
            dialogs_read_outbox_max.put(dialogId, Math.max(value, update.max_id));
        } else if (baseUpdate instanceof TLRPC.TL_updateDeleteMessages) {
            TLRPC.TL_updateDeleteMessages update = (TLRPC.TL_updateDeleteMessages) baseUpdate;
            if (deletedMessages == null) {
                deletedMessages = new LongSparseArray<>();
            }
            ArrayList<Integer> arrayList = deletedMessages.get(0);
            if (arrayList == null) {
                arrayList = new ArrayList<>();
                deletedMessages.put(0, arrayList);
            }
            arrayList.addAll(update.messages);
        } else if (baseUpdate instanceof TLRPC.TL_updateDeleteScheduledMessages) {
            TLRPC.TL_updateDeleteScheduledMessages update = (TLRPC.TL_updateDeleteScheduledMessages) baseUpdate;
            if (scheduledDeletedMessages == null) {
                scheduledDeletedMessages = new LongSparseArray<>();
            }
            long id = MessageObject.getPeerId(update.peer);
            ArrayList<Integer> arrayList = scheduledDeletedMessages.get(MessageObject.getPeerId(update.peer));
            if (arrayList == null) {
                arrayList = new ArrayList<>();
                scheduledDeletedMessages.put(id, arrayList);
            }
            arrayList.addAll(update.messages);
        } else if (baseUpdate instanceof TLRPC.TL_updateUserTyping || baseUpdate instanceof TLRPC.TL_updateChatUserTyping || baseUpdate instanceof TLRPC.TL_updateChannelUserTyping) {
            long userId;
            long chatId;
            int threadId;
            TLRPC.SendMessageAction action;
            if (baseUpdate instanceof TLRPC.TL_updateChannelUserTyping) {
                TLRPC.TL_updateChannelUserTyping update = (TLRPC.TL_updateChannelUserTyping) baseUpdate;
                if (update.from_id.user_id != 0) {
                    userId = update.from_id.user_id;
                } else if (update.from_id.channel_id != 0) {
                    userId = -update.from_id.channel_id;
                } else {
                    userId = -update.from_id.chat_id;
                }
                chatId = update.channel_id;
                action = update.action;
                threadId = update.top_msg_id;
            } else if (baseUpdate instanceof TLRPC.TL_updateUserTyping) {
                TLRPC.TL_updateUserTyping update = (TLRPC.TL_updateUserTyping) baseUpdate;
                userId = update.user_id;
                action = update.action;
                chatId = 0;
                threadId = 0;
                if (update.action instanceof TLRPC.TL_sendMessageEmojiInteraction) {
                    AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.onEmojiInteractionsReceived, update.user_id, update.action));
                    continue;
                }
            } else {
                TLRPC.TL_updateChatUserTyping update = (TLRPC.TL_updateChatUserTyping) baseUpdate;
                chatId = update.chat_id;
                if (update.from_id.user_id != 0) {
                    userId = update.from_id.user_id;
                } else if (update.from_id.channel_id != 0) {
                    userId = -update.from_id.channel_id;
                } else {
                    userId = -update.from_id.chat_id;
                }
                action = update.action;
                threadId = 0;
                if (update.action instanceof TLRPC.TL_sendMessageEmojiInteraction) {
                    AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.onEmojiInteractionsReceived, -update.chat_id, update.action));
                    continue;
                }
            }
            long uid = -chatId;
            if (uid == 0) {
                uid = userId;
            }
            if (action instanceof TLRPC.TL_sendMessageHistoryImportAction) {
                if (importingActions == null) {
                    importingActions = new LongSparseIntArray();
                }
                TLRPC.TL_sendMessageHistoryImportAction importAction = (TLRPC.TL_sendMessageHistoryImportAction) action;
                importingActions.put(uid, importAction.progress);
            } else if (userId != getUserConfig().getClientUserId()) {
                if (action instanceof TLRPC.TL_speakingInGroupCallAction) {
                    if (chatId != 0) {
                        if (groupSpeakingActions == null) {
                            groupSpeakingActions = new LongSparseArray<>();
                        }
                        ArrayList<Long> uids = groupSpeakingActions.get(chatId);
                        if (uids == null) {
                            uids = new ArrayList<>();
                            groupSpeakingActions.put(chatId, uids);
                        }
                        uids.add(userId);
                    }
                } else {
                    ConcurrentHashMap<Integer, ArrayList<PrintingUser>> threads = printingUsers.get(uid);
                    ArrayList<PrintingUser> arr = threads != null ? threads.get(threadId) : null;
                    if (action instanceof TLRPC.TL_sendMessageCancelAction) {
                        if (arr != null) {
                            for (int a = 0, size = arr.size(); a < size; a++) {
                                PrintingUser pu = arr.get(a);
                                if (pu.userId == userId) {
                                    arr.remove(a);
                                    printChanged = true;
                                    break;
                                }
                            }
                            if (arr.isEmpty()) {
                                threads.remove(threadId);
                                if (threads.isEmpty()) {
                                    printingUsers.remove(uid);
                                }
                            }
                        }
                    } else {
                        if (threads == null) {
                            threads = new ConcurrentHashMap<>();
                            printingUsers.put(uid, threads);
                        }
                        if (arr == null) {
                            arr = new ArrayList<>();
                            threads.put(threadId, arr);
                        }
                        boolean exist = false;
                        for (PrintingUser u : arr) {
                            if (u.userId == userId) {
                                exist = true;
                                u.lastTime = currentTime;
                                if (u.action.getClass() != action.getClass()) {
                                    printChanged = true;
                                }
                                u.action = action;
                                break;
                            }
                        }
                        if (!exist) {
                            PrintingUser newUser = new PrintingUser();
                            newUser.userId = userId;
                            newUser.lastTime = currentTime;
                            newUser.action = action;
                            arr.add(newUser);
                            printChanged = true;
                        }
                    }
                }
                if (Math.abs(getConnectionsManager().getCurrentTime() - date) < 30) {
                    onlinePrivacy.put(userId, date);
                }
            }
        } else if (baseUpdate instanceof TLRPC.TL_updateChatParticipants) {
            TLRPC.TL_updateChatParticipants update = (TLRPC.TL_updateChatParticipants) baseUpdate;
            interfaceUpdateMask |= UPDATE_MASK_CHAT_MEMBERS;
            if (chatInfoToUpdate == null) {
                chatInfoToUpdate = new ArrayList<>();
            }
            chatInfoToUpdate.add(update.participants);
        } else if (baseUpdate instanceof TLRPC.TL_updateUserStatus) {
            interfaceUpdateMask |= UPDATE_MASK_STATUS;
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateUserName) {
            interfaceUpdateMask |= UPDATE_MASK_NAME;
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateUserPhoto) {
            TLRPC.TL_updateUserPhoto update = (TLRPC.TL_updateUserPhoto) baseUpdate;
            interfaceUpdateMask |= UPDATE_MASK_AVATAR;
            getMessagesStorage().clearUserPhotos(update.user_id);
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateUserPhone) {
            interfaceUpdateMask |= UPDATE_MASK_PHONE;
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updatePeerSettings) {
            TLRPC.TL_updatePeerSettings update = (TLRPC.TL_updatePeerSettings) baseUpdate;
            if (contactsIds == null) {
                contactsIds = new ArrayList<>();
            }
            if (update.peer instanceof TLRPC.TL_peerUser) {
                TLRPC.User user = usersDict.get(update.peer.user_id);
                if (user != null) {
                    if (user.contact) {
                        int idx = contactsIds.indexOf(-update.peer.user_id);
                        if (idx != -1) {
                            contactsIds.remove(idx);
                        }
                        if (!contactsIds.contains(update.peer.user_id)) {
                            contactsIds.add(update.peer.user_id);
                        }
                    } else {
                        int idx = contactsIds.indexOf(update.peer.user_id);
                        if (idx != -1) {
                            contactsIds.remove(idx);
                        }
                        if (!contactsIds.contains(update.peer.user_id)) {
                            contactsIds.add(-update.peer.user_id);
                        }
                    }
                }
            }
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateNewEncryptedMessage) {
            ArrayList<TLRPC.Message> decryptedMessages = getSecretChatHelper().decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) baseUpdate).message);
            if (decryptedMessages != null && !decryptedMessages.isEmpty()) {
                int cid = ((TLRPC.TL_updateNewEncryptedMessage) baseUpdate).message.chat_id;
                long uid = DialogObject.makeEncryptedDialogId(cid);
                if (messages == null) {
                    messages = new LongSparseArray<>();
                }
                ArrayList<MessageObject> arr = messages.get(uid);
                if (arr == null) {
                    arr = new ArrayList<>();
                    messages.put(uid, arr);
                }
                for (int a = 0, size = decryptedMessages.size(); a < size; a++) {
                    TLRPC.Message message = decryptedMessages.get(a);
                    ImageLoader.saveMessageThumbs(message);
                    if (messagesArr == null) {
                        messagesArr = new ArrayList<>();
                    }
                    messagesArr.add(message);
                    boolean isDialogCreated = createdDialogIds.contains(uid);
                    MessageObject obj = new MessageObject(currentAccount, message, usersDict, chatsDict, isDialogCreated, isDialogCreated);
                    arr.add(obj);
                    if (pushMessages == null) {
                        pushMessages = new ArrayList<>();
                    }
                    pushMessages.add(obj);
                }
            }
        } else if (baseUpdate instanceof TLRPC.TL_updateEncryptedChatTyping) {
            TLRPC.TL_updateEncryptedChatTyping update = (TLRPC.TL_updateEncryptedChatTyping) baseUpdate;
            TLRPC.EncryptedChat encryptedChat = getEncryptedChatDB(update.chat_id, true);
            if (encryptedChat != null) {
                long uid = DialogObject.makeEncryptedDialogId(update.chat_id);
                ConcurrentHashMap<Integer, ArrayList<PrintingUser>> threads = printingUsers.get(uid);
                if (threads == null) {
                    threads = new ConcurrentHashMap<>();
                    printingUsers.put(uid, threads);
                }
                ArrayList<PrintingUser> arr = threads.get(0);
                if (arr == null) {
                    arr = new ArrayList<>();
                    threads.put(0, arr);
                }
                boolean exist = false;
                for (int a = 0, size = arr.size(); a < size; a++) {
                    PrintingUser u = arr.get(a);
                    if (u.userId == encryptedChat.user_id) {
                        exist = true;
                        u.lastTime = currentTime;
                        u.action = new TLRPC.TL_sendMessageTypingAction();
                        break;
                    }
                }
                if (!exist) {
                    PrintingUser newUser = new PrintingUser();
                    newUser.userId = encryptedChat.user_id;
                    newUser.lastTime = currentTime;
                    newUser.action = new TLRPC.TL_sendMessageTypingAction();
                    arr.add(newUser);
                    printChanged = true;
                }
                if (Math.abs(getConnectionsManager().getCurrentTime() - date) < 30) {
                    onlinePrivacy.put(encryptedChat.user_id, date);
                }
            }
        } else if (baseUpdate instanceof TLRPC.TL_updateEncryptedMessagesRead) {
            TLRPC.TL_updateEncryptedMessagesRead update = (TLRPC.TL_updateEncryptedMessagesRead) baseUpdate;
            if (markAsReadEncrypted == null) {
                markAsReadEncrypted = new SparseIntArray();
            }
            markAsReadEncrypted.put(update.chat_id, update.max_date);
            if (tasks == null) {
                tasks = new ArrayList<>();
            }
            tasks.add((TLRPC.TL_updateEncryptedMessagesRead) baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateChatParticipantAdd) {
            TLRPC.TL_updateChatParticipantAdd update = (TLRPC.TL_updateChatParticipantAdd) baseUpdate;
            getMessagesStorage().updateChatInfo(update.chat_id, update.user_id, 0, update.inviter_id, update.version);
        } else if (baseUpdate instanceof TLRPC.TL_updateChatParticipantDelete) {
            TLRPC.TL_updateChatParticipantDelete update = (TLRPC.TL_updateChatParticipantDelete) baseUpdate;
            getMessagesStorage().updateChatInfo(update.chat_id, update.user_id, 1, 0, update.version);
        } else if (baseUpdate instanceof TLRPC.TL_updateDcOptions || baseUpdate instanceof TLRPC.TL_updateConfig) {
            getConnectionsManager().updateDcSettings();
        } else if (baseUpdate instanceof TLRPC.TL_updateEncryption) {
            getSecretChatHelper().processUpdateEncryption((TLRPC.TL_updateEncryption) baseUpdate, usersDict);
        } else if (baseUpdate instanceof TLRPC.TL_updatePeerBlocked) {
            TLRPC.TL_updatePeerBlocked finalUpdate = (TLRPC.TL_updatePeerBlocked) baseUpdate;
            getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> {
                long id = MessageObject.getPeerId(finalUpdate.peer_id);
                if (finalUpdate.blocked) {
                    if (blockePeers.indexOfKey(id) < 0) {
                        blockePeers.put(id, 1);
                    }
                } else {
                    blockePeers.delete(id);
                }
                getNotificationCenter().postNotificationName(NotificationCenter.blockedUsersDidLoad);
            }));
        } else if (baseUpdate instanceof TLRPC.TL_updateNotifySettings) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateServiceNotification) {
            TLRPC.TL_updateServiceNotification update = (TLRPC.TL_updateServiceNotification) baseUpdate;
            if (update.popup && update.message != null && update.message.length() > 0) {
                AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.needShowAlert, 2, update.message, update.type));
            }
            if ((update.flags & 2) != 0) {
                TLRPC.TL_message newMessage = new TLRPC.TL_message();
                newMessage.local_id = newMessage.id = getUserConfig().getNewMessageId();
                getUserConfig().saveConfig(false);
                newMessage.unread = true;
                newMessage.flags = TLRPC.MESSAGE_FLAG_HAS_FROM_ID;
                if (update.inbox_date != 0) {
                    newMessage.date = update.inbox_date;
                } else {
                    newMessage.date = (int) (System.currentTimeMillis() / 1000);
                }
                newMessage.from_id = new TLRPC.TL_peerUser();
                newMessage.from_id.user_id = 777000;
                newMessage.peer_id = new TLRPC.TL_peerUser();
                newMessage.peer_id.user_id = getUserConfig().getClientUserId();
                newMessage.dialog_id = 777000;
                if (update.media != null) {
                    newMessage.media = update.media;
                    newMessage.flags |= TLRPC.MESSAGE_FLAG_HAS_MEDIA;
                }
                newMessage.message = update.message;
                if (update.entities != null) {
                    newMessage.entities = update.entities;
                    newMessage.flags |= 128;
                }
                if (messagesArr == null) {
                    messagesArr = new ArrayList<>();
                }
                messagesArr.add(newMessage);
                boolean isDialogCreated = createdDialogIds.contains(newMessage.dialog_id);
                MessageObject obj = new MessageObject(currentAccount, newMessage, usersDict, chatsDict, isDialogCreated, isDialogCreated);
                if (messages == null) {
                    messages = new LongSparseArray<>();
                }
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                if (pushMessages == null) {
                    pushMessages = new ArrayList<>();
                }
                pushMessages.add(obj);
            }
        } else if (baseUpdate instanceof TLRPC.TL_updateDialogPinned) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updatePinnedDialogs) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateFolderPeers) {
            TLRPC.TL_updateFolderPeers update = (TLRPC.TL_updateFolderPeers) baseUpdate;
            if (folderUpdates == null) {
                folderUpdates = new ArrayList<>();
            }
            folderUpdates.add(update);
        } else if (baseUpdate instanceof TLRPC.TL_updatePrivacy) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateWebPage) {
            TLRPC.TL_updateWebPage update = (TLRPC.TL_updateWebPage) baseUpdate;
            if (webPages == null) {
                webPages = new LongSparseArray<>();
            }
            webPages.put(update.webpage.id, update.webpage);
        } else if (baseUpdate instanceof TLRPC.TL_updateChannelWebPage) {
            TLRPC.TL_updateChannelWebPage update = (TLRPC.TL_updateChannelWebPage) baseUpdate;
            if (webPages == null) {
                webPages = new LongSparseArray<>();
            }
            webPages.put(update.webpage.id, update.webpage);
        } else if (baseUpdate instanceof TLRPC.TL_updateChannelTooLong) {
            TLRPC.TL_updateChannelTooLong update = (TLRPC.TL_updateChannelTooLong) baseUpdate;
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d(baseUpdate + " channelId = " + update.channel_id);
            }
            int channelPts = channelsPts.get(update.channel_id, 0);
            if (channelPts == 0) {
                channelPts = getMessagesStorage().getChannelPtsSync(update.channel_id);
                if (channelPts == 0) {
                    TLRPC.Chat chat = chatsDict.get(update.channel_id);
                    if (chat == null || chat.min) {
                        chat = getChat(update.channel_id);
                    }
                    if (chat == null || chat.min) {
                        chat = getMessagesStorage().getChatSync(update.channel_id);
                        putChat(chat, true);
                    }
                    if (chat != null && !chat.min) {
                        loadUnknownChannel(chat, 0);
                    }
                } else {
                    channelsPts.put(update.channel_id, channelPts);
                }
            }
            if (channelPts != 0) {
                if ((update.flags & 1) != 0) {
                    if (update.pts > channelPts) {
                        getChannelDifference(update.channel_id);
                    }
                } else {
                    getChannelDifference(update.channel_id);
                }
            }
        } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelInbox) {
            TLRPC.TL_updateReadChannelInbox update = (TLRPC.TL_updateReadChannelInbox) baseUpdate;
            if (markAsReadMessagesInbox == null) {
                markAsReadMessagesInbox = new LongSparseIntArray();
            }
            long dialogId = -update.channel_id;
            markAsReadMessagesInbox.put(dialogId, update.max_id);
            Integer value = dialogs_read_inbox_max.get(dialogId);
            if (value == null) {
                value = getMessagesStorage().getDialogReadMax(false, dialogId);
            }
            dialogs_read_inbox_max.put(dialogId, Math.max(value, update.max_id));
        } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelOutbox) {
            TLRPC.TL_updateReadChannelOutbox update = (TLRPC.TL_updateReadChannelOutbox) baseUpdate;
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d(baseUpdate + " channelId = " + update.channel_id);
            }
            if (markAsReadMessagesOutbox == null) {
                markAsReadMessagesOutbox = new LongSparseIntArray();
            }
            long dialogId = -update.channel_id;
            markAsReadMessagesOutbox.put(dialogId, update.max_id);
            Integer value = dialogs_read_outbox_max.get(dialogId);
            if (value == null) {
                value = getMessagesStorage().getDialogReadMax(true, dialogId);
            }
            dialogs_read_outbox_max.put(dialogId, Math.max(value, update.max_id));
        } else if (baseUpdate instanceof TLRPC.TL_updateDeleteChannelMessages) {
            TLRPC.TL_updateDeleteChannelMessages update = (TLRPC.TL_updateDeleteChannelMessages) baseUpdate;
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d(baseUpdate + " channelId = " + update.channel_id);
            }
            if (deletedMessages == null) {
                deletedMessages = new LongSparseArray<>();
            }
            long dialogId = -update.channel_id;
            ArrayList<Integer> arrayList = deletedMessages.get(dialogId);
            if (arrayList == null) {
                arrayList = new ArrayList<>();
                deletedMessages.put(dialogId, arrayList);
            }
            arrayList.addAll(update.messages);
        } else if (baseUpdate instanceof TLRPC.TL_updateChannel) {
            if (BuildVars.LOGS_ENABLED) {
                TLRPC.TL_updateChannel update = (TLRPC.TL_updateChannel) baseUpdate;
                FileLog.d(baseUpdate + " channelId = " + update.channel_id);
            }
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateChat) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateChannelMessageViews) {
            TLRPC.TL_updateChannelMessageViews update = (TLRPC.TL_updateChannelMessageViews) baseUpdate;
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d(baseUpdate + " channelId = " + update.channel_id);
            }
            if (channelViews == null) {
                channelViews = new LongSparseArray<>();
            }
            long dialogId = -update.channel_id;
            SparseIntArray array = channelViews.get(dialogId);
            if (array == null) {
                array = new SparseIntArray();
                channelViews.put(dialogId, array);
            }
            array.put(update.id, update.views);
        } else if (baseUpdate instanceof TLRPC.TL_updateChannelMessageForwards) {
            TLRPC.TL_updateChannelMessageForwards update = (TLRPC.TL_updateChannelMessageForwards) baseUpdate;
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d(baseUpdate + " channelId = " + update.channel_id);
            }
            if (channelForwards == null) {
                channelForwards = new LongSparseArray<>();
            }
            long dialogId = -update.channel_id;
            SparseIntArray array = channelForwards.get(dialogId);
            if (array == null) {
                array = new SparseIntArray();
                channelForwards.put(dialogId, array);
            }
            array.put(update.id, update.forwards);
        } else if (baseUpdate instanceof TLRPC.TL_updateChatParticipantAdmin) {
            TLRPC.TL_updateChatParticipantAdmin update = (TLRPC.TL_updateChatParticipantAdmin) baseUpdate;
            getMessagesStorage().updateChatInfo(update.chat_id, update.user_id, 2, update.is_admin ? 1 : 0, update.version);
        } else if (baseUpdate instanceof TLRPC.TL_updateChatDefaultBannedRights) {
            TLRPC.TL_updateChatDefaultBannedRights update = (TLRPC.TL_updateChatDefaultBannedRights) baseUpdate;
            long chatId;
            if (update.peer.channel_id != 0) {
                chatId = update.peer.channel_id;
            } else {
                chatId = update.peer.chat_id;
            }
            getMessagesStorage().updateChatDefaultBannedRights(chatId, update.default_banned_rights, update.version);
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateStickerSets) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateStickerSetsOrder) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateNewStickerSet) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateDraftMessage) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateSavedGifs) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateEditChannelMessage || baseUpdate instanceof TLRPC.TL_updateEditMessage) {
            TLRPC.Message message;
            if (baseUpdate instanceof TLRPC.TL_updateEditChannelMessage) {
                message = ((TLRPC.TL_updateEditChannelMessage) baseUpdate).message;
                TLRPC.Chat chat = chatsDict.get(message.peer_id.channel_id);
                if (chat == null) {
                    chat = getChat(message.peer_id.channel_id);
                }
                if (chat == null) {
                    chat = getMessagesStorage().getChatSync(message.peer_id.channel_id);
                    putChat(chat, true);
                }
            } else {
                message = ((TLRPC.TL_updateEditMessage) baseUpdate).message;
                if (message.dialog_id == clientUserId) {
                    message.unread = false;
                    message.media_unread = false;
                    message.out = true;
                }
            }
            if (!message.out && message.from_id instanceof TLRPC.TL_peerUser && message.from_id.user_id == clientUserId) {
                message.out = true;
            }
            if (!fromGetDifference) {
                for (int a = 0, count = message.entities.size(); a < count; a++) {
                    TLRPC.MessageEntity entity = message.entities.get(a);
                    if (entity instanceof TLRPC.TL_messageEntityMentionName) {
                        long userId = ((TLRPC.TL_messageEntityMentionName) entity).user_id;
                        TLRPC.User user = usersDict.get(userId);
                        if (user == null || user.min) {
                            user = getUser(userId);
                        }
                        if (user == null || user.min) {
                            user = getMessagesStorage().getUserSync(userId);
                            if (user != null && user.min) {
                                user = null;
                            }
                            putUser(user, true);
                        }
                        if (user == null) {
                            return false;
                        }
                    }
                }
            }
            MessageObject.getDialogId(message);
            ConcurrentHashMap<Long, Integer> read_max = message.out ? dialogs_read_outbox_max : dialogs_read_inbox_max;
            Integer value = read_max.get(message.dialog_id);
            if (value == null) {
                value = getMessagesStorage().getDialogReadMax(message.out, message.dialog_id);
                read_max.put(message.dialog_id, value);
            }
            message.unread = value < message.id;
            if (message.dialog_id == clientUserId) {
                message.out = true;
                message.unread = false;
                message.media_unread = false;
            }
            if (message.out && message.message == null) {
                message.message = "";
                message.attachPath = "";
            }
            ImageLoader.saveMessageThumbs(message);
            boolean isDialogCreated = createdDialogIds.contains(message.dialog_id);
            MessageObject obj = new MessageObject(currentAccount, message, usersDict, chatsDict, isDialogCreated, isDialogCreated);
            LongSparseArray<ArrayList<MessageObject>> array;
            if (editingMessages == null) {
                editingMessages = new LongSparseArray<>();
            }
            array = editingMessages;
            ArrayList<MessageObject> arr = array.get(message.dialog_id);
            if (arr == null) {
                arr = new ArrayList<>();
                array.put(message.dialog_id, arr);
            }
            arr.add(obj);
        } else if (baseUpdate instanceof TLRPC.TL_updatePinnedChannelMessages) {
            TLRPC.TL_updatePinnedChannelMessages update = (TLRPC.TL_updatePinnedChannelMessages) baseUpdate;
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d(baseUpdate + " channelId = " + update.channel_id);
            }
            getMessagesStorage().updatePinnedMessages(-update.channel_id, update.messages, update.pinned, -1, 0, false, null);
        } else if (baseUpdate instanceof TLRPC.TL_updatePinnedMessages) {
            TLRPC.TL_updatePinnedMessages update = (TLRPC.TL_updatePinnedMessages) baseUpdate;
            getMessagesStorage().updatePinnedMessages(MessageObject.getPeerId(update.peer), update.messages, update.pinned, -1, 0, false, null);
        } else if (baseUpdate instanceof TLRPC.TL_updateReadFeaturedStickers) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updatePhoneCall) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateGroupCallParticipants) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateGroupCall) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateGroupCallConnection) {
        } else if (baseUpdate instanceof TLRPC.TL_updateBotCommands) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updatePhoneCallSignalingData) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateLangPack) {
            TLRPC.TL_updateLangPack update = (TLRPC.TL_updateLangPack) baseUpdate;
            AndroidUtilities.runOnUIThread(() -> LocaleController.getInstance().saveRemoteLocaleStringsForCurrentLocale(update.difference, currentAccount));
        } else if (baseUpdate instanceof TLRPC.TL_updateLangPackTooLong) {
            TLRPC.TL_updateLangPackTooLong update = (TLRPC.TL_updateLangPackTooLong) baseUpdate;
            LocaleController.getInstance().reloadCurrentRemoteLocale(currentAccount, update.lang_code, false);
        } else if (baseUpdate instanceof TLRPC.TL_updateFavedStickers) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateContactsReset) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateChannelAvailableMessages) {
            TLRPC.TL_updateChannelAvailableMessages update = (TLRPC.TL_updateChannelAvailableMessages) baseUpdate;
            if (clearHistoryMessages == null) {
                clearHistoryMessages = new LongSparseIntArray();
            }
            long dialogId = -update.channel_id;
            int currentValue = clearHistoryMessages.get(dialogId, 0);
            if (currentValue == 0 || currentValue < update.available_min_id) {
                clearHistoryMessages.put(dialogId, update.available_min_id);
            }
        } else if (baseUpdate instanceof TLRPC.TL_updateDialogUnreadMark) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateMessagePoll) {
            TLRPC.TL_updateMessagePoll update = (TLRPC.TL_updateMessagePoll) baseUpdate;
            long time = getSendMessagesHelper().getVoteSendTime(update.poll_id);
            if (Math.abs(SystemClock.elapsedRealtime() - time) < 600) {
                continue;
            }
            getMessagesStorage().updateMessagePollResults(update.poll_id, update.poll, update.results);
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateMessageReactions) {
            TLRPC.TL_updateMessageReactions update = (TLRPC.TL_updateMessageReactions) baseUpdate;
            long dialogId = MessageObject.getPeerId(update.peer);
            getMessagesStorage().updateMessageReactions(dialogId, update.msg_id, update.reactions);
            if (update.updateUnreadState) {
                SparseBooleanArray sparseBooleanArray = new SparseBooleanArray();
                sparseBooleanArray.put(update.msg_id, MessageObject.hasUnreadReactions(update.reactions));
                checkUnreadReactions(dialogId, sparseBooleanArray);
            }
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updatePeerLocated) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateTheme) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateGeoLiveViewed) {
            getLocationController().setNewLocationEndWatchTime();
        } else if (baseUpdate instanceof TLRPC.TL_updateDialogFilter) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateDialogFilterOrder) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateDialogFilters) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelDiscussionInbox) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelDiscussionOutbox) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updatePeerHistoryTTL) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        } else if (baseUpdate instanceof TLRPC.TL_updatePendingJoinRequests) {
            if (updatesOnMainThread == null) {
                updatesOnMainThread = new ArrayList<>();
            }
            updatesOnMainThread.add(baseUpdate);
        }
    }
    if (messages != null) {
        for (int a = 0, size = messages.size(); a < size; a++) {
            long key = messages.keyAt(a);
            ArrayList<MessageObject> value = messages.valueAt(a);
            if (updatePrintingUsersWithNewMessages(key, value)) {
                printChanged = true;
            }
        }
    }
    if (printChanged) {
        updatePrintingStrings();
    }
    int interfaceUpdateMaskFinal = interfaceUpdateMask;
    boolean printChangedArg = printChanged;
    if (contactsIds != null) {
        getContactsController().processContactsUpdates(contactsIds, usersDict);
    }
    if (pushMessages != null) {
        ArrayList<MessageObject> pushMessagesFinal = pushMessages;
        getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> getNotificationsController().processNewMessages(pushMessagesFinal, true, false, null)));
    }
    if (scheduledMessagesArr != null) {
        getMessagesStorage().putMessages(scheduledMessagesArr, true, true, false, getDownloadController().getAutodownloadMask(), true);
    }
    if (messagesArr != null) {
        getStatsController().incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_MESSAGES, messagesArr.size());
        getMessagesStorage().putMessages(messagesArr, true, true, false, getDownloadController().getAutodownloadMask(), false);
    }
    if (editingMessages != null) {
        for (int b = 0, size = editingMessages.size(); b < size; b++) {
            TLRPC.TL_messages_messages messagesRes = new TLRPC.TL_messages_messages();
            ArrayList<MessageObject> messageObjects = editingMessages.valueAt(b);
            for (int a = 0, size2 = messageObjects.size(); a < size2; a++) {
                messagesRes.messages.add(messageObjects.get(a).messageOwner);
            }
            getMessagesStorage().putMessages(messagesRes, editingMessages.keyAt(b), -2, 0, false, false);
        }
        LongSparseArray<ArrayList<MessageObject>> editingMessagesFinal = editingMessages;
        getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> getNotificationsController().processEditedMessages(editingMessagesFinal)));
    }
    if (channelViews != null || channelForwards != null || channelReplies != null) {
        getMessagesStorage().putChannelViews(channelViews, channelForwards, channelReplies, true);
    }
    if (folderUpdates != null) {
        for (int a = 0, size = folderUpdates.size(); a < size; a++) {
            getMessagesStorage().setDialogsFolderId(folderUpdates.get(a).folder_peers, null, 0, 0);
        }
    }
    LongSparseArray<ArrayList<MessageObject>> editingMessagesFinal = editingMessages;
    LongSparseArray<SparseIntArray> channelViewsFinal = channelViews;
    LongSparseArray<SparseIntArray> channelForwardsFinal = channelForwards;
    LongSparseArray<SparseArray<TLRPC.MessageReplies>> channelRepliesFinal = channelReplies;
    LongSparseArray<TLRPC.WebPage> webPagesFinal = webPages;
    LongSparseArray<ArrayList<MessageObject>> messagesFinal = messages;
    LongSparseArray<ArrayList<MessageObject>> scheduledMessagesFinal = scheduledMessages;
    ArrayList<TLRPC.ChatParticipants> chatInfoToUpdateFinal = chatInfoToUpdate;
    ArrayList<Long> contactsIdsFinal = contactsIds;
    ArrayList<TLRPC.Update> updatesOnMainThreadFinal = updatesOnMainThread;
    ArrayList<ImageLoader.MessageThumb> updateMessageThumbs = messageThumbs;
    ArrayList<TLRPC.TL_updateFolderPeers> folderUpdatesFinal = folderUpdates;
    LongSparseArray<ArrayList<Long>> groupSpeakingActionsFinal = groupSpeakingActions;
    LongSparseIntArray importingActionsFinal = importingActions;
    AndroidUtilities.runOnUIThread(() -> {
        int updateMask = interfaceUpdateMaskFinal;
        boolean forceDialogsUpdate = false;
        int updateDialogFiltersFlags = 0;
        if (updatesOnMainThreadFinal != null) {
            ArrayList<TLRPC.User> dbUsers = new ArrayList<>();
            ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<>();
            SharedPreferences.Editor editor = null;
            for (int a = 0, size = updatesOnMainThreadFinal.size(); a < size; a++) {
                TLRPC.Update baseUpdate = updatesOnMainThreadFinal.get(a);
                if (baseUpdate instanceof TLRPC.TL_updatePrivacy) {
                    TLRPC.TL_updatePrivacy update = (TLRPC.TL_updatePrivacy) baseUpdate;
                    if (update.key instanceof TLRPC.TL_privacyKeyStatusTimestamp) {
                        getContactsController().setPrivacyRules(update.rules, ContactsController.PRIVACY_RULES_TYPE_LASTSEEN);
                    } else if (update.key instanceof TLRPC.TL_privacyKeyChatInvite) {
                        getContactsController().setPrivacyRules(update.rules, ContactsController.PRIVACY_RULES_TYPE_INVITE);
                    } else if (update.key instanceof TLRPC.TL_privacyKeyPhoneCall) {
                        getContactsController().setPrivacyRules(update.rules, ContactsController.PRIVACY_RULES_TYPE_CALLS);
                    } else if (update.key instanceof TLRPC.TL_privacyKeyPhoneP2P) {
                        getContactsController().setPrivacyRules(update.rules, ContactsController.PRIVACY_RULES_TYPE_P2P);
                    } else if (update.key instanceof TLRPC.TL_privacyKeyProfilePhoto) {
                        getContactsController().setPrivacyRules(update.rules, ContactsController.PRIVACY_RULES_TYPE_PHOTO);
                    } else if (update.key instanceof TLRPC.TL_privacyKeyForwards) {
                        getContactsController().setPrivacyRules(update.rules, ContactsController.PRIVACY_RULES_TYPE_FORWARDS);
                    } else if (update.key instanceof TLRPC.TL_privacyKeyPhoneNumber) {
                        getContactsController().setPrivacyRules(update.rules, ContactsController.PRIVACY_RULES_TYPE_PHONE);
                    } else if (update.key instanceof TLRPC.TL_privacyKeyAddedByPhone) {
                        getContactsController().setPrivacyRules(update.rules, ContactsController.PRIVACY_RULES_TYPE_ADDED_BY_PHONE);
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateUserStatus) {
                    TLRPC.TL_updateUserStatus update = (TLRPC.TL_updateUserStatus) baseUpdate;
                    TLRPC.User currentUser = getUser(update.user_id);
                    if (update.status instanceof TLRPC.TL_userStatusRecently) {
                        update.status.expires = -100;
                    } else if (update.status instanceof TLRPC.TL_userStatusLastWeek) {
                        update.status.expires = -101;
                    } else if (update.status instanceof TLRPC.TL_userStatusLastMonth) {
                        update.status.expires = -102;
                    }
                    if (currentUser != null) {
                        currentUser.id = update.user_id;
                        currentUser.status = update.status;
                    }
                    TLRPC.User toDbUser = new TLRPC.TL_user();
                    toDbUser.id = update.user_id;
                    toDbUser.status = update.status;
                    dbUsersStatus.add(toDbUser);
                    if (update.user_id == getUserConfig().getClientUserId()) {
                        getNotificationsController().setLastOnlineFromOtherDevice(update.status.expires);
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateUserName) {
                    TLRPC.TL_updateUserName update = (TLRPC.TL_updateUserName) baseUpdate;
                    TLRPC.User currentUser = getUser(update.user_id);
                    if (currentUser != null) {
                        if (!UserObject.isContact(currentUser)) {
                            currentUser.first_name = update.first_name;
                            currentUser.last_name = update.last_name;
                        }
                        if (!TextUtils.isEmpty(currentUser.username)) {
                            objectsByUsernames.remove(currentUser.username);
                        }
                        if (TextUtils.isEmpty(update.username)) {
                            objectsByUsernames.put(update.username, currentUser);
                        }
                        currentUser.username = update.username;
                    }
                    TLRPC.User toDbUser = new TLRPC.TL_user();
                    toDbUser.id = update.user_id;
                    toDbUser.first_name = update.first_name;
                    toDbUser.last_name = update.last_name;
                    toDbUser.username = update.username;
                    dbUsers.add(toDbUser);
                } else if (baseUpdate instanceof TLRPC.TL_updateDialogPinned) {
                    TLRPC.TL_updateDialogPinned update = (TLRPC.TL_updateDialogPinned) baseUpdate;
                    long did;
                    if (update.peer instanceof TLRPC.TL_dialogPeer) {
                        TLRPC.TL_dialogPeer dialogPeer = (TLRPC.TL_dialogPeer) update.peer;
                        did = DialogObject.getPeerDialogId(dialogPeer.peer);
                    } else {
                        did = 0;
                    }
                    if (!pinDialog(did, update.pinned, null, -1)) {
                        getUserConfig().setPinnedDialogsLoaded(update.folder_id, false);
                        getUserConfig().saveConfig(false);
                        loadPinnedDialogs(update.folder_id, did, null);
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updatePinnedDialogs) {
                    TLRPC.TL_updatePinnedDialogs update = (TLRPC.TL_updatePinnedDialogs) baseUpdate;
                    getUserConfig().setPinnedDialogsLoaded(update.folder_id, false);
                    getUserConfig().saveConfig(false);
                    ArrayList<Long> order;
                    if ((update.flags & 1) != 0) {
                        order = new ArrayList<>();
                        ArrayList<TLRPC.DialogPeer> peers = update.order;
                        for (int b = 0, size2 = peers.size(); b < size2; b++) {
                            long did;
                            TLRPC.DialogPeer dialogPeer = peers.get(b);
                            if (dialogPeer instanceof TLRPC.TL_dialogPeer) {
                                TLRPC.Peer peer = ((TLRPC.TL_dialogPeer) dialogPeer).peer;
                                if (peer.user_id != 0) {
                                    did = peer.user_id;
                                } else if (peer.chat_id != 0) {
                                    did = -peer.chat_id;
                                } else {
                                    did = -peer.channel_id;
                                }
                            } else {
                                did = 0;
                            }
                            order.add(did);
                        }
                    } else {
                        order = null;
                    }
                    loadPinnedDialogs(update.folder_id, 0, order);
                } else if (baseUpdate instanceof TLRPC.TL_updateUserPhoto) {
                    TLRPC.TL_updateUserPhoto update = (TLRPC.TL_updateUserPhoto) baseUpdate;
                    TLRPC.User currentUser = getUser(update.user_id);
                    if (currentUser != null) {
                        currentUser.photo = update.photo;
                    }
                    TLRPC.User toDbUser = new TLRPC.TL_user();
                    toDbUser.id = update.user_id;
                    toDbUser.photo = update.photo;
                    dbUsers.add(toDbUser);
                    if (UserObject.isUserSelf(currentUser)) {
                        getNotificationCenter().postNotificationName(NotificationCenter.mainUserInfoChanged);
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateUserPhone) {
                    TLRPC.TL_updateUserPhone update = (TLRPC.TL_updateUserPhone) baseUpdate;
                    TLRPC.User currentUser = getUser(update.user_id);
                    if (currentUser != null) {
                        currentUser.phone = update.phone;
                        Utilities.phoneBookQueue.postRunnable(() -> getContactsController().addContactToPhoneBook(currentUser, true));
                        if (UserObject.isUserSelf(currentUser)) {
                            getNotificationCenter().postNotificationName(NotificationCenter.mainUserInfoChanged);
                        }
                    }
                    TLRPC.User toDbUser = new TLRPC.TL_user();
                    toDbUser.id = update.user_id;
                    toDbUser.phone = update.phone;
                    dbUsers.add(toDbUser);
                } else if (baseUpdate instanceof TLRPC.TL_updateNotifySettings) {
                    TLRPC.TL_updateNotifySettings update = (TLRPC.TL_updateNotifySettings) baseUpdate;
                    if (update.notify_settings instanceof TLRPC.TL_peerNotifySettings) {
                        updateDialogFiltersFlags |= DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
                        if (editor == null) {
                            editor = notificationsPreferences.edit();
                        }
                        int currentTime1 = getConnectionsManager().getCurrentTime();
                        if (update.peer instanceof TLRPC.TL_notifyPeer) {
                            TLRPC.TL_notifyPeer notifyPeer = (TLRPC.TL_notifyPeer) update.peer;
                            long dialogId;
                            if (notifyPeer.peer.user_id != 0) {
                                dialogId = notifyPeer.peer.user_id;
                            } else if (notifyPeer.peer.chat_id != 0) {
                                dialogId = -notifyPeer.peer.chat_id;
                            } else {
                                dialogId = -notifyPeer.peer.channel_id;
                            }
                            TLRPC.Dialog dialog = dialogs_dict.get(dialogId);
                            if (dialog != null) {
                                dialog.notify_settings = update.notify_settings;
                            }
                            if ((update.notify_settings.flags & 2) != 0) {
                                editor.putBoolean("silent_" + dialogId, update.notify_settings.silent);
                            } else {
                                editor.remove("silent_" + dialogId);
                            }
                            if ((update.notify_settings.flags & 4) != 0) {
                                if (update.notify_settings.mute_until > currentTime1) {
                                    int until = 0;
                                    if (update.notify_settings.mute_until > currentTime1 + 60 * 60 * 24 * 365) {
                                        editor.putInt("notify2_" + dialogId, 2);
                                        if (dialog != null) {
                                            update.notify_settings.mute_until = Integer.MAX_VALUE;
                                        }
                                    } else {
                                        until = update.notify_settings.mute_until;
                                        editor.putInt("notify2_" + dialogId, 3);
                                        editor.putInt("notifyuntil_" + dialogId, update.notify_settings.mute_until);
                                        if (dialog != null) {
                                            update.notify_settings.mute_until = until;
                                        }
                                    }
                                    getMessagesStorage().setDialogFlags(dialogId, ((long) until << 32) | 1);
                                    getNotificationsController().removeNotificationsForDialog(dialogId);
                                } else {
                                    if (dialog != null) {
                                        update.notify_settings.mute_until = 0;
                                    }
                                    editor.putInt("notify2_" + dialogId, 0);
                                    getMessagesStorage().setDialogFlags(dialogId, 0);
                                }
                            } else {
                                if (dialog != null) {
                                    update.notify_settings.mute_until = 0;
                                }
                                editor.remove("notify2_" + dialogId);
                                getMessagesStorage().setDialogFlags(dialogId, 0);
                            }
                        } else if (update.peer instanceof TLRPC.TL_notifyChats) {
                            if ((update.notify_settings.flags & 1) != 0) {
                                editor.putBoolean("EnablePreviewGroup", update.notify_settings.show_previews);
                            }
                            if ((update.notify_settings.flags & 2) != 0) {
                            /*if (update.notify_settings.silent) {
                                        editor.putString("GroupSoundPath", "NoSound");
                                    } else {
                                        editor.remove("GroupSoundPath");
                                    }*/
                            }
                            if ((update.notify_settings.flags & 4) != 0) {
                                if (notificationsPreferences.getInt("EnableGroup2", 0) != update.notify_settings.mute_until) {
                                    editor.putInt("EnableGroup2", update.notify_settings.mute_until);
                                    editor.putBoolean("overwrite_group", true);
                                    AndroidUtilities.runOnUIThread(() -> getNotificationsController().deleteNotificationChannelGlobal(NotificationsController.TYPE_GROUP));
                                }
                            }
                        } else if (update.peer instanceof TLRPC.TL_notifyUsers) {
                            if ((update.notify_settings.flags & 1) != 0) {
                                editor.putBoolean("EnablePreviewAll", update.notify_settings.show_previews);
                            }
                            if ((update.notify_settings.flags & 2) != 0) {
                            /*if (update.notify_settings.silent) {
                                        editor.putString("GlobalSoundPath", "NoSound");
                                    } else {
                                        editor.remove("GlobalSoundPath");
                                    }*/
                            }
                            if ((update.notify_settings.flags & 4) != 0) {
                                if (notificationsPreferences.getInt("EnableAll2", 0) != update.notify_settings.mute_until) {
                                    editor.putInt("EnableAll2", update.notify_settings.mute_until);
                                    editor.putBoolean("overwrite_private", true);
                                    AndroidUtilities.runOnUIThread(() -> getNotificationsController().deleteNotificationChannelGlobal(NotificationsController.TYPE_PRIVATE));
                                }
                            }
                        } else if (update.peer instanceof TLRPC.TL_notifyBroadcasts) {
                            if ((update.notify_settings.flags & 1) != 0) {
                                editor.putBoolean("EnablePreviewChannel", update.notify_settings.show_previews);
                            }
                            if ((update.notify_settings.flags & 2) != 0) {
                            /*if (update.notify_settings.silent) {
                                        editor.putString("ChannelSoundPath", "NoSound");
                                    } else {
                                        editor.remove("ChannelSoundPath");
                                    }*/
                            }
                            if ((update.notify_settings.flags & 4) != 0) {
                                if (notificationsPreferences.getInt("EnableChannel2", 0) != update.notify_settings.mute_until) {
                                    editor.putInt("EnableChannel2", update.notify_settings.mute_until);
                                    editor.putBoolean("overwrite_channel", true);
                                    AndroidUtilities.runOnUIThread(() -> getNotificationsController().deleteNotificationChannelGlobal(NotificationsController.TYPE_CHANNEL));
                                }
                            }
                        }
                        getMessagesStorage().updateMutedDialogsFiltersCounters();
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateChannel) {
                    TLRPC.TL_updateChannel update = (TLRPC.TL_updateChannel) baseUpdate;
                    TLRPC.Dialog dialog = dialogs_dict.get(-update.channel_id);
                    TLRPC.Chat chat = getChat(update.channel_id);
                    if (chat != null) {
                        if (dialog == null && chat instanceof TLRPC.TL_channel && !chat.left) {
                            Utilities.stageQueue.postRunnable(() -> getChannelDifference(update.channel_id, 1, 0, null));
                        } else if (ChatObject.isNotInChat(chat) && dialog != null && (promoDialog == null || promoDialog.id != dialog.id)) {
                            deleteDialog(dialog.id, 0);
                        }
                        if (chat instanceof TLRPC.TL_channelForbidden || chat.kicked) {
                            ChatObject.Call call = getGroupCall(chat.id, false);
                            if (call != null) {
                                TLRPC.TL_updateGroupCall updateGroupCall = new TLRPC.TL_updateGroupCall();
                                updateGroupCall.chat_id = chat.id;
                                updateGroupCall.call = new TLRPC.TL_groupCallDiscarded();
                                updateGroupCall.call.id = call.call.id;
                                updateGroupCall.call.access_hash = call.call.access_hash;
                                call.processGroupCallUpdate(updateGroupCall);
                                if (VoIPService.getSharedInstance() != null) {
                                    VoIPService.getSharedInstance().onGroupCallUpdated(updateGroupCall.call);
                                }
                            }
                        }
                    }
                    updateMask |= UPDATE_MASK_CHAT;
                    loadFullChat(update.channel_id, 0, true);
                } else if (baseUpdate instanceof TLRPC.TL_updateChat) {
                    TLRPC.TL_updateChat update = (TLRPC.TL_updateChat) baseUpdate;
                    TLRPC.Chat chat = getChat(update.chat_id);
                    if (chat != null && (chat instanceof TLRPC.TL_chatForbidden || chat.kicked)) {
                        ChatObject.Call call = getGroupCall(chat.id, false);
                        if (call != null) {
                            TLRPC.TL_updateGroupCall updateGroupCall = new TLRPC.TL_updateGroupCall();
                            updateGroupCall.chat_id = chat.id;
                            updateGroupCall.call = new TLRPC.TL_groupCallDiscarded();
                            updateGroupCall.call.id = call.call.id;
                            updateGroupCall.call.access_hash = call.call.access_hash;
                            call.processGroupCallUpdate(updateGroupCall);
                            if (VoIPService.getSharedInstance() != null) {
                                VoIPService.getSharedInstance().onGroupCallUpdated(updateGroupCall.call);
                            }
                        }
                        TLRPC.Dialog dialog = dialogs_dict.get(-chat.id);
                        if (dialog != null) {
                            deleteDialog(dialog.id, 0);
                        }
                    }
                    updateMask |= UPDATE_MASK_CHAT;
                    loadFullChat(update.chat_id, 0, true);
                } else if (baseUpdate instanceof TLRPC.TL_updateChatDefaultBannedRights) {
                    TLRPC.TL_updateChatDefaultBannedRights update = (TLRPC.TL_updateChatDefaultBannedRights) baseUpdate;
                    long chatId;
                    if (update.peer.channel_id != 0) {
                        chatId = update.peer.channel_id;
                    } else {
                        chatId = update.peer.chat_id;
                    }
                    TLRPC.Chat chat = getChat(chatId);
                    if (chat != null) {
                        chat.default_banned_rights = update.default_banned_rights;
                        AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.channelRightsUpdated, chat));
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateBotCommands) {
                    TLRPC.TL_updateBotCommands update = (TLRPC.TL_updateBotCommands) baseUpdate;
                    getMediaDataController().updateBotInfo(MessageObject.getPeerId(update.peer), update);
                } else if (baseUpdate instanceof TLRPC.TL_updateStickerSets) {
                    TLRPC.TL_updateStickerSets update = (TLRPC.TL_updateStickerSets) baseUpdate;
                    getMediaDataController().loadStickers(MediaDataController.TYPE_IMAGE, false, true);
                } else if (baseUpdate instanceof TLRPC.TL_updateStickerSetsOrder) {
                    TLRPC.TL_updateStickerSetsOrder update = (TLRPC.TL_updateStickerSetsOrder) baseUpdate;
                    getMediaDataController().reorderStickers(update.masks ? MediaDataController.TYPE_MASK : MediaDataController.TYPE_IMAGE, ((TLRPC.TL_updateStickerSetsOrder) baseUpdate).order);
                } else if (baseUpdate instanceof TLRPC.TL_updateFavedStickers) {
                    getMediaDataController().loadRecents(MediaDataController.TYPE_FAVE, false, false, true);
                } else if (baseUpdate instanceof TLRPC.TL_updateContactsReset) {
                    getContactsController().forceImportContacts();
                } else if (baseUpdate instanceof TLRPC.TL_updateNewStickerSet) {
                    TLRPC.TL_updateNewStickerSet update = (TLRPC.TL_updateNewStickerSet) baseUpdate;
                    getMediaDataController().addNewStickerSet(update.stickerset);
                } else if (baseUpdate instanceof TLRPC.TL_updateSavedGifs) {
                    SharedPreferences.Editor editor2 = emojiPreferences.edit();
                    editor2.putLong("lastGifLoadTime", 0).commit();
                } else if (baseUpdate instanceof TLRPC.TL_updateRecentStickers) {
                    SharedPreferences.Editor editor2 = emojiPreferences.edit();
                    editor2.putLong("lastStickersLoadTime", 0).commit();
                } else if (baseUpdate instanceof TLRPC.TL_updateDraftMessage) {
                    TLRPC.TL_updateDraftMessage update = (TLRPC.TL_updateDraftMessage) baseUpdate;
                    forceDialogsUpdate = true;
                    long did;
                    TLRPC.Peer peer = ((TLRPC.TL_updateDraftMessage) baseUpdate).peer;
                    if (peer.user_id != 0) {
                        did = peer.user_id;
                    } else if (peer.channel_id != 0) {
                        did = -peer.channel_id;
                    } else {
                        did = -peer.chat_id;
                    }
                    getMediaDataController().saveDraft(did, 0, update.draft, null, true);
                } else if (baseUpdate instanceof TLRPC.TL_updateReadFeaturedStickers) {
                    getMediaDataController().markFaturedStickersAsRead(false);
                } else if (baseUpdate instanceof TLRPC.TL_updatePhoneCallSignalingData) {
                    TLRPC.TL_updatePhoneCallSignalingData data = (TLRPC.TL_updatePhoneCallSignalingData) baseUpdate;
                    VoIPService svc = VoIPService.getSharedInstance();
                    if (svc != null) {
                        svc.onSignalingData(data);
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateGroupCallParticipants) {
                    TLRPC.TL_updateGroupCallParticipants update = (TLRPC.TL_updateGroupCallParticipants) baseUpdate;
                    ChatObject.Call call = groupCalls.get(update.call.id);
                    if (call != null) {
                        call.processParticipantsUpdate(update, false);
                    }
                    if (VoIPService.getSharedInstance() != null) {
                        VoIPService.getSharedInstance().onGroupCallParticipantsUpdate(update);
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateGroupCall) {
                    TLRPC.TL_updateGroupCall update = (TLRPC.TL_updateGroupCall) baseUpdate;
                    ChatObject.Call call = groupCalls.get(update.call.id);
                    if (call != null) {
                        call.processGroupCallUpdate(update);
                        TLRPC.Chat chat = getChat(call.chatId);
                        if (chat != null) {
                            chat.call_active = update.call instanceof TLRPC.TL_groupCall;
                        }
                    } else {
                        TLRPC.ChatFull chatFull = getChatFull(update.chat_id);
                        if (chatFull != null && (chatFull.call == null || chatFull.call != null && chatFull.call.id != update.call.id)) {
                            loadFullChat(update.chat_id, 0, true);
                        }
                    }
                    if (VoIPService.getSharedInstance() != null) {
                        VoIPService.getSharedInstance().onGroupCallUpdated(update.call);
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updatePhoneCall) {
                    TLRPC.TL_updatePhoneCall upd = (TLRPC.TL_updatePhoneCall) baseUpdate;
                    TLRPC.PhoneCall call = upd.phone_call;
                    VoIPService svc = VoIPService.getSharedInstance();
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("Received call in update: " + call);
                        FileLog.d("call id " + call.id);
                    }
                    if (call instanceof TLRPC.TL_phoneCallRequested) {
                        if (call.date + callRingTimeout / 1000 < getConnectionsManager().getCurrentTime()) {
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("ignoring too old call");
                            }
                            continue;
                        }
                        boolean notificationsDisabled = false;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !NotificationManagerCompat.from(ApplicationLoader.applicationContext).areNotificationsEnabled()) {
                            notificationsDisabled = true;
                            if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) {
                                if (BuildVars.LOGS_ENABLED) {
                                    FileLog.d("Ignoring incoming call because notifications are disabled in system");
                                }
                                continue;
                            }
                        }
                        TelephonyManager tm = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
                        if (svc != null || VoIPService.callIShouldHavePutIntoIntent != null || tm.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("Auto-declining call " + call.id + " because there's already active one");
                            }
                            TLRPC.TL_phone_discardCall req = new TLRPC.TL_phone_discardCall();
                            req.peer = new TLRPC.TL_inputPhoneCall();
                            req.peer.access_hash = call.access_hash;
                            req.peer.id = call.id;
                            req.reason = new TLRPC.TL_phoneCallDiscardReasonBusy();
                            getConnectionsManager().sendRequest(req, (response, error) -> {
                                if (response != null) {
                                    TLRPC.Updates updates1 = (TLRPC.Updates) response;
                                    processUpdates(updates1, false);
                                }
                            });
                            continue;
                        }
                        if (BuildVars.LOGS_ENABLED) {
                            FileLog.d("Starting service for call " + call.id);
                        }
                        VoIPService.callIShouldHavePutIntoIntent = call;
                        Intent intent = new Intent(ApplicationLoader.applicationContext, VoIPService.class);
                        intent.putExtra("is_outgoing", false);
                        intent.putExtra("user_id", call.participant_id == getUserConfig().getClientUserId() ? call.admin_id : call.participant_id);
                        intent.putExtra("account", currentAccount);
                        intent.putExtra("notifications_disabled", notificationsDisabled);
                        try {
                            if (!notificationsDisabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                ApplicationLoader.applicationContext.startForegroundService(intent);
                            } else {
                                ApplicationLoader.applicationContext.startService(intent);
                            }
                            if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) {
                                ignoreSetOnline = true;
                            }
                        } catch (Throwable e) {
                            FileLog.e(e);
                        }
                    } else {
                        if (svc != null && call != null) {
                            svc.onCallUpdated(call);
                        } else if (VoIPService.callIShouldHavePutIntoIntent != null) {
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("Updated the call while the service is starting");
                            }
                            if (call.id == VoIPService.callIShouldHavePutIntoIntent.id) {
                                VoIPService.callIShouldHavePutIntoIntent = call;
                            }
                        }
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateDialogUnreadMark) {
                    TLRPC.TL_updateDialogUnreadMark update = (TLRPC.TL_updateDialogUnreadMark) baseUpdate;
                    long did;
                    if (update.peer instanceof TLRPC.TL_dialogPeer) {
                        TLRPC.TL_dialogPeer dialogPeer = (TLRPC.TL_dialogPeer) update.peer;
                        if (dialogPeer.peer.user_id != 0) {
                            did = dialogPeer.peer.user_id;
                        } else if (dialogPeer.peer.chat_id != 0) {
                            did = -dialogPeer.peer.chat_id;
                        } else {
                            did = -dialogPeer.peer.channel_id;
                        }
                    } else {
                        did = 0;
                    }
                    getMessagesStorage().setDialogUnread(did, update.unread);
                    TLRPC.Dialog dialog = dialogs_dict.get(did);
                    if (dialog != null && dialog.unread_mark != update.unread) {
                        dialog.unread_mark = update.unread;
                        if (dialog.unread_count == 0 && !isDialogMuted(did)) {
                            if (dialog.unread_mark) {
                                unreadUnmutedDialogs++;
                            } else {
                                unreadUnmutedDialogs--;
                            }
                        }
                        updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                        updateDialogFiltersFlags |= DIALOG_FILTER_FLAG_EXCLUDE_READ;
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateMessagePoll) {
                    TLRPC.TL_updateMessagePoll update = (TLRPC.TL_updateMessagePoll) baseUpdate;
                    getNotificationCenter().postNotificationName(NotificationCenter.didUpdatePollResults, update.poll_id, update.poll, update.results);
                } else if (baseUpdate instanceof TLRPC.TL_updatePeerSettings) {
                    TLRPC.TL_updatePeerSettings update = (TLRPC.TL_updatePeerSettings) baseUpdate;
                    long dialogId;
                    if (update.peer instanceof TLRPC.TL_peerUser) {
                        dialogId = update.peer.user_id;
                    } else if (update.peer instanceof TLRPC.TL_peerChat) {
                        dialogId = -update.peer.chat_id;
                    } else {
                        dialogId = -update.peer.channel_id;
                    }
                    savePeerSettings(dialogId, update.settings, true);
                } else if (baseUpdate instanceof TLRPC.TL_updatePeerLocated) {
                    getNotificationCenter().postNotificationName(NotificationCenter.newPeopleNearbyAvailable, baseUpdate);
                } else if (baseUpdate instanceof TLRPC.TL_updateMessageReactions) {
                    TLRPC.TL_updateMessageReactions update = (TLRPC.TL_updateMessageReactions) baseUpdate;
                    long dialogId = MessageObject.getPeerId(update.peer);
                    getNotificationCenter().postNotificationName(NotificationCenter.didUpdateReactions, dialogId, update.msg_id, update.reactions);
                } else if (baseUpdate instanceof TLRPC.TL_updateTheme) {
                    TLRPC.TL_updateTheme update = (TLRPC.TL_updateTheme) baseUpdate;
                    TLRPC.TL_theme theme = (TLRPC.TL_theme) update.theme;
                    Theme.setThemeUploadInfo(null, null, theme, currentAccount, true);
                } else if (baseUpdate instanceof TLRPC.TL_updateDialogFilter) {
                    loadRemoteFilters(true);
                } else if (baseUpdate instanceof TLRPC.TL_updateDialogFilterOrder) {
                    loadRemoteFilters(true);
                } else if (baseUpdate instanceof TLRPC.TL_updateDialogFilters) {
                    loadRemoteFilters(true);
                } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelDiscussionInbox) {
                    TLRPC.TL_updateReadChannelDiscussionInbox update = (TLRPC.TL_updateReadChannelDiscussionInbox) baseUpdate;
                    getNotificationCenter().postNotificationName(NotificationCenter.threadMessagesRead, -update.channel_id, update.top_msg_id, update.read_max_id, 0);
                    if ((update.flags & 1) != 0) {
                        getMessagesStorage().updateRepliesMaxReadId(update.broadcast_id, update.broadcast_post, update.read_max_id, true);
                        getNotificationCenter().postNotificationName(NotificationCenter.commentsRead, update.broadcast_id, update.broadcast_post, update.read_max_id);
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelDiscussionOutbox) {
                    TLRPC.TL_updateReadChannelDiscussionOutbox update = (TLRPC.TL_updateReadChannelDiscussionOutbox) baseUpdate;
                    getNotificationCenter().postNotificationName(NotificationCenter.threadMessagesRead, -update.channel_id, update.top_msg_id, 0, update.read_max_id);
                } else if (baseUpdate instanceof TLRPC.TL_updatePeerHistoryTTL) {
                    TLRPC.TL_updatePeerHistoryTTL updatePeerHistoryTTL = (TLRPC.TL_updatePeerHistoryTTL) baseUpdate;
                    long peerId = MessageObject.getPeerId(updatePeerHistoryTTL.peer);
                    TLRPC.ChatFull chatFull = null;
                    TLRPC.UserFull userFull = null;
                    if (peerId > 0) {
                        userFull = getUserFull(peerId);
                        if (userFull != null) {
                            userFull.ttl_period = updatePeerHistoryTTL.ttl_period;
                            if (userFull.ttl_period == 0) {
                                userFull.flags &= ~16384;
                            } else {
                                userFull.flags |= 16384;
                            }
                        }
                    } else {
                        chatFull = getChatFull(-peerId);
                        if (chatFull != null) {
                            chatFull.ttl_period = updatePeerHistoryTTL.ttl_period;
                            if (chatFull instanceof TLRPC.TL_channelFull) {
                                if (chatFull.ttl_period == 0) {
                                    chatFull.flags &= ~16777216;
                                } else {
                                    chatFull.flags |= 16777216;
                                }
                            } else {
                                if (chatFull.ttl_period == 0) {
                                    chatFull.flags &= ~16384;
                                } else {
                                    chatFull.flags |= 16384;
                                }
                            }
                        }
                    }
                    if (chatFull != null) {
                        getNotificationCenter().postNotificationName(NotificationCenter.chatInfoDidLoad, chatFull, 0, false, false);
                        getMessagesStorage().updateChatInfo(chatFull, false);
                    } else if (userFull != null) {
                        getNotificationCenter().postNotificationName(NotificationCenter.userInfoDidLoad, peerId, userFull);
                        getMessagesStorage().updateUserInfo(userFull, false);
                    }
                } else if (baseUpdate instanceof TLRPC.TL_updatePendingJoinRequests) {
                    TLRPC.TL_updatePendingJoinRequests update = (TLRPC.TL_updatePendingJoinRequests) baseUpdate;
                    getMemberRequestsController().onPendingRequestsUpdated(update);
                }
            }
            if (editor != null) {
                editor.commit();
                getNotificationCenter().postNotificationName(NotificationCenter.notificationsSettingsUpdated);
            }
            getMessagesStorage().updateUsers(dbUsersStatus, true, true, true);
            getMessagesStorage().updateUsers(dbUsers, false, true, true);
        }
        if (groupSpeakingActionsFinal != null) {
            for (int a = 0, N = groupSpeakingActionsFinal.size(); a < N; a++) {
                long chatId = groupSpeakingActionsFinal.keyAt(a);
                ChatObject.Call call = groupCallsByChatId.get(chatId);
                if (call != null) {
                    call.processTypingsUpdate(getAccountInstance(), groupSpeakingActionsFinal.valueAt(a), date);
                }
            }
        }
        if (importingActionsFinal != null) {
            for (int a = 0, N = importingActionsFinal.size(); a < N; a++) {
                long did = importingActionsFinal.keyAt(a);
                SendMessagesHelper.ImportingHistory importingHistory = getSendMessagesHelper().getImportingHistory(did);
                if (importingHistory == null) {
                    continue;
                }
                importingHistory.setImportProgress(importingActionsFinal.valueAt(a));
            }
        }
        if (webPagesFinal != null) {
            getNotificationCenter().postNotificationName(NotificationCenter.didReceivedWebpagesInUpdates, webPagesFinal);
            for (int i = 0; i < 2; i++) {
                HashMap<String, ArrayList<MessageObject>> map = i == 1 ? reloadingScheduledWebpages : reloadingWebpages;
                LongSparseArray<ArrayList<MessageObject>> array = i == 1 ? reloadingScheduledWebpagesPending : reloadingWebpagesPending;
                for (int b = 0, size = webPagesFinal.size(); b < size; b++) {
                    long key = webPagesFinal.keyAt(b);
                    ArrayList<MessageObject> arrayList = array.get(key);
                    array.remove(key);
                    if (arrayList != null) {
                        TLRPC.WebPage webpage = webPagesFinal.valueAt(b);
                        ArrayList<TLRPC.Message> arr = new ArrayList<>();
                        long dialogId = 0;
                        if (webpage instanceof TLRPC.TL_webPage || webpage instanceof TLRPC.TL_webPageEmpty) {
                            for (int a = 0, size2 = arrayList.size(); a < size2; a++) {
                                arrayList.get(a).messageOwner.media.webpage = webpage;
                                if (a == 0) {
                                    dialogId = arrayList.get(a).getDialogId();
                                    ImageLoader.saveMessageThumbs(arrayList.get(a).messageOwner);
                                }
                                arr.add(arrayList.get(a).messageOwner);
                            }
                        } else {
                            array.put(webpage.id, arrayList);
                        }
                        if (!arr.isEmpty()) {
                            getMessagesStorage().putMessages(arr, true, true, false, getDownloadController().getAutodownloadMask(), i == 1);
                            getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialogId, arrayList);
                        }
                    }
                }
            }
        }
        if (updateDialogFiltersFlags != 0) {
            for (int a = 0; a < selectedDialogFilter.length; a++) {
                if (selectedDialogFilter[a] != null && (selectedDialogFilter[a].flags & updateDialogFiltersFlags) != 0) {
                    forceDialogsUpdate = true;
                    break;
                }
            }
        }
        boolean updateDialogs = false;
        if (messagesFinal != null) {
            boolean sorted = false;
            for (int a = 0, size = messagesFinal.size(); a < size; a++) {
                long key = messagesFinal.keyAt(a);
                ArrayList<MessageObject> value = messagesFinal.valueAt(a);
                if (updateInterfaceWithMessages(key, value, false)) {
                    sorted = true;
                }
            }
            boolean applied = applyFoldersUpdates(folderUpdatesFinal);
            if (applied || !sorted && forceDialogsUpdate) {
                sortDialogs(null);
            }
            updateDialogs = true;
        } else {
            boolean applied = applyFoldersUpdates(folderUpdatesFinal);
            if (forceDialogsUpdate || applied) {
                sortDialogs(null);
                updateDialogs = true;
            }
        }
        if (scheduledMessagesFinal != null) {
            for (int a = 0, size = scheduledMessagesFinal.size(); a < size; a++) {
                long key = scheduledMessagesFinal.keyAt(a);
                ArrayList<MessageObject> value = scheduledMessagesFinal.valueAt(a);
                updateInterfaceWithMessages(key, value, true);
            }
        }
        if (editingMessagesFinal != null) {
            for (int b = 0, size = editingMessagesFinal.size(); b < size; b++) {
                long dialogId = editingMessagesFinal.keyAt(b);
                SparseBooleanArray unreadReactions = null;
                ArrayList<MessageObject> arrayList = editingMessagesFinal.valueAt(b);
                for (int a = 0, size2 = arrayList.size(); a < size2; a++) {
                    MessageObject messageObject = arrayList.get(a);
                    if (dialogId > 0) {
                        if (unreadReactions == null) {
                            unreadReactions = new SparseBooleanArray();
                        }
                        unreadReactions.put(messageObject.getId(), MessageObject.hasUnreadReactions(messageObject.messageOwner));
                    }
                }
                if (dialogId > 0) {
                    checkUnreadReactions(dialogId, unreadReactions);
                }
                MessageObject oldObject = dialogMessage.get(dialogId);
                if (oldObject != null) {
                    for (int a = 0, size2 = arrayList.size(); a < size2; a++) {
                        MessageObject newMessage = arrayList.get(a);
                        if (oldObject.getId() == newMessage.getId()) {
                            dialogMessage.put(dialogId, newMessage);
                            if (newMessage.messageOwner.peer_id != null && newMessage.messageOwner.peer_id.channel_id == 0) {
                                dialogMessagesByIds.put(newMessage.getId(), newMessage);
                            }
                            updateDialogs = true;
                            break;
                        } else if (oldObject.getDialogId() == newMessage.getDialogId() && oldObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage && oldObject.replyMessageObject != null && oldObject.replyMessageObject.getId() == newMessage.getId()) {
                            oldObject.replyMessageObject = newMessage;
                            oldObject.generatePinMessageText(null, null);
                            updateDialogs = true;
                            break;
                        }
                    }
                }
                getMediaDataController().loadReplyMessagesForMessages(arrayList, dialogId, false, null);
                getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialogId, arrayList, false);
            }
        }
        if (updateDialogs) {
            getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload);
        }
        if (printChangedArg) {
            updateMask |= UPDATE_MASK_USER_PRINT;
        }
        if (contactsIdsFinal != null) {
            updateMask |= UPDATE_MASK_NAME;
            updateMask |= UPDATE_MASK_USER_PHONE;
        }
        if (chatInfoToUpdateFinal != null) {
            for (int a = 0, size = chatInfoToUpdateFinal.size(); a < size; a++) {
                TLRPC.ChatParticipants info = chatInfoToUpdateFinal.get(a);
                getMessagesStorage().updateChatParticipants(info);
            }
        }
        if (channelViewsFinal != null || channelForwardsFinal != null || channelRepliesFinal != null) {
            getNotificationCenter().postNotificationName(NotificationCenter.didUpdateMessagesViews, channelViewsFinal, channelForwardsFinal, channelRepliesFinal, true);
        }
        if (updateMask != 0) {
            getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, updateMask);
        }
        if (updateMessageThumbs != null) {
            ImageLoader.getInstance().putThumbsToCache(updateMessageThumbs);
        }
    });
    LongSparseIntArray markAsReadMessagesInboxFinal = markAsReadMessagesInbox;
    LongSparseIntArray markAsReadMessagesOutboxFinal = markAsReadMessagesOutbox;
    LongSparseArray<ArrayList<Integer>> markContentAsReadMessagesFinal = markContentAsReadMessages;
    SparseIntArray markAsReadEncryptedFinal = markAsReadEncrypted;
    LongSparseArray<ArrayList<Integer>> deletedMessagesFinal = deletedMessages;
    LongSparseArray<ArrayList<Integer>> scheduledDeletedMessagesFinal = scheduledDeletedMessages;
    LongSparseIntArray clearHistoryMessagesFinal = clearHistoryMessages;
    getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> {
        int updateMask = 0;
        if (markAsReadMessagesInboxFinal != null || markAsReadMessagesOutboxFinal != null) {
            getNotificationCenter().postNotificationName(NotificationCenter.messagesRead, markAsReadMessagesInboxFinal, markAsReadMessagesOutboxFinal);
            if (markAsReadMessagesInboxFinal != null) {
                getNotificationsController().processReadMessages(markAsReadMessagesInboxFinal, 0, 0, 0, false);
                SharedPreferences.Editor editor = notificationsPreferences.edit();
                for (int b = 0, size = markAsReadMessagesInboxFinal.size(); b < size; b++) {
                    long key = markAsReadMessagesInboxFinal.keyAt(b);
                    int messageId = markAsReadMessagesInboxFinal.valueAt(b);
                    TLRPC.Dialog dialog = dialogs_dict.get(key);
                    if (dialog != null && dialog.top_message > 0 && dialog.top_message <= messageId) {
                        MessageObject obj = dialogMessage.get(dialog.id);
                        if (obj != null && !obj.isOut()) {
                            obj.setIsRead();
                            updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                        }
                    }
                    if (key != getUserConfig().getClientUserId()) {
                        editor.remove("diditem" + key);
                        editor.remove("diditemo" + key);
                    }
                }
                editor.commit();
            }
            if (markAsReadMessagesOutboxFinal != null) {
                for (int b = 0, size = markAsReadMessagesOutboxFinal.size(); b < size; b++) {
                    long key = markAsReadMessagesOutboxFinal.keyAt(b);
                    int messageId = markAsReadMessagesOutboxFinal.valueAt(b);
                    TLRPC.Dialog dialog = dialogs_dict.get(key);
                    if (dialog != null && dialog.top_message > 0 && dialog.top_message <= messageId) {
                        MessageObject obj = dialogMessage.get(dialog.id);
                        if (obj != null && obj.isOut()) {
                            obj.setIsRead();
                            updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                        }
                    }
                }
            }
        }
        if (markAsReadEncryptedFinal != null) {
            for (int a = 0, size = markAsReadEncryptedFinal.size(); a < size; a++) {
                int key = markAsReadEncryptedFinal.keyAt(a);
                int value = markAsReadEncryptedFinal.valueAt(a);
                getNotificationCenter().postNotificationName(NotificationCenter.messagesReadEncrypted, key, value);
                long dialogId = DialogObject.makeEncryptedDialogId(key);
                TLRPC.Dialog dialog = dialogs_dict.get(dialogId);
                if (dialog != null) {
                    MessageObject message = dialogMessage.get(dialogId);
                    if (message != null && message.messageOwner.date <= value) {
                        message.setIsRead();
                        updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
                    }
                }
            }
        }
        if (markContentAsReadMessagesFinal != null) {
            for (int a = 0, size = markContentAsReadMessagesFinal.size(); a < size; a++) {
                long key = markContentAsReadMessagesFinal.keyAt(a);
                ArrayList<Integer> value = markContentAsReadMessagesFinal.valueAt(a);
                getNotificationCenter().postNotificationName(NotificationCenter.messagesReadContent, key, value);
            }
        }
        if (deletedMessagesFinal != null) {
            for (int a = 0, size = deletedMessagesFinal.size(); a < size; a++) {
                long dialogId = deletedMessagesFinal.keyAt(a);
                ArrayList<Integer> arrayList = deletedMessagesFinal.valueAt(a);
                if (arrayList == null) {
                    continue;
                }
                getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, arrayList, -dialogId, false);
                if (dialogId == 0) {
                    for (int b = 0, size2 = arrayList.size(); b < size2; b++) {
                        Integer id = arrayList.get(b);
                        MessageObject obj = dialogMessagesByIds.get(id);
                        if (obj != null) {
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("mark messages " + obj.getId() + " deleted");
                            }
                            obj.deleted = true;
                        }
                    }
                } else {
                    MessageObject obj = dialogMessage.get(dialogId);
                    if (obj != null) {
                        for (int b = 0, size2 = arrayList.size(); b < size2; b++) {
                            if (obj.getId() == arrayList.get(b)) {
                                obj.deleted = true;
                                break;
                            }
                        }
                    }
                }
            }
            getNotificationsController().removeDeletedMessagesFromNotifications(deletedMessagesFinal);
        }
        if (scheduledDeletedMessagesFinal != null) {
            for (int a = 0, size = scheduledDeletedMessagesFinal.size(); a < size; a++) {
                long key = scheduledDeletedMessagesFinal.keyAt(a);
                ArrayList<Integer> arrayList = scheduledDeletedMessagesFinal.valueAt(a);
                if (arrayList == null) {
                    continue;
                }
                getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, arrayList, DialogObject.isChatDialog(key) && ChatObject.isChannel(getChat(-key)) ? -key : 0, true);
            }
        }
        if (clearHistoryMessagesFinal != null) {
            for (int a = 0, size = clearHistoryMessagesFinal.size(); a < size; a++) {
                long key = clearHistoryMessagesFinal.keyAt(a);
                int id = clearHistoryMessagesFinal.valueAt(a);
                long did = -key;
                getNotificationCenter().postNotificationName(NotificationCenter.historyCleared, did, id);
                MessageObject obj = dialogMessage.get(did);
                if (obj != null) {
                    if (obj.getId() <= id) {
                        obj.deleted = true;
                        break;
                    }
                }
            }
            getNotificationsController().removeDeletedHisoryFromNotifications(clearHistoryMessagesFinal);
        }
        if (updateMask != 0) {
            getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, updateMask);
        }
    }));
    if (webPages != null) {
        getMessagesStorage().putWebPages(webPages);
    }
    if (markAsReadMessagesInbox != null || markAsReadMessagesOutbox != null || markAsReadEncrypted != null || markContentAsReadMessages != null) {
        if (markAsReadMessagesInbox != null || markAsReadMessagesOutbox != null || markContentAsReadMessages != null) {
            getMessagesStorage().updateDialogsWithReadMessages(markAsReadMessagesInbox, markAsReadMessagesOutbox, markContentAsReadMessages, true);
        }
        getMessagesStorage().markMessagesAsRead(markAsReadMessagesInbox, markAsReadMessagesOutbox, markAsReadEncrypted, true);
    }
    if (markContentAsReadMessages != null) {
        int time = getConnectionsManager().getCurrentTime();
        for (int a = 0, size = markContentAsReadMessages.size(); a < size; a++) {
            long key = markContentAsReadMessages.keyAt(a);
            ArrayList<Integer> arrayList = markContentAsReadMessages.valueAt(a);
            getMessagesStorage().markMessagesContentAsRead(key, arrayList, time);
        }
    }
    if (deletedMessages != null) {
        for (int a = 0, size = deletedMessages.size(); a < size; a++) {
            long key = deletedMessages.keyAt(a);
            ArrayList<Integer> arrayList = deletedMessages.valueAt(a);
            getMessagesStorage().getStorageQueue().postRunnable(() -> {
                ArrayList<Long> dialogIds = getMessagesStorage().markMessagesAsDeleted(key, arrayList, false, true, false);
                getMessagesStorage().updateDialogsWithDeletedMessages(key, -key, arrayList, dialogIds, false);
            });
        }
    }
    if (scheduledDeletedMessages != null) {
        for (int a = 0, size = scheduledDeletedMessages.size(); a < size; a++) {
            long key = scheduledDeletedMessages.keyAt(a);
            ArrayList<Integer> arrayList = scheduledDeletedMessages.valueAt(a);
            getMessagesStorage().markMessagesAsDeleted(key, arrayList, true, false, true);
        }
    }
    if (clearHistoryMessages != null) {
        for (int a = 0, size = clearHistoryMessages.size(); a < size; a++) {
            long key = clearHistoryMessages.keyAt(a);
            int id = clearHistoryMessages.valueAt(a);
            getMessagesStorage().getStorageQueue().postRunnable(() -> {
                ArrayList<Long> dialogIds = getMessagesStorage().markMessagesAsDeleted(key, id, false, true);
                getMessagesStorage().updateDialogsWithDeletedMessages(key, -key, new ArrayList<>(), dialogIds, false);
            });
        }
    }
    if (tasks != null) {
        for (int a = 0, size = tasks.size(); a < size; a++) {
            TLRPC.TL_updateEncryptedMessagesRead update = tasks.get(a);
            getMessagesStorage().createTaskForSecretChat(update.chat_id, update.max_date, update.date, 1, null);
        }
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) SparseIntArray(android.util.SparseIntArray) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Intent(android.content.Intent) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) TLRPC(org.telegram.tgnet.TLRPC) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) LongSparseArray(androidx.collection.LongSparseArray) VoIPService(org.telegram.messenger.voip.VoIPService) SparseBooleanArray(android.util.SparseBooleanArray) SharedPreferences(android.content.SharedPreferences) TelephonyManager(android.telephony.TelephonyManager) SparseArray(android.util.SparseArray) LongSparseArray(androidx.collection.LongSparseArray)

Example 2 with LongSparseIntArray

use of org.telegram.messenger.support.LongSparseIntArray in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesController method processDialogsUpdate.

public void processDialogsUpdate(final TLRPC.messages_Dialogs dialogsRes, ArrayList<TLRPC.EncryptedChat> encChats, boolean fromCache) {
    Utilities.stageQueue.postRunnable(() -> {
        LongSparseArray<TLRPC.Dialog> new_dialogs_dict = new LongSparseArray<>();
        LongSparseArray<MessageObject> new_dialogMessage = new LongSparseArray<>();
        LongSparseArray<TLRPC.User> usersDict = new LongSparseArray<>(dialogsRes.users.size());
        LongSparseArray<TLRPC.Chat> chatsDict = new LongSparseArray<>(dialogsRes.chats.size());
        LongSparseIntArray dialogsToUpdate = new LongSparseIntArray();
        for (int a = 0; a < dialogsRes.users.size(); a++) {
            TLRPC.User u = dialogsRes.users.get(a);
            usersDict.put(u.id, u);
        }
        for (int a = 0; a < dialogsRes.chats.size(); a++) {
            TLRPC.Chat c = dialogsRes.chats.get(a);
            chatsDict.put(c.id, c);
        }
        for (int a = 0; a < dialogsRes.messages.size(); a++) {
            TLRPC.Message message = dialogsRes.messages.get(a);
            if (promoDialogId == 0 || promoDialogId != message.dialog_id) {
                if (message.peer_id.channel_id != 0) {
                    TLRPC.Chat chat = chatsDict.get(message.peer_id.channel_id);
                    if (chat != null && ChatObject.isNotInChat(chat)) {
                        continue;
                    }
                } else if (message.peer_id.chat_id != 0) {
                    TLRPC.Chat chat = chatsDict.get(message.peer_id.chat_id);
                    if (chat != null && (chat.migrated_to != null || ChatObject.isNotInChat(chat))) {
                        continue;
                    }
                }
            }
            MessageObject messageObject = new MessageObject(currentAccount, message, usersDict, chatsDict, false, true);
            new_dialogMessage.put(messageObject.getDialogId(), messageObject);
        }
        for (int a = 0; a < dialogsRes.dialogs.size(); a++) {
            TLRPC.Dialog d = dialogsRes.dialogs.get(a);
            DialogObject.initDialog(d);
            if (promoDialogId == 0 || promoDialogId != d.id) {
                if (DialogObject.isChannel(d)) {
                    TLRPC.Chat chat = chatsDict.get(-d.id);
                    if (chat != null && ChatObject.isNotInChat(chat)) {
                        continue;
                    }
                } else if (DialogObject.isChatDialog(d.id)) {
                    TLRPC.Chat chat = chatsDict.get(-d.id);
                    if (chat != null && (chat.migrated_to != null || ChatObject.isNotInChat(chat))) {
                        continue;
                    }
                }
            }
            if (d.last_message_date == 0) {
                MessageObject mess = new_dialogMessage.get(d.id);
                if (mess != null) {
                    d.last_message_date = mess.messageOwner.date;
                }
            }
            new_dialogs_dict.put(d.id, d);
            dialogsToUpdate.put(d.id, d.unread_count);
            Integer value = dialogs_read_inbox_max.get(d.id);
            if (value == null) {
                value = 0;
            }
            dialogs_read_inbox_max.put(d.id, Math.max(value, d.read_inbox_max_id));
            value = dialogs_read_outbox_max.get(d.id);
            if (value == null) {
                value = 0;
            }
            dialogs_read_outbox_max.put(d.id, Math.max(value, d.read_outbox_max_id));
        }
        AndroidUtilities.runOnUIThread(() -> {
            putUsers(dialogsRes.users, true);
            putChats(dialogsRes.chats, true);
            for (int a = 0; a < new_dialogs_dict.size(); a++) {
                long key = new_dialogs_dict.keyAt(a);
                if (BuildVars.LOGS_ENABLED) {
                    FileLog.d("processDialogsUpdate " + key);
                }
                TLRPC.Dialog value = new_dialogs_dict.valueAt(a);
                TLRPC.Dialog currentDialog = dialogs_dict.get(key);
                MessageObject newMsg = new_dialogMessage.get(value.id);
                if (currentDialog == null) {
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("processDialogsUpdate dialog null");
                    }
                    int offset = nextDialogsCacheOffset.get(value.folder_id, 0) + 1;
                    nextDialogsCacheOffset.put(value.folder_id, offset);
                    dialogs_dict.put(key, value);
                    dialogMessage.put(key, newMsg);
                    if (newMsg == null) {
                        if (fromCache) {
                            checkLastDialogMessage(value, null, 0);
                        }
                        if (BuildVars.LOGS_ENABLED) {
                            FileLog.d("processDialogsUpdate new message is null");
                        }
                    } else if (newMsg.messageOwner.peer_id.channel_id == 0) {
                        dialogMessagesByIds.put(newMsg.getId(), newMsg);
                        dialogsLoadedTillDate = Math.min(dialogsLoadedTillDate, newMsg.messageOwner.date);
                        if (newMsg.messageOwner.random_id != 0) {
                            dialogMessagesByRandomIds.put(newMsg.messageOwner.random_id, newMsg);
                        }
                        if (BuildVars.LOGS_ENABLED) {
                            FileLog.d("processDialogsUpdate new message not null");
                        }
                    }
                } else {
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("processDialogsUpdate dialog not null");
                    }
                    currentDialog.unread_count = value.unread_count;
                    if (currentDialog.unread_mentions_count != value.unread_mentions_count) {
                        currentDialog.unread_mentions_count = value.unread_mentions_count;
                        if (createdDialogMainThreadIds.contains(currentDialog.id)) {
                            getNotificationCenter().postNotificationName(NotificationCenter.updateMentionsCount, currentDialog.id, currentDialog.unread_mentions_count);
                        }
                    }
                    if (currentDialog.unread_reactions_count != value.unread_reactions_count) {
                        currentDialog.unread_reactions_count = value.unread_reactions_count;
                        getNotificationCenter().postNotificationName(NotificationCenter.dialogsUnreadReactionsCounterChanged, currentDialog.id, currentDialog.unread_reactions_count, null);
                    }
                    MessageObject oldMsg = dialogMessage.get(key);
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("processDialogsUpdate oldMsg " + oldMsg + " old top_message = " + currentDialog.top_message + " new top_message = " + value.top_message);
                        FileLog.d("processDialogsUpdate oldMsgDeleted " + (oldMsg != null && oldMsg.deleted));
                    }
                    if (oldMsg == null || currentDialog.top_message > 0) {
                        if (oldMsg != null && oldMsg.deleted || value.top_message > currentDialog.top_message) {
                            dialogs_dict.put(key, value);
                            dialogMessage.put(key, newMsg);
                            if (oldMsg != null && oldMsg.messageOwner.peer_id.channel_id == 0) {
                                dialogMessagesByIds.remove(oldMsg.getId());
                                if (oldMsg.messageOwner.random_id != 0) {
                                    dialogMessagesByRandomIds.remove(oldMsg.messageOwner.random_id);
                                }
                            }
                            if (newMsg != null) {
                                if (oldMsg != null && oldMsg.getId() == newMsg.getId()) {
                                    newMsg.deleted = oldMsg.deleted;
                                }
                                if (newMsg.messageOwner.peer_id.channel_id == 0) {
                                    dialogMessagesByIds.put(newMsg.getId(), newMsg);
                                    dialogsLoadedTillDate = Math.min(dialogsLoadedTillDate, newMsg.messageOwner.date);
                                    if (newMsg.messageOwner.random_id != 0) {
                                        dialogMessagesByRandomIds.put(newMsg.messageOwner.random_id, newMsg);
                                    }
                                }
                            }
                        }
                        if (fromCache && newMsg == null) {
                            checkLastDialogMessage(value, null, 0);
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("processDialogsUpdate new message is null");
                            }
                        }
                    } else {
                        if (oldMsg.deleted || newMsg == null || newMsg.messageOwner.date > oldMsg.messageOwner.date) {
                            dialogs_dict.put(key, value);
                            dialogMessage.put(key, newMsg);
                            if (oldMsg.messageOwner.peer_id.channel_id == 0) {
                                dialogMessagesByIds.remove(oldMsg.getId());
                            }
                            if (newMsg != null) {
                                if (oldMsg.getId() == newMsg.getId()) {
                                    newMsg.deleted = oldMsg.deleted;
                                }
                                if (newMsg.messageOwner.peer_id.channel_id == 0) {
                                    dialogMessagesByIds.put(newMsg.getId(), newMsg);
                                    dialogsLoadedTillDate = Math.min(dialogsLoadedTillDate, newMsg.messageOwner.date);
                                    if (newMsg.messageOwner.random_id != 0) {
                                        dialogMessagesByRandomIds.put(newMsg.messageOwner.random_id, newMsg);
                                    }
                                }
                            }
                            if (oldMsg.messageOwner.random_id != 0) {
                                dialogMessagesByRandomIds.remove(oldMsg.messageOwner.random_id);
                            }
                        }
                    }
                }
            }
            allDialogs.clear();
            for (int a = 0, size = dialogs_dict.size(); a < size; a++) {
                TLRPC.Dialog dialog = dialogs_dict.valueAt(a);
                if (deletingDialogs.indexOfKey(dialog.id) >= 0) {
                    continue;
                }
                allDialogs.add(dialog);
            }
            sortDialogs(null);
            getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload);
            getNotificationsController().processDialogsUpdateRead(dialogsToUpdate);
        });
    });
}
Also used : LongSparseArray(androidx.collection.LongSparseArray) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) TLRPC(org.telegram.tgnet.TLRPC) AlertDialog(org.telegram.ui.ActionBar.AlertDialog)

Example 3 with LongSparseIntArray

use of org.telegram.messenger.support.LongSparseIntArray in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesController method markDialogAsRead.

public void markDialogAsRead(long dialogId, int maxPositiveId, int maxNegativeId, int maxDate, boolean popup, int threadId, int countDiff, boolean readNow, int scheduledCount) {
    boolean createReadTask;
    if (threadId != 0) {
        createReadTask = maxPositiveId != Integer.MAX_VALUE;
    } else {
        boolean countMessages = getNotificationsController().showBadgeMessages;
        if (!DialogObject.isEncryptedDialog(dialogId)) {
            if (maxPositiveId == 0) {
                return;
            }
            Integer value = dialogs_read_inbox_max.get(dialogId);
            if (value == null) {
                value = 0;
            }
            dialogs_read_inbox_max.put(dialogId, Math.max(value, maxPositiveId));
            getMessagesStorage().processPendingRead(dialogId, maxPositiveId, maxNegativeId, scheduledCount);
            getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> {
                TLRPC.Dialog dialog = dialogs_dict.get(dialogId);
                if (dialog != null) {
                    int prevCount = dialog.unread_count;
                    if (countDiff == 0 || maxPositiveId >= dialog.top_message) {
                        dialog.unread_count = 0;
                    } else {
                        dialog.unread_count = Math.max(dialog.unread_count - countDiff, 0);
                        if (maxPositiveId != Integer.MIN_VALUE && dialog.unread_count > dialog.top_message - maxPositiveId) {
                            dialog.unread_count = dialog.top_message - maxPositiveId;
                        }
                    }
                    boolean wasUnread;
                    if (wasUnread = dialog.unread_mark) {
                        dialog.unread_mark = false;
                        getMessagesStorage().setDialogUnread(dialog.id, false);
                    }
                    if ((prevCount != 0 || wasUnread) && dialog.unread_count == 0) {
                        if (!isDialogMuted(dialogId)) {
                            unreadUnmutedDialogs--;
                        }
                        for (int b = 0; b < selectedDialogFilter.length; b++) {
                            if (selectedDialogFilter[b] != null && (selectedDialogFilter[b].flags & DIALOG_FILTER_FLAG_EXCLUDE_READ) != 0) {
                                sortDialogs(null);
                                getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload);
                                break;
                            }
                        }
                    }
                    getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_READ_DIALOG_MESSAGE);
                }
                if (!popup) {
                    getNotificationsController().processReadMessages(null, dialogId, 0, maxPositiveId, false);
                    LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(1);
                    dialogsToUpdate.put(dialogId, 0);
                    getNotificationsController().processDialogsUpdateRead(dialogsToUpdate);
                } else {
                    getNotificationsController().processReadMessages(null, dialogId, 0, maxPositiveId, true);
                    LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(1);
                    dialogsToUpdate.put(dialogId, -1);
                    getNotificationsController().processDialogsUpdateRead(dialogsToUpdate);
                }
            }));
            createReadTask = maxPositiveId != Integer.MAX_VALUE;
        } else {
            if (maxDate == 0) {
                return;
            }
            createReadTask = true;
            TLRPC.EncryptedChat chat = getEncryptedChat(DialogObject.getEncryptedChatId(dialogId));
            getMessagesStorage().processPendingRead(dialogId, maxPositiveId, maxNegativeId, scheduledCount);
            getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> {
                getNotificationsController().processReadMessages(null, dialogId, maxDate, 0, popup);
                TLRPC.Dialog dialog = dialogs_dict.get(dialogId);
                if (dialog != null) {
                    int prevCount = dialog.unread_count;
                    if (countDiff == 0 || maxNegativeId <= dialog.top_message) {
                        dialog.unread_count = 0;
                    } else {
                        dialog.unread_count = Math.max(dialog.unread_count - countDiff, 0);
                        if (maxNegativeId != Integer.MAX_VALUE && dialog.unread_count > maxNegativeId - dialog.top_message) {
                            dialog.unread_count = maxNegativeId - dialog.top_message;
                        }
                    }
                    boolean wasUnread;
                    if (wasUnread = dialog.unread_mark) {
                        dialog.unread_mark = false;
                        getMessagesStorage().setDialogUnread(dialog.id, false);
                    }
                    if ((prevCount != 0 || wasUnread) && dialog.unread_count == 0) {
                        if (!isDialogMuted(dialogId)) {
                            unreadUnmutedDialogs--;
                        }
                        for (int b = 0; b < selectedDialogFilter.length; b++) {
                            if (selectedDialogFilter[b] != null && (selectedDialogFilter[b].flags & DIALOG_FILTER_FLAG_EXCLUDE_READ) != 0) {
                                sortDialogs(null);
                                getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload);
                                break;
                            }
                        }
                    }
                    getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_READ_DIALOG_MESSAGE);
                }
                LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(1);
                dialogsToUpdate.put(dialogId, 0);
                getNotificationsController().processDialogsUpdateRead(dialogsToUpdate);
            }));
            if (chat != null && chat.ttl > 0) {
                int serverTime = Math.max(getConnectionsManager().getCurrentTime(), maxDate);
                getMessagesStorage().createTaskForSecretChat(chat.id, maxDate, serverTime, 0, null);
            }
        }
    }
    if (createReadTask) {
        Utilities.stageQueue.postRunnable(() -> {
            ReadTask currentReadTask;
            if (threadId != 0) {
                currentReadTask = threadsReadTasksMap.get(dialogId + "_" + threadId);
            } else {
                currentReadTask = readTasksMap.get(dialogId);
            }
            if (currentReadTask == null) {
                currentReadTask = new ReadTask();
                currentReadTask.dialogId = dialogId;
                currentReadTask.replyId = threadId;
                currentReadTask.sendRequestTime = SystemClock.elapsedRealtime() + 5000;
                if (!readNow) {
                    if (threadId != 0) {
                        threadsReadTasksMap.put(dialogId + "_" + threadId, currentReadTask);
                        repliesReadTasks.add(currentReadTask);
                    } else {
                        readTasksMap.put(dialogId, currentReadTask);
                        readTasks.add(currentReadTask);
                    }
                }
            }
            currentReadTask.maxDate = maxDate;
            currentReadTask.maxId = maxPositiveId;
            if (readNow) {
                completeReadTask(currentReadTask);
            }
        });
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) TLRPC(org.telegram.tgnet.TLRPC)

Example 4 with LongSparseIntArray

use of org.telegram.messenger.support.LongSparseIntArray in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesStorage method updateFiltersReadCounter.

private void updateFiltersReadCounter(LongSparseIntArray dialogsToUpdate, LongSparseIntArray dialogsToUpdateMentions, boolean read) throws Exception {
    if ((dialogsToUpdate == null || dialogsToUpdate.size() == 0) && (dialogsToUpdateMentions == null || dialogsToUpdateMentions.size() == 0)) {
        return;
    }
    for (int a = 0; a < 2; a++) {
        for (int b = 0; b < 2; b++) {
            contacts[a][b] = nonContacts[a][b] = bots[a][b] = channels[a][b] = groups[a][b] = 0;
        }
        mentionChannels[a] = mentionGroups[a] = 0;
    }
    ArrayList<TLRPC.User> users = new ArrayList<>();
    ArrayList<TLRPC.User> encUsers = new ArrayList<>();
    ArrayList<TLRPC.Chat> chats = new ArrayList<>();
    ArrayList<Long> usersToLoad = new ArrayList<>();
    ArrayList<Long> chatsToLoad = new ArrayList<>();
    ArrayList<Integer> encryptedToLoad = new ArrayList<>();
    LongSparseArray<Integer> dialogsByFolders = new LongSparseArray<>();
    LongSparseArray<Integer> newUnreadDialogs = new LongSparseArray<>();
    for (int b = 0; b < 2; b++) {
        LongSparseIntArray array = b == 0 ? dialogsToUpdate : dialogsToUpdateMentions;
        if (array == null) {
            continue;
        }
        for (int a = 0; a < array.size(); a++) {
            Integer count = array.valueAt(a);
            if (read && count != 0 || !read && count == 0) {
                continue;
            }
            long did = array.keyAt(a);
            if (read) {
                if (b == 0) {
                    dialogsWithUnread.remove(did);
                /*if (BuildVars.DEBUG_VERSION) {
                            FileLog.d("read remove = " + did);
                        }*/
                } else {
                    dialogsWithMentions.remove(did);
                /*if (BuildVars.DEBUG_VERSION) {
                            FileLog.d("mention remove = " + did);
                        }*/
                }
            } else {
                if (dialogsWithMentions.indexOfKey(did) < 0 && dialogsWithUnread.indexOfKey(did) < 0) {
                    newUnreadDialogs.put(did, count);
                }
                if (b == 0) {
                    dialogsWithUnread.put(did, count);
                /*if (BuildVars.DEBUG_VERSION) {
                            FileLog.d("read add = " + did);
                        }*/
                } else {
                    dialogsWithMentions.put(did, count);
                /*if (BuildVars.DEBUG_VERSION) {
                            FileLog.d("mention add = " + did);
                        }*/
                }
            }
            if (dialogsByFolders.indexOfKey(did) < 0) {
                SQLiteCursor cursor = database.queryFinalized("SELECT folder_id FROM dialogs WHERE did = " + did);
                int folderId = 0;
                if (cursor.next()) {
                    folderId = cursor.intValue(0);
                }
                cursor.dispose();
                dialogsByFolders.put(did, folderId);
            }
            if (DialogObject.isEncryptedDialog(did)) {
                int encryptedChatId = DialogObject.getEncryptedChatId(did);
                if (!encryptedToLoad.contains(encryptedChatId)) {
                    encryptedToLoad.add(encryptedChatId);
                }
            } else if (DialogObject.isUserDialog(did)) {
                if (!usersToLoad.contains(did)) {
                    usersToLoad.add(did);
                }
            } else {
                if (!chatsToLoad.contains(-did)) {
                    chatsToLoad.add(-did);
                }
            }
        }
    }
    LongSparseArray<TLRPC.User> usersDict = new LongSparseArray<>();
    LongSparseArray<TLRPC.Chat> chatsDict = new LongSparseArray<>();
    LongSparseArray<TLRPC.User> encUsersDict = new LongSparseArray<>();
    LongSparseArray<Integer> encryptedChatsByUsersCount = new LongSparseArray<>();
    LongSparseArray<Boolean> mutedDialogs = new LongSparseArray<>();
    LongSparseArray<Boolean> archivedDialogs = new LongSparseArray<>();
    if (!usersToLoad.isEmpty()) {
        getUsersInternal(TextUtils.join(",", usersToLoad), users);
        for (int a = 0, N = users.size(); a < N; a++) {
            TLRPC.User user = users.get(a);
            boolean muted = getMessagesController().isDialogMuted(user.id);
            int idx1 = dialogsByFolders.get(user.id);
            int idx2 = muted ? 1 : 0;
            if (muted) {
                mutedDialogs.put(user.id, true);
            }
            if (idx1 == 1) {
                archivedDialogs.put(user.id, true);
            }
            if (user.bot) {
                bots[idx1][idx2]++;
            } else if (user.self || user.contact) {
                contacts[idx1][idx2]++;
            } else {
                nonContacts[idx1][idx2]++;
            }
            usersDict.put(user.id, user);
        }
    }
    if (!encryptedToLoad.isEmpty()) {
        ArrayList<Long> encUsersToLoad = new ArrayList<>();
        ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<>();
        getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, encUsersToLoad);
        if (!encUsersToLoad.isEmpty()) {
            getUsersInternal(TextUtils.join(",", encUsersToLoad), encUsers);
            for (int a = 0, N = encUsers.size(); a < N; a++) {
                TLRPC.User user = encUsers.get(a);
                encUsersDict.put(user.id, user);
            }
            for (int a = 0, N = encryptedChats.size(); a < N; a++) {
                TLRPC.EncryptedChat encryptedChat = encryptedChats.get(a);
                TLRPC.User user = encUsersDict.get(encryptedChat.user_id);
                if (user == null) {
                    continue;
                }
                long did = DialogObject.makeEncryptedDialogId(encryptedChat.id);
                boolean muted = getMessagesController().isDialogMuted(did);
                int idx1 = dialogsByFolders.get(did);
                int idx2 = muted ? 1 : 0;
                if (muted) {
                    mutedDialogs.put(user.id, true);
                }
                if (idx1 == 1) {
                    archivedDialogs.put(user.id, true);
                }
                if (user.self || user.contact) {
                    contacts[idx1][idx2]++;
                } else {
                    nonContacts[idx1][idx2]++;
                }
                int count = encryptedChatsByUsersCount.get(user.id, 0);
                encryptedChatsByUsersCount.put(user.id, count + 1);
            }
        }
    }
    if (!chatsToLoad.isEmpty()) {
        getChatsInternal(TextUtils.join(",", chatsToLoad), chats);
        for (int a = 0, N = chats.size(); a < N; a++) {
            TLRPC.Chat chat = chats.get(a);
            if (chat.migrated_to instanceof TLRPC.TL_inputChannel || ChatObject.isNotInChat(chat)) {
                continue;
            }
            boolean muted = getMessagesController().isDialogMuted(-chat.id, chat);
            boolean hasUnread = dialogsWithUnread.indexOfKey(-chat.id) >= 0;
            boolean hasMention = dialogsWithMentions.indexOfKey(-chat.id) >= 0;
            int idx1 = dialogsByFolders.get(-chat.id);
            int idx2 = muted ? 1 : 0;
            if (muted) {
                mutedDialogs.put(-chat.id, true);
            }
            if (idx1 == 1) {
                archivedDialogs.put(-chat.id, true);
            }
            if (muted && dialogsToUpdateMentions != null && dialogsToUpdateMentions.indexOfKey(-chat.id) >= 0) {
                if (ChatObject.isChannel(chat) && !chat.megagroup) {
                    mentionChannels[idx1]++;
                } else {
                    mentionGroups[idx1]++;
                }
            }
            if (read && !hasUnread && !hasMention || !read && newUnreadDialogs.indexOfKey(-chat.id) >= 0) {
                if (ChatObject.isChannel(chat) && !chat.megagroup) {
                    channels[idx1][idx2]++;
                } else {
                    groups[idx1][idx2]++;
                }
            }
            chatsDict.put(chat.id, chat);
        }
    }
    for (int a = 0, N = dialogFilters.size(); a < N + 2; a++) {
        int unreadCount;
        MessagesController.DialogFilter filter;
        int flags;
        if (a < N) {
            filter = dialogFilters.get(a);
            if (filter.pendingUnreadCount < 0) {
                continue;
            }
            unreadCount = filter.pendingUnreadCount;
            flags = filter.flags;
        } else {
            filter = null;
            flags = MessagesController.DIALOG_FILTER_FLAG_ALL_CHATS;
            if (a == N) {
                unreadCount = pendingMainUnreadCount;
                flags |= MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                if (!getNotificationsController().showBadgeMuted) {
                    flags |= MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
                }
            } else {
                unreadCount = pendingArchiveUnreadCount;
                flags |= MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED;
            }
        }
        if (read) {
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_CONTACTS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount -= contacts[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= contacts[0][1];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount -= contacts[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= contacts[1][1];
                    }
                }
            }
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount -= nonContacts[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= nonContacts[0][1];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount -= nonContacts[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= nonContacts[1][1];
                    }
                }
            }
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_GROUPS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount -= groups[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= groups[0][1];
                    } else {
                        unreadCount -= mentionGroups[0];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount -= groups[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= groups[1][1];
                    } else {
                        unreadCount -= mentionGroups[1];
                    }
                }
            }
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_CHANNELS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount -= channels[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= channels[0][1];
                    } else {
                        unreadCount -= mentionChannels[0];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount -= channels[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= channels[1][1];
                    } else {
                        unreadCount -= mentionChannels[1];
                    }
                }
            }
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_BOTS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount -= bots[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= bots[0][1];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount -= bots[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount -= bots[1][1];
                    }
                }
            }
            if (filter != null) {
                for (int b = 0, N2 = filter.alwaysShow.size(); b < N2; b++) {
                    long did = filter.alwaysShow.get(b);
                    if (DialogObject.isUserDialog(did)) {
                        for (int i = 0; i < 2; i++) {
                            LongSparseArray<TLRPC.User> dict = i == 0 ? usersDict : encUsersDict;
                            TLRPC.User user = dict.get(did);
                            if (user != null) {
                                int count;
                                if (i == 0) {
                                    count = 1;
                                } else {
                                    count = encryptedChatsByUsersCount.get(did, 0);
                                    if (count == 0) {
                                        continue;
                                    }
                                }
                                int flag;
                                if (user.bot) {
                                    flag = MessagesController.DIALOG_FILTER_FLAG_BOTS;
                                } else if (user.self || user.contact) {
                                    flag = MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
                                } else {
                                    flag = MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
                                }
                                if ((flags & flag) == 0) {
                                    unreadCount -= count;
                                } else if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0 && mutedDialogs.indexOfKey(user.id) >= 0) {
                                    unreadCount -= count;
                                } else if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) != 0 && archivedDialogs.indexOfKey(user.id) >= 0) {
                                    unreadCount -= count;
                                }
                            }
                        }
                    } else {
                        TLRPC.Chat chat = chatsDict.get(-did);
                        if (chat != null) {
                            int flag;
                            if (ChatObject.isChannel(chat) && !chat.megagroup) {
                                flag = MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
                            } else {
                                flag = MessagesController.DIALOG_FILTER_FLAG_GROUPS;
                            }
                            if ((flags & flag) == 0) {
                                unreadCount--;
                            } else if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0 && mutedDialogs.indexOfKey(-chat.id) >= 0 && dialogsWithMentions.indexOfKey(-chat.id) < 0) {
                                unreadCount--;
                            } else if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) != 0 && archivedDialogs.indexOfKey(-chat.id) >= 0) {
                                unreadCount--;
                            }
                        }
                    }
                }
                for (int b = 0, N2 = filter.neverShow.size(); b < N2; b++) {
                    long did = filter.neverShow.get(b);
                    if (dialogsToUpdateMentions != null && dialogsToUpdateMentions.indexOfKey(did) >= 0 && mutedDialogs.indexOfKey(did) < 0) {
                        continue;
                    }
                    if (DialogObject.isUserDialog(did)) {
                        for (int i = 0; i < 2; i++) {
                            LongSparseArray<TLRPC.User> dict = i == 0 ? usersDict : encUsersDict;
                            TLRPC.User user = dict.get(did);
                            if (user != null) {
                                int count;
                                if (i == 0) {
                                    count = 1;
                                } else {
                                    count = encryptedChatsByUsersCount.get(did, 0);
                                    if (count == 0) {
                                        continue;
                                    }
                                }
                                int flag;
                                if (user.bot) {
                                    flag = MessagesController.DIALOG_FILTER_FLAG_BOTS;
                                } else if (user.self || user.contact) {
                                    flag = MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
                                } else {
                                    flag = MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
                                }
                                if ((flags & flag) != 0) {
                                    if (((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0 || archivedDialogs.indexOfKey(user.id) < 0) && ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0 || mutedDialogs.indexOfKey(user.id) < 0)) {
                                        unreadCount += count;
                                    }
                                }
                            }
                        }
                    } else {
                        TLRPC.Chat chat = chatsDict.get(-did);
                        if (chat != null) {
                            int flag;
                            if (ChatObject.isChannel(chat) && !chat.megagroup) {
                                flag = MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
                            } else {
                                flag = MessagesController.DIALOG_FILTER_FLAG_GROUPS;
                            }
                            if ((flags & flag) != 0) {
                                if (((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0 || archivedDialogs.indexOfKey(-chat.id) < 0) && ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0 || mutedDialogs.indexOfKey(-chat.id) < 0 || dialogsWithMentions.indexOfKey(-chat.id) >= 0)) {
                                    unreadCount++;
                                }
                            }
                        }
                    }
                }
            }
            if (unreadCount < 0) {
                unreadCount = 0;
            }
        } else {
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_CONTACTS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount += contacts[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += contacts[0][1];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount += contacts[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += contacts[1][1];
                    }
                }
            }
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount += nonContacts[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += nonContacts[0][1];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount += nonContacts[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += nonContacts[1][1];
                    }
                }
            }
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_GROUPS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount += groups[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += groups[0][1];
                    } else {
                        unreadCount += mentionGroups[0];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount += groups[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += groups[1][1];
                    } else {
                        unreadCount += mentionGroups[1];
                    }
                }
            }
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_CHANNELS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount += channels[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += channels[0][1];
                    } else {
                        unreadCount += mentionChannels[0];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount += channels[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += channels[1][1];
                    } else {
                        unreadCount += mentionChannels[1];
                    }
                }
            }
            if ((flags & MessagesController.DIALOG_FILTER_FLAG_BOTS) != 0) {
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_ONLY_ARCHIVED) == 0) {
                    unreadCount += bots[0][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += bots[0][1];
                    }
                }
                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) == 0) {
                    unreadCount += bots[1][0];
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) == 0) {
                        unreadCount += bots[1][1];
                    }
                }
            }
            if (filter != null) {
                if (!filter.alwaysShow.isEmpty()) {
                    if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0) {
                        for (int b = 0, N2 = dialogsToUpdateMentions.size(); b < N2; b++) {
                            long did = dialogsToUpdateMentions.keyAt(b);
                            TLRPC.Chat chat = chatsDict.get(-did);
                            if (ChatObject.isChannel(chat) && !chat.megagroup) {
                                if ((flags & MessagesController.DIALOG_FILTER_FLAG_CHANNELS) == 0) {
                                    continue;
                                }
                            } else {
                                if ((flags & MessagesController.DIALOG_FILTER_FLAG_GROUPS) == 0) {
                                    continue;
                                }
                            }
                            if (mutedDialogs.indexOfKey(did) >= 0 && filter.alwaysShow.contains(did)) {
                                unreadCount--;
                            }
                        }
                    }
                    for (int b = 0, N2 = filter.alwaysShow.size(); b < N2; b++) {
                        long did = filter.alwaysShow.get(b);
                        if (newUnreadDialogs.indexOfKey(did) < 0) {
                            continue;
                        }
                        if (DialogObject.isUserDialog(did)) {
                            TLRPC.User user = usersDict.get(did);
                            if (user != null) {
                                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0 && mutedDialogs.indexOfKey(user.id) >= 0) {
                                    unreadCount++;
                                } else {
                                    if (user.bot) {
                                        if ((flags & MessagesController.DIALOG_FILTER_FLAG_BOTS) == 0) {
                                            unreadCount++;
                                        }
                                    } else if (user.self || user.contact) {
                                        if ((flags & MessagesController.DIALOG_FILTER_FLAG_CONTACTS) == 0) {
                                            unreadCount++;
                                        }
                                    } else {
                                        if ((flags & MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS) == 0) {
                                            unreadCount++;
                                        }
                                    }
                                }
                            }
                            user = encUsersDict.get(did);
                            if (user != null) {
                                int count = encryptedChatsByUsersCount.get(did, 0);
                                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0 && mutedDialogs.indexOfKey(user.id) >= 0) {
                                    unreadCount += count;
                                } else {
                                    if (user.bot) {
                                        if ((flags & MessagesController.DIALOG_FILTER_FLAG_BOTS) == 0) {
                                            unreadCount += count;
                                        }
                                    } else if (user.self || user.contact) {
                                        if ((flags & MessagesController.DIALOG_FILTER_FLAG_CONTACTS) == 0) {
                                            unreadCount += count;
                                        }
                                    } else {
                                        if ((flags & MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS) == 0) {
                                            unreadCount += count;
                                        }
                                    }
                                }
                            }
                        } else {
                            TLRPC.Chat chat = chatsDict.get(-did);
                            if (chat != null) {
                                if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0 && mutedDialogs.indexOfKey(-chat.id) >= 0) {
                                    unreadCount++;
                                } else {
                                    if (ChatObject.isChannel(chat) && !chat.megagroup) {
                                        if ((flags & MessagesController.DIALOG_FILTER_FLAG_CHANNELS) == 0) {
                                            unreadCount++;
                                        }
                                    } else {
                                        if ((flags & MessagesController.DIALOG_FILTER_FLAG_GROUPS) == 0) {
                                            unreadCount++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                for (int b = 0, N2 = filter.neverShow.size(); b < N2; b++) {
                    long did = filter.neverShow.get(b);
                    if (DialogObject.isUserDialog(did)) {
                        TLRPC.User user = usersDict.get(did);
                        if (user != null) {
                            unreadCount--;
                        }
                        user = encUsersDict.get(did);
                        if (user != null) {
                            unreadCount -= encryptedChatsByUsersCount.get(did, 0);
                        }
                    } else {
                        TLRPC.Chat chat = chatsDict.get(-did);
                        if (chat != null) {
                            unreadCount--;
                        }
                    }
                }
            }
        }
        if (filter != null) {
            filter.pendingUnreadCount = unreadCount;
        /*if (BuildVars.DEBUG_VERSION) {
                    FileLog.d("filter " + filter.name + " flags = " + flags + " read = " + read + " unread count = " + filter.pendingUnreadCount);
                }*/
        } else if (a == N) {
            pendingMainUnreadCount = unreadCount;
        } else if (a == N + 1) {
            pendingArchiveUnreadCount = unreadCount;
        }
    }
    AndroidUtilities.runOnUIThread(() -> {
        ArrayList<MessagesController.DialogFilter> filters = getMessagesController().dialogFilters;
        for (int a = 0, N = filters.size(); a < N; a++) {
            filters.get(a).unreadCount = filters.get(a).pendingUnreadCount;
        }
        mainUnreadCount = pendingMainUnreadCount;
        archiveUnreadCount = pendingArchiveUnreadCount;
    });
}
Also used : LongSparseArray(androidx.collection.LongSparseArray) ArrayList(java.util.ArrayList) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) AtomicLong(java.util.concurrent.atomic.AtomicLong)

Example 5 with LongSparseIntArray

use of org.telegram.messenger.support.LongSparseIntArray in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesStorage method putMessages.

public void putMessages(TLRPC.messages_Messages messages, long dialogId, int load_type, int max_id, boolean createDialog, boolean scheduled) {
    storageQueue.postRunnable(() -> {
        try {
            if (scheduled) {
                database.executeFast(String.format(Locale.US, "DELETE FROM scheduled_messages_v2 WHERE uid = %d AND mid > 0", dialogId)).stepThis().dispose();
                SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO scheduled_messages_v2 VALUES(?, ?, ?, ?, ?, ?, NULL, 0)");
                int count = messages.messages.size();
                for (int a = 0; a < count; a++) {
                    TLRPC.Message message = messages.messages.get(a);
                    if (message instanceof TLRPC.TL_messageEmpty) {
                        continue;
                    }
                    fixUnsupportedMedia(message);
                    state_messages.requery();
                    NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize());
                    message.serializeToStream(data);
                    state_messages.bindInteger(1, message.id);
                    state_messages.bindLong(2, dialogId);
                    state_messages.bindInteger(3, message.send_state);
                    state_messages.bindInteger(4, message.date);
                    state_messages.bindByteBuffer(5, data);
                    state_messages.bindInteger(6, message.ttl);
                    state_messages.step();
                    data.reuse();
                }
                state_messages.dispose();
                putUsersInternal(messages.users);
                putChatsInternal(messages.chats);
                database.commitTransaction();
                broadcastScheduledMessagesChange(dialogId);
            } else {
                int mentionCountUpdate = Integer.MAX_VALUE;
                if (messages.messages.isEmpty()) {
                    if (load_type == 0) {
                        doneHolesInTable("messages_holes", dialogId, max_id);
                        doneHolesInMedia(dialogId, max_id, -1);
                    }
                    return;
                }
                database.beginTransaction();
                if (load_type == 0) {
                    int minId = messages.messages.get(messages.messages.size() - 1).id;
                    closeHolesInTable("messages_holes", dialogId, minId, max_id);
                    closeHolesInMedia(dialogId, minId, max_id, -1);
                } else if (load_type == 1) {
                    int maxId = messages.messages.get(0).id;
                    closeHolesInTable("messages_holes", dialogId, max_id, maxId);
                    closeHolesInMedia(dialogId, max_id, maxId, -1);
                } else if (load_type == 3 || load_type == 2 || load_type == 4) {
                    int maxId = max_id == 0 && load_type != 4 ? Integer.MAX_VALUE : messages.messages.get(0).id;
                    int minId = messages.messages.get(messages.messages.size() - 1).id;
                    closeHolesInTable("messages_holes", dialogId, minId, maxId);
                    closeHolesInMedia(dialogId, minId, maxId, -1);
                }
                int count = messages.messages.size();
                // load_type == 0 ? backward loading
                // load_type == 1 ? forward loading
                // load_type == 2 ? load from first unread
                // load_type == 3 ? load around message
                // load_type == 4 ? load around date
                ArrayList<File> filesToDelete = new ArrayList<>();
                ArrayList<String> namesToDelete = new ArrayList<>();
                ArrayList<Pair<Long, Integer>> idsToDelete = new ArrayList<>();
                SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, 0)");
                SQLitePreparedStatement state_media = database.executeFast("REPLACE INTO media_v4 VALUES(?, ?, ?, ?, ?)");
                SQLitePreparedStatement state_polls = null;
                SQLitePreparedStatement state_webpage = null;
                SQLitePreparedStatement state_tasks = null;
                int minDeleteTime = Integer.MAX_VALUE;
                TLRPC.Message botKeyboard = null;
                long channelId = 0;
                for (int a = 0; a < count; a++) {
                    TLRPC.Message message = messages.messages.get(a);
                    if (channelId == 0) {
                        channelId = message.peer_id.channel_id;
                    }
                    if (load_type == -2) {
                        SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, data, ttl, mention, read_state, send_state FROM messages_v2 WHERE mid = %d AND uid = %d", message.id, MessageObject.getDialogId(message)));
                        boolean exist;
                        if (exist = cursor.next()) {
                            NativeByteBuffer data = cursor.byteBufferValue(1);
                            if (data != null) {
                                TLRPC.Message oldMessage = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
                                oldMessage.readAttachPath(data, getUserConfig().clientUserId);
                                data.reuse();
                                int send_state = cursor.intValue(5);
                                if (send_state != 3) {
                                    if (MessageObject.getFileName(oldMessage).equals(MessageObject.getFileName(message))) {
                                        message.attachPath = oldMessage.attachPath;
                                    }
                                    message.ttl = cursor.intValue(2);
                                }
                                boolean sameMedia = false;
                                if (oldMessage.media instanceof TLRPC.TL_messageMediaPhoto && message.media instanceof TLRPC.TL_messageMediaPhoto && oldMessage.media.photo != null && message.media.photo != null) {
                                    sameMedia = oldMessage.media.photo.id == message.media.photo.id;
                                } else if (oldMessage.media instanceof TLRPC.TL_messageMediaDocument && message.media instanceof TLRPC.TL_messageMediaDocument && oldMessage.media.document != null && message.media.document != null) {
                                    sameMedia = oldMessage.media.document.id == message.media.document.id;
                                }
                                if (!sameMedia) {
                                    addFilesToDelete(oldMessage, filesToDelete, idsToDelete, namesToDelete, false);
                                }
                            }
                            boolean oldMention = cursor.intValue(3) != 0;
                            int readState = cursor.intValue(4);
                            if (oldMention != message.mentioned) {
                                if (mentionCountUpdate == Integer.MAX_VALUE) {
                                    SQLiteCursor cursor2 = database.queryFinalized("SELECT unread_count_i FROM dialogs WHERE did = " + dialogId);
                                    if (cursor2.next()) {
                                        mentionCountUpdate = cursor2.intValue(0);
                                    }
                                    cursor2.dispose();
                                }
                                if (oldMention) {
                                    if (readState <= 1) {
                                        mentionCountUpdate--;
                                    }
                                } else {
                                    if (message.media_unread) {
                                        mentionCountUpdate++;
                                    }
                                }
                            }
                        }
                        cursor.dispose();
                        if (!exist) {
                            continue;
                        }
                    }
                    if (a == 0 && createDialog) {
                        int pinned = 0;
                        int mentions = 0;
                        int flags = 0;
                        SQLiteCursor cursor = database.queryFinalized("SELECT pinned, unread_count_i, flags FROM dialogs WHERE did = " + dialogId);
                        boolean exist;
                        if (exist = cursor.next()) {
                            pinned = cursor.intValue(0);
                            mentions = cursor.intValue(1);
                            flags = cursor.intValue(2);
                        }
                        cursor.dispose();
                        SQLitePreparedStatement state3;
                        if (exist) {
                            state3 = database.executeFast("UPDATE dialogs SET date = ?, last_mid = ?, inbox_max = ?, last_mid_i = ?, pts = ?, date_i = ? WHERE did = ?");
                            state3.bindInteger(1, message.date);
                            state3.bindInteger(2, message.id);
                            state3.bindInteger(3, message.id);
                            state3.bindInteger(4, message.id);
                            state3.bindInteger(5, messages.pts);
                            state3.bindInteger(6, message.date);
                            state3.bindLong(7, dialogId);
                        } else {
                            state3 = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                            state3.bindLong(1, dialogId);
                            state3.bindInteger(2, message.date);
                            state3.bindInteger(3, 0);
                            state3.bindInteger(4, message.id);
                            state3.bindInteger(5, message.id);
                            state3.bindInteger(6, 0);
                            state3.bindInteger(7, message.id);
                            state3.bindInteger(8, mentions);
                            state3.bindInteger(9, messages.pts);
                            state3.bindInteger(10, message.date);
                            state3.bindInteger(11, pinned);
                            state3.bindInteger(12, flags);
                            state3.bindInteger(13, -1);
                            state3.bindNull(14);
                            state3.bindInteger(15, 0);
                            unknownDialogsIds.put(dialogId, true);
                        }
                        state3.step();
                        state3.dispose();
                    }
                    fixUnsupportedMedia(message);
                    state_messages.requery();
                    NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize());
                    message.serializeToStream(data);
                    state_messages.bindInteger(1, message.id);
                    state_messages.bindLong(2, dialogId);
                    state_messages.bindInteger(3, MessageObject.getUnreadFlags(message));
                    state_messages.bindInteger(4, message.send_state);
                    state_messages.bindInteger(5, message.date);
                    state_messages.bindByteBuffer(6, data);
                    state_messages.bindInteger(7, (MessageObject.isOut(message) || message.from_scheduled ? 1 : 0));
                    state_messages.bindInteger(8, message.ttl);
                    if ((message.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
                        state_messages.bindInteger(9, message.views);
                    } else {
                        state_messages.bindInteger(9, getMessageMediaType(message));
                    }
                    int flags = 0;
                    if (message.stickerVerified == 0) {
                        flags |= 1;
                    } else if (message.stickerVerified == 2) {
                        flags |= 2;
                    }
                    state_messages.bindInteger(10, flags);
                    state_messages.bindInteger(11, message.mentioned ? 1 : 0);
                    state_messages.bindInteger(12, message.forwards);
                    NativeByteBuffer repliesData = null;
                    if (message.replies != null) {
                        repliesData = new NativeByteBuffer(message.replies.getObjectSize());
                        message.replies.serializeToStream(repliesData);
                        state_messages.bindByteBuffer(13, repliesData);
                    } else {
                        state_messages.bindNull(13);
                    }
                    if (message.reply_to != null) {
                        state_messages.bindInteger(14, message.reply_to.reply_to_top_id != 0 ? message.reply_to.reply_to_top_id : message.reply_to.reply_to_msg_id);
                    } else {
                        state_messages.bindInteger(14, 0);
                    }
                    state_messages.bindLong(15, MessageObject.getChannelId(message));
                    state_messages.step();
                    if (MediaDataController.canAddMessageToMedia(message)) {
                        state_media.requery();
                        state_media.bindInteger(1, message.id);
                        state_media.bindLong(2, dialogId);
                        state_media.bindInteger(3, message.date);
                        state_media.bindInteger(4, MediaDataController.getMediaType(message));
                        state_media.bindByteBuffer(5, data);
                        state_media.step();
                    } else if (message instanceof TLRPC.TL_messageService && message.action instanceof TLRPC.TL_messageActionHistoryClear) {
                        try {
                            database.executeFast(String.format(Locale.US, "DELETE FROM media_v4 WHERE mid = %d AND uid = %d", message.id, dialogId)).stepThis().dispose();
                            database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + dialogId).stepThis().dispose();
                        } catch (Exception e2) {
                            FileLog.e(e2);
                        }
                    }
                    if (repliesData != null) {
                        repliesData.reuse();
                    }
                    data.reuse();
                    if (message.ttl_period != 0 && message.id > 0) {
                        if (state_tasks == null) {
                            state_tasks = database.executeFast("REPLACE INTO enc_tasks_v4 VALUES(?, ?, ?, ?)");
                        }
                        state_tasks.requery();
                        state_tasks.bindInteger(1, message.id);
                        state_tasks.bindLong(2, message.dialog_id);
                        state_tasks.bindInteger(3, message.date + message.ttl_period);
                        state_tasks.bindInteger(4, 0);
                        state_tasks.step();
                        minDeleteTime = Math.min(minDeleteTime, message.date + message.ttl_period);
                    }
                    if (message.media instanceof TLRPC.TL_messageMediaPoll) {
                        if (state_polls == null) {
                            state_polls = database.executeFast("REPLACE INTO polls_v2 VALUES(?, ?, ?)");
                        }
                        TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.media;
                        state_polls.requery();
                        state_polls.bindInteger(1, message.id);
                        state_polls.bindLong(2, message.dialog_id);
                        state_polls.bindLong(3, mediaPoll.poll.id);
                        state_polls.step();
                    } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
                        if (state_webpage == null) {
                            state_webpage = database.executeFast("REPLACE INTO webpage_pending_v2 VALUES(?, ?, ?)");
                        }
                        state_webpage.requery();
                        state_webpage.bindLong(1, message.media.webpage.id);
                        state_webpage.bindInteger(2, message.id);
                        state_webpage.bindLong(3, message.dialog_id);
                        state_webpage.step();
                    }
                    if (load_type == 0 && isValidKeyboardToSave(message)) {
                        if (botKeyboard == null || botKeyboard.id < message.id) {
                            botKeyboard = message;
                        }
                    }
                }
                state_messages.dispose();
                state_media.dispose();
                if (state_webpage != null) {
                    state_webpage.dispose();
                }
                if (state_tasks != null) {
                    state_tasks.dispose();
                    getMessagesController().didAddedNewTask(minDeleteTime, 0, null);
                }
                if (state_polls != null) {
                    state_polls.dispose();
                }
                if (botKeyboard != null) {
                    getMediaDataController().putBotKeyboard(dialogId, botKeyboard);
                }
                deleteFromDownloadQueue(idsToDelete, false);
                AndroidUtilities.runOnUIThread(() -> getFileLoader().cancelLoadFiles(namesToDelete));
                getFileLoader().deleteFiles(filesToDelete, 0);
                putUsersInternal(messages.users);
                putChatsInternal(messages.chats);
                if (mentionCountUpdate != Integer.MAX_VALUE) {
                    database.executeFast(String.format(Locale.US, "UPDATE dialogs SET unread_count_i = %d WHERE did = %d", mentionCountUpdate, dialogId)).stepThis().dispose();
                    LongSparseIntArray sparseArray = new LongSparseIntArray(1);
                    sparseArray.put(dialogId, mentionCountUpdate);
                    getMessagesController().processDialogsUpdateRead(null, sparseArray);
                }
                database.commitTransaction();
                if (createDialog) {
                    updateDialogsWithDeletedMessages(dialogId, channelId, new ArrayList<>(), null, false);
                }
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : ArrayList(java.util.ArrayList) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) TLRPC(org.telegram.tgnet.TLRPC) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement) Pair(android.util.Pair) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteException(org.telegram.SQLite.SQLiteException) File(java.io.File)

Aggregations

LongSparseIntArray (org.telegram.messenger.support.LongSparseIntArray)16 TLRPC (org.telegram.tgnet.TLRPC)11 ArrayList (java.util.ArrayList)9 SQLiteCursor (org.telegram.SQLite.SQLiteCursor)9 SQLiteException (org.telegram.SQLite.SQLiteException)9 LongSparseArray (androidx.collection.LongSparseArray)7 AtomicLong (java.util.concurrent.atomic.AtomicLong)6 SQLitePreparedStatement (org.telegram.SQLite.SQLitePreparedStatement)4 SparseArray (android.util.SparseArray)3 SparseIntArray (android.util.SparseIntArray)3 AlertDialog (org.telegram.ui.ActionBar.AlertDialog)3 Intent (android.content.Intent)2 SharedPreferences (android.content.SharedPreferences)2 SpannableStringBuilder (android.text.SpannableStringBuilder)2 HashMap (java.util.HashMap)2 Manifest (android.Manifest)1 Animator (android.animation.Animator)1 AnimatorListenerAdapter (android.animation.AnimatorListenerAdapter)1 AnimatorSet (android.animation.AnimatorSet)1 ObjectAnimator (android.animation.ObjectAnimator)1