Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit ff08ff3b authored by Vincent Bourgmayer's avatar Vincent Bourgmayer
Browse files

refactor: rewrite the ReLoginWithOidcActivity to use AccountManager.addAccount and clean code style

and add licence header
parent 875ea6cb
Loading
Loading
Loading
Loading
+35 −73
Original line number Diff line number Diff line
/***************************************************************************************************
 * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details.
 **************************************************************************************************/

package at.bitfire.davdroid

import android.accounts.AccountManager
import android.accounts.AccountManager.KEY_ACCOUNT_SESSION_BUNDLE
import android.accounts.AccountManager.KEY_ACCOUNT_NAME
import android.accounts.AccountManager.KEY_BOOLEAN_RESULT
import android.accounts.AccountManager.KEY_INTENT
import android.accounts.AccountManagerFuture
import android.accounts.AuthenticatorException
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.PersistableBundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import at.bitfire.davdroid.log.Logger
import com.owncloud.android.lib.common.operations.OperationCancelledException
@@ -19,82 +21,55 @@ import java.io.IOException

class ReLoginWithOidcActivity : AppCompatActivity() {

    private lateinit var addAccountLauncher: ActivityResultLauncher<Intent>
    private var sessionBundle: Bundle? = null

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)

        val accountManager = AccountManager.get(this)
        // Initialize the ActivityResultLauncher
        addAccountLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            result ->
            if (result.resultCode == RESULT_OK) {
                // Account was added successfully
                // Handle the result here
                accountManager.finishSession(sessionBundle,
                    null, { _ ->
                                Logger.log.info("Vincent: Account added")
                                finish()
                            }, null)
            }
        }
    }

    override fun onStart() {
        super.onStart()

        val accountName = intent?.extras?.getString(AccountManager.KEY_ACCOUNT_NAME, null) ?: return
        val accountName = intent?.extras?.getString(KEY_ACCOUNT_NAME, null) ?: return
        logoutAccount(accountName)
    }

    private fun logoutAccount(accountName: String)
    {
        val accountManager = AccountManager.get(this)
        val eAccountType = applicationContext.getString(R.string.eelo_account_type)
        val eAccounts = accountManager.getAccountsByType(eAccountType)

        val accountRemovalCallback: (AliasFuture) -> Unit =  { future ->
        val callback: (AliasFuture) -> Unit =  { future ->
            val success = future.result.getBoolean(KEY_BOOLEAN_RESULT)

            if (success) {
                Logger.log.info("Vincent: $accountName removed")
                loginAccount()
                loginAccount(eAccountType)
            } else {
                Logger.log.info("failed to remove account: $accountName ")
            }
        }

        logoutAccount(accountName, accountRemovalCallback)
    }

    private fun logoutAccount(accountName: String,
                              callback : (AliasFuture) -> Unit)
    {
        val accountManager = AccountManager.get(this)
        val eAccounts= accountManager.getAccountsByType(applicationContext.getString(R.string.eelo_account_type))
        val activity = this

        eAccounts.first { it.name == accountName }.run {
            Logger.log.info("Vincent: try to remove account: ${this.name} ") //todo remove this before merge
        eAccounts.firstOrNull() {
            it.name == accountName
        } ?.run {
            accountManager.removeAccount(this, activity, callback, null)

        } ?: finish()
    }

    private fun loginAccount() {
    private fun loginAccount(accountType: String) {
        val accountManager = AccountManager.get(this)
        val eAccountType = applicationContext.getString(R.string.eelo_account_type)
        val authTokenType = null

        Logger.log.info("Vincent: Will start add Account Session")

        try {
            //todo only work for API 33 ?
            accountManager.startAddAccountSession(
                eAccountType,
                authTokenType,
                arrayOf(),
            accountManager.addAccount(
                accountType,
                null,
                null,
                this,
                { future -> startAddAccount(future) },
                null,
                null, //todo: choose between this & null
                { future -> startAddAccountActivity(future) },
                null
            )
        } catch (exception: AuthenticatorException) {
            Logger.log.info("Vincent: AuthenticatorException: can't add account: ${exception.message}")

        } catch (exception: IOException) {
            Logger.log.info("Vincent: IOException: can't add account: ${exception.message}")
        } catch (exception: OperationCancelledException) {
@@ -102,29 +77,16 @@ class ReLoginWithOidcActivity : AppCompatActivity() {
        }
    }


    private fun startAddAccount(future: AliasFuture) {
        try {
            val intent: Intent?


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent = future.result.getParcelable(KEY_INTENT, Intent::class.java)
                sessionBundle = future.result.getParcelable(KEY_ACCOUNT_SESSION_BUNDLE, Bundle::class.java)
    private fun startAddAccountActivity(future: AliasFuture) {
        val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            future.result.getParcelable(KEY_INTENT, Intent::class.java)
        } else {
                intent = future.result.getParcelable<Intent>(KEY_INTENT)
                sessionBundle = future.result.getParcelable<Bundle>(KEY_ACCOUNT_SESSION_BUNDLE)
            }

            if (sessionBundle == null) {
                Logger.log.info("Vincent: session bundle is null")
            }

            future.result.getParcelable(KEY_INTENT)
        } ?: return

            intent?.let {
                addAccountLauncher.launch(it)
            }
        } catch (exception: Exception) {
        try {
            startActivity(intent)
        } catch (exception: ActivityNotFoundException) {
            Logger.log.info("Vincent: StartAddAccount: exception: ${exception.message}")
        }
    }