Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix account switching #4636

Merged
merged 2 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
android:name=".MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden|screenLayout|smallestScreenSize"
android:exported="true"
android:launchMode="singleTask"
android:theme="@style/SplashTheme">

<intent-filter>
Expand Down Expand Up @@ -106,7 +107,6 @@
<activity
android:name=".components.compose.ComposeActivity"
android:theme="@style/TuskyDialogActivityTheme"
android:excludeFromRecents="true"
android:windowSoftInputMode="stateVisible|adjustResize" />
<activity
android:name=".components.viewthread.ViewThreadActivity"
Expand Down
112 changes: 49 additions & 63 deletions app/src/main/java/com/keylesspalace/tusky/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {

private val binding by viewBinding(ActivityMainBinding::inflate)

private lateinit var activeAccount: AccountEntity

private lateinit var header: AccountHeaderView

private var onTabSelectedListener: OnTabSelectedListener? = null
Expand Down Expand Up @@ -209,7 +211,7 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
super.onCreate(savedInstanceState)

// will be redirected to LoginActivity by BaseActivity
val activeAccount = accountManager.activeAccount ?: return
activeAccount = accountManager.activeAccount ?: return

if (explodeAnimationWasRequested()) {
overrideActivityTransitionCompat(
Expand All @@ -224,7 +226,12 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
// check for savedInstanceState in order to not handle intent events more than once
if (intent != null && savedInstanceState == null) {
showNotificationTab = handleIntent(intent, activeAccount)
if (isFinishing) {
// handleIntent() finished this activity and started a new one - no need to continue initialization
return
}
}

window.statusBarColor = Color.TRANSPARENT // don't draw a status bar, the DrawerLayout and the MaterialDrawerLayout have their own
setContentView(binding.root)

Expand Down Expand Up @@ -258,10 +265,10 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
setupDrawer(
savedInstanceState,
addSearchButton = hideTopToolbar,
addTrendingTagsButton = !accountManager.activeAccount!!.tabPreferences.hasTab(
addTrendingTagsButton = !activeAccount.tabPreferences.hasTab(
TRENDING_TAGS
),
addTrendingStatusesButton = !accountManager.activeAccount!!.tabPreferences.hasTab(
addTrendingStatusesButton = !activeAccount.tabPreferences.hasTab(
TRENDING_STATUSES
)
)
Expand Down Expand Up @@ -352,7 +359,6 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {

override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
val activeAccount = accountManager.activeAccount ?: return
val showNotificationTab = handleIntent(intent, activeAccount)
if (showNotificationTab) {
val tabs = activeAccount.tabPreferences
Expand Down Expand Up @@ -394,8 +400,7 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
}
val accountRequested = tuskyAccountId != -1L
if (accountRequested && tuskyAccountId != activeAccount.id) {
accountManager.setActiveAccount(tuskyAccountId)
changeAccount(tuskyAccountId, intent, withAnimation = false)
changeAccount(tuskyAccountId, intent)
return false
}

Expand Down Expand Up @@ -451,11 +456,9 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {

// TODO a bit cumbersome (also for resetting)
lifecycleScope.launch(Dispatchers.IO) {
accountManager.activeAccount?.let {
if (it.hasDirectMessageBadge != showBadge) {
it.hasDirectMessageBadge = showBadge
accountManager.saveAccount(it)
}
if (activeAccount.hasDirectMessageBadge != showBadge) {
activeAccount.hasDirectMessageBadge = showBadge
accountManager.saveAccount(activeAccount)
}
}
}
Expand Down Expand Up @@ -562,15 +565,13 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
private fun forwardToComposeActivity(intent: Intent) {
val composeOptions =
intent.getParcelableExtraCompat<ComposeActivity.ComposeOptions>(COMPOSE_OPTIONS)

val composeIntent = if (composeOptions != null) {
ComposeActivity.startIntent(this, composeOptions)
} else {
Intent(this, ComposeActivity::class.java).apply {
action = intent.action
type = intent.type
putExtras(intent)
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
}
startActivity(composeIntent)
Expand Down Expand Up @@ -831,11 +832,9 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
0 -> {
Log.d(TAG, "Creating \"Load more\" gap")
lifecycleScope.launch {
accountManager.activeAccount?.let {
developerToolsUseCase.createLoadMoreGap(
it.id
)
}
developerToolsUseCase.createLoadMoreGap(
activeAccount.id
)
}
}
}
Expand Down Expand Up @@ -864,7 +863,7 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
// Save the previous tab so it can be restored later
val previousTab = tabAdapter.tabs.getOrNull(binding.viewPager.currentItem)

val tabs = accountManager.activeAccount!!.tabPreferences
val tabs = activeAccount.tabPreferences

// Detach any existing mediator before changing tab contents and attaching a new mediator
tabLayoutMediator?.detach()
Expand All @@ -883,7 +882,7 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
}
if (tabs[position].id == DIRECT) {
val badge = tab.orCreateBadge
badge.isVisible = accountManager.activeAccount?.hasDirectMessageBadge ?: false
badge.isVisible = activeAccount.hasDirectMessageBadge
badge.backgroundColor = MaterialColors.getColor(binding.mainDrawer, materialR.attr.colorPrimary)
directMessageTab = tab
}
Expand Down Expand Up @@ -921,11 +920,9 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
if (tab == directMessageTab) {
tab.badge?.isVisible = false

accountManager.activeAccount?.let {
if (it.hasDirectMessageBadge) {
it.hasDirectMessageBadge = false
accountManager.saveAccount(it)
}
if (activeAccount.hasDirectMessageBadge) {
activeAccount.hasDirectMessageBadge = false
accountManager.saveAccount(activeAccount)
}
}
}
Expand Down Expand Up @@ -971,10 +968,8 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
}

private fun handleProfileClick(profile: IProfile, current: Boolean): Boolean {
val activeAccount = accountManager.activeAccount

// open profile when active image was clicked
if (current && activeAccount != null) {
if (current) {
val intent = AccountActivity.getIntent(this, activeAccount.accountId)
startActivityWithSlideInAnimation(intent)
return false
Expand All @@ -994,49 +989,43 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
private fun changeAccount(
newSelectedId: Long,
forward: Intent?,
withAnimation: Boolean = true
) {
cacheUpdater.stop()
accountManager.setActiveAccount(newSelectedId)
val intent = Intent(this, MainActivity::class.java)
if (withAnimation) {
intent.putExtra(OPEN_WITH_EXPLODE_ANIMATION, true)
}
if (forward != null) {
intent.type = forward.type
intent.action = forward.action
intent.putExtras(forward)
}
startActivity(intent)
finish()
startActivity(intent)
}

private fun logout() {
accountManager.activeAccount?.let { activeAccount ->
AlertDialog.Builder(this)
.setTitle(R.string.action_logout)
.setMessage(getString(R.string.action_logout_confirm, activeAccount.fullName))
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
binding.appBar.hide()
binding.viewPager.hide()
binding.progressBar.show()
binding.bottomNav.hide()
binding.composeButton.hide()

lifecycleScope.launch {
val otherAccountAvailable = logoutUsecase.logout()
val intent = if (otherAccountAvailable) {
Intent(this@MainActivity, MainActivity::class.java)
} else {
LoginActivity.getIntent(this@MainActivity, LoginActivity.MODE_DEFAULT)
}
startActivity(intent)
finish()
AlertDialog.Builder(this)
.setTitle(R.string.action_logout)
.setMessage(getString(R.string.action_logout_confirm, activeAccount.fullName))
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
binding.appBar.hide()
binding.viewPager.hide()
binding.progressBar.show()
binding.bottomNav.hide()
binding.composeButton.hide()

lifecycleScope.launch {
val otherAccountAvailable = logoutUsecase.logout(activeAccount)
val intent = if (otherAccountAvailable) {
Intent(this@MainActivity, MainActivity::class.java)
} else {
LoginActivity.getIntent(this@MainActivity, LoginActivity.MODE_DEFAULT)
}
startActivity(intent)
finish()
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}

private fun fetchUserInfo() = lifecycleScope.launch {
Expand All @@ -1058,11 +1047,8 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {

loadDrawerAvatar(me.avatar, false)

accountManager.updateActiveAccount(me)
NotificationHelper.createNotificationChannelsForAccount(
accountManager.activeAccount!!,
this
)
accountManager.updateAccount(activeAccount, me)
NotificationHelper.createNotificationChannelsForAccount(activeAccount, this)

// Setup push notifications
showMigrationNoticeIfNecessary(
Expand Down Expand Up @@ -1217,9 +1203,9 @@ class MainActivity : BottomSheetActivity(), ActionButtonActivity, MenuProvider {
}
header.clear()
header.profiles = profiles
header.setActiveProfile(accountManager.activeAccount!!.id)
header.setActiveProfile(activeAccount.id)
binding.mainToolbar.subtitle = if (accountManager.shouldDisplaySelfUsername()) {
accountManager.activeAccount!!.fullName
activeAccount.fullName
} else {
null
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,9 @@ class ComposeActivity :
}
}
} else if (result == CropImage.CancelledResult) {
Log.w("ComposeActivity", "Edit image cancelled by user")
Log.w(TAG, "Edit image cancelled by user")
} else {
Log.w("ComposeActivity", "Edit image failed: " + result.error)
Log.w(TAG, "Edit image failed: " + result.error)
displayTransientMessage(R.string.error_image_edit_failed)
}
viewModel.cropImageItemOld = null
Expand Down Expand Up @@ -940,7 +940,7 @@ class ComposeActivity :
val errorMessage =
getString(
R.string.error_no_custom_emojis,
accountManager.activeAccount!!.domain
activeAccount
)
displayTransientMessage(errorMessage)
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,10 @@ class LoginActivity : BaseActivity() {
oauthScopes = OAUTH_SCOPES,
newAccount = newAccount
)

finishAffinity()
val intent = Intent(this, MainActivity::class.java)
intent.putExtra(MainActivity.OPEN_WITH_EXPLODE_ANIMATION, true)
startActivity(intent)
finishAffinity()
}, { e ->
setLoading(false)
binding.domainTextInputLayout.error =
Expand Down
66 changes: 31 additions & 35 deletions app/src/main/java/com/keylesspalace/tusky/db/AccountManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ class AccountManager @Inject constructor(
}

activeAccount = newAccountEntity
updateActiveAccount(newAccount)
updateAccount(newAccountEntity, newAccount)
}

/**
Expand All @@ -122,49 +122,45 @@ class AccountManager @Inject constructor(
}

/**
* Logs the current account out by deleting all data of the account.
* Logs an account out by deleting all its data.
* @return the new active account, or null if no other account was found
*/
fun logActiveAccountOut(): AccountEntity? {
return activeAccount?.let { account ->
fun logout(account: AccountEntity): AccountEntity? {
account.logout()

account.logout()
accounts.remove(account)
accountDao.delete(account)

accounts.remove(account)
accountDao.delete(account)

if (accounts.size > 0) {
accounts[0].isActive = true
activeAccount = accounts[0]
Log.d(TAG, "logActiveAccountOut: saving account with id " + accounts[0].id)
accountDao.insertOrReplace(accounts[0])
} else {
activeAccount = null
}
activeAccount
if (accounts.size > 0) {
accounts[0].isActive = true
activeAccount = accounts[0]
Log.d(TAG, "logActiveAccountOut: saving account with id " + accounts[0].id)
accountDao.insertOrReplace(accounts[0])
} else {
activeAccount = null
}
return activeAccount
}

/**
* updates the current account with new information from the mastodon api
* and saves it in the database
* @param account the [Account] object returned from the api
* Updates an account with new information from the Mastodon api
* and saves it in the database.
* @param accountEntity the [AccountEntity] to update
* @param account the [Account] object which the newest data from the api
*/
fun updateActiveAccount(account: Account) {
activeAccount?.let {
it.accountId = account.id
it.username = account.username
it.displayName = account.name
it.profilePictureUrl = account.avatar
it.defaultPostPrivacy = account.source?.privacy ?: Status.Visibility.PUBLIC
it.defaultPostLanguage = account.source?.language.orEmpty()
it.defaultMediaSensitivity = account.source?.sensitive ?: false
it.emojis = account.emojis
it.locked = account.locked

Log.d(TAG, "updateActiveAccount: saving account with id " + it.id)
accountDao.insertOrReplace(it)
}
fun updateAccount(accountEntity: AccountEntity, account: Account) {
accountEntity.accountId = account.id
accountEntity.username = account.username
accountEntity.displayName = account.name
accountEntity.profilePictureUrl = account.avatar
accountEntity.defaultPostPrivacy = account.source?.privacy ?: Status.Visibility.PUBLIC
accountEntity.defaultPostLanguage = account.source?.language.orEmpty()
accountEntity.defaultMediaSensitivity = account.source?.sensitive ?: false
accountEntity.emojis = account.emojis
accountEntity.locked = account.locked

Log.d(TAG, "updateAccount: saving account with id " + accountEntity.id)
accountDao.insertOrReplace(accountEntity)
}

/**
Expand Down
Loading
Loading