Search in sources :

Example 1 with SQLiteCursor

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

the class DialogsSearchAdapter method loadRecentSearch.

public static void loadRecentSearch(int currentAccount, int dialogsType, OnRecentSearchLoaded callback) {
    MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
        try {
            SQLiteCursor cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT did, date FROM search_recent WHERE 1");
            ArrayList<Long> usersToLoad = new ArrayList<>();
            ArrayList<Long> chatsToLoad = new ArrayList<>();
            ArrayList<Integer> encryptedToLoad = new ArrayList<>();
            ArrayList<TLRPC.User> encUsers = new ArrayList<>();
            final ArrayList<RecentSearchObject> arrayList = new ArrayList<>();
            final LongSparseArray<RecentSearchObject> hashMap = new LongSparseArray<>();
            while (cursor.next()) {
                long did = cursor.longValue(0);
                boolean add = false;
                if (DialogObject.isEncryptedDialog(did)) {
                    if (dialogsType == 0 || dialogsType == 3) {
                        int encryptedChatId = DialogObject.getEncryptedChatId(did);
                        if (!encryptedToLoad.contains(encryptedChatId)) {
                            encryptedToLoad.add(encryptedChatId);
                            add = true;
                        }
                    }
                } else if (DialogObject.isUserDialog(did)) {
                    if (dialogsType != 2 && !usersToLoad.contains(did)) {
                        usersToLoad.add(did);
                        add = true;
                    }
                } else {
                    if (!chatsToLoad.contains(-did)) {
                        chatsToLoad.add(-did);
                        add = true;
                    }
                }
                if (add) {
                    RecentSearchObject recentSearchObject = new RecentSearchObject();
                    recentSearchObject.did = did;
                    recentSearchObject.date = cursor.intValue(1);
                    arrayList.add(recentSearchObject);
                    hashMap.put(recentSearchObject.did, recentSearchObject);
                }
            }
            cursor.dispose();
            ArrayList<TLRPC.User> users = new ArrayList<>();
            if (!encryptedToLoad.isEmpty()) {
                ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<>();
                MessagesStorage.getInstance(currentAccount).getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, usersToLoad);
                for (int a = 0; a < encryptedChats.size(); a++) {
                    RecentSearchObject recentSearchObject = hashMap.get(DialogObject.makeEncryptedDialogId(encryptedChats.get(a).id));
                    if (recentSearchObject != null) {
                        recentSearchObject.object = encryptedChats.get(a);
                    }
                }
            }
            if (!chatsToLoad.isEmpty()) {
                ArrayList<TLRPC.Chat> chats = new ArrayList<>();
                MessagesStorage.getInstance(currentAccount).getChatsInternal(TextUtils.join(",", chatsToLoad), chats);
                for (int a = 0; a < chats.size(); a++) {
                    TLRPC.Chat chat = chats.get(a);
                    long did = -chat.id;
                    if (chat.migrated_to != null) {
                        RecentSearchObject recentSearchObject = hashMap.get(did);
                        hashMap.remove(did);
                        if (recentSearchObject != null) {
                            arrayList.remove(recentSearchObject);
                        }
                    } else {
                        RecentSearchObject recentSearchObject = hashMap.get(did);
                        if (recentSearchObject != null) {
                            recentSearchObject.object = chat;
                        }
                    }
                }
            }
            if (!usersToLoad.isEmpty()) {
                MessagesStorage.getInstance(currentAccount).getUsersInternal(TextUtils.join(",", usersToLoad), users);
                for (int a = 0; a < users.size(); a++) {
                    TLRPC.User user = users.get(a);
                    RecentSearchObject recentSearchObject = hashMap.get(user.id);
                    if (recentSearchObject != null) {
                        recentSearchObject.object = user;
                    }
                }
            }
            Collections.sort(arrayList, (lhs, rhs) -> {
                if (lhs.date < rhs.date) {
                    return 1;
                } else if (lhs.date > rhs.date) {
                    return -1;
                } else {
                    return 0;
                }
            });
            AndroidUtilities.runOnUIThread(() -> callback.setRecentSearch(arrayList, hashMap));
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : LongSparseArray(androidx.collection.LongSparseArray) ArrayList(java.util.ArrayList) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC)

Example 2 with SQLiteCursor

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

the class SearchAdapterHelper method loadRecentHashtags.

public boolean loadRecentHashtags() {
    if (hashtagsLoadedFromDb) {
        return true;
    }
    MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
        try {
            SQLiteCursor cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT id, date FROM hashtag_recent_v2 WHERE 1");
            final ArrayList<HashtagObject> arrayList = new ArrayList<>();
            final HashMap<String, HashtagObject> hashMap = new HashMap<>();
            while (cursor.next()) {
                HashtagObject hashtagObject = new HashtagObject();
                hashtagObject.hashtag = cursor.stringValue(0);
                hashtagObject.date = cursor.intValue(1);
                arrayList.add(hashtagObject);
                hashMap.put(hashtagObject.hashtag, hashtagObject);
            }
            cursor.dispose();
            Collections.sort(arrayList, (lhs, rhs) -> {
                if (lhs.date < rhs.date) {
                    return 1;
                } else if (lhs.date > rhs.date) {
                    return -1;
                } else {
                    return 0;
                }
            });
            AndroidUtilities.runOnUIThread(() -> setHashtags(arrayList, hashMap));
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
    return false;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SQLiteCursor(org.telegram.SQLite.SQLiteCursor)

Example 3 with SQLiteCursor

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

the class MessagesController method getNextReactionMention.

public void getNextReactionMention(long dialogId, int count, Consumer<Integer> callback) {
    final MessagesStorage messagesStorage = getMessagesStorage();
    messagesStorage.getStorageQueue().postRunnable(() -> {
        boolean needRequest = true;
        try {
            SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT message_id FROM reaction_mentions WHERE state = 1 AND dialog_id = %d LIMIT 1", dialogId));
            int messageId = 0;
            if (cursor.next()) {
                messageId = cursor.intValue(0);
                needRequest = false;
            }
            cursor.dispose();
            if (messageId != 0) {
                getMessagesStorage().markMessageReactionsAsRead(dialogId, messageId, false);
                int finalMessageId = messageId;
                AndroidUtilities.runOnUIThread(() -> callback.accept(finalMessageId));
            }
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
        if (needRequest) {
            TLRPC.TL_messages_getUnreadReactions req = new TLRPC.TL_messages_getUnreadReactions();
            req.peer = getMessagesController().getInputPeer(dialogId);
            req.limit = 1;
            req.add_offset = count - 1;
            getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
                int messageId = 0;
                if (error != null && res != null && res.messages != null && !res.messages.isEmpty()) {
                    messageId = res.messages.get(0).id;
                }
                int finalMessageId = messageId;
                AndroidUtilities.runOnUIThread(() -> callback.accept(finalMessageId));
            }));
        }
    });
}
Also used : SQLiteException(org.telegram.SQLite.SQLiteException) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC)

Example 4 with SQLiteCursor

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

the class MessagesController method migrateDialogs.

private void migrateDialogs(int offset, int offsetDate, long offsetUser, long offsetChat, long offsetChannel, long accessPeer) {
    if (migratingDialogs || offset == -1) {
        return;
    }
    migratingDialogs = true;
    TLRPC.TL_messages_getDialogs req = new TLRPC.TL_messages_getDialogs();
    req.exclude_pinned = true;
    req.limit = 100;
    req.offset_id = offset;
    req.offset_date = offsetDate;
    if (BuildVars.LOGS_ENABLED) {
        FileLog.d("start migrate with id " + offset + " date " + LocaleController.getInstance().formatterStats.format((long) offsetDate * 1000));
    }
    if (offset == 0) {
        req.offset_peer = new TLRPC.TL_inputPeerEmpty();
    } else {
        if (offsetChannel != 0) {
            req.offset_peer = new TLRPC.TL_inputPeerChannel();
            req.offset_peer.channel_id = offsetChannel;
        } else if (offsetUser != 0) {
            req.offset_peer = new TLRPC.TL_inputPeerUser();
            req.offset_peer.user_id = offsetUser;
        } else {
            req.offset_peer = new TLRPC.TL_inputPeerChat();
            req.offset_peer.chat_id = offsetChat;
        }
        req.offset_peer.access_hash = accessPeer;
    }
    getConnectionsManager().sendRequest(req, (response, error) -> {
        if (error == null) {
            TLRPC.messages_Dialogs dialogsRes = (TLRPC.messages_Dialogs) response;
            getMessagesStorage().getStorageQueue().postRunnable(() -> {
                try {
                    int offsetId;
                    int totalDialogsLoadCount = getUserConfig().getTotalDialogsCount(0);
                    getUserConfig().setTotalDialogsCount(0, totalDialogsLoadCount + dialogsRes.dialogs.size());
                    TLRPC.Message lastMessage = null;
                    for (int a = 0; a < dialogsRes.messages.size(); a++) {
                        TLRPC.Message message = dialogsRes.messages.get(a);
                        if (BuildVars.LOGS_ENABLED) {
                            FileLog.d("search migrate id " + message.id + " date " + LocaleController.getInstance().formatterStats.format((long) message.date * 1000));
                        }
                        if (lastMessage == null || message.date < lastMessage.date) {
                            lastMessage = message;
                        }
                    }
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("migrate step with id " + lastMessage.id + " date " + LocaleController.getInstance().formatterStats.format((long) lastMessage.date * 1000));
                    }
                    if (dialogsRes.dialogs.size() >= 100) {
                        offsetId = lastMessage.id;
                    } else {
                        if (BuildVars.LOGS_ENABLED) {
                            FileLog.d("migrate stop due to not 100 dialogs");
                        }
                        for (int i = 0; i < 2; i++) {
                            getUserConfig().setDialogsLoadOffset(i, Integer.MAX_VALUE, getUserConfig().migrateOffsetDate, getUserConfig().migrateOffsetUserId, getUserConfig().migrateOffsetChatId, getUserConfig().migrateOffsetChannelId, getUserConfig().migrateOffsetAccess);
                        }
                        offsetId = -1;
                    }
                    StringBuilder dids = new StringBuilder(dialogsRes.dialogs.size() * 12);
                    LongSparseArray<TLRPC.Dialog> dialogHashMap = new LongSparseArray<>();
                    for (int a = 0; a < dialogsRes.dialogs.size(); a++) {
                        TLRPC.Dialog dialog = dialogsRes.dialogs.get(a);
                        DialogObject.initDialog(dialog);
                        if (dids.length() > 0) {
                            dids.append(",");
                        }
                        dids.append(dialog.id);
                        dialogHashMap.put(dialog.id, dialog);
                    }
                    SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT did, folder_id FROM dialogs WHERE did IN (%s)", dids.toString()));
                    while (cursor.next()) {
                        long did = cursor.longValue(0);
                        int folder_id = cursor.intValue(1);
                        TLRPC.Dialog dialog = dialogHashMap.get(did);
                        if (dialog != null) {
                            if (dialog.folder_id != folder_id) {
                                continue;
                            }
                            dialogsRes.dialogs.remove(dialog);
                            for (int a = 0; a < dialogsRes.messages.size(); a++) {
                                TLRPC.Message message = dialogsRes.messages.get(a);
                                if (MessageObject.getDialogId(message) != did) {
                                    continue;
                                }
                                dialogsRes.messages.remove(a);
                                a--;
                                if (message.id == dialog.top_message) {
                                    dialog.top_message = 0;
                                    break;
                                }
                            }
                        }
                        dialogHashMap.remove(did);
                    }
                    cursor.dispose();
                    if (BuildVars.LOGS_ENABLED) {
                        FileLog.d("migrate found missing dialogs " + dialogsRes.dialogs.size());
                    }
                    cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT min(date) FROM dialogs WHERE date != 0 AND did >> 32 NOT IN (536870912, 1073741824)");
                    if (cursor.next()) {
                        int date = Math.max(1441062000, cursor.intValue(0));
                        for (int a = 0; a < dialogsRes.messages.size(); a++) {
                            TLRPC.Message message = dialogsRes.messages.get(a);
                            if (message.date < date) {
                                if (offset != -1) {
                                    for (int i = 0; i < 2; i++) {
                                        getUserConfig().setDialogsLoadOffset(i, getUserConfig().migrateOffsetId, getUserConfig().migrateOffsetDate, getUserConfig().migrateOffsetUserId, getUserConfig().migrateOffsetChatId, getUserConfig().migrateOffsetChannelId, getUserConfig().migrateOffsetAccess);
                                    }
                                    offsetId = -1;
                                    if (BuildVars.LOGS_ENABLED) {
                                        FileLog.d("migrate stop due to reached loaded dialogs " + LocaleController.getInstance().formatterStats.format((long) date * 1000));
                                    }
                                }
                                dialogsRes.messages.remove(a);
                                a--;
                                long did = MessageObject.getDialogId(message);
                                TLRPC.Dialog dialog = dialogHashMap.get(did);
                                dialogHashMap.remove(did);
                                if (dialog != null) {
                                    dialogsRes.dialogs.remove(dialog);
                                }
                            }
                        }
                        if (lastMessage != null && lastMessage.date < date && offset != -1) {
                            for (int i = 0; i < 2; i++) {
                                getUserConfig().setDialogsLoadOffset(i, getUserConfig().migrateOffsetId, getUserConfig().migrateOffsetDate, getUserConfig().migrateOffsetUserId, getUserConfig().migrateOffsetChatId, getUserConfig().migrateOffsetChannelId, getUserConfig().migrateOffsetAccess);
                            }
                            offsetId = -1;
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("migrate stop due to reached loaded dialogs " + LocaleController.getInstance().formatterStats.format((long) date * 1000));
                            }
                        }
                    }
                    cursor.dispose();
                    getUserConfig().migrateOffsetDate = lastMessage.date;
                    if (lastMessage.peer_id.channel_id != 0) {
                        getUserConfig().migrateOffsetChannelId = lastMessage.peer_id.channel_id;
                        getUserConfig().migrateOffsetChatId = 0;
                        getUserConfig().migrateOffsetUserId = 0;
                        for (int a = 0; a < dialogsRes.chats.size(); a++) {
                            TLRPC.Chat chat = dialogsRes.chats.get(a);
                            if (chat.id == getUserConfig().migrateOffsetChannelId) {
                                getUserConfig().migrateOffsetAccess = chat.access_hash;
                                break;
                            }
                        }
                    } else if (lastMessage.peer_id.chat_id != 0) {
                        getUserConfig().migrateOffsetChatId = lastMessage.peer_id.chat_id;
                        getUserConfig().migrateOffsetChannelId = 0;
                        getUserConfig().migrateOffsetUserId = 0;
                        for (int a = 0; a < dialogsRes.chats.size(); a++) {
                            TLRPC.Chat chat = dialogsRes.chats.get(a);
                            if (chat.id == getUserConfig().migrateOffsetChatId) {
                                getUserConfig().migrateOffsetAccess = chat.access_hash;
                                break;
                            }
                        }
                    } else if (lastMessage.peer_id.user_id != 0) {
                        getUserConfig().migrateOffsetUserId = lastMessage.peer_id.user_id;
                        getUserConfig().migrateOffsetChatId = 0;
                        getUserConfig().migrateOffsetChannelId = 0;
                        for (int a = 0; a < dialogsRes.users.size(); a++) {
                            TLRPC.User user = dialogsRes.users.get(a);
                            if (user.id == getUserConfig().migrateOffsetUserId) {
                                getUserConfig().migrateOffsetAccess = user.access_hash;
                                break;
                            }
                        }
                    }
                    processLoadedDialogs(dialogsRes, null, 0, offsetId, 0, 0, false, true, false);
                } catch (Exception e) {
                    FileLog.e(e);
                    AndroidUtilities.runOnUIThread(() -> migratingDialogs = false);
                }
            });
        } else {
            AndroidUtilities.runOnUIThread(() -> migratingDialogs = false);
        }
    });
}
Also used : LongSparseArray(androidx.collection.LongSparseArray) TLRPC(org.telegram.tgnet.TLRPC) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) SQLiteException(org.telegram.SQLite.SQLiteException) AlertDialog(org.telegram.ui.ActionBar.AlertDialog)

Example 5 with SQLiteCursor

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

the class MessagesController method checkUnreadReactions.

public void checkUnreadReactions(long dialogId, SparseBooleanArray unreadReactions) {
    getMessagesStorage().getStorageQueue().postRunnable(() -> {
        boolean needReload = false;
        boolean changed = false;
        ArrayList<Integer> newUnreadMessages = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < unreadReactions.size(); i++) {
            int messageId = unreadReactions.keyAt(i);
            if (stringBuilder.length() > 0) {
                stringBuilder.append(", ");
            }
            stringBuilder.append(messageId);
        }
        SparseBooleanArray reactionsMentionsMessageIds = new SparseBooleanArray();
        try {
            SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT message_id, state FROM reaction_mentions WHERE message_id IN (%s) AND dialog_id = %d", stringBuilder.toString(), dialogId));
            while (cursor.next()) {
                int messageId = cursor.intValue(0);
                boolean hasUnreadReactions = cursor.intValue(1) == 1;
                reactionsMentionsMessageIds.put(messageId, hasUnreadReactions);
            }
            cursor.dispose();
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
        int newUnreadCount = 0;
        for (int i = 0; i < unreadReactions.size(); i++) {
            int messageId = unreadReactions.keyAt(i);
            boolean hasUnreadReaction = unreadReactions.valueAt(i);
            if (reactionsMentionsMessageIds.indexOfKey(messageId) >= 0) {
                if (reactionsMentionsMessageIds.get(messageId) != hasUnreadReaction) {
                    newUnreadCount += hasUnreadReaction ? 1 : -1;
                    changed = true;
                }
            } else {
                needReload = true;
            }
            if (hasUnreadReaction) {
                newUnreadMessages.add(messageId);
            }
            SQLitePreparedStatement state = null;
            try {
                state = getMessagesStorage().getDatabase().executeFast("REPLACE INTO reaction_mentions VALUES(?, ?, ?)");
                state.requery();
                state.bindInteger(1, messageId);
                state.bindInteger(2, hasUnreadReaction ? 1 : 0);
                state.bindLong(3, dialogId);
                state.step();
                state.dispose();
            } catch (SQLiteException e) {
                e.printStackTrace();
            }
        }
        if (needReload) {
            TLRPC.TL_messages_getUnreadReactions req = new TLRPC.TL_messages_getUnreadReactions();
            req.limit = 1;
            req.peer = getInputPeer(dialogId);
            ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
                if (response != null) {
                    TLRPC.messages_Messages messages = (TLRPC.messages_Messages) response;
                    int count = Math.max(messages.count, messages.messages.size());
                    AndroidUtilities.runOnUIThread(() -> {
                        TLRPC.Dialog dialog = dialogs_dict.get(dialogId);
                        if (dialog == null) {
                            getMessagesStorage().updateDialogUnreadReactions(dialogId, count, false);
                            return;
                        }
                        dialog.unread_reactions_count = count;
                        getMessagesStorage().updateUnreadReactionsCount(dialogId, count);
                        getNotificationCenter().postNotificationName(NotificationCenter.dialogsUnreadReactionsCounterChanged, dialogId, count, newUnreadMessages);
                    });
                }
            });
        } else if (changed) {
            int finalNewUnreadCount = newUnreadCount;
            AndroidUtilities.runOnUIThread(() -> {
                TLRPC.Dialog dialog = dialogs_dict.get(dialogId);
                if (dialog == null) {
                    getMessagesStorage().updateDialogUnreadReactions(dialogId, finalNewUnreadCount, true);
                    return;
                }
                dialog.unread_reactions_count += finalNewUnreadCount;
                if (dialog.unread_reactions_count < 0) {
                    dialog.unread_reactions_count = 0;
                }
                getMessagesStorage().updateUnreadReactionsCount(dialogId, dialog.unread_reactions_count);
                getNotificationCenter().postNotificationName(NotificationCenter.dialogsUnreadReactionsCounterChanged, dialogId, dialog.unread_reactions_count, newUnreadMessages);
            });
        }
    });
}
Also used : ArrayList(java.util.ArrayList) SQLiteException(org.telegram.SQLite.SQLiteException) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) SparseBooleanArray(android.util.SparseBooleanArray)

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