Search in sources :

Example 11 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class MentionsAdapter method searchUsernameOrHashtag.

public void searchUsernameOrHashtag(String text, int position, ArrayList<MessageObject> messageObjects, boolean usernameOnly, boolean forSearch) {
    if (cancelDelayRunnable != null) {
        AndroidUtilities.cancelRunOnUIThread(cancelDelayRunnable);
        cancelDelayRunnable = null;
    }
    if (channelReqId != 0) {
        ConnectionsManager.getInstance(currentAccount).cancelRequest(channelReqId, true);
        channelReqId = 0;
    }
    if (searchGlobalRunnable != null) {
        AndroidUtilities.cancelRunOnUIThread(searchGlobalRunnable);
        searchGlobalRunnable = null;
    }
    if (TextUtils.isEmpty(text) || text.length() > MessagesController.getInstance(currentAccount).maxMessageLength) {
        searchForContextBot(null, null);
        delegate.needChangePanelVisibility(false);
        lastText = null;
        clearStickers();
        return;
    }
    int searchPostion = position;
    if (text.length() > 0) {
        searchPostion--;
    }
    lastText = null;
    lastUsernameOnly = usernameOnly;
    lastForSearch = forSearch;
    StringBuilder result = new StringBuilder();
    int foundType = -1;
    boolean searchEmoji = !usernameOnly && text != null && text.length() > 0 && text.length() <= 14;
    String originalEmoji = "";
    if (searchEmoji) {
        CharSequence emoji = originalEmoji = text;
        int length = emoji.length();
        for (int a = 0; a < length; a++) {
            char ch = emoji.charAt(a);
            char nch = a < length - 1 ? emoji.charAt(a + 1) : 0;
            if (a < length - 1 && ch == 0xD83C && nch >= 0xDFFB && nch <= 0xDFFF) {
                emoji = TextUtils.concat(emoji.subSequence(0, a), emoji.subSequence(a + 2, emoji.length()));
                length -= 2;
                a--;
            } else if (ch == 0xfe0f) {
                emoji = TextUtils.concat(emoji.subSequence(0, a), emoji.subSequence(a + 1, emoji.length()));
                length--;
                a--;
            }
        }
        lastSticker = emoji.toString().trim();
    }
    boolean isValidEmoji = searchEmoji && (Emoji.isValidEmoji(originalEmoji) || Emoji.isValidEmoji(lastSticker));
    if (isValidEmoji && parentFragment != null && (parentFragment.getCurrentChat() == null || ChatObject.canSendStickers(parentFragment.getCurrentChat()))) {
        stickersToLoad.clear();
        if (SharedConfig.suggestStickers == 2 || !isValidEmoji) {
            if (visibleByStickersSearch && SharedConfig.suggestStickers == 2) {
                visibleByStickersSearch = false;
                delegate.needChangePanelVisibility(false);
                notifyDataSetChanged();
            }
            return;
        }
        stickers = null;
        stickersMap = null;
        foundType = 4;
        if (lastReqId != 0) {
            ConnectionsManager.getInstance(currentAccount).cancelRequest(lastReqId, true);
            lastReqId = 0;
        }
        boolean serverStickersOnly = MessagesController.getInstance(currentAccount).suggestStickersApiOnly;
        delayLocalResults = false;
        if (!serverStickersOnly) {
            final ArrayList<TLRPC.Document> recentStickers = MediaDataController.getInstance(currentAccount).getRecentStickersNoCopy(MediaDataController.TYPE_IMAGE);
            final ArrayList<TLRPC.Document> favsStickers = MediaDataController.getInstance(currentAccount).getRecentStickersNoCopy(MediaDataController.TYPE_FAVE);
            int recentsAdded = 0;
            for (int a = 0, size = Math.min(20, recentStickers.size()); a < size; a++) {
                TLRPC.Document document = recentStickers.get(a);
                if (isValidSticker(document, lastSticker)) {
                    addStickerToResult(document, "recent");
                    recentsAdded++;
                    if (recentsAdded >= 5) {
                        break;
                    }
                }
            }
            for (int a = 0, size = favsStickers.size(); a < size; a++) {
                TLRPC.Document document = favsStickers.get(a);
                if (isValidSticker(document, lastSticker)) {
                    addStickerToResult(document, "fav");
                }
            }
            HashMap<String, ArrayList<TLRPC.Document>> allStickers = MediaDataController.getInstance(currentAccount).getAllStickers();
            ArrayList<TLRPC.Document> newStickers = allStickers != null ? allStickers.get(lastSticker) : null;
            if (newStickers != null && !newStickers.isEmpty()) {
                addStickersToResult(newStickers, null);
            }
            if (stickers != null) {
                Collections.sort(stickers, new Comparator<StickerResult>() {

                    private int getIndex(StickerResult result) {
                        for (int a = 0; a < favsStickers.size(); a++) {
                            if (favsStickers.get(a).id == result.sticker.id) {
                                return a + 2000000;
                            }
                        }
                        for (int a = 0; a < Math.min(20, recentStickers.size()); a++) {
                            if (recentStickers.get(a).id == result.sticker.id) {
                                return recentStickers.size() - a + 1000000;
                            }
                        }
                        return -1;
                    }

                    @Override
                    public int compare(StickerResult lhs, StickerResult rhs) {
                        boolean isAnimated1 = MessageObject.isAnimatedStickerDocument(lhs.sticker, true);
                        boolean isAnimated2 = MessageObject.isAnimatedStickerDocument(rhs.sticker, true);
                        if (isAnimated1 == isAnimated2) {
                            int idx1 = getIndex(lhs);
                            int idx2 = getIndex(rhs);
                            if (idx1 > idx2) {
                                return -1;
                            } else if (idx1 < idx2) {
                                return 1;
                            }
                            return 0;
                        } else {
                            if (isAnimated1) {
                                return -1;
                            } else {
                                return 1;
                            }
                        }
                    }
                });
            }
        }
        if (SharedConfig.suggestStickers == 0 || serverStickersOnly) {
            searchServerStickers(lastSticker, originalEmoji);
        }
        if (stickers != null && !stickers.isEmpty()) {
            if (SharedConfig.suggestStickers == 0 && stickers.size() < 5) {
                delayLocalResults = true;
                delegate.needChangePanelVisibility(false);
                visibleByStickersSearch = false;
            } else {
                checkStickerFilesExistAndDownload();
                boolean show = stickersToLoad.isEmpty();
                delegate.needChangePanelVisibility(show);
                visibleByStickersSearch = true;
            }
            notifyDataSetChanged();
        } else if (visibleByStickersSearch) {
            delegate.needChangePanelVisibility(false);
            visibleByStickersSearch = false;
        }
    } else if (!usernameOnly && needBotContext && text.charAt(0) == '@') {
        int index = text.indexOf(' ');
        int len = text.length();
        String username = null;
        String query = null;
        if (index > 0) {
            username = text.substring(1, index);
            query = text.substring(index + 1);
        } else if (text.charAt(len - 1) == 't' && text.charAt(len - 2) == 'o' && text.charAt(len - 3) == 'b') {
            username = text.substring(1);
            query = "";
        } else {
            searchForContextBot(null, null);
        }
        if (username != null && username.length() >= 1) {
            for (int a = 1; a < username.length(); a++) {
                char ch = username.charAt(a);
                if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) {
                    username = "";
                    break;
                }
            }
        } else {
            username = "";
        }
        searchForContextBot(username, query);
    } else {
        searchForContextBot(null, null);
    }
    if (foundContextBot != null) {
        return;
    }
    final MessagesController messagesController = MessagesController.getInstance(currentAccount);
    int dogPostion = -1;
    if (usernameOnly) {
        result.append(text.substring(1));
        resultStartPosition = 0;
        resultLength = result.length();
        foundType = 0;
    } else {
        for (int a = searchPostion; a >= 0; a--) {
            if (a >= text.length()) {
                continue;
            }
            char ch = text.charAt(a);
            if (a == 0 || text.charAt(a - 1) == ' ' || text.charAt(a - 1) == '\n' || ch == ':') {
                if (ch == '@') {
                    if (needUsernames || needBotContext && a == 0) {
                        if (info == null && a != 0) {
                            lastText = text;
                            lastPosition = position;
                            messages = messageObjects;
                            delegate.needChangePanelVisibility(false);
                            return;
                        }
                        dogPostion = a;
                        foundType = 0;
                        resultStartPosition = a;
                        resultLength = result.length() + 1;
                        break;
                    }
                } else if (ch == '#') {
                    if (searchAdapterHelper.loadRecentHashtags()) {
                        foundType = 1;
                        resultStartPosition = a;
                        resultLength = result.length() + 1;
                        result.insert(0, ch);
                        break;
                    } else {
                        lastText = text;
                        lastPosition = position;
                        messages = messageObjects;
                        delegate.needChangePanelVisibility(false);
                        return;
                    }
                } else if (a == 0 && botInfo != null && ch == '/') {
                    foundType = 2;
                    resultStartPosition = a;
                    resultLength = result.length() + 1;
                    break;
                } else if (ch == ':' && result.length() > 0) {
                    boolean isNextPunctiationChar = punctuationsChars.indexOf(result.charAt(0)) >= 0;
                    if (!isNextPunctiationChar || result.length() > 1) {
                        foundType = 3;
                        resultStartPosition = a;
                        resultLength = result.length() + 1;
                        break;
                    }
                }
            }
            result.insert(0, ch);
        }
    }
    if (foundType == -1) {
        delegate.needChangePanelVisibility(false);
        return;
    }
    if (foundType == 0) {
        final ArrayList<Long> users = new ArrayList<>();
        for (int a = 0; a < Math.min(100, messageObjects.size()); a++) {
            long from_id = messageObjects.get(a).getFromChatId();
            if (from_id > 0 && !users.contains(from_id)) {
                users.add(from_id);
            }
        }
        final String usernameString = result.toString().toLowerCase();
        boolean hasSpace = usernameString.indexOf(' ') >= 0;
        ArrayList<TLObject> newResult = new ArrayList<>();
        final LongSparseArray<TLRPC.User> newResultsHashMap = new LongSparseArray<>();
        final LongSparseArray<TLObject> newMap = new LongSparseArray<>();
        ArrayList<TLRPC.TL_topPeer> inlineBots = MediaDataController.getInstance(currentAccount).inlineBots;
        if (!usernameOnly && needBotContext && dogPostion == 0 && !inlineBots.isEmpty()) {
            int count = 0;
            for (int a = 0; a < inlineBots.size(); a++) {
                TLRPC.User user = messagesController.getUser(inlineBots.get(a).peer.user_id);
                if (user == null) {
                    continue;
                }
                if (!TextUtils.isEmpty(user.username) && (usernameString.length() == 0 || user.username.toLowerCase().startsWith(usernameString))) {
                    newResult.add(user);
                    newResultsHashMap.put(user.id, user);
                    newMap.put(user.id, user);
                    count++;
                }
                if (count == 5) {
                    break;
                }
            }
        }
        final TLRPC.Chat chat;
        int threadId;
        if (parentFragment != null) {
            chat = parentFragment.getCurrentChat();
            threadId = parentFragment.getThreadId();
        } else if (info != null) {
            chat = messagesController.getChat(info.id);
            threadId = 0;
        } else {
            chat = null;
            threadId = 0;
        }
        if (chat != null && info != null && info.participants != null && (!ChatObject.isChannel(chat) || chat.megagroup)) {
            for (int a = (forSearch ? -1 : 0); a < info.participants.participants.size(); a++) {
                String username;
                String firstName;
                String lastName;
                TLObject object;
                long id;
                if (a == -1) {
                    if (usernameString.length() == 0) {
                        newResult.add(chat);
                        continue;
                    }
                    firstName = chat.title;
                    lastName = null;
                    username = chat.username;
                    object = chat;
                    id = -chat.id;
                } else {
                    TLRPC.ChatParticipant chatParticipant = info.participants.participants.get(a);
                    TLRPC.User user = messagesController.getUser(chatParticipant.user_id);
                    if (user == null || !usernameOnly && UserObject.isUserSelf(user) || newResultsHashMap.indexOfKey(user.id) >= 0) {
                        continue;
                    }
                    if (usernameString.length() == 0) {
                        if (!user.deleted) {
                            newResult.add(user);
                            continue;
                        }
                    }
                    firstName = user.first_name;
                    lastName = user.last_name;
                    username = user.username;
                    object = user;
                    id = user.id;
                }
                if (!TextUtils.isEmpty(username) && username.toLowerCase().startsWith(usernameString) || !TextUtils.isEmpty(firstName) && firstName.toLowerCase().startsWith(usernameString) || !TextUtils.isEmpty(lastName) && lastName.toLowerCase().startsWith(usernameString) || hasSpace && ContactsController.formatName(firstName, lastName).toLowerCase().startsWith(usernameString)) {
                    newResult.add(object);
                    newMap.put(id, object);
                }
            }
        }
        Collections.sort(newResult, new Comparator<TLObject>() {

            private long getId(TLObject object) {
                if (object instanceof TLRPC.User) {
                    return ((TLRPC.User) object).id;
                } else {
                    return -((TLRPC.Chat) object).id;
                }
            }

            @Override
            public int compare(TLObject lhs, TLObject rhs) {
                long id1 = getId(lhs);
                long id2 = getId(rhs);
                if (newMap.indexOfKey(id1) >= 0 && newMap.indexOfKey(id2) >= 0) {
                    return 0;
                } else if (newMap.indexOfKey(id1) >= 0) {
                    return -1;
                } else if (newMap.indexOfKey(id2) >= 0) {
                    return 1;
                }
                int lhsNum = users.indexOf(id1);
                int rhsNum = users.indexOf(id2);
                if (lhsNum != -1 && rhsNum != -1) {
                    return lhsNum < rhsNum ? -1 : (lhsNum == rhsNum ? 0 : 1);
                } else if (lhsNum != -1 && rhsNum == -1) {
                    return -1;
                } else if (lhsNum == -1 && rhsNum != -1) {
                    return 1;
                }
                return 0;
            }
        });
        searchResultHashtags = null;
        stickers = null;
        searchResultCommands = null;
        searchResultCommandsHelp = null;
        searchResultCommandsUsers = null;
        searchResultSuggestions = null;
        if (chat != null && chat.megagroup && usernameString.length() > 0) {
            if (newResult.size() < 5) {
                AndroidUtilities.runOnUIThread(cancelDelayRunnable = () -> {
                    cancelDelayRunnable = null;
                    showUsersResult(newResult, newMap, true);
                }, 1000);
            } else {
                showUsersResult(newResult, newMap, true);
            }
            AndroidUtilities.runOnUIThread(searchGlobalRunnable = new Runnable() {

                @Override
                public void run() {
                    if (searchGlobalRunnable != this) {
                        return;
                    }
                    TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants();
                    req.channel = MessagesController.getInputChannel(chat);
                    req.limit = 20;
                    req.offset = 0;
                    TLRPC.TL_channelParticipantsMentions channelParticipantsMentions = new TLRPC.TL_channelParticipantsMentions();
                    channelParticipantsMentions.flags |= 1;
                    channelParticipantsMentions.q = usernameString;
                    if (threadId != 0) {
                        channelParticipantsMentions.flags |= 2;
                        channelParticipantsMentions.top_msg_id = threadId;
                    }
                    req.filter = channelParticipantsMentions;
                    final int currentReqId = ++channelLastReqId;
                    channelReqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                        if (channelReqId != 0 && currentReqId == channelLastReqId && searchResultUsernamesMap != null && searchResultUsernames != null) {
                            showUsersResult(newResult, newMap, false);
                            if (error == null) {
                                TLRPC.TL_channels_channelParticipants res = (TLRPC.TL_channels_channelParticipants) response;
                                messagesController.putUsers(res.users, false);
                                messagesController.putChats(res.chats, false);
                                boolean hasResults = !searchResultUsernames.isEmpty();
                                if (!res.participants.isEmpty()) {
                                    long currentUserId = UserConfig.getInstance(currentAccount).getClientUserId();
                                    for (int a = 0; a < res.participants.size(); a++) {
                                        TLRPC.ChannelParticipant participant = res.participants.get(a);
                                        long peerId = MessageObject.getPeerId(participant.peer);
                                        if (searchResultUsernamesMap.indexOfKey(peerId) >= 0 || !isSearchingMentions && peerId == currentUserId) {
                                            continue;
                                        }
                                        if (peerId >= 0) {
                                            TLRPC.User user = messagesController.getUser(peerId);
                                            if (user == null) {
                                                return;
                                            }
                                            searchResultUsernames.add(user);
                                        } else {
                                            TLRPC.Chat chat = messagesController.getChat(-peerId);
                                            if (chat == null) {
                                                return;
                                            }
                                            searchResultUsernames.add(chat);
                                        }
                                    }
                                }
                            }
                            notifyDataSetChanged();
                            delegate.needChangePanelVisibility(!searchResultUsernames.isEmpty());
                        }
                        channelReqId = 0;
                    }));
                }
            }, 200);
        } else {
            showUsersResult(newResult, newMap, true);
        }
    } else if (foundType == 1) {
        ArrayList<String> newResult = new ArrayList<>();
        String hashtagString = result.toString().toLowerCase();
        ArrayList<SearchAdapterHelper.HashtagObject> hashtags = searchAdapterHelper.getHashtags();
        for (int a = 0; a < hashtags.size(); a++) {
            SearchAdapterHelper.HashtagObject hashtagObject = hashtags.get(a);
            if (hashtagObject != null && hashtagObject.hashtag != null && hashtagObject.hashtag.startsWith(hashtagString)) {
                newResult.add(hashtagObject.hashtag);
            }
        }
        searchResultHashtags = newResult;
        stickers = null;
        searchResultUsernames = null;
        searchResultUsernamesMap = null;
        searchResultCommands = null;
        searchResultCommandsHelp = null;
        searchResultCommandsUsers = null;
        searchResultSuggestions = null;
        notifyDataSetChanged();
        delegate.needChangePanelVisibility(!newResult.isEmpty());
    } else if (foundType == 2) {
        ArrayList<String> newResult = new ArrayList<>();
        ArrayList<String> newResultHelp = new ArrayList<>();
        ArrayList<TLRPC.User> newResultUsers = new ArrayList<>();
        String command = result.toString().toLowerCase();
        for (int b = 0; b < botInfo.size(); b++) {
            TLRPC.BotInfo info = botInfo.valueAt(b);
            for (int a = 0; a < info.commands.size(); a++) {
                TLRPC.TL_botCommand botCommand = info.commands.get(a);
                if (botCommand != null && botCommand.command != null && botCommand.command.startsWith(command)) {
                    newResult.add("/" + botCommand.command);
                    newResultHelp.add(botCommand.description);
                    newResultUsers.add(messagesController.getUser(info.user_id));
                }
            }
        }
        searchResultHashtags = null;
        stickers = null;
        searchResultUsernames = null;
        searchResultUsernamesMap = null;
        searchResultSuggestions = null;
        searchResultCommands = newResult;
        searchResultCommandsHelp = newResultHelp;
        searchResultCommandsUsers = newResultUsers;
        notifyDataSetChanged();
        delegate.needChangePanelVisibility(!newResult.isEmpty());
    } else if (foundType == 3) {
        String[] newLanguage = AndroidUtilities.getCurrentKeyboardLanguage();
        if (!Arrays.equals(newLanguage, lastSearchKeyboardLanguage)) {
            MediaDataController.getInstance(currentAccount).fetchNewEmojiKeywords(newLanguage);
        }
        lastSearchKeyboardLanguage = newLanguage;
        MediaDataController.getInstance(currentAccount).getEmojiSuggestions(lastSearchKeyboardLanguage, result.toString(), false, (param, alias) -> {
            searchResultSuggestions = param;
            searchResultHashtags = null;
            stickers = null;
            searchResultUsernames = null;
            searchResultUsernamesMap = null;
            searchResultCommands = null;
            searchResultCommandsHelp = null;
            searchResultCommandsUsers = null;
            notifyDataSetChanged();
            delegate.needChangePanelVisibility(searchResultSuggestions != null && !searchResultSuggestions.isEmpty());
        });
    } else if (foundType == 4) {
        searchResultHashtags = null;
        searchResultUsernames = null;
        searchResultUsernamesMap = null;
        searchResultSuggestions = null;
        searchResultCommands = null;
        searchResultCommandsHelp = null;
        searchResultCommandsUsers = null;
    }
}
Also used : Arrays(java.util.Arrays) PackageManager(android.content.pm.PackageManager) AndroidUtilities(org.telegram.messenger.AndroidUtilities) Manifest(android.Manifest) View(android.view.View) Emoji(org.telegram.messenger.Emoji) RecyclerView(androidx.recyclerview.widget.RecyclerView) ImageLocation(org.telegram.messenger.ImageLocation) MentionCell(org.telegram.ui.Cells.MentionCell) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) NotificationCenter(org.telegram.messenger.NotificationCenter) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) BotSwitchCell(org.telegram.ui.Cells.BotSwitchCell) Location(android.location.Location) FileLoader(org.telegram.messenger.FileLoader) ChatActivity(org.telegram.ui.ChatActivity) Context(android.content.Context) Theme(org.telegram.ui.ActionBar.Theme) ContextLinkCell(org.telegram.ui.Cells.ContextLinkCell) RequestDelegate(org.telegram.tgnet.RequestDelegate) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) TLObject(org.telegram.tgnet.TLObject) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) MediaDataController(org.telegram.messenger.MediaDataController) Build(android.os.Build) LongSparseArray(androidx.collection.LongSparseArray) DialogObject(org.telegram.messenger.DialogObject) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) File(java.io.File) MessagesController(org.telegram.messenger.MessagesController) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ContactsController(org.telegram.messenger.ContactsController) MessagesStorage(org.telegram.messenger.MessagesStorage) StickerCell(org.telegram.ui.Cells.StickerCell) Comparator(java.util.Comparator) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Collections(java.util.Collections) EmojiView(org.telegram.ui.Components.EmojiView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LongSparseArray(androidx.collection.LongSparseArray) ArrayList(java.util.ArrayList) MessagesController(org.telegram.messenger.MessagesController) TLRPC(org.telegram.tgnet.TLRPC) TLObject(org.telegram.tgnet.TLObject)

Example 12 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class ContactsAdapter method sortOnlineContacts.

public void sortOnlineContacts() {
    if (onlineContacts == null) {
        return;
    }
    try {
        int currentTime = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
        MessagesController messagesController = MessagesController.getInstance(currentAccount);
        Collections.sort(onlineContacts, (o1, o2) -> {
            TLRPC.User user1 = messagesController.getUser(o2.user_id);
            TLRPC.User user2 = messagesController.getUser(o1.user_id);
            int status1 = 0;
            int status2 = 0;
            if (user1 != null) {
                if (user1.self) {
                    status1 = currentTime + 50000;
                } else if (user1.status != null) {
                    status1 = user1.status.expires;
                }
            }
            if (user2 != null) {
                if (user2.self) {
                    status2 = currentTime + 50000;
                } else if (user2.status != null) {
                    status2 = user2.status.expires;
                }
            }
            if (status1 > 0 && status2 > 0) {
                if (status1 > status2) {
                    return 1;
                } else if (status1 < status2) {
                    return -1;
                }
                return 0;
            } else if (status1 < 0 && status2 < 0) {
                if (status1 > status2) {
                    return 1;
                } else if (status1 < status2) {
                    return -1;
                }
                return 0;
            } else if (status1 < 0 && status2 > 0 || status1 == 0 && status2 != 0) {
                return -1;
            } else if (status2 < 0 && status1 > 0 || status2 == 0 && status1 != 0) {
                return 1;
            }
            return 0;
        });
        notifyDataSetChanged();
    } catch (Exception e) {
        FileLog.e(e);
    }
}
Also used : MessagesController(org.telegram.messenger.MessagesController) TLRPC(org.telegram.tgnet.TLRPC)

Example 13 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class GroupVoipInviteAlert method fillContacts.

private void fillContacts() {
    if (!showContacts) {
        return;
    }
    contacts.addAll(ContactsController.getInstance(currentAccount).contacts);
    long selfId = UserConfig.getInstance(currentAccount).clientUserId;
    for (int a = 0, N = contacts.size(); a < N; a++) {
        TLObject object = contacts.get(a);
        if (!(object instanceof TLRPC.TL_contact)) {
            continue;
        }
        long userId = ((TLRPC.TL_contact) object).user_id;
        if (userId == selfId || ignoredUsers.indexOfKey(userId) >= 0 || invitedUsers.contains(userId)) {
            contacts.remove(a);
            a--;
            N--;
        }
    }
    int currentTime = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
    MessagesController messagesController = MessagesController.getInstance(currentAccount);
    Collections.sort(contacts, (o1, o2) -> {
        TLRPC.User user1 = messagesController.getUser(((TLRPC.TL_contact) o2).user_id);
        TLRPC.User user2 = messagesController.getUser(((TLRPC.TL_contact) o1).user_id);
        int status1 = 0;
        int status2 = 0;
        if (user1 != null) {
            if (user1.self) {
                status1 = currentTime + 50000;
            } else if (user1.status != null) {
                status1 = user1.status.expires;
            }
        }
        if (user2 != null) {
            if (user2.self) {
                status2 = currentTime + 50000;
            } else if (user2.status != null) {
                status2 = user2.status.expires;
            }
        }
        if (status1 > 0 && status2 > 0) {
            if (status1 > status2) {
                return 1;
            } else if (status1 < status2) {
                return -1;
            }
            return 0;
        } else if (status1 < 0 && status2 < 0) {
            if (status1 > status2) {
                return 1;
            } else if (status1 < status2) {
                return -1;
            }
            return 0;
        } else if (status1 < 0 && status2 > 0 || status1 == 0 && status2 != 0) {
            return -1;
        } else if (status2 < 0 || status1 != 0) {
            return 1;
        }
        return 0;
    });
}
Also used : TLObject(org.telegram.tgnet.TLObject) MessagesController(org.telegram.messenger.MessagesController) TLRPC(org.telegram.tgnet.TLRPC)

Example 14 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class FilterCreateActivity method saveFilterToServer.

public static void saveFilterToServer(MessagesController.DialogFilter filter, int newFilterFlags, String newFilterName, ArrayList<Long> newAlwaysShow, ArrayList<Long> newNeverShow, LongSparseIntArray newPinned, boolean creatingNew, boolean atBegin, boolean hasUserChanged, boolean resetUnreadCounter, boolean progress, BaseFragment fragment, Runnable onFinish) {
    if (fragment == null || fragment.getParentActivity() == null) {
        return;
    }
    AlertDialog progressDialog;
    if (progress) {
        progressDialog = new AlertDialog(fragment.getParentActivity(), 3);
        progressDialog.setCanCacnel(false);
        progressDialog.show();
    } else {
        progressDialog = null;
    }
    TLRPC.TL_messages_updateDialogFilter req = new TLRPC.TL_messages_updateDialogFilter();
    req.id = filter.id;
    req.flags |= 1;
    req.filter = new TLRPC.TL_dialogFilter();
    req.filter.contacts = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_CONTACTS) != 0;
    req.filter.non_contacts = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS) != 0;
    req.filter.groups = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_GROUPS) != 0;
    req.filter.broadcasts = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_CHANNELS) != 0;
    req.filter.bots = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_BOTS) != 0;
    req.filter.exclude_muted = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0;
    req.filter.exclude_read = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ) != 0;
    req.filter.exclude_archived = (newFilterFlags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) != 0;
    req.filter.id = filter.id;
    req.filter.title = newFilterName;
    MessagesController messagesController = fragment.getMessagesController();
    ArrayList<Long> pinArray = new ArrayList<>();
    if (newPinned.size() != 0) {
        for (int a = 0, N = newPinned.size(); a < N; a++) {
            long key = newPinned.keyAt(a);
            if (DialogObject.isEncryptedDialog(key)) {
                continue;
            }
            pinArray.add(key);
        }
        Collections.sort(pinArray, (o1, o2) -> {
            int idx1 = newPinned.get(o1);
            int idx2 = newPinned.get(o2);
            if (idx1 > idx2) {
                return 1;
            } else if (idx1 < idx2) {
                return -1;
            }
            return 0;
        });
    }
    for (int b = 0; b < 3; b++) {
        ArrayList<Long> fromArray;
        ArrayList<TLRPC.InputPeer> toArray;
        if (b == 0) {
            fromArray = newAlwaysShow;
            toArray = req.filter.include_peers;
        } else if (b == 1) {
            fromArray = newNeverShow;
            toArray = req.filter.exclude_peers;
        } else {
            fromArray = pinArray;
            toArray = req.filter.pinned_peers;
        }
        for (int a = 0, N = fromArray.size(); a < N; a++) {
            long did = fromArray.get(a);
            if (b == 0 && newPinned.indexOfKey(did) >= 0) {
                continue;
            }
            if (!DialogObject.isEncryptedDialog(did)) {
                if (did > 0) {
                    TLRPC.User user = messagesController.getUser(did);
                    if (user != null) {
                        TLRPC.InputPeer inputPeer = new TLRPC.TL_inputPeerUser();
                        inputPeer.user_id = did;
                        inputPeer.access_hash = user.access_hash;
                        toArray.add(inputPeer);
                    }
                } else {
                    TLRPC.Chat chat = messagesController.getChat(-did);
                    if (chat != null) {
                        if (ChatObject.isChannel(chat)) {
                            TLRPC.InputPeer inputPeer = new TLRPC.TL_inputPeerChannel();
                            inputPeer.channel_id = -did;
                            inputPeer.access_hash = chat.access_hash;
                            toArray.add(inputPeer);
                        } else {
                            TLRPC.InputPeer inputPeer = new TLRPC.TL_inputPeerChat();
                            inputPeer.chat_id = -did;
                            toArray.add(inputPeer);
                        }
                    }
                }
            }
        }
    }
    fragment.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
        if (progress) {
            try {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
            } catch (Exception e) {
                FileLog.e(e);
            }
            processAddFilter(filter, newFilterFlags, newFilterName, newAlwaysShow, newNeverShow, creatingNew, atBegin, hasUserChanged, resetUnreadCounter, fragment, onFinish);
        }
    }));
    if (!progress) {
        processAddFilter(filter, newFilterFlags, newFilterName, newAlwaysShow, newNeverShow, creatingNew, atBegin, hasUserChanged, resetUnreadCounter, fragment, onFinish);
    }
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) MessagesController(org.telegram.messenger.MessagesController) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint)

Example 15 with MessagesController

use of org.telegram.messenger.MessagesController in project Telegram-FOSS by Telegram-FOSS-Team.

the class LaunchActivity method findContacts.

private List<TLRPC.TL_contact> findContacts(String userName, String userPhone, boolean allowSelf) {
    final MessagesController messagesController = MessagesController.getInstance(currentAccount);
    final ContactsController contactsController = ContactsController.getInstance(currentAccount);
    final List<TLRPC.TL_contact> contacts = new ArrayList<>(contactsController.contacts);
    final List<TLRPC.TL_contact> foundContacts = new ArrayList<>();
    if (userPhone != null) {
        userPhone = PhoneFormat.stripExceptNumbers(userPhone);
        TLRPC.TL_contact contact = contactsController.contactsByPhone.get(userPhone);
        if (contact == null) {
            String shortUserPhone = userPhone.substring(Math.max(0, userPhone.length() - 7));
            contact = contactsController.contactsByShortPhone.get(shortUserPhone);
        }
        if (contact != null) {
            final TLRPC.User user = messagesController.getUser(contact.user_id);
            if (user != null && (!user.self || allowSelf)) {
                foundContacts.add(contact);
            } else {
                // disable search by name
                userName = null;
            }
        }
    }
    if (foundContacts.isEmpty() && userName != null) {
        final String query1 = userName.trim().toLowerCase();
        if (!TextUtils.isEmpty(query1)) {
            String query2 = LocaleController.getInstance().getTranslitString(query1);
            if (query1.equals(query2) || query2.length() == 0) {
                query2 = null;
            }
            final String[] queries = new String[] { query1, query2 };
            for (int i = 0, size = contacts.size(); i < size; i++) {
                final TLRPC.TL_contact contact = contacts.get(i);
                if (contact != null) {
                    final TLRPC.User user = messagesController.getUser(contact.user_id);
                    if (user != null) {
                        if (user.self && !allowSelf) {
                            continue;
                        }
                        final String[] names = new String[3];
                        names[0] = ContactsController.formatName(user.first_name, user.last_name).toLowerCase();
                        names[1] = LocaleController.getInstance().getTranslitString(names[0]);
                        if (names[0].equals(names[1])) {
                            names[1] = null;
                        }
                        if (UserObject.isReplyUser(user)) {
                            names[2] = LocaleController.getString("RepliesTitle", R.string.RepliesTitle).toLowerCase();
                        } else if (user.self) {
                            names[2] = LocaleController.getString("SavedMessages", R.string.SavedMessages).toLowerCase();
                        }
                        boolean found = false;
                        for (String q : queries) {
                            if (q == null) {
                                continue;
                            }
                            for (int j = 0; j < names.length; j++) {
                                final String name = names[j];
                                if (name != null && (name.startsWith(q) || name.contains(" " + q))) {
                                    found = true;
                                    break;
                                }
                            }
                            if (!found && user.username != null && user.username.startsWith(q)) {
                                found = true;
                            }
                            if (found) {
                                foundContacts.add(contact);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    return foundContacts;
}
Also used : ContactsController(org.telegram.messenger.ContactsController) MessagesController(org.telegram.messenger.MessagesController) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) Paint(android.graphics.Paint) Point(android.graphics.Point)

Aggregations

MessagesController (org.telegram.messenger.MessagesController)20 TLRPC (org.telegram.tgnet.TLRPC)18 ArrayList (java.util.ArrayList)10 Paint (android.graphics.Paint)9 SuppressLint (android.annotation.SuppressLint)7 TextPaint (android.text.TextPaint)7 MessageObject (org.telegram.messenger.MessageObject)7 TLObject (org.telegram.tgnet.TLObject)6 View (android.view.View)5 ChatObject (org.telegram.messenger.ChatObject)5 UserObject (org.telegram.messenger.UserObject)5 Animator (android.animation.Animator)4 AnimatorListenerAdapter (android.animation.AnimatorListenerAdapter)4 ValueAnimator (android.animation.ValueAnimator)4 Context (android.content.Context)4 SharedPreferences (android.content.SharedPreferences)4 Build (android.os.Build)4 TextUtils (android.text.TextUtils)4 ViewGroup (android.view.ViewGroup)4 TextView (android.widget.TextView)4