Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clearing inactive users #33

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Clearing inactive users #33

wants to merge 1 commit into from

Conversation

4nk1r
Copy link

@4nk1r 4nk1r commented Jul 27, 2023

No description provided.

@immat0x1 immat0x1 added the bug Something isn't working label Jul 31, 2023
@immat0x1
Copy link
Member

запрос к получению участников возвращает всего 200 юзеров, нужно делать рекурсивный метод с последующим оффсетом от обработанных юзеров, пока что заниматься не хочу, да и натестился уже, половину чатов вырезал)))))))))

если сам допилишь - respect

@4nk1r
Copy link
Author

4nk1r commented Aug 1, 2023

запрос к получению участников возвращает всего 200 юзеров, нужно делать рекурсивный метод с последующим оффсетом от обработанных юзеров

только это, остальное работает?

@immat0x1
Copy link
Member

immat0x1 commented Aug 1, 2023

забыл, также отсутствует проверка на наличие сообщений у пользователя, поэтому при get(0) вылетает NullPointerException, если у чела нету сообщений

ну и в многопотоке у меня гораздо быстрее отрабатывало, так что стоило бы его тоже как-то организовать для оптимизации

@4nk1r
Copy link
Author

4nk1r commented Aug 1, 2023

Скинь наработки, допилю и дозалью в пр на днях, как будет время

@immat0x1
Copy link
Member

immat0x1 commented Aug 1, 2023

`AlertsCreator.createInactivityPeriodPickerDialog(context, getResourceProvider(), (notify, seconds) -> {
boolean removeDeleted = seconds == 60 * 24 * 365;

                    ClearingInactiveUsersBottomSheet bottomSheet = new ClearingInactiveUsersBottomSheet(context);
                    bottomSheet.show();

                    TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants();
                    req.channel = getMessagesController().getInputChannel(chatId);
                    req.limit = 250000;
                    req.filter = new TLRPC.TL_channelParticipantsRecent();

                    int reqId = getConnectionsManager().sendRequest(req, ((res, err) -> {
                        if (res != null) {
                            AtomicInteger processedUsers = new AtomicInteger(0);
                            ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

                            final TLRPC.TL_channels_channelParticipants response = (TLRPC.TL_channels_channelParticipants) res;

                            List<TLRPC.User> users = response.users.stream()
                                    .filter(user -> removeDeleted ? user.deleted : !UserObject.isUserSelf(user) && !user.bot)
                                    .collect(Collectors.toList());
                            android.util.Log.d("INACTEST", response.users.size() + " " + users.size());
                            for (TLRPC.User user : users) {
                                android.util.Log.d("INACTEST cycle", ContactsController.formatName(user));

                                executorService.execute(() -> {
                                    TLRPC.TL_messages_search searchReq = new TLRPC.TL_messages_search();
                                    searchReq.peer = getMessagesController().getInputPeer(-chatId);
                                    searchReq.from_id = MessagesController.getInputPeer(user);
                                    searchReq.flags |= 1;
                                    searchReq.limit = 1;
                                    searchReq.filter = new TLRPC.TL_inputMessagesFilterEmpty();

                                    getConnectionsManager().sendRequestSync(searchReq, (searchRes, searchErr) -> {
                                        processedUsers.getAndIncrement();
                                        AndroidUtilities.runOnUIThread(() -> {
                                            bottomSheet.setProgress((float) processedUsers.get() / users.size());
                                        });
                                        if (searchRes != null) {
                                            TLRPC.TL_messages_channelMessages searchResponse = (TLRPC.TL_messages_channelMessages) searchRes;
                                            TLRPC.Message msg = null;
                                            if (!searchResponse.messages.isEmpty()) {
                                                msg = searchResponse.messages.get(0);
                                            }
                                            if (user.deleted || msg == null || getConnectionsManager().getCurrentTime() - msg.date > seconds) {
                                                TLRPC.TL_channels_editBanned kickReq = new TLRPC.TL_channels_editBanned();
                                                kickReq.channel = MessagesController.getInputChannel(currentChat);
                                                kickReq.participant = MessagesController.getInputPeer(user);
                                                kickReq.banned_rights = new TLRPC.TL_chatBannedRights();
                                                kickReq.banned_rights.view_messages = true;
                                                kickReq.banned_rights.send_media = true;
                                                kickReq.banned_rights.send_messages = true;
                                                kickReq.banned_rights.send_stickers = true;
                                                kickReq.banned_rights.send_gifs = true;
                                                kickReq.banned_rights.send_games = true;
                                                kickReq.banned_rights.send_inline = true;
                                                kickReq.banned_rights.embed_links = true;
                                                kickReq.banned_rights.pin_messages = true;
                                                kickReq.banned_rights.send_polls = true;
                                                kickReq.banned_rights.invite_users = true;
                                                kickReq.banned_rights.change_info = true;
                                                getConnectionsManager().sendRequest(kickReq, (r, e) -> {
                                                    if (e != null) {
                                                        return;
                                                    }
                                                    android.util.Log.d("INACTEST cycle", "kicked " + ContactsController.formatName(user));

                                                    kickReq.banned_rights = new TLRPC.TL_chatBannedRights();
                                                    getConnectionsManager().sendRequest(kickReq, (rr, ee) -> {
                                                        android.util.Log.d("INACTEST cycle", "unkicked " + ContactsController.formatName(user) + " " + processedUsers.get());

                                                        if (users.size() == processedUsers.get()) {
                                                            getMessagesController().processUpdates((TLRPC.Updates) rr, false);
                                                            AndroidUtilities.runOnUIThread(() -> {
                                                                bottomSheet.dismiss();
                                                                BulletinFactory.of(ChatUsersActivity.this)
                                                                        .createSimpleBulletin(R.raw.swipe_delete, LocaleController.getString(R.string.InactiveUsersRemoved))
                                                                        .show();
                                                            });
                                                        }
                                                    });
                                                });
                                            }
                                        }
                                    });
                                });
                            }
                            executorService.shutdown();
                        } else {
                            AndroidUtilities.runOnUIThread(() -> {
                                bottomSheet.dismiss();
                                BulletinFactory.of(ChatUsersActivity.this)
                                    .createSimpleBulletin(R.raw.error, LocaleController.getString("UnknownError", R.string.UnknownError))
                                    .show();
                            });
                        }
                    }));
                    getConnectionsManager().bindRequestToGuid(reqId, classGuid);
                });`

немного пояснений по тому, чё сделал:

  1. в пикере инактивности убрал "1 год", заменив его на "Удаленные аккаунты", removeDeleted собственно относится к этому
  2. боттомшит можешь заменить обратно на алертдиалог, я там прогрессбар добавил прост
  3. сделал фильтрацию юзеров через stream, убрал каунтер totalUsers
  4. остальное сам поймёшь

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants