Advertisement
Guest User

Untitled

a guest
Dec 27th, 2018
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.27 KB | None | 0 0
  1.  
  2. class ActivityVerifyPhone: ActivityBase()
  3. {
  4. private var name = ""
  5. private var phone = ""
  6. private var password = ""
  7.  
  8. private var isVerified: Boolean = false
  9.  
  10. private val STATE_INITIALIZED = 1
  11. private val STATE_CODE_SENT = 2
  12. private val STATE_VERIFY_FAILED = 3
  13. private val STATE_VERIFY_SUCCESS = 4
  14.  
  15. private var mVerificationInProgress = false
  16. private var mVerificationId: String = ""
  17. private var mResendToken: PhoneAuthProvider.ForceResendingToken? = null
  18. private var mAuth: FirebaseAuth? = null
  19.  
  20. private var mPhoneAuthProvider: PhoneAuthProvider? = null
  21.  
  22. private var countDownTimer: CountDownTimer? = null
  23.  
  24. override fun onCreate(savedInstanceState: Bundle?)
  25. {
  26. super.onCreate(savedInstanceState)
  27.  
  28. setContentView(R.layout.activity_verify_phone)
  29.  
  30. FirebaseApp.initializeApp(applicationContext)
  31. mAuth = FirebaseAuth.getInstance()
  32. //mAuth?.signOut()
  33.  
  34. //Log.v(AppConstants.DEBUG_TAG, "AUTH USER : ${(mAuth?.currentUser == null)}")
  35.  
  36. mPhoneAuthProvider = PhoneAuthProvider.getInstance()
  37.  
  38. initData()
  39.  
  40. initUi()
  41.  
  42. startPhoneNumberVerification(phone)
  43. }
  44.  
  45. override fun initData()
  46. {
  47. super.initData()
  48.  
  49. name = intent.getStringExtra("NAME")
  50.  
  51. phone = intent.getStringExtra("PHONE")
  52.  
  53. password = intent.getStringExtra("PASSWORD")
  54. }
  55.  
  56. private fun initUi()
  57. {
  58. tvRequestAgain.visibility = View.INVISIBLE
  59.  
  60. tvNumber.text = phone
  61.  
  62. tvCancel.setOnClickListener{
  63. onBackPressed()
  64. }
  65.  
  66. tvRequestAgain.setOnClickListener{
  67. startPhoneNumberVerification(phone)
  68. }
  69.  
  70. btnVerify.setOnClickListener{
  71. hideSoftKeyboard()
  72.  
  73. if(validated())
  74. {
  75. if(mVerificationId != "")
  76. {
  77. btnVerify.startAnimation()
  78.  
  79. verifyPhoneNumberWithCode(mVerificationId, etCode.text.toString())
  80. }
  81. }
  82. }
  83. }
  84.  
  85. private fun startPhoneNumberVerification(phoneNumber: String)
  86. {
  87. mPhoneAuthProvider?.verifyPhoneNumber(
  88. phoneNumber, // Phone number to verify
  89. 60, // Timeout duration
  90. TimeUnit.SECONDS, // Unit of timeout
  91. this@ActivityVerifyPhone, // Activity (for callback binding)
  92. mCallbacks) // OnVerificationStateChangedCallbacks
  93. // [END start_phone_auth]
  94.  
  95. mVerificationInProgress = true
  96. }
  97.  
  98. private var mCallbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks()
  99. {
  100. override fun onVerificationCompleted(credential: PhoneAuthCredential)
  101. {
  102. Log.v(AppConstants.DEBUG_TAG, "onVerificationCompleted:$credential")
  103.  
  104. //hideLoading()
  105.  
  106. mVerificationInProgress = false
  107.  
  108. updateUI(STATE_VERIFY_SUCCESS, credential)
  109.  
  110. signInWithPhoneAuthCredential(credential)
  111. }
  112.  
  113. override fun onVerificationFailed(e: FirebaseException)
  114. {
  115. Log.v(AppConstants.DEBUG_TAG, "onVerificationFailed", e)
  116.  
  117. //hideLoading()
  118.  
  119. mVerificationInProgress = false
  120.  
  121. if (e is FirebaseAuthInvalidCredentialsException)
  122. {
  123. showSnackBar(findViewById(R.id.rlMain), getString(R.string.txt_invalid_phone))
  124. }
  125. else if (e is FirebaseTooManyRequestsException)
  126. {
  127. //showSnackBar(rlMain, "Quota exceeded.")
  128. }
  129. //updateUI(STATE_VERIFY_FAILED)
  130.  
  131. }
  132.  
  133. override fun onCodeSent(verificationId: String?, token: PhoneAuthProvider.ForceResendingToken?)
  134. {
  135. Log.d(AppConstants.DEBUG_TAG, "onCodeSent:" + verificationId!!)
  136.  
  137. //hideLoading()
  138.  
  139. // Save verification ID and resending token so we can use them later
  140. mVerificationId = verificationId
  141. mResendToken = token
  142.  
  143. countDownTimer = timer(3*60*1000,1000).start()
  144.  
  145. Toast.makeText(this@ActivityVerifyPhone, getString(R.string.txt_verification_code_sent), Toast.LENGTH_LONG).show()
  146.  
  147. //updateUI(STATE_CODE_SENT)
  148. }
  149.  
  150. override fun onCodeAutoRetrievalTimeOut(s: String?) {
  151. super.onCodeAutoRetrievalTimeOut(s)
  152. }
  153. }
  154.  
  155. // Method to configure and return an instance of CountDownTimer object
  156. private fun timer(millisInFuture:Long,countDownInterval:Long): CountDownTimer {
  157. return object: CountDownTimer(millisInFuture,countDownInterval){
  158. override fun onTick(millisUntilFinished: Long)
  159. {
  160. val timeRemaining = "<b>"+timeString(millisUntilFinished)+"</b> "
  161. tvMsg.text = Html.fromHtml(String.format(getString(R.string.txt_complete_signup), timeRemaining))
  162. }
  163.  
  164. override fun onFinish()
  165. {
  166. //tvTime.text = "00:00"
  167. tvRequestAgain.visibility = View.VISIBLE
  168. }
  169. }
  170. }
  171.  
  172. // Method to get days hours minutes seconds from milliseconds
  173. private fun timeString(millisUntilFinished:Long):String{
  174. var millisUntilFinished:Long = millisUntilFinished
  175. val days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished)
  176. millisUntilFinished -= TimeUnit.DAYS.toMillis(days)
  177.  
  178. val hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished)
  179. millisUntilFinished -= TimeUnit.HOURS.toMillis(hours)
  180.  
  181. val minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)
  182. millisUntilFinished -= TimeUnit.MINUTES.toMillis(minutes)
  183.  
  184. val seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)
  185.  
  186. // Format the string
  187. /*return String.format(
  188. Locale.getDefault(), "%02d day: %02d hour: %02d min: %02d sec",
  189. days,hours, minutes,seconds
  190. )*/
  191.  
  192. return String.format(
  193. Locale.getDefault(), "%02d:%02d",
  194. minutes,seconds)
  195. }
  196.  
  197. private fun validated():Boolean
  198. {
  199. if (!Validator.validateNameNotNull(etCode.text.toString()))
  200. {
  201. showSnackBar(rlMain, getString(R.string.txt_err_verify_code))
  202. return false
  203. }
  204.  
  205. return true
  206. }
  207.  
  208. private fun updateUI(uiState: Int, cred: PhoneAuthCredential?)
  209. {
  210. when(uiState)
  211. {
  212. STATE_INITIALIZED -> {
  213.  
  214. }
  215.  
  216. STATE_CODE_SENT -> {
  217.  
  218. }
  219.  
  220. STATE_VERIFY_FAILED -> {
  221.  
  222. }
  223.  
  224. STATE_VERIFY_SUCCESS -> {
  225. if (cred != null)
  226. {
  227. if(AppConstants.DEBUG) Log.v(AppConstants.DEBUG_TAG, "CODE OTP : CRED")
  228. if (cred.smsCode != null)
  229. {
  230. if(AppConstants.DEBUG) Log.v(AppConstants.DEBUG_TAG, "CODE OTP : OTP")
  231. etCode.setText(cred.smsCode)
  232. }
  233. else
  234. {
  235. //mVerificationField.setText(R.string.instant_validation)
  236. }
  237. }
  238. }
  239. }
  240. }
  241.  
  242. private fun verifyPhoneNumberWithCode(verificationId: String, code: String)
  243. {
  244. val credential = PhoneAuthProvider.getCredential(verificationId, code)
  245.  
  246. signInWithPhoneAuthCredential(credential)
  247. }
  248.  
  249. private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential)
  250. {
  251. if(!btnVerify.isAnimating)
  252. btnVerify.startAnimation()
  253.  
  254. mAuth = FirebaseAuth.getInstance()
  255.  
  256. mAuth?.signInWithCredential(credential)?.addOnCompleteListener(this, OnCompleteListener<AuthResult>
  257. { task ->
  258.  
  259. btnVerify.revertAnimation()
  260. btnVerify.background = ContextCompat.getDrawable(applicationContext, R.drawable.bg_selector_blue_yellow_border_rounded_25)
  261.  
  262. if (task.isSuccessful)
  263. {
  264. Log.v(AppConstants.DEBUG_TAG, "signInWithCredential:success")
  265.  
  266. Toast.makeText(this@ActivityVerifyPhone, getString(R.string.txt_successfully_verified_phone), Toast.LENGTH_LONG).show()
  267.  
  268. isVerified = true
  269.  
  270. //mAuth?.signOut()
  271. val user = mAuth?.currentUser
  272.  
  273. user?.delete()?.addOnCompleteListener {
  274. task ->
  275. if (task.isSuccessful)
  276. {
  277. Log.v(AppConstants.DEBUG_TAG, "AUTH USER : User account deleted.")
  278. }
  279.  
  280. userSignUp()
  281. }
  282. }
  283. else
  284. {
  285. btnVerify.revertAnimation()
  286.  
  287. Toast.makeText(this@ActivityVerifyPhone, getString(R.string.txt_failed_verify_phone), Toast.LENGTH_LONG).show()
  288.  
  289. Log.v(AppConstants.DEBUG_TAG, "signInWithCredential:failure", task.exception)
  290. if (task.exception is FirebaseAuthInvalidCredentialsException)
  291. {
  292.  
  293. }
  294. }
  295. })
  296. }
  297.  
  298. private fun userSignUp()
  299. {
  300. var apiServices = APIClient.client.create(ApiInterface::class.java)
  301.  
  302. val rnd = Random()
  303. val randomNum = 100000 + rnd.nextInt(900000)
  304. var verifyId = ""
  305. if(etCode.text.toString() == "")
  306. verifyId = randomNum.toString()
  307. else
  308. verifyId = etCode.text.toString()
  309.  
  310. val call = apiServices.signupUser(libFile?.getDeviceToken()!!, libFile?.getDeviceId()!!,
  311. name, phone, password, verifyId, libFile?.getAuthorizationToken()!!)
  312.  
  313. call.observeOn(AndroidSchedulers.mainThread())
  314. .subscribeOn(Schedulers.io())
  315. .subscribe ({
  316. result ->
  317. if(AppConstants.DEBUG) Log.v(AppConstants.DEBUG_TAG, "SIGNUP RESPONSE : "+result.toString())
  318.  
  319. btnVerify.revertAnimation()
  320.  
  321. if(result.get("status").asString.equals("success", ignoreCase = false))
  322. {
  323. val userData = Gson().fromJson(result.get("data").asJsonObject.get("userInfo").asJsonObject.toString(), object : TypeToken<UserData>() {}.type) as UserData
  324.  
  325. libFile?.setUserAuthToken(result.get("data").asJsonObject.get("auth_token").asString)
  326. libFile?.setPhoneNumber(userData.phone)
  327. libFile?.setPassword(password)
  328. libFile?.setCurrentUser(userData, this@ActivityVerifyPhone)
  329.  
  330. goToRegisterSuccessScreen(phone)
  331. }
  332. else
  333. {
  334. showOkAlertMessage(getString(R.string.txt_failed), result.get("message").asString, false)
  335. }
  336. }, { error ->
  337. btnVerify.revertAnimation()
  338. showOkAlertMessage(getString(R.string.txt_failed), getString(R.string.txt_something_wrong), false)
  339. error.printStackTrace()
  340. if(AppConstants.DEBUG) Log.v(AppConstants.DEBUG_TAG, "SIGNUP RESPONSE FAILED : "+error.localizedMessage)
  341. })
  342. }
  343.  
  344. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement