use of org.telegram.ui.ActionBar.Theme in project Telegram-FOSS by Telegram-FOSS-Team.
the class DefaultThemesPreviewCell method updateSelectedPosition.
private void updateSelectedPosition() {
if (adapter.items == null) {
return;
}
selectedPosition = -1;
for (int i = 0; i < adapter.items.size(); i++) {
TLRPC.TL_theme theme = adapter.items.get(i).chatTheme.getTlTheme(themeIndex);
Theme.ThemeInfo themeInfo = adapter.items.get(i).chatTheme.getThemeInfo(themeIndex);
if (theme != null) {
int settingsIndex = adapter.items.get(i).chatTheme.getSettingsIndex(themeIndex);
String key = Theme.getBaseThemeKey(theme.settings.get(settingsIndex));
if (Theme.getActiveTheme().name.equals(key)) {
if (Theme.getActiveTheme().accentsByThemeId == null) {
selectedPosition = i;
break;
} else {
Theme.ThemeAccent accent = Theme.getActiveTheme().accentsByThemeId.get(theme.id);
if (accent != null && accent.id == Theme.getActiveTheme().currentAccentId) {
selectedPosition = i;
break;
}
}
}
} else if (themeInfo != null) {
String key = themeInfo.getKey();
if (Theme.getActiveTheme().name.equals(key) && adapter.items.get(i).chatTheme.getAccentId(themeIndex) == Theme.getActiveTheme().currentAccentId) {
selectedPosition = i;
break;
}
}
}
if (selectedPosition == -1 && currentType != ThemeActivity.THEME_TYPE_THEMES_BROWSER) {
selectedPosition = adapter.items.size() - 1;
}
for (int i = 0; i < adapter.items.size(); i++) {
adapter.items.get(i).isSelected = i == selectedPosition;
}
adapter.setSelectedItem(selectedPosition);
}
use of org.telegram.ui.ActionBar.Theme in project Telegram-FOSS by Telegram-FOSS-Team.
the class LaunchActivity method runLinkRequest.
private void runLinkRequest(final int intentAccount, final String username, final String group, final String sticker, final String botUser, final String botChat, final String message, final boolean hasUrl, final Integer messageId, final Long channelId, final Integer threadId, final Integer commentId, final String game, final HashMap<String, String> auth, final String lang, final String unsupportedUrl, final String code, final String loginToken, final TLRPC.TL_wallPaper wallPaper, final String theme, final String voicechat, final String livestream, final int state, final int videoTimestamp) {
if (state == 0 && UserConfig.getActivatedAccountsCount() >= 2 && auth != null) {
AlertsCreator.createAccountSelectDialog(this, account -> {
if (account != intentAccount) {
switchToAccount(account, true);
}
runLinkRequest(account, username, group, sticker, botUser, botChat, message, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, theme, voicechat, livestream, 1, videoTimestamp);
}).show();
return;
} else if (code != null) {
if (NotificationCenter.getGlobalInstance().hasObservers(NotificationCenter.didReceiveSmsCode)) {
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didReceiveSmsCode, code);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("OtherLoginCode", R.string.OtherLoginCode, code)));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showAlertDialog(builder);
}
return;
} else if (loginToken != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTitle(LocaleController.getString("AuthAnotherClient", R.string.AuthAnotherClient));
builder.setMessage(LocaleController.getString("AuthAnotherClientUrl", R.string.AuthAnotherClientUrl));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showAlertDialog(builder);
return;
}
final AlertDialog progressDialog = new AlertDialog(this, 3);
final int[] requestId = new int[] { 0 };
Runnable cancelRunnable = null;
if (username != null) {
TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername();
req.username = username;
requestId[0] = ConnectionsManager.getInstance(intentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (!LaunchActivity.this.isFinishing()) {
boolean hideProgressDialog = true;
final TLRPC.TL_contacts_resolvedPeer res = (TLRPC.TL_contacts_resolvedPeer) response;
if (error == null && actionBarLayout != null && (game == null && voicechat == null || game != null && !res.users.isEmpty() || voicechat != null && !res.chats.isEmpty() || livestream != null && !res.chats.isEmpty())) {
MessagesController.getInstance(intentAccount).putUsers(res.users, false);
MessagesController.getInstance(intentAccount).putChats(res.chats, false);
MessagesStorage.getInstance(intentAccount).putUsersAndChats(res.users, res.chats, false, true);
if (messageId != null && (commentId != null || threadId != null) && !res.chats.isEmpty()) {
requestId[0] = runCommentRequest(intentAccount, progressDialog, messageId, commentId, threadId, res.chats.get(0));
if (requestId[0] != 0) {
hideProgressDialog = false;
}
} else if (game != null) {
Bundle args = new Bundle();
args.putBoolean("onlySelect", true);
args.putBoolean("cantSendToChannels", true);
args.putInt("dialogsType", 1);
args.putString("selectAlertString", LocaleController.getString("SendGameToText", R.string.SendGameToText));
args.putString("selectAlertStringGroup", LocaleController.getString("SendGameToGroupText", R.string.SendGameToGroupText));
DialogsActivity fragment = new DialogsActivity(args);
fragment.setDelegate((fragment1, dids, message1, param) -> {
long did = dids.get(0);
TLRPC.TL_inputMediaGame inputMediaGame = new TLRPC.TL_inputMediaGame();
inputMediaGame.id = new TLRPC.TL_inputGameShortName();
inputMediaGame.id.short_name = game;
inputMediaGame.id.bot_id = MessagesController.getInstance(intentAccount).getInputUser(res.users.get(0));
SendMessagesHelper.getInstance(intentAccount).sendGame(MessagesController.getInstance(intentAccount).getInputPeer(did), inputMediaGame, 0, 0);
Bundle args1 = new Bundle();
args1.putBoolean("scrollToTopOnResume", true);
if (DialogObject.isEncryptedDialog(did)) {
args1.putInt("enc_id", DialogObject.getEncryptedChatId(did));
} else if (DialogObject.isUserDialog(did)) {
args1.putLong("user_id", did);
} else {
args1.putLong("chat_id", -did);
}
if (MessagesController.getInstance(intentAccount).checkCanOpenChat(args1, fragment1)) {
NotificationCenter.getInstance(intentAccount).postNotificationName(NotificationCenter.closeChats);
actionBarLayout.presentFragment(new ChatActivity(args1), true, false, true, false);
}
});
boolean removeLast;
if (AndroidUtilities.isTablet()) {
removeLast = layersActionBarLayout.fragmentsStack.size() > 0 && layersActionBarLayout.fragmentsStack.get(layersActionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity;
} else {
removeLast = actionBarLayout.fragmentsStack.size() > 1 && actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity;
}
actionBarLayout.presentFragment(fragment, removeLast, true, true, false);
if (SecretMediaViewer.hasInstance() && SecretMediaViewer.getInstance().isVisible()) {
SecretMediaViewer.getInstance().closePhoto(false, false);
} else if (PhotoViewer.hasInstance() && PhotoViewer.getInstance().isVisible()) {
PhotoViewer.getInstance().closePhoto(false, true);
} else if (ArticleViewer.hasInstance() && ArticleViewer.getInstance().isVisible()) {
ArticleViewer.getInstance().close(false, true);
}
if (GroupCallActivity.groupCallInstance != null) {
GroupCallActivity.groupCallInstance.dismiss();
}
drawerLayoutContainer.setAllowOpenDrawer(false, false);
if (AndroidUtilities.isTablet()) {
actionBarLayout.showLastFragment();
rightActionBarLayout.showLastFragment();
} else {
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
} else if (botChat != null) {
final TLRPC.User user = !res.users.isEmpty() ? res.users.get(0) : null;
if (user == null || user.bot && user.bot_nochats) {
try {
if (!mainFragmentsStack.isEmpty()) {
BulletinFactory.of(mainFragmentsStack.get(mainFragmentsStack.size() - 1)).createErrorBulletin(LocaleController.getString("BotCantJoinGroups", R.string.BotCantJoinGroups)).show();
}
} catch (Exception e) {
FileLog.e(e);
}
return;
}
Bundle args = new Bundle();
args.putBoolean("onlySelect", true);
args.putInt("dialogsType", 2);
args.putString("addToGroupAlertString", LocaleController.formatString("AddToTheGroupAlertText", R.string.AddToTheGroupAlertText, UserObject.getUserName(user), "%1$s"));
DialogsActivity fragment = new DialogsActivity(args);
fragment.setDelegate((fragment12, dids, message1, param) -> {
long did = dids.get(0);
Bundle args12 = new Bundle();
args12.putBoolean("scrollToTopOnResume", true);
args12.putLong("chat_id", -did);
if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount).checkCanOpenChat(args12, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
NotificationCenter.getInstance(intentAccount).postNotificationName(NotificationCenter.closeChats);
MessagesController.getInstance(intentAccount).addUserToChat(-did, user, 0, botChat, null, null);
actionBarLayout.presentFragment(new ChatActivity(args12), true, false, true, false);
}
});
presentFragment(fragment);
} else {
long dialog_id;
boolean isBot = false;
Bundle args = new Bundle();
if (!res.chats.isEmpty()) {
args.putLong("chat_id", res.chats.get(0).id);
dialog_id = -res.chats.get(0).id;
} else {
args.putLong("user_id", res.users.get(0).id);
dialog_id = res.users.get(0).id;
}
if (botUser != null && res.users.size() > 0 && res.users.get(0).bot) {
args.putString("botUser", botUser);
isBot = true;
}
if (messageId != null) {
args.putInt("message_id", messageId);
}
if (voicechat != null) {
args.putString("voicechat", voicechat);
}
if (livestream != null) {
args.putString("livestream", livestream);
}
if (videoTimestamp >= 0) {
args.putInt("video_timestamp", videoTimestamp);
}
BaseFragment lastFragment = !mainFragmentsStack.isEmpty() && voicechat == null ? mainFragmentsStack.get(mainFragmentsStack.size() - 1) : null;
if (lastFragment == null || MessagesController.getInstance(intentAccount).checkCanOpenChat(args, lastFragment)) {
if (isBot && lastFragment instanceof ChatActivity && ((ChatActivity) lastFragment).getDialogId() == dialog_id) {
((ChatActivity) lastFragment).setBotUser(botUser);
} else {
MessagesController.getInstance(intentAccount).ensureMessagesLoaded(dialog_id, messageId == null ? 0 : messageId, new MessagesController.MessagesLoadedCallback() {
@Override
public void onMessagesLoaded(boolean fromCache) {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
if (!LaunchActivity.this.isFinishing()) {
ChatActivity fragment = new ChatActivity(args);
actionBarLayout.presentFragment(fragment);
}
}
@Override
public void onError() {
if (!LaunchActivity.this.isFinishing()) {
BaseFragment fragment = mainFragmentsStack.get(mainFragmentsStack.size() - 1);
AlertsCreator.showSimpleAlert(fragment, LocaleController.getString("JoinToGroupErrorNotExist", R.string.JoinToGroupErrorNotExist));
}
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
}
});
hideProgressDialog = false;
}
}
}
} else {
try {
if (!mainFragmentsStack.isEmpty()) {
BaseFragment fragment = mainFragmentsStack.get(mainFragmentsStack.size() - 1);
if (error != null && error.text != null && error.text.startsWith("FLOOD_WAIT")) {
BulletinFactory.of(fragment).createErrorBulletin(LocaleController.getString("FloodWait", R.string.FloodWait)).show();
} else {
BulletinFactory.of(fragment).createErrorBulletin(LocaleController.getString("NoUsernameFound", R.string.NoUsernameFound)).show();
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
if (hideProgressDialog) {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
}
}
}, ConnectionsManager.RequestFlagFailOnServerErrors));
} else if (group != null) {
if (state == 0) {
final TLRPC.TL_messages_checkChatInvite req = new TLRPC.TL_messages_checkChatInvite();
req.hash = group;
requestId[0] = ConnectionsManager.getInstance(intentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (!LaunchActivity.this.isFinishing()) {
boolean hideProgressDialog = true;
if (error == null && actionBarLayout != null) {
TLRPC.ChatInvite invite = (TLRPC.ChatInvite) response;
if (invite.chat != null && (!ChatObject.isLeftFromChat(invite.chat) || !invite.chat.kicked && (!TextUtils.isEmpty(invite.chat.username) || invite instanceof TLRPC.TL_chatInvitePeek || invite.chat.has_geo))) {
MessagesController.getInstance(intentAccount).putChat(invite.chat, false);
ArrayList<TLRPC.Chat> chats = new ArrayList<>();
chats.add(invite.chat);
MessagesStorage.getInstance(intentAccount).putUsersAndChats(null, chats, false, true);
Bundle args = new Bundle();
args.putLong("chat_id", invite.chat.id);
if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
boolean[] canceled = new boolean[1];
progressDialog.setOnCancelListener(dialog -> canceled[0] = true);
MessagesController.getInstance(intentAccount).ensureMessagesLoaded(-invite.chat.id, 0, new MessagesController.MessagesLoadedCallback() {
@Override
public void onMessagesLoaded(boolean fromCache) {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
if (canceled[0]) {
return;
}
ChatActivity fragment = new ChatActivity(args);
if (invite instanceof TLRPC.TL_chatInvitePeek) {
fragment.setChatInvite(invite);
}
actionBarLayout.presentFragment(fragment);
}
@Override
public void onError() {
if (!LaunchActivity.this.isFinishing()) {
BaseFragment fragment = mainFragmentsStack.get(mainFragmentsStack.size() - 1);
AlertsCreator.showSimpleAlert(fragment, LocaleController.getString("JoinToGroupErrorNotExist", R.string.JoinToGroupErrorNotExist));
}
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
}
});
hideProgressDialog = false;
}
} else {
BaseFragment fragment = mainFragmentsStack.get(mainFragmentsStack.size() - 1);
fragment.showDialog(new JoinGroupAlert(LaunchActivity.this, invite, group, fragment));
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
if (error.text.startsWith("FLOOD_WAIT")) {
builder.setMessage(LocaleController.getString("FloodWait", R.string.FloodWait));
} else if (error.text.startsWith("INVITE_HASH_EXPIRED")) {
builder.setTitle(LocaleController.getString("ExpiredLink", R.string.ExpiredLink));
builder.setMessage(LocaleController.getString("InviteExpired", R.string.InviteExpired));
} else {
builder.setMessage(LocaleController.getString("JoinToGroupErrorNotExist", R.string.JoinToGroupErrorNotExist));
}
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showAlertDialog(builder);
}
try {
if (hideProgressDialog) {
progressDialog.dismiss();
}
} catch (Exception e) {
FileLog.e(e);
}
}
}), ConnectionsManager.RequestFlagFailOnServerErrors);
} else if (state == 1) {
TLRPC.TL_messages_importChatInvite req = new TLRPC.TL_messages_importChatInvite();
req.hash = group;
ConnectionsManager.getInstance(intentAccount).sendRequest(req, (response, error) -> {
if (error == null) {
TLRPC.Updates updates = (TLRPC.Updates) response;
MessagesController.getInstance(intentAccount).processUpdates(updates, false);
}
AndroidUtilities.runOnUIThread(() -> {
if (!LaunchActivity.this.isFinishing()) {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
if (error == null) {
if (actionBarLayout != null) {
TLRPC.Updates updates = (TLRPC.Updates) response;
if (!updates.chats.isEmpty()) {
TLRPC.Chat chat = updates.chats.get(0);
chat.left = false;
chat.kicked = false;
MessagesController.getInstance(intentAccount).putUsers(updates.users, false);
MessagesController.getInstance(intentAccount).putChats(updates.chats, false);
Bundle args = new Bundle();
args.putLong("chat_id", chat.id);
if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
ChatActivity fragment = new ChatActivity(args);
NotificationCenter.getInstance(intentAccount).postNotificationName(NotificationCenter.closeChats);
actionBarLayout.presentFragment(fragment, false, true, true, false);
}
}
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
if (error.text.startsWith("FLOOD_WAIT")) {
builder.setMessage(LocaleController.getString("FloodWait", R.string.FloodWait));
} else if (error.text.equals("USERS_TOO_MUCH")) {
builder.setMessage(LocaleController.getString("JoinToGroupErrorFull", R.string.JoinToGroupErrorFull));
} else {
builder.setMessage(LocaleController.getString("JoinToGroupErrorNotExist", R.string.JoinToGroupErrorNotExist));
}
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showAlertDialog(builder);
}
}
});
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}
} else if (sticker != null) {
if (!mainFragmentsStack.isEmpty()) {
TLRPC.TL_inputStickerSetShortName stickerset = new TLRPC.TL_inputStickerSetShortName();
stickerset.short_name = sticker;
BaseFragment fragment = mainFragmentsStack.get(mainFragmentsStack.size() - 1);
StickersAlert alert;
if (fragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) fragment;
alert = new StickersAlert(LaunchActivity.this, fragment, stickerset, null, chatActivity.getChatActivityEnterViewForStickers(), chatActivity.getResourceProvider());
alert.setCalcMandatoryInsets(chatActivity.isKeyboardVisible());
} else {
alert = new StickersAlert(LaunchActivity.this, fragment, stickerset, null, null);
}
fragment.showDialog(alert);
}
return;
} else if (message != null) {
Bundle args = new Bundle();
args.putBoolean("onlySelect", true);
args.putInt("dialogsType", 3);
DialogsActivity fragment = new DialogsActivity(args);
fragment.setDelegate((fragment13, dids, m, param) -> {
long did = dids.get(0);
Bundle args13 = new Bundle();
args13.putBoolean("scrollToTopOnResume", true);
args13.putBoolean("hasUrl", hasUrl);
if (DialogObject.isEncryptedDialog(did)) {
args13.putInt("enc_id", DialogObject.getEncryptedChatId(did));
} else if (DialogObject.isUserDialog(did)) {
args13.putLong("user_id", did);
} else {
args13.putLong("chat_id", -did);
}
if (MessagesController.getInstance(intentAccount).checkCanOpenChat(args13, fragment13)) {
NotificationCenter.getInstance(intentAccount).postNotificationName(NotificationCenter.closeChats);
MediaDataController.getInstance(intentAccount).saveDraft(did, 0, message, null, null, false);
actionBarLayout.presentFragment(new ChatActivity(args13), true, false, true, false);
}
});
presentFragment(fragment, false, true);
} else if (auth != null) {
final int bot_id = Utilities.parseInt(auth.get("bot_id"));
if (bot_id == 0) {
return;
}
final String payload = auth.get("payload");
final String nonce = auth.get("nonce");
final String callbackUrl = auth.get("callback_url");
final TLRPC.TL_account_getAuthorizationForm req = new TLRPC.TL_account_getAuthorizationForm();
req.bot_id = bot_id;
req.scope = auth.get("scope");
req.public_key = auth.get("public_key");
requestId[0] = ConnectionsManager.getInstance(intentAccount).sendRequest(req, (response, error) -> {
final TLRPC.TL_account_authorizationForm authorizationForm = (TLRPC.TL_account_authorizationForm) response;
if (authorizationForm != null) {
TLRPC.TL_account_getPassword req2 = new TLRPC.TL_account_getPassword();
requestId[0] = ConnectionsManager.getInstance(intentAccount).sendRequest(req2, (response1, error1) -> AndroidUtilities.runOnUIThread(() -> {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
if (response1 != null) {
TLRPC.TL_account_password accountPassword = (TLRPC.TL_account_password) response1;
MessagesController.getInstance(intentAccount).putUsers(authorizationForm.users, false);
presentFragment(new PassportActivity(PassportActivity.TYPE_PASSWORD, req.bot_id, req.scope, req.public_key, payload, nonce, callbackUrl, authorizationForm, accountPassword));
}
}));
} else {
AndroidUtilities.runOnUIThread(() -> {
try {
progressDialog.dismiss();
if ("APP_VERSION_OUTDATED".equals(error.text)) {
AlertsCreator.showUpdateAppAlert(LaunchActivity.this, LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert), true);
} else {
showAlertDialog(AlertsCreator.createSimpleAlert(LaunchActivity.this, LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred) + "\n" + error.text));
}
} catch (Exception e) {
FileLog.e(e);
}
});
}
});
} else if (unsupportedUrl != null) {
TLRPC.TL_help_getDeepLinkInfo req = new TLRPC.TL_help_getDeepLinkInfo();
req.path = unsupportedUrl;
requestId[0] = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
if (response instanceof TLRPC.TL_help_deepLinkInfo) {
TLRPC.TL_help_deepLinkInfo res = (TLRPC.TL_help_deepLinkInfo) response;
AlertsCreator.showUpdateAppAlert(LaunchActivity.this, res.message, res.update_app);
}
}));
} else if (lang != null) {
TLRPC.TL_langpack_getLanguage req = new TLRPC.TL_langpack_getLanguage();
req.lang_code = lang;
req.lang_pack = "android";
requestId[0] = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
if (response instanceof TLRPC.TL_langPackLanguage) {
TLRPC.TL_langPackLanguage res = (TLRPC.TL_langPackLanguage) response;
showAlertDialog(AlertsCreator.createLanguageAlert(LaunchActivity.this, res));
} else if (error != null) {
if ("LANG_CODE_NOT_SUPPORTED".equals(error.text)) {
showAlertDialog(AlertsCreator.createSimpleAlert(LaunchActivity.this, LocaleController.getString("LanguageUnsupportedError", R.string.LanguageUnsupportedError)));
} else {
showAlertDialog(AlertsCreator.createSimpleAlert(LaunchActivity.this, LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred) + "\n" + error.text));
}
}
}));
} else if (wallPaper != null) {
boolean ok = false;
if (TextUtils.isEmpty(wallPaper.slug)) {
try {
WallpapersListActivity.ColorWallpaper colorWallpaper;
if (wallPaper.settings.third_background_color != 0) {
colorWallpaper = new WallpapersListActivity.ColorWallpaper(Theme.COLOR_BACKGROUND_SLUG, wallPaper.settings.background_color, wallPaper.settings.second_background_color, wallPaper.settings.third_background_color, wallPaper.settings.fourth_background_color);
} else {
colorWallpaper = new WallpapersListActivity.ColorWallpaper(Theme.COLOR_BACKGROUND_SLUG, wallPaper.settings.background_color, wallPaper.settings.second_background_color, AndroidUtilities.getWallpaperRotation(wallPaper.settings.rotation, false));
}
ThemePreviewActivity wallpaperActivity = new ThemePreviewActivity(colorWallpaper, null, true, false);
AndroidUtilities.runOnUIThread(() -> presentFragment(wallpaperActivity));
ok = true;
} catch (Exception e) {
FileLog.e(e);
}
}
if (!ok) {
TLRPC.TL_account_getWallPaper req = new TLRPC.TL_account_getWallPaper();
TLRPC.TL_inputWallPaperSlug inputWallPaperSlug = new TLRPC.TL_inputWallPaperSlug();
inputWallPaperSlug.slug = wallPaper.slug;
req.wallpaper = inputWallPaperSlug;
requestId[0] = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
if (response instanceof TLRPC.TL_wallPaper) {
TLRPC.TL_wallPaper res = (TLRPC.TL_wallPaper) response;
Object object;
if (res.pattern) {
WallpapersListActivity.ColorWallpaper colorWallpaper = new WallpapersListActivity.ColorWallpaper(res.slug, wallPaper.settings.background_color, wallPaper.settings.second_background_color, wallPaper.settings.third_background_color, wallPaper.settings.fourth_background_color, AndroidUtilities.getWallpaperRotation(wallPaper.settings.rotation, false), wallPaper.settings.intensity / 100.0f, wallPaper.settings.motion, null);
colorWallpaper.pattern = res;
object = colorWallpaper;
} else {
object = res;
}
ThemePreviewActivity wallpaperActivity = new ThemePreviewActivity(object, null, true, false);
wallpaperActivity.setInitialModes(wallPaper.settings.blur, wallPaper.settings.motion);
presentFragment(wallpaperActivity);
} else {
showAlertDialog(AlertsCreator.createSimpleAlert(LaunchActivity.this, LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred) + "\n" + error.text));
}
}));
}
} else if (theme != null) {
cancelRunnable = () -> {
loadingThemeFileName = null;
loadingThemeWallpaperName = null;
loadingThemeWallpaper = null;
loadingThemeInfo = null;
loadingThemeProgressDialog = null;
loadingTheme = null;
};
TLRPC.TL_account_getTheme req = new TLRPC.TL_account_getTheme();
req.format = "android";
TLRPC.TL_inputThemeSlug inputThemeSlug = new TLRPC.TL_inputThemeSlug();
inputThemeSlug.slug = theme;
req.theme = inputThemeSlug;
requestId[0] = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
int notFound = 2;
if (response instanceof TLRPC.TL_theme) {
TLRPC.TL_theme t = (TLRPC.TL_theme) response;
TLRPC.ThemeSettings settings = null;
if (t.settings.size() > 0) {
settings = t.settings.get(0);
}
if (settings != null) {
String key = Theme.getBaseThemeKey(settings);
Theme.ThemeInfo info = Theme.getTheme(key);
if (info != null) {
TLRPC.TL_wallPaper object;
if (settings.wallpaper instanceof TLRPC.TL_wallPaper) {
object = (TLRPC.TL_wallPaper) settings.wallpaper;
File path = FileLoader.getPathToAttach(object.document, true);
if (!path.exists()) {
loadingThemeProgressDialog = progressDialog;
loadingThemeAccent = true;
loadingThemeInfo = info;
loadingTheme = t;
loadingThemeWallpaper = object;
loadingThemeWallpaperName = FileLoader.getAttachFileName(object.document);
FileLoader.getInstance(currentAccount).loadFile(object.document, object, 1, 1);
return;
}
} else {
object = null;
}
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
notFound = 0;
openThemeAccentPreview(t, object, info);
} else {
notFound = 1;
}
} else if (t.document != null) {
loadingThemeAccent = false;
loadingTheme = t;
loadingThemeFileName = FileLoader.getAttachFileName(loadingTheme.document);
loadingThemeProgressDialog = progressDialog;
FileLoader.getInstance(currentAccount).loadFile(loadingTheme.document, t, 1, 1);
notFound = 0;
} else {
notFound = 1;
}
} else if (error != null && "THEME_FORMAT_INVALID".equals(error.text)) {
notFound = 1;
}
if (notFound != 0) {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
if (notFound == 1) {
showAlertDialog(AlertsCreator.createSimpleAlert(LaunchActivity.this, LocaleController.getString("Theme", R.string.Theme), LocaleController.getString("ThemeNotSupported", R.string.ThemeNotSupported)));
} else {
showAlertDialog(AlertsCreator.createSimpleAlert(LaunchActivity.this, LocaleController.getString("Theme", R.string.Theme), LocaleController.getString("ThemeNotFound", R.string.ThemeNotFound)));
}
}
}));
} else if (channelId != null && messageId != null) {
if (threadId != null) {
TLRPC.Chat chat = MessagesController.getInstance(intentAccount).getChat(channelId);
if (chat != null) {
requestId[0] = runCommentRequest(intentAccount, progressDialog, messageId, commentId, threadId, chat);
} else {
TLRPC.TL_channels_getChannels req = new TLRPC.TL_channels_getChannels();
TLRPC.TL_inputChannel inputChannel = new TLRPC.TL_inputChannel();
inputChannel.channel_id = channelId;
req.id.add(inputChannel);
requestId[0] = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
boolean notFound = true;
if (response instanceof TLRPC.TL_messages_chats) {
TLRPC.TL_messages_chats res = (TLRPC.TL_messages_chats) response;
if (!res.chats.isEmpty()) {
notFound = false;
MessagesController.getInstance(currentAccount).putChats(res.chats, false);
requestId[0] = runCommentRequest(intentAccount, progressDialog, messageId, commentId, threadId, res.chats.get(0));
}
}
if (notFound) {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
showAlertDialog(AlertsCreator.createSimpleAlert(LaunchActivity.this, LocaleController.getString("LinkNotFound", R.string.LinkNotFound)));
}
}));
}
} else {
Bundle args = new Bundle();
args.putLong("chat_id", channelId);
args.putInt("message_id", messageId);
BaseFragment lastFragment = !mainFragmentsStack.isEmpty() ? mainFragmentsStack.get(mainFragmentsStack.size() - 1) : null;
if (lastFragment == null || MessagesController.getInstance(intentAccount).checkCanOpenChat(args, lastFragment)) {
AndroidUtilities.runOnUIThread(() -> {
if (!actionBarLayout.presentFragment(new ChatActivity(args))) {
TLRPC.TL_channels_getChannels req = new TLRPC.TL_channels_getChannels();
TLRPC.TL_inputChannel inputChannel = new TLRPC.TL_inputChannel();
inputChannel.channel_id = channelId;
req.id.add(inputChannel);
requestId[0] = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
boolean notFound = true;
if (response instanceof TLRPC.TL_messages_chats) {
TLRPC.TL_messages_chats res = (TLRPC.TL_messages_chats) response;
if (!res.chats.isEmpty()) {
notFound = false;
MessagesController.getInstance(currentAccount).putChats(res.chats, false);
TLRPC.Chat chat = res.chats.get(0);
if (lastFragment == null || MessagesController.getInstance(intentAccount).checkCanOpenChat(args, lastFragment)) {
actionBarLayout.presentFragment(new ChatActivity(args));
}
}
}
if (notFound) {
showAlertDialog(AlertsCreator.createSimpleAlert(LaunchActivity.this, LocaleController.getString("LinkNotFound", R.string.LinkNotFound)));
}
}));
}
});
}
}
}
if (requestId[0] != 0) {
final Runnable cancelRunnableFinal = cancelRunnable;
progressDialog.setOnCancelListener(dialog -> {
ConnectionsManager.getInstance(intentAccount).cancelRequest(requestId[0], true);
if (cancelRunnableFinal != null) {
cancelRunnableFinal.run();
}
});
try {
progressDialog.showDelayed(300);
} catch (Exception ignore) {
}
}
}
use of org.telegram.ui.ActionBar.Theme in project Telegram-FOSS by Telegram-FOSS-Team.
the class LaunchActivity method didReceivedNotification.
@Override
@SuppressWarnings("unchecked")
public void didReceivedNotification(int id, final int account, Object... args) {
if (id == NotificationCenter.appDidLogout) {
switchToAvailableAccountOrLogout();
} else if (id == NotificationCenter.closeOtherAppActivities) {
if (args[0] != this) {
onFinish();
finish();
}
} else if (id == NotificationCenter.didUpdateConnectionState) {
int state = ConnectionsManager.getInstance(account).getConnectionState();
if (currentConnectionState != state) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("switch to state " + state);
}
currentConnectionState = state;
updateCurrentConnectionState(account);
}
} else if (id == NotificationCenter.mainUserInfoChanged) {
drawerLayoutAdapter.notifyDataSetChanged();
} else if (id == NotificationCenter.needShowAlert) {
final Integer reason = (Integer) args[0];
if (reason == 6 || reason == 3 && proxyErrorDialog != null) {
return;
} else if (reason == 4) {
showTosActivity(account, (TLRPC.TL_help_termsOfService) args[1]);
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
if (reason != 2 && reason != 3) {
builder.setNegativeButton(LocaleController.getString("MoreInfo", R.string.MoreInfo), (dialogInterface, i) -> {
if (!mainFragmentsStack.isEmpty()) {
MessagesController.getInstance(account).openByUserName("spambot", mainFragmentsStack.get(mainFragmentsStack.size() - 1), 1);
}
});
}
if (reason == 5) {
builder.setMessage(LocaleController.getString("NobodyLikesSpam3", R.string.NobodyLikesSpam3));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
} else if (reason == 0) {
builder.setMessage(LocaleController.getString("NobodyLikesSpam1", R.string.NobodyLikesSpam1));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
} else if (reason == 1) {
builder.setMessage(LocaleController.getString("NobodyLikesSpam2", R.string.NobodyLikesSpam2));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
} else if (reason == 2) {
builder.setMessage((String) args[1]);
String type = (String) args[2];
if (type.startsWith("AUTH_KEY_DROP_")) {
builder.setPositiveButton(LocaleController.getString("Cancel", R.string.Cancel), null);
builder.setNegativeButton(LocaleController.getString("LogOut", R.string.LogOut), (dialog, which) -> MessagesController.getInstance(currentAccount).performLogout(2));
} else {
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
}
} else if (reason == 3) {
builder.setTitle(LocaleController.getString("Proxy", R.string.Proxy));
builder.setMessage(LocaleController.getString("UseProxyTelegramError", R.string.UseProxyTelegramError));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
proxyErrorDialog = showAlertDialog(builder);
return;
}
if (!mainFragmentsStack.isEmpty()) {
mainFragmentsStack.get(mainFragmentsStack.size() - 1).showDialog(builder.create());
}
} else if (id == NotificationCenter.wasUnableToFindCurrentLocation) {
final HashMap<String, MessageObject> waitingForLocation = (HashMap<String, MessageObject>) args[0];
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
builder.setNegativeButton(LocaleController.getString("ShareYouLocationUnableManually", R.string.ShareYouLocationUnableManually), (dialogInterface, i) -> {
if (mainFragmentsStack.isEmpty()) {
return;
}
BaseFragment lastFragment = mainFragmentsStack.get(mainFragmentsStack.size() - 1);
if (!AndroidUtilities.isGoogleMapsInstalled(lastFragment)) {
return;
}
LocationActivity fragment = new LocationActivity(0);
fragment.setDelegate((location, live, notify, scheduleDate) -> {
for (HashMap.Entry<String, MessageObject> entry : waitingForLocation.entrySet()) {
MessageObject messageObject = entry.getValue();
SendMessagesHelper.getInstance(account).sendMessage(location, messageObject.getDialogId(), messageObject, null, null, null, notify, scheduleDate);
}
});
presentFragment(fragment);
});
builder.setMessage(LocaleController.getString("ShareYouLocationUnable", R.string.ShareYouLocationUnable));
if (!mainFragmentsStack.isEmpty()) {
mainFragmentsStack.get(mainFragmentsStack.size() - 1).showDialog(builder.create());
}
} else if (id == NotificationCenter.didSetNewWallpapper) {
if (sideMenu != null) {
View child = sideMenu.getChildAt(0);
if (child != null) {
child.invalidate();
}
}
if (backgroundTablet != null) {
backgroundTablet.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion());
}
} else if (id == NotificationCenter.didSetPasscode) {
if (SharedConfig.passcodeHash.length() > 0 && !SharedConfig.allowScreenCapture) {
try {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
} catch (Exception e) {
FileLog.e(e);
}
} else if (!AndroidUtilities.hasFlagSecureFragment()) {
try {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
} catch (Exception e) {
FileLog.e(e);
}
}
} else if (id == NotificationCenter.reloadInterface) {
boolean last = mainFragmentsStack.size() > 1 && mainFragmentsStack.get(mainFragmentsStack.size() - 1) instanceof ProfileActivity;
if (last) {
ProfileActivity profileActivity = (ProfileActivity) mainFragmentsStack.get(mainFragmentsStack.size() - 1);
if (!profileActivity.isSettings()) {
last = false;
}
}
rebuildAllFragments(last);
} else if (id == NotificationCenter.suggestedLangpack) {
showLanguageAlert(false);
} else if (id == NotificationCenter.openArticle) {
if (mainFragmentsStack.isEmpty()) {
return;
}
ArticleViewer.getInstance().setParentActivity(this, mainFragmentsStack.get(mainFragmentsStack.size() - 1));
ArticleViewer.getInstance().open((TLRPC.TL_webPage) args[0], (String) args[1]);
} else if (id == NotificationCenter.hasNewContactsToImport) {
if (actionBarLayout == null || actionBarLayout.fragmentsStack.isEmpty()) {
return;
}
final int type = (Integer) args[0];
final HashMap<String, ContactsController.Contact> contactHashMap = (HashMap<String, ContactsController.Contact>) args[1];
final boolean first = (Boolean) args[2];
final boolean schedule = (Boolean) args[3];
BaseFragment fragment = actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1);
AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTitle(LocaleController.getString("UpdateContactsTitle", R.string.UpdateContactsTitle));
builder.setMessage(LocaleController.getString("UpdateContactsMessage", R.string.UpdateContactsMessage));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> ContactsController.getInstance(account).syncPhoneBookByAlert(contactHashMap, first, schedule, false));
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (dialog, which) -> ContactsController.getInstance(account).syncPhoneBookByAlert(contactHashMap, first, schedule, true));
builder.setOnBackButtonListener((dialogInterface, i) -> ContactsController.getInstance(account).syncPhoneBookByAlert(contactHashMap, first, schedule, true));
AlertDialog dialog = builder.create();
fragment.showDialog(dialog);
dialog.setCanceledOnTouchOutside(false);
} else if (id == NotificationCenter.didSetNewTheme) {
Boolean nightTheme = (Boolean) args[0];
if (!nightTheme) {
if (sideMenu != null) {
sideMenu.setBackgroundColor(Theme.getColor(Theme.key_chats_menuBackground));
sideMenu.setGlowColor(Theme.getColor(Theme.key_chats_menuBackground));
sideMenu.setListSelectorColor(Theme.getColor(Theme.key_listSelector));
sideMenu.getAdapter().notifyDataSetChanged();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
setTaskDescription(new ActivityManager.TaskDescription(null, null, Theme.getColor(Theme.key_actionBarDefault) | 0xff000000));
} catch (Exception ignore) {
}
}
}
drawerLayoutContainer.setBehindKeyboardColor(Theme.getColor(Theme.key_windowBackgroundWhite));
boolean checkNavigationBarColor = true;
if (args.length > 1) {
checkNavigationBarColor = (boolean) args[1];
}
checkSystemBarColors(true, checkNavigationBarColor);
} else if (id == NotificationCenter.needSetDayNightTheme) {
boolean instant = false;
if (Build.VERSION.SDK_INT >= 21 && args[2] != null) {
if (themeSwitchImageView.getVisibility() == View.VISIBLE) {
return;
}
try {
int[] pos = (int[]) args[2];
boolean toDark = (Boolean) args[4];
RLottieImageView darkThemeView = (RLottieImageView) args[5];
int w = drawerLayoutContainer.getMeasuredWidth();
int h = drawerLayoutContainer.getMeasuredHeight();
if (!toDark) {
darkThemeView.setVisibility(View.INVISIBLE);
}
Bitmap bitmap = Bitmap.createBitmap(drawerLayoutContainer.getMeasuredWidth(), drawerLayoutContainer.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
HashMap<View, Integer> viewLayerTypes = new HashMap<>();
invalidateCachedViews(drawerLayoutContainer);
drawerLayoutContainer.draw(canvas);
frameLayout.removeView(themeSwitchImageView);
if (toDark) {
frameLayout.addView(themeSwitchImageView, 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
themeSwitchSunView.setVisibility(View.GONE);
} else {
frameLayout.addView(themeSwitchImageView, 1, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
themeSwitchSunView.setTranslationX(pos[0] - AndroidUtilities.dp(14));
themeSwitchSunView.setTranslationY(pos[1] - AndroidUtilities.dp(14));
themeSwitchSunView.setVisibility(View.VISIBLE);
themeSwitchSunView.invalidate();
}
themeSwitchImageView.setImageBitmap(bitmap);
themeSwitchImageView.setVisibility(View.VISIBLE);
themeSwitchSunDrawable = darkThemeView.getAnimatedDrawable();
float finalRadius = (float) Math.max(Math.sqrt((w - pos[0]) * (w - pos[0]) + (h - pos[1]) * (h - pos[1])), Math.sqrt(pos[0] * pos[0] + (h - pos[1]) * (h - pos[1])));
float finalRadius2 = (float) Math.max(Math.sqrt((w - pos[0]) * (w - pos[0]) + pos[1] * pos[1]), Math.sqrt(pos[0] * pos[0] + pos[1] * pos[1]));
finalRadius = Math.max(finalRadius, finalRadius2);
Animator anim = ViewAnimationUtils.createCircularReveal(toDark ? drawerLayoutContainer : themeSwitchImageView, pos[0], pos[1], toDark ? 0 : finalRadius, toDark ? finalRadius : 0);
anim.setDuration(400);
anim.setInterpolator(Easings.easeInOutQuad);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
themeSwitchImageView.setImageDrawable(null);
themeSwitchImageView.setVisibility(View.GONE);
themeSwitchSunView.setVisibility(View.GONE);
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.themeAccentListUpdated);
if (!toDark) {
darkThemeView.setVisibility(View.VISIBLE);
}
DrawerProfileCell.switchingTheme = false;
}
});
anim.start();
instant = true;
} catch (Throwable e) {
FileLog.e(e);
try {
themeSwitchImageView.setImageDrawable(null);
frameLayout.removeView(themeSwitchImageView);
DrawerProfileCell.switchingTheme = false;
} catch (Exception e2) {
FileLog.e(e2);
}
}
} else {
DrawerProfileCell.switchingTheme = false;
}
Theme.ThemeInfo theme = (Theme.ThemeInfo) args[0];
boolean nigthTheme = (Boolean) args[1];
int accentId = (Integer) args[3];
actionBarLayout.animateThemedValues(theme, accentId, nigthTheme, instant);
if (AndroidUtilities.isTablet()) {
layersActionBarLayout.animateThemedValues(theme, accentId, nigthTheme, instant);
rightActionBarLayout.animateThemedValues(theme, accentId, nigthTheme, instant);
}
} else if (id == NotificationCenter.notificationsCountUpdated) {
if (sideMenu != null) {
Integer accountNum = (Integer) args[0];
int count = sideMenu.getChildCount();
for (int a = 0; a < count; a++) {
View child = sideMenu.getChildAt(a);
if (child instanceof DrawerUserCell) {
if (((DrawerUserCell) child).getAccountNumber() == accountNum) {
child.invalidate();
break;
}
}
}
}
} else if (id == NotificationCenter.fileLoaded) {
String path = (String) args[0];
if (SharedConfig.isAppUpdateAvailable()) {
String name = FileLoader.getAttachFileName(SharedConfig.pendingAppUpdate.document);
if (name.equals(path)) {
updateAppUpdateViews(true);
}
}
if (loadingThemeFileName != null) {
if (loadingThemeFileName.equals(path)) {
loadingThemeFileName = null;
File locFile = new File(ApplicationLoader.getFilesDirFixed(), "remote" + loadingTheme.id + ".attheme");
Theme.ThemeInfo themeInfo = Theme.fillThemeValues(locFile, loadingTheme.title, loadingTheme);
if (themeInfo != null) {
if (themeInfo.pathToWallpaper != null) {
File file = new File(themeInfo.pathToWallpaper);
if (!file.exists()) {
TLRPC.TL_account_getWallPaper req = new TLRPC.TL_account_getWallPaper();
TLRPC.TL_inputWallPaperSlug inputWallPaperSlug = new TLRPC.TL_inputWallPaperSlug();
inputWallPaperSlug.slug = themeInfo.slug;
req.wallpaper = inputWallPaperSlug;
ConnectionsManager.getInstance(themeInfo.account).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (response instanceof TLRPC.TL_wallPaper) {
TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) response;
loadingThemeInfo = themeInfo;
loadingThemeWallpaperName = FileLoader.getAttachFileName(wallPaper.document);
loadingThemeWallpaper = wallPaper;
FileLoader.getInstance(themeInfo.account).loadFile(wallPaper.document, wallPaper, 1, 1);
} else {
onThemeLoadFinish();
}
}));
return;
}
}
Theme.ThemeInfo finalThemeInfo = Theme.applyThemeFile(locFile, loadingTheme.title, loadingTheme, true);
if (finalThemeInfo != null) {
presentFragment(new ThemePreviewActivity(finalThemeInfo, true, ThemePreviewActivity.SCREEN_TYPE_PREVIEW, false, false));
}
}
onThemeLoadFinish();
}
} else if (loadingThemeWallpaperName != null) {
if (loadingThemeWallpaperName.equals(path)) {
loadingThemeWallpaperName = null;
File file = (File) args[1];
if (loadingThemeAccent) {
openThemeAccentPreview(loadingTheme, loadingThemeWallpaper, loadingThemeInfo);
onThemeLoadFinish();
} else {
Theme.ThemeInfo info = loadingThemeInfo;
Utilities.globalQueue.postRunnable(() -> {
info.createBackground(file, info.pathToWallpaper);
AndroidUtilities.runOnUIThread(() -> {
if (loadingTheme == null) {
return;
}
File locFile = new File(ApplicationLoader.getFilesDirFixed(), "remote" + loadingTheme.id + ".attheme");
Theme.ThemeInfo finalThemeInfo = Theme.applyThemeFile(locFile, loadingTheme.title, loadingTheme, true);
if (finalThemeInfo != null) {
presentFragment(new ThemePreviewActivity(finalThemeInfo, true, ThemePreviewActivity.SCREEN_TYPE_PREVIEW, false, false));
}
onThemeLoadFinish();
});
});
}
}
}
} else if (id == NotificationCenter.fileLoadFailed) {
String path = (String) args[0];
if (path.equals(loadingThemeFileName) || path.equals(loadingThemeWallpaperName)) {
onThemeLoadFinish();
}
if (SharedConfig.isAppUpdateAvailable()) {
String name = FileLoader.getAttachFileName(SharedConfig.pendingAppUpdate.document);
if (name.equals(path)) {
updateAppUpdateViews(true);
}
}
} else if (id == NotificationCenter.screenStateChanged) {
if (ApplicationLoader.mainInterfacePaused) {
return;
}
if (ApplicationLoader.isScreenOn) {
onPasscodeResume();
} else {
onPasscodePause();
}
} else if (id == NotificationCenter.needCheckSystemBarColors) {
checkSystemBarColors();
} else if (id == NotificationCenter.historyImportProgressChanged) {
if (args.length > 1 && !mainFragmentsStack.isEmpty()) {
AlertsCreator.processError(currentAccount, (TLRPC.TL_error) args[2], mainFragmentsStack.get(mainFragmentsStack.size() - 1), (TLObject) args[1]);
}
} else if (id == NotificationCenter.stickersImportComplete) {
MediaDataController.getInstance(account).toggleStickerSet(this, (TLObject) args[0], 2, !mainFragmentsStack.isEmpty() ? mainFragmentsStack.get(mainFragmentsStack.size() - 1) : null, false, true);
} else if (id == NotificationCenter.newSuggestionsAvailable) {
sideMenu.invalidateViews();
} else if (id == NotificationCenter.showBulletin) {
if (!mainFragmentsStack.isEmpty()) {
int type = (int) args[0];
FrameLayout container = null;
BaseFragment fragment = null;
if (GroupCallActivity.groupCallUiVisible && GroupCallActivity.groupCallInstance != null) {
container = GroupCallActivity.groupCallInstance.getContainer();
}
if (container == null) {
fragment = mainFragmentsStack.get(mainFragmentsStack.size() - 1);
}
if (type == Bulletin.TYPE_NAME_CHANGED) {
long peerId = (long) args[1];
String text = peerId > 0 ? LocaleController.getString("YourNameChanged", R.string.YourNameChanged) : LocaleController.getString("CannelTitleChanged", R.string.ChannelTitleChanged);
(container != null ? BulletinFactory.of(container, null) : BulletinFactory.of(fragment)).createErrorBulletin(text).show();
} else if (type == Bulletin.TYPE_BIO_CHANGED) {
long peerId = (long) args[1];
String text = peerId > 0 ? LocaleController.getString("YourBioChanged", R.string.YourBioChanged) : LocaleController.getString("CannelDescriptionChanged", R.string.ChannelDescriptionChanged);
(container != null ? BulletinFactory.of(container, null) : BulletinFactory.of(fragment)).createErrorBulletin(text).show();
} else if (type == Bulletin.TYPE_STICKER) {
TLRPC.Document sticker = (TLRPC.Document) args[1];
StickerSetBulletinLayout layout = new StickerSetBulletinLayout(this, null, (int) args[2], sticker, null);
if (fragment != null) {
Bulletin.make(fragment, layout, Bulletin.DURATION_SHORT).show();
} else {
Bulletin.make(container, layout, Bulletin.DURATION_SHORT).show();
}
} else if (type == Bulletin.TYPE_ERROR) {
if (fragment != null) {
BulletinFactory.of(fragment).createErrorBulletin((String) args[1]).show();
} else {
BulletinFactory.of(container, null).createErrorBulletin((String) args[1]).show();
}
}
}
} else if (id == NotificationCenter.groupCallUpdated) {
checkWasMutedByAdmin(false);
} else if (id == NotificationCenter.fileLoadProgressChanged) {
if (updateTextView != null && SharedConfig.isAppUpdateAvailable()) {
String location = (String) args[0];
String fileName = FileLoader.getAttachFileName(SharedConfig.pendingAppUpdate.document);
if (fileName != null && fileName.equals(location)) {
Long loadedSize = (Long) args[1];
Long totalSize = (Long) args[2];
float loadProgress = loadedSize / (float) totalSize;
updateLayoutIcon.setProgress(loadProgress, true);
updateTextView.setText(LocaleController.formatString("AppUpdateDownloading", R.string.AppUpdateDownloading, (int) (loadProgress * 100)));
}
}
} else if (id == NotificationCenter.appUpdateAvailable) {
updateAppUpdateViews(mainFragmentsStack.size() == 1);
}
}
use of org.telegram.ui.ActionBar.Theme in project Telegram-FOSS by Telegram-FOSS-Team.
the class ThemeSmallPreviewView method setItem.
public void setItem(ChatThemeBottomSheet.ChatThemeItem item, boolean animated) {
boolean itemChanged = chatThemeItem != item;
boolean darkModeChanged = lastThemeIndex != item.themeIndex;
lastThemeIndex = item.themeIndex;
this.chatThemeItem = item;
hasAnimatedEmoji = false;
TLRPC.Document document = null;
if (item.chatTheme.getEmoticon() != null) {
document = MediaDataController.getInstance(currentAccount).getEmojiAnimatedSticker(item.chatTheme.getEmoticon());
}
if (itemChanged) {
if (animationCancelRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(animationCancelRunnable);
animationCancelRunnable = null;
}
backupImageView.animate().cancel();
backupImageView.setScaleX(1f);
backupImageView.setScaleY(1f);
}
if (itemChanged) {
Drawable thumb = null;
if (document != null) {
thumb = DocumentObject.getSvgThumb(document, Theme.key_emptyListPlaceholder, 0.2f);
}
if (thumb == null) {
Emoji.preloadEmoji(item.chatTheme.getEmoticon());
thumb = Emoji.getEmojiDrawable(item.chatTheme.getEmoticon());
}
backupImageView.setImage(ImageLocation.getForDocument(document), "50_50", thumb, null);
}
if (itemChanged || darkModeChanged) {
if (animated) {
changeThemeProgress = 0f;
animateOutThemeDrawable = themeDrawable;
themeDrawable = new ThemeDrawable();
invalidate();
} else {
changeThemeProgress = 1f;
}
updatePreviewBackground(themeDrawable);
TLRPC.TL_theme theme = item.chatTheme.getTlTheme(lastThemeIndex);
if (theme != null) {
final long themeId = theme.id;
TLRPC.WallPaper wallPaper = item.chatTheme.getWallpaper(lastThemeIndex);
if (wallPaper != null) {
final int intensity = wallPaper.settings.intensity;
item.chatTheme.loadWallpaperThumb(lastThemeIndex, result -> {
if (result != null && result.first == themeId) {
if (item.previewDrawable instanceof MotionBackgroundDrawable) {
MotionBackgroundDrawable motionBackgroundDrawable = (MotionBackgroundDrawable) item.previewDrawable;
motionBackgroundDrawable.setPatternBitmap(intensity >= 0 ? 100 : -100, result.second);
motionBackgroundDrawable.setPatternColorFilter(patternColor);
}
invalidate();
}
});
}
} else {
Theme.ThemeInfo themeInfo = item.chatTheme.getThemeInfo(lastThemeIndex);
Theme.ThemeAccent accent = null;
if (themeInfo.themeAccentsMap != null) {
accent = themeInfo.themeAccentsMap.get(item.chatTheme.getAccentId(lastThemeIndex));
}
if (accent != null && accent.info != null && accent.info.settings.size() > 0) {
TLRPC.WallPaper wallPaper = accent.info.settings.get(0).wallpaper;
if (wallPaper != null && wallPaper.document != null) {
TLRPC.Document wallpaperDocument = wallPaper.document;
final TLRPC.PhotoSize thumbSize = FileLoader.getClosestPhotoSizeWithSize(wallpaperDocument.thumbs, 120);
ImageLocation imageLocation = ImageLocation.getForDocument(thumbSize, wallpaperDocument);
ImageReceiver imageReceiver = new ImageReceiver();
imageReceiver.setImage(imageLocation, "120_80", null, null, null, 1);
imageReceiver.setDelegate((receiver, set, thumb, memCache) -> {
ImageReceiver.BitmapHolder holder = receiver.getBitmapSafe();
if (!set || holder == null) {
return;
}
Bitmap resultBitmap = holder.bitmap;
if (resultBitmap != null) {
if (item.previewDrawable instanceof MotionBackgroundDrawable) {
MotionBackgroundDrawable motionBackgroundDrawable = (MotionBackgroundDrawable) item.previewDrawable;
motionBackgroundDrawable.setPatternBitmap(wallPaper.settings == null || wallPaper.settings.intensity >= 0 ? 100 : -100, resultBitmap);
motionBackgroundDrawable.setPatternColorFilter(patternColor);
invalidate();
}
}
});
ImageLoader.getInstance().loadImageForImageReceiver(imageReceiver);
}
} else if (accent != null && accent.info == null) {
ChatThemeController.chatThemeQueue.postRunnable(() -> {
Bitmap bitmap = SvgHelper.getBitmap(R.raw.default_pattern, AndroidUtilities.dp(80), AndroidUtilities.dp(120), Color.BLACK, 3f);
AndroidUtilities.runOnUIThread(() -> {
if (item.previewDrawable instanceof MotionBackgroundDrawable) {
MotionBackgroundDrawable motionBackgroundDrawable = (MotionBackgroundDrawable) item.previewDrawable;
motionBackgroundDrawable.setPatternBitmap(100, bitmap);
motionBackgroundDrawable.setPatternColorFilter(patternColor);
invalidate();
}
});
});
}
}
}
if (!animated) {
backupImageView.animate().cancel();
;
backupImageView.setScaleX(1f);
backupImageView.setScaleY(1f);
AndroidUtilities.cancelRunOnUIThread(animationCancelRunnable);
if (backupImageView.getImageReceiver().getLottieAnimation() != null) {
backupImageView.getImageReceiver().getLottieAnimation().stop();
backupImageView.getImageReceiver().getLottieAnimation().setCurrentFrame(0, false);
}
}
}
use of org.telegram.ui.ActionBar.Theme in project Telegram-FOSS by Telegram-FOSS-Team.
the class ChatActivity method didReceivedNotification.
@Override
public void didReceivedNotification(int id, int account, final Object... args) {
if (id == NotificationCenter.messagesDidLoad) {
int guid = (Integer) args[10];
if (guid != classGuid) {
return;
}
int queryLoadIndex = (Integer) args[11];
boolean doNotRemoveLoadIndex;
if (queryLoadIndex < 0) {
doNotRemoveLoadIndex = true;
queryLoadIndex = -queryLoadIndex;
} else {
doNotRemoveLoadIndex = false;
}
if (!doNotRemoveLoadIndex && !fragmentBeginToShow && !paused) {
int[] alowedNotifications = new int[] { NotificationCenter.messagesDidLoad, NotificationCenter.chatInfoDidLoad, NotificationCenter.groupCallUpdated, NotificationCenter.dialogsNeedReload, NotificationCenter.scheduledMessagesUpdated, NotificationCenter.closeChats, NotificationCenter.botKeyboardDidLoad, NotificationCenter.userInfoDidLoad, NotificationCenter.pinnedInfoDidLoad, NotificationCenter.needDeleteDialog /*, NotificationCenter.botInfoDidLoad*/
};
if (transitionAnimationIndex == 0) {
transitionAnimationIndex = getNotificationCenter().setAnimationInProgress(transitionAnimationIndex, alowedNotifications);
AndroidUtilities.runOnUIThread(() -> getNotificationCenter().onAnimationFinish(transitionAnimationIndex), 800);
} else {
getNotificationCenter().updateAllowedNotifications(transitionAnimationIndex, alowedNotifications);
}
}
int index = waitingForLoad.indexOf(queryLoadIndex);
long currentUserId = getUserConfig().getClientUserId();
int mode = (Integer) args[14];
boolean isCache = (Boolean) args[3];
boolean postponedScroll = postponedScrollToLastMessageQueryIndex > 0 && queryLoadIndex == postponedScrollToLastMessageQueryIndex;
if (postponedScroll) {
postponedScrollToLastMessageQueryIndex = 0;
}
if (index == -1) {
if (chatMode == MODE_SCHEDULED && mode == MODE_SCHEDULED && !isCache) {
waitingForReplyMessageLoad = true;
waitingForLoad.add(lastLoadIndex);
getMessagesController().loadMessages(dialog_id, mergeDialogId, false, AndroidUtilities.isTablet() ? 30 : 20, 0, 0, true, 0, classGuid, 2, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++);
}
return;
} else if (!doNotRemoveLoadIndex) {
waitingForLoad.remove(index);
}
ArrayList<MessageObject> messArr = (ArrayList<MessageObject>) args[2];
if (messages.isEmpty() && messArr.size() == 1 && MessageObject.isSystemSignUp(messArr.get(0))) {
forceHistoryEmpty = true;
endReached[0] = endReached[1] = true;
forwardEndReached[0] = forwardEndReached[1] = true;
firstLoading = false;
showProgressView(false);
if (chatListView != null) {
if (!fragmentOpened) {
chatListView.setAnimateEmptyView(false, 1);
chatListView.setEmptyView(emptyViewContainer);
chatListView.setAnimateEmptyView(true, 1);
} else {
chatListView.setEmptyView(emptyViewContainer);
}
chatAdapter.notifyDataSetChanged(true);
}
resumeDelayedFragmentAnimation();
MessageObject messageObject = messArr.get(0);
getMessagesController().markDialogAsRead(dialog_id, messageObject.getId(), messageObject.getId(), messageObject.messageOwner.date, false, 0, 0, true, 0);
AndroidUtilities.cancelRunOnUIThread(fragmentTransitionRunnable);
fragmentTransitionRunnable.run();
return;
}
if (chatMode != mode) {
if (chatMode != MODE_SCHEDULED) {
scheduledMessagesCount = messArr.size();
updateScheduledInterface(true);
}
return;
}
boolean createUnreadLoading = false;
boolean showDateAfter = waitingForReplyMessageLoad;
if (waitingForReplyMessageLoad) {
if (chatMode != MODE_SCHEDULED && !createUnreadMessageAfterIdLoading) {
boolean found = false;
for (int a = 0; a < messArr.size(); a++) {
MessageObject obj = messArr.get(a);
if (obj.getId() == startLoadFromMessageId) {
found = true;
break;
}
if (a + 1 < messArr.size()) {
MessageObject obj2 = messArr.get(a + 1);
if (obj.getId() >= startLoadFromMessageId && obj2.getId() < startLoadFromMessageId) {
startLoadFromMessageId = obj.getId();
found = true;
break;
}
}
}
if (!found) {
startLoadFromMessageId = 0;
return;
}
}
int startLoadFrom = startLoadFromMessageId;
boolean needSelect = needSelectFromMessageId;
int unreadAfterId = createUnreadMessageAfterId;
createUnreadLoading = createUnreadMessageAfterIdLoading;
clearChatData();
if (chatMode == 0) {
createUnreadMessageAfterId = unreadAfterId;
startLoadFromMessageId = startLoadFrom;
needSelectFromMessageId = needSelect;
}
}
loadsCount++;
long did = (Long) args[0];
int loadIndex = did == dialog_id ? 0 : 1;
int count = (Integer) args[1];
int fnid = (Integer) args[4];
int last_unread_date = (Integer) args[7];
int load_type = (Integer) args[8];
boolean isEnd = (Boolean) args[9];
int loaded_max_id = (Integer) args[12];
int loaded_mentions_count = chatWasReset ? 0 : (Integer) args[13];
if (loaded_mentions_count < 0) {
loaded_mentions_count *= -1;
hasAllMentionsLocal = false;
} else if (first) {
hasAllMentionsLocal = true;
}
if (load_type == 4) {
startLoadFromMessageId = loaded_max_id;
for (int a = messArr.size() - 1; a > 0; a--) {
MessageObject obj = messArr.get(a);
if (obj.type < 0 && obj.getId() == startLoadFromMessageId) {
startLoadFromMessageId = messArr.get(a - 1).getId();
break;
}
}
}
if (postponedScroll) {
if (load_type == 0 && isCache && messArr.size() < count) {
postponedScrollToLastMessageQueryIndex = lastLoadIndex;
waitingForLoad.add(lastLoadIndex);
getMessagesController().loadMessages(dialog_id, mergeDialogId, false, count, 0, 0, false, 0, classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++);
return;
}
if (load_type == 4) {
postponedScrollMessageId = startLoadFromMessageId;
}
if (progressDialog != null) {
progressDialog.dismiss();
}
showPinnedProgress(false);
if (postponedScrollIsCanceled) {
return;
}
if (postponedScrollMessageId == 0) {
clearChatData();
} else {
if (showScrollToMessageError) {
boolean found = false;
for (int k = 0; k < messArr.size(); k++) {
if (messArr.get(k).getId() == postponedScrollMessageId) {
found = true;
break;
}
}
if (!found) {
if (isThreadChat()) {
Bundle bundle = new Bundle();
if (currentEncryptedChat != null) {
bundle.putInt("enc_id", currentEncryptedChat.id);
} else if (currentChat != null) {
bundle.putLong("chat_id", currentChat.id);
} else {
bundle.putLong("user_id", currentUser.id);
}
bundle.putInt("message_id", postponedScrollMessageId);
presentFragment(new ChatActivity(bundle), true);
} else {
BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("MessageNotFound", R.string.MessageNotFound), themeDelegate).show();
}
return;
}
showScrollToMessageError = false;
}
int startLoadFrom = startLoadFromMessageId;
boolean needSelect = needSelectFromMessageId;
int unreadAfterId = createUnreadMessageAfterId;
createUnreadLoading = createUnreadMessageAfterIdLoading;
clearChatData();
if (chatMode == 0) {
createUnreadMessageAfterId = unreadAfterId;
startLoadFromMessageId = startLoadFrom;
needSelectFromMessageId = needSelect;
}
}
}
if (chatListItemAnimator != null) {
chatListItemAnimator.setShouldAnimateEnterFromBottom(false);
}
int unread_to_load = 0;
if (fnid != 0) {
if (!chatWasReset) {
last_message_id = (Integer) args[5];
}
if (load_type == 3) {
if (loadingFromOldPosition) {
if (!chatWasReset) {
unread_to_load = (Integer) args[6];
if (unread_to_load != 0) {
createUnreadMessageAfterId = fnid;
}
}
loadingFromOldPosition = false;
}
first_unread_id = 0;
} else {
first_unread_id = fnid;
if (!chatWasReset) {
unread_to_load = (Integer) args[6];
}
}
} else if (!chatWasReset && startLoadFromMessageId != 0 && (load_type == 3 || load_type == 4)) {
last_message_id = (Integer) args[5];
}
if (isThreadChat() && threadUnreadMessagesCount != 0) {
unread_to_load = threadUnreadMessagesCount;
threadUnreadMessagesCount = 0;
}
int newRowsCount = 0;
if (load_type != 0 && (isThreadChat() && first_unread_id != 0 || startLoadFromMessageId != 0 || last_message_id != 0)) {
forwardEndReached[loadIndex] = false;
hideForwardEndReached = false;
}
if ((load_type == 1 || load_type == 3) && loadIndex == 1) {
endReached[0] = cacheEndReached[0] = true;
forwardEndReached[0] = false;
hideForwardEndReached = false;
minMessageId[0] = 0;
}
if (chatMode == MODE_SCHEDULED) {
endReached[0] = cacheEndReached[0] = true;
forwardEndReached[0] = forwardEndReached[0] = true;
}
if (ChatObject.isChannel(currentChat) && !getMessagesController().dialogs_dict.containsKey(dialog_id) && load_type == 2 && isCache && loadIndex == 0) {
forwardEndReached[0] = false;
hideForwardEndReached = true;
}
if (loadsCount == 1 && messArr.size() > 20) {
loadsCount++;
}
boolean isFirstLoading = firstLoading;
if (firstLoading) {
if (!forwardEndReached[loadIndex]) {
messages.clear();
messagesByDays.clear();
groupedMessagesMap.clear();
threadMessageAdded = false;
for (int a = 0; a < 2; a++) {
messagesDict[a].clear();
if (currentEncryptedChat == null) {
maxMessageId[a] = Integer.MAX_VALUE;
minMessageId[a] = Integer.MIN_VALUE;
} else {
maxMessageId[a] = Integer.MIN_VALUE;
minMessageId[a] = Integer.MAX_VALUE;
}
maxDate[a] = Integer.MIN_VALUE;
minDate[a] = 0;
}
}
firstLoading = false;
AndroidUtilities.runOnUIThread(() -> {
getNotificationCenter().runDelayedNotifications();
resumeDelayedFragmentAnimation();
AndroidUtilities.cancelRunOnUIThread(fragmentTransitionRunnable);
fragmentTransitionRunnable.run();
});
}
if (isThreadChat() && (load_type == 2 || load_type == 3) && !isCache) {
if (load_type == 3 && scrollToThreadMessage) {
startLoadFromMessageId = threadMessageId;
}
int beforMax = 0;
int afterMax = 0;
boolean hasMaxId = false;
for (int a = 0, N = messArr.size(); a < N; a++) {
MessageObject message = messArr.get(a);
int mid = message.getId();
if (mid == loaded_max_id) {
hasMaxId = true;
}
if (mid > loaded_max_id) {
afterMax++;
} else {
beforMax++;
}
}
int num;
if (load_type == 2) {
num = 10;
} else {
num = count / 2;
}
if (hasMaxId) {
num++;
}
if (beforMax < num) {
endReached[0] = true;
}
if (!chatWasReset && afterMax < count - num) {
forwardEndReached[0] = true;
}
}
if (chatMode == MODE_PINNED) {
endReached[loadIndex] = true;
}
if (load_type == 0 && forwardEndReached[0] && !pendingSendMessages.isEmpty()) {
for (int a = 0, N = messArr.size(); a < N; a++) {
MessageObject existing = pendingSendMessagesDict.get(messArr.get(a).getId());
if (existing != null) {
pendingSendMessagesDict.remove(existing.getId());
pendingSendMessages.remove(existing);
}
}
if (!pendingSendMessages.isEmpty()) {
int pasteIndex = 0;
int date = pendingSendMessages.get(0).messageOwner.date;
if (!messArr.isEmpty()) {
if (date >= messArr.get(0).messageOwner.date) {
pasteIndex = 0;
} else if (date <= messArr.get(messArr.size() - 1).messageOwner.date) {
pasteIndex = messArr.size();
} else {
for (int a = 0, N = messArr.size(); a < N - 1; a++) {
if (messArr.get(a).messageOwner.date >= date && messArr.get(a + 1).messageOwner.date <= date) {
pasteIndex = a + 1;
}
}
}
}
messArr = new ArrayList<>(messArr);
messArr.addAll(pasteIndex, pendingSendMessages);
pendingSendMessages.clear();
pendingSendMessagesDict.clear();
}
}
if (!threadMessageAdded && isThreadChat() && (load_type == 0 && messArr.size() < count || (load_type == 2 || load_type == 3) && endReached[0])) {
TLRPC.Message msg = new TLRPC.TL_message();
if (threadMessageObject.getRepliesCount() == 0) {
if (isComments) {
msg.message = LocaleController.getString("NoComments", R.string.NoComments);
} else {
msg.message = LocaleController.getString("NoReplies", R.string.NoReplies);
}
} else {
msg.message = LocaleController.getString("DiscussionStarted", R.string.DiscussionStarted);
}
msg.id = 0;
msg.date = threadMessageObject.messageOwner.date;
replyMessageHeaderObject = new MessageObject(currentAccount, msg, false, false);
replyMessageHeaderObject.type = 10;
replyMessageHeaderObject.contentType = 1;
replyMessageHeaderObject.isDateObject = true;
replyMessageHeaderObject.stableId = lastStableId++;
messArr.add(replyMessageHeaderObject);
updateReplyMessageHeader(false);
messArr.addAll(threadMessageObjects);
count += 2;
threadMessageAdded = true;
}
if (load_type == 1) {
Collections.reverse(messArr);
}
if (currentEncryptedChat == null) {
getMediaDataController().loadReplyMessagesForMessages(messArr, dialog_id, chatMode == MODE_SCHEDULED, null);
}
int approximateHeightSum = 0;
if (!chatWasReset && (load_type == 2 || load_type == 1) && messArr.isEmpty() && !isCache) {
forwardEndReached[0] = true;
}
LongSparseArray<MessageObject.GroupedMessages> newGroups = null;
LongSparseArray<MessageObject.GroupedMessages> changedGroups = null;
MediaController mediaController = MediaController.getInstance();
TLRPC.MessageAction dropPhotoAction = null;
boolean createdWas = false;
boolean moveCurrentDateObject = false;
boolean scrolledToUnread = false;
for (int a = 0, N = messArr.size(); a < N; a++) {
MessageObject obj = messArr.get(N - a - 1);
TLRPC.MessageAction action = obj.messageOwner.action;
if (a == 0 && action instanceof TLRPC.TL_messageActionChatCreate) {
createdWas = true;
} else if (!createdWas) {
break;
} else if (a < 2 && action instanceof TLRPC.TL_messageActionChatEditPhoto) {
dropPhotoAction = action;
}
}
for (int a = 0; a < messArr.size(); a++) {
MessageObject obj = messArr.get(a);
if (obj.replyMessageObject != null) {
repliesMessagesDict.put(obj.replyMessageObject.getId(), obj.replyMessageObject);
addReplyMessageOwner(obj, 0);
}
int messageId = obj.getId();
if (threadMessageId != 0) {
if (messageId <= (obj.isOut() ? threadMaxOutboxReadId : threadMaxInboxReadId)) {
obj.setIsRead();
}
}
approximateHeightSum += obj.getApproximateHeight();
if (currentUser != null) {
if (currentUser.self) {
obj.messageOwner.out = true;
}
if (chatMode != MODE_SCHEDULED && (currentUser.bot && obj.isOut() || currentUser.id == currentUserId)) {
obj.setIsRead();
}
}
if (messagesDict[loadIndex].indexOfKey(messageId) >= 0) {
continue;
}
if (threadMessageId != 0 && obj.messageOwner instanceof TLRPC.TL_messageEmpty) {
continue;
}
if (currentEncryptedChat != null && obj.messageOwner.stickerVerified == 0) {
getMediaDataController().verifyAnimatedStickerMessage(obj.messageOwner);
}
addToPolls(obj, null);
if (isSecretChat()) {
checkSecretMessageForLocation(obj);
}
if (mediaController.isPlayingMessage(obj)) {
MessageObject player = mediaController.getPlayingMessageObject();
obj.audioProgress = player.audioProgress;
obj.audioProgressSec = player.audioProgressSec;
obj.audioPlayerDuration = player.audioPlayerDuration;
}
if (loadIndex == 0 && ChatObject.isChannel(currentChat) && messageId == 1) {
endReached[loadIndex] = true;
cacheEndReached[loadIndex] = true;
}
if (messageId > 0) {
maxMessageId[loadIndex] = Math.min(messageId, maxMessageId[loadIndex]);
minMessageId[loadIndex] = Math.max(messageId, minMessageId[loadIndex]);
} else if (currentEncryptedChat != null) {
maxMessageId[loadIndex] = Math.max(messageId, maxMessageId[loadIndex]);
minMessageId[loadIndex] = Math.min(messageId, minMessageId[loadIndex]);
}
if (obj.messageOwner.date != 0) {
maxDate[loadIndex] = Math.max(maxDate[loadIndex], obj.messageOwner.date);
if (minDate[loadIndex] == 0 || obj.messageOwner.date < minDate[loadIndex]) {
minDate[loadIndex] = obj.messageOwner.date;
}
}
if (!chatWasReset && messageId != 0 && messageId == last_message_id) {
forwardEndReached[loadIndex] = true;
}
TLRPC.MessageAction action = obj.messageOwner.action;
if (obj.type < 0 || loadIndex == 1 && action instanceof TLRPC.TL_messageActionChatMigrateTo) {
continue;
}
if (currentChat != null && currentChat.creator && (action instanceof TLRPC.TL_messageActionChatCreate || dropPhotoAction != null && action == dropPhotoAction)) {
continue;
}
if (obj.messageOwner.action instanceof TLRPC.TL_messageActionChannelMigrateFrom) {
continue;
}
if (needAnimateToMessage != null && needAnimateToMessage.getId() == messageId && messageId < 0 && chatMode != MODE_SCHEDULED) {
obj = needAnimateToMessage;
animatingMessageObjects.add(obj);
needAnimateToMessage = null;
}
messagesDict[loadIndex].put(messageId, obj);
ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey);
if (dayArray == null) {
dayArray = new ArrayList<>();
messagesByDays.put(obj.dateKey, dayArray);
TLRPC.Message dateMsg = new TLRPC.TL_message();
if (chatMode == MODE_SCHEDULED) {
if (obj.messageOwner.date == 0x7ffffffe) {
dateMsg.message = LocaleController.getString("MessageScheduledUntilOnline", R.string.MessageScheduledUntilOnline);
} else {
dateMsg.message = LocaleController.formatString("MessageScheduledOn", R.string.MessageScheduledOn, LocaleController.formatDateChat(obj.messageOwner.date, true));
}
} else {
dateMsg.message = LocaleController.formatDateChat(obj.messageOwner.date);
}
dateMsg.id = 0;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(((long) obj.messageOwner.date) * 1000);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
dateMsg.date = (int) (calendar.getTimeInMillis() / 1000);
MessageObject dateObj = new MessageObject(currentAccount, dateMsg, false, false);
dateObj.type = 10;
dateObj.contentType = 1;
dateObj.isDateObject = true;
dateObj.stableId = lastStableId++;
if (load_type == 1) {
messages.add(0, dateObj);
} else {
messages.add(dateObj);
}
newRowsCount++;
} else {
if (!moveCurrentDateObject && !messages.isEmpty() && messages.get(messages.size() - 1).isDateObject) {
messages.get(messages.size() - 1).stableId = lastStableId++;
moveCurrentDateObject = true;
}
}
if (obj.hasValidGroupId()) {
MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(obj.getGroupIdForUse());
if (groupedMessages != null) {
if (messages.size() > 1) {
MessageObject previous;
if (load_type == 1) {
previous = messages.get(0);
} else {
previous = messages.get(messages.size() - 2);
}
if (previous.getGroupIdForUse() == obj.getGroupIdForUse()) {
if (previous.localGroupId != 0) {
obj.localGroupId = previous.localGroupId;
groupedMessages = groupedMessagesMap.get(previous.localGroupId);
}
} else if (previous.getGroupIdForUse() != obj.getGroupIdForUse()) {
obj.localGroupId = Utilities.random.nextLong();
groupedMessages = null;
}
}
}
if (groupedMessages == null) {
groupedMessages = new MessageObject.GroupedMessages();
groupedMessages.groupId = obj.getGroupId();
groupedMessagesMap.put(groupedMessages.groupId, groupedMessages);
} else if (newGroups == null || newGroups.indexOfKey(obj.getGroupId()) < 0) {
if (changedGroups == null) {
changedGroups = new LongSparseArray<>();
}
changedGroups.put(obj.getGroupId(), groupedMessages);
}
if (newGroups == null) {
newGroups = new LongSparseArray<>();
}
newGroups.put(groupedMessages.groupId, groupedMessages);
if (load_type == 1) {
groupedMessages.messages.add(obj);
} else {
groupedMessages.messages.add(0, obj);
}
} else if (obj.getGroupIdForUse() != 0) {
obj.messageOwner.grouped_id = 0;
obj.localSentGroupId = 0;
}
newRowsCount++;
dayArray.add(obj);
obj.stableId = lastStableId++;
if (load_type == 1) {
messages.add(0, obj);
} else {
messages.get(messages.size() - 1).stableId = lastStableId++;
messages.add(messages.size() - 1, obj);
}
MessageObject prevObj;
if (currentEncryptedChat == null) {
if (createUnreadMessageAfterId != 0 && load_type != 1 && a + 1 < messArr.size()) {
prevObj = messArr.get(a + 1);
if (obj.isOut() && !obj.messageOwner.from_scheduled || prevObj.getId() >= createUnreadMessageAfterId) {
prevObj = null;
}
} else {
prevObj = null;
}
} else {
if (createUnreadMessageAfterId != 0 && load_type != 1 && a - 1 >= 0) {
prevObj = messArr.get(a - 1);
if (obj.isOut() && !obj.messageOwner.from_scheduled || prevObj.getId() >= createUnreadMessageAfterId) {
prevObj = null;
}
} else {
prevObj = null;
}
}
if (load_type == 2 && messageId != 0 && messageId == first_unread_id) {
if ((approximateHeightSum > AndroidUtilities.displaySize.y / 2 || isThreadChat()) || !forwardEndReached[0]) {
if (!isThreadChat() || threadMaxInboxReadId != 0) {
TLRPC.Message dateMsg = new TLRPC.TL_message();
dateMsg.message = "";
dateMsg.id = 0;
MessageObject dateObj = new MessageObject(currentAccount, dateMsg, false, false);
dateObj.type = 6;
dateObj.contentType = 2;
dateObj.stableId = lastStableId++;
messages.add(messages.size() - 1, dateObj);
unreadMessageObject = dateObj;
scrollToMessage = unreadMessageObject;
} else {
scrollToMessage = obj;
}
scrollToMessagePosition = -10000;
scrolledToUnread = true;
newRowsCount++;
}
} else if ((load_type == 3 || load_type == 4) && (startLoadFromMessageId < 0 && messageId == startLoadFromMessageId || startLoadFromMessageId > 0 && messageId > 0 && messageId <= startLoadFromMessageId)) {
removeSelectedMessageHighlight();
if (needSelectFromMessageId && messageId == startLoadFromMessageId) {
highlightMessageId = messageId;
}
if (showScrollToMessageError && messageId != startLoadFromMessageId) {
BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("MessageNotFound", R.string.MessageNotFound), themeDelegate).show();
}
scrollToMessage = obj;
if (postponedScroll) {
postponedScrollMessageId = scrollToMessage.getId();
}
startLoadFromMessageId = 0;
if (scrollToMessagePosition == -10000) {
scrollToMessagePosition = -9000;
}
}
if (load_type != 2 && unreadMessageObject == null && createUnreadMessageAfterId != 0 && (currentEncryptedChat == null && (!obj.isOut() || obj.messageOwner.from_scheduled) && messageId >= createUnreadMessageAfterId || currentEncryptedChat != null && (!obj.isOut() || obj.messageOwner.from_scheduled) && messageId <= createUnreadMessageAfterId) && (load_type == 1 || prevObj != null || prevObj == null && createUnreadLoading && a == messArr.size() - 1)) {
TLRPC.Message dateMsg = new TLRPC.TL_message();
dateMsg.message = "";
dateMsg.id = 0;
MessageObject dateObj = new MessageObject(currentAccount, dateMsg, false, false);
dateObj.type = 6;
dateObj.contentType = 2;
dateObj.stableId = lastStableId++;
if (load_type == 1) {
messages.add(1, dateObj);
} else {
messages.add(messages.size() - 1, dateObj);
}
unreadMessageObject = dateObj;
if (load_type == 3) {
scrollToMessage = unreadMessageObject;
startLoadFromMessageId = 0;
scrollToMessagePosition = -9000;
}
newRowsCount++;
}
}
if (createUnreadLoading) {
createUnreadMessageAfterId = 0;
}
if (load_type == 0 && newRowsCount == 0) {
loadsCount--;
}
if (forwardEndReached[loadIndex] && loadIndex != 1) {
first_unread_id = 0;
last_message_id = 0;
createUnreadMessageAfterId = 0;
}
if (load_type == 1) {
if (!chatWasReset && messArr.size() != count && (!isCache || currentEncryptedChat != null || forwardEndReached[loadIndex])) {
forwardEndReached[loadIndex] = true;
if (loadIndex != 1) {
first_unread_id = 0;
last_message_id = 0;
createUnreadMessageAfterId = 0;
chatAdapter.notifyItemRemoved(chatAdapter.loadingDownRow);
}
startLoadFromMessageId = 0;
}
if (newRowsCount > 0) {
int firstVisPos = chatLayoutManager.findFirstVisibleItemPosition();
int lastVisPos = chatLayoutManager.findLastVisibleItemPosition();
int top = 0;
MessageObject scrollToMessageObject = null;
if (firstVisPos != RecyclerView.NO_POSITION) {
for (int i = firstVisPos; i <= lastVisPos; i++) {
View v = chatLayoutManager.findViewByPosition(i);
if (v instanceof ChatMessageCell) {
scrollToMessageObject = ((ChatMessageCell) v).getMessageObject();
top = chatListView.getMeasuredHeight() - v.getBottom() - chatListView.getPaddingBottom();
break;
} else if (v instanceof ChatActionCell) {
scrollToMessageObject = ((ChatActionCell) v).getMessageObject();
top = chatListView.getMeasuredHeight() - v.getBottom() - chatListView.getPaddingBottom();
break;
}
}
}
if (!postponedScroll) {
chatAdapter.notifyItemRangeInserted(1, newRowsCount);
if (scrollToMessageObject != null) {
int scrollToIndex = messages.indexOf(scrollToMessageObject);
if (scrollToIndex > 0) {
chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + scrollToIndex, top);
}
}
}
}
loadingForward = false;
} else {
if (messArr.size() < count && load_type != 3 && load_type != 4) {
if (isCache) {
if (currentEncryptedChat != null || loadIndex == 1 && mergeDialogId != 0 && isEnd) {
endReached[loadIndex] = true;
}
if (load_type != 2) {
cacheEndReached[loadIndex] = true;
}
} else if (load_type != 2 || messArr.size() == 0 && messages.isEmpty()) {
endReached[loadIndex] = true;
}
}
loading = false;
if (chatListView != null && chatScrollHelper != null) {
if (first || scrollToTopOnResume || forceScrollToTop) {
forceScrollToTop = false;
if (!postponedScroll) {
chatAdapter.notifyDataSetChanged(true);
}
if (scrollToMessage != null) {
addSponsoredMessages(!isFirstLoading);
loadSendAsPeers();
int yOffset;
boolean bottom = true;
if (startLoadFromMessageOffset != Integer.MAX_VALUE) {
yOffset = -startLoadFromMessageOffset - chatListView.getPaddingBottom();
startLoadFromMessageOffset = Integer.MAX_VALUE;
} else if (scrollToMessagePosition == -9000) {
yOffset = getScrollOffsetForMessage(scrollToMessage);
bottom = false;
} else if (scrollToMessagePosition == -10000) {
yOffset = -AndroidUtilities.dp(11);
if (scrolledToUnread && threadMessageId != 0) {
yOffset += AndroidUtilities.dp(48);
}
bottom = false;
} else {
yOffset = scrollToMessagePosition;
}
// in case pinned message view is visible
yOffset += AndroidUtilities.dp(50);
if (!postponedScroll) {
if (!messages.isEmpty()) {
if (chatAdapter.loadingUpRow >= 0 && !messages.isEmpty() && (messages.get(messages.size() - 1) == scrollToMessage || messages.get(messages.size() - 2) == scrollToMessage)) {
chatLayoutManager.scrollToPositionWithOffset(chatAdapter.loadingUpRow, yOffset, bottom);
} else {
chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + messages.indexOf(scrollToMessage), yOffset, bottom);
}
}
}
chatListView.invalidate();
if (scrollToMessagePosition == -10000 || scrollToMessagePosition == -9000) {
canShowPagedownButton = true;
updatePagedownButtonVisibility(true);
if (unread_to_load != 0) {
if (pagedownButtonCounter != null) {
if (prevSetUnreadCount != newUnreadMessageCount) {
pagedownButtonCounter.setCount(newUnreadMessageCount = unread_to_load, openAnimationEnded);
prevSetUnreadCount = newUnreadMessageCount;
}
}
}
}
scrollToMessagePosition = -10000;
scrollToMessage = null;
} else {
addSponsoredMessages(!isFirstLoading);
moveScrollToLastMessage(true);
}
if (loaded_mentions_count != 0) {
showMentionDownButton(true, true);
if (mentiondownButtonCounter != null) {
mentiondownButtonCounter.setVisibility(View.VISIBLE);
mentiondownButtonCounter.setText(String.format("%d", newMentionsCount = loaded_mentions_count));
}
}
} else {
if (newRowsCount != 0) {
int firstVisPos = chatLayoutManager.findFirstVisibleItemPosition();
int lastVisPos = chatLayoutManager.findLastVisibleItemPosition();
int top = 0;
MessageObject scrollToMessageObject = null;
if (firstVisPos != RecyclerView.NO_POSITION) {
for (int i = firstVisPos; i <= lastVisPos; i++) {
View v = chatLayoutManager.findViewByPosition(i);
if (v instanceof ChatMessageCell) {
scrollToMessageObject = ((ChatMessageCell) v).getMessageObject();
top = chatListView.getMeasuredHeight() - v.getBottom() - chatListView.getPaddingBottom();
break;
} else if (v instanceof ChatActionCell) {
scrollToMessageObject = ((ChatActionCell) v).getMessageObject();
top = chatListView.getMeasuredHeight() - v.getBottom() - chatListView.getPaddingBottom();
break;
}
}
}
int insertStart = chatAdapter.messagesEndRow;
int loadingUpRow = chatAdapter.loadingUpRow;
chatAdapter.updateRowsInternal();
if (loadingUpRow >= 0 && chatAdapter.loadingUpRow < 0) {
chatAdapter.notifyItemRemoved(loadingUpRow);
}
if (newRowsCount > 0) {
if (moveCurrentDateObject) {
chatAdapter.notifyItemRemoved(insertStart - 1);
chatAdapter.notifyItemRangeInserted(insertStart - 1, newRowsCount + 1);
} else {
chatAdapter.notifyItemChanged(insertStart - 1);
chatAdapter.notifyItemRangeInserted(insertStart, newRowsCount);
}
}
if (!postponedScroll && scrollToMessageObject != null) {
int scrollToIndex = messages.indexOf(scrollToMessageObject);
if (scrollToIndex > 0) {
chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + scrollToIndex, top);
}
}
} else if (chatAdapter.loadingUpRow >= 0 && endReached[loadIndex] && (loadIndex == 0 && mergeDialogId == 0 || loadIndex == 1)) {
chatAdapter.notifyItemRemoved(chatAdapter.loadingUpRow);
} else {
chatAdapter.notifyDataSetChanged(true);
}
}
if (paused) {
scrollToTopOnResume = true;
if (scrollToMessage != null) {
scrollToTopUnReadOnResume = true;
}
}
if (first) {
if (chatListView != null) {
if (!fragmentBeginToShow) {
chatListView.setAnimateEmptyView(false, 1);
chatListView.setEmptyView(emptyViewContainer);
chatListView.setAnimateEmptyView(true, 1);
} else {
chatListView.setEmptyView(emptyViewContainer);
}
}
}
} else {
scrollToTopOnResume = true;
if (scrollToMessage != null) {
scrollToTopUnReadOnResume = true;
}
}
}
if (newGroups != null) {
for (int a = 0; a < newGroups.size(); a++) {
MessageObject.GroupedMessages groupedMessages = newGroups.valueAt(a);
groupedMessages.calculate();
if (chatAdapter != null && changedGroups != null && changedGroups.indexOfKey(newGroups.keyAt(a)) >= 0) {
MessageObject messageObject = groupedMessages.messages.get(groupedMessages.messages.size() - 1);
int idx = messages.indexOf(messageObject);
if (idx >= 0) {
if (chatListItemAnimator != null) {
chatListItemAnimator.groupWillChanged(groupedMessages);
}
chatAdapter.notifyItemRangeChanged(idx + chatAdapter.messagesStartRow, groupedMessages.messages.size());
}
}
}
}
if (first && messages.size() > 0) {
first = false;
if (isThreadChat()) {
invalidateMessagesVisiblePart();
}
if (startLoadFromDate != 0) {
int dateObjectIndex = -1;
int closeDateObjectIndex = -1;
int closeDateDiff = 0;
for (int i = 0; i < messages.size(); i++) {
if (messages.get(i).isDateObject && Math.abs(startLoadFromDate - messages.get(i).messageOwner.date) <= 100) {
dateObjectIndex = i;
break;
}
if (messages.get(i).isDateObject) {
int timeDiff = Math.abs(startLoadFromDate - messages.get(i).messageOwner.date);
if (closeDateObjectIndex == -1 || timeDiff < closeDateDiff) {
closeDateDiff = timeDiff;
closeDateObjectIndex = i;
}
}
}
if (dateObjectIndex >= 0) {
chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + dateObjectIndex, (int) (AndroidUtilities.dp(4)), false);
} else if (closeDateObjectIndex >= 0) {
chatLayoutManager.scrollToPositionWithOffset(chatAdapter.messagesStartRow + closeDateObjectIndex, chatListView.getMeasuredHeight() / 2 - AndroidUtilities.dp(24), false);
}
}
}
if (messages.isEmpty() && currentEncryptedChat == null && currentUser != null && currentUser.bot && botUser == null) {
botUser = "";
updateBottomOverlay();
}
if (newRowsCount == 0 && (mergeDialogId != 0 && loadIndex == 0 || currentEncryptedChat != null && !endReached[0])) {
first = true;
if (chatListView != null) {
chatListView.setEmptyView(null);
}
if (emptyViewContainer != null) {
emptyViewContainer.setVisibility(View.INVISIBLE);
}
} else {
showProgressView(false);
}
if (newRowsCount == 0 && mergeDialogId != 0 && loadIndex == 0) {
getNotificationCenter().updateAllowedNotifications(transitionAnimationIndex, new int[] { NotificationCenter.chatInfoDidLoad, NotificationCenter.groupCallUpdated, NotificationCenter.dialogsNeedReload, NotificationCenter.scheduledMessagesUpdated, NotificationCenter.closeChats, NotificationCenter.messagesDidLoad, NotificationCenter.botKeyboardDidLoad, NotificationCenter.userInfoDidLoad, NotificationCenter.pinnedInfoDidLoad, NotificationCenter.needDeleteDialog /*, NotificationCenter.botInfoDidLoad*/
});
}
if (showDateAfter) {
showFloatingDateView(false);
}
addSponsoredMessages(!isFirstLoading);
loadSendAsPeers();
checkScrollForLoad(false);
if (postponedScroll) {
chatAdapter.notifyDataSetChanged(true);
if (progressDialog != null) {
progressDialog.dismiss();
}
updatePinnedListButton(false);
if (postponedScrollMessageId == 0) {
chatScrollHelperCallback.scrollTo = null;
chatScrollHelperCallback.lastBottom = true;
chatScrollHelperCallback.lastItemOffset = 0;
chatScrollHelperCallback.lastPadding = (int) chatListViewPaddingTop;
chatScrollHelper.scrollToPosition(0, 0, true, true);
} else {
MessageObject object = messagesDict[loadIndex].get(postponedScrollMessageId);
if (object != null) {
MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(object.getGroupId());
if (object.getGroupId() != 0 && groupedMessages != null) {
MessageObject primary = groupedMessages.findPrimaryMessageObject();
if (primary != null) {
object = primary;
}
}
}
if (object != null) {
int k = messages.indexOf(object);
if (k >= 0) {
int fromPosition = chatLayoutManager.findFirstVisibleItemPosition();
highlightMessageId = object.getId();
int direction;
if (postponedScrollMinMessageId != 0) {
if (highlightMessageId < 0 && postponedScrollMinMessageId < 0) {
direction = highlightMessageId < postponedScrollMinMessageId ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
} else {
direction = highlightMessageId > postponedScrollMinMessageId ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
}
} else {
direction = fromPosition > k ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP;
}
chatScrollHelper.setScrollDirection(direction);
if (!needSelectFromMessageId) {
removeSelectedMessageHighlight();
}
int yOffset = getScrollOffsetForMessage(object);
chatScrollHelperCallback.scrollTo = object;
chatScrollHelperCallback.lastBottom = false;
chatScrollHelperCallback.lastItemOffset = yOffset;
chatScrollHelperCallback.lastPadding = (int) chatListViewPaddingTop;
chatScrollHelper.scrollToPosition(chatAdapter.messagesStartRow + k, yOffset, false, true);
}
}
}
}
chatWasReset = false;
} else if (id == NotificationCenter.invalidateMotionBackground) {
if (chatListView != null) {
chatListView.invalidateViews();
}
if (messageEnterTransitionContainer != null) {
messageEnterTransitionContainer.invalidate();
}
} else if (id == NotificationCenter.emojiLoaded) {
if (chatListView != null) {
chatListView.invalidateViews();
}
if (replyObjectTextView != null) {
replyObjectTextView.invalidate();
}
if (alertTextView != null) {
alertTextView.invalidate();
}
for (int a = 0; a < 2; a++) {
if (pinnedMessageTextView[a] != null) {
pinnedMessageTextView[a].invalidate();
}
}
if (mentionListView != null) {
mentionListView.invalidateViews();
}
if (stickersListView != null) {
stickersListView.invalidateViews();
}
if (messagesSearchListView != null) {
messagesSearchListView.invalidateViews();
}
if (undoView != null) {
undoView.invalidate();
}
if (chatActivityEnterView != null) {
EditTextBoldCursor editText = chatActivityEnterView.getEditField();
int color = editText.getCurrentTextColor();
editText.setTextColor(0xffffffff);
editText.setTextColor(color);
}
} else if (id == NotificationCenter.didUpdateConnectionState) {
int state = ConnectionsManager.getInstance(account).getConnectionState();
if (state == ConnectionsManager.ConnectionStateConnected) {
checkAutoDownloadMessages(false);
}
} else if (id == NotificationCenter.chatOnlineCountDidLoad) {
Long chatId = (Long) args[0];
if (chatInfo == null || currentChat == null || currentChat.id != chatId) {
return;
}
chatInfo.online_count = (Integer) args[1];
if (avatarContainer != null) {
avatarContainer.updateOnlineCount();
avatarContainer.updateSubtitle();
}
} else if (id == NotificationCenter.updateDefaultSendAsPeer) {
long chatId = (long) args[0];
if (chatId == dialog_id) {
chatActivityEnterView.updateSendAsButton();
}
} else if (id == NotificationCenter.updateInterfaces) {
int updateMask = (Integer) args[0];
if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0) {
if (currentChat != null) {
TLRPC.Chat chat = getMessagesController().getChat(currentChat.id);
if (chat != null) {
currentChat = chat;
}
} else if (currentUser != null) {
TLRPC.User user = getMessagesController().getUser(currentUser.id);
if (user != null) {
currentUser = user;
}
}
updateTitle();
}
boolean updateSubtitle = false;
if (!isThreadChat() && ((updateMask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0 || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0)) {
if (currentChat != null && avatarContainer != null) {
avatarContainer.updateOnlineCount();
}
updateSubtitle = true;
}
if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_NAME) != 0) {
checkAndUpdateAvatar();
updateVisibleRows();
}
if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
updateSubtitle = true;
}
if ((updateMask & MessagesController.UPDATE_MASK_CHAT) != 0 && currentChat != null) {
boolean fwdBefore = getMessagesController().isChatNoForwards(currentChat);
TLRPC.Chat chat = getMessagesController().getChat(currentChat.id);
if (chat == null) {
return;
}
currentChat = chat;
boolean fwdChanged = getMessagesController().isChatNoForwards(currentChat) != fwdBefore;
updateSubtitle = !isThreadChat();
updateBottomOverlay();
if (chatActivityEnterView != null) {
chatActivityEnterView.setDialogId(dialog_id, currentAccount);
}
if (currentEncryptedChat != null && SharedConfig.passcodeHash.length() == 0 && !SharedConfig.allowScreenCapture && unregisterFlagSecurePasscode == null) {
unregisterFlagSecurePasscode = AndroidUtilities.registerFlagSecure(getParentActivity().getWindow());
}
if (fwdChanged) {
boolean value = getMessagesController().isChatNoForwards(currentChat);
if (!value && unregisterFlagSecureNoforwards != null) {
unregisterFlagSecureNoforwards.run();
unregisterFlagSecureNoforwards = null;
} else if (value && unregisterFlagSecureNoforwards == null) {
unregisterFlagSecureNoforwards = AndroidUtilities.registerFlagSecure(getParentActivity().getWindow());
}
}
}
if (avatarContainer != null && updateSubtitle) {
avatarContainer.updateSubtitle(true);
}
if ((updateMask & MessagesController.UPDATE_MASK_USER_PHONE) != 0) {
updateTopPanel(true);
}
} else if (id == NotificationCenter.didReceiveNewMessages) {
long did = (Long) args[0];
ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1];
if (did == dialog_id) {
boolean scheduled = (Boolean) args[2];
if (scheduled != (chatMode == MODE_SCHEDULED)) {
if (chatMode != MODE_SCHEDULED && !isPaused && forwardingMessages == null) {
if (!arr.isEmpty() && arr.get(0).getId() < 0) {
openScheduledMessages();
}
}
return;
}
processNewMessages(arr);
} else if (ChatObject.isChannel(currentChat) && !currentChat.megagroup && chatInfo != null && did == -chatInfo.linked_chat_id) {
for (int a = 0, N = arr.size(); a < N; a++) {
MessageObject messageObject = arr.get(a);
if (messageObject.isReply()) {
waitingForReplies.put(messageObject.getId(), messageObject);
}
}
checkWaitingForReplies();
}
} else if (id == NotificationCenter.didLoadSendAsPeers) {
loadSendAsPeers();
} else if (id == NotificationCenter.didLoadSponsoredMessages) {
addSponsoredMessages(true);
} else if (id == NotificationCenter.closeChats) {
if (args != null && args.length > 0) {
long did = (Long) args[0];
if (did == dialog_id) {
finishFragment();
}
} else {
if (AndroidUtilities.isTablet() && parentLayout != null && parentLayout.fragmentsStack.size() > 1) {
finishFragment();
} else {
removeSelfFromStack();
}
}
} else if (id == NotificationCenter.commentsRead) {
long channelId = (Long) args[0];
if (currentChat != null && currentChat.id == channelId) {
int mid = (Integer) args[1];
MessageObject obj = messagesDict[0].get(mid);
if (obj != null && obj.hasReplies()) {
int maxReadId = (Integer) args[2];
if (paused) {
if (delayedReadRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(delayedReadRunnable);
delayedReadRunnable = null;
}
obj.messageOwner.replies.read_max_id = maxReadId;
} else {
AndroidUtilities.runOnUIThread(delayedReadRunnable = () -> {
delayedReadRunnable = null;
obj.messageOwner.replies.read_max_id = maxReadId;
}, 500);
}
}
}
} else if (id == NotificationCenter.changeRepliesCounter) {
long channelId = (Long) args[0];
if (currentChat != null && currentChat.id == channelId) {
int mid = (Integer) args[1];
MessageObject obj = messagesDict[0].get(mid);
if (obj != null && obj.messageOwner.replies != null) {
Integer count = (Integer) args[2];
obj.messageOwner.replies.replies += count;
if (count > 0) {
TLRPC.Peer peer = getMessagesController().getPeer(ChatObject.getSendAsPeerId(currentChat, getMessagesController().getChatFull(currentChat.id)));
for (int c = 0, N = obj.messageOwner.replies.recent_repliers.size(); c < N; c++) {
if (MessageObject.getPeerId(obj.messageOwner.replies.recent_repliers.get(c)) == MessageObject.getPeerId(peer)) {
obj.messageOwner.replies.recent_repliers.remove(c);
break;
}
}
obj.messageOwner.replies.recent_repliers.add(0, peer);
}
if (obj.messageOwner.replies.replies < 0) {
obj.messageOwner.replies.replies = 0;
}
}
}
} else if (id == NotificationCenter.threadMessagesRead) {
long did = (Long) args[0];
if (dialog_id != did) {
return;
}
int threadId = (Integer) args[1];
if (threadId != threadMessageId) {
return;
}
int inbox = (Integer) args[2];
int outbox = (Integer) args[3];
if (inbox > threadMaxInboxReadId) {
threadMaxInboxReadId = inbox;
for (int a = 0, size2 = messages.size(); a < size2; a++) {
MessageObject obj = messages.get(a);
int messageId = obj.getId();
if (!obj.isOut() && messageId > 0 && messageId <= threadMaxInboxReadId) {
if (!obj.isUnread()) {
break;
}
obj.setIsRead();
if (chatAdapter != null) {
chatAdapter.invalidateRowWithMessageObject(obj);
}
}
}
}
if (outbox > threadMaxOutboxReadId) {
threadMaxOutboxReadId = outbox;
for (int a = 0, size2 = messages.size(); a < size2; a++) {
MessageObject obj = messages.get(a);
int messageId = obj.getId();
if (obj.isOut() && messageId > 0 && messageId <= threadMaxOutboxReadId) {
if (!obj.isUnread()) {
break;
}
obj.setIsRead();
if (chatAdapter != null) {
chatAdapter.updateRowWithMessageObject(obj, false);
}
}
}
}
} else if (id == NotificationCenter.messagesRead) {
if (chatMode == MODE_SCHEDULED) {
return;
}
LongSparseIntArray inbox = (LongSparseIntArray) args[0];
LongSparseIntArray outbox = (LongSparseIntArray) args[1];
boolean updated = false;
if (inbox != null) {
for (int b = 0, size = inbox.size(); b < size; b++) {
long key = inbox.keyAt(b);
long messageId = inbox.get(key);
if (key != dialog_id) {
continue;
}
for (int a = 0, size2 = messages.size(); a < size2; a++) {
MessageObject obj = messages.get(a);
if (!obj.isOut() && obj.getId() > 0 && obj.getId() <= (int) messageId) {
if (!obj.isUnread()) {
break;
}
obj.setIsRead();
if (chatAdapter != null) {
chatAdapter.invalidateRowWithMessageObject(obj);
}
updated = true;
newUnreadMessageCount--;
}
}
removeUnreadPlane(false);
break;
}
}
if (updated) {
if (newUnreadMessageCount < 0) {
newUnreadMessageCount = 0;
}
if (pagedownButtonCounter != null) {
if (prevSetUnreadCount != newUnreadMessageCount) {
prevSetUnreadCount = newUnreadMessageCount;
pagedownButtonCounter.setCount(newUnreadMessageCount, true);
}
}
}
if (outbox != null) {
for (int b = 0, size = outbox.size(); b < size; b++) {
long key = outbox.keyAt(b);
int messageId = (int) outbox.get(key);
if (key != dialog_id) {
continue;
}
for (int a = 0, size2 = messages.size(); a < size2; a++) {
MessageObject obj = messages.get(a);
if (obj.isOut() && obj.getId() > 0 && obj.getId() <= messageId) {
obj.setIsRead();
if (chatAdapter != null) {
chatAdapter.invalidateRowWithMessageObject(obj);
}
}
}
break;
}
}
} else if (id == NotificationCenter.historyCleared) {
long did = (Long) args[0];
if (did != dialog_id) {
return;
}
int max_id = (Integer) args[1];
if (!pinnedMessageIds.isEmpty()) {
pinnedMessageIds.clear();
pinnedMessageObjects.clear();
currentPinnedMessageId = 0;
loadedPinnedMessagesCount = 0;
totalPinnedMessagesCount = 0;
updatePinnedMessageView(true);
}
boolean updated = false;
for (int b = 0; b < messages.size(); b++) {
MessageObject obj = messages.get(b);
int mid = obj.getId();
if (mid <= 0 || mid > max_id) {
continue;
}
messages.remove(b);
b--;
messagesDict[0].remove(mid);
ArrayList<MessageObject> dayArr = messagesByDays.get(obj.dateKey);
if (dayArr != null) {
dayArr.remove(obj);
if (dayArr.isEmpty()) {
messagesByDays.remove(obj.dateKey);
if (b >= 0 && b < messages.size()) {
messages.remove(b);
b--;
}
}
}
updated = true;
}
if (messages.isEmpty()) {
if (!endReached[0] && !loading) {
showProgressView(false);
if (chatListView != null) {
chatListView.setEmptyView(null);
}
if (currentEncryptedChat == null) {
maxMessageId[0] = maxMessageId[1] = Integer.MAX_VALUE;
minMessageId[0] = minMessageId[1] = Integer.MIN_VALUE;
} else {
maxMessageId[0] = maxMessageId[1] = Integer.MIN_VALUE;
minMessageId[0] = minMessageId[1] = Integer.MAX_VALUE;
}
maxDate[0] = maxDate[1] = Integer.MIN_VALUE;
minDate[0] = minDate[1] = 0;
waitingForLoad.add(lastLoadIndex);
getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++);
loading = true;
} else {
if (botButtons != null) {
botButtons = null;
if (chatActivityEnterView != null) {
chatActivityEnterView.setButtons(null, false);
}
}
if (currentEncryptedChat == null && currentUser != null && currentUser.bot && botUser == null) {
botUser = "";
updateBottomOverlay();
}
}
}
canShowPagedownButton = false;
updatePagedownButtonVisibility(true);
showMentionDownButton(false, true);
removeUnreadPlane(true);
if (updated && chatAdapter != null) {
chatAdapter.notifyDataSetChanged(false);
}
} else if (id == NotificationCenter.messagesDeleted) {
boolean scheduled = (Boolean) args[2];
if (scheduled != (chatMode == MODE_SCHEDULED)) {
return;
}
ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0];
long channelId = (Long) args[1];
processDeletedMessages(markAsDeletedMessages, channelId);
} else if (id == NotificationCenter.messageReceivedByServer) {
Boolean scheduled = (Boolean) args[6];
if (scheduled != (chatMode == MODE_SCHEDULED)) {
return;
}
Integer msgId = (Integer) args[0];
MessageObject obj = messagesDict[0].get(msgId);
if (isThreadChat() && pendingSendMessagesDict.size() > 0) {
MessageObject object = pendingSendMessagesDict.get(msgId);
if (object != null) {
Integer newMsgId = (Integer) args[1];
pendingSendMessagesDict.put(newMsgId, object);
}
}
if (obj != null) {
checkChecksHint();
if (obj.shouldRemoveVideoEditedInfo) {
obj.videoEditedInfo = null;
obj.shouldRemoveVideoEditedInfo = false;
}
Integer newMsgId = (Integer) args[1];
if (!newMsgId.equals(msgId) && messagesDict[0].indexOfKey(newMsgId) >= 0) {
MessageObject removed = messagesDict[0].get(msgId);
messagesDict[0].remove(msgId);
if (removed != null) {
int index = messages.indexOf(removed);
messages.remove(index);
ArrayList<MessageObject> dayArr = messagesByDays.get(removed.dateKey);
dayArr.remove(obj);
if (dayArr.isEmpty()) {
messagesByDays.remove(obj.dateKey);
if (index >= 0 && index < messages.size()) {
messages.remove(index);
}
}
if (chatAdapter != null) {
chatAdapter.notifyDataSetChanged(true);
}
}
return;
}
TLRPC.Message newMsgObj = (TLRPC.Message) args[2];
Long grouped_id;
if (args.length >= 4) {
grouped_id = (Long) args[4];
} else {
grouped_id = 0L;
}
boolean mediaUpdated = false;
boolean updatedForward = false;
if (newMsgObj != null) {
try {
updatedForward = obj.isForwarded() && (obj.messageOwner.reply_markup == null && newMsgObj.reply_markup != null || !obj.messageOwner.message.equals(newMsgObj.message));
mediaUpdated = updatedForward || obj.messageOwner.params != null && obj.messageOwner.params.containsKey("query_id") || newMsgObj.media != null && obj.messageOwner.media != null && !newMsgObj.media.getClass().equals(obj.messageOwner.media.getClass());
} catch (Exception e) {
FileLog.e(e);
}
if (obj.getGroupId() != 0 && newMsgObj.grouped_id != 0) {
MessageObject.GroupedMessages oldGroup = groupedMessagesMap.get(obj.getGroupId());
if (oldGroup != null) {
groupedMessagesMap.put(newMsgObj.grouped_id, oldGroup);
}
obj.localSentGroupId = obj.messageOwner.grouped_id;
obj.messageOwner.grouped_id = grouped_id;
}
TLRPC.MessageFwdHeader fwdHeader = obj.messageOwner.fwd_from;
obj.messageOwner = newMsgObj;
if (fwdHeader != null && newMsgObj.fwd_from != null && !TextUtils.isEmpty(newMsgObj.fwd_from.from_name)) {
obj.messageOwner.fwd_from = fwdHeader;
}
obj.generateThumbs(true);
obj.setType();
if (newMsgObj.media instanceof TLRPC.TL_messageMediaGame) {
obj.applyNewText();
}
}
if (updatedForward) {
obj.measureInlineBotButtons();
}
messagesDict[0].remove(msgId);
messagesDict[0].put(newMsgId, obj);
obj.messageOwner.id = newMsgId;
obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
obj.forceUpdate = mediaUpdated;
addReplyMessageOwner(obj, msgId);
if (args.length >= 6) {
obj.applyMediaExistanceFlags((Integer) args[5]);
}
addToPolls(obj, null);
ArrayList<MessageObject> messArr = new ArrayList<>();
messArr.add(obj);
if (currentEncryptedChat == null) {
getMediaDataController().loadReplyMessagesForMessages(messArr, dialog_id, chatMode == MODE_SCHEDULED, null);
}
if (chatAdapter != null) {
chatAdapter.updateRowWithMessageObject(obj, false);
}
if (chatLayoutManager != null) {
if (mediaUpdated && chatLayoutManager.findFirstVisibleItemPosition() == 0) {
moveScrollToLastMessage(false);
}
}
getNotificationsController().playOutChatSound();
}
} else if (id == NotificationCenter.messageReceivedByAck) {
Integer msgId = (Integer) args[0];
MessageObject obj = messagesDict[0].get(msgId);
if (obj != null) {
obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
if (chatAdapter != null) {
chatAdapter.updateRowWithMessageObject(obj, false);
}
}
} else if (id == NotificationCenter.messageSendError) {
Integer msgId = (Integer) args[0];
MessageObject obj = messagesDict[0].get(msgId);
if (obj != null) {
obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
updateVisibleRows();
}
} else if (id == NotificationCenter.groupCallUpdated) {
Long chatId = (Long) args[0];
if (dialog_id == -chatId) {
groupCall = getMessagesController().getGroupCall(currentChat.id, false);
if (fragmentContextView != null) {
fragmentContextView.checkCall(openAnimationStartTime == 0 || SystemClock.elapsedRealtime() < openAnimationStartTime + 150);
}
checkGroupCallJoin(false);
}
} else if (id == NotificationCenter.didLoadChatInviter) {
long chatId = (Long) args[0];
if (dialog_id == -chatId && chatInviterId == 0) {
chatInviterId = (Long) args[1];
if (chatInfo != null) {
chatInfo.inviterId = chatInviterId;
}
updateInfoTopView(openAnimationStartTime != 0 && SystemClock.elapsedRealtime() >= openAnimationStartTime + 150);
}
} else if (id == NotificationCenter.chatInfoDidLoad) {
TLRPC.ChatFull chatFull = (TLRPC.ChatFull) args[0];
if (currentChat != null && chatFull.id == currentChat.id) {
if (chatFull instanceof TLRPC.TL_channelFull) {
if (currentChat.megagroup) {
int lastDate = 0;
if (chatFull.participants != null) {
for (int a = 0; a < chatFull.participants.participants.size(); a++) {
lastDate = Math.max(chatFull.participants.participants.get(a).date, lastDate);
}
}
if (lastDate == 0 || Math.abs(System.currentTimeMillis() / 1000 - lastDate) > 60 * 60) {
getMessagesController().loadChannelParticipants(currentChat.id);
}
}
if (chatFull.participants == null && chatInfo != null) {
chatFull.participants = chatInfo.participants;
}
}
showGigagroupConvertAlert();
long prevLinkedChatId = chatInfo != null ? chatInfo.linked_chat_id : 0;
chatInfo = chatFull;
groupCall = getMessagesController().getGroupCall(currentChat.id, true);
if (ChatObject.isChannel(currentChat) && currentChat.megagroup && fragmentContextView != null) {
fragmentContextView.checkCall(openAnimationStartTime == 0 || SystemClock.elapsedRealtime() < openAnimationStartTime + 150);
}
if (chatActivityEnterView != null) {
chatActivityEnterView.updateSendAsButton();
chatActivityEnterView.updateFieldHint(false);
}
if (chatAdapter != null) {
chatAdapter.notifyDataSetChanged(true);
}
if (prevLinkedChatId != chatInfo.linked_chat_id) {
if (prevLinkedChatId != 0) {
TLRPC.Chat chat = getMessagesController().getChat(prevLinkedChatId);
getMessagesController().startShortPoll(chat, classGuid, true);
}
if (chatInfo.linked_chat_id != 0) {
TLRPC.Chat chat = getMessagesController().getChat(chatInfo.linked_chat_id);
if (chat != null && chat.megagroup) {
getMessagesController().startShortPoll(chat, classGuid, false);
}
}
}
boolean animated = openAnimationStartTime != 0 && SystemClock.elapsedRealtime() >= openAnimationStartTime + 150;
checkActionBarMenu(animated);
if (chatInviterId == 0) {
fillInviterId(true);
updateInfoTopView(animated);
}
if (chatActivityEnterView != null) {
chatActivityEnterView.setChatInfo(chatInfo);
}
if (mentionsAdapter != null) {
mentionsAdapter.setChatInfo(chatInfo);
}
if (!isThreadChat()) {
if (avatarContainer != null) {
avatarContainer.updateOnlineCount();
avatarContainer.updateSubtitle();
}
if (!inMenuMode && !loadingPinnedMessagesList && !pinnedMessageIds.isEmpty() && chatInfo.pinned_msg_id > pinnedMessageIds.get(0)) {
getMediaDataController().loadPinnedMessages(dialog_id, 0, chatInfo.pinned_msg_id);
loadingPinnedMessagesList = true;
}
}
if (chatInfo instanceof TLRPC.TL_chatFull) {
hasBotsCommands = false;
botInfo.clear();
botsCount = 0;
URLSpanBotCommand.enabled = false;
for (int a = 0; a < chatInfo.participants.participants.size(); a++) {
TLRPC.ChatParticipant participant = chatInfo.participants.participants.get(a);
TLRPC.User user = getMessagesController().getUser(participant.user_id);
if (user != null && user.bot) {
URLSpanBotCommand.enabled = true;
botsCount++;
if (!isThreadChat()) {
hasBotsCommands = true;
}
getMediaDataController().loadBotInfo(user.id, -chatInfo.id, true, classGuid);
}
}
if (chatListView != null) {
chatListView.invalidateViews();
}
} else if (chatInfo instanceof TLRPC.TL_channelFull) {
hasBotsCommands = false;
botInfo.clear();
botsCount = 0;
URLSpanBotCommand.enabled = !chatInfo.bot_info.isEmpty() && currentChat != null && currentChat.megagroup;
botsCount = chatInfo.bot_info.size();
for (int a = 0; a < chatInfo.bot_info.size(); a++) {
TLRPC.BotInfo bot = chatInfo.bot_info.get(a);
if (!isThreadChat() && !bot.commands.isEmpty() && (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup)) {
hasBotsCommands = true;
}
botInfo.put(bot.user_id, bot);
}
if (chatListView != null) {
chatListView.invalidateViews();
}
if (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup) {
if (mentionsAdapter != null) {
mentionsAdapter.setBotInfo(botInfo);
}
if (chatActivityEnterView != null) {
chatActivityEnterView.setBotInfo(botInfo);
}
}
}
if (chatActivityEnterView != null) {
chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands, true);
}
if (mentionsAdapter != null) {
mentionsAdapter.setBotsCount(botsCount);
}
if (chatMode == 0 && ChatObject.isChannel(currentChat) && mergeDialogId == 0 && chatInfo.migrated_from_chat_id != 0 && !isThreadChat()) {
mergeDialogId = -chatInfo.migrated_from_chat_id;
maxMessageId[1] = chatInfo.migrated_from_max_id;
if (chatAdapter != null) {
chatAdapter.notifyDataSetChanged(true);
}
if (mergeDialogId != 0 && endReached[0]) {
checkScrollForLoad(false);
}
}
checkGroupCallJoin((Boolean) args[3]);
checkThemeEmoticon();
if (pendingRequestsDelegate != null) {
pendingRequestsDelegate.setChatInfo(chatInfo, true);
}
}
} else if (id == NotificationCenter.chatInfoCantLoad) {
long chatId = (Long) args[0];
if (currentChat != null && currentChat.id == chatId) {
int reason = (Integer) args[1];
if (getParentActivity() == null || closeChatDialog != null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
if (reason == 0) {
if (currentChat.has_link) {
builder.setMessage(LocaleController.getString("ChannelCantOpenBannedByAdmin", R.string.ChannelCantOpenBannedByAdmin));
} else {
builder.setMessage(LocaleController.getString("ChannelCantOpenPrivate", R.string.ChannelCantOpenPrivate));
}
} else if (reason == 1) {
builder.setMessage(LocaleController.getString("ChannelCantOpenNa", R.string.ChannelCantOpenNa));
} else if (reason == 2) {
builder.setMessage(LocaleController.getString("ChannelCantOpenBanned", R.string.ChannelCantOpenBanned));
} else if (reason == 3) {
builder.setMessage(LocaleController.getString("JoinByPeekChannelText", R.string.JoinByPeekChannelText));
}
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
if (showDialog(closeChatDialog = builder.create()) == null) {
showCloseChatDialogLater = true;
}
loading = false;
showProgressView(false);
if (chatAdapter != null) {
chatAdapter.notifyDataSetChanged(false);
}
}
} else if (id == NotificationCenter.contactsDidLoad) {
updateTopPanel(true);
if (!isThreadChat() && avatarContainer != null) {
avatarContainer.updateSubtitle();
}
} else if (id == NotificationCenter.encryptedChatUpdated) {
TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) args[0];
if (currentEncryptedChat != null && chat.id == currentEncryptedChat.id) {
currentEncryptedChat = chat;
updateTopPanel(true);
updateSecretStatus();
initStickers();
if (chatActivityEnterView != null) {
chatActivityEnterView.setAllowStickersAndGifs(true, true);
chatActivityEnterView.checkRoundVideo();
}
if (mentionsAdapter != null) {
mentionsAdapter.setNeedBotContext(!chatActivityEnterView.isEditingMessage());
}
}
} else if (id == NotificationCenter.messagesReadEncrypted) {
int encId = (Integer) args[0];
if (currentEncryptedChat != null && currentEncryptedChat.id == encId) {
int date = (Integer) args[1];
for (MessageObject obj : messages) {
if (!obj.isOut()) {
continue;
} else if (obj.isOut() && !obj.isUnread()) {
break;
}
if (obj.messageOwner.date - 1 <= date) {
obj.setIsRead();
if (chatAdapter != null) {
chatAdapter.invalidateRowWithMessageObject(obj);
}
}
}
}
} else if (id == NotificationCenter.removeAllMessagesFromDialog) {
long did = (Long) args[0];
if (dialog_id == did) {
if (threadMessageId != 0) {
if (forwardEndReached[0]) {
forwardEndReached[0] = false;
hideForwardEndReached = false;
chatAdapter.notifyItemInserted(0);
}
getMessagesController().addToViewsQueue(threadMessageObject);
} else {
clearHistory((Boolean) args[1], (TLRPC.TL_updates_channelDifferenceTooLong) args[2]);
}
}
} else if (id == NotificationCenter.screenshotTook) {
updateInformationForScreenshotDetector();
} else if (id == NotificationCenter.blockedUsersDidLoad) {
if (currentUser != null && !UserObject.isReplyUser(currentUser)) {
boolean oldValue = userBlocked;
userBlocked = getMessagesController().blockePeers.indexOfKey(currentUser.id) >= 0;
if (oldValue != userBlocked) {
updateBottomOverlay();
}
}
} else if (id == NotificationCenter.fileNewChunkAvailable) {
MessageObject messageObject = (MessageObject) args[0];
long finalSize = (Long) args[3];
if (finalSize != 0 && dialog_id == messageObject.getDialogId()) {
MessageObject currentObject = messagesDict[0].get(messageObject.getId());
if (currentObject != null && currentObject.messageOwner.media.document != null) {
currentObject.messageOwner.media.document.size = (int) finalSize;
updateVisibleRows();
}
}
} else if (id == NotificationCenter.didCreatedNewDeleteTask) {
long dialogId = (Long) args[0];
if (dialogId != dialog_id) {
return;
}
SparseArray<ArrayList<Integer>> mids = (SparseArray<ArrayList<Integer>>) args[1];
boolean changed = false;
for (int i = 0; i < mids.size(); i++) {
int key = mids.keyAt(i);
ArrayList<Integer> arr = mids.get(key);
for (int a = 0; a < arr.size(); a++) {
Integer mid = arr.get(a);
MessageObject messageObject = messagesDict[0].get(mid);
if (messageObject != null) {
messageObject.messageOwner.destroyTime = key;
changed = true;
}
}
}
if (changed) {
updateVisibleRows();
}
} else if (id == NotificationCenter.messagePlayingDidStart) {
MessageObject messageObject = (MessageObject) args[0];
if (messageObject.eventId != 0) {
return;
}
sendSecretMessageRead(messageObject, true);
if ((messageObject.isRoundVideo() || messageObject.isVideo()) && fragmentView != null && fragmentView.getParent() != null) {
MediaController.getInstance().setTextureView(createTextureView(true), aspectRatioFrameLayout, videoPlayerContainer, true);
updateTextureViewPosition(true);
}
if (chatListView != null) {
int count = chatListView.getChildCount();
for (int a = 0; a < count; a++) {
View view = chatListView.getChildAt(a);
if (view instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) view;
MessageObject messageObject1 = cell.getMessageObject();
if (messageObject1 != null) {
boolean isVideo = messageObject1.isVideo();
if (messageObject1.isRoundVideo() || isVideo) {
cell.checkVideoPlayback(!messageObject.equals(messageObject1), null);
if (!MediaController.getInstance().isPlayingMessage(messageObject1)) {
if (isVideo && !MediaController.getInstance().isGoingToShowMessageObject(messageObject1)) {
AnimatedFileDrawable animation = cell.getPhotoImage().getAnimation();
if (animation != null) {
animation.start();
}
}
if (messageObject1.audioProgress != 0) {
messageObject1.resetPlayingProgress();
cell.invalidate();
}
} else if (isVideo) {
cell.updateButtonState(false, true, false);
}
if (messageObject1.isRoundVideo()) {
int position = chatListView.getChildAdapterPosition(cell);
if (position >= 0) {
if (MediaController.getInstance().isPlayingMessage(messageObject1)) {
boolean keyboardIsVisible = contentView.getKeyboardHeight() >= AndroidUtilities.dp(20);
chatLayoutManager.scrollToPositionWithOffset(position, (int) ((chatListView.getMeasuredHeight() - chatListViewPaddingTop - (keyboardIsVisible ? AndroidUtilities.roundMessageSize : AndroidUtilities.roundPlayingMessageSize)) / 2), false);
}
chatAdapter.notifyItemChanged(position);
}
}
} else if (messageObject1.isVoice() || messageObject1.isMusic()) {
cell.updateButtonState(false, true, false);
}
}
}
}
count = mentionListView.getChildCount();
for (int a = 0; a < count; a++) {
View view = mentionListView.getChildAt(a);
if (view instanceof ContextLinkCell) {
ContextLinkCell cell = (ContextLinkCell) view;
MessageObject messageObject1 = cell.getMessageObject();
if (messageObject1 != null && (messageObject1.isVoice() || messageObject1.isMusic())) {
cell.updateButtonState(false, true);
}
}
}
}
} else if (id == NotificationCenter.messagePlayingGoingToStop) {
boolean injecting = (Boolean) args[1];
if (injecting) {
contentView.removeView(videoPlayerContainer);
videoPlayerContainer = null;
videoTextureView = null;
aspectRatioFrameLayout = null;
} else {
if (chatListView != null && videoPlayerContainer != null && videoPlayerContainer.getTag() != null) {
MessageObject messageObject = (MessageObject) args[0];
int count = chatListView.getChildCount();
for (int a = 0; a < count; a++) {
View view = chatListView.getChildAt(a);
if (view instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) view;
MessageObject messageObject1 = cell.getMessageObject();
if (messageObject == messageObject1) {
AnimatedFileDrawable animation = cell.getPhotoImage().getAnimation();
if (animation != null) {
Bitmap bitmap = animation.getAnimatedBitmap();
if (bitmap != null) {
try {
Bitmap src = videoTextureView.getBitmap(bitmap.getWidth(), bitmap.getHeight());
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(src, 0, 0, null);
src.recycle();
} catch (Throwable e) {
FileLog.e(e);
}
}
animation.seekTo(messageObject.audioProgressMs, !getFileLoader().isLoadingVideo(messageObject.getDocument(), true));
}
break;
}
}
}
}
}
} else if (id == NotificationCenter.messagePlayingDidReset || id == NotificationCenter.messagePlayingPlayStateChanged) {
if (id == NotificationCenter.messagePlayingDidReset) {
AndroidUtilities.runOnUIThread(destroyTextureViewRunnable);
}
int messageId = (int) args[0];
if (chatListView != null) {
int count = chatListView.getChildCount();
for (int a = 0; a < count; a++) {
View view = chatListView.getChildAt(a);
if (view instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) view;
MessageObject messageObject = cell.getMessageObject();
if (messageObject != null) {
if (messageObject.isVoice() || messageObject.isMusic()) {
cell.updateButtonState(false, true, false);
} else if (messageObject.isVideo()) {
cell.updateButtonState(false, true, false);
if (!MediaController.getInstance().isPlayingMessage(messageObject) && !MediaController.getInstance().isGoingToShowMessageObject(messageObject)) {
AnimatedFileDrawable animation = cell.getPhotoImage().getAnimation();
if (animation != null) {
animation.start();
}
}
} else if (messageObject.isRoundVideo()) {
if (!MediaController.getInstance().isPlayingMessage(messageObject)) {
Bitmap bitmap = null;
if (id == NotificationCenter.messagePlayingDidReset && cell.getMessageObject().getId() == messageId && videoTextureView != null) {
bitmap = videoTextureView.getBitmap();
if (bitmap != null && bitmap.getPixel(0, 0) == Color.TRANSPARENT) {
bitmap = null;
}
}
cell.checkVideoPlayback(true, bitmap);
}
int position = chatListView.getChildAdapterPosition(cell);
messageObject.forceUpdate = true;
if (position >= 0) {
chatAdapter.notifyItemChanged(position);
}
}
}
}
}
count = mentionListView.getChildCount();
for (int a = 0; a < count; a++) {
View view = mentionListView.getChildAt(a);
if (view instanceof ContextLinkCell) {
ContextLinkCell cell = (ContextLinkCell) view;
MessageObject messageObject = cell.getMessageObject();
if (messageObject != null && (messageObject.isVoice() || messageObject.isMusic())) {
cell.updateButtonState(false, true);
}
}
}
}
} else if (id == NotificationCenter.messagePlayingProgressDidChanged) {
Integer mid = (Integer) args[0];
if (chatListView != null) {
int count = chatListView.getChildCount();
for (int a = 0; a < count; a++) {
View view = chatListView.getChildAt(a);
if (view instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) view;
MessageObject playing = cell.getMessageObject();
if (playing != null && playing.getId() == mid) {
MessageObject player = MediaController.getInstance().getPlayingMessageObject();
if (player != null && !cell.getSeekBar().isDragging()) {
playing.audioProgress = player.audioProgress;
playing.audioProgressSec = player.audioProgressSec;
playing.audioPlayerDuration = player.audioPlayerDuration;
cell.updatePlayingMessageProgress();
if (drawLaterRoundProgressCell == cell) {
fragmentView.invalidate();
}
}
break;
}
}
}
}
} else if (id == NotificationCenter.didUpdatePollResults) {
long pollId = (Long) args[0];
ArrayList<MessageObject> arrayList = polls.get(pollId);
if (arrayList != null) {
TLRPC.TL_poll poll = (TLRPC.TL_poll) args[1];
TLRPC.PollResults results = (TLRPC.PollResults) args[2];
View pollView = null;
boolean isVotedChanged = false;
boolean isQuiz = false;
for (int a = 0, N = arrayList.size(); a < N; a++) {
MessageObject object = arrayList.get(a);
boolean isVoted = object.isVoted();
TLRPC.TL_messageMediaPoll media = (TLRPC.TL_messageMediaPoll) object.messageOwner.media;
if (poll != null) {
media.poll = poll;
isQuiz = poll.quiz;
} else if (media.poll != null) {
isQuiz = media.poll.quiz;
}
MessageObject.updatePollResults(media, results);
if (chatAdapter != null) {
pollView = chatAdapter.updateRowWithMessageObject(object, true);
}
if (isVoted != object.isVoted()) {
isVotedChanged = true;
}
}
if (isVotedChanged && isQuiz && undoView != null && pollView instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) pollView;
if (cell.isAnimatingPollAnswer()) {
for (int a = 0, N = results.results.size(); a < N; a++) {
TLRPC.TL_pollAnswerVoters voters = results.results.get(a);
if (voters.chosen) {
if (voters.correct) {
fireworksOverlay.start();
pollView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
} else {
((ChatMessageCell) pollView).shakeView();
pollView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
showPollSolution(cell.getMessageObject(), results);
cell.showHintButton(false, true, 0);
}
break;
}
}
}
}
}
} else if (id == NotificationCenter.didUpdateReactions) {
long did = (Long) args[0];
if (did == dialog_id || did == mergeDialogId) {
int msgId = (Integer) args[1];
MessageObject messageObject = messagesDict[did == dialog_id ? 0 : 1].get(msgId);
if (messageObject != null) {
MessageObject.updateReactions(messageObject.messageOwner, (TLRPC.TL_messageReactions) args[2]);
messageObject.forceUpdate = true;
messageObject.reactionsChanged = true;
updateMessageAnimated(messageObject, true);
}
}
} else if (id == NotificationCenter.didVerifyMessagesStickers) {
ArrayList<TLRPC.Message> messages = (ArrayList<TLRPC.Message>) args[0];
for (int a = 0, N = messages.size(); a < N; a++) {
TLRPC.Message message = messages.get(a);
MessageObject existMessageObject = messagesDict[0].get(message.id);
if (existMessageObject != null) {
existMessageObject.messageOwner.stickerVerified = message.stickerVerified;
existMessageObject.setType();
if (chatAdapter != null) {
chatAdapter.updateRowWithMessageObject(existMessageObject, false);
}
}
}
} else if (id == NotificationCenter.updateMessageMedia) {
TLRPC.Message message = (TLRPC.Message) args[0];
MessageObject existMessageObject = messagesDict[0].get(message.id);
if (existMessageObject != null) {
existMessageObject.messageOwner.media = message.media;
existMessageObject.messageOwner.attachPath = message.attachPath;
existMessageObject.generateThumbs(false);
if (existMessageObject.getGroupId() != 0 && (existMessageObject.photoThumbs == null || existMessageObject.photoThumbs.isEmpty())) {
MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(existMessageObject.getGroupId());
if (groupedMessages != null) {
int idx = groupedMessages.messages.indexOf(existMessageObject);
if (idx >= 0) {
int updateCount = groupedMessages.messages.size();
MessageObject messageObject = null;
if (idx > 0 && idx < groupedMessages.messages.size() - 1) {
MessageObject.GroupedMessages slicedGroup = new MessageObject.GroupedMessages();
slicedGroup.groupId = Utilities.random.nextLong();
slicedGroup.messages.addAll(groupedMessages.messages.subList(idx + 1, groupedMessages.messages.size()));
for (int b = 0; b < slicedGroup.messages.size(); b++) {
slicedGroup.messages.get(b).localGroupId = slicedGroup.groupId;
groupedMessages.messages.remove(idx + 1);
}
groupedMessagesMap.put(slicedGroup.groupId, slicedGroup);
messageObject = slicedGroup.messages.get(slicedGroup.messages.size() - 1);
slicedGroup.calculate();
}
groupedMessages.messages.remove(idx);
if (groupedMessages.messages.isEmpty()) {
groupedMessagesMap.remove(groupedMessages.groupId);
} else {
if (messageObject == null) {
messageObject = groupedMessages.messages.get(groupedMessages.messages.size() - 1);
}
groupedMessages.calculate();
int index = messages.indexOf(messageObject);
if (index >= 0) {
if (chatAdapter != null) {
chatAdapter.notifyItemRangeChanged(index + chatAdapter.messagesStartRow, updateCount);
}
}
}
}
}
}
if (message.media.ttl_seconds != 0 && (message.media.photo instanceof TLRPC.TL_photoEmpty || message.media.document instanceof TLRPC.TL_documentEmpty)) {
existMessageObject.setType();
if (chatAdapter != null) {
chatAdapter.updateRowWithMessageObject(existMessageObject, false);
}
} else {
updateVisibleRows();
}
}
} else if (id == NotificationCenter.replaceMessagesObjects) {
long did = (long) args[0];
if (did != dialog_id && did != mergeDialogId) {
return;
}
int loadIndex = did == dialog_id ? 0 : 1;
ArrayList<MessageObject> messageObjects = (ArrayList<MessageObject>) args[1];
replaceMessageObjects(messageObjects, loadIndex, false);
} else if (id == NotificationCenter.notificationsSettingsUpdated) {
updateTitleIcons();
if (ChatObject.isChannel(currentChat) || UserObject.isReplyUser(currentUser)) {
updateBottomOverlay();
}
} else if (id == NotificationCenter.replyMessagesDidLoad) {
long did = (Long) args[0];
if (did == dialog_id) {
ArrayList<MessageObject> loadedMessages = (ArrayList<MessageObject>) args[1];
LongSparseArray<SparseArray<ArrayList<MessageObject>>> replyMessageOwners = (LongSparseArray<SparseArray<ArrayList<MessageObject>>>) args[2];
for (int a = 0, N = loadedMessages.size(); a < N; a++) {
MessageObject obj = loadedMessages.get(a);
repliesMessagesDict.put(obj.getId(), obj);
}
if (replyMessageOwners != null) {
for (int a = 0, N = replyMessageOwners.size(); a < N; a++) {
SparseArray<ArrayList<MessageObject>> sparseArray = replyMessageOwners.valueAt(a);
for (int c = 0, N3 = sparseArray.size(); c < N3; c++) {
ArrayList<MessageObject> arrayList = sparseArray.valueAt(c);
for (int b = 0, N2 = arrayList.size(); b < N2; b++) {
addReplyMessageOwner(arrayList.get(b), 0);
}
}
}
}
updateVisibleRows();
} else if (waitingForReplies.size() != 0 && ChatObject.isChannel(currentChat) && !currentChat.megagroup && chatInfo != null && did == -chatInfo.linked_chat_id) {
checkWaitingForReplies();
}
updateReplyMessageHeader(true);
} else if (id == NotificationCenter.didLoadPinnedMessages) {
long did = (Long) args[0];
if (did == dialog_id) {
ArrayList<Integer> ids = (ArrayList<Integer>) args[1];
boolean pin = (Boolean) args[2];
ArrayList<MessageObject> arrayList = (ArrayList<MessageObject>) args[3];
HashMap<Integer, MessageObject> dict = null;
if (ids != null) {
HashMap<Integer, MessageObject> replaceObjects = (HashMap<Integer, MessageObject>) args[4];
int maxId = (Integer) args[5];
int totalPinnedCount = (Integer) args[6];
boolean endReached = (Boolean) args[7];
HashMap<Integer, MessageObject> oldPinned = new HashMap<>(pinnedMessageObjects);
if (replaceObjects != null) {
loadingPinnedMessagesList = false;
if (maxId == 0) {
pinnedMessageIds.clear();
pinnedMessageObjects.clear();
}
totalPinnedMessagesCount = totalPinnedCount;
pinnedEndReached = endReached;
}
boolean updated = false;
if (arrayList != null) {
getMediaDataController().loadReplyMessagesForMessages(arrayList, dialog_id, false, null);
}
for (int a = 0, N = ids.size(); a < N; a++) {
Integer mid = ids.get(a);
if (pin) {
if (pinnedMessageObjects.containsKey(mid)) {
continue;
}
pinnedMessageIds.add(mid);
MessageObject object = oldPinned.get(mid);
if (object == null) {
object = messagesDict[0].get(mid);
}
if (object == null && arrayList != null) {
if (dict == null) {
dict = new HashMap<>();
for (int b = 0, N2 = arrayList.size(); b < N2; b++) {
MessageObject obj = arrayList.get(b);
if (obj != null) {
dict.put(obj.getId(), obj);
}
}
}
object = dict.get(mid);
}
if (object == null && replaceObjects != null) {
object = replaceObjects.get(mid);
}
pinnedMessageObjects.put(mid, object);
if (replaceObjects == null) {
totalPinnedMessagesCount++;
}
} else {
if (!pinnedMessageObjects.containsKey(mid)) {
continue;
}
pinnedMessageObjects.remove(mid);
pinnedMessageIds.remove(mid);
if (replaceObjects == null) {
totalPinnedMessagesCount--;
}
}
loadedPinnedMessagesCount = pinnedMessageIds.size();
if (chatAdapter != null) {
MessageObject obj = messagesDict[0].get(mid);
if (obj != null) {
if (obj.hasValidGroupId()) {
MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(obj.getGroupId());
if (groupedMessages != null) {
int index = messages.indexOf(groupedMessages.messages.get(groupedMessages.messages.size() - 1));
if (index >= 0) {
chatAdapter.notifyItemRangeChanged(index, groupedMessages.messages.size());
}
}
} else {
chatAdapter.updateRowWithMessageObject(obj, false);
}
}
}
updated = true;
}
if (updated) {
if (chatMode == MODE_PINNED && avatarContainer != null) {
avatarContainer.setTitle(LocaleController.formatPluralString("PinnedMessagesCount", getPinnedMessagesCount()));
}
Collections.sort(pinnedMessageIds, (o1, o2) -> o2.compareTo(o1));
if (pinnedMessageIds.isEmpty()) {
hidePinnedMessageView(true);
} else {
updateMessagesVisiblePart(false);
}
}
if (chatMode == MODE_PINNED) {
if (pin) {
if (arrayList != null) {
processNewMessages(arrayList);
}
} else {
processDeletedMessages(ids, ChatObject.isChannel(currentChat) ? dialog_id : 0);
}
}
} else {
if (pin) {
for (int a = 0, N = arrayList.size(); a < N; a++) {
MessageObject message = arrayList.get(a);
if (pinnedMessageObjects.containsKey(message.getId())) {
pinnedMessageObjects.put(message.getId(), message);
}
loadingPinnedMessages.remove(message.getId());
}
getMediaDataController().loadReplyMessagesForMessages(arrayList, dialog_id, false, null);
updateMessagesVisiblePart(false);
} else {
pinnedMessageIds.clear();
pinnedMessageObjects.clear();
currentPinnedMessageId = 0;
loadedPinnedMessagesCount = 0;
totalPinnedMessagesCount = 0;
hidePinnedMessageView(true);
}
}
}
} else if (id == NotificationCenter.didReceivedWebpages) {
ArrayList<TLRPC.Message> arrayList = (ArrayList<TLRPC.Message>) args[0];
boolean updated = false;
for (int a = 0; a < arrayList.size(); a++) {
TLRPC.Message message = arrayList.get(a);
long did = MessageObject.getDialogId(message);
if (did != dialog_id && did != mergeDialogId) {
continue;
}
MessageObject currentMessage = messagesDict[did == dialog_id ? 0 : 1].get(message.id);
if (currentMessage != null) {
currentMessage.messageOwner.media = new TLRPC.TL_messageMediaWebPage();
currentMessage.messageOwner.media.webpage = message.media.webpage;
currentMessage.generateThumbs(true);
updated = true;
}
}
if (updated) {
updateVisibleRows();
}
} else if (id == NotificationCenter.didReceivedWebpagesInUpdates) {
if (foundWebPage != null) {
LongSparseArray<TLRPC.WebPage> hashMap = (LongSparseArray<TLRPC.WebPage>) args[0];
for (int a = 0; a < hashMap.size(); a++) {
TLRPC.WebPage webPage = hashMap.valueAt(a);
if (webPage.id == foundWebPage.id) {
showFieldPanelForWebPage(!(webPage instanceof TLRPC.TL_webPageEmpty), webPage, false);
break;
}
}
}
} else if (id == NotificationCenter.messagesReadContent) {
long did = (Long) args[0];
if (did != dialog_id && (ChatObject.isChannel(currentChat) || did != 0)) {
return;
}
ArrayList<Integer> arrayList = (ArrayList<Integer>) args[1];
for (int a = 0, N = arrayList.size(); a < N; a++) {
int mid = arrayList.get(a);
MessageObject currentMessage = messagesDict[0].get(mid);
if (currentMessage != null) {
currentMessage.setContentIsRead();
if (currentMessage.messageOwner.mentioned) {
newMentionsCount--;
if (newMentionsCount <= 0) {
newMentionsCount = 0;
hasAllMentionsLocal = true;
showMentionDownButton(false, true);
} else {
if (mentiondownButtonCounter != null) {
mentiondownButtonCounter.setText(String.format("%d", newMentionsCount));
}
}
}
if (chatAdapter != null) {
chatAdapter.invalidateRowWithMessageObject(currentMessage);
}
}
}
} else if (id == NotificationCenter.botInfoDidLoad) {
int guid = (Integer) args[1];
if (classGuid == guid || guid == 0) {
TLRPC.BotInfo info = (TLRPC.BotInfo) args[0];
if (currentEncryptedChat == null) {
if (!info.commands.isEmpty() && !ChatObject.isChannel(currentChat) && !isThreadChat()) {
hasBotsCommands = true;
}
botInfo.put(info.user_id, info);
if (chatAdapter != null) {
int prevRow = chatAdapter.botInfoRow;
chatAdapter.updateRowsInternal();
if (prevRow < 0 && chatAdapter.botInfoRow >= 0) {
chatAdapter.notifyItemInserted(chatAdapter.botInfoRow);
} else if (prevRow >= 0 && chatAdapter.botInfoRow < 0) {
chatAdapter.notifyItemRemoved(prevRow);
} else if (prevRow >= 0 && chatAdapter.botInfoRow >= 0) {
chatAdapter.notifyItemChanged(chatAdapter.botInfoRow);
}
}
if (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup) {
if (mentionsAdapter != null) {
mentionsAdapter.setBotInfo(botInfo);
}
if (chatActivityEnterView != null) {
chatActivityEnterView.setBotInfo(botInfo);
}
}
if (chatActivityEnterView != null) {
chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands, true);
}
}
updateBotButtons();
}
} else if (id == NotificationCenter.botKeyboardDidLoad) {
if (dialog_id == (Long) args[1]) {
TLRPC.Message message = (TLRPC.Message) args[0];
if (message != null && !userBlocked) {
botButtons = new MessageObject(currentAccount, message, false, false);
checkBotKeyboard();
} else {
botButtons = null;
if (chatActivityEnterView != null) {
if (replyingMessageObject != null && botReplyButtons == replyingMessageObject) {
botReplyButtons = null;
hideFieldPanel(true);
}
chatActivityEnterView.setButtons(botButtons);
}
}
}
} else if (id == NotificationCenter.chatSearchResultsAvailable) {
if (classGuid == (Integer) args[0]) {
boolean jumpToMessage = (Boolean) args[6];
if (jumpToMessage) {
int messageId = (Integer) args[1];
long did = (Long) args[3];
if (messageId != 0) {
scrollToMessageId(messageId, 0, true, did == dialog_id ? 0 : 1, true, 0);
} else {
updateVisibleRows();
}
updateSearchButtons((Integer) args[2], (Integer) args[4], (Integer) args[5]);
if (searchItem != null) {
searchItem.setShowSearchProgress(false);
}
}
if (messagesSearchAdapter != null) {
messagesSearchAdapter.notifyDataSetChanged();
}
}
} else if (id == NotificationCenter.chatSearchResultsLoading) {
if (classGuid == (Integer) args[0]) {
if (searchItem != null) {
searchItem.setShowSearchProgress(true);
}
if (messagesSearchAdapter != null) {
messagesSearchAdapter.notifyDataSetChanged();
}
}
} else if (id == NotificationCenter.didUpdateMessagesViews) {
LongSparseArray<SparseIntArray> channelViews = (LongSparseArray<SparseIntArray>) args[0];
LongSparseArray<SparseIntArray> channelForwards = (LongSparseArray<SparseIntArray>) args[1];
LongSparseArray<SparseArray<TLRPC.MessageReplies>> channelReplies = (LongSparseArray<SparseArray<TLRPC.MessageReplies>>) args[2];
boolean addingReplies = (Boolean) args[3];
boolean updated = false;
LongSparseArray<MessageObject.GroupedMessages> newGroups = null;
ArrayList<Integer> updatedRows = null;
for (int b = 0; b < 2; b++) {
LongSparseArray<SparseIntArray> sparseArray = b == 0 ? channelViews : channelForwards;
if (sparseArray == null) {
continue;
}
SparseIntArray array = sparseArray.get(dialog_id);
if (array != null) {
for (int a = 0; a < array.size(); a++) {
int messageId = array.keyAt(a);
MessageObject messageObject = messagesDict[0].get(messageId);
if (messageObject != null) {
int newValue = array.get(messageId);
if (b == 0) {
if (newValue <= messageObject.messageOwner.views) {
continue;
}
messageObject.messageOwner.views = newValue;
} else {
if (newValue <= messageObject.messageOwner.forwards) {
continue;
}
messageObject.messageOwner.forwards = newValue;
}
if (messageObject.hasValidGroupId()) {
MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(messageObject.getGroupId());
if (groupedMessages != null) {
if (newGroups == null) {
newGroups = new LongSparseArray<>();
}
newGroups.put(groupedMessages.groupId, groupedMessages);
}
}
if (chatAdapter != null) {
chatAdapter.updateRowWithMessageObject(messageObject, false);
}
}
}
}
}
if (channelReplies != null) {
SparseArray<TLRPC.MessageReplies> array = channelReplies.get(dialog_id);
boolean hasChatInBack = false;
if (threadMessageObject != null && parentLayout != null) {
for (int a = 0, N = parentLayout.fragmentsStack.size() - 1; a < N; a++) {
BaseFragment fragment = parentLayout.fragmentsStack.get(a);
if (fragment != this && fragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) fragment;
if (chatActivity.needRemovePreviousSameChatActivity && chatActivity.dialog_id == dialog_id && chatActivity.getChatMode() == getChatMode()) {
hasChatInBack = true;
break;
}
}
}
}
if (array != null) {
for (int a = 0; a < array.size(); a++) {
int messageId = array.keyAt(a);
MessageObject messageObject = messagesDict[0].get(messageId);
if (messageObject != null && messageObject != threadMessageObject) {
TLRPC.MessageReplies newValue = array.get(messageId);
if (newValue == null || !addingReplies && messageObject.messageOwner.replies != null && newValue.replies_pts <= messageObject.messageOwner.replies.replies_pts && newValue.read_max_id <= messageObject.messageOwner.replies.read_max_id && newValue.max_id <= messageObject.messageOwner.replies.max_id) {
continue;
}
if (addingReplies) {
if (!hasChatInBack) {
if (messageObject.messageOwner.replies == null) {
messageObject.messageOwner.replies = new TLRPC.TL_messageReplies();
}
messageObject.messageOwner.replies.replies += newValue.replies;
for (int c = 0, N = newValue.recent_repliers.size(); c < N; c++) {
messageObject.messageOwner.replies.recent_repliers.remove(newValue.recent_repliers.get(c));
}
messageObject.messageOwner.replies.recent_repliers.addAll(0, newValue.recent_repliers);
while (messageObject.messageOwner.replies.recent_repliers.size() > 3) {
messageObject.messageOwner.replies.recent_repliers.remove(0);
}
}
} else {
if (messageObject.messageOwner.replies != null && messageObject.messageOwner.replies.read_max_id > newValue.read_max_id) {
newValue.read_max_id = messageObject.messageOwner.replies.read_max_id;
}
messageObject.messageOwner.replies = newValue;
}
if (messageObject.hasValidGroupId()) {
MessageObject.GroupedMessages groupedMessages = groupedMessagesMap.get(messageObject.getGroupId());
if (groupedMessages != null) {
if (newGroups == null) {
newGroups = new LongSparseArray<>();
}
newGroups.put(groupedMessages.groupId, groupedMessages);
for (int b = 0, N2 = groupedMessages.messages.size(); b < N2; b++) {
groupedMessages.messages.get(b).animateComments = true;
}
}
} else if (chatAdapter != null) {
int row = messages.indexOf(messageObject);
if (row >= 0) {
if (updatedRows == null) {
updatedRows = new ArrayList<>();
}
updatedRows.add(row + chatAdapter.messagesStartRow);
}
messageObject.animateComments = true;
}
updated = true;
}
}
}
}
if (updated) {
if (chatAdapter != null) {
if (newGroups != null) {
for (int b = 0, N = newGroups.size(); b < N; b++) {
MessageObject.GroupedMessages groupedMessages = newGroups.valueAt(b);
MessageObject messageObject = groupedMessages.messages.get(groupedMessages.messages.size() - 1);
int index = messages.indexOf(messageObject);
if (index >= 0) {
chatAdapter.notifyItemRangeChanged(index + chatAdapter.messagesStartRow, groupedMessages.messages.size());
}
}
}
if (updatedRows != null) {
for (int b = 0, N = updatedRows.size(); b < N; b++) {
chatAdapter.notifyItemChanged(updatedRows.get(b));
}
}
}
updateVisibleRows();
updateReplyMessageHeader(true);
}
} else if (id == NotificationCenter.peerSettingsDidLoad) {
long did = (Long) args[0];
if (did == dialog_id || currentUser != null && currentUser.id == did) {
updateTopPanel(!paused);
updateInfoTopView(true);
}
} else if (id == NotificationCenter.newDraftReceived) {
long did = (Long) args[0];
if (did == dialog_id) {
applyDraftMaybe(true);
}
} else if (id == NotificationCenter.pinnedInfoDidLoad) {
long did = (Long) args[0];
if (did == dialog_id) {
ArrayList<Integer> pinnedMessages = (ArrayList<Integer>) args[1];
if (chatMode == MODE_PINNED) {
pinnedMessageIds = new ArrayList<>(pinnedMessages);
pinnedMessageObjects = new HashMap<>((HashMap<Integer, MessageObject>) args[2]);
} else {
pinnedMessageIds = pinnedMessages;
pinnedMessageObjects = (HashMap<Integer, MessageObject>) args[2];
}
loadedPinnedMessagesCount = pinnedMessageIds.size();
totalPinnedMessagesCount = (Integer) args[3];
pinnedEndReached = (Boolean) args[4];
getMediaDataController().loadReplyMessagesForMessages(new ArrayList<>(pinnedMessageObjects.values()), dialog_id, false, null);
if (!inMenuMode && !loadingPinnedMessagesList && totalPinnedMessagesCount == 0 && !pinnedEndReached) {
getMediaDataController().loadPinnedMessages(dialog_id, 0, pinnedMessageIds.isEmpty() ? 0 : pinnedMessageIds.get(0));
loadingPinnedMessagesList = true;
}
}
} else if (id == NotificationCenter.userInfoDidLoad) {
Long uid = (Long) args[0];
if (currentUser != null && currentUser.id == uid) {
userInfo = (TLRPC.UserFull) args[1];
checkThemeEmoticon();
if (headerItem != null) {
showAudioCallAsIcon = userInfo.phone_calls_available && !inPreviewMode;
if (userInfo.phone_calls_available) {
if (showAudioCallAsIcon) {
if (audioCallIconItem != null) {
if (openAnimationStartTime != 0 && audioCallIconItem.getVisibility() != View.VISIBLE) {
audioCallIconItem.setAlpha(0f);
audioCallIconItem.animate().alpha(1f).setDuration(150).start();
}
audioCallIconItem.setVisibility(View.VISIBLE);
}
} else {
headerItem.showSubItem(call);
}
if (userInfo.video_calls_available) {
headerItem.showSubItem(video_call);
} else {
headerItem.hideSubItem(video_call);
}
} else {
headerItem.hideSubItem(call);
headerItem.hideSubItem(video_call);
if (audioCallIconItem != null) {
audioCallIconItem.setVisibility(View.GONE);
}
}
}
checkActionBarMenu(false);
if (!inMenuMode && !loadingPinnedMessagesList && !pinnedMessageIds.isEmpty() && userInfo.pinned_msg_id > pinnedMessageIds.get(0)) {
getMediaDataController().loadPinnedMessages(dialog_id, 0, userInfo.pinned_msg_id);
loadingPinnedMessagesList = true;
}
}
} else if (id == NotificationCenter.didSetNewWallpapper) {
if (fragmentView != null) {
contentView.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion());
progressView2.invalidate();
if (emptyView != null) {
emptyView.invalidate();
}
if (bigEmptyView != null) {
bigEmptyView.invalidate();
}
if (floatingDateView != null) {
floatingDateView.invalidate();
}
chatListView.invalidateViews();
}
} else if (id == NotificationCenter.didApplyNewTheme) {
if (undoView == null || paused) {
return;
}
Theme.ThemeInfo themeInfo = (Theme.ThemeInfo) args[0];
Theme.ThemeAccent themeAccent = (Theme.ThemeAccent) args[1];
if (!themeInfo.firstAccentIsDefault || themeAccent == null || themeAccent.id != Theme.DEFALT_THEME_ACCENT_ID) {
return;
}
SharedPreferences preferences = MessagesController.getGlobalMainSettings();
if (preferences.getBoolean("themehint", false)) {
return;
}
preferences.edit().putBoolean("themehint", true).commit();
boolean deleteTheme = (Boolean) args[2];
undoView.showWithAction(0, UndoView.ACTION_THEME_CHANGED, null, () -> {
if (themeAccent != null) {
Theme.ThemeAccent prevAccent = themeInfo.getAccent(false);
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, themeInfo, false, null, themeAccent.id);
if (deleteTheme) {
Theme.deleteThemeAccent(themeInfo, prevAccent, true);
}
} else {
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, themeInfo, false, null, -1);
}
});
} else if (id == NotificationCenter.goingToPreviewTheme) {
isPauseOnThemePreview = true;
if (chatLayoutManager != null) {
scrollToPositionOnRecreate = chatLayoutManager.findFirstVisibleItemPosition();
RecyclerListView.Holder holder = (RecyclerListView.Holder) chatListView.findViewHolderForAdapterPosition(scrollToPositionOnRecreate);
if (holder != null) {
scrollToOffsetOnRecreate = chatListView.getMeasuredHeight() - holder.itemView.getBottom() - chatListView.getPaddingBottom();
} else {
scrollToPositionOnRecreate = -1;
}
}
} else if (id == NotificationCenter.channelRightsUpdated) {
TLRPC.Chat chat = (TLRPC.Chat) args[0];
if (currentChat != null && chat.id == currentChat.id && chatActivityEnterView != null) {
currentChat = chat;
chatActivityEnterView.checkChannelRights();
checkRaiseSensors();
updateSecretStatus();
if (currentChat.gigagroup) {
updateBottomOverlay();
}
}
} else if (id == NotificationCenter.updateMentionsCount) {
if (dialog_id == (Long) args[0]) {
int count = (int) args[1];
if (newMentionsCount > count) {
newMentionsCount = count;
if (newMentionsCount <= 0) {
newMentionsCount = 0;
hasAllMentionsLocal = true;
showMentionDownButton(false, true);
} else {
mentiondownButtonCounter.setText(String.format("%d", newMentionsCount));
}
}
}
} else if (id == NotificationCenter.audioRecordTooShort) {
int guid = (Integer) args[0];
if (guid != classGuid) {
return;
}
int time = (Integer) args[2];
if (time < 100) {
showVoiceHint(false, (Boolean) args[1]);
}
} else if (id == NotificationCenter.videoLoadingStateChanged) {
if (chatListView != null) {
String fileName = (String) args[0];
int count = chatListView.getChildCount();
for (int a = 0; a < count; a++) {
View child = chatListView.getChildAt(a);
if (!(child instanceof ChatMessageCell)) {
continue;
}
ChatMessageCell cell = (ChatMessageCell) child;
TLRPC.Document document = cell.getStreamingMedia();
if (document == null) {
continue;
}
if (FileLoader.getAttachFileName(document).equals(fileName)) {
cell.updateButtonState(false, true, false);
}
}
}
} else if (id == NotificationCenter.scheduledMessagesUpdated) {
long did = (Long) args[0];
if (dialog_id == did) {
scheduledMessagesCount = (Integer) args[1];
updateScheduledInterface(openAnimationEnded);
}
} else if (id == NotificationCenter.diceStickersDidLoad) {
if (chatListView == null) {
return;
}
int count = chatListView.getChildCount();
for (int a = 0; a < count; a++) {
View child = chatListView.getChildAt(a);
if (!(child instanceof ChatMessageCell)) {
continue;
}
ChatMessageCell cell = (ChatMessageCell) child;
if (cell.getMessageObject().isDice()) {
cell.setCurrentDiceValue(true);
}
}
} else if (id == NotificationCenter.dialogDeleted) {
long did = (Long) args[0];
if (did == dialog_id) {
if (parentLayout != null && parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 1) == this) {
finishFragment();
} else {
removeSelfFromStack();
}
}
} else if (id == NotificationCenter.needSetDayNightTheme) {
Theme.ThemeInfo theme = (Theme.ThemeInfo) args[0];
if (theme != null) {
if (chatThemeBottomSheet != null) {
chatThemeBottomSheet.setupLightDarkTheme(theme.isDark());
} else {
themeDelegate.setCurrentTheme(themeDelegate.chatTheme, true, theme.isDark());
}
}
} else if (id == NotificationCenter.chatAvailableReactionsUpdated) {
long chatId = (long) args[0];
if (chatId == -dialog_id) {
chatInfo = getMessagesController().getChatFull(chatId);
}
} else if (id == NotificationCenter.dialogsUnreadReactionsCounterChanged) {
long dialogId = (long) args[0];
if (dialogId == dialog_id) {
reactionsMentionCount = (int) args[1];
ArrayList<Integer> messages = null;
if (args[2] != null) {
messages = (ArrayList<Integer>) args[2];
}
if (messages != null) {
for (int i = 0; i < messages.size(); i++) {
int messageId = messages.get(i);
ChatMessageCell cell = findMessageCell(messageId, true);
if (cell != null && reactionsMentionCount > 0) {
reactionsMentionCount--;
getMessagesStorage().markMessageReactionsAsRead(getDialogId(), cell.getMessageObject().getId(), true);
AndroidUtilities.runOnUIThread(() -> {
playReactionAnimation(messageId);
}, 200);
}
}
}
if (reactionsMentionCount <= 0) {
reactionsMentionCount = 0;
getMessagesController().markReactionsAsRead(dialogId);
}
updateReactionsMentionButton(true);
}
}
}
Aggregations