diff --git a/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwDateTest.kt b/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwDateTest.kt index a7269ad1f..eadfbc4eb 100644 --- a/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwDateTest.kt +++ b/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwDateTest.kt @@ -21,15 +21,15 @@ package com.kunzisoft.keepass.tests import junit.framework.TestCase -import com.kunzisoft.keepass.database.element.PwDate +import com.kunzisoft.keepass.database.element.DateInstant import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils import org.junit.Assert class PwDateTest : TestCase() { fun testDate() { - val jDate = PwDate(System.currentTimeMillis()) - val intermediate = PwDate(jDate) + val jDate = DateInstant(System.currentTimeMillis()) + val intermediate = DateInstant(jDate) val cDate = DatabaseInputOutputUtils.readCDate(DatabaseInputOutputUtils.writeCDate(intermediate.date)!!, 0) Assert.assertTrue("jDate and intermediate not equal", jDate == intermediate) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt index a23fe59b3..ede4208a6 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.kt @@ -38,8 +38,8 @@ import com.kunzisoft.keepass.R import com.kunzisoft.keepass.activities.helpers.ReadOnlyHelper import com.kunzisoft.keepass.activities.lock.LockingHideActivity import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.EntryVersioned -import com.kunzisoft.keepass.database.element.PwNodeId +import com.kunzisoft.keepass.database.element.Entry +import com.kunzisoft.keepass.database.element.NodeId import com.kunzisoft.keepass.education.EntryActivityEducation import com.kunzisoft.keepass.icons.assignDatabaseIcon import com.kunzisoft.keepass.magikeyboard.MagikIME @@ -64,7 +64,7 @@ class EntryActivity : LockingHideActivity() { private var mDatabase: Database? = null - private var mEntry: EntryVersioned? = null + private var mEntry: Entry? = null private var mIsHistory: Boolean = false private var mShowPassword: Boolean = false @@ -115,7 +115,7 @@ class EntryActivity : LockingHideActivity() { // Get Entry from UUID try { - val keyEntry: PwNodeId = intent.getParcelableExtra(KEY_ENTRY) + val keyEntry: NodeId = intent.getParcelableExtra(KEY_ENTRY) mEntry = mDatabase?.getEntryById(keyEntry) } catch (e: ClassCastException) { Log.e(TAG, "Unable to retrieve the entry key") @@ -158,7 +158,7 @@ class EntryActivity : LockingHideActivity() { firstLaunchOfActivity = false } - private fun fillEntryDataInContentsView(entry: EntryVersioned) { + private fun fillEntryDataInContentsView(entry: Entry) { val database = Database.getInstance() database.startManageEntry(entry) @@ -453,7 +453,7 @@ class EntryActivity : LockingHideActivity() { const val KEY_ENTRY = "KEY_ENTRY" const val KEY_ENTRY_HISTORY_POSITION = "KEY_ENTRY_HISTORY_POSITION" - fun launch(activity: Activity, entry: EntryVersioned, readOnly: Boolean, historyPosition: Int? = null) { + fun launch(activity: Activity, entry: Entry, readOnly: Boolean, historyPosition: Int? = null) { if (TimeoutHelper.checkTimeAndLockIfTimeout(activity)) { val intent = Intent(activity, EntryActivity::class.java) intent.putExtra(KEY_ENTRY, entry.nodeId) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/EntryEditActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/EntryEditActivity.kt index 71ee6deed..ef1c090bf 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/EntryEditActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/EntryEditActivity.kt @@ -55,10 +55,10 @@ class EntryEditActivity : LockingHideActivity(), private var mDatabase: Database? = null // Refs of an entry and group in database, are not modifiable - private var mEntry: EntryVersioned? = null - private var mParent: GroupVersioned? = null + private var mEntry: Entry? = null + private var mParent: Group? = null // New or copy of mEntry in the database to be modifiable - private var mNewEntry: EntryVersioned? = null + private var mNewEntry: Entry? = null private var mIsNew: Boolean = false // Views @@ -94,7 +94,7 @@ class EntryEditActivity : LockingHideActivity(), mDatabase = Database.getInstance() // Entry is retrieve, it's an entry to update - intent.getParcelableExtra>(KEY_ENTRY)?.let { + intent.getParcelableExtra>(KEY_ENTRY)?.let { mIsNew = false // Create an Entry copy to modify from the database entry mEntry = mDatabase?.getEntryById(it) @@ -114,7 +114,7 @@ class EntryEditActivity : LockingHideActivity(), || !savedInstanceState.containsKey(KEY_NEW_ENTRY)) { mEntry?.let { entry -> // Create a copy to modify - mNewEntry = EntryVersioned(entry).also { newEntry -> + mNewEntry = Entry(entry).also { newEntry -> // WARNING Remove the parent to keep memory with parcelable newEntry.removeParent() } @@ -123,7 +123,7 @@ class EntryEditActivity : LockingHideActivity(), } // Parent is retrieve, it's a new entry to create - intent.getParcelableExtra>(KEY_PARENT)?.let { + intent.getParcelableExtra>(KEY_PARENT)?.let { mIsNew = true // Create an empty new entry if (savedInstanceState == null @@ -183,7 +183,7 @@ class EntryEditActivity : LockingHideActivity(), } } - private fun populateViewsWithEntry(newEntry: EntryVersioned) { + private fun populateViewsWithEntry(newEntry: Entry) { // Don't start the field reference manager, we want to see the raw ref mDatabase?.stopManageEntry(newEntry) @@ -205,7 +205,7 @@ class EntryEditActivity : LockingHideActivity(), } } - private fun populateEntryWithViews(newEntry: EntryVersioned) { + private fun populateEntryWithViews(newEntry: Entry) { mDatabase?.startManageEntry(newEntry) @@ -227,7 +227,7 @@ class EntryEditActivity : LockingHideActivity(), mDatabase?.stopManageEntry(newEntry) } - private fun temporarilySaveAndShowSelectedIcon(icon: PwIcon) { + private fun temporarilySaveAndShowSelectedIcon(icon: IconImage) { mNewEntry?.icon = icon mDatabase?.drawFactory?.let { iconDrawFactory -> entryEditContentsView?.setIcon(iconDrawFactory, icon) @@ -261,8 +261,8 @@ class EntryEditActivity : LockingHideActivity(), // WARNING Add the parent previously deleted newEntry.parent = mEntry?.parent // Build info - newEntry.lastAccessTime = PwDate() - newEntry.lastModificationTime = PwDate() + newEntry.lastAccessTime = DateInstant() + newEntry.lastModificationTime = DateInstant() populateEntryWithViews(newEntry) @@ -439,7 +439,7 @@ class EntryEditActivity : LockingHideActivity(), * @param activity from activity * @param pwEntry Entry to update */ - fun launch(activity: Activity, pwEntry: EntryVersioned) { + fun launch(activity: Activity, pwEntry: Entry) { if (TimeoutHelper.checkTimeAndLockIfTimeout(activity)) { val intent = Intent(activity, EntryEditActivity::class.java) intent.putExtra(KEY_ENTRY, pwEntry.nodeId) @@ -453,7 +453,7 @@ class EntryEditActivity : LockingHideActivity(), * @param activity from activity * @param pwGroup Group who will contains new entry */ - fun launch(activity: Activity, pwGroup: GroupVersioned) { + fun launch(activity: Activity, pwGroup: Group) { if (TimeoutHelper.checkTimeAndLockIfTimeout(activity)) { val intent = Intent(activity, EntryEditActivity::class.java) intent.putExtra(KEY_PARENT, pwGroup.nodeId) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt index 0d115f458..984b07de0 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.kt @@ -94,9 +94,9 @@ class GroupActivity : LockingActivity(), private var mCurrentGroupIsASearch: Boolean = false // Nodes - private var mRootGroup: GroupVersioned? = null - private var mCurrentGroup: GroupVersioned? = null - private var mOldGroupToUpdate: GroupVersioned? = null + private var mRootGroup: Group? = null + private var mCurrentGroup: Group? = null + private var mOldGroupToUpdate: Group? = null private var mSearchSuggestionAdapter: SearchEntryCursorAdapter? = null @@ -194,11 +194,11 @@ class GroupActivity : LockingActivity(), // Init dialog thread mProgressDialogThread?.onActionFinish = { actionTask, result -> - var oldNodes: List = ArrayList() + var oldNodes: List = ArrayList() result.data?.getBundle(OLD_NODES_KEY)?.let { oldNodesBundle -> oldNodes = getListNodesFromBundle(database, oldNodesBundle) } - var newNodes: List = ArrayList() + var newNodes: List = ArrayList() result.data?.getBundle(NEW_NODES_KEY)?.let { newNodesBundle -> newNodes = getListNodesFromBundle(database, newNodesBundle) } @@ -277,7 +277,7 @@ class GroupActivity : LockingActivity(), } } - private fun openSearchGroup(group: GroupVersioned?) { + private fun openSearchGroup(group: Group?) { // Delete the previous search fragment val searchFragment = supportFragmentManager.findFragmentByTag(SEARCH_FRAGMENT_TAG) if (searchFragment != null) { @@ -289,11 +289,11 @@ class GroupActivity : LockingActivity(), openGroup(group, true) } - private fun openChildGroup(group: GroupVersioned) { + private fun openChildGroup(group: Group) { openGroup(group, false) } - private fun openGroup(group: GroupVersioned?, isASearch: Boolean) { + private fun openGroup(group: Group?, isASearch: Boolean) { // Check TimeoutHelper TimeoutHelper.checkTimeAndLockIfTimeoutOrResetTimeout(this) { // Open a group in a new fragment @@ -333,7 +333,7 @@ class GroupActivity : LockingActivity(), super.onSaveInstanceState(outState) } - private fun retrieveCurrentGroup(intent: Intent, savedInstanceState: Bundle?): GroupVersioned? { + private fun retrieveCurrentGroup(intent: Intent, savedInstanceState: Bundle?): Group? { // Force read only if the database is like that mReadOnly = mDatabase?.isReadOnly == true || mReadOnly @@ -344,7 +344,7 @@ class GroupActivity : LockingActivity(), } // else a real group else { - var pwGroupId: PwNodeId<*>? = null + var pwGroupId: NodeId<*>? = null if (savedInstanceState != null && savedInstanceState.containsKey(GROUP_ID_KEY)) { pwGroupId = savedInstanceState.getParcelable(GROUP_ID_KEY) } else { @@ -353,7 +353,7 @@ class GroupActivity : LockingActivity(), } Log.w(TAG, "Creating tree view") - val currentGroup: GroupVersioned? + val currentGroup: Group? currentGroup = if (pwGroupId == null) { mRootGroup } else { @@ -456,16 +456,16 @@ class GroupActivity : LockingActivity(), addNodeButtonView?.hideButtonOnScrollListener(dy) } - override fun onNodeClick(node: NodeVersioned) { + override fun onNodeClick(node: Node) { when (node.type) { Type.GROUP -> try { - openChildGroup(node as GroupVersioned) + openChildGroup(node as Group) } catch (e: ClassCastException) { Log.e(TAG, "Node can't be cast in Group") } Type.ENTRY -> try { - val entryVersioned = node as EntryVersioned + val entryVersioned = node as Entry EntrySelectionHelper.doEntrySelectionAction(intent, { EntryActivity.launch(this@GroupActivity, entryVersioned, mReadOnly) @@ -503,7 +503,7 @@ class GroupActivity : LockingActivity(), actionNodeMode = null } - override fun onNodeSelected(nodes: List): Boolean { + override fun onNodeSelected(nodes: List): Boolean { if (nodes.isNotEmpty()) { if (actionNodeMode == null || toolbarAction?.getSupportActionModeCallback() == null) { mListNodesFragment?.actionNodesCallback(nodes, this)?.let { @@ -518,34 +518,34 @@ class GroupActivity : LockingActivity(), return true } - override fun onOpenMenuClick(node: NodeVersioned): Boolean { + override fun onOpenMenuClick(node: Node): Boolean { finishNodeAction() onNodeClick(node) return true } - override fun onEditMenuClick(node: NodeVersioned): Boolean { + override fun onEditMenuClick(node: Node): Boolean { finishNodeAction() when (node.type) { Type.GROUP -> { - mOldGroupToUpdate = node as GroupVersioned + mOldGroupToUpdate = node as Group GroupEditDialogFragment.build(mOldGroupToUpdate!!) .show(supportFragmentManager, GroupEditDialogFragment.TAG_CREATE_GROUP) } - Type.ENTRY -> EntryEditActivity.launch(this@GroupActivity, node as EntryVersioned) + Type.ENTRY -> EntryEditActivity.launch(this@GroupActivity, node as Entry) } return true } - override fun onCopyMenuClick(nodes: List): Boolean { + override fun onCopyMenuClick(nodes: List): Boolean { actionNodeMode?.invalidate() // Nothing here fragment calls onPasteMenuClick internally return true } - override fun onMoveMenuClick(nodes: List): Boolean { + override fun onMoveMenuClick(nodes: List): Boolean { actionNodeMode?.invalidate() // Nothing here fragment calls onPasteMenuClick internally @@ -553,7 +553,7 @@ class GroupActivity : LockingActivity(), } override fun onPasteMenuClick(pasteMode: ListNodesFragment.PasteMode?, - nodes: List): Boolean { + nodes: List): Boolean { // Move or copy only if allowed (in root if allowed) if (mCurrentGroup != mDatabase?.rootGroup || mDatabase?.rootCanContainsEntry() == true) { @@ -593,7 +593,7 @@ class GroupActivity : LockingActivity(), return true } - override fun onDeleteMenuClick(nodes: List): Boolean { + override fun onDeleteMenuClick(nodes: List): Boolean { val database = mDatabase // If recycle bin enabled, ensure it exists @@ -619,7 +619,7 @@ class GroupActivity : LockingActivity(), return true } - override fun permanentlyDeleteNodes(nodes: List) { + override fun permanentlyDeleteNodes(nodes: List) { mProgressDialogThread?.startDatabaseDeleteNodes( nodes, !mReadOnly && mAutoSaveEnable @@ -788,7 +788,7 @@ class GroupActivity : LockingActivity(), override fun approveEditGroup(action: GroupEditDialogFragment.EditGroupDialogAction?, name: String?, - icon: PwIcon?) { + icon: IconImage?) { if (name != null && name.isNotEmpty() && icon != null) { when (action) { @@ -813,7 +813,7 @@ class GroupActivity : LockingActivity(), GroupEditDialogFragment.EditGroupDialogAction.UPDATE -> { // If update add new elements mOldGroupToUpdate?.let { oldGroupToUpdate -> - val updateGroup = GroupVersioned(oldGroupToUpdate).let { updateGroup -> + val updateGroup = Group(oldGroupToUpdate).let { updateGroup -> updateGroup.apply { // WARNING remove parent and children to keep memory removeParent() @@ -838,7 +838,7 @@ class GroupActivity : LockingActivity(), override fun cancelEditGroup(action: GroupEditDialogFragment.EditGroupDialogAction?, name: String?, - icon: PwIcon?) { + icon: IconImage?) { // Do nothing here } @@ -949,7 +949,7 @@ class GroupActivity : LockingActivity(), private const val SEARCH_FRAGMENT_TAG = "SEARCH_FRAGMENT_TAG" private const val OLD_GROUP_TO_UPDATE_KEY = "OLD_GROUP_TO_UPDATE_KEY" - private fun buildAndLaunchIntent(context: Context, group: GroupVersioned?, readOnly: Boolean, + private fun buildAndLaunchIntent(context: Context, group: Group?, readOnly: Boolean, intentBuildLauncher: (Intent) -> Unit) { val checkTime = if (context is Activity) TimeoutHelper.checkTimeAndLockIfTimeout(context) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/ListNodesFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/ListNodesFragment.kt index d56b8f912..f839ea185 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/ListNodesFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/ListNodesFragment.kt @@ -19,8 +19,8 @@ import androidx.appcompat.view.ActionMode import com.kunzisoft.keepass.R import com.kunzisoft.keepass.adapters.NodeAdapter import com.kunzisoft.keepass.database.SortNodeEnum -import com.kunzisoft.keepass.database.element.GroupVersioned -import com.kunzisoft.keepass.database.element.NodeVersioned +import com.kunzisoft.keepass.database.element.Group +import com.kunzisoft.keepass.database.element.Node import com.kunzisoft.keepass.activities.dialogs.SortDialogFragment import com.kunzisoft.keepass.activities.helpers.EntrySelectionHelper import com.kunzisoft.keepass.settings.PreferencesUtil @@ -36,7 +36,7 @@ class ListNodesFragment : StylishFragment(), SortDialogFragment.SortSelectionLis private var onScrollListener: OnScrollListener? = null private var listView: RecyclerView? = null - var mainGroup: GroupVersioned? = null + var mainGroup: Group? = null private set private var mAdapter: NodeAdapter? = null @@ -44,8 +44,8 @@ class ListNodesFragment : StylishFragment(), SortDialogFragment.SortSelectionLis private set var nodeActionPasteMode: PasteMode = PasteMode.UNDEFINED private set - private val listActionNodes = LinkedList() - private val listPasteNodes = LinkedList() + private val listActionNodes = LinkedList() + private val listPasteNodes = LinkedList() private var notFoundView: View? = null private var isASearchResult: Boolean = false @@ -103,7 +103,7 @@ class ListNodesFragment : StylishFragment(), SortDialogFragment.SortSelectionLis mAdapter = NodeAdapter(context) mAdapter?.apply { setOnNodeClickListener(object : NodeAdapter.NodeClickCallback { - override fun onNodeClick(node: NodeVersioned) { + override fun onNodeClick(node: Node) { if (nodeActionSelectionMode) { if (listActionNodes.contains(node)) { // Remove selected item if already selected @@ -120,7 +120,7 @@ class ListNodesFragment : StylishFragment(), SortDialogFragment.SortSelectionLis } } - override fun onNodeLongClick(node: NodeVersioned): Boolean { + override fun onNodeLongClick(node: Node): Boolean { if (nodeActionPasteMode == PasteMode.UNDEFINED) { // Select the first item after a long click if (!listActionNodes.contains(node)) @@ -250,7 +250,7 @@ class ListNodesFragment : StylishFragment(), SortDialogFragment.SortSelectionLis } } - fun actionNodesCallback(nodes: List, + fun actionNodesCallback(nodes: List, menuListener: NodesActionMenuListener?) : ActionMode.Callback { return object : ActionMode.Callback { @@ -354,7 +354,7 @@ class ListNodesFragment : StylishFragment(), SortDialogFragment.SortSelectionLis EntryEditActivity.ADD_OR_UPDATE_ENTRY_REQUEST_CODE -> { if (resultCode == EntryEditActivity.ADD_ENTRY_RESULT_CODE || resultCode == EntryEditActivity.UPDATE_ENTRY_RESULT_CODE) { - data?.getParcelableExtra(EntryEditActivity.ADD_OR_UPDATE_ENTRY_KEY)?.let { newNode -> + data?.getParcelableExtra(EntryEditActivity.ADD_OR_UPDATE_ENTRY_KEY)?.let { newNode -> if (resultCode == EntryEditActivity.ADD_ENTRY_RESULT_CODE) mAdapter?.addNode(newNode) if (resultCode == EntryEditActivity.UPDATE_ENTRY_RESULT_CODE) { @@ -369,31 +369,31 @@ class ListNodesFragment : StylishFragment(), SortDialogFragment.SortSelectionLis } } - fun contains(node: NodeVersioned): Boolean { + fun contains(node: Node): Boolean { return mAdapter?.contains(node) ?: false } - fun addNode(newNode: NodeVersioned) { + fun addNode(newNode: Node) { mAdapter?.addNode(newNode) } - fun addNodes(newNodes: List) { + fun addNodes(newNodes: List) { mAdapter?.addNodes(newNodes) } - fun updateNode(oldNode: NodeVersioned, newNode: NodeVersioned? = null) { + fun updateNode(oldNode: Node, newNode: Node? = null) { mAdapter?.updateNode(oldNode, newNode ?: oldNode) } - fun updateNodes(oldNodes: List, newNodes: List) { + fun updateNodes(oldNodes: List, newNodes: List) { mAdapter?.updateNodes(oldNodes, newNodes) } - fun removeNode(pwNode: NodeVersioned) { + fun removeNode(pwNode: Node) { mAdapter?.removeNode(pwNode) } - fun removeNodes(nodes: List) { + fun removeNodes(nodes: List) { mAdapter?.removeNodes(nodes) } @@ -409,20 +409,20 @@ class ListNodesFragment : StylishFragment(), SortDialogFragment.SortSelectionLis * Callback listener to redefine to do an action when a node is click */ interface NodeClickListener { - fun onNodeClick(node: NodeVersioned) - fun onNodeSelected(nodes: List): Boolean + fun onNodeClick(node: Node) + fun onNodeSelected(nodes: List): Boolean } /** * Menu listener to redefine to do an action in menu */ interface NodesActionMenuListener { - fun onOpenMenuClick(node: NodeVersioned): Boolean - fun onEditMenuClick(node: NodeVersioned): Boolean - fun onCopyMenuClick(nodes: List): Boolean - fun onMoveMenuClick(nodes: List): Boolean - fun onDeleteMenuClick(nodes: List): Boolean - fun onPasteMenuClick(pasteMode: PasteMode?, nodes: List): Boolean + fun onOpenMenuClick(node: Node): Boolean + fun onEditMenuClick(node: Node): Boolean + fun onCopyMenuClick(nodes: List): Boolean + fun onMoveMenuClick(nodes: List): Boolean + fun onDeleteMenuClick(nodes: List): Boolean + fun onPasteMenuClick(pasteMode: PasteMode?, nodes: List): Boolean } enum class PasteMode { @@ -447,7 +447,7 @@ class ListNodesFragment : StylishFragment(), SortDialogFragment.SortSelectionLis private const val GROUP_KEY = "GROUP_KEY" private const val IS_SEARCH = "IS_SEARCH" - fun newInstance(group: GroupVersioned?, readOnly: Boolean, isASearch: Boolean): ListNodesFragment { + fun newInstance(group: Group?, readOnly: Boolean, isASearch: Boolean): ListNodesFragment { val bundle = Bundle() if (group != null) { bundle.putParcelable(GROUP_KEY, group) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/DeleteNodesDialogFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/DeleteNodesDialogFragment.kt index bf3d7291a..d1960c070 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/DeleteNodesDialogFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/DeleteNodesDialogFragment.kt @@ -26,14 +26,14 @@ import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.kunzisoft.keepass.R import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.NodeVersioned +import com.kunzisoft.keepass.database.element.Node import com.kunzisoft.keepass.notifications.DatabaseTaskNotificationService import com.kunzisoft.keepass.notifications.DatabaseTaskNotificationService.Companion.getBundleFromListNodes import com.kunzisoft.keepass.notifications.DatabaseTaskNotificationService.Companion.getListNodesFromBundle class DeleteNodesDialogFragment : DialogFragment() { - private var mNodesToDelete: List = ArrayList() + private var mNodesToDelete: List = ArrayList() private var mListener: DeleteNodeListener? = null override fun onAttach(context: Context) { @@ -80,11 +80,11 @@ class DeleteNodesDialogFragment : DialogFragment() { } interface DeleteNodeListener { - fun permanentlyDeleteNodes(nodes: List) + fun permanentlyDeleteNodes(nodes: List) } companion object { - fun getInstance(nodesToDelete: List): DeleteNodesDialogFragment { + fun getInstance(nodesToDelete: List): DeleteNodesDialogFragment { return DeleteNodesDialogFragment().apply { arguments = getBundleFromListNodes(nodesToDelete) } diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt index 8f126d083..5763c0a08 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/GroupEditDialogFragment.kt @@ -33,8 +33,8 @@ import com.kunzisoft.keepass.R import com.kunzisoft.keepass.activities.dialogs.GroupEditDialogFragment.EditGroupDialogAction.CREATION import com.kunzisoft.keepass.activities.dialogs.GroupEditDialogFragment.EditGroupDialogAction.UPDATE import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.GroupVersioned -import com.kunzisoft.keepass.database.element.PwIcon +import com.kunzisoft.keepass.database.element.Group +import com.kunzisoft.keepass.database.element.IconImage import com.kunzisoft.keepass.icons.assignDatabaseIcon class GroupEditDialogFragment : DialogFragment(), IconPickerDialogFragment.IconPickerListener { @@ -45,7 +45,7 @@ class GroupEditDialogFragment : DialogFragment(), IconPickerDialogFragment.IconP private var editGroupDialogAction: EditGroupDialogAction? = null private var nameGroup: String? = null - private var iconGroup: PwIcon? = null + private var iconGroup: IconImage? = null private var nameTextLayoutView: TextInputLayout? = null private var nameTextView: TextView? = null @@ -186,8 +186,8 @@ class GroupEditDialogFragment : DialogFragment(), IconPickerDialogFragment.IconP } interface EditGroupListener { - fun approveEditGroup(action: EditGroupDialogAction?, name: String?, icon: PwIcon?) - fun cancelEditGroup(action: EditGroupDialogAction?, name: String?, icon: PwIcon?) + fun approveEditGroup(action: EditGroupDialogAction?, name: String?, icon: IconImage?) + fun cancelEditGroup(action: EditGroupDialogAction?, name: String?, icon: IconImage?) } companion object { @@ -206,7 +206,7 @@ class GroupEditDialogFragment : DialogFragment(), IconPickerDialogFragment.IconP return fragment } - fun build(group: GroupVersioned): GroupEditDialogFragment { + fun build(group: Group): GroupEditDialogFragment { val bundle = Bundle() bundle.putString(KEY_NAME, group.title) bundle.putParcelable(KEY_ICON, group.icon) diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/IconPickerDialogFragment.kt b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/IconPickerDialogFragment.kt index 7b0691ba9..29d3bf6ec 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/IconPickerDialogFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/activities/dialogs/IconPickerDialogFragment.kt @@ -35,7 +35,7 @@ import android.widget.GridView import android.widget.ImageView import com.kunzisoft.keepass.R import com.kunzisoft.keepass.activities.stylish.StylishActivity -import com.kunzisoft.keepass.database.element.PwIconStandard +import com.kunzisoft.keepass.database.element.IconImageStandard import com.kunzisoft.keepass.icons.IconPack import com.kunzisoft.keepass.icons.IconPackChooser @@ -72,7 +72,7 @@ class IconPickerDialogFragment : DialogFragment() { currIconGridView.setOnItemClickListener { _, _, position, _ -> val bundle = Bundle() - bundle.putParcelable(KEY_ICON_STANDARD, PwIconStandard(position)) + bundle.putParcelable(KEY_ICON_STANDARD, IconImageStandard(position)) iconPickerListener?.iconPicked(bundle) dismiss() } @@ -128,7 +128,7 @@ class IconPickerDialogFragment : DialogFragment() { private const val KEY_ICON_STANDARD = "KEY_ICON_STANDARD" - fun getIconStandardFromBundle(bundle: Bundle): PwIconStandard? { + fun getIconStandardFromBundle(bundle: Bundle): IconImageStandard? { return bundle.getParcelable(KEY_ICON_STANDARD) } diff --git a/app/src/main/java/com/kunzisoft/keepass/adapters/EntryHistoryAdapter.kt b/app/src/main/java/com/kunzisoft/keepass/adapters/EntryHistoryAdapter.kt index bd6744cf2..035f07577 100644 --- a/app/src/main/java/com/kunzisoft/keepass/adapters/EntryHistoryAdapter.kt +++ b/app/src/main/java/com/kunzisoft/keepass/adapters/EntryHistoryAdapter.kt @@ -7,13 +7,13 @@ import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.kunzisoft.keepass.R -import com.kunzisoft.keepass.database.element.EntryVersioned +import com.kunzisoft.keepass.database.element.Entry class EntryHistoryAdapter(val context: Context) : RecyclerView.Adapter() { private val inflater: LayoutInflater = LayoutInflater.from(context) - var entryHistoryList: MutableList = ArrayList() - var onItemClickListener: ((item: EntryVersioned, position: Int)->Unit)? = null + var entryHistoryList: MutableList = ArrayList() + var onItemClickListener: ((item: Entry, position: Int)->Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EntryHistoryViewHolder { return EntryHistoryViewHolder(inflater.inflate(R.layout.item_list_entry_history, parent, false)) diff --git a/app/src/main/java/com/kunzisoft/keepass/adapters/NodeAdapter.kt b/app/src/main/java/com/kunzisoft/keepass/adapters/NodeAdapter.kt index f22e4cb88..c1bf0999a 100644 --- a/app/src/main/java/com/kunzisoft/keepass/adapters/NodeAdapter.kt +++ b/app/src/main/java/com/kunzisoft/keepass/adapters/NodeAdapter.kt @@ -48,7 +48,7 @@ class NodeAdapter (private val context: Context) : RecyclerView.Adapter() { - private val nodeSortedList: SortedList + private val nodeSortedList: SortedList private val inflater: LayoutInflater = LayoutInflater.from(context) private var calculateViewTypeTextSize = Array(2) { true} // number of view type @@ -65,7 +65,7 @@ class NodeAdapter private var showUserNames: Boolean = true private var showNumberEntries: Boolean = true - private var actionNodesList = LinkedList() + private var actionNodesList = LinkedList() private var nodeClickCallback: NodeClickCallback? = null private val mDatabase: Database @@ -83,18 +83,18 @@ class NodeAdapter init { assignPreferences() - this.nodeSortedList = SortedList(NodeVersioned::class.java, object : SortedListAdapterCallback(this) { - override fun compare(item1: NodeVersioned, item2: NodeVersioned): Int { + this.nodeSortedList = SortedList(Node::class.java, object : SortedListAdapterCallback(this) { + override fun compare(item1: Node, item2: Node): Int { return listSort.getNodeComparator(ascendingSort, groupsBeforeSort, recycleBinBottomSort).compare(item1, item2) } - override fun areContentsTheSame(oldItem: NodeVersioned, newItem: NodeVersioned): Boolean { + override fun areContentsTheSame(oldItem: Node, newItem: Node): Boolean { return oldItem.type == newItem.type && oldItem.title == newItem.title && oldItem.icon == newItem.icon } - override fun areItemsTheSame(item1: NodeVersioned, item2: NodeVersioned): Boolean { + override fun areItemsTheSame(item1: Node, item2: Node): Boolean { return item1 == item2 } }) @@ -133,7 +133,7 @@ class NodeAdapter /** * Rebuild the list by clear and build children from the group */ - fun rebuildList(group: GroupVersioned) { + fun rebuildList(group: Group) { this.nodeSortedList.clear() assignPreferences() try { @@ -145,7 +145,7 @@ class NodeAdapter notifyDataSetChanged() } - fun contains(node: NodeVersioned): Boolean { + fun contains(node: Node): Boolean { return nodeSortedList.indexOf(node) != SortedList.INVALID_POSITION } @@ -153,7 +153,7 @@ class NodeAdapter * Add a node to the list * @param node Node to add */ - fun addNode(node: NodeVersioned) { + fun addNode(node: Node) { nodeSortedList.add(node) } @@ -161,7 +161,7 @@ class NodeAdapter * Add nodes to the list * @param nodes Nodes to add */ - fun addNodes(nodes: List) { + fun addNodes(nodes: List) { nodeSortedList.addAll(nodes) } @@ -169,7 +169,7 @@ class NodeAdapter * Remove a node in the list * @param node Node to delete */ - fun removeNode(node: NodeVersioned) { + fun removeNode(node: Node) { nodeSortedList.remove(node) } @@ -177,7 +177,7 @@ class NodeAdapter * Remove nodes in the list * @param nodes Nodes to delete */ - fun removeNodes(nodes: List) { + fun removeNodes(nodes: List) { nodes.forEach { node -> nodeSortedList.remove(node) } @@ -209,7 +209,7 @@ class NodeAdapter * @param oldNode Node before the update * @param newNode Node after the update */ - fun updateNode(oldNode: NodeVersioned, newNode: NodeVersioned) { + fun updateNode(oldNode: Node, newNode: Node) { nodeSortedList.beginBatchedUpdates() nodeSortedList.remove(oldNode) nodeSortedList.add(newNode) @@ -221,7 +221,7 @@ class NodeAdapter * @param oldNodes Nodes before the update * @param newNodes Node after the update */ - fun updateNodes(oldNodes: List, newNodes: List) { + fun updateNodes(oldNodes: List, newNodes: List) { nodeSortedList.beginBatchedUpdates() oldNodes.forEach { oldNode -> nodeSortedList.remove(oldNode) @@ -230,11 +230,11 @@ class NodeAdapter nodeSortedList.endBatchedUpdates() } - fun notifyNodeChanged(node: NodeVersioned) { + fun notifyNodeChanged(node: Node) { notifyItemChanged(nodeSortedList.indexOf(node)) } - fun setActionNodes(actionNodes: List) { + fun setActionNodes(actionNodes: List) { this.actionNodesList.apply { clear() addAll(actionNodes) @@ -315,7 +315,7 @@ class NodeAdapter paintFlags and Paint.STRIKE_THRU_TEXT_FLAG visibility = View.GONE if (subNode.type == Type.ENTRY) { - val entry = subNode as EntryVersioned + val entry = subNode as Entry mDatabase.startManageEntry(entry) @@ -336,7 +336,7 @@ class NodeAdapter if (subNode.type == Type.GROUP) { if (showNumberEntries) { holder.numberChildren?.apply { - text = (subNode as GroupVersioned).getChildEntries(true).size.toString() + text = (subNode as Group).getChildEntries(true).size.toString() setTextSize(textSizeUnit, numberChildrenTextSize) visibility = View.VISIBLE } @@ -361,8 +361,8 @@ class NodeAdapter * Callback listener to redefine to do an action when a node is click */ interface NodeClickCallback { - fun onNodeClick(node: NodeVersioned) - fun onNodeLongClick(node: NodeVersioned): Boolean + fun onNodeClick(node: Node) + fun onNodeLongClick(node: Node): Boolean } class NodeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { diff --git a/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt b/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt index 93d733df6..0e6bf5b98 100644 --- a/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt +++ b/app/src/main/java/com/kunzisoft/keepass/adapters/SearchEntryCursorAdapter.kt @@ -22,7 +22,6 @@ package com.kunzisoft.keepass.adapters import android.content.Context import android.database.Cursor import android.graphics.Color -import androidx.cursoradapter.widget.CursorAdapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -31,8 +30,8 @@ import android.widget.TextView import com.kunzisoft.keepass.R import com.kunzisoft.keepass.database.cursor.EntryCursor import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.EntryVersioned -import com.kunzisoft.keepass.database.element.PwIcon +import com.kunzisoft.keepass.database.element.Entry +import com.kunzisoft.keepass.database.element.IconImage import com.kunzisoft.keepass.icons.assignDatabaseIcon import com.kunzisoft.keepass.settings.PreferencesUtil import java.util.* @@ -76,7 +75,7 @@ class SearchEntryCursorAdapter(context: Context, private val database: Database) val uuid = UUID(cursor.getLong(cursor.getColumnIndex(EntryCursor.COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS)), cursor.getLong(cursor.getColumnIndex(EntryCursor.COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS))) val iconFactory = database.iconFactory - var icon: PwIcon = iconFactory.getIcon( + var icon: IconImage = iconFactory.getIcon( UUID(cursor.getLong(cursor.getColumnIndex(EntryCursor.COLUMN_INDEX_ICON_CUSTOM_UUID_MOST_SIGNIFICANT_BITS)), cursor.getLong(cursor.getColumnIndex(EntryCursor.COLUMN_INDEX_ICON_CUSTOM_UUID_LEAST_SIGNIFICANT_BITS)))) if (icon.isUnknown) { @@ -94,7 +93,7 @@ class SearchEntryCursorAdapter(context: Context, private val database: Database) viewHolder.imageViewIcon?.assignDatabaseIcon(database.drawFactory, icon, iconColor) // Assign title - val showTitle = EntryVersioned.getVisualTitle(false, title, username, url, uuid.toString()) + val showTitle = Entry.getVisualTitle(false, title, username, url, uuid.toString()) viewHolder.textViewTitle?.text = showTitle if (displayUsername && username.isNotEmpty()) { viewHolder.textViewSubTitle?.text = String.format("(%s)", username) @@ -113,8 +112,8 @@ class SearchEntryCursorAdapter(context: Context, private val database: Database) return database.searchEntries(constraint.toString()) } - fun getEntryFromPosition(position: Int): EntryVersioned? { - var pwEntry: EntryVersioned? = null + fun getEntryFromPosition(position: Int): Entry? { + var pwEntry: Entry? = null val cursor = this.cursor if (cursor.moveToFirst() && cursor.move(position)) { diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/AesEngine.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/AesEngine.kt index ac59b4ea4..32904397d 100644 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/AesEngine.kt +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/AesEngine.kt @@ -21,7 +21,7 @@ package com.kunzisoft.keepass.crypto.engine import com.kunzisoft.keepass.crypto.CipherFactory -import com.kunzisoft.keepass.database.element.PwEncryptionAlgorithm +import com.kunzisoft.keepass.database.element.EncryptionAlgorithm import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils import java.security.InvalidAlgorithmParameterException import java.security.InvalidKeyException @@ -41,8 +41,8 @@ class AesEngine : CipherEngine() { return cipher } - override fun getPwEncryptionAlgorithm(): PwEncryptionAlgorithm { - return PwEncryptionAlgorithm.AESRijndael + override fun getPwEncryptionAlgorithm(): EncryptionAlgorithm { + return EncryptionAlgorithm.AESRijndael } companion object { diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/ChaCha20Engine.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/ChaCha20Engine.kt index 34010d18d..009070dbd 100644 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/ChaCha20Engine.kt +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/ChaCha20Engine.kt @@ -19,7 +19,7 @@ */ package com.kunzisoft.keepass.crypto.engine -import com.kunzisoft.keepass.database.element.PwEncryptionAlgorithm +import com.kunzisoft.keepass.database.element.EncryptionAlgorithm import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils import org.spongycastle.jce.provider.BouncyCastleProvider import java.security.InvalidAlgorithmParameterException @@ -44,8 +44,8 @@ class ChaCha20Engine : CipherEngine() { return cipher } - override fun getPwEncryptionAlgorithm(): PwEncryptionAlgorithm { - return PwEncryptionAlgorithm.ChaCha20 + override fun getPwEncryptionAlgorithm(): EncryptionAlgorithm { + return EncryptionAlgorithm.ChaCha20 } companion object { diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/CipherEngine.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/CipherEngine.kt index 260e1787d..eed47d28d 100644 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/CipherEngine.kt +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/CipherEngine.kt @@ -19,7 +19,7 @@ */ package com.kunzisoft.keepass.crypto.engine -import com.kunzisoft.keepass.database.element.PwEncryptionAlgorithm +import com.kunzisoft.keepass.database.element.EncryptionAlgorithm import java.security.InvalidAlgorithmParameterException import java.security.InvalidKeyException @@ -46,6 +46,6 @@ abstract class CipherEngine { return getCipher(opmode, key, IV, false) } - abstract fun getPwEncryptionAlgorithm(): PwEncryptionAlgorithm + abstract fun getPwEncryptionAlgorithm(): EncryptionAlgorithm } diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/TwofishEngine.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/TwofishEngine.kt index 0e323b24b..73b39a7d5 100644 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/TwofishEngine.kt +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/TwofishEngine.kt @@ -20,7 +20,7 @@ package com.kunzisoft.keepass.crypto.engine import com.kunzisoft.keepass.crypto.CipherFactory -import com.kunzisoft.keepass.database.element.PwEncryptionAlgorithm +import com.kunzisoft.keepass.database.element.EncryptionAlgorithm import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils import java.security.InvalidAlgorithmParameterException @@ -47,8 +47,8 @@ class TwofishEngine : CipherEngine() { return cipher } - override fun getPwEncryptionAlgorithm(): PwEncryptionAlgorithm { - return PwEncryptionAlgorithm.Twofish + override fun getPwEncryptionAlgorithm(): EncryptionAlgorithm { + return EncryptionAlgorithm.Twofish } companion object { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.kt b/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.kt index 1dc28111c..efa1ef6fe 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.kt @@ -21,15 +21,15 @@ package com.kunzisoft.keepass.database import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.EntryVersioned -import com.kunzisoft.keepass.database.element.NodeVersioned +import com.kunzisoft.keepass.database.element.Entry +import com.kunzisoft.keepass.database.element.Node import com.kunzisoft.keepass.database.element.Type import java.util.* enum class SortNodeEnum { DB, TITLE, USERNAME, CREATION_TIME, LAST_MODIFY_TIME, LAST_ACCESS_TIME; - fun getNodeComparator(ascending: Boolean, groupsBefore: Boolean, recycleBinBottom: Boolean): Comparator { + fun getNodeComparator(ascending: Boolean, groupsBefore: Boolean, recycleBinBottom: Boolean): Comparator { return when (this) { DB -> NodeNaturalComparator(ascending, groupsBefore, false) // Force false because natural order contains recycle bin TITLE -> NodeTitleComparator(ascending, groupsBefore, recycleBinBottom) @@ -40,11 +40,11 @@ enum class SortNodeEnum { } } - abstract class NodeComparator(var ascending: Boolean, var groupsBefore: Boolean, var recycleBinBottom: Boolean) : Comparator { + abstract class NodeComparator(var ascending: Boolean, var groupsBefore: Boolean, var recycleBinBottom: Boolean) : Comparator { - abstract fun compareBySpecificOrder(object1: NodeVersioned, object2: NodeVersioned): Int + abstract fun compareBySpecificOrder(object1: Node, object2: Node): Int - private fun specificOrderOrHashIfEquals(object1: NodeVersioned, object2: NodeVersioned): Int { + private fun specificOrderOrHashIfEquals(object1: Node, object2: Node): Int { val specificOrderComp = compareBySpecificOrder(object1, object2) return if (specificOrderComp == 0) { @@ -52,7 +52,7 @@ enum class SortNodeEnum { } else if (!ascending) -specificOrderComp else specificOrderComp // If descending, revert } - override fun compare(object1: NodeVersioned,object2: NodeVersioned): Int { + override fun compare(object1: Node, object2: Node): Int { if (object1 == object2) return 0 @@ -99,7 +99,7 @@ enum class SortNodeEnum { class NodeNaturalComparator(ascending: Boolean, groupsBefore: Boolean, recycleBinBottom: Boolean) : NodeComparator(ascending, groupsBefore, recycleBinBottom) { - override fun compareBySpecificOrder(object1: NodeVersioned, object2: NodeVersioned): Int { + override fun compareBySpecificOrder(object1: Node, object2: Node): Int { return object1.nodePositionInParent.compareTo(object2.nodePositionInParent) } } @@ -110,7 +110,7 @@ enum class SortNodeEnum { class NodeTitleComparator(ascending: Boolean, groupsBefore: Boolean, recycleBinBottom: Boolean) : NodeComparator(ascending, groupsBefore, recycleBinBottom) { - override fun compareBySpecificOrder(object1: NodeVersioned, object2: NodeVersioned): Int { + override fun compareBySpecificOrder(object1: Node, object2: Node): Int { return object1.title.compareTo(object2.title, ignoreCase = true) } } @@ -121,11 +121,11 @@ enum class SortNodeEnum { class NodeUsernameComparator(ascending: Boolean, groupsBefore: Boolean, recycleBinBottom: Boolean) : NodeComparator(ascending, groupsBefore, recycleBinBottom) { - override fun compareBySpecificOrder(object1: NodeVersioned, object2: NodeVersioned): Int { + override fun compareBySpecificOrder(object1: Node, object2: Node): Int { if (object1.type == Type.ENTRY && object2.type == Type.ENTRY) { // To get username if it's a ref - return (object1 as EntryVersioned).getEntryInfo(Database.getInstance()).username - .compareTo((object2 as EntryVersioned).getEntryInfo(Database.getInstance()).username, + return (object1 as Entry).getEntryInfo(Database.getInstance()).username + .compareTo((object2 as Entry).getEntryInfo(Database.getInstance()).username, ignoreCase = true) } return NodeTitleComparator(ascending, groupsBefore, recycleBinBottom).compare(object1, object2) @@ -138,7 +138,7 @@ enum class SortNodeEnum { class NodeCreationComparator(ascending: Boolean, groupsBefore: Boolean, recycleBinBottom: Boolean) : NodeComparator(ascending, groupsBefore, recycleBinBottom) { - override fun compareBySpecificOrder(object1: NodeVersioned, object2: NodeVersioned): Int { + override fun compareBySpecificOrder(object1: Node, object2: Node): Int { return object1.creationTime.date .compareTo(object2.creationTime.date) } @@ -150,7 +150,7 @@ enum class SortNodeEnum { class NodeLastModificationComparator(ascending: Boolean, groupsBefore: Boolean, recycleBinBottom: Boolean) : NodeComparator(ascending, groupsBefore, recycleBinBottom) { - override fun compareBySpecificOrder(object1: NodeVersioned, object2: NodeVersioned): Int { + override fun compareBySpecificOrder(object1: Node, object2: Node): Int { return object1.lastModificationTime.date .compareTo(object2.lastModificationTime.date) } @@ -162,7 +162,7 @@ enum class SortNodeEnum { class NodeLastAccessComparator(ascending: Boolean, groupsBefore: Boolean, recycleBinBottom: Boolean) : NodeComparator(ascending, groupsBefore, recycleBinBottom) { - override fun compareBySpecificOrder(object1: NodeVersioned, object2: NodeVersioned): Int { + override fun compareBySpecificOrder(object1: Node, object2: Node): Int { return object1.lastAccessTime.date .compareTo(object2.lastAccessTime.date) } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/ProgressDialogThread.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/ProgressDialogThread.kt index 6a562bad4..fd7baadbd 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/ProgressDialogThread.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/ProgressDialogThread.kt @@ -251,8 +251,8 @@ class ProgressDialogThread(private val activity: FragmentActivity) { ---- */ - fun startDatabaseCreateGroup(newGroup: GroupVersioned, - parent: GroupVersioned, + fun startDatabaseCreateGroup(newGroup: Group, + parent: Group, save: Boolean) { start(Bundle().apply { putParcelable(DatabaseTaskNotificationService.GROUP_KEY, newGroup) @@ -262,8 +262,8 @@ class ProgressDialogThread(private val activity: FragmentActivity) { , ACTION_DATABASE_CREATE_GROUP_TASK) } - fun startDatabaseUpdateGroup(oldGroup: GroupVersioned, - groupToUpdate: GroupVersioned, + fun startDatabaseUpdateGroup(oldGroup: Group, + groupToUpdate: Group, save: Boolean) { start(Bundle().apply { putParcelable(DatabaseTaskNotificationService.GROUP_ID_KEY, oldGroup.nodeId) @@ -273,8 +273,8 @@ class ProgressDialogThread(private val activity: FragmentActivity) { , ACTION_DATABASE_UPDATE_GROUP_TASK) } - fun startDatabaseCreateEntry(newEntry: EntryVersioned, - parent: GroupVersioned, + fun startDatabaseCreateEntry(newEntry: Entry, + parent: Group, save: Boolean) { start(Bundle().apply { putParcelable(DatabaseTaskNotificationService.ENTRY_KEY, newEntry) @@ -284,8 +284,8 @@ class ProgressDialogThread(private val activity: FragmentActivity) { , ACTION_DATABASE_CREATE_ENTRY_TASK) } - fun startDatabaseUpdateEntry(oldEntry: EntryVersioned, - entryToUpdate: EntryVersioned, + fun startDatabaseUpdateEntry(oldEntry: Entry, + entryToUpdate: Entry, save: Boolean) { start(Bundle().apply { putParcelable(DatabaseTaskNotificationService.ENTRY_ID_KEY, oldEntry.nodeId) @@ -296,20 +296,20 @@ class ProgressDialogThread(private val activity: FragmentActivity) { } private fun startDatabaseActionListNodes(actionTask: String, - nodesPaste: List, - newParent: GroupVersioned?, + nodesPaste: List, + newParent: Group?, save: Boolean) { - val groupsIdToCopy = ArrayList>() - val entriesIdToCopy = ArrayList>() + val groupsIdToCopy = ArrayList>() + val entriesIdToCopy = ArrayList>() nodesPaste.forEach { nodeVersioned -> when (nodeVersioned.type) { Type.GROUP -> { - (nodeVersioned as GroupVersioned).nodeId?.let { groupId -> + (nodeVersioned as Group).nodeId?.let { groupId -> groupsIdToCopy.add(groupId) } } Type.ENTRY -> { - entriesIdToCopy.add((nodeVersioned as EntryVersioned).nodeId) + entriesIdToCopy.add((nodeVersioned as Entry).nodeId) } } } @@ -326,19 +326,19 @@ class ProgressDialogThread(private val activity: FragmentActivity) { , actionTask) } - fun startDatabaseCopyNodes(nodesToCopy: List, - newParent: GroupVersioned, + fun startDatabaseCopyNodes(nodesToCopy: List, + newParent: Group, save: Boolean) { startDatabaseActionListNodes(ACTION_DATABASE_COPY_NODES_TASK, nodesToCopy, newParent, save) } - fun startDatabaseMoveNodes(nodesToMove: List, - newParent: GroupVersioned, + fun startDatabaseMoveNodes(nodesToMove: List, + newParent: Group, save: Boolean) { startDatabaseActionListNodes(ACTION_DATABASE_MOVE_NODES_TASK, nodesToMove, newParent, save) } - fun startDatabaseDeleteNodes(nodesToDelete: List, + fun startDatabaseDeleteNodes(nodesToDelete: List, save: Boolean) { startDatabaseActionListNodes(ACTION_DATABASE_DELETE_NODES_TASK, nodesToDelete, null, save) } @@ -393,8 +393,8 @@ class ProgressDialogThread(private val activity: FragmentActivity) { , ACTION_DATABASE_UPDATE_COLOR_TASK) } - fun startDatabaseSaveCompression(oldCompression: PwCompressionAlgorithm, - newCompression: PwCompressionAlgorithm, + fun startDatabaseSaveCompression(oldCompression: CompressionAlgorithm, + newCompression: CompressionAlgorithm, save: Boolean) { start(Bundle().apply { putSerializable(DatabaseTaskNotificationService.OLD_ELEMENT_KEY, oldCompression) @@ -432,8 +432,8 @@ class ProgressDialogThread(private val activity: FragmentActivity) { ------------------- */ - fun startDatabaseSaveEncryption(oldEncryption: PwEncryptionAlgorithm, - newEncryption: PwEncryptionAlgorithm, + fun startDatabaseSaveEncryption(oldEncryption: EncryptionAlgorithm, + newEncryption: EncryptionAlgorithm, save: Boolean) { start(Bundle().apply { putSerializable(DatabaseTaskNotificationService.OLD_ELEMENT_KEY, oldEncryption) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/UpdateCompressionBinariesDatabaseRunnable.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/UpdateCompressionBinariesDatabaseRunnable.kt index 9e58d2b19..45a0661e8 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/UpdateCompressionBinariesDatabaseRunnable.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/UpdateCompressionBinariesDatabaseRunnable.kt @@ -21,13 +21,13 @@ package com.kunzisoft.keepass.database.action import android.content.Context import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.PwCompressionAlgorithm +import com.kunzisoft.keepass.database.element.CompressionAlgorithm class UpdateCompressionBinariesDatabaseRunnable ( context: Context, database: Database, - private val oldCompressionAlgorithm: PwCompressionAlgorithm, - private val newCompressionAlgorithm: PwCompressionAlgorithm, + private val oldCompressionAlgorithm: CompressionAlgorithm, + private val newCompressionAlgorithm: CompressionAlgorithm, saveDatabase: Boolean) : SaveDatabaseRunnable(context, database, saveDatabase) { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/node/AddEntryRunnable.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/node/AddEntryRunnable.kt index 991b91be2..b2172cc8f 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/node/AddEntryRunnable.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/node/AddEntryRunnable.kt @@ -21,15 +21,15 @@ package com.kunzisoft.keepass.database.action.node import android.content.Context import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.EntryVersioned -import com.kunzisoft.keepass.database.element.GroupVersioned -import com.kunzisoft.keepass.database.element.NodeVersioned +import com.kunzisoft.keepass.database.element.Entry +import com.kunzisoft.keepass.database.element.Group +import com.kunzisoft.keepass.database.element.Node class AddEntryRunnable constructor( context: Context, database: Database, - private val mNewEntry: EntryVersioned, - private val mParent: GroupVersioned, + private val mNewEntry: Entry, + private val mParent: Group, save: Boolean, afterActionNodesFinish: AfterActionNodesFinish?) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save) { @@ -47,8 +47,8 @@ class AddEntryRunnable constructor( } } - val oldNodesReturn = ArrayList() - val newNodesReturn = ArrayList() + val oldNodesReturn = ArrayList() + val newNodesReturn = ArrayList() newNodesReturn.add(mNewEntry) return ActionNodesValues(oldNodesReturn, newNodesReturn) } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/node/AddGroupRunnable.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/node/AddGroupRunnable.kt index ebbce2abf..13acb7bfd 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/node/AddGroupRunnable.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/node/AddGroupRunnable.kt @@ -21,14 +21,14 @@ package com.kunzisoft.keepass.database.action.node import android.content.Context import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.GroupVersioned -import com.kunzisoft.keepass.database.element.NodeVersioned +import com.kunzisoft.keepass.database.element.Group +import com.kunzisoft.keepass.database.element.Node class AddGroupRunnable constructor( context: Context, database: Database, - private val mNewGroup: GroupVersioned, - private val mParent: GroupVersioned, + private val mNewGroup: Group, + private val mParent: Group, save: Boolean, afterActionNodesFinish: AfterActionNodesFinish?) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save) { @@ -44,8 +44,8 @@ class AddGroupRunnable constructor( database.removeGroupFrom(mNewGroup, mParent) } - val oldNodesReturn = ArrayList() - val newNodesReturn = ArrayList() + val oldNodesReturn = ArrayList() + val newNodesReturn = ArrayList() newNodesReturn.add(mNewGroup) return ActionNodesValues(oldNodesReturn, newNodesReturn) } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/node/AfterActionNodesFinish.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/node/AfterActionNodesFinish.kt index c509a3223..684c3b992 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/node/AfterActionNodesFinish.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/node/AfterActionNodesFinish.kt @@ -19,7 +19,7 @@ */ package com.kunzisoft.keepass.database.action.node -import com.kunzisoft.keepass.database.element.NodeVersioned +import com.kunzisoft.keepass.database.element.Node import com.kunzisoft.keepass.tasks.ActionRunnable /** @@ -30,7 +30,7 @@ import com.kunzisoft.keepass.tasks.ActionRunnable * - Move : @param oldNodes empty, @param newNodes NodesToMove * - Update : @param oldNodes NodesToUpdate, @param newNodes NodesUpdated */ -class ActionNodesValues(val oldNodes: List, val newNodes: List) +class ActionNodesValues(val oldNodes: List, val newNodes: List) abstract class AfterActionNodesFinish { abstract fun onActionNodesFinish(result: ActionRunnable.Result, actionNodesValues: ActionNodesValues) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/node/CopyNodesRunnable.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/node/CopyNodesRunnable.kt index 4188548af..a482557f6 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/node/CopyNodesRunnable.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/node/CopyNodesRunnable.kt @@ -28,13 +28,13 @@ import com.kunzisoft.keepass.database.exception.CopyGroupDatabaseException class CopyNodesRunnable constructor( context: Context, database: Database, - private val mNodesToCopy: List, - private val mNewParent: GroupVersioned, + private val mNodesToCopy: List, + private val mNewParent: Group, save: Boolean, afterActionNodesFinish: AfterActionNodesFinish?) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save) { - private var mEntriesCopied = ArrayList() + private var mEntriesCopied = ArrayList() override fun nodeAction() { @@ -51,7 +51,7 @@ class CopyNodesRunnable constructor( // Update entry with new values mNewParent.touch(modified = false, touchParents = true) - val entryCopied = database.copyEntryTo(currentNode as EntryVersioned, mNewParent) + val entryCopied = database.copyEntryTo(currentNode as Entry, mNewParent) if (entryCopied != null) { entryCopied.touch(modified = true, touchParents = true) mEntriesCopied.add(entryCopied) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/node/DeleteNodesRunnable.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/node/DeleteNodesRunnable.kt index e24619d46..62526642c 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/node/DeleteNodesRunnable.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/node/DeleteNodesRunnable.kt @@ -24,15 +24,15 @@ import com.kunzisoft.keepass.database.element.* class DeleteNodesRunnable(context: Context, database: Database, - private val mNodesToDelete: List, + private val mNodesToDelete: List, save: Boolean, afterActionNodesFinish: AfterActionNodesFinish) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save) { - private var mParent: GroupVersioned? = null + private var mParent: Group? = null private var mCanRecycle: Boolean = false - private var mNodesToDeleteBackup = ArrayList() + private var mNodesToDeleteBackup = ArrayList() override fun nodeAction() { @@ -43,7 +43,7 @@ class DeleteNodesRunnable(context: Context, when (currentNode.type) { Type.GROUP -> { // Create a copy to keep the old ref and remove it visually - mNodesToDeleteBackup.add(GroupVersioned(currentNode as GroupVersioned)) + mNodesToDeleteBackup.add(Group(currentNode as Group)) // Remove Node from parent mCanRecycle = database.canRecycle(currentNode) if (mCanRecycle) { @@ -54,7 +54,7 @@ class DeleteNodesRunnable(context: Context, } Type.ENTRY -> { // Create a copy to keep the old ref and remove it visually - mNodesToDeleteBackup.add(EntryVersioned(currentNode as EntryVersioned)) + mNodesToDeleteBackup.add(Entry(currentNode as Entry)) // Remove Node from parent mCanRecycle = database.canRecycle(currentNode) if (mCanRecycle) { @@ -74,10 +74,10 @@ class DeleteNodesRunnable(context: Context, mNodesToDeleteBackup.forEach { backupNode -> when (backupNode.type) { Type.GROUP -> { - database.undoRecycle(backupNode as GroupVersioned, it) + database.undoRecycle(backupNode as Group, it) } Type.ENTRY -> { - database.undoRecycle(backupNode as EntryVersioned, it) + database.undoRecycle(backupNode as Entry, it) } } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/node/MoveNodesRunnable.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/node/MoveNodesRunnable.kt index bb80cbf46..81d0c5640 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/node/MoveNodesRunnable.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/node/MoveNodesRunnable.kt @@ -28,13 +28,13 @@ import com.kunzisoft.keepass.database.exception.MoveGroupDatabaseException class MoveNodesRunnable constructor( context: Context, database: Database, - private val mNodesToMove: List, - private val mNewParent: GroupVersioned, + private val mNodesToMove: List, + private val mNewParent: Group, save: Boolean, afterActionNodesFinish: AfterActionNodesFinish?) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save) { - private var mOldParent: GroupVersioned? = null + private var mOldParent: Group? = null override fun nodeAction() { @@ -44,7 +44,7 @@ class MoveNodesRunnable constructor( when (nodeToMove.type) { Type.GROUP -> { - val groupToMove = nodeToMove as GroupVersioned + val groupToMove = nodeToMove as Group // Move group in new parent if not in the current group if (groupToMove != mNewParent && !mNewParent.isContainedIn(groupToMove)) { @@ -57,7 +57,7 @@ class MoveNodesRunnable constructor( } } Type.ENTRY -> { - val entryToMove = nodeToMove as EntryVersioned + val entryToMove = nodeToMove as Entry // Move only if the parent change if (mOldParent != mNewParent // and root can contains entry @@ -82,8 +82,8 @@ class MoveNodesRunnable constructor( if (mOldParent != null && mOldParent != nodeToMove.parent) { when (nodeToMove.type) { - Type.GROUP -> database.moveGroupTo(nodeToMove as GroupVersioned, mOldParent!!) - Type.ENTRY -> database.moveEntryTo(nodeToMove as EntryVersioned, mOldParent!!) + Type.GROUP -> database.moveGroupTo(nodeToMove as Group, mOldParent!!) + Type.ENTRY -> database.moveEntryTo(nodeToMove as Entry, mOldParent!!) } } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/node/UpdateEntryRunnable.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/node/UpdateEntryRunnable.kt index 52cc8295d..ad2f91a35 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/node/UpdateEntryRunnable.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/node/UpdateEntryRunnable.kt @@ -21,20 +21,20 @@ package com.kunzisoft.keepass.database.action.node import android.content.Context import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.EntryVersioned -import com.kunzisoft.keepass.database.element.NodeVersioned +import com.kunzisoft.keepass.database.element.Entry +import com.kunzisoft.keepass.database.element.Node class UpdateEntryRunnable constructor( context: Context, database: Database, - private val mOldEntry: EntryVersioned, - private val mNewEntry: EntryVersioned, + private val mOldEntry: Entry, + private val mNewEntry: Entry, save: Boolean, afterActionNodesFinish: AfterActionNodesFinish?) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save) { // Keep backup of original values in case save fails - private var mBackupEntryHistory: EntryVersioned = EntryVersioned(mOldEntry) + private var mBackupEntryHistory: Entry = Entry(mOldEntry) override fun nodeAction() { // WARNING : Re attribute parent removed in entry edit activity to save memory @@ -45,7 +45,7 @@ class UpdateEntryRunnable constructor( mNewEntry.touch(modified = true, touchParents = true) // Create an entry history (an entry history don't have history) - mOldEntry.addEntryToHistory(EntryVersioned(mBackupEntryHistory, copyHistory = false)) + mOldEntry.addEntryToHistory(Entry(mBackupEntryHistory, copyHistory = false)) database.removeOldestEntryHistory(mOldEntry) // Only change data in index @@ -59,9 +59,9 @@ class UpdateEntryRunnable constructor( database.updateEntry(mOldEntry) } - val oldNodesReturn = ArrayList() + val oldNodesReturn = ArrayList() oldNodesReturn.add(mBackupEntryHistory) - val newNodesReturn = ArrayList() + val newNodesReturn = ArrayList() newNodesReturn.add(mOldEntry) return ActionNodesValues(oldNodesReturn, newNodesReturn) } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/action/node/UpdateGroupRunnable.kt b/app/src/main/java/com/kunzisoft/keepass/database/action/node/UpdateGroupRunnable.kt index 273bb7227..59b990c3b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/action/node/UpdateGroupRunnable.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/action/node/UpdateGroupRunnable.kt @@ -21,20 +21,20 @@ package com.kunzisoft.keepass.database.action.node import android.content.Context import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.GroupVersioned -import com.kunzisoft.keepass.database.element.NodeVersioned +import com.kunzisoft.keepass.database.element.Group +import com.kunzisoft.keepass.database.element.Node class UpdateGroupRunnable constructor( context: Context, database: Database, - private val mOldGroup: GroupVersioned, - private val mNewGroup: GroupVersioned, + private val mOldGroup: Group, + private val mNewGroup: Group, save: Boolean, afterActionNodesFinish: AfterActionNodesFinish?) : ActionNodeDatabaseRunnable(context, database, afterActionNodesFinish, save) { // Keep backup of original values in case save fails - private val mBackupGroup: GroupVersioned = GroupVersioned(mOldGroup) + private val mBackupGroup: Group = Group(mOldGroup) override fun nodeAction() { // WARNING : Re attribute parent and children removed in group activity to save memory @@ -56,9 +56,9 @@ class UpdateGroupRunnable constructor( database.updateGroup(mOldGroup) } - val oldNodesReturn = ArrayList() + val oldNodesReturn = ArrayList() oldNodesReturn.add(mBackupGroup) - val newNodesReturn = ArrayList() + val newNodesReturn = ArrayList() newNodesReturn.add(mOldGroup) return ActionNodesValues(oldNodesReturn, newNodesReturn) } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.kt b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.kt index e9f59624b..d5dbc65a9 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.kt @@ -2,11 +2,11 @@ package com.kunzisoft.keepass.database.cursor import android.database.MatrixCursor import android.provider.BaseColumns -import com.kunzisoft.keepass.database.element.PwEntry -import com.kunzisoft.keepass.database.element.PwIconFactory -import com.kunzisoft.keepass.database.element.PwNodeId +import com.kunzisoft.keepass.database.element.EntryVersioned +import com.kunzisoft.keepass.database.element.IconImageFactory +import com.kunzisoft.keepass.database.element.NodeId -abstract class EntryCursor> : MatrixCursor(arrayOf( +abstract class EntryCursor> : MatrixCursor(arrayOf( _ID, COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS, COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS, @@ -24,9 +24,9 @@ abstract class EntryCursor> : Matr abstract fun addEntry(entry: PwEntryV) - abstract fun getPwNodeId(): PwNodeId + abstract fun getPwNodeId(): NodeId - open fun populateEntry(pwEntry: PwEntryV, iconFactory: PwIconFactory) { + open fun populateEntry(pwEntry: PwEntryV, iconFactory: IconImageFactory) { pwEntry.nodeId = getPwNodeId() pwEntry.title = getString(getColumnIndex(COLUMN_INDEX_TITLE)) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorKDB.kt similarity index 54% rename from app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorKDB.kt index f50b65388..4d78f2bff 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorKDB.kt @@ -1,19 +1,19 @@ package com.kunzisoft.keepass.database.cursor -import com.kunzisoft.keepass.database.element.PwDatabase -import com.kunzisoft.keepass.database.element.PwEntryV3 +import com.kunzisoft.keepass.database.element.DatabaseVersioned +import com.kunzisoft.keepass.database.element.EntryKDB -class EntryCursorV3 : EntryCursorUUID() { +class EntryCursorKDB : EntryCursorUUID() { - override fun addEntry(entry: PwEntryV3) { + override fun addEntry(entry: EntryKDB) { addRow(arrayOf( entryId, entry.id.mostSignificantBits, entry.id.leastSignificantBits, entry.title, entry.icon.iconId, - PwDatabase.UUID_ZERO.mostSignificantBits, - PwDatabase.UUID_ZERO.leastSignificantBits, + DatabaseVersioned.UUID_ZERO.mostSignificantBits, + DatabaseVersioned.UUID_ZERO.leastSignificantBits, entry.username, entry.password, entry.url, diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorKDBX.kt similarity index 85% rename from app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorKDBX.kt index f4fcbb3a1..c0443b27b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorKDBX.kt @@ -1,15 +1,15 @@ package com.kunzisoft.keepass.database.cursor -import com.kunzisoft.keepass.database.element.PwEntryV4 -import com.kunzisoft.keepass.database.element.PwIconFactory +import com.kunzisoft.keepass.database.element.EntryKDBX +import com.kunzisoft.keepass.database.element.IconImageFactory import java.util.UUID -class EntryCursorV4 : EntryCursorUUID() { +class EntryCursorKDBX : EntryCursorUUID() { private val extraFieldCursor: ExtraFieldCursor = ExtraFieldCursor() - override fun addEntry(entry: PwEntryV4) { + override fun addEntry(entry: EntryKDBX) { addRow(arrayOf( entryId, entry.id.mostSignificantBits, @@ -31,7 +31,7 @@ class EntryCursorV4 : EntryCursorUUID() { entryId++ } - override fun populateEntry(pwEntry: PwEntryV4, iconFactory: PwIconFactory) { + override fun populateEntry(pwEntry: EntryKDBX, iconFactory: IconImageFactory) { super.populateEntry(pwEntry, iconFactory) // Retrieve custom icon diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorUUID.kt b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorUUID.kt index 95be574a9..4f41c2a70 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorUUID.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorUUID.kt @@ -1,14 +1,14 @@ package com.kunzisoft.keepass.database.cursor -import com.kunzisoft.keepass.database.element.PwEntry -import com.kunzisoft.keepass.database.element.PwNodeId -import com.kunzisoft.keepass.database.element.PwNodeIdUUID +import com.kunzisoft.keepass.database.element.EntryVersioned +import com.kunzisoft.keepass.database.element.NodeId +import com.kunzisoft.keepass.database.element.NodeIdUUID import java.util.* -abstract class EntryCursorUUID>: EntryCursor() { +abstract class EntryCursorUUID>: EntryCursor() { - override fun getPwNodeId(): PwNodeId { - return PwNodeIdUUID( + override fun getPwNodeId(): NodeId { + return NodeIdUUID( UUID(getLong(getColumnIndex(COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS)), getLong(getColumnIndex(COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS)))) } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.kt b/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.kt index f86a27b82..45a86e34e 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.kt @@ -3,7 +3,7 @@ package com.kunzisoft.keepass.database.cursor import android.database.MatrixCursor import android.provider.BaseColumns -import com.kunzisoft.keepass.database.element.PwEntryV4 +import com.kunzisoft.keepass.database.element.EntryKDBX import com.kunzisoft.keepass.database.element.security.ProtectedString class ExtraFieldCursor : MatrixCursor(arrayOf( @@ -22,7 +22,7 @@ class ExtraFieldCursor : MatrixCursor(arrayOf( fieldId++ } - fun populateExtraFieldInEntry(pwEntry: PwEntryV4) { + fun populateExtraFieldInEntry(pwEntry: EntryKDBX) { pwEntry.putExtraField(getString(getColumnIndex(COLUMN_LABEL)), ProtectedString(getInt(getColumnIndex(COLUMN_PROTECTION)) > 0, getString(getColumnIndex(COLUMN_VALUE)))) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwCompressionAlgorithm.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/CompressionAlgorithm.kt similarity index 82% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwCompressionAlgorithm.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/CompressionAlgorithm.kt index 735bfb018..31748c248 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwCompressionAlgorithm.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/CompressionAlgorithm.kt @@ -31,7 +31,7 @@ import com.kunzisoft.keepass.utils.writeEnum // Note: We can get away with using int's to store unsigned 32-bit ints // since we won't do arithmetic on these values (also unlikely to // reach negative ids). -enum class PwCompressionAlgorithm : ObjectNameResource, Parcelable { +enum class CompressionAlgorithm : ObjectNameResource, Parcelable { None, GZip; @@ -51,12 +51,12 @@ enum class PwCompressionAlgorithm : ObjectNameResource, Parcelable { } } - companion object CREATOR : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwCompressionAlgorithm { - return parcel.readEnum() ?: None + companion object CREATOR : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): CompressionAlgorithm { + return parcel.readEnum() ?: None } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt index e371976f4..62183aa18 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt @@ -26,15 +26,15 @@ import android.net.Uri import android.util.Log import com.kunzisoft.keepass.crypto.keyDerivation.KdfEngine import com.kunzisoft.keepass.database.NodeHandler -import com.kunzisoft.keepass.database.cursor.EntryCursorV3 -import com.kunzisoft.keepass.database.cursor.EntryCursorV4 +import com.kunzisoft.keepass.database.cursor.EntryCursorKDB +import com.kunzisoft.keepass.database.cursor.EntryCursorKDBX import com.kunzisoft.keepass.database.exception.* -import com.kunzisoft.keepass.database.file.PwDbHeaderV3 -import com.kunzisoft.keepass.database.file.PwDbHeaderV4 -import com.kunzisoft.keepass.database.file.load.ImporterV3 -import com.kunzisoft.keepass.database.file.load.ImporterV4 -import com.kunzisoft.keepass.database.file.save.PwDbV3Output -import com.kunzisoft.keepass.database.file.save.PwDbV4Output +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDB +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX +import com.kunzisoft.keepass.database.file.load.ImporterKDB +import com.kunzisoft.keepass.database.file.load.ImporterKDBX +import com.kunzisoft.keepass.database.file.save.DatabaseOutputKDB +import com.kunzisoft.keepass.database.file.save.DatabaseOutputKDBX import com.kunzisoft.keepass.database.search.SearchDbHelper import com.kunzisoft.keepass.icons.IconDrawableFactory import com.kunzisoft.keepass.stream.LEDataInputStream @@ -49,8 +49,8 @@ import java.util.* class Database { // To keep a reference for specific methods provided by version - private var pwDatabaseV3: PwDatabaseV3? = null - private var pwDatabaseV4: PwDatabaseV4? = null + private var mDatabaseKDB: DatabaseKDB? = null + private var mDatabaseKDBX: DatabaseKDBX? = null var fileUri: Uri? = null private set @@ -63,124 +63,124 @@ class Database { var loaded = false - val iconFactory: PwIconFactory + val iconFactory: IconImageFactory get() { - return pwDatabaseV3?.iconFactory ?: pwDatabaseV4?.iconFactory ?: PwIconFactory() + return mDatabaseKDB?.iconFactory ?: mDatabaseKDBX?.iconFactory ?: IconImageFactory() } val allowName: Boolean - get() = pwDatabaseV4 != null + get() = mDatabaseKDBX != null var name: String get() { - return pwDatabaseV4?.name ?: "" + return mDatabaseKDBX?.name ?: "" } set(name) { - pwDatabaseV4?.name = name - pwDatabaseV4?.nameChanged = PwDate() + mDatabaseKDBX?.name = name + mDatabaseKDBX?.nameChanged = DateInstant() } val allowDescription: Boolean - get() = pwDatabaseV4 != null + get() = mDatabaseKDBX != null var description: String get() { - return pwDatabaseV4?.description ?: "" + return mDatabaseKDBX?.description ?: "" } set(description) { - pwDatabaseV4?.description = description - pwDatabaseV4?.descriptionChanged = PwDate() + mDatabaseKDBX?.description = description + mDatabaseKDBX?.descriptionChanged = DateInstant() } val allowDefaultUsername: Boolean - get() = pwDatabaseV4 != null - // TODO get() = pwDatabaseV3 != null || pwDatabaseV4 != null + get() = mDatabaseKDBX != null + // TODO get() = mDatabaseKDB != null || mDatabaseKDBX != null var defaultUsername: String get() { - return pwDatabaseV4?.defaultUserName ?: "" // TODO pwDatabaseV3 default username + return mDatabaseKDBX?.defaultUserName ?: "" // TODO mDatabaseKDB default username } set(username) { - pwDatabaseV4?.defaultUserName = username - pwDatabaseV4?.defaultUserNameChanged = PwDate() + mDatabaseKDBX?.defaultUserName = username + mDatabaseKDBX?.defaultUserNameChanged = DateInstant() } val allowCustomColor: Boolean - get() = pwDatabaseV4 != null - // TODO get() = pwDatabaseV3 != null || pwDatabaseV4 != null + get() = mDatabaseKDBX != null + // TODO get() = mDatabaseKDB != null || mDatabaseKDBX != null // with format "#000000" var customColor: String get() { - return pwDatabaseV4?.color ?: "" // TODO pwDatabaseV3 color + return mDatabaseKDBX?.color ?: "" // TODO mDatabaseKDB color } set(value) { // TODO Check color string - pwDatabaseV4?.color = value + mDatabaseKDBX?.color = value } val allowOTP: Boolean - get() = pwDatabaseV4 != null + get() = mDatabaseKDBX != null val version: String - get() = pwDatabaseV3?.version ?: pwDatabaseV4?.version ?: "-" + get() = mDatabaseKDB?.version ?: mDatabaseKDBX?.version ?: "-" val allowDataCompression: Boolean - get() = pwDatabaseV4 != null + get() = mDatabaseKDBX != null - val availableCompressionAlgorithms: List - get() = pwDatabaseV4?.availableCompressionAlgorithms ?: ArrayList() + val availableCompressionAlgorithms: List + get() = mDatabaseKDBX?.availableCompressionAlgorithms ?: ArrayList() - var compressionAlgorithm: PwCompressionAlgorithm? - get() = pwDatabaseV4?.compressionAlgorithm + var compressionAlgorithm: CompressionAlgorithm? + get() = mDatabaseKDBX?.compressionAlgorithm set(value) { value?.let { - pwDatabaseV4?.compressionAlgorithm = it + mDatabaseKDBX?.compressionAlgorithm = it } } - fun updateDataBinaryCompression(oldCompression: PwCompressionAlgorithm, - newCompression: PwCompressionAlgorithm) { - pwDatabaseV4?.changeBinaryCompression(oldCompression, newCompression) + fun updateDataBinaryCompression(oldCompression: CompressionAlgorithm, + newCompression: CompressionAlgorithm) { + mDatabaseKDBX?.changeBinaryCompression(oldCompression, newCompression) } val allowNoMasterKey: Boolean - get() = pwDatabaseV4 != null + get() = mDatabaseKDBX != null val allowEncryptionAlgorithmModification: Boolean get() = availableEncryptionAlgorithms.size > 1 fun getEncryptionAlgorithmName(resources: Resources): String { - return pwDatabaseV3?.encryptionAlgorithm?.getName(resources) - ?: pwDatabaseV4?.encryptionAlgorithm?.getName(resources) + return mDatabaseKDB?.encryptionAlgorithm?.getName(resources) + ?: mDatabaseKDBX?.encryptionAlgorithm?.getName(resources) ?: "" } - val availableEncryptionAlgorithms: List - get() = pwDatabaseV3?.availableEncryptionAlgorithms ?: pwDatabaseV4?.availableEncryptionAlgorithms ?: ArrayList() + val availableEncryptionAlgorithms: List + get() = mDatabaseKDB?.availableEncryptionAlgorithms ?: mDatabaseKDBX?.availableEncryptionAlgorithms ?: ArrayList() - var encryptionAlgorithm: PwEncryptionAlgorithm? - get() = pwDatabaseV3?.encryptionAlgorithm ?: pwDatabaseV4?.encryptionAlgorithm + var encryptionAlgorithm: EncryptionAlgorithm? + get() = mDatabaseKDB?.encryptionAlgorithm ?: mDatabaseKDBX?.encryptionAlgorithm set(algorithm) { algorithm?.let { - pwDatabaseV4?.encryptionAlgorithm = algorithm - pwDatabaseV4?.setDataEngine(algorithm.cipherEngine) - pwDatabaseV4?.dataCipher = algorithm.dataCipher + mDatabaseKDBX?.encryptionAlgorithm = algorithm + mDatabaseKDBX?.setDataEngine(algorithm.cipherEngine) + mDatabaseKDBX?.dataCipher = algorithm.dataCipher } } val availableKdfEngines: List - get() = pwDatabaseV3?.kdfAvailableList ?: pwDatabaseV4?.kdfAvailableList ?: ArrayList() + get() = mDatabaseKDB?.kdfAvailableList ?: mDatabaseKDBX?.kdfAvailableList ?: ArrayList() val allowKdfModification: Boolean get() = availableKdfEngines.size > 1 var kdfEngine: KdfEngine? - get() = pwDatabaseV3?.kdfEngine ?: pwDatabaseV4?.kdfEngine + get() = mDatabaseKDB?.kdfEngine ?: mDatabaseKDBX?.kdfEngine set(kdfEngine) { kdfEngine?.let { - if (pwDatabaseV4?.kdfParameters?.uuid != kdfEngine.defaultParameters.uuid) - pwDatabaseV4?.kdfParameters = kdfEngine.defaultParameters + if (mDatabaseKDBX?.kdfParameters?.uuid != kdfEngine.defaultParameters.uuid) + mDatabaseKDBX?.kdfParameters = kdfEngine.defaultParameters numberKeyEncryptionRounds = kdfEngine.defaultKeyRounds memoryUsage = kdfEngine.defaultMemoryUsage parallelism = kdfEngine.defaultParallelism @@ -192,62 +192,62 @@ class Database { } var numberKeyEncryptionRounds: Long - get() = pwDatabaseV3?.numberKeyEncryptionRounds ?: pwDatabaseV4?.numberKeyEncryptionRounds ?: 0 + get() = mDatabaseKDB?.numberKeyEncryptionRounds ?: mDatabaseKDBX?.numberKeyEncryptionRounds ?: 0 @Throws(NumberFormatException::class) set(numberRounds) { - pwDatabaseV3?.numberKeyEncryptionRounds = numberRounds - pwDatabaseV4?.numberKeyEncryptionRounds = numberRounds + mDatabaseKDB?.numberKeyEncryptionRounds = numberRounds + mDatabaseKDBX?.numberKeyEncryptionRounds = numberRounds } var memoryUsage: Long get() { - return pwDatabaseV4?.memoryUsage ?: return KdfEngine.UNKNOWN_VALUE.toLong() + return mDatabaseKDBX?.memoryUsage ?: return KdfEngine.UNKNOWN_VALUE.toLong() } set(memory) { - pwDatabaseV4?.memoryUsage = memory + mDatabaseKDBX?.memoryUsage = memory } var parallelism: Int - get() = pwDatabaseV4?.parallelism ?: KdfEngine.UNKNOWN_VALUE + get() = mDatabaseKDBX?.parallelism ?: KdfEngine.UNKNOWN_VALUE set(parallelism) { - pwDatabaseV4?.parallelism = parallelism + mDatabaseKDBX?.parallelism = parallelism } var masterKey: ByteArray - get() = pwDatabaseV3?.masterKey ?: pwDatabaseV4?.masterKey ?: ByteArray(32) + get() = mDatabaseKDB?.masterKey ?: mDatabaseKDBX?.masterKey ?: ByteArray(32) set(masterKey) { - pwDatabaseV3?.masterKey = masterKey - pwDatabaseV4?.masterKey = masterKey + mDatabaseKDB?.masterKey = masterKey + mDatabaseKDBX?.masterKey = masterKey } - val rootGroup: GroupVersioned? + val rootGroup: Group? get() { - pwDatabaseV3?.rootGroup?.let { - return GroupVersioned(it) + mDatabaseKDB?.rootGroup?.let { + return Group(it) } - pwDatabaseV4?.rootGroup?.let { - return GroupVersioned(it) + mDatabaseKDBX?.rootGroup?.let { + return Group(it) } return null } val manageHistory: Boolean - get() = pwDatabaseV4 != null + get() = mDatabaseKDBX != null var historyMaxItems: Int get() { - return pwDatabaseV4?.historyMaxItems ?: 0 + return mDatabaseKDBX?.historyMaxItems ?: 0 } set(value) { - pwDatabaseV4?.historyMaxItems = value + mDatabaseKDBX?.historyMaxItems = value } var historyMaxSize: Long get() { - return pwDatabaseV4?.historyMaxSize ?: 0 + return mDatabaseKDBX?.historyMaxSize ?: 0 } set(value) { - pwDatabaseV4?.historyMaxSize = value + mDatabaseKDBX?.historyMaxSize = value } /** @@ -255,48 +255,48 @@ class Database { * @return true if RecycleBin available */ val allowRecycleBin: Boolean - get() = pwDatabaseV4 != null + get() = mDatabaseKDBX != null var isRecycleBinEnabled: Boolean - // TODO #394 isRecycleBinEnabled pwDatabaseV3 - get() = pwDatabaseV3 != null || pwDatabaseV4?.isRecycleBinEnabled ?: false + // TODO #394 isRecycleBinEnabled mDatabaseKDB + get() = mDatabaseKDB != null || mDatabaseKDBX?.isRecycleBinEnabled ?: false set(value) { - pwDatabaseV4?.isRecycleBinEnabled = value + mDatabaseKDBX?.isRecycleBinEnabled = value } - val recycleBin: GroupVersioned? + val recycleBin: Group? get() { - pwDatabaseV3?.backupGroup?.let { - return GroupVersioned(it) + mDatabaseKDB?.backupGroup?.let { + return Group(it) } - pwDatabaseV4?.recycleBin?.let { - return GroupVersioned(it) + mDatabaseKDBX?.recycleBin?.let { + return Group(it) } return null } fun ensureRecycleBinExists(resources: Resources) { - pwDatabaseV3?.ensureRecycleBinExists() - pwDatabaseV4?.ensureRecycleBinExists(resources) + mDatabaseKDB?.ensureRecycleBinExists() + mDatabaseKDBX?.ensureRecycleBinExists(resources) } fun removeRecycleBin() { - // TODO #394 delete backup pwDatabaseV3?.removeRecycleBin() - pwDatabaseV4?.removeRecycleBin() + // TODO #394 delete backup mDatabaseKDB?.removeRecycleBin() + mDatabaseKDBX?.removeRecycleBin() } - private fun setDatabaseV3(pwDatabaseV3: PwDatabaseV3) { - this.pwDatabaseV3 = pwDatabaseV3 - this.pwDatabaseV4 = null + private fun setDatabaseKDB(databaseKDB: DatabaseKDB) { + this.mDatabaseKDB = databaseKDB + this.mDatabaseKDBX = null } - private fun setDatabaseV4(pwDatabaseV4: PwDatabaseV4) { - this.pwDatabaseV3 = null - this.pwDatabaseV4 = pwDatabaseV4 + private fun setDatabaseKDBX(databaseKDBX: DatabaseKDBX) { + this.mDatabaseKDB = null + this.mDatabaseKDBX = databaseKDBX } fun createData(databaseUri: Uri, databaseName: String, rootName: String) { - setDatabaseV4(PwDatabaseV4(databaseName, rootName)) + setDatabaseKDBX(DatabaseKDBX(databaseName, rootName)) this.fileUri = databaseUri } @@ -354,15 +354,15 @@ class Database { bufferedInputStream.reset() when { - // Header of database V3 - PwDbHeaderV3.matchesHeader(sig1, sig2) -> setDatabaseV3(ImporterV3() + // Header of database KDB + DatabaseHeaderKDB.matchesHeader(sig1, sig2) -> setDatabaseKDB(ImporterKDB() .openDatabase(bufferedInputStream, password, keyFileInputStream, progressTaskUpdater)) - // Header of database V4 - PwDbHeaderV4.matchesHeader(sig1, sig2) -> setDatabaseV4(ImporterV4( + // Header of database KDBX + DatabaseHeaderKDBX.matchesHeader(sig1, sig2) -> setDatabaseKDBX(ImporterKDBX( cacheDirectory, fixDuplicateUUID) .openDatabase(bufferedInputStream, @@ -378,57 +378,57 @@ class Database { loaded = true } - fun isGroupSearchable(group: GroupVersioned, isOmitBackup: Boolean): Boolean { - return pwDatabaseV3?.isGroupSearchable(group.pwGroupV3, isOmitBackup) ?: - pwDatabaseV4?.isGroupSearchable(group.pwGroupV4, isOmitBackup) ?: + fun isGroupSearchable(group: Group, isOmitBackup: Boolean): Boolean { + return mDatabaseKDB?.isGroupSearchable(group.groupKDB, isOmitBackup) ?: + mDatabaseKDBX?.isGroupSearchable(group.groupKDBX, isOmitBackup) ?: false } @JvmOverloads - fun search(str: String, max: Int = Integer.MAX_VALUE): GroupVersioned? { + fun search(str: String, max: Int = Integer.MAX_VALUE): Group? { return mSearchHelper?.search(this, str, max) } fun searchEntries(query: String): Cursor? { - var cursorV3: EntryCursorV3? = null - var cursorV4: EntryCursorV4? = null + var cursorKDB: EntryCursorKDB? = null + var cursorKDBX: EntryCursorKDBX? = null - if (pwDatabaseV3 != null) - cursorV3 = EntryCursorV3() - if (pwDatabaseV4 != null) - cursorV4 = EntryCursorV4() + if (mDatabaseKDB != null) + cursorKDB = EntryCursorKDB() + if (mDatabaseKDBX != null) + cursorKDBX = EntryCursorKDBX() val searchResult = search(query, SearchDbHelper.MAX_SEARCH_ENTRY) if (searchResult != null) { for (entry in searchResult.getChildEntries(true)) { - entry.pwEntryV3?.let { - cursorV3?.addEntry(it) + entry.entryKDB?.let { + cursorKDB?.addEntry(it) } - entry.pwEntryV4?.let { - cursorV4?.addEntry(it) + entry.entryKDBX?.let { + cursorKDBX?.addEntry(it) } } } - return cursorV3 ?: cursorV4 + return cursorKDB ?: cursorKDBX } - fun getEntryFrom(cursor: Cursor): EntryVersioned? { - val iconFactory = pwDatabaseV3?.iconFactory ?: pwDatabaseV4?.iconFactory ?: PwIconFactory() + fun getEntryFrom(cursor: Cursor): Entry? { + val iconFactory = mDatabaseKDB?.iconFactory ?: mDatabaseKDBX?.iconFactory ?: IconImageFactory() val entry = createEntry() // TODO invert field reference manager entry?.let { entryVersioned -> startManageEntry(entryVersioned) - pwDatabaseV3?.let { - entryVersioned.pwEntryV3?.let { entryV3 -> - (cursor as EntryCursorV3).populateEntry(entryV3, iconFactory) + mDatabaseKDB?.let { + entryVersioned.entryKDB?.let { entryKDB -> + (cursor as EntryCursorKDB).populateEntry(entryKDB, iconFactory) } } - pwDatabaseV4?.let { - entryVersioned.pwEntryV4?.let { entryV4 -> - (cursor as EntryCursorV4).populateEntry(entryV4, iconFactory) + mDatabaseKDBX?.let { + entryVersioned.entryKDBX?.let { entryKDBX -> + (cursor as EntryCursorKDBX).populateEntry(entryKDBX, iconFactory) } } stopManageEntry(entryVersioned) @@ -459,8 +459,8 @@ class Database { var fileOutputStream: FileOutputStream? = null try { fileOutputStream = FileOutputStream(tempFile) - val pmo = pwDatabaseV3?.let { PwDbV3Output(it, fileOutputStream) } - ?: pwDatabaseV4?.let { PwDbV4Output(it, fileOutputStream) } + val pmo = mDatabaseKDB?.let { DatabaseOutputKDB(it, fileOutputStream) } + ?: mDatabaseKDBX?.let { DatabaseOutputKDBX(it, fileOutputStream) } pmo?.output() } catch (e: Exception) { throw IOException(e) @@ -484,8 +484,8 @@ class Database { try { outputStream = contentResolver.openOutputStream(uri) val pmo = - pwDatabaseV3?.let { PwDbV3Output(it, outputStream) } - ?: pwDatabaseV4?.let { PwDbV4Output(it, outputStream) } + mDatabaseKDB?.let { DatabaseOutputKDB(it, outputStream) } + ?: mDatabaseKDBX?.let { DatabaseOutputKDBX(it, outputStream) } pmo?.output() } catch (e: Exception) { throw IOException(e) @@ -499,8 +499,8 @@ class Database { fun closeAndClear(filesDirectory: File? = null) { drawFactory.clearCache() // Delete the cache of the database if present - pwDatabaseV3?.clearCache() - pwDatabaseV4?.clearCache() + mDatabaseKDB?.clearCache() + mDatabaseKDBX?.clearCache() // In all cases, delete all the files in the temp dir try { FileUtils.cleanDirectory(filesDirectory) @@ -508,36 +508,36 @@ class Database { Log.e(TAG, "Unable to clear the directory cache.", e) } - this.pwDatabaseV3 = null - this.pwDatabaseV4 = null + this.mDatabaseKDB = null + this.mDatabaseKDBX = null this.fileUri = null this.loaded = false } fun validatePasswordEncoding(password: String?, containsKeyFile: Boolean): Boolean { - return pwDatabaseV3?.validatePasswordEncoding(password, containsKeyFile) - ?: pwDatabaseV4?.validatePasswordEncoding(password, containsKeyFile) + return mDatabaseKDB?.validatePasswordEncoding(password, containsKeyFile) + ?: mDatabaseKDBX?.validatePasswordEncoding(password, containsKeyFile) ?: false } @Throws(IOException::class) fun retrieveMasterKey(key: String?, keyInputStream: InputStream?) { - pwDatabaseV3?.retrieveMasterKey(key, keyInputStream) - pwDatabaseV4?.retrieveMasterKey(key, keyInputStream) + mDatabaseKDB?.retrieveMasterKey(key, keyInputStream) + mDatabaseKDBX?.retrieveMasterKey(key, keyInputStream) } fun rootCanContainsEntry(): Boolean { - return pwDatabaseV3?.rootCanContainsEntry() ?: pwDatabaseV4?.rootCanContainsEntry() ?: false + return mDatabaseKDB?.rootCanContainsEntry() ?: mDatabaseKDBX?.rootCanContainsEntry() ?: false } - fun createEntry(): EntryVersioned? { - pwDatabaseV3?.let { database -> - return EntryVersioned(database.createEntry()).apply { + fun createEntry(): Entry? { + mDatabaseKDB?.let { database -> + return Entry(database.createEntry()).apply { nodeId = database.newEntryId() } } - pwDatabaseV4?.let { database -> - return EntryVersioned(database.createEntry()).apply { + mDatabaseKDBX?.let { database -> + return Entry(database.createEntry()).apply { nodeId = database.newEntryId() } } @@ -545,14 +545,14 @@ class Database { return null } - fun createGroup(): GroupVersioned? { - pwDatabaseV3?.let { database -> - return GroupVersioned(database.createGroup()).apply { + fun createGroup(): Group? { + mDatabaseKDB?.let { database -> + return Group(database.createGroup()).apply { setNodeId(database.newGroupId()) } } - pwDatabaseV4?.let { database -> - return GroupVersioned(database.createGroup()).apply { + mDatabaseKDBX?.let { database -> + return Group(database.createGroup()).apply { setNodeId(database.newGroupId()) } } @@ -560,82 +560,82 @@ class Database { return null } - fun getEntryById(id: PwNodeId): EntryVersioned? { - pwDatabaseV3?.getEntryById(id)?.let { - return EntryVersioned(it) + fun getEntryById(id: NodeId): Entry? { + mDatabaseKDB?.getEntryById(id)?.let { + return Entry(it) } - pwDatabaseV4?.getEntryById(id)?.let { - return EntryVersioned(it) + mDatabaseKDBX?.getEntryById(id)?.let { + return Entry(it) } return null } - fun getGroupById(id: PwNodeId<*>): GroupVersioned? { - if (id is PwNodeIdInt) - pwDatabaseV3?.getGroupById(id)?.let { - return GroupVersioned(it) + fun getGroupById(id: NodeId<*>): Group? { + if (id is NodeIdInt) + mDatabaseKDB?.getGroupById(id)?.let { + return Group(it) } - else if (id is PwNodeIdUUID) - pwDatabaseV4?.getGroupById(id)?.let { - return GroupVersioned(it) + else if (id is NodeIdUUID) + mDatabaseKDBX?.getGroupById(id)?.let { + return Group(it) } return null } - fun addEntryTo(entry: EntryVersioned, parent: GroupVersioned) { - entry.pwEntryV3?.let { entryV3 -> - pwDatabaseV3?.addEntryTo(entryV3, parent.pwGroupV3) + fun addEntryTo(entry: Entry, parent: Group) { + entry.entryKDB?.let { entryKDB -> + mDatabaseKDB?.addEntryTo(entryKDB, parent.groupKDB) } - entry.pwEntryV4?.let { entryV4 -> - pwDatabaseV4?.addEntryTo(entryV4, parent.pwGroupV4) + entry.entryKDBX?.let { entryKDBX -> + mDatabaseKDBX?.addEntryTo(entryKDBX, parent.groupKDBX) } entry.afterAssignNewParent() } - fun updateEntry(entry: EntryVersioned) { - entry.pwEntryV3?.let { entryV3 -> - pwDatabaseV3?.updateEntry(entryV3) + fun updateEntry(entry: Entry) { + entry.entryKDB?.let { entryKDB -> + mDatabaseKDB?.updateEntry(entryKDB) } - entry.pwEntryV4?.let { entryV4 -> - pwDatabaseV4?.updateEntry(entryV4) + entry.entryKDBX?.let { entryKDBX -> + mDatabaseKDBX?.updateEntry(entryKDBX) } } - fun removeEntryFrom(entry: EntryVersioned, parent: GroupVersioned) { - entry.pwEntryV3?.let { entryV3 -> - pwDatabaseV3?.removeEntryFrom(entryV3, parent.pwGroupV3) + fun removeEntryFrom(entry: Entry, parent: Group) { + entry.entryKDB?.let { entryKDB -> + mDatabaseKDB?.removeEntryFrom(entryKDB, parent.groupKDB) } - entry.pwEntryV4?.let { entryV4 -> - pwDatabaseV4?.removeEntryFrom(entryV4, parent.pwGroupV4) + entry.entryKDBX?.let { entryKDBX -> + mDatabaseKDBX?.removeEntryFrom(entryKDBX, parent.groupKDBX) } entry.afterAssignNewParent() } - fun addGroupTo(group: GroupVersioned, parent: GroupVersioned) { - group.pwGroupV3?.let { groupV3 -> - pwDatabaseV3?.addGroupTo(groupV3, parent.pwGroupV3) + fun addGroupTo(group: Group, parent: Group) { + group.groupKDB?.let { entryKDB -> + mDatabaseKDB?.addGroupTo(entryKDB, parent.groupKDB) } - group.pwGroupV4?.let { groupV4 -> - pwDatabaseV4?.addGroupTo(groupV4, parent.pwGroupV4) + group.groupKDBX?.let { entryKDBX -> + mDatabaseKDBX?.addGroupTo(entryKDBX, parent.groupKDBX) } group.afterAssignNewParent() } - fun updateGroup(group: GroupVersioned) { - group.pwGroupV3?.let { groupV3 -> - pwDatabaseV3?.updateGroup(groupV3) + fun updateGroup(group: Group) { + group.groupKDB?.let { entryKDB -> + mDatabaseKDB?.updateGroup(entryKDB) } - group.pwGroupV4?.let { groupV4 -> - pwDatabaseV4?.updateGroup(groupV4) + group.groupKDBX?.let { entryKDBX -> + mDatabaseKDBX?.updateGroup(entryKDBX) } } - fun removeGroupFrom(group: GroupVersioned, parent: GroupVersioned) { - group.pwGroupV3?.let { groupV3 -> - pwDatabaseV3?.removeGroupFrom(groupV3, parent.pwGroupV3) + fun removeGroupFrom(group: Group, parent: Group) { + group.groupKDB?.let { entryKDB -> + mDatabaseKDB?.removeGroupFrom(entryKDB, parent.groupKDB) } - group.pwGroupV4?.let { groupV4 -> - pwDatabaseV4?.removeGroupFrom(groupV4, parent.pwGroupV4) + group.groupKDBX?.let { entryKDBX -> + mDatabaseKDBX?.removeGroupFrom(entryKDBX, parent.groupKDBX) } group.afterAssignNewParent() } @@ -645,45 +645,45 @@ class Database { * @param entryToCopy * @param newParent */ - fun copyEntryTo(entryToCopy: EntryVersioned, newParent: GroupVersioned): EntryVersioned? { - val entryCopied = EntryVersioned(entryToCopy, false) - entryCopied.nodeId = pwDatabaseV3?.newEntryId() ?: pwDatabaseV4?.newEntryId() ?: PwNodeIdUUID() + fun copyEntryTo(entryToCopy: Entry, newParent: Group): Entry? { + val entryCopied = Entry(entryToCopy, false) + entryCopied.nodeId = mDatabaseKDB?.newEntryId() ?: mDatabaseKDBX?.newEntryId() ?: NodeIdUUID() entryCopied.parent = newParent entryCopied.title += " (~)" addEntryTo(entryCopied, newParent) return entryCopied } - fun moveEntryTo(entryToMove: EntryVersioned, newParent: GroupVersioned) { + fun moveEntryTo(entryToMove: Entry, newParent: Group) { entryToMove.parent?.let { removeEntryFrom(entryToMove, it) } addEntryTo(entryToMove, newParent) } - fun moveGroupTo(groupToMove: GroupVersioned, newParent: GroupVersioned) { + fun moveGroupTo(groupToMove: Group, newParent: Group) { groupToMove.parent?.let { removeGroupFrom(groupToMove, it) } addGroupTo(groupToMove, newParent) } - fun deleteEntry(entry: EntryVersioned) { + fun deleteEntry(entry: Entry) { entry.parent?.let { removeEntryFrom(entry, it) } } - fun deleteGroup(group: GroupVersioned) { + fun deleteGroup(group: Group) { group.doForEachChildAndForIt( - object : NodeHandler() { - override fun operate(node: EntryVersioned): Boolean { + object : NodeHandler() { + override fun operate(node: Entry): Boolean { deleteEntry(node) return true } }, - object : NodeHandler() { - override fun operate(node: GroupVersioned): Boolean { + object : NodeHandler() { + override fun operate(node: Group): Boolean { node.parent?.let { removeGroupFrom(node, it) } @@ -692,98 +692,98 @@ class Database { }) } - fun undoDeleteEntry(entry: EntryVersioned, parent: GroupVersioned) { - entry.pwEntryV3?.let { entryV3 -> - pwDatabaseV3?.undoDeleteEntryFrom(entryV3, parent.pwGroupV3) + fun undoDeleteEntry(entry: Entry, parent: Group) { + entry.entryKDB?.let { + mDatabaseKDB?.undoDeleteEntryFrom(it, parent.groupKDB) } - entry.pwEntryV4?.let { entryV4 -> - pwDatabaseV4?.undoDeleteEntryFrom(entryV4, parent.pwGroupV4) + entry.entryKDBX?.let { + mDatabaseKDBX?.undoDeleteEntryFrom(it, parent.groupKDBX) } } - fun undoDeleteGroup(group: GroupVersioned, parent: GroupVersioned) { - group.pwGroupV3?.let { groupV3 -> - pwDatabaseV3?.undoDeleteGroupFrom(groupV3, parent.pwGroupV3) + fun undoDeleteGroup(group: Group, parent: Group) { + group.groupKDB?.let { + mDatabaseKDB?.undoDeleteGroupFrom(it, parent.groupKDB) } - group.pwGroupV4?.let { groupV4 -> - pwDatabaseV4?.undoDeleteGroupFrom(groupV4, parent.pwGroupV4) + group.groupKDBX?.let { + mDatabaseKDBX?.undoDeleteGroupFrom(it, parent.groupKDBX) } } - fun canRecycle(entry: EntryVersioned): Boolean { + fun canRecycle(entry: Entry): Boolean { var canRecycle: Boolean? = null - entry.pwEntryV3?.let { entryV3 -> - canRecycle = pwDatabaseV3?.canRecycle(entryV3) + entry.entryKDB?.let { + canRecycle = mDatabaseKDB?.canRecycle(it) } - entry.pwEntryV4?.let { entryV4 -> - canRecycle = pwDatabaseV4?.canRecycle(entryV4) + entry.entryKDBX?.let { + canRecycle = mDatabaseKDBX?.canRecycle(it) } return canRecycle ?: false } - fun canRecycle(group: GroupVersioned): Boolean { + fun canRecycle(group: Group): Boolean { var canRecycle: Boolean? = null - group.pwGroupV3?.let { groupV3 -> - canRecycle = pwDatabaseV3?.canRecycle(groupV3) + group.groupKDB?.let { + canRecycle = mDatabaseKDB?.canRecycle(it) } - group.pwGroupV4?.let { groupV4 -> - canRecycle = pwDatabaseV4?.canRecycle(groupV4) + group.groupKDBX?.let { + canRecycle = mDatabaseKDBX?.canRecycle(it) } return canRecycle ?: false } - fun recycle(entry: EntryVersioned, resources: Resources) { - entry.pwEntryV3?.let { - pwDatabaseV3?.recycle(it) + fun recycle(entry: Entry, resources: Resources) { + entry.entryKDB?.let { + mDatabaseKDB?.recycle(it) } - entry.pwEntryV4?.let { - pwDatabaseV4?.recycle(it, resources) + entry.entryKDBX?.let { + mDatabaseKDBX?.recycle(it, resources) } } - fun recycle(group: GroupVersioned, resources: Resources) { - group.pwGroupV3?.let { - pwDatabaseV3?.recycle(it) + fun recycle(group: Group, resources: Resources) { + group.groupKDB?.let { + mDatabaseKDB?.recycle(it) } - group.pwGroupV4?.let { - pwDatabaseV4?.recycle(it, resources) + group.groupKDBX?.let { + mDatabaseKDBX?.recycle(it, resources) } } - fun undoRecycle(entry: EntryVersioned, parent: GroupVersioned) { - entry.pwEntryV3?.let { entryV3 -> - parent.pwGroupV3?.let { parentV3 -> - pwDatabaseV3?.undoRecycle(entryV3, parentV3) + fun undoRecycle(entry: Entry, parent: Group) { + entry.entryKDB?.let { entryKDB -> + parent.groupKDB?.let { parentKDB -> + mDatabaseKDB?.undoRecycle(entryKDB, parentKDB) } } - entry.pwEntryV4?.let { entryV4 -> - parent.pwGroupV4?.let { parentV4 -> - pwDatabaseV4?.undoRecycle(entryV4, parentV4) + entry.entryKDBX?.let { entryKDBX -> + parent.groupKDBX?.let { parentKDBX -> + mDatabaseKDBX?.undoRecycle(entryKDBX, parentKDBX) } } } - fun undoRecycle(group: GroupVersioned, parent: GroupVersioned) { - group.pwGroupV3?.let { groupV3 -> - parent.pwGroupV3?.let { parentV3 -> - pwDatabaseV3?.undoRecycle(groupV3, parentV3) + fun undoRecycle(group: Group, parent: Group) { + group.groupKDB?.let { groupKDB -> + parent.groupKDB?.let { parentKDB -> + mDatabaseKDB?.undoRecycle(groupKDB, parentKDB) } } - group.pwGroupV4?.let { groupV4 -> - parent.pwGroupV4?.let { parentV4 -> - pwDatabaseV4?.undoRecycle(groupV4, parentV4) + group.groupKDBX?.let { entryKDBX -> + parent.groupKDBX?.let { parentKDBX -> + mDatabaseKDBX?.undoRecycle(entryKDBX, parentKDBX) } } } - fun startManageEntry(entry: EntryVersioned) { - pwDatabaseV4?.let { + fun startManageEntry(entry: Entry) { + mDatabaseKDBX?.let { entry.startToManageFieldReferences(it) } } - fun stopManageEntry(entry: EntryVersioned) { - pwDatabaseV4?.let { + fun stopManageEntry(entry: Entry) { + mDatabaseKDBX?.let { entry.stopToManageFieldReferences() } } @@ -793,14 +793,14 @@ class Database { */ fun removeOldestHistoryForEachEntry() { rootGroup?.doForEachChildAndForIt( - object : NodeHandler() { - override fun operate(node: EntryVersioned): Boolean { + object : NodeHandler() { + override fun operate(node: Entry): Boolean { removeOldestEntryHistory(node) return true } }, - object : NodeHandler() { - override fun operate(node: GroupVersioned): Boolean { + object : NodeHandler() { + override fun operate(node: Group): Boolean { return true } }) @@ -808,14 +808,14 @@ class Database { fun removeEachEntryHistory() { rootGroup?.doForEachChildAndForIt( - object : NodeHandler() { - override fun operate(node: EntryVersioned): Boolean { + object : NodeHandler() { + override fun operate(node: Entry): Boolean { node.removeAllHistory() return true } }, - object : NodeHandler() { - override fun operate(node: GroupVersioned): Boolean { + object : NodeHandler() { + override fun operate(node: Group): Boolean { return true } }) @@ -824,8 +824,8 @@ class Database { /** * Remove oldest history if more than max items or max memory */ - fun removeOldestEntryHistory(entry: EntryVersioned) { - pwDatabaseV4?.let { + fun removeOldestEntryHistory(entry: Entry) { + mDatabaseKDBX?.let { val maxItems = historyMaxItems if (maxItems >= 0) { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseKDB.kt similarity index 84% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseKDB.kt index 5ce6e34e0..f7f455c24 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseKDB.kt @@ -31,7 +31,7 @@ import java.security.NoSuchAlgorithmException import java.util.* import kotlin.collections.ArrayList -class PwDatabaseV3 : PwDatabase() { +class DatabaseKDB : DatabaseVersioned() { private var numKeyEncRounds: Int = 0 @@ -46,14 +46,14 @@ class PwDatabaseV3 : PwDatabase() { kdfListV3.add(KdfFactory.aesKdf) } - private fun getGroupById(groupId: Int): PwGroupV3? { + private fun getGroupById(groupId: Int): GroupKDB? { if (groupId == -1) return null - return getGroupById(PwNodeIdInt(groupId)) + return getGroupById(NodeIdInt(groupId)) } // Retrieve backup group in index - val backupGroup: PwGroupV3? + val backupGroup: GroupKDB? get() = if (backupGroupId == BACKUP_FOLDER_UNDEFINED_ID) null else getGroupById(backupGroupId) override val kdfEngine: KdfEngine? @@ -62,16 +62,16 @@ class PwDatabaseV3 : PwDatabase() { override val kdfAvailableList: List get() = kdfListV3 - override val availableEncryptionAlgorithms: List + override val availableEncryptionAlgorithms: List get() { - val list = ArrayList() - list.add(PwEncryptionAlgorithm.AESRijndael) + val list = ArrayList() + list.add(EncryptionAlgorithm.AESRijndael) return list } - val rootGroups: List + val rootGroups: List get() { - val kids = ArrayList() + val kids = ArrayList() doForEachGroupInIndex { group -> if (group.level == 0) kids.add(group) @@ -93,7 +93,7 @@ class PwDatabaseV3 : PwDatabase() { } init { - algorithm = PwEncryptionAlgorithm.AESRijndael + algorithm = EncryptionAlgorithm.AESRijndael numKeyEncRounds = DEFAULT_ENCRYPTION_ROUNDS } @@ -102,10 +102,10 @@ class PwDatabaseV3 : PwDatabase() { * * @return new tree id */ - override fun newGroupId(): PwNodeIdInt { - var newId: PwNodeIdInt + override fun newGroupId(): NodeIdInt { + var newId: NodeIdInt do { - newId = PwNodeIdInt() + newId = NodeIdInt() } while (isGroupIdUsed(newId)) return newId @@ -116,10 +116,10 @@ class PwDatabaseV3 : PwDatabase() { * * @return new tree id */ - override fun newEntryId(): PwNodeIdUUID { - var newId: PwNodeIdUUID + override fun newEntryId(): NodeIdUUID { + var newId: NodeIdUUID do { - newId = PwNodeIdUUID() + newId = NodeIdUUID() } while (isEntryIdUsed(newId)) return newId @@ -164,12 +164,12 @@ class PwDatabaseV3 : PwDatabase() { return null } - override fun createGroup(): PwGroupV3 { - return PwGroupV3() + override fun createGroup(): GroupKDB { + return GroupKDB() } - override fun createEntry(): PwEntryV3 { - return PwEntryV3() + override fun createEntry(): EntryKDB { + return EntryKDB() } override fun rootCanContainsEntry(): Boolean { @@ -180,8 +180,8 @@ class PwDatabaseV3 : PwDatabase() { return false } - override fun isInRecycleBin(group: PwGroupV3): Boolean { - var currentGroup: PwGroupV3? = group + override fun isInRecycleBin(group: GroupKDB): Boolean { + var currentGroup: GroupKDB? = group if (currentGroup == backupGroup) return true @@ -225,31 +225,31 @@ class PwDatabaseV3 : PwDatabase() { * @param node Node to remove * @return true if node can be recycle, false elsewhere */ - fun canRecycle(node: PwNode<*, PwGroupV3, PwEntryV3>): Boolean { + fun canRecycle(node: NodeVersioned<*, GroupKDB, EntryKDB>): Boolean { // TODO #394 Backup pw3 return true } - fun recycle(group: PwGroupV3) { + fun recycle(group: GroupKDB) { ensureRecycleBinExists() removeGroupFrom(group, group.parent) addGroupTo(group, backupGroup) group.afterAssignNewParent() } - fun recycle(entry: PwEntryV3) { + fun recycle(entry: EntryKDB) { ensureRecycleBinExists() removeEntryFrom(entry, entry.parent) addEntryTo(entry, backupGroup) entry.afterAssignNewParent() } - fun undoRecycle(group: PwGroupV3, origParent: PwGroupV3) { + fun undoRecycle(group: GroupKDB, origParent: GroupKDB) { removeGroupFrom(group, backupGroup) addGroupTo(group, origParent) } - fun undoRecycle(entry: PwEntryV3, origParent: PwGroupV3) { + fun undoRecycle(entry: EntryKDB, origParent: GroupKDB) { removeEntryFrom(entry, backupGroup) addEntryTo(entry, origParent) } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseKDBX.kt similarity index 79% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseKDBX.kt index 99f48f596..c594e4311 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseKDBX.kt @@ -29,10 +29,10 @@ import com.kunzisoft.keepass.crypto.engine.CipherEngine import com.kunzisoft.keepass.crypto.keyDerivation.KdfEngine import com.kunzisoft.keepass.crypto.keyDerivation.KdfFactory import com.kunzisoft.keepass.crypto.keyDerivation.KdfParameters -import com.kunzisoft.keepass.database.element.PwDatabaseV3.Companion.BACKUP_FOLDER_TITLE +import com.kunzisoft.keepass.database.element.DatabaseKDB.Companion.BACKUP_FOLDER_TITLE import com.kunzisoft.keepass.database.exception.UnknownKDF -import com.kunzisoft.keepass.database.file.PwDbHeaderV4.Companion.FILE_VERSION_32_3 -import com.kunzisoft.keepass.database.file.PwDbHeaderV4.Companion.FILE_VERSION_32_4 +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX.Companion.FILE_VERSION_32_3 +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX.Companion.FILE_VERSION_32_4 import com.kunzisoft.keepass.utils.VariantDictionary import org.w3c.dom.Node import org.w3c.dom.Text @@ -46,30 +46,30 @@ import javax.xml.parsers.DocumentBuilderFactory import javax.xml.parsers.ParserConfigurationException -class PwDatabaseV4 : PwDatabase { +class DatabaseKDBX : DatabaseVersioned { var hmacKey: ByteArray? = null private set var dataCipher = AesEngine.CIPHER_UUID private var dataEngine: CipherEngine = AesEngine() - var compressionAlgorithm = PwCompressionAlgorithm.GZip + var compressionAlgorithm = CompressionAlgorithm.GZip var kdfParameters: KdfParameters? = null - private var kdfV4List: MutableList = ArrayList() + private var kdfList: MutableList = ArrayList() private var numKeyEncRounds: Long = 0 var publicCustomData = VariantDictionary() var kdbxVersion: Long = 0 var name = "" - var nameChanged = PwDate() + var nameChanged = DateInstant() // TODO change setting date - var settingsChanged = PwDate() + var settingsChanged = DateInstant() var description = "" - var descriptionChanged = PwDate() + var descriptionChanged = DateInstant() var defaultUserName = "" - var defaultUserNameChanged = PwDate() + var defaultUserNameChanged = DateInstant() // TODO date - var keyLastChanged = PwDate() + var keyLastChanged = DateInstant() var keyChangeRecDays: Long = -1 var keyChangeForceDays: Long = 1 var isKeyChangeForceOnce = false @@ -84,14 +84,14 @@ class PwDatabaseV4 : PwDatabase { var recycleBinUUID: UUID = UUID_ZERO var recycleBinChanged = Date() var entryTemplatesGroup = UUID_ZERO - var entryTemplatesGroupChanged = PwDate() + var entryTemplatesGroupChanged = DateInstant() var historyMaxItems = DEFAULT_HISTORY_MAX_ITEMS var historyMaxSize = DEFAULT_HISTORY_MAX_SIZE var lastSelectedGroupUUID = UUID_ZERO var lastTopVisibleGroupUUID = UUID_ZERO var memoryProtection = MemoryProtectionConfig() - val deletedObjects = ArrayList() - val customIcons = ArrayList() + val deletedObjects = ArrayList() + val customIcons = ArrayList() val customData = HashMap() var binaryPool = BinaryPool() @@ -99,8 +99,8 @@ class PwDatabaseV4 : PwDatabase { var localizedAppName = "KeePassDX" init { - kdfV4List.add(KdfFactory.aesKdf) - kdfV4List.add(KdfFactory.argon2Kdf) + kdfList.add(KdfFactory.aesKdf) + kdfList.add(KdfFactory.argon2Kdf) } constructor() @@ -110,12 +110,12 @@ class PwDatabaseV4 : PwDatabase { */ constructor(databaseName: String, rootName: String) { name = databaseName - val groupV4 = createGroup().apply { + val group = createGroup().apply { title = rootName icon = iconFactory.folderIcon } - rootGroup = groupV4 - addGroupIndex(groupV4) + rootGroup = group + addGroupIndex(group) } override val version: String @@ -130,22 +130,22 @@ class PwDatabaseV4 : PwDatabase { override val kdfEngine: KdfEngine? get() = try { - getEngineV4(kdfParameters) + getEngineKDBX4(kdfParameters) } catch (unknownKDF: UnknownKDF) { Log.i(TAG, "Unable to retrieve KDF engine", unknownKDF) null } override val kdfAvailableList: List - get() = kdfV4List + get() = kdfList @Throws(UnknownKDF::class) - fun getEngineV4(kdfParameters: KdfParameters?): KdfEngine { + fun getEngineKDBX4(kdfParameters: KdfParameters?): KdfEngine { val unknownKDFException = UnknownKDF() if (kdfParameters == null) { throw unknownKDFException } - for (engine in kdfV4List) { + for (engine in kdfList) { if (engine.uuid == kdfParameters.uuid) { return engine } @@ -153,37 +153,37 @@ class PwDatabaseV4 : PwDatabase { throw unknownKDFException } - val availableCompressionAlgorithms: List + val availableCompressionAlgorithms: List get() { - val list = ArrayList() - list.add(PwCompressionAlgorithm.None) - list.add(PwCompressionAlgorithm.GZip) + val list = ArrayList() + list.add(CompressionAlgorithm.None) + list.add(CompressionAlgorithm.GZip) return list } - fun changeBinaryCompression(oldCompression: PwCompressionAlgorithm, - newCompression: PwCompressionAlgorithm) { + fun changeBinaryCompression(oldCompression: CompressionAlgorithm, + newCompression: CompressionAlgorithm) { binaryPool.doForEachBinary { key, binary -> try { when (oldCompression) { - PwCompressionAlgorithm.None -> { + CompressionAlgorithm.None -> { when (newCompression) { - PwCompressionAlgorithm.None -> { + CompressionAlgorithm.None -> { } - PwCompressionAlgorithm.GZip -> { + CompressionAlgorithm.GZip -> { // To compress, create a new binary with file binary.compress() } } } - PwCompressionAlgorithm.GZip -> { + CompressionAlgorithm.GZip -> { when (newCompression) { - PwCompressionAlgorithm.None -> { + CompressionAlgorithm.None -> { // To decompress, create a new binary with file binary.decompress() } - PwCompressionAlgorithm.GZip -> { + CompressionAlgorithm.GZip -> { } } } @@ -194,12 +194,12 @@ class PwDatabaseV4 : PwDatabase { } } - override val availableEncryptionAlgorithms: List + override val availableEncryptionAlgorithms: List get() { - val list = ArrayList() - list.add(PwEncryptionAlgorithm.AESRijndael) - list.add(PwEncryptionAlgorithm.Twofish) - list.add(PwEncryptionAlgorithm.ChaCha20) + val list = ArrayList() + list.add(EncryptionAlgorithm.AESRijndael) + list.add(EncryptionAlgorithm.Twofish) + list.add(EncryptionAlgorithm.ChaCha20) return list } @@ -247,31 +247,31 @@ class PwDatabaseV4 : PwDatabase { override val passwordEncoding: String get() = "UTF-8" - private fun getGroupByUUID(groupUUID: UUID): PwGroupV4? { + private fun getGroupByUUID(groupUUID: UUID): GroupKDBX? { if (groupUUID == UUID_ZERO) return null - return getGroupById(PwNodeIdUUID(groupUUID)) + return getGroupById(NodeIdUUID(groupUUID)) } // Retrieve recycle bin in index - val recycleBin: PwGroupV4? + val recycleBin: GroupKDBX? get() = if (recycleBinUUID == UUID_ZERO) null else getGroupByUUID(recycleBinUUID) - val lastSelectedGroup: PwGroupV4? + val lastSelectedGroup: GroupKDBX? get() = getGroupByUUID(lastSelectedGroupUUID) - val lastTopVisibleGroup: PwGroupV4? + val lastTopVisibleGroup: GroupKDBX? get() = getGroupByUUID(lastTopVisibleGroupUUID) fun setDataEngine(dataEngine: CipherEngine) { this.dataEngine = dataEngine } - fun getCustomIcons(): List { + fun getCustomIcons(): List { return customIcons } - fun addCustomIcon(customIcon: PwIconCustom) { + fun addCustomIcon(customIcon: IconImageCustom) { this.customIcons.add(customIcon) } @@ -314,7 +314,7 @@ class PwDatabaseV4 : PwDatabase { fun makeFinalKey(masterSeed: ByteArray) { kdfParameters?.let { keyDerivationFunctionParameters -> - val kdfEngine = getEngineV4(keyDerivationFunctionParameters) + val kdfEngine = getEngineKDBX4(keyDerivationFunctionParameters) var transformedMasterKey = kdfEngine.transform(masterKey, keyDerivationFunctionParameters) if (transformedMasterKey.size != 32) { @@ -390,39 +390,39 @@ class PwDatabaseV4 : PwDatabase { return null } - override fun newGroupId(): PwNodeIdUUID { - var newId: PwNodeIdUUID + override fun newGroupId(): NodeIdUUID { + var newId: NodeIdUUID do { - newId = PwNodeIdUUID() + newId = NodeIdUUID() } while (isGroupIdUsed(newId)) return newId } - override fun newEntryId(): PwNodeIdUUID { - var newId: PwNodeIdUUID + override fun newEntryId(): NodeIdUUID { + var newId: NodeIdUUID do { - newId = PwNodeIdUUID() + newId = NodeIdUUID() } while (isEntryIdUsed(newId)) return newId } - override fun createGroup(): PwGroupV4 { - return PwGroupV4() + override fun createGroup(): GroupKDBX { + return GroupKDBX() } - override fun createEntry(): PwEntryV4 { - return PwEntryV4() + override fun createEntry(): EntryKDBX { + return EntryKDBX() } override fun rootCanContainsEntry(): Boolean { return true } - override fun isInRecycleBin(group: PwGroupV4): Boolean { + override fun isInRecycleBin(group: GroupKDBX): Boolean { // To keep compatibility with old V1 databases - var currentGroup: PwGroupV4? = group + var currentGroup: GroupKDBX? = group while (currentGroup != null) { if (currentGroup.parent == rootGroup && currentGroup.title.equals(BACKUP_FOLDER_TITLE, ignoreCase = true)) { @@ -462,7 +462,7 @@ class PwDatabaseV4 : PwDatabase { fun removeRecycleBin() { if (recycleBin != null) { recycleBinUUID = UUID_ZERO - recycleBinChanged = PwDate().date + recycleBinChanged = DateInstant().date } } @@ -471,7 +471,7 @@ class PwDatabaseV4 : PwDatabase { * @param node Node to remove * @return true if node can be recycle, false elsewhere */ - fun canRecycle(node: PwNode<*, PwGroupV4, PwEntryV4>): Boolean { + fun canRecycle(node: NodeVersioned<*, GroupKDBX, EntryKDBX>): Boolean { if (!isRecycleBinEnabled) return false if (recycleBin == null) @@ -481,46 +481,46 @@ class PwDatabaseV4 : PwDatabase { return false } - fun recycle(group: PwGroupV4, resources: Resources) { + fun recycle(group: GroupKDBX, resources: Resources) { ensureRecycleBinExists(resources) removeGroupFrom(group, group.parent) addGroupTo(group, recycleBin) group.afterAssignNewParent() } - fun recycle(entry: PwEntryV4, resources: Resources) { + fun recycle(entry: EntryKDBX, resources: Resources) { ensureRecycleBinExists(resources) removeEntryFrom(entry, entry.parent) addEntryTo(entry, recycleBin) entry.afterAssignNewParent() } - fun undoRecycle(group: PwGroupV4, origParent: PwGroupV4) { + fun undoRecycle(group: GroupKDBX, origParent: GroupKDBX) { removeGroupFrom(group, recycleBin) addGroupTo(group, origParent) } - fun undoRecycle(entry: PwEntryV4, origParent: PwGroupV4) { + fun undoRecycle(entry: EntryKDBX, origParent: GroupKDBX) { removeEntryFrom(entry, recycleBin) addEntryTo(entry, origParent) } - fun getDeletedObjects(): List { + fun getDeletedObjects(): List { return deletedObjects } - fun addDeletedObject(deletedObject: PwDeletedObject) { + fun addDeletedObject(deletedObject: DeletedObject) { this.deletedObjects.add(deletedObject) } - override fun removeEntryFrom(entryToRemove: PwEntryV4, parent: PwGroupV4?) { + override fun removeEntryFrom(entryToRemove: EntryKDBX, parent: GroupKDBX?) { super.removeEntryFrom(entryToRemove, parent) - deletedObjects.add(PwDeletedObject(entryToRemove.id)) + deletedObjects.add(DeletedObject(entryToRemove.id)) } - override fun undoDeleteEntryFrom(entry: PwEntryV4, origParent: PwGroupV4?) { + override fun undoDeleteEntryFrom(entry: EntryKDBX, origParent: GroupKDBX?) { super.undoDeleteEntryFrom(entry, origParent) - deletedObjects.remove(PwDeletedObject(entry.id)) + deletedObjects.remove(DeletedObject(entry.id)) } fun containsPublicCustomData(): Boolean { @@ -543,7 +543,7 @@ class PwDatabaseV4 : PwDatabase { } companion object { - private val TAG = PwDatabaseV4::class.java.name + private val TAG = DatabaseKDBX::class.java.name private const val DEFAULT_HISTORY_MAX_ITEMS = 10 // -1 unlimited private const val DEFAULT_HISTORY_MAX_SIZE = (6 * 1024 * 1024).toLong() // -1 unlimited diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV4XML.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseKDBXXML.kt similarity index 99% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV4XML.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseKDBXXML.kt index 56c2e810d..7fe829991 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV4XML.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseKDBXXML.kt @@ -22,7 +22,7 @@ package com.kunzisoft.keepass.database.element import java.text.SimpleDateFormat import java.util.* -object PwDatabaseV4XML { +object DatabaseKDBXXML { const val ElemDocNode = "KeePassFile" const val ElemMeta = "Meta" diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabase.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseVersioned.kt similarity index 91% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabase.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseVersioned.kt index 544c714b7..5ccc93b4c 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabase.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/DatabaseVersioned.kt @@ -28,15 +28,15 @@ import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.util.* -abstract class PwDatabase< +abstract class DatabaseVersioned< GroupId, EntryId, - Group : PwGroup, - Entry : PwEntry + Group : GroupVersioned, + Entry : EntryVersioned > { // Algorithm used to encrypt the database - protected var algorithm: PwEncryptionAlgorithm? = null + protected var algorithm: EncryptionAlgorithm? = null abstract val kdfEngine: KdfEngine? @@ -46,13 +46,13 @@ abstract class PwDatabase< var finalKey: ByteArray? = null protected set - var iconFactory = PwIconFactory() + var iconFactory = IconImageFactory() protected set var changeDuplicateId = false - private var groupIndexes = LinkedHashMap, Group>() - private var entryIndexes = LinkedHashMap, Entry>() + private var groupIndexes = LinkedHashMap, Group>() + private var entryIndexes = LinkedHashMap, Entry>() abstract val version: String @@ -60,15 +60,15 @@ abstract class PwDatabase< abstract var numberKeyEncryptionRounds: Long - var encryptionAlgorithm: PwEncryptionAlgorithm + var encryptionAlgorithm: EncryptionAlgorithm get() { - return algorithm ?: PwEncryptionAlgorithm.AESRijndael + return algorithm ?: EncryptionAlgorithm.AESRijndael } set(algorithm) { this.algorithm = algorithm } - abstract val availableEncryptionAlgorithms: List + abstract val availableEncryptionAlgorithms: List var rootGroup: Group? = null @@ -192,9 +192,9 @@ abstract class PwDatabase< * ------------------------------------- */ - abstract fun newGroupId(): PwNodeId + abstract fun newGroupId(): NodeId - abstract fun newEntryId(): PwNodeId + abstract fun newEntryId(): NodeId abstract fun createGroup(): Group @@ -219,7 +219,7 @@ abstract class PwDatabase< * ID number to check for * @return True if the ID is used, false otherwise */ - fun isGroupIdUsed(id: PwNodeId): Boolean { + fun isGroupIdUsed(id: NodeId): Boolean { return groupIndexes.containsKey(id) } @@ -234,7 +234,7 @@ abstract class PwDatabase< } } - fun getGroupById(id: PwNodeId): Group? { + fun getGroupById(id: NodeId): Group? { return this.groupIndexes[id] } @@ -275,7 +275,7 @@ abstract class PwDatabase< } } - fun isEntryIdUsed(id: PwNodeId): Boolean { + fun isEntryIdUsed(id: NodeId): Boolean { return entryIndexes.containsKey(id) } @@ -283,7 +283,7 @@ abstract class PwDatabase< return entryIndexes.values } - fun getEntryById(id: PwNodeId): Entry? { + fun getEntryById(id: NodeId): Entry? { return this.entryIndexes[id] } @@ -388,7 +388,7 @@ abstract class PwDatabase< companion object { - private const val TAG = "PwDatabase" + private const val TAG = "DatabaseVersioned" val UUID_ZERO = UUID(0, 0) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDate.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/DateInstant.kt similarity index 86% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwDate.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/DateInstant.kt index 5d8cd906a..5b3eded9a 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDate.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/DateInstant.kt @@ -23,21 +23,16 @@ import android.content.res.Resources import android.os.Parcel import android.os.Parcelable import androidx.core.os.ConfigurationCompat -import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils import java.util.* -/** - * Converting from the C Date format to the Java data format is - * expensive when done for every record at once. - */ -class PwDate : Parcelable { +class DateInstant : Parcelable { private var jDate: Date = Date() val date: Date get() = jDate - constructor(source: PwDate) { + constructor(source: DateInstant) { this.jDate = Date(source.jDate.time) } @@ -80,7 +75,7 @@ class PwDate : Parcelable { return false } - val date = other as PwDate + val date = other as DateInstant return isSameDate(jDate, date.jDate) } @@ -96,7 +91,7 @@ class PwDate : Parcelable { val NEVER_EXPIRE = neverExpire - private val neverExpire: PwDate + private val neverExpire: DateInstant get() { val cal = Calendar.getInstance() cal.set(Calendar.YEAR, 2999) @@ -106,16 +101,16 @@ class PwDate : Parcelable { cal.set(Calendar.MINUTE, 59) cal.set(Calendar.SECOND, 59) - return PwDate(cal.time) + return DateInstant(cal.time) } @JvmField - val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwDate { - return PwDate(parcel) + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): DateInstant { + return DateInstant(parcel) } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDeletedObject.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/DeletedObject.kt similarity index 93% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwDeletedObject.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/DeletedObject.kt index f0d78f5dd..c82a0f7e5 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDeletedObject.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/DeletedObject.kt @@ -22,9 +22,9 @@ package com.kunzisoft.keepass.database.element import java.util.Date import java.util.UUID -class PwDeletedObject { +class DeletedObject { - var uuid: UUID = PwDatabase.UUID_ZERO + var uuid: UUID = DatabaseVersioned.UUID_ZERO var deletionTime: Date? = null get() = if (field == null) { Date(System.currentTimeMillis()) @@ -43,7 +43,7 @@ class PwDeletedObject { return true if (other == null) return false - if (other !is PwDeletedObject) + if (other !is DeletedObject) return false return uuid == other.uuid } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEncryptionAlgorithm.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/EncryptionAlgorithm.kt similarity index 97% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwEncryptionAlgorithm.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/EncryptionAlgorithm.kt index d214bd9cd..d31de59ae 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEncryptionAlgorithm.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/EncryptionAlgorithm.kt @@ -30,7 +30,7 @@ import com.kunzisoft.keepass.utils.ObjectNameResource import java.util.UUID -enum class PwEncryptionAlgorithm : ObjectNameResource { +enum class EncryptionAlgorithm : ObjectNameResource { AESRijndael, Twofish, diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Entry.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Entry.kt new file mode 100644 index 000000000..762e372b8 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Entry.kt @@ -0,0 +1,395 @@ +package com.kunzisoft.keepass.database.element + +import android.os.Parcel +import android.os.Parcelable +import com.kunzisoft.keepass.database.element.security.ProtectedString +import com.kunzisoft.keepass.model.EntryInfo +import com.kunzisoft.keepass.model.Field +import com.kunzisoft.keepass.otp.OtpElement +import com.kunzisoft.keepass.otp.OtpEntryFields +import java.util.* +import kotlin.collections.ArrayList + +class Entry : Node, EntryVersionedInterface { + + var entryKDB: EntryKDB? = null + private set + var entryKDBX: EntryKDBX? = null + private set + + fun updateWith(entry: Entry, copyHistory: Boolean = true) { + entry.entryKDB?.let { + this.entryKDB?.updateWith(it) + } + entry.entryKDBX?.let { + this.entryKDBX?.updateWith(it, copyHistory) + } + } + + /** + * Use this constructor to copy an Entry with exact same values + */ + constructor(entry: Entry, copyHistory: Boolean = true) { + if (entry.entryKDB != null) { + this.entryKDB = EntryKDB() + } + if (entry.entryKDBX != null) { + this.entryKDBX = EntryKDBX() + } + updateWith(entry, copyHistory) + } + + constructor(entry: EntryKDB) { + this.entryKDBX = null + this.entryKDB = entry + } + + constructor(entry: EntryKDBX) { + this.entryKDB = null + this.entryKDBX = entry + } + + constructor(parcel: Parcel) { + entryKDB = parcel.readParcelable(EntryKDB::class.java.classLoader) + entryKDBX = parcel.readParcelable(EntryKDBX::class.java.classLoader) + } + + override fun describeContents(): Int { + return 0 + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeParcelable(entryKDB, flags) + dest.writeParcelable(entryKDBX, flags) + } + + override var nodeId: NodeId + get() = entryKDBX?.nodeId ?: entryKDB?.nodeId ?: NodeIdUUID() + set(value) { + entryKDB?.nodeId = value + entryKDBX?.nodeId = value + } + + override var title: String + get() = entryKDB?.title ?: entryKDBX?.title ?: "" + set(value) { + entryKDB?.title = value + entryKDBX?.title = value + } + + override var icon: IconImage + get() { + return entryKDB?.icon ?: entryKDBX?.icon ?: IconImageStandard() + } + set(value) { + entryKDB?.icon = value + entryKDBX?.icon = value + } + + override val type: Type + get() = Type.ENTRY + + override var parent: Group? + get() { + entryKDB?.parent?.let { + return Group(it) + } + entryKDBX?.parent?.let { + return Group(it) + } + return null + } + set(value) { + entryKDB?.parent = value?.groupKDB + entryKDBX?.parent = value?.groupKDBX + } + + override fun containsParent(): Boolean { + return entryKDB?.containsParent() ?: entryKDBX?.containsParent() ?: false + } + + override fun afterAssignNewParent() { + entryKDBX?.afterChangeParent() + } + + override fun touch(modified: Boolean, touchParents: Boolean) { + entryKDB?.touch(modified, touchParents) + entryKDBX?.touch(modified, touchParents) + } + + override fun isContainedIn(container: Group): Boolean { + var contained: Boolean? = false + container.groupKDB?.let { + contained = entryKDB?.isContainedIn(it) + } + container.groupKDBX?.let { + contained = entryKDBX?.isContainedIn(it) + } + return contained ?: false + } + + override var creationTime: DateInstant + get() = entryKDB?.creationTime ?: entryKDBX?.creationTime ?: DateInstant() + set(value) { + entryKDB?.creationTime = value + entryKDBX?.creationTime = value + } + + override var lastModificationTime: DateInstant + get() = entryKDB?.lastModificationTime ?: entryKDBX?.lastModificationTime ?: DateInstant() + set(value) { + entryKDB?.lastModificationTime = value + entryKDBX?.lastModificationTime = value + } + + override var lastAccessTime: DateInstant + get() = entryKDB?.lastAccessTime ?: entryKDBX?.lastAccessTime ?: DateInstant() + set(value) { + entryKDB?.lastAccessTime = value + entryKDBX?.lastAccessTime = value + } + + override var expiryTime: DateInstant + get() = entryKDB?.expiryTime ?: entryKDBX?.expiryTime ?: DateInstant() + set(value) { + entryKDB?.expiryTime = value + entryKDBX?.expiryTime = value + } + + override var expires: Boolean + get() = entryKDB?.expires ?: entryKDBX?.expires ?: false + set(value) { + entryKDB?.expires = value + entryKDBX?.expires = value + } + + override val isCurrentlyExpires: Boolean + get() = entryKDB?.isCurrentlyExpires ?: entryKDBX?.isCurrentlyExpires ?: false + + override var username: String + get() = entryKDB?.username ?: entryKDBX?.username ?: "" + set(value) { + entryKDB?.username = value + entryKDBX?.username = value + } + + override var password: String + get() = entryKDB?.password ?: entryKDBX?.password ?: "" + set(value) { + entryKDB?.password = value + entryKDBX?.password = value + } + + override var url: String + get() = entryKDB?.url ?: entryKDBX?.url ?: "" + set(value) { + entryKDB?.url = value + entryKDBX?.url = value + } + + override var notes: String + get() = entryKDB?.notes ?: entryKDBX?.notes ?: "" + set(value) { + entryKDB?.notes = value + entryKDBX?.notes = value + } + + private fun isTan(): Boolean { + return title == PMS_TAN_ENTRY && username.isNotEmpty() + } + + fun getVisualTitle(): String { + return getVisualTitle(isTan(), + title, + username, + url, + nodeId.toString()) + } + + /* + ------------ + KDB Methods + ------------ + */ + + /** + * If it's a node with only meta information like Meta-info SYSTEM Database Color + * @return false by default, true if it's a meta stream + */ + val isMetaStream: Boolean + get() = entryKDB?.isMetaStream ?: false + + /* + ------------ + KDBX Methods + ------------ + */ + + var iconCustom: IconImageCustom + get() = entryKDBX?.iconCustom ?: IconImageCustom.UNKNOWN_ICON + set(value) { + entryKDBX?.iconCustom = value + } + + /** + * Retrieve custom fields to show, key is the label, value is the value of field (protected or not) + * @return Map of label/value + */ + val customFields: HashMap + get() = entryKDBX?.customFields ?: HashMap() + + /** + * To redefine if version of entry allow custom field, + * @return true if entry allows custom field + */ + fun allowCustomFields(): Boolean { + return entryKDBX?.allowCustomFields() ?: false + } + + fun removeAllFields() { + entryKDBX?.removeAllFields() + } + + /** + * Update or add an extra field to the list (standard or custom) + * @param label Label of field, must be unique + * @param value Value of field + */ + fun putExtraField(label: String, value: ProtectedString) { + entryKDBX?.putExtraField(label, value) + } + + fun getOtpElement(): OtpElement? { + return OtpEntryFields.parseFields { key -> + customFields[key]?.toString() + } + } + + fun startToManageFieldReferences(db: DatabaseKDBX) { + entryKDBX?.startToManageFieldReferences(db) + } + + fun stopToManageFieldReferences() { + entryKDBX?.stopToManageFieldReferences() + } + + fun getHistory(): ArrayList { + val history = ArrayList() + val entryV4History = entryKDBX?.history ?: ArrayList() + for (entryHistory in entryV4History) { + history.add(Entry(entryHistory)) + } + return history + } + + fun addEntryToHistory(entry: Entry) { + entry.entryKDBX?.let { + entryKDBX?.addEntryToHistory(it) + } + } + + fun removeAllHistory() { + entryKDBX?.removeAllHistory() + } + + fun removeOldestEntryFromHistory() { + entryKDBX?.removeOldestEntryFromHistory() + } + + fun getSize(): Long { + return entryKDBX?.size ?: 0L + } + + fun containsCustomData(): Boolean { + return entryKDBX?.containsCustomData() ?: false + } + + /* + ------------ + Converter + ------------ + */ + + /** + * Retrieve generated entry info, + * Remove parameter fields and add auto generated elements in auto custom fields + */ + fun getEntryInfo(database: Database?, raw: Boolean = false): EntryInfo { + val entryInfo = EntryInfo() + if (raw) + database?.stopManageEntry(this) + else + database?.startManageEntry(this) + entryInfo.id = nodeId.toString() + entryInfo.title = title + entryInfo.username = username + entryInfo.password = password + entryInfo.url = url + entryInfo.notes = notes + for (entry in customFields.entries) { + entryInfo.customFields.add( + Field(entry.key, entry.value)) + } + // Add otpElement to generate token + entryInfo.otpModel = getOtpElement()?.otpModel + // Replace parameter fields by generated OTP fields + entryInfo.customFields = OtpEntryFields.generateAutoFields(entryInfo.customFields) + if (!raw) + database?.stopManageEntry(this) + return entryInfo + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as Entry + + if (entryKDB != other.entryKDB) return false + if (entryKDBX != other.entryKDBX) return false + + return true + } + + override fun hashCode(): Int { + var result = entryKDB?.hashCode() ?: 0 + result = 31 * result + (entryKDBX?.hashCode() ?: 0) + return result + } + + + companion object CREATOR : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): Entry { + return Entry(parcel) + } + + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } + + const val PMS_TAN_ENTRY = "" + + /** + * {@inheritDoc} + * Get the display title from an entry,

+ * [.startManageEntry] and [.stopManageEntry] must be called + * before and after [.getVisualTitle] + */ + fun getVisualTitle(isTan: Boolean, title: String, userName: String, url: String, id: String): String { + return if (isTan) { + "$PMS_TAN_ENTRY $userName" + } else { + if (title.isEmpty()) + if (userName.isEmpty()) + if (url.isEmpty()) + id + else + url + else + userName + else + title + } + } + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryKDB.kt similarity index 84% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/EntryKDB.kt index f379c07ad..4755bbc2d 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryKDB.kt @@ -44,7 +44,7 @@ import java.util.* * @author Dominik Reichl @t-online.de> * @author Jeremy Jamet @kunzisoft.com> */ -class PwEntryV3 : PwEntry, PwNodeV3Interface { +class EntryKDB : EntryVersioned, NodeKDBInterface { /** A string describing what is in pBinaryData */ var binaryDesc = "" @@ -67,12 +67,12 @@ class PwEntryV3 : PwEntry, PwNodeV3Interface { return if (url != PMS_ID_URL) false else icon.isMetaStreamIcon } - override fun initNodeId(): PwNodeId { - return PwNodeIdUUID() + override fun initNodeId(): NodeId { + return NodeIdUUID() } - override fun copyNodeId(nodeId: PwNodeId): PwNodeId { - return PwNodeIdUUID(nodeId.id) + override fun copyNodeId(nodeId: NodeId): NodeId { + return NodeIdUUID(nodeId.id) } constructor() : super() @@ -88,11 +88,11 @@ class PwEntryV3 : PwEntry, PwNodeV3Interface { parcel.readByteArray(binaryData) } - override fun readParentParcelable(parcel: Parcel): PwGroupV3? { - return parcel.readParcelable(PwGroupV3::class.java.classLoader) + override fun readParentParcelable(parcel: Parcel): GroupKDB? { + return parcel.readParcelable(GroupKDB::class.java.classLoader) } - override fun writeParentParcelable(parent: PwGroupV3?, parcel: Parcel, flags: Int) { + override fun writeParentParcelable(parent: GroupKDB?, parcel: Parcel, flags: Int) { parcel.writeParcelable(parent, flags) } @@ -108,7 +108,7 @@ class PwEntryV3 : PwEntry, PwNodeV3Interface { dest.writeByteArray(binaryData) } - fun updateWith(source: PwEntryV3) { + fun updateWith(source: EntryKDB) { super.updateWith(source) title = source.title username = source.username @@ -147,12 +147,12 @@ class PwEntryV3 : PwEntry, PwNodeV3Interface { private const val PMS_ID_URL = "$" @JvmField - val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwEntryV3 { - return PwEntryV3(parcel) + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): EntryKDB { + return EntryKDB(parcel) } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryKDBX.kt similarity index 84% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/EntryKDBX.kt index 5702e1d0b..c3132a3fb 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryKDBX.kt @@ -26,15 +26,15 @@ import com.kunzisoft.keepass.database.element.security.ProtectedString import com.kunzisoft.keepass.utils.ParcelableUtil import java.util.* -class PwEntryV4 : PwEntry, PwNodeV4Interface { +class EntryKDBX : EntryVersioned, NodeKDBXInterface { // To decode each field not parcelable @Transient - private var mDatabase: PwDatabaseV4? = null + private var mDatabase: DatabaseKDBX? = null @Transient private var mDecodeRef = false - override var icon: PwIcon + override var icon: IconImage get() { return when { iconCustom.isUnknown -> super.icon @@ -42,11 +42,11 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { } } set(value) { - if (value is PwIconStandard) - iconCustom = PwIconCustom.UNKNOWN_ICON + if (value is IconImageStandard) + iconCustom = IconImageCustom.UNKNOWN_ICON super.icon = value } - var iconCustom = PwIconCustom.UNKNOWN_ICON + var iconCustom = IconImageCustom.UNKNOWN_ICON private var customData = HashMap() var fields = HashMap() var binaries = HashMap() @@ -54,7 +54,7 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { var backgroundColor = "" var overrideURL = "" var autoType = AutoType() - var history = ArrayList() + var history = ArrayList() var additional = "" var tags = "" @@ -93,9 +93,9 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { constructor() : super() constructor(parcel: Parcel) : super(parcel) { - iconCustom = parcel.readParcelable(PwIconCustom::class.java.classLoader) ?: iconCustom + iconCustom = parcel.readParcelable(IconImageCustom::class.java.classLoader) ?: iconCustom usageCount = parcel.readLong() - locationChanged = parcel.readParcelable(PwDate::class.java.classLoader) ?: locationChanged + locationChanged = parcel.readParcelable(DateInstant::class.java.classLoader) ?: locationChanged customData = ParcelableUtil.readStringParcelableMap(parcel) fields = ParcelableUtil.readStringParcelableMap(parcel, ProtectedString::class.java) binaries = ParcelableUtil.readStringParcelableMap(parcel, BinaryAttachment::class.java) @@ -131,11 +131,11 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { * Update with deep copy of each entry element * @param source */ - fun updateWith(source: PwEntryV4, copyHistory: Boolean = true) { + fun updateWith(source: EntryKDBX, copyHistory: Boolean = true) { super.updateWith(source) - iconCustom = PwIconCustom(source.iconCustom) + iconCustom = IconImageCustom(source.iconCustom) usageCount = source.usageCount - locationChanged = PwDate(source.locationChanged) + locationChanged = DateInstant(source.locationChanged) // Add all custom elements in map customData.clear() customData.putAll(source.customData) @@ -155,7 +155,7 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { tags = source.tags } - fun startToManageFieldReferences(db: PwDatabaseV4) { + fun startToManageFieldReferences(db: DatabaseKDBX) { this.mDatabase = db this.mDecodeRef = true } @@ -165,24 +165,24 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { this.mDecodeRef = false } - override fun initNodeId(): PwNodeId { - return PwNodeIdUUID() + override fun initNodeId(): NodeId { + return NodeIdUUID() } - override fun copyNodeId(nodeId: PwNodeId): PwNodeId { - return PwNodeIdUUID(nodeId.id) + override fun copyNodeId(nodeId: NodeId): NodeId { + return NodeIdUUID(nodeId.id) } - override fun readParentParcelable(parcel: Parcel): PwGroupV4? { - return parcel.readParcelable(PwGroupV4::class.java.classLoader) + override fun readParentParcelable(parcel: Parcel): GroupKDBX? { + return parcel.readParcelable(GroupKDBX::class.java.classLoader) } - override fun writeParentParcelable(parent: PwGroupV4?, parcel: Parcel, flags: Int) { + override fun writeParentParcelable(parent: GroupKDBX?, parcel: Parcel, flags: Int) { parcel.writeParcelable(parent, flags) } /** - * Decode a reference key with the SprEngineV4 + * Decode a reference key with the FieldReferencesEngine * @param decodeRef * @param key * @return @@ -190,7 +190,7 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { private fun decodeRefKey(decodeRef: Boolean, key: String): String { return fields[key]?.toString()?.let { text -> return if (decodeRef) { - if (mDatabase == null) text else SprEngineV4().compile(text, this, mDatabase!!) + if (mDatabase == null) text else FieldReferencesEngine().compile(text, this, mDatabase!!) } else text } ?: "" } @@ -235,10 +235,10 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { override var usageCount: Long = 0 - override var locationChanged = PwDate() + override var locationChanged = DateInstant() fun afterChangeParent() { - locationChanged = PwDate() + locationChanged = DateInstant() } private fun isStandardField(key: String): Boolean { @@ -290,7 +290,7 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { return customData.isNotEmpty() } - fun addEntryToHistory(entry: PwEntryV4) { + fun addEntryToHistory(entry: EntryKDBX) { history.add(entry) } @@ -330,12 +330,12 @@ class PwEntryV4 : PwEntry, PwNodeV4Interface { const val STR_NOTES = "Notes" @JvmField - val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwEntryV4 { - return PwEntryV4(parcel) + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): EntryKDBX { + return EntryKDBX(parcel) } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersioned.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersioned.kt index 900778505..a30ebdfdb 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersioned.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersioned.kt @@ -1,395 +1,18 @@ package com.kunzisoft.keepass.database.element import android.os.Parcel -import android.os.Parcelable -import com.kunzisoft.keepass.database.element.security.ProtectedString -import com.kunzisoft.keepass.model.EntryInfo -import com.kunzisoft.keepass.model.Field -import com.kunzisoft.keepass.otp.OtpElement -import com.kunzisoft.keepass.otp.OtpEntryFields -import java.util.* -import kotlin.collections.ArrayList -class EntryVersioned : NodeVersioned, PwEntryInterface { +abstract class EntryVersioned + < + GroupId, + EntryId, + ParentGroup: GroupVersioned, + Entry: EntryVersioned + > + : NodeVersioned, EntryVersionedInterface { - var pwEntryV3: PwEntryV3? = null - private set - var pwEntryV4: PwEntryV4? = null - private set + constructor() : super() - fun updateWith(entry: EntryVersioned, copyHistory: Boolean = true) { - entry.pwEntryV3?.let { - this.pwEntryV3?.updateWith(it) - } - entry.pwEntryV4?.let { - this.pwEntryV4?.updateWith(it, copyHistory) - } - } + constructor(parcel: Parcel) : super(parcel) - /** - * Use this constructor to copy an Entry with exact same values - */ - constructor(entry: EntryVersioned, copyHistory: Boolean = true) { - if (entry.pwEntryV3 != null) { - this.pwEntryV3 = PwEntryV3() - } - if (entry.pwEntryV4 != null) { - this.pwEntryV4 = PwEntryV4() - } - updateWith(entry, copyHistory) - } - - constructor(entry: PwEntryV3) { - this.pwEntryV4 = null - this.pwEntryV3 = entry - } - - constructor(entry: PwEntryV4) { - this.pwEntryV3 = null - this.pwEntryV4 = entry - } - - constructor(parcel: Parcel) { - pwEntryV3 = parcel.readParcelable(PwEntryV3::class.java.classLoader) - pwEntryV4 = parcel.readParcelable(PwEntryV4::class.java.classLoader) - } - - override fun describeContents(): Int { - return 0 - } - - override fun writeToParcel(dest: Parcel, flags: Int) { - dest.writeParcelable(pwEntryV3, flags) - dest.writeParcelable(pwEntryV4, flags) - } - - override var nodeId: PwNodeId - get() = pwEntryV4?.nodeId ?: pwEntryV3?.nodeId ?: PwNodeIdUUID() - set(value) { - pwEntryV3?.nodeId = value - pwEntryV4?.nodeId = value - } - - override var title: String - get() = pwEntryV3?.title ?: pwEntryV4?.title ?: "" - set(value) { - pwEntryV3?.title = value - pwEntryV4?.title = value - } - - override var icon: PwIcon - get() { - return pwEntryV3?.icon ?: pwEntryV4?.icon ?: PwIconStandard() - } - set(value) { - pwEntryV3?.icon = value - pwEntryV4?.icon = value - } - - override val type: Type - get() = Type.ENTRY - - override var parent: GroupVersioned? - get() { - pwEntryV3?.parent?.let { - return GroupVersioned(it) - } - pwEntryV4?.parent?.let { - return GroupVersioned(it) - } - return null - } - set(value) { - pwEntryV3?.parent = value?.pwGroupV3 - pwEntryV4?.parent = value?.pwGroupV4 - } - - override fun containsParent(): Boolean { - return pwEntryV3?.containsParent() ?: pwEntryV4?.containsParent() ?: false - } - - override fun afterAssignNewParent() { - pwEntryV4?.afterChangeParent() - } - - override fun touch(modified: Boolean, touchParents: Boolean) { - pwEntryV3?.touch(modified, touchParents) - pwEntryV4?.touch(modified, touchParents) - } - - override fun isContainedIn(container: GroupVersioned): Boolean { - var contained: Boolean? = false - container.pwGroupV3?.let { - contained = pwEntryV3?.isContainedIn(it) - } - container.pwGroupV4?.let { - contained = pwEntryV4?.isContainedIn(it) - } - return contained ?: false - } - - override var creationTime: PwDate - get() = pwEntryV3?.creationTime ?: pwEntryV4?.creationTime ?: PwDate() - set(value) { - pwEntryV3?.creationTime = value - pwEntryV4?.creationTime = value - } - - override var lastModificationTime: PwDate - get() = pwEntryV3?.lastModificationTime ?: pwEntryV4?.lastModificationTime ?: PwDate() - set(value) { - pwEntryV3?.lastModificationTime = value - pwEntryV4?.lastModificationTime = value - } - - override var lastAccessTime: PwDate - get() = pwEntryV3?.lastAccessTime ?: pwEntryV4?.lastAccessTime ?: PwDate() - set(value) { - pwEntryV3?.lastAccessTime = value - pwEntryV4?.lastAccessTime = value - } - - override var expiryTime: PwDate - get() = pwEntryV3?.expiryTime ?: pwEntryV4?.expiryTime ?: PwDate() - set(value) { - pwEntryV3?.expiryTime = value - pwEntryV4?.expiryTime = value - } - - override var expires: Boolean - get() = pwEntryV3?.expires ?: pwEntryV4?.expires ?: false - set(value) { - pwEntryV3?.expires = value - pwEntryV4?.expires = value - } - - override val isCurrentlyExpires: Boolean - get() = pwEntryV3?.isCurrentlyExpires ?: pwEntryV4?.isCurrentlyExpires ?: false - - override var username: String - get() = pwEntryV3?.username ?: pwEntryV4?.username ?: "" - set(value) { - pwEntryV3?.username = value - pwEntryV4?.username = value - } - - override var password: String - get() = pwEntryV3?.password ?: pwEntryV4?.password ?: "" - set(value) { - pwEntryV3?.password = value - pwEntryV4?.password = value - } - - override var url: String - get() = pwEntryV3?.url ?: pwEntryV4?.url ?: "" - set(value) { - pwEntryV3?.url = value - pwEntryV4?.url = value - } - - override var notes: String - get() = pwEntryV3?.notes ?: pwEntryV4?.notes ?: "" - set(value) { - pwEntryV3?.notes = value - pwEntryV4?.notes = value - } - - private fun isTan(): Boolean { - return title == PMS_TAN_ENTRY && username.isNotEmpty() - } - - fun getVisualTitle(): String { - return getVisualTitle(isTan(), - title, - username, - url, - nodeId.toString()) - } - - /* - ------------ - V3 Methods - ------------ - */ - - /** - * If it's a node with only meta information like Meta-info SYSTEM Database Color - * @return false by default, true if it's a meta stream - */ - val isMetaStream: Boolean - get() = pwEntryV3?.isMetaStream ?: false - - /* - ------------ - V4 Methods - ------------ - */ - - var iconCustom: PwIconCustom - get() = pwEntryV4?.iconCustom ?: PwIconCustom.UNKNOWN_ICON - set(value) { - pwEntryV4?.iconCustom = value - } - - /** - * Retrieve custom fields to show, key is the label, value is the value of field (protected or not) - * @return Map of label/value - */ - val customFields: HashMap - get() = pwEntryV4?.customFields ?: HashMap() - - /** - * To redefine if version of entry allow custom field, - * @return true if entry allows custom field - */ - fun allowCustomFields(): Boolean { - return pwEntryV4?.allowCustomFields() ?: false - } - - fun removeAllFields() { - pwEntryV4?.removeAllFields() - } - - /** - * Update or add an extra field to the list (standard or custom) - * @param label Label of field, must be unique - * @param value Value of field - */ - fun putExtraField(label: String, value: ProtectedString) { - pwEntryV4?.putExtraField(label, value) - } - - fun getOtpElement(): OtpElement? { - return OtpEntryFields.parseFields { key -> - customFields[key]?.toString() - } - } - - fun startToManageFieldReferences(db: PwDatabaseV4) { - pwEntryV4?.startToManageFieldReferences(db) - } - - fun stopToManageFieldReferences() { - pwEntryV4?.stopToManageFieldReferences() - } - - fun getHistory(): ArrayList { - val history = ArrayList() - val entryV4History = pwEntryV4?.history ?: ArrayList() - for (entryHistory in entryV4History) { - history.add(EntryVersioned(entryHistory)) - } - return history - } - - fun addEntryToHistory(entry: EntryVersioned) { - entry.pwEntryV4?.let { - pwEntryV4?.addEntryToHistory(it) - } - } - - fun removeAllHistory() { - pwEntryV4?.removeAllHistory() - } - - fun removeOldestEntryFromHistory() { - pwEntryV4?.removeOldestEntryFromHistory() - } - - fun getSize(): Long { - return pwEntryV4?.size ?: 0L - } - - fun containsCustomData(): Boolean { - return pwEntryV4?.containsCustomData() ?: false - } - - /* - ------------ - Converter - ------------ - */ - - /** - * Retrieve generated entry info, - * Remove parameter fields and add auto generated elements in auto custom fields - */ - fun getEntryInfo(database: Database?, raw: Boolean = false): EntryInfo { - val entryInfo = EntryInfo() - if (raw) - database?.stopManageEntry(this) - else - database?.startManageEntry(this) - entryInfo.id = nodeId.toString() - entryInfo.title = title - entryInfo.username = username - entryInfo.password = password - entryInfo.url = url - entryInfo.notes = notes - for (entry in customFields.entries) { - entryInfo.customFields.add( - Field(entry.key, entry.value)) - } - // Add otpElement to generate token - entryInfo.otpModel = getOtpElement()?.otpModel - // Replace parameter fields by generated OTP fields - entryInfo.customFields = OtpEntryFields.generateAutoFields(entryInfo.customFields) - if (!raw) - database?.stopManageEntry(this) - return entryInfo - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as EntryVersioned - - if (pwEntryV3 != other.pwEntryV3) return false - if (pwEntryV4 != other.pwEntryV4) return false - - return true - } - - override fun hashCode(): Int { - var result = pwEntryV3?.hashCode() ?: 0 - result = 31 * result + (pwEntryV4?.hashCode() ?: 0) - return result - } - - - companion object CREATOR : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): EntryVersioned { - return EntryVersioned(parcel) - } - - override fun newArray(size: Int): Array { - return arrayOfNulls(size) - } - - const val PMS_TAN_ENTRY = "" - - /** - * {@inheritDoc} - * Get the display title from an entry,

- * [.startManageEntry] and [.stopManageEntry] must be called - * before and after [.getVisualTitle] - */ - fun getVisualTitle(isTan: Boolean, title: String, userName: String, url: String, id: String): String { - return if (isTan) { - "$PMS_TAN_ENTRY $userName" - } else { - if (title.isEmpty()) - if (userName.isEmpty()) - if (url.isEmpty()) - id - else - url - else - userName - else - title - } - } - } -} +} \ No newline at end of file diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryInterface.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersionedInterface.kt similarity index 62% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryInterface.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersionedInterface.kt index ba9ea4012..5eca6d851 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryInterface.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersionedInterface.kt @@ -1,6 +1,6 @@ package com.kunzisoft.keepass.database.element -interface PwEntryInterface : PwNodeInterface { +interface EntryVersionedInterface : NodeVersionedInterface { var username: String diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/SprEngineV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/FieldReferencesEngine.kt similarity index 87% rename from app/src/main/java/com/kunzisoft/keepass/database/element/SprEngineV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/FieldReferencesEngine.kt index 6a3285e07..e8fce6821 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/SprEngineV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/FieldReferencesEngine.kt @@ -19,22 +19,22 @@ */ package com.kunzisoft.keepass.database.element -import com.kunzisoft.keepass.database.search.EntrySearchHandlerV4 -import com.kunzisoft.keepass.database.search.SearchParametersV4 +import com.kunzisoft.keepass.database.search.EntryKDBXSearchHandler +import com.kunzisoft.keepass.database.search.SearchParametersKDBX import com.kunzisoft.keepass.utils.StringUtil import java.util.* -class SprEngineV4 { +class FieldReferencesEngine { - inner class TargetResult(var entry: PwEntryV4?, var wanted: Char) + inner class TargetResult(var entry: EntryKDBX?, var wanted: Char) private inner class SprContextV4 { - var databaseV4: PwDatabaseV4? = null - var entry: PwEntryV4 + var databaseV4: DatabaseKDBX? = null + var entry: EntryKDBX var refsCache: MutableMap = HashMap() - internal constructor(db: PwDatabaseV4, entry: PwEntryV4) { + internal constructor(db: DatabaseKDBX, entry: EntryKDBX) { this.databaseV4 = db this.entry = entry } @@ -46,7 +46,7 @@ class SprEngineV4 { } } - fun compile(text: String, entry: PwEntryV4, database: PwDatabaseV4): String { + fun compile(text: String, entry: EntryKDBX, database: DatabaseKDBX): String { return compileInternal(text, SprContextV4(database, entry), 0) } @@ -139,7 +139,7 @@ class SprEngineV4 { val scan = Character.toUpperCase(ref[2]) val wanted = Character.toUpperCase(ref[0]) - val searchParametersV4 = SearchParametersV4() + val searchParametersV4 = SearchParametersKDBX() searchParametersV4.setupNone() searchParametersV4.searchString = ref.substring(4) @@ -161,7 +161,7 @@ class SprEngineV4 { return null } - val list = ArrayList() + val list = ArrayList() // TODO type parameter searchEntries(contextV4.databaseV4!!.rootGroup, searchParametersV4, list) @@ -195,7 +195,7 @@ class SprEngineV4 { return newText } - private fun searchEntries(root: PwGroupV4?, searchParametersV4: SearchParametersV4?, listStorage: MutableList?) { + private fun searchEntries(root: GroupKDBX?, searchParametersV4: SearchParametersKDBX?, listStorage: MutableList?) { if (searchParametersV4 == null) { return } @@ -205,7 +205,7 @@ class SprEngineV4 { val terms = StringUtil.splitStringTerms(searchParametersV4.searchString) if (terms.size <= 1 || searchParametersV4.regularExpression) { - root!!.doForEachChild(EntrySearchHandlerV4(searchParametersV4, listStorage), null) + root!!.doForEachChild(EntryKDBXSearchHandler(searchParametersV4, listStorage), null) return } @@ -214,9 +214,9 @@ class SprEngineV4 { Collections.sort(terms, stringLengthComparator) val fullSearch = searchParametersV4.searchString - var childEntries: List? = root!!.getChildEntries() + var childEntries: List? = root!!.getChildEntries() for (i in terms.indices) { - val pgNew = ArrayList() + val pgNew = ArrayList() searchParametersV4.searchString = terms[i] @@ -226,12 +226,12 @@ class SprEngineV4 { negate = searchParametersV4.searchString.isNotEmpty() } - if (!root.doForEachChild(EntrySearchHandlerV4(searchParametersV4, pgNew), null)) { + if (!root.doForEachChild(EntryKDBXSearchHandler(searchParametersV4, pgNew), null)) { childEntries = null break } - val complement = ArrayList() + val complement = ArrayList() if (negate) { for (entry in childEntries!!) { if (!pgNew.contains(entry)) { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Group.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Group.kt new file mode 100644 index 000000000..ba2d75803 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Group.kt @@ -0,0 +1,352 @@ +package com.kunzisoft.keepass.database.element + +import android.os.Parcel +import android.os.Parcelable +import java.util.* +import kotlin.collections.ArrayList + +class Group : Node, GroupVersionedInterface { + + var groupKDB: GroupKDB? = null + private set + var groupKDBX: GroupKDBX? = null + private set + + fun updateWith(group: Group) { + group.groupKDB?.let { + this.groupKDB?.updateWith(it) + } + group.groupKDBX?.let { + this.groupKDBX?.updateWith(it) + } + } + + /** + * Use this constructor to copy a Group + */ + constructor(group: Group) { + if (group.groupKDB != null) { + if (this.groupKDB == null) + this.groupKDB = GroupKDB() + } + if (group.groupKDBX != null) { + if (this.groupKDBX == null) + this.groupKDBX = GroupKDBX() + } + updateWith(group) + } + + constructor(group: GroupKDB) { + this.groupKDBX = null + this.groupKDB = group + } + + constructor(group: GroupKDBX) { + this.groupKDB = null + this.groupKDBX = group + } + + constructor(parcel: Parcel) { + groupKDB = parcel.readParcelable(GroupKDB::class.java.classLoader) + groupKDBX = parcel.readParcelable(GroupKDBX::class.java.classLoader) + } + + companion object CREATOR : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): Group { + return Group(parcel) + } + + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } + } + + override fun describeContents(): Int { + return 0 + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeParcelable(groupKDB, flags) + dest.writeParcelable(groupKDBX, flags) + } + + override val nodeId: NodeId<*>? + get() = groupKDBX?.nodeId ?: groupKDB?.nodeId + + override var title: String + get() = groupKDB?.title ?: groupKDBX?.title ?: "" + set(value) { + groupKDB?.title = value + groupKDBX?.title = value + } + + override var icon: IconImage + get() = groupKDB?.icon ?: groupKDBX?.icon ?: IconImageStandard() + set(value) { + groupKDB?.icon = value + groupKDBX?.icon = value + } + + override val type: Type + get() = Type.GROUP + + override var parent: Group? + get() { + groupKDB?.parent?.let { + return Group(it) + } + groupKDBX?.parent?.let { + return Group(it) + } + return null + } + set(value) { + groupKDB?.parent = value?.groupKDB + groupKDBX?.parent = value?.groupKDBX + } + + override fun containsParent(): Boolean { + return groupKDB?.containsParent() ?: groupKDBX?.containsParent() ?: false + } + + override fun afterAssignNewParent() { + groupKDB?.afterAssignNewParent() + groupKDBX?.afterAssignNewParent() + } + + fun addChildrenFrom(group: Group) { + group.groupKDB?.getChildEntries()?.forEach { entryToAdd -> + groupKDB?.addChildEntry(entryToAdd) + } + group.groupKDB?.getChildGroups()?.forEach { groupToAdd -> + groupKDB?.addChildGroup(groupToAdd) + } + + group.groupKDBX?.getChildEntries()?.forEach { entryToAdd -> + groupKDBX?.addChildEntry(entryToAdd) + } + group.groupKDBX?.getChildGroups()?.forEach { groupToAdd -> + groupKDBX?.addChildGroup(groupToAdd) + } + } + + override fun touch(modified: Boolean, touchParents: Boolean) { + groupKDB?.touch(modified, touchParents) + groupKDBX?.touch(modified, touchParents) + } + + override fun isContainedIn(container: Group): Boolean { + var contained: Boolean? = null + container.groupKDB?.let { + contained = groupKDB?.isContainedIn(it) + } + container.groupKDBX?.let { + contained = groupKDBX?.isContainedIn(it) + } + return contained ?: false + } + + override var creationTime: DateInstant + get() = groupKDB?.creationTime ?: groupKDBX?.creationTime ?: DateInstant() + set(value) { + groupKDB?.creationTime = value + groupKDBX?.creationTime = value + } + + override var lastModificationTime: DateInstant + get() = groupKDB?.lastModificationTime ?: groupKDBX?.lastModificationTime ?: DateInstant() + set(value) { + groupKDB?.lastModificationTime = value + groupKDBX?.lastModificationTime = value + } + + override var lastAccessTime: DateInstant + get() = groupKDB?.lastAccessTime ?: groupKDBX?.lastAccessTime ?: DateInstant() + set(value) { + groupKDB?.lastAccessTime = value + groupKDBX?.lastAccessTime = value + } + + override var expiryTime: DateInstant + get() = groupKDB?.expiryTime ?: groupKDBX?.expiryTime ?: DateInstant() + set(value) { + groupKDB?.expiryTime = value + groupKDBX?.expiryTime = value + } + + override var expires: Boolean + get() = groupKDB?.expires ?: groupKDBX?.expires ?: false + set(value) { + groupKDB?.expires = value + groupKDBX?.expires = value + } + + override val isCurrentlyExpires: Boolean + get() = groupKDB?.isCurrentlyExpires ?: groupKDBX?.isCurrentlyExpires ?: false + + override fun getChildGroups(): MutableList { + val children = ArrayList() + + groupKDB?.getChildGroups()?.forEach { + children.add(Group(it)) + } + groupKDBX?.getChildGroups()?.forEach { + children.add(Group(it)) + } + + return children + } + + override fun getChildEntries(): MutableList { + return getChildEntries(false) + } + + fun getChildEntries(withoutMetaStream: Boolean): MutableList { + val children = ArrayList() + + groupKDB?.getChildEntries()?.forEach { + val entryToAddAsChild = Entry(it) + if (!withoutMetaStream || (withoutMetaStream && !entryToAddAsChild.isMetaStream)) + children.add(entryToAddAsChild) + } + groupKDBX?.getChildEntries()?.forEach { + children.add(Entry(it)) + } + + return children + } + + /** + * Filter MetaStream entries and return children + * @return List of direct children (one level below) as NodeVersioned + */ + fun getChildren(withoutMetaStream: Boolean = true): List { + val children = ArrayList() + children.addAll(getChildGroups()) + + groupKDB?.let { + children.addAll(getChildEntries(withoutMetaStream)) + } + groupKDBX?.let { + // No MetasStream in V4 + children.addAll(getChildEntries(withoutMetaStream)) + } + + return children + } + + override fun addChildGroup(group: Group) { + group.groupKDB?.let { + groupKDB?.addChildGroup(it) + } + group.groupKDBX?.let { + groupKDBX?.addChildGroup(it) + } + } + + override fun addChildEntry(entry: Entry) { + entry.entryKDB?.let { + groupKDB?.addChildEntry(it) + } + entry.entryKDBX?.let { + groupKDBX?.addChildEntry(it) + } + } + + override fun removeChildGroup(group: Group) { + group.groupKDB?.let { + groupKDB?.removeChildGroup(it) + } + group.groupKDBX?.let { + groupKDBX?.removeChildGroup(it) + } + } + + override fun removeChildEntry(entry: Entry) { + entry.entryKDB?.let { + groupKDB?.removeChildEntry(it) + } + entry.entryKDBX?.let { + groupKDBX?.removeChildEntry(it) + } + } + + override fun removeChildren() { + groupKDB?.removeChildren() + groupKDBX?.removeChildren() + } + + override fun allowAddEntryIfIsRoot(): Boolean { + return groupKDB?.allowAddEntryIfIsRoot() ?: groupKDBX?.allowAddEntryIfIsRoot() ?: false + } + + /* + ------------ + KDB Methods + ------------ + */ + + var nodeIdKDB: NodeId + get() = groupKDB?.nodeId ?: NodeIdInt() + set(value) { groupKDB?.nodeId = value } + + fun setNodeId(id: NodeIdInt) { + groupKDB?.nodeId = id + } + + fun getLevel(): Int { + return groupKDB?.level ?: -1 + } + + fun setLevel(level: Int) { + groupKDB?.level = level + } + + /* + ------------ + KDBX Methods + ------------ + */ + + var nodeIdKDBX: NodeId + get() = groupKDBX?.nodeId ?: NodeIdUUID() + set(value) { groupKDBX?.nodeId = value } + + fun setNodeId(id: NodeIdUUID) { + groupKDBX?.nodeId = id + } + + fun setEnableAutoType(enableAutoType: Boolean?) { + groupKDBX?.enableAutoType = enableAutoType + } + + fun setEnableSearching(enableSearching: Boolean?) { + groupKDBX?.enableSearching = enableSearching + } + + fun setExpanded(expanded: Boolean) { + groupKDBX?.isExpanded = expanded + } + + fun containsCustomData(): Boolean { + return groupKDBX?.containsCustomData() ?: false + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as Group + + if (groupKDB != other.groupKDB) return false + if (groupKDBX != other.groupKDBX) return false + + return true + } + + override fun hashCode(): Int { + var result = groupKDB?.hashCode() ?: 0 + result = 31 * result + (groupKDBX?.hashCode() ?: 0) + return result + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwGroupV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/GroupKDB.kt similarity index 69% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwGroupV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/GroupKDB.kt index ed2aaec3d..30a885771 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwGroupV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/GroupKDB.kt @@ -24,7 +24,7 @@ import android.os.Parcel import android.os.Parcelable import java.util.* -class PwGroupV3 : PwGroup, PwNodeV3Interface { +class GroupKDB : GroupVersioned, NodeKDBInterface { var level = 0 // short /** Used by KeePass internally, don't use */ @@ -37,11 +37,11 @@ class PwGroupV3 : PwGroup, PwNodeV3Interface { flags = parcel.readInt() } - override fun readParentParcelable(parcel: Parcel): PwGroupV3? { - return parcel.readParcelable(PwGroupV3::class.java.classLoader) + override fun readParentParcelable(parcel: Parcel): GroupKDB? { + return parcel.readParcelable(GroupKDB::class.java.classLoader) } - override fun writeParentParcelable(parent: PwGroupV3?, parcel: Parcel, flags: Int) { + override fun writeParentParcelable(parent: GroupKDB?, parcel: Parcel, flags: Int) { parcel.writeParcelable(parent, flags) } @@ -51,7 +51,7 @@ class PwGroupV3 : PwGroup, PwNodeV3Interface { dest.writeInt(flags) } - fun updateWith(source: PwGroupV3) { + fun updateWith(source: GroupKDB) { super.updateWith(source) level = source.level flags = source.flags @@ -60,12 +60,12 @@ class PwGroupV3 : PwGroup, PwNodeV3Interface { override val type: Type get() = Type.GROUP - override fun initNodeId(): PwNodeId { - return PwNodeIdInt() + override fun initNodeId(): NodeId { + return NodeIdInt() } - override fun copyNodeId(nodeId: PwNodeId): PwNodeId { - return PwNodeIdInt(nodeId.id) + override fun copyNodeId(nodeId: NodeId): NodeId { + return NodeIdInt(nodeId.id) } override fun afterAssignNewParent() { @@ -74,7 +74,7 @@ class PwGroupV3 : PwGroup, PwNodeV3Interface { } fun setGroupId(groupId: Int) { - this.nodeId = PwNodeIdInt(groupId) + this.nodeId = NodeIdInt(groupId) } override fun allowAddEntryIfIsRoot(): Boolean { @@ -84,12 +84,12 @@ class PwGroupV3 : PwGroup, PwNodeV3Interface { companion object { @JvmField - val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwGroupV3 { - return PwGroupV3(parcel) + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): GroupKDB { + return GroupKDB(parcel) } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwGroupV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/GroupKDBX.kt similarity index 73% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwGroupV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/GroupKDBX.kt index d6fa5e454..9a35a6071 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwGroupV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/GroupKDBX.kt @@ -25,10 +25,10 @@ import android.os.Parcelable import java.util.HashMap import java.util.UUID -class PwGroupV4 : PwGroup, PwNodeV4Interface { +class GroupKDBX : GroupVersioned, NodeKDBXInterface { // TODO Encapsulate - override var icon: PwIcon + override var icon: IconImage get() { return if (iconCustom.isUnknown) super.icon @@ -36,11 +36,11 @@ class PwGroupV4 : PwGroup, PwNodeV4Interface { iconCustom } set(value) { - if (value is PwIconStandard) - iconCustom = PwIconCustom.UNKNOWN_ICON + if (value is IconImageStandard) + iconCustom = IconImageCustom.UNKNOWN_ICON super.icon = value } - var iconCustom = PwIconCustom.UNKNOWN_ICON + var iconCustom = IconImageCustom.UNKNOWN_ICON private val customData = HashMap() var notes = "" @@ -48,27 +48,27 @@ class PwGroupV4 : PwGroup, PwNodeV4Interface { var defaultAutoTypeSequence = "" var enableAutoType: Boolean? = null var enableSearching: Boolean? = null - var lastTopVisibleEntry: UUID = PwDatabase.UUID_ZERO + var lastTopVisibleEntry: UUID = DatabaseVersioned.UUID_ZERO override var expires: Boolean = false override val type: Type get() = Type.GROUP - override fun initNodeId(): PwNodeId { - return PwNodeIdUUID() + override fun initNodeId(): NodeId { + return NodeIdUUID() } - override fun copyNodeId(nodeId: PwNodeId): PwNodeId { - return PwNodeIdUUID(nodeId.id) + override fun copyNodeId(nodeId: NodeId): NodeId { + return NodeIdUUID(nodeId.id) } constructor() : super() constructor(parcel: Parcel) : super(parcel) { - iconCustom = parcel.readParcelable(PwIconCustom::class.java.classLoader) ?: iconCustom + iconCustom = parcel.readParcelable(IconImageCustom::class.java.classLoader) ?: iconCustom usageCount = parcel.readLong() - locationChanged = parcel.readParcelable(PwDate::class.java.classLoader) ?: locationChanged + locationChanged = parcel.readParcelable(DateInstant::class.java.classLoader) ?: locationChanged // TODO customData = ParcelableUtil.readStringParcelableMap(in); notes = parcel.readString() ?: notes isExpanded = parcel.readByte().toInt() != 0 @@ -80,11 +80,11 @@ class PwGroupV4 : PwGroup, PwNodeV4Interface { lastTopVisibleEntry = parcel.readSerializable() as UUID } - override fun readParentParcelable(parcel: Parcel): PwGroupV4? { - return parcel.readParcelable(PwGroupV4::class.java.classLoader) + override fun readParentParcelable(parcel: Parcel): GroupKDBX? { + return parcel.readParcelable(GroupKDBX::class.java.classLoader) } - override fun writeParentParcelable(parent: PwGroupV4?, parcel: Parcel, flags: Int) { + override fun writeParentParcelable(parent: GroupKDBX?, parcel: Parcel, flags: Int) { parcel.writeParcelable(parent, flags) } @@ -102,11 +102,11 @@ class PwGroupV4 : PwGroup, PwNodeV4Interface { dest.writeSerializable(lastTopVisibleEntry) } - fun updateWith(source: PwGroupV4) { + fun updateWith(source: GroupKDBX) { super.updateWith(source) - iconCustom = PwIconCustom(source.iconCustom) + iconCustom = IconImageCustom(source.iconCustom) usageCount = source.usageCount - locationChanged = PwDate(source.locationChanged) + locationChanged = DateInstant(source.locationChanged) // Add all custom elements in map customData.clear() for ((key, value) in source.customData) { @@ -122,10 +122,10 @@ class PwGroupV4 : PwGroup, PwNodeV4Interface { override var usageCount: Long = 0 - override var locationChanged = PwDate() + override var locationChanged = DateInstant() override fun afterAssignNewParent() { - locationChanged = PwDate() + locationChanged = DateInstant() } override fun putCustomData(key: String, value: String) { @@ -143,12 +143,12 @@ class PwGroupV4 : PwGroup, PwNodeV4Interface { companion object { @JvmField - val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwGroupV4 { - return PwGroupV4(parcel) + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): GroupKDBX { + return GroupKDBX(parcel) } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/GroupVersioned.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/GroupVersioned.kt index bdef36041..940ccfcb5 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/GroupVersioned.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/GroupVersioned.kt @@ -1,352 +1,80 @@ package com.kunzisoft.keepass.database.element import android.os.Parcel -import android.os.Parcelable -import java.util.* -import kotlin.collections.ArrayList -class GroupVersioned : NodeVersioned, PwGroupInterface { +abstract class GroupVersioned + < + GroupId, + EntryId, + Group: GroupVersioned, + Entry: EntryVersioned + > + : NodeVersioned, GroupVersionedInterface { - var pwGroupV3: PwGroupV3? = null - private set - var pwGroupV4: PwGroupV4? = null - private set + private var titleGroup = "" + @Transient + private val childGroups = ArrayList() + @Transient + private val childEntries = ArrayList() - fun updateWith(group: GroupVersioned) { - group.pwGroupV3?.let { - this.pwGroupV3?.updateWith(it) - } - group.pwGroupV4?.let { - this.pwGroupV4?.updateWith(it) - } - } + constructor() : super() - /** - * Use this constructor to copy a Group - */ - constructor(group: GroupVersioned) { - if (group.pwGroupV3 != null) { - if (this.pwGroupV3 == null) - this.pwGroupV3 = PwGroupV3() - } - if (group.pwGroupV4 != null) { - if (this.pwGroupV4 == null) - this.pwGroupV4 = PwGroupV4() - } - updateWith(group) - } - - constructor(group: PwGroupV3) { - this.pwGroupV4 = null - this.pwGroupV3 = group - } - - constructor(group: PwGroupV4) { - this.pwGroupV3 = null - this.pwGroupV4 = group - } - - constructor(parcel: Parcel) { - pwGroupV3 = parcel.readParcelable(PwGroupV3::class.java.classLoader) - pwGroupV4 = parcel.readParcelable(PwGroupV4::class.java.classLoader) - } - - companion object CREATOR : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): GroupVersioned { - return GroupVersioned(parcel) - } - - override fun newArray(size: Int): Array { - return arrayOfNulls(size) - } - } - - override fun describeContents(): Int { - return 0 + constructor(parcel: Parcel) : super(parcel) { + titleGroup = parcel.readString() ?: titleGroup } override fun writeToParcel(dest: Parcel, flags: Int) { - dest.writeParcelable(pwGroupV3, flags) - dest.writeParcelable(pwGroupV4, flags) + super.writeToParcel(dest, flags) + dest.writeString(titleGroup) } - override val nodeId: PwNodeId<*>? - get() = pwGroupV4?.nodeId ?: pwGroupV3?.nodeId + protected fun updateWith(source: GroupVersioned) { + super.updateWith(source) + titleGroup = source.titleGroup + childGroups.clear() + childGroups.addAll(source.childGroups) + childEntries.clear() + childEntries.addAll(source.childEntries) + } override var title: String - get() = pwGroupV3?.title ?: pwGroupV4?.title ?: "" - set(value) { - pwGroupV3?.title = value - pwGroupV4?.title = value - } + get() = titleGroup + set(value) { titleGroup = value } - override var icon: PwIcon - get() = pwGroupV3?.icon ?: pwGroupV4?.icon ?: PwIconStandard() - set(value) { - pwGroupV3?.icon = value - pwGroupV4?.icon = value - } - - override val type: Type - get() = Type.GROUP - - override var parent: GroupVersioned? - get() { - pwGroupV3?.parent?.let { - return GroupVersioned(it) - } - pwGroupV4?.parent?.let { - return GroupVersioned(it) - } - return null - } - set(value) { - pwGroupV3?.parent = value?.pwGroupV3 - pwGroupV4?.parent = value?.pwGroupV4 - } - - override fun containsParent(): Boolean { - return pwGroupV3?.containsParent() ?: pwGroupV4?.containsParent() ?: false + override fun getChildGroups(): MutableList { + return childGroups } - override fun afterAssignNewParent() { - pwGroupV3?.afterAssignNewParent() - pwGroupV4?.afterAssignNewParent() + override fun getChildEntries(): MutableList { + return childEntries } - fun addChildrenFrom(group: GroupVersioned) { - group.pwGroupV3?.getChildEntries()?.forEach { entryToAdd -> - pwGroupV3?.addChildEntry(entryToAdd) - } - group.pwGroupV3?.getChildGroups()?.forEach { groupToAdd -> - pwGroupV3?.addChildGroup(groupToAdd) - } - - group.pwGroupV4?.getChildEntries()?.forEach { entryToAdd -> - pwGroupV4?.addChildEntry(entryToAdd) - } - group.pwGroupV4?.getChildGroups()?.forEach { groupToAdd -> - pwGroupV4?.addChildGroup(groupToAdd) - } + override fun addChildGroup(group: Group) { + if (childGroups.contains(group)) + removeChildGroup(group) + this.childGroups.add(group) } - override fun touch(modified: Boolean, touchParents: Boolean) { - pwGroupV3?.touch(modified, touchParents) - pwGroupV4?.touch(modified, touchParents) + override fun addChildEntry(entry: Entry) { + if (childEntries.contains(entry)) + removeChildEntry(entry) + this.childEntries.add(entry) } - override fun isContainedIn(container: GroupVersioned): Boolean { - var contained: Boolean? = null - container.pwGroupV3?.let { - contained = pwGroupV3?.isContainedIn(it) - } - container.pwGroupV4?.let { - contained = pwGroupV4?.isContainedIn(it) - } - return contained ?: false + override fun removeChildGroup(group: Group) { + this.childGroups.remove(group) } - override var creationTime: PwDate - get() = pwGroupV3?.creationTime ?: pwGroupV4?.creationTime ?: PwDate() - set(value) { - pwGroupV3?.creationTime = value - pwGroupV4?.creationTime = value - } - - override var lastModificationTime: PwDate - get() = pwGroupV3?.lastModificationTime ?: pwGroupV4?.lastModificationTime ?: PwDate() - set(value) { - pwGroupV3?.lastModificationTime = value - pwGroupV4?.lastModificationTime = value - } - - override var lastAccessTime: PwDate - get() = pwGroupV3?.lastAccessTime ?: pwGroupV4?.lastAccessTime ?: PwDate() - set(value) { - pwGroupV3?.lastAccessTime = value - pwGroupV4?.lastAccessTime = value - } - - override var expiryTime: PwDate - get() = pwGroupV3?.expiryTime ?: pwGroupV4?.expiryTime ?: PwDate() - set(value) { - pwGroupV3?.expiryTime = value - pwGroupV4?.expiryTime = value - } - - override var expires: Boolean - get() = pwGroupV3?.expires ?: pwGroupV4?.expires ?: false - set(value) { - pwGroupV3?.expires = value - pwGroupV4?.expires = value - } - - override val isCurrentlyExpires: Boolean - get() = pwGroupV3?.isCurrentlyExpires ?: pwGroupV4?.isCurrentlyExpires ?: false - - override fun getChildGroups(): MutableList { - val children = ArrayList() - - pwGroupV3?.getChildGroups()?.forEach { - children.add(GroupVersioned(it)) - } - pwGroupV4?.getChildGroups()?.forEach { - children.add(GroupVersioned(it)) - } - - return children - } - - override fun getChildEntries(): MutableList { - return getChildEntries(false) - } - - fun getChildEntries(withoutMetaStream: Boolean): MutableList { - val children = ArrayList() - - pwGroupV3?.getChildEntries()?.forEach { - val entryToAddAsChild = EntryVersioned(it) - if (!withoutMetaStream || (withoutMetaStream && !entryToAddAsChild.isMetaStream)) - children.add(entryToAddAsChild) - } - pwGroupV4?.getChildEntries()?.forEach { - children.add(EntryVersioned(it)) - } - - return children - } - - /** - * Filter MetaStream entries and return children - * @return List of direct children (one level below) as PwNode - */ - fun getChildren(withoutMetaStream: Boolean = true): List { - val children = ArrayList() - children.addAll(getChildGroups()) - - pwGroupV3?.let { - children.addAll(getChildEntries(withoutMetaStream)) - } - pwGroupV4?.let { - // No MetasStream in V4 - children.addAll(getChildEntries(withoutMetaStream)) - } - - return children - } - - override fun addChildGroup(group: GroupVersioned) { - group.pwGroupV3?.let { - pwGroupV3?.addChildGroup(it) - } - group.pwGroupV4?.let { - pwGroupV4?.addChildGroup(it) - } - } - - override fun addChildEntry(entry: EntryVersioned) { - entry.pwEntryV3?.let { - pwGroupV3?.addChildEntry(it) - } - entry.pwEntryV4?.let { - pwGroupV4?.addChildEntry(it) - } - } - - override fun removeChildGroup(group: GroupVersioned) { - group.pwGroupV3?.let { - pwGroupV3?.removeChildGroup(it) - } - group.pwGroupV4?.let { - pwGroupV4?.removeChildGroup(it) - } - } - - override fun removeChildEntry(entry: EntryVersioned) { - entry.pwEntryV3?.let { - pwGroupV3?.removeChildEntry(it) - } - entry.pwEntryV4?.let { - pwGroupV4?.removeChildEntry(it) - } + override fun removeChildEntry(entry: Entry) { + this.childEntries.remove(entry) } override fun removeChildren() { - pwGroupV3?.removeChildren() - pwGroupV4?.removeChildren() + this.childGroups.clear() + this.childEntries.clear() } - override fun allowAddEntryIfIsRoot(): Boolean { - return pwGroupV3?.allowAddEntryIfIsRoot() ?: pwGroupV4?.allowAddEntryIfIsRoot() ?: false - } - - /* - ------------ - V3 Methods - ------------ - */ - - var nodeIdV3: PwNodeId - get() = pwGroupV3?.nodeId ?: PwNodeIdInt() - set(value) { pwGroupV3?.nodeId = value } - - fun setNodeId(id: PwNodeIdInt) { - pwGroupV3?.nodeId = id - } - - fun getLevel(): Int { - return pwGroupV3?.level ?: -1 - } - - fun setLevel(level: Int) { - pwGroupV3?.level = level - } - - /* - ------------ - V4 Methods - ------------ - */ - - var nodeIdV4: PwNodeId - get() = pwGroupV4?.nodeId ?: PwNodeIdUUID() - set(value) { pwGroupV4?.nodeId = value } - - fun setNodeId(id: PwNodeIdUUID) { - pwGroupV4?.nodeId = id - } - - fun setEnableAutoType(enableAutoType: Boolean?) { - pwGroupV4?.enableAutoType = enableAutoType - } - - fun setEnableSearching(enableSearching: Boolean?) { - pwGroupV4?.enableSearching = enableSearching - } - - fun setExpanded(expanded: Boolean) { - pwGroupV4?.isExpanded = expanded - } - - fun containsCustomData(): Boolean { - return pwGroupV4?.containsCustomData() ?: false - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as GroupVersioned - - if (pwGroupV3 != other.pwGroupV3) return false - if (pwGroupV4 != other.pwGroupV4) return false - - return true - } - - override fun hashCode(): Int { - var result = pwGroupV3?.hashCode() ?: 0 - result = 31 * result + (pwGroupV4?.hashCode() ?: 0) - return result + override fun toString(): String { + return titleGroup } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwGroupInterface.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/GroupVersionedInterface.kt similarity index 92% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwGroupInterface.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/GroupVersionedInterface.kt index 11486cd94..3d36efa1a 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwGroupInterface.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/GroupVersionedInterface.kt @@ -2,7 +2,7 @@ package com.kunzisoft.keepass.database.element import com.kunzisoft.keepass.database.NodeHandler -interface PwGroupInterface, Entry> : PwNodeInterface { +interface GroupVersionedInterface, Entry> : NodeVersionedInterface { fun getChildGroups(): MutableList diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwIcon.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/IconImage.kt similarity index 94% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwIcon.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/IconImage.kt index b34ae0222..59cd14b69 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwIcon.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/IconImage.kt @@ -21,7 +21,7 @@ package com.kunzisoft.keepass.database.element import android.os.Parcelable -abstract class PwIcon protected constructor() : Parcelable { +abstract class IconImage protected constructor() : Parcelable { abstract val iconId: Int abstract val isUnknown: Boolean diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwIconCustom.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/IconImageCustom.kt similarity index 81% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwIconCustom.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/IconImageCustom.kt index ce8f47801..b2f6b17a1 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwIconCustom.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/IconImageCustom.kt @@ -24,7 +24,7 @@ import android.os.Parcelable import java.util.UUID -class PwIconCustom : PwIcon { +class IconImageCustom : IconImage { val uuid: UUID @Transient @@ -40,7 +40,7 @@ class PwIconCustom : PwIcon { this.imageData = ByteArray(0) } - constructor(icon: PwIconCustom) : super() { + constructor(icon: IconImageCustom) : super() { uuid = icon.uuid imageData = icon.imageData } @@ -68,7 +68,7 @@ class PwIconCustom : PwIcon { return true if (other == null) return false - if (other !is PwIconCustom) + if (other !is IconImageCustom) return false return uuid == other.uuid } @@ -83,15 +83,15 @@ class PwIconCustom : PwIcon { get() = false companion object { - val UNKNOWN_ICON = PwIconCustom(PwDatabase.UUID_ZERO, ByteArray(0)) + val UNKNOWN_ICON = IconImageCustom(DatabaseVersioned.UUID_ZERO, ByteArray(0)) @JvmField - val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwIconCustom { - return PwIconCustom(parcel) + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): IconImageCustom { + return IconImageCustom(parcel) } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwIconFactory.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/IconImageFactory.kt similarity index 64% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwIconFactory.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/IconImageFactory.kt index d8a53fd7a..4b2dee048 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwIconFactory.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/IconImageFactory.kt @@ -24,54 +24,54 @@ import org.apache.commons.collections.map.ReferenceMap import java.util.UUID -class PwIconFactory { +class IconImageFactory { /** customIconMap * Cache for icon drawable. - * Keys: Integer, Values: PwIconStandard + * Keys: Integer, Values: IconImageStandard */ private val cache = ReferenceMap(AbstractReferenceMap.HARD, AbstractReferenceMap.WEAK) /** standardIconMap * Cache for icon drawable. - * Keys: UUID, Values: PwIconCustom + * Keys: UUID, Values: IconImageCustom */ private val customCache = ReferenceMap(AbstractReferenceMap.HARD, AbstractReferenceMap.WEAK) - val unknownIcon: PwIconStandard - get() = getIcon(PwIcon.UNKNOWN_ID) + val unknownIcon: IconImageStandard + get() = getIcon(IconImage.UNKNOWN_ID) - val keyIcon: PwIconStandard - get() = getIcon(PwIconStandard.KEY) + val keyIcon: IconImageStandard + get() = getIcon(IconImageStandard.KEY) - val trashIcon: PwIconStandard - get() = getIcon(PwIconStandard.TRASH) + val trashIcon: IconImageStandard + get() = getIcon(IconImageStandard.TRASH) - val folderIcon: PwIconStandard - get() = getIcon(PwIconStandard.FOLDER) + val folderIcon: IconImageStandard + get() = getIcon(IconImageStandard.FOLDER) - fun getIcon(iconId: Int): PwIconStandard { - var icon: PwIconStandard? = cache[iconId] as PwIconStandard? + fun getIcon(iconId: Int): IconImageStandard { + var icon: IconImageStandard? = cache[iconId] as IconImageStandard? if (icon == null) { - icon = PwIconStandard(iconId) + icon = IconImageStandard(iconId) cache[iconId] = icon } return icon } - fun getIcon(iconUuid: UUID): PwIconCustom { - var icon: PwIconCustom? = customCache[iconUuid] as PwIconCustom? + fun getIcon(iconUuid: UUID): IconImageCustom { + var icon: IconImageCustom? = customCache[iconUuid] as IconImageCustom? if (icon == null) { - icon = PwIconCustom(iconUuid) + icon = IconImageCustom(iconUuid) customCache[iconUuid] = icon } return icon } - fun put(icon: PwIconCustom) { + fun put(icon: IconImageCustom) { customCache[icon.uuid] = icon } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwIconStandard.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/IconImageStandard.kt similarity index 81% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwIconStandard.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/IconImageStandard.kt index 4d7931986..229dc19bc 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwIconStandard.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/IconImageStandard.kt @@ -22,7 +22,7 @@ package com.kunzisoft.keepass.database.element import android.os.Parcel import android.os.Parcelable -class PwIconStandard : PwIcon { +class IconImageStandard : IconImage { constructor() { this.iconId = KEY @@ -32,7 +32,7 @@ class PwIconStandard : PwIcon { this.iconId = iconId } - constructor(icon: PwIconStandard) { + constructor(icon: IconImageStandard) { this.iconId = icon.iconId } @@ -56,7 +56,7 @@ class PwIconStandard : PwIcon { return true if (other == null) return false - if (other !is PwIconStandard) { + if (other !is IconImageStandard) { return false } return iconId == other.iconId @@ -77,12 +77,12 @@ class PwIconStandard : PwIcon { const val FOLDER = 48 @JvmField - val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwIconStandard { - return PwIconStandard(parcel) + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): IconImageStandard { + return IconImageStandard(parcel) } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Node.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Node.kt new file mode 100644 index 000000000..ba887be30 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Node.kt @@ -0,0 +1,34 @@ +package com.kunzisoft.keepass.database.element + +interface Node: NodeVersionedInterface { + + val nodeId: NodeId<*>? + + val nodePositionInParent: Int + get() { + parent?.getChildren(true)?.let { children -> + children.forEachIndexed { index, nodeVersioned -> + if (nodeVersioned.nodeId == this.nodeId) + return index + } + } + return -1 + } + + fun addParentFrom(node: Node) { + parent = node.parent + } + + fun removeParent() { + parent = null + } +} + +/** + * Type of available Nodes + */ +enum class Type { + GROUP, ENTRY +} + + diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeId.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeId.kt similarity index 93% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeId.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/NodeId.kt index 38bc119b5..a6faa9690 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeId.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeId.kt @@ -22,7 +22,7 @@ package com.kunzisoft.keepass.database.element import android.os.Parcel import android.os.Parcelable -abstract class PwNodeId : Parcelable { +abstract class NodeId : Parcelable { abstract val id: Id @@ -34,7 +34,7 @@ abstract class PwNodeId : Parcelable { override fun equals(other: Any?): Boolean { if (this === other) return true - if (other !is PwNodeId<*>) return false + if (other !is NodeId<*>) return false if (id != other.id) return false diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeIdInt.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeIdInt.kt similarity index 81% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeIdInt.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/NodeIdInt.kt index 6ff613d7f..49fd2e3ff 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeIdInt.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeIdInt.kt @@ -24,12 +24,12 @@ import android.os.Parcelable import java.util.Random -class PwNodeIdInt : PwNodeId { +class NodeIdInt : NodeId { override var id: Int = -1 private set - constructor(source: PwNodeIdInt) : this(source.id) + constructor(source: NodeIdInt) : this(source.id) @JvmOverloads constructor(groupId: Int = Random().nextInt()) : super() { @@ -50,7 +50,7 @@ class PwNodeIdInt : PwNodeId { return true if (other == null) return false - if (other !is PwNodeIdInt) { + if (other !is NodeIdInt) { return false } return id == other.id @@ -66,12 +66,12 @@ class PwNodeIdInt : PwNodeId { companion object { @JvmField - val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwNodeIdInt { - return PwNodeIdInt(parcel) + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): NodeIdInt { + return NodeIdInt(parcel) } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeIdUUID.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeIdUUID.kt similarity index 80% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeIdUUID.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/NodeIdUUID.kt index aac6d7cf8..94ebd6429 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeIdUUID.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeIdUUID.kt @@ -24,12 +24,12 @@ import android.os.Parcelable import java.util.UUID -class PwNodeIdUUID : PwNodeId { +class NodeIdUUID : NodeId { override var id: UUID = UUID.randomUUID() private set - constructor(source: PwNodeIdUUID) : this(source.id) + constructor(source: NodeIdUUID) : this(source.id) @JvmOverloads constructor(uuid: UUID = UUID.randomUUID()) : super() { @@ -50,7 +50,7 @@ class PwNodeIdUUID : PwNodeId { return true if (other == null) return false - if (other !is PwNodeIdUUID) { + if (other !is NodeIdUUID) { return false } return this.id == other.id @@ -66,12 +66,12 @@ class PwNodeIdUUID : PwNodeId { companion object { @JvmField - val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - override fun createFromParcel(parcel: Parcel): PwNodeIdUUID { - return PwNodeIdUUID(parcel) + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): NodeIdUUID { + return NodeIdUUID(parcel) } - override fun newArray(size: Int): Array { + override fun newArray(size: Int): Array { return arrayOfNulls(size) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeV3Interface.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeKDBInterface.kt similarity index 66% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeV3Interface.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/NodeKDBInterface.kt index ee39cc0e6..bd1105e37 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeV3Interface.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeKDBInterface.kt @@ -2,17 +2,17 @@ package com.kunzisoft.keepass.database.element import org.joda.time.LocalDateTime -interface PwNodeV3Interface : NodeTimeInterface { +interface NodeKDBInterface : NodeTimeInterface { override var expires: Boolean // If expireDate is before NEVER_EXPIRE date less 1 month (to be sure) // it is not expires get() = LocalDateTime(expiryTime.date) - .isBefore(LocalDateTime.fromDateFields(PwDate.NEVER_EXPIRE.date) + .isBefore(LocalDateTime.fromDateFields(DateInstant.NEVER_EXPIRE.date) .minusMonths(1)) set(value) { if (!value) - expiryTime = PwDate.NEVER_EXPIRE + expiryTime = DateInstant.NEVER_EXPIRE } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeV4Interface.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeKDBXInterface.kt similarity index 91% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeV4Interface.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/NodeKDBXInterface.kt index 60f87d2c7..ab4c50322 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeV4Interface.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeKDBXInterface.kt @@ -19,11 +19,11 @@ */ package com.kunzisoft.keepass.database.element -interface PwNodeV4Interface : NodeTimeInterface { +interface NodeKDBXInterface : NodeTimeInterface { var usageCount: Long - var locationChanged: PwDate + var locationChanged: DateInstant fun putCustomData(key: String, value: String) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/NodeTimeInterface.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeTimeInterface.kt index 7decbd1c0..aba8d15fd 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/NodeTimeInterface.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeTimeInterface.kt @@ -21,13 +21,13 @@ package com.kunzisoft.keepass.database.element interface NodeTimeInterface { - var creationTime: PwDate + var creationTime: DateInstant - var lastModificationTime: PwDate + var lastModificationTime: DateInstant - var lastAccessTime: PwDate + var lastAccessTime: DateInstant - var expiryTime: PwDate + var expiryTime: DateInstant var expires: Boolean diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/NodeVersioned.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeVersioned.kt index f231245f8..78e92af7e 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/NodeVersioned.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeVersioned.kt @@ -1,34 +1,147 @@ +/* + * Copyright 2019 Jeremy Jamet / Kunzisoft. + * + * This file is part of KeePass DX. + * + * KeePass DX 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. + * + * KeePass DX 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 KeePass DX. If not, see . + * + * + */ package com.kunzisoft.keepass.database.element -interface NodeVersioned: PwNodeInterface { - - val nodeId: PwNodeId<*>? - - val nodePositionInParent: Int - get() { - parent?.getChildren(true)?.let { children -> - children.forEachIndexed { index, nodeVersioned -> - if (nodeVersioned.nodeId == this.nodeId) - return index - } - } - return -1 - } - - fun addParentFrom(node: NodeVersioned) { - parent = node.parent - } - - fun removeParent() { - parent = null - } -} +import android.os.Parcel +import android.os.Parcelable +import org.joda.time.LocalDateTime /** - * Type of available Nodes + * Abstract class who manage Groups and Entries */ -enum class Type { - GROUP, ENTRY +abstract class NodeVersioned, Entry : EntryVersionedInterface> + : NodeVersionedInterface, NodeTimeInterface, Parcelable { + + var nodeId: NodeId = this.initNodeId() + + val id: IdType + get() = nodeId.id + + protected constructor() + + protected constructor(parcel: Parcel) { + this.nodeId = parcel.readParcelable(NodeId::class.java.classLoader) ?: nodeId + this.parent = this.readParentParcelable(parcel) + this.icon = parcel.readParcelable(IconImage::class.java.classLoader) ?: icon + this.creationTime = parcel.readParcelable(DateInstant::class.java.classLoader) ?: creationTime + this.lastModificationTime = parcel.readParcelable(DateInstant::class.java.classLoader) ?: lastModificationTime + this.lastAccessTime = parcel.readParcelable(DateInstant::class.java.classLoader) ?: lastAccessTime + this.expiryTime = parcel.readParcelable(DateInstant::class.java.classLoader) ?: expiryTime + this.expires = parcel.readByte().toInt() != 0 + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeParcelable(nodeId, flags) + writeParentParcelable(parent, dest, flags) + dest.writeParcelable(icon, flags) + dest.writeParcelable(creationTime, flags) + dest.writeParcelable(lastModificationTime, flags) + dest.writeParcelable(lastAccessTime, flags) + dest.writeParcelable(expiryTime, flags) + dest.writeByte((if (expires) 1 else 0).toByte()) + } + + override fun describeContents(): Int { + return 0 + } + + protected fun updateWith(source: NodeVersioned) { + this.nodeId = copyNodeId(source.nodeId) + this.parent = source.parent + this.icon = source.icon + this.creationTime = DateInstant(source.creationTime) + this.lastModificationTime = DateInstant(source.lastModificationTime) + this.lastAccessTime = DateInstant(source.lastAccessTime) + this.expiryTime = DateInstant(source.expiryTime) + this.expires = source.expires + } + + protected abstract fun initNodeId(): NodeId + protected abstract fun copyNodeId(nodeId: NodeId): NodeId + protected abstract fun readParentParcelable(parcel: Parcel): Parent? + protected abstract fun writeParentParcelable(parent: Parent?, parcel: Parcel, flags: Int) + + final override var parent: Parent? = null + + override var icon: IconImage = IconImageStandard() + + final override var creationTime: DateInstant = DateInstant() + + final override var lastModificationTime: DateInstant = DateInstant() + + final override var lastAccessTime: DateInstant = DateInstant() + + final override var expiryTime: DateInstant = DateInstant.NEVER_EXPIRE + + final override val isCurrentlyExpires: Boolean + get() = expires + && LocalDateTime.fromDateFields(expiryTime.date).isBefore(LocalDateTime.now()) + + /** + * @return true if parent is present (false if not present, can be a root or a detach element) + */ + override fun containsParent(): Boolean { + return parent != null + } + + override fun afterAssignNewParent() {} + + override fun isContainedIn(container: Parent): Boolean { + if (this == container) + return true + var cur = this.parent + while (cur != null) { + if (cur == container) { + return true + } + cur = cur.parent + } + return false + } + + override fun touch(modified: Boolean, touchParents: Boolean) { + val now = DateInstant() + lastAccessTime = now + + if (modified) { + lastModificationTime = now + } + + if (touchParents) { + parent?.touch(modified, true) + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) + return true + if (other == null) + return false + if (other !is NodeVersioned<*, *, *>) { + return false + } + return type == other.type && nodeId == other.nodeId + } + + override fun hashCode(): Int { + return nodeId.hashCode() + } } - - diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeInterface.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeVersionedInterface.kt similarity index 81% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeInterface.kt rename to app/src/main/java/com/kunzisoft/keepass/database/element/NodeVersionedInterface.kt index 89db8b52c..a49f0321a 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNodeInterface.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/NodeVersionedInterface.kt @@ -2,14 +2,14 @@ package com.kunzisoft.keepass.database.element import android.os.Parcelable -interface PwNodeInterface : NodeTimeInterface, Parcelable { +interface NodeVersionedInterface : NodeTimeInterface, Parcelable { var title: String /** * @return Visual icon */ - var icon: PwIcon + var icon: IconImage /** * @return Type of Node diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntry.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntry.kt deleted file mode 100644 index e5a1067ae..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntry.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.kunzisoft.keepass.database.element - -import android.os.Parcel -import java.util.* - -abstract class PwEntry - < - GroupId, - EntryId, - ParentGroup: PwGroup, - Entry: PwEntry - > - : PwNode, PwEntryInterface { - - constructor() : super() - - constructor(parcel: Parcel) : super(parcel) - -} \ No newline at end of file diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwGroup.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/PwGroup.kt deleted file mode 100644 index 82c0260e3..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwGroup.kt +++ /dev/null @@ -1,80 +0,0 @@ -package com.kunzisoft.keepass.database.element - -import android.os.Parcel - -abstract class PwGroup - < - GroupId, - EntryId, - Group: PwGroup, - Entry: PwEntry - > - : PwNode, PwGroupInterface { - - private var titleGroup = "" - @Transient - private val childGroups = ArrayList() - @Transient - private val childEntries = ArrayList() - - constructor() : super() - - constructor(parcel: Parcel) : super(parcel) { - titleGroup = parcel.readString() ?: titleGroup - } - - override fun writeToParcel(dest: Parcel, flags: Int) { - super.writeToParcel(dest, flags) - dest.writeString(titleGroup) - } - - protected fun updateWith(source: PwGroup) { - super.updateWith(source) - titleGroup = source.titleGroup - childGroups.clear() - childGroups.addAll(source.childGroups) - childEntries.clear() - childEntries.addAll(source.childEntries) - } - - override var title: String - get() = titleGroup - set(value) { titleGroup = value } - - override fun getChildGroups(): MutableList { - return childGroups - } - - override fun getChildEntries(): MutableList { - return childEntries - } - - override fun addChildGroup(group: Group) { - if (childGroups.contains(group)) - removeChildGroup(group) - this.childGroups.add(group) - } - - override fun addChildEntry(entry: Entry) { - if (childEntries.contains(entry)) - removeChildEntry(entry) - this.childEntries.add(entry) - } - - override fun removeChildGroup(group: Group) { - this.childGroups.remove(group) - } - - override fun removeChildEntry(entry: Entry) { - this.childEntries.remove(entry) - } - - override fun removeChildren() { - this.childGroups.clear() - this.childEntries.clear() - } - - override fun toString(): String { - return titleGroup - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNode.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/PwNode.kt deleted file mode 100644 index 12aa35ceb..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwNode.kt +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2019 Jeremy Jamet / Kunzisoft. - * - * This file is part of KeePass DX. - * - * KeePass DX 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. - * - * KeePass DX 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 KeePass DX. If not, see . - * - * - */ -package com.kunzisoft.keepass.database.element - -import android.os.Parcel -import android.os.Parcelable -import org.joda.time.LocalDateTime - -/** - * Abstract class who manage Groups and Entries - */ -abstract class PwNode, Entry : PwEntryInterface> - : PwNodeInterface, NodeTimeInterface, Parcelable { - - var nodeId: PwNodeId = this.initNodeId() - - val id: IdType - get() = nodeId.id - - protected constructor() - - protected constructor(parcel: Parcel) { - this.nodeId = parcel.readParcelable(PwNodeId::class.java.classLoader) ?: nodeId - this.parent = this.readParentParcelable(parcel) - this.icon = parcel.readParcelable(PwIcon::class.java.classLoader) ?: icon - this.creationTime = parcel.readParcelable(PwDate::class.java.classLoader) ?: creationTime - this.lastModificationTime = parcel.readParcelable(PwDate::class.java.classLoader) ?: lastModificationTime - this.lastAccessTime = parcel.readParcelable(PwDate::class.java.classLoader) ?: lastAccessTime - this.expiryTime = parcel.readParcelable(PwDate::class.java.classLoader) ?: expiryTime - this.expires = parcel.readByte().toInt() != 0 - } - - override fun writeToParcel(dest: Parcel, flags: Int) { - dest.writeParcelable(nodeId, flags) - writeParentParcelable(parent, dest, flags) - dest.writeParcelable(icon, flags) - dest.writeParcelable(creationTime, flags) - dest.writeParcelable(lastModificationTime, flags) - dest.writeParcelable(lastAccessTime, flags) - dest.writeParcelable(expiryTime, flags) - dest.writeByte((if (expires) 1 else 0).toByte()) - } - - override fun describeContents(): Int { - return 0 - } - - protected fun updateWith(source: PwNode) { - this.nodeId = copyNodeId(source.nodeId) - this.parent = source.parent - this.icon = source.icon - this.creationTime = PwDate(source.creationTime) - this.lastModificationTime = PwDate(source.lastModificationTime) - this.lastAccessTime = PwDate(source.lastAccessTime) - this.expiryTime = PwDate(source.expiryTime) - this.expires = source.expires - } - - protected abstract fun initNodeId(): PwNodeId - protected abstract fun copyNodeId(nodeId: PwNodeId): PwNodeId - protected abstract fun readParentParcelable(parcel: Parcel): Parent? - protected abstract fun writeParentParcelable(parent: Parent?, parcel: Parcel, flags: Int) - - final override var parent: Parent? = null - - override var icon: PwIcon = PwIconStandard() - - final override var creationTime: PwDate = PwDate() - - final override var lastModificationTime: PwDate = PwDate() - - final override var lastAccessTime: PwDate = PwDate() - - final override var expiryTime: PwDate = PwDate.NEVER_EXPIRE - - final override val isCurrentlyExpires: Boolean - get() = expires - && LocalDateTime.fromDateFields(expiryTime.date).isBefore(LocalDateTime.now()) - - /** - * @return true if parent is present (false if not present, can be a root or a detach element) - */ - override fun containsParent(): Boolean { - return parent != null - } - - override fun afterAssignNewParent() {} - - override fun isContainedIn(container: Parent): Boolean { - if (this == container) - return true - var cur = this.parent - while (cur != null) { - if (cur == container) { - return true - } - cur = cur.parent - } - return false - } - - override fun touch(modified: Boolean, touchParents: Boolean) { - val now = PwDate() - lastAccessTime = now - - if (modified) { - lastModificationTime = now - } - - if (touchParents) { - parent?.touch(modified, true) - } - } - - override fun equals(other: Any?): Boolean { - if (this === other) - return true - if (other == null) - return false - if (other !is PwNode<*, *, *>) { - return false - } - return type == other.type && nodeId == other.nodeId - } - - override fun hashCode(): Int { - return nodeId.hashCode() - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/security/BinaryAttachment.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/security/BinaryAttachment.kt index a3b8379c8..fa2966850 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/security/BinaryAttachment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/security/BinaryAttachment.kt @@ -21,7 +21,7 @@ package com.kunzisoft.keepass.database.element.security import android.os.Parcel import android.os.Parcelable -import com.kunzisoft.keepass.database.element.PwDatabaseV4.Companion.BUFFER_SIZE_BYTES +import com.kunzisoft.keepass.database.element.DatabaseKDBX.Companion.BUFFER_SIZE_BYTES import com.kunzisoft.keepass.stream.ReadBytes import com.kunzisoft.keepass.stream.readFromStream import java.io.* diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/DatabaseException.kt b/app/src/main/java/com/kunzisoft/keepass/database/exception/DatabaseException.kt index 51033b5e9..bff4a7616 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/DatabaseException.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/DatabaseException.kt @@ -3,7 +3,7 @@ package com.kunzisoft.keepass.database.exception import android.content.res.Resources import androidx.annotation.StringRes import com.kunzisoft.keepass.R -import com.kunzisoft.keepass.database.element.PwNodeId +import com.kunzisoft.keepass.database.element.NodeId import com.kunzisoft.keepass.database.element.Type abstract class DatabaseException : Exception { @@ -56,7 +56,7 @@ class InvalidAlgorithmDatabaseException : LoadDatabaseException { class DuplicateUuidDatabaseException: LoadDatabaseException { @StringRes override var errorId: Int = R.string.invalid_db_same_uuid - constructor(type: Type, uuid: PwNodeId<*>) : super() { + constructor(type: Type, uuid: NodeId<*>) : super() { parameters = arrayOf(type.name, uuid.toString()) } constructor(exception: Throwable) : super(exception) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeader.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/DatabaseHeader.kt similarity index 97% rename from app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeader.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/DatabaseHeader.kt index d8499b25e..2a9432d6f 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeader.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/DatabaseHeader.kt @@ -19,7 +19,7 @@ */ package com.kunzisoft.keepass.database.file -abstract class PwDbHeader { +abstract class DatabaseHeader { /** * Seed that gets hashed with the userkey to form the final key diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/DatabaseHeaderKDB.kt similarity index 98% rename from app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/DatabaseHeaderKDB.kt index 35375309e..12d1a629c 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/DatabaseHeaderKDB.kt @@ -25,7 +25,7 @@ import com.kunzisoft.keepass.stream.LEDataInputStream import java.io.IOException -class PwDbHeaderV3 : PwDbHeader() { +class DatabaseHeaderKDB : DatabaseHeader() { /** * Used for the dwKeyEncRounds AES transformations diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/DatabaseHeaderKDBX.kt similarity index 94% rename from app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/DatabaseHeaderKDBX.kt index bde2a9f33..012a2e2b0 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/DatabaseHeaderKDBX.kt @@ -40,7 +40,7 @@ import java.security.NoSuchAlgorithmException import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec -class PwDbHeaderV4(private val databaseV4: PwDatabaseV4) : PwDbHeader() { +class DatabaseHeaderKDBX(private val databaseV4: DatabaseKDBX) : DatabaseHeader() { var innerRandomStreamKey: ByteArray = ByteArray(32) var streamStartBytes: ByteArray = ByteArray(32) var innerRandomStream: CrsAlgorithm? = null @@ -89,7 +89,7 @@ class PwDbHeaderV4(private val databaseV4: PwDatabaseV4) : PwDbHeader() { this.masterSeed = ByteArray(32) } - private inner class NodeHasCustomData : NodeHandler() { + private inner class NodeHasCustomData : NodeHandler() { internal var containsCustomData = false @@ -102,7 +102,7 @@ class PwDbHeaderV4(private val databaseV4: PwDatabaseV4) : PwDbHeader() { } } - private fun getMinKdbxVersion(databaseV4: PwDatabaseV4): Long { + private fun getMinKdbxVersion(databaseV4: DatabaseKDBX): Long { // https://keepass.info/help/kb/kdbx_4.html // Return v4 if AES is not use @@ -115,8 +115,8 @@ class PwDbHeaderV4(private val databaseV4: PwDatabaseV4) : PwDbHeader() { return FILE_VERSION_32_3 } - val entryHandler = NodeHasCustomData() - val groupHandler = NodeHasCustomData() + val entryHandler = NodeHasCustomData() + val groupHandler = NodeHasCustomData() databaseV4.rootGroup?.doForEachChildAndForIt(entryHandler, groupHandler) return if (databaseV4.containsCustomData() || entryHandler.containsCustomData @@ -256,7 +256,7 @@ class PwDbHeaderV4(private val databaseV4: PwDatabaseV4) : PwDbHeader() { } val flag = LEDataInputStream.readInt(pbFlags, 0) - if (flag < 0 || flag >= PwCompressionAlgorithm.values().size) { + if (flag < 0 || flag >= CompressionAlgorithm.values().size) { throw IOException("Unrecognized compression flag.") } @@ -298,17 +298,17 @@ class PwDbHeaderV4(private val databaseV4: PwDatabaseV4) : PwDbHeader() { const val FILE_VERSION_32_3: Long = 0x00030001 const val FILE_VERSION_32_4: Long = 0x00040000 - fun getCompressionFromFlag(flag: Int): PwCompressionAlgorithm? { + fun getCompressionFromFlag(flag: Int): CompressionAlgorithm? { return when (flag) { - 0 -> PwCompressionAlgorithm.None - 1 -> PwCompressionAlgorithm.GZip + 0 -> CompressionAlgorithm.None + 1 -> CompressionAlgorithm.GZip else -> null } } - fun getFlagFromCompression(compression: PwCompressionAlgorithm): Int { + fun getFlagFromCompression(compression: CompressionAlgorithm): Int { return when (compression) { - PwCompressionAlgorithm.GZip -> 1 + CompressionAlgorithm.GZip -> 1 else -> 0 } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/KDBX4DateUtil.java b/app/src/main/java/com/kunzisoft/keepass/database/file/DateKDBXUtil.java similarity index 98% rename from app/src/main/java/com/kunzisoft/keepass/database/file/KDBX4DateUtil.java rename to app/src/main/java/com/kunzisoft/keepass/database/file/DateKDBXUtil.java index 565393611..35c5a8c23 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/KDBX4DateUtil.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/DateKDBXUtil.java @@ -25,7 +25,7 @@ import org.joda.time.Duration; import java.util.Date; -public class KDBX4DateUtil { +public class DateKDBXUtil { private static final DateTime dotNetEpoch = new DateTime(1, 1, 1, 0, 0, 0, DateTimeZone.UTC); private static final DateTime javaEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeZone.UTC); diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/load/Importer.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/load/Importer.kt index 8743eb855..7009282a5 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/load/Importer.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/load/Importer.kt @@ -19,19 +19,19 @@ */ package com.kunzisoft.keepass.database.file.load -import com.kunzisoft.keepass.database.element.PwDatabase +import com.kunzisoft.keepass.database.element.DatabaseVersioned import com.kunzisoft.keepass.database.exception.LoadDatabaseException import com.kunzisoft.keepass.tasks.ProgressTaskUpdater import java.io.InputStream -abstract class Importer> { +abstract class Importer> { /** - * Load a versioned database file, return contents in a new PwDatabase. + * Load a versioned database file, return contents in a new DatabaseVersioned. * * @param databaseInputStream Existing file to load. * @param password Pass phrase for infile. - * @return new PwDatabase container. + * @return new DatabaseVersioned container. * * @throws LoadDatabaseException on database error (contains IO exceptions) */ diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterKDB.kt similarity index 86% rename from app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterKDB.kt index e968d7183..f71f7bbec 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterKDB.kt @@ -50,8 +50,8 @@ import com.kunzisoft.keepass.R import com.kunzisoft.keepass.crypto.CipherFactory import com.kunzisoft.keepass.database.element.* import com.kunzisoft.keepass.database.exception.* -import com.kunzisoft.keepass.database.file.PwDbHeader -import com.kunzisoft.keepass.database.file.PwDbHeaderV3 +import com.kunzisoft.keepass.database.file.DatabaseHeader +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDB import com.kunzisoft.keepass.stream.LEDataInputStream import com.kunzisoft.keepass.stream.NullOutputStream import com.kunzisoft.keepass.tasks.ProgressTaskUpdater @@ -67,17 +67,17 @@ import java.security.* import java.util.Arrays /** - * Load a v3 database file. + * Load a KDB database file. */ -class ImporterV3 : Importer() { +class ImporterKDB : Importer() { - private lateinit var mDatabaseToOpen: PwDatabaseV3 + private lateinit var mDatabaseToOpen: DatabaseKDB @Throws(LoadDatabaseException::class) override fun openDatabase(databaseInputStream: InputStream, password: String?, keyInputStream: InputStream?, - progressTaskUpdater: ProgressTaskUpdater?): PwDatabaseV3 { + progressTaskUpdater: ProgressTaskUpdater?): DatabaseKDB { try { // Load entire file, most of it's encrypted. @@ -87,12 +87,12 @@ class ImporterV3 : Importer() { databaseInputStream.close() // Parse header (unencrypted) - if (fileSize < PwDbHeaderV3.BUF_SIZE) + if (fileSize < DatabaseHeaderKDB.BUF_SIZE) throw IOException("File too short for header") - val hdr = PwDbHeaderV3() + val hdr = DatabaseHeaderKDB() hdr.loadFromFile(filebuf, 0) - if (hdr.signature1 != PwDbHeader.PWM_DBSIG_1 || hdr.signature2 != PwDbHeaderV3.DBSIG_2) { + if (hdr.signature1 != DatabaseHeader.PWM_DBSIG_1 || hdr.signature2 != DatabaseHeaderKDB.DBSIG_2) { throw SignatureDatabaseException() } @@ -101,13 +101,13 @@ class ImporterV3 : Importer() { } progressTaskUpdater?.updateMessage(R.string.retrieving_db_key) - mDatabaseToOpen = PwDatabaseV3() + mDatabaseToOpen = DatabaseKDB() mDatabaseToOpen.retrieveMasterKey(password, keyInputStream) // Select algorithm when { - hdr.flags and PwDbHeaderV3.FLAG_RIJNDAEL != 0 -> mDatabaseToOpen.encryptionAlgorithm = PwEncryptionAlgorithm.AESRijndael - hdr.flags and PwDbHeaderV3.FLAG_TWOFISH != 0 -> mDatabaseToOpen.encryptionAlgorithm = PwEncryptionAlgorithm.Twofish + hdr.flags and DatabaseHeaderKDB.FLAG_RIJNDAEL != 0 -> mDatabaseToOpen.encryptionAlgorithm = EncryptionAlgorithm.AESRijndael + hdr.flags and DatabaseHeaderKDB.FLAG_TWOFISH != 0 -> mDatabaseToOpen.encryptionAlgorithm = EncryptionAlgorithm.Twofish else -> throw InvalidAlgorithmDatabaseException() } @@ -120,9 +120,9 @@ class ImporterV3 : Importer() { // Initialize Rijndael algorithm val cipher: Cipher try { - if (mDatabaseToOpen.encryptionAlgorithm === PwEncryptionAlgorithm.AESRijndael) { + if (mDatabaseToOpen.encryptionAlgorithm === EncryptionAlgorithm.AESRijndael) { cipher = CipherFactory.getInstance("AES/CBC/PKCS5Padding") - } else if (mDatabaseToOpen.encryptionAlgorithm === PwEncryptionAlgorithm.Twofish) { + } else if (mDatabaseToOpen.encryptionAlgorithm === EncryptionAlgorithm.Twofish) { cipher = CipherFactory.getInstance("Twofish/CBC/PKCS7PADDING") } else { throw IOException("Encryption algorithm is not supported") @@ -145,7 +145,7 @@ class ImporterV3 : Importer() { // Decrypt! The first bytes aren't encrypted (that's the header) val encryptedPartSize: Int try { - encryptedPartSize = cipher.doFinal(filebuf, PwDbHeaderV3.BUF_SIZE, fileSize - PwDbHeaderV3.BUF_SIZE, filebuf, PwDbHeaderV3.BUF_SIZE) + encryptedPartSize = cipher.doFinal(filebuf, DatabaseHeaderKDB.BUF_SIZE, fileSize - DatabaseHeaderKDB.BUF_SIZE, filebuf, DatabaseHeaderKDB.BUF_SIZE) } catch (e1: ShortBufferException) { throw IOException("Buffer too short") } catch (e1: IllegalBlockSizeException) { @@ -163,7 +163,7 @@ class ImporterV3 : Importer() { val nos = NullOutputStream() val dos = DigestOutputStream(nos, md) - dos.write(filebuf, PwDbHeaderV3.BUF_SIZE, encryptedPartSize) + dos.write(filebuf, DatabaseHeaderKDB.BUF_SIZE, encryptedPartSize) dos.close() val hash = md.digest() @@ -173,13 +173,13 @@ class ImporterV3 : Importer() { throw InvalidCredentialsDatabaseException() } - // New manual root because V3 contains multiple root groups (here available with getRootGroups()) + // New manual root because KDB contains multiple root groups (here available with getRootGroups()) val newRoot = mDatabaseToOpen.createGroup() newRoot.level = -1 mDatabaseToOpen.rootGroup = newRoot // Import all groups - var pos = PwDbHeaderV3.BUF_SIZE + var pos = DatabaseHeaderKDB.BUF_SIZE var newGrp = mDatabaseToOpen.createGroup() run { var i = 0 @@ -233,7 +233,7 @@ class ImporterV3 : Importer() { return mDatabaseToOpen } - private fun buildTreeGroups(previousGroup: PwGroupV3, currentGroup: PwGroupV3, groupIterator: Iterator) { + private fun buildTreeGroups(previousGroup: GroupKDB, currentGroup: GroupKDB, groupIterator: Iterator) { if (currentGroup.parent == null && (previousGroup.level + 1) == currentGroup.level) { // Current group has an increment level compare to the previous, current group is a child @@ -282,7 +282,7 @@ class ImporterV3 : Importer() { * @throws UnsupportedEncodingException */ @Throws(UnsupportedEncodingException::class) - private fun readGroupField(db: PwDatabaseV3, grp: PwGroupV3, fieldType: Int, buf: ByteArray, offset: Int) { + private fun readGroupField(db: DatabaseKDB, grp: GroupKDB, fieldType: Int, buf: ByteArray, offset: Int) { when (fieldType) { 0x0000 -> { } @@ -299,7 +299,7 @@ class ImporterV3 : Importer() { } @Throws(UnsupportedEncodingException::class) - private fun readEntryField(db: PwDatabaseV3, ent: PwEntryV3, buf: ByteArray, offset: Int) { + private fun readEntryField(db: DatabaseKDB, ent: EntryKDB, buf: ByteArray, offset: Int) { var offsetMutable = offset val fieldType = LEDataInputStream.readUShort(buf, offsetMutable) offsetMutable += 2 @@ -309,11 +309,11 @@ class ImporterV3 : Importer() { when (fieldType) { 0x0000 -> { } - 0x0001 -> ent.nodeId = PwNodeIdUUID(LEDataInputStream.readUuid(buf, offsetMutable)) + 0x0001 -> ent.nodeId = NodeIdUUID(LEDataInputStream.readUuid(buf, offsetMutable)) 0x0002 -> { - val pwGroupV3 = mDatabaseToOpen.createGroup() - pwGroupV3.nodeId = PwNodeIdInt(LEDataInputStream.readInt(buf, offsetMutable)) - ent.parent = pwGroupV3 + val groupKDB = mDatabaseToOpen.createGroup() + groupKDB.nodeId = NodeIdInt(LEDataInputStream.readInt(buf, offsetMutable)) + ent.parent = groupKDB } 0x0003 -> { var iconId = LEDataInputStream.readInt(buf, offsetMutable) @@ -340,6 +340,6 @@ class ImporterV3 : Importer() { } companion object { - private val TAG = ImporterV3::class.java.name + private val TAG = ImporterKDB::class.java.name } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterKDBX.kt similarity index 73% rename from app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterKDBX.kt index 9c39f0940..3a755dc0b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterKDBX.kt @@ -25,12 +25,12 @@ import com.kunzisoft.keepass.crypto.CipherFactory import com.kunzisoft.keepass.crypto.StreamCipherFactory import com.kunzisoft.keepass.crypto.engine.CipherEngine import com.kunzisoft.keepass.database.element.* -import com.kunzisoft.keepass.database.element.PwDatabaseV4.Companion.BASE_64_FLAG +import com.kunzisoft.keepass.database.element.DatabaseKDBX.Companion.BASE_64_FLAG import com.kunzisoft.keepass.database.element.security.BinaryAttachment import com.kunzisoft.keepass.database.element.security.ProtectedString import com.kunzisoft.keepass.database.exception.* -import com.kunzisoft.keepass.database.file.KDBX4DateUtil -import com.kunzisoft.keepass.database.file.PwDbHeaderV4 +import com.kunzisoft.keepass.database.file.DateKDBXUtil +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX import com.kunzisoft.keepass.stream.* import com.kunzisoft.keepass.tasks.ProgressTaskUpdater import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils @@ -47,11 +47,11 @@ import java.util.zip.GZIPOutputStream import javax.crypto.Cipher import kotlin.math.min -class ImporterV4(private val streamDir: File, - private val fixDuplicateUUID: Boolean = false) : Importer() { +class ImporterKDBX(private val streamDir: File, + private val fixDuplicateUUID: Boolean = false) : Importer() { private var randomStream: StreamCipher? = null - private lateinit var mDatabase: PwDatabaseV4 + private lateinit var mDatabase: DatabaseKDBX private var hashOfHeader: ByteArray? = null @@ -59,9 +59,9 @@ class ImporterV4(private val streamDir: File, get() = mDatabase.binaryPool.findUnusedKey().toString() private var readNextNode = true - private val ctxGroups = Stack() - private var ctxGroup: PwGroupV4? = null - private var ctxEntry: PwEntryV4? = null + private val ctxGroups = Stack() + private var ctxGroup: GroupKDBX? = null + private var ctxEntry: EntryKDBX? = null private var ctxStringName: String? = null private var ctxStringValue: ProtectedString? = null private var ctxBinaryName: String? = null @@ -69,9 +69,9 @@ class ImporterV4(private val streamDir: File, private var ctxATName: String? = null private var ctxATSeq: String? = null private var entryInHistory = false - private var ctxHistoryBase: PwEntryV4? = null - private var ctxDeletedObject: PwDeletedObject? = null - private var customIconID = PwDatabase.UUID_ZERO + private var ctxHistoryBase: EntryKDBX? = null + private var ctxDeletedObject: DeletedObject? = null + private var customIconID = DatabaseVersioned.UUID_ZERO private var customIconData: ByteArray? = null private var customDataKey: String? = null private var customDataValue: String? = null @@ -84,17 +84,17 @@ class ImporterV4(private val streamDir: File, override fun openDatabase(databaseInputStream: InputStream, password: String?, keyInputStream: InputStream?, - progressTaskUpdater: ProgressTaskUpdater?): PwDatabaseV4 { + progressTaskUpdater: ProgressTaskUpdater?): DatabaseKDBX { try { // TODO performance progressTaskUpdater?.updateMessage(R.string.retrieving_db_key) - mDatabase = PwDatabaseV4() + mDatabase = DatabaseKDBX() mDatabase.changeDuplicateId = fixDuplicateUUID - val header = PwDbHeaderV4(mDatabase) + val header = DatabaseHeaderKDBX(mDatabase) val headerAndHash = header.loadFromFile(databaseInputStream) mDatabase.kdbxVersion = header.version @@ -119,7 +119,7 @@ class ImporterV4(private val streamDir: File, } val isPlain: InputStream - if (mDatabase.kdbxVersion < PwDbHeaderV4.FILE_VERSION_32_4) { + if (mDatabase.kdbxVersion < DatabaseHeaderKDBX.FILE_VERSION_32_4) { val decrypted = attachCipherStream(databaseInputStream, cipher) val dataDecrypted = LEDataInputStream(decrypted) @@ -146,7 +146,7 @@ class ImporterV4(private val streamDir: File, } val hmacKey = mDatabase.hmacKey ?: throw LoadDatabaseException() - val headerHmac = PwDbHeaderV4.computeHeaderHmac(pbHeader, hmacKey) + val headerHmac = DatabaseHeaderKDBX.computeHeaderHmac(pbHeader, hmacKey) val storedHmac = isData.readBytes(32) if (storedHmac == null || storedHmac.size != 32) { throw InvalidCredentialsDatabaseException() @@ -163,11 +163,11 @@ class ImporterV4(private val streamDir: File, val inputStreamXml: InputStream inputStreamXml = when (mDatabase.compressionAlgorithm) { - PwCompressionAlgorithm.GZip -> GZIPInputStream(isPlain) + CompressionAlgorithm.GZip -> GZIPInputStream(isPlain) else -> isPlain } - if (mDatabase.kdbxVersion >= PwDbHeaderV4.FILE_VERSION_32_4) { + if (mDatabase.kdbxVersion >= DatabaseHeaderKDBX.FILE_VERSION_32_4) { loadInnerHeader(inputStreamXml, header) } @@ -202,7 +202,7 @@ class ImporterV4(private val streamDir: File, } @Throws(IOException::class) - private fun loadInnerHeader(inputStream: InputStream, header: PwDbHeaderV4) { + private fun loadInnerHeader(inputStream: InputStream, header: DatabaseHeaderKDBX) { val lis = LEDataInputStream(inputStream) while (true) { @@ -211,27 +211,27 @@ class ImporterV4(private val streamDir: File, } @Throws(IOException::class) - private fun readInnerHeader(dataInputStream: LEDataInputStream, header: PwDbHeaderV4): Boolean { + private fun readInnerHeader(dataInputStream: LEDataInputStream, header: DatabaseHeaderKDBX): Boolean { val fieldId = dataInputStream.read().toByte() val size = dataInputStream.readInt() if (size < 0) throw IOException("Corrupted file") when (fieldId) { - PwDbHeaderV4.PwDbInnerHeaderV4Fields.EndOfHeader -> { + DatabaseHeaderKDBX.PwDbInnerHeaderV4Fields.EndOfHeader -> { return false } - PwDbHeaderV4.PwDbInnerHeaderV4Fields.InnerRandomStreamID -> { + DatabaseHeaderKDBX.PwDbInnerHeaderV4Fields.InnerRandomStreamID -> { val data = if (size > 0) dataInputStream.readBytes(size) else ByteArray(0) header.setRandomStreamID(data) } - PwDbHeaderV4.PwDbInnerHeaderV4Fields.InnerRandomstreamKey -> { + DatabaseHeaderKDBX.PwDbInnerHeaderV4Fields.InnerRandomstreamKey -> { val data = if (size > 0) dataInputStream.readBytes(size) else ByteArray(0) header.innerRandomStreamKey = data } - PwDbHeaderV4.PwDbInnerHeaderV4Fields.Binary -> { + DatabaseHeaderKDBX.PwDbInnerHeaderV4Fields.Binary -> { val flag = dataInputStream.readBytes(1)[0].toInt() != 0 - val protectedFlag = flag && PwDbHeaderV4.KdbxBinaryFlags.Protected.toInt() != PwDbHeaderV4.KdbxBinaryFlags.None.toInt() + val protectedFlag = flag && DatabaseHeaderKDBX.KdbxBinaryFlags.Protected.toInt() != DatabaseHeaderKDBX.KdbxBinaryFlags.None.toInt() val byteLength = size - 1 // Read in a file val file = File(streamDir, unusedCacheFileName) @@ -316,22 +316,22 @@ class ImporterV4(private val streamDir: File, private fun readXmlElement(ctx: KdbContext, xpp: XmlPullParser): KdbContext { val name = xpp.name when (ctx) { - KdbContext.Null -> if (name.equals(PwDatabaseV4XML.ElemDocNode, ignoreCase = true)) { + KdbContext.Null -> if (name.equals(DatabaseKDBXXML.ElemDocNode, ignoreCase = true)) { return switchContext(ctx, KdbContext.KeePassFile, xpp) } else readUnknown(xpp) - KdbContext.KeePassFile -> if (name.equals(PwDatabaseV4XML.ElemMeta, ignoreCase = true)) { + KdbContext.KeePassFile -> if (name.equals(DatabaseKDBXXML.ElemMeta, ignoreCase = true)) { return switchContext(ctx, KdbContext.Meta, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemRoot, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemRoot, ignoreCase = true)) { return switchContext(ctx, KdbContext.Root, xpp) } else { readUnknown(xpp) } - KdbContext.Meta -> if (name.equals(PwDatabaseV4XML.ElemGenerator, ignoreCase = true)) { + KdbContext.Meta -> if (name.equals(DatabaseKDBXXML.ElemGenerator, ignoreCase = true)) { readString(xpp) // Ignore - } else if (name.equals(PwDatabaseV4XML.ElemHeaderHash, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemHeaderHash, ignoreCase = true)) { val encodedHash = readString(xpp) if (encodedHash.isNotEmpty() && hashOfHeader != null) { val hash = Base64.decode(encodedHash, BASE_64_FLAG) @@ -339,85 +339,85 @@ class ImporterV4(private val streamDir: File, throw LoadDatabaseException() } } - } else if (name.equals(PwDatabaseV4XML.ElemSettingsChanged, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemSettingsChanged, ignoreCase = true)) { mDatabase.settingsChanged = readPwTime(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDbName, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbName, ignoreCase = true)) { mDatabase.name = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDbNameChanged, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbNameChanged, ignoreCase = true)) { mDatabase.nameChanged = readPwTime(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDbDesc, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbDesc, ignoreCase = true)) { mDatabase.description = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDbDescChanged, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbDescChanged, ignoreCase = true)) { mDatabase.descriptionChanged = readPwTime(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDbDefaultUser, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbDefaultUser, ignoreCase = true)) { mDatabase.defaultUserName = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDbDefaultUserChanged, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbDefaultUserChanged, ignoreCase = true)) { mDatabase.defaultUserNameChanged = readPwTime(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDbColor, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbColor, ignoreCase = true)) { mDatabase.color = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDbMntncHistoryDays, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbMntncHistoryDays, ignoreCase = true)) { mDatabase.maintenanceHistoryDays = readUInt(xpp, DEFAULT_HISTORY_DAYS) - } else if (name.equals(PwDatabaseV4XML.ElemDbKeyChanged, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbKeyChanged, ignoreCase = true)) { mDatabase.keyLastChanged = readPwTime(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDbKeyChangeRec, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbKeyChangeRec, ignoreCase = true)) { mDatabase.keyChangeRecDays = readLong(xpp, -1) - } else if (name.equals(PwDatabaseV4XML.ElemDbKeyChangeForce, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbKeyChangeForce, ignoreCase = true)) { mDatabase.keyChangeForceDays = readLong(xpp, -1) - } else if (name.equals(PwDatabaseV4XML.ElemDbKeyChangeForceOnce, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDbKeyChangeForceOnce, ignoreCase = true)) { mDatabase.isKeyChangeForceOnce = readBool(xpp, false) - } else if (name.equals(PwDatabaseV4XML.ElemMemoryProt, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemMemoryProt, ignoreCase = true)) { return switchContext(ctx, KdbContext.MemoryProtection, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemCustomIcons, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemCustomIcons, ignoreCase = true)) { return switchContext(ctx, KdbContext.CustomIcons, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemRecycleBinEnabled, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemRecycleBinEnabled, ignoreCase = true)) { mDatabase.isRecycleBinEnabled = readBool(xpp, true) - } else if (name.equals(PwDatabaseV4XML.ElemRecycleBinUuid, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemRecycleBinUuid, ignoreCase = true)) { mDatabase.recycleBinUUID = readUuid(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemRecycleBinChanged, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemRecycleBinChanged, ignoreCase = true)) { mDatabase.recycleBinChanged = readTime(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemEntryTemplatesGroup, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemEntryTemplatesGroup, ignoreCase = true)) { mDatabase.entryTemplatesGroup = readUuid(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemEntryTemplatesGroupChanged, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemEntryTemplatesGroupChanged, ignoreCase = true)) { mDatabase.entryTemplatesGroupChanged = readPwTime(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemHistoryMaxItems, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemHistoryMaxItems, ignoreCase = true)) { mDatabase.historyMaxItems = readInt(xpp, -1) - } else if (name.equals(PwDatabaseV4XML.ElemHistoryMaxSize, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemHistoryMaxSize, ignoreCase = true)) { mDatabase.historyMaxSize = readLong(xpp, -1) - } else if (name.equals(PwDatabaseV4XML.ElemLastSelectedGroup, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemLastSelectedGroup, ignoreCase = true)) { mDatabase.lastSelectedGroupUUID = readUuid(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemLastTopVisibleGroup, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemLastTopVisibleGroup, ignoreCase = true)) { mDatabase.lastTopVisibleGroupUUID = readUuid(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemBinaries, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemBinaries, ignoreCase = true)) { return switchContext(ctx, KdbContext.Binaries, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemCustomData, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemCustomData, ignoreCase = true)) { return switchContext(ctx, KdbContext.CustomData, xpp) } - KdbContext.MemoryProtection -> if (name.equals(PwDatabaseV4XML.ElemProtTitle, ignoreCase = true)) { + KdbContext.MemoryProtection -> if (name.equals(DatabaseKDBXXML.ElemProtTitle, ignoreCase = true)) { mDatabase.memoryProtection.protectTitle = readBool(xpp, false) - } else if (name.equals(PwDatabaseV4XML.ElemProtUserName, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemProtUserName, ignoreCase = true)) { mDatabase.memoryProtection.protectUserName = readBool(xpp, false) - } else if (name.equals(PwDatabaseV4XML.ElemProtPassword, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemProtPassword, ignoreCase = true)) { mDatabase.memoryProtection.protectPassword = readBool(xpp, false) - } else if (name.equals(PwDatabaseV4XML.ElemProtURL, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemProtURL, ignoreCase = true)) { mDatabase.memoryProtection.protectUrl = readBool(xpp, false) - } else if (name.equals(PwDatabaseV4XML.ElemProtNotes, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemProtNotes, ignoreCase = true)) { mDatabase.memoryProtection.protectNotes = readBool(xpp, false) - } else if (name.equals(PwDatabaseV4XML.ElemProtAutoHide, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemProtAutoHide, ignoreCase = true)) { mDatabase.memoryProtection.autoEnableVisualHiding = readBool(xpp, false) } else { readUnknown(xpp) } - KdbContext.CustomIcons -> if (name.equals(PwDatabaseV4XML.ElemCustomIconItem, ignoreCase = true)) { + KdbContext.CustomIcons -> if (name.equals(DatabaseKDBXXML.ElemCustomIconItem, ignoreCase = true)) { return switchContext(ctx, KdbContext.CustomIcon, xpp) } else { readUnknown(xpp) } - KdbContext.CustomIcon -> if (name.equals(PwDatabaseV4XML.ElemCustomIconItemID, ignoreCase = true)) { + KdbContext.CustomIcon -> if (name.equals(DatabaseKDBXXML.ElemCustomIconItemID, ignoreCase = true)) { customIconID = readUuid(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemCustomIconItemData, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemCustomIconItemData, ignoreCase = true)) { val strData = readString(xpp) if (strData.isNotEmpty()) { customIconData = Base64.decode(strData, BASE_64_FLAG) @@ -428,8 +428,8 @@ class ImporterV4(private val streamDir: File, readUnknown(xpp) } - KdbContext.Binaries -> if (name.equals(PwDatabaseV4XML.ElemBinary, ignoreCase = true)) { - val key = xpp.getAttributeValue(null, PwDatabaseV4XML.AttrId) + KdbContext.Binaries -> if (name.equals(DatabaseKDBXXML.ElemBinary, ignoreCase = true)) { + val key = xpp.getAttributeValue(null, DatabaseKDBXXML.AttrId) if (key != null) { val pbData = readBinary(xpp) val id = Integer.parseInt(key) @@ -441,21 +441,21 @@ class ImporterV4(private val streamDir: File, readUnknown(xpp) } - KdbContext.CustomData -> if (name.equals(PwDatabaseV4XML.ElemStringDictExItem, ignoreCase = true)) { + KdbContext.CustomData -> if (name.equals(DatabaseKDBXXML.ElemStringDictExItem, ignoreCase = true)) { return switchContext(ctx, KdbContext.CustomDataItem, xpp) } else { readUnknown(xpp) } - KdbContext.CustomDataItem -> if (name.equals(PwDatabaseV4XML.ElemKey, ignoreCase = true)) { + KdbContext.CustomDataItem -> if (name.equals(DatabaseKDBXXML.ElemKey, ignoreCase = true)) { customDataKey = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemValue, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemValue, ignoreCase = true)) { customDataValue = readString(xpp) } else { readUnknown(xpp) } - KdbContext.Root -> if (name.equals(PwDatabaseV4XML.ElemGroup, ignoreCase = true)) { + KdbContext.Root -> if (name.equals(DatabaseKDBXXML.ElemGroup, ignoreCase = true)) { if (ctxGroups.size != 0) throw IOException("Group list should be empty.") @@ -464,38 +464,38 @@ class ImporterV4(private val streamDir: File, ctxGroup = ctxGroups.peek() return switchContext(ctx, KdbContext.Group, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDeletedObjects, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDeletedObjects, ignoreCase = true)) { return switchContext(ctx, KdbContext.RootDeletedObjects, xpp) } else { readUnknown(xpp) } - KdbContext.Group -> if (name.equals(PwDatabaseV4XML.ElemUuid, ignoreCase = true)) { - ctxGroup?.nodeId = PwNodeIdUUID(readUuid(xpp)) + KdbContext.Group -> if (name.equals(DatabaseKDBXXML.ElemUuid, ignoreCase = true)) { + ctxGroup?.nodeId = NodeIdUUID(readUuid(xpp)) ctxGroup?.let { mDatabase.addGroupIndex(it) } - } else if (name.equals(PwDatabaseV4XML.ElemName, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemName, ignoreCase = true)) { ctxGroup?.title = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemNotes, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemNotes, ignoreCase = true)) { ctxGroup?.notes = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemIcon, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemIcon, ignoreCase = true)) { ctxGroup?.icon = mDatabase.iconFactory.getIcon(readUInt(xpp, 0).toInt()) - } else if (name.equals(PwDatabaseV4XML.ElemCustomIconID, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemCustomIconID, ignoreCase = true)) { ctxGroup?.iconCustom = mDatabase.iconFactory.getIcon(readUuid(xpp)) - } else if (name.equals(PwDatabaseV4XML.ElemTimes, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemTimes, ignoreCase = true)) { return switchContext(ctx, KdbContext.GroupTimes, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemIsExpanded, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemIsExpanded, ignoreCase = true)) { ctxGroup?.isExpanded = readBool(xpp, true) - } else if (name.equals(PwDatabaseV4XML.ElemGroupDefaultAutoTypeSeq, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemGroupDefaultAutoTypeSeq, ignoreCase = true)) { ctxGroup?.defaultAutoTypeSequence = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemEnableAutoType, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemEnableAutoType, ignoreCase = true)) { ctxGroup?.enableAutoType = readOptionalBool(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemEnableSearching, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemEnableSearching, ignoreCase = true)) { ctxGroup?.enableSearching = readOptionalBool(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemLastTopVisibleEntry, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemLastTopVisibleEntry, ignoreCase = true)) { ctxGroup?.lastTopVisibleEntry = readUuid(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemCustomData, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemCustomData, ignoreCase = true)) { return switchContext(ctx, KdbContext.GroupCustomData, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemGroup, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemGroup, ignoreCase = true)) { ctxGroup = mDatabase.createGroup() val groupPeek = ctxGroups.peek() ctxGroup?.let { @@ -505,7 +505,7 @@ class ImporterV4(private val streamDir: File, } return switchContext(ctx, KdbContext.Group, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemEntry, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemEntry, ignoreCase = true)) { ctxEntry = mDatabase.createEntry() ctxEntry?.let { ctxGroup?.addChildEntry(it) @@ -517,43 +517,43 @@ class ImporterV4(private val streamDir: File, } else { readUnknown(xpp) } - KdbContext.GroupCustomData -> if (name.equals(PwDatabaseV4XML.ElemStringDictExItem, ignoreCase = true)) { + KdbContext.GroupCustomData -> if (name.equals(DatabaseKDBXXML.ElemStringDictExItem, ignoreCase = true)) { return switchContext(ctx, KdbContext.GroupCustomDataItem, xpp) } else { readUnknown(xpp) } KdbContext.GroupCustomDataItem -> when { - name.equals(PwDatabaseV4XML.ElemKey, ignoreCase = true) -> groupCustomDataKey = readString(xpp) - name.equals(PwDatabaseV4XML.ElemValue, ignoreCase = true) -> groupCustomDataValue = readString(xpp) + name.equals(DatabaseKDBXXML.ElemKey, ignoreCase = true) -> groupCustomDataKey = readString(xpp) + name.equals(DatabaseKDBXXML.ElemValue, ignoreCase = true) -> groupCustomDataValue = readString(xpp) else -> readUnknown(xpp) } - KdbContext.Entry -> if (name.equals(PwDatabaseV4XML.ElemUuid, ignoreCase = true)) { - ctxEntry?.nodeId = PwNodeIdUUID(readUuid(xpp)) - } else if (name.equals(PwDatabaseV4XML.ElemIcon, ignoreCase = true)) { + KdbContext.Entry -> if (name.equals(DatabaseKDBXXML.ElemUuid, ignoreCase = true)) { + ctxEntry?.nodeId = NodeIdUUID(readUuid(xpp)) + } else if (name.equals(DatabaseKDBXXML.ElemIcon, ignoreCase = true)) { ctxEntry?.icon = mDatabase.iconFactory.getIcon(readUInt(xpp, 0).toInt()) - } else if (name.equals(PwDatabaseV4XML.ElemCustomIconID, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemCustomIconID, ignoreCase = true)) { ctxEntry?.iconCustom = mDatabase.iconFactory.getIcon(readUuid(xpp)) - } else if (name.equals(PwDatabaseV4XML.ElemFgColor, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemFgColor, ignoreCase = true)) { ctxEntry?.foregroundColor = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemBgColor, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemBgColor, ignoreCase = true)) { ctxEntry?.backgroundColor = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemOverrideUrl, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemOverrideUrl, ignoreCase = true)) { ctxEntry?.overrideURL = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemTags, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemTags, ignoreCase = true)) { ctxEntry?.tags = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemTimes, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemTimes, ignoreCase = true)) { return switchContext(ctx, KdbContext.EntryTimes, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemString, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemString, ignoreCase = true)) { return switchContext(ctx, KdbContext.EntryString, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemBinary, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemBinary, ignoreCase = true)) { return switchContext(ctx, KdbContext.EntryBinary, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemAutoType, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemAutoType, ignoreCase = true)) { return switchContext(ctx, KdbContext.EntryAutoType, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemCustomData, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemCustomData, ignoreCase = true)) { return switchContext(ctx, KdbContext.EntryCustomData, xpp) - } else if (name.equals(PwDatabaseV4XML.ElemHistory, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemHistory, ignoreCase = true)) { if (!entryInHistory) { ctxHistoryBase = ctxEntry return switchContext(ctx, KdbContext.EntryHistory, xpp) @@ -563,19 +563,19 @@ class ImporterV4(private val streamDir: File, } else { readUnknown(xpp) } - KdbContext.EntryCustomData -> if (name.equals(PwDatabaseV4XML.ElemStringDictExItem, ignoreCase = true)) { + KdbContext.EntryCustomData -> if (name.equals(DatabaseKDBXXML.ElemStringDictExItem, ignoreCase = true)) { return switchContext(ctx, KdbContext.EntryCustomDataItem, xpp) } else { readUnknown(xpp) } KdbContext.EntryCustomDataItem -> when { - name.equals(PwDatabaseV4XML.ElemKey, ignoreCase = true) -> entryCustomDataKey = readString(xpp) - name.equals(PwDatabaseV4XML.ElemValue, ignoreCase = true) -> entryCustomDataValue = readString(xpp) + name.equals(DatabaseKDBXXML.ElemKey, ignoreCase = true) -> entryCustomDataKey = readString(xpp) + name.equals(DatabaseKDBXXML.ElemValue, ignoreCase = true) -> entryCustomDataValue = readString(xpp) else -> readUnknown(xpp) } KdbContext.GroupTimes, KdbContext.EntryTimes -> { - val tl: PwNodeV4Interface? = + val tl: NodeKDBXInterface? = if (ctx == KdbContext.GroupTimes) { ctxGroup } else { @@ -583,53 +583,53 @@ class ImporterV4(private val streamDir: File, } when { - name.equals(PwDatabaseV4XML.ElemLastModTime, ignoreCase = true) -> tl?.lastModificationTime = readPwTime(xpp) - name.equals(PwDatabaseV4XML.ElemCreationTime, ignoreCase = true) -> tl?.creationTime = readPwTime(xpp) - name.equals(PwDatabaseV4XML.ElemLastAccessTime, ignoreCase = true) -> tl?.lastAccessTime = readPwTime(xpp) - name.equals(PwDatabaseV4XML.ElemExpiryTime, ignoreCase = true) -> tl?.expiryTime = readPwTime(xpp) - name.equals(PwDatabaseV4XML.ElemExpires, ignoreCase = true) -> tl?.expires = readBool(xpp, false) - name.equals(PwDatabaseV4XML.ElemUsageCount, ignoreCase = true) -> tl?.usageCount = readULong(xpp, 0) - name.equals(PwDatabaseV4XML.ElemLocationChanged, ignoreCase = true) -> tl?.locationChanged = readPwTime(xpp) + name.equals(DatabaseKDBXXML.ElemLastModTime, ignoreCase = true) -> tl?.lastModificationTime = readPwTime(xpp) + name.equals(DatabaseKDBXXML.ElemCreationTime, ignoreCase = true) -> tl?.creationTime = readPwTime(xpp) + name.equals(DatabaseKDBXXML.ElemLastAccessTime, ignoreCase = true) -> tl?.lastAccessTime = readPwTime(xpp) + name.equals(DatabaseKDBXXML.ElemExpiryTime, ignoreCase = true) -> tl?.expiryTime = readPwTime(xpp) + name.equals(DatabaseKDBXXML.ElemExpires, ignoreCase = true) -> tl?.expires = readBool(xpp, false) + name.equals(DatabaseKDBXXML.ElemUsageCount, ignoreCase = true) -> tl?.usageCount = readULong(xpp, 0) + name.equals(DatabaseKDBXXML.ElemLocationChanged, ignoreCase = true) -> tl?.locationChanged = readPwTime(xpp) else -> readUnknown(xpp) } } - KdbContext.EntryString -> if (name.equals(PwDatabaseV4XML.ElemKey, ignoreCase = true)) { + KdbContext.EntryString -> if (name.equals(DatabaseKDBXXML.ElemKey, ignoreCase = true)) { ctxStringName = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemValue, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemValue, ignoreCase = true)) { ctxStringValue = readProtectedString(xpp) } else { readUnknown(xpp) } - KdbContext.EntryBinary -> if (name.equals(PwDatabaseV4XML.ElemKey, ignoreCase = true)) { + KdbContext.EntryBinary -> if (name.equals(DatabaseKDBXXML.ElemKey, ignoreCase = true)) { ctxBinaryName = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemValue, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemValue, ignoreCase = true)) { ctxBinaryValue = readBinary(xpp) } - KdbContext.EntryAutoType -> if (name.equals(PwDatabaseV4XML.ElemAutoTypeEnabled, ignoreCase = true)) { + KdbContext.EntryAutoType -> if (name.equals(DatabaseKDBXXML.ElemAutoTypeEnabled, ignoreCase = true)) { ctxEntry?.autoType?.enabled = readBool(xpp, true) - } else if (name.equals(PwDatabaseV4XML.ElemAutoTypeObfuscation, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemAutoTypeObfuscation, ignoreCase = true)) { ctxEntry?.autoType?.obfuscationOptions = readUInt(xpp, 0) - } else if (name.equals(PwDatabaseV4XML.ElemAutoTypeDefaultSeq, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemAutoTypeDefaultSeq, ignoreCase = true)) { ctxEntry?.autoType?.defaultSequence = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemAutoTypeItem, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemAutoTypeItem, ignoreCase = true)) { return switchContext(ctx, KdbContext.EntryAutoTypeItem, xpp) } else { readUnknown(xpp) } - KdbContext.EntryAutoTypeItem -> if (name.equals(PwDatabaseV4XML.ElemWindow, ignoreCase = true)) { + KdbContext.EntryAutoTypeItem -> if (name.equals(DatabaseKDBXXML.ElemWindow, ignoreCase = true)) { ctxATName = readString(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemKeystrokeSequence, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemKeystrokeSequence, ignoreCase = true)) { ctxATSeq = readString(xpp) } else { readUnknown(xpp) } - KdbContext.EntryHistory -> if (name.equals(PwDatabaseV4XML.ElemEntry, ignoreCase = true)) { - ctxEntry = PwEntryV4() + KdbContext.EntryHistory -> if (name.equals(DatabaseKDBXXML.ElemEntry, ignoreCase = true)) { + ctxEntry = EntryKDBX() ctxEntry?.let { ctxHistoryBase?.addEntryToHistory(it) } entryInHistory = true @@ -638,8 +638,8 @@ class ImporterV4(private val streamDir: File, readUnknown(xpp) } - KdbContext.RootDeletedObjects -> if (name.equals(PwDatabaseV4XML.ElemDeletedObject, ignoreCase = true)) { - ctxDeletedObject = PwDeletedObject() + KdbContext.RootDeletedObjects -> if (name.equals(DatabaseKDBXXML.ElemDeletedObject, ignoreCase = true)) { + ctxDeletedObject = DeletedObject() ctxDeletedObject?.let { mDatabase.addDeletedObject(it) } return switchContext(ctx, KdbContext.DeletedObject, xpp) @@ -647,9 +647,9 @@ class ImporterV4(private val streamDir: File, readUnknown(xpp) } - KdbContext.DeletedObject -> if (name.equals(PwDatabaseV4XML.ElemUuid, ignoreCase = true)) { + KdbContext.DeletedObject -> if (name.equals(DatabaseKDBXXML.ElemUuid, ignoreCase = true)) { ctxDeletedObject?.uuid = readUuid(xpp) - } else if (name.equals(PwDatabaseV4XML.ElemDeletionTime, ignoreCase = true)) { + } else if (name.equals(DatabaseKDBXXML.ElemDeletionTime, ignoreCase = true)) { ctxDeletedObject?.deletionTime = readTime(xpp) } else { readUnknown(xpp) @@ -664,32 +664,32 @@ class ImporterV4(private val streamDir: File, // (xpp.getEventType() == XmlPullParser.END_TAG); val name = xpp.name - if (ctx == KdbContext.KeePassFile && name.equals(PwDatabaseV4XML.ElemDocNode, ignoreCase = true)) { + if (ctx == KdbContext.KeePassFile && name.equals(DatabaseKDBXXML.ElemDocNode, ignoreCase = true)) { return KdbContext.Null - } else if (ctx == KdbContext.Meta && name.equals(PwDatabaseV4XML.ElemMeta, ignoreCase = true)) { + } else if (ctx == KdbContext.Meta && name.equals(DatabaseKDBXXML.ElemMeta, ignoreCase = true)) { return KdbContext.KeePassFile - } else if (ctx == KdbContext.Root && name.equals(PwDatabaseV4XML.ElemRoot, ignoreCase = true)) { + } else if (ctx == KdbContext.Root && name.equals(DatabaseKDBXXML.ElemRoot, ignoreCase = true)) { return KdbContext.KeePassFile - } else if (ctx == KdbContext.MemoryProtection && name.equals(PwDatabaseV4XML.ElemMemoryProt, ignoreCase = true)) { + } else if (ctx == KdbContext.MemoryProtection && name.equals(DatabaseKDBXXML.ElemMemoryProt, ignoreCase = true)) { return KdbContext.Meta - } else if (ctx == KdbContext.CustomIcons && name.equals(PwDatabaseV4XML.ElemCustomIcons, ignoreCase = true)) { + } else if (ctx == KdbContext.CustomIcons && name.equals(DatabaseKDBXXML.ElemCustomIcons, ignoreCase = true)) { return KdbContext.Meta - } else if (ctx == KdbContext.CustomIcon && name.equals(PwDatabaseV4XML.ElemCustomIconItem, ignoreCase = true)) { - if (customIconID != PwDatabase.UUID_ZERO && customIconData != null) { - val icon = PwIconCustom(customIconID, customIconData!!) + } else if (ctx == KdbContext.CustomIcon && name.equals(DatabaseKDBXXML.ElemCustomIconItem, ignoreCase = true)) { + if (customIconID != DatabaseVersioned.UUID_ZERO && customIconData != null) { + val icon = IconImageCustom(customIconID, customIconData!!) mDatabase.addCustomIcon(icon) mDatabase.iconFactory.put(icon) } - customIconID = PwDatabase.UUID_ZERO + customIconID = DatabaseVersioned.UUID_ZERO customIconData = null return KdbContext.CustomIcons - } else if (ctx == KdbContext.Binaries && name.equals(PwDatabaseV4XML.ElemBinaries, ignoreCase = true)) { + } else if (ctx == KdbContext.Binaries && name.equals(DatabaseKDBXXML.ElemBinaries, ignoreCase = true)) { return KdbContext.Meta - } else if (ctx == KdbContext.CustomData && name.equals(PwDatabaseV4XML.ElemCustomData, ignoreCase = true)) { + } else if (ctx == KdbContext.CustomData && name.equals(DatabaseKDBXXML.ElemCustomData, ignoreCase = true)) { return KdbContext.Meta - } else if (ctx == KdbContext.CustomDataItem && name.equals(PwDatabaseV4XML.ElemStringDictExItem, ignoreCase = true)) { + } else if (ctx == KdbContext.CustomDataItem && name.equals(DatabaseKDBXXML.ElemStringDictExItem, ignoreCase = true)) { if (customDataKey != null && customDataValue != null) { mDatabase.putCustomData(customDataKey!!, customDataValue!!) } @@ -698,8 +698,8 @@ class ImporterV4(private val streamDir: File, customDataValue = null return KdbContext.CustomData - } else if (ctx == KdbContext.Group && name.equals(PwDatabaseV4XML.ElemGroup, ignoreCase = true)) { - if (ctxGroup != null && ctxGroup?.id == PwDatabase.UUID_ZERO) { + } else if (ctx == KdbContext.Group && name.equals(DatabaseKDBXXML.ElemGroup, ignoreCase = true)) { + if (ctxGroup != null && ctxGroup?.id == DatabaseVersioned.UUID_ZERO) { ctxGroup?.nodeId = mDatabase.newGroupId() mDatabase.addGroupIndex(ctxGroup!!) } @@ -713,11 +713,11 @@ class ImporterV4(private val streamDir: File, ctxGroup = ctxGroups.peek() return KdbContext.Group } - } else if (ctx == KdbContext.GroupTimes && name.equals(PwDatabaseV4XML.ElemTimes, ignoreCase = true)) { + } else if (ctx == KdbContext.GroupTimes && name.equals(DatabaseKDBXXML.ElemTimes, ignoreCase = true)) { return KdbContext.Group - } else if (ctx == KdbContext.GroupCustomData && name.equals(PwDatabaseV4XML.ElemCustomData, ignoreCase = true)) { + } else if (ctx == KdbContext.GroupCustomData && name.equals(DatabaseKDBXXML.ElemCustomData, ignoreCase = true)) { return KdbContext.Group - } else if (ctx == KdbContext.GroupCustomDataItem && name.equals(PwDatabaseV4XML.ElemStringDictExItem, ignoreCase = true)) { + } else if (ctx == KdbContext.GroupCustomDataItem && name.equals(DatabaseKDBXXML.ElemStringDictExItem, ignoreCase = true)) { if (groupCustomDataKey != null && groupCustomDataValue != null) { ctxGroup?.putCustomData(groupCustomDataKey!!, groupCustomDataValue!!) } @@ -727,9 +727,9 @@ class ImporterV4(private val streamDir: File, return KdbContext.GroupCustomData - } else if (ctx == KdbContext.Entry && name.equals(PwDatabaseV4XML.ElemEntry, ignoreCase = true)) { + } else if (ctx == KdbContext.Entry && name.equals(DatabaseKDBXXML.ElemEntry, ignoreCase = true)) { - if (ctxEntry?.id == PwDatabase.UUID_ZERO) + if (ctxEntry?.id == DatabaseVersioned.UUID_ZERO) ctxEntry?.nodeId = mDatabase.newEntryId() if (entryInHistory) { @@ -742,34 +742,34 @@ class ImporterV4(private val streamDir: File, } return KdbContext.Group - } else if (ctx == KdbContext.EntryTimes && name.equals(PwDatabaseV4XML.ElemTimes, ignoreCase = true)) { + } else if (ctx == KdbContext.EntryTimes && name.equals(DatabaseKDBXXML.ElemTimes, ignoreCase = true)) { return KdbContext.Entry - } else if (ctx == KdbContext.EntryString && name.equals(PwDatabaseV4XML.ElemString, ignoreCase = true)) { + } else if (ctx == KdbContext.EntryString && name.equals(DatabaseKDBXXML.ElemString, ignoreCase = true)) { if (ctxStringName != null && ctxStringValue != null) ctxEntry?.putExtraField(ctxStringName!!, ctxStringValue!!) ctxStringName = null ctxStringValue = null return KdbContext.Entry - } else if (ctx == KdbContext.EntryBinary && name.equals(PwDatabaseV4XML.ElemBinary, ignoreCase = true)) { + } else if (ctx == KdbContext.EntryBinary && name.equals(DatabaseKDBXXML.ElemBinary, ignoreCase = true)) { if (ctxBinaryName != null && ctxBinaryValue != null) ctxEntry?.putProtectedBinary(ctxBinaryName!!, ctxBinaryValue!!) ctxBinaryName = null ctxBinaryValue = null return KdbContext.Entry - } else if (ctx == KdbContext.EntryAutoType && name.equals(PwDatabaseV4XML.ElemAutoType, ignoreCase = true)) { + } else if (ctx == KdbContext.EntryAutoType && name.equals(DatabaseKDBXXML.ElemAutoType, ignoreCase = true)) { return KdbContext.Entry - } else if (ctx == KdbContext.EntryAutoTypeItem && name.equals(PwDatabaseV4XML.ElemAutoTypeItem, ignoreCase = true)) { + } else if (ctx == KdbContext.EntryAutoTypeItem && name.equals(DatabaseKDBXXML.ElemAutoTypeItem, ignoreCase = true)) { if (ctxATName != null && ctxATSeq != null) ctxEntry?.autoType?.put(ctxATName!!, ctxATSeq!!) ctxATName = null ctxATSeq = null return KdbContext.EntryAutoType - } else if (ctx == KdbContext.EntryCustomData && name.equals(PwDatabaseV4XML.ElemCustomData, ignoreCase = true)) { + } else if (ctx == KdbContext.EntryCustomData && name.equals(DatabaseKDBXXML.ElemCustomData, ignoreCase = true)) { return KdbContext.Entry - } else if (ctx == KdbContext.EntryCustomDataItem && name.equals(PwDatabaseV4XML.ElemStringDictExItem, ignoreCase = true)) { + } else if (ctx == KdbContext.EntryCustomDataItem && name.equals(DatabaseKDBXXML.ElemStringDictExItem, ignoreCase = true)) { if (entryCustomDataKey != null && entryCustomDataValue != null) { ctxEntry?.putCustomData(entryCustomDataKey!!, entryCustomDataValue!!) } @@ -778,12 +778,12 @@ class ImporterV4(private val streamDir: File, entryCustomDataValue = null return KdbContext.EntryCustomData - } else if (ctx == KdbContext.EntryHistory && name.equals(PwDatabaseV4XML.ElemHistory, ignoreCase = true)) { + } else if (ctx == KdbContext.EntryHistory && name.equals(DatabaseKDBXXML.ElemHistory, ignoreCase = true)) { entryInHistory = false return KdbContext.Entry - } else if (ctx == KdbContext.RootDeletedObjects && name.equals(PwDatabaseV4XML.ElemDeletedObjects, ignoreCase = true)) { + } else if (ctx == KdbContext.RootDeletedObjects && name.equals(DatabaseKDBXXML.ElemDeletedObjects, ignoreCase = true)) { return KdbContext.Root - } else if (ctx == KdbContext.DeletedObject && name.equals(PwDatabaseV4XML.ElemDeletedObject, ignoreCase = true)) { + } else if (ctx == KdbContext.DeletedObject && name.equals(DatabaseKDBXXML.ElemDeletedObject, ignoreCase = true)) { ctxDeletedObject = null return KdbContext.RootDeletedObjects } else { @@ -796,8 +796,8 @@ class ImporterV4(private val streamDir: File, } @Throws(IOException::class, XmlPullParserException::class) - private fun readPwTime(xpp: XmlPullParser): PwDate { - return PwDate(readTime(xpp)) + private fun readPwTime(xpp: XmlPullParser): DateInstant { + return DateInstant(readTime(xpp)) } @Throws(IOException::class, XmlPullParserException::class) @@ -805,7 +805,7 @@ class ImporterV4(private val streamDir: File, val sDate = readString(xpp) var utcDate: Date? = null - if (mDatabase.kdbxVersion >= PwDbHeaderV4.FILE_VERSION_32_4) { + if (mDatabase.kdbxVersion >= DatabaseHeaderKDBX.FILE_VERSION_32_4) { var buf = Base64.decode(sDate, BASE_64_FLAG) if (buf.size != 8) { val buf8 = ByteArray(8) @@ -814,12 +814,12 @@ class ImporterV4(private val streamDir: File, } val seconds = LEDataInputStream.readLong(buf, 0) - utcDate = KDBX4DateUtil.convertKDBX4Time(seconds) + utcDate = DateKDBXUtil.convertKDBX4Time(seconds) } else { try { - utcDate = PwDatabaseV4XML.dateFormatter.get()?.parse(sDate) + utcDate = DatabaseKDBXXML.dateFormatter.get()?.parse(sDate) } catch (e: ParseException) { // Catch with null test below } @@ -846,8 +846,8 @@ class ImporterV4(private val streamDir: File, val str = readString(xpp) return when { - str.equals(PwDatabaseV4XML.ValTrue, ignoreCase = true) -> true - str.equals(PwDatabaseV4XML.ValFalse, ignoreCase = true) -> false + str.equals(DatabaseKDBXXML.ValTrue, ignoreCase = true) -> true + str.equals(DatabaseKDBXXML.ValFalse, ignoreCase = true) -> false else -> bDefault } } @@ -857,9 +857,9 @@ class ImporterV4(private val streamDir: File, val str = readString(xpp) return when { - str.equals(PwDatabaseV4XML.ValTrue, ignoreCase = true) -> true - str.equals(PwDatabaseV4XML.ValFalse, ignoreCase = true) -> false - str.equals(PwDatabaseV4XML.ValNull, ignoreCase = true) -> null + str.equals(DatabaseKDBXXML.ValTrue, ignoreCase = true) -> true + str.equals(DatabaseKDBXXML.ValFalse, ignoreCase = true) -> false + str.equals(DatabaseKDBXXML.ValNull, ignoreCase = true) -> null else -> bDefault } } @@ -869,7 +869,7 @@ class ImporterV4(private val streamDir: File, val encoded = readString(xpp) if (encoded.isEmpty()) { - return PwDatabase.UUID_ZERO + return DatabaseVersioned.UUID_ZERO } val buf = Base64.decode(encoded, BASE_64_FLAG) @@ -941,7 +941,7 @@ class ImporterV4(private val streamDir: File, private fun readBinary(xpp: XmlPullParser): BinaryAttachment? { // Reference Id to a binary already present in binary pool - val ref = xpp.getAttributeValue(null, PwDatabaseV4XML.AttrRef) + val ref = xpp.getAttributeValue(null, DatabaseKDBXXML.AttrRef) if (ref != null) { xpp.next() // Consume end tag @@ -955,14 +955,14 @@ class ImporterV4(private val streamDir: File, var protected = false if (xpp.attributeCount > 0) { - val compress = xpp.getAttributeValue(null, PwDatabaseV4XML.AttrCompressed) + val compress = xpp.getAttributeValue(null, DatabaseKDBXXML.AttrCompressed) if (compress != null) { - compressed = compress.equals(PwDatabaseV4XML.ValTrue, ignoreCase = true) + compressed = compress.equals(DatabaseKDBXXML.ValTrue, ignoreCase = true) } - val protect = xpp.getAttributeValue(null, PwDatabaseV4XML.AttrProtected) + val protect = xpp.getAttributeValue(null, DatabaseKDBXXML.AttrProtected) if (protect != null) { - protected = protect.equals(PwDatabaseV4XML.ValTrue, ignoreCase = true) + protected = protect.equals(DatabaseKDBXXML.ValTrue, ignoreCase = true) } } @@ -974,7 +974,7 @@ class ImporterV4(private val streamDir: File, val file = File(streamDir, unusedCacheFileName) return FileOutputStream(file).use { outputStream -> // Force compression in this specific case - if (mDatabase.compressionAlgorithm == PwCompressionAlgorithm.GZip + if (mDatabase.compressionAlgorithm == CompressionAlgorithm.GZip && compressed == false) { GZIPOutputStream(outputStream).write(data) BinaryAttachment(file, protected, true) @@ -1018,8 +1018,8 @@ class ImporterV4(private val streamDir: File, //(xpp.getEventType() == XmlPullParser.START_TAG); if (xpp.attributeCount > 0) { - val protect = xpp.getAttributeValue(null, PwDatabaseV4XML.AttrProtected) - if (protect != null && protect.equals(PwDatabaseV4XML.ValTrue, ignoreCase = true)) { + val protect = xpp.getAttributeValue(null, DatabaseKDBXXML.AttrProtected) + if (protect != null && protect.equals(DatabaseKDBXXML.ValTrue, ignoreCase = true)) { return readBase64String(xpp) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutput.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseHeaderOutput.kt similarity index 96% rename from app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutput.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseHeaderOutput.kt index c60316549..932b09a6e 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutput.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseHeaderOutput.kt @@ -19,7 +19,7 @@ */ package com.kunzisoft.keepass.database.file.save -open class PwDbHeaderOutput { +open class DatabaseHeaderOutput { var hashOfHeader: ByteArray? = null protected set } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseHeaderOutputKDB.kt similarity index 92% rename from app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseHeaderOutputKDB.kt index ee38fc881..e4fa3ee11 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseHeaderOutputKDB.kt @@ -19,13 +19,13 @@ */ package com.kunzisoft.keepass.database.file.save -import com.kunzisoft.keepass.database.file.PwDbHeaderV3 +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDB import com.kunzisoft.keepass.stream.LEDataOutputStream import java.io.IOException import java.io.OutputStream -class PwDbHeaderOutputV3(private val mHeader: PwDbHeaderV3, private val mOS: OutputStream) { +class DatabaseHeaderOutputKDB(private val mHeader: DatabaseHeaderKDB, private val mOS: OutputStream) { @Throws(IOException::class) fun outputStart() { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseHeaderOutputKDBX.kt similarity index 64% rename from app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseHeaderOutputKDBX.kt index fcc86f68f..8c2343752 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseHeaderOutputKDBX.kt @@ -21,9 +21,9 @@ package com.kunzisoft.keepass.database.file.save import com.kunzisoft.keepass.utils.VariantDictionary import com.kunzisoft.keepass.crypto.keyDerivation.KdfParameters -import com.kunzisoft.keepass.database.element.PwDatabaseV4 -import com.kunzisoft.keepass.database.file.PwDbHeader -import com.kunzisoft.keepass.database.file.PwDbHeaderV4 +import com.kunzisoft.keepass.database.element.DatabaseKDBX +import com.kunzisoft.keepass.database.file.DatabaseHeader +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX import com.kunzisoft.keepass.database.exception.DatabaseOutputException import com.kunzisoft.keepass.stream.HmacBlockStream import com.kunzisoft.keepass.stream.LEDataOutputStream @@ -41,8 +41,8 @@ import java.security.NoSuchAlgorithmException import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec -class PwDbHeaderOutputV4 @Throws(DatabaseOutputException::class) -constructor(private val db: PwDatabaseV4, private val header: PwDbHeaderV4, os: OutputStream) : PwDbHeaderOutput() { +class DatabaseHeaderOutputKDBX @Throws(DatabaseOutputException::class) +constructor(private val db: DatabaseKDBX, private val header: DatabaseHeaderKDBX, os: OutputStream) : DatabaseHeaderOutput() { private val los: LEDataOutputStream private val mos: MacOutputStream private val dos: DigestOutputStream @@ -82,39 +82,39 @@ constructor(private val db: PwDatabaseV4, private val header: PwDbHeaderV4, os: @Throws(IOException::class) fun output() { - los.writeUInt(PwDbHeader.PWM_DBSIG_1.toLong()) - los.writeUInt(PwDbHeaderV4.DBSIG_2.toLong()) + los.writeUInt(DatabaseHeader.PWM_DBSIG_1.toLong()) + los.writeUInt(DatabaseHeaderKDBX.DBSIG_2.toLong()) los.writeUInt(header.version) - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.CipherID, DatabaseInputOutputUtils.uuidToBytes(db.dataCipher)) - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.CompressionFlags, LEDataOutputStream.writeIntBuf(PwDbHeaderV4.getFlagFromCompression(db.compressionAlgorithm))) - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.MasterSeed, header.masterSeed) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.CipherID, DatabaseInputOutputUtils.uuidToBytes(db.dataCipher)) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.CompressionFlags, LEDataOutputStream.writeIntBuf(DatabaseHeaderKDBX.getFlagFromCompression(db.compressionAlgorithm))) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.MasterSeed, header.masterSeed) - if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.TransformSeed, header.transformSeed) - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.TransformRounds, LEDataOutputStream.writeLongBuf(db.numberKeyEncryptionRounds)) + if (header.version < DatabaseHeaderKDBX.FILE_VERSION_32_4) { + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.TransformSeed, header.transformSeed) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.TransformRounds, LEDataOutputStream.writeLongBuf(db.numberKeyEncryptionRounds)) } else { - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.KdfParameters, KdfParameters.serialize(db.kdfParameters!!)) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.KdfParameters, KdfParameters.serialize(db.kdfParameters!!)) } if (header.encryptionIV.isNotEmpty()) { - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.EncryptionIV, header.encryptionIV) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.EncryptionIV, header.encryptionIV) } - if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.InnerRandomstreamKey, header.innerRandomStreamKey) - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.StreamStartBytes, header.streamStartBytes) - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.InnerRandomStreamID, LEDataOutputStream.writeIntBuf(header.innerRandomStream!!.id)) + if (header.version < DatabaseHeaderKDBX.FILE_VERSION_32_4) { + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.InnerRandomstreamKey, header.innerRandomStreamKey) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.StreamStartBytes, header.streamStartBytes) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.InnerRandomStreamID, LEDataOutputStream.writeIntBuf(header.innerRandomStream!!.id)) } if (db.containsPublicCustomData()) { val bos = ByteArrayOutputStream() val los = LEDataOutputStream(bos) VariantDictionary.serialize(db.publicCustomData, los) - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.PublicCustomData, bos.toByteArray()) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.PublicCustomData, bos.toByteArray()) } - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.EndOfHeader, EndHeaderValue) + writeHeaderField(DatabaseHeaderKDBX.PwDbHeaderV4Fields.EndOfHeader, EndHeaderValue) los.flush() hashOfHeader = dos.messageDigest.digest() @@ -136,7 +136,7 @@ constructor(private val db: PwDatabaseV4, private val header: PwDbHeaderV4, os: @Throws(IOException::class) private fun writeHeaderFieldSize(size: Int) { - if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { + if (header.version < DatabaseHeaderKDBX.FILE_VERSION_32_4) { los.writeUShort(size) } else { los.writeInt(size) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbInnerHeaderOutputV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseInnerHeaderOutputKDBX.kt similarity index 70% rename from app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbInnerHeaderOutputV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseInnerHeaderOutputKDBX.kt index 4c3d59e85..148c11ddb 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbInnerHeaderOutputV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseInnerHeaderOutputKDBX.kt @@ -19,9 +19,9 @@ */ package com.kunzisoft.keepass.database.file.save -import com.kunzisoft.keepass.database.element.PwDatabaseV4 -import com.kunzisoft.keepass.database.element.PwDatabaseV4.Companion.BUFFER_SIZE_BYTES -import com.kunzisoft.keepass.database.file.PwDbHeaderV4 +import com.kunzisoft.keepass.database.element.DatabaseKDBX +import com.kunzisoft.keepass.database.element.DatabaseKDBX.Companion.BUFFER_SIZE_BYTES +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX import com.kunzisoft.keepass.stream.ReadBytes import com.kunzisoft.keepass.stream.LEDataOutputStream import com.kunzisoft.keepass.stream.readFromStream @@ -29,32 +29,32 @@ import java.io.IOException import java.io.OutputStream import kotlin.experimental.or -class PwDbInnerHeaderOutputV4(private val database: PwDatabaseV4, - private val header: PwDbHeaderV4, - outputStream: OutputStream) { +class DatabaseInnerHeaderOutputKDBX(private val database: DatabaseKDBX, + private val header: DatabaseHeaderKDBX, + outputStream: OutputStream) { private val dataOutputStream: LEDataOutputStream = LEDataOutputStream(outputStream) @Throws(IOException::class) fun output() { - dataOutputStream.write(PwDbHeaderV4.PwDbInnerHeaderV4Fields.InnerRandomStreamID.toInt()) + dataOutputStream.write(DatabaseHeaderKDBX.PwDbInnerHeaderV4Fields.InnerRandomStreamID.toInt()) dataOutputStream.writeInt(4) if (header.innerRandomStream == null) throw IOException("Can't write innerRandomStream") dataOutputStream.writeInt(header.innerRandomStream!!.id) val streamKeySize = header.innerRandomStreamKey.size - dataOutputStream.write(PwDbHeaderV4.PwDbInnerHeaderV4Fields.InnerRandomstreamKey.toInt()) + dataOutputStream.write(DatabaseHeaderKDBX.PwDbInnerHeaderV4Fields.InnerRandomstreamKey.toInt()) dataOutputStream.writeInt(streamKeySize) dataOutputStream.write(header.innerRandomStreamKey) database.binaryPool.doForEachBinary { _, protectedBinary -> - var flag = PwDbHeaderV4.KdbxBinaryFlags.None + var flag = DatabaseHeaderKDBX.KdbxBinaryFlags.None if (protectedBinary.isProtected) { - flag = flag or PwDbHeaderV4.KdbxBinaryFlags.Protected + flag = flag or DatabaseHeaderKDBX.KdbxBinaryFlags.Protected } - dataOutputStream.write(PwDbHeaderV4.PwDbInnerHeaderV4Fields.Binary.toInt()) + dataOutputStream.write(DatabaseHeaderKDBX.PwDbInnerHeaderV4Fields.Binary.toInt()) dataOutputStream.writeInt(protectedBinary.length().toInt() + 1) // TODO verify dataOutputStream.write(flag.toInt()) @@ -67,7 +67,7 @@ class PwDbInnerHeaderOutputV4(private val database: PwDatabaseV4, ) } - dataOutputStream.write(PwDbHeaderV4.PwDbInnerHeaderV4Fields.EndOfHeader.toInt()) + dataOutputStream.write(DatabaseHeaderKDBX.PwDbInnerHeaderV4Fields.EndOfHeader.toInt()) dataOutputStream.writeInt(0) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbOutput.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseOutput.kt similarity index 90% rename from app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbOutput.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseOutput.kt index 6d59bd776..c731c0ca9 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbOutput.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseOutput.kt @@ -19,14 +19,14 @@ */ package com.kunzisoft.keepass.database.file.save -import com.kunzisoft.keepass.database.file.PwDbHeader +import com.kunzisoft.keepass.database.file.DatabaseHeader import com.kunzisoft.keepass.database.exception.DatabaseOutputException import java.io.OutputStream import java.security.NoSuchAlgorithmException import java.security.SecureRandom -abstract class PwDbOutput
protected constructor(protected var mOS: OutputStream) { +abstract class DatabaseOutput
protected constructor(protected var mOS: OutputStream) { @Throws(DatabaseOutputException::class) protected open fun setIVs(header: Header): SecureRandom { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV3Output.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseOutputKDB.kt similarity index 78% rename from app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV3Output.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseOutputKDB.kt index 6cb0f5d51..0e2790ffb 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV3Output.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseOutputKDB.kt @@ -20,11 +20,10 @@ package com.kunzisoft.keepass.database.file.save import com.kunzisoft.keepass.crypto.CipherFactory -import com.kunzisoft.keepass.database.NodeHandler import com.kunzisoft.keepass.database.element.* import com.kunzisoft.keepass.database.exception.DatabaseOutputException -import com.kunzisoft.keepass.database.file.PwDbHeader -import com.kunzisoft.keepass.database.file.PwDbHeaderV3 +import com.kunzisoft.keepass.database.file.DatabaseHeader +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDB import com.kunzisoft.keepass.stream.LEDataOutputStream import com.kunzisoft.keepass.stream.NullOutputStream @@ -39,16 +38,16 @@ import java.io.OutputStream import java.security.* import java.util.ArrayList -class PwDbV3Output(private val mDatabaseV3: PwDatabaseV3, os: OutputStream) : PwDbOutput(os) { +class DatabaseOutputKDB(private val mDatabaseKDB: DatabaseKDB, os: OutputStream) : DatabaseOutput(os) { private var headerHashBlock: ByteArray? = null @Throws(DatabaseOutputException::class) - fun getFinalKey(header: PwDbHeader): ByteArray? { + fun getFinalKey(header: DatabaseHeader): ByteArray? { try { - val h3 = header as PwDbHeaderV3 - mDatabaseV3.makeFinalKey(h3.masterSeed, h3.transformSeed, mDatabaseV3.numberKeyEncryptionRounds) - return mDatabaseV3.finalKey + val headerKDB = header as DatabaseHeaderKDB + mDatabaseKDB.makeFinalKey(headerKDB.masterSeed, headerKDB.transformSeed, mDatabaseKDB.numberKeyEncryptionRounds) + return mDatabaseKDB.finalKey } catch (e: IOException) { throw DatabaseOutputException("Key creation failed.", e) } @@ -67,9 +66,9 @@ class PwDbV3Output(private val mDatabaseV3: PwDatabaseV3, os: OutputStream) : Pw val cipher: Cipher cipher = try { when { - mDatabaseV3.encryptionAlgorithm === PwEncryptionAlgorithm.AESRijndael-> + mDatabaseKDB.encryptionAlgorithm === EncryptionAlgorithm.AESRijndael-> CipherFactory.getInstance("AES/CBC/PKCS5Padding") - mDatabaseV3.encryptionAlgorithm === PwEncryptionAlgorithm.Twofish -> + mDatabaseKDB.encryptionAlgorithm === EncryptionAlgorithm.Twofish -> CipherFactory.getInstance("Twofish/CBC/PKCS7PADDING") else -> throw Exception() @@ -99,34 +98,34 @@ class PwDbV3Output(private val mDatabaseV3: PwDatabaseV3, os: OutputStream) : Pw } @Throws(DatabaseOutputException::class) - override fun setIVs(header: PwDbHeaderV3): SecureRandom { + override fun setIVs(header: DatabaseHeaderKDB): SecureRandom { val random = super.setIVs(header) random.nextBytes(header.transformSeed) return random } @Throws(DatabaseOutputException::class) - override fun outputHeader(outputStream: OutputStream): PwDbHeaderV3 { + override fun outputHeader(outputStream: OutputStream): DatabaseHeaderKDB { // Build header - val header = PwDbHeaderV3() - header.signature1 = PwDbHeader.PWM_DBSIG_1 - header.signature2 = PwDbHeaderV3.DBSIG_2 - header.flags = PwDbHeaderV3.FLAG_SHA2 + val header = DatabaseHeaderKDB() + header.signature1 = DatabaseHeader.PWM_DBSIG_1 + header.signature2 = DatabaseHeaderKDB.DBSIG_2 + header.flags = DatabaseHeaderKDB.FLAG_SHA2 when { - mDatabaseV3.encryptionAlgorithm === PwEncryptionAlgorithm.AESRijndael -> { - header.flags = header.flags or PwDbHeaderV3.FLAG_RIJNDAEL + mDatabaseKDB.encryptionAlgorithm === EncryptionAlgorithm.AESRijndael -> { + header.flags = header.flags or DatabaseHeaderKDB.FLAG_RIJNDAEL } - mDatabaseV3.encryptionAlgorithm === PwEncryptionAlgorithm.Twofish -> { - header.flags = header.flags or PwDbHeaderV3.FLAG_TWOFISH + mDatabaseKDB.encryptionAlgorithm === EncryptionAlgorithm.Twofish -> { + header.flags = header.flags or DatabaseHeaderKDB.FLAG_TWOFISH } else -> throw DatabaseOutputException("Unsupported algorithm.") } - header.version = PwDbHeaderV3.DBVER_DW - header.numGroups = mDatabaseV3.numberOfGroups() - header.numEntries = mDatabaseV3.numberOfEntries() - header.numKeyEncRounds = mDatabaseV3.numberKeyEncryptionRounds.toInt() + header.version = DatabaseHeaderKDB.DBVER_DW + header.numGroups = mDatabaseKDB.numberOfGroups() + header.numEntries = mDatabaseKDB.numberOfEntries() + header.numKeyEncRounds = mDatabaseKDB.numberKeyEncryptionRounds.toInt() setIVs(header) @@ -150,7 +149,7 @@ class PwDbV3Output(private val mDatabaseV3: PwDatabaseV3, os: OutputStream) : Pw val headerDos = DigestOutputStream(nos, headerDigest) // Output header for the purpose of calculating the header checksum - var pho = PwDbHeaderOutputV3(header, headerDos) + var pho = DatabaseHeaderOutputKDB(header, headerDos) try { pho.outputStart() pho.outputEnd() @@ -177,7 +176,7 @@ class PwDbV3Output(private val mDatabaseV3: PwDatabaseV3, os: OutputStream) : Pw header.contentsHash = messageDigest!!.digest() // Output header for real output, containing content hash - pho = PwDbHeaderOutputV3(header, outputStream) + pho = DatabaseHeaderOutputKDB(header, outputStream) try { pho.outputStart() dos.on(false) @@ -209,16 +208,16 @@ class PwDbV3Output(private val mDatabaseV3: PwDatabaseV3, os: OutputStream) : Pw } // Groups - mDatabaseV3.doForEachGroupInIndex { group -> - val pgo = PwGroupOutputV3(group, os) + mDatabaseKDB.doForEachGroupInIndex { group -> + val pgo = GroupOutputKDB(group, os) try { pgo.output() } catch (e: IOException) { throw DatabaseOutputException("Failed to output a tree", e) } } - mDatabaseV3.doForEachEntryInIndex { entry -> - val peo = PwEntryOutputV3(entry, os) + mDatabaseKDB.doForEachEntryInIndex { entry -> + val peo = EntryOutputKDB(entry, os) try { peo.output() } catch (e: IOException) { @@ -228,15 +227,15 @@ class PwDbV3Output(private val mDatabaseV3: PwDatabaseV3, os: OutputStream) : Pw } private fun sortGroupsForOutput() { - val groupList = ArrayList() + val groupList = ArrayList() // Rebuild list according to coalation sorting order removing any orphaned groups - for (rootGroup in mDatabaseV3.rootGroups) { + for (rootGroup in mDatabaseKDB.rootGroups) { sortGroup(rootGroup, groupList) } - mDatabaseV3.setGroupIndexes(groupList) + mDatabaseKDB.setGroupIndexes(groupList) } - private fun sortGroup(group: PwGroupV3, groupList: MutableList) { + private fun sortGroup(group: GroupKDB, groupList: MutableList) { // Add current tree groupList.add(group) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV4Output.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseOutputKDBX.kt similarity index 59% rename from app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV4Output.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseOutputKDBX.kt index c452eaba6..56f47b6a5 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV4Output.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/DatabaseOutputKDBX.kt @@ -29,14 +29,14 @@ import com.kunzisoft.keepass.crypto.engine.CipherEngine import com.kunzisoft.keepass.crypto.keyDerivation.KdfFactory import com.kunzisoft.keepass.database.NodeHandler import com.kunzisoft.keepass.database.element.* -import com.kunzisoft.keepass.database.element.PwDatabaseV4.Companion.BASE_64_FLAG -import com.kunzisoft.keepass.database.element.PwDatabaseV4.Companion.BUFFER_SIZE_BYTES +import com.kunzisoft.keepass.database.element.DatabaseKDBX.Companion.BASE_64_FLAG +import com.kunzisoft.keepass.database.element.DatabaseKDBX.Companion.BUFFER_SIZE_BYTES import com.kunzisoft.keepass.database.element.security.BinaryAttachment import com.kunzisoft.keepass.database.element.security.ProtectedString import com.kunzisoft.keepass.database.exception.DatabaseOutputException import com.kunzisoft.keepass.database.exception.UnknownKDF -import com.kunzisoft.keepass.database.file.KDBX4DateUtil -import com.kunzisoft.keepass.database.file.PwDbHeaderV4 +import com.kunzisoft.keepass.database.file.DateKDBXUtil +import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX import com.kunzisoft.keepass.stream.* import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils import org.joda.time.DateTime @@ -52,12 +52,12 @@ import javax.crypto.Cipher import javax.crypto.CipherOutputStream -class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, - outputStream: OutputStream) : PwDbOutput(outputStream) { +class DatabaseOutputKDBX(private val mDatabaseKDBX: DatabaseKDBX, + outputStream: OutputStream) : DatabaseOutput(outputStream) { private var randomStream: StreamCipher? = null private lateinit var xml: XmlSerializer - private var header: PwDbHeaderV4? = null + private var header: DatabaseHeaderKDBX? = null private var hashOfHeader: ByteArray? = null private var headerHmac: ByteArray? = null private var engine: CipherEngine? = null @@ -67,7 +67,7 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, try { try { - engine = CipherFactory.getInstance(mDatabaseV4.dataCipher) + engine = CipherFactory.getInstance(mDatabaseKDBX.dataCipher) } catch (e: NoSuchAlgorithmException) { throw DatabaseOutputException("No such cipher", e) } @@ -75,7 +75,7 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, header = outputHeader(mOS) val osPlain: OutputStream - osPlain = if (header!!.version < PwDbHeaderV4.FILE_VERSION_32_4) { + osPlain = if (header!!.version < DatabaseHeaderKDBX.FILE_VERSION_32_4) { val cos = attachStreamEncryptor(header!!, mOS) cos.write(header!!.streamStartBytes) @@ -84,18 +84,18 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, mOS.write(hashOfHeader!!) mOS.write(headerHmac!!) - attachStreamEncryptor(header!!, HmacBlockOutputStream(mOS, mDatabaseV4.hmacKey)) + attachStreamEncryptor(header!!, HmacBlockOutputStream(mOS, mDatabaseKDBX.hmacKey)) } val osXml: OutputStream try { - osXml = when(mDatabaseV4.compressionAlgorithm) { - PwCompressionAlgorithm.GZip -> GZIPOutputStream(osPlain) + osXml = when(mDatabaseKDBX.compressionAlgorithm) { + CompressionAlgorithm.GZip -> GZIPOutputStream(osPlain) else -> osPlain } - if (header!!.version >= PwDbHeaderV4.FILE_VERSION_32_4) { - val ihOut = PwDbInnerHeaderOutputV4(mDatabaseV4, header!!, osXml) + if (header!!.version >= DatabaseHeaderKDBX.FILE_VERSION_32_4) { + val ihOut = DatabaseInnerHeaderOutputKDBX(mDatabaseKDBX, header!!, osXml) ihOut.output() } @@ -120,19 +120,19 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, xml.setOutput(outputStream, "UTF-8") xml.startDocument("UTF-8", true) - xml.startTag(null, PwDatabaseV4XML.ElemDocNode) + xml.startTag(null, DatabaseKDBXXML.ElemDocNode) writeMeta() - mDatabaseV4.rootGroup?.let { root -> - xml.startTag(null, PwDatabaseV4XML.ElemRoot) + mDatabaseKDBX.rootGroup?.let { root -> + xml.startTag(null, DatabaseKDBXXML.ElemRoot) startGroup(root) - val groupStack = Stack() + val groupStack = Stack() groupStack.push(root) if (!root.doForEachChild( - object : NodeHandler() { - override fun operate(node: PwEntryV4): Boolean { + object : NodeHandler() { + override fun operate(node: EntryKDBX): Boolean { try { writeEntry(node, false) } catch (ex: IOException) { @@ -142,8 +142,8 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, return true } }, - object : NodeHandler() { - override fun operate(node: PwGroupV4): Boolean { + object : NodeHandler() { + override fun operate(node: GroupKDBX): Boolean { while (true) { try { if (node.parent === groupStack.peek()) { @@ -167,73 +167,73 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, throw RuntimeException("Writing groups failed") while (groupStack.size > 1) { - xml.endTag(null, PwDatabaseV4XML.ElemGroup) + xml.endTag(null, DatabaseKDBXXML.ElemGroup) groupStack.pop() } } endGroup() - writeDeletedObjects(mDatabaseV4.deletedObjects) + writeDeletedObjects(mDatabaseKDBX.deletedObjects) - xml.endTag(null, PwDatabaseV4XML.ElemRoot) + xml.endTag(null, DatabaseKDBXXML.ElemRoot) - xml.endTag(null, PwDatabaseV4XML.ElemDocNode) + xml.endTag(null, DatabaseKDBXXML.ElemDocNode) xml.endDocument() } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeMeta() { - xml.startTag(null, PwDatabaseV4XML.ElemMeta) + xml.startTag(null, DatabaseKDBXXML.ElemMeta) - writeObject(PwDatabaseV4XML.ElemGenerator, mDatabaseV4.localizedAppName) + writeObject(DatabaseKDBXXML.ElemGenerator, mDatabaseKDBX.localizedAppName) if (hashOfHeader != null) { - writeObject(PwDatabaseV4XML.ElemHeaderHash, String(Base64.encode(hashOfHeader!!, BASE_64_FLAG))) + writeObject(DatabaseKDBXXML.ElemHeaderHash, String(Base64.encode(hashOfHeader!!, BASE_64_FLAG))) } - writeObject(PwDatabaseV4XML.ElemDbName, mDatabaseV4.name, true) - writeObject(PwDatabaseV4XML.ElemDbNameChanged, mDatabaseV4.nameChanged.date) - writeObject(PwDatabaseV4XML.ElemDbDesc, mDatabaseV4.description, true) - writeObject(PwDatabaseV4XML.ElemDbDescChanged, mDatabaseV4.descriptionChanged.date) - writeObject(PwDatabaseV4XML.ElemDbDefaultUser, mDatabaseV4.defaultUserName, true) - writeObject(PwDatabaseV4XML.ElemDbDefaultUserChanged, mDatabaseV4.defaultUserNameChanged.date) - writeObject(PwDatabaseV4XML.ElemDbMntncHistoryDays, mDatabaseV4.maintenanceHistoryDays) - writeObject(PwDatabaseV4XML.ElemDbColor, mDatabaseV4.color) - writeObject(PwDatabaseV4XML.ElemDbKeyChanged, mDatabaseV4.keyLastChanged.date) - writeObject(PwDatabaseV4XML.ElemDbKeyChangeRec, mDatabaseV4.keyChangeRecDays) - writeObject(PwDatabaseV4XML.ElemDbKeyChangeForce, mDatabaseV4.keyChangeForceDays) + writeObject(DatabaseKDBXXML.ElemDbName, mDatabaseKDBX.name, true) + writeObject(DatabaseKDBXXML.ElemDbNameChanged, mDatabaseKDBX.nameChanged.date) + writeObject(DatabaseKDBXXML.ElemDbDesc, mDatabaseKDBX.description, true) + writeObject(DatabaseKDBXXML.ElemDbDescChanged, mDatabaseKDBX.descriptionChanged.date) + writeObject(DatabaseKDBXXML.ElemDbDefaultUser, mDatabaseKDBX.defaultUserName, true) + writeObject(DatabaseKDBXXML.ElemDbDefaultUserChanged, mDatabaseKDBX.defaultUserNameChanged.date) + writeObject(DatabaseKDBXXML.ElemDbMntncHistoryDays, mDatabaseKDBX.maintenanceHistoryDays) + writeObject(DatabaseKDBXXML.ElemDbColor, mDatabaseKDBX.color) + writeObject(DatabaseKDBXXML.ElemDbKeyChanged, mDatabaseKDBX.keyLastChanged.date) + writeObject(DatabaseKDBXXML.ElemDbKeyChangeRec, mDatabaseKDBX.keyChangeRecDays) + writeObject(DatabaseKDBXXML.ElemDbKeyChangeForce, mDatabaseKDBX.keyChangeForceDays) - writeMemoryProtection(mDatabaseV4.memoryProtection) + writeMemoryProtection(mDatabaseKDBX.memoryProtection) writeCustomIconList() - writeObject(PwDatabaseV4XML.ElemRecycleBinEnabled, mDatabaseV4.isRecycleBinEnabled) - writeUuid(PwDatabaseV4XML.ElemRecycleBinUuid, mDatabaseV4.recycleBinUUID) - writeObject(PwDatabaseV4XML.ElemRecycleBinChanged, mDatabaseV4.recycleBinChanged) - writeUuid(PwDatabaseV4XML.ElemEntryTemplatesGroup, mDatabaseV4.entryTemplatesGroup) - writeObject(PwDatabaseV4XML.ElemEntryTemplatesGroupChanged, mDatabaseV4.entryTemplatesGroupChanged.date) - writeObject(PwDatabaseV4XML.ElemHistoryMaxItems, mDatabaseV4.historyMaxItems.toLong()) - writeObject(PwDatabaseV4XML.ElemHistoryMaxSize, mDatabaseV4.historyMaxSize) - writeUuid(PwDatabaseV4XML.ElemLastSelectedGroup, mDatabaseV4.lastSelectedGroupUUID) - writeUuid(PwDatabaseV4XML.ElemLastTopVisibleGroup, mDatabaseV4.lastTopVisibleGroupUUID) + writeObject(DatabaseKDBXXML.ElemRecycleBinEnabled, mDatabaseKDBX.isRecycleBinEnabled) + writeUuid(DatabaseKDBXXML.ElemRecycleBinUuid, mDatabaseKDBX.recycleBinUUID) + writeObject(DatabaseKDBXXML.ElemRecycleBinChanged, mDatabaseKDBX.recycleBinChanged) + writeUuid(DatabaseKDBXXML.ElemEntryTemplatesGroup, mDatabaseKDBX.entryTemplatesGroup) + writeObject(DatabaseKDBXXML.ElemEntryTemplatesGroupChanged, mDatabaseKDBX.entryTemplatesGroupChanged.date) + writeObject(DatabaseKDBXXML.ElemHistoryMaxItems, mDatabaseKDBX.historyMaxItems.toLong()) + writeObject(DatabaseKDBXXML.ElemHistoryMaxSize, mDatabaseKDBX.historyMaxSize) + writeUuid(DatabaseKDBXXML.ElemLastSelectedGroup, mDatabaseKDBX.lastSelectedGroupUUID) + writeUuid(DatabaseKDBXXML.ElemLastTopVisibleGroup, mDatabaseKDBX.lastTopVisibleGroupUUID) // Seem to work properly if always in meta - // if (header!!.version < PwDbHeaderV4.FILE_VERSION_32_4) + // if (header!!.version < DatabaseHeaderKDBX.FILE_VERSION_32_4) writeMetaBinaries() - writeCustomData(mDatabaseV4.customData) + writeCustomData(mDatabaseKDBX.customData) - xml.endTag(null, PwDatabaseV4XML.ElemMeta) + xml.endTag(null, DatabaseKDBXXML.ElemMeta) } @Throws(DatabaseOutputException::class) - private fun attachStreamEncryptor(header: PwDbHeaderV4, os: OutputStream): CipherOutputStream { + private fun attachStreamEncryptor(header: DatabaseHeaderKDBX, os: OutputStream): CipherOutputStream { val cipher: Cipher try { - //mDatabaseV4.makeFinalKey(header.masterSeed, mDatabaseV4.kdfParameters); + //mDatabaseKDBX.makeFinalKey(header.masterSeed, mDatabaseKDBX.kdfParameters); - cipher = engine!!.getCipher(Cipher.ENCRYPT_MODE, mDatabaseV4.finalKey!!, header.encryptionIV) + cipher = engine!!.getCipher(Cipher.ENCRYPT_MODE, mDatabaseKDBX.finalKey!!, header.encryptionIV) } catch (e: Exception) { throw DatabaseOutputException("Invalid algorithm.", e) } @@ -242,7 +242,7 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, } @Throws(DatabaseOutputException::class) - override fun setIVs(header: PwDbHeaderV4): SecureRandom { + override fun setIVs(header: DatabaseHeaderKDBX): SecureRandom { val random = super.setIVs(header) random.nextBytes(header.masterSeed) @@ -252,18 +252,18 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, } random.nextBytes(header.encryptionIV) - if (mDatabaseV4.kdfParameters == null) { - mDatabaseV4.kdfParameters = KdfFactory.aesKdf.defaultParameters + if (mDatabaseKDBX.kdfParameters == null) { + mDatabaseKDBX.kdfParameters = KdfFactory.aesKdf.defaultParameters } try { - val kdf = mDatabaseV4.getEngineV4(mDatabaseV4.kdfParameters) - kdf.randomize(mDatabaseV4.kdfParameters!!) + val kdf = mDatabaseKDBX.getEngineKDBX4(mDatabaseKDBX.kdfParameters) + kdf.randomize(mDatabaseKDBX.kdfParameters!!) } catch (unknownKDF: UnknownKDF) { Log.e(TAG, "Unable to retrieve header", unknownKDF) } - if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { + if (header.version < DatabaseHeaderKDBX.FILE_VERSION_32_4) { header.innerRandomStream = CrsAlgorithm.Salsa20 header.innerRandomStreamKey = ByteArray(32) } else { @@ -277,7 +277,7 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, throw DatabaseOutputException("Invalid random cipher") } - if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { + if (header.version < DatabaseHeaderKDBX.FILE_VERSION_32_4) { random.nextBytes(header.streamStartBytes) } @@ -285,12 +285,12 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, } @Throws(DatabaseOutputException::class) - override fun outputHeader(outputStream: OutputStream): PwDbHeaderV4 { + override fun outputHeader(outputStream: OutputStream): DatabaseHeaderKDBX { - val header = PwDbHeaderV4(mDatabaseV4) + val header = DatabaseHeaderKDBX(mDatabaseKDBX) setIVs(header) - val pho = PwDbHeaderOutputV4(mDatabaseV4, header, outputStream) + val pho = DatabaseHeaderOutputKDBX(mDatabaseKDBX, header, outputStream) try { pho.output() } catch (e: IOException) { @@ -304,46 +304,46 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) - private fun startGroup(group: PwGroupV4) { - xml.startTag(null, PwDatabaseV4XML.ElemGroup) - writeUuid(PwDatabaseV4XML.ElemUuid, group.id) - writeObject(PwDatabaseV4XML.ElemName, group.title) - writeObject(PwDatabaseV4XML.ElemNotes, group.notes) - writeObject(PwDatabaseV4XML.ElemIcon, group.icon.iconId.toLong()) + private fun startGroup(group: GroupKDBX) { + xml.startTag(null, DatabaseKDBXXML.ElemGroup) + writeUuid(DatabaseKDBXXML.ElemUuid, group.id) + writeObject(DatabaseKDBXXML.ElemName, group.title) + writeObject(DatabaseKDBXXML.ElemNotes, group.notes) + writeObject(DatabaseKDBXXML.ElemIcon, group.icon.iconId.toLong()) - if (group.iconCustom != PwIconCustom.UNKNOWN_ICON) { - writeUuid(PwDatabaseV4XML.ElemCustomIconID, group.iconCustom.uuid) + if (group.iconCustom != IconImageCustom.UNKNOWN_ICON) { + writeUuid(DatabaseKDBXXML.ElemCustomIconID, group.iconCustom.uuid) } writeTimes(group) - writeObject(PwDatabaseV4XML.ElemIsExpanded, group.isExpanded) - writeObject(PwDatabaseV4XML.ElemGroupDefaultAutoTypeSeq, group.defaultAutoTypeSequence) - writeObject(PwDatabaseV4XML.ElemEnableAutoType, group.enableAutoType) - writeObject(PwDatabaseV4XML.ElemEnableSearching, group.enableSearching) - writeUuid(PwDatabaseV4XML.ElemLastTopVisibleEntry, group.lastTopVisibleEntry) + writeObject(DatabaseKDBXXML.ElemIsExpanded, group.isExpanded) + writeObject(DatabaseKDBXXML.ElemGroupDefaultAutoTypeSeq, group.defaultAutoTypeSequence) + writeObject(DatabaseKDBXXML.ElemEnableAutoType, group.enableAutoType) + writeObject(DatabaseKDBXXML.ElemEnableSearching, group.enableSearching) + writeUuid(DatabaseKDBXXML.ElemLastTopVisibleEntry, group.lastTopVisibleEntry) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun endGroup() { - xml.endTag(null, PwDatabaseV4XML.ElemGroup) + xml.endTag(null, DatabaseKDBXXML.ElemGroup) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) - private fun writeEntry(entry: PwEntryV4, isHistory: Boolean) { + private fun writeEntry(entry: EntryKDBX, isHistory: Boolean) { - xml.startTag(null, PwDatabaseV4XML.ElemEntry) + xml.startTag(null, DatabaseKDBXXML.ElemEntry) - writeUuid(PwDatabaseV4XML.ElemUuid, entry.id) - writeObject(PwDatabaseV4XML.ElemIcon, entry.icon.iconId.toLong()) + writeUuid(DatabaseKDBXXML.ElemUuid, entry.id) + writeObject(DatabaseKDBXXML.ElemIcon, entry.icon.iconId.toLong()) - if (entry.iconCustom != PwIconCustom.UNKNOWN_ICON) { - writeUuid(PwDatabaseV4XML.ElemCustomIconID, entry.iconCustom.uuid) + if (entry.iconCustom != IconImageCustom.UNKNOWN_ICON) { + writeUuid(DatabaseKDBXXML.ElemCustomIconID, entry.iconCustom.uuid) } - writeObject(PwDatabaseV4XML.ElemFgColor, entry.foregroundColor) - writeObject(PwDatabaseV4XML.ElemBgColor, entry.backgroundColor) - writeObject(PwDatabaseV4XML.ElemOverrideUrl, entry.overrideURL) - writeObject(PwDatabaseV4XML.ElemTags, entry.tags) + writeObject(DatabaseKDBXXML.ElemFgColor, entry.foregroundColor) + writeObject(DatabaseKDBXXML.ElemBgColor, entry.backgroundColor) + writeObject(DatabaseKDBXXML.ElemOverrideUrl, entry.overrideURL) + writeObject(DatabaseKDBXXML.ElemTags, entry.tags) writeTimes(entry) @@ -355,7 +355,7 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, writeEntryHistory(entry.history) } - xml.endTag(null, PwDatabaseV4XML.ElemEntry) + xml.endTag(null, DatabaseKDBXXML.ElemEntry) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) @@ -374,11 +374,11 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeObject(name: String, value: Date?) { - if (header!!.version < PwDbHeaderV4.FILE_VERSION_32_4) { - writeObject(name, PwDatabaseV4XML.dateFormatter.get().format(value)) + if (header!!.version < DatabaseHeaderKDBX.FILE_VERSION_32_4) { + writeObject(name, DatabaseKDBXXML.dateFormatter.get().format(value)) } else { val dt = DateTime(value) - val seconds = KDBX4DateUtil.convertDateToKDBX4Time(dt) + val seconds = DateKDBXUtil.convertDateToKDBX4Time(dt) val buf = LEDataOutputStream.writeLongBuf(seconds) val b64 = String(Base64.encode(buf, BASE_64_FLAG)) writeObject(name, b64) @@ -393,9 +393,9 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeObject(name: String, value: Boolean?) { val text: String = when { - value == null -> PwDatabaseV4XML.ValNull - value -> PwDatabaseV4XML.ValTrue - else -> PwDatabaseV4XML.ValFalse + value == null -> DatabaseKDBXXML.ValNull + value -> DatabaseKDBXXML.ValTrue + else -> DatabaseKDBXXML.ValFalse } writeObject(name, text) @@ -409,23 +409,23 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeMetaBinaries() { - xml.startTag(null, PwDatabaseV4XML.ElemBinaries) + xml.startTag(null, DatabaseKDBXXML.ElemBinaries) - mDatabaseV4.binaryPool.doForEachBinary { key, binary -> - xml.startTag(null, PwDatabaseV4XML.ElemBinary) - xml.attribute(null, PwDatabaseV4XML.AttrId, key.toString()) + mDatabaseKDBX.binaryPool.doForEachBinary { key, binary -> + xml.startTag(null, DatabaseKDBXXML.ElemBinary) + xml.attribute(null, DatabaseKDBXXML.AttrId, key.toString()) // Force binary compression from database (compression was harmonized during import) - xml.attribute(null, PwDatabaseV4XML.AttrCompressed, - if (mDatabaseV4.compressionAlgorithm === PwCompressionAlgorithm.GZip) { - PwDatabaseV4XML.ValTrue + xml.attribute(null, DatabaseKDBXXML.AttrCompressed, + if (mDatabaseKDBX.compressionAlgorithm === CompressionAlgorithm.GZip) { + DatabaseKDBXXML.ValTrue } else { - PwDatabaseV4XML.ValFalse + DatabaseKDBXXML.ValFalse } ) // Force decompression in this specific case - val binaryInputStream = if (mDatabaseV4.compressionAlgorithm == PwCompressionAlgorithm.None + val binaryInputStream = if (mDatabaseKDBX.compressionAlgorithm == CompressionAlgorithm.None && binary.isCompressed == true) { GZIPInputStream(binary.getInputDataStream()) } else { @@ -442,10 +442,10 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, } ) - xml.endTag(null, PwDatabaseV4XML.ElemBinary) + xml.endTag(null, DatabaseKDBXXML.ElemBinary) } - xml.endTag(null, PwDatabaseV4XML.ElemBinaries) + xml.endTag(null, DatabaseKDBXXML.ElemBinaries) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) @@ -465,20 +465,20 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeAutoType(autoType: AutoType) { - xml.startTag(null, PwDatabaseV4XML.ElemAutoType) + xml.startTag(null, DatabaseKDBXXML.ElemAutoType) - writeObject(PwDatabaseV4XML.ElemAutoTypeEnabled, autoType.enabled) - writeObject(PwDatabaseV4XML.ElemAutoTypeObfuscation, autoType.obfuscationOptions) + writeObject(DatabaseKDBXXML.ElemAutoTypeEnabled, autoType.enabled) + writeObject(DatabaseKDBXXML.ElemAutoTypeObfuscation, autoType.obfuscationOptions) if (autoType.defaultSequence.isNotEmpty()) { - writeObject(PwDatabaseV4XML.ElemAutoTypeDefaultSeq, autoType.defaultSequence, true) + writeObject(DatabaseKDBXXML.ElemAutoTypeDefaultSeq, autoType.defaultSequence, true) } for ((key, value) in autoType.entrySet()) { - writeObject(PwDatabaseV4XML.ElemAutoTypeItem, PwDatabaseV4XML.ElemWindow, key, PwDatabaseV4XML.ElemKeystrokeSequence, value) + writeObject(DatabaseKDBXXML.ElemAutoTypeItem, DatabaseKDBXXML.ElemWindow, key, DatabaseKDBXXML.ElemKeystrokeSequence, value) } - xml.endTag(null, PwDatabaseV4XML.ElemAutoType) + xml.endTag(null, DatabaseKDBXXML.ElemAutoType) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) @@ -492,24 +492,24 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeField(key: String, value: ProtectedString) { - xml.startTag(null, PwDatabaseV4XML.ElemString) - xml.startTag(null, PwDatabaseV4XML.ElemKey) + xml.startTag(null, DatabaseKDBXXML.ElemString) + xml.startTag(null, DatabaseKDBXXML.ElemKey) xml.text(safeXmlString(key)) - xml.endTag(null, PwDatabaseV4XML.ElemKey) + xml.endTag(null, DatabaseKDBXXML.ElemKey) - xml.startTag(null, PwDatabaseV4XML.ElemValue) + xml.startTag(null, DatabaseKDBXXML.ElemValue) var protect = value.isProtected when (key) { - MemoryProtectionConfig.ProtectDefinition.TITLE_FIELD -> protect = mDatabaseV4.memoryProtection.protectTitle - MemoryProtectionConfig.ProtectDefinition.USERNAME_FIELD -> protect = mDatabaseV4.memoryProtection.protectUserName - MemoryProtectionConfig.ProtectDefinition.PASSWORD_FIELD -> protect = mDatabaseV4.memoryProtection.protectPassword - MemoryProtectionConfig.ProtectDefinition.URL_FIELD -> protect = mDatabaseV4.memoryProtection.protectUrl - MemoryProtectionConfig.ProtectDefinition.NOTES_FIELD -> protect = mDatabaseV4.memoryProtection.protectNotes + MemoryProtectionConfig.ProtectDefinition.TITLE_FIELD -> protect = mDatabaseKDBX.memoryProtection.protectTitle + MemoryProtectionConfig.ProtectDefinition.USERNAME_FIELD -> protect = mDatabaseKDBX.memoryProtection.protectUserName + MemoryProtectionConfig.ProtectDefinition.PASSWORD_FIELD -> protect = mDatabaseKDBX.memoryProtection.protectPassword + MemoryProtectionConfig.ProtectDefinition.URL_FIELD -> protect = mDatabaseKDBX.memoryProtection.protectUrl + MemoryProtectionConfig.ProtectDefinition.NOTES_FIELD -> protect = mDatabaseKDBX.memoryProtection.protectNotes } if (protect) { - xml.attribute(null, PwDatabaseV4XML.AttrProtected, PwDatabaseV4XML.ValTrue) + xml.attribute(null, DatabaseKDBXXML.AttrProtected, DatabaseKDBXXML.ValTrue) val data = value.toString().toByteArray(charset("UTF-8")) val valLength = data.size @@ -523,38 +523,38 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, xml.text(safeXmlString(value.toString())) } - xml.endTag(null, PwDatabaseV4XML.ElemValue) - xml.endTag(null, PwDatabaseV4XML.ElemString) + xml.endTag(null, DatabaseKDBXXML.ElemValue) + xml.endTag(null, DatabaseKDBXXML.ElemString) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) - private fun writeDeletedObject(value: PwDeletedObject) { - xml.startTag(null, PwDatabaseV4XML.ElemDeletedObject) + private fun writeDeletedObject(value: DeletedObject) { + xml.startTag(null, DatabaseKDBXXML.ElemDeletedObject) - writeUuid(PwDatabaseV4XML.ElemUuid, value.uuid) - writeObject(PwDatabaseV4XML.ElemDeletionTime, value.deletionTime) + writeUuid(DatabaseKDBXXML.ElemUuid, value.uuid) + writeObject(DatabaseKDBXXML.ElemDeletionTime, value.deletionTime) - xml.endTag(null, PwDatabaseV4XML.ElemDeletedObject) + xml.endTag(null, DatabaseKDBXXML.ElemDeletedObject) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeEntryBinaries(binaries: Map) { for ((key, binary) in binaries) { - xml.startTag(null, PwDatabaseV4XML.ElemBinary) - xml.startTag(null, PwDatabaseV4XML.ElemKey) + xml.startTag(null, DatabaseKDBXXML.ElemBinary) + xml.startTag(null, DatabaseKDBXXML.ElemKey) xml.text(safeXmlString(key)) - xml.endTag(null, PwDatabaseV4XML.ElemKey) + xml.endTag(null, DatabaseKDBXXML.ElemKey) - xml.startTag(null, PwDatabaseV4XML.ElemValue) - val ref = mDatabaseV4.binaryPool.findKey(binary) + xml.startTag(null, DatabaseKDBXXML.ElemValue) + val ref = mDatabaseKDBX.binaryPool.findKey(binary) if (ref != null) { - xml.attribute(null, PwDatabaseV4XML.AttrRef, ref.toString()) + xml.attribute(null, DatabaseKDBXXML.AttrRef, ref.toString()) } else { val binaryLength = binary.length() if (binaryLength > 0) { if (binary.isProtected) { - xml.attribute(null, PwDatabaseV4XML.AttrProtected, PwDatabaseV4XML.ValTrue) + xml.attribute(null, DatabaseKDBXXML.AttrProtected, DatabaseKDBXXML.ValTrue) readFromStream(binary.getInputDataStream(), BUFFER_SIZE_BYTES, object : ReadBytes { @@ -577,71 +577,71 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, } } } - xml.endTag(null, PwDatabaseV4XML.ElemValue) + xml.endTag(null, DatabaseKDBXXML.ElemValue) - xml.endTag(null, PwDatabaseV4XML.ElemBinary) + xml.endTag(null, DatabaseKDBXXML.ElemBinary) } } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) - private fun writeDeletedObjects(value: List) { - xml.startTag(null, PwDatabaseV4XML.ElemDeletedObjects) + private fun writeDeletedObjects(value: List) { + xml.startTag(null, DatabaseKDBXXML.ElemDeletedObjects) for (pdo in value) { writeDeletedObject(pdo) } - xml.endTag(null, PwDatabaseV4XML.ElemDeletedObjects) + xml.endTag(null, DatabaseKDBXXML.ElemDeletedObjects) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeMemoryProtection(value: MemoryProtectionConfig) { - xml.startTag(null, PwDatabaseV4XML.ElemMemoryProt) + xml.startTag(null, DatabaseKDBXXML.ElemMemoryProt) - writeObject(PwDatabaseV4XML.ElemProtTitle, value.protectTitle) - writeObject(PwDatabaseV4XML.ElemProtUserName, value.protectUserName) - writeObject(PwDatabaseV4XML.ElemProtPassword, value.protectPassword) - writeObject(PwDatabaseV4XML.ElemProtURL, value.protectUrl) - writeObject(PwDatabaseV4XML.ElemProtNotes, value.protectNotes) + writeObject(DatabaseKDBXXML.ElemProtTitle, value.protectTitle) + writeObject(DatabaseKDBXXML.ElemProtUserName, value.protectUserName) + writeObject(DatabaseKDBXXML.ElemProtPassword, value.protectPassword) + writeObject(DatabaseKDBXXML.ElemProtURL, value.protectUrl) + writeObject(DatabaseKDBXXML.ElemProtNotes, value.protectNotes) - xml.endTag(null, PwDatabaseV4XML.ElemMemoryProt) + xml.endTag(null, DatabaseKDBXXML.ElemMemoryProt) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeCustomData(customData: Map) { - xml.startTag(null, PwDatabaseV4XML.ElemCustomData) + xml.startTag(null, DatabaseKDBXXML.ElemCustomData) for ((key, value) in customData) { writeObject( - PwDatabaseV4XML.ElemStringDictExItem, - PwDatabaseV4XML.ElemKey, + DatabaseKDBXXML.ElemStringDictExItem, + DatabaseKDBXXML.ElemKey, key, - PwDatabaseV4XML.ElemValue, + DatabaseKDBXXML.ElemValue, value ) } - xml.endTag(null, PwDatabaseV4XML.ElemCustomData) + xml.endTag(null, DatabaseKDBXXML.ElemCustomData) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) - private fun writeTimes(node: PwNodeV4Interface) { - xml.startTag(null, PwDatabaseV4XML.ElemTimes) + private fun writeTimes(node: NodeKDBXInterface) { + xml.startTag(null, DatabaseKDBXXML.ElemTimes) - writeObject(PwDatabaseV4XML.ElemLastModTime, node.lastModificationTime.date) - writeObject(PwDatabaseV4XML.ElemCreationTime, node.creationTime.date) - writeObject(PwDatabaseV4XML.ElemLastAccessTime, node.lastAccessTime.date) - writeObject(PwDatabaseV4XML.ElemExpiryTime, node.expiryTime.date) - writeObject(PwDatabaseV4XML.ElemExpires, node.expires) - writeObject(PwDatabaseV4XML.ElemUsageCount, node.usageCount) - writeObject(PwDatabaseV4XML.ElemLocationChanged, node.locationChanged.date) + writeObject(DatabaseKDBXXML.ElemLastModTime, node.lastModificationTime.date) + writeObject(DatabaseKDBXXML.ElemCreationTime, node.creationTime.date) + writeObject(DatabaseKDBXXML.ElemLastAccessTime, node.lastAccessTime.date) + writeObject(DatabaseKDBXXML.ElemExpiryTime, node.expiryTime.date) + writeObject(DatabaseKDBXXML.ElemExpires, node.expires) + writeObject(DatabaseKDBXXML.ElemUsageCount, node.usageCount) + writeObject(DatabaseKDBXXML.ElemLocationChanged, node.locationChanged.date) - xml.endTag(null, PwDatabaseV4XML.ElemTimes) + xml.endTag(null, DatabaseKDBXXML.ElemTimes) } @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) - private fun writeEntryHistory(value: List) { - val element = PwDatabaseV4XML.ElemHistory + private fun writeEntryHistory(value: List) { + val element = DatabaseKDBXXML.ElemHistory xml.startTag(null, element) @@ -654,21 +654,21 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeCustomIconList() { - val customIcons = mDatabaseV4.customIcons + val customIcons = mDatabaseKDBX.customIcons if (customIcons.size == 0) return - xml.startTag(null, PwDatabaseV4XML.ElemCustomIcons) + xml.startTag(null, DatabaseKDBXXML.ElemCustomIcons) for (icon in customIcons) { - xml.startTag(null, PwDatabaseV4XML.ElemCustomIconItem) + xml.startTag(null, DatabaseKDBXXML.ElemCustomIconItem) - writeUuid(PwDatabaseV4XML.ElemCustomIconItemID, icon.uuid) - writeObject(PwDatabaseV4XML.ElemCustomIconItemData, String(Base64.encode(icon.imageData, BASE_64_FLAG))) + writeUuid(DatabaseKDBXXML.ElemCustomIconItemID, icon.uuid) + writeObject(DatabaseKDBXXML.ElemCustomIconItemData, String(Base64.encode(icon.imageData, BASE_64_FLAG))) - xml.endTag(null, PwDatabaseV4XML.ElemCustomIconItem) + xml.endTag(null, DatabaseKDBXXML.ElemCustomIconItem) } - xml.endTag(null, PwDatabaseV4XML.ElemCustomIcons) + xml.endTag(null, DatabaseKDBXXML.ElemCustomIcons) } private fun safeXmlString(text: String): String { @@ -692,6 +692,6 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, } companion object { - private val TAG = PwDbV4Output::class.java.name + private val TAG = DatabaseOutputKDBX::class.java.name } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwEntryOutputV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/EntryOutputKDB.kt similarity index 96% rename from app/src/main/java/com/kunzisoft/keepass/database/file/save/PwEntryOutputV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/save/EntryOutputKDB.kt index 6c8798e81..4509311af 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwEntryOutputV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/EntryOutputKDB.kt @@ -19,18 +19,18 @@ */ package com.kunzisoft.keepass.database.file.save -import com.kunzisoft.keepass.database.element.PwEntryV3 +import com.kunzisoft.keepass.database.element.EntryKDB import com.kunzisoft.keepass.stream.LEDataOutputStream import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils import java.io.IOException import java.io.OutputStream -class PwEntryOutputV3 +class EntryOutputKDB /** - * Output the PwGroupV3 to the stream + * Output the GroupKDB to the stream */ -(private val mEntry: PwEntryV3, private val mOutputStream: OutputStream) { +(private val mEntry: EntryKDB, private val mOutputStream: OutputStream) { /** * Returns the number of bytes written by the stream * @return Number of bytes written diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwGroupOutputV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/GroupOutputKDB.kt similarity index 95% rename from app/src/main/java/com/kunzisoft/keepass/database/file/save/PwGroupOutputV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/file/save/GroupOutputKDB.kt index fea1c209b..2174c07e6 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwGroupOutputV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/GroupOutputKDB.kt @@ -19,7 +19,7 @@ */ package com.kunzisoft.keepass.database.file.save -import com.kunzisoft.keepass.database.element.PwGroupV3 +import com.kunzisoft.keepass.database.element.GroupKDB import com.kunzisoft.keepass.stream.LEDataOutputStream import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils @@ -27,9 +27,9 @@ import java.io.IOException import java.io.OutputStream /** - * Output the PwGroupV3 to the stream + * Output the GroupKDB to the stream */ -class PwGroupOutputV3 (private val mGroup: PwGroupV3, private val mOutputStream: OutputStream) { +class GroupOutputKDB (private val mGroup: GroupKDB, private val mOutputStream: OutputStream) { @Throws(IOException::class) fun output() { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/EntrySearchHandlerV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/search/EntryKDBXSearchHandler.kt similarity index 70% rename from app/src/main/java/com/kunzisoft/keepass/database/search/EntrySearchHandlerV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/search/EntryKDBXSearchHandler.kt index a14670220..4c0ab3aad 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/search/EntrySearchHandlerV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/search/EntryKDBXSearchHandler.kt @@ -20,23 +20,23 @@ package com.kunzisoft.keepass.database.search import com.kunzisoft.keepass.database.NodeHandler -import com.kunzisoft.keepass.database.element.PwEntryV4 -import com.kunzisoft.keepass.database.search.iterator.EntrySearchStringIteratorV4 +import com.kunzisoft.keepass.database.element.EntryKDBX +import com.kunzisoft.keepass.database.search.iterator.EntrySearchStringIteratorKDBX import com.kunzisoft.keepass.utils.StringUtil import java.util.Locale -class EntrySearchHandlerV4(private val mSearchParametersV4: SearchParametersV4, private val mListStorage: MutableList) : NodeHandler() { +class EntryKDBXSearchHandler(private val mSearchParametersKDBX: SearchParametersKDBX, private val mListStorage: MutableList) : NodeHandler() { - override fun operate(node: PwEntryV4): Boolean { + override fun operate(node: EntryKDBX): Boolean { - if (mSearchParametersV4.excludeExpired + if (mSearchParametersKDBX.excludeExpired && node.isCurrentlyExpires) { return true } - var term = mSearchParametersV4.searchString - if (mSearchParametersV4.ignoreCase) { + var term = mSearchParametersKDBX.searchString + if (mSearchParametersKDBX.ignoreCase) { term = term.toLowerCase() } @@ -45,11 +45,11 @@ class EntrySearchHandlerV4(private val mSearchParametersV4: SearchParametersV4, return true } - if (mSearchParametersV4.searchInGroupNames) { + if (mSearchParametersKDBX.searchInGroupNames) { val parent = node.parent if (parent != null) { var groupName = parent.title - if (mSearchParametersV4.ignoreCase) { + if (mSearchParametersKDBX.ignoreCase) { groupName = groupName.toLowerCase() } @@ -68,21 +68,21 @@ class EntrySearchHandlerV4(private val mSearchParametersV4: SearchParametersV4, return true } - private fun searchID(entry: PwEntryV4): Boolean { - if (mSearchParametersV4.searchInUUIDs) { + private fun searchID(entry: EntryKDBX): Boolean { + if (mSearchParametersKDBX.searchInUUIDs) { val hex = UuidUtil.toHexString(entry.id) - return StringUtil.indexOfIgnoreCase(hex, mSearchParametersV4.searchString, Locale.ENGLISH) >= 0 + return StringUtil.indexOfIgnoreCase(hex, mSearchParametersKDBX.searchString, Locale.ENGLISH) >= 0 } return false } - private fun searchStrings(entry: PwEntryV4, term: String): Boolean { - val iterator = EntrySearchStringIteratorV4(entry, mSearchParametersV4) + private fun searchStrings(entry: EntryKDBX, term: String): Boolean { + val iterator = EntrySearchStringIteratorKDBX(entry, mSearchParametersKDBX) while (iterator.hasNext()) { var str = iterator.next() if (str.isNotEmpty()) { - if (mSearchParametersV4.ignoreCase) { + if (mSearchParametersKDBX.ignoreCase) { str = str.toLowerCase() } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/SearchDbHelper.kt b/app/src/main/java/com/kunzisoft/keepass/database/search/SearchDbHelper.kt index 626b3eb41..52e5fa17f 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/search/SearchDbHelper.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/search/SearchDbHelper.kt @@ -21,11 +21,11 @@ package com.kunzisoft.keepass.database.search import com.kunzisoft.keepass.database.NodeHandler import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.EntryVersioned -import com.kunzisoft.keepass.database.element.GroupVersioned +import com.kunzisoft.keepass.database.element.Entry +import com.kunzisoft.keepass.database.element.Group import com.kunzisoft.keepass.database.search.iterator.EntrySearchStringIterator -import com.kunzisoft.keepass.database.search.iterator.EntrySearchStringIteratorV3 -import com.kunzisoft.keepass.database.search.iterator.EntrySearchStringIteratorV4 +import com.kunzisoft.keepass.database.search.iterator.EntrySearchStringIteratorKDB +import com.kunzisoft.keepass.database.search.iterator.EntrySearchStringIteratorKDBX import java.util.* class SearchDbHelper(private val isOmitBackup: Boolean) { @@ -36,7 +36,7 @@ class SearchDbHelper(private val isOmitBackup: Boolean) { private var incrementEntry = 0 - fun search(database: Database, qStr: String, max: Int): GroupVersioned? { + fun search(database: Database, qStr: String, max: Int): Group? { val searchGroup = database.createGroup() searchGroup?.title = "\"" + qStr + "\"" @@ -47,8 +47,8 @@ class SearchDbHelper(private val isOmitBackup: Boolean) { incrementEntry = 0 database.rootGroup?.doForEachChild( - object : NodeHandler() { - override fun operate(node: EntryVersioned): Boolean { + object : NodeHandler() { + override fun operate(node: Entry): Boolean { if (incrementEntry >= max) return false if (entryContainsString(node, finalQStr, loc)) { @@ -59,8 +59,8 @@ class SearchDbHelper(private val isOmitBackup: Boolean) { return incrementEntry < max } }, - object : NodeHandler() { - override fun operate(node: GroupVersioned): Boolean { + object : NodeHandler() { + override fun operate(node: Group): Boolean { return when { incrementEntry >= max -> false database.isGroupSearchable(node, isOmitBackup) -> true @@ -73,7 +73,7 @@ class SearchDbHelper(private val isOmitBackup: Boolean) { return searchGroup } - private fun entryContainsString(entry: EntryVersioned, searchString: String, locale: Locale): Boolean { + private fun entryContainsString(entry: Entry, searchString: String, locale: Locale): Boolean { // Entry don't contains string if the search string is empty if (searchString.isEmpty()) @@ -81,11 +81,11 @@ class SearchDbHelper(private val isOmitBackup: Boolean) { // Search all strings in the entry var iterator: EntrySearchStringIterator? = null - entry.pwEntryV3?.let { - iterator = EntrySearchStringIteratorV3(it) + entry.entryKDB?.let { + iterator = EntrySearchStringIteratorKDB(it) } - entry.pwEntryV4?.let { - iterator = EntrySearchStringIteratorV4(it) + entry.entryKDBX?.let { + iterator = EntrySearchStringIteratorKDBX(it) } iterator?.let { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/SearchParametersV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/search/SearchParametersKDBX.kt similarity index 90% rename from app/src/main/java/com/kunzisoft/keepass/database/search/SearchParametersV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/search/SearchParametersKDBX.kt index 740e7e3fc..c3dac8cd6 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/search/SearchParametersV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/search/SearchParametersKDBX.kt @@ -19,7 +19,7 @@ */ package com.kunzisoft.keepass.database.search -class SearchParametersV4 : SearchParameters { +class SearchParametersKDBX : SearchParameters { var searchInOther = true var searchInUUIDs = false @@ -27,7 +27,7 @@ class SearchParametersV4 : SearchParameters { constructor() : super() - constructor(searchParametersV4: SearchParametersV4) : super(searchParametersV4) { + constructor(searchParametersV4: SearchParametersKDBX) : super(searchParametersV4) { this.searchInOther = searchParametersV4.searchInOther this.searchInUUIDs = searchParametersV4.searchInUUIDs this.searchInTags = searchParametersV4.searchInTags diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorKDB.kt similarity index 94% rename from app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorV3.kt rename to app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorKDB.kt index cf786054d..173ddb5be 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorKDB.kt @@ -19,15 +19,15 @@ */ package com.kunzisoft.keepass.database.search.iterator -import com.kunzisoft.keepass.database.element.PwEntryV3 +import com.kunzisoft.keepass.database.element.EntryKDB import com.kunzisoft.keepass.database.search.SearchParameters import java.util.NoSuchElementException -class EntrySearchStringIteratorV3 +class EntrySearchStringIteratorKDB @JvmOverloads -constructor(private val mEntry: PwEntryV3, +constructor(private val mEntry: EntryKDB, private val mSearchParameters: SearchParameters? = SearchParameters()) : EntrySearchStringIterator() { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorKDBX.kt similarity index 74% rename from app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorV4.kt rename to app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorKDBX.kt index 564e5b4f4..f81254ca2 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/search/iterator/EntrySearchStringIteratorKDBX.kt @@ -19,25 +19,25 @@ */ package com.kunzisoft.keepass.database.search.iterator -import com.kunzisoft.keepass.database.element.PwEntryV4 -import com.kunzisoft.keepass.database.search.SearchParametersV4 +import com.kunzisoft.keepass.database.element.EntryKDBX +import com.kunzisoft.keepass.database.search.SearchParametersKDBX import com.kunzisoft.keepass.database.element.security.ProtectedString import java.util.* import kotlin.collections.Map.Entry -class EntrySearchStringIteratorV4 : EntrySearchStringIterator { +class EntrySearchStringIteratorKDBX : EntrySearchStringIterator { private var mCurrent: String? = null private var mSetIterator: Iterator>? = null - private var mSearchParametersV4: SearchParametersV4 + private var mSearchParametersV4: SearchParametersKDBX - constructor(entry: PwEntryV4) { - this.mSearchParametersV4 = SearchParametersV4() + constructor(entry: EntryKDBX) { + this.mSearchParametersV4 = SearchParametersKDBX() mSetIterator = entry.fields.entries.iterator() advance() } - constructor(entry: PwEntryV4, searchParametersV4: SearchParametersV4) { + constructor(entry: EntryKDBX, searchParametersV4: SearchParametersKDBX) { this.mSearchParametersV4 = searchParametersV4 mSetIterator = entry.fields.entries.iterator() advance() @@ -75,11 +75,11 @@ class EntrySearchStringIteratorV4 : EntrySearchStringIterator { private fun searchInField(key: String): Boolean { return when (key) { - PwEntryV4.STR_TITLE -> mSearchParametersV4.searchInTitles - PwEntryV4.STR_USERNAME -> mSearchParametersV4.searchInUserNames - PwEntryV4.STR_PASSWORD -> mSearchParametersV4.searchInPasswords - PwEntryV4.STR_URL -> mSearchParametersV4.searchInUrls - PwEntryV4.STR_NOTES -> mSearchParametersV4.searchInNotes + EntryKDBX.STR_TITLE -> mSearchParametersV4.searchInTitles + EntryKDBX.STR_USERNAME -> mSearchParametersV4.searchInUserNames + EntryKDBX.STR_PASSWORD -> mSearchParametersV4.searchInPasswords + EntryKDBX.STR_URL -> mSearchParametersV4.searchInUrls + EntryKDBX.STR_NOTES -> mSearchParametersV4.searchInNotes else -> mSearchParametersV4.searchInOther } } diff --git a/app/src/main/java/com/kunzisoft/keepass/icons/IconDrawableFactory.kt b/app/src/main/java/com/kunzisoft/keepass/icons/IconDrawableFactory.kt index aef481e31..32ba25615 100644 --- a/app/src/main/java/com/kunzisoft/keepass/icons/IconDrawableFactory.kt +++ b/app/src/main/java/com/kunzisoft/keepass/icons/IconDrawableFactory.kt @@ -33,9 +33,9 @@ import androidx.core.widget.ImageViewCompat import android.util.Log import android.widget.ImageView import com.kunzisoft.keepass.R -import com.kunzisoft.keepass.database.element.PwIcon -import com.kunzisoft.keepass.database.element.PwIconCustom -import com.kunzisoft.keepass.database.element.PwIconStandard +import com.kunzisoft.keepass.database.element.IconImage +import com.kunzisoft.keepass.database.element.IconImageCustom +import com.kunzisoft.keepass.database.element.IconImageStandard import org.apache.commons.collections.map.AbstractReferenceMap import org.apache.commons.collections.map.ReferenceMap @@ -73,13 +73,13 @@ class IconDrawableFactory { /** * Get the [SuperDrawable] [icon] (from cache, or build it and add it to the cache if not exists yet), then [tint] it with [tintColor] if needed */ - fun getIconSuperDrawable(context: Context, icon: PwIcon, width: Int, tint: Boolean = false, tintColor: Int = Color.WHITE): SuperDrawable { + fun getIconSuperDrawable(context: Context, icon: IconImage, width: Int, tint: Boolean = false, tintColor: Int = Color.WHITE): SuperDrawable { return when (icon) { - is PwIconStandard -> { + is IconImageStandard -> { val resId = IconPackChooser.getSelectedIconPack(context)?.iconToResId(icon.iconId) ?: R.drawable.ic_blank_32dp getIconSuperDrawable(context, resId, width, tint, tintColor) } - is PwIconCustom -> { + is IconImageCustom -> { SuperDrawable(getIconDrawable(context.resources, icon), true) } else -> { @@ -89,7 +89,7 @@ class IconDrawableFactory { } /** - * Get the [SuperDrawable] PwIconStandard from [iconId] (cache, or build it and add it to the cache if not exists yet) + * Get the [SuperDrawable] IconImageStandard from [iconId] (cache, or build it and add it to the cache if not exists yet) * , then [tint] it with [tintColor] if needed */ fun getIconSuperDrawable(context: Context, iconId: Int, width: Int, tint: Boolean, tintColor: Int): SuperDrawable { @@ -128,7 +128,7 @@ class IconDrawableFactory { /** * Build a custom [Drawable] from custom [icon] */ - private fun getIconDrawable(resources: Resources, icon: PwIconCustom): Drawable { + private fun getIconDrawable(resources: Resources, icon: IconImageCustom): Drawable { val patternIcon = PatternIcon(resources) var draw: Drawable? = customIconMap[icon.uuid] as Drawable? @@ -249,7 +249,7 @@ fun ImageView.assignDefaultDatabaseIcon(iconFactory: IconDrawableFactory, tintCo /** * Assign a database [icon] to an ImageView and tint it with [tintColor] if needed */ -fun ImageView.assignDatabaseIcon(iconFactory: IconDrawableFactory, icon: PwIcon, tintColor: Int = Color.WHITE) { +fun ImageView.assignDatabaseIcon(iconFactory: IconDrawableFactory, icon: IconImage, tintColor: Int = Color.WHITE) { IconPackChooser.getSelectedIconPack(context)?.let { selectedIconPack -> iconFactory.assignDrawableToImageView( diff --git a/app/src/main/java/com/kunzisoft/keepass/notifications/DatabaseTaskNotificationService.kt b/app/src/main/java/com/kunzisoft/keepass/notifications/DatabaseTaskNotificationService.kt index 0edb42bde..abf1773da 100644 --- a/app/src/main/java/com/kunzisoft/keepass/notifications/DatabaseTaskNotificationService.kt +++ b/app/src/main/java/com/kunzisoft/keepass/notifications/DatabaseTaskNotificationService.kt @@ -298,7 +298,7 @@ class DatabaseTaskNotificationService : NotificationService(), ProgressTaskUpdat ) { val database = Database.getInstance() database.getGroupById(intent.getParcelableExtra(GROUP_ID_KEY))?.let { oldGroup -> - val newGroup: GroupVersioned = intent.getParcelableExtra(GROUP_KEY) + val newGroup: Group = intent.getParcelableExtra(GROUP_KEY) UpdateGroupRunnable(this, database, oldGroup, @@ -337,7 +337,7 @@ class DatabaseTaskNotificationService : NotificationService(), ProgressTaskUpdat ) { val database = Database.getInstance() database.getEntryById(intent.getParcelableExtra(ENTRY_ID_KEY))?.let { oldEntry -> - val newEntry: EntryVersioned = intent.getParcelableExtra(ENTRY_KEY) + val newEntry: Entry = intent.getParcelableExtra(ENTRY_KEY) UpdateEntryRunnable(this, database, oldEntry, @@ -535,14 +535,14 @@ class DatabaseTaskNotificationService : NotificationService(), ProgressTaskUpdat const val OLD_ELEMENT_KEY = "OLD_ELEMENT_KEY" // Warning type of this thing change every time const val NEW_ELEMENT_KEY = "NEW_ELEMENT_KEY" // Warning type of this thing change every time - fun getListNodesFromBundle(database: Database, bundle: Bundle): List { - val nodesAction = ArrayList() - bundle.getParcelableArrayList>(GROUPS_ID_KEY)?.forEach { + fun getListNodesFromBundle(database: Database, bundle: Bundle): List { + val nodesAction = ArrayList() + bundle.getParcelableArrayList>(GROUPS_ID_KEY)?.forEach { database.getGroupById(it)?.let { groupRetrieve -> nodesAction.add(groupRetrieve) } } - bundle.getParcelableArrayList>(ENTRIES_ID_KEY)?.forEach { + bundle.getParcelableArrayList>(ENTRIES_ID_KEY)?.forEach { database.getEntryById(it)?.let { entryRetrieve -> nodesAction.add(entryRetrieve) } @@ -550,18 +550,18 @@ class DatabaseTaskNotificationService : NotificationService(), ProgressTaskUpdat return nodesAction } - fun getBundleFromListNodes(nodes: List): Bundle { - val groupsId = ArrayList>() - val entriesId = ArrayList>() + fun getBundleFromListNodes(nodes: List): Bundle { + val groupsId = ArrayList>() + val entriesId = ArrayList>() nodes.forEach { nodeVersioned -> when (nodeVersioned.type) { Type.GROUP -> { - (nodeVersioned as GroupVersioned).nodeId?.let { groupId -> + (nodeVersioned as Group).nodeId?.let { groupId -> groupsId.add(groupId) } } Type.ENTRY -> { - entriesId.add((nodeVersioned as EntryVersioned).nodeId) + entriesId.add((nodeVersioned as Entry).nodeId) } } } diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/NestedDatabaseSettingsFragment.kt b/app/src/main/java/com/kunzisoft/keepass/settings/NestedDatabaseSettingsFragment.kt index 16c63b342..e6acd6135 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/NestedDatabaseSettingsFragment.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/NestedDatabaseSettingsFragment.kt @@ -1,6 +1,5 @@ package com.kunzisoft.keepass.settings -import android.content.Context import android.graphics.Color import android.os.Bundle import android.util.Log @@ -15,10 +14,9 @@ import com.kunzisoft.keepass.activities.dialogs.AssignMasterKeyDialogFragment import com.kunzisoft.keepass.activities.helpers.ReadOnlyHelper import com.kunzisoft.keepass.activities.lock.lock import com.kunzisoft.keepass.crypto.keyDerivation.KdfEngine -import com.kunzisoft.keepass.database.action.ProgressDialogThread import com.kunzisoft.keepass.database.element.Database -import com.kunzisoft.keepass.database.element.PwCompressionAlgorithm -import com.kunzisoft.keepass.database.element.PwEncryptionAlgorithm +import com.kunzisoft.keepass.database.element.CompressionAlgorithm +import com.kunzisoft.keepass.database.element.EncryptionAlgorithm import com.kunzisoft.keepass.notifications.DatabaseTaskNotificationService import com.kunzisoft.keepass.settings.preference.* import com.kunzisoft.keepass.settings.preferencedialogfragment.* @@ -125,7 +123,7 @@ class NestedDatabaseSettingsFragment : NestedSettingsFragment() { dbDataCompressionPref = findPreference(getString(R.string.database_data_compression_key)) if (mDatabase.allowDataCompression) { dbDataCompressionPref?.summary = (mDatabase.compressionAlgorithm - ?: PwCompressionAlgorithm.None).getName(resources) + ?: CompressionAlgorithm.None).getName(resources) } else { dbCompressionPrefCategory?.isVisible = false } @@ -333,8 +331,8 @@ class NestedDatabaseSettingsFragment : NestedSettingsFragment() { dbCustomColorPref?.summary = defaultColorToShow } DatabaseTaskNotificationService.ACTION_DATABASE_UPDATE_COMPRESSION_TASK -> { - val oldCompression = data.getSerializable(DatabaseTaskNotificationService.OLD_ELEMENT_KEY) as PwCompressionAlgorithm - val newCompression = data.getSerializable(DatabaseTaskNotificationService.NEW_ELEMENT_KEY) as PwCompressionAlgorithm + val oldCompression = data.getSerializable(DatabaseTaskNotificationService.OLD_ELEMENT_KEY) as CompressionAlgorithm + val newCompression = data.getSerializable(DatabaseTaskNotificationService.NEW_ELEMENT_KEY) as CompressionAlgorithm val algorithmToShow = if (result.isSuccess) { newCompression @@ -375,8 +373,8 @@ class NestedDatabaseSettingsFragment : NestedSettingsFragment() { -------- */ DatabaseTaskNotificationService.ACTION_DATABASE_UPDATE_ENCRYPTION_TASK -> { - val oldEncryption = data.getSerializable(DatabaseTaskNotificationService.OLD_ELEMENT_KEY) as PwEncryptionAlgorithm - val newEncryption = data.getSerializable(DatabaseTaskNotificationService.NEW_ELEMENT_KEY) as PwEncryptionAlgorithm + val oldEncryption = data.getSerializable(DatabaseTaskNotificationService.OLD_ELEMENT_KEY) as EncryptionAlgorithm + val newEncryption = data.getSerializable(DatabaseTaskNotificationService.NEW_ELEMENT_KEY) as EncryptionAlgorithm val algorithmToShow = if (result.isSuccess) { newEncryption diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/preferencedialogfragment/DatabaseDataCompressionPreferenceDialogFragmentCompat.kt b/app/src/main/java/com/kunzisoft/keepass/settings/preferencedialogfragment/DatabaseDataCompressionPreferenceDialogFragmentCompat.kt index 9fff3a5ea..c6925abc9 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/preferencedialogfragment/DatabaseDataCompressionPreferenceDialogFragmentCompat.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/preferencedialogfragment/DatabaseDataCompressionPreferenceDialogFragmentCompat.kt @@ -24,14 +24,14 @@ import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.kunzisoft.keepass.R -import com.kunzisoft.keepass.database.element.PwCompressionAlgorithm +import com.kunzisoft.keepass.database.element.CompressionAlgorithm import com.kunzisoft.keepass.settings.preferencedialogfragment.adapter.ListRadioItemAdapter class DatabaseDataCompressionPreferenceDialogFragmentCompat : DatabaseSavePreferenceDialogFragmentCompat(), - ListRadioItemAdapter.RadioItemSelectedCallback { + ListRadioItemAdapter.RadioItemSelectedCallback { - private var compressionSelected: PwCompressionAlgorithm? = null + private var compressionSelected: CompressionAlgorithm? = null override fun onBindDialogView(view: View) { super.onBindDialogView(view) @@ -42,7 +42,7 @@ class DatabaseDataCompressionPreferenceDialogFragmentCompat recyclerView.layoutManager = LinearLayoutManager(context) activity?.let { activity -> - val compressionAdapter = ListRadioItemAdapter(activity) + val compressionAdapter = ListRadioItemAdapter(activity) compressionAdapter.setRadioItemSelectedCallback(this) recyclerView.adapter = compressionAdapter @@ -70,7 +70,7 @@ class DatabaseDataCompressionPreferenceDialogFragmentCompat } } - override fun onItemSelected(item: PwCompressionAlgorithm) { + override fun onItemSelected(item: CompressionAlgorithm) { this.compressionSelected = item } diff --git a/app/src/main/java/com/kunzisoft/keepass/settings/preferencedialogfragment/DatabaseEncryptionAlgorithmPreferenceDialogFragmentCompat.kt b/app/src/main/java/com/kunzisoft/keepass/settings/preferencedialogfragment/DatabaseEncryptionAlgorithmPreferenceDialogFragmentCompat.kt index c9042a4cb..cb179dffd 100644 --- a/app/src/main/java/com/kunzisoft/keepass/settings/preferencedialogfragment/DatabaseEncryptionAlgorithmPreferenceDialogFragmentCompat.kt +++ b/app/src/main/java/com/kunzisoft/keepass/settings/preferencedialogfragment/DatabaseEncryptionAlgorithmPreferenceDialogFragmentCompat.kt @@ -24,14 +24,14 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.View import com.kunzisoft.keepass.R -import com.kunzisoft.keepass.database.element.PwEncryptionAlgorithm +import com.kunzisoft.keepass.database.element.EncryptionAlgorithm import com.kunzisoft.keepass.settings.preferencedialogfragment.adapter.ListRadioItemAdapter class DatabaseEncryptionAlgorithmPreferenceDialogFragmentCompat : DatabaseSavePreferenceDialogFragmentCompat(), - ListRadioItemAdapter.RadioItemSelectedCallback { + ListRadioItemAdapter.RadioItemSelectedCallback { - private var algorithmSelected: PwEncryptionAlgorithm? = null + private var algorithmSelected: EncryptionAlgorithm? = null override fun onBindDialogView(view: View) { super.onBindDialogView(view) @@ -42,7 +42,7 @@ class DatabaseEncryptionAlgorithmPreferenceDialogFragmentCompat recyclerView.layoutManager = LinearLayoutManager(context) activity?.let { activity -> - val encryptionAlgorithmAdapter = ListRadioItemAdapter(activity) + val encryptionAlgorithmAdapter = ListRadioItemAdapter(activity) encryptionAlgorithmAdapter.setRadioItemSelectedCallback(this) recyclerView.adapter = encryptionAlgorithmAdapter @@ -72,7 +72,7 @@ class DatabaseEncryptionAlgorithmPreferenceDialogFragmentCompat } } - override fun onItemSelected(item: PwEncryptionAlgorithm) { + override fun onItemSelected(item: EncryptionAlgorithm) { this.algorithmSelected = item } diff --git a/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.kt b/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.kt index ff98e6459..1f65bba78 100644 --- a/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.kt +++ b/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.kt @@ -42,7 +42,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA package com.kunzisoft.keepass.utils -import com.kunzisoft.keepass.database.element.PwDate +import com.kunzisoft.keepass.database.element.DateInstant import com.kunzisoft.keepass.stream.LEDataInputStream import com.kunzisoft.keepass.stream.LEDataOutputStream import java.io.IOException @@ -136,7 +136,7 @@ object DatabaseInputOutputUtils { * Unpack date from 5 byte format. The five bytes at 'offset' are unpacked * to a java.util.Date instance. */ - fun readCDate(buf: ByteArray, offset: Int, calendar: Calendar = Calendar.getInstance()): PwDate { + fun readCDate(buf: ByteArray, offset: Int, calendar: Calendar = Calendar.getInstance()): DateInstant { val dateSize = 5 val cDate = ByteArray(dateSize) System.arraycopy(buf, offset, cDate, 0, dateSize) @@ -161,7 +161,7 @@ object DatabaseInputOutputUtils { // File format is a 1 based day, java Calendar uses a 1 based day calendar.set(year, month - 1, day, hour, minute, second) - return PwDate(calendar.time) + return DateInstant(calendar.time) } fun writeCDate(date: Date?, calendar: Calendar = Calendar.getInstance()): ByteArray? { diff --git a/app/src/main/java/com/kunzisoft/keepass/view/EntryContentsView.kt b/app/src/main/java/com/kunzisoft/keepass/view/EntryContentsView.kt index ffb03cf9b..fdfbff4a7 100644 --- a/app/src/main/java/com/kunzisoft/keepass/view/EntryContentsView.kt +++ b/app/src/main/java/com/kunzisoft/keepass/view/EntryContentsView.kt @@ -33,8 +33,8 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.kunzisoft.keepass.R import com.kunzisoft.keepass.adapters.EntryHistoryAdapter -import com.kunzisoft.keepass.database.element.EntryVersioned -import com.kunzisoft.keepass.database.element.PwDate +import com.kunzisoft.keepass.database.element.Entry +import com.kunzisoft.keepass.database.element.DateInstant import com.kunzisoft.keepass.database.element.security.ProtectedString import com.kunzisoft.keepass.otp.OtpElement import com.kunzisoft.keepass.otp.OtpType @@ -304,15 +304,15 @@ class EntryContentsView @JvmOverloads constructor(context: Context, extrasContainerView.visibility = View.GONE } - fun assignCreationDate(date: PwDate) { + fun assignCreationDate(date: DateInstant) { creationDateView.text = date.getDateTimeString(resources) } - fun assignModificationDate(date: PwDate) { + fun assignModificationDate(date: DateInstant) { modificationDateView.text = date.getDateTimeString(resources) } - fun assignLastAccessDate(date: PwDate) { + fun assignLastAccessDate(date: DateInstant) { lastAccessDateView.text = date.getDateTimeString(resources) } @@ -320,7 +320,7 @@ class EntryContentsView @JvmOverloads constructor(context: Context, expiresImageView.visibility = if (isExpires) View.VISIBLE else View.GONE } - fun assignExpiresDate(date: PwDate) { + fun assignExpiresDate(date: DateInstant) { assignExpiresDate(date.getDateTimeString(resources)) } @@ -340,12 +340,12 @@ class EntryContentsView @JvmOverloads constructor(context: Context, historyAdapter.notifyDataSetChanged() } - fun assignHistory(history: ArrayList) { + fun assignHistory(history: ArrayList) { historyAdapter.clear() historyAdapter.entryHistoryList.addAll(history) } - fun onHistoryClick(action: (historyItem: EntryVersioned, position: Int)->Unit) { + fun onHistoryClick(action: (historyItem: Entry, position: Int)->Unit) { historyAdapter.onItemClickListener = { item, position -> action.invoke(item, position) } diff --git a/app/src/main/java/com/kunzisoft/keepass/view/EntryEditContentsView.kt b/app/src/main/java/com/kunzisoft/keepass/view/EntryEditContentsView.kt index d3354da34..8f3e1424f 100644 --- a/app/src/main/java/com/kunzisoft/keepass/view/EntryEditContentsView.kt +++ b/app/src/main/java/com/kunzisoft/keepass/view/EntryEditContentsView.kt @@ -11,7 +11,7 @@ import android.widget.EditText import android.widget.ImageView import android.widget.LinearLayout import com.kunzisoft.keepass.R -import com.kunzisoft.keepass.database.element.PwIcon +import com.kunzisoft.keepass.database.element.IconImage import com.kunzisoft.keepass.database.element.security.ProtectedString import com.kunzisoft.keepass.icons.IconDrawableFactory import com.kunzisoft.keepass.icons.assignDatabaseIcon @@ -81,7 +81,7 @@ class EntryEditContentsView @JvmOverloads constructor(context: Context, entryIconView.assignDefaultDatabaseIcon(iconFactory, iconColor) } - fun setIcon(iconFactory: IconDrawableFactory, icon: PwIcon) { + fun setIcon(iconFactory: IconDrawableFactory, icon: IconImage) { entryIconView.assignDatabaseIcon(iconFactory, icon, iconColor) }