fix: Sort by access with actions refactoring #1911

This commit is contained in:
J-Jamet committed 2026-05-20 16:28:13 +02:00
1 parent 0d878b70f2
commit 7594aad0e4
34 files changed
+853 -477

No files matched your search

@@ -294,6 +294,9 @@ class EntryActivity : DatabaseLockActivity() {
mBackgroundColor = if (showEntryColors) entryInfo.backgroundColor else null
mForegroundColor = if (showEntryColors) entryInfo.foregroundColor else null
// To sort by access
touchEntry(entryInfo)
loadingView?.hideByFading()
} else {
finish()
@@ -363,16 +363,6 @@ class EntryEditActivity : DatabaseLockActivity(),
mAttachmentFileBinderManager?.removeBinaryAttachment(it)
}
// Build new entry from the entry info retrieved
mEntryEditViewModel.onEntrySaved.observe(this) { entrySave ->
// Open a progress dialog and save entry
entrySave.parent?.let { parent ->
createEntry(entrySave.newEntry, parent)
} ?: run {
updateEntry(entrySave.oldEntry, entrySave.newEntry)
}
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
mEntryEditViewModel.entryEditState.collect { entryEditState ->
@@ -420,6 +410,21 @@ class EntryEditActivity : DatabaseLockActivity(),
}
}
is EntryEditViewModel.EntryEditState.OnFieldProtectionUpdated -> {}
is EntryEditViewModel.EntryEditState.CreateEntry -> {
// Build new entry from the entry info retrieved
createEntry(
parentId = entryEditState.parentId,
entryInfo = entryEditState.newEntry
)
mEntryEditViewModel.actionPerformed()
}
is EntryEditViewModel.EntryEditState.UpdateEntry -> {
updateEntry(
oldEntryId = entryEditState.oldEntryId,
entryInfo = entryEditState.updateEntry
)
mEntryEditViewModel.actionPerformed()
}
is EntryEditViewModel.EntryEditState.CloseEntry -> {
when(entryEditState.closeType) {
EntryEditViewModel.CloseType.DATABASE_BACK_PRESSED -> {
@@ -87,7 +87,6 @@ import com.kunzisoft.keepass.database.element.Group
import com.kunzisoft.keepass.database.element.SortNodeEnum
import com.kunzisoft.keepass.database.element.node.Node
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.database.element.node.NodeIdUUID
import com.kunzisoft.keepass.database.element.node.Type
import com.kunzisoft.keepass.database.exception.RegisterInReadOnlyDatabaseException
import com.kunzisoft.keepass.database.helper.SearchHelper
@@ -95,6 +94,7 @@ import com.kunzisoft.keepass.database.helper.SearchHelper.getSearchParametersFro
import com.kunzisoft.keepass.database.search.SearchParameters
import com.kunzisoft.keepass.education.GroupActivityEducation
import com.kunzisoft.keepass.model.DataTime
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.model.GroupInfo
import com.kunzisoft.keepass.model.RegisterInfo
import com.kunzisoft.keepass.model.SearchInfo
@@ -344,7 +344,7 @@ class GroupActivity : DatabaseLockActivity(),
drawerLayout?.addDrawerListener(toggle)
toggle.syncState()
// Manage 'merge from" and "save to"
// Manage "merge from" and "save to"
mExternalFileHelper = ExternalFileHelper(this)
mExternalFileHelper?.buildOpenDocument { uri ->
launchDialogToAskMainCredential(uri)
@@ -510,24 +510,6 @@ class GroupActivity : DatabaseLockActivity(),
}
}
mGroupEditViewModel.onGroupCreated.observe(this) { groupInfo ->
if (groupInfo.title.isNotEmpty()) {
mMainGroup?.let { parentGroup ->
createGroup(parentGroup, groupInfo)
}
}
}
mGroupEditViewModel.onGroupUpdated.observe(this) { groupInfo ->
if (groupInfo.title.isNotEmpty()) {
groupInfo.id?.let { groupId ->
mDatabase?.getGroupById(NodeIdUUID(groupId))?.let { oldGroupToUpdate ->
updateGroup(oldGroupToUpdate, groupInfo)
}
}
}
}
// Add listeners to the add buttons
addNodeButtonView?.setAddGroupClickListener {
mMainGroup?.let { currentGroup ->
@@ -600,6 +582,26 @@ class GroupActivity : DatabaseLockActivity(),
}
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.RESUMED) {
mGroupEditViewModel.groupEditState.collect { groupEditState ->
when (groupEditState) {
is GroupEditViewModel.GroupEditState.Wait -> {}
is GroupEditViewModel.GroupEditState.CreateGroup -> {
mMainGroup?.nodeId?.let { parentId ->
createGroup(parentId, groupEditState.groupInfo)
}
mGroupEditViewModel.actionPerformed()
}
is GroupEditViewModel.GroupEditState.UpdateGroup -> {
updateGroup(groupEditState.oldGroupId, groupEditState.groupInfo)
mGroupEditViewModel.actionPerformed()
}
}
}
}
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.RESUMED) {
mUserVerificationViewModel.userVerificationState.collect { uVState ->
@@ -710,7 +712,7 @@ class GroupActivity : DatabaseLockActivity(),
adapter = mBreadcrumbAdapter
}
mGroupEditViewModel.setGroupNamesNotAllowed(database.groupNamesNotAllowed)
mGroupEditViewModel.groupNamesNotAllowed = database.groupNamesNotAllowed
mRecyclingBinEnabled = !mDatabaseReadOnly
&& database.isRecycleBinEnabled == true
@@ -939,6 +941,7 @@ class GroupActivity : DatabaseLockActivity(),
}
Type.ENTRY -> try {
// TODO Manage EntryInfo
val entryVersioned = node as Entry
EntrySelectionHelper.doSpecialAction(
intent = intent,
@@ -1067,30 +1070,34 @@ class GroupActivity : DatabaseLockActivity(),
entry: Entry,
registerInfo: RegisterInfo
) {
val newEntry = Entry(entry)
val entryInfo = newEntry.getEntryInfo(
val entryInfo = Entry(entry).getEntryInfo(
database,
raw = true,
removeTemplateConfiguration = false
raw = true
)
entryInfo.saveRegisterInfo(database, registerInfo)
newEntry.setEntryInfo(database, entryInfo)
updateEntry(entry, newEntry)
updateEntry(entry.nodeId, entryInfo)
}
// TODO Remove
private fun Entry.allowedToSaveSearchInfo(
database: ContextualDatabase,
searchInfo: SearchInfo?
): Boolean {
return getEntryInfo(
database,
raw = true
).allowedToSaveSearchInfo(database, searchInfo)
}
private fun EntryInfo.allowedToSaveSearchInfo(
database: ContextualDatabase,
searchInfo: SearchInfo?
): Boolean {
if (database.isReadOnly)
return false
if (searchInfo == null || searchInfo.toString().isEmpty())
return false
return !(getEntryInfo(
database,
raw = true,
removeTemplateConfiguration = false
).containsSearchInfo(searchInfo))
return !(this.containsSearchInfo(searchInfo))
}
private fun editEntry(database: ContextualDatabase?, entryId: NodeId<*>?) {
@@ -19,7 +19,7 @@ import kotlinx.coroutines.launch
abstract class DatabaseDialogFragment : DialogFragment(), DatabaseRetrieval {
private val mDatabaseViewModel: DatabaseViewModel by activityViewModels()
protected val mDatabaseViewModel: DatabaseViewModel by activityViewModels()
private val mDatabase: ContextualDatabase?
get() = mDatabaseViewModel.database
@@ -165,6 +165,9 @@ class GroupDialogFragment : DatabaseDialogFragment() {
}
}
// To sort by access
mDatabaseViewModel.touchGroup(mGroupInfo)
val builder = AlertDialog.Builder(activity)
builder.setView(root)
.setPositiveButton(android.R.string.ok){ _, _ ->
@@ -53,7 +53,6 @@ class GroupEditDialogFragment : DatabaseDialogFragment() {
private var mPopulateIconMethod: ((ImageView, IconImage) -> Unit)? = null
private var mEditGroupDialogAction = NONE
private var mGroupInfo = GroupInfo()
private var mGroupNamesNotAllowed: List<String>? = null
private lateinit var iconButtonView: ImageView
private var mIconColor: Int = 0
@@ -106,10 +105,6 @@ class GroupEditDialogFragment : DatabaseDialogFragment() {
mGroupInfo.expiryTime.setTime(viewModelTime.hour, viewModelTime.minute)
expirationView.dateTime = mGroupInfo.expiryTime
}
mGroupEditViewModel.groupNamesNotAllowed.observe(this) { namesNotAllowed ->
this.mGroupNamesNotAllowed = namesNotAllowed
}
}
override fun onDatabaseRetrieved(database: ContextualDatabase) {
@@ -273,10 +268,10 @@ class GroupEditDialogFragment : DatabaseDialogFragment() {
name.isEmpty() -> {
Error(true, R.string.error_no_name)
}
mGroupNamesNotAllowed == null -> {
mGroupEditViewModel.groupNamesNotAllowed == null -> {
Error(true, R.string.error_word_reserved)
}
mGroupNamesNotAllowed?.find { it.equals(name, ignoreCase = true) } != null -> {
mGroupEditViewModel.groupNamesNotAllowed?.find { it.equals(name, ignoreCase = true) } != null -> {
Error(true, R.string.error_word_reserved)
}
else -> {
@@ -285,6 +285,12 @@ class EntryEditFragment: DatabaseFragment() {
updateFieldProtection(entryEditState.fieldProtection)
mEntryEditViewModel.actionPerformed()
}
is EntryEditViewModel.EntryEditState.CreateEntry -> {
// Managed in entry edit activity
}
is EntryEditViewModel.EntryEditState.UpdateEntry -> {
// Managed in entry edit activity
}
is EntryEditViewModel.EntryEditState.CloseEntry -> {
// Managed in entry edit activity
}
@@ -19,6 +19,7 @@ import com.kunzisoft.keepass.R
import com.kunzisoft.keepass.adapters.EntryAttachmentsItemsAdapter
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Attachment
import com.kunzisoft.keepass.database.element.template.Template
import com.kunzisoft.keepass.model.EntryAttachmentState
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.model.FieldProtection
@@ -99,7 +100,6 @@ class EntryFragment: DatabaseFragment() {
mEntryViewModel.entryInfoHistory.observe(viewLifecycleOwner) { entryInfoHistory ->
if (entryInfoHistory != null) {
templateView.setTemplate(entryInfoHistory.template)
assignEntryInfo(entryInfoHistory.entryInfo)
// Smooth appearing
rootView.showByFading()
@@ -175,6 +175,9 @@ class EntryFragment: DatabaseFragment() {
}
}
// Set template
templateView.setTemplate(entryInfo?.template ?: Template.STANDARD)
// Populate entry views
templateView.setEntryInfo(entryInfo)
@@ -43,6 +43,7 @@ import com.kunzisoft.keepass.database.element.Entry
import com.kunzisoft.keepass.database.element.Group
import com.kunzisoft.keepass.database.element.node.Node
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.model.GroupInfo
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService
import com.kunzisoft.keepass.settings.PreferencesUtil
@@ -184,6 +185,7 @@ abstract class DatabaseLockActivity : DatabaseModeActivity(),
}
fun assignMainCredential(mainCredential: MainCredential) {
// TODO Move in ViewModel
mDatabase?.let { database ->
database.fileUri?.let { databaseUri ->
// Show the progress dialog now or after dialog confirmation
@@ -221,17 +223,23 @@ abstract class DatabaseLockActivity : DatabaseModeActivity(),
}
fun createEntry(
newEntry: Entry,
parent: Group
parentId: NodeId<*>,
entryInfo: EntryInfo
) {
mDatabaseViewModel.createEntry(newEntry, parent, mAutoSaveEnable)
mDatabaseViewModel.createEntry(parentId, entryInfo, mAutoSaveEnable)
}
fun updateEntry(
oldEntry: Entry,
entryToUpdate: Entry
oldEntryId: NodeId<UUID>,
entryInfo: EntryInfo
) {
mDatabaseViewModel.updateEntry(oldEntry, entryToUpdate, mAutoSaveEnable)
mDatabaseViewModel.updateEntry(oldEntryId, entryInfo, mAutoSaveEnable)
}
fun touchEntry(
entryInfo: EntryInfo
) {
mDatabaseViewModel.touchEntry(entryInfo)
}
fun copyNodes(
@@ -286,36 +294,17 @@ abstract class DatabaseLockActivity : DatabaseModeActivity(),
}
fun createGroup(
parent: Group,
groupInfo: GroupInfo?
parentId: NodeId<*>,
groupInfo: GroupInfo
) {
// TODO Move in ViewModel
// Build the group
mDatabase?.createGroup()?.let { newGroup ->
groupInfo?.let { info ->
newGroup.setGroupInfo(info)
}
// Not really needed here because added in runnable but safe
newGroup.parent = parent
mDatabaseViewModel.createGroup(newGroup, parent, mAutoSaveEnable)
}
mDatabaseViewModel.createGroup(parentId, groupInfo, mAutoSaveEnable)
}
fun updateGroup(
oldGroup: Group,
oldGroupId: NodeId<*>,
groupInfo: GroupInfo
) {
// TODO Move in ViewModel
// If group updated save it in the database
val updateGroup = Group(oldGroup).let { updateGroup ->
updateGroup.apply {
// WARNING remove parent and children to keep memory
removeParent()
removeChildren()
this.setGroupInfo(groupInfo)
}
}
mDatabaseViewModel.updateGroup(oldGroup, updateGroup, mAutoSaveEnable)
mDatabaseViewModel.updateGroup(oldGroupId, groupInfo, mAutoSaveEnable)
}
fun restoreEntryHistory(
@@ -102,7 +102,7 @@ class PasskeyLauncherActivity : AuthenticationLauncherActivity() {
)
}
is PasskeyLauncherViewModel.UIState.UpdateEntry -> {
updateEntry(uiState.oldEntry, uiState.newEntry)
updateEntry(uiState.oldEntryId, uiState.newEntry)
}
}
}
@@ -77,17 +77,6 @@ class PasswordLauncherActivity : AuthenticationLauncherActivity() {
lifecycleScope.launch {
// Initialize the parameters
passwordLauncherViewModel.initialize()
// Retrieve the UI
passwordLauncherViewModel.uiState.collect { uiState ->
when (uiState) {
is PasswordLauncherViewModel.UIState.Loading -> {
// Nothing to do
}
is PasswordLauncherViewModel.UIState.UpdateEntry -> {
updateEntry(uiState.oldEntry, uiState.newEntry)
}
}
}
}
lifecycleScope.launch {
passwordLauncherViewModel.credentialUiState.collect { uiState ->
@@ -16,13 +16,6 @@ import com.kunzisoft.keepass.credentialprovider.EntrySelectionHelper.removeInfo
import com.kunzisoft.keepass.credentialprovider.EntrySelectionHelper.removeNodeId
import com.kunzisoft.keepass.credentialprovider.EntrySelectionHelper.retrieveNodeId
import com.kunzisoft.keepass.credentialprovider.EntrySelectionHelper.retrieveSearchInfo
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.buildCreatePublicKeyCredentialResponse
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.buildPasskeyPublicKeyCredential
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.getVerifiedGETClientDataResponse
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.removePasskey
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.retrievePasskey
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.retrievePasskeyCreationRequestParameters
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.retrievePasskeyUsageRequestParameters
import com.kunzisoft.keepass.credentialprovider.SpecialMode
import com.kunzisoft.keepass.credentialprovider.TypeMode
import com.kunzisoft.keepass.credentialprovider.passkey.data.AndroidPrivilegedApp
@@ -31,14 +24,23 @@ import com.kunzisoft.keepass.credentialprovider.passkey.data.PublicKeyCredential
import com.kunzisoft.keepass.credentialprovider.passkey.util.PassHelper.checkSecurity
import com.kunzisoft.keepass.credentialprovider.passkey.util.PassHelper.removeAppOrigin
import com.kunzisoft.keepass.credentialprovider.passkey.util.PassHelper.retrieveAppOrigin
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.buildCreatePublicKeyCredentialResponse
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.buildPasskeyPublicKeyCredential
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.getVerifiedGETClientDataResponse
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.removePasskey
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.retrievePasskey
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.retrievePasskeyCreationRequestParameters
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasskeyHelper.retrievePasskeyUsageRequestParameters
import com.kunzisoft.keepass.credentialprovider.passkey.util.PrivilegedAllowLists
import com.kunzisoft.keepass.credentialprovider.passkey.util.PrivilegedAllowLists.saveCustomPrivilegedApps
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Entry
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.database.element.node.NodeIdUUID
import com.kunzisoft.keepass.database.exception.RegisterInReadOnlyDatabaseException
import com.kunzisoft.keepass.database.helper.SearchHelper
import com.kunzisoft.keepass.model.AppOrigin
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.model.Passkey
import com.kunzisoft.keepass.model.RegisterInfo
import com.kunzisoft.keepass.model.SearchInfo
@@ -122,24 +124,23 @@ class PasskeyLauncherViewModel(application: Application): CredentialLauncherView
showError(e)
}) {
// Update the entry with app signature
val oldEntryId = NodeIdUUID(nodeId)
val entry = database
?.getEntryById(NodeIdUUID(nodeId))
?.getEntryById(oldEntryId)
?: throw GetCredentialUnknownException(
"No passkey with nodeId $nodeId found"
"No passkey with nodeId $oldEntryId found"
)
if (database.isReadOnly)
throw RegisterInReadOnlyDatabaseException()
val newEntry = Entry(entry)
val entryInfo = newEntry.getEntryInfo(
database,
raw = true,
removeTemplateConfiguration = false
raw = true
)
entryInfo.saveAppOrigin(database, temptingApp)
newEntry.setEntryInfo(database, entryInfo)
mUiState.value = UIState.UpdateEntry(
oldEntry = entry,
newEntry = newEntry
oldEntryId = oldEntryId,
newEntry = entryInfo
)
}
}
@@ -549,8 +550,8 @@ class PasskeyLauncherViewModel(application: Application): CredentialLauncherView
val nodeId: UUID
): UIState()
data class UpdateEntry(
val oldEntry: Entry,
val newEntry: Entry
val oldEntryId: NodeId<UUID>,
val newEntry: EntryInfo
): UIState()
}
@@ -25,7 +25,6 @@ import com.kunzisoft.keepass.credentialprovider.passkey.util.PasswordHelper.retr
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasswordHelper.retrievePasswordInfo
import com.kunzisoft.keepass.credentialprovider.passkey.util.PasswordHelper.retrievePasswordUsageRequestParameters
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Entry
import com.kunzisoft.keepass.database.element.node.NodeIdUUID
import com.kunzisoft.keepass.database.helper.SearchHelper
import com.kunzisoft.keepass.model.AppOrigin
@@ -35,9 +34,6 @@ import com.kunzisoft.keepass.model.SearchInfo
import com.kunzisoft.keepass.settings.PreferencesUtil
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
@@ -55,9 +51,6 @@ class PasswordLauncherViewModel(application: Application): CredentialLauncherVie
private var mLockDatabaseAfterSelection: Boolean = false
private val mUiState = MutableStateFlow<UIState>(UIState.Loading)
val uiState: StateFlow<UIState> = mUiState.asStateFlow()
fun initialize() {
mLockDatabaseAfterSelection = PreferencesUtil.isPasskeyCloseDatabaseEnable(getApplication())
}
@@ -339,14 +332,6 @@ class PasswordLauncherViewModel(application: Application): CredentialLauncherVie
}
}
sealed class UIState {
object Loading : UIState()
data class UpdateEntry(
val oldEntry: Entry,
val newEntry: Entry
): UIState()
}
companion object {
private val TAG = PasswordLauncherViewModel::class.java.name
}
@@ -2,11 +2,20 @@ package com.kunzisoft.keepass.database
import android.net.Uri
import com.kunzisoft.keepass.database.element.Database
import com.kunzisoft.keepass.database.element.Entry
import com.kunzisoft.keepass.database.element.Group
import com.kunzisoft.keepass.database.element.icon.IconImageCustom
import com.kunzisoft.keepass.database.element.node.NodeIdUUID
import com.kunzisoft.keepass.icons.IconDrawableFactory
import com.kunzisoft.keepass.model.AttachmentState
import com.kunzisoft.keepass.model.EntryAttachmentState
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.model.GroupInfo
import com.kunzisoft.keepass.model.StreamDirection
import com.kunzisoft.keepass.utils.SingletonHolder
import java.io.File
// TODO Change to DatabaseInfo
class ContextualDatabase: Database() {
var fileUri: Uri? = null
@@ -16,11 +25,96 @@ class ContextualDatabase: Database() {
retrieveCustomIconBinary = { iconId -> getBinaryForCustomIcon(iconId) }
)
val tempAttachments = mutableListOf<EntryAttachmentState>()
fun getEntryInfoFrom(entry: Entry, raw: Boolean = false): EntryInfo {
return entry.getEntryInfo(database = this, raw = raw)
}
fun getHistoryEntryInfoFrom(entry: Entry): List<EntryInfo> {
return entry.getHistory().map { entryHistory ->
entryHistory.getEntryInfo(database = this)
}
}
/**
* Build a new Entry from an EntryInfo
*/
fun getEntryFrom(entryInfo: EntryInfo): Entry? {
// Delete temp attachment if not completely downloaded
removeTempAttachmentsNotCompleted(entryInfo)
// Create the new entry
val newEntry = getEntryById(NodeIdUUID(entryInfo.id))?.let { oldEntry ->
// Create a clone
Entry(oldEntry)
} ?: createEntry()
newEntry?.apply {
// Build info
setEntryInfo(this@ContextualDatabase, entryInfo)
// Delete temp attachment from entry if not used
removeTempAttachmentsNotUsed()
}
// Return entry to save
return newEntry
}
/**
* Build a new Group from a GroupInfo
*/
fun getGroupFrom(groupInfo: GroupInfo): Group? {
// Create the new entry
val newGroup = groupInfo.id?.let { groupId ->
getGroupById(NodeIdUUID(groupId))
}?.let { oldGroup ->
Group(oldGroup)
} ?: createGroup()
newGroup?.apply {
// WARNING remove parent and children to keep memory
removeParent()
removeChildren()
setGroupInfo(groupInfo)
}
return newGroup
}
override fun removeCustomIcon(customIcon: IconImageCustom) {
iconDrawableFactory.clearFromCache(customIcon)
super.removeCustomIcon(customIcon)
}
private fun removeTempAttachmentsNotCompleted(entryInfo: EntryInfo) {
// Do not save entry in upload progression
tempAttachments.forEach { attachmentState ->
if (attachmentState.streamDirection == StreamDirection.UPLOAD) {
when (attachmentState.downloadState) {
AttachmentState.START,
AttachmentState.IN_PROGRESS,
AttachmentState.CANCELED,
AttachmentState.ERROR -> {
// Remove attachment not finished from info
entryInfo.attachments = entryInfo.attachments.toMutableList().apply {
remove(attachmentState.attachment)
}
}
else -> {}
}
}
}
}
private fun Entry.removeTempAttachmentsNotUsed() {
tempAttachments.forEach { tempAttachmentState ->
val tempAttachment = tempAttachmentState.attachment
attachmentPool.let { binaryPool ->
if (!this.getAttachments(binaryPool)
.contains(tempAttachment)
) {
removeAttachmentIfNotUsed(tempAttachment)
}
}
}
}
override fun clearIndexesAndBinaries(filesDirectory: File?) {
iconDrawableFactory.clearCache()
super.clearIndexesAndBinaries(filesDirectory)
@@ -45,6 +45,8 @@ import com.kunzisoft.keepass.database.element.node.Node
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.database.element.node.Type
import com.kunzisoft.keepass.model.CipherEncryptDatabase
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.model.GroupInfo
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_CHALLENGE_RESPONDED
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_ASSIGN_CREDENTIAL_TASK
@@ -62,6 +64,8 @@ import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_REMOVE_UNLINKED_DATA_TASK
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_RESTORE_ENTRY_HISTORY
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_SAVE
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_TOUCH_ENTRY_TASK
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_TOUCH_GROUP_TASK
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_UPDATE_COLOR_TASK
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_UPDATE_COMPRESSION_TASK
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_UPDATE_DEFAULT_USERNAME_TASK
@@ -321,53 +325,69 @@ class DatabaseTaskProvider(
*/
fun startDatabaseCreateGroup(
newGroup: Group,
parent: Group,
parentId: NodeId<*>,
newGroup: GroupInfo,
save: Boolean
) {
start(Bundle().apply {
putParcelable(DatabaseTaskNotificationService.PARENT_ID_KEY, parentId)
putParcelable(DatabaseTaskNotificationService.GROUP_KEY, newGroup)
putParcelable(DatabaseTaskNotificationService.PARENT_ID_KEY, parent.nodeId)
putBoolean(DatabaseTaskNotificationService.SAVE_DATABASE_KEY, save)
}, ACTION_DATABASE_CREATE_GROUP_TASK)
}
fun startDatabaseUpdateGroup(
oldGroup: Group,
groupToUpdate: Group,
oldGroupId: NodeId<*>,
updateGroup: GroupInfo,
save: Boolean
) {
start(Bundle().apply {
putParcelable(DatabaseTaskNotificationService.GROUP_ID_KEY, oldGroup.nodeId)
putParcelable(DatabaseTaskNotificationService.GROUP_KEY, groupToUpdate)
putParcelable(DatabaseTaskNotificationService.GROUP_ID_KEY, oldGroupId)
putParcelable(DatabaseTaskNotificationService.GROUP_KEY, updateGroup)
putBoolean(DatabaseTaskNotificationService.SAVE_DATABASE_KEY, save)
}, ACTION_DATABASE_UPDATE_GROUP_TASK)
}
fun startDatabaseTouchGroup(
groupId: NodeId<UUID>
) {
start(Bundle().apply {
putParcelable(DatabaseTaskNotificationService.GROUP_ID_KEY, groupId)
}, ACTION_DATABASE_TOUCH_GROUP_TASK)
}
fun startDatabaseCreateEntry(
newEntry: Entry,
parent: Group,
parentId: NodeId<*>,
newEntry: EntryInfo,
save: Boolean
) {
start(Bundle().apply {
putParcelable(DatabaseTaskNotificationService.PARENT_ID_KEY, parentId)
putParcelable(DatabaseTaskNotificationService.ENTRY_KEY, newEntry)
putParcelable(DatabaseTaskNotificationService.PARENT_ID_KEY, parent.nodeId)
putBoolean(DatabaseTaskNotificationService.SAVE_DATABASE_KEY, save)
}, ACTION_DATABASE_CREATE_ENTRY_TASK)
}
fun startDatabaseUpdateEntry(
oldEntry: Entry,
entryToUpdate: Entry,
oldEntryId: NodeId<UUID>,
updateEntry: EntryInfo,
save: Boolean
) {
start(Bundle().apply {
putParcelable(DatabaseTaskNotificationService.ENTRY_ID_KEY, oldEntry.nodeId)
putParcelable(DatabaseTaskNotificationService.ENTRY_KEY, entryToUpdate)
putParcelable(DatabaseTaskNotificationService.ENTRY_ID_KEY, oldEntryId)
putParcelable(DatabaseTaskNotificationService.ENTRY_KEY, updateEntry)
putBoolean(DatabaseTaskNotificationService.SAVE_DATABASE_KEY, save)
}, ACTION_DATABASE_UPDATE_ENTRY_TASK)
}
fun startDatabaseTouchEntry(
entryId: NodeId<UUID>
) {
start(Bundle().apply {
putParcelable(DatabaseTaskNotificationService.ENTRY_ID_KEY, entryId)
}, ACTION_DATABASE_TOUCH_ENTRY_TASK)
}
private fun startDatabaseActionListNodes(
actionTask: String,
nodesPaste: List<Node>,
@@ -23,40 +23,49 @@ import android.content.Context
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.action.node.UpdateEntryRunnable
import com.kunzisoft.keepass.database.element.Entry
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.hardware.HardwareKey
import com.kunzisoft.keepass.tasks.ActionRunnable
import java.util.UUID
class RestoreEntryHistoryDatabaseRunnable (
private val context: Context,
private val database: ContextualDatabase,
private val mainEntry: Entry,
entryId: NodeId<UUID>,
private val entryHistoryPosition: Int,
private val saveDatabase: Boolean,
private val save: Boolean,
private val challengeResponseRetriever: (HardwareKey, ByteArray?) -> ByteArray
) : ActionRunnable() {
private var updateEntryRunnable: UpdateEntryRunnable? = null
private var mMainEntry: Entry? = null
init {
database.getEntryById(entryId)?.let { entry ->
mMainEntry = entry
}
}
override fun onStartRun() {
try {
val historyToRestore = Entry(mainEntry.getHistory()[entryHistoryPosition])
// Copy history of main entry in the restore entry
mainEntry.getHistory().forEach {
historyToRestore.addEntryToHistory(it)
}
// Update the entry with the fresh formatted entry to restore
updateEntryRunnable = UpdateEntryRunnable(
context,
database,
mainEntry,
historyToRestore,
saveDatabase,
null,
challengeResponseRetriever
)
updateEntryRunnable?.onStartRun()
mMainEntry?.let { mainEntry ->
val historyToRestore = Entry(mainEntry.getHistory()[entryHistoryPosition]).getEntryInfo(
database = database,
raw = true
)
// Update the entry with the fresh formatted entry to restore
updateEntryRunnable = UpdateEntryRunnable(
context = context,
database = database,
oldEntryId = mainEntry.nodeId,
newEntry = historyToRestore,
save = save,
afterActionNodesFinish = null,
challengeResponseRetriever = challengeResponseRetriever
)
updateEntryRunnable?.onStartRun()
} ?: setError("Entry to restore cannot be null")
} catch (e: Exception) {
setError(e)
}
@@ -20,33 +20,62 @@
package com.kunzisoft.keepass.database.action.node
import android.content.Context
import android.util.Log
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Entry
import com.kunzisoft.keepass.database.element.Group
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.hardware.HardwareKey
import com.kunzisoft.keepass.model.EntryInfo
class AddEntryRunnable(
context: Context,
database: ContextualDatabase,
private val mNewEntry: Entry,
private val mParent: Group,
parentId: NodeId<*>,
newEntry: EntryInfo,
save: Boolean,
afterActionNodesFinish: AfterActionNodesFinish?,
challengeResponseRetriever: (HardwareKey, ByteArray?) -> ByteArray
) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save, challengeResponseRetriever) {
private var mParent: Group? = null
private var mNewEntry: Entry? = null
init {
database.getGroupById(parentId)?.let { parent ->
mParent = parent
}
if (mParent == null) {
Log.w(TAG, "Unable to retrieve the parent to create the entry")
mParent = database.rootGroup
}
mNewEntry = database.getEntryFrom(newEntry)
}
override fun nodeAction() {
mNewEntry.touch(modified = true, touchParents = true)
mParent.touch(modified = true, touchParents = true)
database.addEntryTo(mNewEntry, mParent)
mNewEntry?.let { newEntry ->
newEntry.touch(modified = true, touchParents = true)
mParent?.let { parent ->
parent.touch(modified = true, touchParents = true)
database.addEntryTo(newEntry, parent)
}
}
}
override fun nodeFinish(): ActionNodesValues {
if (!result.isSuccess) {
mNewEntry.parent?.let {
database.removeEntryFrom(mNewEntry, it)
mNewEntry?.let { newEntry ->
newEntry.parent?.let {
database.removeEntryFrom(newEntry, it)
}
}
}
return ActionNodesValues(listOf(), listOf(mNewEntry))
return ActionNodesValues(
oldNodes = listOf(),
newNodes = mNewEntry?.let { listOf(it) } ?: listOf())
}
companion object {
private val TAG = AddEntryRunnable::class.simpleName
}
}
@@ -20,30 +20,61 @@
package com.kunzisoft.keepass.database.action.node
import android.content.Context
import android.util.Log
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Group
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.hardware.HardwareKey
import com.kunzisoft.keepass.model.GroupInfo
class AddGroupRunnable(
context: Context,
database: ContextualDatabase,
private val mNewGroup: Group,
private val mParent: Group,
parentId: NodeId<*>,
newGroup: GroupInfo,
save: Boolean,
afterActionNodesFinish: AfterActionNodesFinish?,
challengeResponseRetriever: (HardwareKey, ByteArray?) -> ByteArray
) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save, challengeResponseRetriever) {
private var mParent: Group? = null
private var mNewGroup: Group? = null
init {
database.getGroupById(parentId)?.let { parent ->
mParent = parent
}
if (mParent == null) {
Log.w(TAG, "Unable to retrieve the parent to create the group")
mParent = database.rootGroup
}
mNewGroup = database.getGroupFrom(newGroup)
}
override fun nodeAction() {
mNewGroup.touch(modified = true, touchParents = true)
mParent.touch(modified = true, touchParents = true)
database.addGroupTo(mNewGroup, mParent)
mNewGroup?.let { newGroup ->
newGroup.touch(modified = true, touchParents = true)
mParent?.let { parent ->
parent.touch(modified = true, touchParents = true)
database.addGroupTo(newGroup, parent)
}
}
}
override fun nodeFinish(): ActionNodesValues {
if (!result.isSuccess) {
database.removeGroupFrom(mNewGroup, mParent)
mNewGroup?.let { newGroup ->
newGroup.parent?.let { parent ->
database.removeGroupFrom(newGroup, parent)
}
}
}
return ActionNodesValues(listOf(), listOf(mNewGroup))
return ActionNodesValues(
oldNodes = listOf(),
newNodes = mNewGroup?.let { listOf(it) } ?: listOf())
}
companion object {
private val TAG = AddGroupRunnable::class.simpleName
}
}
@@ -29,6 +29,7 @@ import com.kunzisoft.keepass.tasks.ActionRunnable
* - Delete : @param oldNodes NodesToDelete, @param newNodes empty
* - Move : @param oldNodes empty, @param newNodes NodesToMove
* - Update : @param oldNodes NodesToUpdate, @param newNodes NodesUpdated
* - Touch : @param olNodes TouchedNodes, @param newNodes empty
*/
class ActionNodesValues(val oldNodes: List<Node>, val newNodes: List<Node>)
@@ -0,0 +1,64 @@
/*
* Copyright 2026 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePassDX.
*
* KeePassDX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePassDX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePassDX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node
import android.content.Context
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Entry
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.hardware.HardwareKey
import java.util.UUID
class TouchEntryRunnable(
context: Context,
database: ContextualDatabase,
oldEntryId: NodeId<UUID>,
afterActionNodesFinish: AfterActionNodesFinish?,
challengeResponseRetriever: (HardwareKey, ByteArray?) -> ByteArray
) : ActionNodeDatabaseRunnable(
context,
database,
afterActionNodesFinish,
save = false,
challengeResponseRetriever
) {
private var mEntry: Entry? = null
init {
database.getEntryById(oldEntryId)?.let { entry ->
mEntry = entry
}
}
override fun nodeAction() {
mEntry?.let { entry ->
entry.touch(modified = false, touchParents = true)
database.updateEntry(entry = entry, dataModified = false)
}
}
override fun nodeFinish(): ActionNodesValues {
return ActionNodesValues(
oldNodes = mEntry?.let { listOf(it) } ?: listOf(),
newNodes = listOf()
)
}
}
@@ -0,0 +1,64 @@
/*
* Copyright 2026 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePassDX.
*
* KeePassDX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePassDX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePassDX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.action.node
import android.content.Context
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Group
import com.kunzisoft.keepass.database.element.node.Node
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.hardware.HardwareKey
class TouchGroupRunnable(
context: Context,
database: ContextualDatabase,
groupId: NodeId<*>,
afterActionNodesFinish: AfterActionNodesFinish?,
challengeResponseRetriever: (HardwareKey, ByteArray?) -> ByteArray
) : ActionNodeDatabaseRunnable(
context,
database,
afterActionNodesFinish,
save = false,
challengeResponseRetriever
) {
private var mGroup: Group? = null
init {
database.getGroupById(groupId)?.let { oldGroupToUpdate ->
mGroup = oldGroupToUpdate
}
}
override fun nodeAction() {
mGroup?.let { group ->
group.touch(modified = false, touchParents = true)
database.updateGroup(group = group, dataModified = false)
}
}
override fun nodeFinish(): ActionNodesValues {
return ActionNodesValues(
oldNodes = mGroup?.let { listOf<Node>(it) } ?: listOf(),
newNodes = listOf()
)
}
}
@@ -22,33 +22,48 @@ package com.kunzisoft.keepass.database.action.node
import android.content.Context
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Entry
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.hardware.HardwareKey
import com.kunzisoft.keepass.model.EntryInfo
import java.util.UUID
class UpdateEntryRunnable(
context: Context,
database: ContextualDatabase,
private val mOldEntry: Entry,
private val mNewEntry: Entry,
oldEntryId: NodeId<UUID>,
newEntry: EntryInfo,
save: Boolean,
afterActionNodesFinish: AfterActionNodesFinish?,
challengeResponseRetriever: (HardwareKey, ByteArray?) -> ByteArray
) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save, challengeResponseRetriever) {
private var mOldEntry: Entry? = null
private var mNewEntry: Entry? = null
init {
database.getEntryById(oldEntryId)?.let { oldEntry ->
mOldEntry = oldEntry
}
mNewEntry = database.getEntryFrom(newEntry)
}
override fun nodeAction() {
if (mOldEntry.nodeId == mNewEntry.nodeId) {
val oldEntry = mOldEntry
val newEntry = mNewEntry
if (oldEntry != null && newEntry != null && oldEntry.nodeId == newEntry.nodeId) {
// WARNING : Re attribute parent removed in entry edit activity to save memory
mNewEntry.addParentFrom(mOldEntry)
newEntry.addParentFrom(oldEntry)
// Re-attribute history removed to save memory in Bundle creation
// Clear to be sure
mNewEntry.clearHistory()
mOldEntry.getHistory().forEach {
mNewEntry.addEntryToHistory(it)
newEntry.clearHistory()
oldEntry.getHistory().forEach {
newEntry.addEntryToHistory(it)
}
// Build oldest attachments
val oldEntryAttachments = mOldEntry.getAttachments(database.attachmentPool, true)
val newEntryAttachments = mNewEntry.getAttachments(database.attachmentPool, true)
val oldEntryAttachments = oldEntry.getAttachments(database.attachmentPool, true)
val newEntryAttachments = newEntry.getAttachments(database.attachmentPool, true)
val attachmentsToRemove = oldEntryAttachments.toMutableList()
// Not use equals because only check name
newEntryAttachments.forEach { newAttachment ->
@@ -61,14 +76,14 @@ class UpdateEntryRunnable(
}
// Update entry with new values
mNewEntry.touch(modified = true, touchParents = true)
newEntry.touch(modified = true, touchParents = true)
// Create an entry history (an entry history don't have history)
mNewEntry.addEntryToHistory(Entry(mOldEntry, copyHistory = false))
database.removeOldestEntryHistory(mNewEntry, database.attachmentPool)
newEntry.addEntryToHistory(Entry(oldEntry, copyHistory = false))
database.removeOldestEntryHistory(newEntry, database.attachmentPool)
// Only change data in index
database.updateEntry(mNewEntry)
database.updateEntry(newEntry)
// Remove oldest attachments
attachmentsToRemove.forEach {
@@ -80,8 +95,13 @@ class UpdateEntryRunnable(
override fun nodeFinish(): ActionNodesValues {
if (!result.isSuccess) {
// If we fail to save, back out changes to global structure
database.updateEntry(mOldEntry)
mOldEntry?.let { oldEntry ->
database.updateEntry(oldEntry)
}
}
return ActionNodesValues(listOf(mOldEntry), listOf(mNewEntry))
return ActionNodesValues(
oldNodes = mOldEntry?.let { listOf(it) } ?: listOf(),
newNodes = mNewEntry?.let { listOf(it) } ?: listOf()
)
}
}
@@ -23,32 +23,48 @@ import android.content.Context
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Group
import com.kunzisoft.keepass.database.element.node.Node
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.hardware.HardwareKey
import com.kunzisoft.keepass.model.GroupInfo
class UpdateGroupRunnable constructor(
class UpdateGroupRunnable(
context: Context,
database: ContextualDatabase,
private val mOldGroup: Group,
private val mNewGroup: Group,
oldGroupId: NodeId<*>,
newGroup: GroupInfo,
save: Boolean,
afterActionNodesFinish: AfterActionNodesFinish?,
challengeResponseRetriever: (HardwareKey, ByteArray?) -> ByteArray
) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save, challengeResponseRetriever) {
private var mOldGroup: Group? = null
private var mNewGroup: Group? = null
init {
database.getGroupById(oldGroupId)?.let { oldGroupToUpdate ->
mOldGroup = oldGroupToUpdate
}
mNewGroup = database.getGroupFrom(newGroup)
}
override fun nodeAction() {
if (mOldGroup.nodeId == mNewGroup.nodeId) {
// WARNING : Re attribute parent and children removed in group activity to save memory
mNewGroup.addParentFrom(mOldGroup)
mNewGroup.addChildrenFrom(mOldGroup)
mOldGroup?.let { oldGroup ->
mNewGroup?.let { newGroup ->
if (oldGroup.nodeId == newGroup.nodeId) {
// WARNING : Re attribute parent and children removed in group activity to save memory
newGroup.addParentFrom(oldGroup)
newGroup.addChildrenFrom(oldGroup)
// Update group with new values
mNewGroup.touch(modified = true, touchParents = true)
// Update group with new values
newGroup.touch(modified = true, touchParents = true)
if (database.rootGroup == mOldGroup) {
database.rootGroup = mNewGroup
if (database.rootGroup == oldGroup) {
database.rootGroup = newGroup
}
// Only change data in index
database.updateGroup(newGroup)
}
}
// Only change data in index
database.updateGroup(mNewGroup)
}
}
@@ -58,11 +74,13 @@ class UpdateGroupRunnable constructor(
if (database.rootGroup == mNewGroup) {
database.rootGroup = mOldGroup
}
database.updateGroup(mOldGroup)
mOldGroup?.let { oldGroup ->
database.updateGroup(oldGroup)
}
}
return ActionNodesValues(
listOf<Node>(mOldGroup),
listOf<Node>(mNewGroup)
oldNodes = mOldGroup?.let { listOf<Node>(it) } ?: listOf(),
newNodes = mNewGroup?.let { listOf<Node>(it) } ?: listOf()
)
}
}
@@ -53,6 +53,8 @@ import com.kunzisoft.keepass.database.action.node.AfterActionNodesFinish
import com.kunzisoft.keepass.database.action.node.CopyNodesRunnable
import com.kunzisoft.keepass.database.action.node.DeleteNodesRunnable
import com.kunzisoft.keepass.database.action.node.MoveNodesRunnable
import com.kunzisoft.keepass.database.action.node.TouchEntryRunnable
import com.kunzisoft.keepass.database.action.node.TouchGroupRunnable
import com.kunzisoft.keepass.database.action.node.UpdateEntryRunnable
import com.kunzisoft.keepass.database.action.node.UpdateGroupRunnable
import com.kunzisoft.keepass.database.element.Entry
@@ -63,6 +65,8 @@ import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.database.element.node.Type
import com.kunzisoft.keepass.hardware.HardwareKey
import com.kunzisoft.keepass.model.CipherEncryptDatabase
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.model.GroupInfo
import com.kunzisoft.keepass.model.SnapFileDatabaseInfo
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.tasks.ActionRunnable
@@ -350,8 +354,10 @@ open class DatabaseTaskNotificationService : LockNotificationService(), Progress
ACTION_DATABASE_ASSIGN_CREDENTIAL_TASK -> buildDatabaseAssignCredentialActionTask(intent, database)
ACTION_DATABASE_CREATE_GROUP_TASK -> buildDatabaseCreateGroupActionTask(intent, database)
ACTION_DATABASE_UPDATE_GROUP_TASK -> buildDatabaseUpdateGroupActionTask(intent, database)
ACTION_DATABASE_TOUCH_GROUP_TASK -> buildDatabaseTouchGroupActionTask(intent, database)
ACTION_DATABASE_CREATE_ENTRY_TASK -> buildDatabaseCreateEntryActionTask(intent, database)
ACTION_DATABASE_UPDATE_ENTRY_TASK -> buildDatabaseUpdateEntryActionTask(intent, database)
ACTION_DATABASE_TOUCH_ENTRY_TASK -> buildDatabaseTouchEntryActionTask(intent, database)
ACTION_DATABASE_COPY_NODES_TASK -> buildDatabaseCopyNodesActionTask(intent, database)
ACTION_DATABASE_MOVE_NODES_TASK -> buildDatabaseMoveNodesActionTask(intent, database)
ACTION_DATABASE_DELETE_NODES_TASK -> buildDatabaseDeleteNodesActionTask(intent, database)
@@ -972,19 +978,18 @@ open class DatabaseTaskNotificationService : LockNotificationService(), Progress
&& intent.hasExtra(SAVE_DATABASE_KEY)
) {
val parentId: NodeId<*>? = intent.getParcelableExtraCompat(PARENT_ID_KEY)
val newGroup: Group? = intent.getParcelableExtraCompat(GROUP_KEY)
val newGroup: GroupInfo? = intent.getParcelableExtraCompat(GROUP_KEY)
if (parentId == null || newGroup == null) return null
val saveDatabase = intent.getBooleanExtra(SAVE_DATABASE_KEY, false)
database.getGroupById(parentId)?.let { parent ->
AddGroupRunnable(this,
database,
newGroup,
parent,
!database.isReadOnly && saveDatabase,
AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
AddGroupRunnable(
context = this,
database = database,
parentId = parentId,
newGroup = newGroup,
save = !database.isReadOnly && saveDatabase,
afterActionNodesFinish = AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
} else {
null
@@ -1000,19 +1005,37 @@ open class DatabaseTaskNotificationService : LockNotificationService(), Progress
&& intent.hasExtra(SAVE_DATABASE_KEY)
) {
val groupId: NodeId<*>? = intent.getParcelableExtraCompat(GROUP_ID_KEY)
val newGroup: Group? = intent.getParcelableExtraCompat(GROUP_KEY)
val newGroup: GroupInfo? = intent.getParcelableExtraCompat(GROUP_KEY)
if (groupId == null || newGroup == null) return null
val saveDatabase = intent.getBooleanExtra(SAVE_DATABASE_KEY, false)
database.getGroupById(groupId)?.let { oldGroup ->
UpdateGroupRunnable(this,
database,
oldGroup,
newGroup,
!database.isReadOnly && saveDatabase,
AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
UpdateGroupRunnable(
context = this,
database = database,
oldGroupId = groupId,
newGroup = newGroup,
save = !database.isReadOnly && saveDatabase,
afterActionNodesFinish = AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
} else {
null
}
}
private fun buildDatabaseTouchGroupActionTask(
intent: Intent,
database: ContextualDatabase,
): ActionRunnable? {
return if (intent.hasExtra(GROUP_ID_KEY)) {
val groupId: NodeId<*> = intent.getParcelableExtraCompat(GROUP_ID_KEY) ?: return null
TouchGroupRunnable(
context = this,
database = database,
groupId = groupId,
afterActionNodesFinish = AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
} else {
null
@@ -1028,19 +1051,18 @@ open class DatabaseTaskNotificationService : LockNotificationService(), Progress
&& intent.hasExtra(SAVE_DATABASE_KEY)
) {
val parentId: NodeId<*>? = intent.getParcelableExtraCompat(PARENT_ID_KEY)
val newEntry: Entry? = intent.getParcelableExtraCompat(ENTRY_KEY)
val newEntry: EntryInfo? = intent.getParcelableExtraCompat(ENTRY_KEY)
if (parentId == null || newEntry == null) return null
val saveDatabase = intent.getBooleanExtra(SAVE_DATABASE_KEY, false)
database.getGroupById(parentId)?.let { parent ->
AddEntryRunnable(this,
database,
newEntry,
parent,
!database.isReadOnly && saveDatabase,
AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
AddEntryRunnable(
context = this,
database = database,
parentId = parentId,
newEntry = newEntry,
save = !database.isReadOnly && saveDatabase,
afterActionNodesFinish = AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
} else {
null
@@ -1056,19 +1078,38 @@ open class DatabaseTaskNotificationService : LockNotificationService(), Progress
&& intent.hasExtra(SAVE_DATABASE_KEY)
) {
val entryId: NodeId<UUID>? = intent.getParcelableExtraCompat(ENTRY_ID_KEY)
val newEntry: Entry? = intent.getParcelableExtraCompat(ENTRY_KEY)
val newEntry: EntryInfo? = intent.getParcelableExtraCompat(ENTRY_KEY)
if (entryId == null || newEntry == null) return null
val saveDatabase = intent.getBooleanExtra(SAVE_DATABASE_KEY, false)
database.getEntryById(entryId)?.let { oldEntry ->
UpdateEntryRunnable(this,
database,
oldEntry,
newEntry,
!database.isReadOnly && saveDatabase,
AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
UpdateEntryRunnable(
context = this,
database = database,
oldEntryId = entryId,
newEntry = newEntry,
save = !database.isReadOnly && saveDatabase,
afterActionNodesFinish = AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
} else {
null
}
}
private fun buildDatabaseTouchEntryActionTask(
intent: Intent,
database: ContextualDatabase,
): ActionRunnable? {
return if (intent.hasExtra(ENTRY_ID_KEY)
) {
val entryId: NodeId<UUID> = intent.getParcelableExtraCompat(ENTRY_ID_KEY) ?: return null
TouchEntryRunnable(
context = this,
database = database,
oldEntryId = entryId,
afterActionNodesFinish = AfterActionNodesRunnable()
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
} else {
null
@@ -1162,15 +1203,13 @@ open class DatabaseTaskNotificationService : LockNotificationService(), Progress
) {
val entryId: NodeId<UUID> = intent.getParcelableExtraCompat(ENTRY_ID_KEY) ?: return null
val saveDatabase = intent.getBooleanExtra(SAVE_DATABASE_KEY, false)
database.getEntryById(entryId)?.let { mainEntry ->
RestoreEntryHistoryDatabaseRunnable(this,
database,
mainEntry,
intent.getIntExtra(ENTRY_HISTORY_POSITION_KEY, -1),
!database.isReadOnly && saveDatabase
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
RestoreEntryHistoryDatabaseRunnable(this,
database = database,
entryId = entryId,
entryHistoryPosition = intent.getIntExtra(ENTRY_HISTORY_POSITION_KEY, -1),
save = !database.isReadOnly && saveDatabase
) { hardwareKey, seed ->
retrieveResponseFromChallenge(hardwareKey, seed)
}
} else {
null
@@ -1340,8 +1379,10 @@ open class DatabaseTaskNotificationService : LockNotificationService(), Progress
const val ACTION_DATABASE_ASSIGN_CREDENTIAL_TASK = "ACTION_DATABASE_ASSIGN_CREDENTIAL_TASK"
const val ACTION_DATABASE_CREATE_GROUP_TASK = "ACTION_DATABASE_CREATE_GROUP_TASK"
const val ACTION_DATABASE_UPDATE_GROUP_TASK = "ACTION_DATABASE_UPDATE_GROUP_TASK"
const val ACTION_DATABASE_TOUCH_GROUP_TASK = "ACTION_DATABASE_TOUCH_GROUP_TASK"
const val ACTION_DATABASE_CREATE_ENTRY_TASK = "ACTION_DATABASE_CREATE_ENTRY_TASK"
const val ACTION_DATABASE_UPDATE_ENTRY_TASK = "ACTION_DATABASE_UPDATE_ENTRY_TASK"
const val ACTION_DATABASE_TOUCH_ENTRY_TASK = "ACTION_DATABASE_TOUCH_ENTRY_TASK"
const val ACTION_DATABASE_COPY_NODES_TASK = "ACTION_DATABASE_COPY_NODES_TASK"
const val ACTION_DATABASE_MOVE_NODES_TASK = "ACTION_DATABASE_MOVE_NODES_TASK"
const val ACTION_DATABASE_DELETE_NODES_TASK = "ACTION_DATABASE_DELETE_NODES_TASK"
@@ -520,6 +520,10 @@ abstract class TemplateAbstractView<
}
retrieveCustomFieldsFromView(templateFieldNotEmpty, retrieveDefaultValues)
mTemplate?.let {
mEntryInfo?.template = it
}
}
fun getEntryInfo(): EntryInfo {
@@ -10,13 +10,15 @@ import com.kunzisoft.keepass.database.MainCredential
import com.kunzisoft.keepass.database.ProgressMessage
import com.kunzisoft.keepass.database.crypto.EncryptionAlgorithm
import com.kunzisoft.keepass.database.crypto.kdf.KdfEngine
import com.kunzisoft.keepass.database.element.Entry
import com.kunzisoft.keepass.database.element.Group
import com.kunzisoft.keepass.database.element.binary.BinaryData
import com.kunzisoft.keepass.database.element.database.CompressionAlgorithm
import com.kunzisoft.keepass.database.element.node.Node
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.database.element.node.NodeIdUUID
import com.kunzisoft.keepass.model.CipherEncryptDatabase
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.model.GroupInfo
import com.kunzisoft.keepass.model.SnapFileDatabaseInfo
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService
import com.kunzisoft.keepass.tasks.ActionRunnable
@@ -169,31 +171,33 @@ class DatabaseViewModel(application: Application): AndroidViewModel(application)
*/
fun createEntry(
newEntry: Entry,
parent: Group,
parentId: NodeId<*>,
newEntry: EntryInfo,
save: Boolean
) {
mDatabaseTaskProvider.startDatabaseCreateEntry(
newEntry,
parent,
save
parentId = parentId,
newEntry = newEntry,
save = save
)
}
fun updateEntry(
oldEntry: Entry,
entryToUpdate: Entry,
oldEntryId: NodeId<UUID>,
updateEntry: EntryInfo,
save: Boolean
) {
// Remove the history to keep memory
entryToUpdate.clearHistory()
mDatabaseTaskProvider.startDatabaseUpdateEntry(
oldEntry,
entryToUpdate,
save
oldEntryId = oldEntryId,
updateEntry = updateEntry,
save = save
)
}
fun touchEntry(entryInfo: EntryInfo) {
mDatabaseTaskProvider.startDatabaseTouchEntry(entryId = entryInfo.nodeId)
}
fun restoreEntryHistory(
mainEntryId: NodeId<UUID>,
entryHistoryPosition: Int,
@@ -219,27 +223,40 @@ class DatabaseViewModel(application: Application): AndroidViewModel(application)
}
fun createGroup(
newGroup: Group,
parent: Group,
parentId: NodeId<*>,
newGroup: GroupInfo,
save: Boolean
) {
mDatabaseTaskProvider.startDatabaseCreateGroup(
newGroup,
parent,
save
)
if (newGroup.title.isNotEmpty()) {
mDatabaseTaskProvider.startDatabaseCreateGroup(
parentId = parentId,
newGroup = newGroup,
save = save
)
}
}
fun updateGroup(
oldGroup: Group,
groupToUpdate: Group,
oldGroupId: NodeId<*>,
updateGroup: GroupInfo,
save: Boolean
) {
mDatabaseTaskProvider.startDatabaseUpdateGroup(
oldGroup,
groupToUpdate,
save
)
if (updateGroup.title.isNotEmpty()) {
mDatabaseTaskProvider.startDatabaseUpdateGroup(
oldGroupId = oldGroupId,
updateGroup = updateGroup,
save = save
)
}
}
fun touchGroup(
groupInfo: GroupInfo
) {
// Implicitly filters KDB databases
groupInfo.id?.let { groupId ->
mDatabaseTaskProvider.startDatabaseTouchGroup(groupId = NodeIdUUID(groupId))
}
}
fun copyNodes(
@@ -13,12 +13,10 @@ import com.kunzisoft.keepass.database.element.icon.IconImage
import com.kunzisoft.keepass.database.element.icon.IconImageStandard
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.database.element.template.Template
import com.kunzisoft.keepass.model.AttachmentState
import com.kunzisoft.keepass.model.EntryAttachmentState
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.model.FieldProtection
import com.kunzisoft.keepass.model.RegisterInfo
import com.kunzisoft.keepass.model.StreamDirection
import com.kunzisoft.keepass.otp.OtpElement
import com.kunzisoft.keepass.utils.IOActionTask
import kotlinx.coroutines.flow.MutableStateFlow
@@ -41,7 +39,6 @@ class EntryEditViewModel: NodeEditViewModel() {
private set
var allowOTP: Boolean = false
private set
private val mTempAttachments = mutableListOf<EntryAttachmentState>()
var passwordField: Field? = null
@@ -58,8 +55,6 @@ class EntryEditViewModel: NodeEditViewModel() {
val requestEntryInfoUpdate : LiveData<Void?> get() = _requestEntryInfoUpdate
private val _requestEntryInfoUpdate = SingleLiveEvent<Void?>()
val onEntrySaved : LiveData<EntrySave> get() = _onEntrySaved
private val _onEntrySaved = SingleLiveEvent<EntrySave>()
val onTemplateChanged : LiveData<Template> get() = _onTemplateChanged
private val _onTemplateChanged = MutableLiveData<Template>()
@@ -115,6 +110,7 @@ class EntryEditViewModel: NodeEditViewModel() {
this.mParentId = parentId
this.mRegisterInfo = registerInfo
// TODO Move in Database
database?.let {
mEntryId?.let {
IOActionTask(
@@ -203,27 +199,22 @@ class EntryEditViewModel: NodeEditViewModel() {
registerInfo: RegisterInfo?
): TemplatesEntry {
val templates = database.getTemplates(isTemplate)
val entryTemplate = entry?.let { database.getTemplate(it) }
?: Template.STANDARD
var entryInfo: EntryInfo? = null
var overwrittenData = false
// Decode the entry / load entry info
entry?.let {
database.decodeEntryWithTemplateConfiguration(it).let { entry ->
// Load entry info
entry.getEntryInfo(database, true).let { tempEntryInfo ->
// Retrieve data from registration
registerInfo?.let { regInfo ->
overwrittenData = tempEntryInfo.saveRegisterInfo(database, regInfo)
}
entryInfo = tempEntryInfo
database.getEntryInfoFrom(entry = it, raw = true).let { tempEntryInfo ->
// Retrieve data from registration
registerInfo?.let { regInfo ->
overwrittenData = tempEntryInfo.saveRegisterInfo(database, regInfo)
}
entryInfo = tempEntryInfo
}
}
return TemplatesEntry(
template = onTemplateChanged.value,
templates = templates,
defaultTemplate = entryTemplate,
defaultTemplate = entryInfo?.template ?: Template.STANDARD,
entryInfo = entryInfo,
overwrittenData = overwrittenData
)
@@ -246,69 +237,16 @@ class EntryEditViewModel: NodeEditViewModel() {
fun saveEntryInfo(entryInfo: EntryInfo) {
if (actionLocked.not()) {
actionLocked = true
IOActionTask(
scope = viewModelScope,
action = {
removeTempAttachmentsNotCompleted(entryInfo)
mDatabase?.let { database ->
mEntry?.let { oldEntry ->
// Create a clone
var newEntry = Entry(oldEntry)
// Build info
newEntry.setEntryInfo(database, entryInfo)
// Encode entry properties for template
_onTemplateChanged.value?.let { template ->
newEntry = database.encodeEntryWithTemplateConfiguration(
newEntry,
template
)
}
// Delete temp attachment if not used
mTempAttachments.forEach { tempAttachmentState ->
val tempAttachment = tempAttachmentState.attachment
database.attachmentPool.let { binaryPool ->
if (!newEntry.getAttachments(binaryPool)
.contains(tempAttachment)
) {
database.removeAttachmentIfNotUsed(tempAttachment)
}
}
}
// Return entry to save
EntrySave(oldEntry, newEntry, mParent)
}
}
},
onActionComplete = { entrySave ->
entrySave?.let {
_onEntrySaved.value = it
}
}
).execute()
}
}
private fun removeTempAttachmentsNotCompleted(entryInfo: EntryInfo) {
// Do not save entry in upload progression
mTempAttachments.forEach { attachmentState ->
if (attachmentState.streamDirection == StreamDirection.UPLOAD) {
when (attachmentState.downloadState) {
AttachmentState.START,
AttachmentState.IN_PROGRESS,
AttachmentState.CANCELED,
AttachmentState.ERROR -> {
// Remove attachment not finished from info
entryInfo.attachments = entryInfo.attachments.toMutableList().apply {
remove(attachmentState.attachment)
}
}
else -> {
}
}
mParent?.nodeId?.let { parentId ->
mEntryEditState.value = EntryEditState.CreateEntry(
parentId = parentId,
newEntry = entryInfo
)
} ?: mEntry?.nodeId?.let { oldEntryId ->
mEntryEditState.value = EntryEditState.UpdateEntry(
oldEntryId = oldEntryId,
updateEntry = entryInfo
)
}
}
}
@@ -367,12 +305,14 @@ class EntryEditViewModel: NodeEditViewModel() {
}
fun onAttachmentAction(entryAttachmentState: EntryAttachmentState?) {
// Add in temp list
if (mTempAttachments.contains(entryAttachmentState)) {
mTempAttachments.remove(entryAttachmentState)
}
if (entryAttachmentState != null) {
mTempAttachments.add(entryAttachmentState)
mDatabase?.tempAttachments?.let { tempAttachments ->
// Add in temp list
if (tempAttachments.contains(entryAttachmentState)) {
tempAttachments.remove(entryAttachmentState)
}
if (entryAttachmentState != null) {
tempAttachments.add(entryAttachmentState)
}
}
_onAttachmentAction.value = entryAttachmentState
}
@@ -418,7 +358,6 @@ class EntryEditViewModel: NodeEditViewModel() {
val entryInfo: EntryInfo?,
val overwrittenData: Boolean = false
)
data class EntrySave(val oldEntry: Entry, val newEntry: Entry, val parent: Group?)
data class FieldEdition(val oldField: Field?, val newField: Field?)
data class AttachmentBuild(val attachmentToUploadUri: Uri, val fileName: String)
data class AttachmentUpload(val attachmentToUploadUri: Uri, val attachment: Attachment)
@@ -433,6 +372,12 @@ class EntryEditViewModel: NodeEditViewModel() {
data class OnFieldProtectionUpdated(
val fieldProtection: FieldProtection
): EntryEditState()
data class CreateEntry(
val parentId: NodeId<*>, val newEntry: EntryInfo
): EntryEditState()
data class UpdateEntry(
val oldEntryId: NodeId<UUID>, val updateEntry: EntryInfo
): EntryEditState()
data class CloseEntry(
val closeType: CloseType
): EntryEditState()
@@ -27,8 +27,6 @@ import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.database.element.Attachment
import com.kunzisoft.keepass.database.element.Field
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.database.element.node.NodeIdUUID
import com.kunzisoft.keepass.database.element.template.Template
import com.kunzisoft.keepass.database.element.template.TemplateField
import com.kunzisoft.keepass.database.helper.getLocalizedName
import com.kunzisoft.keepass.model.EntryAttachmentState
@@ -92,45 +90,22 @@ class EntryViewModel(application: Application): AndroidViewModel(application) {
if (database != null && mainEntryId != null) {
IOActionTask(
{
val mainEntry = database.getEntryById(mainEntryId)
// To sort by access
/* TODO Sort by access #1911, revert because of #2527
if (database.isReadOnly) {
mainEntry?.let {
it.touch(modified = false, touchParents = false)
database.updateEntry(entry = it)
}
}*/
val currentEntry = if (historyPosition > -1) {
mainEntry?.getHistory()?.get(historyPosition)
} else {
mainEntry
}
val entryTemplate = currentEntry?.let {
database.getTemplate(it)
} ?: Template.STANDARD
// To simplify template field visibility
currentEntry?.let { entry ->
// Add mainEntry to check the parent and define the template state
database.decodeEntryWithTemplateConfiguration(entry, mainEntry).let {
// To update current modification time
it.touch(modified = false, touchParents = false)
// Build history info
val entryInfoHistory = it.getHistory().map { entryHistory ->
entryHistory.getEntryInfo(database)
}
EntryInfoHistory(
mainEntry!!.nodeId,
historyPosition,
entryTemplate,
it.getEntryInfo(database),
entryInfoHistory
)
database.getEntryById(mainEntryId)?.let { mainEntry ->
val isHistory = historyPosition > -1
val currentEntry = if (isHistory) {
mainEntry.getHistory()[historyPosition]
} else {
mainEntry
}
// To simplify template field visibility
EntryInfoHistory(
mainEntryId = mainEntry.nodeId,
historyPosition = historyPosition,
entryInfo = database.getEntryInfoFrom(currentEntry),
entryHistory = if (!isHistory)
database.getHistoryEntryInfoFrom(mainEntry)
else listOf()
)
}
},
{ entryInfoHistory ->
@@ -179,7 +154,7 @@ class EntryViewModel(application: Application): AndroidViewModel(application) {
}
fun onHistorySelected(item: EntryInfo, position: Int) {
_historySelected.value = EntryHistory(NodeIdUUID(item.id), null, item, position)
_historySelected.value = EntryHistory(item.nodeId, item, position)
}
fun selectSection(section: EntrySection) {
@@ -202,16 +177,18 @@ class EntryViewModel(application: Application): AndroidViewModel(application) {
mEntryState.value = EntryState.Loading
}
data class EntryInfoHistory(var mainEntryId: NodeId<UUID>,
var historyPosition: Int,
val template: Template,
val entryInfo: EntryInfo,
val entryHistory: List<EntryInfo>)
data class EntryInfoHistory(
var mainEntryId: NodeId<UUID>,
var historyPosition: Int,
val entryInfo: EntryInfo,
val entryHistory: List<EntryInfo>
)
// Custom data class to manage entry to retrieve and define is it's an history item (!= -1)
data class EntryHistory(var nodeId: NodeId<UUID>,
var template: Template?,
var entryInfo: EntryInfo,
var historyPosition: Int = -1)
data class EntryHistory(
var nodeId: NodeId<UUID>,
var entryInfo: EntryInfo,
var historyPosition: Int = -1
)
enum class EntrySection(var position: Int) {
MAIN(0), ADVANCED(1);
@@ -1,29 +1,42 @@
package com.kunzisoft.keepass.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.database.element.node.NodeIdUUID
import com.kunzisoft.keepass.model.GroupInfo
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
class GroupEditViewModel: NodeEditViewModel() {
val groupNamesNotAllowed : LiveData<List<String>?> get() = _groupNamesNotAllowed
private val _groupNamesNotAllowed = MutableLiveData<List<String>?>()
private val mGroupEditState = MutableStateFlow<GroupEditState>(GroupEditState.Wait)
val groupEditState: StateFlow<GroupEditState> = mGroupEditState.asStateFlow()
val onGroupCreated : LiveData<GroupInfo> get() = _onGroupCreated
private val _onGroupCreated = SingleLiveEvent<GroupInfo>()
val onGroupUpdated : LiveData<GroupInfo> get() = _onGroupUpdated
private val _onGroupUpdated = SingleLiveEvent<GroupInfo>()
fun setGroupNamesNotAllowed(groupNames: List<String>?) {
this._groupNamesNotAllowed.value = groupNames
}
var groupNamesNotAllowed : List<String>? = null
fun approveGroupCreation(groupInfo: GroupInfo) {
this._onGroupCreated.value = groupInfo
this.mGroupEditState.value = GroupEditState.CreateGroup(groupInfo)
}
fun approveGroupUpdate(groupInfo: GroupInfo) {
this._onGroupUpdated.value = groupInfo
// Assume it's only possible with UUID in KDBX database
groupInfo.id?.let { groupId ->
this.mGroupEditState.value = GroupEditState.UpdateGroup(NodeIdUUID(groupId), groupInfo)
}
}
fun actionPerformed() {
this.mGroupEditState.value = GroupEditState.Wait
}
sealed class GroupEditState {
object Wait: GroupEditState()
data class CreateGroup(
val groupInfo: GroupInfo
): GroupEditState()
data class UpdateGroup(
var oldGroupId: NodeId<*>,
val groupInfo: GroupInfo
): GroupEditState()
}
}
@@ -173,37 +173,42 @@ open class Database {
}
fun entryIsTemplate(entry: Entry?): Boolean {
// Define is current entry is a template (in direct template group)
// Define if current entry is a template (in direct template group)
if (entry == null || templatesGroup == null)
return false
return templatesGroup == entry.parent
}
// Not the same as decode, here remove in all cases the template link in the entry data
fun removeTemplateConfiguration(entry: Entry): Entry {
entry.entryKDBX?.let {
mDatabaseKDBX?.decodeEntryWithTemplateConfiguration(it, false)?.let { decode ->
return Entry(decode)
}
}
return entry
// Retrieve the main historic entry to check if it's a template
val mainEntry = if (entry.isHistoric()) {
getEntryById(entry.getMainEntryHistoryId()) ?: entry
} else entry
return templatesGroup == mainEntry.parent
}
// Remove the template link in the entry data if it's a basic entry
// or compress the template fields (as pseudo language) if it's a template entry
fun decodeEntryWithTemplateConfiguration(entry: Entry, lastEntryVersion: Entry? = null): Entry {
fun decodeEntryWithTemplateConfiguration(
entry: Entry
): Entry {
entry.entryKDBX?.let {
val lastEntry = lastEntryVersion ?: entry
mDatabaseKDBX?.decodeEntryWithTemplateConfiguration(it, entryIsTemplate(lastEntry))?.let { decode ->
mDatabaseKDBX?.decodeEntryWithTemplateConfiguration(
entryKDBX = it,
entryIsTemplate = entryIsTemplate(entry)
)?.let { decode ->
return Entry(decode)
}
}
return entry
}
fun encodeEntryWithTemplateConfiguration(entry: Entry, template: Template): Entry {
fun encodeEntryWithTemplateConfiguration(
entry: Entry,
template: Template
): Entry {
entry.entryKDBX?.let {
mDatabaseKDBX?.encodeEntryWithTemplateConfiguration(it, entryIsTemplate(entry), template)?.let { encode ->
mDatabaseKDBX?.encodeEntryWithTemplateConfiguration(
entryKDBX = it,
entryIsTemplate = entryIsTemplate(entry),
template = template
)?.let { encode ->
return Entry(encode)
}
}
@@ -1083,8 +1088,8 @@ open class Database {
entry.afterAssignNewParent()
}
fun updateEntry(entry: Entry) {
dataModifiedSinceLastLoading = true
fun updateEntry(entry: Entry, dataModified: Boolean = true) {
dataModifiedSinceLastLoading = dataModified
entry.entryKDB?.let { entryKDB ->
mDatabaseKDB?.updateEntry(entryKDB)
}
@@ -1115,8 +1120,8 @@ open class Database {
group.afterAssignNewParent()
}
fun updateGroup(group: Group) {
dataModifiedSinceLastLoading = true
fun updateGroup(group: Group, dataModified: Boolean = true) {
dataModifiedSinceLastLoading = dataModified
group.groupKDB?.let { entryKDB ->
mDatabaseKDB?.updateGroup(entryKDB)
}
@@ -1142,7 +1147,7 @@ open class Database {
* @param newParent
*/
fun copyEntryTo(entryToCopy: Entry, newParent: Group): Entry {
val entryCopied = Entry(entryToCopy, false)
val entryCopied = Entry(entryToCopy, copyHistory = false)
entryCopied.nodeId = mDatabaseKDB?.newEntryId() ?: mDatabaseKDBX?.newEntryId() ?: NodeIdUUID()
entryCopied.parent = newParent
entryCopied.title += " (~)"
@@ -45,6 +45,7 @@ import com.kunzisoft.keepass.otp.OtpEntryFields
import com.kunzisoft.keepass.utils.StringUtil.toFormattedColorInt
import com.kunzisoft.keepass.utils.StringUtil.toFormattedColorString
import com.kunzisoft.keepass.utils.readParcelableCompat
import java.io.IOException
import java.util.UUID
class Entry : Node, EntryVersionedInterface<Group> {
@@ -422,6 +423,8 @@ class Entry : Node, EntryVersionedInterface<Group> {
}
fun getHistory(): List<Entry> {
if (isHistoric())
throw IOException("Cannot get history from a historical entry")
val history = mutableListOf<Entry>()
val entryKDBXHistory = entryKDBX?.history ?: listOf()
for (entryHistory in entryKDBXHistory) {
@@ -430,6 +433,14 @@ class Entry : Node, EntryVersionedInterface<Group> {
return history
}
fun getMainEntryHistoryId(): NodeId<UUID> {
return entryKDBX?.historyMainEntryId?.let { NodeIdUUID(it) } ?: nodeId
}
fun isHistoric(): Boolean {
return entryKDBX?.isHistoric() ?: false
}
fun addEntryToHistory(entry: Entry) {
entry.entryKDBX?.let {
entryKDBX?.addEntryToHistory(it)
@@ -468,15 +479,16 @@ class Entry : Node, EntryVersionedInterface<Group> {
* Retrieve generated entry info.
* If are not [raw] data, remove parameter fields and add auto generated elements in auto custom fields
*/
fun getEntryInfo(database: Database?,
raw: Boolean = false,
removeTemplateConfiguration: Boolean = true): EntryInfo {
fun getEntryInfo(
database: Database?,
raw: Boolean = false
): EntryInfo {
val entryInfo = EntryInfo()
// Remove unwanted template fields
val baseInfo = if (removeTemplateConfiguration)
database?.removeTemplateConfiguration(this) ?: this
else
this
// Fetch template and remove unwanted template fields
database?.getTemplate(this)?.let {
entryInfo.template = it
}
val baseInfo = database?.decodeEntryWithTemplateConfiguration(entry = this) ?: this
baseInfo.apply {
if (raw)
database?.stopManageEntry(this)
@@ -554,6 +566,12 @@ class Entry : Node, EntryVersionedInterface<Group> {
}
database?.stopManageEntry(this)
// Encode entry properties for template
entryKDBX = database?.encodeEntryWithTemplateConfiguration(
entry = this,
template = newEntryInfo.template
)?.entryKDBX
}
override fun equals(other: Any?): Boolean {
@@ -64,6 +64,7 @@ class EntryKDBX : EntryVersioned<UUID, UUID, GroupKDBX, EntryKDBX>, NodeKDBXInte
override var previousParentGroup: UUID = DatabaseVersioned.UUID_ZERO
var qualityCheck = true
var autoType = AutoType()
var historyMainEntryId: UUID? = null
var history = mutableListOf<EntryKDBX>()
var additional = ""
@@ -81,8 +82,9 @@ class EntryKDBX : EntryVersioned<UUID, UUID, GroupKDBX, EntryKDBX>, NodeKDBXInte
backgroundColor = parcel.readString() ?: backgroundColor
overrideURL = parcel.readString() ?: overrideURL
tags = parcel.readParcelableCompat() ?: tags
previousParentGroup = parcel.readParcelableCompat<ParcelUuid>()?.uuid ?: DatabaseVersioned.UUID_ZERO
previousParentGroup = parcel.readParcelableCompat<ParcelUuid>()?.uuid ?: previousParentGroup
autoType = parcel.readParcelableCompat() ?: autoType
historyMainEntryId = parcel.readParcelableCompat<ParcelUuid>()?.uuid ?: historyMainEntryId
parcel.readTypedList(history, CREATOR)
additional = parcel.readString() ?: additional
}
@@ -108,6 +110,7 @@ class EntryKDBX : EntryVersioned<UUID, UUID, GroupKDBX, EntryKDBX>, NodeKDBXInte
dest.writeParcelable(tags, flags)
dest.writeParcelable(ParcelUuid(previousParentGroup), flags)
dest.writeParcelable(autoType, flags)
dest.writeParcelable(ParcelUuid(historyMainEntryId), flags)
dest.writeTypedList(history)
dest.writeString(additional)
}
@@ -116,9 +119,11 @@ class EntryKDBX : EntryVersioned<UUID, UUID, GroupKDBX, EntryKDBX>, NodeKDBXInte
* Update with deep copy of each entry element
* @param source
*/
fun updateWith(source: EntryKDBX,
copyHistory: Boolean = true,
updateParents: Boolean = true) {
fun updateWith(
source: EntryKDBX,
copyHistory: Boolean = true,
updateParents: Boolean = true
) {
super.updateWith(source, updateParents)
usageCount = source.usageCount
locationChanged = DateInstant(source.locationChanged)
@@ -133,6 +138,7 @@ class EntryKDBX : EntryVersioned<UUID, UUID, GroupKDBX, EntryKDBX>, NodeKDBXInte
tags = source.tags
previousParentGroup = source.previousParentGroup
autoType = AutoType(source.autoType)
historyMainEntryId = source.historyMainEntryId
history.clear()
if (copyHistory)
history.addAll(source.history)
@@ -354,7 +360,16 @@ class EntryKDBX : EntryVersioned<UUID, UUID, GroupKDBX, EntryKDBX>, NodeKDBXInte
return size
}
fun isHistoric(): Boolean {
return historyMainEntryId != null
}
fun addEntryToHistory(entry: EntryKDBX) {
// The current entry is no longer part of the history once we add a history entry to it
// And the history entry we add must not contain any history in it
historyMainEntryId = null
entry.clearHistory()
entry.historyMainEntryId = nodeId.id
history.add(entry)
}
@@ -529,7 +529,7 @@ class DatabaseKDBXMerger(private var database: DatabaseKDBX) {
}
/**
* Utility method to merge an history from an [entryA]
* Utility method to merge a history from an [entryA]
*/
private fun EntryKDBX.addHistoryFrom(entryA: EntryKDBX) {
// Keep entry as history if already not present
@@ -27,6 +27,9 @@ import com.kunzisoft.keepass.database.element.Database
import com.kunzisoft.keepass.database.element.Field
import com.kunzisoft.keepass.database.element.Tags
import com.kunzisoft.keepass.database.element.entry.AutoType
import com.kunzisoft.keepass.database.element.node.NodeId
import com.kunzisoft.keepass.database.element.node.NodeIdUUID
import com.kunzisoft.keepass.database.element.template.Template
import com.kunzisoft.keepass.model.AppOriginEntryField.containsDomainOrApplicationId
import com.kunzisoft.keepass.model.AppOriginEntryField.setAppOrigin
import com.kunzisoft.keepass.model.AppOriginEntryField.setApplicationId
@@ -39,11 +42,9 @@ import com.kunzisoft.keepass.otp.OtpEntryFields.OTP_TOKEN_FIELD
import com.kunzisoft.keepass.otp.OtpEntryFields.isOTP
import com.kunzisoft.keepass.otp.OtpEntryFields.setOtp
import com.kunzisoft.keepass.utils.CharArrayUtil.clear
import com.kunzisoft.keepass.utils.readBooleanCompat
import com.kunzisoft.keepass.utils.readCharArrayCompat
import com.kunzisoft.keepass.utils.readListCompat
import com.kunzisoft.keepass.utils.readParcelableCompat
import com.kunzisoft.keepass.utils.writeBooleanCompat
import com.kunzisoft.keepass.utils.writeCharArrayCompat
import java.util.Locale
import java.util.UUID
@@ -65,7 +66,8 @@ class EntryInfo : NodeInfo {
var creditCard: CreditCard? = null
var passkey: Passkey? = null
var appOrigin: AppOrigin? = null
var isTemplate: Boolean = false
var template: Template = Template.STANDARD
constructor() : super()
@@ -85,7 +87,7 @@ class EntryInfo : NodeInfo {
this.creditCard = entryToCopy.creditCard?.let { CreditCard(it) }
this.passkey = entryToCopy.passkey?.let { Passkey(it) }
this.appOrigin = entryToCopy.appOrigin?.let { AppOrigin(it) }
this.isTemplate = entryToCopy.isTemplate
this.template = entryToCopy.template
}
constructor(parcel: Parcel) : super(parcel) {
@@ -106,7 +108,7 @@ class EntryInfo : NodeInfo {
creditCard = parcel.readParcelableCompat() ?: creditCard
passkey = parcel.readParcelableCompat() ?: passkey
appOrigin = parcel.readParcelableCompat() ?: appOrigin
isTemplate = parcel.readBooleanCompat()
template = parcel.readParcelableCompat() ?: template
}
override fun describeContents(): Int {
@@ -130,9 +132,12 @@ class EntryInfo : NodeInfo {
parcel.writeParcelable(creditCard, flags)
parcel.writeParcelable(passkey, flags)
parcel.writeParcelable(appOrigin, flags)
parcel.writeBooleanCompat(isTemplate)
parcel.writeParcelable(template, flags)
}
val nodeId: NodeId<UUID>
get() = NodeIdUUID(id)
fun clear() {
password.clear()
customFields.forEach { it.clear() }
@@ -314,7 +319,7 @@ class EntryInfo : NodeInfo {
if (creditCard != other.creditCard) return false
if (passkey != other.passkey) return false
if (appOrigin != other.appOrigin) return false
if (isTemplate != other.isTemplate) return false
if (template != other.template) return false
return true
}
@@ -336,7 +341,7 @@ class EntryInfo : NodeInfo {
result = 31 * result + (creditCard?.hashCode() ?: 0)
result = 31 * result + (passkey?.hashCode() ?: 0)
result = 31 * result + (appOrigin?.hashCode() ?: 0)
result = 31 * result + isTemplate.hashCode()
result = 31 * result + template.hashCode()
return result
}