Search in sources :

Example 21 with SQLiteCursor

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

the class MediaDataController method getMediaCounts.

public void getMediaCounts(long dialogId, int classGuid) {
    getMessagesStorage().getStorageQueue().postRunnable(() -> {
        try {
            int[] counts = new int[] { -1, -1, -1, -1, -1, -1, -1, -1 };
            int[] countsFinal = new int[] { -1, -1, -1, -1, -1, -1, -1, -1 };
            int[] old = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT type, count, old FROM media_counts_v2 WHERE uid = %d", dialogId));
            while (cursor.next()) {
                int type = cursor.intValue(0);
                if (type >= 0 && type < MEDIA_TYPES_COUNT) {
                    countsFinal[type] = counts[type] = cursor.intValue(1);
                    old[type] = cursor.intValue(2);
                }
            }
            cursor.dispose();
            if (DialogObject.isEncryptedDialog(dialogId)) {
                for (int a = 0; a < counts.length; a++) {
                    if (counts[a] == -1) {
                        cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM media_v4 WHERE uid = %d AND type = %d LIMIT 1", dialogId, a));
                        if (cursor.next()) {
                            counts[a] = cursor.intValue(0);
                        } else {
                            counts[a] = 0;
                        }
                        cursor.dispose();
                        putMediaCountDatabase(dialogId, a, counts[a]);
                    }
                }
                AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.mediaCountsDidLoad, dialogId, counts));
            } else {
                boolean missing = false;
                TLRPC.TL_messages_getSearchCounters req = new TLRPC.TL_messages_getSearchCounters();
                req.peer = getMessagesController().getInputPeer(dialogId);
                for (int a = 0; a < counts.length; a++) {
                    if (req.peer == null) {
                        counts[a] = 0;
                        continue;
                    }
                    if (counts[a] == -1 || old[a] == 1) {
                        if (a == MEDIA_PHOTOVIDEO) {
                            req.filters.add(new TLRPC.TL_inputMessagesFilterPhotoVideo());
                        } else if (a == MEDIA_FILE) {
                            req.filters.add(new TLRPC.TL_inputMessagesFilterDocument());
                        } else if (a == MEDIA_AUDIO) {
                            req.filters.add(new TLRPC.TL_inputMessagesFilterRoundVoice());
                        } else if (a == MEDIA_URL) {
                            req.filters.add(new TLRPC.TL_inputMessagesFilterUrl());
                        } else if (a == MEDIA_MUSIC) {
                            req.filters.add(new TLRPC.TL_inputMessagesFilterMusic());
                        } else if (a == MEDIA_PHOTOS_ONLY) {
                            req.filters.add(new TLRPC.TL_inputMessagesFilterPhotos());
                        } else if (a == MEDIA_VIDEOS_ONLY) {
                            req.filters.add(new TLRPC.TL_inputMessagesFilterVideo());
                        } else {
                            req.filters.add(new TLRPC.TL_inputMessagesFilterGif());
                        }
                        if (counts[a] == -1) {
                            missing = true;
                        } else if (old[a] == 1) {
                            counts[a] = -1;
                        }
                    }
                }
                if (!req.filters.isEmpty()) {
                    int reqId = getConnectionsManager().sendRequest(req, (response, error) -> {
                        for (int i = 0; i < counts.length; i++) {
                            if (counts[i] < 0) {
                                counts[i] = 0;
                            }
                        }
                        if (response != null) {
                            TLRPC.Vector res = (TLRPC.Vector) response;
                            for (int a = 0, N = res.objects.size(); a < N; a++) {
                                TLRPC.TL_messages_searchCounter searchCounter = (TLRPC.TL_messages_searchCounter) res.objects.get(a);
                                int type;
                                if (searchCounter.filter instanceof TLRPC.TL_inputMessagesFilterPhotoVideo) {
                                    type = MEDIA_PHOTOVIDEO;
                                } else if (searchCounter.filter instanceof TLRPC.TL_inputMessagesFilterDocument) {
                                    type = MEDIA_FILE;
                                } else if (searchCounter.filter instanceof TLRPC.TL_inputMessagesFilterRoundVoice) {
                                    type = MEDIA_AUDIO;
                                } else if (searchCounter.filter instanceof TLRPC.TL_inputMessagesFilterUrl) {
                                    type = MEDIA_URL;
                                } else if (searchCounter.filter instanceof TLRPC.TL_inputMessagesFilterMusic) {
                                    type = MEDIA_MUSIC;
                                } else if (searchCounter.filter instanceof TLRPC.TL_inputMessagesFilterGif) {
                                    type = MEDIA_GIF;
                                } else if (searchCounter.filter instanceof TLRPC.TL_inputMessagesFilterPhotos) {
                                    type = MEDIA_PHOTOS_ONLY;
                                } else if (searchCounter.filter instanceof TLRPC.TL_inputMessagesFilterVideo) {
                                    type = MEDIA_VIDEOS_ONLY;
                                } else {
                                    continue;
                                }
                                counts[type] = searchCounter.count;
                                putMediaCountDatabase(dialogId, type, counts[type]);
                            }
                        }
                        AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.mediaCountsDidLoad, dialogId, counts));
                    });
                    getConnectionsManager().bindRequestToGuid(reqId, classGuid);
                }
                if (!missing) {
                    AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.mediaCountsDidLoad, dialogId, countsFinal));
                }
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}
Also used : SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) Paint(android.graphics.Paint) SQLiteException(org.telegram.SQLite.SQLiteException)

Example 22 with SQLiteCursor

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

the class MediaDataController method loadHints.

public void loadHints(boolean cache) {
    if (loading || !getUserConfig().suggestContacts) {
        return;
    }
    if (cache) {
        if (loaded) {
            return;
        }
        loading = true;
        getMessagesStorage().getStorageQueue().postRunnable(() -> {
            ArrayList<TLRPC.TL_topPeer> hintsNew = new ArrayList<>();
            ArrayList<TLRPC.TL_topPeer> inlineBotsNew = new ArrayList<>();
            ArrayList<TLRPC.User> users = new ArrayList<>();
            ArrayList<TLRPC.Chat> chats = new ArrayList<>();
            long selfUserId = getUserConfig().getClientUserId();
            try {
                ArrayList<Long> usersToLoad = new ArrayList<>();
                ArrayList<Long> chatsToLoad = new ArrayList<>();
                SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT did, type, rating FROM chat_hints WHERE 1 ORDER BY rating DESC");
                while (cursor.next()) {
                    long did = cursor.longValue(0);
                    if (did == selfUserId) {
                        continue;
                    }
                    int type = cursor.intValue(1);
                    TLRPC.TL_topPeer peer = new TLRPC.TL_topPeer();
                    peer.rating = cursor.doubleValue(2);
                    if (did > 0) {
                        peer.peer = new TLRPC.TL_peerUser();
                        peer.peer.user_id = did;
                        usersToLoad.add(did);
                    } else {
                        peer.peer = new TLRPC.TL_peerChat();
                        peer.peer.chat_id = -did;
                        chatsToLoad.add(-did);
                    }
                    if (type == 0) {
                        hintsNew.add(peer);
                    } else if (type == 1) {
                        inlineBotsNew.add(peer);
                    }
                }
                cursor.dispose();
                if (!usersToLoad.isEmpty()) {
                    getMessagesStorage().getUsersInternal(TextUtils.join(",", usersToLoad), users);
                }
                if (!chatsToLoad.isEmpty()) {
                    getMessagesStorage().getChatsInternal(TextUtils.join(",", chatsToLoad), chats);
                }
                AndroidUtilities.runOnUIThread(() -> {
                    getMessagesController().putUsers(users, true);
                    getMessagesController().putChats(chats, true);
                    loading = false;
                    loaded = true;
                    hints = hintsNew;
                    inlineBots = inlineBotsNew;
                    buildShortcuts();
                    getNotificationCenter().postNotificationName(NotificationCenter.reloadHints);
                    getNotificationCenter().postNotificationName(NotificationCenter.reloadInlineHints);
                    if (Math.abs(getUserConfig().lastHintsSyncTime - (int) (System.currentTimeMillis() / 1000)) >= 24 * 60 * 60) {
                        loadHints(false);
                    }
                });
            } catch (Exception e) {
                FileLog.e(e);
            }
        });
        loaded = true;
    } else {
        loading = true;
        TLRPC.TL_contacts_getTopPeers req = new TLRPC.TL_contacts_getTopPeers();
        req.hash = 0;
        req.bots_pm = false;
        req.correspondents = true;
        req.groups = false;
        req.channels = false;
        req.bots_inline = true;
        req.offset = 0;
        req.limit = 20;
        getConnectionsManager().sendRequest(req, (response, error) -> {
            if (response instanceof TLRPC.TL_contacts_topPeers) {
                AndroidUtilities.runOnUIThread(() -> {
                    TLRPC.TL_contacts_topPeers topPeers = (TLRPC.TL_contacts_topPeers) response;
                    getMessagesController().putUsers(topPeers.users, false);
                    getMessagesController().putChats(topPeers.chats, false);
                    for (int a = 0; a < topPeers.categories.size(); a++) {
                        TLRPC.TL_topPeerCategoryPeers category = topPeers.categories.get(a);
                        if (category.category instanceof TLRPC.TL_topPeerCategoryBotsInline) {
                            inlineBots = category.peers;
                            getUserConfig().botRatingLoadTime = (int) (System.currentTimeMillis() / 1000);
                        } else {
                            hints = category.peers;
                            long selfUserId = getUserConfig().getClientUserId();
                            for (int b = 0; b < hints.size(); b++) {
                                TLRPC.TL_topPeer topPeer = hints.get(b);
                                if (topPeer.peer.user_id == selfUserId) {
                                    hints.remove(b);
                                    break;
                                }
                            }
                            getUserConfig().ratingLoadTime = (int) (System.currentTimeMillis() / 1000);
                        }
                    }
                    getUserConfig().saveConfig(false);
                    buildShortcuts();
                    getNotificationCenter().postNotificationName(NotificationCenter.reloadHints);
                    getNotificationCenter().postNotificationName(NotificationCenter.reloadInlineHints);
                    getMessagesStorage().getStorageQueue().postRunnable(() -> {
                        try {
                            getMessagesStorage().getDatabase().executeFast("DELETE FROM chat_hints WHERE 1").stepThis().dispose();
                            getMessagesStorage().getDatabase().beginTransaction();
                            getMessagesStorage().putUsersAndChats(topPeers.users, topPeers.chats, false, false);
                            SQLitePreparedStatement state = getMessagesStorage().getDatabase().executeFast("REPLACE INTO chat_hints VALUES(?, ?, ?, ?)");
                            for (int a = 0; a < topPeers.categories.size(); a++) {
                                int type;
                                TLRPC.TL_topPeerCategoryPeers category = topPeers.categories.get(a);
                                if (category.category instanceof TLRPC.TL_topPeerCategoryBotsInline) {
                                    type = 1;
                                } else {
                                    type = 0;
                                }
                                for (int b = 0; b < category.peers.size(); b++) {
                                    TLRPC.TL_topPeer peer = category.peers.get(b);
                                    state.requery();
                                    state.bindLong(1, MessageObject.getPeerId(peer.peer));
                                    state.bindInteger(2, type);
                                    state.bindDouble(3, peer.rating);
                                    state.bindInteger(4, 0);
                                    state.step();
                                }
                            }
                            state.dispose();
                            getMessagesStorage().getDatabase().commitTransaction();
                            AndroidUtilities.runOnUIThread(() -> {
                                getUserConfig().suggestContacts = true;
                                getUserConfig().lastHintsSyncTime = (int) (System.currentTimeMillis() / 1000);
                                getUserConfig().saveConfig(false);
                            });
                        } catch (Exception e) {
                            FileLog.e(e);
                        }
                    });
                });
            } else if (response instanceof TLRPC.TL_contacts_topPeersDisabled) {
                AndroidUtilities.runOnUIThread(() -> {
                    getUserConfig().suggestContacts = false;
                    getUserConfig().lastHintsSyncTime = (int) (System.currentTimeMillis() / 1000);
                    getUserConfig().saveConfig(false);
                    clearTopPeers();
                });
            }
        });
    }
}
Also used : ArrayList(java.util.ArrayList) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) SQLitePreparedStatement(org.telegram.SQLite.SQLitePreparedStatement) Paint(android.graphics.Paint) SQLiteException(org.telegram.SQLite.SQLiteException)

Example 23 with SQLiteCursor

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

the class MessagesStorage method getContacts.

public void getContacts() {
    storageQueue.postRunnable(() -> {
        ArrayList<TLRPC.TL_contact> contacts = new ArrayList<>();
        ArrayList<TLRPC.User> users = new ArrayList<>();
        try {
            SQLiteCursor cursor = database.queryFinalized("SELECT * FROM contacts WHERE 1");
            StringBuilder uids = new StringBuilder();
            while (cursor.next()) {
                long userId = cursor.intValue(0);
                TLRPC.TL_contact contact = new TLRPC.TL_contact();
                contact.user_id = userId;
                contact.mutual = cursor.intValue(1) == 1;
                if (uids.length() != 0) {
                    uids.append(",");
                }
                contacts.add(contact);
                uids.append(contact.user_id);
            }
            cursor.dispose();
            if (uids.length() != 0) {
                getUsersInternal(uids.toString(), users);
            }
        } catch (Exception e) {
            contacts.clear();
            users.clear();
            FileLog.e(e);
        }
        getContactsController().processLoadedContacts(contacts, users, 1);
    });
}
Also used : SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) SQLiteCursor(org.telegram.SQLite.SQLiteCursor) TLRPC(org.telegram.tgnet.TLRPC) SQLiteException(org.telegram.SQLite.SQLiteException)

Example 24 with SQLiteCursor

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

the class MessagesStorage method updateFiltersReadCounter.

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

Example 25 with SQLiteCursor

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

the class MessagesStorage method updateMessagePollResults.

public void updateMessagePollResults(long pollId, TLRPC.Poll poll, TLRPC.PollResults results) {
    storageQueue.postRunnable(() -> {
        try {
            LongSparseArray<ArrayList<Integer>> dialogs = null;
            SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, mid FROM polls_v2 WHERE id = %d", pollId));
            while (cursor.next()) {
                long dialogId = cursor.longValue(0);
                if (dialogs == null) {
                    dialogs = new LongSparseArray<>();
                }
                ArrayList<Integer> mids = dialogs.get(dialogId);
                if (mids == null) {
                    mids = new ArrayList<>();
                    dialogs.put(dialogId, mids);
                }
                mids.add(cursor.intValue(1));
            }
            cursor.dispose();
            if (dialogs != null) {
                database.beginTransaction();
                SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET data = ? WHERE mid = ? AND uid = ?");
                for (int b = 0, N2 = dialogs.size(); b < N2; b++) {
                    long dialogId = dialogs.keyAt(b);
                    ArrayList<Integer> mids = dialogs.valueAt(b);
                    for (int a = 0, N = mids.size(); a < N; a++) {
                        Integer mid = mids.get(a);
                        cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM messages_v2 WHERE mid = %d AND uid = %d", mid, dialogId));
                        if (cursor.next()) {
                            NativeByteBuffer data = cursor.byteBufferValue(0);
                            if (data != null) {
                                TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
                                message.readAttachPath(data, getUserConfig().clientUserId);
                                data.reuse();
                                if (message.media instanceof TLRPC.TL_messageMediaPoll) {
                                    TLRPC.TL_messageMediaPoll media = (TLRPC.TL_messageMediaPoll) message.media;
                                    if (poll != null) {
                                        media.poll = poll;
                                    }
                                    if (results != null) {
                                        MessageObject.updatePollResults(media, results);
                                    }
                                    data = new NativeByteBuffer(message.getObjectSize());
                                    message.serializeToStream(data);
                                    state.requery();
                                    state.bindByteBuffer(1, data);
                                    state.bindInteger(2, mid);
                                    state.bindLong(3, dialogId);
                                    state.step();
                                    data.reuse();
                                }
                            }
                        } else {
                            database.executeFast(String.format(Locale.US, "DELETE FROM polls_v2 WHERE mid = %d AND uid = %d", mid, dialogId)).stepThis().dispose();
                        }
                        cursor.dispose();
                    }
                }
                state.dispose();
                database.commitTransaction();
            }
        } 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)

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