fix: Remove Clipboard notifications #2301

This commit is contained in:
J-Jamet committed 2025-12-05 14:05:39 +01:00
1 parent 2afc829133
commit 363cbf6208
58 files changed
+3 -727

No files matched your search

@@ -70,7 +70,6 @@ import com.kunzisoft.keepass.education.EntryActivityEducation
import com.kunzisoft.keepass.model.EntryAttachmentState
import com.kunzisoft.keepass.otp.OtpType
import com.kunzisoft.keepass.services.AttachmentFileNotificationService
import com.kunzisoft.keepass.services.ClipboardEntryNotificationService
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_DELETE_ENTRY_HISTORY
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_RESTORE_ENTRY_HISTORY
import com.kunzisoft.keepass.settings.PreferencesUtil
@@ -258,8 +257,6 @@ class EntryActivity : DatabaseLockActivity() {
val entryInfo = entryInfoHistory.entryInfo
// Manage entry copy to start notification if allowed (at the first start)
if (savedInstanceState == null) {
// Manage entry to launch copying notification if allowed
ClipboardEntryNotificationService.checkAndLaunchNotification(this, entryInfo)
// Manage entry to populate Magikeyboard and launch keyboard notification if allowed
if (PreferencesUtil.isKeyboardEntrySelectionEnable(this)) {
MagikeyboardService.addEntry(this, entryInfo)
@@ -81,7 +81,6 @@ import com.kunzisoft.keepass.model.RegisterInfo
import com.kunzisoft.keepass.model.SearchInfo
import com.kunzisoft.keepass.otp.OtpElement
import com.kunzisoft.keepass.services.AttachmentFileNotificationService
import com.kunzisoft.keepass.services.ClipboardEntryNotificationService
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_CREATE_ENTRY_TASK
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.ACTION_DATABASE_UPDATE_ENTRY_TASK
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.getNewEntry
@@ -195,7 +194,6 @@ class EntryEditActivity : DatabaseLockActivity(),
))
}
stopService(Intent(this, ClipboardEntryNotificationService::class.java))
stopService(Intent(this, KeyboardEntryNotificationService::class.java))
// Entry is retrieve, it's an entry to update
@@ -1,149 +0,0 @@
/*
* Copyright 2019 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePassDX.
*
* KeePassDX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePassDX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePassDX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.services
import android.os.Parcel
import android.os.Parcelable
import android.util.Log
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.otp.OtpEntryFields.OTP_TOKEN_FIELD
import java.util.*
/**
* Utility class to manage fields in Notifications
*/
class ClipboardEntryNotificationField : Parcelable {
private var id: NotificationFieldId = NotificationFieldId.UNKNOWN
var label: String = ""
val isSensitive: Boolean
get() {
return id == NotificationFieldId.PASSWORD
}
val actionKey: String
get() = getActionKey(id)
val extraKey: String
get() = getExtraKey(id)
constructor(id: NotificationFieldId, label: String) {
this.id = id
this.label = label
}
constructor(parcel: Parcel) {
id = NotificationFieldId.values()[parcel.readInt()]
label = parcel.readString() ?: label
}
fun getGeneratedValue(entryInfo: EntryInfo?): String {
return when (id) {
NotificationFieldId.UNKNOWN -> ""
NotificationFieldId.USERNAME -> entryInfo?.username ?: ""
NotificationFieldId.PASSWORD -> entryInfo?.password ?: ""
NotificationFieldId.OTP -> entryInfo?.getGeneratedFieldValue(OTP_TOKEN_FIELD) ?: ""
NotificationFieldId.FIELD_A,
NotificationFieldId.FIELD_B,
NotificationFieldId.FIELD_C -> entryInfo?.getGeneratedFieldValue(label) ?: ""
}
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(id.ordinal)
dest.writeString(label)
}
override fun describeContents(): Int {
return 0
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val field = other as ClipboardEntryNotificationField
return id == field.id
}
override fun hashCode(): Int {
return id.hashCode()
}
enum class NotificationFieldId {
UNKNOWN, USERNAME, PASSWORD, OTP, FIELD_A, FIELD_B, FIELD_C;
companion object {
val anonymousFieldId: Array<NotificationFieldId>
get() = arrayOf(FIELD_A, FIELD_B, FIELD_C)
}
}
companion object {
private val TAG = ClipboardEntryNotificationField::class.java.name
@JvmField
val CREATOR: Parcelable.Creator<ClipboardEntryNotificationField> = object : Parcelable.Creator<ClipboardEntryNotificationField> {
override fun createFromParcel(`in`: Parcel): ClipboardEntryNotificationField {
return ClipboardEntryNotificationField(`in`)
}
override fun newArray(size: Int): Array<ClipboardEntryNotificationField?> {
return arrayOfNulls(size)
}
}
private const val ACTION_COPY_PREFIX = "ACTION_COPY_"
private const val EXTRA_KEY_PREFIX = "EXTRA_"
/**
* Return EXTRA_KEY link to ACTION_KEY, or null if ACTION_KEY is unknown
*/
fun getExtraKeyLinkToActionKey(actionKey: String): String? {
try {
if (actionKey.startsWith(ACTION_COPY_PREFIX)) {
val idName = actionKey.substring(ACTION_COPY_PREFIX.length, actionKey.length)
return getExtraKey(NotificationFieldId.valueOf(idName))
}
} catch (e: Exception) {
Log.e(TAG, "Can't get Extra Key from Action Key", e)
}
return null
}
private fun getActionKey(id: NotificationFieldId): String {
return ACTION_COPY_PREFIX + id.name
}
private fun getExtraKey(id: NotificationFieldId): String {
return EXTRA_KEY_PREFIX + id.name
}
val allActionKeys: List<String>
get() {
val actionKeys = ArrayList<String>()
for (id in NotificationFieldId.values()) {
actionKeys.add(getActionKey(id))
}
return actionKeys
}
}
}
@@ -1,358 +0,0 @@
/*
* Copyright 2019 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePassDX.
*
* KeePassDX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePassDX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePassDX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.services
import android.app.Activity
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.kunzisoft.keepass.R
import com.kunzisoft.keepass.model.EntryInfo
import com.kunzisoft.keepass.otp.OtpEntryFields.OTP_TOKEN_FIELD
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.timeout.ClipboardHelper
import com.kunzisoft.keepass.timeout.TimeoutHelper.NEVER
import com.kunzisoft.keepass.utils.LOCK_ACTION
import com.kunzisoft.keepass.utils.getParcelableExtraCompat
import com.kunzisoft.keepass.utils.getParcelableList
import com.kunzisoft.keepass.utils.putParcelableList
class ClipboardEntryNotificationService : LockNotificationService() {
override val notificationId = 485
private var mEntryInfo: EntryInfo? = null
private var clipboardHelper: ClipboardHelper? = null
override fun retrieveChannelId(): String {
return CHANNEL_CLIPBOARD_ID
}
override fun retrieveChannelName(): String {
return getString(R.string.clipboard)
}
override fun onCreate() {
super.onCreate()
clipboardHelper = ClipboardHelper(this)
}
private fun stopNotificationAndSendLockIfNeeded() {
// Clear the entry if define in preferences
if (PreferencesUtil.isClearClipboardNotificationEnable(this)) {
sendBroadcast(Intent(LOCK_ACTION))
}
// Stop the service
stopService()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
// Get entry info from intent
mEntryInfo = intent?.getParcelableExtraCompat(EXTRA_ENTRY_INFO)
when {
intent == null -> Log.w(TAG, "null intent")
ACTION_NEW_NOTIFICATION == intent.action -> {
newNotification(mEntryInfo?.title, constructListOfField(intent))
}
ACTION_CLEAN_CLIPBOARD == intent.action -> {
mTimerJob?.cancel()
clipboardHelper?.cleanClipboard()
stopNotificationAndSendLockIfNeeded()
}
else -> for (actionKey in ClipboardEntryNotificationField.allActionKeys) {
if (actionKey == intent.action) {
intent.getParcelableExtraCompat<ClipboardEntryNotificationField>(
ClipboardEntryNotificationField.getExtraKeyLinkToActionKey(actionKey))?.let {
fieldToCopy ->
val nextFields = constructListOfField(intent)
// Remove the current field from the next fields
nextFields.remove(fieldToCopy)
copyField(fieldToCopy, nextFields)
}
}
}
}
return START_NOT_STICKY
}
private fun constructListOfField(intent: Intent?): MutableList<ClipboardEntryNotificationField> {
val fieldList = mutableListOf<ClipboardEntryNotificationField>()
if (intent?.extras?.containsKey(EXTRA_CLIPBOARD_FIELDS) == true) {
intent.getParcelableList<ClipboardEntryNotificationField>(EXTRA_CLIPBOARD_FIELDS)?.let { retrieveFields ->
fieldList.clear()
fieldList.addAll(retrieveFields)
}
}
return fieldList
}
private fun getCopyPendingIntent(fieldToCopy: ClipboardEntryNotificationField, fieldsToAdd: MutableList<ClipboardEntryNotificationField>): PendingIntent {
val copyIntent = Intent(this, ClipboardEntryNotificationService::class.java).apply {
action = fieldToCopy.actionKey
putExtra(EXTRA_ENTRY_INFO, mEntryInfo)
putExtra(fieldToCopy.extraKey, fieldToCopy)
putParcelableList(EXTRA_CLIPBOARD_FIELDS, fieldsToAdd)
}
return PendingIntent.getService(
this, 0, copyIntent,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
)
}
private fun newNotification(title: String?, fieldsToAdd: MutableList<ClipboardEntryNotificationField>) {
mTimerJob?.cancel()
val builder = buildNewNotification()
.setSmallIcon(R.drawable.notification_ic_clipboard_key_24dp)
if (title != null)
builder.setContentTitle(title)
if (fieldsToAdd.size > 0) {
val field = fieldsToAdd[0]
builder.setContentText(getString(R.string.select_to_copy, field.label))
builder.setContentIntent(getCopyPendingIntent(field, fieldsToAdd))
// Add extra actions without 1st field
val fieldsWithoutFirstField = mutableListOf<ClipboardEntryNotificationField>()
fieldsWithoutFirstField.addAll(fieldsToAdd)
fieldsWithoutFirstField.remove(field)
// Add extra actions
for (fieldToAdd in fieldsWithoutFirstField) {
builder.addAction(R.drawable.notification_ic_clipboard_key_24dp, fieldToAdd.label,
getCopyPendingIntent(fieldToAdd, fieldsToAdd))
}
}
checkNotificationsPermission {
notificationManager?.notify(notificationId, builder.build())
}
}
private fun copyField(fieldToCopy: ClipboardEntryNotificationField, nextFields: MutableList<ClipboardEntryNotificationField>) {
mTimerJob?.cancel()
try {
var generatedValue = fieldToCopy.getGeneratedValue(mEntryInfo)
clipboardHelper?.copyToClipboard(
fieldToCopy.label,
generatedValue,
fieldToCopy.isSensitive
)
val builder = buildNewNotification()
.setSmallIcon(R.drawable.notification_ic_clipboard_key_24dp)
.setContentTitle(fieldToCopy.label)
// New action with next field if click
if (nextFields.size > 0) {
val nextField = nextFields[0]
builder.setContentText(getString(R.string.select_to_copy, nextField.label))
builder.setContentIntent(getCopyPendingIntent(nextField, nextFields))
}
val cleanIntent = Intent(this, ClipboardEntryNotificationService::class.java)
cleanIntent.action = ACTION_CLEAN_CLIPBOARD
val cleanPendingIntent = PendingIntent.getService(
this, 0, cleanIntent,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
)
builder.setDeleteIntent(cleanPendingIntent)
//Get settings
val notificationTimeoutMilliSecs = PreferencesUtil.getClipboardTimeout(this)
if (notificationTimeoutMilliSecs != NEVER) {
defineTimerJob(
builder,
NotificationServiceType.CLIPBOARD,
notificationTimeoutMilliSecs,
{
val newGeneratedValue = fieldToCopy.getGeneratedValue(mEntryInfo)
// New auto generated value
if (generatedValue != newGeneratedValue) {
generatedValue = newGeneratedValue
clipboardHelper?.copyToClipboard(
fieldToCopy.label,
generatedValue,
fieldToCopy.isSensitive
)
}
},
{
stopNotificationAndSendLockIfNeeded()
// Clean password only if no next field
if (nextFields.size <= 0)
clipboardHelper?.cleanClipboard()
}
)
} else {
// No timer
checkNotificationsPermission {
notificationManager?.notify(notificationId, builder.build())
}
}
} catch (e: Exception) {
Log.e(TAG, "Clipboard can't be populate", e)
}
}
private fun checkNotificationsPermission(action: () -> Unit) {
checkNotificationsPermission(
this,
PreferencesUtil.isClipboardNotificationsEnable(this),
action
)
}
override fun onTaskRemoved(rootIntent: Intent?) {
clipboardHelper?.cleanClipboard()
super.onTaskRemoved(rootIntent)
}
override fun onDestroy() {
clipboardHelper?.cleanClipboard()
super.onDestroy()
}
companion object {
private val TAG = ClipboardEntryNotificationService::class.java.name
private const val CHANNEL_CLIPBOARD_ID = "com.kunzisoft.keepass.notification.channel.clipboard"
const val ACTION_NEW_NOTIFICATION = "ACTION_NEW_NOTIFICATION"
const val EXTRA_ENTRY_INFO = "EXTRA_ENTRY_INFO"
const val EXTRA_CLIPBOARD_FIELDS = "EXTRA_CLIPBOARD_FIELDS"
const val ACTION_CLEAN_CLIPBOARD = "ACTION_CLEAN_CLIPBOARD"
fun checkAndLaunchNotification(
activity: Activity,
entry: EntryInfo
) {
checkNotificationsPermission(
activity,
PreferencesUtil.isClipboardNotificationsEnable(activity)
) {
launchNotificationIfAllowed(activity, entry)
}
}
private fun launchNotificationIfAllowed(context: Context, entry: EntryInfo) {
val containsUsernameToCopy = entry.username.isNotEmpty()
val containsPasswordToCopy = entry.password.isNotEmpty()
&& PreferencesUtil.allowCopyProtectedFields(context)
val containsOTPToCopy = entry.containsCustomField(OTP_TOKEN_FIELD)
val customFields = entry.getCustomFieldsForFilling()
val containsExtraFieldToCopy = customFields.isNotEmpty()
&& (customFields.any { !it.protectedValue.isProtected }
||
(customFields.any { it.protectedValue.isProtected }
&& PreferencesUtil.allowCopyProtectedFields(context))
)
var startService = false
val intent = Intent(context, ClipboardEntryNotificationService::class.java)
// If notifications enabled in settings
// Don't if application timeout
if (PreferencesUtil.isClipboardNotificationsEnable(context)) {
if (containsUsernameToCopy
|| containsPasswordToCopy
|| containsOTPToCopy
|| containsExtraFieldToCopy) {
// username already copied, waiting for user's action before copy password.
intent.action = ACTION_NEW_NOTIFICATION
intent.putExtra(EXTRA_ENTRY_INFO, entry)
// Construct notification fields
val notificationFields = mutableListOf<ClipboardEntryNotificationField>()
// Add username if exists to notifications
if (containsUsernameToCopy)
notificationFields.add(
ClipboardEntryNotificationField(
ClipboardEntryNotificationField.NotificationFieldId.USERNAME,
context.getString(R.string.entry_user_name)))
// Add password to notifications
if (containsPasswordToCopy) {
notificationFields.add(
ClipboardEntryNotificationField(
ClipboardEntryNotificationField.NotificationFieldId.PASSWORD,
context.getString(R.string.entry_password)))
}
// Add OTP
if (containsOTPToCopy) {
notificationFields.add(
ClipboardEntryNotificationField(
ClipboardEntryNotificationField.NotificationFieldId.OTP,
OTP_TOKEN_FIELD))
}
// Add extra fields
if (containsExtraFieldToCopy) {
try {
var anonymousFieldNumber = 0
entry.getCustomFieldsForFilling().forEach { field ->
//If value is not protected or allowed
if ((!field.protectedValue.isProtected
|| PreferencesUtil.allowCopyProtectedFields(context))
&& field.name != OTP_TOKEN_FIELD) {
notificationFields.add(
ClipboardEntryNotificationField(
ClipboardEntryNotificationField.NotificationFieldId.anonymousFieldId[anonymousFieldNumber],
field.name))
anonymousFieldNumber++
}
}
} catch (e: ArrayIndexOutOfBoundsException) {
Log.w("NotificationEntryCopyMg", "Only " + ClipboardEntryNotificationField.NotificationFieldId.anonymousFieldId.size +
" anonymous notifications are available")
}
}
// Add notifications
startService = true
intent.putParcelableList(EXTRA_CLIPBOARD_FIELDS, notificationFields)
context.startService(intent)
}
}
if (!startService)
context.stopService(intent)
}
fun removeNotification(context: Context?) {
context?.stopService(Intent(context, ClipboardEntryNotificationService::class.java))
}
}
}
@@ -42,7 +42,6 @@ import com.kunzisoft.keepass.credentialprovider.magikeyboard.MagikeyboardService
import com.kunzisoft.keepass.credentialprovider.magikeyboard.MagikeyboardService.Companion.showKeyboardDeviceSettings
import com.kunzisoft.keepass.education.Education
import com.kunzisoft.keepass.icons.IconPackChooser
import com.kunzisoft.keepass.services.ClipboardEntryNotificationService
import com.kunzisoft.keepass.settings.preference.IconPackListPreference
import com.kunzisoft.keepass.settings.preferencedialogfragment.DurationDialogFragmentCompat
import com.kunzisoft.keepass.utils.AppUtil.isContributingUser
@@ -171,13 +170,6 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
}
}
findPreference<Preference>(getString(R.string.clipboard_notifications_key))?.setOnPreferenceChangeListener { _, newValue ->
if (!(newValue as Boolean)) {
ClipboardEntryNotificationService.removeNotification(context)
}
true
}
findPreference<Preference>(getString(R.string.clipboard_explanation_key))?.setOnPreferenceClickListener {
context?.openUrl(R.string.clipboard_explanation_url)
false
@@ -413,12 +413,6 @@ object PreferencesUtil {
}
}
fun isClipboardNotificationsEnable(context: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getBoolean(context.getString(R.string.clipboard_notifications_key),
context.resources.getBoolean(R.bool.clipboard_notifications_default))
}
/**
* Save current time, can be retrieve with `getTimeSaved()`
*/
@@ -583,12 +577,6 @@ object PreferencesUtil {
context.resources.getBoolean(R.bool.allow_copy_password_default))
}
fun isClearClipboardNotificationEnable(context: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getBoolean(context.getString(R.string.clear_clipboard_notification_key),
context.resources.getBoolean(R.bool.clear_clipboard_notification_default))
}
fun isClearKeyboardNotificationEnable(context: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getBoolean(context.getString(R.string.keyboard_notification_entry_clear_close_key),
@@ -855,8 +843,6 @@ object PreferencesUtil {
context.getString(R.string.temp_device_unlock_timeout_key) -> editor.putString(name, value.toLong().toString())
context.getString(R.string.magic_keyboard_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.clipboard_notifications_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.clear_clipboard_notification_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.clipboard_timeout_key) -> editor.putString(name, value.toLong().toString())
context.getString(R.string.keyboard_notification_entry_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.keyboard_notification_entry_clear_close_key) -> editor.putBoolean(name, value.toBoolean())
@@ -34,7 +34,6 @@ import com.kunzisoft.keepass.R
import com.kunzisoft.keepass.app.AppLifecycleObserver
import com.kunzisoft.keepass.database.ContextualDatabase
import com.kunzisoft.keepass.credentialprovider.magikeyboard.MagikeyboardService
import com.kunzisoft.keepass.services.ClipboardEntryNotificationService
import com.kunzisoft.keepass.services.KeyboardEntryNotificationService
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.timeout.TimeoutHelper
@@ -151,8 +150,6 @@ fun Context.closeDatabase(database: ContextualDatabase?) {
MagikeyboardService.removeEntry(this)
// Stop the notification service
stopService(Intent(this, ClipboardEntryNotificationService::class.java))
Log.i(Context::class.java.name, "Close database after inactivity or manual lock")
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?)?.apply {
cancelAll()