use of org.telegram.tgnet.TLObject 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;
}
}
use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.
the class SearchAdapterHelper method queryServerSearch.
public void queryServerSearch(String query, boolean allowUsername, boolean allowChats, boolean allowBots, boolean allowSelf, boolean canAddGroupsOnly, long channelId, boolean phoneNumbers, int type, int searchId, Runnable onEnd) {
for (int reqId : pendingRequestIds) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(reqId, true);
}
pendingRequestIds.clear();
if (query == null) {
groupSearch.clear();
groupSearchMap.clear();
globalSearch.clear();
globalSearchMap.clear();
localServerSearch.clear();
phonesSearch.clear();
phoneSearchMap.clear();
delegate.onDataSetChanged(searchId);
return;
}
boolean hasChanged = false;
ArrayList<Pair<TLObject, RequestDelegate>> requests = new ArrayList<>();
if (query.length() > 0) {
if (channelId != 0) {
TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants();
if (type == ChatUsersActivity.TYPE_ADMIN) {
req.filter = new TLRPC.TL_channelParticipantsAdmins();
} else if (type == ChatUsersActivity.TYPE_KICKED) {
req.filter = new TLRPC.TL_channelParticipantsBanned();
} else if (type == ChatUsersActivity.TYPE_BANNED) {
req.filter = new TLRPC.TL_channelParticipantsKicked();
} else {
req.filter = new TLRPC.TL_channelParticipantsSearch();
}
req.filter.q = query;
req.limit = 50;
req.offset = 0;
req.channel = MessagesController.getInstance(currentAccount).getInputChannel(channelId);
requests.add(new Pair<>(req, (response, error) -> {
if (error == null) {
TLRPC.TL_channels_channelParticipants res = (TLRPC.TL_channels_channelParticipants) response;
lastFoundChannel = query.toLowerCase();
MessagesController.getInstance(currentAccount).putUsers(res.users, false);
MessagesController.getInstance(currentAccount).putChats(res.chats, false);
groupSearch.clear();
groupSearchMap.clear();
groupSearch.addAll(res.participants);
long currentUserId = UserConfig.getInstance(currentAccount).getClientUserId();
for (int a = 0, N = res.participants.size(); a < N; a++) {
TLRPC.ChannelParticipant participant = res.participants.get(a);
long peerId = MessageObject.getPeerId(participant.peer);
if (!allowSelf && peerId == currentUserId) {
groupSearch.remove(participant);
continue;
}
groupSearchMap.put(peerId, participant);
}
}
}));
} else {
lastFoundChannel = query.toLowerCase();
}
} else {
groupSearch.clear();
groupSearchMap.clear();
hasChanged = true;
}
if (allowUsername) {
if (query.length() > 0) {
TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search();
req.q = query;
req.limit = 20;
requests.add(new Pair<>(req, (response, error) -> {
if (delegate.canApplySearchResults(searchId)) {
if (error == null) {
TLRPC.TL_contacts_found res = (TLRPC.TL_contacts_found) response;
globalSearch.clear();
globalSearchMap.clear();
localServerSearch.clear();
MessagesController.getInstance(currentAccount).putChats(res.chats, false);
MessagesController.getInstance(currentAccount).putUsers(res.users, false);
MessagesStorage.getInstance(currentAccount).putUsersAndChats(res.users, res.chats, true, true);
LongSparseArray<TLRPC.Chat> chatsMap = new LongSparseArray<>();
LongSparseArray<TLRPC.User> usersMap = new LongSparseArray<>();
for (int a = 0; a < res.chats.size(); a++) {
TLRPC.Chat chat = res.chats.get(a);
chatsMap.put(chat.id, chat);
}
for (int a = 0; a < res.users.size(); a++) {
TLRPC.User user = res.users.get(a);
usersMap.put(user.id, user);
}
for (int b = 0; b < 2; b++) {
ArrayList<TLRPC.Peer> arrayList;
if (b == 0) {
if (!allResultsAreGlobal) {
continue;
}
arrayList = res.my_results;
} else {
arrayList = res.results;
}
for (int a = 0; a < arrayList.size(); a++) {
TLRPC.Peer peer = arrayList.get(a);
TLRPC.User user = null;
TLRPC.Chat chat = null;
if (peer.user_id != 0) {
user = usersMap.get(peer.user_id);
} else if (peer.chat_id != 0) {
chat = chatsMap.get(peer.chat_id);
} else if (peer.channel_id != 0) {
chat = chatsMap.get(peer.channel_id);
}
if (chat != null) {
if (!allowChats || canAddGroupsOnly && !ChatObject.canAddBotsToChat(chat) || !allowGlobalResults && ChatObject.isNotInChat(chat)) {
continue;
}
globalSearch.add(chat);
globalSearchMap.put(-chat.id, chat);
} else if (user != null) {
if (canAddGroupsOnly || !allowBots && user.bot || !allowSelf && user.self || !allowGlobalResults && b == 1 && !user.contact) {
continue;
}
globalSearch.add(user);
globalSearchMap.put(user.id, user);
}
}
}
if (!allResultsAreGlobal) {
for (int a = 0; a < res.my_results.size(); a++) {
TLRPC.Peer peer = res.my_results.get(a);
TLRPC.User user = null;
TLRPC.Chat chat = null;
if (peer.user_id != 0) {
user = usersMap.get(peer.user_id);
} else if (peer.chat_id != 0) {
chat = chatsMap.get(peer.chat_id);
} else if (peer.channel_id != 0) {
chat = chatsMap.get(peer.channel_id);
}
if (chat != null) {
if (!allowChats || canAddGroupsOnly && !ChatObject.canAddBotsToChat(chat)) {
continue;
}
localServerSearch.add(chat);
globalSearchMap.put(-chat.id, chat);
} else if (user != null) {
if (canAddGroupsOnly || !allowBots && user.bot || !allowSelf && user.self) {
continue;
}
localServerSearch.add(user);
globalSearchMap.put(user.id, user);
}
}
}
lastFoundUsername = query.toLowerCase();
}
}
}));
} else {
globalSearch.clear();
globalSearchMap.clear();
localServerSearch.clear();
hasChanged = false;
}
}
if (!canAddGroupsOnly && phoneNumbers && query.startsWith("+") && query.length() > 3) {
phonesSearch.clear();
phoneSearchMap.clear();
String phone = PhoneFormat.stripExceptNumbers(query);
ArrayList<TLRPC.TL_contact> arrayList = ContactsController.getInstance(currentAccount).contacts;
boolean hasFullMatch = false;
for (int a = 0, N = arrayList.size(); a < N; a++) {
TLRPC.TL_contact contact = arrayList.get(a);
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(contact.user_id);
if (user == null) {
continue;
}
if (user.phone != null && user.phone.startsWith(phone)) {
if (!hasFullMatch) {
hasFullMatch = user.phone.length() == phone.length();
}
phonesSearch.add(user);
phoneSearchMap.put(user.id, user);
}
}
if (!hasFullMatch) {
phonesSearch.add("section");
phonesSearch.add(phone);
}
hasChanged = false;
}
if (hasChanged) {
delegate.onDataSetChanged(searchId);
}
final AtomicInteger gotResponses = new AtomicInteger(0);
final ArrayList<Pair<TLObject, TLRPC.TL_error>> responses = new ArrayList<>();
for (int i = 0; i < requests.size(); ++i) {
final int index = i;
Pair<TLObject, RequestDelegate> r = requests.get(i);
TLObject req = r.first;
responses.add(null);
AtomicInteger reqId = new AtomicInteger();
reqId.set(ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
responses.set(index, new Pair<>(response, error));
Integer reqIdValue = reqId.get();
if (!pendingRequestIds.contains(reqIdValue)) {
return;
}
pendingRequestIds.remove(reqIdValue);
if (gotResponses.incrementAndGet() == requests.size()) {
for (int j = 0; j < requests.size(); ++j) {
RequestDelegate callback = requests.get(j).second;
Pair<TLObject, TLRPC.TL_error> res = responses.get(j);
if (res == null)
continue;
callback.run(res.first, res.second);
}
removeGroupSearchFromGlobal();
if (localSearchResults != null) {
mergeResults(localSearchResults);
}
mergeExcludeResults();
delegate.onDataSetChanged(searchId);
if (onEnd != null) {
onEnd.run();
}
}
})));
pendingRequestIds.add(reqId.get());
}
}
use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.
the class SearchAdapterHelper method addGroupMembers.
public void addGroupMembers(ArrayList<TLObject> participants) {
groupSearch.clear();
groupSearch.addAll(participants);
for (int a = 0, N = participants.size(); a < N; a++) {
TLObject object = participants.get(a);
if (object instanceof TLRPC.ChatParticipant) {
groupSearchMap.put(((TLRPC.ChatParticipant) object).user_id, object);
} else if (object instanceof TLRPC.ChannelParticipant) {
groupSearchMap.put(MessageObject.getPeerId(((TLRPC.ChannelParticipant) object).peer), object);
}
}
removeGroupSearchFromGlobal();
}
use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.
the class SearchAdapterHelper method mergeResults.
public void mergeResults(ArrayList<Object> localResults) {
localSearchResults = localResults;
if (globalSearchMap.size() == 0 || localResults == null) {
return;
}
int count = localResults.size();
for (int a = 0; a < count; a++) {
Object obj = localResults.get(a);
if (obj instanceof ShareAlert.DialogSearchResult) {
ShareAlert.DialogSearchResult searchResult = (ShareAlert.DialogSearchResult) obj;
obj = searchResult.object;
}
if (obj instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) obj;
TLRPC.User u = (TLRPC.User) globalSearchMap.get(user.id);
if (u != null) {
globalSearch.remove(u);
localServerSearch.remove(u);
globalSearchMap.remove(u.id);
}
TLObject participant = groupSearchMap.get(user.id);
if (participant != null) {
groupSearch.remove(participant);
groupSearchMap.remove(user.id);
}
Object object = phoneSearchMap.get(user.id);
if (object != null) {
phonesSearch.remove(object);
phoneSearchMap.remove(user.id);
}
} else if (obj instanceof TLRPC.Chat) {
TLRPC.Chat chat = (TLRPC.Chat) obj;
TLRPC.Chat c = (TLRPC.Chat) globalSearchMap.get(-chat.id);
if (c != null) {
globalSearch.remove(c);
localServerSearch.remove(c);
globalSearchMap.remove(-c.id);
}
}
}
}
use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.
the class DialogsSearchAdapter method onBindViewHolder.
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch(holder.getItemViewType()) {
case 0:
{
ProfileSearchCell cell = (ProfileSearchCell) holder.itemView;
long oldDialogId = cell.getDialogId();
TLRPC.User user = null;
TLRPC.Chat chat = null;
TLRPC.EncryptedChat encryptedChat = null;
CharSequence username = null;
CharSequence name = null;
boolean isRecent = false;
String un = null;
Object obj = getItem(position);
if (obj instanceof TLRPC.User) {
user = (TLRPC.User) obj;
un = user.username;
} else if (obj instanceof TLRPC.Chat) {
chat = MessagesController.getInstance(currentAccount).getChat(((TLRPC.Chat) obj).id);
if (chat == null) {
chat = (TLRPC.Chat) obj;
}
un = chat.username;
} else if (obj instanceof TLRPC.EncryptedChat) {
encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(((TLRPC.EncryptedChat) obj).id);
user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id);
}
if (isRecentSearchDisplayed()) {
isRecent = true;
cell.useSeparator = position != getItemCount() - 1;
} else {
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
ArrayList<Object> phoneSearch = searchAdapterHelper.getPhoneSearch();
int localCount = searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int phoneCount = phoneSearch.size();
if (phoneCount > 3 && phoneCollapsed) {
phoneCount = 3;
}
int phoneCount2 = phoneCount;
if (phoneCount > 0 && phoneSearch.get(phoneCount - 1) instanceof String) {
phoneCount2 -= 2;
}
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
if (globalCount > 4 && globalSearchCollapsed) {
globalCount = 4;
}
cell.useSeparator = (position != getItemCount() - 1 && position != localCount + phoneCount2 + localServerCount - 1 && position != localCount + globalCount + phoneCount + localServerCount - 1);
if (position < searchResult.size()) {
name = searchResultNames.get(position);
if (name != null && user != null && user.username != null && user.username.length() > 0) {
if (name.toString().startsWith("@" + user.username)) {
username = name;
name = null;
}
}
} else {
String foundUserName = searchAdapterHelper.getLastFoundUsername();
if (!TextUtils.isEmpty(foundUserName)) {
String nameSearch = null;
int index;
if (user != null) {
nameSearch = ContactsController.formatName(user.first_name, user.last_name);
} else if (chat != null) {
nameSearch = chat.title;
}
if (nameSearch != null && (index = AndroidUtilities.indexOfIgnoreCase(nameSearch, foundUserName)) != -1) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(nameSearch);
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
name = spannableStringBuilder;
} else if (un != null) {
if (foundUserName.startsWith("@")) {
foundUserName = foundUserName.substring(1);
}
try {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
spannableStringBuilder.append("@");
spannableStringBuilder.append(un);
if ((index = AndroidUtilities.indexOfIgnoreCase(un, foundUserName)) != -1) {
int len = foundUserName.length();
if (index == 0) {
len++;
} else {
index++;
}
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
username = spannableStringBuilder;
} catch (Exception e) {
username = un;
FileLog.e(e);
}
}
}
}
cell.setChecked(false, false);
}
boolean savedMessages = false;
if (user != null && user.id == selfUserId) {
name = LocaleController.getString("SavedMessages", R.string.SavedMessages);
username = null;
savedMessages = true;
}
if (chat != null && chat.participants_count != 0) {
String membersString;
if (ChatObject.isChannel(chat) && !chat.megagroup) {
membersString = LocaleController.formatPluralString("Subscribers", chat.participants_count);
} else {
membersString = LocaleController.formatPluralString("Members", chat.participants_count);
}
if (username instanceof SpannableStringBuilder) {
((SpannableStringBuilder) username).append(", ").append(membersString);
} else if (!TextUtils.isEmpty(username)) {
username = TextUtils.concat(username, ", ", membersString);
} else {
username = membersString;
}
}
cell.setData(user != null ? user : chat, encryptedChat, name, username, isRecent, savedMessages);
cell.setChecked(delegate.isSelected(cell.getDialogId()), oldDialogId == cell.getDialogId());
break;
}
case 1:
{
GraySectionCell cell = (GraySectionCell) holder.itemView;
if (isRecentSearchDisplayed()) {
int offset = (!MediaDataController.getInstance(currentAccount).hints.isEmpty() ? 1 : 0);
if (position < offset) {
cell.setText(LocaleController.getString("ChatHints", R.string.ChatHints));
} else {
cell.setText(LocaleController.getString("Recent", R.string.Recent), LocaleController.getString("ClearButton", R.string.ClearButton), v -> {
if (delegate != null) {
delegate.needClearList();
}
});
}
} else if (!searchResultHashtags.isEmpty()) {
cell.setText(LocaleController.getString("Hashtags", R.string.Hashtags), LocaleController.getString("ClearButton", R.string.ClearButton), v -> {
if (delegate != null) {
delegate.needClearList();
}
});
} else {
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
int localCount = searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int phoneCount = searchAdapterHelper.getPhoneSearch().size();
if (phoneCount > 3 && phoneCollapsed) {
phoneCount = 3;
}
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
if (globalCount > 4 && globalSearchCollapsed) {
globalCount = 4;
}
int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1;
position -= localCount + localServerCount;
String title;
boolean showMore = false;
Runnable onClick = null;
if (position >= 0 && position < phoneCount) {
title = LocaleController.getString("PhoneNumberSearch", R.string.PhoneNumberSearch);
if (searchAdapterHelper.getPhoneSearch().size() > 3) {
showMore = phoneCollapsed;
onClick = () -> {
phoneCollapsed = !phoneCollapsed;
notifyDataSetChanged();
};
}
} else {
position -= phoneCount;
if (position >= 0 && position < globalCount) {
title = LocaleController.getString("GlobalSearch", R.string.GlobalSearch);
if (searchAdapterHelper.getGlobalSearch().size() > 3) {
showMore = globalSearchCollapsed;
onClick = () -> {
globalSearchCollapsed = !globalSearchCollapsed;
notifyDataSetChanged();
};
}
} else {
title = LocaleController.getString("SearchMessages", R.string.SearchMessages);
}
}
if (onClick == null) {
cell.setText(title);
} else {
final Runnable finalOnClick = onClick;
cell.setText(title, showMore ? LocaleController.getString("ShowMore", R.string.ShowMore) : LocaleController.getString("ShowLess", R.string.ShowLess), e -> finalOnClick.run());
}
}
break;
}
case 2:
{
DialogCell cell = (DialogCell) holder.itemView;
cell.useSeparator = (position != getItemCount() - 1);
MessageObject messageObject = (MessageObject) getItem(position);
cell.setDialog(messageObject.getDialogId(), messageObject, messageObject.messageOwner.date, false);
break;
}
case 4:
{
HashtagSearchCell cell = (HashtagSearchCell) holder.itemView;
cell.setText(searchResultHashtags.get(position - 1));
cell.setNeedDivider(position != searchResultHashtags.size());
break;
}
case 5:
{
RecyclerListView recyclerListView = (RecyclerListView) holder.itemView;
((CategoryAdapterRecycler) recyclerListView.getAdapter()).setIndex(position / 2);
break;
}
case 6:
{
String str = (String) getItem(position);
TextCell cell = (TextCell) holder.itemView;
cell.setColors(null, Theme.key_windowBackgroundWhiteBlueText2);
cell.setText(LocaleController.formatString("AddContactByPhone", R.string.AddContactByPhone, PhoneFormat.getInstance().format("+" + str)), false);
break;
}
}
}
Aggregations