diff --git a/data/build.gradle b/data/build.gradle index 7077cecd..1819170d 100644 --- a/data/build.gradle +++ b/data/build.gradle @@ -81,6 +81,7 @@ dependencies { implementation "com.f2prateek.rx.preferences2:rx-preferences:$rx_preferences_version" implementation "com.jakewharton.timber:timber:$timber_version" implementation "com.squareup.moshi:moshi:$moshi_version" + kapt "com.squareup.moshi:moshi-kotlin-codegen:$moshi_version" implementation "com.squareup.okhttp3:okhttp:$okhttp3_version" implementation 'io.michaelrocks:libphonenumber-android:8.13.47' implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" diff --git a/data/src/main/assets/emojis/en.json b/data/src/main/assets/emojis/en.json new file mode 100644 index 00000000..e36ffacd --- /dev/null +++ b/data/src/main/assets/emojis/en.json @@ -0,0 +1,22 @@ +{ + "emoji_reaction_ios_generic_added": "^(?s)Reacted (.+?) to “(.+?)”$", + "emoji_reaction_ios_generic_removed": "^(?s)Removed (.+?) from “(.+?)”$", + + "emoji_reaction_ios_heart_added": "^(?s)Loved “(.+?)”$", + "emoji_reaction_ios_heart_removed": "^(?s)Removed a heart from “(.+?)”$", + + "emoji_reaction_ios_like_added": "^(?s)Liked “(.+?)”$", + "emoji_reaction_ios_like_removed": "^(?s)Removed a like from “(.+?)”$", + + "emoji_reaction_ios_dislike_added": "^(?s)Disliked “(.+?)”$", + "emoji_reaction_ios_dislike_removed": "^(?s)Removed a dislike from “(.+?)”$", + + "emoji_reaction_ios_laugh_added": "^(?s)Laughed at “(.+?)”$", + "emoji_reaction_ios_laugh_removed": "^(?s)Removed a laugh from “(.+?)”$", + + "emoji_reaction_ios_exclamation_added": "^(?s)Emphasized “(.+?)”$", + "emoji_reaction_ios_exclamation_removed": "^(?s)Removed an exclamation from “(.+?)”$", + + "emoji_reaction_ios_question_mark_added": "^(?s)Questioned “(.+?)”$", + "emoji_reaction_ios_question_mark_removed": "^(?s)Removed a question mark from “(.+?)”$" +} diff --git a/data/src/main/assets/emojis/ru.json b/data/src/main/assets/emojis/ru.json new file mode 100644 index 00000000..f93d0e96 --- /dev/null +++ b/data/src/main/assets/emojis/ru.json @@ -0,0 +1,13 @@ +{ + "emoji_reaction_ios_heart_added": "^(?s)Очень понравилось «(.+?)»$", + + "emoji_reaction_ios_like_added": "^(?s)Понравилось «(.+?)»$", + + "emoji_reaction_ios_dislike_added": "^(?s)Не понравилось «(.+?)»$", + + "emoji_reaction_ios_laugh_added": "^(?s)Посмеялись над «(.+?)»$", + + "emoji_reaction_ios_exclamation_added": "^(?s)Отмечено «(.+?)»$", + + "emoji_reaction_ios_question_mark_added": "^(?s)Поставлен вопрос на «(.+?)»$" +} diff --git a/data/src/main/java/com/moez/QKSMS/migration/QkRealmMigration.kt b/data/src/main/java/com/moez/QKSMS/migration/QkRealmMigration.kt index 3e56541f..7f221a65 100644 --- a/data/src/main/java/com/moez/QKSMS/migration/QkRealmMigration.kt +++ b/data/src/main/java/com/moez/QKSMS/migration/QkRealmMigration.kt @@ -36,7 +36,7 @@ class QkRealmMigration @Inject constructor( ) : RealmMigration { companion object { - const val SchemaVersion: Long = 13 + const val SchemaVersion: Long = 14 } @SuppressLint("ApplySharedPref") @@ -252,6 +252,31 @@ class QkRealmMigration @Inject constructor( if (version == 12L) { realm.schema.get("Conversation") ?.addField("draftDate", Long::class.java, FieldAttribute.REQUIRED) + + version++ + } + + if (version == 13L) { + val emojiReactionTable = realm.schema.create("EmojiReaction") + .addField("id", Long::class.java, FieldAttribute.PRIMARY_KEY, FieldAttribute.REQUIRED) + .addField("reactionMessageId", Long::class.java, FieldAttribute.INDEXED, FieldAttribute.REQUIRED) + .addField("senderAddress", String::class.java, FieldAttribute.REQUIRED) + .addField("emoji", String::class.java, FieldAttribute.REQUIRED) + .addField("originalMessageText", String::class.java, FieldAttribute.REQUIRED) + .addField("threadId", Long::class.java, FieldAttribute.INDEXED, FieldAttribute.REQUIRED) + + realm.schema.get("Message") + ?.addField("isEmojiReaction", Boolean::class.java, FieldAttribute.REQUIRED) + ?.addRealmListField("emojiReactions", emojiReactionTable) + ?.transform { msg -> + msg.setBoolean("isEmojiReaction", false) + } + + realm.schema.create("EmojiSyncNeeded") + .addField("createdAt", Long::class.java, FieldAttribute.REQUIRED) + + realm.createObject("EmojiSyncNeeded") + version++ } diff --git a/data/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepositoryImpl.kt b/data/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepositoryImpl.kt new file mode 100644 index 00000000..81aba099 --- /dev/null +++ b/data/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepositoryImpl.kt @@ -0,0 +1,296 @@ +/* + * Copyright (C) 2025 + * + * This file is part of QUIK. + * + * QUIK 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. + * + * QUIK 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 QUIK. If not, see . + */ +package dev.octoshrimpy.quik.repository + +import android.content.Context +import com.squareup.moshi.Moshi +import dev.octoshrimpy.quik.extensions.insertOrUpdate +import dev.octoshrimpy.quik.manager.KeyManager +import dev.octoshrimpy.quik.model.EmojiReaction +import dev.octoshrimpy.quik.model.Message +import dev.octoshrimpy.quik.util.EmojiPatternStrings +import io.realm.Realm +import io.realm.Sort +import timber.log.Timber +import javax.inject.Inject + +class EmojiReactionRepositoryImpl @Inject constructor( + private val context: Context, + private val keyManager: KeyManager, + private val moshi: Moshi, +) : EmojiReactionRepository { + // We use an ordered map to make sure we can test tapback regexes before generic ones + private val reactionPatterns: LinkedHashMap ParsedEmojiReaction?> = linkedMapOf( + Regex( // Google Messages + "(?s)^\u200a[^\u200b\u200a]*\u200b([^\u200b]*)\u200b[^\u200b\u200a]*\u200a(.*)\u200a[^\u200b\u200a]*\u200a\\Z" + ) to { match -> ParsedEmojiReaction(match.groupValues[1], match.groupValues[2]) } + ) + private val removalPatterns: LinkedHashMap ParsedEmojiReaction?> = linkedMapOf( + Regex( // Google Messages + "(?s)^\u200a[^\u200c\u200a]*\u200c([^\u200c]*)\u200c[^\u200c\u200a]*\u200a(.*)\u200a[^\u200c\u200a]*\u200a\\Z" + ) to { match -> ParsedEmojiReaction(match.groupValues[1], match.groupValues[2], isRemoval = true) } + ) + + init { + val assetEntries = loadEmojiPatternEntriesFromAssets() + assetEntries.forEach { (localeTag, strings) -> + try { + addPatternsForLocaleStrings(localeTag, strings, reactionPatterns, removalPatterns) + } catch (e: Exception) { + Timber.w(e, "Failed to load asset patterns for locale: $localeTag") + } + } + Timber.i("Loaded emoji reaction patterns for locales: ${assetEntries.map { it.first }}") + } + + private fun addPatternsForLocaleStrings( + localeTag: String, + strings: EmojiPatternStrings, + reactionPatterns: LinkedHashMap ParsedEmojiReaction?>, + removalPatterns: LinkedHashMap ParsedEmojiReaction?> + ) { + // iOS tapbacks (important to add these before generic emoji patterns as the regexes may overlap) + listOf( + Triple("❤️", strings.iosHeartAdded, strings.iosHeartRemoved), + Triple("👍", strings.iosLikeAdded, strings.iosLikeRemoved), + Triple("👎", strings.iosDislikeAdded, strings.iosDislikeRemoved), + Triple("😂", strings.iosLaughAdded, strings.iosLaughRemoved), + Triple("‼️", strings.iosExclamationAdded, strings.iosExclamationRemoved), + Triple("❓", strings.iosQuestionMarkAdded, strings.iosQuestionMarkRemoved) + ).forEach { (emoji, added, removed) -> + added?.let { + reactionPatterns[Regex(it)] = + { match -> ParsedEmojiReaction(emoji, match.groupValues[1]) } + } + removed?.let { + removalPatterns[Regex(it)] = + { match -> ParsedEmojiReaction(emoji, match.groupValues[1], isRemoval = true) } + } + } + + // Generic iOS emoji patterns + strings.iosGenericAdded?.let { pattern -> + reactionPatterns[Regex(pattern)] = { match -> + if (match.groupValues.getOrNull(1) == "with a sticker") null // TODO: localize "with a sticker" + else ParsedEmojiReaction(match.groupValues[1], match.groupValues[2]) + } + } + strings.iosGenericRemoved?.let { pattern -> + removalPatterns[Regex(pattern)] = { match -> + ParsedEmojiReaction(match.groupValues[1], match.groupValues[2], isRemoval = true) + } + } + + Timber.d("Loaded emoji regex patterns for $localeTag from assets") + } + + private fun loadEmojiPatternEntriesFromAssets(): List> { + val dir = "emojis" + val files = context.assets.list(dir) ?: emptyArray() + return files.filter { it.endsWith(".json", ignoreCase = true) } + .mapNotNull { filename -> + val localeTag = filename.removeSuffix(".json") + try { + val json = context.assets.open("$dir/$filename").bufferedReader().use { it.readText() } + val data = parseEmojiPatternsJson(json) + localeTag to data + } catch (e: Exception) { + Timber.w(e, "Failed parsing emoji patterns asset: $filename") + null + } + } + } + + private fun parseEmojiPatternsJson(json: String): EmojiPatternStrings { + val adapter = moshi.adapter(EmojiPatternStrings::class.java) + return requireNotNull(adapter.fromJson(json)) { "Invalid emoji patterns JSON" } + } + + override fun parseEmojiReaction(body: String): ParsedEmojiReaction? { + val removal = parseRemoval(body) + if (removal != null) return removal + + for ((pattern, parser) in reactionPatterns) { + val match = pattern.find(body) + if (match == null) continue; + + val result = parser(match) + if (result == null) continue + + Timber.d("Reaction found with ${result.emoji}") + return result + } + + return null + } + + private fun parseRemoval(body: String): ParsedEmojiReaction? { + for ((pattern, parser) in removalPatterns) { + val match = pattern.find(body) + if (match == null) continue; + + val result = parser(match) + if (result == null) continue + + Timber.d("Removal found with ${result.emoji}") + return result + } + + return null + } + + /** + * Search for messages in the same thread with matching text content + * We'll search recent messages first + */ + override fun findTargetMessage( + threadId: Long, + originalMessageText: String, + realm: Realm + ): Message? { + val startTime = System.currentTimeMillis() + val messages = realm.where(Message::class.java) + .equalTo("threadId", threadId) + .sort("date", Sort.DESCENDING) + .findAll() + val endTime = System.currentTimeMillis() + Timber.d("Found ${messages.size} messages as potential emoji targets in ${endTime - startTime}ms") + + val match = messages.find { message -> + message.getText(false).trim() == originalMessageText.trim() + } + if (match != null) { + Timber.d("Found match for reaction target: message ID ${match.id}") + return match + } + + Timber.w("No target message found for reaction text: '$originalMessageText'") + return null + } + + private fun removeEmojiReaction( + reactionMessage: Message, + reaction: ParsedEmojiReaction, + targetMessage: Message?, + realm: Realm, + ) { + if (targetMessage == null) { + Timber.w("Cannot remove emoji reaction '${reaction.emoji}': no target message found") + return + } + + val existingReaction = targetMessage.emojiReactions.find { candidate -> + candidate.senderAddress == reactionMessage.address && candidate.emoji == reaction.emoji + } + + if (existingReaction != null) { + existingReaction.deleteFromRealm() + Timber.d("Removed emoji reaction: ${reaction.emoji} to message ${targetMessage.id}") + } else { + Timber.w("No existing emoji reaction found to remove: ${reaction.emoji} to message ${targetMessage.id}") + } + + reactionMessage.isEmojiReaction = true + realm.insertOrUpdate(reactionMessage) + } + + override fun saveEmojiReaction( + reactionMessage: Message, + parsedReaction: ParsedEmojiReaction, + targetMessage: Message?, + realm: Realm, + ) { + if (parsedReaction.isRemoval) { + removeEmojiReaction(reactionMessage, parsedReaction, targetMessage, realm) + return + } + + val reaction = EmojiReaction().apply { + id = keyManager.newId() + reactionMessageId = reactionMessage.id + senderAddress = reactionMessage.address + emoji = parsedReaction.emoji + originalMessageText = parsedReaction.originalMessage + threadId = reactionMessage.threadId + } + realm.insertOrUpdate(reaction) + + if (targetMessage != null) { + reactionMessage.isEmojiReaction = true + realm.insertOrUpdate(reactionMessage) + + // Overwrite any previous reaction from this sender for this target + val priorFromSender = targetMessage.emojiReactions.filter { it.senderAddress == reaction.senderAddress } + priorFromSender.forEach { it.deleteFromRealm() } + + targetMessage.emojiReactions.add(reaction) + + Timber.i("Saved emoji reaction: ${reaction.emoji} to message ${targetMessage.id}") + } else { + Timber.w("No target message, cannot save emoji reaction: ${reaction.emoji}") + } + } + + override fun deleteAndReparseAllEmojiReactions(realm: Realm) { + val startTime = System.currentTimeMillis() + + realm.delete(EmojiReaction::class.java) + realm.where(Message::class.java).findAll().map { + it.isEmojiReaction = false + } + + val allMessages = realm.where(Message::class.java) + .beginGroup() + .beginGroup() + .equalTo("type", "sms") + .isNotEmpty("body") + .endGroup() + .or() + .beginGroup() + .equalTo("type", "mms") + .notEqualTo("messageType", 130.toLong()) + .isNotEmpty("parts.text") + .endGroup() + .endGroup() + .sort("date", Sort.ASCENDING) // parse oldest to newest to handle reactions & removals properly + .findAll() + + allMessages.forEach { message -> + val text = message.getText(false) + val parsedReaction = parseEmojiReaction(text) + if (parsedReaction != null) { + val targetMessage = findTargetMessage( + message.threadId, + parsedReaction.originalMessage, + realm + ) + saveEmojiReaction( + message, + parsedReaction, + targetMessage, + realm, + ) + } + } + + val endTime = System.currentTimeMillis() + Timber.d("Deleted and reparsed all emoji reactions in ${endTime - startTime}ms") + } + +} diff --git a/data/src/main/java/com/moez/QKSMS/repository/MessageRepositoryImpl.kt b/data/src/main/java/com/moez/QKSMS/repository/MessageRepositoryImpl.kt index f90bda9d..068b579d 100644 --- a/data/src/main/java/com/moez/QKSMS/repository/MessageRepositoryImpl.kt +++ b/data/src/main/java/com/moez/QKSMS/repository/MessageRepositoryImpl.kt @@ -78,6 +78,7 @@ open class MessageRepositoryImpl @Inject constructor( private val phoneNumberUtils: PhoneNumberUtils, private val prefs: Preferences, private val syncRepository: SyncRepository, + private val reactions: EmojiReactionRepository, ) : MessageRepository { companion object { @@ -88,6 +89,7 @@ open class MessageRepositoryImpl @Inject constructor( Realm.getDefaultInstance() .where(Message::class.java) .equalTo("threadId", threadId) + .equalTo("isEmojiReaction", false) .let { when (query.isEmpty()) { true -> it @@ -761,6 +763,25 @@ open class MessageRepositoryImpl @Inject constructor( // Update contentId after the message has been inserted to the content provider realm.executeTransaction { managedMessage?.contentId = id } } + + managedMessage?.let { savedMessage -> + val parsedReaction = reactions.parseEmojiReaction(body) + if (parsedReaction != null) { + val targetMessage = reactions.findTargetMessage( + savedMessage.threadId, + parsedReaction.originalMessage, + realm + ) + realm.executeTransaction { + reactions.saveEmojiReaction( + savedMessage, + parsedReaction, + targetMessage, + realm, + ) + } + } + } } return message diff --git a/data/src/main/java/com/moez/QKSMS/repository/SyncRepositoryImpl.kt b/data/src/main/java/com/moez/QKSMS/repository/SyncRepositoryImpl.kt index 986cfd9b..78ca1636 100644 --- a/data/src/main/java/com/moez/QKSMS/repository/SyncRepositoryImpl.kt +++ b/data/src/main/java/com/moez/QKSMS/repository/SyncRepositoryImpl.kt @@ -39,6 +39,7 @@ import dev.octoshrimpy.quik.mapper.CursorToRecipient import dev.octoshrimpy.quik.model.Contact import dev.octoshrimpy.quik.model.ContactGroup import dev.octoshrimpy.quik.model.Conversation +import dev.octoshrimpy.quik.model.EmojiReaction import dev.octoshrimpy.quik.model.Message import dev.octoshrimpy.quik.model.MmsPart import dev.octoshrimpy.quik.model.PhoneNumber @@ -68,7 +69,8 @@ class SyncRepositoryImpl @Inject constructor( private val cursorToContactGroupMember: CursorToContactGroupMember, private val keys: KeyManager, private val phoneNumberUtils: PhoneNumberUtils, - private val rxPrefs: RxSharedPreferences + private val rxPrefs: RxSharedPreferences, + private val reactions: EmojiReactionRepository, ) : SyncRepository { override val syncProgress: Subject = @@ -228,6 +230,9 @@ class SyncRepositoryImpl @Inject constructor( syncProgress.onNext(SyncRepository.SyncProgress.Running(0, 0, true)) + // Now that we have all the messages, we can scan for emoji reactions + reactions.deleteAndReparseAllEmojiReactions(realm) + realm.insert(SyncLog()) }, { handlerThread.quitSafely() @@ -287,6 +292,26 @@ class SyncRepositoryImpl @Inject constructor( conversationRepo.getOrCreateConversation(threadId) insertOrUpdate() + + val text = getText(false) + val parsedReaction = reactions.parseEmojiReaction(text) + if (parsedReaction != null) { + Realm.getDefaultInstance().use { realm -> + val targetMessage = reactions.findTargetMessage( + threadId, + parsedReaction.originalMessage, + realm + ) + realm.executeTransaction { + reactions.saveEmojiReaction( + this, + parsedReaction, + targetMessage, + realm, + ) + } + } + } } } } diff --git a/data/src/main/java/com/moez/QKSMS/util/EmojiPatternStrings.kt b/data/src/main/java/com/moez/QKSMS/util/EmojiPatternStrings.kt new file mode 100644 index 00000000..d2509232 --- /dev/null +++ b/data/src/main/java/com/moez/QKSMS/util/EmojiPatternStrings.kt @@ -0,0 +1,28 @@ +package dev.octoshrimpy.quik.util + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +@JsonClass(generateAdapter = false) +data class EmojiPatternStrings( + @Json(name = "emoji_reaction_ios_generic_added") val iosGenericAdded: String? = null, + @Json(name = "emoji_reaction_ios_generic_removed") val iosGenericRemoved: String? = null, + + @Json(name = "emoji_reaction_ios_heart_added") val iosHeartAdded: String? = null, + @Json(name = "emoji_reaction_ios_heart_removed") val iosHeartRemoved: String? = null, + + @Json(name = "emoji_reaction_ios_like_added") val iosLikeAdded: String? = null, + @Json(name = "emoji_reaction_ios_like_removed") val iosLikeRemoved: String? = null, + + @Json(name = "emoji_reaction_ios_dislike_added") val iosDislikeAdded: String? = null, + @Json(name = "emoji_reaction_ios_dislike_removed") val iosDislikeRemoved: String? = null, + + @Json(name = "emoji_reaction_ios_laugh_added") val iosLaughAdded: String? = null, + @Json(name = "emoji_reaction_ios_laugh_removed") val iosLaughRemoved: String? = null, + + @Json(name = "emoji_reaction_ios_exclamation_added") val iosExclamationAdded: String? = null, + @Json(name = "emoji_reaction_ios_exclamation_removed") val iosExclamationRemoved: String? = null, + + @Json(name = "emoji_reaction_ios_question_mark_added") val iosQuestionMarkAdded: String? = null, + @Json(name = "emoji_reaction_ios_question_mark_removed") val iosQuestionMarkRemoved: String? = null, +) diff --git a/domain/src/main/java/com/moez/QKSMS/model/EmojiReaction.kt b/domain/src/main/java/com/moez/QKSMS/model/EmojiReaction.kt new file mode 100644 index 00000000..437a2809 --- /dev/null +++ b/domain/src/main/java/com/moez/QKSMS/model/EmojiReaction.kt @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2025 + * + * This file is part of QUIK. + * + * QKSMS 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. + * + * QKSMS 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 QKSMS. If not, see . + */ +package dev.octoshrimpy.quik.model + +import io.realm.RealmObject +import io.realm.annotations.Index +import io.realm.annotations.PrimaryKey + +open class EmojiReaction : RealmObject() { + @PrimaryKey var id: Long = 0 + + /** The reaction message ID itself */ + @Index var reactionMessageId: Long = 0 + + /** The sender's address (phone number) */ + var senderAddress: String = "" + + /** The emoji used in the reaction */ + var emoji: String = "" + + /** The original message text that was reacted to */ + var originalMessageText: String = "" + + /** Thread ID for easier querying */ + @Index var threadId: Long = 0 +} diff --git a/domain/src/main/java/com/moez/QKSMS/model/EmojiSyncNeeded.kt b/domain/src/main/java/com/moez/QKSMS/model/EmojiSyncNeeded.kt new file mode 100644 index 00000000..1801df38 --- /dev/null +++ b/domain/src/main/java/com/moez/QKSMS/model/EmojiSyncNeeded.kt @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2025 + * + * This file is part of QUIK. + * + * QUIK 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. + * + * QUIK 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 QUIK. If not, see . + */ +package dev.octoshrimpy.quik.model + +import io.realm.RealmObject + +open class EmojiSyncNeeded : RealmObject() { + var createdAt: Long = System.currentTimeMillis() +} diff --git a/domain/src/main/java/com/moez/QKSMS/model/Message.kt b/domain/src/main/java/com/moez/QKSMS/model/Message.kt index 25300368..51029f15 100644 --- a/domain/src/main/java/com/moez/QKSMS/model/Message.kt +++ b/domain/src/main/java/com/moez/QKSMS/model/Message.kt @@ -74,6 +74,8 @@ open class Message : RealmObject() { var subject: String = "" var textContentType: String = "" var parts: RealmList = RealmList() + var isEmojiReaction: Boolean = false + val emojiReactions: RealmList = RealmList() fun getUri(): Uri { val baseUri = if (isMms()) Mms.CONTENT_URI else Sms.CONTENT_URI diff --git a/domain/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepository.kt b/domain/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepository.kt new file mode 100644 index 00000000..8c648249 --- /dev/null +++ b/domain/src/main/java/com/moez/QKSMS/repository/EmojiReactionRepository.kt @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2025 + * + * This file is part of QUIK. + * + * QUIK 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. + * + * QUIK 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 QUIK. If not, see . + */ +package dev.octoshrimpy.quik.repository + +import dev.octoshrimpy.quik.model.Message +import io.realm.Realm + +data class ParsedEmojiReaction(val emoji: String, val originalMessage: String, val isRemoval: Boolean = false) + +interface EmojiReactionRepository { + fun parseEmojiReaction(body: String): ParsedEmojiReaction? + + fun findTargetMessage(threadId: Long, originalMessageText: String, realm: Realm): Message? + + fun saveEmojiReaction( + reactionMessage: Message, + parsedReaction: ParsedEmojiReaction, + targetMessage: Message?, + realm: Realm, + ) + + fun deleteAndReparseAllEmojiReactions(realm: Realm) +} diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/compose/BubbleUtils.kt b/presentation/src/main/java/com/moez/QKSMS/feature/compose/BubbleUtils.kt index fde7149b..b5d2c550 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/compose/BubbleUtils.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/compose/BubbleUtils.kt @@ -28,6 +28,7 @@ object BubbleUtils { fun canGroup(message: Message, other: Message?): Boolean { if (other == null) return false + if (message.emojiReactions.isNotEmpty() || other.emojiReactions.isNotEmpty()) return false val diff = TimeUnit.MILLISECONDS.toMinutes(Math.abs(message.date - other.date)) return message.compareSender(other) && diff < TIMESTAMP_THRESHOLD } diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessagesAdapter.kt b/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessagesAdapter.kt index 7aa6ea93..b6fd29c4 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessagesAdapter.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/compose/MessagesAdapter.kt @@ -74,7 +74,9 @@ import io.reactivex.subjects.Subject import io.realm.RealmResults import kotlinx.android.synthetic.main.message_list_item_in.* import kotlinx.android.synthetic.main.message_list_item_in.body +import kotlinx.android.synthetic.main.message_list_item_in.reactionText import kotlinx.android.synthetic.main.message_list_item_in.parts +import kotlinx.android.synthetic.main.message_list_item_in.reactions import kotlinx.android.synthetic.main.message_list_item_in.sim import kotlinx.android.synthetic.main.message_list_item_in.simIndex import kotlinx.android.synthetic.main.message_list_item_in.status @@ -389,6 +391,50 @@ class MessagesAdapter @Inject constructor( contextMenuValue = message.id clicks.subscribe(partClicks) // part clicks gets passed back to compose view model } + + showEmojiReactions(holder, message) + } + + private fun showEmojiReactions(holder: QkViewHolder, message: Message) { + holder.reactions?.let { reactionsContainer -> + val reactions = message.emojiReactions + val hasReactions = reactions.isNotEmpty() + + if (hasReactions) { + val reactionCounts = reactions.groupBy { it.emoji } + .mapValues { it.value.size } + .toList() + .sortedByDescending { it.second } // Sort by count, most reactions first + + // For now, show just the first (most popular) reaction + val topReaction = reactionCounts.first() + val reactionText = if (topReaction.second == 1) { + topReaction.first + } else { + // Use a non-breaking space to keep the emoji and count together + "${topReaction.first}\u00A0${topReaction.second}" + } + + holder.reactionText?.text = reactionText + reactionsContainer.setVisible(true) + makeRoomForEmojis(holder) + } else { + reactionsContainer.setVisible(false) + } + } + } + + private fun makeRoomForEmojis(holder: QkViewHolder) { + val paddingBottom = 25.dpToPx(context) + + (holder.reactions?.parent?.parent as? ViewGroup)?.let { parent -> + parent.setPadding( + parent.paddingLeft, + parent.paddingTop, + parent.paddingRight, + paddingBottom + ) + } } private fun bindStatus( @@ -471,4 +517,4 @@ class MessagesAdapter @Inject constructor( } } -} \ No newline at end of file +} diff --git a/presentation/src/main/java/com/moez/QKSMS/feature/main/MainViewModel.kt b/presentation/src/main/java/com/moez/QKSMS/feature/main/MainViewModel.kt index 36a4d96a..cdfe7194 100644 --- a/presentation/src/main/java/com/moez/QKSMS/feature/main/MainViewModel.kt +++ b/presentation/src/main/java/com/moez/QKSMS/feature/main/MainViewModel.kt @@ -42,8 +42,10 @@ import dev.octoshrimpy.quik.manager.BillingManager import dev.octoshrimpy.quik.manager.ChangelogManager import dev.octoshrimpy.quik.manager.PermissionManager import dev.octoshrimpy.quik.manager.RatingManager +import dev.octoshrimpy.quik.model.EmojiSyncNeeded import dev.octoshrimpy.quik.model.SyncLog import dev.octoshrimpy.quik.repository.ConversationRepository +import dev.octoshrimpy.quik.repository.EmojiReactionRepository import dev.octoshrimpy.quik.repository.MessageRepository import dev.octoshrimpy.quik.repository.SyncRepository import dev.octoshrimpy.quik.util.Preferences @@ -79,6 +81,7 @@ class MainViewModel @Inject constructor( private val permissionManager: PermissionManager, private val prefs: Preferences, private val ratingManager: RatingManager, + private val reactions: EmojiReactionRepository, private val syncContacts: SyncContacts, private val syncMessages: SyncMessages ) : QkViewModel( @@ -121,6 +124,15 @@ class MainViewModel @Inject constructor( syncMessages.execute(Unit) } + // This is only used when we update to a version that newly supports emoji reactions + Realm.getDefaultInstance().executeTransactionAsync { realm -> + val emojiSyncNeeded = realm.where(EmojiSyncNeeded::class.java).findFirst() + if (emojiSyncNeeded != null) { + reactions.deleteAndReparseAllEmojiReactions(realm) + emojiSyncNeeded.deleteFromRealm() + } + } + // Sync contacts when we detect a change if (permissionManager.hasContacts()) { disposables += contactAddedListener.listen() diff --git a/presentation/src/main/java/com/moez/QKSMS/injection/AppModule.kt b/presentation/src/main/java/com/moez/QKSMS/injection/AppModule.kt index 8a1d35b2..8d52fe2f 100644 --- a/presentation/src/main/java/com/moez/QKSMS/injection/AppModule.kt +++ b/presentation/src/main/java/com/moez/QKSMS/injection/AppModule.kt @@ -81,6 +81,8 @@ import dev.octoshrimpy.quik.repository.ContactRepository import dev.octoshrimpy.quik.repository.ContactRepositoryImpl import dev.octoshrimpy.quik.repository.ConversationRepository import dev.octoshrimpy.quik.repository.ConversationRepositoryImpl +import dev.octoshrimpy.quik.repository.EmojiReactionRepository +import dev.octoshrimpy.quik.repository.EmojiReactionRepositoryImpl import dev.octoshrimpy.quik.repository.MessageContentFilterRepository import dev.octoshrimpy.quik.repository.MessageContentFilterRepositoryImpl import dev.octoshrimpy.quik.repository.MessageRepository @@ -219,6 +221,9 @@ class AppModule(private var application: Application) { @Provides fun provideSyncRepository(repository: SyncRepositoryImpl): SyncRepository = repository + @Provides + fun provideEmojiReactionRepository(repository: EmojiReactionRepositoryImpl): EmojiReactionRepository = repository + // worker factory @Provides fun provideWorkerFactory(workerFactory: InjectionWorkerFactory): WorkerFactory = workerFactory diff --git a/presentation/src/main/res/layout/message_list_item_in.xml b/presentation/src/main/res/layout/message_list_item_in.xml index dc58afd8..792727ef 100644 --- a/presentation/src/main/res/layout/message_list_item_in.xml +++ b/presentation/src/main/res/layout/message_list_item_in.xml @@ -79,7 +79,9 @@ android:layout_height="wrap_content" android:layout_marginStart="12dp" android:orientation="horizontal" - app:layout_constraintBottom_toBottomOf="parent"> + app:layout_constraintBottom_toBottomOf="parent" + android:clipToPadding="false" + android:clipChildren="false"> - + android:clipToPadding="false" + android:clipChildren="false" + android:paddingEnd="4dp" + android:paddingStart="4dp"> - + + + + + + + + @@ -139,4 +179,4 @@ - \ No newline at end of file + diff --git a/presentation/src/main/res/layout/message_list_item_out.xml b/presentation/src/main/res/layout/message_list_item_out.xml index d3c79871..16cc8886 100644 --- a/presentation/src/main/res/layout/message_list_item_out.xml +++ b/presentation/src/main/res/layout/message_list_item_out.xml @@ -92,7 +92,8 @@ + android:layout_height="wrap_content" + android:clipToPadding="false"> + android:orientation="horizontal" + android:clipChildren="false" + android:clipToPadding="false"> - + android:paddingStart="18dp" + android:clipToPadding="false" + android:clipChildren="false"> + + + + + + + + + + - \ No newline at end of file +