Search in sources :

Example 41 with SQLiteCursor

use of org.telegram.SQLite.SQLiteCursor in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesStorage method getDialogPhotos.

public void getDialogPhotos(long did, int count, int maxId, int classGuid) {
    storageQueue.postRunnable(() -> {
        try {
            SQLiteCursor cursor;
            if (maxId != 0) {
                cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM user_photos WHERE uid = %d AND id < %d ORDER BY rowid ASC LIMIT %d", did, maxId, count));
            } else {
                cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM user_photos WHERE uid = %d ORDER BY rowid ASC LIMIT %d", did, count));
            }
            TLRPC.photos_Photos res = new TLRPC.TL_photos_photos();
            ArrayList<TLRPC.Message> messages = new ArrayList<>();
            while (cursor.next()) {
                NativeByteBuffer data = cursor.byteBufferValue(0);
                if (data != null) {
                    TLRPC.Photo photo = TLRPC.Photo.TLdeserialize(data, data.readInt32(false), false);
                    if (data.remaining() > 0) {
                        messages.add(TLRPC.Message.TLdeserialize(data, data.readInt32(false), false));
                    } else {
                        messages.add(null);
                    }
                    data.reuse();
                    res.photos.add(photo);
                }
            }
            cursor.dispose();
            Utilities.stageQueue.postRunnable(() -> getMessagesController().processLoadedUserPhotos(res, messages, did, count, maxId, true, classGuid));
        } 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 42 with SQLiteCursor

use of org.telegram.SQLite.SQLiteCursor in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesStorage method closeHolesInTable.

private void closeHolesInTable(String table, long did, int minId, int maxId) {
    try {
        boolean ok = false;
        SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT start, end FROM " + table + " WHERE uid = %d AND ((end >= %d AND end <= %d) OR (start >= %d AND start <= %d) OR (start >= %d AND end <= %d) OR (start <= %d AND end >= %d))", did, minId, maxId, minId, maxId, minId, maxId, minId, maxId));
        ArrayList<Hole> holes = null;
        while (cursor.next()) {
            if (holes == null) {
                holes = new ArrayList<>();
            }
            int start = cursor.intValue(0);
            int end = cursor.intValue(1);
            if (start == end && start == 1) {
                continue;
            }
            holes.add(new Hole(start, end));
        }
        cursor.dispose();
        if (holes != null) {
            for (int a = 0; a < holes.size(); a++) {
                Hole hole = holes.get(a);
                if (maxId >= hole.end - 1 && minId <= hole.start + 1) {
                    database.executeFast(String.format(Locale.US, "DELETE FROM " + table + " WHERE uid = %d AND start = %d AND end = %d", did, hole.start, hole.end)).stepThis().dispose();
                } else if (maxId >= hole.end - 1) {
                    if (hole.end != minId) {
                        try {
                            database.executeFast(String.format(Locale.US, "UPDATE " + table + " SET end = %d WHERE uid = %d AND start = %d AND end = %d", minId, did, hole.start, hole.end)).stepThis().dispose();
                        } catch (Exception e) {
                            FileLog.e(e, false);
                        }
                    }
                } else if (minId <= hole.start + 1) {
                    if (hole.start != maxId) {
                        try {
                            database.executeFast(String.format(Locale.US, "UPDATE " + table + " SET start = %d WHERE uid = %d AND start = %d AND end = %d", maxId, did, hole.start, hole.end)).stepThis().dispose();
                        } catch (Exception e) {
                            FileLog.e(e, false);
                        }
                    }
                } else {
                    database.executeFast(String.format(Locale.US, "DELETE FROM " + table + " WHERE uid = %d AND start = %d AND end = %d", did, hole.start, hole.end)).stepThis().dispose();
                    SQLitePreparedStatement state = database.executeFast("REPLACE INTO " + table + " VALUES(?, ?, ?)");
                    state.requery();
                    state.bindLong(1, did);
                    state.bindInteger(2, hole.start);
                    state.bindInteger(3, minId);
                    state.step();
                    state.requery();
                    state.bindLong(1, did);
                    state.bindInteger(2, maxId);
                    state.bindInteger(3, hole.end);
                    state.step();
                    state.dispose();
                }
            }
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
}
Also used : SQLiteCursor(org.telegram.SQLite.SQLiteCursor) SQLiteException(org.telegram.SQLite.SQLiteException) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement)

Example 43 with SQLiteCursor

use of org.telegram.SQLite.SQLiteCursor in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesStorage method overwriteChannel.

public void overwriteChannel(long channelId, TLRPC.TL_updates_channelDifferenceTooLong difference, int newDialogType) {
    storageQueue.postRunnable(() -> {
        try {
            boolean checkInvite = false;
            long did = -channelId;
            int pinned = 0;
            SQLiteCursor cursor = database.queryFinalized("SELECT pinned FROM dialogs WHERE did = " + did);
            if (!cursor.next()) {
                if (newDialogType != 0) {
                    checkInvite = true;
                }
            } else {
                pinned = cursor.intValue(0);
            }
            cursor.dispose();
            database.executeFast("DELETE FROM chat_pinned_count WHERE uid = " + did).stepThis().dispose();
            database.executeFast("DELETE FROM chat_pinned_v2 WHERE uid = " + did).stepThis().dispose();
            database.executeFast("DELETE FROM messages_v2 WHERE uid = " + did).stepThis().dispose();
            database.executeFast("DELETE FROM bot_keyboard WHERE uid = " + did).stepThis().dispose();
            database.executeFast("UPDATE media_counts_v2 SET old = 1 WHERE uid = " + did).stepThis().dispose();
            database.executeFast("DELETE FROM media_v4 WHERE uid = " + did).stepThis().dispose();
            database.executeFast("DELETE FROM messages_holes WHERE uid = " + did).stepThis().dispose();
            database.executeFast("DELETE FROM media_holes_v2 WHERE uid = " + did).stepThis().dispose();
            getMediaDataController().clearBotKeyboard(did, null);
            TLRPC.TL_messages_dialogs dialogs = new TLRPC.TL_messages_dialogs();
            dialogs.chats.addAll(difference.chats);
            dialogs.users.addAll(difference.users);
            dialogs.messages.addAll(difference.messages);
            TLRPC.Dialog dialog = difference.dialog;
            dialog.id = did;
            dialog.flags = 1;
            dialog.notify_settings = null;
            dialog.pinned = pinned != 0;
            dialog.pinnedNum = pinned;
            dialogs.dialogs.add(dialog);
            putDialogsInternal(dialogs, 0);
            updateDialogsWithDeletedMessages(-channelId, channelId, new ArrayList<>(), null, false);
            AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did, true, difference));
            if (checkInvite) {
                if (newDialogType == 1) {
                    getMessagesController().checkChatInviter(channelId, true);
                } else {
                    getMessagesController().generateJoinMessage(channelId, false);
                }
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) SQLiteException(org.telegram.SQLite.SQLiteException)

Example 44 with SQLiteCursor

use of org.telegram.SQLite.SQLiteCursor in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesStorage method updateChatParticipants.

public void updateChatParticipants(TLRPC.ChatParticipants participants) {
    if (participants == null) {
        return;
    }
    storageQueue.postRunnable(() -> {
        try {
            SQLiteCursor cursor = database.queryFinalized("SELECT info, pinned, online, inviter FROM chat_settings_v2 WHERE uid = " + participants.chat_id);
            TLRPC.ChatFull info = null;
            ArrayList<TLRPC.User> loadedUsers = new ArrayList<>();
            if (cursor.next()) {
                NativeByteBuffer data = cursor.byteBufferValue(0);
                if (data != null) {
                    info = TLRPC.ChatFull.TLdeserialize(data, data.readInt32(false), false);
                    data.reuse();
                    info.pinned_msg_id = cursor.intValue(1);
                    info.online_count = cursor.intValue(2);
                    info.inviterId = cursor.longValue(3);
                }
            }
            cursor.dispose();
            if (info instanceof TLRPC.TL_chatFull) {
                info.participants = participants;
                TLRPC.ChatFull finalInfo = info;
                AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.chatInfoDidLoad, finalInfo, 0, false, false));
                SQLitePreparedStatement state = database.executeFast("REPLACE INTO chat_settings_v2 VALUES(?, ?, ?, ?, ?, ?)");
                NativeByteBuffer data = new NativeByteBuffer(info.getObjectSize());
                info.serializeToStream(data);
                state.bindLong(1, info.id);
                state.bindByteBuffer(2, data);
                state.bindInteger(3, info.pinned_msg_id);
                state.bindInteger(4, info.online_count);
                state.bindLong(5, info.inviterId);
                state.bindInteger(6, info.invitesCount);
                state.step();
                state.dispose();
                data.reuse();
            }
        } 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)

Example 45 with SQLiteCursor

use of org.telegram.SQLite.SQLiteCursor in project Telegram-FOSS by Telegram-FOSS-Team.

the class MessagesStorage method loadUnreadMessages.

public void loadUnreadMessages() {
    storageQueue.postRunnable(() -> {
        try {
            ArrayList<Long> usersToLoad = new ArrayList<>();
            ArrayList<Long> chatsToLoad = new ArrayList<>();
            ArrayList<Integer> encryptedChatIds = new ArrayList<>();
            LongSparseArray<Integer> pushDialogs = new LongSparseArray<>();
            SQLiteCursor cursor = database.queryFinalized("SELECT d.did, d.unread_count, s.flags FROM dialogs as d LEFT JOIN dialog_settings as s ON d.did = s.did WHERE d.unread_count > 0");
            StringBuilder ids = new StringBuilder();
            int currentTime = getConnectionsManager().getCurrentTime();
            while (cursor.next()) {
                long flags = cursor.longValue(2);
                boolean muted = (flags & 1) != 0;
                int mutedUntil = (int) (flags >> 32);
                if (cursor.isNull(2) || !muted || mutedUntil != 0 && mutedUntil < currentTime) {
                    long did = cursor.longValue(0);
                    if (DialogObject.isFolderDialogId(did)) {
                        continue;
                    }
                    int count = cursor.intValue(1);
                    pushDialogs.put(did, count);
                    if (ids.length() != 0) {
                        ids.append(",");
                    }
                    ids.append(did);
                    if (DialogObject.isEncryptedDialog(did)) {
                        int encryptedChatId = DialogObject.getEncryptedChatId(did);
                        if (!encryptedChatIds.contains(encryptedChatId)) {
                            encryptedChatIds.add(encryptedChatId);
                        }
                    } else if (DialogObject.isUserDialog(did)) {
                        if (!usersToLoad.contains(did)) {
                            usersToLoad.add(did);
                        }
                    } else {
                        if (!chatsToLoad.contains(-did)) {
                            chatsToLoad.add(-did);
                        }
                    }
                }
            }
            cursor.dispose();
            LongSparseArray<SparseArray<ArrayList<TLRPC.Message>>> replyMessageOwners = new LongSparseArray<>();
            LongSparseArray<ArrayList<Integer>> dialogReplyMessagesIds = new LongSparseArray<>();
            ArrayList<TLRPC.Message> messages = new ArrayList<>();
            ArrayList<MessageObject> pushMessages = new ArrayList<>();
            ArrayList<TLRPC.User> users = new ArrayList<>();
            ArrayList<TLRPC.Chat> chats = new ArrayList<>();
            ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<>();
            int maxDate = 0;
            if (ids.length() > 0) {
                cursor = database.queryFinalized("SELECT read_state, data, send_state, mid, date, uid, replydata FROM messages_v2 WHERE uid IN (" + ids.toString() + ") AND out = 0 AND read_state IN(0,2) ORDER BY date DESC LIMIT 50");
                while (cursor.next()) {
                    NativeByteBuffer data = cursor.byteBufferValue(1);
                    if (data != null) {
                        TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
                        message.readAttachPath(data, getUserConfig().clientUserId);
                        data.reuse();
                        MessageObject.setUnreadFlags(message, cursor.intValue(0));
                        message.id = cursor.intValue(3);
                        message.date = cursor.intValue(4);
                        message.dialog_id = cursor.longValue(5);
                        messages.add(message);
                        maxDate = Math.max(maxDate, message.date);
                        addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad);
                        message.send_state = cursor.intValue(2);
                        if (message.peer_id.channel_id == 0 && !MessageObject.isUnread(message) && !DialogObject.isEncryptedDialog(message.dialog_id) || message.id > 0) {
                            message.send_state = 0;
                        }
                        if (DialogObject.isEncryptedDialog(message.dialog_id) && !cursor.isNull(5)) {
                            message.random_id = cursor.longValue(5);
                        }
                        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(6)) {
                                    data = cursor.byteBufferValue(6);
                                    if (data != null) {
                                        message.replyMessage = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
                                        message.replyMessage.readAttachPath(data, getUserConfig().clientUserId);
                                        data.reuse();
                                        if (message.replyMessage != null) {
                                            addUsersAndChatsFromMessage(message.replyMessage, usersToLoad, chatsToLoad);
                                        }
                                    }
                                }
                                if (message.replyMessage == null) {
                                    addReplyMessages(message, replyMessageOwners, dialogReplyMessagesIds);
                                }
                            }
                        } catch (Exception e) {
                            FileLog.e(e);
                        }
                    }
                }
                cursor.dispose();
                database.executeFast("DELETE FROM unread_push_messages WHERE date <= " + maxDate).stepThis().dispose();
                cursor = database.queryFinalized("SELECT data, mid, date, uid, random, fm, name, uname, flags FROM unread_push_messages WHERE 1 ORDER BY date DESC LIMIT 50");
                while (cursor.next()) {
                    NativeByteBuffer data = cursor.byteBufferValue(0);
                    if (data != null) {
                        TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
                        data.reuse();
                        message.id = cursor.intValue(1);
                        message.date = cursor.intValue(2);
                        message.dialog_id = cursor.longValue(3);
                        message.random_id = cursor.longValue(4);
                        String messageText = cursor.isNull(5) ? null : cursor.stringValue(5);
                        String name = cursor.isNull(6) ? null : cursor.stringValue(6);
                        String userName = cursor.isNull(7) ? null : cursor.stringValue(7);
                        int flags = cursor.intValue(8);
                        if (MessageObject.getFromChatId(message) == 0) {
                            if (DialogObject.isUserDialog(message.dialog_id)) {
                                message.from_id = new TLRPC.TL_peerUser();
                                message.from_id.user_id = message.dialog_id;
                            }
                        }
                        if (DialogObject.isUserDialog(message.dialog_id)) {
                            if (!usersToLoad.contains(message.dialog_id)) {
                                usersToLoad.add(message.dialog_id);
                            }
                        } else if (DialogObject.isChatDialog(message.dialog_id)) {
                            if (!chatsToLoad.contains(-message.dialog_id)) {
                                chatsToLoad.add(-message.dialog_id);
                            }
                        }
                        pushMessages.add(new MessageObject(currentAccount, message, messageText, name, userName, (flags & 1) != 0, (flags & 2) != 0, (message.flags & 0x80000000) != 0, false));
                        addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad);
                    }
                }
                cursor.dispose();
                loadReplyMessages(replyMessageOwners, dialogReplyMessagesIds, usersToLoad, chatsToLoad);
                if (!encryptedChatIds.isEmpty()) {
                    getEncryptedChatsInternal(TextUtils.join(",", encryptedChatIds), encryptedChats, usersToLoad);
                }
                if (!usersToLoad.isEmpty()) {
                    getUsersInternal(TextUtils.join(",", usersToLoad), users);
                }
                if (!chatsToLoad.isEmpty()) {
                    getChatsInternal(TextUtils.join(",", chatsToLoad), chats);
                    for (int a = 0; a < chats.size(); a++) {
                        TLRPC.Chat chat = chats.get(a);
                        if (chat != null && (ChatObject.isNotInChat(chat) || chat.min || chat.migrated_to != null)) {
                            long did = -chat.id;
                            database.executeFast("UPDATE dialogs SET unread_count = 0 WHERE did = " + did).stepThis().dispose();
                            database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET read_state = 3 WHERE uid = %d AND mid > 0 AND read_state IN(0,2) AND out = 0", did)).stepThis().dispose();
                            chats.remove(a);
                            a--;
                            pushDialogs.remove(did);
                            for (int b = 0; b < messages.size(); b++) {
                                TLRPC.Message message = messages.get(b);
                                if (message.dialog_id == did) {
                                    messages.remove(b);
                                    b--;
                                }
                            }
                        }
                    }
                }
            }
            Collections.reverse(messages);
            AndroidUtilities.runOnUIThread(() -> getNotificationsController().processLoadedUnreadMessages(pushDialogs, messages, pushMessages, users, chats, encryptedChats));
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : LongSparseArray(androidx.collection.LongSparseArray) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteException(org.telegram.SQLite.SQLiteException) LongSparseArray(androidx.collection.LongSparseArray) SparseArray(android.util.SparseArray) AtomicLong(java.util.concurrent.atomic.AtomicLong)

Aggregations

SQLiteCursor (org.telegram.SQLite.SQLiteCursor)118 SQLiteException (org.telegram.SQLite.SQLiteException)105 TLRPC (org.telegram.tgnet.TLRPC)77 NativeByteBuffer (org.telegram.tgnet.NativeByteBuffer)66 ArrayList (java.util.ArrayList)58 SQLitePreparedStatement (org.telegram.SQLite.SQLitePreparedStatement)42 LongSparseArray (androidx.collection.LongSparseArray)25 AtomicLong (java.util.concurrent.atomic.AtomicLong)19 Paint (android.graphics.Paint)18 SparseArray (android.util.SparseArray)11 CountDownLatch (java.util.concurrent.CountDownLatch)11 SpannableStringBuilder (android.text.SpannableStringBuilder)10 LongSparseIntArray (org.telegram.messenger.support.LongSparseIntArray)10 File (java.io.File)8 HashMap (java.util.HashMap)7 Pair (android.util.Pair)6 TLObject (org.telegram.tgnet.TLObject)6 LinkedHashMap (java.util.LinkedHashMap)4 SharedPreferences (android.content.SharedPreferences)3 SpannedString (android.text.SpannedString)3