Search in sources :

Example 66 with SQLiteCursor

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

the class MessagesStorage method getWidgetDialogIds.

public void getWidgetDialogIds(int widgetId, int type, ArrayList<Long> dids, ArrayList<TLRPC.User> users, ArrayList<TLRPC.Chat> chats, boolean edit) {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    storageQueue.postRunnable(() -> {
        try {
            ArrayList<Long> usersToLoad = new ArrayList<>();
            ArrayList<Long> chatsToLoad = new ArrayList<>();
            SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT did FROM shortcut_widget WHERE id = %d ORDER BY ord ASC", widgetId));
            while (cursor.next()) {
                long id = cursor.longValue(0);
                if (id == -1) {
                    continue;
                }
                dids.add(id);
                if (users != null && chats != null) {
                    if (DialogObject.isUserDialog(id)) {
                        usersToLoad.add(id);
                    } else {
                        chatsToLoad.add(-id);
                    }
                }
            }
            cursor.dispose();
            if (!edit && dids.isEmpty()) {
                if (type == EditWidgetActivity.TYPE_CHATS) {
                    cursor = database.queryFinalized("SELECT did FROM dialogs WHERE folder_id = 0 ORDER BY pinned DESC, date DESC LIMIT 0,10");
                    while (cursor.next()) {
                        long dialogId = cursor.longValue(0);
                        if (DialogObject.isFolderDialogId(dialogId)) {
                            continue;
                        }
                        dids.add(dialogId);
                        if (users != null && chats != null) {
                            if (DialogObject.isUserDialog(dialogId)) {
                                usersToLoad.add(dialogId);
                            } else {
                                chatsToLoad.add(-dialogId);
                            }
                        }
                    }
                    cursor.dispose();
                } else {
                    cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT did FROM chat_hints WHERE type = 0 ORDER BY rating DESC LIMIT 4");
                    while (cursor.next()) {
                        long dialogId = cursor.longValue(0);
                        dids.add(dialogId);
                        if (users != null && chats != null) {
                            if (DialogObject.isUserDialog(dialogId)) {
                                usersToLoad.add(dialogId);
                            } else {
                                chatsToLoad.add(-dialogId);
                            }
                        }
                    }
                    cursor.dispose();
                }
            }
            if (users != null && chats != null) {
                if (!chatsToLoad.isEmpty()) {
                    getChatsInternal(TextUtils.join(",", chatsToLoad), chats);
                }
                if (!usersToLoad.isEmpty()) {
                    getUsersInternal(TextUtils.join(",", usersToLoad), users);
                }
            }
        } catch (Exception e) {
            FileLog.e(e);
        } finally {
            countDownLatch.countDown();
        }
    });
    try {
        countDownLatch.await();
    } catch (Exception e) {
        FileLog.e(e);
    }
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) SQLiteException(org.telegram.SQLite.SQLiteException)

Example 67 with SQLiteCursor

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

the class MessagesStorage method setDialogUnread.

public void setDialogUnread(long did, boolean unread) {
    storageQueue.postRunnable(() -> {
        try {
            int flags = 0;
            SQLiteCursor cursor = null;
            try {
                cursor = database.queryFinalized("SELECT flags FROM dialogs WHERE did = " + did);
                if (cursor.next()) {
                    flags = cursor.intValue(0);
                }
            } catch (Exception e) {
                FileLog.e(e);
            } finally {
                if (cursor != null) {
                    cursor.dispose();
                }
            }
            if (unread) {
                flags |= 1;
            } else {
                flags &= ~1;
            }
            SQLitePreparedStatement state = database.executeFast("UPDATE dialogs SET flags = ? WHERE did = ?");
            state.bindInteger(1, flags);
            state.bindLong(2, did);
            state.step();
            state.dispose();
            resetAllUnreadCounters(false);
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : SQLiteCursor(org.telegram.SQLite.SQLiteCursor) SQLiteException(org.telegram.SQLite.SQLiteException) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement)

Example 68 with SQLiteCursor

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

the class MessagesStorage method getCachedPhoneBook.

public void getCachedPhoneBook(boolean byError) {
    storageQueue.postRunnable(() -> {
        SQLiteCursor cursor = null;
        try {
            cursor = database.queryFinalized("SELECT name FROM sqlite_master WHERE type='table' AND name='user_contacts_v6'");
            boolean migrate = cursor.next();
            cursor.dispose();
            cursor = null;
            if (migrate) {
                int count = 16;
                cursor = database.queryFinalized("SELECT COUNT(uid) FROM user_contacts_v6 WHERE 1");
                if (cursor.next()) {
                    count = Math.min(5000, cursor.intValue(0));
                }
                cursor.dispose();
                SparseArray<ContactsController.Contact> contactHashMap = new SparseArray<>(count);
                cursor = database.queryFinalized("SELECT us.uid, us.fname, us.sname, up.phone, up.sphone, up.deleted, us.imported FROM user_contacts_v6 as us LEFT JOIN user_phones_v6 as up ON us.uid = up.uid WHERE 1");
                while (cursor.next()) {
                    int uid = cursor.intValue(0);
                    ContactsController.Contact contact = contactHashMap.get(uid);
                    if (contact == null) {
                        contact = new ContactsController.Contact();
                        contact.first_name = cursor.stringValue(1);
                        contact.last_name = cursor.stringValue(2);
                        contact.imported = cursor.intValue(6);
                        if (contact.first_name == null) {
                            contact.first_name = "";
                        }
                        if (contact.last_name == null) {
                            contact.last_name = "";
                        }
                        contact.contact_id = uid;
                        contactHashMap.put(uid, contact);
                    }
                    String phone = cursor.stringValue(3);
                    if (phone == null) {
                        continue;
                    }
                    contact.phones.add(phone);
                    String sphone = cursor.stringValue(4);
                    if (sphone == null) {
                        continue;
                    }
                    if (sphone.length() == 8 && phone.length() != 8) {
                        sphone = PhoneFormat.stripExceptNumbers(phone);
                    }
                    contact.shortPhones.add(sphone);
                    contact.phoneDeleted.add(cursor.intValue(5));
                    contact.phoneTypes.add("");
                    if (contactHashMap.size() == 5000) {
                        break;
                    }
                }
                cursor.dispose();
                cursor = null;
                getContactsController().migratePhoneBookToV7(contactHashMap);
                return;
            }
        } catch (Throwable e) {
            FileLog.e(e);
        } finally {
            if (cursor != null) {
                cursor.dispose();
            }
        }
        int count = 16;
        int currentContactsCount = 0;
        int start = 0;
        try {
            cursor = database.queryFinalized("SELECT COUNT(key) FROM user_contacts_v7 WHERE 1");
            if (cursor.next()) {
                currentContactsCount = cursor.intValue(0);
                count = Math.min(5000, currentContactsCount);
                if (currentContactsCount > 5000) {
                    start = currentContactsCount - 5000;
                }
                if (BuildVars.LOGS_ENABLED) {
                    FileLog.d(currentAccount + " current cached contacts count = " + currentContactsCount);
                }
            }
        } catch (Throwable e) {
            FileLog.e(e);
        } finally {
            if (cursor != null) {
                cursor.dispose();
            }
        }
        HashMap<String, ContactsController.Contact> contactHashMap = new HashMap<>(count);
        try {
            if (start != 0) {
                cursor = database.queryFinalized("SELECT us.key, us.uid, us.fname, us.sname, up.phone, up.sphone, up.deleted, us.imported FROM user_contacts_v7 as us LEFT JOIN user_phones_v7 as up ON us.key = up.key WHERE 1 LIMIT " + 0 + "," + currentContactsCount);
            } else {
                cursor = database.queryFinalized("SELECT us.key, us.uid, us.fname, us.sname, up.phone, up.sphone, up.deleted, us.imported FROM user_contacts_v7 as us LEFT JOIN user_phones_v7 as up ON us.key = up.key WHERE 1");
            }
            while (cursor.next()) {
                String key = cursor.stringValue(0);
                ContactsController.Contact contact = contactHashMap.get(key);
                if (contact == null) {
                    contact = new ContactsController.Contact();
                    contact.contact_id = cursor.intValue(1);
                    contact.first_name = cursor.stringValue(2);
                    contact.last_name = cursor.stringValue(3);
                    contact.imported = cursor.intValue(7);
                    if (contact.first_name == null) {
                        contact.first_name = "";
                    }
                    if (contact.last_name == null) {
                        contact.last_name = "";
                    }
                    contactHashMap.put(key, contact);
                }
                String phone = cursor.stringValue(4);
                if (phone == null) {
                    continue;
                }
                contact.phones.add(phone);
                String sphone = cursor.stringValue(5);
                if (sphone == null) {
                    continue;
                }
                if (sphone.length() == 8 && phone.length() != 8) {
                    sphone = PhoneFormat.stripExceptNumbers(phone);
                }
                contact.shortPhones.add(sphone);
                contact.phoneDeleted.add(cursor.intValue(6));
                contact.phoneTypes.add("");
                if (contactHashMap.size() == 5000) {
                    break;
                }
            }
            cursor.dispose();
            cursor = null;
        } catch (Exception e) {
            contactHashMap.clear();
            FileLog.e(e);
        } finally {
            if (cursor != null) {
                cursor.dispose();
            }
        }
        getContactsController().performSyncPhoneBook(contactHashMap, true, true, false, false, !byError, false);
    });
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) SQLiteException(org.telegram.SQLite.SQLiteException) LongSparseArray(androidx.collection.LongSparseArray) SparseArray(android.util.SparseArray)

Example 69 with SQLiteCursor

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

the class MessagesStorage method putMessagesInternal.

private void putMessagesInternal(ArrayList<TLRPC.Message> messages, boolean withTransaction, boolean doNotUpdateDialogDate, int downloadMask, boolean ifNoLastMessage, boolean scheduled) {
    try {
        if (scheduled) {
            if (withTransaction) {
                database.beginTransaction();
            }
            SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO scheduled_messages_v2 VALUES(?, ?, ?, ?, ?, ?, NULL, 0)");
            SQLitePreparedStatement state_randoms = database.executeFast("REPLACE INTO randoms_v2 VALUES(?, ?, ?)");
            ArrayList<Long> dialogsToUpdate = new ArrayList<>();
            for (int a = 0; a < messages.size(); a++) {
                TLRPC.Message message = messages.get(a);
                if (message instanceof TLRPC.TL_messageEmpty) {
                    continue;
                }
                fixUnsupportedMedia(message);
                state_messages.requery();
                int messageId = message.id;
                if (message.local_id != 0) {
                    messageId = message.local_id;
                }
                NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize());
                message.serializeToStream(data);
                long did = MessageObject.getDialogId(message);
                state_messages.bindInteger(1, messageId);
                state_messages.bindLong(2, did);
                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();
                if (message.random_id != 0) {
                    state_randoms.requery();
                    state_randoms.bindLong(1, message.random_id);
                    state_randoms.bindInteger(2, messageId);
                    state_randoms.bindLong(3, message.dialog_id);
                    state_randoms.step();
                }
                data.reuse();
                if (!dialogsToUpdate.contains(did)) {
                    dialogsToUpdate.add(did);
                }
            }
            state_messages.dispose();
            state_randoms.dispose();
            if (withTransaction) {
                database.commitTransaction();
            }
            for (int a = 0, N = dialogsToUpdate.size(); a < N; a++) {
                broadcastScheduledMessagesChange(dialogsToUpdate.get(a));
            }
        } else {
            if (ifNoLastMessage) {
                TLRPC.Message lastMessage = messages.get(0);
                if (lastMessage.dialog_id == 0) {
                    MessageObject.getDialogId(lastMessage);
                }
                int lastMid = -1;
                SQLiteCursor cursor = database.queryFinalized("SELECT last_mid FROM dialogs WHERE did = " + lastMessage.dialog_id);
                if (cursor.next()) {
                    lastMid = cursor.intValue(0);
                }
                cursor.dispose();
                if (lastMid != 0) {
                    return;
                }
            }
            if (withTransaction) {
                database.beginTransaction();
            }
            LongSparseArray<TLRPC.Message> messagesMap = new LongSparseArray<>();
            LongSparseIntArray messagesCounts = new LongSparseIntArray();
            LongSparseIntArray newMessagesCounts = new LongSparseIntArray();
            LongSparseIntArray newMentionsCounts = new LongSparseIntArray();
            LongSparseIntArray mentionCounts = new LongSparseIntArray();
            SparseArray<LongSparseIntArray> mediaCounts = null;
            LongSparseArray<TLRPC.Message> botKeyboards = new LongSparseArray<>();
            LongSparseArray<ArrayList<Integer>> dialogMessagesMediaIdsMap = null;
            LongSparseArray<SparseIntArray> dialogsMediaTypesChange = null;
            LongSparseArray<StringBuilder> mediaIdsMap = null;
            LongSparseArray<SparseIntArray> dialogMediaTypes = null;
            LongSparseArray<StringBuilder> messageIdsMap = new LongSparseArray<>();
            LongSparseIntArray dialogsReadMax = new LongSparseIntArray();
            LongSparseArray<ArrayList<Integer>> dialogMessagesIdsMap = new LongSparseArray<>();
            LongSparseArray<ArrayList<Integer>> dialogMentionsIdsMap = new LongSparseArray<>();
            SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, 0)");
            SQLitePreparedStatement state_media = null;
            SQLitePreparedStatement state_randoms = database.executeFast("REPLACE INTO randoms_v2 VALUES(?, ?, ?)");
            SQLitePreparedStatement state_download = database.executeFast("REPLACE INTO download_queue VALUES(?, ?, ?, ?, ?)");
            SQLitePreparedStatement state_webpage = database.executeFast("REPLACE INTO webpage_pending_v2 VALUES(?, ?, ?)");
            SQLitePreparedStatement state_polls = null;
            SQLitePreparedStatement state_tasks = null;
            int minDeleteTime = Integer.MAX_VALUE;
            for (int a = 0; a < messages.size(); a++) {
                TLRPC.Message message = messages.get(a);
                int messageId = message.id;
                MessageObject.getDialogId(message);
                if (message.mentioned && message.media_unread) {
                    ArrayList<Integer> ids = dialogMentionsIdsMap.get(message.dialog_id);
                    if (ids == null) {
                        ids = new ArrayList<>();
                        dialogMentionsIdsMap.put(message.dialog_id, ids);
                    }
                    ids.add(messageId);
                }
                if (!(message.action instanceof TLRPC.TL_messageActionHistoryClear) && (!MessageObject.isOut(message) || message.from_scheduled) && (message.id > 0 || MessageObject.isUnread(message))) {
                    int currentMaxId = dialogsReadMax.get(message.dialog_id, -1);
                    if (currentMaxId == -1) {
                        SQLiteCursor cursor = database.queryFinalized("SELECT inbox_max FROM dialogs WHERE did = " + message.dialog_id);
                        if (cursor.next()) {
                            currentMaxId = cursor.intValue(0);
                        } else {
                            currentMaxId = 0;
                        }
                        cursor.dispose();
                        dialogsReadMax.put(message.dialog_id, currentMaxId);
                    }
                    if (message.id < 0 || currentMaxId < message.id) {
                        StringBuilder messageIds = messageIdsMap.get(message.dialog_id);
                        if (messageIds == null) {
                            messageIds = new StringBuilder();
                            messageIdsMap.put(message.dialog_id, messageIds);
                        }
                        if (messageIds.length() > 0) {
                            messageIds.append(",");
                        }
                        messageIds.append(messageId);
                        ArrayList<Integer> ids = dialogMessagesIdsMap.get(message.dialog_id);
                        if (ids == null) {
                            ids = new ArrayList<>();
                            dialogMessagesIdsMap.put(message.dialog_id, ids);
                        }
                        ids.add(messageId);
                    }
                }
                if (MediaDataController.canAddMessageToMedia(message)) {
                    if (mediaIdsMap == null) {
                        mediaIdsMap = new LongSparseArray<>();
                        dialogMessagesMediaIdsMap = new LongSparseArray<>();
                        dialogMediaTypes = new LongSparseArray<>();
                    }
                    StringBuilder messageMediaIds = mediaIdsMap.get(message.dialog_id);
                    if (messageMediaIds == null) {
                        messageMediaIds = new StringBuilder();
                        mediaIdsMap.put(message.dialog_id, messageMediaIds);
                    }
                    if (messageMediaIds.length() > 0) {
                        messageMediaIds.append(",");
                    }
                    messageMediaIds.append(messageId);
                    ArrayList<Integer> ids = dialogMessagesMediaIdsMap.get(message.dialog_id);
                    if (ids == null) {
                        ids = new ArrayList<>();
                        dialogMessagesMediaIdsMap.put(message.dialog_id, ids);
                    }
                    ids.add(messageId);
                    SparseIntArray mediaTypes = dialogMediaTypes.get(message.dialog_id);
                    if (mediaTypes == null) {
                        mediaTypes = new SparseIntArray();
                        dialogMediaTypes.put(message.dialog_id, mediaTypes);
                    }
                    mediaTypes.put(messageId, MediaDataController.getMediaType(message));
                }
                if (isValidKeyboardToSave(message)) {
                    TLRPC.Message oldMessage = botKeyboards.get(message.dialog_id);
                    if (oldMessage == null || oldMessage.id < message.id) {
                        botKeyboards.put(message.dialog_id, message);
                    }
                }
            }
            for (int a = 0; a < botKeyboards.size(); a++) {
                getMediaDataController().putBotKeyboard(botKeyboards.keyAt(a), botKeyboards.valueAt(a));
            }
            if (mediaIdsMap != null) {
                for (int b = 0, N2 = mediaIdsMap.size(); b < N2; b++) {
                    long dialogId = mediaIdsMap.keyAt(b);
                    StringBuilder messageMediaIds = mediaIdsMap.valueAt(b);
                    SparseIntArray mediaTypes = dialogMediaTypes.get(dialogId);
                    ArrayList<Integer> messagesMediaIdsMap = dialogMessagesMediaIdsMap.get(dialogId);
                    SparseIntArray mediaTypesChange = null;
                    SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, type FROM media_v4 WHERE mid IN(%s) AND uid = %d", messageMediaIds.toString(), dialogId));
                    while (cursor.next()) {
                        int mid = cursor.intValue(0);
                        int type = cursor.intValue(1);
                        if (type == mediaTypes.get(mid)) {
                            messagesMediaIdsMap.remove((Integer) mid);
                        } else {
                            if (mediaTypesChange == null) {
                                if (dialogsMediaTypesChange == null) {
                                    dialogsMediaTypesChange = new LongSparseArray<>();
                                }
                                mediaTypesChange = dialogsMediaTypesChange.get(dialogId);
                                if (mediaTypesChange == null) {
                                    mediaTypesChange = new SparseIntArray();
                                    dialogsMediaTypesChange.put(dialogId, mediaTypesChange);
                                }
                            }
                            mediaTypesChange.put(mid, type);
                        }
                    }
                    cursor.dispose();
                    if (mediaCounts == null) {
                        mediaCounts = new SparseArray<>();
                    }
                    for (int a = 0, N = messagesMediaIdsMap.size(); a < N; a++) {
                        int key = messagesMediaIdsMap.get(a);
                        int type = mediaTypes.get(key);
                        LongSparseIntArray counts = mediaCounts.get(type);
                        int count;
                        if (counts == null) {
                            counts = new LongSparseIntArray();
                            mediaCounts.put(type, counts);
                            count = 0;
                        } else {
                            count = counts.get(dialogId, Integer.MIN_VALUE);
                        }
                        if (count == Integer.MIN_VALUE) {
                            count = 0;
                        }
                        count++;
                        counts.put(dialogId, count);
                        if (mediaTypesChange != null) {
                            int previousType = mediaTypesChange.get(key, -1);
                            if (previousType >= 0) {
                                counts = mediaCounts.get(previousType);
                                if (counts == null) {
                                    counts = new LongSparseIntArray();
                                    count = 0;
                                    mediaCounts.put(previousType, counts);
                                } else {
                                    count = counts.get(dialogId, Integer.MIN_VALUE);
                                }
                                if (count == Integer.MIN_VALUE) {
                                    count = 0;
                                }
                                count--;
                                counts.put(dialogId, count);
                            }
                        }
                    }
                }
            }
            if (!messageIdsMap.isEmpty()) {
                for (int b = 0, N2 = messageIdsMap.size(); b < N2; b++) {
                    long dialogId = messageIdsMap.keyAt(b);
                    StringBuilder messageIds = messageIdsMap.valueAt(b);
                    ArrayList<Integer> messagesIdsMap = dialogMessagesIdsMap.get(dialogId);
                    ArrayList<Integer> mentionsIdsMap = dialogMentionsIdsMap.get(dialogId);
                    SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages_v2 WHERE mid IN(%s) AND uid = %d", messageIds.toString(), dialogId));
                    while (cursor.next()) {
                        Integer mid = cursor.intValue(0);
                        if (messagesIdsMap != null) {
                            messagesIdsMap.remove(mid);
                        }
                        if (mentionsIdsMap != null) {
                            mentionsIdsMap.remove(mid);
                        }
                    }
                    cursor.dispose();
                    if (messagesCounts != null) {
                        int count = messagesCounts.get(dialogId, -1);
                        if (count < 0) {
                            count = 0;
                        }
                        count += messagesIdsMap.size();
                        messagesCounts.put(dialogId, count);
                    }
                    if (mentionsIdsMap != null) {
                        int count = mentionCounts.get(dialogId, -1);
                        if (count < 0) {
                            count = 0;
                        }
                        count += mentionsIdsMap.size();
                        mentionCounts.put(dialogId, count);
                    }
                }
            }
            int downloadMediaMask = 0;
            for (int a = 0; a < messages.size(); a++) {
                TLRPC.Message message = messages.get(a);
                fixUnsupportedMedia(message);
                state_messages.requery();
                int messageId = message.id;
                if (message.local_id != 0) {
                    messageId = message.local_id;
                }
                NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize());
                message.serializeToStream(data);
                boolean updateDialog = true;
                if (message.action instanceof TLRPC.TL_messageEncryptedAction && !(message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL || message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages)) {
                    updateDialog = false;
                } else if (message.out) {
                    SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages_v2 WHERE mid = %d AND uid = %d", messageId, message.dialog_id));
                    if (cursor.next()) {
                        updateDialog = false;
                    }
                    cursor.dispose();
                }
                if (updateDialog) {
                    TLRPC.Message lastMessage = messagesMap.get(message.dialog_id);
                    if (lastMessage == null || message.date > lastMessage.date || lastMessage.id > 0 && message.id > lastMessage.id || lastMessage.id < 0 && message.id < lastMessage.id) {
                        messagesMap.put(message.dialog_id, message);
                    }
                }
                state_messages.bindInteger(1, messageId);
                state_messages.bindLong(2, message.dialog_id);
                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 (message.random_id != 0) {
                    state_randoms.requery();
                    state_randoms.bindLong(1, message.random_id);
                    state_randoms.bindInteger(2, messageId);
                    state_randoms.bindLong(3, message.dialog_id);
                    state_randoms.step();
                }
                if (MediaDataController.canAddMessageToMedia(message)) {
                    if (state_media == null) {
                        state_media = database.executeFast("REPLACE INTO media_v4 VALUES(?, ?, ?, ?, ?)");
                    }
                    state_media.requery();
                    state_media.bindInteger(1, messageId);
                    state_media.bindLong(2, message.dialog_id);
                    state_media.bindInteger(3, message.date);
                    state_media.bindInteger(4, MediaDataController.getMediaType(message));
                    state_media.bindByteBuffer(5, data);
                    state_media.step();
                }
                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, messageId);
                    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, messageId);
                    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) {
                    state_webpage.requery();
                    state_webpage.bindLong(1, message.media.webpage.id);
                    state_webpage.bindInteger(2, messageId);
                    state_webpage.bindLong(3, message.dialog_id);
                    state_webpage.step();
                }
                if (repliesData != null) {
                    repliesData.reuse();
                }
                data.reuse();
                if (downloadMask != 0 && (message.peer_id.channel_id == 0 || message.post) && message.date >= getConnectionsManager().getCurrentTime() - 60 * 60 && getDownloadController().canDownloadMedia(message) == 1) {
                    if (message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaDocument || message.media instanceof TLRPC.TL_messageMediaWebPage) {
                        int type = 0;
                        long id = 0;
                        TLRPC.MessageMedia object = null;
                        TLRPC.Document document = MessageObject.getDocument(message);
                        TLRPC.Photo photo = MessageObject.getPhoto(message);
                        if (MessageObject.isVoiceMessage(message)) {
                            id = document.id;
                            type = DownloadController.AUTODOWNLOAD_TYPE_AUDIO;
                            object = new TLRPC.TL_messageMediaDocument();
                            object.document = document;
                            object.flags |= 1;
                        } else if (MessageObject.isStickerMessage(message) || MessageObject.isAnimatedStickerMessage(message)) {
                            id = document.id;
                            type = DownloadController.AUTODOWNLOAD_TYPE_PHOTO;
                            object = new TLRPC.TL_messageMediaDocument();
                            object.document = document;
                            object.flags |= 1;
                        } else if (MessageObject.isVideoMessage(message) || MessageObject.isRoundVideoMessage(message) || MessageObject.isGifMessage(message)) {
                            id = document.id;
                            type = DownloadController.AUTODOWNLOAD_TYPE_VIDEO;
                            object = new TLRPC.TL_messageMediaDocument();
                            object.document = document;
                            object.flags |= 1;
                        } else if (document != null) {
                            id = document.id;
                            type = DownloadController.AUTODOWNLOAD_TYPE_DOCUMENT;
                            object = new TLRPC.TL_messageMediaDocument();
                            object.document = document;
                            object.flags |= 1;
                        } else if (photo != null) {
                            TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, AndroidUtilities.getPhotoSize());
                            if (photoSize != null) {
                                id = photo.id;
                                type = DownloadController.AUTODOWNLOAD_TYPE_PHOTO;
                                object = new TLRPC.TL_messageMediaPhoto();
                                object.photo = photo;
                                object.flags |= 1;
                                if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
                                    object.flags |= 0x80000000;
                                }
                            }
                        }
                        if (object != null) {
                            if (message.media.ttl_seconds != 0) {
                                object.ttl_seconds = message.media.ttl_seconds;
                                object.flags |= 4;
                            }
                            downloadMediaMask |= type;
                            state_download.requery();
                            data = new NativeByteBuffer(object.getObjectSize());
                            object.serializeToStream(data);
                            state_download.bindLong(1, id);
                            state_download.bindInteger(2, type);
                            state_download.bindInteger(3, message.date);
                            state_download.bindByteBuffer(4, data);
                            state_download.bindString(5, "sent_" + (message.peer_id != null ? message.peer_id.channel_id : 0) + "_" + message.id);
                            state_download.step();
                            data.reuse();
                        }
                    }
                }
            }
            state_messages.dispose();
            if (state_media != null) {
                state_media.dispose();
            }
            if (state_tasks != null) {
                state_tasks.dispose();
                getMessagesController().didAddedNewTask(minDeleteTime, 0, null);
            }
            if (state_polls != null) {
                state_polls.dispose();
            }
            state_randoms.dispose();
            state_download.dispose();
            state_webpage.dispose();
            SQLitePreparedStatement state_dialogs_replace = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            SQLitePreparedStatement state_dialogs_update = database.executeFast("UPDATE dialogs SET date = ?, unread_count = ?, last_mid = ?, unread_count_i = ? WHERE did = ?");
            ArrayList<Long> dids = new ArrayList<>();
            for (int a = 0; a < messagesMap.size(); a++) {
                long key = messagesMap.keyAt(a);
                if (key == 0) {
                    continue;
                }
                TLRPC.Message message = messagesMap.valueAt(a);
                long channelId = MessageObject.getChannelId(message);
                SQLiteCursor cursor = database.queryFinalized("SELECT date, unread_count, last_mid, unread_count_i FROM dialogs WHERE did = " + key);
                int dialog_date = 0;
                int last_mid = 0;
                int old_unread_count = 0;
                int old_mentions_count = 0;
                boolean exists;
                if (exists = cursor.next()) {
                    dialog_date = cursor.intValue(0);
                    old_unread_count = Math.max(0, cursor.intValue(1));
                    last_mid = cursor.intValue(2);
                    old_mentions_count = Math.max(0, cursor.intValue(3));
                } else if (channelId != 0) {
                    getMessagesController().checkChatInviter(channelId, true);
                }
                cursor.dispose();
                int mentions_count = mentionCounts.get(key, -1);
                int unread_count = messagesCounts.get(key, -1);
                if (unread_count == -1) {
                    unread_count = 0;
                } else {
                    messagesCounts.put(key, unread_count + old_unread_count);
                }
                if (mentions_count == -1) {
                    mentions_count = 0;
                } else {
                    mentionCounts.put(key, mentions_count + old_mentions_count);
                }
                int messageId = message != null ? message.id : last_mid;
                if (message != null) {
                    if (message.local_id != 0) {
                        messageId = message.local_id;
                    }
                }
                if (old_unread_count == 0 && unread_count != 0) {
                    newMessagesCounts.put(key, unread_count);
                }
                if (old_mentions_count == 0 && mentions_count != 0) {
                    newMentionsCounts.put(key, mentions_count);
                }
                dids.add(key);
                if (exists) {
                    state_dialogs_update.requery();
                    state_dialogs_update.bindInteger(1, message != null && (!doNotUpdateDialogDate || dialog_date == 0) ? message.date : dialog_date);
                    state_dialogs_update.bindInteger(2, old_unread_count + unread_count);
                    state_dialogs_update.bindInteger(3, messageId);
                    state_dialogs_update.bindInteger(4, old_mentions_count + mentions_count);
                    state_dialogs_update.bindLong(5, key);
                    state_dialogs_update.step();
                } else {
                    state_dialogs_replace.requery();
                    state_dialogs_replace.bindLong(1, key);
                    state_dialogs_replace.bindInteger(2, message != null && (!doNotUpdateDialogDate || dialog_date == 0) ? message.date : dialog_date);
                    state_dialogs_replace.bindInteger(3, old_unread_count + unread_count);
                    state_dialogs_replace.bindInteger(4, messageId);
                    state_dialogs_replace.bindInteger(5, 0);
                    state_dialogs_replace.bindInteger(6, 0);
                    state_dialogs_replace.bindLong(7, 0);
                    state_dialogs_replace.bindInteger(8, old_mentions_count + mentions_count);
                    state_dialogs_replace.bindInteger(9, channelId != 0 ? 1 : 0);
                    state_dialogs_replace.bindInteger(10, 0);
                    state_dialogs_replace.bindInteger(11, 0);
                    state_dialogs_replace.bindInteger(12, 0);
                    state_dialogs_replace.bindInteger(13, 0);
                    state_dialogs_replace.bindNull(14);
                    state_dialogs_replace.bindInteger(15, 0);
                    state_dialogs_replace.step();
                    unknownDialogsIds.put(key, true);
                }
            }
            state_dialogs_update.dispose();
            state_dialogs_replace.dispose();
            if (mediaCounts != null) {
                state_randoms = database.executeFast("REPLACE INTO media_counts_v2 VALUES(?, ?, ?, ?)");
                for (int a = 0, N = mediaCounts.size(); a < N; a++) {
                    int type = mediaCounts.keyAt(a);
                    LongSparseIntArray value = mediaCounts.valueAt(a);
                    for (int b = 0, N2 = value.size(); b < N2; b++) {
                        long uid = value.keyAt(b);
                        int count = -1;
                        int old = 0;
                        SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT count, old FROM media_counts_v2 WHERE uid = %d AND type = %d LIMIT 1", uid, type));
                        if (cursor.next()) {
                            count = cursor.intValue(0);
                            old = cursor.intValue(1);
                        }
                        cursor.dispose();
                        if (count != -1) {
                            state_randoms.requery();
                            count += value.valueAt(b);
                            state_randoms.bindLong(1, uid);
                            state_randoms.bindInteger(2, type);
                            state_randoms.bindInteger(3, Math.max(0, count));
                            state_randoms.bindInteger(4, old);
                            state_randoms.step();
                        }
                    }
                }
                state_randoms.dispose();
            }
            if (withTransaction) {
                database.commitTransaction();
            }
            updateFiltersReadCounter(newMessagesCounts, newMentionsCounts, false);
            getMessagesController().processDialogsUpdateRead(messagesCounts, mentionCounts);
            if (downloadMediaMask != 0) {
                int downloadMediaMaskFinal = downloadMediaMask;
                AndroidUtilities.runOnUIThread(() -> getDownloadController().newDownloadObjectsAvailable(downloadMediaMaskFinal));
            }
            updateWidgets(dids);
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
}
Also used : LongSparseArray(androidx.collection.LongSparseArray) SpannableStringBuilder(android.text.SpannableStringBuilder) 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) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteException(org.telegram.SQLite.SQLiteException) SparseIntArray(android.util.SparseIntArray) LongSparseIntArray(org.telegram.messenger.support.LongSparseIntArray) AtomicLong(java.util.concurrent.atomic.AtomicLong)

Example 70 with SQLiteCursor

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

the class MessagesStorage method loadChatInfoInternal.

private TLRPC.ChatFull loadChatInfoInternal(long chatId, boolean isChannel, boolean force, boolean byChannelUsers, int fromMessageId) {
    TLRPC.ChatFull info = null;
    ArrayList<TLRPC.User> loadedUsers = new ArrayList<>();
    HashMap<Integer, MessageObject> pinnedMessagesMap = new HashMap<>();
    ArrayList<Integer> pinnedMessages = new ArrayList<>();
    int totalPinnedCount = 0;
    boolean pinnedEndReached = false;
    try {
        SQLiteCursor cursor = database.queryFinalized("SELECT info, pinned, online, inviter, links FROM chat_settings_v2 WHERE uid = " + chatId);
        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);
                info.invitesCount = cursor.intValue(4);
            }
        }
        cursor.dispose();
        if (info instanceof TLRPC.TL_chatFull) {
            StringBuilder usersToLoad = new StringBuilder();
            for (int a = 0; a < info.participants.participants.size(); a++) {
                TLRPC.ChatParticipant c = info.participants.participants.get(a);
                if (usersToLoad.length() != 0) {
                    usersToLoad.append(",");
                }
                usersToLoad.append(c.user_id);
            }
            if (usersToLoad.length() != 0) {
                getUsersInternal(usersToLoad.toString(), loadedUsers);
            }
        } else if (info instanceof TLRPC.TL_channelFull) {
            cursor = database.queryFinalized("SELECT us.data, us.status, cu.data, cu.date FROM channel_users_v2 as cu LEFT JOIN users as us ON us.uid = cu.uid WHERE cu.did = " + (-chatId) + " ORDER BY cu.date DESC");
            info.participants = new TLRPC.TL_chatParticipants();
            while (cursor.next()) {
                try {
                    TLRPC.User user = null;
                    TLRPC.ChannelParticipant participant = null;
                    NativeByteBuffer data = cursor.byteBufferValue(0);
                    if (data != null) {
                        user = TLRPC.User.TLdeserialize(data, data.readInt32(false), false);
                        data.reuse();
                    }
                    data = cursor.byteBufferValue(2);
                    if (data != null) {
                        participant = TLRPC.ChannelParticipant.TLdeserialize(data, data.readInt32(false), false);
                        data.reuse();
                    }
                    if (participant != null && participant.user_id == getUserConfig().clientUserId) {
                        user = getUserConfig().getCurrentUser();
                    }
                    if (user != null && participant != null) {
                        if (user.status != null) {
                            user.status.expires = cursor.intValue(1);
                        }
                        loadedUsers.add(user);
                        participant.date = cursor.intValue(3);
                        TLRPC.TL_chatChannelParticipant chatChannelParticipant = new TLRPC.TL_chatChannelParticipant();
                        chatChannelParticipant.user_id = MessageObject.getPeerId(participant.peer);
                        chatChannelParticipant.date = participant.date;
                        chatChannelParticipant.inviter_id = participant.inviter_id;
                        chatChannelParticipant.channelParticipant = participant;
                        info.participants.participants.add(chatChannelParticipant);
                    }
                } catch (Exception e) {
                    FileLog.e(e);
                }
            }
            cursor.dispose();
            StringBuilder usersToLoad = new StringBuilder();
            for (int a = 0; a < info.bot_info.size(); a++) {
                TLRPC.BotInfo botInfo = info.bot_info.get(a);
                if (usersToLoad.length() != 0) {
                    usersToLoad.append(",");
                }
                usersToLoad.append(botInfo.user_id);
            }
            if (usersToLoad.length() != 0) {
                getUsersInternal(usersToLoad.toString(), loadedUsers);
            }
        }
        if (info != null && info.inviterId != 0) {
            getUsersInternal("" + info.inviterId, loadedUsers);
        }
        cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT mid FROM chat_pinned_v2 WHERE uid = %d ORDER BY mid DESC", -chatId));
        while (cursor.next()) {
            int id = cursor.intValue(0);
            pinnedMessages.add(id);
            pinnedMessagesMap.put(id, null);
        }
        cursor.dispose();
        cursor = database.queryFinalized("SELECT count, end FROM chat_pinned_count WHERE uid = " + (-chatId));
        if (cursor.next()) {
            totalPinnedCount = cursor.intValue(0);
            pinnedEndReached = cursor.intValue(1) != 0;
        }
        cursor.dispose();
        if (info != null && info.pinned_msg_id != 0) {
            if (pinnedMessages.isEmpty() || info.pinned_msg_id > pinnedMessages.get(0)) {
                pinnedMessages.clear();
                pinnedMessages.add(info.pinned_msg_id);
                pinnedMessagesMap.put(info.pinned_msg_id, null);
            }
        }
        if (!pinnedMessages.isEmpty()) {
            ArrayList<MessageObject> messageObjects = getMediaDataController().loadPinnedMessages(-chatId, isChannel ? chatId : 0, pinnedMessages, false);
            if (messageObjects != null) {
                for (int a = 0, N = messageObjects.size(); a < N; a++) {
                    MessageObject messageObject = messageObjects.get(a);
                    pinnedMessagesMap.put(messageObject.getId(), messageObject);
                }
            }
        }
    } catch (Exception e) {
        FileLog.e(e);
    } finally {
        getMessagesController().processChatInfo(chatId, info, loadedUsers, true, force, byChannelUsers, pinnedMessages, pinnedMessagesMap, totalPinnedCount, pinnedEndReached);
    }
    return info;
}
Also used : SpannableStringBuilder(android.text.SpannableStringBuilder) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) NativeByteBuffer(org.telegram.tgnet.NativeByteBuffer) SQLiteException(org.telegram.SQLite.SQLiteException)

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