2
0
mirror of https://github.com/KDE/kdeconnect-android synced 2025-08-29 13:17:43 +00:00

Refactoring

This commit is contained in:
TPJ Schikhof 2024-12-29 10:23:08 +01:00 committed by Simon Redman
parent e363a5875a
commit 49a9cd5ea7
2 changed files with 37 additions and 105 deletions

View File

@ -52,7 +52,6 @@ object SMSHelper {
private const val THUMBNAIL_WIDTH = 100 private const val THUMBNAIL_WIDTH = 100
// The constant Telephony.Mms.Part.CONTENT_URI was added in API 29 // The constant Telephony.Mms.Part.CONTENT_URI was added in API 29
@JvmField
val mMSPartUri : Uri = Uri.parse("content://mms/part/") val mMSPartUri : Uri = Uri.parse("content://mms/part/")
/** /**
@ -94,10 +93,7 @@ object SMSHelper {
* @param context android.content.Context running the request * @param context android.content.Context running the request
* @return Timestamp of the oldest known message. * @return Timestamp of the oldest known message.
*/ */
@JvmStatic fun getNewestMessageTimestamp(context: Context): Long {
fun getNewestMessageTimestamp(
context: Context
): Long {
var oldestMessageTimestamp = Long.MIN_VALUE var oldestMessageTimestamp = Long.MIN_VALUE
val newestMessage = getMessagesInRange(context, null, Long.MAX_VALUE, 1L, true) val newestMessage = getMessagesInRange(context, null, Long.MAX_VALUE, 1L, true)
// There should only be one, but in case for some reason there are more, take the latest // There should only be one, but in case for some reason there are more, take the latest
@ -117,12 +113,7 @@ object SMSHelper {
* @param numberToGet Number of messages to return. Pass null for "all" * @param numberToGet Number of messages to return. Pass null for "all"
* @return List of all messages in the thread * @return List of all messages in the thread
*/ */
@JvmStatic fun getMessagesInThread(context: Context, threadID: ThreadID, numberToGet: Long?): List<Message> {
fun getMessagesInThread(
context: Context,
threadID: ThreadID,
numberToGet: Long?
): List<Message> {
return getMessagesInRange(context, threadID, Long.MAX_VALUE, numberToGet, true) return getMessagesInRange(context, threadID, Long.MAX_VALUE, numberToGet, true)
} }
@ -136,7 +127,6 @@ object SMSHelper {
* @param getMessagesOlderStartTime If true, get messages with timestamps before the startTimestamp. If false, get newer messages * @param getMessagesOlderStartTime If true, get messages with timestamps before the startTimestamp. If false, get newer messages
* @return Some messages in the requested conversation * @return Some messages in the requested conversation
*/ */
@JvmStatic
@SuppressLint("NewApi") @SuppressLint("NewApi")
fun getMessagesInRange( fun getMessagesInRange(
context: Context, context: Context,
@ -441,10 +431,7 @@ object SMSHelper {
* @param context android.content.Context running the request * @param context android.content.Context running the request
* @return Non-blocking iterable of the first message in each conversation * @return Non-blocking iterable of the first message in each conversation
*/ */
@JvmStatic fun getConversations(context: Context): Sequence<Message> {
fun getConversations(
context: Context
): Sequence<Message> {
val uri = getConversationUri() val uri = getConversationUri()
// Used to avoid spewing logs in case there is an overall problem with fetching thread IDs // Used to avoid spewing logs in case there is an overall problem with fetching thread IDs
@ -507,14 +494,10 @@ object SMSHelper {
} }
threadTimestampPair.add(Pair(threadID, messageDate)) threadTimestampPair.add(Pair(threadID, messageDate))
} }
threadIds = threadTimestampPair.stream() threadIds = threadTimestampPair
.sorted { left: Pair<ThreadID, Long>, right: Pair<ThreadID, Long> -> // Sort most-recent to least-recent (largest to smallest)
right.second.compareTo( .sortedWith { left: Pair<ThreadID, Long>, right: Pair<ThreadID, Long> -> right.second.compareTo(left.second) }
left.second
)
} // Sort most-recent to least-recent (largest to smallest)
.map { threadTimestampPairElement: Pair<ThreadID, Long> -> threadTimestampPairElement.first } .map { threadTimestampPairElement: Pair<ThreadID, Long> -> threadTimestampPairElement.first }
.collect(Collectors.toList())
} }
// Step 2: Get the actual message object from each thread ID // Step 2: Get the actual message object from each thread ID
@ -538,25 +521,16 @@ object SMSHelper {
} }
} }
private fun addEventFlag( private fun addEventFlag(oldEvent: Int, eventFlag: Int): Int {
oldEvent: Int,
eventFlag: Int
): Int {
return oldEvent or eventFlag return oldEvent or eventFlag
} }
/** /**
* Parse all parts of an SMS into a Message * Parse all parts of an SMS into a Message
*/ */
private fun parseSMS( private fun parseSMS(context: Context, messageInfo: Map<String, String?>): Message {
context: Context, val event = addEventFlag(Message.EVENT_UNKNOWN, Message.EVENT_TEXT_MESSAGE)
messageInfo: Map<String, String?> val address = listOf(Address(context, messageInfo[Telephony.Sms.ADDRESS]!!))
): Message {
var event = Message.EVENT_UNKNOWN
event = addEventFlag(event, Message.EVENT_TEXT_MESSAGE)
val address = listOf(
Address(context, messageInfo[Telephony.Sms.ADDRESS]!!)
)
val maybeBody = messageInfo.getOrDefault(Message.BODY, "") val maybeBody = messageInfo.getOrDefault(Message.BODY, "")
val body = maybeBody ?: "" val body = maybeBody ?: ""
val date = NumberUtils.toLong(messageInfo.getOrDefault(Message.DATE, null)) val date = NumberUtils.toLong(messageInfo.getOrDefault(Message.DATE, null))
@ -569,28 +543,14 @@ object SMSHelper {
) )
) )
val uID = NumberUtils.toLong(messageInfo.getOrDefault(Message.U_ID, null)) val uID = NumberUtils.toLong(messageInfo.getOrDefault(Message.U_ID, null))
val subscriptionID = val subscriptionID = NumberUtils.toInt(messageInfo.getOrDefault(Message.SUBSCRIPTION_ID, null))
NumberUtils.toInt(messageInfo.getOrDefault(Message.SUBSCRIPTION_ID, null))
// Examine all the required SMS columns and emit a log if something seems amiss // Examine all the required SMS columns and emit a log if something seems amiss
val anyNulls = Arrays.stream( val anyNulls = arrayOf(Telephony.Sms.ADDRESS, Message.BODY, Message.DATE, Message.TYPE, Message.READ, Message.THREAD_ID, Message.U_ID)
arrayOf(
Telephony.Sms.ADDRESS,
Message.BODY,
Message.DATE,
Message.TYPE,
Message.READ,
Message.THREAD_ID,
Message.U_ID
)
)
.map { key: String -> messageInfo.getOrDefault(key, null) } .map { key: String -> messageInfo.getOrDefault(key, null) }
.anyMatch { obj: String? -> Objects.isNull(obj) } .any { obj: String? -> Objects.isNull(obj) }
if (anyNulls) { if (anyNulls) {
Log.e( Log.e("parseSMS", "Some fields were invalid. This indicates either a corrupted SMS database or an unsupported device.")
"parseSMS",
"Some fields were invalid. This indicates either a corrupted SMS database or an unsupported device."
)
} }
return Message( return Message(
address, address,
@ -610,11 +570,7 @@ object SMSHelper {
* Parse all parts of the MMS message into a message * Parse all parts of the MMS message into a message
* Original implementation from https://stackoverflow.com/a/6446831/3723163 * Original implementation from https://stackoverflow.com/a/6446831/3723163
*/ */
private fun parseMMS( private fun parseMMS(context: Context, messageInfo: Map<String, String?>, userPhoneNumbers: List<LocalPhoneNumber>): Message {
context: Context,
messageInfo: Map<String, String?>,
userPhoneNumbers: List<LocalPhoneNumber>
): Message {
var event = Message.EVENT_UNKNOWN var event = Message.EVENT_UNKNOWN
var body = "" var body = ""
val read = NumberUtils.toInt(messageInfo[Message.READ]) val read = NumberUtils.toInt(messageInfo[Message.READ])
@ -747,8 +703,8 @@ object SMSHelper {
val to = SmsMmsUtils.getMmsTo(context, msg) val to = SmsMmsUtils.getMmsTo(context, msg)
val addresses: MutableList<Address> = ArrayList() val addresses: MutableList<Address> = ArrayList()
if (from != null) { if (from != null) {
val isLocalPhoneNumber = userPhoneNumbers.stream() val isLocalPhoneNumber = userPhoneNumbers
.anyMatch { localPhoneNumber: LocalPhoneNumber -> .any { localPhoneNumber: LocalPhoneNumber ->
localPhoneNumber.isMatchingPhoneNumber(from.getAddress()) localPhoneNumber.isMatchingPhoneNumber(from.getAddress())
} }
if (!isLocalPhoneNumber && from.toString() != "insert-address-token") { if (!isLocalPhoneNumber && from.toString() != "insert-address-token") {
@ -757,8 +713,8 @@ object SMSHelper {
} }
if (to != null) { if (to != null) {
for (toAddress in to) { for (toAddress in to) {
val isLocalPhoneNumber = userPhoneNumbers.stream() val isLocalPhoneNumber = userPhoneNumbers
.anyMatch { localPhoneNumber: LocalPhoneNumber -> .any { localPhoneNumber: LocalPhoneNumber ->
localPhoneNumber.isMatchingPhoneNumber(toAddress.getAddress()) localPhoneNumber.isMatchingPhoneNumber(toAddress.getAddress())
} }
if (!isLocalPhoneNumber && toAddress.toString() != "insert-address-token") { if (!isLocalPhoneNumber && toAddress.toString() != "insert-address-token") {
@ -837,16 +793,8 @@ object SMSHelper {
* *
* @param observer ContentObserver to alert on Message changes * @param observer ContentObserver to alert on Message changes
*/ */
@JvmStatic fun registerObserver(observer: ContentObserver, context: Context) {
fun registerObserver( context.contentResolver.registerContentObserver(getConversationUri(), true, observer)
observer: ContentObserver,
context: Context
) {
context.contentResolver.registerContentObserver(
getConversationUri(),
true,
observer
)
} }
/** /**
@ -862,10 +810,7 @@ object SMSHelper {
* ... * ...
* ] * ]
</String></String></String></Attachment> */ </String></String></String></Attachment> */
@JvmStatic fun jsonArrayToAttachmentsList(jsonArray: JSONArray?): List<Attachment> {
fun jsonArrayToAttachmentsList(
jsonArray: JSONArray?
): List<Attachment> {
if (jsonArray == null) { if (jsonArray == null) {
return emptyList() return emptyList()
} }
@ -887,7 +832,6 @@ object SMSHelper {
/** /**
* converts a given JSONArray into List<Address> * converts a given JSONArray into List<Address>
</Address> */ </Address> */
@JvmStatic
fun jsonArrayToAddressList(context: Context, jsonArray: JSONArray): List<Address> { fun jsonArrayToAddressList(context: Context, jsonArray: JSONArray): List<Address> {
val addresses: MutableList<Address> = ArrayList() val addresses: MutableList<Address> = ArrayList()
try { try {
@ -906,13 +850,9 @@ object SMSHelper {
* Represent an ID used to uniquely identify a message thread * Represent an ID used to uniquely identify a message thread
*/ */
class ThreadID(val threadID: Long) { class ThreadID(val threadID: Long) {
override fun toString(): String { override fun toString(): String = threadID.toString()
return threadID.toString()
}
override fun hashCode(): Int { override fun hashCode(): Int = java.lang.Long.hashCode(threadID)
return java.lang.Long.hashCode(threadID)
}
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
return other!!.javaClass.isAssignableFrom(ThreadID::class.java) && (other as ThreadID?)!!.threadID == threadID return other!!.javaClass.isAssignableFrom(ThreadID::class.java) && (other as ThreadID?)!!.threadID == threadID
@ -930,9 +870,9 @@ object SMSHelper {
class Attachment( class Attachment(
private val partID: Long, private val partID: Long,
@JvmField val mimeType: String, val mimeType: String,
@JvmField val base64EncodedFile: String?, val base64EncodedFile: String?,
@JvmField val uniqueIdentifier: String val uniqueIdentifier: String
) { ) {
@Throws(JSONException::class) @Throws(JSONException::class)
@ -1017,7 +957,7 @@ object SMSHelper {
class Message internal constructor( class Message internal constructor(
private val addresses: List<Address>, private val addresses: List<Address>,
val body: String, val body: String,
@JvmField val date: Long, val date: Long,
val type: Int, val type: Int,
val read: Int, val read: Int,
private val threadID: ThreadID, private val threadID: ThreadID,
@ -1146,7 +1086,7 @@ object SMSHelper {
* Since this means a thread has to be spawned, this method might block until that thread is * Since this means a thread has to be spawned, this method might block until that thread is
* ready to serve requests * ready to serve requests
*/ */
@JvmStatic @JvmStatic // required for ConnectivityReportPlugin.java
fun getLooper(): Looper? { fun getLooper(): Looper? {
if (singleton == null) { if (singleton == null) {
looperReadyLock.lock() looperReadyLock.lock()

View File

@ -220,11 +220,11 @@ object SmsMmsUtils {
configOverrides.putBoolean(SmsManager.MMS_CONFIG_GROUP_MMS_ENABLED, klinkerSettings.group) configOverrides.putBoolean(SmsManager.MMS_CONFIG_GROUP_MMS_ENABLED, klinkerSettings.group)
// Write the PDUs to disk so that we can pass them to the SmsManager // Write the PDUs to disk so that we can pass them to the SmsManager
val fileName = "send." + abs(Random().nextLong().toDouble()) + ".dat" val fileName = "send.${abs(Random().nextLong().toDouble())}.dat"
val mSendFile = File(context.cacheDir, fileName) val mSendFile = File(context.cacheDir, fileName)
val contentUri = (Uri.Builder()) val contentUri = (Uri.Builder())
.authority(context.packageName + ".MmsFileProvider") .authority("${context.packageName}.MmsFileProvider")
.path(fileName) .path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT) .scheme(ContentResolver.SCHEME_CONTENT)
.build() .build()
@ -320,10 +320,7 @@ object SmsMmsUtils {
// Set Content-Location. // Set Content-Location.
part.contentLocation = filename.toByteArray() part.contentLocation = filename.toByteArray()
val index = filename.lastIndexOf(".") val index = filename.lastIndexOf(".")
val contentId = if ((index == -1)) val contentId = if (index == -1) filename else filename.substring(0, index)
filename
else
filename.substring(0, index)
part.contentId = contentId.toByteArray() part.contentId = contentId.toByteArray()
part.data = p.Data part.data = p.Data
pb.addPart(part) pb.addPart(part)
@ -339,8 +336,7 @@ object SmsMmsUtils {
if (msg == null) { if (msg == null) {
return null return null
} }
val encodedStringValue = msg.from return SMSHelper.Address(context, msg.from.string)
return SMSHelper.Address(context, encodedStringValue.string)
} }
/** /**
@ -351,9 +347,10 @@ object SmsMmsUtils {
if (msg == null) { if (msg == null) {
return null return null
} }
val toBuilder = StringBuilder()
val to = msg.to
val toBuilder = StringBuilder()
val to = msg.to
if (to != null) { if (to != null) {
toBuilder.append(EncodedStringValue.concat(to)) toBuilder.append(EncodedStringValue.concat(to))
} }
@ -366,10 +363,7 @@ object SmsMmsUtils {
} }
} }
var built = toBuilder.toString().replace(";", ", ") val built = toBuilder.toString().replace(";", ", ").removePrefix(", ")
if (built.startsWith(", ")) {
built = built.substring(2)
}
return stripDuplicatePhoneNumbers(context, built) return stripDuplicatePhoneNumbers(context, built)
} }
@ -471,9 +465,7 @@ object SmsMmsUtils {
val np = NetworkPacket(type) val np = NetworkPacket(type)
np["filename"] = filename np["filename"] = filename
np.payload = NetworkPacket.Payload(inputStream, size) np.payload = NetworkPacket.Payload(inputStream, size)
return np return np
} catch (e: Exception) { } catch (e: Exception) {
return null return null