package com.notifyhub.viewer.ui import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.notifyhub.viewer.NotizViewerApp import com.notifyhub.viewer.R import com.notifyhub.viewer.data.AuthRepository import com.notifyhub.viewer.databinding.ActivityTwoFactorBinding import com.notifyhub.viewer.util.deviceName import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class TwoFactorActivity : AppCompatActivity() { private lateinit var binding: ActivityTwoFactorBinding private lateinit var app: NotizViewerApp private lateinit var repo: AuthRepository private var challengeId: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) app = application as NotizViewerApp repo = AuthRepository(app.api, app.preferences, deviceName()) challengeId = intent.getStringExtra(EXTRA_CHALLENGE_ID) binding = ActivityTwoFactorBinding.inflate(layoutInflater) setContentView(binding.root) binding.subtitleText.text = intent.getStringExtra(EXTRA_MESSAGE) ?: getString(R.string.two_factor_subtitle) binding.verifyButton.setOnClickListener { verify() } binding.resendButton.setOnClickListener { resend() } } private fun verify() { val code = binding.codeInput.text?.toString()?.trim().orEmpty() val id = challengeId ?: run { binding.statusText.text = getString(R.string.error_message, "Session expired. Sign in again.") return } if (code.isBlank()) { binding.statusText.text = getString(R.string.error_message, "Enter the code.") return } binding.verifyButton.isEnabled = false binding.statusText.text = getString(R.string.verifying) lifecycleScope.launch { val outcome = withContext(Dispatchers.IO) { repo.verify(id, code) } binding.verifyButton.isEnabled = true when (outcome) { is AuthRepository.VerifyOutcome.Success -> { startActivity(Intent(this@TwoFactorActivity, HomeActivity::class.java)) finish() } is AuthRepository.VerifyOutcome.Failed -> { binding.statusText.text = outcome.message } } } } private fun resend() { val id = challengeId ?: return binding.resendButton.isEnabled = false lifecycleScope.launch { val error = withContext(Dispatchers.IO) { repo.resend(id) } binding.resendButton.isEnabled = true binding.statusText.text = error ?: "A new code was sent." } } companion object { const val EXTRA_CHALLENGE_ID = "extra_challenge_id" const val EXTRA_MESSAGE = "extra_message" } }