Search in sources :

Example 66 with NativeByteBuffer

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

the class MessagesStorage method emptyMessagesMedia.

public void emptyMessagesMedia(long dialogId, ArrayList<Integer> mids) {
    storageQueue.postRunnable(() -> {
        try {
            ArrayList<File> filesToDelete = new ArrayList<>();
            ArrayList<String> namesToDelete = new ArrayList<>();
            ArrayList<Pair<Long, Integer>> idsToDelete = new ArrayList<>();
            ArrayList<TLRPC.Message> messages = new ArrayList<>();
            SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages_v2 WHERE mid IN (%s) AND uid = %d", TextUtils.join(",", mids), dialogId));
            while (cursor.next()) {
                NativeByteBuffer data = cursor.byteBufferValue(0);
                if (data != null) {
                    TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
                    message.readAttachPath(data, getUserConfig().clientUserId);
                    data.reuse();
                    if (message.media != null) {
                        if (!addFilesToDelete(message, filesToDelete, idsToDelete, namesToDelete, true)) {
                            continue;
                        } else {
                            if (message.media.document != null) {
                                message.media.document = new TLRPC.TL_documentEmpty();
                            } else if (message.media.photo != null) {
                                message.media.photo = new TLRPC.TL_photoEmpty();
                            }
                        }
                        message.media.flags = message.media.flags & ~1;
                        message.id = cursor.intValue(1);
                        message.date = cursor.intValue(2);
                        message.dialog_id = cursor.longValue(3);
                        messages.add(message);
                    }
                }
            }
            cursor.dispose();
            deleteFromDownloadQueue(idsToDelete, true);
            if (!messages.isEmpty()) {
                SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, 0)");
                for (int a = 0; a < messages.size(); a++) {
                    TLRPC.Message message = messages.get(a);
                    NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize());
                    message.serializeToStream(data);
                    state.requery();
                    state.bindInteger(1, message.id);
                    state.bindLong(2, message.dialog_id);
                    state.bindInteger(3, MessageObject.getUnreadFlags(message));
                    state.bindInteger(4, message.send_state);
                    state.bindInteger(5, message.date);
                    state.bindByteBuffer(6, data);
                    state.bindInteger(7, (MessageObject.isOut(message) || message.from_scheduled ? 1 : 0));
                    state.bindInteger(8, message.ttl);
                    if ((message.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
                        state.bindInteger(9, message.views);
                    } else {
                        state.bindInteger(9, getMessageMediaType(message));
                    }
                    int flags = 0;
                    if (message.stickerVerified == 0) {
                        flags |= 1;
                    } else if (message.stickerVerified == 2) {
                        flags |= 2;
                    }
                    state.bindInteger(10, flags);
                    state.bindInteger(11, message.mentioned ? 1 : 0);
                    state.bindInteger(12, message.forwards);
                    NativeByteBuffer repliesData = null;
                    if (message.replies != null) {
                        repliesData = new NativeByteBuffer(message.replies.getObjectSize());
                        message.replies.serializeToStream(repliesData);
                        state.bindByteBuffer(13, repliesData);
                    } else {
                        state.bindNull(13);
                    }
                    if (message.reply_to != null) {
                        state.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.bindInteger(14, 0);
                    }
                    state.bindLong(15, MessageObject.getChannelId(message));
                    state.step();
                    data.reuse();
                    if (repliesData != null) {
                        repliesData.reuse();
                    }
                }
                state.dispose();
                AndroidUtilities.runOnUIThread(() -> {
                    for (int a = 0; a < messages.size(); a++) {
                        getNotificationCenter().postNotificationName(NotificationCenter.updateMessageMedia, messages.get(a));
                    }
                });
            }
            AndroidUtilities.runOnUIThread(() -> getFileLoader().cancelLoadFiles(namesToDelete));
            getFileLoader().deleteFiles(filesToDelete, 0);
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : ArrayList(java.util.ArrayList) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) SQLiteException(org.telegram.SQLite.SQLiteException) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement) File(java.io.File) Pair(android.util.Pair)

Example 67 with NativeByteBuffer

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

the class MessagesStorage method getDownloadQueue.

public void getDownloadQueue(int type) {
    storageQueue.postRunnable(() -> {
        try {
            ArrayList<DownloadObject> objects = new ArrayList<>();
            SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, type, data, parent FROM download_queue WHERE type = %d ORDER BY date DESC LIMIT 3", type));
            while (cursor.next()) {
                DownloadObject downloadObject = new DownloadObject();
                downloadObject.type = cursor.intValue(1);
                downloadObject.id = cursor.longValue(0);
                downloadObject.parent = cursor.stringValue(3);
                NativeByteBuffer data = cursor.byteBufferValue(2);
                if (data != null) {
                    TLRPC.MessageMedia messageMedia = TLRPC.MessageMedia.TLdeserialize(data, data.readInt32(false), false);
                    data.reuse();
                    if (messageMedia.document != null) {
                        downloadObject.object = messageMedia.document;
                        downloadObject.secret = MessageObject.isVideoDocument(messageMedia.document) && messageMedia.ttl_seconds > 0 && messageMedia.ttl_seconds <= 60;
                    } else if (messageMedia.photo != null) {
                        downloadObject.object = messageMedia.photo;
                        downloadObject.secret = messageMedia.ttl_seconds > 0 && messageMedia.ttl_seconds <= 60;
                    }
                    downloadObject.forceCache = (messageMedia.flags & 0x80000000) != 0;
                }
                objects.add(downloadObject);
            }
            cursor.dispose();
            AndroidUtilities.runOnUIThread(() -> getDownloadController().processDownloadObjects(type, objects));
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : ArrayList(java.util.ArrayList) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) SQLiteException(org.telegram.SQLite.SQLiteException)

Example 68 with NativeByteBuffer

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

the class MessagesStorage method getDialogs.

public void getDialogs(int folderId, int offset, int count, boolean loadDraftsPeersAndFolders) {
    long[] draftsDialogIds;
    if (loadDraftsPeersAndFolders) {
        LongSparseArray<SparseArray<TLRPC.DraftMessage>> drafts = getMediaDataController().getDrafts();
        int draftsCount = drafts.size();
        if (draftsCount > 0) {
            draftsDialogIds = new long[draftsCount];
            for (int i = 0; i < draftsCount; i++) {
                SparseArray<TLRPC.DraftMessage> threads = drafts.valueAt(i);
                if (threads.get(0) == null) {
                    continue;
                }
                draftsDialogIds[i] = drafts.keyAt(i);
            }
        } else {
            draftsDialogIds = null;
        }
    } else {
        draftsDialogIds = null;
    }
    storageQueue.postRunnable(() -> {
        TLRPC.messages_Dialogs dialogs = new TLRPC.TL_messages_dialogs();
        ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<>();
        try {
            ArrayList<Long> usersToLoad = new ArrayList<>();
            usersToLoad.add(getUserConfig().getClientUserId());
            ArrayList<Long> chatsToLoad = new ArrayList<>();
            ArrayList<Integer> encryptedToLoad = new ArrayList<>();
            ArrayList<Long> loadedDialogs = new ArrayList<>();
            LongSparseArray<SparseArray<ArrayList<TLRPC.Message>>> replyMessageOwners = new LongSparseArray<>();
            LongSparseArray<ArrayList<Integer>> dialogReplyMessagesIds = new LongSparseArray<>();
            ArrayList<Integer> foldersToLoad = new ArrayList<>(2);
            foldersToLoad.add(folderId);
            for (int a = 0; a < foldersToLoad.size(); a++) {
                int fid = foldersToLoad.get(a);
                int off;
                int cnt;
                if (a == 0) {
                    off = offset;
                    cnt = count;
                } else {
                    off = 0;
                    cnt = 100;
                }
                SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags, m.date, d.pts, d.inbox_max, d.outbox_max, m.replydata, d.pinned, d.unread_count_i, d.flags, d.folder_id, d.data, d.unread_reactions FROM dialogs as d LEFT JOIN messages_v2 as m ON d.last_mid = m.mid AND d.did = m.uid LEFT JOIN dialog_settings as s ON d.did = s.did WHERE d.folder_id = %d ORDER BY d.pinned DESC, d.date DESC LIMIT %d,%d", fid, off, cnt));
                while (cursor.next()) {
                    long dialogId = cursor.longValue(0);
                    TLRPC.Dialog dialog;
                    if (DialogObject.isFolderDialogId(dialogId)) {
                        TLRPC.TL_dialogFolder dialogFolder = new TLRPC.TL_dialogFolder();
                        if (!cursor.isNull(18)) {
                            NativeByteBuffer data = cursor.byteBufferValue(18);
                            if (data != null) {
                                dialogFolder.folder = TLRPC.TL_folder.TLdeserialize(data, data.readInt32(false), false);
                                data.reuse();
                            } else {
                                dialogFolder.folder = new TLRPC.TL_folder();
                                dialogFolder.folder.id = DialogObject.getFolderId(dialogId);
                            }
                        }
                        dialog = dialogFolder;
                        if (a == 0) {
                            foldersToLoad.add(dialogFolder.folder.id);
                        }
                    } else {
                        dialog = new TLRPC.TL_dialog();
                    }
                    dialog.id = dialogId;
                    dialog.top_message = cursor.intValue(1);
                    dialog.unread_count = cursor.intValue(2);
                    dialog.last_message_date = cursor.intValue(3);
                    dialog.pts = cursor.intValue(10);
                    dialog.flags = dialog.pts == 0 || DialogObject.isUserDialog(dialog.id) ? 0 : 1;
                    dialog.read_inbox_max_id = cursor.intValue(11);
                    dialog.read_outbox_max_id = cursor.intValue(12);
                    dialog.pinnedNum = cursor.intValue(14);
                    dialog.pinned = dialog.pinnedNum != 0;
                    dialog.unread_mentions_count = cursor.intValue(15);
                    int dialog_flags = cursor.intValue(16);
                    dialog.unread_mark = (dialog_flags & 1) != 0;
                    long flags = cursor.longValue(8);
                    int low_flags = (int) flags;
                    dialog.notify_settings = new TLRPC.TL_peerNotifySettings();
                    if ((low_flags & 1) != 0) {
                        dialog.notify_settings.mute_until = (int) (flags >> 32);
                        if (dialog.notify_settings.mute_until == 0) {
                            dialog.notify_settings.mute_until = Integer.MAX_VALUE;
                        }
                    }
                    dialog.folder_id = cursor.intValue(17);
                    dialog.unread_reactions_count = cursor.intValue(19);
                    dialogs.dialogs.add(dialog);
                    if (draftsDialogIds != null) {
                        loadedDialogs.add(dialogId);
                    }
                    NativeByteBuffer data = cursor.byteBufferValue(4);
                    if (data != null) {
                        TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
                        if (message != null) {
                            message.readAttachPath(data, getUserConfig().clientUserId);
                            data.reuse();
                            MessageObject.setUnreadFlags(message, cursor.intValue(5));
                            message.id = cursor.intValue(6);
                            int date = cursor.intValue(9);
                            if (date != 0) {
                                dialog.last_message_date = date;
                            }
                            message.send_state = cursor.intValue(7);
                            message.dialog_id = dialog.id;
                            dialogs.messages.add(message);
                            addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad);
                            try {
                                if (message.reply_to != null && message.reply_to.reply_to_msg_id != 0 && (message.action instanceof TLRPC.TL_messageActionPinMessage || message.action instanceof TLRPC.TL_messageActionPaymentSent || message.action instanceof TLRPC.TL_messageActionGameScore)) {
                                    if (!cursor.isNull(13)) {
                                        NativeByteBuffer data2 = cursor.byteBufferValue(13);
                                        if (data2 != null) {
                                            message.replyMessage = TLRPC.Message.TLdeserialize(data2, data2.readInt32(false), false);
                                            message.replyMessage.readAttachPath(data2, getUserConfig().clientUserId);
                                            data2.reuse();
                                            if (message.replyMessage != null) {
                                                addUsersAndChatsFromMessage(message.replyMessage, usersToLoad, chatsToLoad);
                                            }
                                        }
                                    }
                                    if (message.replyMessage == null) {
                                        addReplyMessages(message, replyMessageOwners, dialogReplyMessagesIds);
                                    }
                                }
                            } catch (Exception e) {
                                FileLog.e(e);
                            }
                        } else {
                            data.reuse();
                        }
                    }
                    if (DialogObject.isEncryptedDialog(dialogId)) {
                        int encryptedChatId = DialogObject.getEncryptedChatId(dialogId);
                        if (!encryptedToLoad.contains(encryptedChatId)) {
                            encryptedToLoad.add(encryptedChatId);
                        }
                    } else if (DialogObject.isUserDialog(dialogId)) {
                        if (!usersToLoad.contains(dialogId)) {
                            usersToLoad.add(dialogId);
                        }
                    } else if (DialogObject.isChatDialog(dialogId)) {
                        if (!chatsToLoad.contains(-dialogId)) {
                            chatsToLoad.add(-dialogId);
                        }
                    }
                }
                cursor.dispose();
            }
            loadReplyMessages(replyMessageOwners, dialogReplyMessagesIds, usersToLoad, chatsToLoad);
            if (draftsDialogIds != null) {
                ArrayList<Long> unloadedDialogs = new ArrayList<>();
                for (int i = 0; i < draftsDialogIds.length; i++) {
                    long dialogId = draftsDialogIds[i];
                    if (DialogObject.isEncryptedDialog(dialogId)) {
                        continue;
                    }
                    if (dialogId > 0) {
                        if (!usersToLoad.contains(dialogId)) {
                            usersToLoad.add(dialogId);
                        }
                    } else {
                        if (!chatsToLoad.contains(-dialogId)) {
                            chatsToLoad.add(-dialogId);
                        }
                    }
                    if (!loadedDialogs.contains(draftsDialogIds[i])) {
                        unloadedDialogs.add(draftsDialogIds[i]);
                    }
                }
                LongSparseArray<Integer> folderIds;
                if (!unloadedDialogs.isEmpty()) {
                    folderIds = new LongSparseArray<>(unloadedDialogs.size());
                    SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT did, folder_id FROM dialogs WHERE did IN(%s)", TextUtils.join(",", unloadedDialogs)));
                    while (cursor.next()) {
                        folderIds.put(cursor.longValue(0), cursor.intValue(1));
                    }
                    cursor.dispose();
                } else {
                    folderIds = null;
                }
                AndroidUtilities.runOnUIThread(() -> {
                    MediaDataController mediaDataController = getMediaDataController();
                    mediaDataController.clearDraftsFolderIds();
                    if (folderIds != null) {
                        for (int i = 0, size = folderIds.size(); i < size; i++) {
                            mediaDataController.setDraftFolderId(folderIds.keyAt(i), folderIds.valueAt(i));
                        }
                    }
                });
            }
            if (!encryptedToLoad.isEmpty()) {
                getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, usersToLoad);
            }
            if (!chatsToLoad.isEmpty()) {
                getChatsInternal(TextUtils.join(",", chatsToLoad), dialogs.chats);
            }
            if (!usersToLoad.isEmpty()) {
                getUsersInternal(TextUtils.join(",", usersToLoad), dialogs.users);
            }
            getMessagesController().processLoadedDialogs(dialogs, encryptedChats, folderId, offset, count, 1, false, false, true);
        } catch (Exception e) {
            dialogs.dialogs.clear();
            dialogs.users.clear();
            dialogs.chats.clear();
            encryptedChats.clear();
            FileLog.e(e);
            getMessagesController().processLoadedDialogs(dialogs, encryptedChats, folderId, 0, 100, 1, true, false, true);
        }
    });
}
Also used : LongSparseArray(androidx.collection.LongSparseArray) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteException(org.telegram.SQLite.SQLiteException) LongSparseArray(androidx.collection.LongSparseArray) SparseArray(android.util.SparseArray) AtomicLong(java.util.concurrent.atomic.AtomicLong)

Example 69 with NativeByteBuffer

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

the class MessagesController method checkLastDialogMessage.

protected void checkLastDialogMessage(TLRPC.Dialog dialog, TLRPC.InputPeer peer, long taskId) {
    if (DialogObject.isEncryptedDialog(dialog.id) || checkingLastMessagesDialogs.indexOfKey(dialog.id) >= 0) {
        return;
    }
    TLRPC.TL_messages_getHistory req = new TLRPC.TL_messages_getHistory();
    req.peer = peer == null ? getInputPeer(dialog.id) : peer;
    if (req.peer == null) {
        return;
    }
    req.limit = 1;
    checkingLastMessagesDialogs.put(dialog.id, true);
    if (BuildVars.LOGS_ENABLED) {
        FileLog.d("checkLastDialogMessage for " + dialog.id);
    }
    long newTaskId;
    if (taskId == 0) {
        NativeByteBuffer data = null;
        try {
            data = new NativeByteBuffer(60 + req.peer.getObjectSize());
            data.writeInt32(14);
            data.writeInt64(dialog.id);
            data.writeInt32(dialog.top_message);
            data.writeInt32(dialog.read_inbox_max_id);
            data.writeInt32(dialog.read_outbox_max_id);
            data.writeInt32(dialog.unread_count);
            data.writeInt32(dialog.last_message_date);
            data.writeInt32(dialog.pts);
            data.writeInt32(dialog.flags);
            data.writeBool(dialog.pinned);
            data.writeInt32(dialog.pinnedNum);
            data.writeInt32(dialog.unread_mentions_count);
            data.writeBool(dialog.unread_mark);
            data.writeInt32(dialog.folder_id);
            req.peer.serializeToStream(data);
        } catch (Exception e) {
            FileLog.e(e);
        }
        newTaskId = getMessagesStorage().createPendingTask(data);
    } else {
        newTaskId = taskId;
    }
    getConnectionsManager().sendRequest(req, (response, error) -> {
        if (response != null) {
            TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
            removeDeletedMessagesFromArray(dialog.id, res.messages);
            if (!res.messages.isEmpty()) {
                if (BuildVars.LOGS_ENABLED) {
                    FileLog.d("checkLastDialogMessage for " + dialog.id + " has message");
                }
                TLRPC.TL_messages_dialogs dialogs = new TLRPC.TL_messages_dialogs();
                TLRPC.Message newMessage = res.messages.get(0);
                TLRPC.Dialog newDialog = new TLRPC.TL_dialog();
                newDialog.flags = dialog.flags;
                newDialog.top_message = newMessage.id;
                newDialog.last_message_date = newMessage.date;
                newDialog.notify_settings = dialog.notify_settings;
                newDialog.pts = dialog.pts;
                newDialog.unread_count = dialog.unread_count;
                newDialog.unread_mark = dialog.unread_mark;
                newDialog.unread_mentions_count = dialog.unread_mentions_count;
                newDialog.unread_reactions_count = dialog.unread_reactions_count;
                newDialog.read_inbox_max_id = dialog.read_inbox_max_id;
                newDialog.read_outbox_max_id = dialog.read_outbox_max_id;
                newDialog.pinned = dialog.pinned;
                newDialog.pinnedNum = dialog.pinnedNum;
                newDialog.folder_id = dialog.folder_id;
                newMessage.dialog_id = newDialog.id = dialog.id;
                dialogs.users.addAll(res.users);
                dialogs.chats.addAll(res.chats);
                dialogs.dialogs.add(newDialog);
                dialogs.messages.addAll(res.messages);
                dialogs.count = 1;
                processDialogsUpdate(dialogs, null, false);
                getMessagesStorage().putMessages(res.messages, true, true, false, getDownloadController().getAutodownloadMask(), true, false);
            } else {
                AndroidUtilities.runOnUIThread(() -> {
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("checkLastDialogMessage for " + dialog.id + " has not message");
                    }
                    if (getMediaDataController().getDraft(dialog.id, 0) == null) {
                        TLRPC.Dialog currentDialog = dialogs_dict.get(dialog.id);
                        if (currentDialog == null) {
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("checkLastDialogMessage for " + dialog.id + " current dialog not found");
                            }
                            getMessagesStorage().isDialogHasTopMessage(dialog.id, () -> deleteDialog(dialog.id, 3));
                        } else {
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("checkLastDialogMessage for " + dialog.id + " current dialog top message " + currentDialog.top_message);
                            }
                            if (currentDialog.top_message == 0) {
                                deleteDialog(dialog.id, 3);
                            }
                        }
                    }
                });
            }
        }
        if (newTaskId != 0) {
            getMessagesStorage().removePendingTask(newTaskId);
        }
        AndroidUtilities.runOnUIThread(() -> checkingLastMessagesDialogs.delete(dialog.id));
    });
}
Also used : NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) TLRPC(org.telegram.tgnet.TLRPC) SQLiteException(org.telegram.SQLite.SQLiteException)

Example 70 with NativeByteBuffer

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

the class MessagesController method getChannelDifference.

protected void getChannelDifference(long channelId, int newDialogType, long taskId, TLRPC.InputChannel inputChannel) {
    boolean gettingDifferenceChannel = gettingDifferenceChannels.get(channelId, false);
    if (gettingDifferenceChannel) {
        return;
    }
    int limit = 100;
    int channelPts;
    if (newDialogType == 1) {
        channelPts = channelsPts.get(channelId);
        if (channelPts != 0) {
            return;
        }
        channelPts = 1;
        limit = 1;
    } else {
        channelPts = channelsPts.get(channelId);
        if (channelPts == 0) {
            channelPts = getMessagesStorage().getChannelPtsSync(channelId);
            if (channelPts != 0) {
                channelsPts.put(channelId, channelPts);
            }
            if (channelPts == 0 && (newDialogType == 2 || newDialogType == 3)) {
                return;
            }
        }
        if (channelPts == 0) {
            return;
        }
    }
    if (inputChannel == null) {
        TLRPC.Chat chat = getChat(channelId);
        if (chat == null) {
            chat = getMessagesStorage().getChatSync(channelId);
            if (chat != null) {
                putChat(chat, true);
            }
        }
        inputChannel = getInputChannel(chat);
    }
    if (inputChannel.access_hash == 0) {
        if (taskId != 0) {
            getMessagesStorage().removePendingTask(taskId);
        }
        return;
    }
    long newTaskId;
    if (taskId == 0) {
        NativeByteBuffer data = null;
        try {
            data = new NativeByteBuffer(16 + inputChannel.getObjectSize());
            data.writeInt32(25);
            data.writeInt64(channelId);
            data.writeInt32(newDialogType);
            inputChannel.serializeToStream(data);
        } catch (Exception e) {
            FileLog.e(e);
        }
        newTaskId = getMessagesStorage().createPendingTask(data);
    } else {
        newTaskId = taskId;
    }
    gettingDifferenceChannels.put(channelId, true);
    TLRPC.TL_updates_getChannelDifference req = new TLRPC.TL_updates_getChannelDifference();
    req.channel = inputChannel;
    req.filter = new TLRPC.TL_channelMessagesFilterEmpty();
    req.pts = channelPts;
    req.limit = limit;
    req.force = newDialogType != 3;
    if (BuildVars.LOGS_ENABLED) {
        FileLog.d("start getChannelDifference with pts = " + channelPts + " channelId = " + channelId);
    }
    getConnectionsManager().sendRequest(req, (response, error) -> {
        if (response != null) {
            TLRPC.updates_ChannelDifference res = (TLRPC.updates_ChannelDifference) response;
            LongSparseArray<TLRPC.User> usersDict = new LongSparseArray<>();
            for (int a = 0; a < res.users.size(); a++) {
                TLRPC.User user = res.users.get(a);
                usersDict.put(user.id, user);
            }
            TLRPC.Chat channel = null;
            for (int a = 0; a < res.chats.size(); a++) {
                TLRPC.Chat chat = res.chats.get(a);
                if (chat.id == channelId) {
                    channel = chat;
                    break;
                }
            }
            TLRPC.Chat channelFinal = channel;
            ArrayList<TLRPC.TL_updateMessageID> msgUpdates = new ArrayList<>();
            if (!res.other_updates.isEmpty()) {
                for (int a = 0; a < res.other_updates.size(); a++) {
                    TLRPC.Update upd = res.other_updates.get(a);
                    if (upd instanceof TLRPC.TL_updateMessageID) {
                        msgUpdates.add((TLRPC.TL_updateMessageID) upd);
                        res.other_updates.remove(a);
                        a--;
                    }
                }
            }
            getMessagesStorage().putUsersAndChats(res.users, res.chats, true, true);
            AndroidUtilities.runOnUIThread(() -> {
                putUsers(res.users, false);
                putChats(res.chats, false);
            });
            getMessagesStorage().getStorageQueue().postRunnable(() -> {
                if (!msgUpdates.isEmpty()) {
                    SparseArray<long[]> corrected = new SparseArray<>();
                    for (TLRPC.TL_updateMessageID update : msgUpdates) {
                        long[] ids = getMessagesStorage().updateMessageStateAndId(update.random_id, -channelId, null, update.id, 0, false, -1);
                        if (ids != null) {
                            corrected.put(update.id, ids);
                        }
                    }
                    if (corrected.size() != 0) {
                        AndroidUtilities.runOnUIThread(() -> {
                            for (int a = 0; a < corrected.size(); a++) {
                                int newId = corrected.keyAt(a);
                                long[] ids = corrected.valueAt(a);
                                getSendMessagesHelper().processSentMessage((int) ids[1]);
                                getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, (int) ids[1], newId, null, ids[0], 0L, -1, false);
                            }
                        });
                    }
                }
                Utilities.stageQueue.postRunnable(() -> {
                    if (res instanceof TLRPC.TL_updates_channelDifference || res instanceof TLRPC.TL_updates_channelDifferenceEmpty) {
                        if (!res.new_messages.isEmpty()) {
                            LongSparseArray<ArrayList<MessageObject>> messages = new LongSparseArray<>();
                            ImageLoader.saveMessagesThumbs(res.new_messages);
                            ArrayList<MessageObject> pushMessages = new ArrayList<>();
                            long dialogId = -channelId;
                            Integer inboxValue = dialogs_read_inbox_max.get(dialogId);
                            if (inboxValue == null) {
                                inboxValue = getMessagesStorage().getDialogReadMax(false, dialogId);
                                dialogs_read_inbox_max.put(dialogId, inboxValue);
                            }
                            Integer outboxValue = dialogs_read_outbox_max.get(dialogId);
                            if (outboxValue == null) {
                                outboxValue = getMessagesStorage().getDialogReadMax(true, dialogId);
                                dialogs_read_outbox_max.put(dialogId, outboxValue);
                            }
                            for (int a = 0; a < res.new_messages.size(); a++) {
                                TLRPC.Message message = res.new_messages.get(a);
                                if (message instanceof TLRPC.TL_messageEmpty) {
                                    continue;
                                }
                                message.unread = !(channelFinal != null && channelFinal.left || (message.out ? outboxValue : inboxValue) >= message.id || message.action instanceof TLRPC.TL_messageActionChannelCreate);
                                boolean isDialogCreated = createdDialogIds.contains(dialogId);
                                MessageObject obj = new MessageObject(currentAccount, message, usersDict, isDialogCreated, isDialogCreated);
                                if ((!obj.isOut() || obj.messageOwner.from_scheduled) && obj.isUnread()) {
                                    pushMessages.add(obj);
                                }
                                long uid = -channelId;
                                ArrayList<MessageObject> arr = messages.get(uid);
                                if (arr == null) {
                                    arr = new ArrayList<>();
                                    messages.put(uid, arr);
                                }
                                arr.add(obj);
                            }
                            AndroidUtilities.runOnUIThread(() -> {
                                for (int a = 0; a < messages.size(); a++) {
                                    long key = messages.keyAt(a);
                                    ArrayList<MessageObject> value = messages.valueAt(a);
                                    updateInterfaceWithMessages(key, value, false);
                                }
                                getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload);
                            });
                            getMessagesStorage().getStorageQueue().postRunnable(() -> {
                                if (!pushMessages.isEmpty()) {
                                    AndroidUtilities.runOnUIThread(() -> getNotificationsController().processNewMessages(pushMessages, true, false, null));
                                }
                                getMessagesStorage().putMessages(res.new_messages, true, false, false, getDownloadController().getAutodownloadMask(), false);
                            });
                        }
                        if (!res.other_updates.isEmpty()) {
                            processUpdateArray(res.other_updates, res.users, res.chats, true, 0);
                        }
                        processChannelsUpdatesQueue(channelId, 1);
                        getMessagesStorage().saveChannelPts(channelId, res.pts);
                    } else if (res instanceof TLRPC.TL_updates_channelDifferenceTooLong) {
                        long dialogId = -channelId;
                        Integer inboxValue = dialogs_read_inbox_max.get(dialogId);
                        if (inboxValue == null) {
                            inboxValue = getMessagesStorage().getDialogReadMax(false, dialogId);
                            dialogs_read_inbox_max.put(dialogId, inboxValue);
                        }
                        Integer outboxValue = dialogs_read_outbox_max.get(dialogId);
                        if (outboxValue == null) {
                            outboxValue = getMessagesStorage().getDialogReadMax(true, dialogId);
                            dialogs_read_outbox_max.put(dialogId, outboxValue);
                        }
                        for (int a = 0; a < res.messages.size(); a++) {
                            TLRPC.Message message = res.messages.get(a);
                            message.dialog_id = -channelId;
                            message.unread = !(message.action instanceof TLRPC.TL_messageActionChannelCreate || channelFinal != null && channelFinal.left || (message.out ? outboxValue : inboxValue) >= message.id);
                        }
                        getMessagesStorage().overwriteChannel(channelId, (TLRPC.TL_updates_channelDifferenceTooLong) res, newDialogType);
                    }
                    gettingDifferenceChannels.delete(channelId);
                    channelsPts.put(channelId, res.pts);
                    if ((res.flags & 2) != 0) {
                        shortPollChannels.put(channelId, (int) (System.currentTimeMillis() / 1000) + res.timeout);
                    }
                    if (!res.isFinal) {
                        getChannelDifference(channelId);
                    }
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("received channel difference with pts = " + res.pts + " channelId = " + channelId);
                        FileLog.d("new_messages = " + res.new_messages.size() + " messages = " + res.messages.size() + " users = " + res.users.size() + " chats = " + res.chats.size() + " other updates = " + res.other_updates.size());
                    }
                    if (newTaskId != 0) {
                        getMessagesStorage().removePendingTask(newTaskId);
                    }
                });
            });
        } else if (error != null) {
            AndroidUtilities.runOnUIThread(() -> checkChannelError(error.text, channelId));
            gettingDifferenceChannels.delete(channelId);
            if (newTaskId != 0) {
                getMessagesStorage().removePendingTask(newTaskId);
            }
        }
    });
}
Also used : LongSparseArray(androidx.collection.LongSparseArray) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteException(org.telegram.SQLite.SQLiteException) SparseArray(android.util.SparseArray) LongSparseArray(androidx.collection.LongSparseArray)

Aggregations

NativeByteBuffer (org.telegram.tgnet.NativeByteBuffer)108 TLRPC (org.telegram.tgnet.TLRPC)92 SQLiteException (org.telegram.SQLite.SQLiteException)91 SQLiteCursor (org.telegram.SQLite.SQLiteCursor)68 SQLitePreparedStatement (org.telegram.SQLite.SQLitePreparedStatement)54 ArrayList (java.util.ArrayList)47 Paint (android.graphics.Paint)19 LongSparseArray (androidx.collection.LongSparseArray)18 SparseArray (android.util.SparseArray)12 File (java.io.File)11 AtomicLong (java.util.concurrent.atomic.AtomicLong)11 TLObject (org.telegram.tgnet.TLObject)11 CountDownLatch (java.util.concurrent.CountDownLatch)8 SpannableStringBuilder (android.text.SpannableStringBuilder)7 SharedPreferences (android.content.SharedPreferences)6 Pair (android.util.Pair)6 HashMap (java.util.HashMap)6 SparseIntArray (android.util.SparseIntArray)5 SQLiteDatabase (org.telegram.SQLite.SQLiteDatabase)5 LongSparseIntArray (org.telegram.messenger.support.LongSparseIntArray)5