Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ActivityVerifyPhone: ActivityBase()
- {
- private var name = ""
- private var phone = ""
- private var password = ""
- private var isVerified: Boolean = false
- private val STATE_INITIALIZED = 1
- private val STATE_CODE_SENT = 2
- private val STATE_VERIFY_FAILED = 3
- private val STATE_VERIFY_SUCCESS = 4
- private var mVerificationInProgress = false
- private var mVerificationId: String = ""
- private var mResendToken: PhoneAuthProvider.ForceResendingToken? = null
- private var mAuth: FirebaseAuth? = null
- private var mPhoneAuthProvider: PhoneAuthProvider? = null
- private var countDownTimer: CountDownTimer? = null
- override fun onCreate(savedInstanceState: Bundle?)
- {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_verify_phone)
- FirebaseApp.initializeApp(applicationContext)
- mAuth = FirebaseAuth.getInstance()
- //mAuth?.signOut()
- //Log.v(AppConstants.DEBUG_TAG, "AUTH USER : ${(mAuth?.currentUser == null)}")
- mPhoneAuthProvider = PhoneAuthProvider.getInstance()
- initData()
- initUi()
- startPhoneNumberVerification(phone)
- }
- override fun initData()
- {
- super.initData()
- name = intent.getStringExtra("NAME")
- phone = intent.getStringExtra("PHONE")
- password = intent.getStringExtra("PASSWORD")
- }
- private fun initUi()
- {
- tvRequestAgain.visibility = View.INVISIBLE
- tvNumber.text = phone
- tvCancel.setOnClickListener{
- onBackPressed()
- }
- tvRequestAgain.setOnClickListener{
- startPhoneNumberVerification(phone)
- }
- btnVerify.setOnClickListener{
- hideSoftKeyboard()
- if(validated())
- {
- if(mVerificationId != "")
- {
- btnVerify.startAnimation()
- verifyPhoneNumberWithCode(mVerificationId, etCode.text.toString())
- }
- }
- }
- }
- private fun startPhoneNumberVerification(phoneNumber: String)
- {
- mPhoneAuthProvider?.verifyPhoneNumber(
- phoneNumber, // Phone number to verify
- 60, // Timeout duration
- TimeUnit.SECONDS, // Unit of timeout
- this@ActivityVerifyPhone, // Activity (for callback binding)
- mCallbacks) // OnVerificationStateChangedCallbacks
- // [END start_phone_auth]
- mVerificationInProgress = true
- }
- private var mCallbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks()
- {
- override fun onVerificationCompleted(credential: PhoneAuthCredential)
- {
- Log.v(AppConstants.DEBUG_TAG, "onVerificationCompleted:$credential")
- //hideLoading()
- mVerificationInProgress = false
- updateUI(STATE_VERIFY_SUCCESS, credential)
- signInWithPhoneAuthCredential(credential)
- }
- override fun onVerificationFailed(e: FirebaseException)
- {
- Log.v(AppConstants.DEBUG_TAG, "onVerificationFailed", e)
- //hideLoading()
- mVerificationInProgress = false
- if (e is FirebaseAuthInvalidCredentialsException)
- {
- showSnackBar(findViewById(R.id.rlMain), getString(R.string.txt_invalid_phone))
- }
- else if (e is FirebaseTooManyRequestsException)
- {
- //showSnackBar(rlMain, "Quota exceeded.")
- }
- //updateUI(STATE_VERIFY_FAILED)
- }
- override fun onCodeSent(verificationId: String?, token: PhoneAuthProvider.ForceResendingToken?)
- {
- Log.d(AppConstants.DEBUG_TAG, "onCodeSent:" + verificationId!!)
- //hideLoading()
- // Save verification ID and resending token so we can use them later
- mVerificationId = verificationId
- mResendToken = token
- countDownTimer = timer(3*60*1000,1000).start()
- Toast.makeText(this@ActivityVerifyPhone, getString(R.string.txt_verification_code_sent), Toast.LENGTH_LONG).show()
- //updateUI(STATE_CODE_SENT)
- }
- override fun onCodeAutoRetrievalTimeOut(s: String?) {
- super.onCodeAutoRetrievalTimeOut(s)
- }
- }
- // Method to configure and return an instance of CountDownTimer object
- private fun timer(millisInFuture:Long,countDownInterval:Long): CountDownTimer {
- return object: CountDownTimer(millisInFuture,countDownInterval){
- override fun onTick(millisUntilFinished: Long)
- {
- val timeRemaining = "<b>"+timeString(millisUntilFinished)+"</b> "
- tvMsg.text = Html.fromHtml(String.format(getString(R.string.txt_complete_signup), timeRemaining))
- }
- override fun onFinish()
- {
- //tvTime.text = "00:00"
- tvRequestAgain.visibility = View.VISIBLE
- }
- }
- }
- // Method to get days hours minutes seconds from milliseconds
- private fun timeString(millisUntilFinished:Long):String{
- var millisUntilFinished:Long = millisUntilFinished
- val days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished)
- millisUntilFinished -= TimeUnit.DAYS.toMillis(days)
- val hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished)
- millisUntilFinished -= TimeUnit.HOURS.toMillis(hours)
- val minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)
- millisUntilFinished -= TimeUnit.MINUTES.toMillis(minutes)
- val seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)
- // Format the string
- /*return String.format(
- Locale.getDefault(), "%02d day: %02d hour: %02d min: %02d sec",
- days,hours, minutes,seconds
- )*/
- return String.format(
- Locale.getDefault(), "%02d:%02d",
- minutes,seconds)
- }
- private fun validated():Boolean
- {
- if (!Validator.validateNameNotNull(etCode.text.toString()))
- {
- showSnackBar(rlMain, getString(R.string.txt_err_verify_code))
- return false
- }
- return true
- }
- private fun updateUI(uiState: Int, cred: PhoneAuthCredential?)
- {
- when(uiState)
- {
- STATE_INITIALIZED -> {
- }
- STATE_CODE_SENT -> {
- }
- STATE_VERIFY_FAILED -> {
- }
- STATE_VERIFY_SUCCESS -> {
- if (cred != null)
- {
- if(AppConstants.DEBUG) Log.v(AppConstants.DEBUG_TAG, "CODE OTP : CRED")
- if (cred.smsCode != null)
- {
- if(AppConstants.DEBUG) Log.v(AppConstants.DEBUG_TAG, "CODE OTP : OTP")
- etCode.setText(cred.smsCode)
- }
- else
- {
- //mVerificationField.setText(R.string.instant_validation)
- }
- }
- }
- }
- }
- private fun verifyPhoneNumberWithCode(verificationId: String, code: String)
- {
- val credential = PhoneAuthProvider.getCredential(verificationId, code)
- signInWithPhoneAuthCredential(credential)
- }
- private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential)
- {
- if(!btnVerify.isAnimating)
- btnVerify.startAnimation()
- mAuth = FirebaseAuth.getInstance()
- mAuth?.signInWithCredential(credential)?.addOnCompleteListener(this, OnCompleteListener<AuthResult>
- { task ->
- btnVerify.revertAnimation()
- btnVerify.background = ContextCompat.getDrawable(applicationContext, R.drawable.bg_selector_blue_yellow_border_rounded_25)
- if (task.isSuccessful)
- {
- Log.v(AppConstants.DEBUG_TAG, "signInWithCredential:success")
- Toast.makeText(this@ActivityVerifyPhone, getString(R.string.txt_successfully_verified_phone), Toast.LENGTH_LONG).show()
- isVerified = true
- //mAuth?.signOut()
- val user = mAuth?.currentUser
- user?.delete()?.addOnCompleteListener {
- task ->
- if (task.isSuccessful)
- {
- Log.v(AppConstants.DEBUG_TAG, "AUTH USER : User account deleted.")
- }
- userSignUp()
- }
- }
- else
- {
- btnVerify.revertAnimation()
- Toast.makeText(this@ActivityVerifyPhone, getString(R.string.txt_failed_verify_phone), Toast.LENGTH_LONG).show()
- Log.v(AppConstants.DEBUG_TAG, "signInWithCredential:failure", task.exception)
- if (task.exception is FirebaseAuthInvalidCredentialsException)
- {
- }
- }
- })
- }
- private fun userSignUp()
- {
- var apiServices = APIClient.client.create(ApiInterface::class.java)
- val rnd = Random()
- val randomNum = 100000 + rnd.nextInt(900000)
- var verifyId = ""
- if(etCode.text.toString() == "")
- verifyId = randomNum.toString()
- else
- verifyId = etCode.text.toString()
- val call = apiServices.signupUser(libFile?.getDeviceToken()!!, libFile?.getDeviceId()!!,
- name, phone, password, verifyId, libFile?.getAuthorizationToken()!!)
- call.observeOn(AndroidSchedulers.mainThread())
- .subscribeOn(Schedulers.io())
- .subscribe ({
- result ->
- if(AppConstants.DEBUG) Log.v(AppConstants.DEBUG_TAG, "SIGNUP RESPONSE : "+result.toString())
- btnVerify.revertAnimation()
- if(result.get("status").asString.equals("success", ignoreCase = false))
- {
- val userData = Gson().fromJson(result.get("data").asJsonObject.get("userInfo").asJsonObject.toString(), object : TypeToken<UserData>() {}.type) as UserData
- libFile?.setUserAuthToken(result.get("data").asJsonObject.get("auth_token").asString)
- libFile?.setPhoneNumber(userData.phone)
- libFile?.setPassword(password)
- libFile?.setCurrentUser(userData, this@ActivityVerifyPhone)
- goToRegisterSuccessScreen(phone)
- }
- else
- {
- showOkAlertMessage(getString(R.string.txt_failed), result.get("message").asString, false)
- }
- }, { error ->
- btnVerify.revertAnimation()
- showOkAlertMessage(getString(R.string.txt_failed), getString(R.string.txt_something_wrong), false)
- error.printStackTrace()
- if(AppConstants.DEBUG) Log.v(AppConstants.DEBUG_TAG, "SIGNUP RESPONSE FAILED : "+error.localizedMessage)
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement