From 4c686bb278ab49ff2a975bfd96d32abedde11613 Mon Sep 17 00:00:00 2001 From: "B. Petersen" Date: Fri, 7 Oct 2016 15:20:18 +0200 Subject: [PATCH] Delete some files; add native functions for readling mrloginparam_t. --- TMessagesProj/jni/mr_wrapper.c | 92 +- .../org/telegram/messenger/MrMailbox.java | 17 + .../org/telegram/ui/ChangePhoneActivity.java | 1415 ----------------- .../telegram/ui/ChangePhoneHelpActivity.java | 156 -- .../telegram/ui/ChannelCreateActivity.java | 1176 -------------- .../org/telegram/ui/ChannelEditActivity.java | 605 ------- .../telegram/ui/ChannelEditTypeActivity.java | 538 ------- .../org/telegram/ui/ChannelIntroActivity.java | 150 -- .../org/telegram/ui/ChannelUsersActivity.java | 717 --------- .../ui/TwoStepVerificationActivity.java | 1072 ------------- 10 files changed, 106 insertions(+), 5832 deletions(-) delete mode 100644 TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java delete mode 100644 TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneHelpActivity.java delete mode 100644 TMessagesProj/src/main/java/org/telegram/ui/ChannelCreateActivity.java delete mode 100644 TMessagesProj/src/main/java/org/telegram/ui/ChannelEditActivity.java delete mode 100644 TMessagesProj/src/main/java/org/telegram/ui/ChannelEditTypeActivity.java delete mode 100644 TMessagesProj/src/main/java/org/telegram/ui/ChannelIntroActivity.java delete mode 100644 TMessagesProj/src/main/java/org/telegram/ui/ChannelUsersActivity.java delete mode 100644 TMessagesProj/src/main/java/org/telegram/ui/TwoStepVerificationActivity.java diff --git a/TMessagesProj/jni/mr_wrapper.c b/TMessagesProj/jni/mr_wrapper.c index 27850f606..92af674ed 100644 --- a/TMessagesProj/jni/mr_wrapper.c +++ b/TMessagesProj/jni/mr_wrapper.c @@ -31,11 +31,10 @@ #define CHAR_REF(a) \ - const char* a##Ptr = (*env)->GetStringUTFChars(env, (a), 0); \ - if( a##Ptr == NULL ) { return 0; } + const char* a##Ptr = (a)? (*env)->GetStringUTFChars(env, (a), 0) : NULL; /* passing a NULL-jstring results in a NULL-ptr */ #define CHAR_UNREF(a) \ - (*env)->ReleaseStringUTFChars(env, (a), a##Ptr); + if(a) { (*env)->ReleaseStringUTFChars(env, (a), a##Ptr); } #define JSTRING_NEW(a) \ (*env)->NewStringUTF(env, a? a : "") /*should handle NULL arguments!*/ @@ -140,6 +139,18 @@ JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrMailboxGetConfig(JNIEn } +JNIEXPORT jlong Java_org_telegram_messenger_MrMailbox_MrMailboxSuggestConfig(JNIEnv *env, jclass c, jlong hMailbox) +{ + return (jlong)mrmailbox_suggest_config((mrmailbox_t*)hMailbox); +} + + +JNIEXPORT jint Java_org_telegram_messenger_MrMailbox_MrMailboxIsConfigured(JNIEnv *env, jclass c, jlong hMailbox) +{ + return (jint)mrmailbox_is_configured((mrmailbox_t*)hMailbox); +} + + /******************************************************************************* * MrChatlist ******************************************************************************/ @@ -337,6 +348,81 @@ JNIEXPORT jint Java_org_telegram_messenger_MrMailbox_MrPoortextGetState(JNIEnv * } +/******************************************************************************* + * MrLoginparam + ******************************************************************************/ + + +JNIEXPORT void Java_org_telegram_messenger_MrMailbox_MrLoginparamUnref(JNIEnv *env, jclass c, jlong hLoginparam) +{ + return mrloginparam_unref((mrloginparam_t*)hLoginparam); +} + + +JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrLoginparamGetAddr(JNIEnv *env, jclass c, jlong hLoginparam) +{ + mrloginparam_t* ths = (mrloginparam_t*)hLoginparam; if( ths == NULL ) { return JSTRING_NEW(NULL); } + return JSTRING_NEW(ths->m_addr); +} + + +JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrLoginparamGetMailServer(JNIEnv *env, jclass c, jlong hLoginparam) +{ + mrloginparam_t* ths = (mrloginparam_t*)hLoginparam; if( ths == NULL ) { return JSTRING_NEW(NULL); } + return JSTRING_NEW(ths->m_mail_server); +} + + +JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrLoginparamGetMailUser(JNIEnv *env, jclass c, jlong hLoginparam) +{ + mrloginparam_t* ths = (mrloginparam_t*)hLoginparam; if( ths == NULL ) { return JSTRING_NEW(NULL); } + return JSTRING_NEW(ths->m_mail_user); +} + + + +JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrLoginparamGetMailPw(JNIEnv *env, jclass c, jlong hLoginparam) +{ + mrloginparam_t* ths = (mrloginparam_t*)hLoginparam; if( ths == NULL ) { return JSTRING_NEW(NULL); } + return JSTRING_NEW(ths->m_mail_pw); +} + + +JNIEXPORT jint Java_org_telegram_messenger_MrMailbox_MrLoginparamGetMailPort(JNIEnv *env, jclass c, jlong hLoginparam) +{ + mrloginparam_t* ths = (mrloginparam_t*)hLoginparam; if( ths == NULL ) { return JSTRING_NEW(NULL); } + return (jint)ths->m_mail_port; +} + + +JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrLoginparamGetSendServer(JNIEnv *env, jclass c, jlong hLoginparam) +{ + mrloginparam_t* ths = (mrloginparam_t*)hLoginparam; if( ths == NULL ) { return JSTRING_NEW(NULL); } + return JSTRING_NEW(ths->m_send_server); +} + + +JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrLoginparamGetSendUser(JNIEnv *env, jclass c, jlong hLoginparam) +{ + mrloginparam_t* ths = (mrloginparam_t*)hLoginparam; if( ths == NULL ) { return JSTRING_NEW(NULL); } + return JSTRING_NEW(ths->m_send_user); +} + + +JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrLoginparamGetSendPw(JNIEnv *env, jclass c, jlong hLoginparam) +{ + mrloginparam_t* ths = (mrloginparam_t*)hLoginparam; if( ths == NULL ) { return JSTRING_NEW(NULL); } + return JSTRING_NEW(ths->m_send_pw); +} + + +JNIEXPORT jint Java_org_telegram_messenger_MrMailbox_MrLoginparamGetSendPort(JNIEnv *env, jclass c, jlong hLoginparam) +{ + mrloginparam_t* ths = (mrloginparam_t*)hLoginparam; if( ths == NULL ) { return JSTRING_NEW(NULL); } + return (jint)ths->m_send_port; +} + + /******************************************************************************* * Tools ******************************************************************************/ diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MrMailbox.java b/TMessagesProj/src/main/java/org/telegram/messenger/MrMailbox.java index 2b41fd324..75ad36e77 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MrMailbox.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MrMailbox.java @@ -89,6 +89,11 @@ public class MrMailbox { public native static long MrMailboxGetChatlist (long hMailbox); // returns hChatlist which must be unref'd after usage public native static long MrMailboxGetChatById (long hMailbox, int id); // return hChat which must be unref'd after usage + public native static int MrMailboxSetConfig (long hMailbox, String key, String value); // value may be NULL + public native static String MrMailboxGetConfig (long hMailbox, String key, String def); // def may be NULL, returns empty string as NULL + public native static long MrMailboxSuggestConfig (long hMailbox); // return hLoginparam which must be unref'd after usage + public native static int MrMailboxIsConfigured (long hMailbox); + // MrChatlist objects public native static void MrChatlistUnref (long hChatlist); public native static int MrChatlistGetCnt (long hChatlist); @@ -125,6 +130,18 @@ public class MrMailbox { public native static long MrPoortextGetTimestamp (long hPoortext); public native static int MrPoortextGetState (long hPoortext); + // MrLoginparam objects + public native static void MrLoginparamUnref (long hLoginparam); + public native static String MrLoginparamGetAddr (long hLoginparam); + public native static String MrLoginparamGetMailServer (long hLoginparam); + public native static String MrLoginparamGetMailUser (long hLoginparam); + public native static String MrLoginparamGetMailPw (long hLoginparam); + public native static int MrLoginparamGetMailPort (long hLoginparam); + public native static String MrLoginparamGetSendServer (long hLoginparam); + public native static String MrLoginparamGetSendUser (long hLoginparam); + public native static String MrLoginparamGetSendPw (long hLoginparam); + public native static int MrLoginparamGetSendPort (long hLoginparam); + // Tools public native static void MrStockAddStr (int id, String str); public native static String MrGetVersionStr (); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java deleted file mode 100644 index 4ab801a98..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java +++ /dev/null @@ -1,1415 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.ui; - -import android.Manifest; -import android.animation.Animator; -import android.animation.AnimatorSet; -import android.animation.ObjectAnimator; -import android.app.Activity; -import android.app.AlertDialog; -import android.app.Dialog; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.os.Build; -import android.os.Bundle; -import android.telephony.TelephonyManager; -import android.text.Editable; -import android.text.InputFilter; -import android.text.InputType; -import android.text.TextUtils; -import android.text.TextWatcher; -import android.util.TypedValue; -import android.view.Gravity; -import android.view.KeyEvent; -import android.view.View; -import android.view.animation.AccelerateDecelerateInterpolator; -import android.view.inputmethod.EditorInfo; -import android.widget.AdapterView; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ScrollView; -import android.widget.TextView; - -import org.telegram.PhoneFormat.PhoneFormat; -import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.MessagesController; -import org.telegram.messenger.MessagesStorage; -import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.ApplicationLoader; -import org.telegram.messenger.BuildVars; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.R; -import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.RequestDelegate; -import org.telegram.tgnet.TLObject; -import org.telegram.tgnet.TLRPC; -import org.telegram.messenger.UserConfig; -import org.telegram.ui.ActionBar.ActionBar; -import org.telegram.ui.ActionBar.ActionBarMenu; -import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.messenger.AnimatorListenerAdapterProxy; -import org.telegram.ui.Components.HintEditText; -import org.telegram.ui.Components.LayoutHelper; -import org.telegram.ui.Components.SlideView; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Locale; -import java.util.Timer; -import java.util.TimerTask; - -public class ChangePhoneActivity extends BaseFragment { - - private int currentViewNum = 0; - private SlideView[] views = new SlideView[5]; - private ProgressDialog progressDialog; - private Dialog permissionsDialog; - private ArrayList permissionsItems = new ArrayList<>(); - private boolean checkPermissions = true; - private View doneButton; - - private final static int done_button = 1; - - @Override - public void onFragmentDestroy() { - super.onFragmentDestroy(); - for (int a = 0; a < views.length; a++) { - if (views[a] != null) { - views[a].onDestroyActivity(); - } - } - if (progressDialog != null) { - try { - progressDialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - progressDialog = null; - } - AndroidUtilities.removeAdjustResize(getParentActivity(), classGuid); - } - - @Override - public View createView(Context context) { - actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName)); - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == done_button) { - views[currentViewNum].onNextPressed(); - } else if (id == -1) { - finishFragment(); - } - } - }); - - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - fragmentView = new ScrollView(context); - ScrollView scrollView = (ScrollView) fragmentView; - scrollView.setFillViewport(true); - - FrameLayout frameLayout = new FrameLayout(context); - scrollView.addView(frameLayout, LayoutHelper.createScroll(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT)); - - views[0] = new PhoneView(context); - views[1] = new LoginActivitySmsView(context, 1); - views[2] = new LoginActivitySmsView(context, 2); - views[3] = new LoginActivitySmsView(context, 3); - views[4] = new LoginActivitySmsView(context, 4); - - for (int a = 0; a < views.length; a++) { - views[a].setVisibility(a == 0 ? View.VISIBLE : View.GONE); - frameLayout.addView(views[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, a == 0 ? LayoutHelper.WRAP_CONTENT : LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 26 : 18, 30, AndroidUtilities.isTablet() ? 26 : 18, 0)); - //LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 30, 16, 0) - } - - actionBar.setTitle(views[0].getHeaderName()); - - return fragmentView; - } - - @Override - public void onResume() { - super.onResume(); - AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid); - } - - @Override - public void onRequestPermissionsResultFragment(int requestCode, String[] permissions, int[] grantResults) { - if (requestCode == 6) { - checkPermissions = false; - if (currentViewNum == 0) { - views[currentViewNum].onNextPressed(); - } - } - } - - @Override - protected void onDialogDismiss(Dialog dialog) { - if (Build.VERSION.SDK_INT >= 23 && dialog == permissionsDialog && !permissionsItems.isEmpty()) { - getParentActivity().requestPermissions(permissionsItems.toArray(new String[permissionsItems.size()]), 6); - } - } - - @Override - public boolean onBackPressed() { - if (currentViewNum == 0) { - for (int a = 0; a < views.length; a++) { - if (views[a] != null) { - views[a].onDestroyActivity(); - } - } - return true; - } else { - views[currentViewNum].onBackPressed(); - setPage(0, true, null, true); - } - return false; - } - - @Override - public void onTransitionAnimationEnd(boolean isOpen, boolean backward) { - if (isOpen) { - views[currentViewNum].onShow(); - } - } - - public void needShowAlert(final String text) { - if (text == null || getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setMessage(text); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); - showDialog(builder.create()); - } - - public void needShowProgress() { - if (getParentActivity() == null || getParentActivity().isFinishing() || progressDialog != null) { - return; - } - progressDialog = new ProgressDialog(getParentActivity()); - progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); - progressDialog.setCanceledOnTouchOutside(false); - progressDialog.setCancelable(false); - progressDialog.show(); - } - - public void needHideProgress() { - if (progressDialog == null) { - return; - } - try { - progressDialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - progressDialog = null; - } - - public void setPage(int page, boolean animated, Bundle params, boolean back) { - if (page == 3) { - doneButton.setVisibility(View.GONE); - } else { - if (page == 0) { - checkPermissions = true; - } - doneButton.setVisibility(View.VISIBLE); - } - final SlideView outView = views[currentViewNum]; - final SlideView newView = views[page]; - currentViewNum = page; - - newView.setParams(params); - actionBar.setTitle(newView.getHeaderName()); - newView.onShow(); - newView.setX(back ? -AndroidUtilities.displaySize.x : AndroidUtilities.displaySize.x); - - AnimatorSet animatorSet = new AnimatorSet(); - animatorSet.setInterpolator(new AccelerateDecelerateInterpolator()); - animatorSet.setDuration(300); - animatorSet.playTogether( - ObjectAnimator.ofFloat(outView, "translationX", back ? AndroidUtilities.displaySize.x : -AndroidUtilities.displaySize.x), - ObjectAnimator.ofFloat(newView, "translationX", 0)); - animatorSet.addListener(new AnimatorListenerAdapterProxy() { - @Override - public void onAnimationStart(Animator animation) { - newView.setVisibility(View.VISIBLE); - } - - @Override - public void onAnimationEnd(Animator animation) { - outView.setVisibility(View.GONE); - outView.setX(0); - } - }); - animatorSet.start(); - } - - private void fillNextCodeParams(Bundle params, TLRPC.TL_auth_sentCode res) { - params.putString("phoneHash", res.phone_code_hash); - if (res.next_type instanceof TLRPC.TL_auth_codeTypeCall) { - params.putInt("nextType", 4); - } else if (res.next_type instanceof TLRPC.TL_auth_codeTypeFlashCall) { - params.putInt("nextType", 3); - } else if (res.next_type instanceof TLRPC.TL_auth_codeTypeSms) { - params.putInt("nextType", 2); - } - if (res.type instanceof TLRPC.TL_auth_sentCodeTypeApp) { - params.putInt("type", 1); - params.putInt("length", res.type.length); - setPage(1, true, params, false); - } else { - if (res.timeout == 0) { - res.timeout = 60; - } - params.putInt("timeout", res.timeout * 1000); - if (res.type instanceof TLRPC.TL_auth_sentCodeTypeCall) { - params.putInt("type", 4); - params.putInt("length", res.type.length); - setPage(4, true, params, false); - } else if (res.type instanceof TLRPC.TL_auth_sentCodeTypeFlashCall) { - params.putInt("type", 3); - params.putString("pattern", res.type.pattern); - setPage(3, true, params, false); - } else if (res.type instanceof TLRPC.TL_auth_sentCodeTypeSms) { - params.putInt("type", 2); - params.putInt("length", res.type.length); - setPage(2, true, params, false); - } - } - } - - public class PhoneView extends SlideView implements AdapterView.OnItemSelectedListener { - - private EditText codeField; - private HintEditText phoneField; - private TextView countryButton; - - private int countryState = 0; - - private ArrayList countriesArray = new ArrayList<>(); - private HashMap countriesMap = new HashMap<>(); - private HashMap codesMap = new HashMap<>(); - private HashMap phoneFormatMap = new HashMap<>(); - - private boolean ignoreSelection = false; - private boolean ignoreOnTextChange = false; - private boolean ignoreOnPhoneChange = false; - private boolean nextPressed = false; - - public PhoneView(Context context) { - super(context); - - setOrientation(VERTICAL); - - countryButton = new TextView(context); - countryButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - countryButton.setPadding(AndroidUtilities.dp(12), AndroidUtilities.dp(10), AndroidUtilities.dp(12), 0); - countryButton.setTextColor(0xff212121); - countryButton.setMaxLines(1); - countryButton.setSingleLine(true); - countryButton.setEllipsize(TextUtils.TruncateAt.END); - countryButton.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_HORIZONTAL); - countryButton.setBackgroundResource(R.drawable.spinner_states); - addView(countryButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 0, 0, 0, 14)); - countryButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - CountrySelectActivity fragment = new CountrySelectActivity(); - fragment.setCountrySelectActivityDelegate(new CountrySelectActivity.CountrySelectActivityDelegate() { - @Override - public void didSelectCountry(String name) { - selectCountry(name); - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - AndroidUtilities.showKeyboard(phoneField); - } - }, 300); - phoneField.requestFocus(); - phoneField.setSelection(phoneField.length()); - } - }); - presentFragment(fragment); - } - }); - - View view = new View(context); - view.setPadding(AndroidUtilities.dp(12), 0, AndroidUtilities.dp(12), 0); - view.setBackgroundColor(0xffdbdbdb); - addView(view, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 1, 4, -17.5f, 4, 0)); - - LinearLayout linearLayout = new LinearLayout(context); - linearLayout.setOrientation(HORIZONTAL); - addView(linearLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 20, 0, 0)); - - TextView textView = new TextView(context); - textView.setText("+"); - textView.setTextColor(0xff212121); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - linearLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); - - codeField = new EditText(context); - codeField.setInputType(InputType.TYPE_CLASS_PHONE); - codeField.setTextColor(0xff212121); - AndroidUtilities.clearCursorDrawable(codeField); - codeField.setPadding(AndroidUtilities.dp(10), 0, 0, 0); - codeField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - codeField.setMaxLines(1); - codeField.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); - codeField.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI); - InputFilter[] inputFilters = new InputFilter[1]; - inputFilters[0] = new InputFilter.LengthFilter(5); - codeField.setFilters(inputFilters); - linearLayout.addView(codeField, LayoutHelper.createLinear(55, 36, -9, 0, 16, 0)); - codeField.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void afterTextChanged(Editable editable) { - if (ignoreOnTextChange) { - return; - } - ignoreOnTextChange = true; - String text = PhoneFormat.stripExceptNumbers(codeField.getText().toString()); - codeField.setText(text); - if (text.length() == 0) { - countryButton.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); - phoneField.setHintText(null); - countryState = 1; - } else { - String country; - boolean ok = false; - String textToSet = null; - if (text.length() > 4) { - ignoreOnTextChange = true; - for (int a = 4; a >= 1; a--) { - String sub = text.substring(0, a); - country = codesMap.get(sub); - if (country != null) { - ok = true; - textToSet = text.substring(a, text.length()) + phoneField.getText().toString(); - codeField.setText(text = sub); - break; - } - } - if (!ok) { - ignoreOnTextChange = true; - textToSet = text.substring(1, text.length()) + phoneField.getText().toString(); - codeField.setText(text = text.substring(0, 1)); - } - } - country = codesMap.get(text); - if (country != null) { - int index = countriesArray.indexOf(country); - if (index != -1) { - ignoreSelection = true; - countryButton.setText(countriesArray.get(index)); - String hint = phoneFormatMap.get(text); - phoneField.setHintText(hint != null ? hint.replace('X', '–') : null); - countryState = 0; - } else { - countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry)); - phoneField.setHintText(null); - countryState = 2; - } - } else { - countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry)); - phoneField.setHintText(null); - countryState = 2; - } - if (!ok) { - codeField.setSelection(codeField.getText().length()); - } - if (textToSet != null) { - phoneField.requestFocus(); - phoneField.setText(textToSet); - phoneField.setSelection(phoneField.length()); - } - } - ignoreOnTextChange = false; - } - }); - codeField.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_NEXT) { - phoneField.requestFocus(); - phoneField.setSelection(phoneField.length()); - return true; - } - return false; - } - }); - - phoneField = new HintEditText(context); - phoneField.setInputType(InputType.TYPE_CLASS_PHONE); - phoneField.setTextColor(0xff212121); - phoneField.setHintTextColor(0xff979797); - phoneField.setPadding(0, 0, 0, 0); - AndroidUtilities.clearCursorDrawable(phoneField); - phoneField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - phoneField.setMaxLines(1); - phoneField.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); - phoneField.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI); - linearLayout.addView(phoneField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36)); - phoneField.addTextChangedListener(new TextWatcher() { - - private int characterAction = -1; - private int actionPosition; - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - if (count == 0 && after == 1) { - characterAction = 1; - } else if (count == 1 && after == 0) { - if (s.charAt(start) == ' ' && start > 0) { - characterAction = 3; - actionPosition = start - 1; - } else { - characterAction = 2; - } - } else { - characterAction = -1; - } - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - if (ignoreOnPhoneChange) { - return; - } - int start = phoneField.getSelectionStart(); - String phoneChars = "0123456789"; - String str = phoneField.getText().toString(); - if (characterAction == 3) { - str = str.substring(0, actionPosition) + str.substring(actionPosition + 1, str.length()); - start--; - } - StringBuilder builder = new StringBuilder(str.length()); - for (int a = 0; a < str.length(); a++) { - String ch = str.substring(a, a + 1); - if (phoneChars.contains(ch)) { - builder.append(ch); - } - } - ignoreOnPhoneChange = true; - String hint = phoneField.getHintText(); - if (hint != null) { - for (int a = 0; a < builder.length(); a++) { - if (a < hint.length()) { - if (hint.charAt(a) == ' ') { - builder.insert(a, ' '); - a++; - if (start == a && characterAction != 2 && characterAction != 3) { - start++; - } - } - } else { - builder.insert(a, ' '); - if (start == a + 1 && characterAction != 2 && characterAction != 3) { - start++; - } - break; - } - } - } - phoneField.setText(builder); - if (start >= 0) { - phoneField.setSelection(start <= phoneField.length() ? start : phoneField.length()); - } - phoneField.onTextChange(); - ignoreOnPhoneChange = false; - } - }); - phoneField.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_NEXT) { - onNextPressed(); - return true; - } - return false; - } - }); - - textView = new TextView(context); - textView.setText(LocaleController.getString("ChangePhoneHelp", R.string.ChangePhoneHelp)); - textView.setTextColor(0xff757575); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - textView.setLineSpacing(AndroidUtilities.dp(2), 1.0f); - addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 0, 28, 0, 10)); - - HashMap languageMap = new HashMap<>(); - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(getResources().getAssets().open("countries.txt"))); - String line; - while ((line = reader.readLine()) != null) { - String[] args = line.split(";"); - countriesArray.add(0, args[2]); - countriesMap.put(args[2], args[0]); - codesMap.put(args[0], args[2]); - if (args.length > 3) { - phoneFormatMap.put(args[0], args[3]); - } - languageMap.put(args[1], args[2]); - } - reader.close(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - Collections.sort(countriesArray, new Comparator() { - @Override - public int compare(String lhs, String rhs) { - return lhs.compareTo(rhs); - } - }); - - String country = null; - - try { - TelephonyManager telephonyManager = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE); - if (telephonyManager != null) { - country = telephonyManager.getSimCountryIso().toUpperCase(); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - if (country != null) { - String countryName = languageMap.get(country); - if (countryName != null) { - int index = countriesArray.indexOf(countryName); - if (index != -1) { - codeField.setText(countriesMap.get(countryName)); - countryState = 0; - } - } - } - if (codeField.length() == 0) { - countryButton.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); - phoneField.setHintText(null); - countryState = 1; - } - - if (codeField.length() != 0) { - AndroidUtilities.showKeyboard(phoneField); - phoneField.requestFocus(); - phoneField.setSelection(phoneField.length()); - } else { - AndroidUtilities.showKeyboard(codeField); - codeField.requestFocus(); - } - } - - public void selectCountry(String name) { - int index = countriesArray.indexOf(name); - if (index != -1) { - ignoreOnTextChange = true; - String code = countriesMap.get(name); - codeField.setText(code); - countryButton.setText(name); - String hint = phoneFormatMap.get(code); - phoneField.setHintText(hint != null ? hint.replace('X', '–') : null); - countryState = 0; - ignoreOnTextChange = false; - } - } - - @Override - public void onItemSelected(AdapterView adapterView, View view, int i, long l) { - if (ignoreSelection) { - ignoreSelection = false; - return; - } - ignoreOnTextChange = true; - String str = countriesArray.get(i); - codeField.setText(countriesMap.get(str)); - ignoreOnTextChange = false; - } - - @Override - public void onNothingSelected(AdapterView adapterView) { - - } - - @Override - public void onNextPressed() { - if (getParentActivity() == null || nextPressed) { - return; - } - TelephonyManager tm = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE); - boolean simcardAvailable = tm.getSimState() != TelephonyManager.SIM_STATE_ABSENT && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE; - boolean allowCall = true; - if (Build.VERSION.SDK_INT >= 23 && simcardAvailable) { - allowCall = getParentActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED; - boolean allowSms = getParentActivity().checkSelfPermission(Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED; - if (checkPermissions) { - permissionsItems.clear(); - if (!allowCall) { - permissionsItems.add(Manifest.permission.READ_PHONE_STATE); - } - if (!allowSms) { - permissionsItems.add(Manifest.permission.RECEIVE_SMS); - } - if (!permissionsItems.isEmpty()) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - if (preferences.getBoolean("firstlogin", true) || getParentActivity().shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE) || getParentActivity().shouldShowRequestPermissionRationale(Manifest.permission.RECEIVE_SMS)) { - preferences.edit().putBoolean("firstlogin", false).commit(); - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); - if (permissionsItems.size() == 2) { - builder.setMessage(LocaleController.getString("AllowReadCallAndSms", R.string.AllowReadCallAndSms)); - } else if (!allowSms) { - builder.setMessage(LocaleController.getString("AllowReadSms", R.string.AllowReadSms)); - } else { - builder.setMessage(LocaleController.getString("AllowReadCall", R.string.AllowReadCall)); - } - permissionsDialog = showDialog(builder.create()); - } else { - getParentActivity().requestPermissions(permissionsItems.toArray(new String[permissionsItems.size()]), 6); - } - return; - } - } - } - - if (countryState == 1) { - needShowAlert(LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); - return; - } else if (countryState == 2 && !BuildVars.DEBUG_VERSION) { - needShowAlert(LocaleController.getString("WrongCountry", R.string.WrongCountry)); - return; - } - if (codeField.length() == 0) { - needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); - return; - } - TLRPC.TL_account_sendChangePhoneCode req = new TLRPC.TL_account_sendChangePhoneCode(); - String phone = PhoneFormat.stripExceptNumbers("" + codeField.getText() + phoneField.getText()); - req.phone_number = phone; - req.allow_flashcall = simcardAvailable && allowCall; - if (req.allow_flashcall) { - String number = tm.getLine1Number(); - req.current_number = number != null && number.length() != 0 && (phone.contains(number) || number.contains(phone)); - } - - final Bundle params = new Bundle(); - params.putString("phone", "+" + codeField.getText() + phoneField.getText()); - try { - params.putString("ephone", "+" + PhoneFormat.stripExceptNumbers(codeField.getText().toString()) + " " + PhoneFormat.stripExceptNumbers(phoneField.getText().toString())); - } catch (Exception e) { - FileLog.e("tmessages", e); - params.putString("ephone", "+" + phone); - } - params.putString("phoneFormated", phone); - nextPressed = true; - needShowProgress(); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - nextPressed = false; - if (error == null) { - fillNextCodeParams(params, (TLRPC.TL_auth_sentCode) response); - } else { - if (error.text != null) { - if (error.text.contains("PHONE_NUMBER_INVALID")) { - needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); - } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { - needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode)); - } else if (error.text.contains("PHONE_CODE_EXPIRED")) { - needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired)); - } else if (error.text.startsWith("FLOOD_WAIT")) { - needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait)); - } else if (error.text.startsWith("PHONE_NUMBER_OCCUPIED")) { - needShowAlert(LocaleController.formatString("ChangePhoneNumberOccupied", R.string.ChangePhoneNumberOccupied, params.getString("phone"))); - } else { - needShowAlert(LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred)); - } - } - } - needHideProgress(); - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors); - } - - @Override - public void onShow() { - super.onShow(); - if (phoneField != null) { - if (codeField.length() != 0) { - AndroidUtilities.showKeyboard(phoneField); - phoneField.requestFocus(); - phoneField.setSelection(phoneField.length()); - } else { - AndroidUtilities.showKeyboard(codeField); - codeField.requestFocus(); - } - } - } - - @Override - public String getHeaderName() { - return LocaleController.getString("ChangePhoneNewNumber", R.string.ChangePhoneNewNumber); - } - } - - public class LoginActivitySmsView extends SlideView implements NotificationCenter.NotificationCenterDelegate { - - private class ProgressView extends View { - - private Paint paint = new Paint(); - private Paint paint2 = new Paint(); - private float progress; - - public ProgressView(Context context) { - super(context); - paint.setColor(0xffe1eaf2); - paint2.setColor(0xff62a0d0); - } - - public void setProgress(float value) { - progress = value; - invalidate(); - } - - @Override - protected void onDraw(Canvas canvas) { - int start = (int) (getMeasuredWidth() * progress); - canvas.drawRect(0, 0, start, getMeasuredHeight(), paint2); - canvas.drawRect(start, 0, getMeasuredWidth(), getMeasuredHeight(), paint); - } - } - - private String phone; - private String phoneHash; - private String requestPhone; - private String emailPhone; - private EditText codeField; - private TextView confirmTextView; - private TextView timeText; - private TextView problemText; - private Bundle currentParams; - private ProgressView progressView; - - private Timer timeTimer; - private Timer codeTimer; - private int openTime; - private final Object timerSync = new Object(); - private volatile int time = 60000; - private volatile int codeTime = 15000; - private double lastCurrentTime; - private double lastCodeTime; - private boolean ignoreOnTextChange; - private boolean waitingForEvent; - private boolean nextPressed; - private String lastError = ""; - private int currentType; - private int nextType; - private String pattern = "*"; - private int length; - private int timeout; - - public LoginActivitySmsView(Context context, final int type) { - super(context); - - currentType = type; - setOrientation(VERTICAL); - - confirmTextView = new TextView(context); - confirmTextView.setTextColor(0xff757575); - confirmTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - confirmTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - confirmTextView.setLineSpacing(AndroidUtilities.dp(2), 1.0f); - - if (currentType == 3) { - FrameLayout frameLayout = new FrameLayout(context); - - ImageView imageView = new ImageView(context); - imageView.setImageResource(R.drawable.phone_activate); - if (LocaleController.isRTL) { - frameLayout.addView(imageView, LayoutHelper.createFrame(64, 76, Gravity.LEFT | Gravity.CENTER_VERTICAL, 2, 2, 0, 0)); - frameLayout.addView(confirmTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 64 + 18, 0, 0, 0)); - } else { - frameLayout.addView(confirmTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 0, 0, 64 + 18, 0)); - frameLayout.addView(imageView, LayoutHelper.createFrame(64, 76, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 2, 0, 2)); - } - addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - } else { - addView(confirmTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - } - - codeField = new EditText(context); - codeField.setTextColor(0xff212121); - codeField.setHint(LocaleController.getString("Code", R.string.Code)); - AndroidUtilities.clearCursorDrawable(codeField); - codeField.setHintTextColor(0xff979797); - codeField.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI); - codeField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - codeField.setInputType(InputType.TYPE_CLASS_PHONE); - codeField.setMaxLines(1); - codeField.setPadding(0, 0, 0, 0); - addView(codeField, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, Gravity.CENTER_HORIZONTAL, 0, 20, 0, 0)); - codeField.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - if (ignoreOnTextChange) { - return; - } - if (length != 0 && codeField.length() == length) { - onNextPressed(); - } - } - }); - codeField.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_NEXT) { - onNextPressed(); - return true; - } - return false; - } - }); - if (currentType == 3) { - codeField.setEnabled(false); - codeField.setInputType(InputType.TYPE_NULL); - codeField.setVisibility(GONE); - } - - timeText = new TextView(context); - timeText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - timeText.setTextColor(0xff757575); - timeText.setLineSpacing(AndroidUtilities.dp(2), 1.0f); - timeText.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - addView(timeText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 0, 30, 0, 0)); - - if (currentType == 3) { - progressView = new ProgressView(context); - addView(progressView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 3, 0, 12, 0, 0)); - } - - problemText = new TextView(context); - problemText.setText(LocaleController.getString("DidNotGetTheCode", R.string.DidNotGetTheCode)); - problemText.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - problemText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - problemText.setTextColor(0xff4d83b3); - problemText.setLineSpacing(AndroidUtilities.dp(2), 1.0f); - problemText.setPadding(0, AndroidUtilities.dp(2), 0, AndroidUtilities.dp(12)); - addView(problemText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 0, 20, 0, 0)); - problemText.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - if (nextPressed) { - return; - } - if (nextType != 0 && nextType != 4) { - resendCode(); - } else { - try { - PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0); - String version = String.format(Locale.US, "%s (%d)", pInfo.versionName, pInfo.versionCode); - - Intent mailer = new Intent(Intent.ACTION_SEND); - mailer.setType("message/rfc822"); - mailer.putExtra(Intent.EXTRA_EMAIL, new String[]{"sms@stel.com"}); - mailer.putExtra(Intent.EXTRA_SUBJECT, "Android registration/login issue " + version + " " + emailPhone); - mailer.putExtra(Intent.EXTRA_TEXT, "Phone: " + requestPhone + "\nApp version: " + version + "\nOS version: SDK " + Build.VERSION.SDK_INT + "\nDevice Name: " + Build.MANUFACTURER + Build.MODEL + "\nLocale: " + Locale.getDefault() + "\nError: " + lastError); - getContext().startActivity(Intent.createChooser(mailer, "Send email...")); - } catch (Exception e) { - needShowAlert(LocaleController.getString("NoMailInstalled", R.string.NoMailInstalled)); - } - } - } - }); - - LinearLayout linearLayout = new LinearLayout(context); - linearLayout.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); - addView(linearLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - - TextView wrongNumber = new TextView(context); - wrongNumber.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_HORIZONTAL); - wrongNumber.setTextColor(0xff4d83b3); - wrongNumber.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - wrongNumber.setLineSpacing(AndroidUtilities.dp(2), 1.0f); - wrongNumber.setPadding(0, AndroidUtilities.dp(24), 0, 0); - linearLayout.addView(wrongNumber, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), 0, 0, 0, 10)); - wrongNumber.setText(LocaleController.getString("WrongNumber", R.string.WrongNumber)); - wrongNumber.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - TLRPC.TL_auth_cancelCode req = new TLRPC.TL_auth_cancelCode(); - req.phone_number = requestPhone; - req.phone_code_hash = phoneHash; - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - - } - }, ConnectionsManager.RequestFlagFailOnServerErrors); - onBackPressed(); - setPage(0, true, null, true); - } - }); - } - - private void resendCode() { - final Bundle params = new Bundle(); - params.putString("phone", phone); - params.putString("ephone", emailPhone); - params.putString("phoneFormated", requestPhone); - - nextPressed = true; - needShowProgress(); - - TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode(); - req.phone_number = requestPhone; - req.phone_code_hash = phoneHash; - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - nextPressed = false; - if (error == null) { - fillNextCodeParams(params, (TLRPC.TL_auth_sentCode) response); - } else { - if (error.text != null) { - if (error.text.contains("PHONE_NUMBER_INVALID")) { - needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); - } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { - needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode)); - } else if (error.text.contains("PHONE_CODE_EXPIRED")) { - onBackPressed(); - setPage(0, true, null, true); - needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired)); - } else if (error.text.startsWith("FLOOD_WAIT")) { - needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait)); - } else if (error.code != -1000) { - needShowAlert(LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred) + "\n" + error.text); - } - } - } - needHideProgress(); - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors); - } - - @Override - public String getHeaderName() { - return LocaleController.getString("YourCode", R.string.YourCode); - } - - @Override - public void setParams(Bundle params) { - if (params == null) { - return; - } - codeField.setText(""); - waitingForEvent = true; - if (currentType == 2) { - AndroidUtilities.setWaitingForSms(true); - NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReceiveSmsCode); - } else if (currentType == 3) { - AndroidUtilities.setWaitingForCall(true); - NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReceiveCall); - } - - currentParams = params; - phone = params.getString("phone"); - emailPhone = params.getString("ephone"); - requestPhone = params.getString("phoneFormated"); - phoneHash = params.getString("phoneHash"); - timeout = time = params.getInt("timeout"); - openTime = (int) (System.currentTimeMillis() / 1000); - nextType = params.getInt("nextType"); - pattern = params.getString("pattern"); - length = params.getInt("length"); - - if (length != 0) { - InputFilter[] inputFilters = new InputFilter[1]; - inputFilters[0] = new InputFilter.LengthFilter(length); - codeField.setFilters(inputFilters); - } else { - codeField.setFilters(new InputFilter[0]); - } - if (progressView != null) { - progressView.setVisibility(nextType != 0 ? VISIBLE : GONE); - } - - if (phone == null) { - return; - } - - String number = PhoneFormat.getInstance().format(phone); - CharSequence str = ""; - if (currentType == 1) { - str = AndroidUtilities.replaceTags(LocaleController.getString("SentAppCode", R.string.SentAppCode)); - } else if (currentType == 2) { - str = AndroidUtilities.replaceTags(LocaleController.formatString("SentSmsCode", R.string.SentSmsCode, number)); - } else if (currentType == 3) { - str = AndroidUtilities.replaceTags(LocaleController.formatString("SentCallCode", R.string.SentCallCode, number)); - } else if (currentType == 4) { - str = AndroidUtilities.replaceTags(LocaleController.formatString("SentCallOnly", R.string.SentCallOnly, number)); - } - confirmTextView.setText(str); - - if (currentType != 3) { - AndroidUtilities.showKeyboard(codeField); - codeField.requestFocus(); - } else { - AndroidUtilities.hideKeyboard(codeField); - } - - destroyTimer(); - destroyCodeTimer(); - - lastCurrentTime = System.currentTimeMillis(); - if (currentType == 1) { - problemText.setVisibility(VISIBLE); - timeText.setVisibility(GONE); - } else if (currentType == 3 && (nextType == 4 || nextType == 2)) { - problemText.setVisibility(GONE); - timeText.setVisibility(VISIBLE); - if (nextType == 4) { - timeText.setText(LocaleController.formatString("CallText", R.string.CallText, 1, 0)); - } else if (nextType == 2) { - timeText.setText(LocaleController.formatString("SmsText", R.string.SmsText, 1, 0)); - } - createTimer(); - } else if (currentType == 2 && (nextType == 4 || nextType == 3)) { - timeText.setVisibility(VISIBLE); - timeText.setText(LocaleController.formatString("CallText", R.string.CallText, 2, 0)); - problemText.setVisibility(time < 1000 ? VISIBLE : GONE); - createTimer(); - } else { - timeText.setVisibility(GONE); - problemText.setVisibility(GONE); - createCodeTimer(); - } - } - - private void createCodeTimer() { - if (codeTimer != null) { - return; - } - codeTime = 15000; - codeTimer = new Timer(); - lastCodeTime = System.currentTimeMillis(); - codeTimer.schedule(new TimerTask() { - @Override - public void run() { - double currentTime = System.currentTimeMillis(); - double diff = currentTime - lastCodeTime; - codeTime -= diff; - lastCodeTime = currentTime; - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (codeTime <= 1000) { - problemText.setVisibility(VISIBLE); - destroyCodeTimer(); - } - } - }); - } - }, 0, 1000); - } - - private void destroyCodeTimer() { - try { - synchronized (timerSync) { - if (codeTimer != null) { - codeTimer.cancel(); - codeTimer = null; - } - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - - private void createTimer() { - if (timeTimer != null) { - return; - } - timeTimer = new Timer(); - timeTimer.schedule(new TimerTask() { - @Override - public void run() { - if (timeTimer == null) { - return; - } - final double currentTime = System.currentTimeMillis(); - double diff = currentTime - lastCurrentTime; - time -= diff; - lastCurrentTime = currentTime; - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (time >= 1000) { - int minutes = time / 1000 / 60; - int seconds = time / 1000 - minutes * 60; - if (nextType == 4 || nextType == 3) { - timeText.setText(LocaleController.formatString("CallText", R.string.CallText, minutes, seconds)); - } else if (nextType == 2) { - timeText.setText(LocaleController.formatString("SmsText", R.string.SmsText, minutes, seconds)); - } - if (progressView != null) { - progressView.setProgress(1.0f - (float) time / (float) timeout); - } - } else { - if (progressView != null) { - progressView.setProgress(1.0f); - } - destroyTimer(); - if (currentType == 3) { - AndroidUtilities.setWaitingForCall(false); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveCall); - waitingForEvent = false; - destroyCodeTimer(); - resendCode(); - } else if (currentType == 2) { - if (nextType == 4) { - timeText.setText(LocaleController.getString("Calling", R.string.Calling)); - createCodeTimer(); - TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode(); - req.phone_number = requestPhone; - req.phone_code_hash = phoneHash; - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, final TLRPC.TL_error error) { - if (error != null && error.text != null) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - lastError = error.text; - } - }); - } - } - }, ConnectionsManager.RequestFlagFailOnServerErrors); - } else if (nextType == 3) { - AndroidUtilities.setWaitingForSms(false); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveSmsCode); - waitingForEvent = false; - destroyCodeTimer(); - resendCode(); - } - } - } - } - }); - } - }, 0, 1000); - } - - private void destroyTimer() { - try { - synchronized (timerSync) { - if (timeTimer != null) { - timeTimer.cancel(); - timeTimer = null; - } - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - - @Override - public void onNextPressed() { - if (nextPressed) { - return; - } - nextPressed = true; - if (currentType == 2) { - AndroidUtilities.setWaitingForSms(false); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveSmsCode); - } else if (currentType == 3) { - AndroidUtilities.setWaitingForCall(false); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveCall); - } - waitingForEvent = false; - final TLRPC.TL_account_changePhone req = new TLRPC.TL_account_changePhone(); - req.phone_number = requestPhone; - req.phone_code = codeField.getText().toString(); - req.phone_code_hash = phoneHash; - destroyTimer(); - needShowProgress(); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - needHideProgress(); - nextPressed = false; - if (error == null) { - TLRPC.User user = (TLRPC.User) response; - destroyTimer(); - destroyCodeTimer(); - UserConfig.setCurrentUser(user); - UserConfig.saveConfig(true); - ArrayList users = new ArrayList<>(); - users.add(user); - MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); - MessagesController.getInstance().putUser(user, false); - finishFragment(); - } else { - lastError = error.text; - if (currentType == 3 && (nextType == 4 || nextType == 2) || currentType == 2 && (nextType == 4 || nextType == 3)) { - createTimer(); - } - if (currentType == 2) { - AndroidUtilities.setWaitingForSms(true); - NotificationCenter.getInstance().addObserver(LoginActivitySmsView.this, NotificationCenter.didReceiveSmsCode); - } else if (currentType == 3) { - AndroidUtilities.setWaitingForCall(true); - NotificationCenter.getInstance().addObserver(LoginActivitySmsView.this, NotificationCenter.didReceiveCall); - } - waitingForEvent = true; - if (currentType != 3) { - if (error.text.contains("PHONE_NUMBER_INVALID")) { - needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); - } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { - needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode)); - } else if (error.text.contains("PHONE_CODE_EXPIRED")) { - needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired)); - } else if (error.text.startsWith("FLOOD_WAIT")) { - needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait)); - } else { - needShowAlert(error.text); - } - } - } - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors); - } - - @Override - public void onBackPressed() { - destroyTimer(); - destroyCodeTimer(); - currentParams = null; - if (currentType == 2) { - AndroidUtilities.setWaitingForSms(false); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveSmsCode); - } else if (currentType == 3) { - AndroidUtilities.setWaitingForCall(false); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveCall); - } - waitingForEvent = false; - } - - @Override - public void onDestroyActivity() { - super.onDestroyActivity(); - if (currentType == 2) { - AndroidUtilities.setWaitingForSms(false); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveSmsCode); - } else if (currentType == 3) { - AndroidUtilities.setWaitingForCall(false); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveCall); - } - waitingForEvent = false; - destroyTimer(); - destroyCodeTimer(); - } - - @Override - public void onShow() { - super.onShow(); - if (codeField != null) { - codeField.requestFocus(); - codeField.setSelection(codeField.length()); - } - } - - @Override - public void didReceivedNotification(int id, final Object... args) { - if (!waitingForEvent || codeField == null) { - return; - } - if (id == NotificationCenter.didReceiveSmsCode) { - ignoreOnTextChange = true; - codeField.setText("" + args[0]); - ignoreOnTextChange = false; - onNextPressed(); - } else if (id == NotificationCenter.didReceiveCall) { - String num = "" + args[0]; - if (!pattern.equals("*")) { - String patternNumbers = pattern.replace("*", ""); - if (!num.contains(patternNumbers)) { - return; - } - } - ignoreOnTextChange = true; - codeField.setText(num); - ignoreOnTextChange = false; - onNextPressed(); - } - } - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneHelpActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneHelpActivity.java deleted file mode 100644 index bb14930ad..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneHelpActivity.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.ui; - -import android.app.AlertDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.util.TypedValue; -import android.view.Gravity; -import android.view.MotionEvent; -import android.view.View; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.RelativeLayout; -import android.widget.ScrollView; -import android.widget.TextView; - -import org.telegram.PhoneFormat.PhoneFormat; -import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.R; -import org.telegram.tgnet.TLRPC; -import org.telegram.messenger.UserConfig; -import org.telegram.ui.ActionBar.ActionBar; -import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.ui.Components.LayoutHelper; - -public class ChangePhoneHelpActivity extends BaseFragment { - - @Override - public View createView(Context context) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - - TLRPC.User user = UserConfig.getCurrentUser(); - String value; - if (user != null && user.phone != null && user.phone.length() != 0) { - value = PhoneFormat.getInstance().format("+" + user.phone); - } else { - value = LocaleController.getString("NumberUnknown", R.string.NumberUnknown); - } - - actionBar.setTitle(value); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } - } - }); - - fragmentView = new RelativeLayout(context); - fragmentView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - RelativeLayout relativeLayout = (RelativeLayout) fragmentView; - - ScrollView scrollView = new ScrollView(context); - relativeLayout.addView(scrollView); - RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) scrollView.getLayoutParams(); - layoutParams3.width = LayoutHelper.MATCH_PARENT; - layoutParams3.height = LayoutHelper.WRAP_CONTENT; - layoutParams3.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); - scrollView.setLayoutParams(layoutParams3); - - LinearLayout linearLayout = new LinearLayout(context); - linearLayout.setOrientation(LinearLayout.VERTICAL); - linearLayout.setPadding(0, AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20)); - scrollView.addView(linearLayout); - ScrollView.LayoutParams layoutParams = (ScrollView.LayoutParams) linearLayout.getLayoutParams(); - layoutParams.width = ScrollView.LayoutParams.MATCH_PARENT; - layoutParams.height = ScrollView.LayoutParams.WRAP_CONTENT; - linearLayout.setLayoutParams(layoutParams); - - ImageView imageView = new ImageView(context); - imageView.setImageResource(R.drawable.phone_change); - linearLayout.addView(imageView); - LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) imageView.getLayoutParams(); - layoutParams2.width = LayoutHelper.WRAP_CONTENT; - layoutParams2.height = LayoutHelper.WRAP_CONTENT; - layoutParams2.gravity = Gravity.CENTER_HORIZONTAL; - imageView.setLayoutParams(layoutParams2); - - TextView textView = new TextView(context); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - textView.setGravity(Gravity.CENTER_HORIZONTAL); - textView.setTextColor(0xff212121); - - try { - textView.setText(AndroidUtilities.replaceTags(LocaleController.getString("PhoneNumberHelp", R.string.PhoneNumberHelp))); - } catch (Exception e) { - FileLog.e("tmessages", e); - textView.setText(LocaleController.getString("PhoneNumberHelp", R.string.PhoneNumberHelp)); - } - linearLayout.addView(textView); - layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams(); - layoutParams2.width = LayoutHelper.WRAP_CONTENT; - layoutParams2.height = LayoutHelper.WRAP_CONTENT; - layoutParams2.gravity = Gravity.CENTER_HORIZONTAL; - layoutParams2.leftMargin = AndroidUtilities.dp(20); - layoutParams2.rightMargin = AndroidUtilities.dp(20); - layoutParams2.topMargin = AndroidUtilities.dp(56); - textView.setLayoutParams(layoutParams2); - - textView = new TextView(context); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - textView.setGravity(Gravity.CENTER_HORIZONTAL); - textView.setTextColor(0xff4d83b3); - textView.setText(LocaleController.getString("PhoneNumberChange", R.string.PhoneNumberChange)); - textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - textView.setPadding(0, AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10)); - linearLayout.addView(textView); - layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams(); - layoutParams2.width = LayoutHelper.WRAP_CONTENT; - layoutParams2.height = LayoutHelper.WRAP_CONTENT; - layoutParams2.gravity = Gravity.CENTER_HORIZONTAL; - layoutParams2.leftMargin = AndroidUtilities.dp(20); - layoutParams2.rightMargin = AndroidUtilities.dp(20); - layoutParams2.topMargin = AndroidUtilities.dp(46); - textView.setLayoutParams(layoutParams2); - - textView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setMessage(LocaleController.getString("PhoneNumberAlert", R.string.PhoneNumberAlert)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - presentFragment(new ChangePhoneActivity(), true); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showDialog(builder.create()); - } - }); - - return fragmentView; - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChannelCreateActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChannelCreateActivity.java deleted file mode 100644 index 938228083..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChannelCreateActivity.java +++ /dev/null @@ -1,1176 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.ui; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.drawable.BitmapDrawable; -import android.os.Bundle; -import android.os.Vibrator; -import android.text.Editable; -import android.text.InputFilter; -import android.text.InputType; -import android.text.Spannable; -import android.text.SpannableString; -import android.text.SpannableStringBuilder; -import android.text.TextWatcher; -import android.text.style.ImageSpan; -import android.util.TypedValue; -import android.view.Gravity; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.inputmethod.EditorInfo; -import android.widget.AbsListView; -import android.widget.AdapterView; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.Toast; - -import org.telegram.PhoneFormat.PhoneFormat; -import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.ApplicationLoader; -import org.telegram.messenger.ChatObject; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.MessagesController; -import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.R; -import org.telegram.messenger.UserObject; -import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.RequestDelegate; -import org.telegram.tgnet.TLObject; -import org.telegram.tgnet.TLRPC; -import org.telegram.ui.ActionBar.ActionBar; -import org.telegram.ui.ActionBar.ActionBarMenu; -import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.ui.Adapters.ContactsAdapter; -import org.telegram.ui.Adapters.SearchAdapter; -import org.telegram.ui.Cells.HeaderCell; -import org.telegram.ui.Cells.RadioButtonCell; -import org.telegram.ui.Cells.ShadowSectionCell; -import org.telegram.ui.Cells.TextBlockCell; -import org.telegram.ui.Cells.TextInfoPrivacyCell; -import org.telegram.ui.Cells.UserCell; -import org.telegram.ui.Components.AvatarDrawable; -import org.telegram.ui.Components.AvatarUpdater; -import org.telegram.ui.Components.BackupImageView; -import org.telegram.ui.Components.ChipSpan; -import org.telegram.ui.Components.LayoutHelper; -import org.telegram.ui.Components.LetterSectionsListView; - -import java.util.ArrayList; -import java.util.HashMap; - -public class ChannelCreateActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, AvatarUpdater.AvatarUpdaterDelegate { - - private View doneButton; - private EditText nameTextView; - private ProgressDialog progressDialog = null; - - private BackupImageView avatarImage; - private AvatarDrawable avatarDrawable; - private AvatarUpdater avatarUpdater; - private EditText descriptionTextView; - private TLRPC.FileLocation avatar; - private String nameToSet = null; - - private LinearLayout linkContainer; - private LinearLayout publicContainer; - private TextBlockCell privateContainer; - private RadioButtonCell radioButtonCell1; - private RadioButtonCell radioButtonCell2; - private TextInfoPrivacyCell typeInfoCell; - private TextView checkTextView; - private HeaderCell headerCell; - private int checkReqId = 0; - private String lastCheckName = null; - private Runnable checkRunnable = null; - private boolean lastNameAvailable = false; - private boolean isPrivate = false; - private boolean loadingInvite; - private TLRPC.ExportedChatInvite invite; - - private ContactsAdapter listViewAdapter; - private TextView emptyTextView; - private LetterSectionsListView listView; - private SearchAdapter searchListViewAdapter; - private boolean searchWas; - private boolean searching; - private HashMap selectedContacts = new HashMap<>(); - private ArrayList allSpans = new ArrayList<>(); - private int beforeChangeIndex; - private boolean ignoreChange; - private CharSequence changeString; - - private int currentStep; - private int chatId; - private boolean canCreatePublic = true; - private TLRPC.InputFile uploadedAvatar; - - private boolean createAfterUpload; - private boolean donePressed; - - private final static int done_button = 1; - - public ChannelCreateActivity(Bundle args) { - super(args); - currentStep = args.getInt("step", 0); - if (currentStep == 0) { - avatarDrawable = new AvatarDrawable(); - avatarUpdater = new AvatarUpdater(); - - TLRPC.TL_channels_checkUsername req = new TLRPC.TL_channels_checkUsername(); - req.username = "1"; - req.channel = new TLRPC.TL_inputChannelEmpty(); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - canCreatePublic = error == null || !error.text.equals("CHANNELS_ADMIN_PUBLIC_TOO_MUCH"); - } - }); - } - }); - } else { - if (currentStep == 1) { - canCreatePublic = args.getBoolean("canCreatePublic", true); - isPrivate = !canCreatePublic; - } - chatId = args.getInt("chat_id", 0); - } - } - - @SuppressWarnings("unchecked") - @Override - public boolean onFragmentCreate() { - NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); - NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatDidCreated); - NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatDidFailCreate); - if (currentStep == 2) { - NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded); - } else if (currentStep == 1) { - generateLink(); - } - if (avatarUpdater != null) { - avatarUpdater.parentFragment = this; - avatarUpdater.delegate = this; - } - return super.onFragmentCreate(); - } - - @Override - public void onFragmentDestroy() { - super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatDidCreated); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatDidFailCreate); - if (currentStep == 2) { - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded); - } - if (avatarUpdater != null) { - avatarUpdater.clear(); - } - AndroidUtilities.removeAdjustResize(getParentActivity(), classGuid); - } - - @Override - public void onResume() { - super.onResume(); - AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid); - } - - @Override - public View createView(Context context) { - searching = false; - searchWas = false; - - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - if (currentStep == 0) { - if (donePressed) { - return; - } - if (nameTextView.length() == 0) { - Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); - if (v != null) { - v.vibrate(200); - } - AndroidUtilities.shakeView(nameTextView, 2, 0); - return; - } - donePressed = true; - if (avatarUpdater.uploadingAvatar != null) { - createAfterUpload = true; - progressDialog = new ProgressDialog(getParentActivity()); - progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); - progressDialog.setCanceledOnTouchOutside(false); - progressDialog.setCancelable(false); - progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - createAfterUpload = false; - progressDialog = null; - donePressed = false; - try { - dialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - progressDialog.show(); - return; - } - final int reqId = MessagesController.getInstance().createChat(nameTextView.getText().toString(), new ArrayList(), descriptionTextView.getText().toString(), ChatObject.CHAT_TYPE_CHANNEL, ChannelCreateActivity.this); - progressDialog = new ProgressDialog(getParentActivity()); - progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); - progressDialog.setCanceledOnTouchOutside(false); - progressDialog.setCancelable(false); - progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - ConnectionsManager.getInstance().cancelRequest(reqId, true); - donePressed = false; - try { - dialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - progressDialog.show(); - } else if (currentStep == 1) { - if (!isPrivate) { - if (nameTextView.length() == 0) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setMessage(LocaleController.getString("ChannelPublicEmptyUsername", R.string.ChannelPublicEmptyUsername)); - builder.setPositiveButton(LocaleController.getString("Close", R.string.Close), null); - showDialog(builder.create()); - return; - } else { - if (!lastNameAvailable) { - Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); - if (v != null) { - v.vibrate(200); - } - AndroidUtilities.shakeView(checkTextView, 2, 0); - return; - } else { - MessagesController.getInstance().updateChannelUserName(chatId, lastCheckName); - } - } - } - Bundle args = new Bundle(); - args.putInt("step", 2); - args.putInt("chat_id", chatId); - presentFragment(new ChannelCreateActivity(args), true); - } else { - ArrayList result = new ArrayList<>(); - for (Integer uid : selectedContacts.keySet()) { - TLRPC.InputUser user = MessagesController.getInputUser(MessagesController.getInstance().getUser(uid)); - if (user != null) { - result.add(user); - } - } - MessagesController.getInstance().addUsersToChannel(chatId, result, null); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); - Bundle args2 = new Bundle(); - args2.putInt("chat_id", chatId); - presentFragment(new ChatActivity(args2), true); - } - } - } - }); - - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - LinearLayout linearLayout; - if (currentStep != 2) { - fragmentView = new ScrollView(context); - ScrollView scrollView = (ScrollView) fragmentView; - scrollView.setFillViewport(true); - linearLayout = new LinearLayout(context); - scrollView.addView(linearLayout, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - } else { - fragmentView = new LinearLayout(context); - fragmentView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - linearLayout = (LinearLayout) fragmentView; - } - linearLayout.setOrientation(LinearLayout.VERTICAL); - - if (currentStep == 0) { - actionBar.setTitle(LocaleController.getString("NewChannel", R.string.NewChannel)); - fragmentView.setBackgroundColor(0xffffffff); - FrameLayout frameLayout = new FrameLayout(context); - linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - avatarImage = new BackupImageView(context); - avatarImage.setRoundRadius(AndroidUtilities.dp(32)); - avatarDrawable.setInfo(5, null, null, false); - avatarDrawable.setDrawPhoto(true); - avatarImage.setImageDrawable(avatarDrawable); - frameLayout.addView(avatarImage, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 12, LocaleController.isRTL ? 16 : 0, 12)); - avatarImage.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - - CharSequence[] items; - - if (avatar != null) { - items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; - } else { - items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; - } - - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (i == 0) { - avatarUpdater.openCamera(); - } else if (i == 1) { - avatarUpdater.openGallery(); - } else if (i == 2) { - avatar = null; - uploadedAvatar = null; - avatarImage.setImage(avatar, "50_50", avatarDrawable); - } - } - }); - showDialog(builder.create()); - } - }); - - nameTextView = new EditText(context); - nameTextView.setHint(LocaleController.getString("EnterChannelName", R.string.EnterChannelName)); - if (nameToSet != null) { - nameTextView.setText(nameToSet); - nameToSet = null; - } - nameTextView.setMaxLines(4); - nameTextView.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - nameTextView.setHintTextColor(0xff979797); - nameTextView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); - nameTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); - InputFilter[] inputFilters = new InputFilter[1]; - inputFilters[0] = new InputFilter.LengthFilter(100); - nameTextView.setFilters(inputFilters); - nameTextView.setPadding(0, 0, 0, AndroidUtilities.dp(8)); - AndroidUtilities.clearCursorDrawable(nameTextView); - nameTextView.setTextColor(0xff212121); - frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 16 : 96, 0, LocaleController.isRTL ? 96 : 16, 0)); - nameTextView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - avatarDrawable.setInfo(5, nameTextView.length() > 0 ? nameTextView.getText().toString() : null, null, false); - avatarImage.invalidate(); - } - }); - - descriptionTextView = new EditText(context); - descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - descriptionTextView.setHintTextColor(0xff979797); - descriptionTextView.setTextColor(0xff212121); - descriptionTextView.setPadding(0, 0, 0, AndroidUtilities.dp(6)); - descriptionTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - descriptionTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - descriptionTextView.setImeOptions(EditorInfo.IME_ACTION_DONE); - inputFilters = new InputFilter[1]; - inputFilters[0] = new InputFilter.LengthFilter(120); - descriptionTextView.setFilters(inputFilters); - descriptionTextView.setHint(LocaleController.getString("DescriptionPlaceholder", R.string.DescriptionPlaceholder)); - AndroidUtilities.clearCursorDrawable(descriptionTextView); - linearLayout.addView(descriptionTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 24, 18, 24, 0)); - descriptionTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) { - doneButton.performClick(); - return true; - } - return false; - } - }); - descriptionTextView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - TextView helpTextView = new TextView(context); - helpTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - helpTextView.setTextColor(0xff6d6d72); - helpTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - helpTextView.setText(LocaleController.getString("DescriptionInfo", R.string.DescriptionInfo)); - linearLayout.addView(helpTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 24, 10, 24, 20)); - } else if (currentStep == 1) { - actionBar.setTitle(LocaleController.getString("ChannelSettings", R.string.ChannelSettings)); - fragmentView.setBackgroundColor(0xfff0f0f0); - - LinearLayout linearLayout2 = new LinearLayout(context); - linearLayout2.setOrientation(LinearLayout.VERTICAL); - linearLayout2.setBackgroundColor(0xffffffff); - linearLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - radioButtonCell1 = new RadioButtonCell(context); - radioButtonCell1.setBackgroundResource(R.drawable.list_selector); - radioButtonCell1.setTextAndValue(LocaleController.getString("ChannelPublic", R.string.ChannelPublic), LocaleController.getString("ChannelPublicInfo", R.string.ChannelPublicInfo), !isPrivate, false); - linearLayout2.addView(radioButtonCell1, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - radioButtonCell1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (!canCreatePublic) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setMessage(LocaleController.getString("ChannelPublicLimitReached", R.string.ChannelPublicLimitReached)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); - showDialog(builder.create()); - return; - } - if (!isPrivate) { - return; - } - isPrivate = false; - updatePrivatePublic(); - } - }); - - radioButtonCell2 = new RadioButtonCell(context); - radioButtonCell2.setBackgroundResource(R.drawable.list_selector); - radioButtonCell2.setTextAndValue(LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate), LocaleController.getString("ChannelPrivateInfo", R.string.ChannelPrivateInfo), isPrivate, false); - linearLayout2.addView(radioButtonCell2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - radioButtonCell2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (isPrivate) { - return; - } - isPrivate = true; - updatePrivatePublic(); - } - }); - - ShadowSectionCell sectionCell = new ShadowSectionCell(context); - linearLayout.addView(sectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - linkContainer = new LinearLayout(context); - linkContainer.setOrientation(LinearLayout.VERTICAL); - linkContainer.setBackgroundColor(0xffffffff); - linearLayout.addView(linkContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - headerCell = new HeaderCell(context); - linkContainer.addView(headerCell); - - publicContainer = new LinearLayout(context); - publicContainer.setOrientation(LinearLayout.HORIZONTAL); - linkContainer.addView(publicContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 17, 7, 17, 0)); - - EditText editText = new EditText(context); - editText.setText("telegram.me/"); - editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - editText.setHintTextColor(0xff979797); - editText.setTextColor(0xff212121); - editText.setMaxLines(1); - editText.setLines(1); - editText.setEnabled(false); - editText.setBackgroundDrawable(null); - editText.setPadding(0, 0, 0, 0); - editText.setSingleLine(true); - editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - editText.setImeOptions(EditorInfo.IME_ACTION_DONE); - publicContainer.addView(editText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36)); - - nameTextView = new EditText(context); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - nameTextView.setHintTextColor(0xff979797); - nameTextView.setTextColor(0xff212121); - nameTextView.setMaxLines(1); - nameTextView.setLines(1); - nameTextView.setBackgroundDrawable(null); - nameTextView.setPadding(0, 0, 0, 0); - nameTextView.setSingleLine(true); - nameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - nameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE); - nameTextView.setHint(LocaleController.getString("ChannelUsernamePlaceholder", R.string.ChannelUsernamePlaceholder)); - AndroidUtilities.clearCursorDrawable(nameTextView); - publicContainer.addView(nameTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36)); - nameTextView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { - checkUserName(nameTextView.getText().toString(), false); - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - privateContainer = new TextBlockCell(context); - privateContainer.setBackgroundResource(R.drawable.list_selector); - linkContainer.addView(privateContainer); - privateContainer.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (invite == null) { - return; - } - try { - android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); - android.content.ClipData clip = android.content.ClipData.newPlainText("label", invite.link); - clipboard.setPrimaryClip(clip); - Toast.makeText(getParentActivity(), LocaleController.getString("LinkCopied", R.string.LinkCopied), Toast.LENGTH_SHORT).show(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - - checkTextView = new TextView(context); - checkTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - checkTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - checkTextView.setVisibility(View.GONE); - linkContainer.addView(checkTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 17, 3, 17, 7)); - - typeInfoCell = new TextInfoPrivacyCell(context); - typeInfoCell.setBackgroundResource(R.drawable.greydivider_bottom); - linearLayout.addView(typeInfoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - updatePrivatePublic(); - } else if (currentStep == 2) { - actionBar.setTitle(LocaleController.getString("ChannelAddMembers", R.string.ChannelAddMembers)); - actionBar.setSubtitle(LocaleController.formatPluralString("Members", selectedContacts.size())); - - searchListViewAdapter = new SearchAdapter(context, null, false, false, false, false); - searchListViewAdapter.setCheckedMap(selectedContacts); - searchListViewAdapter.setUseUserCell(true); - listViewAdapter = new ContactsAdapter(context, 1, false, null, false); - listViewAdapter.setCheckedMap(selectedContacts); - - FrameLayout frameLayout = new FrameLayout(context); - linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - nameTextView = new EditText(context); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - nameTextView.setHintTextColor(0xff979797); - nameTextView.setTextColor(0xff212121); - nameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_MULTI_LINE); - nameTextView.setMinimumHeight(AndroidUtilities.dp(54)); - nameTextView.setSingleLine(false); - nameTextView.setLines(2); - nameTextView.setMaxLines(2); - nameTextView.setVerticalScrollBarEnabled(true); - nameTextView.setHorizontalScrollBarEnabled(false); - nameTextView.setPadding(0, 0, 0, 0); - nameTextView.setHint(LocaleController.getString("AddMutual", R.string.AddMutual)); - nameTextView.setTextIsSelectable(false); - nameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI); - nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); - AndroidUtilities.clearCursorDrawable(nameTextView); - frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0)); - - nameTextView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { - if (!ignoreChange) { - beforeChangeIndex = nameTextView.getSelectionStart(); - changeString = new SpannableString(charSequence); - } - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void afterTextChanged(Editable editable) { - if (!ignoreChange) { - boolean search = false; - int afterChangeIndex = nameTextView.getSelectionEnd(); - if (editable.toString().length() < changeString.toString().length()) { - String deletedString = ""; - try { - deletedString = changeString.toString().substring(afterChangeIndex, beforeChangeIndex); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - if (deletedString.length() > 0) { - if (searching && searchWas) { - search = true; - } - Spannable span = nameTextView.getText(); - for (int a = 0; a < allSpans.size(); a++) { - ChipSpan sp = allSpans.get(a); - if (span.getSpanStart(sp) == -1) { - allSpans.remove(sp); - selectedContacts.remove(sp.uid); - } - } - actionBar.setSubtitle(LocaleController.formatPluralString("Members", selectedContacts.size())); - listView.invalidateViews(); - } else { - search = true; - } - } else { - search = true; - } - if (search) { - String text = nameTextView.getText().toString().replace("<", ""); - if (text.length() != 0) { - searching = true; - searchWas = true; - if (listView != null) { - listView.setAdapter(searchListViewAdapter); - searchListViewAdapter.notifyDataSetChanged(); - listView.setFastScrollAlwaysVisible(false); - listView.setFastScrollEnabled(false); - listView.setVerticalScrollBarEnabled(true); - } - if (emptyTextView != null) { - emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); - } - searchListViewAdapter.searchDialogs(text); - } else { - searchListViewAdapter.searchDialogs(null); - searching = false; - searchWas = false; - listView.setAdapter(listViewAdapter); - listViewAdapter.notifyDataSetChanged(); - listView.setFastScrollAlwaysVisible(true); - listView.setFastScrollEnabled(true); - listView.setVerticalScrollBarEnabled(false); - emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); - } - } - } - } - }); - - LinearLayout emptyTextLayout = new LinearLayout(context); - emptyTextLayout.setVisibility(View.INVISIBLE); - emptyTextLayout.setOrientation(LinearLayout.VERTICAL); - linearLayout.addView(emptyTextLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); - emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - emptyTextView = new TextView(context); - emptyTextView.setTextColor(0xff808080); - emptyTextView.setTextSize(20); - emptyTextView.setGravity(Gravity.CENTER); - emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); - emptyTextLayout.addView(emptyTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0.5f)); - - FrameLayout frameLayout2 = new FrameLayout(context); - emptyTextLayout.addView(frameLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0.5f)); - - listView = new LetterSectionsListView(context); - listView.setEmptyView(emptyTextLayout); - listView.setVerticalScrollBarEnabled(false); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setFastScrollEnabled(true); - listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); - listView.setAdapter(listViewAdapter); - listView.setFastScrollAlwaysVisible(true); - listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); - linearLayout.addView(listView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - TLRPC.User user; - if (searching && searchWas) { - user = (TLRPC.User) searchListViewAdapter.getItem(i); - } else { - int section = listViewAdapter.getSectionForPosition(i); - int row = listViewAdapter.getPositionInSectionForPosition(i); - if (row < 0 || section < 0) { - return; - } - user = (TLRPC.User) listViewAdapter.getItem(section, row); - } - if (user == null) { - return; - } - - boolean check = true; - if (selectedContacts.containsKey(user.id)) { - check = false; - try { - ChipSpan span = selectedContacts.get(user.id); - selectedContacts.remove(user.id); - SpannableStringBuilder text = new SpannableStringBuilder(nameTextView.getText()); - text.delete(text.getSpanStart(span), text.getSpanEnd(span)); - allSpans.remove(span); - ignoreChange = true; - nameTextView.setText(text); - nameTextView.setSelection(text.length()); - ignoreChange = false; - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } else { - ignoreChange = true; - ChipSpan span = createAndPutChipForUser(user); - if (span != null) { - span.uid = user.id; - } - ignoreChange = false; - if (span == null) { - return; - } - } - actionBar.setSubtitle(LocaleController.formatPluralString("Members", selectedContacts.size())); - if (searching || searchWas) { - ignoreChange = true; - SpannableStringBuilder ssb = new SpannableStringBuilder(""); - for (ImageSpan sp : allSpans) { - ssb.append("<<"); - ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); - } - nameTextView.setText(ssb); - nameTextView.setSelection(ssb.length()); - ignoreChange = false; - - searchListViewAdapter.searchDialogs(null); - searching = false; - searchWas = false; - listView.setAdapter(listViewAdapter); - listViewAdapter.notifyDataSetChanged(); - listView.setFastScrollAlwaysVisible(true); - listView.setFastScrollEnabled(true); - listView.setVerticalScrollBarEnabled(false); - emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); - } else { - if (view instanceof UserCell) { - ((UserCell) view).setChecked(check, true); - } - } - } - }); - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView absListView, int i) { - if (i == SCROLL_STATE_TOUCH_SCROLL) { - AndroidUtilities.hideKeyboard(nameTextView); - } - if (listViewAdapter != null) { - listViewAdapter.setIsScrolling(i != SCROLL_STATE_IDLE); - } - } - - @Override - public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (absListView.isFastScrollEnabled()) { - AndroidUtilities.clearDrawableAnimation(absListView); - } - } - }); - } - - return fragmentView; - } - - private void generateLink() { - if (loadingInvite || invite != null) { - return; - } - loadingInvite = true; - TLRPC.TL_channels_exportInvite req = new TLRPC.TL_channels_exportInvite(); - req.channel = MessagesController.getInputChannel(chatId); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (error == null) { - invite = (TLRPC.ExportedChatInvite) response; - } - loadingInvite = false; - privateContainer.setText(invite != null ? invite.link : LocaleController.getString("Loading", R.string.Loading), false); - } - }); - } - }); - } - - private void updatePrivatePublic() { - radioButtonCell1.setChecked(!isPrivate, true); - radioButtonCell2.setChecked(isPrivate, true); - typeInfoCell.setText(isPrivate ? LocaleController.getString("ChannelPrivateLinkHelp", R.string.ChannelPrivateLinkHelp) : LocaleController.getString("ChannelUsernameHelp", R.string.ChannelUsernameHelp)); - headerCell.setText(isPrivate ? LocaleController.getString("ChannelInviteLinkTitle", R.string.ChannelInviteLinkTitle) : LocaleController.getString("ChannelLinkTitle", R.string.ChannelLinkTitle)); - publicContainer.setVisibility(isPrivate ? View.GONE : View.VISIBLE); - privateContainer.setVisibility(isPrivate ? View.VISIBLE : View.GONE); - linkContainer.setPadding(0, 0, 0, isPrivate ? 0 : AndroidUtilities.dp(7)); - privateContainer.setText(invite != null ? invite.link : LocaleController.getString("Loading", R.string.Loading), false); - nameTextView.clearFocus(); - checkTextView.setVisibility(!isPrivate && checkTextView.length() != 0 ? View.VISIBLE : View.GONE); - AndroidUtilities.hideKeyboard(nameTextView); - } - - @Override - public void didUploadedPhoto(final TLRPC.InputFile file, final TLRPC.PhotoSize small, final TLRPC.PhotoSize big) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - uploadedAvatar = file; - avatar = small.location; - avatarImage.setImage(avatar, "50_50", avatarDrawable); - if (createAfterUpload) { - try { - if (progressDialog != null && progressDialog.isShowing()) { - progressDialog.dismiss(); - progressDialog = null; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - doneButton.performClick(); - } - } - }); - } - - @Override - public void onActivityResultFragment(int requestCode, int resultCode, Intent data) { - avatarUpdater.onActivityResult(requestCode, resultCode, data); - } - - @Override - public void saveSelfArgs(Bundle args) { - if (currentStep == 0) { - if (avatarUpdater != null && avatarUpdater.currentPicturePath != null) { - args.putString("path", avatarUpdater.currentPicturePath); - } - if (nameTextView != null) { - String text = nameTextView.getText().toString(); - if (text != null && text.length() != 0) { - args.putString("nameTextView", text); - } - } - } - } - - @Override - public void restoreSelfArgs(Bundle args) { - if (currentStep == 0) { - if (avatarUpdater != null) { - avatarUpdater.currentPicturePath = args.getString("path"); - } - String text = args.getString("nameTextView"); - if (text != null) { - if (nameTextView != null) { - nameTextView.setText(text); - } else { - nameToSet = text; - } - } - } - } - - @Override - public void onTransitionAnimationEnd(boolean isOpen, boolean backward) { - if (isOpen && currentStep != 1) { - nameTextView.requestFocus(); - AndroidUtilities.showKeyboard(nameTextView); - } - } - - @Override - public void didReceivedNotification(int id, final Object... args) { - if (id == NotificationCenter.updateInterfaces) { - int mask = (Integer)args[0]; - if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { - updateVisibleRows(mask); - } - } else if (id == NotificationCenter.chatDidFailCreate) { - if (progressDialog != null) { - try { - progressDialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - donePressed = false; - } else if (id == NotificationCenter.chatDidCreated) { - if (progressDialog != null) { - try { - progressDialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - int chat_id = (Integer) args[0]; - Bundle bundle = new Bundle(); - bundle.putInt("step", 1); - bundle.putInt("chat_id", chat_id); - bundle.putBoolean("canCreatePublic", canCreatePublic); - if (uploadedAvatar != null) { - MessagesController.getInstance().changeChatAvatar(chat_id, uploadedAvatar); - } - presentFragment(new ChannelCreateActivity(bundle), true); - } else if (id == NotificationCenter.contactsDidLoaded) { - if (listViewAdapter != null) { - listViewAdapter.notifyDataSetChanged(); - } - } - } - - private boolean checkUserName(final String name, boolean alert) { - if (name != null && name.length() > 0) { - checkTextView.setVisibility(View.VISIBLE); - } else { - checkTextView.setVisibility(View.GONE); - } - if (alert && name.length() == 0) { - return true; - } - if (checkRunnable != null) { - AndroidUtilities.cancelRunOnUIThread(checkRunnable); - checkRunnable = null; - lastCheckName = null; - if (checkReqId != 0) { - ConnectionsManager.getInstance().cancelRequest(checkReqId, true); - } - } - lastNameAvailable = false; - if (name != null) { - if (name.startsWith("_") || name.endsWith("_")) { - checkTextView.setText(LocaleController.getString("LinkInvalid", R.string.LinkInvalid)); - checkTextView.setTextColor(0xffcf3030); - return false; - } - for (int a = 0; a < name.length(); a++) { - char ch = name.charAt(a); - if (a == 0 && ch >= '0' && ch <= '9') { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber)); - checkTextView.setTextColor(0xffcf3030); - } - return false; - } - if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalid", R.string.LinkInvalid)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalid", R.string.LinkInvalid)); - checkTextView.setTextColor(0xffcf3030); - } - return false; - } - } - } - if (name == null || name.length() < 5) { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort)); - checkTextView.setTextColor(0xffcf3030); - } - return false; - } - if (name.length() > 32) { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalidLong", R.string.LinkInvalidLong)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalidLong", R.string.LinkInvalidLong)); - checkTextView.setTextColor(0xffcf3030); - } - return false; - } - - if (!alert) { - checkTextView.setText(LocaleController.getString("LinkChecking", R.string.LinkChecking)); - checkTextView.setTextColor(0xff6d6d72); - lastCheckName = name; - checkRunnable = new Runnable() { - @Override - public void run() { - TLRPC.TL_channels_checkUsername req = new TLRPC.TL_channels_checkUsername(); - req.username = name; - req.channel = MessagesController.getInputChannel(chatId); - checkReqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - checkReqId = 0; - if (lastCheckName != null && lastCheckName.equals(name)) { - if (error == null && response instanceof TLRPC.TL_boolTrue) { - checkTextView.setText(LocaleController.formatString("LinkAvailable", R.string.LinkAvailable, name)); - checkTextView.setTextColor(0xff26972c); - lastNameAvailable = true; - } else { - if (error != null && error.text.equals("CHANNELS_ADMIN_PUBLIC_TOO_MUCH")) { - checkTextView.setText(LocaleController.getString("ChannelPublicLimitReached", R.string.ChannelPublicLimitReached)); - } else { - checkTextView.setText(LocaleController.getString("LinkInUse", R.string.LinkInUse)); - } - checkTextView.setTextColor(0xffcf3030); - lastNameAvailable = false; - } - } - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors); - } - }; - AndroidUtilities.runOnUIThread(checkRunnable, 300); - } - return true; - } - - private void showErrorAlert(String error) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - switch (error) { - case "USERNAME_INVALID": - builder.setMessage(LocaleController.getString("LinkInvalid", R.string.LinkInvalid)); - break; - case "USERNAME_OCCUPIED": - builder.setMessage(LocaleController.getString("LinkInUse", R.string.LinkInUse)); - break; - case "USERNAMES_UNAVAILABLE": - builder.setMessage(LocaleController.getString("FeatureUnavailable", R.string.FeatureUnavailable)); - break; - default: - builder.setMessage(LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred)); - break; - } - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); - showDialog(builder.create()); - } - - private void updateVisibleRows(int mask) { - if (listView == null) { - return; - } - int count = listView.getChildCount(); - for (int a = 0; a < count; a++) { - View child = listView.getChildAt(a); - if (child instanceof UserCell) { - ((UserCell) child).update(mask); - } - } - } - - private ChipSpan createAndPutChipForUser(TLRPC.User user) { - try { - LayoutInflater lf = (LayoutInflater) ApplicationLoader.applicationContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); - View textView = lf.inflate(R.layout.group_create_bubble, null); - TextView text = (TextView)textView.findViewById(R.id.bubble_text_view); - String name = UserObject.getUserName(user); - if (name.length() == 0 && user.phone != null && user.phone.length() != 0) { - name = PhoneFormat.getInstance().format("+" + user.phone); - } - text.setText(name + ", "); - - int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); - textView.measure(spec, spec); - textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight()); - Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(b); - canvas.translate(-textView.getScrollX(), -textView.getScrollY()); - textView.draw(canvas); - textView.setDrawingCacheEnabled(true); - Bitmap cacheBmp = textView.getDrawingCache(); - Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true); - textView.destroyDrawingCache(); - - final BitmapDrawable bmpDrawable = new BitmapDrawable(b); - bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight()); - - SpannableStringBuilder ssb = new SpannableStringBuilder(""); - ChipSpan span = new ChipSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE); - allSpans.add(span); - selectedContacts.put(user.id, span); - for (ImageSpan sp : allSpans) { - ssb.append("<<"); - ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); - } - nameTextView.setText(ssb); - nameTextView.setSelection(ssb.length()); - return span; - } catch (Exception e) { - FileLog.e("tmessages", e); - } - return null; - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChannelEditActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChannelEditActivity.java deleted file mode 100644 index 47d402c4a..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChannelEditActivity.java +++ /dev/null @@ -1,605 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.ui; - -import android.app.AlertDialog; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Bundle; -import android.os.Vibrator; -import android.text.Editable; -import android.text.InputFilter; -import android.text.InputType; -import android.text.TextWatcher; -import android.util.TypedValue; -import android.view.Gravity; -import android.view.KeyEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.inputmethod.EditorInfo; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.LinearLayout; -import android.widget.ScrollView; -import android.widget.TextView; - -import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.MessagesController; -import org.telegram.messenger.MessagesStorage; -import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.R; -import org.telegram.messenger.UserConfig; -import org.telegram.tgnet.TLRPC; -import org.telegram.ui.ActionBar.ActionBar; -import org.telegram.ui.ActionBar.ActionBarMenu; -import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.ui.Cells.ShadowSectionCell; -import org.telegram.ui.Cells.TextCheckCell; -import org.telegram.ui.Cells.TextInfoPrivacyCell; -import org.telegram.ui.Cells.TextSettingsCell; -import org.telegram.ui.Components.AvatarDrawable; -import org.telegram.ui.Components.AvatarUpdater; -import org.telegram.ui.Components.BackupImageView; -import org.telegram.ui.Components.LayoutHelper; - -import java.util.concurrent.Semaphore; - -public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.AvatarUpdaterDelegate, NotificationCenter.NotificationCenterDelegate { - - private View doneButton; - private EditText nameTextView; - private EditText descriptionTextView; - private BackupImageView avatarImage; - private AvatarDrawable avatarDrawable; - private AvatarUpdater avatarUpdater; - private ProgressDialog progressDialog; - private TextSettingsCell typeCell; - private TextSettingsCell adminCell; - - private TLRPC.FileLocation avatar; - private TLRPC.Chat currentChat; - private TLRPC.ChatFull info; - private int chatId; - private TLRPC.InputFile uploadedAvatar; - private boolean signMessages; - - private boolean createAfterUpload; - private boolean donePressed; - - private final static int done_button = 1; - - public ChannelEditActivity(Bundle args) { - super(args); - avatarDrawable = new AvatarDrawable(); - avatarUpdater = new AvatarUpdater(); - chatId = args.getInt("chat_id", 0); - } - - @SuppressWarnings("unchecked") - @Override - public boolean onFragmentCreate() { - currentChat = MessagesController.getInstance().getChat(chatId); - if (currentChat == null) { - final Semaphore semaphore = new Semaphore(0); - MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { - @Override - public void run() { - currentChat = MessagesStorage.getInstance().getChat(chatId); - semaphore.release(); - } - }); - try { - semaphore.acquire(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - if (currentChat != null) { - MessagesController.getInstance().putChat(currentChat, true); - } else { - return false; - } - if (info == null) { - MessagesStorage.getInstance().loadChatInfo(chatId, semaphore, false, false); - try { - semaphore.acquire(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - if (info == null) { - return false; - } - } - } - avatarUpdater.parentFragment = this; - avatarUpdater.delegate = this; - signMessages = currentChat.signatures; - NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded); - NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); - return super.onFragmentCreate(); - } - - @Override - public void onFragmentDestroy() { - super.onFragmentDestroy(); - if (avatarUpdater != null) { - avatarUpdater.clear(); - } - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatInfoDidLoaded); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); - AndroidUtilities.removeAdjustResize(getParentActivity(), classGuid); - } - - @Override - public void onResume() { - super.onResume(); - AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid); - } - - @Override - public View createView(Context context) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - if (donePressed) { - return; - } - if (nameTextView.length() == 0) { - Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); - if (v != null) { - v.vibrate(200); - } - AndroidUtilities.shakeView(nameTextView, 2, 0); - return; - } - donePressed = true; - - if (avatarUpdater.uploadingAvatar != null) { - createAfterUpload = true; - progressDialog = new ProgressDialog(getParentActivity()); - progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); - progressDialog.setCanceledOnTouchOutside(false); - progressDialog.setCancelable(false); - progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - createAfterUpload = false; - progressDialog = null; - donePressed = false; - try { - dialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - progressDialog.show(); - return; - } - if (!currentChat.title.equals(nameTextView.getText().toString())) { - MessagesController.getInstance().changeChatTitle(chatId, nameTextView.getText().toString()); - } - if (info != null && !info.about.equals(descriptionTextView.getText().toString())) { - MessagesController.getInstance().updateChannelAbout(chatId, descriptionTextView.getText().toString(), info); - } - if (signMessages != currentChat.signatures) { - currentChat.signatures = true; - MessagesController.getInstance().toogleChannelSignatures(chatId, signMessages); - } - if (uploadedAvatar != null) { - MessagesController.getInstance().changeChatAvatar(chatId, uploadedAvatar); - } else if (avatar == null && currentChat.photo instanceof TLRPC.TL_chatPhoto) { - MessagesController.getInstance().changeChatAvatar(chatId, null); - } - finishFragment(); - } - } - }); - - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - LinearLayout linearLayout; - - fragmentView = new ScrollView(context); - fragmentView.setBackgroundColor(0xfff0f0f0); - ScrollView scrollView = (ScrollView) fragmentView; - scrollView.setFillViewport(true); - linearLayout = new LinearLayout(context); - scrollView.addView(linearLayout, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - - linearLayout.setOrientation(LinearLayout.VERTICAL); - - actionBar.setTitle(LocaleController.getString("ChannelEdit", R.string.ChannelEdit)); - - LinearLayout linearLayout2 = new LinearLayout(context); - linearLayout2.setOrientation(LinearLayout.VERTICAL); - linearLayout2.setBackgroundColor(0xffffffff); - linearLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - FrameLayout frameLayout = new FrameLayout(context); - linearLayout2.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - avatarImage = new BackupImageView(context); - avatarImage.setRoundRadius(AndroidUtilities.dp(32)); - avatarDrawable.setInfo(5, null, null, false); - avatarDrawable.setDrawPhoto(true); - frameLayout.addView(avatarImage, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 12, LocaleController.isRTL ? 16 : 0, 12)); - avatarImage.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - - CharSequence[] items; - - if (avatar != null) { - items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; - } else { - items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; - } - - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (i == 0) { - avatarUpdater.openCamera(); - } else if (i == 1) { - avatarUpdater.openGallery(); - } else if (i == 2) { - avatar = null; - uploadedAvatar = null; - avatarImage.setImage(avatar, "50_50", avatarDrawable); - } - } - }); - showDialog(builder.create()); - } - }); - - nameTextView = new EditText(context); - if (currentChat.megagroup) { - nameTextView.setHint(LocaleController.getString("GroupName", R.string.GroupName)); - } else { - nameTextView.setHint(LocaleController.getString("EnterChannelName", R.string.EnterChannelName)); - } - nameTextView.setMaxLines(4); - nameTextView.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - nameTextView.setHintTextColor(0xff979797); - nameTextView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); - nameTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); - nameTextView.setPadding(0, 0, 0, AndroidUtilities.dp(8)); - InputFilter[] inputFilters = new InputFilter[1]; - inputFilters[0] = new InputFilter.LengthFilter(100); - nameTextView.setFilters(inputFilters); - AndroidUtilities.clearCursorDrawable(nameTextView); - nameTextView.setTextColor(0xff212121); - frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 16 : 96, 0, LocaleController.isRTL ? 96 : 16, 0)); - nameTextView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - avatarDrawable.setInfo(5, nameTextView.length() > 0 ? nameTextView.getText().toString() : null, null, false); - avatarImage.invalidate(); - } - }); - - View lineView = new View(context); - lineView.setBackgroundColor(0xffcfcfcf); - linearLayout.addView(lineView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1)); - - linearLayout2 = new LinearLayout(context); - linearLayout2.setOrientation(LinearLayout.VERTICAL); - linearLayout2.setBackgroundColor(0xffffffff); - linearLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - descriptionTextView = new EditText(context); - descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - descriptionTextView.setHintTextColor(0xff979797); - descriptionTextView.setTextColor(0xff212121); - descriptionTextView.setPadding(0, 0, 0, AndroidUtilities.dp(6)); - descriptionTextView.setBackgroundDrawable(null); - descriptionTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - descriptionTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - descriptionTextView.setImeOptions(EditorInfo.IME_ACTION_DONE); - inputFilters = new InputFilter[1]; - inputFilters[0] = new InputFilter.LengthFilter(255); - descriptionTextView.setFilters(inputFilters); - descriptionTextView.setHint(LocaleController.getString("DescriptionOptionalPlaceholder", R.string.DescriptionOptionalPlaceholder)); - AndroidUtilities.clearCursorDrawable(descriptionTextView); - linearLayout2.addView(descriptionTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 17, 12, 17, 6)); - descriptionTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) { - doneButton.performClick(); - return true; - } - return false; - } - }); - descriptionTextView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - ShadowSectionCell sectionCell = new ShadowSectionCell(context); - sectionCell.setSize(20); - linearLayout.addView(sectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - if (currentChat.megagroup || !currentChat.megagroup) { - frameLayout = new FrameLayout(context); - frameLayout.setBackgroundColor(0xffffffff); - linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - typeCell = new TextSettingsCell(context); - updateTypeCell(); - typeCell.setBackgroundResource(R.drawable.list_selector); - frameLayout.addView(typeCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - lineView = new View(context); - lineView.setBackgroundColor(0xffcfcfcf); - linearLayout.addView(lineView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1)); - - frameLayout = new FrameLayout(context); - frameLayout.setBackgroundColor(0xffffffff); - linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - if (!currentChat.megagroup) { - TextCheckCell textCheckCell = new TextCheckCell(context); - textCheckCell.setBackgroundResource(R.drawable.list_selector); - textCheckCell.setTextAndCheck(LocaleController.getString("ChannelSignMessages", R.string.ChannelSignMessages), signMessages, false); - frameLayout.addView(textCheckCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - textCheckCell.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - signMessages = !signMessages; - ((TextCheckCell) v).setChecked(signMessages); - } - }); - - TextInfoPrivacyCell infoCell = new TextInfoPrivacyCell(context); - infoCell.setBackgroundResource(R.drawable.greydivider); - infoCell.setText(LocaleController.getString("ChannelSignMessagesInfo", R.string.ChannelSignMessagesInfo)); - linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - } else { - adminCell = new TextSettingsCell(context); - updateAdminCell(); - adminCell.setBackgroundResource(R.drawable.list_selector); - frameLayout.addView(adminCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - adminCell.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Bundle args = new Bundle(); - args.putInt("chat_id", chatId); - args.putInt("type", 1); - presentFragment(new ChannelUsersActivity(args)); - } - }); - - sectionCell = new ShadowSectionCell(context); - sectionCell.setSize(20); - linearLayout.addView(sectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - if (!currentChat.creator) { - sectionCell.setBackgroundResource(R.drawable.greydivider_bottom); - } - } - } - - if (currentChat.creator) { - frameLayout = new FrameLayout(context); - frameLayout.setBackgroundColor(0xffffffff); - linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - TextSettingsCell textCell = new TextSettingsCell(context); - textCell.setTextColor(0xffed3d39); - textCell.setBackgroundResource(R.drawable.list_selector); - if (currentChat.megagroup) { - textCell.setText(LocaleController.getString("DeleteMega", R.string.DeleteMega), false); - } else { - textCell.setText(LocaleController.getString("ChannelDelete", R.string.ChannelDelete), false); - } - frameLayout.addView(textCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - textCell.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - if (currentChat.megagroup) { - builder.setMessage(LocaleController.getString("MegaDeleteAlert", R.string.MegaDeleteAlert)); - } else { - builder.setMessage(LocaleController.getString("ChannelDeleteAlert", R.string.ChannelDeleteAlert)); - } - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); - if (AndroidUtilities.isTablet()) { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats, -(long) chatId); - } else { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); - } - MessagesController.getInstance().deleteUserFromChat(chatId, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), info); - finishFragment(); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showDialog(builder.create()); - } - }); - - TextInfoPrivacyCell infoCell = new TextInfoPrivacyCell(context); - infoCell.setBackgroundResource(R.drawable.greydivider_bottom); - if (currentChat.megagroup) { - infoCell.setText(LocaleController.getString("MegaDeleteInfo", R.string.MegaDeleteInfo)); - } else { - infoCell.setText(LocaleController.getString("ChannelDeleteInfo", R.string.ChannelDeleteInfo)); - } - linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - } - - nameTextView.setText(currentChat.title); - nameTextView.setSelection(nameTextView.length()); - if (info != null) { - descriptionTextView.setText(info.about); - } - if (currentChat.photo != null) { - avatar = currentChat.photo.photo_small; - avatarImage.setImage(avatar, "50_50", avatarDrawable); - } else { - avatarImage.setImageDrawable(avatarDrawable); - } - - return fragmentView; - } - - @Override - public void didReceivedNotification(int id, Object... args) { - if (id == NotificationCenter.chatInfoDidLoaded) { - TLRPC.ChatFull chatFull = (TLRPC.ChatFull) args[0]; - if (chatFull.id == chatId) { - if (info == null) { - descriptionTextView.setText(chatFull.about); - } - info = chatFull; - updateAdminCell(); - updateTypeCell(); - } - } else if (id == NotificationCenter.updateInterfaces) { - int updateMask = (Integer) args[0]; - if ((updateMask & MessagesController.UPDATE_MASK_CHANNEL) != 0) { - updateTypeCell(); - } - } - } - - @Override - public void didUploadedPhoto(final TLRPC.InputFile file, final TLRPC.PhotoSize small, final TLRPC.PhotoSize big) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - uploadedAvatar = file; - avatar = small.location; - avatarImage.setImage(avatar, "50_50", avatarDrawable); - if (createAfterUpload) { - try { - if (progressDialog != null && progressDialog.isShowing()) { - progressDialog.dismiss(); - progressDialog = null; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - doneButton.performClick(); - } - } - }); - } - - @Override - public void onActivityResultFragment(int requestCode, int resultCode, Intent data) { - avatarUpdater.onActivityResult(requestCode, resultCode, data); - } - - @Override - public void saveSelfArgs(Bundle args) { - if (avatarUpdater != null && avatarUpdater.currentPicturePath != null) { - args.putString("path", avatarUpdater.currentPicturePath); - } - if (nameTextView != null) { - String text = nameTextView.getText().toString(); - if (text != null && text.length() != 0) { - args.putString("nameTextView", text); - } - } - } - - @Override - public void restoreSelfArgs(Bundle args) { - if (avatarUpdater != null) { - avatarUpdater.currentPicturePath = args.getString("path"); - } - } - - public void setInfo(TLRPC.ChatFull chatFull) { - info = chatFull; - } - - private void updateTypeCell() { - String type = currentChat.username == null || currentChat.username.length() == 0 ? LocaleController.getString("ChannelTypePrivate", R.string.ChannelTypePrivate) : LocaleController.getString("ChannelTypePublic", R.string.ChannelTypePublic); - if (currentChat.megagroup) { - typeCell.setTextAndValue(LocaleController.getString("GroupType", R.string.GroupType), type, false); - } else { - typeCell.setTextAndValue(LocaleController.getString("ChannelType", R.string.ChannelType), type, false); - } - - if (currentChat.creator && (info == null || info.can_set_username)) { - typeCell.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Bundle args = new Bundle(); - args.putInt("chat_id", chatId); - ChannelEditTypeActivity fragment = new ChannelEditTypeActivity(args); - fragment.setInfo(info); - presentFragment(fragment); - } - }); - typeCell.setTextColor(0xff212121); - typeCell.setTextValueColor(0xff2f8cc9); - } else { - typeCell.setOnClickListener(null); - typeCell.setTextColor(0xffa8a8a8); - typeCell.setTextValueColor(0xffa8a8a8); - } - } - - private void updateAdminCell() { - if (adminCell == null) { - return; - } - if (info != null) { - adminCell.setTextAndValue(LocaleController.getString("ChannelAdministrators", R.string.ChannelAdministrators), String.format("%d", info.admins_count), false); - } else { - adminCell.setText(LocaleController.getString("ChannelAdministrators", R.string.ChannelAdministrators), false); - } - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChannelEditTypeActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChannelEditTypeActivity.java deleted file mode 100644 index c317236ac..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChannelEditTypeActivity.java +++ /dev/null @@ -1,538 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.ui; - -import android.app.AlertDialog; -import android.content.Context; -import android.os.Bundle; -import android.os.Vibrator; -import android.text.Editable; -import android.text.InputType; -import android.text.TextWatcher; -import android.util.TypedValue; -import android.view.Gravity; -import android.view.View; -import android.view.ViewGroup; -import android.view.inputmethod.EditorInfo; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.Toast; - -import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.ApplicationLoader; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.MessagesController; -import org.telegram.messenger.MessagesStorage; -import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.R; -import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.RequestDelegate; -import org.telegram.tgnet.TLObject; -import org.telegram.tgnet.TLRPC; -import org.telegram.ui.ActionBar.ActionBar; -import org.telegram.ui.ActionBar.ActionBarMenu; -import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.ui.Cells.HeaderCell; -import org.telegram.ui.Cells.RadioButtonCell; -import org.telegram.ui.Cells.ShadowSectionCell; -import org.telegram.ui.Cells.TextBlockCell; -import org.telegram.ui.Cells.TextInfoPrivacyCell; -import org.telegram.ui.Components.LayoutHelper; - -import java.util.concurrent.Semaphore; - -public class ChannelEditTypeActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { - - private LinearLayout linkContainer; - private LinearLayout publicContainer; - private TextBlockCell privateContainer; - private RadioButtonCell radioButtonCell1; - private RadioButtonCell radioButtonCell2; - private TextInfoPrivacyCell typeInfoCell; - private TextView checkTextView; - private HeaderCell headerCell; - private EditText nameTextView; - private boolean isPrivate = false; - private boolean loadingInvite; - private TLRPC.ExportedChatInvite invite; - - private int checkReqId = 0; - private String lastCheckName = null; - private Runnable checkRunnable = null; - private boolean lastNameAvailable = false; - private TLRPC.Chat currentChat; - private int chatId; - - private boolean donePressed; - - private final static int done_button = 1; - - public ChannelEditTypeActivity(Bundle args) { - super(args); - chatId = args.getInt("chat_id", 0); - } - - @SuppressWarnings("unchecked") - @Override - public boolean onFragmentCreate() { - currentChat = MessagesController.getInstance().getChat(chatId); - if (currentChat == null) { - final Semaphore semaphore = new Semaphore(0); - MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { - @Override - public void run() { - currentChat = MessagesStorage.getInstance().getChat(chatId); - semaphore.release(); - } - }); - try { - semaphore.acquire(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - if (currentChat != null) { - MessagesController.getInstance().putChat(currentChat, true); - } else { - return false; - } - } - isPrivate = currentChat.username == null || currentChat.username.length() == 0; - NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded); - return super.onFragmentCreate(); - } - - @Override - public void onFragmentDestroy() { - super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatInfoDidLoaded); - AndroidUtilities.removeAdjustResize(getParentActivity(), classGuid); - } - - @Override - public void onResume() { - super.onResume(); - AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid); - } - - @Override - public View createView(Context context) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - if (donePressed) { - return; - } - - if (!isPrivate && ((currentChat.username == null && nameTextView.length() != 0) || (currentChat.username != null && !currentChat.username.equalsIgnoreCase(nameTextView.getText().toString())))) { - if (nameTextView.length() != 0 && !lastNameAvailable) { - Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); - if (v != null) { - v.vibrate(200); - } - AndroidUtilities.shakeView(checkTextView, 2, 0); - return; - } - } - donePressed = true; - - String oldUserName = currentChat.username != null ? currentChat.username : ""; - String newUserName = isPrivate ? "" : nameTextView.getText().toString(); - if (!oldUserName.equals(newUserName)) { - MessagesController.getInstance().updateChannelUserName(chatId, newUserName); - } - finishFragment(); - } - } - }); - - ActionBarMenu menu = actionBar.createMenu(); - menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - LinearLayout linearLayout; - - fragmentView = new ScrollView(context); - fragmentView.setBackgroundColor(0xfff0f0f0); - ScrollView scrollView = (ScrollView) fragmentView; - scrollView.setFillViewport(true); - linearLayout = new LinearLayout(context); - scrollView.addView(linearLayout, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - - linearLayout.setOrientation(LinearLayout.VERTICAL); - - if (currentChat.megagroup) { - actionBar.setTitle(LocaleController.getString("GroupType", R.string.GroupType)); - } else { - actionBar.setTitle(LocaleController.getString("ChannelType", R.string.ChannelType)); - } - - LinearLayout linearLayout2 = new LinearLayout(context); - linearLayout2.setOrientation(LinearLayout.VERTICAL); - linearLayout2.setBackgroundColor(0xffffffff); - linearLayout.addView(linearLayout2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - radioButtonCell1 = new RadioButtonCell(context); - radioButtonCell1.setBackgroundResource(R.drawable.list_selector); - if (currentChat.megagroup) { - radioButtonCell1.setTextAndValue(LocaleController.getString("MegaPublic", R.string.MegaPublic), LocaleController.getString("MegaPublicInfo", R.string.MegaPublicInfo), !isPrivate, false); - } else { - radioButtonCell1.setTextAndValue(LocaleController.getString("ChannelPublic", R.string.ChannelPublic), LocaleController.getString("ChannelPublicInfo", R.string.ChannelPublicInfo), !isPrivate, false); - } - linearLayout2.addView(radioButtonCell1, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - radioButtonCell1.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (!isPrivate) { - return; - } - isPrivate = false; - updatePrivatePublic(); - } - }); - - radioButtonCell2 = new RadioButtonCell(context); - radioButtonCell2.setBackgroundResource(R.drawable.list_selector); - if (currentChat.megagroup) { - radioButtonCell2.setTextAndValue(LocaleController.getString("MegaPrivate", R.string.MegaPrivate), LocaleController.getString("MegaPrivateInfo", R.string.MegaPrivateInfo), isPrivate, false); - } else { - radioButtonCell2.setTextAndValue(LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate), LocaleController.getString("ChannelPrivateInfo", R.string.ChannelPrivateInfo), isPrivate, false); - } - linearLayout2.addView(radioButtonCell2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - radioButtonCell2.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (isPrivate) { - return; - } - isPrivate = true; - updatePrivatePublic(); - } - }); - - ShadowSectionCell sectionCell = new ShadowSectionCell(context); - linearLayout.addView(sectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - linkContainer = new LinearLayout(context); - linkContainer.setOrientation(LinearLayout.VERTICAL); - linkContainer.setBackgroundColor(0xffffffff); - linearLayout.addView(linkContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - headerCell = new HeaderCell(context); - linkContainer.addView(headerCell); - - publicContainer = new LinearLayout(context); - publicContainer.setOrientation(LinearLayout.HORIZONTAL); - linkContainer.addView(publicContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 17, 7, 17, 0)); - - EditText editText = new EditText(context); - editText.setText("telegram.me/"); - editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - editText.setHintTextColor(0xff979797); - editText.setTextColor(0xff212121); - editText.setMaxLines(1); - editText.setLines(1); - editText.setEnabled(false); - editText.setBackgroundDrawable(null); - editText.setPadding(0, 0, 0, 0); - editText.setSingleLine(true); - editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - editText.setImeOptions(EditorInfo.IME_ACTION_DONE); - publicContainer.addView(editText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36)); - - nameTextView = new EditText(context); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - if (!isPrivate) { - nameTextView.setText(currentChat.username); - } - nameTextView.setHintTextColor(0xff979797); - nameTextView.setTextColor(0xff212121); - nameTextView.setMaxLines(1); - nameTextView.setLines(1); - nameTextView.setBackgroundDrawable(null); - nameTextView.setPadding(0, 0, 0, 0); - nameTextView.setSingleLine(true); - nameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - nameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE); - nameTextView.setHint(LocaleController.getString("ChannelUsernamePlaceholder", R.string.ChannelUsernamePlaceholder)); - AndroidUtilities.clearCursorDrawable(nameTextView); - publicContainer.addView(nameTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36)); - nameTextView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { - checkUserName(nameTextView.getText().toString(), false); - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - privateContainer = new TextBlockCell(context); - privateContainer.setBackgroundResource(R.drawable.list_selector); - linkContainer.addView(privateContainer); - privateContainer.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (invite == null) { - return; - } - try { - android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); - android.content.ClipData clip = android.content.ClipData.newPlainText("label", invite.link); - clipboard.setPrimaryClip(clip); - Toast.makeText(getParentActivity(), LocaleController.getString("LinkCopied", R.string.LinkCopied), Toast.LENGTH_SHORT).show(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - - checkTextView = new TextView(context); - checkTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - checkTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - checkTextView.setVisibility(View.GONE); - linkContainer.addView(checkTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 17, 3, 17, 7)); - - typeInfoCell = new TextInfoPrivacyCell(context); - typeInfoCell.setBackgroundResource(R.drawable.greydivider_bottom); - linearLayout.addView(typeInfoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - - updatePrivatePublic(); - - return fragmentView; - } - - @Override - public void didReceivedNotification(int id, Object... args) { - if (id == NotificationCenter.chatInfoDidLoaded) { - TLRPC.ChatFull chatFull = (TLRPC.ChatFull) args[0]; - if (chatFull.id == chatId) { - invite = chatFull.exported_invite; - updatePrivatePublic(); - } - } - } - - public void setInfo(TLRPC.ChatFull chatFull) { - if (chatFull != null) { - if (chatFull.exported_invite instanceof TLRPC.TL_chatInviteExported) { - invite = chatFull.exported_invite; - } else { - generateLink(); - } - } - } - - private void updatePrivatePublic() { - radioButtonCell1.setChecked(!isPrivate, true); - radioButtonCell2.setChecked(isPrivate, true); - if (currentChat.megagroup) { - typeInfoCell.setText(isPrivate ? LocaleController.getString("MegaPrivateLinkHelp", R.string.MegaPrivateLinkHelp) : LocaleController.getString("MegaUsernameHelp", R.string.MegaUsernameHelp)); - headerCell.setText(isPrivate ? LocaleController.getString("ChannelInviteLinkTitle", R.string.ChannelInviteLinkTitle) : LocaleController.getString("ChannelLinkTitle", R.string.ChannelLinkTitle)); - } else { - typeInfoCell.setText(isPrivate ? LocaleController.getString("ChannelPrivateLinkHelp", R.string.ChannelPrivateLinkHelp) : LocaleController.getString("ChannelUsernameHelp", R.string.ChannelUsernameHelp)); - headerCell.setText(isPrivate ? LocaleController.getString("ChannelInviteLinkTitle", R.string.ChannelInviteLinkTitle) : LocaleController.getString("ChannelLinkTitle", R.string.ChannelLinkTitle)); - } - publicContainer.setVisibility(isPrivate ? View.GONE : View.VISIBLE); - privateContainer.setVisibility(isPrivate ? View.VISIBLE : View.GONE); - linkContainer.setPadding(0, 0, 0, isPrivate ? 0 : AndroidUtilities.dp(7)); - privateContainer.setText(invite != null ? invite.link : LocaleController.getString("Loading", R.string.Loading), false); - nameTextView.clearFocus(); - checkTextView.setVisibility(!isPrivate && checkTextView.length() != 0 ? View.VISIBLE : View.GONE); - AndroidUtilities.hideKeyboard(nameTextView); - } - - private boolean checkUserName(final String name, boolean alert) { - if (name != null && name.length() > 0) { - checkTextView.setVisibility(View.VISIBLE); - } else { - checkTextView.setVisibility(View.GONE); - } - if (alert && name.length() == 0) { - return true; - } - if (checkRunnable != null) { - AndroidUtilities.cancelRunOnUIThread(checkRunnable); - checkRunnable = null; - lastCheckName = null; - if (checkReqId != 0) { - ConnectionsManager.getInstance().cancelRequest(checkReqId, true); - } - } - lastNameAvailable = false; - if (name != null) { - if (name.startsWith("_") || name.endsWith("_")) { - checkTextView.setText(LocaleController.getString("LinkInvalid", R.string.LinkInvalid)); - checkTextView.setTextColor(0xffcf3030); - return false; - } - for (int a = 0; a < name.length(); a++) { - char ch = name.charAt(a); - if (a == 0 && ch >= '0' && ch <= '9') { - if (currentChat.megagroup) { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalidStartNumberMega", R.string.LinkInvalidStartNumberMega)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalidStartNumberMega", R.string.LinkInvalidStartNumberMega)); - checkTextView.setTextColor(0xffcf3030); - } - } else { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber)); - checkTextView.setTextColor(0xffcf3030); - } - } - return false; - } - if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalid", R.string.LinkInvalid)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalid", R.string.LinkInvalid)); - checkTextView.setTextColor(0xffcf3030); - } - return false; - } - } - } - if (name == null || name.length() < 5) { - if (currentChat.megagroup) { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalidShortMega", R.string.LinkInvalidShortMega)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalidShortMega", R.string.LinkInvalidShortMega)); - checkTextView.setTextColor(0xffcf3030); - } - } else { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort)); - checkTextView.setTextColor(0xffcf3030); - } - } - return false; - } - if (name.length() > 32) { - if (alert) { - showErrorAlert(LocaleController.getString("LinkInvalidLong", R.string.LinkInvalidLong)); - } else { - checkTextView.setText(LocaleController.getString("LinkInvalidLong", R.string.LinkInvalidLong)); - checkTextView.setTextColor(0xffcf3030); - } - return false; - } - - if (!alert) { - checkTextView.setText(LocaleController.getString("LinkChecking", R.string.LinkChecking)); - checkTextView.setTextColor(0xff6d6d72); - lastCheckName = name; - checkRunnable = new Runnable() { - @Override - public void run() { - TLRPC.TL_channels_checkUsername req = new TLRPC.TL_channels_checkUsername(); - req.username = name; - req.channel = MessagesController.getInputChannel(chatId); - checkReqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - checkReqId = 0; - if (lastCheckName != null && lastCheckName.equals(name)) { - if (error == null && response instanceof TLRPC.TL_boolTrue) { - checkTextView.setText(LocaleController.formatString("LinkAvailable", R.string.LinkAvailable, name)); - checkTextView.setTextColor(0xff26972c); - lastNameAvailable = true; - } else { - if (error != null && error.text.equals("CHANNELS_ADMIN_PUBLIC_TOO_MUCH")) { - checkTextView.setText(LocaleController.getString("ChangePublicLimitReached", R.string.ChangePublicLimitReached)); - } else { - checkTextView.setText(LocaleController.getString("LinkInUse", R.string.LinkInUse)); - } - checkTextView.setTextColor(0xffcf3030); - lastNameAvailable = false; - } - } - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors); - } - }; - AndroidUtilities.runOnUIThread(checkRunnable, 300); - } - return true; - } - - private void generateLink() { - if (loadingInvite || invite != null) { - return; - } - loadingInvite = true; - TLRPC.TL_channels_exportInvite req = new TLRPC.TL_channels_exportInvite(); - req.channel = MessagesController.getInputChannel(chatId); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (error == null) { - invite = (TLRPC.ExportedChatInvite) response; - } - loadingInvite = false; - privateContainer.setText(invite != null ? invite.link : LocaleController.getString("Loading", R.string.Loading), false); - } - }); - } - }); - } - - private void showErrorAlert(String error) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - switch (error) { - case "USERNAME_INVALID": - builder.setMessage(LocaleController.getString("LinkInvalid", R.string.LinkInvalid)); - break; - case "USERNAME_OCCUPIED": - builder.setMessage(LocaleController.getString("LinkInUse", R.string.LinkInUse)); - break; - case "USERNAMES_UNAVAILABLE": - builder.setMessage(LocaleController.getString("FeatureUnavailable", R.string.FeatureUnavailable)); - break; - default: - builder.setMessage(LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred)); - break; - } - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); - showDialog(builder.create()); - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChannelIntroActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChannelIntroActivity.java deleted file mode 100644 index 1ad5b77b8..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChannelIntroActivity.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.ui; - -import android.content.Context; -import android.os.Bundle; -import android.util.TypedValue; -import android.view.Gravity; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.R; -import org.telegram.ui.ActionBar.ActionBar; -import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.ui.ActionBar.Theme; - -public class ChannelIntroActivity extends BaseFragment { - - private ImageView imageView; - private TextView createChannelText; - private TextView whatIsChannelText; - private TextView descriptionText; - - @Override - public View createView(Context context) { - actionBar.setBackgroundColor(Theme.ACTION_BAR_CHANNEL_INTRO_COLOR); - actionBar.setBackButtonImage(R.drawable.pl_back); - actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_CHANNEL_INTRO_SELECTOR_COLOR); - actionBar.setCastShadows(false); - if (!AndroidUtilities.isTablet()) { - actionBar.showActionModeTop(); - } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } - } - }); - - fragmentView = new ViewGroup(context) { - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int width = MeasureSpec.getSize(widthMeasureSpec); - int height = MeasureSpec.getSize(heightMeasureSpec); - - if (width > height) { - imageView.measure(MeasureSpec.makeMeasureSpec((int) (width * 0.45f), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec((int) (height * 0.78f), MeasureSpec.EXACTLY)); - whatIsChannelText.measure(MeasureSpec.makeMeasureSpec((int) (width * 0.6f), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED)); - descriptionText.measure(MeasureSpec.makeMeasureSpec((int) (width * 0.5f), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED)); - createChannelText.measure(MeasureSpec.makeMeasureSpec((int) (width * 0.6f), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.EXACTLY)); - } else { - imageView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec((int) (height * 0.44f), MeasureSpec.EXACTLY)); - whatIsChannelText.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED)); - descriptionText.measure(MeasureSpec.makeMeasureSpec((int) (width * 0.9f), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED)); - createChannelText.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.EXACTLY)); - } - - setMeasuredDimension(width, height); - } - - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - int width = r - l; - int height = b - t; - - if (r > b) { - int y = (int) (height * 0.05f); - imageView.layout(0, y, imageView.getMeasuredWidth(), y + imageView.getMeasuredHeight()); - int x = (int) (width * 0.4f); - y = (int) (height * 0.14f); - whatIsChannelText.layout(x, y, x + whatIsChannelText.getMeasuredWidth(), y + whatIsChannelText.getMeasuredHeight()); - y = (int) (height * 0.61f); - createChannelText.layout(x, y, x + createChannelText.getMeasuredWidth(), y + createChannelText.getMeasuredHeight()); - x = (int) (width * 0.45f); - y = (int) (height * 0.31f); - descriptionText.layout(x, y, x + descriptionText.getMeasuredWidth(), y + descriptionText.getMeasuredHeight()); - } else { - int y = (int) (height * 0.05f); - imageView.layout(0, y, imageView.getMeasuredWidth(), y + imageView.getMeasuredHeight()); - y = (int) (height * 0.59f); - whatIsChannelText.layout(0, y, whatIsChannelText.getMeasuredWidth(), y + whatIsChannelText.getMeasuredHeight()); - y = (int) (height * 0.68f); - int x = (int) (width * 0.05f); - descriptionText.layout(x, y, x + descriptionText.getMeasuredWidth(), y + descriptionText.getMeasuredHeight()); - y = (int) (height * 0.86f); - createChannelText.layout(0, y, createChannelText.getMeasuredWidth(), y + createChannelText.getMeasuredHeight()); - } - } - }; - fragmentView.setBackgroundColor(0xffffffff); - ViewGroup viewGroup = (ViewGroup) fragmentView; - viewGroup.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - imageView = new ImageView(context); - imageView.setImageResource(R.drawable.channelintro); - imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); - viewGroup.addView(imageView); - - whatIsChannelText = new TextView(context); - whatIsChannelText.setTextColor(0xff212121); - whatIsChannelText.setGravity(Gravity.CENTER_HORIZONTAL); - whatIsChannelText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 24); - whatIsChannelText.setText(LocaleController.getString("ChannelAlertTitle", R.string.ChannelAlertTitle)); - viewGroup.addView(whatIsChannelText); - - descriptionText = new TextView(context); - descriptionText.setTextColor(0xff787878); - descriptionText.setGravity(Gravity.CENTER_HORIZONTAL); - descriptionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - descriptionText.setText(LocaleController.getString("ChannelAlertText", R.string.ChannelAlertText)); - viewGroup.addView(descriptionText); - - createChannelText = new TextView(context); - createChannelText.setTextColor(0xff4c8eca); - createChannelText.setGravity(Gravity.CENTER); - createChannelText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - createChannelText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - createChannelText.setText(LocaleController.getString("ChannelAlertCreate", R.string.ChannelAlertCreate)); - viewGroup.addView(createChannelText); - createChannelText.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Bundle args = new Bundle(); - args.putInt("step", 0); - presentFragment(new ChannelCreateActivity(args), true); - } - }); - - return fragmentView; - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChannelUsersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChannelUsersActivity.java deleted file mode 100644 index 958a1e7ad..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChannelUsersActivity.java +++ /dev/null @@ -1,717 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.ui; - -import android.app.AlertDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.os.Bundle; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.FrameLayout; -import android.widget.ListView; - -import org.telegram.PhoneFormat.PhoneFormat; -import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.MessagesController; -import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.R; -import org.telegram.messenger.UserConfig; -import org.telegram.messenger.Utilities; -import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.RequestDelegate; -import org.telegram.tgnet.TLObject; -import org.telegram.tgnet.TLRPC; -import org.telegram.ui.ActionBar.ActionBar; -import org.telegram.ui.ActionBar.ActionBarMenu; -import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.ui.Adapters.BaseFragmentAdapter; -import org.telegram.ui.Cells.HeaderCell; -import org.telegram.ui.Cells.RadioCell; -import org.telegram.ui.Cells.ShadowSectionCell; -import org.telegram.ui.Cells.TextCell; -import org.telegram.ui.Cells.TextInfoPrivacyCell; -import org.telegram.ui.Cells.TextSettingsCell; -import org.telegram.ui.Cells.UserCell; -import org.telegram.ui.Components.AlertsCreator; -import org.telegram.ui.Components.EmptyTextProgressView; -import org.telegram.ui.Components.LayoutHelper; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; - -public class ChannelUsersActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { - - private ListAdapter listViewAdapter; - private EmptyTextProgressView emptyView; - - private ArrayList participants = new ArrayList<>(); - private int chatId; - private int type; - private boolean loadingUsers; - private boolean firstLoaded; - private boolean isAdmin; - private boolean isPublic; - private boolean isMegagroup; - private int participantsStartRow; - - public ChannelUsersActivity(Bundle args) { - super(args); - chatId = arguments.getInt("chat_id"); - type = arguments.getInt("type"); - TLRPC.Chat chat = MessagesController.getInstance().getChat(chatId); - if (chat != null) { - if (chat.creator) { - isAdmin = true; - isPublic = (chat.flags & TLRPC.CHAT_FLAG_IS_PUBLIC) != 0; - } - isMegagroup = chat.megagroup; - } - if (type == 0) { - participantsStartRow = 0; - } else if (type == 1) { - participantsStartRow = isAdmin && isMegagroup ? 4 : 0; - } else if (type == 2) { - participantsStartRow = isAdmin ? (isPublic ? 2 : 3) : 0; - } - } - - @Override - public boolean onFragmentCreate() { - super.onFragmentCreate(); - NotificationCenter.getInstance().addObserver(this, NotificationCenter.chatInfoDidLoaded); - getChannelParticipants(0, 200); - return true; - } - - @Override - public void onFragmentDestroy() { - super.onFragmentDestroy(); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.chatInfoDidLoaded); - } - - @Override - public View createView(Context context) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - if (type == 0) { - actionBar.setTitle(LocaleController.getString("ChannelBlockedUsers", R.string.ChannelBlockedUsers)); - } else if (type == 1) { - actionBar.setTitle(LocaleController.getString("ChannelAdministrators", R.string.ChannelAdministrators)); - } else if (type == 2) { - actionBar.setTitle(LocaleController.getString("ChannelMembers", R.string.ChannelMembers)); - } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } - } - }); - - ActionBarMenu menu = actionBar.createMenu(); - - fragmentView = new FrameLayout(context); - fragmentView.setBackgroundColor(0xfff0f0f0); - FrameLayout frameLayout = (FrameLayout) fragmentView; - - emptyView = new EmptyTextProgressView(context); - if (type == 0) { - if (isMegagroup) { - emptyView.setText(LocaleController.getString("NoBlockedGroup", R.string.NoBlockedGroup)); - } else { - emptyView.setText(LocaleController.getString("NoBlocked", R.string.NoBlocked)); - } - } - frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); - - final ListView listView = new ListView(context); - listView.setEmptyView(emptyView); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setDrawSelectorOnTop(true); - listView.setAdapter(listViewAdapter = new ListAdapter(context)); - listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); - frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); - - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (type == 2) { - if (isAdmin) { - if (i == 0) { - Bundle args = new Bundle(); - args.putBoolean("onlyUsers", true); - args.putBoolean("destroyAfterSelect", true); - args.putBoolean("returnAsResult", true); - args.putBoolean("needForwardCount", false); - args.putBoolean("allowUsernameSearch", false); - args.putString("selectAlertString", LocaleController.getString("ChannelAddTo", R.string.ChannelAddTo)); - ContactsActivity fragment = new ContactsActivity(args); - fragment.setDelegate(new ContactsActivity.ContactsActivityDelegate() { - @Override - public void didSelectContact(TLRPC.User user, String param) { - MessagesController.getInstance().addUserToChat(chatId, user, null, param != null ? Utilities.parseInt(param) : 0, null, ChannelUsersActivity.this); - } - }); - presentFragment(fragment); - } else if (!isPublic && i == 1) { - presentFragment(new GroupInviteActivity(chatId)); - } - } - - } else if (type == 1) { - if (isAdmin) { - if (isMegagroup && (i == 1 || i == 2)) { - TLRPC.Chat chat = MessagesController.getInstance().getChat(chatId); - if (chat == null) { - return; - } - boolean changed = false; - if (i == 1 && !chat.democracy) { - chat.democracy = true; - changed = true; - } else if (i == 2 && chat.democracy) { - chat.democracy = false; - changed = true; - } - if (changed) { - MessagesController.getInstance().toogleChannelInvites(chatId, chat.democracy); - int count = listView.getChildCount(); - for (int a = 0; a < count; a++) { - View child = listView.getChildAt(a); - if (child instanceof RadioCell) { - int num = (Integer) child.getTag(); - ((RadioCell) child).setChecked(num == 0 && chat.democracy || num == 1 && !chat.democracy, true); - } - } - } - return; - } - if (i == participantsStartRow + participants.size()) { - Bundle args = new Bundle(); - args.putBoolean("onlyUsers", true); - args.putBoolean("destroyAfterSelect", true); - args.putBoolean("returnAsResult", true); - args.putBoolean("needForwardCount", false); - args.putBoolean("allowUsernameSearch", true); - /*if (isMegagroup) { - args.putBoolean("allowBots", false); - }*/ - args.putString("selectAlertString", LocaleController.getString("ChannelAddUserAdminAlert", R.string.ChannelAddUserAdminAlert)); - ContactsActivity fragment = new ContactsActivity(args); - fragment.setDelegate(new ContactsActivity.ContactsActivityDelegate() { - @Override - public void didSelectContact(TLRPC.User user, String param) { - setUserChannelRole(user, new TLRPC.TL_channelRoleEditor()); - } - }); - presentFragment(fragment); - return; - } - } - } - TLRPC.ChannelParticipant participant = null; - if (i >= participantsStartRow && i < participants.size() + participantsStartRow) { - participant = participants.get(i - participantsStartRow); - } - if (participant != null) { - Bundle args = new Bundle(); - args.putInt("user_id", participant.user_id); - presentFragment(new ProfileActivity(args)); - } - } - }); - - if (isAdmin || isMegagroup && type == 0) { - listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { - if (getParentActivity() == null) { - return false; - } - TLRPC.ChannelParticipant participant = null; - if (i >= participantsStartRow && i < participants.size() + participantsStartRow) { - participant = participants.get(i - participantsStartRow); - } - if (participant != null) { - final TLRPC.ChannelParticipant finalParticipant = participant; - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - CharSequence[] items = null; - if (type == 0) { - items = new CharSequence[]{LocaleController.getString("Unblock", R.string.Unblock)}; - } else if (type == 1) { - items = new CharSequence[]{LocaleController.getString("ChannelRemoveUserAdmin", R.string.ChannelRemoveUserAdmin)}; - } else if (type == 2) { - items = new CharSequence[]{LocaleController.getString("ChannelRemoveUser", R.string.ChannelRemoveUser)}; - } - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (i == 0) { - if (type == 0) { - participants.remove(finalParticipant); - listViewAdapter.notifyDataSetChanged(); - TLRPC.TL_channels_kickFromChannel req = new TLRPC.TL_channels_kickFromChannel(); - req.kicked = false; - req.user_id = MessagesController.getInputUser(finalParticipant.user_id); - req.channel = MessagesController.getInputChannel(chatId); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (response != null) { - final TLRPC.Updates updates = (TLRPC.Updates) response; - MessagesController.getInstance().processUpdates(updates, false); - if (!updates.chats.isEmpty()) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - TLRPC.Chat chat = updates.chats.get(0); - MessagesController.getInstance().loadFullChat(chat.id, 0, true); - } - }, 1000); - } - } - } - }); - } else if (type == 1) { - setUserChannelRole(MessagesController.getInstance().getUser(finalParticipant.user_id), new TLRPC.TL_channelRoleEmpty()); - } else if (type == 2) { - MessagesController.getInstance().deleteUserFromChat(chatId, MessagesController.getInstance().getUser(finalParticipant.user_id), null); - } - } - } - }); - showDialog(builder.create()); - return true; - } else { - return false; - } - } - }); - } - - if (loadingUsers) { - emptyView.showProgress(); - } else { - emptyView.showTextView(); - } - return fragmentView; - } - - public void setUserChannelRole(TLRPC.User user, TLRPC.ChannelParticipantRole role) { - if (user == null || role == null) { - return; - } - TLRPC.TL_channels_editAdmin req = new TLRPC.TL_channels_editAdmin(); - req.channel = MessagesController.getInputChannel(chatId); - req.user_id = MessagesController.getInputUser(user); - req.role = role; - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, final TLRPC.TL_error error) { - if (error == null) { - MessagesController.getInstance().processUpdates((TLRPC.Updates) response, false); - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - MessagesController.getInstance().loadFullChat(chatId, 0, true); - } - }, 1000); - } else { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - AlertsCreator.showAddUserAlert(error.text, ChannelUsersActivity.this, !isMegagroup); - } - }); - } - } - }); - } - - @Override - public void didReceivedNotification(int id, Object... args) { - if (id == NotificationCenter.chatInfoDidLoaded) { - TLRPC.ChatFull chatFull = (TLRPC.ChatFull) args[0]; - if (chatFull.id == chatId) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - getChannelParticipants(0, 200); - } - }); - } - } - } - - private int getChannelAdminParticipantType(TLRPC.ChannelParticipant participant) { - if (participant instanceof TLRPC.TL_channelParticipantCreator || participant instanceof TLRPC.TL_channelParticipantSelf) { - return 0; - } else if (participant instanceof TLRPC.TL_channelParticipantEditor) { - return 1; - } else { - return 2; - } - } - - private void getChannelParticipants(int offset, int count) { - if (loadingUsers) { - return; - } - loadingUsers = true; - if (emptyView != null && !firstLoaded) { - emptyView.showProgress(); - } - if (listViewAdapter != null) { - listViewAdapter.notifyDataSetChanged(); - } - TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants(); - req.channel = MessagesController.getInputChannel(chatId); - if (type == 0) { - req.filter = new TLRPC.TL_channelParticipantsKicked(); - } else if (type == 1) { - req.filter = new TLRPC.TL_channelParticipantsAdmins(); - } else if (type == 2) { - req.filter = new TLRPC.TL_channelParticipantsRecent(); - } - req.offset = offset; - req.limit = count; - int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (error == null) { - TLRPC.TL_channels_channelParticipants res = (TLRPC.TL_channels_channelParticipants) response; - MessagesController.getInstance().putUsers(res.users, false); - participants = res.participants; - try { - if (type == 0 || type == 2) { - Collections.sort(participants, new Comparator() { - @Override - public int compare(TLRPC.ChannelParticipant lhs, TLRPC.ChannelParticipant rhs) { - TLRPC.User user1 = MessagesController.getInstance().getUser(rhs.user_id); - TLRPC.User user2 = MessagesController.getInstance().getUser(lhs.user_id); - int status1 = 0; - int status2 = 0; - if (user1 != null && user1.status != null) { - if (user1.id == UserConfig.getClientUserId()) { - status1 = ConnectionsManager.getInstance().getCurrentTime() + 50000; - } else { - status1 = user1.status.expires; - } - } - if (user2 != null && user2.status != null) { - if (user2.id == UserConfig.getClientUserId()) { - status2 = ConnectionsManager.getInstance().getCurrentTime() + 50000; - } else { - status2 = user2.status.expires; - } - } - if (status1 > 0 && status2 > 0) { - if (status1 > status2) { - return 1; - } else if (status1 < status2) { - return -1; - } - return 0; - } else if (status1 < 0 && status2 < 0) { - if (status1 > status2) { - return 1; - } else if (status1 < status2) { - return -1; - } - return 0; - } else if (status1 < 0 && status2 > 0 || status1 == 0 && status2 != 0) { - return -1; - } else if (status2 < 0 && status1 > 0 || status2 == 0 && status1 != 0) { - return 1; - } - return 0; - } - }); - } else if (type == 1) { - Collections.sort(res.participants, new Comparator() { - @Override - public int compare(TLRPC.ChannelParticipant lhs, TLRPC.ChannelParticipant rhs) { - int type1 = getChannelAdminParticipantType(lhs); - int type2 = getChannelAdminParticipantType(rhs); - if (type1 > type2) { - return 1; - } else if (type1 < type2) { - return -1; - } - return 0; - } - }); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - loadingUsers = false; - firstLoaded = true; - if (emptyView != null) { - emptyView.showTextView(); - } - if (listViewAdapter != null) { - listViewAdapter.notifyDataSetChanged(); - } - } - }); - } - }); - ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid); - } - - @Override - public void onResume() { - super.onResume(); - if (listViewAdapter != null) { - listViewAdapter.notifyDataSetChanged(); - } - } - - private class ListAdapter extends BaseFragmentAdapter { - private Context mContext; - - public ListAdapter(Context context) { - mContext = context; - } - - @Override - public boolean areAllItemsEnabled() { - return false; - } - - @Override - public boolean isEnabled(int i) { - if (type == 2) { - if (isAdmin) { - if (!isPublic) { - if (i == 0 || i == 1) { - return true; - } else if (i == 2) { - return false; - } - } else { - if (i == 0) { - return true; - } else if (i == 1) { - return false; - } - } - } - } else if (type == 1) { - if (i == participantsStartRow + participants.size()) { - return isAdmin; - } else if (i == participantsStartRow + participants.size() + 1) { - return false; - } else if (isMegagroup && isAdmin && i < 4) { - return i == 1 || i == 2; - } - } - return i != participants.size() + participantsStartRow && participants.get(i - participantsStartRow).user_id != UserConfig.getClientUserId(); - } - - @Override - public int getCount() { - if (participants.isEmpty() && type == 0 || loadingUsers && !firstLoaded) { - return 0; - } else if (type == 1) { - return participants.size() + (isAdmin ? 2 : 1) + (isAdmin && isMegagroup ? 4 : 0); - } - return participants.size() + participantsStartRow + 1; - } - - @Override - public Object getItem(int i) { - return null; - } - - @Override - public long getItemId(int i) { - return i; - } - - @Override - public boolean hasStableIds() { - return false; - } - - @Override - public View getView(int i, View view, ViewGroup viewGroup) { - int viewType = getItemViewType(i); - if (viewType == 0) { - if (view == null) { - view = new UserCell(mContext, 1, 0, false); - view.setBackgroundColor(0xffffffff); - } - UserCell userCell = (UserCell) view; - TLRPC.ChannelParticipant participant = participants.get(i - participantsStartRow); - TLRPC.User user = MessagesController.getInstance().getUser(participant.user_id); - if (user != null) { - if (type == 0) { - userCell.setData(user, null, user.phone != null && user.phone.length() != 0 ? PhoneFormat.getInstance().format("+" + user.phone) : LocaleController.getString("NumberUnknown", R.string.NumberUnknown), 0); - } else if (type == 1) { - String role = null; - if (participant instanceof TLRPC.TL_channelParticipantCreator || participant instanceof TLRPC.TL_channelParticipantSelf) { - role = LocaleController.getString("ChannelCreator", R.string.ChannelCreator); - } else if (participant instanceof TLRPC.TL_channelParticipantModerator) { - role = LocaleController.getString("ChannelModerator", R.string.ChannelModerator); - } else if (participant instanceof TLRPC.TL_channelParticipantEditor) { - role = LocaleController.getString("ChannelEditor", R.string.ChannelEditor); - } - userCell.setData(user, null, role, 0); - } else if (type == 2) { - userCell.setData(user, null, null, 0); - } - } - } else if (viewType == 1) { - if (view == null) { - view = new TextInfoPrivacyCell(mContext); - } - if (type == 0) { - ((TextInfoPrivacyCell) view).setText(String.format("%1$s\n\n%2$s", LocaleController.getString("NoBlockedGroup", R.string.NoBlockedGroup), LocaleController.getString("UnblockText", R.string.UnblockText))); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } else if (type == 1) { - if (isAdmin) { - if (isMegagroup) { - ((TextInfoPrivacyCell) view).setText(LocaleController.getString("MegaAdminsInfo", R.string.MegaAdminsInfo)); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } else { - ((TextInfoPrivacyCell) view).setText(LocaleController.getString("ChannelAdminsInfo", R.string.ChannelAdminsInfo)); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } - } else { - ((TextInfoPrivacyCell) view).setText(""); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } - } else if (type == 2) { - if ((!isPublic && i == 2 || i == 1) && isAdmin) { - if (isMegagroup) { - ((TextInfoPrivacyCell) view).setText(""); - } else { - ((TextInfoPrivacyCell) view).setText(LocaleController.getString("ChannelMembersInfo", R.string.ChannelMembersInfo)); - } - view.setBackgroundResource(R.drawable.greydivider); - } else { - ((TextInfoPrivacyCell) view).setText(""); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } - } - } else if (viewType == 2) { - if (view == null) { - view = new TextSettingsCell(mContext); - view.setBackgroundColor(0xffffffff); - } - TextSettingsCell actionCell = (TextSettingsCell) view; - if (type == 2) { - if (i == 0) { - actionCell.setText(LocaleController.getString("AddMember", R.string.AddMember), true); - } else if (i == 1) { - actionCell.setText(LocaleController.getString("ChannelInviteViaLink", R.string.ChannelInviteViaLink), false); - } - } else if (type == 1) { - actionCell.setTextAndIcon(LocaleController.getString("ChannelAddAdmin", R.string.ChannelAddAdmin), R.drawable.managers, false); - } - } else if (viewType == 3) { - if (view == null) { - view = new ShadowSectionCell(mContext); - } - } else if (viewType == 4) { - if (view == null) { - view = new TextCell(mContext); - view.setBackgroundColor(0xffffffff); - } - ((TextCell) view).setTextAndIcon(LocaleController.getString("ChannelAddAdmin", R.string.ChannelAddAdmin), R.drawable.managers); - } else if (viewType == 5) { - if (view == null) { - view = new HeaderCell(mContext); - view.setBackgroundColor(0xffffffff); - } - ((HeaderCell) view).setText(LocaleController.getString("WhoCanAddMembers", R.string.WhoCanAddMembers)); - } else if (viewType == 6) { - if (view == null) { - view = new RadioCell(mContext); - view.setBackgroundColor(0xffffffff); - } - RadioCell radioCell = (RadioCell) view; - TLRPC.Chat chat = MessagesController.getInstance().getChat(chatId); - if (i == 1) { - radioCell.setTag(0); - radioCell.setText(LocaleController.getString("WhoCanAddMembersAllMembers", R.string.WhoCanAddMembersAllMembers), chat != null && chat.democracy, true); - } else if (i == 2) { - radioCell.setTag(1); - radioCell.setText(LocaleController.getString("WhoCanAddMembersAdmins", R.string.WhoCanAddMembersAdmins), chat != null && !chat.democracy, false); - } - } - return view; - } - - @Override - public int getItemViewType(int i) { - if (type == 1) { - if (isAdmin) { - if (isMegagroup) { - if (i == 0) { - return 5; - } else if (i == 1 || i == 2) { - return 6; - } else if (i == 3) { - return 3; - } - } - if (i == participantsStartRow + participants.size()) { - return 4; - } else if (i == participantsStartRow + participants.size() + 1) { - return 1; - } - } - } else if (type == 2) { - if (isAdmin) { - if (!isPublic) { - if (i == 0 || i == 1) { - return 2; - } else if (i == 2) { - return 1; - } - } else { - if (i == 0) { - return 2; - } else if (i == 1) { - return 1; - } - } - } - } - if (i == participants.size() + participantsStartRow) { - return 1; - } - return 0; - } - - @Override - public int getViewTypeCount() { - return 7; - } - - @Override - public boolean isEmpty() { - return getCount() == 0 || participants.isEmpty() && loadingUsers; - } - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/TwoStepVerificationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/TwoStepVerificationActivity.java deleted file mode 100644 index 63e638ee6..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/TwoStepVerificationActivity.java +++ /dev/null @@ -1,1072 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.ui; - -import android.app.AlertDialog; -import android.app.Dialog; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.graphics.Typeface; -import android.os.Vibrator; -import android.text.InputType; -import android.text.method.PasswordTransformationMethod; -import android.util.TypedValue; -import android.view.ActionMode; -import android.view.Gravity; -import android.view.KeyEvent; -import android.view.Menu; -import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.inputmethod.EditorInfo; -import android.widget.AdapterView; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.ProgressBar; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.Toast; - -import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.R; -import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.RequestDelegate; -import org.telegram.tgnet.TLObject; -import org.telegram.tgnet.TLRPC; -import org.telegram.messenger.Utilities; -import org.telegram.ui.ActionBar.ActionBar; -import org.telegram.ui.ActionBar.ActionBarMenu; -import org.telegram.ui.ActionBar.ActionBarMenuItem; -import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.ui.Adapters.BaseFragmentAdapter; -import org.telegram.ui.Cells.TextInfoPrivacyCell; -import org.telegram.ui.Cells.TextSettingsCell; -import org.telegram.ui.Components.LayoutHelper; - -public class TwoStepVerificationActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { - - private ListAdapter listAdapter; - private ListView listView; - private TextView titleTextView; - private TextView bottomTextView; - private TextView bottomButton; - private EditText passwordEditText; - private ProgressDialog progressDialog; - private FrameLayout progressView; - private ActionBarMenuItem doneItem; - private ScrollView scrollView; - - private int type; - private int passwordSetState; - private String firstPassword; - private String hint; - private String email; - private boolean emailOnly; - private boolean loading; - private boolean destroyed; - private boolean waitingForEmail; - private TLRPC.account_Password currentPassword; - private boolean passwordEntered = true; - private byte[] currentPasswordHash = new byte[0]; - private Runnable shortPollRunnable; - - private int setPasswordRow; - private int setPasswordDetailRow; - private int changePasswordRow; - private int shadowRow; - private int turnPasswordOffRow; - private int setRecoveryEmailRow; - private int changeRecoveryEmailRow; - private int abortPasswordRow; - private int passwordSetupDetailRow; - private int passwordEnabledDetailRow; - private int passwordEmailVerifyDetailRow; - private int rowCount; - - private final static int done_button = 1; - - public TwoStepVerificationActivity(int type) { - super(); - this.type = type; - if (type == 0) { - loadPasswordInfo(false); - } - } - - @Override - public boolean onFragmentCreate() { - super.onFragmentCreate(); - updateRows(); - if (type == 0) { - NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetTwoStepPassword); - } - return true; - } - - @Override - public void onFragmentDestroy() { - super.onFragmentDestroy(); - if (type == 0) { - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didSetTwoStepPassword); - if (shortPollRunnable != null) { - AndroidUtilities.cancelRunOnUIThread(shortPollRunnable); - shortPollRunnable = null; - } - destroyed = true; - } - if (progressDialog != null) { - try { - progressDialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - progressDialog = null; - } - AndroidUtilities.removeAdjustResize(getParentActivity(), classGuid); - } - - @Override - public View createView(Context context) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(false); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - processDone(); - } - } - }); - - fragmentView = new FrameLayout(context); - FrameLayout frameLayout = (FrameLayout) fragmentView; - frameLayout.setBackgroundColor(0xfff0f0f0); - - ActionBarMenu menu = actionBar.createMenu(); - doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - scrollView = new ScrollView(context); - scrollView.setFillViewport(true); - frameLayout.addView(scrollView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) scrollView.getLayoutParams(); - layoutParams.width = LayoutHelper.MATCH_PARENT; - layoutParams.height = LayoutHelper.MATCH_PARENT; - scrollView.setLayoutParams(layoutParams); - - LinearLayout linearLayout = new LinearLayout(context); - linearLayout.setOrientation(LinearLayout.VERTICAL); - scrollView.addView(linearLayout); - ScrollView.LayoutParams layoutParams2 = (ScrollView.LayoutParams) linearLayout.getLayoutParams(); - layoutParams2.width = ScrollView.LayoutParams.MATCH_PARENT; - layoutParams2.height = ScrollView.LayoutParams.WRAP_CONTENT; - linearLayout.setLayoutParams(layoutParams2); - - titleTextView = new TextView(context); - titleTextView.setTextColor(0xff757575); - titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - titleTextView.setGravity(Gravity.CENTER_HORIZONTAL); - linearLayout.addView(titleTextView); - LinearLayout.LayoutParams layoutParams3 = (LinearLayout.LayoutParams) titleTextView.getLayoutParams(); - layoutParams3.width = LayoutHelper.WRAP_CONTENT; - layoutParams3.height = LayoutHelper.WRAP_CONTENT; - layoutParams3.gravity = Gravity.CENTER_HORIZONTAL; - layoutParams3.topMargin = AndroidUtilities.dp(38); - titleTextView.setLayoutParams(layoutParams3); - - passwordEditText = new EditText(context); - passwordEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - passwordEditText.setTextColor(0xff000000); - passwordEditText.setMaxLines(1); - passwordEditText.setLines(1); - passwordEditText.setGravity(Gravity.CENTER_HORIZONTAL); - passwordEditText.setSingleLine(true); - passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); - passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); - passwordEditText.setTypeface(Typeface.DEFAULT); - AndroidUtilities.clearCursorDrawable(passwordEditText); - linearLayout.addView(passwordEditText); - layoutParams3 = (LinearLayout.LayoutParams) passwordEditText.getLayoutParams(); - layoutParams3.topMargin = AndroidUtilities.dp(32); - layoutParams3.height = AndroidUtilities.dp(36); - layoutParams3.leftMargin = AndroidUtilities.dp(40); - layoutParams3.rightMargin = AndroidUtilities.dp(40); - layoutParams3.gravity = Gravity.TOP | Gravity.LEFT; - layoutParams3.width = LayoutHelper.MATCH_PARENT; - passwordEditText.setLayoutParams(layoutParams3); - passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_NEXT || i == EditorInfo.IME_ACTION_DONE) { - processDone(); - return true; - } - return false; - } - }); - passwordEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() { - public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - return false; - } - - public void onDestroyActionMode(ActionMode mode) { - } - - public boolean onCreateActionMode(ActionMode mode, Menu menu) { - return false; - } - - public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - return false; - } - }); - - bottomTextView = new TextView(context); - bottomTextView.setTextColor(0xff757575); - bottomTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - bottomTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); - bottomTextView.setText(LocaleController.getString("YourEmailInfo", R.string.YourEmailInfo)); - linearLayout.addView(bottomTextView); - layoutParams3 = (LinearLayout.LayoutParams) bottomTextView.getLayoutParams(); - layoutParams3.width = LayoutHelper.WRAP_CONTENT; - layoutParams3.height = LayoutHelper.WRAP_CONTENT; - layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; - layoutParams3.topMargin = AndroidUtilities.dp(30); - layoutParams3.leftMargin = AndroidUtilities.dp(40); - layoutParams3.rightMargin = AndroidUtilities.dp(40); - bottomTextView.setLayoutParams(layoutParams3); - - LinearLayout linearLayout2 = new LinearLayout(context); - linearLayout2.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL); - linearLayout.addView(linearLayout2); - layoutParams3 = (LinearLayout.LayoutParams) linearLayout2.getLayoutParams(); - layoutParams3.width = LayoutHelper.MATCH_PARENT; - layoutParams3.height = LayoutHelper.MATCH_PARENT; - linearLayout2.setLayoutParams(layoutParams3); - - bottomButton = new TextView(context); - bottomButton.setTextColor(0xff4d83b3); - bottomButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - bottomButton.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM); - bottomButton.setText(LocaleController.getString("YourEmailSkip", R.string.YourEmailSkip)); - bottomButton.setPadding(0, AndroidUtilities.dp(10), 0, 0); - linearLayout2.addView(bottomButton); - layoutParams3 = (LinearLayout.LayoutParams) bottomButton.getLayoutParams(); - layoutParams3.width = LayoutHelper.WRAP_CONTENT; - layoutParams3.height = LayoutHelper.WRAP_CONTENT; - layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; - layoutParams3.bottomMargin = AndroidUtilities.dp(14); - layoutParams3.leftMargin = AndroidUtilities.dp(40); - layoutParams3.rightMargin = AndroidUtilities.dp(40); - bottomButton.setLayoutParams(layoutParams3); - bottomButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (type == 0) { - if (currentPassword.has_recovery) { - needShowProgress(); - TLRPC.TL_auth_requestPasswordRecovery req = new TLRPC.TL_auth_requestPasswordRecovery(); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - needHideProgress(); - if (error == null) { - final TLRPC.TL_auth_passwordRecovery res = (TLRPC.TL_auth_passwordRecovery) response; - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.formatString("RestoreEmailSent", R.string.RestoreEmailSent, res.email_pattern)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(1); - fragment.currentPassword = currentPassword; - fragment.currentPassword.email_unconfirmed_pattern = res.email_pattern; - fragment.passwordSetState = 4; - presentFragment(fragment); - } - }); - Dialog dialog = showDialog(builder.create()); - if (dialog != null) { - dialog.setCanceledOnTouchOutside(false); - dialog.setCancelable(false); - } - } else { - if (error.text.startsWith("FLOOD_WAIT")) { - int time = Utilities.parseInt(error.text); - String timeString; - if (time < 60) { - timeString = LocaleController.formatPluralString("Seconds", time); - } else { - timeString = LocaleController.formatPluralString("Minutes", time / 60); - } - showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); - } else { - showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); - } - } - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); - } else { - showAlertWithText(LocaleController.getString("RestorePasswordNoEmailTitle", R.string.RestorePasswordNoEmailTitle), LocaleController.getString("RestorePasswordNoEmailText", R.string.RestorePasswordNoEmailText)); - } - } else { - if (passwordSetState == 4) { - showAlertWithText(LocaleController.getString("RestorePasswordNoEmailTitle", R.string.RestorePasswordNoEmailTitle), LocaleController.getString("RestoreEmailTroubleText", R.string.RestoreEmailTroubleText)); - } else { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("YourEmailSkipWarningText", R.string.YourEmailSkipWarningText)); - builder.setTitle(LocaleController.getString("YourEmailSkipWarning", R.string.YourEmailSkipWarning)); - builder.setPositiveButton(LocaleController.getString("YourEmailSkip", R.string.YourEmailSkip), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - email = ""; - setNewPassword(false); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showDialog(builder.create()); - } - } - } - }); - - if (type == 0) { - progressView = new FrameLayout(context); - frameLayout.addView(progressView); - layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = LayoutHelper.MATCH_PARENT; - layoutParams.height = LayoutHelper.MATCH_PARENT; - progressView.setLayoutParams(layoutParams); - progressView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - ProgressBar progressBar = new ProgressBar(context); - progressView.addView(progressBar); - layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = LayoutHelper.WRAP_CONTENT; - layoutParams.height = LayoutHelper.WRAP_CONTENT; - layoutParams.gravity = Gravity.CENTER; - progressView.setLayoutParams(layoutParams); - - listView = new ListView(context); - listView.setDivider(null); - listView.setEmptyView(progressView); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - listView.setDrawSelectorOnTop(true); - frameLayout.addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = LayoutHelper.MATCH_PARENT; - layoutParams.height = LayoutHelper.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - listView.setLayoutParams(layoutParams); - listView.setAdapter(listAdapter = new ListAdapter(context)); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (i == setPasswordRow || i == changePasswordRow) { - TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(1); - fragment.currentPasswordHash = currentPasswordHash; - fragment.currentPassword = currentPassword; - presentFragment(fragment); - } else if (i == setRecoveryEmailRow || i == changeRecoveryEmailRow) { - TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(1); - fragment.currentPasswordHash = currentPasswordHash; - fragment.currentPassword = currentPassword; - fragment.emailOnly = true; - fragment.passwordSetState = 3; - presentFragment(fragment); - } else if (i == turnPasswordOffRow || i == abortPasswordRow) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("TurnPasswordOffQuestion", R.string.TurnPasswordOffQuestion)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - setNewPassword(true); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showDialog(builder.create()); - } - } - }); - - updateRows(); - - actionBar.setTitle(LocaleController.getString("TwoStepVerification", R.string.TwoStepVerification)); - titleTextView.setText(LocaleController.getString("PleaseEnterCurrentPassword", R.string.PleaseEnterCurrentPassword)); - } else if (type == 1) { - setPasswordSetState(passwordSetState); - } - - return fragmentView; - } - - @Override - public void didReceivedNotification(int id, Object... args) { - if (id == NotificationCenter.didSetTwoStepPassword) { - if (args != null && args.length > 0 && args[0] != null) { - currentPasswordHash = (byte[]) args[0]; - } - loadPasswordInfo(false); - updateRows(); - } - } - - @Override - public void onResume() { - super.onResume(); - if (type == 1) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (passwordEditText != null) { - passwordEditText.requestFocus(); - AndroidUtilities.showKeyboard(passwordEditText); - } - } - }, 200); - } - AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid); - } - - @Override - public void onTransitionAnimationEnd(boolean isOpen, boolean backward) { - if (isOpen && type == 1) { - AndroidUtilities.showKeyboard(passwordEditText); - } - } - - private void loadPasswordInfo(final boolean silent) { - if (!silent) { - loading = true; - } - TLRPC.TL_account_getPassword req = new TLRPC.TL_account_getPassword(); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - loading = false; - if (error == null) { - if (!silent) { - passwordEntered = currentPassword != null || response instanceof TLRPC.TL_account_noPassword; - } - currentPassword = (TLRPC.account_Password) response; - waitingForEmail = currentPassword.email_unconfirmed_pattern.length() > 0; - byte[] salt = new byte[currentPassword.new_salt.length + 8]; - Utilities.random.nextBytes(salt); - System.arraycopy(currentPassword.new_salt, 0, salt, 0, currentPassword.new_salt.length); - currentPassword.new_salt = salt; - } - if (type == 0 && !destroyed && shortPollRunnable == null) { - shortPollRunnable = new Runnable() { - @Override - public void run() { - if (shortPollRunnable == null) { - return; - } - loadPasswordInfo(true); - shortPollRunnable = null; - } - }; - AndroidUtilities.runOnUIThread(shortPollRunnable, 5000); - } - updateRows(); - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); - } - - private void setPasswordSetState(int state) { - if (passwordEditText == null) { - return; - } - passwordSetState = state; - if (passwordSetState == 0) { - actionBar.setTitle(LocaleController.getString("YourPassword", R.string.YourPassword)); - if (currentPassword instanceof TLRPC.TL_account_noPassword) { - titleTextView.setText(LocaleController.getString("PleaseEnterFirstPassword", R.string.PleaseEnterFirstPassword)); - } else { - titleTextView.setText(LocaleController.getString("PleaseEnterPassword", R.string.PleaseEnterPassword)); - } - passwordEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT); - passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); - bottomTextView.setVisibility(View.INVISIBLE); - bottomButton.setVisibility(View.INVISIBLE); - } else if (passwordSetState == 1) { - actionBar.setTitle(LocaleController.getString("YourPassword", R.string.YourPassword)); - titleTextView.setText(LocaleController.getString("PleaseReEnterPassword", R.string.PleaseReEnterPassword)); - passwordEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT); - passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); - bottomTextView.setVisibility(View.INVISIBLE); - bottomButton.setVisibility(View.INVISIBLE); - } else if (passwordSetState == 2) { - actionBar.setTitle(LocaleController.getString("PasswordHint", R.string.PasswordHint)); - titleTextView.setText(LocaleController.getString("PasswordHintText", R.string.PasswordHintText)); - passwordEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT); - passwordEditText.setTransformationMethod(null); - bottomTextView.setVisibility(View.INVISIBLE); - bottomButton.setVisibility(View.INVISIBLE); - } else if (passwordSetState == 3) { - actionBar.setTitle(LocaleController.getString("RecoveryEmail", R.string.RecoveryEmail)); - titleTextView.setText(LocaleController.getString("YourEmail", R.string.YourEmail)); - passwordEditText.setImeOptions(EditorInfo.IME_ACTION_DONE); - passwordEditText.setTransformationMethod(null); - passwordEditText.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); - bottomTextView.setVisibility(View.VISIBLE); - bottomButton.setVisibility(emailOnly ? View.INVISIBLE : View.VISIBLE); - } else if (passwordSetState == 4) { - actionBar.setTitle(LocaleController.getString("PasswordRecovery", R.string.PasswordRecovery)); - titleTextView.setText(LocaleController.getString("PasswordCode", R.string.PasswordCode)); - bottomTextView.setText(LocaleController.getString("RestoreEmailSentInfo", R.string.RestoreEmailSentInfo)); - bottomButton.setText(LocaleController.formatString("RestoreEmailTrouble", R.string.RestoreEmailTrouble, currentPassword.email_unconfirmed_pattern)); - passwordEditText.setImeOptions(EditorInfo.IME_ACTION_DONE); - passwordEditText.setTransformationMethod(null); - passwordEditText.setInputType(InputType.TYPE_CLASS_PHONE); - bottomTextView.setVisibility(View.VISIBLE); - bottomButton.setVisibility(View.VISIBLE); - } - passwordEditText.setText(""); - } - - private void updateRows() { - rowCount = 0; - setPasswordRow = -1; - setPasswordDetailRow = -1; - changePasswordRow = -1; - turnPasswordOffRow = -1; - setRecoveryEmailRow = -1; - changeRecoveryEmailRow = -1; - abortPasswordRow = -1; - passwordSetupDetailRow = -1; - passwordEnabledDetailRow = -1; - passwordEmailVerifyDetailRow = -1; - shadowRow = -1; - if (!loading && currentPassword != null) { - if (currentPassword instanceof TLRPC.TL_account_noPassword) { - if (waitingForEmail) { - passwordSetupDetailRow = rowCount++; - abortPasswordRow = rowCount++; - shadowRow = rowCount++; - } else { - setPasswordRow = rowCount++; - setPasswordDetailRow = rowCount++; - } - } else if (currentPassword instanceof TLRPC.TL_account_password) { - changePasswordRow = rowCount++; - turnPasswordOffRow = rowCount++; - if (currentPassword.has_recovery) { - changeRecoveryEmailRow = rowCount++; - } else { - setRecoveryEmailRow = rowCount++; - } - if (waitingForEmail) { - passwordEmailVerifyDetailRow = rowCount++; - } else { - passwordEnabledDetailRow = rowCount++; - } - } - } - - if (listAdapter != null) { - listAdapter.notifyDataSetChanged(); - } - if (passwordEntered) { - if (listView != null) { - listView.setVisibility(View.VISIBLE); - scrollView.setVisibility(View.INVISIBLE); - progressView.setVisibility(View.VISIBLE); - listView.setEmptyView(progressView); - } - if (passwordEditText != null) { - doneItem.setVisibility(View.GONE); - passwordEditText.setVisibility(View.INVISIBLE); - titleTextView.setVisibility(View.INVISIBLE); - bottomTextView.setVisibility(View.INVISIBLE); - bottomButton.setVisibility(View.INVISIBLE); - } - } else { - if (listView != null) { - listView.setEmptyView(null); - listView.setVisibility(View.INVISIBLE); - scrollView.setVisibility(View.VISIBLE); - progressView.setVisibility(View.INVISIBLE); - } - if (passwordEditText != null) { - doneItem.setVisibility(View.VISIBLE); - passwordEditText.setVisibility(View.VISIBLE); - titleTextView.setVisibility(View.VISIBLE); - bottomButton.setVisibility(View.VISIBLE); - bottomTextView.setVisibility(View.INVISIBLE); - bottomButton.setText(LocaleController.getString("ForgotPassword", R.string.ForgotPassword)); - if (currentPassword.hint != null && currentPassword.hint.length() > 0) { - passwordEditText.setHint(currentPassword.hint); - } else { - passwordEditText.setHint(""); - } - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (passwordEditText != null) { - passwordEditText.requestFocus(); - AndroidUtilities.showKeyboard(passwordEditText); - } - } - }, 200); - } - } - } - - private void needShowProgress() { - if (getParentActivity() == null || getParentActivity().isFinishing() || progressDialog != null) { - return; - } - progressDialog = new ProgressDialog(getParentActivity()); - progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); - progressDialog.setCanceledOnTouchOutside(false); - progressDialog.setCancelable(false); - progressDialog.show(); - } - - private void needHideProgress() { - if (progressDialog == null) { - return; - } - try { - progressDialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - progressDialog = null; - } - - private boolean isValidEmail(String text) { - if (text == null || text.length() < 3) { - return false; - } - int dot = text.lastIndexOf('.'); - int dog = text.lastIndexOf('@'); - return !(dot < 0 || dog < 0 || dot < dog); - } - - private void showAlertWithText(String title, String text) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); - builder.setTitle(title); - builder.setMessage(text); - showDialog(builder.create()); - } - - private void setNewPassword(final boolean clear) { - final TLRPC.TL_account_updatePasswordSettings req = new TLRPC.TL_account_updatePasswordSettings(); - req.current_password_hash = currentPasswordHash; - req.new_settings = new TLRPC.TL_account_passwordInputSettings(); - if (clear) { - if (waitingForEmail && currentPassword instanceof TLRPC.TL_account_noPassword) { - req.new_settings.flags = 2; - req.new_settings.email = ""; - req.current_password_hash = new byte[0]; - } else { - req.new_settings.flags = 3; - req.new_settings.hint = ""; - req.new_settings.new_password_hash = new byte[0]; - req.new_settings.new_salt = new byte[0]; - req.new_settings.email = ""; - } - } else { - if (firstPassword != null && firstPassword.length() > 0) { - byte[] newPasswordBytes = null; - try { - newPasswordBytes = firstPassword.getBytes("UTF-8"); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - byte[] new_salt = currentPassword.new_salt; - byte[] hash = new byte[new_salt.length * 2 + newPasswordBytes.length]; - System.arraycopy(new_salt, 0, hash, 0, new_salt.length); - System.arraycopy(newPasswordBytes, 0, hash, new_salt.length, newPasswordBytes.length); - System.arraycopy(new_salt, 0, hash, hash.length - new_salt.length, new_salt.length); - req.new_settings.flags |= 1; - req.new_settings.hint = hint; - req.new_settings.new_password_hash = Utilities.computeSHA256(hash, 0, hash.length); - req.new_settings.new_salt = new_salt; - } - if (email.length() > 0) { - req.new_settings.flags |= 2; - req.new_settings.email = email; - } - } - needShowProgress(); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - needHideProgress(); - if (error == null && response instanceof TLRPC.TL_boolTrue) { - if (clear) { - currentPassword = null; - currentPasswordHash = new byte[0]; - loadPasswordInfo(false); - updateRows(); - } else { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.didSetTwoStepPassword, (Object) req.new_settings.new_password_hash); - finishFragment(); - } - }); - builder.setMessage(LocaleController.getString("YourPasswordSuccessText", R.string.YourPasswordSuccessText)); - builder.setTitle(LocaleController.getString("YourPasswordSuccess", R.string.YourPasswordSuccess)); - Dialog dialog = showDialog(builder.create()); - if (dialog != null) { - dialog.setCanceledOnTouchOutside(false); - dialog.setCancelable(false); - } - } - } else if (error != null) { - if (error.text.equals("EMAIL_UNCONFIRMED")) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.didSetTwoStepPassword, (Object) req.new_settings.new_password_hash); - finishFragment(); - } - }); - builder.setMessage(LocaleController.getString("YourEmailAlmostThereText", R.string.YourEmailAlmostThereText)); - builder.setTitle(LocaleController.getString("YourEmailAlmostThere", R.string.YourEmailAlmostThere)); - Dialog dialog = showDialog(builder.create()); - if (dialog != null) { - dialog.setCanceledOnTouchOutside(false); - dialog.setCancelable(false); - } - } else { - if (error.text.equals("EMAIL_INVALID")) { - showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("PasswordEmailInvalid", R.string.PasswordEmailInvalid)); - } else if (error.text.startsWith("FLOOD_WAIT")) { - int time = Utilities.parseInt(error.text); - String timeString; - if (time < 60) { - timeString = LocaleController.formatPluralString("Seconds", time); - } else { - timeString = LocaleController.formatPluralString("Minutes", time / 60); - } - showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); - } else { - showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); - } - } - } - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); - } - - private void processDone() { - if (type == 0) { - if (!passwordEntered) { - String oldPassword = passwordEditText.getText().toString(); - if (oldPassword.length() == 0) { - onPasscodeError(false); - return; - } - byte[] oldPasswordBytes = null; - try { - oldPasswordBytes = oldPassword.getBytes("UTF-8"); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - needShowProgress(); - byte[] hash = new byte[currentPassword.current_salt.length * 2 + oldPasswordBytes.length]; - System.arraycopy(currentPassword.current_salt, 0, hash, 0, currentPassword.current_salt.length); - System.arraycopy(oldPasswordBytes, 0, hash, currentPassword.current_salt.length, oldPasswordBytes.length); - System.arraycopy(currentPassword.current_salt, 0, hash, hash.length - currentPassword.current_salt.length, currentPassword.current_salt.length); - - final TLRPC.TL_account_getPasswordSettings req = new TLRPC.TL_account_getPasswordSettings(); - req.current_password_hash = Utilities.computeSHA256(hash, 0, hash.length); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - needHideProgress(); - if (error == null) { - currentPasswordHash = req.current_password_hash; - passwordEntered = true; - AndroidUtilities.hideKeyboard(passwordEditText); - updateRows(); - } else { - if (error.text.equals("PASSWORD_HASH_INVALID")) { - onPasscodeError(true); - } else if (error.text.startsWith("FLOOD_WAIT")) { - int time = Utilities.parseInt(error.text); - String timeString; - if (time < 60) { - timeString = LocaleController.formatPluralString("Seconds", time); - } else { - timeString = LocaleController.formatPluralString("Minutes", time / 60); - } - showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); - } else { - showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); - } - } - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); - } - } else if (type == 1) { - if (passwordSetState == 0) { - if (passwordEditText.getText().length() == 0) { - onPasscodeError(false); - return; - } - titleTextView.setText(LocaleController.getString("ReEnterYourPasscode", R.string.ReEnterYourPasscode)); - firstPassword = passwordEditText.getText().toString(); - setPasswordSetState(1); - } else if (passwordSetState == 1) { - if (!firstPassword.equals(passwordEditText.getText().toString())) { - try { - Toast.makeText(getParentActivity(), LocaleController.getString("PasswordDoNotMatch", R.string.PasswordDoNotMatch), Toast.LENGTH_SHORT).show(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - onPasscodeError(true); - return; - } - setPasswordSetState(2); - } else if (passwordSetState == 2) { - hint = passwordEditText.getText().toString(); - if (hint.toLowerCase().equals(firstPassword.toLowerCase())) { - try { - Toast.makeText(getParentActivity(), LocaleController.getString("PasswordAsHintError", R.string.PasswordAsHintError), Toast.LENGTH_SHORT).show(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - onPasscodeError(false); - return; - } - if (!currentPassword.has_recovery) { - setPasswordSetState(3); - } else { - email = ""; - setNewPassword(false); - } - } else if (passwordSetState == 3) { - email = passwordEditText.getText().toString(); - if (!isValidEmail(email)) { - onPasscodeError(false); - return; - } - setNewPassword(false); - } else if (passwordSetState == 4) { - String code = passwordEditText.getText().toString(); - if (code.length() == 0) { - onPasscodeError(false); - return; - } - TLRPC.TL_auth_recoverPassword req = new TLRPC.TL_auth_recoverPassword(); - req.code = code; - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (error == null) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.didSetTwoStepPassword); - finishFragment(); - } - }); - builder.setMessage(LocaleController.getString("PasswordReset", R.string.PasswordReset)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - Dialog dialog = showDialog(builder.create()); - if (dialog != null) { - dialog.setCanceledOnTouchOutside(false); - dialog.setCancelable(false); - } - } else { - if (error.text.startsWith("CODE_INVALID")) { - onPasscodeError(true); - } else if (error.text.startsWith("FLOOD_WAIT")) { - int time = Utilities.parseInt(error.text); - String timeString; - if (time < 60) { - timeString = LocaleController.formatPluralString("Seconds", time); - } else { - timeString = LocaleController.formatPluralString("Minutes", time / 60); - } - showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); - } else { - showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); - } - } - } - }); - } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); - } - } - } - - private void onPasscodeError(boolean clear) { - if (getParentActivity() == null) { - return; - } - Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); - if (v != null) { - v.vibrate(200); - } - if (clear) { - passwordEditText.setText(""); - } - AndroidUtilities.shakeView(titleTextView, 2, 0); - } - - private class ListAdapter extends BaseFragmentAdapter { - private Context mContext; - - public ListAdapter(Context context) { - mContext = context; - } - - @Override - public boolean areAllItemsEnabled() { - return false; - } - - @Override - public boolean isEnabled(int i) { - return i != setPasswordDetailRow && i != shadowRow && i != passwordSetupDetailRow && i != passwordEmailVerifyDetailRow && i != passwordEnabledDetailRow; - } - - @Override - public int getCount() { - return loading || currentPassword == null ? 0 : rowCount; - } - - @Override - public Object getItem(int i) { - return null; - } - - @Override - public long getItemId(int i) { - return i; - } - - @Override - public boolean hasStableIds() { - return false; - } - - @Override - public View getView(int i, View view, ViewGroup viewGroup) { - int viewType = getItemViewType(i); - if (viewType == 0) { - if (view == null) { - view = new TextSettingsCell(mContext); - view.setBackgroundColor(0xffffffff); - } - TextSettingsCell textCell = (TextSettingsCell) view; - textCell.setTextColor(0xff212121); - if (i == changePasswordRow) { - textCell.setText(LocaleController.getString("ChangePassword", R.string.ChangePassword), true); - } else if (i == setPasswordRow) { - textCell.setText(LocaleController.getString("SetAdditionalPassword", R.string.SetAdditionalPassword), true); - } else if (i == turnPasswordOffRow) { - textCell.setText(LocaleController.getString("TurnPasswordOff", R.string.TurnPasswordOff), true); - } else if (i == changeRecoveryEmailRow) { - textCell.setText(LocaleController.getString("ChangeRecoveryEmail", R.string.ChangeRecoveryEmail), abortPasswordRow != -1); - } else if (i == setRecoveryEmailRow) { - textCell.setText(LocaleController.getString("SetRecoveryEmail", R.string.SetRecoveryEmail), false); - } else if (i == abortPasswordRow) { - textCell.setTextColor(0xffd24949); - textCell.setText(LocaleController.getString("AbortPassword", R.string.AbortPassword), false); - } - } else if (viewType == 1) { - if (view == null) { - view = new TextInfoPrivacyCell(mContext); - } - if (i == setPasswordDetailRow) { - ((TextInfoPrivacyCell) view).setText(LocaleController.getString("SetAdditionalPasswordInfo", R.string.SetAdditionalPasswordInfo)); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } else if (i == shadowRow) { - ((TextInfoPrivacyCell) view).setText(""); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } else if (i == passwordSetupDetailRow) { - ((TextInfoPrivacyCell) view).setText(LocaleController.formatString("EmailPasswordConfirmText", R.string.EmailPasswordConfirmText, currentPassword.email_unconfirmed_pattern)); - view.setBackgroundResource(R.drawable.greydivider_top); - } else if (i == passwordEnabledDetailRow) { - ((TextInfoPrivacyCell) view).setText(LocaleController.getString("EnabledPasswordText", R.string.EnabledPasswordText)); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } else if (i == passwordEmailVerifyDetailRow) { - ((TextInfoPrivacyCell) view).setText(LocaleController.formatString("PendingEmailText", R.string.PendingEmailText, currentPassword.email_unconfirmed_pattern)); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } - } - return view; - } - - @Override - public int getItemViewType(int i) { - if (i == setPasswordDetailRow || i == shadowRow || i == passwordSetupDetailRow || i == passwordEnabledDetailRow || i == passwordEmailVerifyDetailRow) { - return 1; - } - return 0; - } - - @Override - public int getViewTypeCount() { - return 2; - } - - @Override - public boolean isEmpty() { - return loading || currentPassword == null; - } - } -}