Skip to content

Commit

Permalink
Delete orphan address book accounts
Browse files Browse the repository at this point in the history
  • Loading branch information
sunkup committed Sep 18, 2024
1 parent 04b6e35 commit cbb2718
Showing 1 changed file with 20 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package at.bitfire.davdroid.sync.account

import android.accounts.Account
import android.accounts.AccountManager
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.ExistingPeriodicWorkPolicy
Expand All @@ -15,6 +16,8 @@ import androidx.work.WorkerParameters
import at.bitfire.davdroid.R
import at.bitfire.davdroid.db.AppDatabase
import at.bitfire.davdroid.repository.AccountRepository
import at.bitfire.davdroid.repository.DavCollectionRepository
import at.bitfire.davdroid.resource.LocalAddressBook.Companion.USER_DATA_COLLECTION_ID
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import java.time.Duration
Expand All @@ -27,6 +30,7 @@ class AccountsCleanupWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParameters: WorkerParameters,
private val accountRepository: AccountRepository,
private val collectionRepository: DavCollectionRepository,
private val db: AppDatabase,
private val logger: Logger
): Worker(appContext, workerParameters) {
Expand Down Expand Up @@ -73,13 +77,28 @@ class AccountsCleanupWorker @AssistedInject constructor(
val accountNames = accounts
.filter { account -> account.type == accountType }
.map { it.name }

// delete orphaned services in DB
val serviceDao = db.serviceDao()
if (accountNames.isEmpty())
serviceDao.deleteAll()
else
serviceDao.deleteExceptAccounts(accountNames.toTypedArray())

// Delete orphan address book accounts (where db collection is missing)
val accountManager = AccountManager.get(applicationContext)
accounts.filter { account ->
account.type == applicationContext.getString(R.string.account_type_address_book)
}.forEach { addressBookAccount ->
val collection = accountManager
.getUserData(addressBookAccount, USER_DATA_COLLECTION_ID)
.toLongOrNull()?.let { collectionId ->
collectionRepository.get(collectionId)
}
if (collection == null)
// If no collection for this address book exists, we can delete it
accountManager.removeAccountExplicitly(addressBookAccount)
}
}

}

0 comments on commit cbb2718

Please sign in to comment.